text stringlengths 8 6.05M |
|---|
def jonSnowParents(dad, mom):
if dad == 'Rhaegar Targaryen' and mom == 'Lyanna Stark':
return 'Jon Snow you deserve the throne'
return 'Jon Snow, you know nothing'
|
from django.contrib import admin
from .models import device, data
# Register your models here.
@admin.register(device)
class DeviceAdmin(admin.ModelAdmin):
list_filter = ('id',)
search_fields = ('id',)
@admin.register(data)
class DataAdmin(admin.ModelAdmin):
list_filter = ('name',)
search_fields = (... |
# Copyright 2022 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
from pants.backend.python.subsystems.python_tool_base import PythonToolBase
from pants.backend.python.target_types import ConsoleScript
from pants.engin... |
import matplotlib.pyplot as plt
import numpy as np
y = np.arange(4)
country = ['Germany', 'US', 'Korea', 'Canada']
values = [9, 243, 45, 239]
plt.title("The figure of Gold medal in four different countries")
plt.grid(True, axis='x', color='#D9E4E7', alpha=0.5, linestyle='--')
plt.barh(y, values, height=-0.6, align='... |
# -*- coding: utf-8 -*-
# Copyright 2015 Mirantis, Inc.
#
# 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 requi... |
__author__ = 'sb5518'
from unittest import TestCase
import os
import aggregated_grades_generator as agg
import graph_generator as gg
import data_cleaner as dc
import grades_calculator as gc
import warnings
warnings.filterwarnings("ignore") # This is used to avoid printing some Pandas FutureWarnings
class all_tests... |
from rest_framework import serializers
from rest_framework.reverse import reverse as drf_reverse
from .models import Mimic
class MimicSerializer(serializers.ModelSerializer):
links = serializers.SerializerMethodField()
class Meta:
model = Mimic
def get_links(self, obj):
request = self.co... |
#!/usr/bin/python2.7
# -*- coding:utf-8 -*-
'''
每年六一儿童节,牛客都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此。
HF作为牛客的资深元老,自然也准备了一些小游戏。其中,有个游戏是这样的:首先,让小朋友们围成一个大圈。
然后,他随机指定一个数m,让编号为0的小朋友开始报数。每次喊到m-1的那个小朋友要出列唱首歌,
然后可以在礼品箱中任意的挑选礼物,并且不再回到圈中,从他的下一个小朋友开始,继续0...m-1报数....
这样下去....直到剩下最后一个小朋友,可以不用表演,并且拿到牛客名贵的“名侦探柯南”典藏版(名额有限哦!!^_^)。
请你试着想下,哪个小朋友会得到这份礼品... |
import cv2 as cv
import numpy as np
from nptyping import NDArray
from display import Display
class DisplaySim(Display):
__WINDOW_NAME: str = "RacecarSim display window"
def __init__(self, isHeadless) -> None:
Display.__init__(self, isHeadless)
def create_window(self) -> None:
if not sel... |
import unittest
from katas.kyu_7.sum_of_all_arguments import sum_args
class SumArgsTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(sum_args(1, 2, 3), 6)
def test_equals_2(self):
self.assertEqual(sum_args(8, 2), 10)
def test_equals_3(self):
self.assertEqual(s... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Field(object):
def __init__(self, name, datatypename, description, required):
self._name = name
self._datatypename = datatypename
self._description = description
self._required = required
@property
def name(self):
... |
import numpy as np
import tensorflow as tf
# Hyperparameter define / 하이퍼 파라미터 정의
# Learning Rate = Alpha
class DQN:
def __init__(self, session: tf.Session, state_size: int, action_size: int, name: str="main") -> None:
"""Dueling QN Agent can
1) Build network
2) Predict Q_value given stat... |
g = int(input("g: "))
if g < 60:
print("Bad!")
elif 60 <= g < 70:
print("Not Bad")
elif 70 <= g < 80:
print("Good!")
elif 80 <= g < 90:
print("Great!")
elif 90 <= g < 100:
print("Excellent!")
elif g == 100:
print("Perfect!")
else:
print("Pardon?")
# 檔名: exercise0603.py
# 作者: Kaiching Chang
# 時間... |
from django.urls import path
from django.urls.conf import re_path, path
from .apis import *
urlpatterns = [
path('imports/add', AddImportApi.as_view(), name='import_add'),
re_path(r'^imports/list/(?:start=(?P<start>(?:19|20)\d{2}(0[1-9]|1[012])))&(?:end=(?P<end>(?:19|20)\d{2}(0[1-9]|1[012])))$', ImportListApi... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Thu May 23 08:06:43 2019
@author: juancastro
"""
import turicreate
data = turicreate.SFrame({
'user_id': ["Ann", "Ann", "Ann", "Brian", "Brian", "Brian"],
'item_id': ["Item1", "Item2", "Item4", "Item2", "Item3", "Item5"],
'rating': [1, 3, 2, 5, 4, 2]})
m =... |
#encoding:utf-8
from flask import Flask
import config
from flask_rabbitmq import Queue, RabbitMQ
app = Flask(__name__)
app.config.from_object(config)
queue = Queue()
rpc = RabbitMQ(app, queue)
from app import views,demo |
class Myqueue:
#构造函数设置默认队列
def __init__(self,size = 10):
self._content = []
self._size = size
self._current = 0
def setSize(self,size):
if size < self._current:
for i in range(size,self._current)[::-1]:
del self._content[i]
self._curre... |
import tensorflow as tf
import numpy as np
tf.reset_default_graph()
a = tf.placeholder(tf.int32, shape=(), name="input")
b = tf.get_variable("b", shape=(), dtype=tf.int32)
asquare = tf.multiply(a, a, name="output")
sess = tf.Session()
sess.run(tf.global_variables_initializer())
print(sess.run([asquare], feed_dict={a:... |
"""
Tools for IO coder:
* Creating RecordingChannel and making links with AnalogSignals and
SPikeTrains
"""
try:
from collections.abc import MutableSequence
except ImportError:
from collections import MutableSequence
import numpy as np
from neo.core import (AnalogSignal, Block,
Ep... |
from socket import *
import os
import sys
import struct
import time
import select
import binascii
ICMP_ECHO_REQUEST = 8
RTT_list = [] #list of RTTs
pkts_sent = 0 #number of packets sent
pkts_rec = 0 #number of packets received
def MyChecksum(hexlist):
summ=0
carry=0
for i in range(0,le... |
import cv2
import time
import numpy
import sys
from . import controller
# Camera 0 is the integrated web cam on my netbook
camera_port = 0
# Number of frames to throw away while the camera adjusts to light levels
ramp_frames = 30
# Now we can initialize the camera capture object with the cv2.VideoCapture class.
# Al... |
import unittest
from katas.kyu_7.please_help_bob import err_bob
class BobTestCase(unittest.TestCase):
def test_equal_1(self):
self.assertEqual(err_bob('r r r r r r r r'),
'rerr rerr rerr rerr rerr rerr rerr rerr')
def test_equal_2(self):
self.assertEqual(err_bob('THI... |
import error_log
def connection_string():
return 'pq://postgres:postgres@localhost:5432/postgres'
def get_element_area(screen_area, element, db):
sql = "select " + element + " from screen_coordinates where screen_area = $1 and active = 1"
data = db.query.first(sql, int(screen_area))
return data
de... |
'''
Created on Nov 24, 2014
@author: Idan
'''
import unittest
import k_mean_module
from src.k_mean_module import mean_varience_diff
K_STATIC = 4
ITER_STATIC = 50
SIG=0.5
MU=1
class Kmean_Test(unittest.TestCase):
def setUp(self,P=80):
'''
#for fixture
define the fixure
'''
... |
# -*- coding: utf-8 -*-
"""
Created on Sat May 23 18:05:45 2015
@author: Martin Nguyen
"""
numberofPatients = 6
class PlottingSystem(object):
def __init__(self,plt):
self.plt = plt
self.newlist = []
self.newlist1 = []
self.newlist2 = []
self.newlist3 = []
self.newlis... |
output = 'Hello, World!'
print(output)
|
class Solution:
def is_prime(self, input):
answer = True
for i in range(2,input):
if input%i == 0:
answer = False
break
else:
continue
return answer
|
#Cleaning data by removing unimportant columns and creating a DataFrame for classification process.
dataSubTrajectories = pd.DataFrame(A2FiltTraj, columns = ['t_user_id', 'transportation_mode', 'date_Start', 'flag'
, 'minDis' ,'maxDis', 'meanDis', 'medianDis', 'stdDis'
... |
from dronekit import connect, VehicleMode, LocationGlobalRelative, APIException, Command
import time
import socket
import exceptions
import math
import argparse #To import some values from command line and use it on our python script
from pymavlink import mavutil
#####################functions####
def conne... |
#coding: utf-8
from __future__ import print_function, absolute_import
import logging
import re
import json
import requests
import uuid
import time
import os
import argparse
import uuid
import datetime
import socket
import apache_beam as beam
from apache_beam.io import ReadFromText
from apache_beam.io import WriteToTe... |
# coding: utf-8
from __future__ import print_function
def retrain(data):
print('scikit_entries.retrain called.')
def fetch():
print('scikit_entries.fetch called.')
def main(rpc_service,
continuum_host='localhost',
continuum_port=7001,
redis_host='localhost',
redis_port=... |
class Solution:
def countAndSay(self, n):
"""
:type n: int
:rtype: str
https://leetcode.com/problems/count-and-say/discuss/16043/C++-solution-easy-understand
https://leetcode.com/problems/count-and-say/discuss/16044/Simple-Python-Solution
"""
res = "1"
... |
import random
import colorama
from colorama import Fore, Back, Style
class Deck:
cards = []
def __init__(self):
for card_num in range(1,6):
if card_num == 1:
n = 3
elif card_num == 5:
n = 1
else:
n = 2
... |
import io
from random import randint
from typing import List
import pytest
from starlette.applications import Starlette
from starlette.endpoints import HTTPEndpoint
from starlette.responses import JSONResponse
from starlette.routing import Mount, Route
from starlette.staticfiles import StaticFiles
from starlette.testc... |
from SupportClasses.DatasetLabels import DatasetLabels
from SupportClasses.LabelDictionary import LabelDictionary
import numpy as np
class DatasetChildLabels(DatasetLabels):
def __init__(self, dataset, labelPosition='last'):
# super
DatasetLabels.__init__(self, dataset, labelPosition)
# o... |
from django.contrib import admin
from .models import Question, Quiz
class QuizAdmin(admin.ModelAdmin):
list_display = ('name', 'is_active',)
search_fields = ('name', 'is_active')
admin.site.register(Question)
admin.site.register(Quiz, QuizAdmin)
|
from django.db import models
# Create your models here.
class User(models.Model):
username = models.CharField(max_length=32)
password = models.CharField(max_length=32)
email = models.EmailField(max_length=75, default='')
name = models.CharField(max_length=256, default='')
# Allows for a bala... |
from __future__ import print_function
import time
import unittest
from flexp.flow.parallel import parallelize
def add_two(x):
return x + 2
class TestParallel(unittest.TestCase):
def test_parallel(self):
count = 50
data = range(0, count)
start = time.clock()
res = list(par... |
import openpyxl
if __name__ == "__main__":
wb = openpyxl.load_workbook('tongyong.xlsx')
sheets = wb.sheetnames
for sheet in wb:
# 创建一个文件保存通用词
tmp = ''
for row in sheet.values:
for value in row:
if value is not None:
tmp += value + '\n'... |
import sys
tree = {}
length = 0
while True:
n = sys.stdin.readline().rstrip()
if not n:
break
tree.setdefault(n, 0)
tree[n] += 1
length += 1
for i in sorted(tree.keys()):
print('%s %.4f' %(i, ((tree[i] / length) * 100))) |
from flask import Flask, request, render_template, redirect, send_file
from docx import Document
from docx.shared import Inches
from builtins import str
import os
import docx
from datetime import datetime
app = Flask(__name__)
@app.route('/')
def my_form():
return render_template('index.html') # Return here yo... |
# importing module https://github.com/ytdl-org/youtube-dl
import youtube_dl
ydl_opts = {}
def dwl_vid():
with youtube_dl.YoutubeDL(ydl_opts) as ydl:
ydl.download([zxt])
link_of_the_video = "https://www.youtube.com/watch?v=XXXXXX"
zxt = link_of_the_video.strip()
dwl_vid()
|
import argparse
class Config():
def __init__(self):
pass
def parse(self):
parser = argparse.ArgumentParser(description='GAN generation')
###parsing
parser.add_argument('--input_nc_G_parsing', type=int, default=45, help='# of input image channels: 3 for RGB and 1 for g... |
from django.conf.urls import url
from . import views
from django.urls import path,include
urlpatterns = [
url(r'^activate/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{1,13}-[0-9A-Za-z]{1,20})/$',
views.activate, name='user-activate'),
url(r'^terms/(?P<uidb64>[0-9A-Za-z_\-]+)/(?P<token>[0-9A-Za-z]{... |
Последовательность x_n имеет предел, а последовательность y_n не имеет предела. Отметьте утверждения, которые могут оказаться верными. (Т.е. существуют такие имеющая конечный предел последовательность xn и не имеющая предела последовательность yn, что...)
Последовательность x_n*y_n не имеет предела
Последовательность ... |
import html
import logging
import re
import time
from bs4 import BeautifulSoup
from pymongo import MongoClient, errors
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
class PikabuParser:
def __init__(self, urls):
self.urls = urls
def initWebdriver(self, is_hea... |
class MedianFinder(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.big_queue = []
self.small_queue = []
def addNum(self, num):
"""
:type num: int
:rtype: None
"""
if len(self.big_queue) == 0:
... |
input = "28992"
inputChars = (
'2000' ,
'2001' ,
'2002' ,
'2003' ,
'2004' ,
'2005' ,
'2006' ,
'2007' ,
'2008' ,
'2009' ,
'2010' ,
'2011' ,
'2012' ,
'2013' ,
'2014' ,
'2015' ,
'2016' ,
'2017' ,
'2018' ,
'2019' ,
'2020' ,
'2021' ,
'2022' ,
'2023' ,
'2024' ,
'2025' ,
'2026' ,
'2027' ,
'2028' ,
'2029' ,
'2030' ,
'2031' ,
'... |
# Input a number and find its factors
n=input("Enter a number:")
for i in range (1,n+1):
if(n%i==0):
print i
|
"""
This is the autoML interface.
[Modified to interact with pytorch and to use it as API]
Replace THISISYOURSERVICEACCOUNT.json in line 40 with your service account credentials.
"""
import os
import pickle
# from PIL import Image
# import numpy as np
from google.cloud import automl, storage
import google
from a... |
# coding: utf-8
# Python script created by Lucas Hale and Karina Stetsyuk
# Standard library imports
import datetime
import random
from typing import Optional
# https://github.com/usnistgov/atomman
import atomman as am
import atomman.lammps as lmp
import atomman.unitconvert as uc
from atomman.tools import filltempl... |
from ._caffe import *
from .pycaffe import Net, SGDSolver
from .proto.caffe_pb2 import TRAIN, TEST
from .classifier import Classifier
from .detector import Detector
from . import io
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class Test(models.Model):
name=models.CharField(max_length=128)
def __unicode__(self):
return self.name
class Publisher(models.Model):
name = models.CharField(max_length=30)
... |
def Mod(x,y):
print(x/y)
|
# -*- coding: utf-8 -*-
#字元判斷
a=input()
if a.isalpha():
print(a,"is an alphabet.")
elif a.isdigit():
print(a,"is a number.")
else:
print(a,"is a symbol.")
|
__author__ = 'Ben'
from helper import greeting
greeting("master branch new file")
greeting("same file though") |
import numpy as np
import sys
def add_mat(A,B):
(n,p)=np.shape(A)
C=np.zeros([n,p])
for i in range(n):
for j in range(p):
C[i,j]=A[i,j]+B[i,j]
return C
#A=np.arange(1,12,2).reshape(3,2)
#print(add_mat(A,A))
def mult_scal_mat(A,x):
(n,p)=np.shape(A)
for i in ra... |
import json
with open('config.json') as config_file:
config = json.load(config_file)
if config is None:
raise Exception('No `config.json` provided.')
FREQUENCY = config['frequency_seconds']
REPOS = config['repos']
|
"""
Написать программу "Автодиллер", в которой будут:
Определятся три класса моделей авто:
- Бюджет (стоимость до 1000$, налог 3%),
- Семейный (стоимость до 5000$, налог 7%),
- Премиум (стоимость до 10000$, налог 12%)
Пользователь выбирает класс, указывает желаемую стоимость.
Программа расчитывает чистую стоимост... |
# FOR-IN
# ------
list1 = [1,2,3,4,5,6,7,8,9]
list2 = ["Blue", "Red", "Green", "Yellow"]
for item in list1: # item -> element di list
print(item) # mencetak item setiap item berurutan
# seperti
# print(1)
# print(2)
# print(3)
# print(4)
# print(5)
# print(6)
# print(7)
# print(8)
# print(9)
for element in lis... |
'''
결과를 각각 테스트 케이스가 끝날때마다 출력하면 ValueError가 떠버린다.
그래서 result 배열에 모든 결과를 저장해놓고 있다가 입력이 전부 끝나면
순차적으로 출력해줘야한다.
'''
from sys import stdin
from collections import deque
test = int(stdin.readline())
q = deque()
result = []
for i in range(test) :
checkReverse = 0 # 거꾸로 뒤집었는지 안뒤집었는지 체크하는 변수
errorCheck = Fa... |
# import subprocess
# #
# #
# #
# # while 1:
# # inp = input('>>>')
# #
# # obj = subprocess.Popen(inp,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
# # cmd_out = obj.stdout.read()
# # cmd_error = obj.stderr.read()
# #
# # print('------',str(cmd_error,'gbk'))
# # print(st... |
from django.db import models
class Tag(models.Model):
title = models.CharField(max_length=200)
def __str__(self):
return self.title
class Task(models.Model):
tag = models.ManyToManyField(Tag)
title = models.CharField(max_length=200)
description = models.TextField()
def __str__(self... |
#!/usr/bin/python
denoms = [200, 100, 50, 20, 10, 5, 2, 1]
def branch(total, index):
if total < 0:
return 0
elif total == 0:
return 1
else:
count = 0
for j in range(index, len(denoms)):
count += branch(total - denoms[j], j)
return count
print(branch(20... |
from django.shortcuts import render
# Create your views here.
def test_homepage(request):
context = {
}
return render(request, 'test_page.html', context)
|
################################################################################
# #
# UTILITY FUNCTIONS #
# ... |
###
### Copyright (C) 2018-2019 Intel Corporation
###
### SPDX-License-Identifier: BSD-3-Clause
###
from ....lib import *
from ..util import *
@slash.requires(have_ffmpeg)
@slash.requires(have_ffmpeg_vaapi_accel)
class EncoderTest(slash.Test):
def gen_input_opts(self):
opts = "-f rawvideo -pix_fmt {mformat} -s:... |
from unittest import TestCase
import os
from data_cleaner import DataReader
from restaurant_grades import RestaurantGrader
__author__ = 'obr214'
class Test(TestCase):
def test_datareader_file_not_found(self):
"""
Passing wrong filename to the DataReader Object
Result: It should raise IO... |
#程序爬取完当天数据的一个休眠时间
SLEEP_TIME = 60*60*12
#当爬取频率过高网站被封时的休眠时间
ERROR_SLEEP_TIME = 60*60*2
#当前爬取的域名
DOMAIN = 'http://www.zimeika.com'
#服务器地址
DB_HOST = '127.0.0.1'
#数据库名
DB_NAME = ''
#用户名
DB_USER = ''
#密码
DB_PWD = ''
|
from appium import webdriver
from common.base import log
from page.login_page import LoginPage
from page.home_page import HomePage
from page.deposit_record_page import DepositRecordPage
from page.account.bankcard_manage_page import BankcardManagePage
from page.withdraw.withdraw_page import WithdrawPage
from logic im... |
import math
import random
class Environment():
def __init__(self, width, height):
'''Takes width and height and creates a 2D environment of that size'''
self.width, self.height = width, height
self.obstacles = { (x, 0) for x in range(self.width) }
self.obstacles.update( [(x, self.height-1) for x in range(se... |
# Generated by Django 2.1.1 on 2018-09-20 07:59
import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('monitor', '0001_initial'),
]
operations = [
migrations.CreateMo... |
from django.conf.urls import url
from . import apis
urlpatterns = [
url(
regex="^rooms/$",
view=apis.RoomsApiListView.as_view(),
name='rooms',
),
url(
regex="^rooms/(?P<pk>\d+)/messages/$",
view=apis.MessagesApiListView.as_view(),
name='messages',
),
] |
from .raft import *
|
from __future__ import division, print_function, absolute_import
import tensorflow as tf
import numpy as np
import math
import matplotlib.pyplot as plt
def to_grayscale(im, weights = np.c_[0.2989, 0.5870, 0.1140]):
tile = np.tile(weights, reps = (im.shape[0], im.shape[1], 1))
return np.sum(tile * im, axis=2)
def c... |
def is_prime(n):
if n <= 1:
return False
for x in xrange(2, n):
if n % x == 0:
return False
return True
|
s=0
i=1
while i<=100:
if(i%7==0):
i+=1
continue
s+=i
i+=1
print("1부터 1000까지의 수 중에 7의 배수를 생략한 합",s)
s=0
for i in range(1,101):
if i%7==0:
continue
s+=i
print("1부터 1000까지의 수 중에 7의 배수를 생략한 합",s)
|
import sys,os
sys.path.insert(1,os.path.abspath(os.path.join(os.path.dirname( __file__ ),'..','..','lib')))
import time, pytest
from clsCommon import Common
import clsTestService
import enums
from localSettings import *
import localSettings
from utilityTestFunc import *
class Test:
#=========================... |
# -*- coding: utf-8 -*-
# Generated by Django 1.10.5 on 2017-05-03 13:32
from __future__ import unicode_literals
from django.db import migrations, models
import django.utils.timezone
class Migration(migrations.Migration):
dependencies = [
('myplace', '0001_initial'),
]
operations = [
mi... |
#!/usr/bin/python
"""
straightLineSpeedTest2.py needs to be run from the command line
This code is for use in the Straight Line Speed Test - PiWars 2017 challenge
http://piwars.org/
"""
# Import required libraries
import time
import logging
import KeyboardCharacterReader
import DualMotorController
import UltrasonicSen... |
import json
from django.core.management.base import BaseCommand
from django.utils import timezone
from routes.models import Route
class Command(BaseCommand):
"""
Create Route object from json.
The json data needs to have this format in order to be
displayed properly in the map:
{"polyline": [... |
from django.core.management.base import BaseCommand
from django.utils import timezone
from datetime import datetime, timedelta
from notification.models import Notification
from django.utils import timezone
from visitors.models import Track_Entry
from django_redis import get_redis_connection
class Command(BaseCom... |
from heart_server_helpers import hr_avg_since
import pytest
@pytest.mark.parametrize("pat_id, start_time, expected", [
(-1, "2017-01-01 12:00:00.000000", 90),
(-1, "2018-11-16 11:19:00.000000", 100),
(-1, "2018-11-16 12:30:00.000000", 100),
(-1, "2018-11-17 12:10:00.000000", 0),
])
def test_existing_b... |
from hue import HueControlUtil as hue
from wemo import WemoControlUtil as wemo
from alexa import AlexaControlUtil as alexa
from googleApis.googleSheetController import GoogleSheetController
from googleApis.googleDriveController import GoogleDriveController
from googleApis.gmailController import GmailController
import t... |
import os
import argparse
import glob
import sys
import skimage.color as skcolor
import skimage.io as skio
import skimage.filters as skfilters
import skimage.feature as skfeature
import numpy as np
import matplotlib.pyplot as plt
import warnings
warnings.filterwarnings("ignore")
from tqdm import tqdm
# Fucking impe... |
from .settings import *
from .pipeline import *
from .logging import *
from .cache import *
from .local import *
if CACHING:
MIDDLEWARE_CLASSES = ['django.middleware.cache.UpdateCacheMiddleware'] + MIDDLEWARE_CLASSES + ['django.middleware.cache.FetchFromCacheMiddleware']
|
from pyasn1.type.namedtype import NamedType, NamedTypes, OptionalNamedType, DefaultedNamedType
from pyasn1.type.namedval import NamedValues
from asn1PERser.classes.data.builtin import *
from asn1PERser.classes.types.type import AdditiveNamedTypes
from asn1PERser.classes.types.constraint import MIN, MAX, NoConstraint, E... |
from django.shortcuts import render, reverse
# Create your views here.
from django.http import HttpResponse, JsonResponse
from django.template import Context, loader
from django.contrib.auth.decorators import login_required
from django.views.generic import TemplateView
from django.utils.decorators import method_decora... |
import math
import numbers
import warnings
from typing import Any, Callable, Dict, List, Tuple
import PIL.Image
import torch
from torch.nn.functional import one_hot
from torch.utils._pytree import tree_flatten, tree_unflatten
from torchvision import transforms as _transforms, tv_tensors
from torchvision.transforms.v2 ... |
##############################################################################
#import statements
##############################################################################
#from sklearn import learning_curve
import pandas as pd
import calendar
import numpy as np
from sklearn.tree import DecisionTreeClassifier
fr... |
import cv2
import pyttsx3
import numpy as np
from minimal_object_detection_lib import MinimalObjectDetector
cameraId = 0
cap = cv2.VideoCapture(cameraId)
detector = MinimalObjectDetector()
detector.Initialize()
engine = pyttsx3.init()
engine.setProperty("rate", 120)
i = 0
while True:
_, frame = ... |
# -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'main_gui.ui'
#
# Created by: PyQt5 UI code generator 5.13.1
#
# WARNING! All changes made in this file will be lost!
from PyQt5 import QtCore, QtGui, QtWidgets
class Ui_main(object):
def setupUi_main(self, main_page):
main_pa... |
import datetime
import django
from ckeditor.fields import RichTextField
from django.db import models
# Create your models here.
class Blog(models.Model):
status_type = [
('1','Publish'),
('0','Draft')
]
title = models.CharField(max_length=100)
slug = models.CharField(max_length=100)
... |
import traceback
import redis
class Pubsub(object):
MESSAGE_PREFIX = '~M~'
MESSAGE_PREFIX_LEN = 3
EXIT_MESSAGE = '~EXIT~'
def __init__(self, logger, rc):
"""
@type rc: redis.Redis
"""
super(Pubsub, self).__init__()
self.logger = logger
self.rc = rc
... |
# Copyright 2020 Marta Bianca Maria Ranzini and contributors
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0
# Unless required by applicable law... |
import os
import sys
import pickle as pkl
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import numpy as np
def store_checkpoints(model, opts):
opts.model = model
torch.save(model.state_dict(), opts.checkpoints_dir+'/best_model.pth')
def restore_checkpoints(model, direct):
mod... |
from PIL import ImageGrab as IG
import pyautogui as pa
import sys
import os
import time
import re
pa.FAILSAFE = True
#윈도우 창찾기
def findWindowAndPosition(title):
all = pa.getWindows()
for i in all:
if title in i:
r_window = i
else:
continue
pa.getWindow(r_window).set... |
import os
import requests
from flask import Flask, session, render_template, request, redirect, url_for, jsonify
from flask_session import Session
from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker
app = Flask(__name__)
# Check for environment variable
if not os.getenv("DATA... |
# Importing datetime to display the chat time and date
from datetime import datetime
# created class for spy
class Spy:
def __init__(self, name, salutation, age, rating):
# Initializing the values
self.name = name #name of the spy
self.salutation = salutation #salutation of the spy
... |
# -*- coding: utf-8 -*-
"""
用于处理 ObjSpace 的命令行接口
"""
import json
import os
import sys
import codecs
import flask
from flask import Flask
from flask.ext.script import Manager, Command, Option
import csftweb
def create_app(config=None):
# configure your app
app = Flask(__name__)
if config is None:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.