text stringlengths 8 6.05M |
|---|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 8/23/2017 3:28 PM
# @Author : Winnichen
# @File : settings_global.py
import pytest
testcase_path="./autocase/testCase.xlsx"
browser=pytest.config.getoption('--browser').lower()
if browser not in ("chrome","ie","firefox"):
browser="chrome" |
from .verb import Verb
from .exceptions import WorkloadExceededError
from .interpreter import Interpreter, build_node_tree
|
import RPi.GPIO as GPIO
import time
class Flash:
def __init__(self, BCM_NUM=19):
self.bcm_num = BCM_NUM
GPIO.setmode(GPIO.BCM) #GPIOへアクセスする番号をBCMの番号で指定することを宣言します。
GPIO.setup(self.bcm_num, GPIO.OUT) #BCMの{BCM_NUM}ピンを出力に追加する.j
def flash(self, COUNT):... |
#!/usr/bin/env python
# -*- coding: utf8 -*-
'''
MIT License
Copyright (c) [2019] [Orlin Dimitrov]
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 limitat... |
from django.urls import path
from . import views
app_name='survey'
urlpatterns = [
path('', views.notice, name='notice'),
path('recognize/', views.recognize, name='recognize'),
path('temperature/', views.temperature, name='temperature'),
path('<int:student_id>/<str:temp>/survey/', views.survey, name='... |
from base64 import b64encode, b64decode
from json import dump, load
from os.path import isfile
from security.encryption import Encryption
class Database:
def __init__(self, filename):
self.filename = filename
self.PWs = {}
self.hashedPW = None
self.salt = None
self.crypto =... |
import cv2
video_capture = cv2.VideoCapture("nvcamerasrc ! video/x-raw(memory:NVMM), width=(int)640, height=(int)480, format=(string)I420, framerate=(fraction)30/1 ! nvvidconv ! video/x-raw, format=(string)BGRx ! videoconvert ! video/x-raw, format=(string)BGR ! appsink")
while True:
video_capture_result, frame = v... |
from django.shortcuts import render
from django.http import HttpResponse
from django.shortcuts import redirect
from datetime import datetime
from crawler.algo import *
from crawler.crawl import *
def main_page(request):
projected_likes = 0
projected_days = 0
mean_like=0
mean_days=0
print "LLL"
# company_u... |
def calculate_discount(item_cost, relative_discount, absolute_discount):
""" Caluclate the sale price"""
percent = float(relative_discount * 0.01)
temp = item_cost - (item_cost * percent)
if temp <= 0:
raise ValueError("relative_discount too large")
print temp
final = temp - absolute_discount
if final <= 0... |
# class Pessoa:
# def _init_(self, nome, telefone):
# self.nome = nome
# self.telefone = telefone
# -------------------------------------------
# class Queue:
# def _int_(self):
# self.q = []
#
# def isEmpty(self):
# return (len(self.q)) == 0)
#
# def enqueue(self, item):... |
from classes.background import Background
import pygame
class Game:
def __init__(self):
self.clock = pygame.time.Clock()
self.playing = True
self.screen = pygame.display.set_mode((500, 500))
self.__background = Background()
def flip(self):
"""
No se que es pero... |
from distutils.core import setup
from distutils.extension import Extension
from Cython.Distutils import build_ext
import numpy
ext_modules=[ Extension("QF_utilities",
["QF_utilities.pyx"],
libraries=["m"],
extra_compile_args = ["-ffast-math"])]
setup(
name='Utilities for ... |
# 수집한 mouse file을 시간(T)을 단위로 split
# base_data_save 이전에 수행
import ai_pred_pattern as ap
import os
import pandas as pd
# mouse filed에 client timestamp를 기준으로 T size로 file을 나눠 저장함
# file(file dictionary)
def mouse_time_split_save(file):
T = 300000 # window size
df = pd.read_csv(file['path'], eng... |
'''
Created on Mar 5, 2013
@author: pvicente
'''
from astar_exceptions import FromCityNotFound, GoalCityNotFound
from Queue import PriorityQueue
class Cities_AStarSolver(object):
def __init__(self, city_map):
self._cities = city_map
@property
def cities(self):
return self._cities
... |
import time
import numpy
from smqtk.representation import DescriptorElement
# Try to import required module
try:
import solr
except ImportError:
solr = None
class SolrDescriptorElement (DescriptorElement):
"""
Descriptor element that uses a Solr instance as the backend storage medium.
Fields ... |
from argparse import Namespace
from collections import defaultdict
from dataclasses import dataclass
from typing import List, Dict, Tuple, Callable, Union, Optional
import torch
from parseridge.corpus.corpus import CorpusIterator, Corpus
from parseridge.corpus.sentence import Sentence
from parseridge.corpus.treebank ... |
# -*- coding: utf-8 -*-
import psycopg2
from model.objectView import ObjectView
class InstitutionalMail:
def persistMail(self,con,user):
if (self.findMail(con,user['id'])) == None:
params = (user['id'],)
cur = con.cursor()
cur.execute('insert into mail.users (id) values... |
#coding=utf-8
from sqlalchemy import Column,Integer,String,DATETIME
from models import Model,CRUD
import datetime
from enum import Enum
class Log(Model,CRUD):
def __init__(self,usr_id,name,text,target):
self.usr_id=usr_id
self.displayName=name
self.text=text
self.target... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django import forms
from .models import *
from django.contrib.auth.forms import UserCreationForm
class BusquedaForm(forms.Form):
e = forms.CharField(label='e', max_length=20)
class RegistroForm(UserCreationForm):
class Meta:
model = ... |
# encoding: utf-8
"""
@author: liaoxingyu
@contact: xyliao1993@qq.com
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import itertools
import torch.nn.functional as F
from torch import nn
from .resnet import R... |
from django.shortcuts import render
# Create your views here.
# def test_view(request):
# return HttpResponse("I am a very nice view!")
# def homepage(request):
# return HttpResponse("Welcome to the homepage")
def test_view(request):
return render(request, 'test.html') |
#!/usr/local/bin/python2.7
# encoding: utf-8
'''
rundaemon -- starts GPIO server
rundaemon is a server exposing GPIOs via HTTP-REST and XMPP
@author: h0ru5
@copyright: 2013. All rights reserved.
@license: Apache 2.0
@contact: johannes.hund@gmail.com
@deffield updated: Updated
'''
imp... |
import pymysql
from faker import Faker
import random
fake = Faker()
conn = pymysql.connect(
host = "localhost",
database="practice",
user= "root",
password=""
)
cursor = conn.cursor()
# SET sql_mode = '';
## If you are getting the gourpby error ! a
query1 = """create table Customer (
... |
from django.shortcuts import render
from django.views.generic import ListView, DetailView
from django.http import Http404
from django.db.models import Q
from .models import ProductType, Product, Category
class ProductSearchListView(ListView):
model = Product
template_name = 'products/product-list.html'
... |
#!/usr/bin/env python
import sys
import parmed as pmd
d = pmd.load_file(sys.argv[1])
for key in d:
res0 = d[key]
c0 = [a.charge for a in res0.atoms]
#print(res0, c0, sum(c0))
print(res0, sum(c0))
|
import xlrd
import xlwt
import re
from xlutils import copy
book = xlrd.open_workbook('改(补).xlsx')
wbook = copy.copy(book)
table = book.sheet_by_index(0)
wtable = wbook.get_sheet(0)
def run():
list = ['未见', '未见异常', '未见明显异常']
nrow = table.nrows
for i in range(1, nrow):
data = table.cell(i, 7).val... |
X = int(input())
N = int(input())
leftover = 0
for OUTER in range(N):
leftover += X
leftover -= int(input())
print(leftover+X)
|
from django.shortcuts import render, get_object_or_404, redirect
from .models import Profile
from .forms import SignupForm, ChangePasswordForm, EditProfileForm, LoginForm
from django.contrib.auth.models import User
from posts.models import Post, Follow, Stream
from django.contrib.auth import update_session_auth_hash
... |
import os
def main():
infile = open('/Users/Python/Desktop/mypython/mypython-4/employees2.txt','r')
outfile = open('/Users/Python/Desktop/mypython/mypython-4/behidemidterm/file/temp.txt','w')
oldname = input('Enter old name : ')
newname = input('Enter new name : ')
for line in infile :
rec ... |
# coding: utf-8
# # Problem 4
#
# This problem consists of a single exercise worth ten (10) points.
#
# **Exercise 0** (10 points). Complete the function `flatten(L)`, which takes a "complex list," `L`, as input and returns a "flat" copy.
#
# By complex, we mean that the input list `L` consists of **arbitrarily ne... |
import random
import pickle
import pymongo
##############################################################
def get_gabra_word_groups():
'''
Create a list of words obtained from a loaded Gabra MongoDB database and group them by lemma. Caches result into a pickle to avoid using the MongoDB database again.
... |
"""
Enter a number and have the program generate PI up to that many decimal places.
Keep a limit to how far the program will go
"""
from math import pi
print('value of pi: ' )
|
# -*- coding: utf-8 -*-
# @Time : 2020/5/23 21:21
# @Author : J
# @File : 绘图功能.py
# @Software: PyCharm
import numpy as np
import cv2 as cv
img = np.zeros((512,512,3),np.uint8)
# np.zeros()有两个参数,一个是创建的图片矩阵大小,另一个是数据类型
# 512,512是像素(第一个512像素高,第二个是512像素宽),3指BGR三种颜色
# uint8是用0-255表示所有颜色。
cv.line(img,(0,0),(5... |
import os
import random
import time
def clear_screen():
os.system('cls')
os.system('clear')
def display_page(self):
clear_screen()
print(self.copy)
print('')
if self.end_program == True:
exit()
choice = ''
while choice not in self.answers:
question = self.question
... |
#!/usr/bin/env python3
from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from Controllers.ProbeController import api_routes
app = Flask(__name__)
app.config.from_pyfile('config.py')
db = SQLAlchemy(app)
app.register_blueprint(api_routes, url_prefix='/api')
if __name__ == '__main__':
app.run(host='... |
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 28 00:44:25 2021
@author: chakati
"""
import cv2
import os
import tensorflow as tf
import frameextractor as fe
import handshape_feature_extractor as hfe
import csv
import re as regex
class GestureDetail:
def __init__(self, gesture_key, gesture_name, ... |
import re
import sys
import numpy as np
import matplotlib.pyplot as plt
import healpy as hp
# ----------------------------------------------------------------------
#def ctp_binning(cls):
# intype = type(cls)
# if intype.upper() == "STRING":
# ----------------------------------------------------------------... |
"""
Copyright 1999 Illinois Institute of Technology
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, modify, merge, publis... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.apps import AppConfig
class ResearchReportConfig(AppConfig):
name = 'research_report'
|
# -*- coding: utf-8 -*-
"""
Created on Tue May 16 15:07:06 2017
@author: toelch
"""
import pandas as pd
data = pd.read_csv('https://dataverse.harvard.edu/api/access/datafile/3005330')
|
# -*- coding: utf-8 -*-
# Copyright (c) 2015, Indictrans and contributors
# For license information, please see license.txt
from __future__ import unicode_literals
import frappe
from frappe.model.document import Document
from mycfo.kpi.doctype.skill_mapping.skill_mapping import get_sample_data
class CustomerSkillMapp... |
from backend import *
from backendConfig import *
from decomp import *
|
from PIL import Image
def show_board():
img=Image.open("sal.png")
img.show()
show_board() |
import esphome.codegen as cg
import esphome.config_validation as cv
from esphome.components import binary_sensor
from esphome.const import CONF_ID
from . import EmptySensorHub, CONF_HUB_ID
DEPENDENCIES = ['empty_sensor_hub']
binary_sensor_ns = cg.esphome_ns.namespace('binary_sensor')
BinarySensor = binary_sensor_ns.c... |
import os
#import numpy
import time
from time import clock
os.environ['JAVA_HOME'] = '/usr/lib/jvm/java-7-oracle/'
#os.environ['JAVA_HOME'] = '/usr/lib/jvm/java-7-openjdk-amd64/'
from neo4j import GraphDatabase, INCOMING, Evaluation, OUTGOING, ANY
from array import array
#acessar o banco de dados
db = GraphDatabase('... |
import Plugin
import connection
class EchoPlugin(Plugin.EasyPlugin):
'''This Plugin responds to the sender with received package'''
def command_echo(self, package):
''' echo the package '''
package.connection.sendResponse(package)
def command_frontendEcho(self, package):
''' echo this package to the fronden... |
import numpy as np
import matplotlib.pyplot as plt
from scipy.optimize import curve_fit
T = [15, 20, 25, 30, 35, 40, 45, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140,
150, 160, 170, 180, 190, 200, 210, 220, 230, 240, 250, 260, 270, 280, 290, 298, 300]
c = np.array([0.022, 0.054, 0.112, 0.203, 0.332, 0.500, 0.698, ... |
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import logging
from dataclasses import dataclass
from typing import Any
from pants.backend.scala.subsystems.scalatest import Scalatest
from pants.backen... |
try:
from charm.core.math.integer import integer,randomBits,random,randomPrime,isPrime,encode,decode,hashInt,bitsize,legendre,gcd,lcm,serialize,deserialize,int2Bytes,toInt
#from charm.core.math.integer import InitBenchmark,StartBenchmark,EndBenchmark,GetBenchmark,GetGeneralBenchmarks,ClearBenchmark
except Exception... |
import cv2
from scipy.misc import imread, imsave
import time
import numpy as np
import os
from skimage.feature import register_translation
from scipy.ndimage import filters
import errno
import matplotlib.pyplot as plt
import tifffile as tiff
from joblib import Parallel, delayed
from stuckpy.microscopy import inout
fro... |
import random
suits = ["Hearts","Spades","Clubs","Diamonds"]
ranks = ["Two","Three","Four","Five","Six","Seven","Eight","Nine","Ten","Jack","Queen","King","Ace"]
value = {"Two":2,"Three":3,"Four":4,"Five":5,"Six":6,"Seven":7,"Eight":8,"Nine":9,"Ten":10,"Jack":10,"Queen":10,"King":10,"Ace":11}
playing = True
class Card... |
__author__ = "Narwhale"
#异常结构
try:
# 主代码块
pass
except KeyError as e:
# 异常时,执行该块
pass
else:
# 主代码块执行完,执行该块
pass
finally:
# 无论异常与否,最终执行该块
pass
while True:
num1 = input('num1:')
num2 = input('num2:')
try:
num1 = int(num1)
num2 = int(num2)
result = num1 ... |
import numpy as np
from numba import njit
import game.consts as consts
@njit('u8(u8[:, :])')
def pack(arr):
bits = np.uint64(0)
for x in range(8):
for y in range(8):
bits += arr[x, y] << (x * 8 + y)
return bits
@njit('u8[:, :](u8)')
def unpack(bits):
arr = np.empty((8, 8), dtype=... |
# Copyright 2014 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from textwrap import dedent
from typing import Dict, List, Union
import pytest
from pants.option.custom_types import (
DictValueComponent,
ListValueComponent,
UnsetBool,
... |
from allennlp.common.util import JsonDict
from allennlp.data import Instance
from allennlp.predictors import Predictor
@Predictor.register("covid_predictor")
class CovidPredictor(Predictor):
def _json_to_instance(self, json_dict: JsonDict) -> Instance:
instance = self._dataset_reader.text_to_instance(
... |
# created by Ryan Spies
# 4/13/2015
# Python 2.7
# Description: generate an input file with for the MAP preprocessor
# MAP input format: http://www.nws.noaa.gov/oh/hrl/nwsrfs/users_manual/part3/_pdf/37map.pdf
import os
import dateutil
os.chdir("../..")
maindir = os.getcwd()
################### user input ###########... |
#!/usr/bin/env python3
import hashlib
import platform
import re
import subprocess
# did you do "pip install requests"?
import requests
def register():
nodename = getMyNodeName()
ips = getMyIpAddresses()
ips = ",".join(ips)
token = generateToken(["set", nodename, ips])
# https://host/myip/set/foob... |
import random
from dolfin import *
import numpy as np
eps = 0.005
class InitialConditions(UserExpression):
def __init__(self, **kwargs):
random.seed(2 + MPI.rank(MPI.comm_world))
super().__init__(**kwargs)
def eval(self, values, x):
values[0] = 0.5 + 0.1*(0.5 - random.random())
... |
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 30 12:51:18 2018
@author: Harsha Vardhan Manoj
"""
import pandas as pd
import re
import time
import numpy as np
udata = ['user_id', 'gender', 'age', 'occupation','zip']
users = pd.read_table('ml-latest-small/users.dat',sep='::',
header=... |
# Task 1
import time
def decorator1(fun):
count = 0
def wrapper(*args):
exec_time = 0
nonlocal count
count += 1
start_time = 0
start_time = time.time()
fun(*args)
exec_time = time.time() - start_time
print(fun.__name__ ,'call:', count, 'executed in', format(exec_time, '.8f'), 'sec')
retu... |
"""
Module for tests
"""
from bitstring import BitArray
import binascii
from itertools import permutations
import datetime
from Polynomial_Extractor import PolynomialExtractor
from Polynomial_Generator import PolynomialGenerator
import Vault_Verifier
from Minutia import *
from Minutiae_Extractor import MinutiaeEx... |
from django.contrib.auth.models import User
from django.contrib.auth.backends import ModelBackend
class EmailAuthenticationBackend(ModelBackend):
def authenticate(self, request, email = None, password = None):
if email and password:
try:
user = User.objects.get(email = email)
... |
#!/usr/bin/python
arr = [list(line.rstrip('\n')) for line in open('problem_79.in')]
chars = ['0', '1', '2', '3', '6', '7', '8', '9']
ans = ""
while len(arr) > 0:
char = arr[0][0]
for i in range(len(arr)):
if arr[i][1] == char:
char = arr[i][0]
ans += char
chars.remove(char)
for... |
# coding: utf-8
#
# In[9]:
from datetime import datetime
import requests
import sys
# see http://docs.python-requests.org/en/master/user/quickstart/ for package documentation
geoportalBaseURL = 'http://datadiscoverystudio.org/geoportal/'
catalogISOmetadataBase = geoportalBaseURL + 'rest/metadata/item/'
print ca... |
from mytoy import toy
def test_toy_default():
assert toy() == 1
def test_toy_0():
assert toy(0) == 1
def test_toy_1():
assert toy(1) == 2
|
import requests as req
from bs4 import BeautifulSoup as soup
import json
def crawl ():
url = "https://www.kabum.com.br/cgi-local/site/listagem/listagem.cgi?string=teclado&btnG= "
rs = req.get(url)
content =rs.content
json = []
page_soup = soup(content,'html.parser')
containers = pag... |
import define
def signal(symbol ,data ,databig , position , signal, sleep , file ,initialsignal ,datasmall):
histogram = data[define.ema24] - data[define.ema52] - data[define.signal18]
file.write(str(symbol))
file.write (' histogram = ')
file.write(str(histogram))
file.write('\n')
#if histogram > 0 and position... |
import pygame
import source.setup
from source.constants import SCR_X ,SCR_Y,EN1_01_IMGPATH,OPEN_DOOR,OPEN_BULL,MU_ST_1
# stage = 0 # 游戏阶段
class Game:
def __init__(self):
self.screen = pygame.display.get_surface()
self.clock = pygame.time.Clock()
self.stage = 0
self.enemy1_img = ... |
# Create Multiple Regression for the “Restaurant Revenue Prediction” dataset.
# Evaluate the model using RMSE and R2 score.
# importing libraries
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
plt.style.use(style='ggplot')
plt.rcParams['figure.figsize'] = (10, 6)
# fetching the data from data.... |
def LCS(seq1, seq2, equal):
s1 = range(0, len(seq1)+1)
s2 = range(0, len(seq2)+1)
score = [[0 for s in s2] for s in s1]
prev = [[0 for s in s2] for s in s1]
for i in s1[:-1]:
for j in s2[:-1]:
if equal(seq1[i], seq2[j]):
score[i+1][j+1] = score[i][j] + 1
else:
... |
# -*- coding: utf-8 -*-
# !/usr/bin/env python
"""
-------------------------------------------------
File Name: pmid_crawler.py
Description: 蜘蛛类,终极方法:pubmed网站大招
Author: Dexter Chen
Date:2018-10-10
-------------------------------------------------
"""
from __future__ import division
import time
import sys
i... |
import json
from component_detect import*
from best_practice_check import*
class Page:
def __init__(self, page_name, page_type):
self.url = "Unknown"
self.page_name = page_name
self.page_type = page_type
self.states = {}
self.best_practices = []
self.best_practices_followed = "Unknown"
self.score = "Un... |
#!/usr/bin/python
limit = 12000
a = 1
b = 3
c = 4000
d = 11999
result = 0
while not (c == 1 and d == 2):
result += 1
k = (limit + b) / d
e = k * c - a
f = k * d - b
a = c
b = d
c = e
d = f
print(result)
|
import pandas.io.sql as psql
import sys
import pandas.io.sql as psql
crypto_arbing_dir = os.getcwd().split('/crypto_db')[0]
sys.path.append(crypto_arbing_dir)
class ArbCheck(object):
"""
"""
def __init__(self):
"""
"""
self.port = 3306
self.host = "127.0.0.1"
sel... |
# -*- coding: utf-8 -*-
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import interp1d
import peakdet
from statistics import normalize, xy_mean
def draw_curve(x_args, legends, interpolate=False):
fig = plt.figure()
ax = fig.add_subplot(111)
fig.canvas.set_window_title('График')... |
def ReversePrint(head):
if head:
ReversePrint(head.next)
print(head.data)
|
# Generated by Django 2.1.1 on 2018-10-01 01:58
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Auth',
fields=[
... |
from sklearn import datasets
from sklearn.feature_extraction.text import TfidfVectorizer
import numpy as np
from sklearn.model_selection import KFold
from sklearn.svm import SVC
from sklearn.model_selection import GridSearchCV
import pandas as pn
newsgroups = datasets.fetch_20newsgroups(
subset='a... |
import os
from scipy.io import loadmat
from prepare_caltech_dataset import convert_sequence, convert_annotations
import cv2
import glob
import json
def process_seqs():
"""Convert the sequence files and save to similar dir structure"""
for dir_name in glob.glob('data/set*'):
parent_dir = os.path.split(... |
import copy
import math
import random
import time
import numpy as np
import Config
from control_algorithms.base import dubins_path_planner as plan
from control_algorithms.base.Node import Node
class PRM_star:
# PRM* algorithm using average variance per unit path length as cost function and Dubins path planner for ... |
#coding:utf-8
from flask.ext.wtf import Form
from wtforms import StringField, SubmitField, BooleanField, FileField, TextAreaField
from wtforms.validators import DataRequired, Email,EqualTo
class FileUploadForm(Form):
file = FileField(u'照片路径:',validators=[DataRequired(message=u'照片路径不能为空')])
submit = SubmitFie... |
# -*- coding: utf-8 -*-
"""
Spyder Editor
This is a temporary script file.
"""
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
class BasicBlock(nn.Module):
def __init__(self,in_channels,out_channels,stride):
super().__init__()
self.residual_... |
# Copyright 2010 Alon Zakai ('kripken'). All rights reserved.
# This file is part of Syntensity/the Intensity Engine, an open source project. See COPYING.txt for licensing.
import os, json
INTENSITY_HOME_DIR_LABEL = 'INTENSITY_HOME_DIR'
config = None
home_dir = os.path.dirname(__file__) # Default value, is the one... |
#!/usr/bin/env python
import versioneer
from setuptools import setup
from os.path import exists
setup(name='aiopeewee',
version=versioneer.get_version(),
cmdclass=versioneer.get_cmdclass(),
packages=['aiopeewee'],
description='Async Peewee',
url='http://github.com/kszucs/aiopeewee',
... |
from unittest import TestCase
from src.entry_point import Entry
class TestEntry(TestCase):
def setUp(self):
# This is run before EVERY test
self.test = Entry()
def tearDown(self):
pass
def test_adder(self):
self.assertEqual(self.test.adder(1, 2), 3)
def test_subtracto... |
cnt =0
for i in range(12):
if 'r' in input():
cnt+=1
print(cnt) |
from itertools import zip_longest
import hashlib
from dataclasses import dataclass
def get_hash(s: str):
"""Hash function."""
h = hashlib.sha1()
h.update(s.encode('utf-8'))
return h.hexdigest()
@dataclass(frozen=True, eq=True)
class ExampleId:
id: int
unlabeled: bool = False
def __repr_... |
from django.db.models import Count, Avg, Min, Max
from collections import defaultdict
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.views.generic import TemplateView, View, DetailView, ListView
from common.models import ReleaseNotes
from common.phylogenetic_... |
## 主要做了一些数据的变换
import numpy as np
import pandas as pd
from datetime import datetime, date, timedelta
from scipy.stats import skew
from scipy.special import boxcox1p
from scipy.stats import boxcox_normmax
import os
import re
import seaborn as sns
import matplotlib.pyplot as plt
import time
from itertools... |
# Generated by Django 2.1.5 on 2019-01-26 20:59
from django.conf import settings
import django.contrib.auth.models
import django.contrib.auth.validators
from django.db import migrations, models
import django.db.models.deletion
import django.utils.timezone
class Migration(migrations.Migration):
initial = True
... |
from nab import show_elem, match, episode
class Season(show_elem.ShowParentElem, show_elem.ShowElem):
def __init__(self, show, num, title=None, titles=None):
show_elem.ShowParentElem.__init__(self)
show_elem.ShowElem.__init__(self, show, title, titles)
self.num = num
@property
def... |
# Eni for operatori xaqida for bu ko'rsatilgan chegaragacha ya'ni qadam va qadam chiqarib ber degani
prices=[10,20,30,40,2,4,3] # bu qandydir narxlar yozilgan list bo'lsin
total=0 # bu boshlangích narx
for price in prices:
total=total+price # bu degani shu boshlangích narxni va keyingi narxlarni qo'shish degani
pri... |
# coding: utf-8
__author__ = 'Chris Lee'
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
import os
cwp = os.path.dirname(os.path.abspath(__file__))
import pymongo
import json
import re
import datetime
def prepare_mongo_data():
in_host = 'localhost'
in_port = 27017
in_db = 'resume'
in_table... |
#!/proj/sot/ska3/flight/bin/python
import sys
print(sys.path) |
from mutagen.id3 import ID3
from songs_handler import data_handler
class metadata_getter():
def get_metadata(path):
audio = ID3(path)
song = audio['TIT2'].text[0]
artist = audio['TPE1'].text[0]
album = audio['TBPM'].text[0]
genre = audio['TCON'].text[0]
bpm = audi... |
# -*- coding: utf-8 -*-
#
# This file is part of Flask-AppExts
# Copyright (C) 2015 CERN.
#
# Flask-AppExts is free software; you can redistribute it and/or
# modify it under the terms of the Revised BSD License; see LICENSE
# file for more details.
"""Flask-Breadcrumbs extension."""
from __future__ import absolute_i... |
import numpy as np
import torch
def as_numpy(x:torch.Tensor) -> np.ndarray:
if isinstance(x, np.ndarray):
return x
x = x.detach()
if x.device.type >= 'cuda':
x = x.cpu()
x = x.numpy()
return x
def accuracy(y:torch.Tensor, t:torch.Tensor) -> float:
y = as_numpy(y)
t = as_num... |
import os
def install_source_package(src_package, config):
print(f"We install with apt-source >{src_package}< into >{config['ubuntu_src_pkgs']}{src_package}<")
try:
os.mkdir(config['ubuntu_src_pkgs'] + src_package)
except OSError:
print (f"Creation of the directory {config['ubuntu_src... |
#Read in .csv file with all salamander scores
import pandas as pd
from shutil import move
import os
os.chdir('/Users/maggie/Dropbox/P.cinereus_ML/Consensus_scores_NAs_updated/')
df = pd.read_csv('All_salamander_scores.csv')
#df = pd.read_csv('/Users/maggie/Dropbox/P.cinereus_ML/Consensus_scores_NAs_updated/All_salam... |
import yaml
import os
import os.path
from optparse import OptionParser
from shutil import copyfile
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import appdirs
from nab.scheduler import scheduler, tasks
from nab import log
_log = log.log.getChild("config")
config_dir = a... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.