text stringlengths 38 1.54M |
|---|
from Tkinter import *
from multicast import multicast
import os
class GUI():
def __init__(self, MCAST_GROUP, MCAST_PORT, BASE_PATH):
self.MCAST_GROUP = MCAST_GROUP
self.MCAST_PORT = MCAST_PORT
self.BASE_PATH = BASE_PATH
# MAIN WINDOW
mainWindow = PanedWindow(orient=VERTICAL)
mainWindow.pack(fill=BOTH,... |
#affine cipher
#Lab 2, Max Grbic, March 1, 2019
#List of all potential characters to be used
letter = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]
digits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
symbol = [",", ".", ... |
"""
This module contains all the methods in selenium
"""
from time import sleep
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
from selenium.webdriver.common.by impor... |
from flask_login import LoginManager
from .database.models import User
login_manager = LoginManager()
@login_manager.user_loader
def load_user(id):
return User.query.filter(User.id == id).first()
|
from influxdb import InfluxDBClient
from datetime import datetime
from datetime import timedelta
import random
client = InfluxDBClient(host='127.0.0.1', port=8086, database='caml_events')
config = [
['2020-09-08 06:00:00', 10, 50],
['2020-09-09 06:00:00', 10, 50]
]
space_id = 216
for row in config:
day =... |
'''Tendo como dado de entrada a altura (h) de uma pessoa, construa um algoritmo que calcule seu
peso ideal, utilizando as seguintes fórmulas:
Para homens: (72.7*h) - 58
Para mulheres: (62.1*h) - 44.7''' |
import boto3
import json
import os
aws_access_key_id = os.environ['ACCESS_KEY']
aws_secret_access_key = os.environ['SECRET_KEY']
region_name='us-west-2'
rk = boto3.client('rekognition', region_name=region_name, aws_access_key_id = aws_access_key_id, aws_secret_access_key = aws_secret_access_key)
s3 = boto3... |
import sys
from magma import *
from mantle import *
from loam.shields.megawing import MegaWing
megawing = MegaWing()
megawing.Switch.on(4)
megawing.LED.on(2)
main = megawing.main()
A = main.SWITCH[0:2]
B = main.SWITCH[2:4]
C = main.LED
add = Add(2)
add(A,B)
wire(add.O, C)
compile(sys.argv[1], main)
|
import json
import socket # 导入 socket 模块
import numpy as np
# from encrypt_paillier import create_key_pair
import pickle
s = socket.socket() # 创建 socket 对象
host = socket.gethostname() # 获取本地主机名
port = 12346 # 设置端口
s.bind((host, port)) # 绑定端口
flag = 0
s.listen(5) # 等待客户端连接
list = []
p = []
p1 = []
C = []
c1 = []
... |
sa = list(input())
sb = list(input())
sc = list(input())
dic = {'a':sa,'b':sb,'c':sc}
res = 'a'
for _ in range(len(sa+sb+sc)):
if len(dic[res])==0:
print(res.upper())
break
res = dic[res].pop(0)
|
import os
import pickle
import time
import pickle
import logger
def save_cur_iter_dynamics_model(params, saver, sess, itr):
if params.get("save_variables"):
save_path = saver.save(sess, os.path.join(params['exp_dir'], "model-iter{}.ckpt".format(itr)))
logger.log("Model saved in path {}".format(sa... |
#coding="utf-8"
import requests,re
from urllib.parse import urlparse
def get_url(url):
headers={"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3610.2 Safari/537.36"}
result = requests.get(url,headers=headers,verify=False)
result.encoding = 'utf-8'... |
import boto3
import time
import sys
QUEUE_URL = 'https://sqs.us-east-2.amazonaws.com/334146420596/bhalwan-test-queue1.fifo'
def main():
while True:
try:
message_count = get_pending_message_count()
publish_metric(message_count)
time.sleep(5)
except:... |
from __future__ import division
from wonder.layout.generic import Generic
from wonder.utils import color_utils
import time
import math
class RaverPlaid:
layout = None
start_time = 0
# How many sine wave cycles are squeezed into our n_pixels
# 24 happens to create nice diagonal stripes on the wall ... |
# -*- coding: utf-8 -*-
from __future__ import with_statement
from ConfigParser import RawConfigParser, DEFAULTSECT
from obspy.core import UTCDateTime
import os
import sys
class DBConfigParser(RawConfigParser):
"""
Config parser for the database viewer. Inherits from
ConfigParser.RawConfigParser and add... |
import tkinter as tk
import tkinter.ttk as ttk
from tkinter.font import Font
from tkinter.messagebox import *
import pandas as pd
import numpy as np
import re
from string import punctuation
import datetime
# python scripts
import discussion_table
import clerk_management_page
import main
#... |
from typing import Tuple
import numpy as np
import matplotlib.pyplot as plt
def estimate_params(X: np.ndarray, Y: np.ndarray, Td: float) -> Tuple[float, float, float, np.ndarray]:
k = np.linalg.inv(X.T @ X) @ X.T @ Y
R = (1 - k[1]) / k[0]
Te = -Td / np.log(k[1])
L = Te * R
return (R, L, Te, k)
... |
import logging
import os
import time
from typing import NamedTuple
import boto3
from botocore.exceptions import ClientError
log = logging.getLogger()
log.setLevel(os.getenv("LOG_LEVEL", logging.INFO))
class DNSRegistrator(object):
def __init__(self, task_arn: str, cluster_arn: str, task_definition_arn):
... |
from django.urls import path
from . import views
from django.contrib.auth.views import LoginView,LogoutView
urlpatterns = [
path('',views.indexView,name="home"),
path('dashboard/',views.dashboardView,name="dashboard"),
path('login/',LoginView.as_view(),name="login_url"),
path('register/',views.registerV... |
from django.conf.urls import url
from django.urls import path
from django.views.generic import TemplateView
urlpatterns = path('',
url('^$', TemplateView.as_view(template_name='index.html')),
) |
#
# @lc app=leetcode id=421 lang=python3
#
# [421] Maximum XOR of Two Numbers in an Array
#
# @lc code=start
class Trie:
def __init__(self):
self.root = {}
def insert(self, num):
node = self.root
for i in range(31, -1, -1):
bit = (num >> i) & 1
if bit not in no... |
import pytest
from test_checkout import Checkout
@pytest.fixture()
def checkout():
checkout=Checkout()
return checkout
def test_CanAddItemPrice(checkout):
checkout.addItemPrice("a",1)
def test_CanAddItem(checkout):
checkout.addItem("b")
def test_CanCalculateTotal(checkout):
assert checkout.calcu... |
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('efilings', '0007_auto_20150825_0120'),
]
operations = [
migrations.AddField(
model_name='filing',
na... |
from math import*
vi = float(input(" eank "))
d1 = int(input(" fhrfv "))
d2 = int(input(" iuguyl "))
dano= abs(sqrt(5* d1)+pi**(d2/3))
real= int(dano)
resto= int(vi - real)
print(resto) |
#!/usr/bin/env python
import os
import sys
from setuptools import setup
setup(name='giantbls',
version='0.0.0',
description="",
author='Samuel Grunblatt, Nicholas Saunders',
license='',
package_dir={'giantbls': 'giantbls'},
)
|
# Show a table of the squares of the first four numbers
# Para ficar com a tabela, temos que ter todo ordenado à direita (sinal de maior, no format)
# Temos que também ajustar o espaçamento
print("{:>2s} {:>3s} {:>7s}".format("n", "n²", "2**n"))
# a função range vai desde A, inclusivo, a B, exclusivo.
# Como queremos ... |
# Definition for a binary tree node.
class TreeNode(object):
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution(object):
def increasingBST(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
def buildT... |
from collections import Counter
from datetime import datetime, timedelta
import configparser
import numpy as np
import os
import pandas as pd
import smtplib
import re
import lib as ipr_lib
output_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '..//input_output//'))
def get_grades(personnel, behaviora... |
from config import exp_ranges
from utilities import create_pairs_list, load_data, resample_ohlc
from trading.strategies import strat_dict # contains all strategies with metadata
from functions import optimise_backtest, optimise_bt_multi, calc_stats_many
import time
'''
Cycles through all pairs and all timescales, each... |
# -*- coding: utf-8 -*-
"""
Created on Mon May 20 16:49:25 2019
@author: xuan
"""
import sys
import numpy as np
import scipy.io as sio
from scipy import stats
# adding os.path to do filetesting - CP, 2019-06-19
import os.path
from os import path
if sys.version[0] == '2':
import cPickle as pickle
else:
import... |
#!/usr/bin/env python3
'''Plot all items from the dataset and highlight the skyline.'''
import argparse
import numpy as np
import matplotlib.pyplot as plt
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument(
'dataset',
type=str,
help='name of the file with the dataset',
)
ap.add_argumen... |
from django.conf.urls import include, url
from django.utils.translation import gettext_lazy as _
from . import views
urlpatterns = [
url(r'^$', views.cart_detail, name='detail'),
url(_(r'^add/(?P<product_id>\d+)/$'), views.cart_add, name='add'),
url(_(r'^remove/(?P<product_id>\d+)/$'), views.cart_remove , ... |
import logging
from decimal import Decimal, ROUND_HALF_UP
logging.basicConfig(
level=logging.INFO,
)
logger = logging.getLogger('')
class FrozenDict(dict):
""" An implementation of an immutable dictionary. """
def __delitem__(self, key):
raise NotImplementedError("'__delitem__' not supported on ... |
#!/usr/bin/env python
# coding: utf-8
# # Capstone Project
#
# ### This Porject is the part of the final assignment for the *IBM Data Science Professional Certification*.
#
# This is also a separate course by itself, titled **'Applied Data Science Capstone'**
# In[1]:
import pandas as pd
import numpy as np
prin... |
from utils import stats
import argparse
parser = argparse.ArgumentParser()
parser.add_argument(
"--dataset_script_path",
help="Path to the dataset script",
type=str,
default="./en_wiki_multi_news.py",
)
parser.add_argument(
"--dataset_cache_path",
help="Path to the cache folder",
type=str,
... |
import requests
from bs4 import BeautifulSoup as BS
import hashlib
import os
import gzip
import pickle
import sys
import re
import random
url = 'https://auctions.yahoo.co.jp/category/list/S%E3%82%B5%E3%82%A4%E3%82%BA-%E9%95%B7%E8%A2%96T%E3%82%B7%E3%83%A3%E3%83%84-%E3%83%88%E3%83%83%E3%83%97%E3%82%B9-%E5%A5%B3%E6%80%A7... |
'''
Views for app.
'''
from flask import Blueprint, redirect, render_template, url_for
from app.forms import ConfirmForm, SignupForm
from app.functions import add_user, confirm_user
from app.models import User
main = Blueprint('main', __name__, template_folder='app/templates')
@main.route('/', methods=['GET', 'POST... |
# -*- coding: utf-8 -*-
'''
Short Problem Definition:
Given a table A of N integers from 0 to N-1 calculate the smallest such index
P, that that {A[0],…,A[N-1]} = {A[0],…,A[P]}.
Link
PrefixSet
Complexity:
expected worst-case time complexity is O(N)
expected worst-case space complexity is O(N)
Execution:
Based on t... |
"""
All actions use up one stack/queue space
"""
action_bindings = [
'q', # Use normal attack
'w', # Use strong attack
'e', # Use special attack, only available after 1/3 of all allied pieces dead and on certain units
'a', # Move, click to determine coordinates
's', # Drop flag
'd' # Special action for king, onl... |
from num2words import num2words
import matplotlib.pyplot as plt
import unicodedata
def wordstoscore(word):
score=sum([ord(x) % 32 for x in word])
return score
def num2score(num, language):
u = num2words(num, lang=language).replace(' and', '').replace(' ', '').replace('-', '')
return wordstoscore(
... |
from django.apps import AppConfig
class TradeConfig(AppConfig):
name = 'trade'
verbose_name = "实战信息"
app_label= "实战信息"
|
from django.db import models
from django.contrib import admin
class Register(models.Model):
username = models.CharField(u"用户名", max_length = 200)
passwd = models.CharField(u"密码", max_length = 200)
repasswd = models.CharField(u"确认密码", max_length = 200)
email = models.EmailField(u"邮箱地址",max_length = 20... |
from collections import deque
def bfs(start, end):
queue = deque([start])
location[start] = 0
while queue:
X = queue.popleft()
if X == end:
return location[X]
if X+1 < MAX and location[X] + 1 < location[X+1]:
location[X+1] = location[X] + 1
qu... |
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
# Examples:
#url(r'^$', 'monitor.views.index', name='index'),
#url(r'^/index[/]?$', 'monitor.views.index', name='index'),
url(r'^monitor/', include('monitor.urls')),
#url(r'^admin/', i... |
print ('동전 합산 해드리겠습니다... 음수는 넣지마세요.\n' )
OhBack = int(input('오백원짜리 몇개? '))
Back = int(input('백원짜리 몇개? '))
OhShip = int(input('오십원짜리 몇개? '))
Ship = int(input('십원짜리 몇개? '))
Total = (OhBack*500) + (Back*100) + (OhShip * 50) + (Ship *10)
print ('\n 당신이 갖고 있는 동전은 총', Total, '원 입니다.' ) |
import pytest
from selenium import webdriver
from PageObjects.LoginPage import LoginPage
from utilities.readProperties import ReadConfig
from utilities.customLogger import LogGen
#NamingConvention: Test_ID_nameoftestcase
class Test_001_Login():
baseURL = ReadConfig.getApplicationURL()
username = ReadConfig.... |
#!/bin/python3
import logging
import time
import gevent
from gevent import queue, monkey
from client_socket import ClientSocket
monkey.patch_all()
logger = logging.getLogger(__name__)
fh = logging.FileHandler('client/.data/client.log')
logger.setLevel(logging.DEBUG)
logger.addHandler(fh)
class SendingQueue():
''... |
import csv
def execute(data, savepath):
csv_reader = csv.reader(open(data))
f = open(savepath, 'wb')
for line in csv_reader:
label = line[0]
features = line[1:]
libsvm_line = label + ' '
for index, feature in enumerate(features):
libsvm_line += str(index + 1) ... |
from season import Season
from PredictionStats import PredictionStats
year_to_predict = 2017
min_mins_played = 10.0
min_games_played = 20
statsToPredict = PredictionStats.statsToPredictLoop.value
statsToUse = PredictionStats.statsToLoop.value
season_predict = Season()
players = season_predict.calcSeason('season/' + ... |
# Generated by Django 3.0.3 on 2020-04-10 19:20
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('basic_app', '0008_auto_20200409_2247'),
]
operations = [
migrations.AlterField(
model_name='exam',
name='branch',
... |
def partition(lst, begin, end):
i = begin - 1
for j in xrange(begin, end):
if lst[j] < lst[end]:
i += 1
lst[i], lst[j] = lst[j], lst[i]
if lst[end] < lst[i + 1]:
lst[i + 1], lst[end] = lst[end], lst[i + 1]
return i + 1
def _qsort(lst, begin, end):
if begin <... |
"""
Main smartglass client
Common script that handles several subcommands
See `Commands`
"""
import os
import sys
import logging
import argparse
import functools
import asyncio
import aioconsole
import aiohttp
from typing import List
from logging.handlers import RotatingFileHandler
from xbox.webapi.authentication.mo... |
import unittest
from .update_profiles import HdfsReader
from .update_profiles import ArgoApiClient
class TestClass(unittest.TestCase):
def test_hdfs_reader(self):
hdfs_host = "foo"
hdfs_port = "9000"
hdfs_sync = "/user/foo/argo/tenants/{{tenant}}/sync"
hdfs = HdfsReader(hdfs_host,... |
# coding: utf-8
# Nuevo videojuego
import webapp2
import time
from webapp2_extras import jinja2
from model.videojuego import Videojuego
class NuevoVideojuegoHandler(webapp2.RequestHandler):
def get(self):
valores_plantilla = {
}
jinja = jinja2.get_jinja2(app=self.app)
self.resp... |
#2.列表
squres=[1,2,3,4,5]
print(squres[0])#下标是从零开始
newSqures=squres+[2,78,3,6]
print(newSqures)
#与字符串不同的是,列表可以更改列表项的值
a=3**5
squres[2]=a
print(squres)
#append()方法可以将元素添加在列表最后一项
cu=["p","y","t","h","o","n"]
cube1=["p""y""t""h""o""n"]#当每个列表中字符串之间不加逗号的时候,默认为拼接在一起的一个单词,一个引号把所有内容放在里面
print(cu)
print(cube1)
cu.append("myLove"... |
import unittest
import os
from kanbanflow_cli.kanban_board import KanbanBoard
import setup_tests
class TestKanbanBoardAPICalls(unittest.TestCase):
def setUp(self):
setup_tests.set_kbflow_api_environ_var(config_ini_path="config.ini")
self.board = KanbanBoard()
def test_board_json_is_dict(self)... |
#!/usr/bin/python
#!coding=utf-8
import string
#[end-y_end, end-start, high-low, $2/$3, end_level, 缺口, 包线]
class kline():
def cal_kline(self, list):
y_e = list[0][2]
y_l = list[0][3]
y_h = list[0][4]
ret = []
for day in list:
result = []
low = day[3]
high = day[4]
start = day[1]
end = day[2]
... |
from datetime import datetime
from factory import django, Faker, fuzzy
from pytz import UTC
from user.models import User
from .models import Lesson
class LessonFactory(django.DjangoModelFactory):
class Meta:
model = Lesson
date_and_time = fuzzy.FuzzyDateTime(start_dt=datetime(2019, 1, 1, tzinfo=UTC)... |
# Generated by Django 2.0.6 on 2018-12-16 07:49
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
]
operations = [
migrations.CreateModel(
name='Camera',
fields=[
... |
import random
pool = "0123456789abcdefABCDEF"
l = 20
for x in range(150):
tmp = ""
l = random.randint(24, 30)
for i in range(l):
index = random.randint(0, len(pool)-1)
tmp += pool[index]
print('char flag%d[50] = "%s";'%(x, tmp))
|
class Node:
def __init__(self, data, next_data = None):
self.__data = data
self.__next = next_data
def __str__(self):
return self.__data
def get_data(self):
return self.__data
def get_next(self):
return self.__next
def set_data(self,data):
self.__data ... |
from CNN.AbstractLayer import Layer
import numpy as np
from multiprocessing import Pool
from os import cpu_count
from math import ceil
class ConvolutionLayer(Layer):
def __init__(self, filters, learningRate, stride=1, isLearning=True, allowedThreads=None):
super(ConvolutionLayer, self).__init__(isLearni... |
import Tkinter as tk
import time
top = tk.Tk()
def addText():
tickerSymbols = ["VTIAX","PTTRX","PRFDX","DBLTX","TGBAX","FCNTX","CNSAX","ANZAX","FISCX","FACVX","PACIX","VCVSX","DEEAX","ACCBX","CLDAX"]
for i in tickerSymbols:
i = tickerSymbols.index(i)
i = str(i)
currentPercentage = L.cget("text"... |
"""Test cassandra storage."""
import logging
import unittest
from cassandra import cluster as cassandra_driver
from cassandra.protocol import ConfigurationException
from ccmlib import common
from ccmlib.cluster import Cluster as CCMCluster
from ccmlib.cluster_factory import ClusterFactory as CCMClusterFactory
from cfm... |
import cfscrape
import requests
import re
import random
import chardet
from time import sleep
import subprocess
def icurl(url):
user_agent = ichoieUa()
startUrl = "https://www.yifile.com"
referer = startUrl
cookie_arg, a = cfscrape.get_cookie_string(startUrl)
#print(cookie_arg, a)
cmd = ... |
"""Mecabによるチャットの解析"""
import sys
import codecs
from collections import defaultdict
import MeCab
import youtube_db
def main(argvs, argc):
"""Mecabによるチャットの解析"""
if argc < 2:
print("Usage #python %s video_id1 video_id2 ..." % argvs[0])
return 1
video_list = []
for id in argvs[1:]:
... |
class Solution:
# @param {string} s
# @param {string} p
# @return {boolean}
def isMatch(self, s, p):
if p == s:
return True
elif p == None or p == "":
return False
ls = len(s)
lp = len(p)
last_s = 0
last_p = -1
i = j = 0... |
# coding: utf-8
# In[3]:
from scipy.sparse import csr_matrix, hstack
from sklearn.feature_extraction.text import CountVectorizer, TfidfVectorizer
from sklearn.preprocessing import LabelBinarizer
from sklearn.model_selection import train_test_split, cross_val_score
import string
import numpy as np
import pandas as ... |
## 토마토
## M,N,H 행렬이 주어질 때, 토마토가 전부 익을 때까지 걸리는 일수를 구하라. 불가능하면 -1을 반환하라.
## BFS
## 토마토 개수와 최종적으로 익은 토마토 개수를 비교
###############입력###############
import heapq
import sys
from collections import deque, defaultdict
r = sys.stdin.readline
m, n, h = map(int, r().split())
tomato_list = [[list(map(int, r().split())) for _ in r... |
import pymysql
import Config
conn = pymysql.connect(**Config.sql_conn_dict)
cur=conn.cursor()
sql = 'select * from student'
cur.execute(sql)
#cur.fetchone()
print(cur.fetchone())
print(cur.fetchone())
print(cur.fetchone())
print(cur.fetchone())
print(cur.fetchone())
print(cur.fetchone())
cur.close()
conn.close()
... |
from django.db import models
# Create your models here.
class Level(models.Model):
short_name = models.CharField(max_length=10, unique=True)
name = models.CharField(max_length=30, unique=True)
describe = models.TextField()
need_exp = models.IntegerField()
def __str__(self):
return self.s... |
import sys
import json
from collections import defaultdict
from httplib import HTTPConnection
import logging
from os import makedirs
from os.path import isdir, join
import re
from urllib2 import HTTPError, urlopen, Request
from urlparse import urlsplit
import config
import egginst
from enstaller import Enstaller
from ... |
"""
This simulates the mlab-ns lookup request, whose code lives here:
https://code.google.com/p/m-lab/source/browse/server/mlabns/handlers/lookup.py?repo=ns
The difference in this module is that we don't support features which
ooni-support does not use and we augment features which ooni-support
would rely on if mlab-... |
import grpc
import time
from ray import serve
from ray.serve.drivers import DefaultgRPCDriver, DAGDriver
import asyncio
import aiohttp
from ray.serve.generated import serve_pb2, serve_pb2_grpc
import numpy as np
import click
import starlette
from typing import Optional
from serve_test_utils import save_test_results
@... |
#!/usr/local/opt/python3/bin/python3
import cv2
import numpy as np
canvas = np.zeros((300,300,3), dtype = 'uint8')
red = (0,0,255)
green = (0,255,0)
for row in range(0,300,20):
for col in range(10,300,20):
cv2.rectangle(canvas, (col,row), (col+10,row+10), red, -1)
for row in range(10,300,20):
for col in... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 9 13:34:38 2018
@author: ivabruge
GeniePath: Graph Neural Networks with Adaptive Receptive Paths
Paper: https://arxiv.org/abs/1802.00910
this model uses an LSTM on the node reductions of the message-passing step
we store the network states at t... |
## Import all the required libraries
import random
'''
Step 1 - DNA Sequencing
DNA sequencing is the process of determining the sequence of nucleotide bases (As, Ts, Cs, and Gs) in a piece of DNA.
'''
def dnaSequencing():
nucleotide_bases = ['A', 'T', 'C', 'G']
nucleotide_encoding_table = dict()
... |
from flask import session
from myforum import app
app.secret_key = 'cxblmawefl345lrgf435f43ac541fanlm2356y0xvn1234'
app.PER_PAGE = 3
app.run(host='127.0.0.1', debug=True)
|
import sys
sys.stdin = open("D3_3032_input.txt", "r")
def gcd(a, b):
x, y, u, v = 0, 1, 1, 0
while a != 0:
q, r = b // a, b % a
m, n = x - u * q, y - v * q
b, a, x, y, u, v = a, r, u, v, m, n
return x, y
T = int(input())
for test_case in range(T):
A, B = map(int, input().split(... |
import json
import os
import socket
import struct
import requests
class RdpServer:
def __init__(self, backlog=5, addr=('0.0.0.0', 7788)):
# 默认使用AF_INET协议族,即ipv4地址和端口号的组合以及tcp协议
self.serverSocket = socket.socket()
# 绑定监听的ip地址和端口号
self.serverSocket.bind(addr)
# 开始等待
s... |
"""
127 Word Ladder
Given two words (beginWord and endWord), and a dictionary's word list, find the length of shortest transformation sequence from beginWord to endWord, such that:
Only one letter can be changed at a time.
Each transformed word must exist in the word list. Note that beginWord is not a transformed wo... |
import argparse
from torch.utils.data import DataLoader
from torch import multiprocessing
import torch.nn.functional as F
from torchvision import transforms
from bdcn import BDCN
from datasets import PoseLoadDataset, TensorProducer, NYUDataset
from utils import *
from PIL import Image
from net import Cycle
# Ignore ... |
from django.urls import path
from .views import *
urlpatterns = [
path("", MoviesView.as_view()),
path("<slug:slug>/", MovieDetailView.as_view(), name='movie_detail'),
path("review/<int:pk>/", AddReview.as_view(), name="add_review"),
] |
import pickle
import sys
import numpy as np
# sys.path.append()
import codecs
from new_test_7_3 import code_method4
import functools
def cmp(x, y):
# 用来调整顺序
if x[0] > y[0]:
return -1
if x[0] < y[0]:
return 1
return 0
def get_pr_points(sorted_score, relevant_label):
"""
:param... |
# coding:utf-8
# -*- 微米支付 -*-
import json
import words
import urllib
import logging
import tornado.web
import tornado.gen
from model.order_model import ThirdPayOrders
from model.table_base import Wanted
from tornado.httpclient import AsyncHTTPClient
class WmPrepayHandler(tornado.web.RequestHandler):
CP = 'ol100... |
# coding: utf-8
import xlrd
import xlwt
import os
import logging
from customize import getCellStyle, getWidthByColumn, getColOutlineLevel
from constants import requiredColumnsSorted
from constants import headRowIdx, firstDataRowIdx, fbpSheetName, pathSep
from dataHandler import DataHandler
from FBPLoader import FBPLoa... |
import numpy as np
import matplotlib.pyplot as plt
import scipy.fftpack
import pyaudio
import time
time.sleep(1)
np.set_printoptions(suppress=True) # don't use scientific notation
CHUNK = 1024 # number of data points to read at a time
RATE = 1000 # time resolution of the recording device (Hz)
WIDTH = 2
p=pyaudio... |
import pickle
import numpy as np
import datetime
from .utils import get_data
import torch
class NetCoach(object):
"""
Trains a player using MCTS.
"""
def __init__(self, mcts, net, train_kw = None, max_moves=2000,
buffer=20, episodes=20, iterations = 100, train_time=0,
... |
from sklearn.metrics import confusion_matrix
from sklearn.metrics import classification_report
def output_fusion_matrix(predict, ground_truth):
print("混淆矩阵如下: ")
labels = set(ground_truth)
cf_matrix = confusion_matrix(y_pred=predict, y_true=ground_truth, labels=list(labels))
print("labels = ", labels)... |
import ray
import time
import asyncio
from ray import serve
@serve.deployment(num_replicas=2)
def model_one(input_data):
print("Model 1 predict")
time.sleep(4)
return 1
@serve.deployment(num_replicas=2)
def model_two(input_data):
print("Model 2 predict")
time.sleep(4)
return 2
@serve.depl... |
# import dependencies
import os
import csv
# Set path for file
csvpath = os.path.join('Resources','budget_data.csv')
# the functions takes csvreader as a parameter and extracts three lists:
# date, profit/losses, and the change.
# Change list will allow finding the max and min change val and date indexes
def py_analy... |
import re
def xmlmetricf(file):
sline = ""
for line in file:
sline += str(line.decode("utf-8"))
mo = re.compile(r'<\?xml version="1\.0" encoding="UTF-8"\?>(\r\n)*<!DOCTYPE\ssprawozdanie\sPUBLIC\s"sprawozdanie"\s"http:\/\/mhanckow\.vm\.wmi\.amu\.edu\.pl:20002/zajecia/file-storage/view/sprawozdanie\.... |
import requests
import json
import uuid
import tempfile
from bs4 import BeautifulSoup
# django
from django.contrib.sites.models import Site
from django.db.models import F
from django.conf import settings
from django.utils.translation import activate
from django.core import files
# mockups
from base.mockups import Mo... |
import contextily as cx
import geopandas as gpd
import matplotlib as mpl
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib import colorbar
from seaborn.axisgrid import FacetGrid, Grid
from aves.visualization.colors import colormap_from_palette
from aves.visualization.maps.utils import geographical_... |
import fresh_tomatoes
import media
import urllib
import json
import connect
# Estanciando uma array para enviar no final
movies_list = []
# Esse FOR foi criado para receber os JSON e tratar eles para o HTML
for item in connect.movie_query["items"]:
# Pegando o titulo do filme
title = item["title"]
# Pegado... |
nota1 = float(input('Nota da Prova de Química: '))
nota2 = float(input('Nota da Prova de Matemática: '))
nota3 = float(input('Nota da Prova de Física: '))
nota1 = nota1 * 1
nota2 = nota2 * 1
nota3 = nota3 * 2
mp = nota1 + nota2 + nota3/1+1+2
if mp >= 60:
print('Aprovado')
else:
print('Repr... |
class Human:
def __init__(self, name, age, height):
self.name = name
self.age = age
self.height = height
def eat(self): pass
def drink(self): pass
def breath(self): pass
def __str__(self):
return f'Human: {self.age} | {self.name} | {self.height}'
class Superhero(... |
import scrapy
from scrapy.spidermiddlewares.httperror import HttpError
from twisted.internet.error import DNSLookupError
from twisted.internet.error import TimeoutError, TCPTimedOutError
from util import *
header = {
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Ge... |
test_list = [{"id" : 1, "data" : "HappY"},
{"id" : 2, "data" : "BirthDaY"},
{"id" : 3, "data" : "Rash"}]
res = [i for i in test_list if not (i["id"] == 2)]
print(test_list)
print(res) |
from argparse import ArgumentParser
import airsimneurips as airsim
import cv2
import threading
import time
import utils
import numpy as np
import math
# Params
level_name = "Final_Tier_1"
tier=1
drone_name = "drone_1"
takeoff_height = 1.0
viz_traj = True
viz_traj_color_rgba = [1.0, 0.0, 0.0, 1.0]
# Setup
client = air... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.