text stringlengths 8 6.05M |
|---|
import math
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import statsmodels.api as sm
from scipy import optimize
def func(t, A, tau, C):
"""Function to fit data."""
return A*np.exp(-tau*t) + C
# Column names
time = 'time'
curr_0 = 'I=0.15'
curr_1 = 'I=0.25'
curr_2 = 'I=0.35'
curr... |
from Testing import ZopeTestCase as ztc
from collective.cart.core.content.product import ProductAnnotations
from collective.cart.core.interfaces import IAddableToCart
from collective.cart.core.interfaces import IProduct
from collective.cart.core.tests.base import FUNCTIONAL_TESTING
from hexagonit.testing.browser import... |
#!/usr/bin/python
import pjsua as pj
import threading
import datetime
from keypad import RaspiBoard
import time
from threading import Timer
LOG_LEVEL_PJSIP = 3
#SIP_SERVER="192.168.137.1"
#SIP_SERVER="192.168.137.139"
SIP_SERVER="localhost"
SIP_USER="entrada"
SIP_PASS="kxgs8zn6TwM7"
SIP_REALM="asterisk"
SIP_LOCAL_P... |
import numpy as np
from sklearn.datasets import load_boston
dataset = load_boston()
x = dataset.data
y = dataset.target
print(x.shape, y.shape) # (506, 13) (506, )
from sklearn.model_selection import train_test_split
x_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=45)
x_train,... |
import cv2
import numpy
from matplotlib import pyplot
def display_colored_balls():
original_image = cv2.cv2.imread("colored_balls.jpg", cv2.cv2.IMREAD_GRAYSCALE)
_, mask = cv2.cv2.threshold(original_image, 220, 255, cv2.cv2.THRESH_BINARY_INV)
kernal = numpy.ones((2,2), numpy.uint8)
dilation = cv2.cv2... |
import logging
import os
from functools import partialmethod
from django.conf import settings
from django.db import models
from django.utils.html import mark_safe
from preview_generator.manager import PreviewManager
def _tohtml(obj, previewfield):
previewfile = getattr(obj, previewfield.name)
originalfile = ... |
from django.conf.urls import url, include
from rest_framework.routers import DefaultRouter
from Auth.views import CompanyViewSet
router = DefaultRouter()
router.register(r'company', CompanyViewSet, base_name='companies')
urlpatterns = [
url(r'^', include(router.urls))
]
|
# @Title: Pow(x, n) (Pow(x, n))
# @Author: 2464512446@qq.com
# @Date: 2020-11-16 16:52:56
# @Runtime: 40 ms
# @Memory: 13.5 MB
class Solution:
def myPow(self, x: float, n: int) -> float:
if x == 1 or x == 0:
return x
if n < 0:
x,n = 1/x,-n
res = 1
while n:
... |
#========================================================================#
# Generate LSWT "completeness monitoring" plots in batch mode
#------------------------------------------------------------------------#
# Creates the following plots:
# 1. Temporal check - barplot for each dekad, showing daily number of
# ... |
import json
import scrapy
from scrapy.http import Request
from scrapy.loader import ItemLoader
from scrapy.item import Item, Field
from tripadvisor_review.items import TripadvisorReviewItem
from scrapy.selector import Selector
class ReviewsScraper(scrapy.Spider):
name = "restaurantreviews"
allowed_domains = ["... |
#game_functions.py
import sys
from time import sleep#pause the game for a while
import pygame
from bullet import Bullet
from alien import Alien
def check_keydown_events(event,infrompy_settings, screen, ship, bullets):
"""Respond to keypresses"""
if event.key == pygame.K_RIGHT:
ship.moving_right ... |
# Generated by Django 2.2.5 on 2019-12-07 08:18
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('trips', '0014_auto_20191207_0736'),
]
operations = [
migrations.AddField(
model_name='selectedtrip',
name='total',
... |
import PIL as p
import PIL.ImageTk as ptk
class Picture():
def __init__(self,path):
self.image = p.Image.open(path)
self.width, self.height = self.image.size
self.w=int(self.width/2)
self.h=int(self.height/2)
self.new_size=self.image.resize((self.w,self.h))
self.img=p... |
from .GPR_meta_mll import GPRegressionMetaLearned
from .GPR_meta_vi import GPRegressionMetaLearnedVI
from .GPR_meta_svgd import GPRegressionMetaLearnedSVGD
from .GPR_mll import GPRegressionLearned
from .MAML import MAMLRegression
from .NPR_meta import NPRegressionMetaLearned |
import boto.swf.layer2 as swf
from boto.swf.exceptions import SWFWorkflowExecutionAlreadyStartedError
import json
import logging
from logging.handlers import RotatingFileHandler
file_handler = RotatingFileHandler('/var/log/postmash/redisworker.log')
file_handler.setLevel(logging.INFO)
logger = logging.getLogger('redisw... |
# Write a program to generate the following arithmetic examples.
# Hints:
# (1) Divide-and-conquer: what simpler problem do you need to solve? (2) Consider using strings to build numbers and then convert.
# (3) The range iterator may be helpful.
# read input variables par and score
par = int(input("Enter the par value... |
import os
from pydub import AudioSegment
dir = "neg"
out_dir = "neg_new"
count = 1
for filename in os.listdir(dir):
print (filename)
src = dir+"/"+filename
dst = str(count)+".wav"
count = count + 1
# convert wav to mp3
sound = AudioSe... |
from PIL import Image
import numpy as np
import json
import os
W, H = 0, 1
RED, GREEN, BLUE = 0, 1, 2
sqsize = 50 #maybe add formula to auto calculate square size?? (probably optimize for about 1600 squares)
imgfp = 'InputImages/earth.png' #later modify to allow multiple images
imgname = imgfp.split('.')[0].split... |
# -*- coding: utf-8 -*-
from utils.operation_log import logger
from utils.operation_profile import get_web_data
from pages.web.baidu_page.baiduMainPage import baiduMainPage
class TestBaiduSearch:
"""测试百度搜索流程用例"""
def setup(self):
self.BAIDUURL = get_web_data("BAIDU", "BAIDUURL")
def test_search... |
def test():
a, b, c = 1, 2, 32
line = 'HelloWorld'
print(test.__code__.co_nlocals)
|
from .pagination import QueryTypePagination
|
N = int(input())
group = list(map(int, input().split()))
# 오름차순 버전
answer = 0 # 총 그룹 수
count = 0 # 단위 그룹 수
group.sort()
for i in group:
count += 1
if count >= i:
answer += 1
count = 0
print(answer)
# 내림차순 버전
# group.sort(reverse=True)
# answer = []
# temp = []
# while True:
# if len(grou... |
from django.shortcuts import render,Http404
from django.http import HttpResponse, HttpResponseRedirect
from django.template import loader
from .models import Bitly
from django.views import View
def redirect(request, keys=None, *args, **kwargs):
try:
obj=Bitly.objects.get(keys=keys)
except Bitly.Does... |
# coding=utf-8
import json
import requests
from logbook import Logger
log = Logger(__name__)
dice10k_url = "http://localhost:3000"
def call_counter(func):
def helper(*args, **kwargs):
helper.calls += 1
return func(*args, **kwargs)
helper.calls = 0
helper.__name__ = func.__name__
re... |
"""
created by Nagaj at 04/05/2021
"""
|
# -*- coding: utf-8 -*-
from src.functions.Functions import Functions as Selenium
import unittest
class Test_012(Selenium, unittest.TestCase):
def setUp(self):
Selenium.abrir_navegador(self, "https://www.mercadolibre.com.ar/registration")
Selenium.get_json_file(self, "mercadolibre_ar")
... |
# -----------------------------------------------------------------------------
# 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.
# ------------------------------------------------... |
###This performs the topology profiling on a set of introgressed blocks that are annotated
###with mutation motifs.
###Mutation motifs can be retrieved using vcftools or bcftools by e.g. cutting down VCFs
###to the 4 relevant individuals [Target,Deni,Nean,HumanOutgroup] where HumanOutgroup is
###a human sequence (for ... |
#https://learnmeabitcoin.com/guide/target
CIBLE_MAX = ((2**16-1)*2**208)
def cibleToDifficulte(cible):
return CIBLE_MAX/cible
#initial target (Block 0)
target0 = "00000000ffff0000000000000000000000000000000000000000000000000000"
#current target (Block 614,308)
target614308 = "000000000000000000130c78000000000000000... |
import os
from ctypes import windll
import pygame
import pymunk
class Window:
def __init__(self, fullscreen=True):
pygame.init()
screen_size = pygame.display.Info()
self.__width = screen_size.current_w
self.__height = screen_size.current_h
windll.user32.SetProce... |
import bisect
import time
from collections import deque
class Scheduler(object):
""""A timer based on EventLoop class"""
@classmethod
def instance(cls):
if not hasattr(cls, "_instance"):
cls._instance = cls()
return cls._instance
def __init__(self):
self.tasks = de... |
# _*_coding:utf-8_*_
# Author:Topaz
import scrapy
import hashlib
from scrapy.selector import Selector
from scrapy.http import Request
from scrapy.http.cookies import CookieJar
import json
from selenium import webdriver
import os
class ZhiHuSpider(scrapy.Spider):
name = 'zhihu'
allow_domains = ["zhi... |
import requests
from random import randint
from time import sleep
def get_user_detail(user_id):
user_detail_address = 'http://18.219.29.53:5000/users/' + user_id + '/detail'
r = requests.get(user_detail_address)
return r.json()['detail']
def step1_login(user_id):
login_address = 'http://18.219.29... |
from typing import NoReturn
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from collections import Counter
from errors import UnknownGraph
from main import ALPHA
def show_frequency(single_freq: dict, show: bool = True) -> NoReturn:
"""Show the graph of single frequency dictionary.
A... |
from django.urls import path
from . import views
from django.contrib.auth import views as auth_views
app_name = 'accounts'
urlpatterns = [
path('', views.home, name='home'),
path('signup/', views.signup, name='signup'),
path('login/', auth_views.LoginView.as_view(
template_name='accounts/signin.htm... |
# coding: utf-8
"""
Lilt REST API
The Lilt REST API enables programmatic access to the full-range of Lilt backend services including: * Training of and translating with interactive, adaptive machine translation * Large-scale translation memory * The Lexicon (a large-scale termbase) * Programmatic cont... |
import torch
import torch.nn as nn
import torch.nn.functional as F
from torchvision import models
import os
import numpy as np
import data_helper_habitat as dhh
class MapNet(nn.Module):
# Implementation of MapNet and all its core components following the paper:
# Henriques and Vedaldi, MapNet: An Allocentric ... |
'''
Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.
Find all the elements of [1, n] inclusive that do not appear in this array.
Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.... |
from flask_restplus import fields
class AdminSchema:
schema_user_req = {
'username': fields.String(required=True, description='username'),
'email': fields.String(required=True, description='email'),
'role': fields.String(required=False, description='Role user')
}
schema_user_res = {
'id': field... |
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU... |
list = []
str = input()
list = str.split()
print(list[2],list[0],list[1]) |
from core.base import Base
try:
from .base import *
except:
from base import *
class LaGou(SpiderBase, Base):
name = 'lagou'
def __init__(self, logger=None,*args):
super(LaGou, self).__init__(logger, *args)
def open_search_home(self):
headers = {
'Connection': 'kee... |
import cv2
import numpy as np
import time
from matplotlib import pyplot as plt
a=['wheat_grain21.jpeg','wheat_grain27.jpeg','wheat_grain32.jpeg','wheat_grain37.jpeg']
data_path='/home/ambuje/Desktop/'
import mpi4py.MPI
rank = mpi4py.MPI.COMM_WORLD.Get_rank()
size = mpi4py.MPI.COMM_WORLD.Get_size()
task_list = range(4)... |
#!/bin/python
import sys
d1,m1,y1 = raw_input().strip().split(' ')
d1,m1,y1 = [int(d1),int(m1),int(y1)]
d2,m2,y2 = raw_input().strip().split(' ')
d2,m2,y2 = [int(d2),int(m2),int(y2)]
y= y1 - y2
if y == 0:
m = m1 - m2
if m == 0:
if d1 <= d2:
print 0
else:
print str(15*... |
import mysql.connector as mariadb
import sys
mariadb_connection = mariadb.connect(user='root', password='', database='doorlock') ## Connect to db
cursor = mariadb_connection.cursor()
query = "SELECT position FROM status ORDER BY time DESC LIMIT 1;" ## Get the latest position of the lock
cursor.execute(query)
response ... |
def gcd(a, b):
while b != 0:
a, b = b, a % b
return(a)
A, B, C, D = map( int, input().split())
CD = C*D//gcd(C,D)
print(B-A+1 - (B//C - (A-1)//C) - (B//D-(A-1)//D) + (B//CD - (A-1)//CD))
|
"""
Python module to perform data ingress operations
for the Advanticsys sensors
"""
import pandas as pd
# from crop.db import create_database
from .constants import (
CONST_ADVANTICSYS_COL_LIST,
CONST_ADVANTICSYS_COL_TIMESTAMP,
CONST_ADVANTICSYS_COL_MODBUSID,
CONST_ADVANTICSYS_COL_TEMPERATURE,
C... |
# Broadcast message server
import socket
import select
import sys
print 'Hello World! I am the KitChat server. Your wish is my command!'
PORT = 5999
# CONNECTION_LIST will hold available clients
# We can read iterate through the list and see if there is data available on each socket
# if there is data, we want to r... |
from django.contrib import admin
from .models import *
admin.site.register(Gun)
admin.site.register(Solider)
admin.site.register(Platoon)
admin.site.register(Ranks)
admin.site.register(Ammo)
|
/home/miaojian/miniconda3/lib/python3.7/hmac.py |
import logging
from pylons import request, response, session, tmpl_context as c, url
from pylons.controllers.util import abort, redirect, Response
from time import time
import os
import shutil
import plistlib
from pcpbridge.lib.base import BaseController, render
from pcpbridge.lib import PCastDEV as PCast
log = log... |
x=int(input())
if(x<2):
print('N')
elif(x==2):
print('Y')
else:
for i in range(2,x):
if(x%i==0):
print('N')
break
else:
print('Y')
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (C) 2006-2013 Music Technology Group - Universitat Pompeu Fabra
#
# This file is part of Gaia
#
# Gaia is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Fou... |
class Solution:
def rightView(self, root, res, depth):
if not root:
return
if depth == len(res):
res.append(root.val)
self.rightView(root.right, res, depth + 1)
self.rightView(root.left, res, depth + 1)
def rightSideView(self, root):
result = []
... |
"""trying with postgres again
Revision ID: d671b27f6ff0
Revises:
Create Date: 2021-05-10 12:53:44.257464
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql
from sqlalchemy.orm import sessionmaker
Session = sessionmaker()
# revision identifiers, used by Alembic.
revision =... |
class Solution(object):
def reverse(self , x):
a = 0
b = x if x > 0 else -x
while b:
if a > 2 ** 31 / 10:
return 0
else:
a = a * 10 + b % 10
b= b / 10
return a if x > 0 else -a
|
"""change domain config options
Revision ID: 253ae54f5788
Revises: 36c91aa9b3b5
Create Date: 2019-11-16 16:58:11.287152
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = "253ae54f5788"
down_revision = "36c91aa9b3b5"
branch_labels = None
depends_on = None
def up... |
# http://www.iso.org/iso/country_codes/iso_3166_code_lists.htm
COUNTRIES = (
(u'AFG', u'Afghanistan'),
(u'ALA', u'Aland Islands'),
(u'ALB', u'Albania'),
(u'DZA', u'Algeria'),
(u'ASM', u'American Samoa'),
(u'AND', u'Andorra'),
(u'AGO', u'Angola'),
(u'AIA', u'Anguilla'),
(u'ATG', u'An... |
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Class for vehicle data
"""
class Vehicle(object):
# accepts, optional, vehicle object
def __init__(self, v=None):
self.current_stop_number = None
self.current_stop_id = None
self.timestamp = None
self.current_stop_status = None
... |
class Primitives(object):
def __init__(self, universe):
self.universe = universe
self._holder = None
def install_primitives_in(self, value):
# Save a reference to the holder class
self._holder = value
# Install the primitives from this primitives class
self.inst... |
from django.contrib import admin
from .models import Product
from .models import Review
admin.site.register(Product)
admin.site.register(Review) |
#!/usr/bin/env python
import ptpy
camera = ptpy.PTPy()
with camera.session():
handles = camera.get_object_handles(
0,
all_storage_ids=True,
all_formats=True,
)
for handle in handles:
info = camera.get_object_info(handle)
print(info)
# Download all things tha... |
#!/usr/bin/env python
from keras.models import Sequential
from keras.layers import Dense, Input, Activation
from keras.layers import Convolution2D, MaxPooling2D, Flatten, normalization,Dropout
from keras.models import model_from_json
from keras.optimizers import Adam
import cv2
import matplotlib.pyplot as plt
from skl... |
# -*- coding: utf-8 -*-
import subprocess
from airtest.core.api import *
from poco.drivers.android.uiautomation import AndroidUiautomationPoco
from utils.operation_profile import get_android_config
ADDRESS = get_android_config().get("ADDRESS") # 获取config.yml中ADDRESS
def android_get_devices():
"""用于获取当前连接机器"""
... |
from django.http import HttpResponse
from django.shortcuts import render
# Create your views here.
def index(request):
return HttpResponse("나는 장고의 가장 기본이 되는 원리를 깨우쳐버렸다...")
|
from Common.DBConnection import cursor
from DataAccess.DataModel import *
from BizModel.Entity import PageEntity
import math
def get_brand(brand_id: int):
row_number = cursor.execute('SELECT * FROM tb_fqs_brand WHERE id=%s', brand_id)
if row_number == 0:
return None
else:
row = cursor.fetc... |
import mysql.connector
mydb = mysql.connector.connect(host="localhost",
user="root",
password="jyotiadate",
database="Society_db")
class operator:
def show(self,mee,mpur,mdes):
... |
# -*- coding: utf-8 -*-
import config
import telebot
import vk
import time
import random
import db
session = vk.AuthSession(config.my_app_id, config.user_login, config.user_password,scope='wall, messages')
vkapi = vk.API(session, v="5.62")
bot = telebot.TeleBot(config.token)
id_group=config.id_group #... |
import socket
from thread import *
HOST = '0.0.0.0'
PORT = 2222
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(10)
def clientthread(conct):
while True:
data = conct.recv(1024)
if data == 'close':
break
conct.send(data)
conct.close... |
from django.db import models
from django.contrib.auth.models import User
class post(models.Model):
imagen = models.ImageField(upload_to='fotos')
miniatura = models.ImageField(upload_to='fotos')
titulo = models.CharField(max_length=100)
slug = models.SlugField(max_length=100)
cuerpo = models.TextField()
fecha = m... |
__author__ = 'ferdous'
import random
def run():
lines = open('/usr/share/dict/words').readlines()
for line in range(1,301):
ln = ''.join(['<li><a href="#">', random.choice(lines).rstrip(), '</a></li>'])
print ln
if __name__ == "__main__":
run()
|
# -*- coding: utf-8 -*-
# Generated by Django 1.10.7 on 2017-09-19 08:08
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('nova', '0019_task_svn_url'),
]
operations = [
migrations.RemoveField(
... |
import urllib
import urllib.request
import re
import random
import time
import os
import pandas as pd
import json
import guesssp
import dataarrange
#import numpy
#抓取所需内容
user_agent = ["Mozilla/5.0 (Windows NT 10.0; WOW64)", 'Mozilla/5.0 (Windows NT 6.3; WOW64)',
'Mozilla/5.0 (Windows NT 6.1) ... |
cont1 = 1
while cont1 <= 6:
cont2 = 1
#inicio do cont 1
while cont2 <= 6:
#inicio do cont 2
if (cont1+cont2) == 7:
print(cont1, cont2)
cont2 = cont2 + 1
#fim do cont 2
cont1 = cont1 + 1
#fim do cont 1 |
version_info = (2, 4, 3, 'dev')
_specifier_ = {'alpha': 'a', 'beta': 'b', 'candidate': 'rc', 'final': '', 'dev': 'dev'}
postfix = ''
if version_info[3] != 'final':
if version_info[3] == 'dev' and len(version_info) < 5:
postfix = 'dev0'
else:
postfix = _specifier_[version_info[3]] + str(version... |
from django.conf.urls import url,include
from . import views
urlpatterns = [
url(r'^billgenrate/$',views.billgenerate.as_view(), name="bill"),
url(r'^billgroup/',views.billgroup.as_view(),name='billgroup'),
url(r'^bills/(?P<appointment_id>[0-9]+)/$', views.billsview, name='billstemplate'),
url(r'^billi... |
#!/usr/bin/python3
"""defines class Base"""
class Base:
"""Class Base"""
__nb_objects = 0
def __init__(self, id=None):
"""constructor"""
if id is not None:
self.id = id
else:
self.__nb_objects += 1
self.id = self.__nb_objects
|
# Canny Edge and Hough Transform Example:
#
# This example demonstrates using the Canny edge detector
# And the Hough transform to find straight lines in an image.
import sensor, image, time
sensor.reset() # Initialize the camera sensor.
sensor.set_pixformat(sensor.GRAYSCALE) # or sensor.RGB565
sensor.set_framesize(se... |
#!/usr/bin/env python3
#
# Development Order #4:
#
# Determine the duration of a specified test.
#
import datetime
import sys
import pscheduler
logger = pscheduler.Log(prefix='tool-ethr', quiet=True)
json = pscheduler.json_load(exit_on_error=True)
# Duration: How long the test should run
# TODO: Need to make a... |
a=int(input())
d=0
if(a>1):
for i in range(1,a+1):
c=a%i
if(c==0):
d+=1
if(d>2):
print("yes")
else:
print("no")
|
"""
* You should write your code inside a function
* Your function should take the input(s) as argument(s)
* Your function should return the answer as a data-structure
* You can validate/test your code by calling your function and printing the data-structure it returns
* Your function should return the same output ... |
# Calculate Profit
# ---------------------------------------
profite = {
"costPrice": 55,
"sellPrice": 65,
"invontory": 1500
}
def totalProfite(profite):
return (profite["sellPrice"] * profite["invontory"]) - (profite["costPrice"] * profite["invontory"])
print(totalProfite(profite))
# 150000 |
from discord.ext import commands
import commons.errors as errors
class Events(commands.Cog):
def __init__(self, bot):
self.bot = bot
@commands.Cog.listener()
async def on_message(self, message):
if message.author.bot:
return
if self.bot.user in message.mentions:
... |
from __future__ import print_function,division
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import torch.nn.init as init
from utils.utils_trans import *
#from voxel_net2 import add_conv_stage
def weights_init(m):
classname = m.__class__.__name__
if clas... |
numero = int(input('Digite um número inteiro: '))
print("""Escolha uma das bases de conversões
[ 1 ] Converter para BINÁRIO
[ 2 ] Converter para OCTAL
[ 3 ] Converter para HEXADECIMAL""")
opção = int(input('Sua opção: '))
if opção == 1:
print(f'O número {numero} convertido para BINÁRIO é {bin(numero)[2:]}')
elif op... |
from django.conf.urls import url
from .views import *
app_name = "footy"
urlpatterns = [
url(r'^$', ShowMatchesView.as_view(), name="show_matches"),
url(r'^new_match/$', CreateEventView.as_view(), name="new_match"),
url(r'^add_location/$', AddLocationView.as_view(), name="add_location"),
url(r'^joined... |
#------------------CONTROL PID--------------------
import math
import time
#controller direction variables
#DIRECT = 0
#REVERSE = 1
class PID(object):
#def __init__(self, c_input, c_output, c_setpoint, kp, ki, kd, controller_direction):
def __init__(self, c_setpoint, kp, ki, kd, controller_direction): ... |
import elektra
import pandas as pd
import filecmp
import datetime as dt
flow_date = dt.datetime(2020, 10, 17)
### Create Prices (make a daily from lmps)
print('\n\n--- Create Block Prices ---')
prices = pd.read_csv('lmps.csv')
result = elektra.create_prices(flow_date, 'M.P4F8', 'INDIANA.HUB', 'miso', '2x16', 'daily'... |
import numpy as np
import pandas as pd
import keras
from keras.datasets import fashion_mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout, Flatten
from keras.layers import Conv2D, MaxPooling2D
from keras.utils import np_utils
import matplotlib.pyplot as plt
np.random.seed(7)
(X_train,y_t... |
'''
Created on Sep 15, 2015
@author: Jonathan Yu
'''
def minutesNeeded(m):
return 60 + (m - 1) * 25
if __name__ == '__main__':
pass |
total = 0
for i in range(101):
total = total + i;
print('loop counter is: ' + str(i) + ' and total is: ' + str(total))
print('final total is: ' + str(total))
|
import random
import time
import string
import threading
import _thread
from socket import *
import ast
import sys
import hashlib
import config
from socket import error
import datetime
import pickle
import os.path
from os import path
initialBalances = {'A': 100, 'B': 100, 'C': 100, 'D': 100, 'E': 100}
timeOutDuratio... |
"""
#------------------------------------------------------------------------------
# Recording and processing OpenCV data for experiments - record_camera_live.py
#
# Track a payload, save the position data, and output the processed data
#
# Created: 4/27/17 - Daniel Newman -- danielnewman09@gmail.com
#
# Modified:
# ... |
# -----------------------------------------------------------------------------
# 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.
# ------------------------------------------------... |
# By Rakeen Rouf
import matplotlib.pyplot as plt
import math
import time
import matplotlib.animation as animation
import pandas as pd
import numpy as np
from scipy.spatial import distance
class FogDataPlotter:
def __init__(self):
self.fig_iter_num = 0
self.v = 0
self.iv = 0
def update... |
from aiohttp.web import View, Response
class BaseView(View):
async def get(self, *args, **kwargs):
return Response(body=b"OK")
|
# @Title: 有序矩阵中第K小的元素 (Kth Smallest Element in a Sorted Matrix)
# @Author: 2464512446@qq.com
# @Date: 2020-07-02 16:10:43
# @Runtime: 252 ms
# @Memory: 19.2 MB
class Solution:
def kthSmallest(self, matrix: List[List[int]], k: int) -> int:
n = len(matrix)
pq = [(matrix[i][0], i, 0) for i in range(n... |
# Module Maker
# Reads from a json file of modules and generates both latex and html code for copy pasting.
# Designed December 2020 by Joe Manlove
# Version 1.0 completed 12/11/2020, latex is properly generated in file.
# Version 1.0.2 completed 12/18/2020, html is properly generated in file
import json
from module ... |
'''Instrcciones Raice'''
'''Creacion de exepciones porpias(Mas adelante)'''
import math
def evaluaedad(edad):
if edad<0:
raise TypeError("La edad no puede ser menor que 0 ")
if edad<20:
return "eres muy jover"
elif edad<40:
return "eres jover"
elif edad<100:
return "Cuid... |
import Player
import random
class Computer(Player.Player):
def __init__(self,health,i):
self.name = 'Computer{}'.format(i)
super().__init__(health,self.name)
rand1 = random.randint(0,1000)
rand2 = random.randint(0,1000)
rand3 = random.randint(0,1000)
t = rand1 + ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.