text stringlengths 8 6.05M |
|---|
# The isBadVersion API is already defined for you.
# @param version, an integer
# @return a bool
# def isBadVersion(version):
class Solution:
def firstBadVersion(self, n):
"""
:type n: int
:rtype: int
"""
#二分搜索
l = 1
h = n
while l<h:... |
from amath.constants import inf
from .mean import mean
def slope(x1, y1, x2, y2):
from amath.DataTypes.Fraction import Fraction
dx = x1 - x2
dy = y1 - y2
if dx == 0:
return inf
return Fraction(dy, dx)
def sum(f, i=None, maximum=None, step=1, l=None):
try:
if type(f(2)) != flo... |
import datetime
import pandas as pd
columns = ["datetime", "label", "logits", "entropy"]
file_path = "tracking/training_data.csv"
def reset_data():
df = pd.DataFrame({}, columns=columns)
df.to_csv(file_path, header=True, index=False)
def save_data(label, logits, entropy):
df = pd.DataFrame({
"dat... |
# -*- coding: utf-8 -*-
'''
72. Edit Distance
Runtime: 232 ms
Memory Usage: 16.1 MB
'''
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
'''
Operations:
__________________
| replace | remove |
|_________|________|
| insert | |
|_________|________|
This ... |
from distutils.core import setup
setup(
name='KVM',
version='0.1',
author='Warren Spits',
author_email='warren@spits.id.au',
url='https://github.com/spitsw/kvm',
license='Creative Commons Attribution-Noncommercial-Share Alike license'
) |
import sqlite3
def create_table():
# will create if doesn't exist
conn=sqlite3.connect("lite.db")
print("db created")
cur=conn.cursor()
cur.execute("CREATE TABLE IF NOT EXISTS scoreboard (name TEXT, score INT)")
conn.commit()
print ("table created")
conn.close()
create_table()
|
import asyncio
from collections import deque
from concurrent.futures import ThreadPoolExecutor
from random import choice
from aiohttp import web
from common.request import post_request, get_request
class Scraper:
def __init__(self, host, port, parser_endpoints):
self.host = host
... |
from numpy import loadtxt
import numpy as np
from plotData import plotData
from computeCost import computeCost
from gradientDescent import gradientDescent
'''
%% Machine Learning Online Class - Exercise 1: Linear Regression
% Instructions
% ------------
%
% This file contains code that helps you get started on the
... |
from collections import defaultdict
from math import ceil
def solution(fees, records):
answer, visitor, time = [], [], []
record_dict = defaultdict(int)
for i in records:
if i[11:] == 'IN':
visitor.append(i[6:10])
time.append(int(i[0:2]) * 60 + int(i[3:5]))
else:
... |
# -*- coding: utf-8 -*-
import requests
import os
import json
import os.path
import PixivNotifier
import PixivUtil
def getFileExt(path):
return os.path.splitext(path)[1]
def getFileDir(file):
return os.path.split(file)[0]
class imgCache:
def __init__(self, d = 'imgCache/'):
self.setCacheDir(d)
def setCacheD... |
import uvicorn
uvicorn.run()
|
#! -*- coding:utf8 -*-
import os
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
from gensqlalorm.utils import (
format_for_hump
)
from gensqlalorm.db import (
desc_table,
show_tables,
show_create_table
)
def show_all_tables(project_name):
return show_tables(project_name)
def gen_table... |
CSRF_ENABLED = True
SECRET_KEY = 'CZ3003_Extinguisher'
SQLALCHEMY_DATABASE_URI = 'mysql://extinguisher:extinguisher@127.0.0.1/subscription'
|
s = input()
ps1 = s[:len(s)//2]
ps2 = s[(len(s)+2)//2:]
if s == s[::-1] and ps1 == ps1[::-1] and ps2 == ps2[::-1]:
print("Yes")
else :
print("No") |
import torch
import numpy as np
import torch.nn as nn
import copy
import math
from torch.nn import functional as F
def Linear(inputdim, outputdim, bias=True):
linear = nn.Linear(inputdim, outputdim, bias)
return linear
def clone(module, N):
return nn.ModuleList([copy.deepcopy(module) for _ in range(N)])... |
from openpyxl.compat.strings import unicode
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.keys import Keys
from base import *
import clsTestService
import enums
from general import General
class FreeTrial(Base):
driver = None
clsCommon = None
d... |
import glob, os, sys
import numpy as np
from random import*
import matplotlib.pyplot as plt
import matplotlib.cm as cmx
import matplotlib.colors as colors
def get_rand_color(val):
h,s,v = random()*6, 0.5, 243.2
colors = []
for i in range(val):
h += 3.75#3.708
tmp = ((v, v-v*s*abs(1-h%2), v-... |
# pip3 install --user QCustomPlot2
# change gui font size in linux: xrandr --output HDMI-0 --dpi 55
# https://pypi.org/project/QCustomPlot2/
# https://osdn.net/users/salsergey/pf/QCustomPlot2-PyQt5/scm/blobs/master/examples/plots/mainwindow.py
import PyQt5
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtWidgets... |
from sklearn.svm import SVR
import matplotlib.pylab as plt
import mglearn
import numpy as np
X, y = mglearn.datasets.make_wave(n_samples=100)
line = np.linspace(-3, 3, 1000, endpoint=False).reshape(-1, 1)
for gamma in [1, 10]:
svr = SVR(gamma=gamma).fit(X,y)
plt.plot(line, svr.predict(line), label='... |
import os
x = os.environ.get('EMAIL_USER')
y = os.environ.get('EMAIL_PASS')
ID = "working"
print(x)
print(y)
print(ID)
|
class Movie(object):
"""
This class represents movie object.
Attributes:
title (str): Title of the movie
story_line (str): A short description for the movie
poster_image_url (str): An URL of the poster image
trailer_youtube_url (str): An URL of the youtube trailer
""... |
import lasagne
import logging
import sys
import numpy as np
from braindecode.analysis.stats import wrap_reshape_topo, corr
from braindecode.experiments.experiment import create_experiment
from braindecode.experiments.load import load_exp_and_model
from braindecode.results.results import ResultPool
from braindecode.vega... |
import numpy
def rsi(prices, n=14):
'''
params:
prices: python list type, close price of list of time series candles
n: rsi params, default is 14
return:
rsi: python list type, rsi value of prices
'''
pass |
from django.shortcuts import render
from django.contrib.auth.models import User
from rest_framework import viewsets
from signin.serializers import UserSerializer
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
class UserViewSet(viewsets.Mod... |
# insurance-project
# This is an insurance project from codecademy
# Add your code here
medical_costs = {}
# medical_costs["James"] = 3323.3
medical_costs.update({"Marina": 6607.0, "Vinay": 3225.0})
medical_costs.update({"Connie": 8886.0, "Issac": 16444.0, "Valentina": 6420.0})
print(medical_costs)
medical_costs["Vin... |
import json
from bokeh.embed import components
from bokeh.layouts import column
from bokeh.models import ColumnDataSource, CustomJS, Select
from bokeh.plotting import figure
from bokeh.resources import INLINE
from bokeh.util.string import encode_utf8
from flask import Flask, jsonify, request
from jinja2 import Templat... |
q = int(input())
a, na = [], []
for c in range(q):
m, n = map(float, input().split(' '))
a.append(m)
na.append(n)
if max(na) < 8:
print('Minimum note not reached')
else:
for c in range(q):
if max(na) == na[c]:
print(int(a[c]))
|
import RPi.GPIO as GPIO
class Peltier:
@staticmethod
def init():
GPIO.setmode(GPIO.BOARD)
# warm
GPIO.setup(19,GPIO.OUT)
# cool
GPIO.setup(24,GPIO.OUT)
# enable
GPIO.setup(12,GPIO.OUT)
# test
#GPIO.setup(26,GPIO.OUT)
@staticmethod
def hot():
print("hot")
GPIO.output(19,GPIO.LOW)
GPIO.outp... |
# Copyright (c) 2018, EPFL/Human Brain Project PCO
#
# 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 applic... |
import argparse
import io
import re
import ebooklib
from bs4 import BeautifulSoup
from ebooklib import epub
from google.cloud import texttospeech
from google.oauth2 import service_account
from pydub import AudioSegment
from tqdm import tqdm
# max chunks to send each time
MAX_CHAR = 5000
blacklist = [
"[document]... |
# encoding: utf-8
from tastypie.constants import * |
import multiprocessing
import time
from object_recognition_multiprocessing.functions.evaluation import generate_json_evaluation
from object_recognition_multiprocessing.functions.final_filters import final_filter
from object_recognition_multiprocessing.functions.images_manager import ask_test_image, get_templates
from ... |
import itertools
import os
import urllib.request
import re
# PREWORK
TMP = os.getenv("TMP", "/tmp")
DICT = 'dictionary.txt'
DICTIONARY = os.path.join(TMP, DICT)
urllib.request.urlretrieve(
f'https://bites-data.s3.us-east-2.amazonaws.com/{DICT}',
DICTIONARY
)
with open(DICTIONARY) as f:
dict... |
import pkg_resources
import sys
import warnings
import threading
import time
from logger.scream import say
try:
import MySQLdb as MSQL
except ImportError:
import _mysql as MSQL
IP_ADDRESS = "10.4.4.3" # Be sure to update this to your needs
threads = []
connection = None
def deprecated(fu... |
import os
# 获得当前路径
cwd = os.getcwd()
print(cwd)
# 得到当前文件夹下的所有文件和文件夹
print(os.listdir()) # listdir(../)
# 检查是否是文件/文件夹
print(os.path.isfile('E:/sanfordpython/self_study/exercise/tests/path.py'))
print(os.path.isdir('E:/sanfordpython/self_study/exercise/tests'))
# 检查文件路径是否存在
print(os.path.exists('E:/sanfordpython/sel... |
from prediction.Tournament import *
RRR = "dsf" |
print 'Saludos'
|
# Generated by Django 3.1.5 on 2021-01-27 12:42
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Photo',
fields=[
('id', models.AutoField(au... |
#!/usr/bin/env python
# encoding: utf-8
"""
@author: ShengGW
@time: 19/07/28 16:08
@file: GetShapefileCover.py
@version: ??
@software: PyCharm
@contact: shenggw95@gmail.com
"""
from osgeo import gdal, gdalnumeric, ogr
from PIL import Image, ImageDraw
import os
import numpy as np
import DIPy.SpectralIndex ... |
# Generated by Django 2.2.4 on 2019-08-31 14:47
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('encuestas', '0002_auto_20190831_1145'),
]
operations = [
migrations.AddConstraint(
model_name='pregunta',
constraint... |
#coding:utf-8
#实时边缘检测
#导入opencv-python
import cv2
#导入科学计算库numpy
import numpy as np
#获取摄像头,传入0表示获取系统默认摄像头
cap = cv2.VideoCapture(0,cv2.CAP_DSHOW)
#打开cap
cap.open(0)
#循环
while cap.isOpened():
#获取画面
flag,frame = cap.read()
if not flag:
break
#进行canny边缘检测
frame = cv2.Canny(frame,50,100)
#... |
#!/usr/bin/env python3
from sys import getsizeof
from pathlib import Path
import subprocess
import os
import io
import re
class Exit:
def __init__(self, arguments, instream):
instream.close()
def execute(self):
exit()
class Cd:
def __init__(self, arguments, instream):
self.argu... |
import uml
from labop import Primitive, Protocol, SampleArray, SampleData, SampleMap, SampleMask
def protocol_template():
"""
Create a template instantiation of a protocol. Used for populating UI elements.
:param
:return: str
"""
return f'protocol = labop.Protocol(\n\t"Identity",\n\tname="Nam... |
#-*- coding:utf8 -*-
# Copyright (c) 2020 barriery
# Python release: 3.7.0
# Create time: 2020-07-20
import sys
import json
import grpc
from .proto import schedule_service_pb2 as schedule_pb2
from .proto import schedule_service_pb2_grpc as schedule_service_pb2_grpc
class ScheduleClient(object):
def __init__(self):... |
import os
import numpy as np
import pytest
try:
from unittest import mock
except ImportError:
import mock
from smalldataviewer import DataViewer
from smalldataviewer.files import offset_shape_to_slicing, FileReader, NORMALISED_TYPES
from .constants import OFFSET, SHAPE, INTERNAL_PATH
@pytest.mark.parametr... |
from django.http import HttpResponse,HttpResponseRedirect
from django.shortcuts import render_to_response
from LSMS.SM.libs import *
from LSMS.SM.models import *
import datetime
def msg(request):
return render_to_response('message.html',{'mbody':request.GET.get('mbody',''), 'mtype':request.GET.get('mtype','... |
from datetime import datetime
from flask import Flask, render_template, url_for, request, session, redirect, flash
import data_manager
from util import json_response
app = Flask('__name__')
# app.secret_key = data_manager.random_api_key()
app.secret_key = '123'
@app.route('/')
def index():
return render_templat... |
import os
import shutil
from datetime import datetime
from django import forms
from django.core.files.storage import default_storage
from excelapp.models import Tm_Department, Tm_Service
from excelapp.utils.file_util import CustomFile
class ServiceForm(forms.Form):
department = forms.ModelChoiceField(
l... |
# coding=utf-8
import os
import sys
import json
import time
import wave
import base64
import signal
import pyaudio
import threading
#from apa102_pi.colorschemes import colorschemes
IS_PY3 = sys.version_info.major == 3
WIDTH = 2
CHANNELS = 1
RECORD_SECONDS = 5
CHUNK = 1024
if IS_PY3:
from ur... |
__author__ = 'Greg Ziegan'
from .models import User
class PhoneAuthBackend(object):
def authenticate(self, phone, password):
try:
user = User.objects.get(phone=phone)
if user.check_password(password):
return user
except User.DoesNotExist:
return... |
# -*- coding: utf-8 -*-
{
'name': 'POS Graph Customize',
'summary': 'New Point of Sale Graph with new filters',
'version': '0.1',
'category': 'Point of sale',
'description': """
POS Graph Customize
============================================================================================
Features... |
from regionProposal import processing
import cv2
def outputVideo(clf, nonFiltered):
# loading video
print('Load video')
try:
mpgFile = '../data/input.mpg'
vidcap = cv2.VideoCapture(mpgFile)
cnt = 0
falseCnt = 0
prevRect = []
printed = []
length = in... |
for i in range(0, 6):
print i
a='a'
print ord('A')
print chr(65) |
import sys
import sdl2
import sdl2.ext
class MovementSystemAirHockey(sdl2.ext.Applicator):
def __init__(self, minx, miny, maxx, maxy, midline):
super(MovementSystemAirHockey, self).__init__()
self.componenttypes = Velocity, sdl2.ext.Sprite
self.minx = minx
self.miny = miny
s... |
'''
具体思考见java解法,主要是要理清楚思路
'''
class Solution:
def convert(self, s: str, numRows: int) -> str:
if s is None or len(s) <= numRows or numRows == 1:
return s
k1 = 2 * numRows - 2
result = ""
for i in range(numRows):
if i == 0 or i == numRows - 1:
... |
'''
added xavier_initializer
added dropout
'''
import numpy as np
import tensorflow as tf
import os
import sys
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets('/home/mhkim/data/mnist', one_hot=True)
train_checkpoint = '/home/mhkim/data/checkpoint/mnist_nn/'
if tf.gfile.E... |
# encoding: utf-8
from tastypie.authorization import * |
"""
Ejercicio 2
Una empresa requiere cierto número de trabajadores que laboren durante 8 horas diarias en diferentes días de la semana.
Los trabajadores deben desempeñar sus cargos 5 días consecutivos y descansar 2 días. Por ejemplo, un trabajador que labora
de martes a sábado, descansaría el domingo y el lunes
"""
... |
import fnmatch
import os
import string
import shutil
searchStr = u"\u003F"
for root, dirnames, filenames in os.walk('./wiki/commons/'):
for dirname in dirnames:
if "?" in dirname or "\"" in dirname or "*" in dirname:
print(root+'/'+dirname)
shutil.rmtree(root+'/'+dirname)
|
# -*- coding: utf8 -*-
from jiendia.test.io import DATA_DIR
def test_read():
from jiendia.io.archive.seq import SeqArchive
with SeqArchive(DATA_DIR + '/010_01_01_STAND_R.SEQ') as seq:
assert len(seq.frames) > 0
for index, frame in enumerate(seq.frames):
assert frame.number == index ... |
# 优化前
class Solution:
def plusOne(self, digits: List[int]) -> List[int]:
ret = []
sign = 0
for i in range(len(digits)-1, -1, -1):
if i == len(digits)-1:
t = digits[i] + 1
else:
t = digits[i] + sign
if t == 10:
... |
from lib import settings
class Controller:
def steer_left(self):
pass
def steer_right(self):
pass
def steer_neutral(self):
pass
def forward(self, power: int = 100):
pass
def reverse(self, power: int = 100):
pass
def neutral(self):
pass
... |
import requests, ctypes, urllib.request
from unsplash import Unsplash
# Path for the image
path = "YourPath/unsplash.jpg"
# Instantiate Unsplash Object
u = Unsplash()
# Photo url
photo = ""
# -------------------
# Change Background
# -------------------
def change_desktop(photo):
# save image locally
urllib.req... |
#!/usr/bin/env python
# coding: utf-8
from reconciliationICBC import DealExcelICBC,CheckICBC
from reconciliationABC import DealExcelABC,CheckABC
from reconciliationBOC import DealExcelBOC,CheckBOC
from reconciliationCCB import DealExcelCCB,CheckCCB
from reconciliationCEB import DealExcelCEB,CheckCEB
from recon... |
import numpy as np
import pandas as pd
import chartify
data = pd.DataFrame({'time': pd.date_range('2015-01-01', '2018-01-01')})
n_days = len(data)
data['1st'] = np.array(list(range(n_days))) + np.random.normal(
0, 10, size=n_days)
data['2nd'] = np.array(list(range(n_days))) + np.random.normal(
0, 10, size=n_da... |
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# 示例一,函数传入可变参数的几个问题-------------------------------------------
def change(a, b):
"""
两种传递参数的方式:
1.不可变对象作参数,通过“值”进行传递
2.可变对象作参数,通过“指针”进行传递。如果在函数中,对不可变参数进行了原处修改(如append),其全局对象也会改变
"""
a = 2
b[0] = 'spam'
x = 1
y = [1, 2]
change(x, y)
print(x, y)... |
# -*- coding: utf-8 -*-
from typing import Text
# noinspection PyProtectedMember
from bs4 import SoupStrainer
from .base import FeedFetcher
class SmzdmFetcher(FeedFetcher):
FILTER = SoupStrainer('article', 'article-details')
def __init__(self, keywords=None):
super().__init__()
self.keyword... |
# -*- coding: utf-8 -*-
from scrapy import Spider, Request
from linux_jobs.items import LinuxJobsItem
from bs4 import BeautifulSoup
import re
class LinuxJobSpider(Spider):
name = 'linux_job'
allowed_domains = ['51job.com']
start_urls = ['https://m.51job.com/search/joblist.php?keyword=linux&keywordtype=2']... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# otra_app.py
#
from Tkinter import *
def mi_funcion():
print esto
app = Tk()
app.title("Aplicacion grafica en python")
etiqueta = Label(app, text="Hola mundo!!!")
boton = Button(app, text="OK!!")
mi funcion = "eje"
etiqueta.pack()
boton.pack()
app.mainloop()... |
from app import app
from flask import render_template, jsonify, request
from flask import send_file
from response import *
import random
from lxml import etree
from urllib.request import urlopen
import json
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import requests
from pytz impor... |
from abc import ABC, abstractmethod
import torch
from torch import nn
from torch import distributions as D
class BaseSPN(nn.Module, ABC):
'''
based on a RAT-SPN structure
batch: batch size
R: number of replicas in the RAT-SPN
xdim: number of dime... |
import logging
import random
from opencensus.trace import config_integration
from opencensus.trace.samplers import AlwaysOnSampler
from opencensus.trace.tracer import Tracer
from opencensus.stats import aggregation as aggregation_module
from opencensus.stats import measure as measure_module
from opencensus.stats impo... |
import numpy as np
import funcs
import math
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as pltt
print 'PSO routine to find minimum of defined objective function'
print '=========================================================\n'
#Standard PSO routine---------------------------------------------... |
from pyasn1.type.constraint import ValueRangeConstraint, ConstraintsIntersection, ConstraintsUnion, SingleValueConstraint, \
ValueSizeConstraint
MIN = float('-inf')
MAX = float('inf')
class NoConstraint(ConstraintsIntersection):
def __init__(self):
self.extensionMarker = False
self.lowerEndp... |
from django.shortcuts import render
from django.http import HttpResponse, HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.template import RequestContext
from app.authhelper import get_signin_url, get_token_from_code
import requests
import urllib
def home(request):
# Redirect to group... |
import re
class Config:
def __init__(self):
self.data = {
'dataset' : None,
'mnist_la_autoencoder' : None,
'mnist_la_autoencoder_classifier' : None,
'mnist_la_simple_classifier' : None,
'fashion_mnist_la_autoencoder' : None,
'fashion_m... |
print ("This is Anjar")
print ("Welcome to Python Tutorial by Anjar") |
from django.db import models
from django.utils.timezone import now
class forecast_img(models.Model):
img = models.ImageField(upload_to='forecast_img')
name = models.CharField(max_length=100)
class forecastol_img(models.Model):
'''
name = models.CharField(max_length=50, default="")
time = models.Da... |
import core.models as coremodels
damadam_url = 'http://apollo7788.pagekite.me'
damadam_user = 'aasanads'
damadam_pass = 'damadam1234'
import json
import unirest
def deleteTopup(tid, callback):
data = {}
data['tid'] = tid
data = json.dumps(data)
unirest.post(damadam_url + "/api/ad/delete/", headers={ "Content-type"... |
# -*- coding:utf-8 -*-
# 递归解法
'''
解决两个字符串的动态规划问题,一般都是用两个指针 i,j 分别指向两个字符串的最后,然后一步步往前走,缩小问题的规模。
'''
'''
dp(i, j)的定义:返回 s1[0..i] 和 s2[0..j] 的最小编辑距离
'''
def min_distance(s1, s2):
def dp(i,j):
if i == -1:
return j + 1
if j == -1:
return i + 1
if s1[i] == s2[j]:
return dp(i-1, j-1)
else:
# 插入情况 ... |
def generateKey(string, key):
key = list(key)
if len(string) == len(key):
return (key)
else:
for i in range(len(string) -
len(key)):
key.append(key[i % len(key)])
return ("".join(key))
def cipher_text(string, key):
cipher_text = []
for i in ra... |
from datetime import datetime
from django import forms
from django.contrib import admin
from organisations.models import OrganisationDivision
class CurrentDivisionFilter(admin.SimpleListFilter):
title = "Current Divisions"
parameter_name = "is_current"
def lookups(self, request, model_admin):
re... |
#coding:utf-8
def script(s, player=None):
from NaoQuest.quest import Quest
from NaoSensor.plant import Plant
if not player:
print("Error in execution of post_script \"testobj1_post\": player is None")
return
# on choppe la plante liée à cette quete pour modifier ce que doit dire nao
... |
from preprocessing.misc_processing import *
from preprocessing.evaluator import *
from preprocessing.dataset_loader import *
from preprocessing.dataset import *
from preprocessing.tweet_paraphrase import *
from preprocessing.mrpc import *
|
from RPi import GPIO
import datetime
import logging
import subprocess
from Lib import *
from pathlib import Path
import mysql.connector as mariadb
logging.basicConfig(level=logging.DEBUG)
log = logging.getLogger("MAIN_LOG")
class Device:
def __init__(self):
GPIO.cleanup()
# pinmode BCM
G... |
from init import get_driver
from mattermostdriver.exceptions import ResourceNotFound
class Notifier:
def __init__(self):
self.client = get_driver()
self.client.login()
self.user_id = self.client.users.get_user_by_username("jarvisbot")["id"]
def notify(self, message, email):
... |
# Generated by Django 3.1.3 on 2020-11-16 00:23
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('rest_api', '0004_auto_20201115_1735'),
]
operations = [
migrations.CreateModel(
name='Profile',... |
#!/usr/bin/env python
# encoding: utf-8
"""
hfetcher.py
Created by yang.zhou on 2012-10-29.
Copyright (c) 2012 zhouyang.me. All rights reserved.
"""
|
import pytest
def test_fail():
if True == False:
pytest.fail()
<warning descr="This code is unreachable">print("should be reported as unreachable")</warning>
else:
return 1 |
from rdflib.namespace import RDF
from source.utils import id2uri, g_add_with_valid
import csv
import json
def create_ttl(g, u, row: dict):
"""
baid: 99415175
activity: Active
aid: 47346
sid: 103186613
cid: 44273608
geneid: 10203
pmid: 9438028
aidtype: Confirmatory
aidmdate: 201... |
d1, d2, d3 = map(int, input().split())
print(min([2*(d1+d2), d1+d2+d3, 2*(d1+d3), 2*(d2+d3)]))
|
# -*- coding: utf-8 -*-
'''
Created on 24-08-2013
@author: Krzysztof Langner
'''
from sloppy.interpreter import Runtime
import os.path
import unittest
COMMANDS_FILE = os.path.join(os.path.dirname(__file__), 'testdata/commands.txt')
PARSER_KEYWORDS = [
['count'],
['events']
... |
def solution(food):
foods = ''
for i in range(1, len(food)):
if food[i] % 2 == 1:
foods += str(i) * ((food[i] - 1) // 2)
else:
foods += str(i) * (food[i] // 2)
return foods + '0' + foods[::-1] |
from collections import defaultdict, deque, Counter
import sys
from decimal import *
from heapq import heapify, heappop, heappush
import math
import random
import string
from copy import deepcopy
from itertools import combinations, permutations, product
from operator import mul, itemgetter
from functools import reduce,... |
from django.shortcuts import render
def home_index(request):
return render(request, 'home_index.html', {'nav': 'home'}) |
from django import forms
from django.forms import ModelForm
from .models import User,Patient,Doctor,Service,Appointment
class LoginForm(forms.Form):
email = forms.EmailField(required=True)
password = forms.CharField(required=True)
class SignUpForm(forms.Form):
email = forms.EmailField(required=True)
... |
import sys
sys.path.append('../1/')
sys.path.append('../2/') |
import sys
import random
train_file = 'train.tsv'
dev_file = 'dev.tsv'
train_data_ratio = 0.7 # train.tsvのデータとdev.tsvのデータの比率
random.seed(0)
def read_file(input_file):
with open(input_file, 'r', encoding='utf-8', newline='') as fr:
text = fr.readlines()
for i, line in enumerate(text):
... |
#!/usr/bin/python3
try:
some codes
except(RuntimError, TypeError, NameError):
exception handlers
except:
default handler
else:
print("something will be done if no exception")
finally:
print("finally clause: do some clean-up actions")
# some exceptions
* SyntaxError
* ImportError
* NameError name ... |
import RPi.GPIO as GPIO
from itertools import repeat
from datetime import datetime,time
from time import sleep
from pytz import timezone
import logging,pdb, sys
'''initial var'''
RELAIS_4_GPIO = 22
water_time = 1800 #30 min
tz = 'Rome'
'''logging config'''
logging.basicConfig(
level=logging.INFO,
file... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.