text stringlengths 8 6.05M |
|---|
x = [1, 2, 3]
def oops(num_list, n):
for i in num_list:
try:
print(num_list[n] + 2)
break
except IndexError:
print('oops')
break
def main():
try:
oops(x, 3)
except KeyError:
print('oops')
main()
|
def triangle(a,b,c):
if (((a+b)>c)and((b+c)>a)and((c+a)>b)):
return True;
else:
return False;
a=input();
b=input();
c=input();
print triangle(a,b,c);
|
import logging
import redis
from django.conf import settings
# from .api_connection import ApiConnection
from .db_connection import DbConnection
# from .util import Util
class HistoricalManager:
def __init__(self):
self.logger = logging.getLogger(__name__)
# self.util = Util()
self.db_conn = DbConnection()
# self.api_conn = ApiConnection()
self.rdb = redis.StrictRedis(host='localhost', port=6379)
|
#-- GAUDI jobOptions generated on Tue Jul 14 16:29:02 2015
#-- Contains event types :
#-- 11104401 - 145 files - 3002924 events - 876.12 GBytes
#-- Extra information about the data processing phases:
from Gaudi.Configuration import *
from GaudiConf import IOHelper
IOHelper('ROOT').inputFiles(['LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000001_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000002_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000003_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000004_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000005_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000006_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000007_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000008_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000009_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000010_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000011_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000012_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000013_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000014_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000015_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000016_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000017_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000018_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000019_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000020_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000021_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000022_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000023_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000024_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000025_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000026_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000027_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000028_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000029_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000030_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000031_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000032_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000033_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000034_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000035_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000036_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000037_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000039_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000040_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000041_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000042_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000043_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000044_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000045_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000046_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000047_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000048_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000049_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000050_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000051_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000052_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000053_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000054_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000055_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000056_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000057_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000058_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000059_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000060_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000061_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000062_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000063_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000064_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000065_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000066_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000067_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000068_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000069_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000070_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000071_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000072_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000073_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000074_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000075_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000076_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000077_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000078_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000079_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000080_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000081_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000082_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000083_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000084_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000085_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000086_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000087_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000088_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000089_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000090_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000091_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000092_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000093_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000095_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000096_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000097_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000098_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000099_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000100_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000101_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000102_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000104_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000105_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000106_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000107_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000108_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000109_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000110_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000112_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000113_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000114_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000115_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000116_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000117_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000118_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000119_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000120_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000121_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000122_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000123_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000124_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000126_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000127_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000128_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000129_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000130_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000131_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000132_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000133_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000134_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000135_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000136_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000137_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000138_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000139_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000140_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000141_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000142_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000143_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000144_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000145_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000146_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000147_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000148_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000149_2.AllStreams.dst',
'LFN:/lhcb/MC/2012/ALLSTREAMS.DST/00038843/0000/00038843_00000150_2.AllStreams.dst'
], clear=True)
|
import os
import numpy as np
import glob
import cv2
import random
import torch
import logging
from datetime import datetime
def mkdir(path):
if not os.path.exists(path):
os.mkdir(path)
def mkdir_experiments(path):
mkdir(path)
mkdir(os.path.join(path, 'models'))
mkdir(os.path.join(path, 'training_state'))
def radiance_writer(out_path, image):
with open(out_path, "wb") as f:
f.write(b"#?RADIANCE\n# Made with Python & Numpy\nFORMAT=32-bit_rle_rgbe\n\n")
f.write(b"-Y %d +X %d\n" %(image.shape[0], image.shape[1]))
brightest = np.maximum(np.maximum(image[...,0], image[...,1]), image[...,2])
mantissa = np.zeros_like(brightest)
exponent = np.zeros_like(brightest)
np.frexp(brightest, mantissa, exponent)
scaled_mantissa = mantissa * 255.0 / brightest
rgbe = np.zeros((image.shape[0], image.shape[1], 4), dtype=np.uint8)
rgbe[...,0:3] = np.around(image[...,0:3] * scaled_mantissa[...,None])
rgbe[...,3] = np.around(exponent + 128)
rgbe.flatten().tofile(f)
def get_image_paths(dataroot):
paths = None
if os.path.basename(dataroot) == 'ldr':
paths = sorted(_get_paths_from_ldr_images(dataroot))
elif os.path.basename(dataroot) == 'hdr':
paths = sorted(_get_paths_from_hdr_images(dataroot))
else:
print('wrong!')
return paths
def _get_paths_from_ldr_images(path):
assert os.path.isdir(path), '{:s} is not a valid directory'.format(path)
img_path = glob.glob(os.path.join(path, '*_1.tif'))
img_path = sorted(img_path)
return img_path
def _get_paths_from_hdr_images(path):
assert os.path.isdir(path), '{:s} is not a valid directory'.format(path)
img_path = glob.glob(os.path.join(path, '*.hdr'))
img_path = sorted(img_path)
return img_path
def read_img(path, need_resize=False, size=(720, 480)):
# read image by cv2
# return: Numpy float32, HWC, BGR, [-1,1]
assert os.path.exists(path), '{} is not exists'.format(path)
if path.endswith('hdr'):
img = cv2.imread(path, -1).astype(np.float32)
elif path.endswith('tif'):
img = cv2.imread(path) / 255.
img = img.astype(np.float32)
elif path.endswith('jpg'):
img = cv2.imread(path) / 255.
img = img.astype(np.float32)
else:
raise NotImplementedError("!!!!!!!!!!!!!!!!!1")
if need_resize:
w, h = size
img = cv2.resize(img, (w, h))
img = img * 2. - 1
return img.astype(np.float32)
def read_img_01(path, need_resize=False, size=(720, 480)):
# read image by cv2
# return: Numpy float32, HWC, BGR, [-1,1]
assert os.path.exists(path), '{} is not exists'.format(path)
if path.endswith('hdr'):
img = cv2.imread(path, -1).astype(np.float32)
elif path.endswith('tif'):
img = cv2.imread(path) / 255.
img = img.astype(np.float32)
elif path.endswith('jpg'):
img = cv2.imread(path) / 255.
img = img.astype(np.float32)
else:
raise NotImplementedError("!!!!!!!!!!!!!!!!!1")
if need_resize:
w, h = size
img = cv2.resize(img, (w, h))
return img.astype(np.float32)
def data_augment(img_list, hflip=True, rot=True):
# horizontal flip OR rotate
hflip = hflip and random.random() < 0.5
vflip = rot and random.random() < 0.5
rot90 = rot and random.random() < 0.5
def _augment(img):
if hflip: img = img[:, ::-1, :]
if vflip: img = img[::-1, :, :]
if rot90: img = img.transpose(1, 0, 2)
return img
return [_augment(img) for img in img_list]
def LDR2HDR(img, expo): # input/output -1~1
GAMMA = 2.2
return (((img + 1) / 2.) ** GAMMA / expo) * 2. - 1
def LDR2HDR_01(img, expo):
GAMMA = 2.2
return (img ** GAMMA / expo)
def tonemap(images): # input/output -1~1
MU = 5000. # tunemapping parameter
return torch.log(1 + MU * (images + 1) / 2.) / np.log(1 + MU) * 2. - 1
def tonemap_01(images): # input/output 0~1
MU = 5000. # tunemapping parameter
return torch.log(1 + MU * (images)) / np.log(1 + MU)
def setup_logger(logger_name, root, phase, level=logging.INFO, screen=False):
'''set up logger'''
l = logging.getLogger(logger_name)
formatter = logging.Formatter(
'%(asctime)s.%(msecs)03d - %(levelname)s: %(message)s', datefmt='%y-%m-%d %H:%M:%S')
log_file = os.path.join(root, phase + '_{}.log'.format(get_timestamp()))
fh = logging.FileHandler(log_file, mode='w')
fh.setFormatter(formatter)
l.setLevel(level)
l.addHandler(fh)
if screen:
sh = logging.StreamHandler()
sh.setFormatter(formatter)
l.addHandler(sh)
def get_timestamp():
return datetime.now().strftime('%y%m%d-%H%M%S')
def tensor2img(tensor, min_max=(0, 1)):
tensor = inverse_transform(tensor)
tensor = tensor.squeeze().float().cpu().clamp_(*min_max) # clamp
img_np = tensor.numpy()
img_np = np.transpose(img_np, (1, 2, 0)) # HWC
return img_np
def tensor2img_01(tensor, min_max=(0, 1)):
tensor = tensor.squeeze().float().cpu().clamp_(*min_max) # clamp
img_np = tensor.numpy()
img_np = np.transpose(img_np, (1, 2, 0)) # HWC
return img_np
def tensor2img_2(tensor, min_max=(-1, 1)):
# tensor = inverse_transform(tensor)
tensor = tensor.squeeze().float().cpu().clamp_(*min_max) # clamp
img_np = tensor.numpy()
img_np = np.transpose(img_np, (1, 2, 0)) # HWC
return img_np
def inverse_transform(images):
return (images + 1.) / 2.
def save_results(img, img_path):
# input 0~1
radiance_writer(img_path, img)
def save_resluts_2(img, img_path):
img = img * 255
img = img[:, :, [2, 1, 0]]
cv2.imwrite(img_path, img) |
from __future__ import annotations
from wiki.inheritance.Lamborghini import Lamborghini, Aventador
class IsaacEdition(Lamborghini):
__onlyInstance: IsaacEdition = None
def __init__(self):
super(IsaacEdition, self).__init__()
if IsaacEdition.__onlyInstance is not None:
raise RuntimeError("Unable to instantiate more than 1 Isaac edition.")
self.max_speed_in_kmph = 400
IsaacEdition.__onlyInstance = self
@staticmethod
def get_instance() -> IsaacEdition:
return IsaacEdition.__onlyInstance if IsaacEdition.__onlyInstance is not None else IsaacEdition()
if __name__ == '__main__':
lamborghini1 = Aventador()
lamborghini2 = Aventador()
# This condition evaluates to False as both of them are separate instances.
print(lamborghini1 == lamborghini2)
# Instance method
lamborghini2.get_speed_in_kmph()
# This won't work
# Aventador.get_max_speed_in_kmph()
_ = IsaacEdition()
# This won't work as IsaacEdition is a singleton.
# isaac_edition2 = IsaacEdition()
isaac_edition_instance1 = IsaacEdition.get_instance()
isaac_edition_instance2 = IsaacEdition.get_instance()
# This condition evaluates to True as both of them are the same instance.
print(isaac_edition_instance1 == isaac_edition_instance2)
# TODO: Implement an n-ton class.
|
from django.db import models
# Create your models here.
class Autor(models.Model):
nome = models.CharField(max_length=150, blank=False, null=False)
class Meta:
verbose_name_plural = 'Autores'
def __str__(self):
return self.nome
class Livro(models.Model):
CATEGORIA_CHOICES = {
(1, 'Terror'),
(2, 'Romance'),
(3, 'Fantasia'),
}
categoria = models.IntegerField(choices=CATEGORIA_CHOICES)
data_publicacao = models.DateField(null=False, blank=False)
titulo = models.CharField(max_length=150, blank=False, null=False)
isbn = models.IntegerField(blank=False, null=False)
autor = models.ForeignKey(Autor, related_name= 'livros', on_delete=models.CASCADE)
def __str__(self):
return self.titulo# + "-" + self.autor
|
a=list(input('Enter the list'))
x=int(input('Enter the value to be searched'))
count=0
for i in range(0,len(a)):
if x == int(a[i]) :
count+=1
print(count)
if count>0:
print('Element is present',count,'times')
else:
print('Element is not present') |
try:
from django.conf import settings
except ImportError:
pass
def overridable(name, default=None):
try:
return getattr(settings, name, default)
except NameError:
return default
# Enables Suds request/response logging
DEBUG = overridable('DEBUG', False)
# Remove the Suds file cache of pickled WSDLs upon process exit
REMOVE_CACHE_ON_EXIT = overridable('SOAP_REMOVE_CACHE_ON_EXIT', False)
# Optional mapping of http(s):// WSDL URLs => file:// URLs to locally saved versions of the WSDL
WSDL_INTERCEPTS = overridable('SOAP_WSDL_INTERCEPTS', {})
# Optional HTTP/HTTPS proxy URL
PROXY_URL = overridable('SOAP_PROXY_URL')
# Timeouts for opening WSDLs and sending method calls. Should be a
# tuple containing (1) the TCP connect timeout and (2) the response
# timeout.
OPEN_TIMEOUT = overridable('SOAP_OPEN_TIMEOUT', (3.05, 27))
SEND_TIMEOUT = overridable('SOAP_SEND_TIMEOUT', (3.05, 10))
|
import cv2
cam0 = cv2.VideoCapture(0)
cam1 = cv2.VideoCapture(1)
# windows7 + python3.7+ opencv 3.4
# fourcc = cv2.VideoWriter_fourcc(*'XVID')
# Raspberry pi+ python2.7+opencv 2.4.9
fourcc = cv2.cv.CV_FOURCC('m', 'p', '4', 'v')
out0 = cv2.VideoWriter('out0.avi', fourcc, 20.0, (640, 480))
out1 = cv2.VideoWriter('out1.avi', fourcc, 20.0, (640, 480))
s0,s1 = False,False
while True:
ret0, frame0 = cam0.read()
ret1, frame1 = cam1.read()
out0.write(frame0)
out1.write(frame1)
cv2.imshow('cam0',frame0)
cv2.imshow('cam1',frame1)
if cv2.waitKey(5) & 0xFF == ord('q'):
break
cam0.release()
cam1.release()
out0.release()
out1.release()
cv2.destroyAllWindows()
|
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.preprocessing import scale
from sklearn.datasets import make_circles
X, y = make_circles(n_samples=10000, factor=.3, noise=.07)
y_fit = KMeans(n_clusters=2).fit(X)
plt.figure(1)
plt.subplot(221)
reds = y == 0
blues = y == 1
plt.plot(X[reds, 0], X[reds, 1], "ro")
plt.plot(X[blues, 0], X[blues, 1], "bo")
plt.title('Its so Raw')
plt.subplot(222)
reds = y_fit.labels_ == 0
blues = y_fit.labels_ == 1
plt.plot(X[reds, 0], X[reds, 1], "ro")
plt.plot(X[blues, 0], X[blues, 1], "bo")
plt.title('K-means done fucked it')
plt.show(); |
import numpy as np
from numpy import pi
from . import qg_diagnostics
try:
import mkl
np.use_fastnumpy = True
except ImportError:
pass
try:
import pyfftw
pyfftw.interfaces.cache.enable()
except ImportError:
pass
class QGModel(qg_diagnostics.QGDiagnostics):
r"""Two layer quasigeostrophic model.
This model is meant to representflows driven by baroclinic instabilty of a
base-state shear :math:`U_1-U_2`. The upper and lower
layer potential vorticity anomalies :math:`q_1` and :math:`q_2` are
.. math::
q_1 &= \nabla^2\psi_1 + F_1(\psi_2 - \psi_1) \\
q_2 &= \nabla^2\psi_2 + F_2(\psi_1 - \psi_2)
with
.. math::
F_1 &\equiv \frac{k_d^2}{1 + \delta^2} \\
F_2 &\equiv \delta F_1 \ .
The layer depth ratio is given by :math:`\delta = H_1 / H_2`.
The total depth is :math:`H = H_1 + H_2`.
The background potential vorticity gradients are
.. math::
\beta_1 &= \beta + F_1(U_1 - U_2) \\
\beta_2 &= \beta - F_2( U_1 - U_2) \ .
The evolution equations for :math:`q_1` and :math:`q_2` are
.. math::
\partial_t\,{q_1} + J(\psi_1\,, q_1) + \beta_1\,
{\psi_1}_x &= \text{ssd} \\
\partial_t\,{q_2} + J(\psi_2\,, q_2)+ \beta_2\, {\psi_2}_x
&= -r_{ek}\nabla^2 \psi_2 + \text{ssd}\,.
where `ssd` represents small-scale dissipation and :math:`r_{ek}` is the
Ekman friction parameter.
"""
def __init__(
self,
beta=1.5e-11, # gradient of coriolis parameter
#rek=5.787e-7, # linear drag in lower layer
rd=15000.0, # deformation radius
delta=0.25, # layer thickness ratio (H1/H2)
H1 = 500, # depth of layer 1 (H1)
U1=0.025, # upper layer flow
U2=0.0, # lower layer flow
**kwargs
):
"""
Parameters
----------
beta : number
Gradient of coriolis parameter. Units: meters :sup:`-1`
seconds :sup:`-1`
rek : number
Linear drag in lower layer. Units: seconds :sup:`-1`
rd : number
Deformation radius. Units: meters.
delta : number
Layer thickness ratio (H1/H2)
U1 : number
Upper layer flow. Units: meters seconds :sup:`-1`
U2 : number
Lower layer flow. Units: meters seconds :sup:`-1`
"""
# physical
self.beta = beta
#self.rek = rek
self.rd = rd
self.delta = delta
self.Hi = np.array([ H1, H1/delta])
self.U1 = U1
self.U2 = U2
#self.filterfac = filterfac
super().__init__(nz=2, **kwargs)
# initial conditions: (PV anomalies)
self.set_q1q2(
1e-7*np.random.rand(self.ny,self.nx) + 1e-6*(
np.ones((self.ny,1)) * np.random.rand(1,self.nx) ),
np.zeros_like(self.x) )
### PRIVATE METHODS - not meant to be called by user ###
def _initialize_background(self):
"""Set up background state (zonal flow and PV gradients)."""
# Background zonal flow (m/s):
self.H = self.Hi.sum()
self.set_U1U2(self.U1, self.U2)
self.U = self.U1 - self.U2
self.Vbg = np.zeros_like(self.Ubg)
# the F parameters
self.F1 = self.rd**-2 / (1.+self.delta)
self.F2 = self.delta*self.F1
# the meridional PV gradients in each layer
self.Qy1 = self.beta + self.F1*(self.U1 - self.U2)
self.Qy2 = self.beta - self.F2*(self.U1 - self.U2)
self.Qy = np.array([self.Qy1, self.Qy2])
# complex versions, multiplied by k, speeds up computations to precompute
self.ikQy1 = self.Qy1 * 1j * self.k
self.ikQy2 = self.Qy2 * 1j * self.k
# vector version
self.ikQy = np.vstack([self.ikQy1[np.newaxis,...],
self.ikQy2[np.newaxis,...]])
self.ilQx = 0.
# layer spacing
self.del1 = self.delta/(self.delta+1.)
self.del2 = (self.delta+1.)**-1
@property
def S(self):
# Define stretching matrix to be used in diagnostics
return np.array([[-self.F1, self.F1],
[self.F2, -self.F2]]).astype(np.float64)
def _initialize_inversion_matrix(self):
# The matrix multiplication will look like this
# ph[0] = a[0,0] * self.qh[0] + a[0,1] * self.qh[1]
# ph[1] = a[1,0] * self.qh[0] + a[1,1] * self.qh[1]
a = np.ma.zeros((self.nz, self.nz, self.nl, self.nk), np.dtype('float64'))
# inverse determinant
det_inv = np.ma.masked_equal(
self.wv2 * (self.wv2 + self.F1 + self.F2), 0.)**-1
a[0,0] = -(self.wv2 + self.F2)*det_inv
a[0,1] = -self.F1*det_inv
a[1,0] = -self.F2*det_inv
a[1,1] = -(self.wv2 + self.F1)*det_inv
self.a = np.ma.masked_invalid(a).filled(0.)
def _initialize_forcing(self):
pass
#"""Set up frictional filter."""
# this defines the spectral filter (following Arbic and Flierl, 2003)
# cphi=0.65*pi
# wvx=np.sqrt((self.k*self.dx)**2.+(self.l*self.dy)**2.)
# self.filtr = np.exp(-self.filterfac*(wvx-cphi)**4.)
# self.filtr[wvx<=cphi] = 1.
def set_q1q2(self, q1, q2, check=False):
"""Set upper and lower layer PV anomalies.
Parameters
----------
q1 : array-like
Upper layer PV anomaly in spatial coordinates.
q1 : array-like
Lower layer PV anomaly in spatial coordinates.
"""
self.set_q(np.vstack([q1[np.newaxis,:,:], q2[np.newaxis,:,:]]))
#self.q[0] = q1
#self.q[1] = q2
# initialize spectral PV
#self.qh = self.fft2(self.q)
# check that it works
if check:
np.testing.assert_allclose(self.q1, q1)
np.testing.assert_allclose(self.q1, self.ifft2(self.qh1))
def set_U1U2(self, U1, U2):
"""Set background zonal flow.
Parameters
----------
U1 : number
Upper layer flow. Units: meters seconds :sup:`-1`
U2 : number
Lower layer flow. Units: meters seconds :sup:`-1`
"""
self.U1 = U1
self.U2 = U2
#self.Ubg = np.array([U1,U2])[:,np.newaxis,np.newaxis]
self.Ubg = np.array([U1,U2])
### All the diagnostic stuff follows. ###
def _calc_derived_fields(self):
self.p = self.ifft(self.ph)
self.xi =self.ifft(-self.wv2*self.ph)
self.Jptpc = -self._advect(
(self.p[0] - self.p[1]),
(self.del1*self.u[0] + self.del2*self.u[1]),
(self.del1*self.v[0] + self.del2*self.v[1]))
# fix for delta.neq.1
self.Jpxi = self._advect(self.xi, self.u, self.v)
self.Jq = self._advect(self.q, self.u, self.v)
self.Sph = np.einsum("ij,jkl->ikl",self.S,self.ph)
def _initialize_model_diagnostics(self):
"""Extra diagnostics for two-layer model"""
super()._initialize_model_diagnostics()
self.add_diagnostic('APEflux',
description='spectral flux of available potential energy',
function= (lambda self:
self.rd**-2 * self.del1*self.del2 *
np.real((self.ph[0]-self.ph[1])*np.conj(self.Jptpc))/self.M**2 ),
units='m^2 s^-3',
dims=('l','k'),
sums_with=['paramspec_APEflux'],
)
self.add_diagnostic('KEflux',
description='spectral flux of kinetic energy',
function= (lambda self:
(np.real(self.del1*self.ph[0]*np.conj(self.Jpxi[0])) +
np.real(self.del2*self.ph[1]*np.conj(self.Jpxi[1])))/self.M**2 ),
units='m^2 s^-3',
dims=('l','k'),
sums_with=['paramspec_KEflux'],
)
self.add_diagnostic('APEgen',
description='total available potential energy generation',
function= (lambda self: self.U * self.rd**-2 * self.del1 * self.del2 *
np.real((1j*self.k*
(self.del1*self.ph[0] + self.del2*self.ph[1]) *
np.conj(self.ph[0] - self.ph[1])).sum()
+(1j*self.k[:,1:-2]*
(self.del1*self.ph[0,:,1:-2] + self.del2*self.ph[1,:,1:-2]) *
np.conj(self.ph[0,:,1:-2] - self.ph[1,:,1:-2])).sum()) /
(self.M**2) ),
units='m^2 s^-3',
dims=('time',)
)
|
__author__ = 'Галлям'
import logging
import asyncore
from PyQt5 import QtCore
from .import asynchat_patched
logger = logging.getLogger(__name__)
class ProtocolInterpreter(QtCore.QThread, asynchat_patched.AsyncChat):
wait_until_next_command = QtCore.pyqtSignal() # 100
data_canal_opened_transfer_started = QtCore.pyqtSignal() # 125
data_canal_opening = QtCore.pyqtSignal() # 150
correct_command = QtCore.pyqtSignal() # 200
unsupported_command = QtCore.pyqtSignal() # 202
username_required = QtCore.pyqtSignal() # 220
quit_success = QtCore.pyqtSignal() # 221
canal_opened_but_no_transfer = QtCore.pyqtSignal() # 225
canal_closing_success_transfer = QtCore.pyqtSignal() # 226
passive_mode = QtCore.pyqtSignal(tuple) # 227
user_authorised = QtCore.pyqtSignal() # 230
wait_until_file_downloaded = QtCore.pyqtSignal() # 232
request_succeeded = QtCore.pyqtSignal() # 250
path_created = QtCore.pyqtSignal() # 257
password_required = QtCore.pyqtSignal() # 331
authentication_required = QtCore.pyqtSignal() # 332
requested_action_require_more_info = QtCore.pyqtSignal() # 350
server_not_found = QtCore.pyqtSignal() # 404
impossible_procedure_canal_closing = QtCore.pyqtSignal() # 421
cannot_open_transfer_canal = QtCore.pyqtSignal() # 425
canal_closed_transfer_cancelled = QtCore.pyqtSignal() # 426
host_unavailable = QtCore.pyqtSignal() # 434
file_unavailable = QtCore.pyqtSignal() # 450
local_error_operation_cancelled = QtCore.pyqtSignal() # 451
not_enough_space = QtCore.pyqtSignal() # 452
syntax_error = QtCore.pyqtSignal() # 500
syntax_error_wrong_argument = QtCore.pyqtSignal() # 501
unused_command = QtCore.pyqtSignal() # 502
wrong_command_sequence = QtCore.pyqtSignal() # 503
not_appropriate_command_and_argument = QtCore.pyqtSignal() # 504
logging_in_failed = QtCore.pyqtSignal() # 530
authentication_required_for_file_saving = QtCore.pyqtSignal() # 532
file_not_found = QtCore.pyqtSignal() # 550
buffer_changed = QtCore.pyqtSignal(list)
def __init__(self, host, port):
QtCore.QThread.__init__(self)
asynchat_patched.AsyncChat.__init__(self)
self.create_socket()
self.set_reuse_addr()
self.host = host
self.port = port
self.set_terminator(b'\r\n')
self._buffer = []
self._ftp_codes = {
'100': self.wait_until_next_command.emit,
'110': None,
'120': None,
'125': self.data_canal_opened_transfer_started.emit,
'150': self.data_canal_opening.emit,
'200': self.correct_command.emit,
'202': self.unsupported_command.emit,
'211': None,
'212': None,
'213': None,
'214': None,
'215': None,
'220': self.username_required.emit,
'221': self.quit_success.emit,
'225': self.canal_opened_but_no_transfer.emit,
'226': self.canal_closing_success_transfer.emit,
'227': self.handle_passive_mode_entering,
'228': None,
'229': None,
'230': self.user_authorised.emit,
'231': None,
'232': self.wait_until_file_downloaded.emit,
'250': self.request_succeeded.emit,
'257': self.path_created.emit,
'331': self.password_required.emit,
'332': self.authentication_required.emit,
'350': self.requested_action_require_more_info.emit,
'404': self.server_not_found.emit,
'421': self.impossible_procedure_canal_closing.emit,
'425': self.cannot_open_transfer_canal.emit,
'426': self.canal_closed_transfer_cancelled.emit,
'434': self.host_unavailable.emit,
'450': self.file_unavailable.emit,
'451': self.local_error_operation_cancelled.emit,
'452': self.not_enough_space.emit,
'500': self.syntax_error.emit,
'501': self.syntax_error_wrong_argument.emit,
'502': self.unused_command.emit,
'503': self.wrong_command_sequence.emit,
'504': self.not_appropriate_command_and_argument.emit,
'530': self.logging_in_failed.emit,
'532': self.authentication_required_for_file_saving.emit,
'550': self.file_not_found.emit,
'551': None,
'552': None,
'553': None,
}
def run(self):
self.connect((self.host, self.port))
asyncore.loop()
def collect_incoming_data(self, data):
self._collect_incoming_data(data)
def found_terminator(self):
received_message = self._get_data().decode()
self._buffer.append(received_message)
if received_message[3] == '-' or received_message[0] == " ":
return
self.buffer_changed.emit(self._buffer.copy())
self._ftp_codes[received_message[:3]]()
del self._buffer[:]
def readable(self):
return True
def handle_connect(self):
pass
def send_username(self, username: str='anonymous'):
username_request = bytes(('USER %s\r\n' % username), 'utf8')
self.push(username_request)
def send_password(self, password: str):
password_request = bytes(('PASS %s\r\n' % password), 'utf8')
self.push(password_request)
def handle_passive_mode_entering(self): # 227
in_brackets = False
result = ""
for i in self._buffer[0]:
if i == '(':
in_brackets = True
continue
if i == ")":
break
if in_brackets:
result += i
result = result.split(',')
ip = '.'.join(result[:4])
port = int(result[4]) * 256 + int(result[5])
self.passive_mode.emit((ip, port))
logger.debug('entering passive mode %s:%s' % (ip, str(port)))
def get_current_dir(self):
self.push(b'PWD\r\n')
def push(self, data: bytes):
super().push(data)
if data[:4] == b'PASS':
self.buffer_changed.emit(['PASS *********'])
else:
self.buffer_changed.emit([data.decode()[:-2]])
def send_ip_and_port(self, ip: str, port: tuple):
ip = ip.split('.')
logger.debug('port: {0}'.format(port))
port = (str(x) for x in port)
port_msg = bytes(("PORT " + ','.join(ip) + ','
+ ','.join(port) + '\r\n').
encode())
logger.debug(port_msg)
self.push(port_msg)
def initiate_passive_mode(self):
self.push(b'PASV\r\n')
def get_dirlist_in_passive(self):
self.push(b'MLSD\r\n')
def set_binary_type(self):
self.push(b'TYPE I\r\n')
def change_dir(self, path: str):
self.push(b'CWD ' + path.encode() + b'/\r\n')
def download_file(self, filename: str):
self.push(b'RETR ' + filename.encode() + b'\r\n')
|
#Dobro, o triplo e raiz quadrada
n1 = float(input('Digite um numero: '))
dob = n1 * 2
trip = n1 * 3
raiz = n1 ** (1/2)
print('O dobro é {}, o triplo é {} e raiz quadrada é {:.3f}'.format(dob, trip, raiz))
|
# Hough Line Transform : 직선을 찾기 위해 사용되는 알고리즘
import math
import cv2 as cv
import numpy as np
# img_gray = cv.imread("../sample/circle.jpg", cv.IMREAD_GRAYSCALE)
img_gray = cv.imread("../sample/orange.png", cv.IMREAD_GRAYSCALE)
img_gray = cv.medianBlur(img_gray, 5)
img_color = cv.cvtColor(img_gray, cv.COLOR_GRAY2BGR)
circles = cv.HoughCircles(img_gray, cv.HOUGH_GRADIENT, 1, 20,
param1=50, param2=35, minRadius= 0, maxRadius=0)
circles = np.uint16(np.around(circles))
for c in circles[0,:]:
center = (c[0], c[1])
radius = c[2]
cv.circle(img_color, center, radius, (0,255,0), 2)
cv.circle(img_color, center, 2, (0,255,0), 3 )
cv.imshow('detected circles', img_color)
cv.waitKey()
cv.destroyAllWindows() |
#Para inicializar um dicionário usamos:
carro = {
'Fabricante':'Honda',
'Modelo':'NSX',
'Ano':'1992',
'Cor':'Vermelho'
}#Chave:Valor
#Para exibir todos os elementos do dicionario usamos
print(carro)
print('---------------------------')
#Para exibir cada elemento do dicionario usamos
print('Fabricante do Carro')
print(carro['Fabricante'])
print('Modelo do Carro')
print(carro['Modelo'])
print('Ano do Carro')
print(carro['Ano'])
#Para exibir cada elemento do dicionario tambem podemos usar o get()
print('Cor do Carro[get]')
print(carro.get('Cor'))
print('---------------------------')
#Podemos mudar um valor de um dicionario usando:
carro['Cor'] = 'Prata'
print('Pintando Carro...')
print(carro)
print('---------------------------')
#Podemos percorrer as chaves de um dicionario usando:
print('Percorrendo Chaves...')
for key in carro:
print(key)
#Podemos percorrer os valores de um dicionario usando:
print('Percorrendo Valores...')
for key in carro:
print(carro[key])
#Podemos percorrer cada chave/valor de um dicionario usando:
print('Percorrendo Chaves/Valores...')
for key, value in carro.items():
print(key + " : " + value)
print('---------------------------')
#Podemos verificar se uma chave está no dicionario
if 'Modelo' in carro:
print('Modelo está em carro')
else:
print('Modelo NÃO está em carro')
if 'Motorista' in carro:
print('Motorista está em carro')
else:
print('Motorista NÃO está em carro')
print('---------------------------')
#Podemos retornar o tamanho do dicionario(qtde de pares chave/valor)
print('Tamanho do dicionário : ', len(carro))
print('---------------------------')
#Podemos adicionar elementos no dicionário
carro['Cambio'] = 'Manual'
print(carro)
print('---------------------------')
#Podemos remover elementos do dicionário de duas maneiras
carro.pop('Cambio')
del carro['Cor']
print(carro)
#Para remover o dicionario por completo usamos clear()
carro.clear()
print('Carro removido')
|
from rest_framework.serializers import ValidationError
def get_query_switches(
query_params,
switches,
raise_on_none=False,
all_true_on_none=False,
):
active_switches = set()
if query_params:
for switch in switches:
if switch in query_params:
value = query_params[switch]
if value == '' or value == '1':
active_switches.add(switch)
if not active_switches:
if raise_on_none:
msg = f'Need at least one active query parameter: {switches}'
raise ValidationError({'detail': msg})
if all_true_on_none:
return set(switches)
return active_switches
|
x = int(raw_input("Dime un numero: "))
y = int(raw_input("Dime otro numero: "))
while x<=y:
if x%2==0:
print x
x += 1 |
#-------------------------------------------------------------------------------
# Name: module1
# Purpose:
#
# Author: Admin
#
# Created: 30/10/2017
# Copyright: (c) Admin 2017
# Licence: <your licence>
#-------------------------------------------------------------------------------
def main():
Belgium = "Belgium,10445852,Brussels,737966,Europe,1830,Euro,Catholicism,Dutch,French,German"
items = Belgium.split(",")
print ("-" * len(Belgium))
print(":".join(items))
print(int(items[1]) + int(items[3]))
main() |
from keras.models import Sequential
from keras.layers import Dense
import random
import numpy as np
import matplotlib.pyplot as plt
#目標の関数
f = lambda x: np.sin(x) + 0.3*x**2
#nの数だけランダムにy=sinxを生成
def get_data(n):
x = np.random.uniform(-10, 10, n)
x = np.reshape(x, [n,1])
y = f(x)
return x, y
#
batch = 100
epoch = 100
test_size = 10000
#訓練データ作成
x_train, t_train = get_data(batch * epoch)
print("x_train:{}, t_train:{}".format(x_train.shape, t_train.shape))
#モデル作成
model = Sequential()
model.add(Dense(units=10, activation='relu', input_shape=(1, )))
model.add(Dense(units=1))
model.compile(optimizer='rmsprop',
loss='mean_squared_error',
metrics=['accuracy'])
model.summary()
#訓練
model.fit(x_train, t_train,
batch_size=batch,
epochs=epoch,
verbose=1)
#検証
#score = model.evaluate(x_test, t_test)
#print(score)
#予測
x_test = np.linspace(-10, 10, test_size)
x_test = np.reshape(x_test, [test_size,1])
t_test = f(x_test)
plt.plot(x_test, t_test, color="red")
#print(x_train.shape, x_test.shape)
y_test = model.predict(x_test)
#y_test = np.asarray([])
#for i in range(100):
# y_test = np.append(y_test, model.evaluate(x_test[i], batch_size=100))
plt.plot(x_test, y_test, color="blue")
plt.show()
|
# -*- coding:utf-8 -*-
"""
HZ偶尔会拿些专业问题来忽悠那些非计算机专业的同学。今天测试组开完会后,
他又发话了:在古老的一维模式识别中,常常需要计算连续子向量的最大和,当向
量全为正数的时候,问题很好解决。但是,如果向量中包含负数,是否应该包含某
个负数,并期望旁边的正数会弥补它呢?例如:{6,-3,-2,7,-15,1,2,2},连续子
向量的最大和为8(从第0个开始,到第3个为止)。给一个数组,返回它的最大连续
子序列的和,你会不会被他忽悠住?(子向量的长度至少是1)
"""
class Solution:
def FindGreatestSumOfSubArray(self, array):
# write code here
if len(array) == 1:
return array[0]
max_sum = 0
temp = 0
i = 0
while i < len(array):
temp += array[i]
if temp <= 0:
temp = 0
else:
if temp > max_sum:
max_sum = temp
i += 1
if max_sum == 0:
return max(array)
else:
return max_sum
s = Solution()
print(s.FindGreatestSumOfSubArray([6, -3, -2, 7, -15, 1, 2, 2])) |
import urllib.parse
from pymongo import HASHED
from .ssrn_base import BaseSsrnSpider
class SsrnSpider_3526433(BaseSsrnSpider):
name = 'ssrn_3526433'
# DB specs
collections_config = {
'Scraper_papers_ssrn_com_3526433': [
[('Doi', HASHED)],
[('Title', HASHED)],
'Publication_Date',
],
}
def build_query_url(self):
query_dict = {
'form_name': 'journalBrowse',
'journal_id': '3526433',
}
return 'https://papers.ssrn.com/sol3/JELJOUR_Results.cfm?' + urllib.parse.urlencode(query_dict)
|
# 8 11
# a b
# a c
# b c
# b g
# a e
# a d
# e d
# h d
# f h
# f e
# f g
# a
# 6 6
# a c
# a b
# c d
# b d
# d e
# e f
# a
n,e=map(int,input().split())
adj_dict={}
#for bfs we need visited array
visited={}
for i in range(e):
x,y=input().split()
if x not in adj_dict:
adj_dict[x]=[y]
else:
adj_dict[x].append(y)
if y not in adj_dict:
adj_dict[y]=[x]
else:
adj_dict[y].append(x)
start = input()
for node in adj_dict:
visited[node]=False
# using stack dfs search
def dfs(adj_dict,start):
if start not in adj_dict:
return -1
stack,path=[start],[]
while stack:
vertex=stack.pop()
if vertex in path:
continue
path.append(vertex)
for n in adj_dict[vertex]:
stack.append(n)
return path
# using recursion
def dfs(adj_dict,start,path=[]):
if start not in adj_dict:
return -1
path+=[start]
for n in adj_dict[start]:
if n not in path:
path=dfs(adj_dict,n,path)
return path
#bfs search
# from queue import Queue
# def bfs(adj,start):
# q=Queue()
# path=[]
# q.put(start)
# visited[start]=True
# while not q.empty():
# v = q.get()
# path.append(v)
# for n in adj[v]:
# if not visited[n]:
# visited[n]=True
# q.put(n)
# return path
path=bfs(adj_dict,start)
print(path)
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
import imageio
import os
import sys
import numpy as np
import SimpleITK as sitk
import tensorflow as tf
from tensorflow.contrib.slim.python.slim.nets import inception
from geomstats.special_orthogonal_group import SpecialOrthogonalGroup
from geomstats.special_euclidean_group import SpecialEuclideanGroup
from evaluate_quality_img import (
calc_psnr, calc_ssim, calc_mse, calc_correlation)
# command line argument parser
ARGPARSER = argparse.ArgumentParser(
description='Evaluate SVRnet iFIND')
# directory parameters
ARGPARSER.add_argument(
'--data_dir', type=str, default='/tmp/data/ifind-dataset',
help='The path to the dataset directory.')
ARGPARSER.add_argument(
'--scan_dir', type=str, default='/tmp/data/ifind-dataset',
help='The path to the nifti volume directory.')
ARGPARSER.add_argument(
'--subject_id', type=str, default='recon-ifind00080',
help='Subject ID to evaluate')
ARGPARSER.add_argument(
'--model_dir', type=str, default='/tmp/models/SVRnet',
help='The directory where the model will be stored.')
ARGPARSER.add_argument(
'--loss', type=str, default='PoseNet',
help='The loss function used. \
Available loss are: AP | PoseNet | SE3')
ARGPARSER.add_argument(
'--n_iter', type=int, default=100,
help='The number of epochs to train.')
ARGPARSER.add_argument(
'--n_samples', type=int, default=10,
help='The number of epochs to train.')
ARGPARSER.add_argument(
'--debug', default=False, action='store_true',
help="Enables debugging mode for more verbose logging and tensorboard \
output.")
def matrix_from_anchor_points(AP1, AP2, AP3):
v1 = AP3 - AP1
v2 = AP2 - AP1
n1 = np.cross(v1, v2)
n2 = np.cross(n1, v1)
v1_norm = v1 / np.linalg.norm(v1) # x
n2_norm = n2 / np.linalg.norm(n2) # y
n1_norm = n1 / np.linalg.norm(n1) # z
# SimpleITK does not like this...
# R_recon = np.vstack((v1_norm, n2_norm, n1_norm)).T
R_recon = np.zeros([3, 3])
R_recon[0, 0] = v1_norm[0]
R_recon[0, 1] = n2_norm[0]
R_recon[0, 2] = n1_norm[0]
R_recon[1, 0] = v1_norm[1]
R_recon[1, 1] = n2_norm[1]
R_recon[1, 2] = n1_norm[1]
R_recon[2, 0] = v1_norm[2]
R_recon[2, 1] = n2_norm[2]
R_recon[2, 2] = n1_norm[2]
return R_recon
def resample_sitk(fixed_image_sitk, rx, tx):
# rx is the rotation of the plane, R is the rotation of the brain
R = np.linalg.inv(rx)
size = fixed_image_sitk.GetSize()
spacing = fixed_image_sitk.GetSpacing()
new_origin = (60, 60, 60) - R.dot(np.array(size) / 2) - R.dot(tx)
fixed_image_sitk.SetOrigin(new_origin)
fixed_image_sitk.SetDirection(np.array(R.flatten()))
# resample filter
resampleFilter = sitk.ResampleImageFilter()
resampleFilter.SetOutputDirection((1, 0, 0, 0, 1, 0, 0, 0, 1)) # Identity
resampleFilter.SetInterpolator(sitk.sitkNearestNeighbor)
resampleFilter.SetOutputSpacing(spacing)
resampleFilter.SetOutputOrigin((0, 0, 0))
resampleFilter.SetDefaultPixelValue(0)
resampleFilter.SetSize((120, 120, 120))
# transform the image
moving_image_sitk = resampleFilter.Execute(fixed_image_sitk)
npimage = sitk.GetArrayFromImage(moving_image_sitk)[60,...]
return npimage
def _parse_function_ifind(serialized_example):
features = tf.parse_single_example(
serialized_example,
features = {
'image' : tf.FixedLenFeature([], tf.string),
'vec' : tf.FixedLenFeature([], tf.string),
'qt' : tf.FixedLenFeature([], tf.string),
'AP1' : tf.FixedLenFeature([], tf.string),
'AP2' : tf.FixedLenFeature([], tf.string),
'AP3' : tf.FixedLenFeature([], tf.string)})
image = tf.reshape(tf.decode_raw(features['image'], tf.float32),[120,120,1]) #* 255.
vec = tf.reshape(tf.decode_raw(features['vec'], tf.float32),[3])
qt = tf.reshape(tf.decode_raw(features['qt'], tf.float32),[4])
AP1 = tf.reshape(tf.decode_raw(features['AP1'], tf.float32),[3])
AP2 = tf.reshape(tf.decode_raw(features['AP2'], tf.float32),[3])
AP3 = tf.reshape(tf.decode_raw(features['AP3'], tf.float32),[3])
return image, vec, qt, AP1, AP2, AP3
def main(argv):
# TF Record
datafiles = FLAGS.data_dir + '/test/' + FLAGS.subject_id + '.tfrecord'
dataset = tf.data.TFRecordDataset(datafiles)
dataset = dataset.map(_parse_function_ifind)
# dataset = dataset.repeat()
# dataset = dataset.shuffle(FLAGS.queue_buffer)
dataset = dataset.batch(1)
image, vec, qt, AP1, AP2, AP3 = dataset.make_one_shot_iterator().get_next()
# Nifti Volume
subject_path = FLAGS.scan_dir + '/test/' + FLAGS.subject_id + '.nii.gz'
fixed_image_sitk_tmp = sitk.ReadImage(subject_path, sitk.sitkFloat32)
fixed_image_sitk = sitk.GetImageFromArray(sitk.GetArrayFromImage(fixed_image_sitk_tmp))
fixed_image_sitk = sitk.RescaleIntensity(fixed_image_sitk, 0, 1) # * 255.
# Network Definition
image_input = tf.placeholder(shape=[1, 224, 224, 1], dtype=tf.float32)
image_resized = tf.image.resize_images(image, size=[224, 224])
if FLAGS.loss == 'PoseNet':
y_pred, _ = inception.inception_v3(image_input, num_classes=7)
quaternion_pred, translation_pred = tf.split(y_pred, [4, 3], axis=1)
sess = tf.Session()
ckpt_file = tf.train.latest_checkpoint(FLAGS.model_dir)
tf.train.Saver().restore(sess, ckpt_file)
print('restoring parameters from', ckpt_file)
SO3_GROUP = SpecialOrthogonalGroup(3)
for i in range(FLAGS.n_iter):
_image, _image_resized, _quaternion_true, _translation_true = \
sess.run([image, image_resized, qt, AP2], )
_quaternion_pred_sample = []
_translation_pred_sample = []
for j in range(FLAGS.n_samples):
_quaternion_pred_i, _translation_pred_i = \
sess.run([quaternion_pred, translation_pred],
feed_dict={image_input: _image_resized})
_quaternion_pred_sample.append(_quaternion_pred_i)
_translation_pred_sample.append(_translation_pred_i)
print(_quaternion_pred_i, _translation_pred_i)
_quaternion_pred_sample = np.vstack(_quaternion_pred_sample)
_rotvec_pred_sample = SO3_GROUP.rotation_vector_from_quaternion(_quaternion_pred_sample)
_rotvec_pred = SO3_GROUP.left_canonical_metric.mean(_rotvec_pred_sample)
_quaternion_pred = SO3_GROUP.quaternion_from_rotation_vector(_rotvec_pred)
_translation_pred = np.mean(np.vstack(_translation_pred_sample),axis=0)
# _quaternion_pred_variance = SO3_GROUP.left_canonical_metric.variance(_rotvec_pred_sample)
_translation_pred_variance = np.var(np.vstack(_translation_pred_sample),axis=0)
rx = SO3_GROUP.matrix_from_quaternion(_quaternion_pred)[0]
tx = _translation_pred[0] * 60.
image_true = np.squeeze(_image)
image_pred = resample_sitk(fixed_image_sitk, rx, tx)
imageio.imsave('imgdump/image_{}_true.png'.format(i),_image[0,...])
imageio.imsave('imgdump/image_{}_pred.png'.format(i),image_pred)
calc_psnr(image_pred, image_true)
calc_mse(image_pred, image_true)
calc_ssim(image_pred, image_true)
calc_correlation(image_pred, image_true)
elif FLAGS.loss == 'AP':
y_pred, _ = inception.inception_v3(image_input, num_classes=9)
AP1_pred, AP2_pred, AP3_pred = tf.split(y_pred, 3, axis=1)
sess = tf.Session()
ckpt_file = tf.train.latest_checkpoint(FLAGS.model_dir)
tf.train.Saver().restore(sess, ckpt_file)
print('restoring parameters from', ckpt_file)
for i in range(FLAGS.n_iter):
_image, _image_resized, _AP1, _AP2, _AP3 = \
sess.run([image, image_resized, AP1, AP2, AP3])
_AP1_sample = []
_AP2_sample = []
_AP3_sample = []
for j in range(FLAGS.n_samples):
_AP1_pred_i, _AP2_pred_i, _AP3_pred_i = \
sess.run([AP1_pred, AP2_pred, AP3_pred],
feed_dict={image_input: _image_resized})
_AP1_sample.append(_AP1_pred_i)
_AP2_sample.append(_AP2_pred_i)
_AP3_sample.append(_AP3_pred_i)
_AP1_pred = np.mean(np.vstack(_AP1_sample),axis=0)
_AP2_pred = np.mean(np.vstack(_AP2_sample),axis=0)
_AP3_pred = np.mean(np.vstack(_AP3_sample),axis=0)
_AP1_pred_variance = np.var(np.vstack(_AP1_sample),axis=0)
_AP2_pred_variance = np.var(np.vstack(_AP2_sample),axis=0)
_AP3_pred_variance = np.var(np.vstack(_AP3_sample),axis=0)
dist_ap1 = np.linalg.norm(_AP1 - _AP1_pred)
dist_ap2 = np.linalg.norm(_AP2 - _AP2_pred)
dist_ap3 = np.linalg.norm(_AP3 - _AP3_pred)
rx = matrix_from_anchor_points(_AP1_pred[0], _AP2_pred[0], _AP3_pred[0])
tx = _AP2_pred[0] * 60.
image_true = np.squeeze(_image)
image_pred = resample_sitk(fixed_image_sitk, rx, tx)
imageio.imsave('imgdump/image_{}_true.png'.format(i),_image[0,...])
imageio.imsave('imgdump/image_{}_pred.png'.format(i),image_pred)
calc_psnr(image_pred, image_true)
calc_mse(image_pred, image_true)
calc_ssim(image_pred, image_true)
calc_correlation(image_pred, image_true)
elif FLAGS.loss == 'SE3':
y_pred, _ = inception.inception_v3(image_input, num_classes=6)
sess = tf.Session()
ckpt_file = tf.train.latest_checkpoint(FLAGS.model_dir)
tf.train.Saver().restore(sess, ckpt_file)
print('restoring parameters from', ckpt_file)
SO3_GROUP = SpecialOrthogonalGroup(3)
SE3_GROUP = SpecialEuclideanGroup(3)
for i in range(FLAGS.n_iter):
print(i)
_image, _image_resized, _rvec, _tvec = \
sess.run([image, image_resized, vec, AP2])
_y_pred_sample = []
for j in range(FLAGS.n_samples):
_y_pred_i = sess.run([y_pred], feed_dict={image_input: _image_resized})
_y_pred_sample.append(_y_pred_i[0])
_y_pred_sample = np.vstack(_y_pred_sample)
_y_pred = SE3_GROUP.left_canonical_metric.mean(_y_pred_sample)
_y_pred_variance = SE3_GROUP.left_canonical_metric.variance(_y_pred_sample)
rx = SO3_GROUP.matrix_from_rotation_vector(_y_pred[0,:3])[0]
tx = _y_pred[0,3:] * 60.
image_true = np.squeeze(_image)
image_pred = resample_sitk(fixed_image_sitk, rx, tx)
imageio.imsave('imgdump/image_{}_true.png'.format(i),_image[0,...])
imageio.imsave('imgdump/image_{}_pred.png'.format(i),image_pred)
calc_psnr(image_pred, image_true)
calc_mse(image_pred, image_true)
calc_ssim(image_pred, image_true)
calc_correlation(image_pred, image_true)
else:
print('Invalid Option:',FLAGS.loss)
raise SystemExit
if __name__ == '__main__':
print('Evaluate SVRnet Model on iFIND data')
FLAGS, UNPARSED_ARGV = ARGPARSER.parse_known_args()
print('FLAGS:', FLAGS)
print('UNPARSED_ARGV:', UNPARSED_ARGV)
# Set verbosity
if FLAGS.debug:
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '1'
tf.logging.set_verbosity(tf.logging.INFO)
else:
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'
tf.logging.set_verbosity(tf.logging.ERROR)
# using the Winograd non-fused algorithms provides a small performance boost
os.environ['TF_ENABLE_WINOGRAD_NONFUSED'] = '1'
tf.app.run(main=main, argv=[sys.argv[0]] + UNPARSED_ARGV)
|
"""Classes for melon orders."""
class AbstractMelonOrder:
def __init__(self, species, qty, order_type, tax):
self.species = species
self.qty = qty
self.shipped = False
self.order_type = order_type
self.tax = tax
def get_total(self):
"""Calculate price, including tax."""
base_price = 5
if self.species == "Christmas Melon":
base_price *= 1.5
total = (1 + self.tax) * self.qty * base_price
if self.order_type == "international" and self.qty < 10:
total = total + 3
return total
def mark_shipped(self):
"""Record the fact than an order has been shipped."""
self.shipped = True
class DomesticMelonOrder(AbstractMelonOrder):
"""A melon order within the USA."""
def __init__(self, species, qty):
super().__init__(species, qty, "domestic", 0.08)
class InternationalMelonOrder(AbstractMelonOrder):
"""An international (non-US) melon order."""
def __init__(self, species, qty, country_code):
super().__init__(species, qty, "international", 0.17)
self.country_code = country_code
def get_country_code(self):
"""Return the country code."""
return self.country_code
class GovernmentMelonOrder(AbstractMelonOrder):
"""A government melon order with no tax and inspection."""
def __init__(self, species, qty):
super().__init__(species, qty, "government", 0)
self.passed_inspection = False
def mark_inspection(self):
self.passed_inspection = True
# thought process:
# self.tax = tax
# self.order_typer = order_type
# def __init__(self, species, qty, country_Code):
# super().__init__(species, qty, "international", 0.17)
# self.country_code = country_code
# if self.order_type = "international":
# self.order_type = ""
# self.tax = 0
# we'll be pulling the attributes from the super class, InternationalMelon
# using the super(). ...
# can we do an else statement like
# if self.order_type = "international":
# self.tax = 0.17
# else:
# self.tax = 0.08 |
from common import *
def dice_accuracy(prob, truth, threshold=0.5, is_average=True):
batch_size = prob.size(0)
p = prob.detach().view(batch_size,-1)
t = truth.detach().view(batch_size,-1)
p = p>threshold
t = t>0.5
intersection = p & t
union = p | t
dice = (intersection.float().sum(1)+EPS) / (union.float().sum(1)+EPS)
if is_average:
dice = dice.sum()/batch_size
return dice
else:
return dice
def accuracy(prob, truth, threshold=0.5, is_average=True):
batch_size = prob.size(0)
p = prob.detach().view(batch_size,-1)
t = truth.detach().view(batch_size,-1)
p = p>threshold
t = t>0.5
correct = ( p == t).float()
accuracy = correct.sum(1)/p.size(1)
if is_average:
accuracy = accuracy.sum()/batch_size
return accuracy
else:
return accuracy
### kaggle metric #################################################################################
# https://github.com/neptune-ml/open-solution-salt-detection/blob/master/src/metrics.py
# https://www.kaggle.com/c/tgs-salt-identification-challenge/discussion/61550
# https://www.kaggle.com/c/tgs-salt-identification-challenge#evaluation
#rle encode/edcode
def do_length_encode(x):
bs = np.where(x.T.flatten())[0]
rle = []
prev = -2
for b in bs:
if (b>prev+1): rle.extend((b + 1, 0))
rle[-1] += 1
prev = b
#https://www.kaggle.com/c/data-science-bowl-2018/discussion/48561#
#if len(rle)!=0 and rle[-1]+rle[-2] == x.size:
# rle[-2] = rle[-2] -1
rle = ' '.join([str(r) for r in rle])
return rle
def do_length_decode(rle, H, W, fill_value=255):
mask = np.zeros((H,W), np.uint8)
if rle=='': return mask
mask = mask.reshape(-1)
rle = np.array([int(s) for s in rle.split(' ')]).reshape(-1, 2)
for r in rle:
start = r[0]-1
end = start + r[1]
mask[start : end] = fill_value
mask = mask.reshape(W, H).T # H, W need to swap as transposing.
return mask
def do_kaggle_metric(predict,truth, threshold=0.5):
N = len(predict)
predict = predict.reshape(N,-1)
truth = truth.reshape(N,-1)
predict = predict>threshold
truth = truth>0.5
intersection = truth & predict
union = truth | predict
iou = intersection.sum(1)/(union.sum(1)+EPS)
#-------------------------------------------
result = []
precision = []
is_empty_truth = (truth.sum(1)==0)
is_empty_predict = (predict.sum(1)==0)
threshold = np.array([0.50, 0.55, 0.60, 0.65, 0.70, 0.75, 0.80, 0.85, 0.90, 0.95])
for t in threshold:
p = iou>=t
tp = (~is_empty_truth) & (~is_empty_predict) & (iou> t)
fp = (~is_empty_truth) & (~is_empty_predict) & (iou<=t)
fn = (~is_empty_truth) & ( is_empty_predict)
fp_empty = ( is_empty_truth) & (~is_empty_predict)
tn_empty = ( is_empty_truth) & ( is_empty_predict)
p = (tp + tn_empty) / (tp + tn_empty + fp + fp_empty + fn)
result.append( np.column_stack((tp,fp,fn,tn_empty,fp_empty)) )
precision.append(p)
result = np.array(result).transpose(1,2,0)
precision = np.column_stack(precision)
precision = precision.mean(1)
return precision, result, threshold
# main #################################################################
if __name__ == '__main__':
print( '%s: calling main function ... ' % os.path.basename(__file__))
print('\nsucess!')
|
# -*- coding: utf-8 -*-
"""
Created on Tue Aug 27 21:09:05 2019
@author: gustavo.fonseca
"""
import numpy as np
import matplotlib.pyplot as plt
#Tarefa 20:
α=0.01
β=0.001
δ=0.007
γ=0.000009
'''Os valores dos parâmetros foram modificados para funcionar com o período de
tempo (0.01 dias por instante)'''
C=np.zeros((100000))
R=np.zeros((100000))
'''Definiremos R e C como vetores com 10^5 elementos para plotar o gráfico de 1000
dias pedido no exercício'''
C[0]=1000
R[0]=12
for i in range (1,len(C)):
C[i]=C[i-1]+(α*C[i-1]-β*C[i-1]*R[i-1])*0.01
R[i]=R[i-1]+(γ*R[i-1]*C[i-1]-δ*R[i-1])*0.01
plt.subplot(2,1,1)
plt.plot(C)
plt.title('Variação de Coelhos e Raposas')
plt.ylabel('Quantidade de Coelhos')
plt.grid()
plt.subplot(2,1,2)
plt.plot(R)
plt.ylabel('Quantidade de Raposas')
plt.xlabel('Tempo(1000 dias * 10²)')
plt.grid()
plt.show()
print('O valor máximo de coelhos no intervalo de tempo foi',np.max(C),'e o mínimo foi',np.min(C)) |
import tensorflow as tf
from tensorflow import keras
from tensorflow.keras import backend as K
class Attention_Encoder(keras.layers.Layer):
def __init__(self, time_steps, nb_rnn_units, **kwargs):
super(Attention_Encoder, self).__init__(**kwargs)
self.en_dense_We = keras.layers.Dense(time_steps, use_bias=False)
self.en_dense_Ue = keras.layers.Dense(time_steps, use_bias=False)
self.en_dense_ve = keras.layers.Dense(1, use_bias=False)
self.en_LSTM_cell = keras.layers.LSTM(nb_rnn_units, return_state=True)
def call(self, inputs, **kwargs):
# x_shape : <batch_size, time_steps, input_dims>
x, s, h = inputs[0], inputs[1], inputs[2]
time_steps, nb_time_series = K.shape(x)[1], K.shape(x)[2]
attention_weight_t = None
for t in range(time_steps):
context = self.one_encoder_attention_step(h, s, x, time_steps) #(batch_size, 1, input_dims)
x = keras.layers.Lambda(lambda x: x[:, t, :])(x)
x = keras.layers.Reshape((1, nb_time_series))(x)
h, _, s = self.en_LSTM_cell(x, initial_state=[h, s])
if t!= 0:
attention_weight_t = keras.layers.Concatenate(axis=1)([attention_weight_t, context])
else:
attention_weight_t = context
x_ = keras.layers.Multiply()([attention_weight_t, x])
return x_
def one_encoder_attention_step(self, h_prev, s_prev, x, time_steps):
"""
:param h_prev: previous hidden state
:param s_prev: previous cell state
:param x: (T, n), n is length of input series at time t, T is length of time series
:return: x_t's attention weights, total n numbers, sum these are 1
"""
concat = keras.layers.Concatenate()([h_prev, s_prev]) # <none, 1, 2m> m is the lstm hidden units
r1 = self.en_dense_We(concat) # <none, 1, T>
r1 = keras.layers.RepeatVector(x.shape[2])(r1) # <none, n, T>
xt = keras.layers.Permute((2, 1))(x) # <none, n, T>
r2 = self.en_dense_Ue(time_steps)(xt) # <none, n, T>
r3 = keras.layers.Add()([r1, r2]) # <none, n, T>
r4 = keras.layers.Activation(activation='tanh')(r3) # <none, n, T>
r5 = self.en_dense_ve(r4) # <none, n, 1>
r5 = keras.layers.Permute((2, 1))(r5) # <none, 1, n>
alpha = keras.layers.Activation(activation='softmax')(r5) # <none, 1, n>
return alpha
class Attention_Decoder(keras.layers.Layer):
def __init__(self, time_steps, nb_rnn_units, **kwargs):
super(Attention_Decoder, self).__init__(**kwargs)
self.time_steps = time_steps
self.dn_dense_We = keras.layers.Dense(nb_rnn_units, use_bias=False)
self.dn_dense_Ue = keras.layers.Dense(nb_rnn_units, use_bias=False)
self.dn_dense_ve = keras.layers.Dense(1, use_bias=False)
self._pred_dense = keras.layers.Dense(1)
self.dn_LSTM_cell = keras.layers.LSTM(nb_rnn_units, return_state=True)
def call(self, inputs, **kwargs):
# y_shape: <batch_size, time_steps, 1>
h_en_all, y, s, h = inputs[0], inputs[1], inputs[2], inputs[3]
for t in range(self.time_steps - 1):
y_prev = keras.layers.Lambda(lambda y: y[:, t, :])(y)
y_prev = keras.layers.Reshape((1, 1))(y_prev) # (batch_size, 1, 1)
context = self.one_decoder_attention_step(h, s, h_en_all) # (batch_size, 1, nb_rnn_units)
y_prev = keras.layers.Concatenate(axis=2)([y_prev, context]) # (batch_size, 1, nb_rnn_units+1)
y_prev = self._pred_dense(y_prev) # (batch_size, 1, 1)
h, _, s = self.dn_LSTM_cell(y_prev, initial_state=[h, s])
context = self.one_decoder_attention_step(h, s, h_en_all)
return h, context
def one_decoder_attention_step(self, h_de_prev, s_de_prev, h_en_all):
"""
:param h_de_prev: previous hidden state
:param s_de_prev: previous cell state
:param h_en_all: (None, T, m), m is length of rnn output series at time t, T is length of time series
:return: x_t's attention weights, total m numbers, sum these are 1
"""
concat = keras.layers.Concatenate()([h_de_prev, s_de_prev]) # <none, 1, 2p> p is the lstm hidden units p=m
r1 = self.dn_dense_We(concat) # <none, 1, m>
r1 = keras.layers.RepeatVector(self.time_steps)(r1) # <none, T, m>
r2 = self.dn_dense_Ue(h_en_all) # <none, T, m>
r3 = keras.layers.Add()([r1, r2]) # <none, T, m>
r4 = keras.layers.Activation(activation='tanh')(r3) # <none, T, m>
r5 = self.dn_dense_ve(r4) # <none, T, 1>
r5 = keras.layers.Permute((2, 1))(r5) # <none, 1, T>
beta = keras.layers.Activation(activation='softmax')(r5) # <none, 1, T>
context = keras.layers.Dot(axes=1)([beta, h_en_all]) # <none, 1, m>
return context
def DARNN(init, X_input_shape, Y_input_shape):
ip_x = keras.layers.Input(X_input_shape)
ip_y = keras.layers.Input(Y_input_shape)
en_s0 = keras.layers.Lambda(lambda x: K.zeros(shape=(K.shape(x)[0], init.RNNUnits)))(ip_x)
en_h0 = keras.layers.Lambda(lambda x: K.zeros(shape=(K.shape(x)[0], init.RNNUnits)))(ip_x)
de_s0 = keras.layers.Lambda(lambda x: K.zeros(shape=(K.shape(x)[0], init.RNNUnits)))(ip_x)
de_h0 = keras.layers.Lambda(lambda x: K.zeros(shape=(K.shape(x)[0], init.RNNUnits)))(ip_x)
x_ = Attention_Encoder(time_steps=init.TimeSteps, nb_rnn_units=init.RNNUnits)([ip_x, en_s0, en_h0])
h_en_all = keras.layers.LSTM(init.RNNUnits, return_sequences=True)(x_)
h_en_all = keras.layers.Reshape((init.TimeSteps, -1))(h_en_all)
h, context = Attention_Decoder(time_steps=init.TimeSteps, nb_rnn_units=init.RNNUnits)([h_en_all, ip_y, de_s0, de_h0])
concat = keras.layers.Concatenate(axis=2)([h, context])
concat = keras.layers.Reshape((-1,))(concat)
result = keras.layers.Dense(init.RNNUnits)(concat)
out = keras.layers.Dense(init.FeatDims)(result)
if init.task == 'classification':
out = keras.layers.Activation('relu')(out)
model = keras.models.Model(inputs=[ip_x, ip_y], outputs=out)
return model
|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
for n in range(100,1000):# 遍历所有三位数
a = n% 10 # 取余找出个位数
b = int(n/100) # 求商找出百位数
c = int(n/100) % 10 # 通过求商取整找出百位和十位,然后求商找出十位
if n == a**3 + b**3 + c**3:
print("%d"%n)
def isIpV4AddrLegal(ipStr):
'''切割IP地址为一个列表'''
ip_split_list = ipStr.strip().split('.')
# 切割后列表必须有4个元素
if 4 != len(ip_split_list):
return False
for i in range(4):
try:
# 每个元素必须为数字
ip_split_list[i] = int(ip_split_list[i])
except:
print("IP invalid:" + ipStr)
return False
for i in range(4):
# 每个元素值必须在0-255之间
if ip_split_list[i] <= 255 and ip_split_list[i] >= 0:
pass
else:
print("IP invalid:" + ipStr)
return False
return True
print(isIpV4AddrLegal('12.0.2.1'))
print(isIpV4AddrLegal('0.0.2.1'))
|
# -*- coding: utf-8 -*-
from django.template.response import TemplateResponse
from snippets.views import BaseTemplateView
class TemplateResponse400(TemplateResponse):
status_code = 400
class TemplateResponse403(TemplateResponse):
status_code = 403
class TemplateResponse404(TemplateResponse):
status_code = 404
class TemplateResponse500(TemplateResponse):
status_code = 500
class BaseErrorView(BaseTemplateView):
def get_context_data(self, **kwargs):
kwargs = super(BaseErrorView, self).get_context_data(**kwargs)
message = kwargs.get('message', '')
request = kwargs.get('view').request
kwargs.update(
request_path=request.path,
message=message,
is_error_page=True
)
return kwargs
class Error400View(BaseErrorView):
"""Неправильный запрос"""
response_class = TemplateResponse400
template_name = 'errors/400.html'
class Error403View(BaseErrorView):
"""Доступ запрещен"""
response_class = TemplateResponse403
template_name = 'errors/403.html'
class Error404View(BaseErrorView):
"""Страница не найдена"""
response_class = TemplateResponse404
template_name = 'errors/404.html'
class Error500View(BaseErrorView):
"""Внутренняя ошибка сервера"""
response_class = TemplateResponse500
template_name = 'errors/500.html'
|
# coding: utf-8
"""
NiFi Rest API
The Rest API provides programmatic access to command and control a NiFi instance in real time. Start and stop processors, monitor queues, query provenance data, and more. Each endpoint below includes a description, definitions of the expected input and output, potential response codes, and the authorizations required to invoke each service.
OpenAPI spec version: 1.19.0
Contact: dev@nifi.apache.org
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import sys
import os
import re
# python 2 and python 3 compatibility library
from six import iteritems
from ..configuration import Configuration
from ..api_client import ApiClient
class AccessoidcApi(object):
"""
NOTE: This class is auto generated by the swagger code generator program.
Do not edit the class manually.
Ref: https://github.com/swagger-api/swagger-codegen
"""
def __init__(self, api_client=None):
config = Configuration()
if api_client:
self.api_client = api_client
else:
if not config.api_client:
config.api_client = ApiClient()
self.api_client = config.api_client
def oidc_callback(self, **kwargs):
"""
Redirect/callback URI for processing the result of the OpenId Connect login sequence.
Note: This endpoint is subject to change as NiFi and it's REST API evolve.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.oidc_callback(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.oidc_callback_with_http_info(**kwargs)
else:
(data) = self.oidc_callback_with_http_info(**kwargs)
return data
def oidc_callback_with_http_info(self, **kwargs):
"""
Redirect/callback URI for processing the result of the OpenId Connect login sequence.
Note: This endpoint is subject to change as NiFi and it's REST API evolve.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.oidc_callback_with_http_info(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method oidc_callback" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['tokenAuth']
return self.api_client.call_api('/access/oidc/callback', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None,
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def oidc_exchange(self, **kwargs):
"""
Retrieves a JWT following a successful login sequence using the configured OpenId Connect provider.
Note: This endpoint is subject to change as NiFi and it's REST API evolve.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.oidc_exchange(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.oidc_exchange_with_http_info(**kwargs)
else:
(data) = self.oidc_exchange_with_http_info(**kwargs)
return data
def oidc_exchange_with_http_info(self, **kwargs):
"""
Retrieves a JWT following a successful login sequence using the configured OpenId Connect provider.
Note: This endpoint is subject to change as NiFi and it's REST API evolve.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.oidc_exchange_with_http_info(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:return: str
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method oidc_exchange" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['text/plain'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['tokenAuth']
return self.api_client.call_api('/access/oidc/exchange', 'POST',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type='str',
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def oidc_logout(self, **kwargs):
"""
Performs a logout in the OpenId Provider.
Note: This endpoint is subject to change as NiFi and it's REST API evolve.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.oidc_logout(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.oidc_logout_with_http_info(**kwargs)
else:
(data) = self.oidc_logout_with_http_info(**kwargs)
return data
def oidc_logout_with_http_info(self, **kwargs):
"""
Performs a logout in the OpenId Provider.
Note: This endpoint is subject to change as NiFi and it's REST API evolve.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.oidc_logout_with_http_info(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method oidc_logout" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['tokenAuth']
return self.api_client.call_api('/access/oidc/logout', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None,
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def oidc_logout_callback(self, **kwargs):
"""
Redirect/callback URI for processing the result of the OpenId Connect logout sequence.
Note: This endpoint is subject to change as NiFi and it's REST API evolve.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.oidc_logout_callback(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.oidc_logout_callback_with_http_info(**kwargs)
else:
(data) = self.oidc_logout_callback_with_http_info(**kwargs)
return data
def oidc_logout_callback_with_http_info(self, **kwargs):
"""
Redirect/callback URI for processing the result of the OpenId Connect logout sequence.
Note: This endpoint is subject to change as NiFi and it's REST API evolve.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.oidc_logout_callback_with_http_info(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method oidc_logout_callback" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['tokenAuth']
return self.api_client.call_api('/access/oidc/logoutCallback', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None,
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
def oidc_request(self, **kwargs):
"""
Initiates a request to authenticate through the configured OpenId Connect provider.
Note: This endpoint is subject to change as NiFi and it's REST API evolve.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.oidc_request(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
kwargs['_return_http_data_only'] = True
if kwargs.get('callback'):
return self.oidc_request_with_http_info(**kwargs)
else:
(data) = self.oidc_request_with_http_info(**kwargs)
return data
def oidc_request_with_http_info(self, **kwargs):
"""
Initiates a request to authenticate through the configured OpenId Connect provider.
Note: This endpoint is subject to change as NiFi and it's REST API evolve.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please define a `callback` function
to be invoked when receiving the response.
>>> def callback_function(response):
>>> pprint(response)
>>>
>>> thread = api.oidc_request_with_http_info(callback=callback_function)
:param callback function: The callback function
for asynchronous request. (optional)
:return: None
If the method is called asynchronously,
returns the request thread.
"""
all_params = []
all_params.append('callback')
all_params.append('_return_http_data_only')
all_params.append('_preload_content')
all_params.append('_request_timeout')
params = locals()
for key, val in iteritems(params['kwargs']):
if key not in all_params:
raise TypeError(
"Got an unexpected keyword argument '%s'"
" to method oidc_request" % key
)
params[key] = val
del params['kwargs']
collection_formats = {}
path_params = {}
query_params = []
header_params = {}
form_params = []
local_var_files = {}
body_params = None
# HTTP header `Accept`
header_params['Accept'] = self.api_client.\
select_header_accept(['*/*'])
# HTTP header `Content-Type`
header_params['Content-Type'] = self.api_client.\
select_header_content_type(['*/*'])
# Authentication setting
auth_settings = ['tokenAuth']
return self.api_client.call_api('/access/oidc/request', 'GET',
path_params,
query_params,
header_params,
body=body_params,
post_params=form_params,
files=local_var_files,
response_type=None,
auth_settings=auth_settings,
callback=params.get('callback'),
_return_http_data_only=params.get('_return_http_data_only'),
_preload_content=params.get('_preload_content', True),
_request_timeout=params.get('_request_timeout'),
collection_formats=collection_formats)
|
from user_group import *
from skill import *
from skill_rate_log import *
from company_manag import *
from job import *
from job_requests import *
|
while True:
x = input("Enter the list (separated by commas) you wish to have reversed; or type 'exit': ")
if x == 'exit': break
try:
print(x.replace(' ','').split(',')[::-1])
except:
print("Please check your formatting and try again!")
|
import scipy.io
import numpy as np
import sys
import numpy as np
import random
import matplotlib.pyplot as plt
from sklearn.tree import DecisionTreeRegressor
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import AdaBoostRegressor
from sklearn.ensemble import AdaBoostClassifier
from sklearn.ensemble import GradientBoostingClassifier
from sklearn.ensemble import GradientBoostingRegressor
from sklearn.metrics import precision_score
from sklearn.utils import shuffle
from sklearn.datasets import fetch_mldata
rng = np.random.RandomState(1)
X = np.linspace(0, 6, 1000)[:, np.newaxis]
Y = np.sin(X).ravel() + np.sin(7 * X).ravel() + rng.normal(0, 0.4, X.shape[0])
adaregr = AdaBoostRegressor(DecisionTreeRegressor(max_depth=5),
n_estimators=300, random_state=rng)
gregr = GradientBoostingRegressor(n_estimators=200, max_depth=4,
learning_rate=.01,
min_samples_split=5, loss='ls')
for t in range(00,300):
Y[random.randrange(0,1000)] = Y[random.randrange(0,1000)]*random.randrange(-1,2,2)*1.5
adaregr.fit(X, Y)
ada1 = adaregr.predict(X)
gregr.fit(X, Y)
g1 = gregr.predict(X)
plt.figure()
plt.scatter(X, Y, c=(0.75,0.75,0.75), label="training samples")
plt.plot(X, ada1, c="g", label="ADABoost", linewidth=2)
plt.plot(X, g1, c="r", label="Gradient", linewidth=2)
plt.ylabel('Y')
plt.xlabel('X')
plt.title('ADABoost vs Gradient Boost Regression')
plt.legend(loc=2)
plt.savefig('frame'+str(t).zfill(3)+'.png')
plt.clf()
for j in range(00,1000,100):
score = 0
i = 20;
YNoise = Y;
samples = random.sample(range(0, len(Y)),j);
for k in samples:
YNoise[k]=random.randrange(0,10);
bdt = AdaBoostClassifier(n_estimators=i)
bdt.fit(X[0:testlen, :], YNoise[0:testlen])
ypred = bdt.predict(X[testlen:,:])
scores.append(precision_score(YNoise[testlen:],ypred, average='micro'))
print("ADA:" + str(scores[-1]))
bdt = GradientBoostingClassifier(n_estimators=5,learning_rate=1.0,max_depth=3,)
bdt.fit(X[0:testlen, :], YNoise[0:testlen])
ypred = bdt.predict(X[testlen:,:])
gscores.append(precision_score(YNoise[testlen:],ypred, average='micro'))
print("GRA:" + str(gscores[-1]))
plt.plot(range(0,len(scores)), scores)
plt.savefig('GRANoise.png')
scores=list()
gscores=list()
for j in range(0,110,10):
score = 0
i = 20;
XNoise = X;
if j>0:
XNoise[np.unravel_index(random.sample(range(0, len(X)*len(X[1,:])), round(j*len(X)/2)),(70000,784))]=0;
XNoise[np.unravel_index(random.sample(range(0, len(X)*len(X[1,:])), round(j*len(X)/2)),(70000,784))]=255;
#plt.imshow(XNoise[1,:].reshape(28,28), cmap=plt.cm.gray_r, interpolation='nearest')
#plt.axis('off')
#plt.savefig('Noised'+str(j)+'.png')
bdt = AdaBoostClassifier(n_estimators=i)
bdt.fit(XNoise[0:testlen, :], Y[0:testlen])
ypred = bdt.predict(XNoise[testlen:,:])
scores.append(precision_score(Y[testlen:],ypred, average='micro'))
print("ADA:" + str(scores[-1]))
bdt = GradientBoostingClassifier(n_estimators=5,learning_rate=1.0,max_depth=3,)
bdt.fit(X[0:testlen, :], Y[0:testlen])
ypred = bdt.predict(X[testlen:,:])
gscores.append(precision_score(Y[testlen:],ypred, average='micro'))
print("GRA:" + str(gscores[-1]))
plt.plot(range(0,len(scores)), scores)
plt.savefig('ADANoise.png')
for i in range(10,15):
bdt = AdaBoostClassifier(n_estimators=i)
bdt.fit(X[0:testlen, :], Y[0:testlen])
ypred = bdt.predict(X[testlen:,:])
scores.append(precision_score(Y[testlen:],ypred, average='micro'))
scores=list()
for i in range(1,20):
bdt = GradientBoostingClassifier(n_estimators=1,learning_rate=1.0,max_depth=3,)
bdt.fit(X[0:testlen, :], Y[0:testlen])
ypred = bdt.predict(X[testlen:,:])
scores.append(precision_score(Y[testlen:],ypred, average='micro'))
print(scores[-1])
plt.plot(range(1,20), scores)
plt.show()
plot_step = 0.02
x_min, x_max = X[:, 0].min(), X[:, 0].max()
y_min, y_max = X[:, 1].min(), X[:, 1].max()
xx, yy = np.meshgrid(np.arange(x_min, x_max, plot_step),
np.arange(y_min, y_max, plot_step))
Z = bdt.predict(np.c_[xx.ravel(), yy.ravel()])
Z = Z.reshape(xx.shape)
cs = plt.contourf(xx, yy, Z, cmap=plt.cm.Paired)
plt.axis("tight")
plt.scatter(X[:,0],X[:,1], c=Y)
plot_colors = "br"
#plt.show()
|
__version__ = "1.1.5"
|
def qsort(nums, l, r):
if l > r: return
p = partition(nums, l, r)
qsort(nums, l, p-1)
qsort(nums, p+1, r)
pass
def partition(nums, l, r):
key = r
keyval = nums[r]
while l < r:
while l < r and nums[l] <= keyval:
l += 1
while l < r and nums[r] >= keyval:
r -= 1
nums[l], nums[r] = nums[r], nums[l]
nums[l], nums[key] = nums[key], nums[l]
return l
list = [0]
qsort(list,0,len(list)-1)
print list
|
列表生成式
#列表 a = [0,1,2,3,4,5,6,7,8,9], 把列表里的每个值加1,怎么实现?
#方法一:
b = []
for i in a:
b.append(i+1)
a = b
print(a)
#方法二:原值修改
for index,i in enumerate(a):
a[index] += 1
print(a)
#方法三
list = map(lambda n:n+1,a)
for i in list:
print(i)
#方法四
a = [i+1 for i in range(10)]
print(a)
#以上就是列表生成
生成器:
1.python中一边循环一遍计算的机制叫生成器:generator
2.为啥要有生成器:列表受内存限制,容量有限
3.使用生成器的前提:列表的元素可以按照某种算法推算出来,能在循环过程中不断推算出后面的元素,就可以使用生成器,不用创建完整列表了
4.创建generator
1)一个列表生成式的[]改成(),就创建了一个generator
>>> L = [x * x for x in range(10)]
>>> L
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> g = (x * x for x in range(10))
>>> g
<generator object <genexpr> at 0x1022ef630>
#创建L和g的区别仅在于最外层的[]和()
2)在普通函数中包含yield关键字,就变成了一个generator
'''来把两种创建生成器的方式结合一下'''
list_gen = (i for i in range(3)) #第一种
def fun_gen(n): #第二种,就是普通函数加上yield这种
while n < 3:
print("hello here is fun_gen ==>",n)
yield n
n += 1
for num in list_gen: #0,1,2
for i in fun_gen(num): #循环拿到0,1,2的生成器fun_gen
print(i) #拿到fun_gen yield的值
5.打印generator中的元素
1)通过next()函数获得generator的下一个返回值
>>> next(g)
0
>>> next(g)
1
#generator保存的是算法,每次调用next(g),就计算出g的下一个元素的值,直到计算到最后一个元素,没有更多的元素时,抛出StopIteration的错误。
2)最好使用for循环,因为generator也是可迭代对象
>>> g = (x * x for x in range(10))
>>> for n in g:
... print(n)
0
1
4
6.算法复杂的列表,可以用函数来生成
比如,著名的斐波拉契数列(Fibonacci),除第一个和第二个数外,任意一个数都可由前两个数相加得到:
1, 1, 2, 3, 5, 8, 13, 21, 34, ...
def fib(max):
'''
1.这段代码定义了波拉契数列的推算规则,逻辑和generator很相似
2.只要把print(b)改为yield b,fib函数就变成generator了,就是上面说的第二种定义generator的方法
3.函数和generator的区别:
函数 ==> 顺序执行,遇到return语句或者最后一行函数语句返回
generator ==> 每次调用next()的时候执行,遇到yield语句返回,再次执行时从上次返回的yield语句处继续执行 '''
n, a, b = 0, 0, 1
while n < max:
print(b)
a, b = b, a + b
n = n + 1
return 'done'
>>> fib(5)
1
1
2
3
5
done
7.拿到generator的return返回值
但是用for循环调用generator时,发现拿不到generator的return语句的返回值。如果想要拿到返回值,必须捕获StopIteration错误,返回值包含在StopIteration的value中:
>>> g = fib(3)
>>> while True:
... try:
... x = next(g)
... print('g:', x)
... except StopIteration as e:
... print('Generator return value:', e.value)
... break
g: 1
g: 1
g: 2
Generator return value: done
8.例子:通过yield实现在单线程的情况下实现并发运算的效果
例1:
import time
def consumer(name):
print("%s 准备吃包子啦!" %name)
while True:
baozi = yield
# print(baozi)
print("包子[%s]来了,被[%s]吃了!" %(baozi,name))
def producer():
c = consumer('豹子头林冲') #这步什么都不会发生
c2 = consumer('花和尚鲁智深')
c.__next__() #调用next,打印到yield之前,然后不会有任何期待的事情发生 ==> A 准备吃包子啦!
c2.__next__()
print("老子开始准备做包子啦!") #打印做包子
for i in range(10): #这步主要是为了做10次包子
time.sleep(1)
print("做了2个包子!")
c.send(i) #直到遇到了send,期待的事发生了,consumer yield后面的语句打印惹~
c2.send(i)
producer()
# send是什么 ==> http://www.cnblogs.com/coderzh/archive/2008/05/18/1202040.html
例2:(简陋的例子,方便理解send写的)
def h(name):
print(name)
while True:
print("打死你")
m = yield
print(m)
def i():
c = h("你说我啥")
c.__next__()
c.send("怕不怕")
c.__next__()
i()
'''
不写while会引发的报错 ==> 每次调用next(g),就计算出g的下一个元素的值。。。
Traceback (most recent call last):
File "G:/Topaz/Mall/shopping/tests.py", line 43, in <module>
i()
File "G:/Topaz/Mall/shopping/tests.py", line 41, in i
c.send("怕不怕")
StopIteration
'''
迭代器:
可迭代对象(Iterable):
1.可以for循环的对象统称可迭代对象,有以下两类:
集合类型:list,tuple,dict,set,str
generator:包括生成器和带 yield 的 generator function
2.使用isinstance()判断一个对象是否是Iterable对象
>>> from collections import Iterable
>>> isinstance([],Iterable)
True
>>> isinstance({},Iterable)
True
>>> isinstance('abc',Iterable)
True
>>> isinstance(100,Iterable)
False
迭代器(Iterator):
1.迭代器可以被next()函数调用,并不断返回下一个值,举个例子:生成器
2.使用isinstance()判断一个对象是否是Iterator对象
>>> from collections import Iterator
>>> isinstance([],Iterator)
False
>>> isinstance((x for x in range(10)),Iterator)
True
PS:使用iter()函数,把list,dict,str等Iterable变成Iterator
>>> isinstance(iter([]),Iterator)
True
>>> isinstance(iter('abc'),Iterator)
True
你可能会问,为什么list、dict、str等数据类型不是Iterator?
这是因为Python的Iterator对象表示的是一个数据流,Iterator对象可以被next()函数调用并不断返回下一个数据,直到没有数据时抛出StopIteration错误。可以把这个数据流看做是一个有序序列,但我们却不能提前知道序列的长度,只能不断通过next()函数实现按需计算下一个数据,所以Iterator的计算是惰性的,只有在需要返回下一个数据时它才会计算。
Iterator甚至可以表示一个无限大的数据流,例如全体自然数。而使用list是永远不可能存储全体自然数的。
小结:
1.生成器又是Iterator又是Iterable
2.可以for循环的都是可迭代对象
3.可以调用next()函数的都是Iterator类型,Iterator类型是惰性计算的序列
3.集合数据类型(str,dict,list)可以通过iter()函数获得一个Iterator对象
4.Python的for循环本质上就是不断调用next()函数
for x in [1, 2, 3, 4, 5]:
pass
等价于:
a = iter([1,2,3,4,5])
while True:
try:
x = next(a)
except StopIteration:
break
装饰器:
遵循软件开发的“开放-封闭”原则,它规定已经实现的功能代码不允许被修改,但可以被扩展,即:
封闭:已实现的功能代码块
开放:对扩展开发
实例:
已有功能:多个视频专区模块video,movie
扩展功能:用户登陆认证
应用:在某个或多个视频专区(video,movie)里应用用户登陆认证功能
1.0v 独立的函数:需要认证的调用它
问题:已实现功能的代码被修改
1.1v 高阶函数:把需要认证的函数当做参数传给认证函数
问题:调用方式发生变化,之前的调用方式 video(),现在的调用方式login(video)
PS:如果100个视频模块要认证,100个不是一个人写的,都要改调用方式,被骂死惹
1.2v 高阶函数调用方式不变的修改
america = login(america) #函数赋值给变量名
america() #用户调用是这样的,还是原来的配方美滋滋
问题:大哥你就没发现,用户没调用之前它自己就执行了吗,来下一个版本我们解决这个问题
1.3v 高阶函数调用方式不变,不自己执行的修改(就是装饰器啦)
def login(func): #把要执行的模块从这里传进来
def inner(): #再定义一层函数
if user_status == True:
func() # 看这里看这里,只要验证通过了,就调用相应功能
return inner #用户调用login时,只会返回inner的内存地址,下次再调用时加上()才会执行inner函数
究极体2.0v 以上实现了装饰器(诨名语法糖儿),不过还能写的更简单~
america = login(america) #这个去掉
@login #在需要调用用户认证的函数上@login
def video():
究极体变异(传参):
def inner(arg1) #在inner里加参数就可以了,还可以用非固定参数(*args,**kargs)
func(arg1)
代码:
#练习1:我不想多加一层,试下能不能直接返回func,可以的。
def login(func):
print("here is login~~")
# 不加直接返回func的内存地址
# print(func) #<function video at 0x000001BBA1D25510>
return func
'''
在里面加一层返回inner的内存地址
def inner(*args):
return func(*args)
# print(inner) #<function login.<locals>.inner at 0x000001E5E1BBD840>
return inner
'''
@login
def video(*args):
print("video",*args)
def movie():
print("movie")
video(1,2,3) #调用
输出:
here is login~~
video 1 2 3
#练习2:(login本身有参数,只能再多加一层传func。但是inner是不需要的)
def login(auth_type): #把要执行的模块从这里传进来
def auth(func):
def inner(*args,**kwargs):#再定义一层函数
if auth_type == "qq":
_username = "topaz" #假装这是DB里存的用户信息
_password = "123" #假装这是DB里存的用户信息
global user_status
if user_status == False:
username = input("user:")
password = input("pasword:")
if username == _username and password == _password:
print("welcome login....")
user_status = True
else:
print("wrong username or password!")
if user_status == True:
return func(*args,**kwargs) # 看这里看这里,只要验证通过了,就调用相应功能
else:
print("only support qq ")
return inner #用户调用login时,只会返回inner的内存地址,下次再调用时加上()才会执行inner函数
return auth
def home():
print("---首页----")
@login('qq')
def america(*args,**kwargs):
#login() #执行前加上验证
print("----欧美专区----",args)
home()
america()
#另一种调用方式,等同于america()
america = login('qq')(america)
america(1,2,3)
软件目录结构规范:
可读性高:不熟悉代码的人,能一眼看懂目录结构,知道程序启动脚本是哪个,测试目录在哪,配置文件在哪,快速了解项目
可维护性高:定义好组织规则后,维护者能明确知道,新增的哪个文件和代码应该放在什么目录下,好处是,随着时间推移,代码/配置规模增加,项目结构不会混乱
目录结构:
Foo/
|-- bin/ #存放项目的一些可执行文件,当然你可以起名script/之类的也行。
| |-- foo
|
|-- foo/ #存放项目的所有源代码,源代码中的所有模块、包都应该放在此目录。不要置于顶层目录
| |-- tests/ #tests/存放单元测试代码
| | |-- __init__.py
| | |-- test_main.py
| |
| |-- __init__.py
| |-- main.py #程序的入口最好命名为main.py
|
|-- docs/ #存放一些文档
| |-- conf.py
| |-- abc.rst
|
|-- setup.py #安装、部署、打包的脚本
|-- requirements.txt #存放软件依赖的外部Python包列表
|-- README #项目说明文件
更多参考:https://jeffknupp.com/blog/2013/08/16/open-sourcing-a-python-project-the-right-way/
README需要说明以下几个事项:
软件定位,软件的基本功能。
运行代码的方法: 安装环境、启动命令等。
简要的使用说明。
代码目录结构说明,更详细点可以说明软件的基本原理。
常见问题说明。
参考:Redis源码中Readme的写法 https://github.com/antirez/redis#what-is-redis
setup.py:
一般来说,用setup.py来管理代码的打包、安装、部署问题。业界标准的写法是用Python流行的打包工具setuptools来管理这些事情。这种方式普遍应用于开源项目中。不过这里的核心思想不是用标准化的工具来解决这些问题,而是说,一个项目一定要有一个安装部署工具,能快速便捷的在一台新机器上将环境装好、代码部署好和将程序运行起来。
我刚开始接触Python写项目的时候,安装环境、部署代码、运行程序这个过程全是手动完成,遇到过以下问题:
安装环境时经常忘了最近又添加了一个新的Python包,结果一到线上运行,程序就出错了。
Python包的版本依赖问题,有时候我们程序中使用的是一个版本的Python包,但是官方的已经是最新的包了,通过手动安装就可能装错了。
如果依赖的包很多的话,一个一个安装这些依赖是很费时的事情。
新同学开始写项目的时候,将程序跑起来非常麻烦,因为可能经常忘了要怎么安装各种依赖。
setup.py可以将这些事情自动化起来,提高效率、减少出错的概率。"复杂的东西自动化,能自动化的东西一定要自动化。"是一个非常好的习惯。
setuptools的文档比较庞大,刚接触的话,可能不太好找到切入点。学习技术的方式就是看他人是怎么用的,可以参考一下Python的一个Web框架,flask是如何写的:https://github.com/mitsuhiko/flask/blob/master/setup.py
当然,简单点自己写个安装脚本(deploy.sh)替代setup.py也未尝不可。
requirements.txt:
方便开发者维护软件的包依赖。将开发过程中新增的包添加进这个列表中,避免在setup.py安装依赖时漏掉软件包。
方便读者明确项目使用了哪些Python包。
这个文件的格式是每一行包含一个包依赖的说明,通常是flask>=0.10这种格式,要求是这个格式能被pip识别,这样就可以简单的通过 pip install -r requirements.txt来把所有Python包依赖都装好了。具体格式说明<a href="https://pip.readthedocs.org/en/1.1/requirements.html">点这里</a>
关于配置文件的使用方法
注意,在上面的目录结构中,没有将conf.py放在源码目录下,而是放在docs/目录下。
很多项目对配置文件的使用做法是:
配置文件写在一个或多个python文件中,比如此处的conf.py。
项目中哪个模块用到这个配置文件就直接通过import conf这种形式来在代码中使用配置。
这种做法我不太赞同:
这让单元测试变得困难(因为模块内部依赖了外部配置)
另一方面配置文件作为用户控制程序的接口,应当可以由用户自由指定该文件的路径。
程序组件可复用性太差,因为这种贯穿所有模块的代码硬编码方式,使得大部分模块都依赖conf.py这个文件。
所以,我认为配置的使用,更好的方式是:
模块的配置都是可以灵活配置的,不受外部配置文件的影响。
程序的配置也是可以灵活控制的。
能够佐证这个思想的是,用过nginx和mysql的同学都知道,nginx、mysql这些程序都可以自由的指定用户配置。
所以,不应当在代码中直接import conf来使用配置文件。上面目录结构中的conf.py,是给出的一个配置样例,不是在写死在程序中直接引用的配置文件。可以通过给main.py启动参数指定配置路径的方式来让程序读取配置内容。当然,这里的conf.py你可以换个类似的名字,比如settings.py。或者你也可以使用其他格式的内容来编写配置文件,比如settings.yaml之类的。
|
# -*- coding: utf-8 -*-
"""
Created on Thu Apr 29 13:03:27 2021
@author: ali_k
"""
import datetime as dt
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import time, requests
graph_limit = 10
# Create figure for plotting
fig, axs = plt.subplots(2, 2)
arrx = []
arrbtc = []
arrada = []
arreth = []
arratom = []
arrtrx = []
uri1 = "https://api.btcturk.com/api/v2/ticker?pairSymbol="
uri2 = "https://api.binance.com/api/v3/ticker/price?symbol="
# SNX MATIC BAT
def animate(i, arrx, arrbtc, arrtrx, arrada, arreth):
#Read data
print('===BTC===')
result1 = requests.get(url=uri1 + 'BTC_TRY').json()["data"][0]["last"]
result2 = float(requests.get(url=uri2 + 'BTCTRY').json()["price"])
print('BTC: ', result1)
print('BNN: ', result2)
diff = (100 * abs(result1 - result2) / min(result1, result2))
arrbtc.append(diff)
print('Diff: ', diff)
print('===TRX===')
result1 = requests.get(url=uri1 + 'TRX_TRY').json()["data"][0]["last"]
result2 = float(requests.get(url=uri2 + 'TRXTRY').json()["price"])
print('BTC: ', result1)
print('BNN: ', result2)
diff = (100 * abs(result1 - result2) / min(result1, result2))
arrtrx.append(diff)
print('Diff: ', diff)
print('===ADA===')
result1 = requests.get(url=uri1 + 'ADA_TRY').json()["data"][0]["last"]
result2 = float(requests.get(url=uri2 + 'ADATRY').json()["price"])
print('BTC: ', result1)
print('BNN: ', result2)
diff = (100 * abs(result1 - result2) / min(result1, result2))
arrada.append(diff)
print('Diff: ', diff)
print('===ETH===')
result1 = requests.get(url=uri1 + 'ETH_TRY').json()["data"][0]["last"]
result2 = float(requests.get(url=uri2 + 'ETHTRY').json()["price"])
print('BTC: ', result1)
print('BNN: ', result2)
diff = (100 * abs(result1 - result2) / min(result1, result2))
arreth.append(diff)
print('Diff: ', diff)
# Add x and y to lists
arrx.append(dt.datetime.now().strftime('%H:%M:%S'))
# Limit x and y lists to 20 items
arrx = arrx[-graph_limit:]
arrbtc = arrbtc[-graph_limit:]
arrtrx = arrtrx[-graph_limit:]
arrada = arrada[-graph_limit:]
arreth = arreth[-graph_limit:]
# Draw x and y lists
axs[0, 0].clear()
axs[0, 0].plot(arrx, arrbtc)
axs[0, 0].set_title('BTC')
axs[0, 1].clear()
axs[0, 1].plot(arrx, arrtrx)
axs[0, 1].set_title('TRX')
axs[1, 0].clear()
axs[1, 0].plot(arrx, arrada)
axs[1, 0].set_title('ADA')
axs[1, 1].clear()
axs[1, 1].plot(arrx, arreth)
axs[1, 1].set_title('ETH')
plt.setp(axs[0, 0].get_xticklabels(), rotation=45)
plt.setp(axs[0, 1].get_xticklabels(), rotation=45)
plt.setp(axs[1, 0].get_xticklabels(), rotation=45)
plt.setp(axs[1, 1].get_xticklabels(), rotation=45)
time.sleep(1)
# Set up plot to call animate() function periodically
ani = animation.FuncAnimation(fig, animate, fargs=(arrx, arrbtc, arrtrx, arrada, arreth), interval=1000)
plt.show() |
import os
import asyncio
import discord
from discord.ext import commands
from cogs.utils.dataIO import dataIO
from cogs.utils import checks
from discord.utils import find
class StreamAnnouncer:
"""Configureable stream announcements"""
__author__ = "mikeshardmind"
__version__ = "0.2"
def __init__(self, bot):
self.bot = bot
self.settings = dataIO.load_json('data/streamannouncer/settings.json')
def save_json(self):
dataIO.save_json("data/streamannouncer/settings.json", self.settings)
@checks.admin_or_permissions(Manage_server=True)
@commands.group(name="strannounceset", pass_context=True, no_pm=True,
aliases=['strset'])
async def _strset(self, ctx):
if ctx.invoked_subcommand is None:
await self.bot.send_cmd_help(ctx)
@checks.admin_or_permissions(Manage_server=True)
@_strset.command(name="output", pass_context=True, no_pm=True)
async def strset_output(self, ctx):
"""set the output channel to the current channel"""
server = ctx.message.server
channel = ctx.message.channel
if server.id not in self.settings:
self.settings[server.id] = {"output": None,
"role_id": None}
if self.settings[server.id]["output"] == channel.id:
self.settings[server.id]["output"] = None
await self.bot.say("This channel was set for output already, "
"I am removing it now.")
else:
self.settings[server.id]["output"] = channel.id
await self.bot.say("Announcement channel selected.")
self.save_json()
@checks.admin_or_permissions(Manage_server=True)
@_strset.command(name="role", pass_context=True, no_pm=True)
async def strset_role(self, ctx, role: discord.Role):
"""set the role required to get an announcement on stream start"""
server = ctx.message.server
channel = ctx.message.channel
if server.id not in self.settings:
self.settings[server.id] = {"output": None,
"role_id": None}
if self.settings[server.id]["role_id"] == role.id:
self.settings[server.id]["role_id"] = None
self.save_json()
await self.bot.say("That role was set before, removing it")
else:
self.settings[server.id]["role_id"] = role.id
self.save_json()
await self.bot.say("Role required to be announced set")
async def on_stream(self, memb_before, memb_after):
if memb_after.game is None:
return
if memb_after.game.type != 1:
return
if memb_before.server.id not in self.settings:
self.settings[memb_before.server.id] = {"output": None,
"role_id": None}
self.save_json()
server_settings = self.settings[memb_before.server.id]
if server_settings["output"] is None \
or server_settings["role_id"] is None:
return
streamer_role = find(lambda m: m.id == server_settings["role_id"],
memb_before.server.roles)
dest = find(lambda m: m.id == server_settings["output"],
memb_before.server.channels)
if streamer_role is None or dest is None:
return
if streamer_role not in memb_after.roles:
return
stream_url = memb_after.game.url
msg = "{} just started streaming: {}".format(memb_after.mention,
stream_url)
await self.bot.send_message(dest, msg)
def check_folder():
f = 'data/streamannouncer'
if not os.path.exists(f):
os.makedirs(f)
def check_file():
f = 'data/streamannouncer/settings.json'
if dataIO.is_valid_json(f) is False:
dataIO.save_json(f, {})
f = 'data/streamannouncer/list.json'
if dataIO.is_valid_json(f) is False:
dataIO.save_json(f, {})
def setup(bot):
check_folder()
check_file()
n = StreamAnnouncer(bot)
bot.add_listener(n.on_stream, "on_member_update")
bot.add_cog(n)
|
import pytest
from k8s_utils import *
from s2i_utils import *
from java_utils import *
@pytest.fixture(scope="module")
def single_namespace_seldon_helm(request):
version = get_seldon_version()
create_seldon_single_namespace_helm(request,version)
port_forward(request)
@pytest.fixture(scope="module")
def clusterwide_seldon_helm(request):
version = get_seldon_version()
create_seldon_clusterwide_helm(request,version)
port_forward(request)
@pytest.fixture(scope="module")
def single_namespace_seldon_ksonnet(request):
create_seldon_single_namespace_ksonnet(request)
port_forward(request)
@pytest.fixture(scope="module")
def clusterwide_seldon_ksonnet(request):
create_seldon_clusterwide_ksonnet(request)
port_forward(request)
@pytest.fixture(scope="module")
def setup_python_s2i(request):
build_python_s2i_images()
@pytest.fixture(scope="module")
def s2i_python_version():
return get_s2i_python_version()
@pytest.fixture(scope="session")
def seldon_java_images(request):
create_docker_repo(request)
port_forward_docker_repo(request)
build_java_images()
@pytest.fixture(scope="session")
def seldon_version():
return get_seldon_version()
|
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.Qt import *
class ContentWidget(QWidget):
def __init__(self, parent=None):
super(ContentWidget, self).__init__(parent)
self.palette = QPalette()
self.top_widget = QWidget()
self.down_widget = QWidget()
self.top_widget.setStyleSheet("background-image: url(./images/contentWidget/background.png)")
self.down_widget.setStyleSheet("background-image: url(./images/contentWidget/background.png)")
self.palette.setBrush(QPalette.Window, QBrush(Qt.white)) #创建画刷
self.setPalette(self.palette)
self.setAutoFillBackground(True)
self.InitTopWidget() #设置上边窗体
self.InitDownWidget() #设置下边窗体
#设置主窗体
self.main_layout = QVBoxLayout()
self.main_layout.addWidget(self.top_widget)
self.main_layout.addWidget(self.down_widget)
self.main_layout.setSpacing(0)
self.main_layout.setContentsMargins(0, 0, 0, 0)
self.setLayout(self.main_layout)
self.translateLanguage()
#按键映射
self.searchButton.clicked.connect(parent.OpenUrl)
self.startButton.clicked.connect(parent.RunAnalyzer)
# 设置上边窗体
def InitTopWidget(self):
self.computerLabel = QLabel() # 电脑的图片
self.searchButton = QPushButton() #搜索按钮
self.searchButton.setCursor(Qt.PointingHandCursor)
self.urlTextEdit = QTextEdit()
self.urlTextEdit.setFixedSize(400,30)
self.urlTextEdit.setStyleSheet("background-image: url()")
self.top_widget.resize(650, 500)
#电脑图片属性
label_pixmap = QPixmap("./images/contentWidget/computer.png")
self.computerLabel.setPixmap(label_pixmap)
self.computerLabel.setFixedSize(label_pixmap.size())
#搜索按钮属性
pixmap = QPixmap("./images/contentWidget/power.png")
self.searchButton.setIcon(QIcon(pixmap))
self.searchButton.setIconSize(pixmap.size())
self.searchButton.setFixedSize(180, 70)
self.searchButton.setStyleSheet("QPushButton{border-radius:5px;background:rgb(110, 190, 10);color:white}"
"QPushButton:hover{background:rgb(140, 220, 35)}")
searchFont = QFont() # 字体设置
searchFont.setPointSize(16)
self.searchButton.setFont(searchFont)
h_layout = QHBoxLayout() # 水平布局
h_layout.addStretch(1)
h_layout.addWidget(self.computerLabel, 0, Qt.AlignVCenter) # 垂直方向居中
h_layout.addStretch(2)
h_layout.addWidget(self.urlTextEdit, 0, Qt.AlignVCenter)
h_layout.addStretch(2)
h_layout.addWidget(self.searchButton, 0, Qt.AlignRight)
h_layout.addStretch(2)
#h_layout.setSpacing(50) #控件之间的间距
h_layout.setContentsMargins(30, 20, 0, 0) #布局距离窗体四周边缘距离
self.top_widget.setLayout(h_layout) #最后装入top_widget返回
# 设置下边窗体
def InitDownWidget(self):
#中间部分文字的widget
self.firstLabel = QLabel()
self.firstLabel.setFixedSize(190,50)
self.firstLabel.setStyleSheet("background: transparent;\n"
"font: 75 18pt \"Microsoft YaHei UI\";")
#二级标题
self.secondList = []
for i in range(3):
self.tempLabel = QLabel()
self.tempLabel.setFixedSize(90,30)
self.tempLabel.setStyleSheet("background: transparent;\n"
"font: 14pt \"Microsoft YaHei UI\";")
self.secondList.append(self.tempLabel)
#三级标题
self.thirdList = []
for i in range(3):
self.tempLabel = QLabel()
self.tempLabel.setFixedSize(250, 20)
self.tempLabel.setStyleSheet("background: transparent;\n"
"font: 10pt \"Microsoft YaHei UI\";")
self.thirdList.append(self.tempLabel)
#文字左侧图标
self.leftIconLabel = QLabel()
label_pixmap = QPixmap ("./images/contentWidget/wallIcon.png")
self.leftIconLabel.setPixmap(label_pixmap)
self.leftIconLabel.setFixedSize(label_pixmap.size())
self.leftIconLabel.setStyleSheet("background-image: url()") #防止继承父类背景
self.leftIconLabel2 = QLabel()
label_pixmap = QPixmap ("./images/contentWidget/monitorIcon.png")
self.leftIconLabel2.setPixmap(label_pixmap)
self.leftIconLabel2.setFixedSize(label_pixmap.size())
self.leftIconLabel2.setStyleSheet("background-image: url()")
self.leftIconLabel3 = QLabel()
label_pixmap = QPixmap ("./images/contentWidget/reportIcon.png")
self.leftIconLabel3.setPixmap(label_pixmap)
self.leftIconLabel3.setFixedSize(label_pixmap.size())
self.leftIconLabel3.setStyleSheet("background-image: url()")
self.leftBigIconLabel = QLabel() #最左侧大图标
label_pixmap = QPixmap("./images/contentWidget/protectIcon.png")
self.leftBigIconLabel.setPixmap(label_pixmap)
self.leftBigIconLabel.setFixedSize(label_pixmap.size())
self.leftBigIconLabel.setStyleSheet("background-image: url()")
#右侧按钮和艺术字
self.startButton = QPushButton()
self.startButton.setCursor(Qt.PointingHandCursor)
self.startButton.setFixedSize(180, 70)
self.startButton.setStyleSheet("QPushButton{border-radius:5px;background:rgb(110, 190, 10);color:white}"
"QPushButton:hover{background:rgb(140, 220, 35)}")
power_font = QFont() #= self.power_button.font()
power_font.setPointSize(16)
self.startButton.setFont(power_font)
self.artLabel = QLabel()
label_pixmap = QPixmap("./images/contentWidget/artword.png")
self.artLabel.setPixmap(label_pixmap)
self.artLabel.setFixedSize(label_pixmap.size())
self.artLabel.setStyleSheet("background: transparent;")
self.down_widget.resize(650, 500)
#左侧图标布局
icon_layout = QVBoxLayout() # 垂直布局
icon_layout.addWidget(self.leftIconLabel, 0, Qt.AlignLeft)
icon_layout.addWidget(self.leftIconLabel2, 0, Qt.AlignLeft)
icon_layout.addWidget(self.leftIconLabel3, 0, Qt.AlignLeft)
icon_layout.addStretch()
icon_layout.setSpacing(45) #控件之间的间距
icon_layout.setContentsMargins(0, 85, 0, 0) #布局距离窗体四周边缘距离
#中间文字布局
text_layout = QVBoxLayout() #垂直布局
text_layout.addWidget(self.firstLabel, 0, Qt.AlignLeft) #水平方向靠左
text_layout.addWidget(self.secondList[0], 0, Qt.AlignLeft)
text_layout.addWidget(self.thirdList[0], 0, Qt.AlignLeft)
text_layout.addWidget(self.secondList[1], 0, Qt.AlignLeft)
text_layout.addWidget(self.thirdList[1], 0, Qt.AlignLeft)
text_layout.addWidget(self.secondList[2], 0, Qt.AlignLeft)
text_layout.addWidget(self.thirdList[2], 0, Qt.AlignLeft)
text_layout.addStretch()
text_layout.setSpacing(15) #控件之间的间距
text_layout.setContentsMargins(0, 20, 0, 20) #布局距离窗体四周边缘距离
#右侧布局
right_layout = QVBoxLayout() # 垂直布局
right_layout.addWidget(self.startButton, 0, Qt.AlignCenter)
right_layout.addWidget(self.artLabel, 0, Qt.AlignCenter)
right_layout.addStretch()
right_layout.setSpacing(100) #控件之间的间距
right_layout.setContentsMargins(0, 40, 0, 0) #布局距离窗体四周边缘距离
#总的布局
main_layout = QHBoxLayout() # 水平布局
main_layout.addStretch(1) #空白部分比例(所有的addStretch之间的比例)
main_layout.addWidget(self.leftBigIconLabel,0,Qt.AlignVCenter)
main_layout.addStretch(5)
main_layout.addLayout(icon_layout)
main_layout.addStretch(1)
main_layout.addLayout(text_layout)
main_layout.addStretch(5)
main_layout.addLayout(right_layout)
main_layout.addStretch(1)
main_layout.setSpacing(15)
main_layout.setContentsMargins(0, 0, 0, 0)
self.down_widget.setLayout(main_layout) #最后装入down_widget返回
def translateLanguage(self):
self.searchButton.setText(u"search")
self.firstLabel.setText(u"检测未知程序")
self.secondList[0].setText(u"隔离保护")
self.secondList[1].setText(u"监测检测")
self.secondList[2].setText(u"生成报告")
self.thirdList[0].setText(u"避免计算机收到来自未知程序的伤害")
self.thirdList[1].setText(u"检测未知程序调用的API函数")
self.thirdList[2].setText(u"生成未知程序的测试报告")
self.startButton.setText(u"开始检测")
#事件过滤器(具体作用没了解)
def eventFilter(self, obj, event):
if(obj is QLabel):
if(event.type() == QEvent.Paint):
label_height_1 = self.line_label_1.height()
label_width_1 = self.line_label_1.width()
painter = QPainter (self.line_label_1)
painter.setPen(QPen(QColor(220, 220, 220), 1, Qt.DashLine))
painter.drawLine(label_width_1 / 2, 0, label_width_1 / 2, label_height_1)
label_height_2 = self.line_label_2.height()
label_width_2 = self.line_label_2.width()
painter2 = QPainter (self.line_label_2)
painter2.setPen(QPen(QColor(220, 220, 220), 1, Qt.DashLine))
painter2.drawLine(label_width_2 / 2, 0, label_width_2 / 2, label_height_2)
return True
return False#self.eventFilter(obj, event)
class ContentWidget2(QWidget):
def __init__(self, parent=None):
super(ContentWidget2, self).__init__(parent)
self.palette = QPalette()
self.top_widget = QWidget()
self.down_widget = QWidget()
self.top_widget.setStyleSheet("background-image: url(./images/contentWidget/background.png)")
self.down_widget.setStyleSheet("background-image: url(./images/contentWidget/background.png)")
self.palette.setBrush(QPalette.Window, QBrush(Qt.white)) #创建画刷
self.setPalette(self.palette)
self.setAutoFillBackground(True)
self.main_splitter = QSplitter() #分割窗口
self.main_splitter.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.main_splitter.setOrientation(Qt.Vertical) #横向排列
self.main_splitter.setHandleWidth(1) #设置窗口分割线
self.main_splitter.setStyleSheet("QSplitter.handle{background:lightgray}")
self.InitTopWidget() #设置上边窗体
self.InitDownWidget() #设置下边窗体
#设置主窗体
self.main_splitter.addWidget(self.top_widget)
self.main_splitter.addWidget(self.down_widget)
self.main_layout = QVBoxLayout()
self.main_layout.addWidget(self.main_splitter)
self.main_layout.setSpacing(0)
self.main_layout.setContentsMargins(0, 0, 0, 0)
#设置按键映射
self.rightButtonList[0].clicked.connect(parent.OpenWeb1)
self.rightButtonList[1].clicked.connect(parent.OpenWeb2)
self.rightButtonList[2].clicked.connect(parent.OpenWeb3)
self.rightButtonList[3].clicked.connect(parent.OpenWeb4)
self.setLayout(self.main_layout)
self.translateLanguage()
# 设置上边窗体
def InitTopWidget(self):
self.computerLabel = QLabel() # 电脑的图片
self.showButton = QPushButton() #显示按钮
self.showButton.setCursor(Qt.PointingHandCursor)
#进度条
self.progressBar = QProgressBar()
self.progressBar.setFixedSize(500,30)
self.progressBar.setProperty("value", 0)
self.top_widget.resize(650, 500)
#电脑图片属性
label_pixmap = QPixmap("./images/contentWidget/computer.png")
self.computerLabel.setPixmap(label_pixmap)
self.computerLabel.setFixedSize(label_pixmap.size())
#显示信息按钮属性
self.showButton.setFixedSize(150, 50)
self.showButton.setStyleSheet("QPushButton{border-radius:5px;background:rgb(110, 190, 10);color:white}"
"QPushButton:hover{background:rgb(140, 220, 35)}")
searchFont = QFont() # 字体设置
searchFont.setPointSize(16)
self.showButton.setFont(searchFont)
h_layout = QHBoxLayout() # 水平布局
h_layout.addStretch(1)
h_layout.addWidget(self.computerLabel, 0, Qt.AlignVCenter) # 垂直方向居中
h_layout.addStretch(1)
h_layout.addWidget(self.progressBar, 0, Qt.AlignVCenter)
h_layout.addStretch(1)
h_layout.addWidget(self.showButton, 0, Qt.AlignVCenter)
h_layout.addStretch(6)
#h_layout.setSpacing(50) #控件之间的间距
h_layout.setContentsMargins(30, 20, 0, 0) #布局距离窗体四周边缘距离
'''main_layout = QVBoxLayout() # 垂直布局
main_layout.addLayout(h_layout)
main_layout.addWidget(self.power_button, 0, Qt.AlignCenter) # 水平方向居中
main_layout.addStretch()
main_layout.setSpacing(0)
main_layout.setContentsMargins(0, 0, 0, 0)'''
self.top_widget.setLayout(h_layout) #最后装入top_widget返回
# 设置下边窗体
def InitDownWidget(self):
self.reportTextEdit = QPlainTextEdit()
self.reportTextEdit.setFixedSize(500,270)
self.reportTextEdit.setStyleSheet("background-image: url(./images/contentWidget/whitebackground.png);")
#右侧四个按钮
self.rightButtonList = []
temp_button = QToolButton()
temp_button.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
recovery_pixmap = QPixmap ("./images/contentWidget/scalars.png")
temp_button.setIcon(QIcon(recovery_pixmap))
temp_button.setIconSize(recovery_pixmap.size())
temp_button.setFixedSize(recovery_pixmap.width() + 50, recovery_pixmap.height() + 35)
#修复hover样式
temp_button.setStyleSheet("QToolButton{background:transparent}"
"QToolButton:hover{border-radius:5px;border:1px solid rgb(210, 225, 230)}")
self.rightButtonList.append(temp_button)
temp_button = QToolButton()
temp_button.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
recovery_pixmap = QPixmap ("./images/contentWidget/graphs.png")
temp_button.setIcon(QIcon(recovery_pixmap))
temp_button.setIconSize(recovery_pixmap.size())
temp_button.setFixedSize(recovery_pixmap.width() + 50, recovery_pixmap.height() + 35)
#修复hover样式
temp_button.setStyleSheet("QToolButton{background:transparent}"
"QToolButton:hover{border-radius:5px;border:1px solid rgb(210, 225, 230)}")
self.rightButtonList.append(temp_button)
temp_button = QToolButton()
temp_button.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
recovery_pixmap = QPixmap ("./images/contentWidget/distributions.png")
temp_button.setIcon(QIcon(recovery_pixmap))
temp_button.setIconSize(recovery_pixmap.size())
temp_button.setFixedSize(recovery_pixmap.width() + 50, recovery_pixmap.height() + 35)
#修复hover样式
temp_button.setStyleSheet("QToolButton{background:transparent}"
"QToolButton:hover{border-radius:5px;border:1px solid rgb(210, 225, 230)}")
self.rightButtonList.append(temp_button)
temp_button = QToolButton()
temp_button.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
recovery_pixmap = QPixmap ("./images/contentWidget/histograms.png")
temp_button.setIcon(QIcon(recovery_pixmap))
temp_button.setIconSize(recovery_pixmap.size())
temp_button.setFixedSize(recovery_pixmap.width() + 50, recovery_pixmap.height() + 35)
#修复hover样式
temp_button.setStyleSheet("QToolButton{background:transparent}"
"QToolButton:hover{border-radius:5px;border:1px solid rgb(210, 225, 230)}")
self.rightButtonList.append(temp_button)
self.down_widget.resize(650, 500)
#左侧布局(主要是为了控制距离窗体的距离)
left_layout = QVBoxLayout()
left_layout.addWidget(self.reportTextEdit, 0, Qt.AlignCenter)
left_layout.setContentsMargins(40, 40, 40, 40) #布局距离窗体四周边缘距离
#右侧布局
v_layout1 = QHBoxLayout() #水平布局
v_layout1.addWidget(self.rightButtonList[0], 0, Qt.AlignCenter)
v_layout1.addWidget(self.rightButtonList[1], 0, Qt.AlignCenter)
v_layout2 = QHBoxLayout() #水平布局
v_layout2.addWidget(self.rightButtonList[2], 0, Qt.AlignCenter)
v_layout2.addWidget(self.rightButtonList[3], 0, Qt.AlignCenter)
right_layout = QVBoxLayout() # 垂直布局
right_layout.addLayout(v_layout1)
right_layout.addLayout(v_layout2)
right_layout.addStretch()
right_layout.setSpacing(30) #控件之间的间距
right_layout.setContentsMargins(0, 50, 40, 0) #布局距离窗体四周边缘距离
#总的布局
main_layout = QHBoxLayout() # 水平布局
main_layout.addStretch(1) #空白部分比例(所有的addStretch之间的比例)
main_layout.addLayout(left_layout)
main_layout.addStretch(2)
main_layout.addLayout(right_layout)
main_layout.addStretch(1)
main_layout.setSpacing(15)
main_layout.setContentsMargins(0, 0, 0, 0)
self.down_widget.setLayout(main_layout) #最后装入down_widget返回
def translateLanguage(self):
self.showButton.setText(u"显示信息")
self.rightButtonList[0].setText(u"SCALARS")
self.rightButtonList[1].setText(u"GRAPHS")
self.rightButtonList[2].setText(u"DISTRIBUTIONS")
self.rightButtonList[3].setText(u"HISTOGRAMS")
#事件过滤器(具体作用没了解)
def eventFilter(self, obj, event):
if(obj is QLabel):
if(event.type() == QEvent.Paint):
label_height_1 = self.line_label_1.height()
label_width_1 = self.line_label_1.width()
painter = QPainter (self.line_label_1)
painter.setPen(QPen(QColor(220, 220, 220), 1, Qt.DashLine))
painter.drawLine(label_width_1 / 2, 0, label_width_1 / 2, label_height_1)
label_height_2 = self.line_label_2.height()
label_width_2 = self.line_label_2.width()
painter2 = QPainter (self.line_label_2)
painter2.setPen(QPen(QColor(220, 220, 220), 1, Qt.DashLine))
painter2.drawLine(label_width_2 / 2, 0, label_width_2 / 2, label_height_2)
return True
return False#self.eventFilter(obj, event)
class ContentWidget3(QWidget):
def __init__(self, parent=None):
super(ContentWidget3, self).__init__(parent)
self.palette = QPalette()
self.top_widget = QWidget()
self.down_widget = QWidget()
self.top_widget.setStyleSheet("background-image: url(./images/contentWidget/background.png)")
self.down_widget.setStyleSheet("background-image: url(./images/contentWidget/background.png)")
self.palette.setBrush(QPalette.Window, QBrush(Qt.white)) #创建画刷
self.setPalette(self.palette)
self.setAutoFillBackground(True)
self.main_splitter = QSplitter() #分割窗口
self.main_splitter.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.main_splitter.setOrientation(Qt.Vertical) #横向排列
self.main_splitter.setHandleWidth(1) #设置窗口分割线
self.main_splitter.setStyleSheet("QSplitter.handle{background:lightgray}")
self.InitTopWidget() #设置上边窗体
self.InitDownWidget() #设置下边窗体
#设置主窗体
self.main_splitter.addWidget(self.top_widget)
self.main_splitter.addWidget(self.down_widget)
self.main_layout = QVBoxLayout()
self.main_layout.addWidget(self.main_splitter)
self.main_layout.setSpacing(0)
self.main_layout.setContentsMargins(0, 0, 0, 0)
self.setLayout(self.main_layout)
self.translateLanguage()
# 设置上边窗体
def InitTopWidget(self):
self.computerLabel = QLabel() # 电脑的图片
self.showButton = QPushButton() #显示按钮
self.showButton.setCursor(Qt.PointingHandCursor)
#进度条
self.progressBar = QProgressBar()
self.progressBar.setFixedSize(500,30)
self.progressBar.setProperty("value", 0)
self.top_widget.resize(650, 500)
#电脑图片属性
label_pixmap = QPixmap("./images/contentWidget/computer.png")
self.computerLabel.setPixmap(label_pixmap)
self.computerLabel.setFixedSize(label_pixmap.size())
#显示信息按钮属性
self.showButton.setFixedSize(150, 50)
self.showButton.setStyleSheet("QPushButton{border-radius:5px;background:rgb(110, 190, 10);color:white}"
"QPushButton:hover{background:rgb(140, 220, 35)}")
searchFont = QFont() # 字体设置
searchFont.setPointSize(16)
self.showButton.setFont(searchFont)
h_layout = QHBoxLayout() # 水平布局
h_layout.addStretch(1)
h_layout.addWidget(self.computerLabel, 0, Qt.AlignVCenter) # 垂直方向居中
h_layout.addStretch(1)
h_layout.addWidget(self.progressBar, 0, Qt.AlignVCenter)
h_layout.addStretch(1)
h_layout.addWidget(self.showButton, 0, Qt.AlignVCenter)
h_layout.addStretch(6)
#h_layout.setSpacing(50) #控件之间的间距
h_layout.setContentsMargins(30, 20, 0, 0) #布局距离窗体四周边缘距离
self.top_widget.setLayout(h_layout) #最后装入top_widget返回
# 设置下边窗体
def InitDownWidget(self):
self.reportTextEdit = QPlainTextEdit()
self.reportTextEdit.setFixedSize(500,270)
self.reportTextEdit.setStyleSheet("background-image: url(./images/contentWidget/whitebackground.png);")
self.grayTextLabel = QLabel()
self.grayTextLabel.setFixedSize(90, 30)
self.grayTextLabel.setStyleSheet("background: transparent;\n"
"font: 14pt \"Microsoft YaHei UI\";")
self.grayPictureLabel = QLabel() # 电脑的图片
#电脑图片属性
label_pixmap = QPixmap("./images/contentWidget/gray.png")
self.grayPictureLabel.setPixmap(label_pixmap)
self.grayPictureLabel.setFixedSize(label_pixmap.size())
self.down_widget.resize(650, 500)
#左侧布局(主要是为了控制距离窗体的距离)
left_layout = QVBoxLayout()
left_layout.addWidget(self.reportTextEdit, 0, Qt.AlignCenter)
left_layout.setContentsMargins(40, 40, 40, 40) #布局距离窗体四周边缘距离
#右侧布局
right_layout = QVBoxLayout() # 垂直布局
right_layout.addWidget(self.grayPictureLabel, 0, Qt.AlignCenter)
right_layout.addWidget(self.grayTextLabel, 0, Qt.AlignCenter)
right_layout.setSpacing(10) #控件之间的间距
right_layout.setContentsMargins(0, 45, 20, 0) #布局距离窗体四周边缘距离
#总的布局
main_layout = QHBoxLayout() # 水平布局
main_layout.addStretch(1) #空白部分比例(所有的addStretch之间的比例)
main_layout.addLayout(left_layout)
main_layout.addStretch(5)
main_layout.addLayout(right_layout)
main_layout.addStretch(1)
main_layout.setSpacing(15)
main_layout.setContentsMargins(0, 0, 0, 0)
self.down_widget.setLayout(main_layout) #最后装入down_widget返回
def translateLanguage(self):
self.showButton.setText(u"显示信息")
self.grayTextLabel.setText(u"灰度图像")
#事件过滤器(具体作用没了解)
def eventFilter(self, obj, event):
if(obj is QLabel):
if(event.type() == QEvent.Paint):
label_height_1 = self.line_label_1.height()
label_width_1 = self.line_label_1.width()
painter = QPainter (self.line_label_1)
painter.setPen(QPen(QColor(220, 220, 220), 1, Qt.DashLine))
painter.drawLine(label_width_1 / 2, 0, label_width_1 / 2, label_height_1)
label_height_2 = self.line_label_2.height()
label_width_2 = self.line_label_2.width()
painter2 = QPainter (self.line_label_2)
painter2.setPen(QPen(QColor(220, 220, 220), 1, Qt.DashLine))
painter2.drawLine(label_width_2 / 2, 0, label_width_2 / 2, label_height_2)
return True
return False#self.eventFilter(obj, event)
class ContentWidget4(QWidget):
def __init__(self, parent=None):
super(ContentWidget4, self).__init__(parent)
self.palette = QPalette() #改变控件颜色
self.right_widget = QWidget()
self.left_widget = QWidget()
self.left_widget.setStyleSheet("background-image: url(./images/contentWidget/background.png)")
self.right_widget.setStyleSheet("background-image: url(./images/contentWidget/background_right.png)")
self.palette.setBrush(QPalette.Window, QBrush(Qt.white)) #创建画刷
self.setPalette(self.palette)
self.setAutoFillBackground(True)
self.initLeft()
self.initRight()
self.main_layout = QHBoxLayout()
self.main_layout.addWidget(self.left_widget)
self.main_layout.addWidget(self.right_widget)
self.main_layout.setSpacing(0)
self.main_layout.setContentsMargins(0, 0, 0, 0)
self.setLayout(self.main_layout)
self.translateLanguage()
def initLeft(self):
self.computerLabel = QLabel() # 电脑的图片
self.neuralButton = QPushButton() # 神经网络按钮
self.neuralButton.setCursor(Qt.PointingHandCursor)
#中间部分文字的widget
self.resultLabel = QLabel()
self.resultLabel.setFixedSize(250,100)
self.resultLabel.setStyleSheet("background: transparent;\n"
"font: 75 13pt \"Microsoft YaHei UI\";")
self.left_widget.resize(650, 500)
# 电脑图片属性
label_pixmap = QPixmap("./images/contentWidget/computer.png")
self.computerLabel.setPixmap(label_pixmap)
self.computerLabel.setFixedSize(label_pixmap.size())
# 显示神经网络按钮属性
self.neuralButton.setFixedSize(150, 50)
self.neuralButton.setStyleSheet("QPushButton{border-radius:5px;background:rgb(110, 190, 10);color:white}"
"QPushButton:hover{background:rgb(140, 220, 35)}")
searchFont = QFont() # 字体设置
searchFont.setPointSize(16)
self.neuralButton.setFont(searchFont)
#显示报告文本
self.reportTextEdit = QPlainTextEdit()
self.reportTextEdit.setFixedSize(600,250)
self.reportTextEdit.setStyleSheet("background-image: url(./images/contentWidget/whitebackground.png);")
h_layout = QHBoxLayout() # 水平布局
h_layout.addStretch(1)
h_layout.addWidget(self.computerLabel, 0, Qt.AlignVCenter) # 垂直方向居中
h_layout.addStretch(3)
h_layout.addWidget(self.resultLabel, 0, Qt.AlignVCenter)
h_layout.addStretch(3)
h_layout.addWidget(self.neuralButton, 0, Qt.AlignVCenter)
h_layout.addStretch(6)
# h_layout.setSpacing(50) #控件之间的间距
h_layout.setContentsMargins(0, 20, 0, 0) # 布局距离窗体四周边缘距离
v_layout = QVBoxLayout() #垂直布局
v_layout.addLayout(h_layout)
v_layout.addStretch(1)
v_layout.addWidget(self.reportTextEdit)
v_layout.addStretch(2)
v_layout.setContentsMargins(20, 20, 20, 0) # 布局距离窗体四周边缘距离
self.left_widget.setLayout(v_layout) # 最后装入top_widget返回
def initRight(self):
'''self.grayTextLabel = QLabel()
self.grayTextLabel.setFixedSize(90, 30)
self.grayTextLabel.setStyleSheet("background: transparent;\n"
"font: 14pt \"Microsoft YaHei UI\";")'''
self.grayTextbutton = QPushButton()
self.grayTextbutton.setFixedSize(240, 60)
self.grayTextbutton.setStyleSheet("QPushButton{color:green;border-image:url(./images/contentWidget/gray_button.png)}"
"QPushButton:hover{color:rgb(110, 190, 10)}")
login_font = QFont()
login_font.setBold(True)
login_font.setPointSize(12)
self.grayTextbutton.setFont(login_font)
self.grayPictureLabel = QLabel() # 电脑的图片
# 电脑图片属性
label_pixmap = QPixmap("./images/contentWidget/gray4.png")
self.grayPictureLabel.setPixmap(label_pixmap)
self.grayPictureLabel.setFixedSize(label_pixmap.size())
self.right_widget.resize(300, 250)
# 右侧布局
main_layout = QVBoxLayout() # 垂直布局
main_layout.addWidget(self.grayTextbutton, 0, Qt.AlignRight)
main_layout.addWidget(self.grayPictureLabel, 0, Qt.AlignCenter)
main_layout.setSpacing(10) # 控件之间的间距
main_layout.setContentsMargins(10, 0, 10, 10) # 布局距离窗体四周边缘距离
self.right_widget.setLayout(main_layout) # 最后装入right_widget返回
def translateLanguage(self):
self.resultLabel.setText(u"当前未进行检测")
self.neuralButton.setText(u"显示神经网络")
self.grayTextbutton.setText(u"灰度图像")
#这个是原来360的widget
class ContentWidget5(QWidget):
def __init__(self, parent=None):
super(ContentWidget5, self).__init__(parent)
self.palette = QPalette() #改变控件颜色
self.right_splitter = QSplitter() #分割窗口
self.right_top_widget = QWidget()
self.right_center_widget = QWidget()
self.right_bottom_widget = QWidget()
self.right_center_function_widget = QWidget()
self.left_widget = QWidget()
self.palette.setBrush(QPalette.Window, QBrush(Qt.white)) #创建画刷
self.setPalette(self.palette)
self.setAutoFillBackground(True)
self.main_splitter = QSplitter() #分割窗口
self.main_splitter.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding)
self.main_splitter.setOrientation(Qt.Horizontal) #横向排列
self.main_splitter.setHandleWidth(1) #设置窗口分割线
self.main_splitter.setStyleSheet("QSplitter.handle{background:lightgray}")
self.initLeft()
self.initRight()
self.initRightTop()
self.initRightCenter()
self.initRightCenterFunction()
self.initRightBottom()
self.right_splitter.setSizePolicy(QSizePolicy.Fixed, QSizePolicy.Fixed)
self.right_splitter.setOrientation(Qt.Vertical)
self.right_splitter.setHandleWidth(1)
self.right_splitter.setStyleSheet("QSplitter.handle{background:lightgray}")
self.right_top_widget.setFixedSize(250, 130)
self.right_center_widget.setFixedSize(250, 90)
self.right_bottom_widget.setFixedSize(250, 30)
self.right_splitter.addWidget(self.right_top_widget)
self.right_splitter.addWidget(self.right_center_widget)
self.right_splitter.addWidget(self.right_center_function_widget)
self.right_splitter.addWidget(self.right_bottom_widget)
self.main_splitter.addWidget(self.left_widget)
self.main_splitter.addWidget(self.right_splitter)
#禁止拖动
for i in range(self.right_splitter.count()):
handle = QSplitterHandle(Qt.Horizontal, self.right_splitter)
self.right_splitter.handle(i)
handle.setEnabled(False)
for i in range(self.main_splitter.count()):
handle = QSplitterHandle(Qt.Horizontal, self.right_splitter)
self.main_splitter.handle(i)
handle.setEnabled(False)
self.main_layout = QHBoxLayout()
self.main_layout.addWidget(self.main_splitter)
self.main_layout.setSpacing(0)
self.main_layout.setContentsMargins(0, 0, 0, 0)
self.setLayout(self.main_layout)
self.translateLanguage()
def initLeft(self):
#self.left_widget = QWidget()
self.label = QLabel() #电脑的图片
self.suggest_label = QLabel()
self.system_safe_label = QLabel()
self.power_button = QPushButton()
self.left_widget.resize(650, 500)
label_pixmap = QPixmap ("./images/contentWidget/computer.png")
self.label.setPixmap(label_pixmap)
self.label.setFixedSize(label_pixmap.size())
#设置字体
suggest_font = QFont() #= self.suggest_label.font()
suggest_font.setPointSize(12)
suggest_font.setBold(True)
self.suggest_label.setFont(suggest_font)
self.suggest_label.setStyleSheet("color:gray")
system_safe_font = QFont()# = self.system_safe_label.font()
system_safe_font.setBold(True)
self.system_safe_label.setFont(system_safe_font)
self.system_safe_label.setStyleSheet("color:gray")
pixmap = QPixmap("./images/contentWidget/power.png") #
self.power_button.setIcon(QIcon(pixmap))
self.power_button.setIconSize(pixmap.size())
self.power_button.setFixedSize(180, 70)
self.power_button.setStyleSheet("QPushButton{border-radius:5px;background:rgb(110, 190, 10);color:white}"
"QPushButton:hover{background:rgb(140, 220, 35)}")
power_font = QFont() #= self.power_button.font()
power_font.setPointSize(16)
self.power_button.setFont(power_font)
v_layout = QVBoxLayout() #垂直布局
v_layout.addWidget(self.suggest_label)
v_layout.addWidget(self.system_safe_label)
v_layout.addStretch()
v_layout.setSpacing(15) #控件之间的间距
v_layout.setContentsMargins(0, 20, 0, 0) #布局距离窗体四周边缘距离
h_layout = QHBoxLayout() #水平布局
h_layout.addWidget(self.label, 0, Qt.AlignTop) #垂直方向靠上
h_layout.addLayout(v_layout)
h_layout.addStretch()
h_layout.setSpacing(20)
h_layout.setContentsMargins(30, 20, 0, 0)
main_layout = QVBoxLayout() #垂直布局
main_layout.addLayout(h_layout)
main_layout.addWidget(self.power_button, 0, Qt.AlignCenter) #水平方向居中
main_layout.addStretch()
main_layout.setSpacing(0)
main_layout.setContentsMargins(0, 0, 0, 0)
self.left_widget.setLayout(main_layout)
def initRight(self):
self.right_splitter = QSplitter()
#self.right_splitter.resize(250, 500)
def initRightTop(self):
self.right_top_widget = QWidget()
self.login_button = QPushButton()
priv_label = QLabel()
self.info_label = QLabel()
self.privilege_label = QLabel()
self.register_button = QPushButton()
safe_button = QPushButton()
tab_button = QPushButton()
pet_button = QPushButton()
lottery_button = QPushButton()
cloud_five_button = QPushButton()
caipiao_button = QPushButton()
self.login_button.setFixedSize(240, 60)
self.login_button.setStyleSheet("QPushButton{color:green;border-image:url(./images/contentWidget/login.png)}"
"QPushButton:hover{color:rgb(110, 190, 10)}")
login_font = QFont()# = self.login_button.font()
login_font.setBold(True)
login_font.setPointSize(12)
self.login_button.setFont(login_font)
priv_label.setPixmap(QPixmap("./images/contentWidget/priv.png"))
safe_pixmap = QPixmap ("./images/contentWidget/360")
safe_button.setIcon(QIcon(safe_pixmap))
safe_button.setFixedSize(safe_pixmap.size())
tab_pixmap = QPixmap ("./images/contentWidget/tab.png")
tab_button.setIcon(QIcon(tab_pixmap))
tab_button.setFixedSize(tab_pixmap.size())
pet_pixmap = QPixmap ("./images/contentWidget/pet.png")
pet_button.setIcon(QIcon(pet_pixmap))
pet_button.setFixedSize(tab_pixmap.size())
lottery_pixmap = QPixmap ("./images/contentWidget/lottery.png")
lottery_button.setIcon(QIcon(lottery_pixmap))
lottery_button.setFixedSize(lottery_pixmap.size())
cloud_five_pixmap = QPixmap ("./images/contentWidget/cloud_five.png")
cloud_five_button.setIcon(QIcon(cloud_five_pixmap))
cloud_five_button.setFixedSize(cloud_five_pixmap.size())
caipiao_pixmap = QPixmap ("./images/contentWidget/caipiao.png")
caipiao_button.setIcon(QIcon(caipiao_pixmap))
caipiao_button.setFixedSize(caipiao_pixmap.size())
self.register_button.setCursor(Qt.PointingHandCursor)
safe_button.setCursor(Qt.PointingHandCursor)
tab_button.setCursor(Qt.PointingHandCursor)
pet_button.setCursor(Qt.PointingHandCursor)
lottery_button.setCursor(Qt.PointingHandCursor)
cloud_five_button.setCursor(Qt.PointingHandCursor)
caipiao_button.setCursor(Qt.PointingHandCursor)
#修复无法parses的问题:elf.register_button.setStyleSheet("color:rgb(0, 120, 230) background:transparent")
self.register_button.setStyleSheet("color:rgb(0, 120, 230);background:transparent")
safe_button.setStyleSheet("background:transparent")
tab_button.setStyleSheet("background:transparent")
pet_button.setStyleSheet("background:transparent")
lottery_button.setStyleSheet("background:transparent")
cloud_five_button.setStyleSheet("background:transparent")
caipiao_button.setStyleSheet("background:transparent")
login_layout = QHBoxLayout()
login_layout.addWidget(self.login_button)
login_layout.addStretch()
login_layout.setContentsMargins(15, 0, 0, 0)
register_layout = QHBoxLayout()
register_layout.addStretch()
register_layout.addWidget(priv_label)
register_layout.addWidget(self.info_label)
register_layout.addWidget(self.register_button)
register_layout.addStretch()
register_layout.setSpacing(5)
register_layout.setContentsMargins(0, 0, 0, 0)
privilege_layout = QHBoxLayout()
privilege_layout.addStretch()
privilege_layout.addWidget(self.privilege_label)
privilege_layout.addWidget(safe_button)
privilege_layout.addWidget(tab_button)
privilege_layout.addWidget(pet_button)
privilege_layout.addWidget(lottery_button)
privilege_layout.addWidget(cloud_five_button)
privilege_layout.addWidget(caipiao_button)
privilege_layout.addStretch()
privilege_layout.setSpacing(8)
privilege_layout.setContentsMargins(0, 0, 0, 0)
main_layout = QVBoxLayout()
main_layout.addStretch()
main_layout.addLayout(login_layout)
main_layout.addLayout(register_layout)
main_layout.addLayout(privilege_layout)
main_layout.addStretch()
main_layout.setSpacing(5)
main_layout.setContentsMargins(10, 10, 10, 10)
self.right_top_widget.setLayout(main_layout)
def initRightCenter(self):
self.right_center_widget = QWidget()
self.fireproof_button = QToolButton()
self.triggerman_button = QToolButton()
self.net_shop_button = QToolButton()
self.line_label_1 = QLabel()
self.line_label_2 = QLabel()
self.line_label_1.setFixedWidth(10)
self.line_label_2.setFixedWidth(10)
self.line_label_1.installEventFilter(self)
self.line_label_2.installEventFilter(self)
self.fireproof_button.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
self.triggerman_button.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
self.net_shop_button.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
#设置图标
fireproof_pixmap = QPixmap ("./images/contentWidget/fireproof.png")
self.fireproof_button.setIcon(QIcon(fireproof_pixmap))
self.fireproof_button.setIconSize(fireproof_pixmap.size())
self.fireproof_button.setFixedSize(fireproof_pixmap.width() + 25, fireproof_pixmap.height() + 25)
triggerman_pixmap = QPixmap ("./images/contentWidget/triggerman.png")
self.triggerman_button.setIcon(QIcon(triggerman_pixmap))
self.triggerman_button.setIconSize(triggerman_pixmap.size())
self.triggerman_button.setFixedSize(triggerman_pixmap.width() + 25, triggerman_pixmap.height() + 25)
net_shop_pixmap = QPixmap ("./images/contentWidget/net_shop.png")
self.net_shop_button.setIcon(QIcon(net_shop_pixmap))
self.net_shop_button.setIconSize(net_shop_pixmap.size())
self.net_shop_button.setFixedSize(net_shop_pixmap.width() + 25, net_shop_pixmap.height() + 25)
self.fireproof_button.setStyleSheet("background:transparent")
self.triggerman_button.setStyleSheet("background:transparent")
self.net_shop_button.setStyleSheet("background:transparent")
h_layout = QHBoxLayout()
h_layout.addWidget(self.fireproof_button)
h_layout.addWidget(self.line_label_1)
h_layout.addWidget(self.triggerman_button)
h_layout.addWidget(self.line_label_2)
h_layout.addWidget(self.net_shop_button)
h_layout.setSpacing(0)
h_layout.setContentsMargins(0, 0, 0, 0)
self.right_center_widget.setLayout(h_layout)
def initRightCenterFunction(self):
self.right_center_function_widget = QWidget()
self.function_label = QLabel()
self.more_button = QPushButton()
function_font = QFont()# = self.function_label.font()
function_font.setBold(True)
self.function_label.setFont(function_font)
self.function_label.setStyleSheet("color:green")
self.more_button.setFixedSize(50, 25)
self.more_button.setStyleSheet("QPushButton{color:rgb(0, 120, 230);background:transparent}")
self.more_button.setCursor(Qt.PointingHandCursor)
h_layout = QHBoxLayout()
h_layout.addWidget(self.function_label)
h_layout.addStretch()
h_layout.addWidget(self.more_button)
h_layout.setSpacing(0)
h_layout.setContentsMargins(10, 5, 0, 0)
self.recovery_button = QToolButton()
self.recovery_button.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
recovery_pixmap = QPixmap ("./images/contentWidget/recovery.png")
self.recovery_button.setIcon(QIcon(recovery_pixmap))
self.recovery_button.setIconSize(recovery_pixmap.size())
self.recovery_button.setFixedSize(recovery_pixmap.width() + 50, recovery_pixmap.height() + 35)
#修复hover样式
self.recovery_button.setStyleSheet("QToolButton{background:transparent}"
"QToolButton:hover{border-radius:5px;border:1px solid rgb(210, 225, 230)}")
self.mobile_button = QToolButton()
self.mobile_button.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
mobile_pixmap = QPixmap ("./images/contentWidget/mobile.png")
self.mobile_button.setIcon(QIcon(mobile_pixmap))
self.mobile_button.setIconSize(mobile_pixmap.size())
self.mobile_button.setFixedSize(mobile_pixmap.width() + 50, mobile_pixmap.height() + 35)
self.mobile_button.setStyleSheet("QToolButton{background:transparent}"
"QToolButton:hover{border-radius:5px;border:1px solid rgb(210, 225, 230)}")
self.game_box_button = QToolButton()
self.game_box_button.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
game_box_pixmap = QPixmap ("./images/contentWidget/game_box.png")
self.game_box_button.setIcon(QIcon(game_box_pixmap))
self.game_box_button.setIconSize(game_box_pixmap.size())
self.game_box_button.setFixedSize(game_box_pixmap.width() + 50, game_box_pixmap.height() + 35)
self.game_box_button.setStyleSheet("QToolButton{background:transparent}"
"QToolButton:hover{border-radius:5px;border:1px solid rgb(210, 225, 230)}")
self.desktop_button = QToolButton()
self.desktop_button.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
desktop_pixmap = QPixmap ("./images/contentWidget/desktop.png")
self.desktop_button.setIcon(QIcon(desktop_pixmap))
self.desktop_button.setIconSize(desktop_pixmap.size())
self.desktop_button.setFixedSize(desktop_pixmap.width() + 50, desktop_pixmap.height() + 35)
self.desktop_button.setStyleSheet("QToolButton{background:transparent}"
"QToolButton:hover{border-radius:5px;border:1px solid rgb(210, 225, 230)}")
self.net_repair_button = QToolButton()
self.net_repair_button.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
net_repair_pixmap = QPixmap ("./images/contentWidget/net_repair.png")
self.net_repair_button.setIcon(QIcon(net_repair_pixmap))
self.net_repair_button.setIconSize(net_repair_pixmap.size())
self.net_repair_button.setFixedSize(net_repair_pixmap.width() + 50, net_repair_pixmap.height() + 35)
self.net_repair_button.setStyleSheet("QToolButton{background:transparent}"
"QToolButton:hover{border-radius:5px;border:1px solid rgb(210, 225, 230)}")
self.auto_run_button = QToolButton()
self.auto_run_button.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
auto_run_pixmap = QPixmap ("./images/contentWidget/auto_run.png")
self.auto_run_button.setIcon(QIcon(auto_run_pixmap))
self.auto_run_button.setIconSize(auto_run_pixmap.size())
self.auto_run_button.setFixedSize(auto_run_pixmap.width() + 50, auto_run_pixmap.height() + 35)
self.auto_run_button.setStyleSheet("QToolButton{background:transparent}"
"QToolButton:hover{border-radius:5px;border:1px solid rgb(210, 225, 230)}")
self.net_speed_button = QToolButton()
self.net_speed_button.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
net_speed_pixmap = QPixmap ("./images/contentWidget/net_speed.png")
self.net_speed_button.setIcon(QIcon(net_speed_pixmap))
self.net_speed_button.setIconSize(net_speed_pixmap.size())
self.net_speed_button.setFixedSize(net_speed_pixmap.width() + 50, net_speed_pixmap.height() + 35)
self.net_speed_button.setStyleSheet("QToolButton{background:transparent}"
"QToolButton:hover{border-radius:5px;border:1px solid rgb(210, 225, 230)}")
self.net_pretext_button = QToolButton()
self.net_pretext_button.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
net_pretext_pixmap = QPixmap ("./images/contentWidget/net_pretext.png")
self.net_pretext_button.setIcon(QIcon(net_pretext_pixmap))
self.net_pretext_button.setIconSize(net_pretext_pixmap.size())
self.net_pretext_button.setFixedSize(net_pretext_pixmap.width() + 50, net_pretext_pixmap.height() + 35)
self.net_pretext_button.setStyleSheet("QToolButton{background:transparent}"
"QToolButton:hover{border-radius:5px;border:1px solid rgb(210, 225, 230)}")
self.first_add_button = QToolButton()
self.first_add_button.setToolButtonStyle(Qt.ToolButtonTextUnderIcon)
first_add_pixmap = QPixmap ("./images/contentWidget/first_add.png")
self.first_add_button.setIcon(QIcon(first_add_pixmap))
self.first_add_button.setIconSize(first_add_pixmap.size())
self.first_add_button.setFixedSize(first_add_pixmap.width() + 50, first_add_pixmap.height() + 35)
self.first_add_button.setStyleSheet("QToolButton{background:transparent}"
"QToolButton:hover{border-radius:5px;border:1px solid rgb(210, 225, 230)}")
grid_layout = QGridLayout()
grid_layout.addWidget(self.recovery_button, 0, 0)
grid_layout.addWidget(self.mobile_button, 0, 1)
grid_layout.addWidget(self.game_box_button, 0, 2)
grid_layout.addWidget(self.desktop_button, 1, 0)
grid_layout.addWidget(self.net_repair_button, 1, 1)
grid_layout.addWidget(self.auto_run_button, 1, 2)
grid_layout.addWidget(self.net_speed_button, 3, 0)
grid_layout.addWidget(self.net_pretext_button, 3, 1)
grid_layout.addWidget(self.first_add_button, 3, 2)
grid_layout.setSpacing(0)
grid_layout.setContentsMargins(5, 0, 5, 5)
v_layout = QVBoxLayout()
v_layout.addLayout(h_layout)
v_layout.addLayout(grid_layout)
v_layout.addStretch()
v_layout.setSpacing(10)
v_layout.setContentsMargins(0, 0, 0, 0)
self.right_center_function_widget.setLayout(v_layout)
def initRightBottom(self):
self.right_bottom_widget = QWidget()
icon_label = QLabel()
self.connect_label = QLabel()
self.version_label = QLabel()
version_button = QPushButton()
label_pixmap = QPixmap ("./images/contentWidget/cloud.png")
icon_label.setPixmap(label_pixmap)
icon_label.setFixedSize(label_pixmap.size())
pixmap = QPixmap ("./images/contentWidget/version.png")
version_button.setIcon(QIcon(pixmap))
version_button.setIconSize(pixmap.size())
version_button.setFixedSize(20, 20)
version_button.setStyleSheet("background:transparent")
bottom_layout = QHBoxLayout()
bottom_layout.addWidget(icon_label)
bottom_layout.addWidget(self.connect_label)
bottom_layout.addStretch()
bottom_layout.addWidget(self.version_label)
bottom_layout.addWidget(version_button)
bottom_layout.setSpacing(5)
bottom_layout.setContentsMargins(10, 0, 10, 0)
self.right_bottom_widget.setLayout(bottom_layout)
def translateLanguage(self):
self.suggest_label.setText(u"suggest")
self.system_safe_label.setText(u"system safe")
self.power_button.setText(u"power")
self.login_button.setText(u"login home")
self.info_label.setText(u"show beautifull icon")
self.register_button.setText(u"register")
self.privilege_label.setText(u"privilege power")
self.fireproof_button.setText(u"fireproof")
self.triggerman_button.setText(u"triggerman")
self.net_shop_button.setText(u"net shop")
self.function_label.setText(u"function")
self.more_button.setText(u"more")
self.recovery_button.setText(u"recovery")
self.mobile_button.setText(u"mobile")
self.game_box_button.setText(u"game box")
self.desktop_button.setText(u"desktop")
self.net_repair_button.setText(u"net repair")
self.auto_run_button.setText(u"auto run")
self.net_speed_button.setText(u"net speed")
self.net_pretext_button.setText(u"net pretext")
self.first_add_button.setText(u"first add")
self.connect_label.setText(u"connect success")
self.version_label.setText(u"version")
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
content = ContentWidget()
content.show()
sys.exit(app.exec_())
|
#!/usr/bin/env python3
import db
from flask import Flask, abort
from misaka import html
app = Flask(__name__)
app.config.update(
SECRET_KEY = 'keyval',
DEBUG = True
)
@app.route('/')
def index():
with open('README.md') as readme: return html(readme.read())
@app.route('/<key>/')
@app.route('/<key>/<value>/')
def getvalue(key, value=None):
existing = db.Value.getbykey(key)
if value is None:
if existing: return existing.value
abort(404)
else:
if not existing: return db.Value(key, value).value
existing.value = value
db.session.commit()
return value
if __name__ == '__main__':
from sys import argv
try: app.run(host='0.0.0.0', port=int(argv[1]))
except: app.run(host='0.0.0.0')
|
import numpy as np
import matplotlib.pyplot as plt
from scipy.stats import beta
NUM_TRIALS = 2000
BANDIT_PROBABILITIES = [0.2, 0.5, 0.6]
class Bandit:
def __init__(self, p):
self.p = p
self.a = 1
self.b = 1
def pull(self):
return np.random.random() < self.p
def sample(self):
beta_sample = np.random.beta(self.a, self.b)
print("Beta sample for bandit {0}: {1}".format(self.p, beta_sample))
return beta_sample
def update(self, x):
"""
x must be either 0 or 1
"""
self.a += x
print("a parameter for bandit {0} updated to {1}".format(self.p, self.a))
self.b += 1 -x
print("a parameter for bandit {0} updated to {1}".format(self.p, self.b))
def plot(bandits, trial):
x = np.linspace(0,1,200)
for b in bandits:
y = beta.pdf(x, b.a, b.b)
plt.plot(x, y, label = "Real p: {0}".format(b.p))
plt.title("Bandit distributions after {0}".format(trial))
plt.legend()
plt.show()
def experiment():
bandits = [Bandit(p) for p in BANDIT_PROBABILITIES]
sample_points = [5, 10, 20, 50, 100, 500, 1000, 1999]
for i in range(NUM_TRIALS):
best_bandit = None # indicator for the best bandit machine
maxsample = -1
allsamples = []
for bandit in bandits:
sample = bandit.sample()
allsamples.append(sample)
if sample > maxsample:
best_bandit = bandit
maxsample = sample
if i in sample_points:
print("Current samples: {0}".format(allsamples))
plot(bandits, i)
print("The best current bandit is {0}".format(best_bandit.p))
x = best_bandit.pull()
best_bandit.update(x)
if __name__ == '__main__':
experiment()
|
import gl, conc
class Rule:
def __init__(self,actualconcept): # an instance represents a single rule to apply for the actual concept
self.actual = actualconcept # index of concept in WM for which we found a rule
self.rule = -1 # index of rule in KB, an IM(g,k) concept
self.condition = [] # indices (in KB) of a,b,c in IM(Z(a,b),k) . here c=Z(a,b)
self.match=[] # indices of m,n,q in WM, where m matches a, n matches b etc
self.matchrelation=-2 # if for example b=X(%2,%3) and n matches b, then we store the relation found in m
self.matchvalue = [] # %1 %2 %3 matching concepts
self.matchp = [] # p1 p2 etc matching p values
|
import json
import pytest
from freezegun import freeze_time
from datetime import datetime, timedelta
from models.users import PasswordRecoveryToken
@freeze_time("2019-09-28 13:48:00")
def test_multiple_user(multiple_users, testing_app):
r = testing_app.get('/api/admin/users')
assert r.status_code == 200
assert r.json == [
{
'id': 1,
'name': 'John',
'surname': 'Doe',
'email': 'jdoe@gmail.com',
'password': 'insecure',
'phone': '4444-5555',
'subscription': 'flat',
'role': 'user',
'photo_url': None,
'creation_date': '2019-09-28T13:48:00',
'status': 'active',
'active': True,
'favor_balance': 0,
'cash_balance': 0,
'reputation': None,
},
{
'id': 2,
'name': 'Jane',
'surname': 'Doe',
'email': 'janedoe@gmail.com',
'password': 'insecure',
'phone': '4444-5555',
'subscription': 'flat',
'role': 'user',
'photo_url': None,
'creation_date': '2019-09-28T13:48:00',
'status': 'active',
'active': True,
'favor_balance': 0,
'cash_balance': 0,
'reputation': None,
}
]
@freeze_time("2019-09-28 13:48:00")
def test_single_user(multiple_users, testing_app):
r = testing_app.get('/api/admin/users/1')
assert r.status_code == 200
assert r.json == {
'id': 1,
'name': 'John',
'surname': 'Doe',
'email': 'jdoe@gmail.com',
'password': 'insecure',
'phone': '4444-5555',
'subscription': 'flat',
'role': 'user',
'photo_url': None,
'creation_date': '2019-09-28T13:48:00',
'status': 'active',
'active': True,
'favor_balance': 0,
'cash_balance': 0,
'reputation': None,
}
def test_single_nonexistent_user(multiple_users, testing_app):
r = testing_app.get('/api/admin/users/999')
assert r.status_code == 404
assert r.json == 'User with id 999 was not found'
def test_no_user(db_session, testing_app):
r = testing_app.get('/api/admin/users')
assert r.status_code == 200
assert r.json == []
@freeze_time("2019-09-28 13:48:00")
def test_new_user(db_session, testing_app):
"""
Tests the creation of a new user through the API and the server's response
"""
# Setup
json_body = {
'name': 'Juancito',
'surname': 'Lopez',
'email': 'juancito@gmail.com',
'password': 'insecure',
'phone': '4781-6140'
}
r = testing_app.post(
'/api/new_user',
data=json.dumps(json_body),
content_type='application/json'
)
assert r.status_code == 201
assert r.json == {
'id': 1,
'name': 'Juancito',
'surname': 'Lopez',
'email': 'juancito@gmail.com',
'password': 'insecure',
'phone': '4781-6140',
'subscription': 'flat',
'role': 'user',
'photo_url': None,
'creation_date': '2019-09-28T13:48:00',
'status': 'active',
'active': True,
'cash_balance': 0,
'favor_balance': 0,
'reputation': None,
}
def test_user_existing_email(one_user, testing_app):
json_body = {
'name': 'Single',
'surname': 'User',
'email': 'suser@gmail.com',
'password': 'insecure',
'phone': '4444-5555'
}
r = testing_app.post(
'/api/new_user',
data=json.dumps(json_body),
content_type='application/json'
)
assert r.status_code == 400
assert r.json == {'email': ['Email already exists']}
def test_login_existing_user(mocker, one_user, testing_app):
mocker.patch('models.users.random_string', return_value='abcdedcba')
json_body = {
'email': 'suser@gmail.com',
'password': 'insecure'
}
r = testing_app.post(
'/api/login',
data=json.dumps(json_body),
)
assert r.status_code == 200
assert r.json == {'token': f'{one_user.id}.abcdedcba'}
# Secuential calls should return the same
r = testing_app.post(
'/api/login',
data=json.dumps(json_body),
)
assert r.status_code == 200
assert r.json == {'token': f'{one_user.id}.abcdedcba'}
def test_login_nonexistent_user(db_session, testing_app):
json_body = {
'email': 'nobody@gmail.com',
'password': 'asdqwer'
}
r = testing_app.post(
'/api/login',
data=json.dumps(json_body),
)
assert r.status_code == 404
assert r.json == 'User not found'
def test_login_wrong_password(one_user, testing_app):
json_body = {
'email': 'suser@gmail.com',
'password': 'thisisnotthepassword'
}
r = testing_app.post(
'/api/login',
data=json.dumps(json_body),
)
assert r.status_code == 401
assert r.json == 'Wrong Password'
@pytest.mark.parametrize('missing', ('email', 'password'))
def test_login_missing_field(missing, testing_app):
json_body = {
'email': 'suser@gmail.com',
'password': 'thisisnotthepassword'
}
json_body.pop(missing)
r = testing_app.post(
'/api/login',
data=json.dumps(json_body),
)
assert r.status_code == 400
assert r.json == {missing: ['Missing data for required field.']}
@freeze_time("2019-09-28 13:48:12")
def test_forgot_password(mocker, one_user, testing_app):
send_mail = mocker.patch('api.auth.send_token_to_mail')
mocker.patch('models.users.random_string', return_value="abcdDCBA")
json_body = {
'email': 'suser@gmail.com',
}
r = testing_app.post(
'/api/forgot_password',
data=json.dumps(json_body),
)
assert r.status_code == 200
send_mail.assert_called_once_with('abcdDCBA',
one_user.email,
datetime.utcnow()+timedelta(days=1))
@pytest.mark.parametrize("email", (None, 'foo@gmail.com', 'sarasa'))
def test_forgot_password_error(one_user, testing_app, email):
"""
Tests for errors in the Forgot Password API
- Missing email field
- Non-existent mail
- invalid mail format
"""
json_body = {}
if email:
json_body['email'] = email
r = testing_app.post(
'/api/forgot_password',
data=json.dumps(json_body),
)
assert r.status_code == 400
def test_reset_password(one_user, testing_app):
token = PasswordRecoveryToken.generate_token(one_user.id)
new_password = '123456'
assert one_user.password != new_password
assert token.valid is True
json_body = {
'email': one_user.email,
'token': token.token,
'password': new_password,
'confirm_password': new_password
}
r = testing_app.post(
'/api/reset_password',
data=json.dumps(json_body),
)
assert r.status_code == 200
assert r.json == 'Password Changed'
assert token.valid is False # Token Cannot be reused
assert one_user.password == new_password # User password changed
|
'''
File which handles the parsing of strings into syntax trees
'''
from syntax import *
from state import *
import re
from robot import Robot
def matchParen(s,i):
l=s[i]
if l=='(':
r=")"
elif l=="{":
r="}"
elif l=="[":
r="]"
elif l=="<":
r=">"
else:
raise Exception()
cnt=0
for j in range(i,len(s)):
if s[j]==l:
cnt+=1
elif s[j]==r:
cnt-=1
if cnt==0:
return j
return None
def findTopLevel(s):
'''
Takes in a string and finds the top level syntax token along with arguments
Returns: operator*string list
'''
ops_list = ['?', ':=', ';', '++']
s = s.strip()
# If {} surround the entire string, strip and recurse
if(s[0] == '{' and matchParen(s, 0) == len(s) - 1):
return findTopLevel(s[1:-1])
# If {}* surround the entire string, return loop
if(s[0] == '{' and matchParen(s, 0) == len(s) - 2 and s[-1] == "*"):
return (Loop, [s[1:-2]])
top_op = None
top_op_idx = None
i = 0
while(i < len(s)):
if(s[i] == '{'):
# Skip to matching paren
j = matchParen(s,i)
if j is None:
raise Exception('Unmatched left bracket in HP')
i = j + 1
continue
elif (s[i] == "\'"):
# Found ', entire string is ODE
return(ODE, [s])
elif (s[i] in ops_list):
if top_op is None or ops_list.index(s[i]) > ops_list.index(top_op):
# Replace if binds looser
top_op = s[i]
top_op_idx = i
i = i + 1
elif (s[i:i+2] in ops_list):
if top_op is None or ops_list.index(s[i:i+2]) > ops_list.index(top_op):
# Replace if binds looser
top_op = s[i:i+2]
top_op_idx = i
i = i + 2
else:
i = i + 1
if(top_op is None):
return (None, s)
op_class = None
if(top_op == ':='):
op_class = Assign
elif (top_op == '++'):
op_class = Choice
elif (top_op == ';'):
op_class = Compose
elif (top_op == '?'):
return (Test, [s[1:]])
# Split up the string by top_op location
return (op_class, [s[:top_op_idx], s[top_op_idx+len(top_op):]])
def isExp(s):
'''
Returns true if the string is a well-formed expression
'''
#checks that there are no =,<,>,!,++,{,}
prohibited=["=","<",">","!","++","{","}",";","true","false"]
for p in prohibited:
if p in s:return False
return True
def isQEForm(s):
'''
Returns true if the string is a formula with no further decomposition needed
to determine truth value
'''
prohibited=["?",":=",";","++","}","{"]
for p in prohibited:
if p in s:return False
return not isExp(s)
def parseHP(s):
'''
Takes a string representing a hybrid program and returns a syntax tree
by recursively constructing it
'''
if isExp(s):
return Term(s)
if isQEForm(s):
return Form(s)
obj,args=findTopLevel(s)
if obj==ODE:return ODE(args[0])
argobjs=[parseHP(a) for a in args]
return obj(*argobjs)
def sanitize(s):
'''
Replaces all the weird KX syntax with python syntax
'''
replaces = {"&":" and ","|":" or ","^":"**","!":"not "}
for k in replaces:
s=s.replace(k,replaces[k])
return s
def firstInt(s):
for i in range(len(s)):
if s[i].isdigit():return i
return -1
def parse(s):
'''
Takes in an entire Keymaera program and parses the variables, constants,
program, and pre/post conditions
returns: State * Form * Form * HP * robot list
(state, precons, postcons, HP syntax tree, list of Robot objects)
'''
#do some sanitation
if s.find("!=")>=0:
raise Exception("Can't have the symbol '!=' in the program")
findend = lambda st,w: st.find(w)+len(w)#convenience
s=sanitize(s)
#0. remove comments
s = re.sub(r'\/\*.+?\*\/','', s)
#1. parse the variables out
assert(s.find("ProgramVariables")>=0 or s.find("Definitions")>=0)
defs=s[findend(s,'Definitions'):]
defs=defs[:defs.find('End.')].strip()
variables = s[findend(s,'ProgramVariables'):]
variables = variables[:variables.find("End.")].strip()
state=State()
robot_dicts={}#maps from id->dict
for line in defs.splitlines()+variables.splitlines():
if 'Real' not in line:continue
assignment = line[findend(line,'Real '):line.find(';')]
if ":" in assignment:
#parse out the type, and delete it to be unchanged for the following lines
typeend=assignment.find("=") if "=" in assignment else len(assignment)
typ = assignment[findend(assignment,":"):typeend].strip()
#update the dicts
rob_id=int(typ[firstInt(typ):])
var_name=typ[:firstInt(typ)]
if rob_id not in robot_dicts:
d=dict()
robot_dicts[rob_id]=d
else:
d=robot_dicts[rob_id]
d[var_name]=assignment[:assignment.find(":")]
assignment=assignment[:assignment.find(":")]+assignment[typeend:]
if '=' in assignment:
val = float(assignment[findend(assignment,'='):].strip())
state.addVar(assignment[:assignment.find('=')].strip(),val)
else:
state.addVar(assignment.strip())
robot_list=[Robot(robot_dicts[k],k) for k in robot_dicts]
#2. isolate the program section
progsec = s[findend(s,'Problem'):]
progsec = progsec[:progsec.find("End.")].strip()
#3. find precon and postcon
precon = progsec[findend(progsec,'('):matchParen(progsec,progsec.find("("))]
progsec= progsec[findend(progsec,"->"):].strip()
hpstring = progsec[1:matchParen(progsec,0)]
# print("precon: ",precon)
print("HP: ",hpstring)
postcon=progsec[matchParen(progsec,0)+1:].strip()
# print("postcon: ",postcon)
# print("state:",state.vars())
#4. parse HP inside box or diamond
tree = parseHP(hpstring)
return state,Form(precon),Form(postcon),tree,robot_list
if __name__=="__main__":
testprog=\
'''
ArchiveEntry "testprog"
Definitions
Real A = 2;
Real kp;
Real kd;
Real T;
End.
ProgramVariables
Real a;
Real v;
Real x;
Real t;
Real vThresh;
Real xThresh;
End.
Problem
( kp > 0 & kd > 0 ) ->
[{t:=0;{v' = kp * -1 * x, x'= v, t'=1 & t<T}}*]
(v < vThresh & x < xThresh)
End.
End.
'''
lab1=\
'''
ProgramVariables
Real pos;
Real vel;
Real acc;
Real station;
End.
Problem
(pos < station & vel > 0 )
->
[
acc := (-vel*vel)/(2*(station-pos));
{pos' = vel, vel' = acc & vel >= 0}
](
(pos<=station & (pos=station -> vel=0))
& (!(pos<station&vel=0))
)
End.
'''
lab1_3=\
lab3=\
'''
Definitions
Real A; /* Robot's maximum acceleration*/
Real B; /* Robot's maximum braking */
End.
ProgramVariables
Real x; /* Position of robot in x direction */
Real y; /* Position of robot in y direction */
Real dx; /* Unit vector in direction of travel, x direction */
Real dy; /* Unit vector in direction of travel, y direction */
Real trackr; /* Robot track radius */
Real cx; /* center of track x*/
Real cy; /* center of track y*/
Real v; /* Linear velocity of robot */
Real a; /* Linear acceleration of robot */
End.
Problem
((cx-x)^2+(cy-y)^2=trackr^2 & dx^2+dy^2=1)
->
[
{
/* Control steering using trackr */
{trackr:=*;?trackr!=0;cx:=x-dy*trackr;cy:=y+dx*trackr};
/* Control acceleration (a) */
{a:=*;?a>-B&a<A};
{v'=a,x'=dx*v,y'=dy*v,dx'=-v*dy/trackr,dy'=v*dx/trackr /* differential equations for this system. Make sure everything that changes continuously is included. */
& v >= 0
}
}*
]((cx-x)^2+(cy-y)^2=trackr^2) /* Safety condition. */
End.
End.
'''
lab3=\
'''
Definitions
Real r; /* Racetrack radius */
Real T; /* Maximal time interval between consecutive triggerings of the controller */
Real A; /* The robot accelerates with acceleration A */
Real B; /* The robot brakes with acceleration -B */
Real ox; /* Cartesian coordinate x of the obstacle */
Real oy; /* Cartesian coordinate y of the obstacle */
/* Optional: function/predicate definitions, with explanatory comment. */
/*
*/
End.
ProgramVariables
Real t; /* Elapsed time since the last controller triggering */
Real x; /* Cartesian coordinate x of the robot */
Real y; /* Cartesian coordinate y of the robot */
Real v; /* Linear velocity (ground speed) of the robot */
Real a; /* Linear acceleration of the robot */
End.
Problem
(
/* Constant assumptions and initial conditions */
(T > 0 & A > 0 & B > 0 & r > 0 & ox = -r & oy = 0) & v >= 0 &
0.5*v^2/B < (x-ox)
& x^2 + y^2 = r^2
)
->
[
{
/* Robot controller */
{
{
?(
/* When is it safe to accelerate? */
y>=0 & 0.5*(v+A*T)^2/B + 0.5*A*T^2 + v*T < (x-ox)
);
a := A
} ++ { a := -B }
};
/* Continuous dynamic */
t:=0;
{ x'=-v*y/r, y'=v*x/r, v'=a, t'=1 & v >= 0 & t <= T }
}*
]
/* Safety condition: the robot stays on the track and never hits the obstacle */
(x^2+y^2=r^2 & !(x=ox & y=ox))
End.
'''
lab4_1=\
'''
Definitions
Real A; /* Robot's maximum acceleration*/
Real B; /* Robot's maximum braking */
End.
ProgramVariables
Real x; /* Position of robot in x direction */
Real y; /* Position of robot in y direction */
Real dx; /* Unit vector in direction of travel, x direction */
Real dy; /* Unit vector in direction of travel, y direction */
Real trackr; /* Robot track radius */
Real cx; /* center of track x*/
Real cy; /* center of track y*/
Real v; /* Linear velocity of robot */
Real a; /* Linear acceleration of robot */
End.
Problem
((cx-x)^2+(cy-y)^2=trackr^2 & dx^2+dy^2=1)
->
[
{
/* Control steering using trackr */
{trackr:=*;?trackr!=0;cx:=x-dy*trackr;cy:=y+dx*trackr};
/* Control acceleration (a) */
{a:=*;?a>-B&a<A};
{v'=a,x'=dx*v,y'=dy*v,dx'=-v*dy/trackr,dy'=v*dx/trackr /* differential equations for this system. Make sure everything that changes continuously is included. */
& v >= 0
}
}*
]((cx-x)^2+(cy-y)^2=trackr^2) /* Safety condition. */
End.
End.
'''
parsetest=\
'''
ProgramVariables
Real x:x0 = 1; /* Position of robot in x direction */
Real y:y0=1;
End.
Problem
(true)-> [{{x'=1 & x<.5};?x<10}++{x:=2}]x>1
End.
'''
state,precon,postcon,tree,robots=parse(parsetest)
# print(state.vars)
# print(precon.arg)
# print(postcon.arg)
print("Tree:")
tree.print()
print("Traces:")
traces=tree.expand(state)
for choices,end_state in traces:
print("Choices:",choices)
print("End state",end_state.vars())
print()
s =Sim(parsetest)
|
from scrapy.spider import BaseSpider
from apple.items import AppleItem
from scrapy.selector import HtmlXPathSelector
import re
class DmozSpider(BaseSpider):
name = "dmoz"
allowed_domains = ["apple.com"]
start_urls = [
"http://store.apple.com/sg/browse/home/specialdeals/mac"#,
#"http://store.apple.com/sg/browse/home/specialdeals/mac"
]
def parse(self, response):
hxs = HtmlXPathSelector(response)
sites = hxs.select('//td[contains(@class,"specs")]/text()').extract()
items = []
for site in sites:
#print site
item = AppleItem()
s = re.sub(r"\W", "", site.encode("utf8"))
if not "2013" in s:
continue
else:
item['date'] = s
item['price'] = site.encode("utf8")
items.append(item)
return items |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# ˅
from behavioral_patterns.template_method.abstract_display import AbstractDisplay
# ˄
class StringDisplay(AbstractDisplay):
# ˅
# ˄
def __init__(self, string):
self.__string = string
# String width
self.__width = len(string)
# ˅
pass
# ˄
def open(self):
# ˅
self.__write_line() # Write a line
# ˄
def write(self):
# ˅
print(f'|{self.__string}|') # Display the character with "|"
# ˄
def close(self):
# ˅
self.__write_line() # Write a line
# ˄
def __write_line(self):
# ˅
print('+', end='') # Display an end mark "+"
print('-' * self.__width, end='') # Display a line "-"
print('+') # Display an end mark "+"
# ˄
# ˅
# ˄
# ˅
# ˄
|
N = int(input())
*S, = list(input())
A = [chr(i) for i in range(97, 97+26)]
K = 0
for L in range(1,N):
cnt = 0
for alpha in A:
if alpha in S[:L] and alpha in S[L:]:
cnt += 1
K = max(K,cnt)
print(K)
|
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
t=int(input())
for i in range(t):
n=int(input())
s=input()
x="2020"
ans=[0]*4
a=0
b=n-1
for p in range(4):
if s[p]==x[p]:
ans[p]=1
else:
break
for p in range(4):
if s[b]==x[3-p]:
ans[3-p]=1
else:
break
b-=1
print("YES" if sum(ans)==4 else "NO")
|
#import sys
#input = sys.stdin.readline
# from bisect import bisect_left
def main():
K = int(input())
ans = 0
A = [i**2 for i in range(10**3)]
for i in range(1, K+1):
L = K//i
for j in range(1,L+1):
ans += L//j
print(ans)
if __name__ == '__main__':
main()
|
from flask import Flask, render_template, request
import os.path
import json
import requests
from pyGTrends import pyGTrends
app = Flask(__name__)
global connection
global counter
global popList
connection = None
counter = 0
popList = None
@app.route("/", methods=['GET', 'POST'])
def index():
global connection
global popList
popList = popularList()
if request.method == "GET":
if connection == None:
return render_template("index.html", logged=False)
else:
return render_template("index.html", logged=True, popular=popList)
else:
google_username = request.form['username']
google_password = request.form['password']
try:
connection = pyGTrends(google_username, google_password)
except:
return render_template("index.html", err="Incorrect Username or Password", logged=False)
return render_template("index.html", logged=True, popular=popList)
return render_template("index.html", logged=False)
@app.route("/search", methods=['GET'])
def search():
if request.method == "GET":
term = request.args.get('search')
data = trend(term)
results = parseTrend(data)
return json.dumps(results)
@app.route("/popular")
def popular():
global counter
global popList
if counter >= 20:
counter = 0
data = trend(popList[counter].encode("utf-8"))
print(popList[counter].encode("utf-8"))
counter += 1
r = parseTrend(data)
return json.dumps(r)
def trend(term):
path = "data/" + (term.decode("utf-8")).encode("ascii", "ignore") + ".csv"
if not (os.path.isfile(path)):
connection.request_report(term, hl='en-US', cat=None, geo=None, date=None)
connection.save_csv("data/", (term.decode("utf-8")).encode("ascii", "ignore"))
with open(path, "r") as f:
data = (f.read()).split("\n")
return data
def popularList():
results = requests.get("http://hawttrends.appspot.com/api/terms/")
r = results.json()
return r["42"]
def parseTrend(data):
results = []
yearNums = []
year = "2004"
if data[4].split(",")[0] == "Month":
for x in range(5, len(data)):
if data[x] == "":
if yearNums != []:
results.append(sum(yearNums) / float(len(yearNums)))
return results
else:
dates = data[x].split("-")
if dates[0] != year:
year = dates[0]
results.append(sum(yearNums) / float(len(yearNums)))
yearNums = []
else:
yearNums.append(int((dates[1].split(","))[1]))
else:
for x in range(5, len(data)):
if data[x] == "":
if yearNums != []:
results.append(sum(yearNums) / float(len(yearNums)))
return results
else:
chars = data[x].split(" ")
dates = chars[2].split("-")
if dates[0] != year:
year = dates[0]
results.append(sum(yearNums) / float(len(yearNums)))
yearNums = []
else:
yearNums.append(int((dates[2].split(","))[1]))
return results
if __name__ == "__main__":
app.debug = True
app.run(host="0.0.0.0", port=8000)
|
from interface import admin_interface
def frozen():
while True:
frozen_user = input('请输入要冻结的用户名:')
flag,msg = admin_interface.frozen_interface(
frozen_user
)
if flag:
print(msg)
break
else:
print(msg)
continue
def change_balance():
while True:
change_bal_user = input('请输入要修改余额的用户名:')
change_money = input('请输入要修改的金额:')
flag,msg = admin_interface.change_bal_interface(
change_bal_user,change_money
)
if flag:
print(msg)
break
else:
print(msg)
continue
def relieve():
while True:
relieve_user = input('请输入要解冻的用户名:')
flag, msg = admin_interface.relieve_interface(
relieve_user
)
if flag:
print(msg)
break
else:
print(msg)
continue
tab_dic ={
"0":0,
"1":frozen,
"2":change_balance,
"3":relieve,
}
def run():
while True:
print(
'''
=====欢迎进入管理员功能=====
0、退出
1、冻结功能
2、修改余额功能
3、解冻功能
=====欢迎进入管理员功能=====
'''
)
count = input("请输入要进行的操作编号:")
if count in tab_dic:
if count != "0" :
tab_dic[count]()
else:
exit("退出成功,欢迎下次继续使用")
else:
print("请重新输入编号")
continue |
"""
Module for holding constants (and some variables with "fixed" values) used
all over the program.
"""
import os.path
import glib
from constant_constants import *
# Path of the program (bad assumption)
TV_PATH = "/usr/bin/tunesviewer"
TV_VERSION = "1.5" #also needs changing in debian conf file somewhere
# Directory under which we write configuration files
USER_PREFS_DIR = glib.get_user_config_dir()
PREFS_DIR = os.path.join(USER_PREFS_DIR, "tunesviewer")
PREFS_FILE = os.path.join(PREFS_DIR, "tunesviewer.conf")
# Directory under which we write state data
USER_DATA_DIR = glib.get_user_data_dir()
DATA_DIR = os.path.join(USER_DATA_DIR, "tunesviewer")
DATA_FILE = os.path.join(DATA_DIR, "state") # Holds current downloads, in case of crash, resumes.
DATA_SOCKET = os.path.join(DATA_DIR, "tunesviewerLOCK") # Holds socket, so second app calls first instance with url.
# Directory under which we write downloaded files
DOWNLOADS_DIR = os.path.expanduser("~")
# connection programs
DEFAULT_OPENER = "vlc --http-user-agent=%s --http-caching=10000" % (USER_AGENT, )
|
from app.database.cache import get_from_cache, add_to_cache
from app.database.database import execute_query
def get_teen_pregnancy_by_state(year):
query = get_query(year)
data = get_from_cache(query)
print("DB Query: " + query)
if data is None:
data = execute_query(query)
add_to_cache(query, data)
return data
def get_query(year):
return f'''
SELECT *
FROM BirthsPerYearAndState
WHERE "year" = '{year}'
'''
|
#!/usr/bin/python
# Copyright 2010 Google Inc.
# Licensed under the Apache License, Version 2.0
# http://www.apache.org/licenses/LICENSE-2.0
# Google's Python Class
# http://code.google.com/edu/languages/google-python-class/
import sys
import re
import os
import shutil
import commands
from os import listdir
from os.path import isdir, isfile, join
import zipfile
"""Copy Special exercise
"""
# +++your code here+++
# Write functions and modify main() to call them
def get_special_files(theDir):
""" finds and returns a list of all files in the given dir with
the pattern __w__ in the filename
"""
if(os.path.isdir(theDir)):
filesInDir = [f for f in listdir(theDir) if isfile(join(theDir, f))]
specialFiles = []
for aFile in filesInDir:
match = re.match(r'.*\_\_\w+\_\_.*\.\w+', aFile)
if(match):
specialFiles.append(match.group(0))
return specialFiles
else:
return False
def to_dir(theFilePath, path):
""" check if the path exists and make if it's not there
then copy the file to the path
"""
if(not os.path.isdir(path)):
os.makedirs(path)
shutil.copy(theFilePath,path)
def to_zip(theFileList, zipFileToMake):
""" takes the files listed in theFileList (must be full path)
and adds them to the zipFileToMake
"""
if ".zip" not in zipFileToMake:
zipFileToMake += ".zip"
zf = zipfile.ZipFile(zipFileToMake, "w")
for filename in theFileList:
print 'zipping %s into %s' % (filename,zipFileToMake)
zf.write(filename, os.path.relpath(filename))
zf.close()
def main():
# This basic command line argument parsing code is provided.
# Add code to call your functions below.
# Make a list of command line arguments, omitting the [0] element
# which is the script itself.
args = sys.argv[1:]
if not args:
print "usage: [--todir dir][--tozip zipfile] dir [dir ...]"
sys.exit(1)
# todir and tozip are either set from command line
# or left as the empty string.
# The args array is left just containing the dirs.
todir = ''
if args[0] == '--todir':
todir = args[1]
del args[0:2]
tozip = ''
if args[0] == '--tozip':
tozip = args[1]
del args[0:2]
if len(args) == 0:
print "error: must specify one or more dirs"
sys.exit(1)
# +++your code here+++
# Call your functions
#collect full paths
fullFilePaths = []
for dirName in args:
specialFilesInDir = get_special_files(dirName)
if specialFilesInDir:
for eachFile in specialFilesInDir:
fullFilePaths.append(os.path.realpath(eachFile))
if todir:
for filePath in fullFilePaths:
to_dir(filePath, todir)
elif tozip:
to_zip(fullFilePaths, tozip)
else:
print fullFilePaths
if __name__ == "__main__":
main()
|
from Login.NewContract import *
from selenium import webdriver
driver = webdriver.Chrome()
# driver.maximize_window()
driver.implicitly_wait(10)
test_user_login(driver)
# test_contract2(driver)
|
import sys
input = sys.stdin.readline
def find(A,x):
p = A[x]
if p == x:
return x
a = find(A,p)
A[x] = a
return a
def union(A, x, y):
if find(A,x) > find(A,y):
bx, by = find(A,y), find(A,x)
else:
bx, by = find(A,x), find(A,y)
A[y] = bx
A[by] = bx
def main():
N, M = map(int,input().split())
A = list(map(int,input().split()))
B = list(map(int,input().split()))
V = [i for i in range(N)]
CD = [ tuple(map(lambda x: int(x)-1, input().split())) for _ in range(M)]
for c, d in CD:
union(V,c,d)
SA = [0]*N
SB = [0]*N
for i in range(N):
SA[find(V,i)] += A[i]
SB[find(V,i)] += B[i]
for i in range(N):
if SA[i] != SB[i]:
print("No")
return
print("Yes")
if __name__ == '__main__':
main()
|
Name:Siddhant Pawar
State:Maharashtra
|
# Generated by Django 2.2.1 on 2019-05-25 23:52
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('web_api', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='eventplaceseattype',
name='seat_type',
),
migrations.AddField(
model_name='eventplaceseattype',
name='name',
field=models.CharField(default='new', max_length=128),
preserve_default=False,
),
migrations.DeleteModel(
name='SeatType',
),
]
|
import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import lr_scheduler
import gc
import os
import math
import time
from tqdm import tqdm
from vdgnn.utils.eval_utils import process_ranks, scores_to_ranks, get_gt_ranks
from vdgnn.utils.metrics import NDCG
class Trainer(object):
def __init__(self, dataloader, dataloader_val, model_args):
self.args = model_args
self.output_dir = model_args.save_path
self.num_epochs = model_args.num_epochs
self.lr = model_args.lr
self.lr_decay_rate = model_args.lr_decay_rate
self.min_lr = model_args.min_lr
self.ckpt = model_args.ckpt
self.use_cuda = model_args.use_cuda
self.log_step = model_args.log_step
self.dataloader = dataloader
self.dataloader_val = dataloader_val
self.model_dir = os.path.join(self.output_dir, 'checkpoints')
def train(self, encoder, decoder):
criterion = nn.CrossEntropyLoss()
running_loss = None
optimizer = optim.Adam(list(encoder.parameters()) + list(decoder.parameters()),
lr=self.lr)
scheduler = lr_scheduler.StepLR(optimizer, step_size=1, gamma=self.lr_decay_rate)
if self.ckpt != None:
components = torch.load(self.ckpt)
print('Loaded checkpoint from: ' + self.ckpt)
encoder.load_state_dict(components['encoder'])
decoder.load_state_dict(components['decoder'])
if self.use_cuda:
encoder = encoder.cuda()
decoder = decoder.cuda()
criterion = criterion.cuda()
for epoch in range(1, self.num_epochs+1):
epoch_time = time.time()
encoder.train()
decoder.train()
iter_time = time.time()
for iter, batch in enumerate(self.dataloader):
optimizer.zero_grad()
for key in batch:
if not isinstance(batch[key], list):
if self.use_cuda:
batch[key] = batch[key].cuda()
batch_size, max_num_rounds = batch['ques'].size()[:2]
enc_output = torch.zeros(batch_size, max_num_rounds, self.args.message_size, requires_grad=True)
if self.use_cuda:
enc_output = enc_output.cuda()
# iterate over dialog rounds
for rnd in range(max_num_rounds):
round_info = {}
round_info['img_feat'] = batch['img_feat']
round_info['ques'] = batch['ques'][:, rnd, :]
round_info['ques_len'] = batch['ques_len'][:, rnd]
round_info['hist'] = batch['hist'][:,:rnd+1, :]
round_info['hist_len'] = batch['hist_len'][:, :rnd+1]
round_info['round'] = rnd
pred_adj_mat, enc_out = encoder(round_info, self.args)
enc_output[:, rnd, :] = enc_out
dec_out = decoder(enc_output.contiguous().view(-1, self.args.message_size), batch)
cur_loss = criterion(dec_out, batch['ans_ind'].view(-1))
cur_loss.backward()
optimizer.step()
gc.collect()
if running_loss is not None:
running_loss = 0.95 * running_loss + 0.05 * cur_loss.data
else:
running_loss = cur_loss.data
if optimizer.param_groups[0]['lr'] > self.min_lr:
scheduler.step()
# --------------------------------------------------------------------
# Logging
# --------------------------------------------------------------------
if (iter+1) % self.log_step == 0:
print("[Epoch: {:3d}][Iter: {:6d}][Loss: {:6f}][lr: {:6f}][Duration: {:6.2f}s]".format(
epoch, iter+1, running_loss, optimizer.param_groups[0]['lr'], time.time() - iter_time))
iter_time = time.time()
print("[Epoch: {:3d}][Loss: {:6f}][lr: {:6f}][Time: {:6.2f}s]".format(
epoch, running_loss, optimizer.param_groups[0]['lr'], time.time() - epoch_time))
# --------------------------------------------------------------------
# Save checkpoints
# --------------------------------------------------------------------
if epoch % 1 == 0:
if not os.path.exists(self.model_dir):
os.makedirs(self.model_dir)
torch.save({
'encoder':encoder.state_dict(),
'decoder':decoder.state_dict(),
'optimizer': optimizer.state_dict(),
'model_args': self.args
}, os.path.join(self.model_dir, 'model_epoch_{:06d}.pth'.format(epoch)))
val_res = self.validate(encoder, decoder, epoch)
torch.save({
'encoder':encoder.state_dict(),
'decoder':decoder.state_dict(),
'optimizer': optimizer.state_dict(),
'model_args': self.args
}, os.path.join(self.model_dir, 'model_epoch_final.pth'))
def validate(self, encoder, decoder, epoch):
print('Evaluating...')
encoder.eval()
decoder.eval()
ndcg = NDCG()
eval_time = time.time()
all_ranks = []
for i, batch in enumerate(tqdm(self.dataloader_val)):
for key in batch:
if not isinstance(batch[key], list):
if self.use_cuda:
batch[key] = batch[key].cuda()
batch_size, max_num_rounds = batch['ques'].size()[:2]
enc_output = torch.zeros(batch_size, max_num_rounds, self.args.message_size, requires_grad=True)
if self.use_cuda:
enc_output = enc_output.cuda()
# iterate over dialog rounds
with torch.no_grad():
for rnd in range(max_num_rounds):
round_info = {}
round_info['img_feat'] = batch['img_feat']
round_info['ques'] = batch['ques'][:, rnd, :]
round_info['ques_len'] = batch['ques_len'][:, rnd]
round_info['hist'] = batch['hist'][:,:rnd+1, :]
round_info['hist_len'] = batch['hist_len'][:, :rnd+1]
round_info['round'] = rnd
pred_adj_mat, enc_out = encoder(round_info, self.args)
enc_output[:, rnd, :] = enc_out
dec_out = decoder(enc_output.contiguous().view(-1, self.args.message_size), batch)
ranks = scores_to_ranks(dec_out.data)
gt_ranks = get_gt_ranks(ranks, batch['ans_ind'].data)
all_ranks.append(gt_ranks)
if 'gt_relevance' in batch:
num_opts = dec_out.size(1)
output = dec_out.view(batch_size, max_num_rounds, num_opts)
output = output[torch.arange(batch_size), batch['round_id']-1, :]
ndcg.observe(output, batch['gt_relevance'])
all_ranks = torch.cat(all_ranks, 0)
eval_res = process_ranks(all_ranks)
eval_res['ndcg'] = ndcg.retrieve(reset=True)
print("[Epoch: {:3d}][R@1: {:6f}][R@5: {:6f}][R@10: {:6f}][MR: {:6f}][MRR: {:6f}][NDCG: {:6f}][Time: {:6.2f}s]".format(epoch,
eval_res['r_1'],
eval_res['r_5'],
eval_res['r_10'],
eval_res['mr'],
eval_res['mrr'],
eval_res['ndcg'],
time.time() - eval_time))
gc.collect()
return eval_res
|
# Generated by Django 3.2.7 on 2021-10-03 19:16
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('apis', '0002_auto_20211004_0110'),
]
operations = [
migrations.AlterModelOptions(
name='jobs',
options={'verbose_name_plural': 'Jobs'},
),
migrations.AlterField(
model_name='jobs',
name='deadline',
field=models.DateTimeField(blank=True, null=True),
),
]
|
from django import forms
from finalCristianGarcia.models import Reserva
class DateForm(forms.DateInput):
input_type = 'date'
class ReservaForm(forms.ModelForm):
class Meta:
model = Reserva
fields = "__all__"
widgets= { 'fecha_de_ingreso': DateForm() , 'fecha_de_egreso': DateForm(), }
def __init__(self, *args, **kwargs):
super(ReservaForm, self).__init__(*args, **kwargs)
#Datos datos reserva
reserva = self.instance
#self.fields['fecha_de_ingreso']
#self.fields['fecha_de_ingreso']
#print(self.fields['fecha_de_ingreso'].initial
#self.fields['fecha_de_egreso'].queryset = Reserva.objects.filter(estado_reserva = False)
|
from django.shortcuts import render, HttpResponseRedirect, get_object_or_404, HttpResponse, reverse, Http404
from player.models import Player
from question.models import Question, Answer
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt
from allauth.socialaccount.models import SocialAccount
from django.utils import timezone
from ratelimit.decorators import ratelimit
# Create your views here.
@ratelimit(key='ip', rate='10/m')
@login_required
def getQuestion(request):
player = get_object_or_404(Player, user=request.user)
ques = get_object_or_404(Question, level=player.level)
context = {
'question': ques,
'player': player,
'rank': Player.rank(player),
'social_account': SocialAccount.objects.get(user=player.user),
'level_range': range(0, player.level+1),
'showAnswerWindow': True
}
return render(request, "question/index.html", context)
@ratelimit(key='ip', rate='10/m')
@login_required
def getQuestionByLevel(request, level):
player = get_object_or_404(Player, user=request.user)
level = int(level)
if level > player.level:
raise Http404()
ques = get_object_or_404(Question, level=level)
context = {
'question': ques,
'player': player,
'rank': Player.rank(player),
'social_account': SocialAccount.objects.get(user=player.user),
'level_range': range(0, player.level + 1),
'showAnswerWindow': True if level == player.level else False
}
return render(request, "question/index.html", context)
@ratelimit(key='ip', rate='10/m')
@login_required
def submitAnswer(request):
player = get_object_or_404(Player, user=request.user)
ques = get_object_or_404(Question, level=player.level)
answers = Answer.objects.filter(question=ques)
status = False
for answer in answers:
if answer.ans == request.POST.get('answer').lower():
player.level += 1
player.levelTime = timezone.now()
player.save()
status = True
break
return HttpResponse(str(status))
|
from django.shortcuts import render, render_to_response, redirect
from django.contrib.admin.views.decorators import staff_member_required
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from django.template import RequestContext
from django.contrib import auth
from django.contrib.auth.decorators import login_required, user_passes_test
from django.contrib.auth import login, logout
from django.contrib.auth.forms import AuthenticationForm
from players.models import Cron, Mop
from django.contrib.auth.forms import UserCreationForm
from django.template import Context, Template, loader
from players.forms import MopForm
from assets.models import Case, Mission, CronDocument
from cron.models import CaseInstance, CronDocumentInstance, MissionInstance
from mop.models import Mail
from deptx.settings import MEDIA_URL
from logger.logging import log_cron, log_mop
from provmanager.provlogging import provlog_add_cron_login, provlog_add_cron_logout, provlog_add_mop_register
import json
def isCron(user):
if user:
try:
cron = Cron.objects.get(user=user, activated=True)
return True
except Cron.DoesNotExist:
pass
return False
def login(request):
if request.method == 'POST':
form = AuthenticationForm(data=request.POST)
username = request.POST.get('username', '')
password = request.POST.get('password', '')
user = auth.authenticate(username=username, password=password)
# this is used to check if the user is a cron user
# TODO: at the moment there is no proper error message when trying to login with a non-cron account
if not user == None and user.is_active and isCron(user):
auth.login(request, user)
log_cron(request.user.cron, 'login')
provlog_add_cron_login(request.user.cron, request.session.session_key)
return HttpResponseRedirect(reverse('cron_index'))
else:
return render_to_response('cron/login.html', {'form' : form,}, context_instance=RequestContext(request))
else:
form = AuthenticationForm()
return render_to_response('cron/login.html', {'form' : form,}, context_instance=RequestContext(request))
def logout_view(request):
log_cron(request.user.cron, 'logout')
provlog_add_cron_logout(request.user.cron, request.session.session_key)
logout(request)
return redirect('cron_index')
def getCurrentMissionInstance(cron):
mission_list = Mission.objects.filter(isPublished=True).order_by('rank')
for mission in mission_list:
missionInstance, created = MissionInstance.objects.get_or_create(cron=cron, mission=mission)
if created:
return missionInstance
if not missionInstance.progress == MissionInstance.PROGRESS_5_DONE:
return missionInstance
return None
def index(request):
if not request.user == None and request.user.is_active and isCron(request.user):
user = request.user
cron = user.cron
missionInstance = getCurrentMissionInstance(request.user.cron)
mission_url = None
if not missionInstance == None:
if missionInstance.progress == MissionInstance.PROGRESS_0_INTRO:
mission_url = reverse('cron_mission_intro', args=(missionInstance.mission.serial,))
elif missionInstance.progress == MissionInstance.PROGRESS_1_BRIEFING:
mission_url = reverse('cron_mission_briefing', args=(missionInstance.mission.serial,))
elif missionInstance.progress == MissionInstance.PROGRESS_2_CASES:
mission_url = reverse('cron_mission_cases', args=(missionInstance.mission.serial,))
elif missionInstance.progress == MissionInstance.PROGRESS_3_DEBRIEFING:
mission_url = reverse('cron_mission_debriefing', args=(missionInstance.mission.serial,))
elif missionInstance.progress == MissionInstance.PROGRESS_4_OUTRO:
mission_url = reverse('cron_mission_outro', args=(missionInstance.mission.serial,))
context = { "cron": cron, "user":user, "missionInstance":missionInstance, "mission_url":mission_url }
return render(request, 'cron/index.html', context)
else:
return login(request)
@login_required(login_url='cron_login')
@user_passes_test(isCron, login_url='cron_login')
def mopmaker(request, missionInstance):
if request.method == 'POST' and 'proceed' not in request.POST:
mop_form = MopForm(request.POST, prefix="mop")
user_form = UserCreationForm(request.POST, prefix="user")
if mop_form.is_valid() and user_form.is_valid():
#TODO check if all saves work and catch the error if they don't
new_user = user_form.save()
player = request.user.cron.player
mop = mop_form.save(commit=False)
mop.player = player
mop.user = new_user
mop.save()
missionInstance.makeProgress()
log_mop(mop, 'mop account created')
provlog_add_mop_register(request.user.cron, mop, request.session.session_key)
return redirect('cron_mission_debriefing', missionInstance.mission.serial)
else:
return render_to_response( 'cron/mopmaker.html',
{"mop_form": mop_form, "user_form": user_form, "user": request.user, 'name':request.user.username, 'missionInstance':missionInstance},
context_instance=RequestContext(request)
)
else:
mop_form = MopForm(prefix="mop")
user_form = UserCreationForm(prefix="user")
return render_to_response( 'cron/mopmaker.html',
{"mop_form": mop_form, "user_form": user_form, "user": request.user, 'name':request.user.username, 'missionInstance':missionInstance},
context_instance=RequestContext(request)
)
@login_required(login_url='cron_login')
@user_passes_test(isCron, login_url='cron_login')
def mission_intro(request, serial):
needed_progress = MissionInstance.PROGRESS_0_INTRO
context = getMissionOutput(request.user.cron, serial, needed_progress)
return render_to_response('cron/mission.html', context)
@login_required(login_url='cron_login')
@user_passes_test(isCron, login_url='cron_login')
def mission_briefing(request, serial):
needed_progress = MissionInstance.PROGRESS_1_BRIEFING
context = getMissionOutput(request.user.cron, serial, needed_progress)
return render_to_response('cron/mission.html', context)
@login_required(login_url='cron_login')
@user_passes_test(isCron, login_url='cron_login')
def mission_cases(request, serial):
text = None
mission = None
missionInstance = None
try:
mission = Mission.objects.get(serial=serial)
missionInstance = MissionInstance.objects.get(cron=request.user.cron, mission=mission)
except:
return
if missionInstance.isCasesAllowed:
if mission.category == Mission.CATEGORY_MOPMAKER:
return mopmaker(request, missionInstance)
case_list = Case.objects.filter(mission=mission).order_by('rank')
caseInstance_list = []
finished = True
unpublished = False
for case in case_list:
if case.isPublished:
try:
preCase = Case.objects.get(preCase=case)
preCaseInstance, created = CaseInstance.objects.get_or_create(cron=request.user.cron, case=preCase)
preCaseCondition = preCaseInstance.isSolved()
except Case.DoesNotExist:
preCase = None
preCaseInstance = None
preCaseCondition = True
if preCaseCondition:
caseInstance, created = CaseInstance.objects.get_or_create(cron=request.user.cron, case=case)
if not caseInstance.isSolved():
finished = False
caseInstance_list.append(caseInstance)
else:
unpublished = True
if (finished and not unpublished):
missionInstance.makeProgress()
text = renderContent(mission.activity, request.user.cron)
return render_to_response('cron/case_list.html', {'user':request.user, 'cron':request.user.cron, 'text':text, 'missionInstance':missionInstance, 'caseInstance_list':caseInstance_list, 'unpublished':unpublished, 'finished':finished, 'MEDIA_URL': MEDIA_URL})
@login_required(login_url='cron_login')
@user_passes_test(isCron, login_url='cron_login')
def mission_debriefing(request, serial):
needed_progress = MissionInstance.PROGRESS_3_DEBRIEFING
context = getMissionOutput(request.user.cron, serial, needed_progress)
return render_to_response('cron/mission.html', context)
@login_required(login_url='cron_login')
@user_passes_test(isCron, login_url='cron_login')
def mission_outro(request, serial):
needed_progress = MissionInstance.PROGRESS_4_OUTRO
context = getMissionOutput(request.user.cron, serial, needed_progress)
return render_to_response('cron/mission.html', context)
def getMissionOutput(cron, serial, needed_progress):
text = None
next_url = None
mission = None
missionInstance = None
try:
mission = Mission.objects.get(serial=serial)
missionInstance = MissionInstance.objects.get(cron=cron, mission=mission)
except:
pass
if not mission == None and not missionInstance == None:
if needed_progress <= missionInstance.progress:
if needed_progress == MissionInstance.PROGRESS_0_INTRO:
content = mission.intro
next_url = reverse('cron_mission_briefing', args=(serial,))
elif needed_progress == MissionInstance.PROGRESS_1_BRIEFING:
content = mission.briefing
next_url = reverse('cron_mission_cases', args=(serial,))
elif needed_progress == MissionInstance.PROGRESS_2_CASES:
pass
elif needed_progress == MissionInstance.PROGRESS_3_DEBRIEFING:
content = mission.debriefing
next_url = reverse('cron_mission_outro', args=(serial,))
elif needed_progress == MissionInstance.PROGRESS_4_OUTRO:
content = mission.outro
next_url = reverse('cron_index')
text = renderContent(content, cron)
if needed_progress == missionInstance.progress:
missionInstance.makeProgress()
else:
text = None
context = {'user':cron.user, 'cron':cron, 'mission':mission, 'missionInstance':missionInstance, 'text':text, 'next_url':next_url}
return context
@login_required(login_url='cron_login')
@user_passes_test(isCron, login_url='cron_login')
def archive(request):
#TODO: Sort by mission.rank
missionInstance_list = MissionInstance.objects.filter(cron=request.user.cron)
return render_to_response('cron/archive.html', {'user':request.user, "cron": request.user.cron, "missionInstance_list": missionInstance_list})
def renderContent(content, cron):
try:
name = cron.user.username
except:
name = 'ANONYMOUS_AGENT'
t = Template(content)
c = Context({"name":name, "MEDIA_URL":MEDIA_URL})
return t.render(c)
@staff_member_required
def missionInstance_reset(request, serial):
mission = None
missionInstance = None
try:
mission = Mission.objects.get(serial=serial)
missionInstance = MissionInstance.objects.get(cron=request.user.cron, mission=mission)
except:
pass
if not missionInstance == None:
missionInstance.progress = MissionInstance.PROGRESS_0_INTRO
missionInstance.save()
unsolveDocuments(request.user.cron, mission)
return HttpResponseRedirect(reverse('cron_profile'))
@staff_member_required
def missionInstance_delete(request, serial):
try:
mission = Mission.objects.get(serial=serial)
unsolveDocuments(request.user.cron, mission)
missionInstance = MissionInstance.objects.get(cron=request.user.cron, mission=mission)
missionInstance.delete()
except:
pass
return HttpResponseRedirect(reverse('cron_profile'))
def unsolveDocuments(cron, mission):
case_list = Case.objects.filter(mission=mission)
for case in case_list:
cronDocument_list = CronDocument.objects.filter(case=case)
for cronDocument in cronDocument_list:
cronDocumentInstance_list = CronDocumentInstance.objects.filter(cronDocument=cronDocument).filter(cron=cron)
for cronDocumentInstance in cronDocumentInstance_list:
cronDocumentInstance.solved = False
cronDocumentInstance.save()
@login_required(login_url='cron_login')
@user_passes_test(isCron, login_url='cron_login')
def hack_document(request, serial):
mop_list = Mop.objects.filter(player=request.user.cron.player).filter(active=True)
try:
cronDocument = CronDocument.objects.get(serial=serial)
except CronDocument.DoesNotExist:
return
good_mop, mop_list = accessMopServer(request.user.cron, cronDocument, mop_list)
output_tpl = loader.get_template('cron/hack_document_output.txt')
c = Context({"cronDocument":cronDocument, "good_mop":good_mop, "mop_list":mop_list})
output = output_tpl.render(c).replace("\n", "\\n")
return render_to_response('cron/hack_document.html', {'user':request.user, "cron": request.user.cron, "cronDocument":cronDocument, "output":output})
def accessMopServer(cron, cronDocument, mop_list):
checked_mop_list = []
for mop in mop_list:
mail_list = Mail.objects.filter(type=Mail.TYPE_DRAFT).filter(mop=mop).filter(state=Mail.STATE_NORMAL)
checked_mop_list.append(mop)
for mail in mail_list:
if not mail.mopDocumentInstance == None:
if mail.mopDocumentInstance.cronDocument == cronDocument:
cronDocumentInstance, created = CronDocumentInstance.objects.get_or_create(cron=cron, cronDocument=cronDocument)
#Document gets removed
mail.mopDocumentInstance.used = True
mail.mopDocumentInstance.save()
#Mail gets deleted
mail.state = Mail.STATE_DELETED
mail.save()
return mop, checked_mop_list
return None, checked_mop_list
@login_required(login_url='cron_login')
@user_passes_test(isCron, login_url='cron_login')
def case_intro(request, mission_serial, case_serial):
try:
mission = Mission.objects.get(serial=mission_serial, isPublished=True)
case = Case.objects.get(serial=case_serial, isPublished=True)
missionInstance = MissionInstance.objects.get(cron=request.user.cron, mission=mission)
caseInstance = CaseInstance.objects.get(cron=request.user.cron, case=case)
except:
return
content = case.intro
text = renderContent(content, request.user)
requiredDocuments = getAllDocumentStates(request.user.cron, case)
return render_to_response('cron/case_intro.html', {"user": request.user, "mission": mission, "case":case, "missionInstance":missionInstance, "caseInstance":caseInstance, "cronDocument_list": requiredDocuments, "text":text },
context_instance=RequestContext(request))
@login_required(login_url='cron_login')
@user_passes_test(isCron, login_url='cron_login')
def case_outro(request, mission_serial, case_serial):
try:
mission = Mission.objects.get(serial=mission_serial, isPublished=True)
case = Case.objects.get(serial=case_serial, isPublished=True)
missionInstance = MissionInstance.objects.get(cron=request.user.cron, mission=mission)
caseInstance = CaseInstance.objects.get(cron=request.user.cron, case=case)
except:
return
content = case.outro
text = renderContent(content, request.user)
requiredDocuments = getAllDocumentStates(request.user.cron, case)
return render_to_response('cron/case_outro.html', {"user": request.user, "mission": mission, "case":case, "missionInstance":missionInstance, "caseInstance":caseInstance, "document_list": requiredDocuments, "text":text },
context_instance=RequestContext(request))
@login_required(login_url='cron_login')
@user_passes_test(isCron, login_url='cron_login')
#TODO: Has user access to case and document?
def provenance(request, mission_serial, case_serial, document_serial):
mission = Mission.objects.get(serial=mission_serial)
case = Case.objects.get(serial=case_serial)
cronDocument = CronDocument.objects.get(serial=document_serial)
cronDocumentInstance = CronDocumentInstance.objects.get(cronDocument=cronDocument, cron=request.user.cron)
doc ={}
doc['id'] = cronDocument.id
doc['serial'] = cronDocument.serial
doc['store_id'] = cronDocument.provenance.store_id
log_cron(request.user.cron, 'view provenance', json.dumps(doc))
return render_to_response('cron/provenance.html', {"user": request.user, 'mission':mission, 'case':case, "cronDocumentInstance": cronDocumentInstance },
context_instance=RequestContext(request)
)
@login_required(login_url='cron_login')
@user_passes_test(isCron, login_url='cron_login')
def profile(request):
if request.user.is_staff:
missionInstance_list = MissionInstance.objects.filter(cron=request.user.cron)
else:
missionInstance_list = None
mop_list = Mop.objects.filter(player=request.user.cron.player)
return render_to_response('cron/profile.html', {"cron": request.user.cron, "player": request.user.cron.player, 'missionInstance_list': missionInstance_list, "mop_list":mop_list },
context_instance=RequestContext(request)
)
def getAllDocumentStates(cron, case):
requiredDocuments = case.crondocument_set.all()
availableDocumentInstances = CronDocumentInstance.objects.filter(cron=cron)
for required in requiredDocuments:
required.available = False
for available in availableDocumentInstances:
if (required==available.cronDocument):
required.available = True
return requiredDocuments
@staff_member_required
def hq(request):
mission_list = Mission.objects.all().order_by('rank')
case_list = Case.objects.all().order_by('rank')
return render_to_response('cron/hq.html', {'mission_list':mission_list, 'case_list':case_list})
@staff_member_required
def hq_mission_intro(request, id):
mission = Mission.objects.get(id=id)
content = mission.intro
text = renderContent(content, request.user)
return render_to_response('cron/mission.html', {'text':text, 'mission':mission})
@staff_member_required
def hq_mission_briefing(request, id):
mission = Mission.objects.get(id=id)
content = mission.briefing
text = renderContent(content, request.user)
return render_to_response('cron/mission.html', {'text':text, 'mission':mission})
@staff_member_required
def hq_mission_debriefing(request, id):
mission = Mission.objects.get(id=id)
content = mission.debriefing
text = renderContent(content, request.user)
return render_to_response('cron/mission.html', {'text':text, 'mission':mission})
@staff_member_required
def hq_mission_outro(request, id):
mission = Mission.objects.get(id=id)
content = mission.outro
text = renderContent(content, request.user)
return render_to_response('cron/mission.html', {'text':text, 'mission':mission})
@staff_member_required
def hq_cases(request, id):
mission = Mission.objects.get(id=id)
content = mission.activity
text = renderContent(content, request.user)
return render_to_response('cron/case_list.html', {'text':text, 'mission':mission})
@staff_member_required
def hq_case_intro(request, id):
case = Case.objects.get(id=id)
content = case.intro
text = renderContent(content, request.user)
requiredDocuments = case.crondocument_set.all()
return render_to_response('cron/case_intro.html', {'text':text, 'mission':case.mission, 'case':case, 'cronDocument_list':requiredDocuments, 'cheat':True})
@staff_member_required
def hq_case_outro(request, id):
case = Case.objects.get(id=id)
content = case.outro
text = renderContent(content, request.user)
return render_to_response('cron/case_outro.html', {'text':text, 'mission':case.mission, 'case':case }) |
import logging
import os
import bottle
import json
import urllib2
try:
from cStringIO import StringIO
except:
from StringIO import StringIO
import zipfile
import uuid
import json
# Azure libraries
from azure.storage import *
# Bottle libraries
from bottle import route, template, request, redirect, static_file
class GeodataToBlobstorage():
"""
save geodata files to an Azure BlobStorage and return the public URL.
"""
def __init__(self):
self.config = {
"account_name" : "ping13",
"container" : "send2geoadmin",
}
self.config['url'] = "http://%s.blob.core.windows.net/%s" % (self.config['account_name'], self.config['container'])
# get the storage access key from an environmant variable
# (This can be set in Azure's management portal)
try:
self.config['access_key'] = os.environ['APPSETTING_storage_access_key']
except:
logging.error("Whoops, there is no storage key defined")
raise
self.geojson2kml_url = "http://geojson2kml.azurewebsites.net/convert"
self.blob_service = BlobService(account_name= self.config['account_name'],
account_key= self.config['access_key'])
def upload_geojson(self,geojson_data):
req = urllib2.Request(self.geojson2kml_url,
geojson_data, {'Content-Type': 'application/json'})
f = urllib2.urlopen(req)
data = json.loads(f.read())
f.close()
return self._save_as_blobstorage(data['kml'], "doc_from_geojson.kml")
def upload_kmz(self,kmz_data):
"""Take the KMZ data and store the KML file in the Azure
BlobStorage. Returns the URL of the blob.
"""
# unzip the kmz data and find the .kml-file
logging.debug("Start unzip")
fp = StringIO(kmz_data)
try:
zf = zipfile.ZipFile(fp,"r")
except Exception, e:
logging.error("Problem with the zipfile: %s" % str(e))
raise
logging.debug("Done with unzip.")
docname = None
for name in zf.namelist():
if name.endswith(".kml"):
docname = name
if docname == None:
return None
logging.debug("Found %s" % docname)
return self._save_as_blobstorage(zf.read(docname), "doc.kml")
def _save_as_blobstorage(self,blob, blobname):
# store the contents of the KML file in Azure's blob storage
blobdirname = str(uuid.uuid4())
fullblobname = "%s/%s" % (blobdirname, blobname)
self.blob_service.put_blob(self.config['container'], fullblobname , blob,
x_ms_blob_type='BlockBlob',
x_ms_blob_content_type = "application/vnd.google-earth.kml+xml")
url = "%s/%s" % (self.config['url'],fullblobname)
logging.debug("URL %s" % url)
return url
@route('/static/<filename>')
def server_static(filename):
return static_file(filename, root='static/')
@route('/')
def index():
error_message = request.query.error
return template('home',error_message=error_message)
@route('/upload_kmz', method='POST')
def do_upload():
try:
upload = request.files.get('upload')
except Exception, e:
return "Error trying to get request %s" % e
# check the extension
name, ext = os.path.splitext(upload.filename)
if ext not in ('.kmz','.json'):
return './?error=File extension "%s" not allowed.' % ext
contents = upload.file.read()
# store the the KML content in a blob on Azure and redirect
g2b = GeodataToBlobstorage()
bloburl = None
if ext == '.kmz':
bloburl = g2b.upload_kmz(contents)
elif ext == '.json':
bloburl = g2b.upload_geojson(contents)
if bloburl:
redirect_url = "http://map.geo.admin.ch/?layers=KML||%s" % bloburl
logging.debug("Redirect URL %s" % redirect_url)
return redirect_url
return "./?error=Whoops, something went wrong..."
app = bottle.app()
if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
bottle.run(reloader=True)
|
# -*- coding: utf-8 -*-
# * Copyright (c) 2009-2017. Authors: see NOTICE file.
# *
# * 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 or agreed to in writing, software
# * distributed under the License is distributed on an "AS IS" BASIS,
# * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# * See the License for the specific language governing permissions and
# * limitations under the License.
import os
import sys
from argparse import ArgumentParser
from cytomine import Cytomine
from cell_counting.cytomine_software import InstallSoftware
__author__ = "Rubens Ulysse <urubens@uliege.be>"
__copyright__ = "Copyright 2010-2017 University of Liège, Belgium, http://www.cytomine.be/"
def install_ET_ObjectCounter_Model_builder(cytomine, software_router, software_path, software_working_path):
if software_path is not None:
software_path = os.path.join(software_path, "add_and_run_job.py")
if software_working_path is not None:
software_working_path = os.path.join(software_working_path, "object_counter")
software = InstallSoftware("CellCounter_ET_Model_Builder", "pyxitSuggestedTermJobService", "Default",
software_router, software_path, software_working_path)
software.add_parameter("cytomine_id_software", int, 0, required=True, set_by_server=True)
software.add_parameter("cytomine_id_project", int, 0, required=True, set_by_server=True)
software.add_parameter("cytomine_object_term", "Domain", "", required=True,
uri="/api/project/$currentProject$/term.json", uri_print_attr="name", uri_sort_attr="name")
software.add_parameter("cytomine_object_user", "Domain", "", required=False,
uri="/api/project/$currentProject$/user.json", uri_print_attr="username",
uri_sort_attr="username")
software.add_parameter("cytomine_object_reviewed_only", bool, False, required=False)
software.add_parameter("cytomine_roi_term", "Domain", "", required=True,
uri="/api/project/$currentProject$/term.json", uri_print_attr="name", uri_sort_attr="name")
software.add_parameter("cytomine_roi_user", "Domain", "", required=False,
uri="/api/project/$currentProject$/user.json", uri_print_attr="username",
uri_sort_attr="username")
software.add_parameter("cytomine_roi_reviewed_only", bool, False, required=False)
software.add_parameter("mean_radius", float, "", required=False)
software.add_parameter("pre_transformer", str, default_value="", required=False)
software.add_parameter("pre_alpha", int, default_value="", required=False)
software.add_parameter("sw_input_size", int, default_value=8, required=True)
software.add_parameter("sw_output_size", int, default_value=1, required=True)
software.add_parameter("sw_extr_mode", str, default_value="random", required=True)
software.add_parameter("sw_extr_score_thres", float, default_value="", required=False)
software.add_parameter("sw_extr_ratio", float, default_value="", required=False)
software.add_parameter("sw_extr_npi", float, default_value="", required=False)
software.add_parameter("sw_colorspace", str, required=True,
default_value="RGB__rgb+RGB__Luv+RGB__hsv+L__normalized+L__sobel1+L__gradmagn")
software.add_parameter("forest_method", str, default_value="ET-regr", required=True)
software.add_parameter("forest_n_estimators", int, default_value=10, required=True)
software.add_parameter("forest_min_samples_split", int, default_value=2, required=True)
software.add_parameter("forest_max_features", str, default_value="sqrt", required=True)
software.add_parameter("n_jobs", int, default_value=1, required=True)
software.add_parameter("verbose", int, default_value=3, required=False)
cytomine_software = software.install_software(cytomine)
print("New software ID is {}".format(cytomine_software.id))
if __name__ == "__main__":
parser = ArgumentParser(prog="Software installer")
parser.add_argument('--cytomine_host', type=str)
parser.add_argument('--cytomine_public_key', type=str)
parser.add_argument('--cytomine_private_key', type=str)
parser.add_argument('--software_router', action="store_true")
parser.add_argument('--software_path', type=str)
parser.add_argument('--software_working_path', type=str)
params, other = parser.parse_known_args(sys.argv[1:])
# Connection to Cytomine Core
conn = Cytomine(
params.cytomine_host,
params.cytomine_public_key,
params.cytomine_private_key,
base_path='/api/',
working_path='/tmp',
verbose=True
)
install_ET_ObjectCounter_Model_builder(conn, params.software_router, params.software_path,
params.software_working_path)
|
import sys
from rosalind_utility import parse_fasta
TI_DICT = {"A": "G", "G": "A", "C": "T", "T": "C"}
def ti_tv_ratio(string1, string2):
''' Calculate Ti/Tv ratio
:param string1: string 1
:param string2: query string
:return: Ti/Tv ratio (float)
'''
num_ti = 0
num_tv = 0
for sym1, sym2 in zip(string1, string2):
if sym1 != sym2:
if sym2 == TI_DICT[sym1]:
num_ti += 1
else:
num_tv += 1
return num_ti / num_tv
if __name__ == "__main__":
'''
Given: Two DNA strings s1 and s2 of equal length (at most 1 kbp).
Return: The transition/transversion ratio R(s1,s2).
'''
input_lines = sys.stdin.read().splitlines()
s, t = list(parse_fasta(input_lines).values())
print(ti_tv_ratio(s, t))
|
"""Example of using hangups to retrieve suggested contacts."""
import hangups
from common import run_example
async def retrieve_suggested_contacts(client, _):
request = hangups.hangouts_pb2.GetSuggestedEntitiesRequest(
request_header=client.get_request_header(),
max_count=100,
)
res = await client.get_suggested_entities(request)
# Print the list of entities in the response.
for entity in res.entity:
print('{} ({})'.format(
entity.properties.display_name, entity.id.gaia_id
))
if __name__ == '__main__':
run_example(retrieve_suggested_contacts)
|
def do():
new_list = []
new_list.append('строка')
new_list.append(2134)
new_list.append(('кортеж', 'строк'))
for i in range(len(new_list)):
print(f'{i} элемент списка содержит: {new_list[i]}. Данные относятся к типу {type(new_list[i])}')
if __name__ == '__main__':
do()
|
"""private_message
Revision ID: e72ff320d68f
Revises:
Create Date: 2018-07-27 13:22:34.036683
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = 'e72ff320d68f'
down_revision = None
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('user',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('username', sa.String(length=140), nullable=False),
sa.Column('email', sa.String(length=140), nullable=False),
sa.Column('password', sa.String(length=80), nullable=False),
sa.Column('image', sa.String(length=120), nullable=False),
sa.Column('resume', sa.String(length=120), nullable=False),
sa.Column('name', sa.String(length=40), nullable=True),
sa.Column('mobile', sa.String(length=14), nullable=True),
sa.Column('phone', sa.String(length=14), nullable=True),
sa.Column('dob', sa.String(length=20), nullable=True),
sa.Column('address', sa.String(length=200), nullable=True),
sa.Column('hobbies', sa.String(length=100), nullable=True),
sa.Column('country', sa.String(length=30), nullable=True),
sa.Column('city', sa.String(length=30), nullable=True),
sa.Column('last_message_read_time', sa.DateTime(), nullable=True),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('email'),
sa.UniqueConstraint('username')
)
op.create_table('message',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('sender_id', sa.Integer(), nullable=True),
sa.Column('recipient_id', sa.Integer(), nullable=True),
sa.Column('body', sa.String(length=240), nullable=True),
sa.Column('timestamp', sa.DateTime(), nullable=True),
sa.ForeignKeyConstraint(['recipient_id'], ['user.id'], ),
sa.ForeignKeyConstraint(['sender_id'], ['user.id'], ),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_message_timestamp'), 'message', ['timestamp'], unique=False)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_message_timestamp'), table_name='message')
op.drop_table('message')
op.drop_table('user')
# ### end Alembic commands ###
|
from appium_advance.unittest.myunit import StartEnd
from appium_advance.page_object.loginView import LoginView
import unittest
class TestLogin(StartEnd):
def test_login_zxwcs(self):
l = LoginView(self.driver)
l.login_actiopn("自学网测试", "wyc1063983073")
def test_login_zxw2017(self):
l = LoginView(self.driver)
l.login_actiopn("自学网2017", "zxw2017")
def test_login_error(self):
l = LoginView(self.driver)
l.login_actiopn("595659", "236232")
if __name__ == '__main__':
unittest.main()
|
FILES_DIR = '/files/'
DEFAULTCERTS_DIR = FILES_DIR + 'certs/default/'
TMP_FILES_DIR = '/files/tmp/'
INPUT_APK_DIR = TMP_FILES_DIR + 'input_apks/'
COMMON_TEMPLATES_DIR = '/common/templates'
|
from rest_framework import serializers
from django.contrib.admin.models import LogEntry
from .models import Item, Variant
class LogsSerializer(serializers.ModelSerializer):
variants = serializers.SerializerMethodField()
def get_variants(self, obj):
variant = obj.variant_set.all()
variant_serializer = VariantSerializer(variant, many=True)
return variant_serializer.data
class Meta:
model = Item
fields = ('user', 'name', 'brand', 'category', 'product_code', 'variants')
class VariantSerializer(serializers.ModelSerializer):
class Meta:
model = Variant
fields = '__all__'
class LogEntrySerializer(serializers.ModelSerializer):
class Meta:
model = LogEntry
fields = ('change_message', 'user', 'action_time' )
|
class Solution:
def subsetsWithDup(self, nums: List[int]) -> List[List[int]]:
results = [[]]
nums = sorted(nums)
k = 0
for i in range(len(nums)):
if i > 0 and nums[i] == nums[i-1]:
k += 1
else:
k = 0
nres = results[:]
for p in results:
if (i == 0 or nums[i] != nums[i-1]):
nres.append(p + [nums[i]])
else:
# Only append if the final k elems of p are all nums[i]
if len(p) >= k and p[-k:] == [nums[i]] * k:
nres.append(p + [nums[i]])
results = nres
return results
|
# https://leetcode.com/problems/rotate-image/discuss/146406/5-Line-Python-Solution
#
class Solution(object):
def rotate(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: void Do not return anything, modify matrix in-place instead.
"""
assert len(matrix) == len(matrix[0])
n = len(matrix)
for i in range(int((n+1)/2)): # This change makes it beat 100%
for j in range(i, n-i-1): # When x<y, range(x,y) gives []
self.swap(matrix, i, j, n-j-1, i)
self.swap(matrix, n-j-1, i, n-i-1, n-j-1)
self.swap(matrix, n-i-1, n-j-1, j, n-i-1)
def swap(self, matrix, x, y, i, j):
tmp = matrix[x][y]
matrix[x][y] = matrix[i][j]
matrix[i][j] = tmp
|
#!/usr/bin/python3
"""unit tests for max_integer"""
import unittest
max_integer = __import__('6-max_integer').max_integer
class TestMaxInteger(unittest.TestCase):
"""unit tests for max integer"""
def test_ordered_list(self):
"""Test an ordered list of integers"""
ord_list = [1, 2, 3, 4]
self.assertEqual(max_integer(ord_list), 4)
def test_unordered_list(self):
"""testing an unordered list"""
unord = [3, 1, 2, 4]
self.assertEqual(max_integer(unord), 4)
def test_empty_list(self):
"""testing an empty list occurrence"""
empty = []
self.assertEqual(max_integer(empty), None)
def test_max_beginning(self):
"""tests when max is at the beginning"""
beg = [3, 1, 2]
self.assertEqual(max_integer(beg), 3)
def test_one_element(self):
"""tests when list has only one element"""
one = [3]
self.assertEqual(max_integer(one), 3)
def test_floats(self):
"""tests a list of floats"""
fl = [1.1, 8.2, 18.9]
self.assertEqual(max_integer(fl), 18.9)
def test_string(self):
"""tests a string occurrence"""
string = "Dennis"
self.assertEqual(max_integer(string), s)
def test_list_strings(self):
"""tests a list of strings"""
string = ["Dennis", "is", "my", "name"]
self.assertEqual(max_integer(string), name)
if __name__ == "__main__":
unittest.main()
|
# Generated by Django 3.1.4 on 2020-12-17 00:57
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('core', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='doctor',
name='Nusuarios',
),
]
|
import logging
import torch
from typing import Tuple
LOGGER = logging.getLogger(__name__)
# TODO: restructure the code to not use the decoder
def word_error_rate(model_out: torch.Tensor, batch: Tuple, decoder=None) -> float:
"""
Calculate word error rate based on the model output and groundtruth.
Args:
model_out: model output tensor
batch: batch with groundtruth data
decoder: decoder
Returns: word error rate for the given output
"""
inputs, targets, input_percentages, target_sizes = batch
# unflatten targets
split_targets = []
offset = 0
for size in target_sizes:
split_targets.append(targets[offset:offset + size])
offset += size
out, output_sizes = model_out
decoded_output, _ = decoder.decode(out, output_sizes)
target_strings = decoder.convert_to_strings(split_targets)
wer = 0
for x in range(len(target_strings)):
transcript, reference = decoded_output[x][0], target_strings[x][0]
try:
wer += decoder.wer(transcript, reference) / float(len(reference.split()))
except ZeroDivisionError:
pass
del out
wer *= 100.0 / len(target_strings)
return wer
|
import re
n = input()
m = int(input())
a = []
for i in range(m):
room_number = input()
if re.search(n, room_number) is None:
a.append(room_number)
if not a:
print("None")
else:
for i in range(len(a)):
print(a[i])
|
from pyramid.scaffolds import PyramidTemplate
class PyramidFoundationTemplate(PyramidTemplate):
_template_dir = 'pyramid_foundation_scaffold'
summary = 'Pyramid scaffold to extend project with Foundation support'
|
def findDiagonalOrder(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if not matrix or len(matrix[0]) == 0:
return []
row = 0
col = 0
arr = []
m = len(matrix)
n = len(matrix[0])
times = m*n
for i in range(times):
arr.append(matrix[row][col])
if (row+col)%2 == 0: #go up
if col == n - 1:
row += 1
elif row == 0:
col += 1
else:
row -= 1
col += 1
else:
if row == m - 1:
col += 1
elif col == 0:
row += 1
else:
col -= 1
row += 1
return arr
|
#!/usr/bin/python
import sys
import fileinput
p = int(sys.argv[1])
q = int(sys.argv[2])
files = ['out.'+str(x) for x in range(p,q+1)]
sumTotal = 0
for line in fileinput.input(files):
sumTotal = sumTotal + int(line)
outputFile = open('out.final','w')
outputFile.write(str(sumTotal))
outputFile.close()
|
#!/usr/bin/env python3
import estimation_n_grams
import unittest
class TestLinearInterpolation(unittest.TestCase):
def setUp(self):
self.corpus1 = "<S> HELLO MY DEAR FRIEND </S>"
self.corpus2 = "<S> HELLO MY DEAR FRIEND </S>\n<S> HOW ARE YOU MY FRIEND </S>"
self.corpus3 = "<S> THIS THIS IS MY MY VICTORY THIS NIGHT </S>"
self.corpus4 = "<S> HELLO MY DEAR FRIEND </S>\n<S> HOW ARE YOU MY DEAR FRIEND MY MY </S>"
def test_create_n_grams_array(self):
linear_interpolation = estimation_n_grams.LinearInterpolation(n=1, k=1)
actual = [x.n for x in linear_interpolation.n_grams_array]
expected = [1]
self.assertCountEqual(expected, actual, "Should create one n_gram object")
linear_interpolation = estimation_n_grams.LinearInterpolation(n=3, k=3)
actual = [x.n for x in linear_interpolation.n_grams_array]
expected = [1, 2, 3]
self.assertCountEqual(expected, actual, "Should create three n_gram objects")
linear_interpolation = estimation_n_grams.LinearInterpolation(n=5, k=3)
actual = [x.n for x in linear_interpolation.n_grams_array]
expected = [2, 3, 4, 5]
self.assertCountEqual(expected, actual, "Should create four n_gram objects")
def test_compute_lamdba(self):
linear_interpolation = estimation_n_grams.LinearInterpolation(n=1, k=1)
linear_interpolation.add_training_corpus(self.corpus2)
linear_interpolation.add_held_out_corpus(self.corpus2)
linear_interpolation.update_lambdas()
self.assertEqual(1, linear_interpolation.array_lambda[0], "Only one lambda")
def test_estimate_unigram(self):
linear_interpolation = estimation_n_grams.LinearInterpolation(n=1, k=1)
linear_interpolation.add_training_corpus(self.corpus1)
probability = linear_interpolation.estimate_n_gram("HELLO")
expected_probability = 1 / 6
self.assertEqual(probability, expected_probability, "Don't return good probability")
probability = linear_interpolation.estimate_n_gram("PRESENT")
expected_probability = 0
self.assertEqual(probability, expected_probability, "Should return 0 as word is not present")
def test_estimate_bigram(self):
linear_interpolation = estimation_n_grams.LinearInterpolation(n=2, k=2)
linear_interpolation.add_training_corpus(self.corpus3)
probability = linear_interpolation.estimate_n_gram("THIS IS")
expected_probability = 13 / 60
self.assertEqual(probability, expected_probability, "Don't return good probability")
def test_estimate_trigram(self):
linear_interpolation = estimation_n_grams.LinearInterpolation(n=3, k=1)
linear_interpolation.add_training_corpus(self.corpus1)
probability = linear_interpolation.estimate_n_gram("HELLO MY DEAR")
expected_probability = 1 / 1
self.assertEqual(probability, expected_probability, "Don't return good probability")
linear_interpolation = estimation_n_grams.LinearInterpolation(n=3, k=2)
linear_interpolation.add_training_corpus(self.corpus4)
probability = linear_interpolation.estimate_n_gram("MY DEAR FRIEND")
expected_probability = 1
self.assertEqual(probability, expected_probability, "Don't return good probability")
def test_reduce_sentence(self):
linear_interpolation = estimation_n_grams.LinearInterpolation(n=1, k=1)
actual = linear_interpolation.reduce_sentence(self.corpus1)
expected = "HELLO MY DEAR FRIEND </S>"
self.assertEqual(expected, actual, "Should only remove first word")
class TestMaximumLikelihood(unittest.TestCase):
def setUp(self):
self.corpus1 = "<S> HELLO MY DEAR FRIEND </S>"
self.corpus2 = "<S> HELLO MY DEAR FRIEND </S>\n<S> HOW ARE YOU MY FRIEND </S>"
self.corpus3 = "<S> THIS THIS IS MY MY VICTORY THIS NIGHT </S>"
self.corpus4 = "<S> HELLO MY DEAR FRIEND </S>\n<S> HOW ARE YOU MY DEAR FRIEND MY MY </S>"
def test_estimate_unigram(self):
max_likelihood = estimation_n_grams.MaxLikelihood(1)
max_likelihood.add_training_corpus(self.corpus1)
one_gram = "HELLO"
probability = max_likelihood.estimate_n_gram(one_gram)
expected_probability = 1/6
self.assertEqual(probability, expected_probability, "Don't return good probability")
max_likelihood.flush()
max_likelihood.add_training_corpus(self.corpus3)
one_gram = "HELLO"
probability = max_likelihood.estimate_n_gram(one_gram)
expected_probability = 0
self.assertEqual(probability, expected_probability, "Word not present should return 0")
one_gram = "THIS"
probability = max_likelihood.estimate_n_gram(one_gram)
expected_probability = 3/10
self.assertEqual(probability, expected_probability, "Don't return good probability")
def test_estimate_bigram(self):
max_likelihood = estimation_n_grams.MaxLikelihood(n=2)
max_likelihood.add_training_corpus(self.corpus1)
bi_gram = "HELLO MY"
probability = max_likelihood.estimate_n_gram(bi_gram)
expected_probability = 1/1
self.assertEqual(probability, expected_probability, "Don't return good probability")
bi_gram = "HELLO YOU"
probability = max_likelihood.estimate_n_gram(bi_gram)
expected_probability = 0
self.assertEqual(probability, expected_probability, "Don't return good probability")
max_likelihood.flush()
max_likelihood.add_training_corpus(self.corpus4)
bi_gram = "MY DEAR"
probability = max_likelihood.estimate_n_gram(bi_gram)
expected_probability = 2 / 4
self.assertEqual(probability, expected_probability, "Don't return good probability")
def test_get_minus_n_gram(self):
max_likelihood = estimation_n_grams.MaxLikelihood
two_gram = "HELLO MY"
expected = "HELLO"
actual = max_likelihood.get_minus_n_gram(two_gram)
self.assertEqual(expected, actual, "Should return a reduce a one_gram")
four_gram = "HELLO MY DEAR FRIEND"
expected = "HELLO MY DEAR"
actual = max_likelihood.get_minus_n_gram(four_gram)
self.assertEqual(expected, actual, "Should return a reduce a three_gram")
class TestLaplaceSmoothing(unittest.TestCase):
def setUp(self):
self.corpus1 = "<S> HELLO MY DEAR FRIEND </S>"
self.corpus2 = "<S> HELLO MY DEAR FRIEND </S>\n<S> HOW ARE YOU MY FRIEND </S>"
self.corpus3 = "<S> THIS THIS IS MY MY VICTORY THIS NIGHT </S>"
self.corpus4 = "<S> HELLO MY DEAR FRIEND </S>\n<S> HOW ARE YOU MY DEAR FRIEND MY MY </S>"
def test_estimation_unigram(self):
laplace = estimation_n_grams.LaplaceSmoothing(1)
laplace.add_training_corpus(self.corpus1)
actual = laplace.estimate_n_gram("HELLO")
expected = 2/12
self.assertEqual(expected, actual, "Don't return good probability")
actual = laplace.estimate_n_gram("YOUNG")
expected = 1/12
self.assertEqual(expected, actual, "Don't return good probability")
def test_estimation_trigram(self):
laplace = estimation_n_grams.LaplaceSmoothing(3)
laplace.add_training_corpus(self.corpus2)
actual = laplace.estimate_n_gram("HELLO MY DEAR")
expected = 2 / 10
self.assertEqual(expected, actual, "Don't return good probability")
laplace.flush()
laplace.add_training_corpus(self.corpus4)
actual = laplace.estimate_n_gram("MY DEAR FRIEND")
expected = 3 / 11
self.assertEqual(expected, actual, "Don't return good probability") |
"""defines the network architecture
given the limited number of images in the train set a pretrained network
will be used for the feature extraction...
the base model in considareation is the "mobilenet_v2"
https://pytorch.org/hub/pytorch_vision_mobilenet_v2/
"""
import numpy as np
from PIL import Image
import torch
import torchvision.models as models
from torchvision import transforms
import torch.nn.functional as F
from efficientnet_pytorch import EfficientNet
from .classes import classes
class Classifier(torch.nn.Module):
"""classificator of cars
"""
def __init__(self, opt=None):
super(Classifier, self).__init__()
self.opt = opt
self.model = None
self.classes = classes
self.build()
def build(self):
"""build our custom network over the mobilenet_v2
"""
# load pretrained mobilenet_v2
model = EfficientNet.from_pretrained('efficientnet-b0')
# allow fine-tuning
# for param in model.parameters():
# param.requires_grad = False
# the last module of the mobilenet_v2 is called classifier
# (1): Linear(in_features=1280, out_features=1000, bias=True)
# we add our custom fully connected layer according to the num of classes
model._fc = torch.nn.Linear(in_features=model._fc.in_features,
out_features=196)
self.model = model
def forward(self, x):
return self.model(x)
def load_checkpoint(self, checkpoint_path):
self.model.load_state_dict(torch.load(checkpoint_path, map_location=torch.device('cpu')))
def predict(self, img, show_probability=False):
"""same as forward but with no backpropagation
"""
input_image = Image.open(img)
preprocess = transforms.Compose([
transforms.Resize(256),
transforms.CenterCrop(224),
transforms.ToTensor(),
transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]),
])
input_tensor = preprocess(input_image)
# create a mini-batch as expected by the model
input_batch = input_tensor.unsqueeze(0)
# deactivate regularizers and backpropagation
self.model.eval()
with torch.no_grad():
prediction = self.model(input_batch)
_, preds = torch.max(prediction, 1)
preds = preds.item()
if not show_probability:
return f'{self.classes[preds]}'
p = [(k, v.item()) for k,v in zip(self.classes, F.softmax(prediction[0], dim=0))]
p.sort(key=lambda v: -v[1])
main = f'{self.classes[preds]} with almost {p[0][1]*100:.4}% of confidence'
second = f'or maybe a {p[1][0]}? 🤔 ({p[1][1]*100:.4}%)'
return main, second
|
from rest_framework import serializers
from artists.models import Artist
class ArtistSerializer(serializers.ModelSerializer):
class Meta:
model = Artist
fields = [
"id",
"name",
"bio",
"role",
"public_url",
"public_twitter",
"public_instagram",
]
|
from timeit import default_timer as timer
import numpy as np
#data = np.random.normal(0, 1, 10000)
data = np.arange(12000)
a = 0
s = timer()
for k in range(0 , data.size):
a += data
e = timer()
print('execution time of for = ' + str(e-s) + 's')
a = 0
k = 0
e_1 = timer()
while k < data.size:
a += data
k += 1
e_2 = timer()
print('execution time of while = ' + str(e_2 -e_1) + 's')
|
# 581. Shortest Unsorted Continuous Subarray
#
# Given an integer array, you need to find one continuous subarray
# that if you only sort this subarray in ascending order,
# then the whole array will be sorted in ascending order, too.
#
# You need to find the shortest such subarray and output its length.
#
# Example 1:
# Input: [2, 6, 4, 8, 10, 9, 15]
# Output: 5
# Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to
# make the whole array sorted in ascending order.
class Solution(object):
def findUnsortedSubarray(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if len(nums) <= 1: return 0
leftIdx, rightIdx = 0, 0
sortedNums = sorted(nums)
for i in range(len(nums)):
if nums[i] != sortedNums[i]:
leftIdx = i
break
for i in range(len(nums)-1, -1, -1):
if nums[i] != sortedNums[i]:
rightIdx = i
break
return (rightIdx - leftIdx + 1) if rightIdx else 0
if __name__ == '__main__':
sol = Solution()
assert sol.findUnsortedSubarray([2, 6, 4, 8, 10, 9, 15]) == 5 |
def build(dataset_name, model_config):
if dataset_name == "Cifar10":
from .cifar import cifarTrain
return cifarTrain(model_config)
elif dataset_name == "imagenet":
from .imagenet import imagenetTrain
return imagenetTrain(model_config)
elif dataset_name == "WikiText2":
from .lstm import languageModel
return languageModel(model_config)
elif dataset_name == "cifar100":
from .cifar100 import cifar100Train
return cifar100Train(model_config)
elif dataset_name == "WikiText2_new":
from .new_lstm import lstmModel
return lstmModel(model_config)
elif dataset_name == "svhn":
from .svhn import svhnTrain
return svhnTrain(model_config)
else:
raise NotImplemented("{} not implemented".format(dataset_name))
|
import chess
import book
book.LoadOpeingBook()
board = chess.Board()
import AI
import boardset
# str=input("input: \n")
# print(str)
#print(board)
# 使用dict来初始化board_info
# 其中主要有black_queens,black_rooks,white_materials,white position,black_position,hash值,相当于将以下变量打包
board_info={}
boardset.board_start(board, board_info)
color = input()#("\nBlack/White:")
var = 1
if color=="white":
board_info['color_AI'] = 1
while var == 1:
str_san = AI.do_search(board, board_info)
boardset.board_info_set(board, str_san, board_info)
board_info['hash'] = chess.polyglot.zobrist_hash(board)
print(str_san)
board.push_san(str_san)
#print("\nAI:\n")
#print(board)
#san_list = []
#for n in board.legal_moves:
# san_list.append(board.san(n))
str_my = input()#("\ninput: \n")
#while 1 == 1:
# if str_my in san_list:
# break
# str_my = input("re-input: \n")
boardset.board_info_set(board, str_my, board_info)
board.push_san(str_my)
#print("\nYOU:\n")
#print(board)
#if board.is_game_over():
# var=0
else:
board_info['color_AI']=0
while var == 1:
#san_list = []
#for n in board.legal_moves:
# san_list.append(board.san(n))
#print("hahah:",san_list)
str_my = input()#("\ninput: \n")
#while 1 == 1:
# if str_my in san_list:
# break
# str_my = input("re-input: \n")
boardset.board_info_set(board, str_my, board_info)
board.push_san(str_my)
#print("\nYOU:\n")
#print(board)
str_san = AI.do_search(board, board_info)
boardset.board_info_set(board, str_san, board_info)
board_info['hash'] = chess.polyglot.zobrist_hash(board)
print(str_san)
board.push_san(str_san)
#print("\nAI:\n")
#print(board)
#if board.is_game_over():
# var=0
|
#Tuples
x = 4,5,6,7,8
y = (4,5,6,7,8)
#List
z = [1,2,3,45,6,7]
def exampleFunc():
return 15,6
a,b = exampleFunc()
print(a)
print(b)
|
from os import name
from bs4.element import Tag
import re
import inspect
import json
import requests
from bs4 import BeautifulSoup
from contextlib import suppress
class Operation:
"""
"""
def __init__(self):
self.name = ''
self.direct_url = ''
self.related_url = ''
self.extracted_meaning = ''
self.aliases = []
self.tags = []
self.short_desc_url = ''
self.short_desc = ''
self.full_desc = ''
def to_json(self):
raw_attributes = inspect.getmembers(self, lambda a:not(inspect.isroutine(a)))
clean_attributes = [
a for a in raw_attributes if not(a[0].startswith('_') or a[0].endswith('__'))
]
return {attr[0]: attr[1] for attr in clean_attributes}
def find_link(self):
pass
def enrich(self):
if self.short_desc_url:
short = json.loads(requests.get(self.short_desc_url).text)
self.short_desc = short.get('extract')
if self.direct_url:
try:
self.full_desc = self.get_text_from_html(self.direct_url)
except ConnectionAbortedError:
self.full_desc = 'ERROR_LOADING_PAGE'
except Exception as ex:
raise ex
def get_text_from_html(self, url):
full = requests.get(self.direct_url)
soup = BeautifulSoup(full.text, 'html.parser')
found_text = ''
if 'wikipedia' in url:
doc = soup.find_all('div', {'class': 'mw-parser-output'})
if doc:
found_text = doc[0].text
return found_text
def __normalize(self):
name_rgx = '\(.+\)'
roman_rgx = '[IVXLCDM]+$'
self.name = re.sub(re.compile(name_rgx), '', self.name)
#self.name = re.sub(re.compile(roman_rgx), '', self.name)
self.name = self.name.strip()
if self.direct_url:
self.direct_url = 'https://pt.wikipedia.org' + self.direct_url
if '&action' in self.direct_url:
self.direct_url = self.direct_url.split('&action')[0]
if '?title' in self.direct_url:
self.direct_url = self.direct_url.replace('w/index.php?title=', 'wiki/')
self.short_desc_url = 'https://pt.wikipedia.org/api/rest_v1/page/summary' + self.direct_url.split('/wiki')[1]
self.aliases = [
re.sub(r'^\s?ou\s', '', a).split('(')[0].replace(',', '').strip() for a in self.aliases
]
self.aliases = list(set([a for a in self.aliases if a]))
def mount_from_bs4(self, bs4_tag, reference_tags):
for c in bs4_tag.contents:
if isinstance(c, str) and not self.name:
self.name = c
elif isinstance(c, str) and self.name:
self.aliases.append(c)
else:
if 'href' in c.attrs:
self.direct_url = c.attrs['href']
if isinstance(c.next, str):
self.name = c.next
else:
self.name = c.attrs['title']
elif c.name == 'sup':
self.related_url = c.next['href'].replace('#', '')
if c.parent.parent.parent.name == 'li':
self.aliases.append(c.parent.parent.parent.contents[0].next)
if self.related_url:
with suppress(KeyError):
self.related_url = reference_tags[self.related_url]
self.__normalize()
return self
|
#!/usr/bin/env python3
from collections import defaultdict
class CallCount:
"""
This module will return how many times
this module was called with same parameters
"""
def __init__(self):
self._count = defaultdict(int)
def __call__(self, argument):
self._count[argument] += 1
return self._count[argument]
|
#Dictionary is a key value pairs
p = {'apple':4,'banana':9,'orange':12,'pineapple':20}
print(p['apple']) #index
print(p['orange'])
print(p)
studentid = {
"1" : "Mehedi Amin",
"2" : "hassan",
"3" : "kamal",
}
print(studentid["1"])
|
# -*- coding: utf-8 -*-
from django.db import models
from django.conf import settings
# Create your models here.
class Character_sheet(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1)
name = models.CharField(max_length=40)
GENDER_CHOICES = (
('M', 'Mężczyzna'),
('F', 'Kobieta'),
)
gender = models.CharField(max_length=1, choices=GENDER_CHOICES, default='M')
RACE_CHOICES = (
('H', 'Człowiek'),
('O', 'Ork'),
('E', 'Elf'),
('D', 'Krasnolud'),
)
race = models.CharField(max_length=1, choices=RACE_CHOICES, default='H')
CLASS_CHOICES = (
('W', 'Wojownik'),
('R', 'Łotrzyk'),
('M', 'Mag'),
('C', 'Kusznik'),
)
class_x = models.CharField(max_length=1, choices=CLASS_CHOICES, default='W')
gold = models.IntegerField(default=1000)
def __unicode__(self):
return self.name
def __str__(self):
return self.name
class Equipment(models.Model):
name = models.CharField(max_length=40)
price = models.IntegerField(default=0)
WEAPON_TYPE_CHOICES = (
('M', 'Broń ręczna'),
('D', 'Broń zasięgowa'),
('A', 'Pancerz/Ubiór'),
('C', 'Użytkowy'),
)
weapon_type = models.CharField(max_length=1, choices=WEAPON_TYPE_CHOICES, default='C')
description = models.TextField(max_length=300)
owned_by = models.ManyToManyField(Character_sheet)
def __unicode__(self):
return self.name
def __str__(self):
return self.name
|
# Generated by Django 3.2.8 on 2021-10-30 23:31
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('pr_employee', '0002_alter_company_table'),
]
operations = [
migrations.RenameField(
model_name='employee',
old_name='first_name',
new_name='f_name',
),
migrations.RenameField(
model_name='employee',
old_name='last_name',
new_name='l_name',
),
migrations.RenameField(
model_name='employee',
old_name='middle_name',
new_name='m_name',
),
]
|
# -*- coding: utf-8 -*-
# Generated by Django 1.11.16 on 2019-07-11 17:21
from __future__ import unicode_literals
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
dependencies = [
('store', '0005_generalproduct_gp_description'),
]
operations = [
migrations.CreateModel(
name='MobiDetail',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('m_type', models.CharField(choices=[('SM', 'Smart Phone'), ('SP', 'Simple Phone'), ('TA', 'Tablet')], default='SM', max_length=2, verbose_name='type of mobile device')),
('m_os', models.CharField(max_length=60, verbose_name='OS')),
('m_cpu', models.CharField(max_length=60, verbose_name='CPU size')),
('m_size', models.CharField(max_length=60, verbose_name='size of item')),
('m_size_num', models.DecimalField(decimal_places=1, max_digits=3, verbose_name='size')),
('m_int_memory', models.CharField(max_length=60, verbose_name='internal memory')),
('m_storage', models.CharField(max_length=60, verbose_name='storage size')),
('m_storage_num', models.IntegerField(verbose_name='Storage Size')),
('m_has_wifi', models.BooleanField(default=True, verbose_name='Wifi Capable')),
('m_has_bluetooth', models.BooleanField(default=True, verbose_name='bluetooth Capable')),
('m_has_gps', models.BooleanField(default=True, verbose_name='GPS Capable')),
('m_simcard', models.CharField(choices=[('S', 'Single Sim'), ('D', 'Dual Sim')], default='S', max_length=1, verbose_name='sim type')),
('m_camera_px', models.IntegerField(verbose_name='camera pixels')),
('m_product', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='store.GeneralProduct')),
],
options={
'ordering': ['m_type'],
'verbose_name': 'Mobile Detail',
},
),
]
|
from unittest import TestCase, main
from ... import UndirectedGraph
class TestGetVertexWeight(TestCase):
def setUp(self) -> None:
self.g = UndirectedGraph(
edges={("a", "b"): 1, ("b", "c"): 2, ("e", "f"): 3},
vertices={"a": 10, "b": 20, "c": 30, "e": 40},
)
def test_get_weight(self) -> None:
self.assertEqual(self.g.get_vertex_weight("a"), 10, "Should get vertex weight.")
self.assertEqual(self.g.get_vertex_weight("b"), 20, "Should get vertex weight.")
self.assertEqual(self.g.get_vertex_weight("c"), 30, "Should get vertex weight.")
self.assertEqual(self.g.get_vertex_weight("e"), 40, "Should get vertex weight.")
self.assertEqual(self.g.get_vertex_weight("f"), 0, "Should get vertex weight.")
def test_invalid(self) -> None:
with self.assertRaises(
ValueError, msg="Should throw exception if vertex is invalid."
):
self.g.get_vertex_weight("w")
with self.assertRaises(
ValueError, msg="Should throw exception if vertex is invalid."
):
self.g.get_vertex_weight("vertex")
if __name__ == "__main__":
main()
|
# Generated by Django 2.2.2 on 2020-06-08 12:10
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('jazz', '0032_remove_lineup_date'),
]
operations = [
migrations.DeleteModel(
name='Lineup',
),
]
|
class Solution(object):
def largestRectangleArea(self, height):
# An O(n) algorithm. (Each element is pushed and popped into/from the
# stack at most once.)
# Add a sentinel to help with cleaning the stack.
height_with_sentinel = height[:] + [0]
max_area = 0
# Rectangles are pushed into the stack in height-ascending order. If a
# new rectangle is shorter than previous, it is merged with previous
# rectangle(s) until the merged rectangle is the highest. The stack is
# initialized with a sentinel element of negative height.
stack = [(-1, 0, 0)] # Element: (height, left boundary, right boundary)
for i in range(len(height_with_sentinel)):
h = height_with_sentinel[i]
if h > stack[-1][0]:
stack.append((h, i, i+1))
else: # h <= ... . Let's merge.
right_boundary = stack[-1][2]
# Pop elements and check if they can form a large enough area.
while True:
top = stack.pop()
# height*(right_boundary-left_boundary)
area = top[0] * (right_boundary - top[1])
if area > max_area:
max_area = area
if stack[-1][0] < h:
break
# Push the merged rectangle
stack.append((h, top[1], i+1))
return max_area
def test():
f = Solution().largestRectangleArea
assert f([2,1,5,6,2,3]) == 10
assert f([2,1,5,6,5,2,3]) == 15
assert f([2,1,5,6,4,2,3]) == 12
assert f([2,1,5,6,4,2,3,5,6,7]) == 16
assert f([2,1,5,6,4,2,3,6,6,7]) == 18
assert f([]) == 0
assert f([2]) == 2
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.