text stringlengths 8 6.05M |
|---|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__version__ = '1.0.1'
get_notification_type_list_query = """
SELECT *
FROM public.notification_type AS nt
WHERE nt.deleted is FALSE
AND nt.active is TRUE
AND (
$1::VARCHAR is NULL OR
nt.name ILIKE $1::VARCHAR || '%' OR
nt.name ILIKE '%' || $1::VARCHAR || '%' OR
nt.name ILIKE $1::VARCHAR || '%')
"""
|
# -*- coding: utf-8 -*-
##############################################################################
#
# OpenERP, Open Source Management Solution
# Copyright (C) 2015 DevIntelle Consulting Service Pvt.Ltd (<http://www.devintellecs.com>).
#
# For Module Support : devintelle@gmail.com or Skype : devintelle
#
##############################################################################
from odoo import models,api, fields
import base64
import xlrd
from datetime import datetime
class import_loan(models.TransientModel):
_name = "import.loan"
_description = 'import_loan'
file_type = fields.Selection([('excel','Excel'),('csv','CSV')],string='Tipo de archivo', default='csv')
csv_file = fields.Binary(string='Archivo')
@api.multi
def get_employee_id(self,name):
emp_id = self.env['hr.employee'].search([('name','=',name)],limit=1)
if emp_id:
return emp_id
else:
return False
@api.multi
def get_loan_type(self,name):
type_id = self.env['employee.loan.type'].search([('name','=',name)],limit=1)
if type_id:
return type_id
else:
return False
@api.multi
def add_in_remark(self,remark,coment):
if remark:
remark += ' , '+ coment
else:
remark = coment
return remark
@api.multi
def get_check_employee_loan(self,employee_id):
now = datetime.now()
year = now.year
s_date = str(year)+'-01-01'
e_date = str(year)+'-12-01'
loan_ids = self.env['employee.loan'].search([('employee_id','=',employee_id.id),('date','<=',e_date),('date','>=',s_date)])
return len(loan_ids)
@api.multi
def import_loan(self):
lines =[]
if self.file_type == 'csv':
file_data = base64.decodestring(self.csv_file)
csv_data = str(file_data.decode("utf-8"))
csv_data = csv_data.split('\n')
for csv_line in csv_data:
if csv_line:
lines.append(csv_line.split(','))
lines.pop(0)
else:
file_datas = base64.decodestring(self.csv_file)
workbook = xlrd.open_workbook(file_contents=file_datas)
sheet = workbook.sheet_by_index(0)
lines = [[sheet.cell_value(r, c) for c in range(sheet.ncols)] for r in range(sheet.nrows)]
lines.pop(0)
count = 1
logs = ''
for line in lines:
count += 1
remark =''
employee_id = self.get_employee_id(line[0])
if not employee_id:
remark = self.add_in_remark(remark,'Employee')
else:
emp_loan = self.get_check_employee_loan(employee_id)
if emp_loan >= employee_id.loan_request:
remark = self.add_in_remark(remark,'Employee Can not create more then '+ str(employee_id.loan_request))+' Loans'
manager_id = self.get_employee_id(line[1])
if not manager_id:
remark = self.add_in_remark(remark,'Departnent Manager')
loan_type_id = self.get_loan_type(line[3])
if not loan_type_id:
remark = self.add_in_remark(remark,'Loan type')
if not remark:
res ={
'employee_id':employee_id.id,
'manager_id':manager_id.id,
'job_id':employee_id.job_id and employee_id.job_id.id or False,
'department_id':employee_id.department_id and employee_id.department_id.id or False,
'payment_method':'by_payslip',
'loan_amount':line[2],
'loan_type_id':loan_type_id.id,
'start_date':line[4],
'term':loan_type_id.loan_term,
'interest_rate':loan_type_id.interest_rate,
'interest_type':loan_type_id.interest_type,
'notes':line[5],
}
self.env['employee.loan'].create(res)
else:
remark = 'Line No:'+str(count)+' '+remark+' Not Match \n'
logs += remark
if logs:
log_id=self.env['import.logs'].create({'name':logs})
return {
'view_mode': 'form',
'res_id': log_id.id,
'res_model': 'import.logs',
'view_type': 'form',
'type': 'ir.actions.act_window',
'target': 'new',
}
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:
|
import pandas as pd
import csv
original_csv = pd.read_csv('./Fuzzy_dataset.csv')
normal_csv = open('./fuzzy_normal_dataset.csv', 'w', newline='', encoding='utf-8')
normal_csv_file = csv.writer(normal_csv)
abnormal_csv = open('./fuzzy_abnormal_dataset.csv', 'w', newline='', encoding='utf-8')
abnormal_csv_file = csv.writer(abnormal_csv)
idx = 0
normal_first = False
abnormal_first = False
while idx < len(original_csv) // 30:
original_row = original_csv.iloc[idx]
number_of_data = original_row[2]
is_regular = (original_row[number_of_data + 3] == 'R')
original_row.dropna(inplace=True)
if is_regular:
if not normal_first and number_of_data != 8:
idx += 1
continue
normal_first = True
normal_csv_file.writerow(original_row[1:])
else:
if not abnormal_first and number_of_data != 8:
idx += 1
continue
abnormal_first = True
abnormal_csv_file.writerow(original_row[1:])
idx += 1
if idx % 500000 == 0:
print(idx) |
'''VoidFinder - Hoyle & Vogeley (2002)'''
################################################################################
#
# IMPORT MODULES
#
################################################################################
import sys
sys.path.insert(1, '/home/oneills2/VoidFinder/python/')
#sys.path.insert(1, '/Users/kellydouglass/Documents/Research/VoidFinder/python/')
from voidfinder import filter_galaxies, find_voids
from voidfinder.absmag_comovingdist_functions import Distance
from astropy.table import Table
import pickle
import numpy as np
################################################################################
#
# USER INPUTS
#
################################################################################
# Number of CPUs available for analysis
num_cpus = 4
#-------------------------------------------------------------------------------
survey_name = 'SDSS_dr12n_'
# File header
in_directory = '/home/oneills2/VoidFinder/python/voidfinder/data/'
out_directory = '/home/oneills2/VoidFinder/python/voidfinder/data/'
# Input file names
galaxies_filename = 'dr12n.dat' # File format: RA, dec, redshift, comoving distance, absolute magnitude
#mask_filename = 'cbpdr7mask.dat' # File format: RA, dec
mask_filename = 'dr12n_mask.pickle'
in_filename = in_directory + galaxies_filename
mask_filename = in_directory + mask_filename
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
# Survey parameters
determine_parameters = False
min_dist = 1085.0
max_dist = 1755.0 # z = 0.107 -> 313 h-1 Mpc z = 0.087 -> 257 h-1 Mpc
# Cosmology
Omega_M = 0.3
h = 1
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
# Remove faint galaxies?
mag_cut = True
# Remove isolated galaxies?
rm_isolated = True
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
# Output file names
if mag_cut and rm_isolated:
out1_suffix = '_maximal.txt'
out2_suffix = '_holes.txt'
elif rm_isolated:
out1_suffix = '_maximal_noMagCut.txt'
out2_suffix = '_holes_noMagCut.txt'
elif mag_cut:
out1_suffix = '_maximal_keepIsolated.txt'
out2_suffix = '_holes_keepIsolated.txt'
else:
out1_suffix = '_maximal_noFiltering.txt'
out2_suffix = 'holes_noFiltering.txt'
out1_filename = out_directory + galaxies_filename[:-4] + out1_suffix # List of maximal spheres of each void region: x, y, z, radius, distance, ra, dec
out2_filename = out_directory + galaxies_filename[:-4] + out2_suffix # List of holes for all void regions: x, y, z, radius, flag (to which void it belongs)
#out3_filename = out_directory + 'out3_vollim_dr7.txt' # List of void region sizes: radius, effective radius, evolume, x, y, z, deltap, nfield, vol_maxhole
#voidgals_filename = out_directory + 'vollim_voidgals_dr7.txt' # List of the void galaxies: x, y, z, void region
#-------------------------------------------------------------------------------
################################################################################
#
# OPEN FILES
#
################################################################################
infile = Table.read(in_filename, format='ascii.commented_header')
#maskfile = Table.read(mask_filename, format='ascii.commented_header')
#maskfile = np.load(mask_filename)
mask_infile = open(mask_filename, 'rb')
mask_resolution, maskfile = pickle.load(mask_infile)
mask_infile.close()
#-------------------------------------------------------------------------------
# Print min and max distances
if determine_parameters:
# Minimum distance
min_z = min(infile['z'])
# Maximum distance
max_z = max(infile['z'])
# Convert redshift to comoving distance
dist_limits = Distance([min_z, max_z], Omega_M, h)
print('Minimum distance =', dist_limits[0], 'Mpc/h')
print('Maximum distance =', dist_limits[1], 'Mpc/h')
exit()
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
# Rename columns
if 'rabsmag' not in infile.columns:
infile['magnitude'].name = 'rabsmag'
#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------
# Calculate comoving distance
if 'Rgal' not in infile.columns:
infile['Rgal'] = Distance(infile['z'], Omega_M, h)
#-------------------------------------------------------------------------------
################################################################################
#
# FILTER GALAXIES
#
################################################################################
coord_min_table, mask, ngrid = filter_galaxies(infile, maskfile, mask_resolution,
min_dist, max_dist, survey_name,
mag_cut, rm_isolated)
temp_outfile = open("filter_galaxies_output.pickle", 'wb')
pickle.dump((coord_min_table, mask, ngrid), temp_outfile)
temp_outfile.close()
################################################################################
#
# FIND VOIDS
#
################################################################################
temp_infile = open("filter_galaxies_output.pickle", 'rb')
coord_min_table, mask, ngrid = pickle.load(temp_infile)
temp_infile.close()
find_voids(ngrid, min_dist, max_dist, coord_min_table, mask, mask_resolution,
out1_filename, out2_filename, survey_name, num_cpus)
|
import subprocess
from functools import lru_cache
import ffmpeg
from audiotsm import phasevocoder
from audiotsm.io.wav import WavReader, WavWriter
from scipy.io import wavfile
import numpy as np
import math
from shutil import copyfile, rmtree
import os
import argparse
from pytube import YouTube
from toolz import first
class AudioInfo:
sample_rate = None
audio_data = None
def __init__(self,sample_rate, audio_data, frame_rate):
self.sample_rate = sample_rate
self.frame_rate = frame_rate
self.audio_data = audio_data
@property
def audio_sample_count(self): return self.audio_data.shape[0]
@property
def max_audio_volume(self): return get_max_volume(self.audio_data)
@property
def samples_per_frame(self): return self.sample_rate / self.frame_rate
@property
def audio_frame_count(self): return int(math.ceil(self.audio_sample_count / self.samples_per_frame))
class Config:
def __init__(self,
frame_rate,
sample_rate,
silent_threshold,
frame_spread,
new_speed,
url,
frame_quality,
input_file,
output_file,
):
self.frame_rate = frame_rate
self.sample_rate = sample_rate
self.silent_threshold = silent_threshold
self.frame_spread = frame_spread
self.new_speed = new_speed or []
self.url = url
self.frame_quality = frame_quality
self.input_file = input_file
self.output_file = output_file
self.temp_folder = "TEMP"
self.audio_fade_envelope_size = 400 # smooth out transitiion's audio by quickly fading in/out (arbitrary magic number whatever)
@staticmethod
def from_args(args):
return Config(
args.frame_rate,
args.sample_rate,
args.silent_threshold,
args.frame_margin,
(args.silent_speed, args.sounded_speed),
args.url,
args.frame_quality,
args.input_file if not args.url else download_file(args.url),
args.output_file if len(args.output_file) >= 1 else input_to_output_filename(args.input_file)
)
def download_file(url):
name = YouTube(url).streams.first().download()
new_name = name.replace(' ', '_')
os.rename(name, new_name)
return new_name
def get_max_volume(s):
maxv = np.max(s)
minv = np.min(s)
return max(maxv, -minv)
def copy_frame(input_frame, output_frame):
src = f"{conf.temp_folder}/frame{input_frame + 1:06d}.jpg"
dst = f"{conf.temp_folder}/newFrame{output_frame + 1:06d}.jpg"
if not os.path.isfile(src):
return False
copyfile(src, dst)
if output_frame % 20 == 19:
print(f"{output_frame + 1} time-altered frames saved.")
return True
def input_to_output_filename(file_name):
dot_index = file_name.rfind(".")
return f"{file_name[:dot_index]}_ALTERED{file_name[dot_index:]}"
def create_path(s):
# assert (not os.path.exists(s)), "The filepath "+s+" already exists. Don't want to overwrite it. Aborting."
try:
os.mkdir(s)
except OSError:
assert False, "Creation of the directory %s failed. (The TEMP folder may already exist. Delete or rename it, and try again.)"
def delete_path(s): # Dangerous! Watch out!
try:
rmtree(s, ignore_errors=False)
except OSError:
print("Deletion of the directory %s failed" % s)
print(OSError)
def parse_args():
parser = argparse.ArgumentParser(
description='Modifies a video file to play at different speeds when there is sound vs. silence.')
parser.add_argument('--input_file', type=str, help='the video file you want modified')
parser.add_argument('--url', type=str, help='A youtube url to download and process')
parser.add_argument('--output_file', type=str, default="",
help="the output file. (optional. if not included, it'll just modify the input file name)")
parser.add_argument('--silent_threshold', type=float, default=0.03,
help="the volume amount that frames' audio needs to surpass to be consider \"sounded\". It ranges from 0 (silence) to 1 (max volume)")
parser.add_argument('--sounded_speed', type=float, default=1.00,
help="the speed that sounded (spoken) frames should be played at. Typically 1.")
parser.add_argument('--silent_speed', type=float, default=5.00,
help="the speed that silent frames should be played at. 999999 for jumpcutting.")
parser.add_argument('--frame_margin', type=float, default=1,
help="some silent frames adjacent to sounded frames are included to provide context. How many frames on either the side of speech should be included? That's this variable.")
parser.add_argument('--sample_rate', type=float, default=44100, help="sample rate of the input and output videos")
parser.add_argument('--frame_rate', type=float, default=30,
help="frame rate of the input and output videos. optional... I try to find it out myself, but it doesn't always work.")
parser.add_argument('--frame_quality', type=int, default=3,
help="quality of frames to be extracted from input video. 1 is highest, 31 is lowest, 3 is the default.")
return parser.parse_args()
conf = Config.from_args(parse_args())
delete_path(conf.temp_folder)
create_path(conf.temp_folder)
def ffmpeg_get_frame_rate():
probe = ffmpeg.probe(conf.input_file)
frame_rate_str = first(filter(lambda x: x['codec_type'] == 'video', probe['streams'])).get('avg_frame_rate')
if frame_rate_str:
l, r = frame_rate_str.split('/')
return int(l) / int(r)
def ffmpeg_scale():
return ffmpeg.input(conf.input_file).output(f'{conf.temp_folder}/frame%06d.jpg', **{'qscale:v': 3}).run()
def ffmpeg_extract_audio():
return ffmpeg.input(conf.input_file).audio.output(f'{conf.temp_folder}/audio.wav', ab='160k', ac=2, ar=conf.sample_rate).run()
ffmpeg_scale()
ffmpeg_extract_audio()
@lru_cache()
def get_audio_info(path, frame_rate=None) -> AudioInfo:
return AudioInfo(*wavfile.read(path), frame_rate or ffmpeg_get_frame_rate())
ai = get_audio_info(f"{conf.temp_folder}/audio.wav")
def get_loud_samples(audio_info: AudioInfo):
has_loud_audio = np.zeros((audio_info.audio_frame_count,))
for i in range(audio_info.audio_frame_count):
start = int(i * audio_info.samples_per_frame)
end = min(int((i + 1) * audio_info.samples_per_frame), audio_info.audio_sample_count)
audio_chunks = audio_info.audio_data[start:end]
max_chunks_volume = float(get_max_volume(audio_chunks)) / audio_info.max_audio_volume
if max_chunks_volume >= conf.silent_threshold:
has_loud_audio[i] = 1
return has_loud_audio
def get_chunks(audio_info: AudioInfo, loud_samples):
chunks = [[0, 0, 0]]
should_include_frame = np.zeros((audio_info.audio_frame_count,))
for i in range(audio_info.audio_frame_count):
start = int(max(0, i - conf.frame_spread))
end = int(min(audio_info.audio_frame_count, i + 1 + conf.frame_spread))
should_include_frame[i] = np.max(loud_samples[start:end])
if i >= 1 and should_include_frame[i] != should_include_frame[i - 1]: # Did we flip?
chunks.append([chunks[-1][1], i, should_include_frame[i - 1]])
chunks.append([chunks[-1][1], audio_info.audio_frame_count, should_include_frame[audio_info.audio_frame_count - 1]])
return chunks[1:]
output_audio_data = np.zeros((0, ai.audio_data.shape[1]))
output_pointer = 0
last_existing_frame = None
for chunk in get_chunks(ai, get_loud_samples(ai)):
audioChunk = ai.audio_data[int(chunk[0] * ai.samples_per_frame):int(chunk[1] * ai.samples_per_frame)]
sFile = f"{conf.temp_folder}/tempStart.wav"
eFile = f"{conf.temp_folder}/tempEnd.wav"
wavfile.write(sFile, conf.sample_rate, audioChunk)
with WavReader(sFile) as reader:
with WavWriter(eFile, reader.channels, reader.samplerate) as writer:
tsm = phasevocoder(reader.channels, speed=conf.new_speed[int(chunk[2])])
tsm.run(reader, writer)
_, altered_audio_data = wavfile.read(eFile)
leng = altered_audio_data.shape[0]
end_pointer = output_pointer + leng
output_audio_data = np.concatenate((output_audio_data, altered_audio_data / ai.max_audio_volume))
if leng < conf.audio_fade_envelope_size:
output_audio_data[output_pointer:end_pointer] = 0 # audio is less than 0.01 sec, let's just remove it.
else:
pre_mask = np.arange(conf.audio_fade_envelope_size) / conf.audio_fade_envelope_size
mask = np.repeat(pre_mask[:, np.newaxis], 2, axis=1) # make the fade-envelope mask stereo
output_audio_data[output_pointer:output_pointer + conf.audio_fade_envelope_size] *= mask
output_audio_data[end_pointer - conf.audio_fade_envelope_size:end_pointer] *= 1 - mask
start_output_frame = int(math.ceil(output_pointer / ai.samples_per_frame))
endOutputFrame = int(math.ceil(end_pointer / ai.samples_per_frame))
for output_frame in range(start_output_frame, endOutputFrame):
input_frame = int(chunk[0] + conf.new_speed[int(chunk[2])] * (output_frame - start_output_frame))
didItWork = copy_frame(input_frame, output_frame)
if didItWork:
last_existing_frame = input_frame
else:
copy_frame(last_existing_frame, output_frame)
output_pointer = end_pointer
wavfile.write(f"{conf.temp_folder}/audioNew.wav", conf.sample_rate, output_audio_data)
'''
output_frame = math.ceil(output_pointer/samples_per_frame)
for endGap in range(output_frame,audio_frame_count):
copyFrame(int(audio_sample_count/samples_per_frame)-1,endGap)
'''
command = f"ffmpeg -framerate {conf.frame_rate} -i {conf.temp_folder}/newFrame%06d.jpg -i {conf.temp_folder}/audioNew.wav -strict -2 {conf.output_file}"
subprocess.call(command, shell=True)
|
# Copyright 2021 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from native import name
if __name__ == "__main__":
print(f"Hello {name.get_name()}")
|
from flask_sqlalchemy import SQLAlchemy
from flask_login import UserMixin
from passlib.hash import bcrypt
db = SQLAlchemy()
# User class
class User(UserMixin, db.Model):
# single fields
id = db.Column(db.Integer, primary_key=True)
first = db.Column(db.String(127), nullable=False)
last = db.Column(db.String(127), nullable=False)
email = db.Column(db.String(127), unique=True, nullable=False)
password = db.Column(db.String(127), nullable=False)
email_consent = db.Column(db.Boolean, nullable=False, default=False)
# basic init
def __init__(self, first: str, last: str, email: str, password: str, consent: bool):
self.first = first
self.last = last
self.email = email
self.password = bcrypt.encrypt(password)
self.consent = consent
def validate_password(self, password):
return bcrypt.verify(password, self.password)
def __repr__(self):
return '<User %r>' % self.email
def __str__(self):
return '<User %r>' % self.email
|
from setuptools import setup, find_packages
import os
name = "piecemaker"
version = "0.0.1"
def read(*rnames):
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()
setup(
name=name,
version=version,
author='Jake Hickenlooper',
author_email='jake@weboftomorrow.com',
description="Create jigsaw puzzle pieces from an image",
long_description=read('README.rst'),
url='https://github.com/jkenlooper/piecemaker',
classifiers=[
'Development Status :: 2 - Pre-Alpha',
'Intended Audience :: Developers',
'License :: OSI Approved :: GNU General Public License v3 or later (GPLv3+)',
'Natural Language :: English',
'Operating System :: POSIX',
'Programming Language :: Python :: 2.6',
'Topic :: Software Development :: Build Tools',
],
package_dir={'': 'src'},
packages=find_packages('src'),
zip_safe=False,
install_requires=[
'Pillow == 1.7.8',
'pixsaw',
'beautifulsoup4',
'svgwrite',
'html',
'glue',
],
entry_points="""
[console_scripts]
piecemaker = piecemaker.script:piecemaker
""",
)
|
from bot import *
import requests
CONST_URL = "https://api.telegram.org/bot708914610:AAFtLSerk5aw-72yKKvljZbrrRSmd4yHV8I/"
from time import sleep
#admin id 60201964
class functional:
def __init__(self):
self.bot = bot()
def send_message(self, id, message):
bot.send_message( id, message)
send_message(60201964, 'ты админ?')
def get_updates_json(self,request):
params = {'timeout': 100, 'offset': None}
response = requests.get(request + 'getUpdates', data=params)
return response.json()
def get_chat_id(self,update):
chat_id = update['message']['chat']['id']
return chat_id
def last_update(self,data):
results = data['result']
total_updates = len(results) - 1
return results[total_updates]
def get_chat_text(self,update):
chat_text = update['message']['text']
return chat_text
def send_mess(self,chat, text):
params = {'chat_id': chat, 'text': text}
response = requests.post(CONST_URL + 'sendMessage', data=params)
return response
def send_mess_all(self,id_list, text):
for id in id_list:
params = {'chat_id': id, 'text': text}
response = requests.post(CONST_URL + 'sendMessage', data=params) |
# coding: utf-8
#geling修改注释 20180421
#liuyubiao修改策略输出为多策略输出
import numpy as np
import pprint
import sys
import PolicyEvaluationSolution
if "../" not in sys.path:
sys.path.append("../")
from lib.envs.gridworld import GridworldEnv
# 进行多策略的输出
# 定义两个全局变量用来记录运算的次数
v_num = 1
i_num = 1
# 根据传入的四个行为选择值函数最大的索引,返回的是一个索引数组和一个行为策略
def get_max_index(action_values):
indexs = []
policy_arr = np.zeros(len(action_values))
action_max_value = np.max(action_values)
for i in range(len(action_values)):
action_value = action_values[i]
if action_value == action_max_value:
indexs.append(i)
policy_arr[i] = 1
return indexs,policy_arr
# 将策略中的每行可能行为改成元组形式,方便对多个方向的表示
def change_policy(policys):
action_tuple = []
for policy in policys:
indexs, policy_arr = get_max_index(policy)
action_tuple.append(tuple(indexs))
return action_tuple
#policy_improvement是策略迭代方法,输入为环境env,策略评估函数policy_eval_,折扣因子。输出为最优值函数和最优策略
# policy_eval_fn=PolicyEvaluationSolution.policy_eval表示对PolicyEvaluationSolution文件的policy_eval方法进行调用。
def policy_improvement(env, policy_eval_fn=PolicyEvaluationSolution.policy_eval, discount_factor=1.0):
"""
Policy Improvement Algorithm. Iteratively evaluates and improves a policy
until an optimal policy is found.
Args:
env: The OpenAI envrionment.
policy_eval_fn: Policy Evaluation function that takes 3 arguments:
policy, env, discount_factor.
discount_factor: gamma discount factor.
Returns:
A tuple (policy, V).
policy is the optimal policy, a matrix of shape [S, A] where each state s
contains a valid probability distribution over actions.
V is the value function for the optimal policy.
"""
# 初始化一个随机策略
policy = np.ones([env.nS, env.nA]) / env.nA
print("初始的随机策略")
print(policy)
print("*"*50)
while True:
global i_num
global v_num
v_num = 1
# 评估当前的策略,输出为各状态的当前的状态值函数
V = policy_eval_fn(policy, env, discount_factor)
print("第%d次策略提升时求出的各状态值函数"%i_num)
print(V)
print("")
# 定义一个当前策略是否改变的标识
policy_stable = True
# 遍历各状态
for s in range(env.nS):
# 取出当前状态下最优行为的索引值
chosen_a = np.argmax(policy[s])
# 初始化行为数组[0,0,0,0]
action_values = np.zeros(env.nA)
for a in range(env.nA):
# 遍历各行为
for prob, next_state, reward, done in env.P[s][a]:
# 根据各状态值函数求出行为值函数
action_values[a] += prob * (reward + discount_factor * V[next_state])
# v1.0版更新内容,因为np.argmax(action_values)只会选取第一个最大值出现的索引,所以会丢掉其他方向的可能性,现在会输出一个状态下所有的可能性
best_a_arr, policy_arr = get_max_index(action_values)
# 如果求出的最大行为值函数的索引(方向)没有改变,则定义当前策略未改变,收敛输出
# 否则将当前的状态中将有最大行为值函数的方向置1,其余方向置0
if chosen_a not in best_a_arr:
policy_stable = False
policy[s] = policy_arr
print("第%d次策略提升结果"%i_num)
print(policy)
print("*"*50)
i_num = i_num + 1
# 如果当前策略没有发生改变,即已经到了最优策略,返回
if policy_stable:
print("第%d次之后得到的结果已经收敛,运算结束"%(i_num-1))
return policy, V
env = GridworldEnv()
policy, v = policy_improvement(env)
print("策略可能的方向值:")
print(policy)
print("")
print("策略网格形式 (0=up, 1=right, 2=down, 3=left):")
# v1.0版本修改:现在输出同一个状态下会有多个最优行为,而argmax只会选取第一个进行,所以需要修改
# print(np.reshape(np.argmax(policy, axis=1), env.shape))
update_policy_type = change_policy(policy)
print(np.reshape(update_policy_type, env.shape))
print("")
print("值函数:")
print(v)
print("")
print("值函数的网格形式:")
print(v.reshape(env.shape))
print("")
# 验证最终求出的值函数符合预期
expected_v = np.array([-4, -3, -2, -1, -2, -3, -2, -1, 0, -1, -4, -3, -2, -1, -2, -5, -4, -3, -2, -3, -6, -5, -4, -3, -4])
np.testing.assert_array_almost_equal(v, expected_v, decimal=2)
|
""" This is a script showing how to use os to get the names of subdirectories and files started with specific letter"""
import subprocess
import os
import sys
"""define main function"""
def main(argv):
# Use the subprocess.os module to get a list of files and directories
# in your ubuntu home directory
# Hint: look in subprocess.os and/or subprocess.os.path and/or
# subprocess.os.walk for helpful functions
#################################
#~Get a list of files and
#~directories in your home/ that start with an uppercase 'C'
# Type your code here:
# Get the user's home directory.
home = subprocess.os.path.expanduser("~")
# Create a list to store the results.
FilesDirsStartingWithC = []
# Use a for loop to walk through the home directory.
for (dirs, subdirs, files) in subprocess.os.walk(home):
FilesDirsStartingWithC += [subdir for subdir in subdirs if subdir.startswith("C")]
FilesDirsStartingWithC += [file for file in files if file.startswith("C")]
# for subdir in subdirs:
# if subdir[0] == 'C':
# FilesDirsStartingWithC.append(subdir)
# for file in files:
# if files[0] == 'C':
# FilesDirsStartingWithC.append(file)
print(FilesDirsStartingWithC)
#################################
# Get files and directories in your home/ that start with either an
# upper or lower case 'C'
# Type your code here:
home = subprocess.os.path.expanduser("~")
FilesDirsStartingWithCc = []
for (dirs, subdirs, files) in subprocess.os.walk(home):
# for subdir in subdirs:
# if subdir.lower().startswith("c"):
# FilesDirsStartingWithCc.append(subdir)
# for f in files:
# if f.lower().startswith("c"):
# FilesDirsStartingWithCc.append(f)
FilesDirsStartingWithCc += [subdir for subdir in subdirs if subdir.lower().startswith("c")]
FilesDirsStartingWithCc += [f for f in files if f.lower().startswith("c")]
print(FilesDirsStartingWithCc)
#################################
# Get only directories in your home/ that start with either an upper or
#~lower case 'C'
# Type your code here:
home = subprocess.os.path.expanduser("~")
DirsStartingWithCc = []
for (dirs, subdirs, files) in subprocess.os.walk(home):
DirsStartingWithCc += [subdir for subdir in subdirs if subdir.lower().startswith("c")]
print(DirsStartingWithCc)
if __name__ == "__main__":
status = main(sys.argv)
sys.exit(status)
|
# coding=utf-8
import sys,os
from time import sleep
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException, NoAlertPresentException
from selenium.webdriver.support.ui import Select
import win32com.server.util, win32com.client
sys.path.append(os.environ.get('PY_DEV_HOME'))
from webTest_pro.common.initData import init
import SendKeys
import win32con
import win32api
import time
reload(sys)
sys.setdefaultencoding("utf-8")
base_url = init.base_url
loginInfo =init.loginInfo
def admin_login(driver):
"""
administrator login
Args: web driver
-
Usage: admin_login(driver)
"""
# open url
driver.get(base_url + "/middleclient/index.do")
driver.maximize_window()
# select platform and login
driver.find_element_by_id('s_username').clear()
driver.find_element_by_id('s_username').send_keys('administrator')
driver.find_element_by_id('s_password').clear()
driver.find_element_by_id('s_password').send_keys('xungejiaoyu')
# click login btn
sleep(0.5)
driver.find_element_by_name('submit').click()
sleep(0.5)
def user_login(driver, **kwargs):
"""
Func desc
Args:
-
Usage:
"""
print "loginfo:\nuser:{0},platform:{1}".format(kwargs['username'],
kwargs['platformname'])
# open url
driver.get(base_url + "/middleclient/index.do")
driver.maximize_window()
driver.refresh()
# select platform and login
Select(driver.find_element_by_id("platform")).select_by_visible_text(
kwargs['platformname'])
driver.find_element_by_id('s_username').clear()
driver.find_element_by_id('s_username').send_keys(kwargs['username'])
driver.find_element_by_id('s_password').clear()
driver.find_element_by_id('s_password').send_keys('111111')
# click login btn
driver.find_element_by_name('submit').click()
sleep(0.5)
def add_tenants(driver, **kwargs):
"""
添加租户
Args:administrator operate
-
Usage: add_tenants(driver)
"""
print "add tenant info: 河南教育局"
try:
driver.refresh()
driver.find_element_by_link_text(u"系统管理").click()
driver.find_element_by_link_text(u"租户管理").click()
sleep(0.5)
driver.find_element_by_css_selector("i.fa.fa-plus").click()
sleep(0.5)
driver.find_element_by_css_selector(
"#areaId > div.col-sm-9 > input.form-control").click()
sleep(2)
# driver.find_element_by_xpath("//div[@id='treeview']/ul/li[17]").click()
driver.find_element_by_xpath(kwargs["areaid"]).click()
sleep(2)
# driver.find_element_by_css_selector("div.modal-content > div.text-center > button.btn.btn-end").click()
driver.find_element_by_xpath(
"//*[@id='treeviews']/div/div/div[2]/button[1]").click()
sleep(1)
driver.find_element_by_css_selector(
"#platmarkName > div.col-sm-9 > input.form-control").clear()
# driver.find_element_by_css_selector("#platmarkName > div.col-sm-9 > input.form-control").send_keys(u"河南教育局")
driver.find_element_by_css_selector(
"#platmarkName > div.col-sm-9 > input.form-control").send_keys(
kwargs["platmarkName"])
driver.find_element_by_css_selector(
"#platmarkCode > div.col-sm-9 > input.form-control").clear()
# driver.find_element_by_css_selector("#platmarkCode > div.col-sm-9 > input.form-control").send_keys("001")
driver.find_element_by_css_selector(
"#platmarkCode > div.col-sm-9 > input.form-control").send_keys(
kwargs["platmarkCode"])
sleep(1)
driver.find_element_by_id("submit").click()
sleep(1)
print "add tenant 河南教育局 end."
except Exception as e:
print e
print "修改:%s 失败。" % kwargs['platmarkName']
# schools = [{'schoolName': u'二中', 'schoolType': u'高中', 'schoolArea': u'郑州市'},
# {'schoolName': u'三中', 'schoolType': u'中学', 'schoolArea': u'郑州市'},
# {'schoolName': u'四中', 'schoolType': u'中学', 'schoolArea': u'开封市'},
# {'schoolName': u'五中', 'schoolType': u'小学', 'schoolArea': u'开封市'},
# {'schoolName': u'六中', 'schoolType': u'小学', 'schoolArea': u'开封市'},
# {'schoolName': u'一中', 'schoolType': u'高中', 'schoolArea': u'郑州市'}]
schools = [{
'schoolName': u'二中',
'schoolType': u'高中',
'schoolArea': u'郑州市'
}, {
'schoolName': u'三中',
'schoolType': u'中学',
'schoolArea': u'郑州市'
}]
def add_schools(driver, **kwargs):
"""
Func desc
Args:
-
Usage:
"""
# para:schoolName,schoolType,schoolArea
'''添加学校'''
print "添加学校信息:{0},{1},{2}".format(
kwargs['schoolName'], kwargs['schoolType'], kwargs['schoolArea'])
driver.refresh()
driver.find_element_by_link_text(u"系统管理").click()
driver.find_element_by_link_text(u"学校管理").click()
# select area
driver.find_element_by_id("choosearea").click()
sleep(1)
driver.find_element_by_xpath("//div[@id='treeview']/ul/li").click()
driver.find_element_by_css_selector(
"div.col-sm-9.text-center > #submit").click()
sleep(1)
# 添加学校btn
driver.find_element_by_xpath("//*[@id='addSchool']").click()
sleep(1)
# 输入学校
driver.find_element_by_xpath("//*[@id='schoolName']/div/input").clear()
driver.find_element_by_xpath("//*[@id='schoolName']/div/input").send_keys(
kwargs['schoolName'])
# 选择学校类型
Select(driver.find_element_by_css_selector(
"select.form-control")).select_by_visible_text(kwargs['schoolType'])
# 学校选择区域
# Select(driver.find_element_by_xpath("//div[@id='areaSelect']/select[2]")).select_by_visible_text(kwargs['schoolArea'])
# //div[@id='schoolTypeId']/div/select
# click确定
driver.find_element_by_xpath("//button[@id='submit']").click()
# self.assertEqual(u"添加成功!", driver.find_element_by_css_selector(".layui-layer-content").text)
sleep(2)
print "添加:%s 成功。" % kwargs['schoolName']
# print "添加:%s 失败。" % kwargs['schoolName']
classromms = [{
'className': '31className',
'classAccNumber': '1'
}, {
'className': '32className',
'classAccNumber': '1'
}]
def add_classrooms(driver, **kwargs):
"""
添加教室组
Args:
-
Usage:
"""
# para:
print "add info:{0},{1}".format(kwargs['className'],
kwargs['classAccNumber'])
# refresh main page
try:
driver.refresh()
# goto test page
driver.find_element_by_link_text(u"系统管理").click()
driver.find_element_by_link_text(u"学校管理").click()
sleep(1)
# click add btn
driver.find_element_by_css_selector(u"a[title=\"添加教室\"] > span").click(
)
sleep(0.5)
# operation
driver.find_element_by_css_selector(
"#className > div.col-sm-9 > input.form-control").clear()
driver.find_element_by_css_selector(
"#className > div.col-sm-9 > input.form-control").send_keys(kwargs[
'className'])
driver.find_element_by_css_selector(
"#classAccNumber > div.col-sm-9 > input.form-control").clear()
driver.find_element_by_css_selector(
"#classAccNumber > div.col-sm-9 > input.form-control").send_keys(
kwargs['classAccNumber'])
# click 确定
driver.find_element_by_xpath("(//button[@id='submit'])[3]").click()
# driver.find_element_by_css_selector(
# "css=#classroommodal > div.modal-dialog > div.modal-content > form.form-horizontal > div.modal-body.row > div.form-group > div.col-sm-9 > #submit")
sleep(1)
print "add {} end.".format(kwargs['className'])
except Exception as e:
print e
print "add {} failed.".format(kwargs['className'])
integrateds = [{
'className': '32className',
'equipment_name': '81lb',
'ipAddr': '10.1.0.81',
'locAddr': '10.1.0.81',
'equipmentLogName': 'admin',
'equipmentLogPwd': 'admin'
}, {
'className': '31className',
'equipment_name': '82lb',
'ipAddr': '10.1.0.82',
'locAddr': '10.1.0.81',
'equipmentLogName': 'admin',
'equipmentLogPwd': 'admin'
}]
terminals = [{
'equipmentModel': u'Group系列',
'className': u'81教室',
'equipment_name': '81lb',
'ipAddr': '10.1.0.81',
'locAddr': '10.1.0.81',
'equipmentLogName': 'admin',
'equipmentLogPwd': 'admin'
}, {
'equipmentModel': u'Group系列',
'className': u'82教室',
'equipment_name': '82lb',
'ipAddr': '10.1.0.82',
'locAddr': '10.1.0.81',
'equipmentLogName': 'admin',
'equipmentLogPwd': 'admin'
}]
def add_terminals(driver, **kwargs):
"""
Func desc
Args:
-
Usage:
"""
# para: {'equipmentModel': u'Group系列',
# 'classroom': '32className',
# 'equipment_name': '81lb',
# 'ipAddr': '10.1.0.81',
# 'locAddr': '10.1.0.81',
# 'equipmentLogName': 'admin',
# 'equipmentLogPwd': 'admin'},
'''添加一个终端'''
print "add info:{0},{1}".format(kwargs['equipment_name'],
kwargs['className'])
# refresh main page
driver.refresh()
# goto test page
driver.find_element_by_link_text(u"系统管理").click()
sleep(0.5)
driver.find_element_by_link_text(u"学校管理").click()
sleep(0.5)
driver.find_element_by_link_text(u"教室列表").click()
sleep(1)
driver.find_element_by_link_text(kwargs['className']).click()
sleep(1)
# driver.find_element_by_xpath(u"//a[contains(text(),'设备管理')]").click()
driver.find_element_by_xpath(u"(//a[contains(text(),'设备管理')])[2]").click()
sleep(1)
# click add btn
driver.find_element_by_id("addterminal").click()
sleep(1)
# operation
driver.find_element_by_css_selector(
"div.modal-body > div > #name > div.col-sm-9 > input.form-control"
).clear()
driver.find_element_by_css_selector(
"div.modal-body > div > #name > div.col-sm-9 > input.form-control"
).send_keys(kwargs['equipment_name'])
Select(
driver.find_element_by_css_selector(
"div.modal-body > div > #equipmentModel > div.col-sm-9 > select"
)).select_by_visible_text(kwargs['equipmentModel'])
driver.find_element_by_css_selector(
"div.modal-body > div > #ipAddr > div.col-sm-9 > input.form-control"
).clear()
driver.find_element_by_css_selector(
"div.modal-body > div > #ipAddr > div.col-sm-9 > input.form-control"
).send_keys(kwargs['ipAddr'])
driver.find_element_by_css_selector(
"div.modal-body > div > #locAddr > div.col-sm-9 > input.form-control"
).clear()
driver.find_element_by_css_selector(
"div.modal-body > div > #locAddr > div.col-sm-9 > input.form-control"
).send_keys(kwargs['locAddr'])
driver.find_element_by_css_selector(
"div.modal-body > div > #equipmentLogName > div.col-sm-9 > input.form-control"
).clear()
driver.find_element_by_css_selector(
"div.modal-body > div > #equipmentLogName > div.col-sm-9 > input.form-control"
).send_keys(kwargs['equipmentLogName'])
driver.find_element_by_css_selector(
"div.modal-body > div > #equipmentLogPwd > div.col-sm-9 > input.form-control"
).clear()
driver.find_element_by_css_selector(
"div.modal-body > div > #equipmentLogPwd > div.col-sm-9 > input.form-control"
).send_keys(kwargs['equipmentLogPwd'])
# click OK
driver.find_element_by_css_selector(
"#terminal > div.modal-dialog > div.modal-content > #formrole > div.modal-body > div.text-center > #submit"
).click()
sleep(1)
print "add {} end.".format(kwargs['equipment_name'])
# except Exception as e:
# print e
# print "add {} failed.".format(kwargs['equipment_name'])
def add_integrateds(driver, **kwargs):
"""
Func desc
Args:
-
Usage:
"""
# para:
'''添加一体机'''
print "add info:{0},{1}".format(kwargs['equipment_name'],
kwargs['className'])
# refresh main page
try:
driver.refresh()
# goto test page
driver.find_element_by_link_text(u"系统管理").click()
driver.find_element_by_link_text(u"学校管理").click()
driver.find_element_by_link_text(u"教室列表").click()
sleep(1)
driver.find_element_by_link_text(kwargs['className']).click()
sleep(1)
# 2060bug页面修改
# driver.find_element_by_xpath(u"//a[contains(text(),'设备管理')]").click()
driver.find_element_by_xpath(u"(//a[contains(text(),'设备管理')])[2]").click()
sleep(1)
# click add btn
driver.find_element_by_id("addIntegrated").click()
sleep(0.5)
# operation
driver.find_element_by_css_selector(
"div.modal-body.row > div > #name > div.col-sm-9 > input.form-control"
).clear()
driver.find_element_by_css_selector(
"div.modal-body.row > div > #name > div.col-sm-9 > input.form-control"
).send_keys(kwargs['equipment_name'])
driver.find_element_by_css_selector(
"div.modal-body.row > div > #ipAddr > div.col-sm-9 > input.form-control"
).clear()
driver.find_element_by_css_selector(
"div.modal-body.row > div > #ipAddr > div.col-sm-9 > input.form-control"
).send_keys(kwargs['ipAddr'])
driver.find_element_by_css_selector(
"div.modal-body.row > div > #locAddr > div.col-sm-9 > input.form-control"
).clear()
driver.find_element_by_css_selector(
"div.modal-body.row > div > #locAddr > div.col-sm-9 > input.form-control"
).send_keys(kwargs['locAddr'])
driver.find_element_by_css_selector(
"div.modal-body.row > div > #equipmentLogName > div.col-sm-9 > input.form-control"
).clear()
driver.find_element_by_css_selector(
"div.modal-body.row > div > #equipmentLogName > div.col-sm-9 > input.form-control"
).send_keys(kwargs['equipmentLogName'])
driver.find_element_by_css_selector(
"div.modal-body.row > div > #equipmentLogPwd > div.col-sm-9 > input.form-control"
).clear()
driver.find_element_by_css_selector(
"div.modal-body.row > div > #equipmentLogPwd > div.col-sm-9 > input.form-control"
).send_keys(kwargs['equipmentLogPwd'])
# click 确定
driver.find_element_by_css_selector(
"#Integrated > div.modal-dialog > div.modal-content > #formrole > div.modal-body.row > div.text-center > #submit"
).click()
sleep(1)
print "add {} end.".format(kwargs['equipment_name'])
except Exception as e:
print e
print "add {} failed.".format(kwargs['equipment_name'])
subjectsGroups = [{
'groupName': u'计算机',
'groupCode': '001',
'description': u'计算机'
}, {
'groupName': u'计算机1',
'groupCode': '002',
'description': u'计算机'
}]
def add_groupsubGrps(driver, **kwargs):
"""
Func desc
Args:
-
Usage:
"""
# para:
'''添加教室组'''
print "add info:{0},{1}".format(kwargs['groupName'], kwargs['groupCode'],
kwargs['description'])
# refresh main page
driver.refresh()
# goto test page
driver.find_element_by_link_text(u"系统管理").click()
driver.find_element_by_link_text(u"组管理").click()
sleep(1)
# click add btn
driver.find_element_by_xpath("//a[@id='addscgroup']").click()
sleep(0.5)
# operation
driver.find_element_by_xpath("//*[@id='groupName']/div/input").clear()
driver.find_element_by_xpath("//*[@id='groupName']/div/input").send_keys(
kwargs['groupName'])
driver.find_element_by_xpath("//*[@id='groupCode']/div/input").clear()
driver.find_element_by_xpath("//*[@id='groupCode']/div/input").send_keys(
kwargs['groupCode'])
driver.find_element_by_xpath("//*[@id='description']/div/textarea").clear()
driver.find_element_by_xpath(
"//*[@id='description']/div/textarea").send_keys(kwargs['description'])
# click 确定
driver.find_element_by_xpath("//button[@id='submit']").click()
sleep(1)
print "add {} end.".format(kwargs['groupName'])
# print "add {} failed.".format(kwargs[''])
users = [{
'loginName': 'user',
'trueName': 'teacher'
}, {
'loginName': 'user1',
'trueName': 'teacher1'
}, {
'loginName': 'user2',
'trueName': 'teacher2'
}, {
'loginName': 'user3',
'trueName': 'teacher3'
}, {
'loginName': 'user4',
'trueName': 'teacher4'
}]
def add_users(driver, **kwargs):
"""
Func desc
Args:
-
Usage:
"""
# pra: loginName, trueName
'''添加用户'''
print "添加用户的信息:{0},{1}".format(kwargs['loginName'], kwargs['trueName'])
try:
# driver.find_element_by_css_selector("#div_menu > ul.nav.nav-list > li > a.dropdown-toggle > span.menu-text").click()
driver.refresh()
driver.find_element_by_link_text(u"系统管理").click()
driver.find_element_by_link_text(u"用户列表").click()
driver.find_element_by_id("adduserlist").click()
sleep(1)
driver.find_element_by_name("loginName").clear()
driver.find_element_by_name("loginName").send_keys(kwargs['loginName'])
driver.find_element_by_name("pwd").clear()
driver.find_element_by_name("pwd").send_keys("111111")
driver.find_element_by_name("passwords").clear()
driver.find_element_by_name("passwords").send_keys("111111")
driver.find_element_by_name("mobile").clear()
driver.find_element_by_name("mobile").send_keys("13700010001")
driver.find_element_by_name("email").clear()
driver.find_element_by_name("email").send_keys("user@3bu.cn")
driver.find_element_by_name("trueName").clear()
driver.find_element_by_name("trueName").send_keys(kwargs['trueName'])
driver.find_element_by_id("determine").click()
sleep(1)
print "添加用户{0}成功。".format(kwargs['trueName'])
except Exception as e:
print "添加用户{0}失败。".format(kwargs['trueName'])
print e
def add_userswithschool(driver, **kwargs):
"""
Func desc
Args:
-
Usage:
"""
# pra: loginName, trueName
'''添加用户'''
print "添加用户的信息:{0},{1}".format(kwargs['loginName'], kwargs['trueName'])
try:
# driver.find_element_by_css_selector("#div_menu > ul.nav.nav-list > li > a.dropdown-toggle > span.menu-text").click()
driver.refresh()
driver.find_element_by_link_text(u"系统管理").click()
driver.find_element_by_link_text(u"用户列表").click()
driver.find_element_by_id("adduserlist").click()
sleep(1)
driver.find_element_by_name("loginName").clear()
driver.find_element_by_name("loginName").send_keys(kwargs['loginName'])
driver.find_element_by_name("pwd").clear()
driver.find_element_by_name("pwd").send_keys("111111")
driver.find_element_by_name("passwords").clear()
driver.find_element_by_name("passwords").send_keys("111111")
driver.find_element_by_name("mobile").clear()
driver.find_element_by_name("mobile").send_keys("13700010001")
driver.find_element_by_name("email").clear()
driver.find_element_by_name("email").send_keys("user@3bu.cn")
driver.find_element_by_name("trueName").clear()
driver.find_element_by_name("trueName").send_keys(kwargs['trueName'])
driver.find_element_by_id("determine").click()
sleep(1)
print "添加用户{0}成功。".format(kwargs['trueName'])
except Exception as e:
print "添加用户{0}失败。".format(kwargs['trueName'])
print e
roles = [{
'roleName': 'a2role19',
'roleCode': '000',
'description': 'comment role'
}, {
'roleName': 'a2role11',
'roleCode': '000',
'description': 'comment role'
}, {
'roleName': 'a2role31',
'roleCode': '000',
'description': 'comment role'
}, {
'roleName': 'a2role41',
'roleCode': '000',
'description': 'comment role'
}, {
'roleName': 'a2role21',
'roleCode': '000',
'description': 'comment role'
}, {
'roleName': 'arole51',
'roleCode': '000',
'description': 'comment role'
}, {
'roleName': 'a2role61',
'roleCode': '000',
'description': 'comment role'
}, {
'roleName': 'a2role71',
'roleCode': '000',
'description': 'comment role'
}]
def add_roles(driver, **kwargs):
"""
Func desc
Args:
-
Usage:
"""
# para: driver,roleName, roleCode, description
'''添加角色'''
print "添加的角色信息:{0},{1},{2}".format(kwargs['roleName'], kwargs['roleCode'],
kwargs['description'])
try:
driver.refresh()
driver.find_element_by_link_text(u"系统管理").click()
driver.find_element_by_link_text(u"角色管理").click()
sleep(0.5)
# click addrole button
driver.find_element_by_xpath("//a[@id='addrole']").click()
sleep(0.5)
driver.find_element_by_xpath(".//*[@id='roleName']").clear()
driver.find_element_by_xpath(".//*[@id='roleName']").send_keys(kwargs[
'roleName'])
driver.find_element_by_xpath(".//*[@id='roleCode']").clear()
driver.find_element_by_xpath(".//*[@id='roleCode']").send_keys(kwargs[
'roleCode'])
driver.find_element_by_xpath(".//*[@id='description']").clear()
driver.find_element_by_xpath(".//*[@id='description']").send_keys(
kwargs['description'])
driver.find_element_by_xpath(".//*[@id='insertrole']").click()
sleep(1)
print "添加角色{}成功。".format(kwargs['roleName'])
except Exception as e:
print e
print "添加角色{}失败。".format(kwargs['roleName'])
interactgrps = [{
'grpName': 'grp1',
'schoolgrTypeId': u'课程组'
}, {
'grpName': 'grp2',
'schoolgrTypeId': u'会议组'
}, {
'grpName': 'grp3',
'schoolgrTypeId': u'会议组'
}]
def add_interactgrps(driver, **kwargs):
"""
Func desc
Args:
-
Usage:
"""
# para:grpName,schoolgrTypeId
'''添加教室组'''
print "add info:{0},{1}".format(kwargs['grpName'],
kwargs['schoolgrTypeId'])
try:
# refresh main page
driver.refresh()
# goto test page
driver.find_element_by_link_text(u"系统管理").click()
driver.find_element_by_link_text(u"互动组管理").click()
sleep(0.5)
# click add btn
driver.find_element_by_xpath("//button[@id='addSchool']").click()
sleep(0.5)
# //*[@id='schoolName']/div/input
# operation
driver.find_element_by_xpath(
"//div[@id='schoolName']/div/input").clear()
driver.find_element_by_xpath(
"//div[@id='schoolName']/div/input").send_keys(kwargs['grpName'])
Select(
driver.find_element_by_xpath("//div[@id='schoolTypeId']/div/select"
)).select_by_visible_text(kwargs[
'schoolgrTypeId'])
# //*[@id='schoolTypeId']/div/select
# click 确定
driver.find_element_by_xpath("//button[@id='submit']").click()
# driver.find_element_by_xpath("//*[@id='submit']").click()
sleep(1)
print "add {} end.".format(kwargs['grpName'])
except Exception as e:
print e
print "add {} failed.".format(kwargs['grpName'])
subjects = [{
'subjectName': u'书法',
'description': u'学习中国文化'
}, {
'subjectName': u'计算机',
'description': u'计算机基础应用'
}]
def add_subjects(driver, **kwargs):
"""
Func desc
Args:
-
Usage:
"""
# para:
'''添加科目'''
print "add info:{0},{1}".format(kwargs['subjectName'],
kwargs['description'])
# refresh main page
try:
driver.refresh()
# goto test page
driver.find_element_by_link_text(u"基础数据").click()
driver.find_element_by_link_text(u"科目管理").click()
sleep(1)
# click add btn
driver.find_element_by_xpath("//a[@id='addsubject']").click()
# //*[@id='addsubject']
sleep(0.5)
# operation
driver.find_element_by_xpath("//input[@id='subjectName']").clear()
driver.find_element_by_xpath("//input[@id='subjectName']").send_keys(
kwargs['subjectName'])
driver.find_element_by_xpath("//*[@id='description']").clear()
driver.find_element_by_xpath("//*[@id='description']").send_keys(
kwargs["description"])
# click 确定
driver.find_element_by_xpath("//button[@id='insertsubject']").click()
sleep(1)
print "add {} end.".format(kwargs['subjectName'])
except Exception as e:
print e
print "add {} failed.".format(kwargs['subjectName'])
chapters = [{
'gradeid': u"二年级",
'subjectid': u"数学",
'chapterName': u'第一章a',
'chapterCode': u'助记码1'
}, {
'gradeid': u"二年级",
'subjectid': u"数学",
'chapterName': u'第一章b',
'chapterCode': u'助记码1'
}]
def add_chapters(driver, **kwargs):
"""
Func desc
Args:
-
Usage:
"""
# para:
'''添加章'''
print "add info:{0},{1},{2},{3}".format(
kwargs['gradeid'], kwargs['subjectid'], kwargs['chapterName'],
kwargs['chapterCode'])
# refresh main page
try:
driver.refresh()
# goto test page
driver.find_element_by_link_text(u"基础数据").click()
driver.find_element_by_link_text(u"章管理").click()
sleep(1)
# click add btn
driver.find_element_by_xpath("//a[@id='addchapter']").click()
sleep(0.5)
# operation
Select(driver.find_element_by_xpath("//select[@id='gradeid']")
).select_by_visible_text(kwargs['gradeid'])
Select(driver.find_element_by_xpath("//select[@id='subjectid']")
).select_by_visible_text(kwargs['subjectid'])
driver.find_element_by_xpath("//input[@id='chapterName']").clear()
driver.find_element_by_xpath("//input[@id='chapterName']").send_keys(
kwargs['chapterName'])
driver.find_element_by_xpath("//input[@id='chapterCode']").clear()
driver.find_element_by_xpath("//input[@id='chapterCode']").send_keys(
kwargs['chapterCode'])
# click 确定
driver.find_element_by_xpath("//button[@id='insertchapter']").click()
sleep(1)
print "add {} end.".format(kwargs['chapterName'])
except Exception as e:
print e
print "add {} failed.".format(kwargs['chapterName'])
sections = [{
'gradeid': u"二年级",
'subjectid': u"数学",
'chapterid': "zmc11",
'sectionName': u"第一节",
'sectionCode': u"第一节zjm"
}, {
'gradeid': u"二年级",
'subjectid': u"数学",
'chapterid': "zmc11",
'sectionName': u"第二节",
'sectionCode': u"第二节zjm"
}]
def add_sections(driver, **kwargs):
"""
Func desc
Args:
-
Usage:
"""
# para:
'''添加节'''
print "add info:{0},{1},{2},{3},{4}".format(
kwargs['gradeid'], kwargs['subjectid'], kwargs['chapterid'],
kwargs['sectionName'], kwargs['sectionCode'])
# refresh main page
try:
driver.refresh()
# goto test page
driver.find_element_by_link_text(u"基础数据").click()
driver.find_element_by_link_text(u"节管理").click()
sleep(1)
# click add btn
driver.find_element_by_xpath("//a[@id='addsection']/i").click()
sleep(0.5)
# operation
Select(driver.find_element_by_xpath("//select[@id='gradeid']")
).select_by_visible_text(kwargs['gradeid'])
Select(driver.find_element_by_xpath("//select[@id='subjectid']")
).select_by_visible_text(kwargs['subjectid'])
Select(driver.find_element_by_xpath("//select[@id='chapterid']")
).select_by_visible_text(kwargs['chapterid'])
driver.find_element_by_xpath("//input[@id='sectionName']").clear()
driver.find_element_by_xpath("//input[@id='sectionName']").send_keys(
kwargs['sectionName'])
driver.find_element_by_xpath("//input[@id='sectionCode']").clear()
driver.find_element_by_xpath("//input[@id='sectionCode']").send_keys(
kwargs['sectionCode'])
# click 确定
driver.find_element_by_xpath("//button[@id='insertsection']").click()
sleep(1)
print "add {} end.".format(kwargs['sectionName'])
except Exception as e:
print e
print "add {} failed.".format(kwargs['sectionName'])
knowledges = [{
'gradeid': u'六年级/小学',
'subjectid': u'自然科学',
'chapterid': u'第二章',
'sectionid': u"第二节",
'knowledgeName': u"双细胞",
'knowledgeCode': u"双细胞1"
}, {
'gradeid': u'六年级/小学',
'subjectid': u'自然科学',
'chapterid': u'第二章',
'sectionid': u"第二节",
'knowledgeName': u"多细胞",
'knowledgeCode': u"多细胞1"
}]
def add_knowledges(driver, **kwargs):
"""
Func desc
Args:
-
Usage:
"""
# para:
'''添加知识点'''
print "add info:{0},{1}".format(kwargs['knowledgeName'],
kwargs['subjectid'])
# refresh main page
try:
driver.refresh()
# goto test page
driver.find_element_by_link_text(u"基础数据").click()
driver.find_element_by_link_text(u"知识点管理").click()
sleep(1)
# click add btn
driver.find_element_by_xpath("//a[@id='addknowledge']").click()
sleep(0.5)
# operation
Select(driver.find_element_by_xpath("//select[@id='gradeid']")
).select_by_visible_text(kwargs['gradeid'])
Select(driver.find_element_by_xpath("//select[@id='subjectid']")
).select_by_visible_text(kwargs['subjectid'])
Select(driver.find_element_by_xpath("//select[@id='chapterid']")
).select_by_visible_text(kwargs['chapterid'])
Select(driver.find_element_by_xpath("//select[@id='sectionid']")
).select_by_visible_text(kwargs['sectionid'])
driver.find_element_by_xpath("//input[@id='knowledgeName']").clear()
driver.find_element_by_xpath("//input[@id='knowledgeName']").send_keys(
kwargs['knowledgeName'])
driver.find_element_by_xpath("//input[@id='knowledgeCode']").clear()
driver.find_element_by_xpath("//input[@id='knowledgeCode']").send_keys(
kwargs['knowledgeCode'])
# click 确定
driver.find_element_by_xpath("//button[@id='insertknowledge']").click()
sleep(1)
print "add {} end.".format(kwargs['knowledgeName'])
except Exception as e:
print e
print "add {} failed.".format(kwargs['knowledgeName'])
MCUequipments = [{
'equipmentName': '85mcu',
'equipIpAddr': '10.1.0.85',
'mcu_port': '80',
'mcuLoginName': 'POLYCOM',
'mcuPasswd': 'POLYCOM'
}, {
'equipmentName': '95mcu',
'equipIpAddr': '10.1.0.95',
'mcu_port': '10000',
'mcuLoginName': 'POLYCOM',
'mcuPasswd': 'POLYCOM'
}]
def add_MCUequipments(driver, **kwargs):
"""
Func desc
Args:
-
Usage:
"""
# para:equipmentName,equipIpAddr,mcu_port,mcuLoginName,mcuPasswd
'''添加mcu'''
print "add info:{0},{1},{2},{3}".format(
kwargs['equipmentName'], kwargs['equipIpAddr'], kwargs['mcuLoginName'],
kwargs['mcuPasswd'])
# refresh main page
try:
driver.refresh()
# goto test page
driver.find_element_by_link_text(u"设备管理").click()
driver.find_element_by_link_text(u"中心设备").click()
sleep(1)
# click add btn
sleep(1)
driver.find_element_by_css_selector("i.fa.fa-plus").click()
sleep(1)
driver.find_element_by_id("mcuAreaName").click()
sleep(0.5)
# operation
driver.find_element_by_css_selector(
"li.list-group-item.node-treeview").click()
sleep(1)
driver.find_element_by_id("equipmentName").clear()
driver.find_element_by_id("equipmentName").send_keys(kwargs[
'equipmentName'])
driver.find_element_by_id("equipIpAddr").clear()
driver.find_element_by_id("equipIpAddr").send_keys(kwargs[
'equipIpAddr'])
driver.find_element_by_id("mcu_port").clear()
driver.find_element_by_id("mcu_port").send_keys(kwargs['mcu_port'])
driver.find_element_by_id("mcuLoginName").clear()
driver.find_element_by_id("mcuLoginName").send_keys(kwargs[
'mcuLoginName'])
driver.find_element_by_id("mcuPasswd").clear()
driver.find_element_by_id("mcuPasswd").send_keys(kwargs['mcuPasswd'])
# click 确定
driver.find_element_by_xpath("//button[@id='submit']").click()
sleep(1)
print "add {} end.".format(kwargs['equipmentName'])
except Exception as e:
print e
print "add {} failed.".format(kwargs['equipmentName'])
def conf_drivers_child(driver):
"""
Func desc
Args:
-
Usage:
"""
# driver = webdriver.Chrome()
# user_login(driver, 'hnsadmin', u"河南教育局")
driver.refresh()
driver.find_element_by_link_text(u"设备管理").click()
sleep(0.5)
driver.find_element_by_link_text(u"中心设备").click()
sleep(1)
# 点击MCU管理区域按键
driver.find_element_by_xpath("(//button[@id='current'])[2]").click()
sleep(1)
# 选择区域
driver.find_element_by_xpath(
"//div[@id='AreaMcutreeview']/ul/li/span[3]").click()
sleep(1)
# save区域
driver.find_element_by_id("saveAreaMcu").click()
sleep(1)
driver.find_element_by_id("xiaoximiddleware").click()
sleep(1)
# 选择消息中间件
driver.find_element_by_xpath(
"//table[@id='middlewaretable']/tbody/tr[2]/td[2]").click()
# //table[@id='middlewaretable']/tbody/tr/td[2]
sleep(1)
# failed 1
driver.find_element_by_css_selector("i.fa.fa-server").click()
sleep(1)
# save
driver.find_element_by_name("ckrelevmcuid").click()
sleep(1)
driver.find_element_by_id("saverelevmcumiddleware").click()
sleep(1)
# driver.find_element_by_xpath("//table[@id='middlewaretable']/tbody/tr[2]/td[2]").click() # 选择interact
# 选择消息中间件管理mcu的时间较长
sleep(12)
# driver.find_element_by_xpath("//table[@id='middlewaretable']/tbody/tr[2]/td[2]").click()
driver.find_element_by_css_selector("i.fa.fa-bars").click()
sleep(1)
driver.find_element_by_css_selector(
"#listofschooltable > tr > td > input[type=\"checkbox\"]").click()
sleep(1)
driver.find_element_by_id("insertmiddlewareschool").click()
sleep(1)
# driver.find_element_by_xpath("//table[@id='middlewaretable']/tbody/tr[2]/td[2]").click()
# sleep(1)
# driver.find_element_by_id("theschoollist").click()
def conf_drivers_local(driver):
"""
Func desc: cfg the center interact manager mcu and school
Args:
-
Usage:
"""
# driver = webdriver.Chrome()
# user_login(driver, 'hnsadmin', u"河南教育局")
driver.refresh()
driver.find_element_by_link_text(u"设备管理").click()
sleep(0.5)
driver.find_element_by_link_text(u"中心设备").click()
sleep(1)
# 点击MCU管理区域按键
driver.find_element_by_xpath("(//button[@id='current'])[2]").click()
sleep(1)
# 选择区域
driver.find_element_by_xpath(
"//div[@id='AreaMcutreeview']/ul/li/span[3]").click()
sleep(1)
# save区域
driver.find_element_by_id("saveAreaMcu").click()
sleep(1)
driver.find_element_by_id("xiaoximiddleware").click()
sleep(1)
# 选择消息中间件
# //table[@id='middlewaretable']/tbody/tr/td[2] 第一个
# //table[@id='middlewaretable']/tbody/tr[2]/td[2] 第二个
driver.find_element_by_xpath(
"//table[@id='middlewaretable']/tbody/tr/td[2]").click()
sleep(1)
# 关联MCU
driver.find_element_by_css_selector("i.fa.fa-server").click()
sleep(1)
driver.find_element_by_xpath("//input[@name='ckrelevmcuid']").click()
sleep(1)
driver.find_element_by_xpath("(//input[@name='ckrelevmcuid'])[2]").click()
sleep(1)
# 点击确定
driver.find_element_by_id("saverelevmcumiddleware").click()
sleep(1.5)
# 关联school
driver.find_element_by_css_selector("i.fa.fa-bars").click()
sleep(1)
driver.find_element_by_xpath("//tbody[@id='listofschooltable']/tr/td/input").click()
sleep(1)
driver.find_element_by_xpath("//tbody[@id='listofschooltable']/tr[2]/td/input").click()
sleep(1)
# 点击确定
driver.find_element_by_id("insertmiddlewareschool").click()
sleep(2)
###############
# driver.find_element_by_css_selector("i.fa.fa-server").click()
# sleep(1)
# driver.find_element_by_name("ckrelevmcuid").click()
# sleep(1)
# # save
# driver.find_element_by_id("saverelevmcumiddleware").click()
# # driver.find_element_by_xpath("//table[@id='middlewaretable']/tbody/tr[2]/td[2]").click() # 选择interact
# # 选择消息中间件管理mcu的时间较长
# sleep(2)
# # driver.find_element_by_xpath("//table[@id='middlewaretable']/tbody/tr[2]/td[2]").click()
# driver.find_element_by_css_selector("i.fa.fa-bars").click()
# sleep(1)
# driver.find_element_by_css_selector(
# "#listofschooltable > tr > td > input[type=\"checkbox\"]").click()
# sleep(1)
# driver.find_element_by_id("insertmiddlewareschool").click()
###################
# driver.find_element_by_xpath("//table[@id='middlewaretable']/tbody/tr[2]/td[2]").click()
# sleep(1)
# driver.find_element_by_id("theschoollist").click()
interacts = [{
'host': '10.1.0.2',
'port': '80',
'username': 'administrator',
'password': 'xungejiaoyu'
}, {
'host': '10.1.0.3',
'port': '80',
'username': 'administrator',
'password': 'xungejiaoyu'
}]
def add_interacts(driver, **kwargs):
"""
Func desc
Args:
-
Usage:
"""
# para:host,port,username,password
'''添加消息中间件'''
print "add info:{0},{1},{2},{3}".format(
kwargs['host'], kwargs['port'], kwargs['username'], kwargs['password'])
# refresh main page
try:
driver.refresh()
driver.find_element_by_link_text(u"设备管理").click()
driver.find_element_by_link_text(u"中心设备").click()
sleep(1)
driver.find_element_by_id("xiaoximiddleware").click()
sleep(1)
driver.find_element_by_css_selector(
"#addmiddleware > i.fa.fa-plus").click()
sleep(1)
driver.find_element_by_id("host").clear()
driver.find_element_by_id("host").send_keys(kwargs['host'])
driver.find_element_by_id("port").clear()
driver.find_element_by_id("port").send_keys(kwargs['port'])
driver.find_element_by_id("username").clear()
driver.find_element_by_id("username").send_keys(kwargs['username'])
driver.find_element_by_id("password").clear()
driver.find_element_by_id("password").send_keys(kwargs['password'])
sleep(0.5)
driver.find_element_by_id("insertmiddleware").click()
sleep(1)
print "add {} end.".format(kwargs['host'])
except Exception as e:
print e
print "add {} failed.".format(kwargs['host'])
def conf_interact_local(driver, interactaddr):
"""
Func desc:local interactmgr platform config
Args:
-
Usage:
"""
# open url
driver.get("http://" + interactaddr + "/interact/login.do")
driver.maximize_window()
driver.find_element_by_id("username").clear()
driver.find_element_by_id("username").send_keys("administrator")
driver.find_element_by_id("password").clear()
driver.find_element_by_id("password").send_keys("xungejiaoyu")
sleep(1)
driver.find_element_by_id("buttlogin").click()
sleep(2)
driver.find_element_by_id("sysconfig").click()
sleep(1)
# failed 1
driver.find_element_by_xpath(
"//table[@id='table']/tbody/tr[2]/td[3]/a/i").click()
sleep(1)
driver.find_element_by_id("value").clear()
driver.find_element_by_id("value").send_keys(interactaddr)
driver.find_element_by_xpath("(//button[@type='button'])[4]").click()
sleep(1)
driver.find_element_by_id("sysmiddlewarelocal").click()
sleep(1)
driver.find_element_by_id("addLocal").click() # 获取消息中间件
sleep(1)
driver.find_element_by_xpath("(//input[@name='text'])").click()
sleep(1)
driver.find_element_by_id("determines").click()
sleep(2)
driver.switch_to_alert().accept()
sleep(1)
driver.find_element_by_css_selector(u"button[title=\"设为本地连接中间件\"]").click()
sleep(2.5)
driver.switch_to_alert().accept()
sleep(1)
driver.find_element_by_css_selector(u"button[title=\"手动连接中间件\"]").click()
sleep(6)
try:
driver.switch_to_alert().accept()
except NoAlertPresentException as e:
print e
sleep(1)
def conf_child_interact(driver, interactaddr, serveraddr):
"""
Func desc:child interactmgr platform config
Args:
-
Usage:
"""
# //tbody[@id='selectLocal']/tr/td //input[@name='text'] //tbody[@id='selectLocal']/tr/td[4]/input 10.1.0.45
# //tbody[@id='selectLocal']/tr[2]/td xpath=(//input[@name='text'])[2] //tbody[@id='selectLocal']/tr[2]/td[4]/input 10.1.0.56
driver.get("http://" + interactaddr + "/interact/login.do")
driver.maximize_window()
driver.find_element_by_id("username").clear()
driver.find_element_by_id("username").send_keys("administrator")
driver.find_element_by_id("password").clear()
driver.find_element_by_id("password").send_keys("xungejiaoyu")
sleep(1)
driver.find_element_by_id("buttlogin").click()
sleep(1)
driver.find_element_by_id("sysconfig").click()
sleep(1)
driver.find_element_by_xpath(
"//table[@id='table']/tbody/tr[2]/td[3]/a/i").click()
sleep(1)
driver.find_element_by_id("value").clear()
driver.find_element_by_id("value").send_keys(serveraddr)
driver.find_element_by_xpath("(//button[@type='button'])[4]").click()
sleep(1)
driver.find_element_by_id("sysmiddlewarelocal").click()
sleep(1)
# 选择消息中间件弹出页面btn
driver.find_element_by_id("addLocal").click()
sleep(1)
firstIpPageText = driver.find_element_by_xpath(
"//tbody[@id='selectLocal']/tr/td ").text
secondIpPageText = driver.find_element_by_xpath(
"//tbody[@id='selectLocal']/tr[2]/td").text
print firstIpPageText, secondIpPageText
sleep(1)
# 配置本地消息中间件
if firstIpPageText == interactaddr:
driver.find_element_by_xpath("//input[@name='text']").click()
sleep(0.5)
driver.find_element_by_id("determines").click()
sleep(3)
driver.switch_to_alert().accept()
sleep(1)
driver.find_element_by_css_selector(
u"button[title=\"设为本地连接中间件\"]").click()
sleep(3)
driver.switch_to_alert().accept()
sleep(1)
driver.find_element_by_css_selector(
u"button[title=\"手动连接中间件\"]").click()
sleep(6)
driver.switch_to_alert().accept()
sleep(2)
elif secondIpPageText == interactaddr:
driver.find_element_by_xpath("(//input[@name='text'])[2]").click()
sleep(0.5)
driver.find_element_by_id("determines").click()
sleep(3)
driver.switch_to_alert().accept()
sleep(1)
driver.find_element_by_css_selector(
u"button[title=\"设为本地连接中间件\"]").click()
sleep(3)
driver.switch_to_alert().accept()
sleep(1)
driver.find_element_by_css_selector(
u"button[title=\"手动连接中间件\"]").click()
sleep(6)
driver.switch_to_alert().accept()
else:
print "non-existent:{} local interact".format(interactaddr)
driver.find_element_by_id("addLocal").click()
sleep(1)
firstIpPageText = driver.find_element_by_xpath(
"//tbody[@id='selectLocal']/tr/td ").text
secondIpPageText = driver.find_element_by_xpath(
"//tbody[@id='selectLocal']/tr[2]/td").text
print firstIpPageText, secondIpPageText
if firstIpPageText == serveraddr:
driver.find_element_by_xpath("//input[@name='text']").click()
sleep(0.5)
driver.find_element_by_id("determines").click()
sleep(3)
driver.switch_to_alert().accept()
sleep(1)
driver.find_element_by_xpath(
"//tbody[@id='localQuery']/tr[2]/th[8]/button[4]").click()
sleep(3)
driver.switch_to_alert().accept()
sleep(1)
driver.find_element_by_xpath(
"//tbody[@id='localQuery']/tr[2]/th[8]/button[2]").click()
sleep(3)
driver.switch_to_alert().accept()
sleep(4)
elif secondIpPageText == serveraddr:
driver.find_element_by_xpath("(//input[@name='text'])[2]").click()
sleep(0.5)
driver.find_element_by_id("determines").click()
sleep(3)
driver.switch_to_alert().accept()
sleep(1)
driver.find_element_by_xpath(
"//tbody[@id='localQuery']/tr[2]/th[8]/button[4]").click()
sleep(3)
driver.switch_to_alert().accept()
sleep(1)
driver.find_element_by_xpath(
"//tbody[@id='localQuery']/tr[2]/th[8]/button[2]").click()
sleep(3)
driver.switch_to_alert().accept()
sleep(4)
else:
print "non-existent:{} middle interact".format(serveraddr)
hdk_lesson_cfgs = [{'name': u'互动课模板'}, {'name': u'互动课模板480p'}]
jp_lesson_cfgs = [{'name': u'精品课'}, {'name': u'精品课480p'}]
conference_cfgs = [{'name': u'会议'}, {'name': u'会议480p'}]
speaker_lesson_cfgs = [{'name': u'主讲下课'}, {'name': u'主讲下课_1'}]
listener_lesson_cfgs = [{'name': u'听讲下课'}, {'name': u'听讲下课_1'}]
def add_cfg_listener_lessons(driver, **kwargs):
"""
Func desc
Args:
-
Usage:
"""
# para:name
'''添加听讲下课模板'''
print "add info:{0}".format(kwargs['name'])
# refresh main page
try:
driver.refresh()
# goto test page
driver.find_element_by_link_text(u"配置管理").click()
driver.find_element_by_link_text(u"模板管理").click()
driver.find_element_by_link_text(u"听课下课").click()
sleep(1)
# click add btn
driver.find_element_by_xpath("//a[@id='addlisteningclass']/i").click()
sleep(0.5)
# operation
driver.find_element_by_xpath("(//input[@id='name'])[7]").clear()
driver.find_element_by_xpath("(//input[@id='name'])[7]").send_keys(
kwargs['name'])
# click 确定
driver.find_element_by_xpath(
"//button[@id='insertlectureclass']").click()
sleep(1)
print "add {} end.".format(kwargs['name'])
except Exception as e:
print e
print "add {} failed.".format(kwargs['name'])
def add_cfg_speaker_lessons(driver, **kwargs):
"""
Func desc
Args:
-
Usage:
"""
# para:name
'''添加主讲下课模板'''
print "add info:{0}".format(kwargs['name'])
# refresh main page
try:
driver.refresh()
# goto test page
driver.find_element_by_link_text(u"配置管理").click()
driver.find_element_by_link_text(u"模板管理").click()
driver.find_element_by_link_text(u"主讲下课").click()
sleep(1)
# click add btn
driver.find_element_by_xpath("//a[@id='addlectureclass']/i").click()
sleep(0.5)
# operation
driver.find_element_by_xpath("(//input[@id='name'])[7]").clear()
driver.find_element_by_xpath("(//input[@id='name'])[7]").send_keys(
kwargs['name'])
# click 确定
driver.find_element_by_id("insertlectureclass").click()
sleep(1)
print "add {} end.".format(kwargs['name'])
except Exception as e:
print e
print "add {} failed.".format(kwargs['name'])
def add_cfg_conferences(driver, **kwargs):
"""
Func desc
Args:
-
Usage:
"""
# para:name
'''添加会议模板'''
print "add info:{0}".format(kwargs['name'])
# refresh main page
try:
driver.refresh()
# goto test page
driver.find_element_by_link_text(u"配置管理").click()
driver.find_element_by_link_text(u"模板管理").click()
driver.find_element_by_xpath(
u"(//a[contains(text(),'视频会议')])[2]").click()
sleep(1)
# click add btn
driver.find_element_by_xpath("//a[@id='addvideoconference']/i").click()
sleep(0.5)
# operation
driver.find_element_by_xpath("(//input[@id='name'])[5]").clear()
driver.find_element_by_xpath("(//input[@id='name'])[5]").send_keys(
kwargs['name'])
# click 确定
driver.find_element_by_xpath(
"//button[@id='insertvideoconference']").click()
sleep(1)
print "add {} end.".format(kwargs['name'])
except Exception as e:
print e
print "add {} failed.".format(kwargs['name'])
def add_cfg_jpks(driver, **kwargs):
"""
Func desc
Args:
-
Usage:
"""
# para:name
'''添加精品课模板'''
print "add info:{0}".format(kwargs['name'])
# refresh main page
try:
driver.refresh()
# goto test page
driver.find_element_by_link_text(u"配置管理").click()
driver.find_element_by_link_text(u"模板管理").click()
driver.find_element_by_xpath(
u"(//a[contains(text(),'精品课堂')])[2]").click()
sleep(1)
# click add btn
driver.find_element_by_xpath("//a[@id='addexcellentclass']/i").click()
sleep(0.5)
# operation
driver.find_element_by_xpath("(//input[@id='name'])[3]").clear()
driver.find_element_by_xpath("(//input[@id='name'])[3]").send_keys(
kwargs['name'])
# click 确定
driver.find_element_by_xpath(
"//button[@id='insertexcellentclass']").click()
sleep(1)
print "add {} end.".format(kwargs['name'])
except Exception as e:
print e
print "add {} failed.".format(kwargs['name'])
def add_cfg_hdks(driver, **kwargs):
"""
Func desc
Args:
-
Usage:
"""
# para:name
'''添加互动模板'''
print "add info:{0}".format(kwargs['name'])
# refresh main page
try:
driver.refresh()
# goto test page
driver.find_element_by_link_text(u"配置管理").click()
driver.find_element_by_link_text(u"模板管理").click()
driver.find_element_by_xpath(
u"(//a[contains(text(),'精品课堂')])[2]").click()
sleep(1)
driver.find_element_by_xpath(
u"(//a[contains(text(),'互动教学')])[2]").click()
sleep(1)
# click add btn
driver.find_element_by_xpath("//a[@id='addinteractteach']/i").click()
sleep(0.5)
# operation
driver.find_element_by_xpath("//input[@id='name']").clear()
driver.find_element_by_xpath("//input[@id='name']").send_keys(kwargs[
'name'])
# click 确定
driver.find_element_by_xpath(
"//button[@id='insertinteractteach']").click()
sleep(1)
print "add {} end.".format(kwargs['name'])
except NoSuchElementException as e:
print e
print "add {} failed.".format(kwargs['name'])
emails = [{
'smtp': 'smtp.162.com',
'fromName': 'haosea@qq.com',
'password': '111111'
}, {
'smtp': 'smtp.163.com',
'fromName': 'haosea1@qq.com',
'password': '111111'
}]
def add_emails(driver, **kwargs):
"""
Func desc
Args:
-
Usage:
"""
# para:
'''添加邮箱服务'''
print "add info:{0},{1},{2}".format(kwargs['smtp'], kwargs['fromName'],
kwargs['password'])
# refresh main page
try:
driver.refresh()
# goto test page
driver.find_element_by_link_text(u"配置管理").click()
driver.find_element_by_link_text(u"邮箱服务管理").click()
sleep(1)
# click add btn
driver.find_element_by_xpath(
"//button[@id='add_email_setting']").click()
sleep(0.5)
# operation
driver.find_element_by_xpath("//input[@id='smtp']").clear()
driver.find_element_by_xpath("//input[@id='smtp']").send_keys(kwargs[
'smtp'])
driver.find_element_by_xpath("//input[@id='fromName']").clear()
driver.find_element_by_xpath("//input[@id='fromName']").send_keys(
kwargs['fromName'])
driver.find_element_by_xpath("// input[@id='password']").clear()
driver.find_element_by_xpath("//input[@id='password']").send_keys(
kwargs['password'])
driver.find_element_by_xpath("//input[@id='status0']").click()
# click 确定
driver.find_element_by_xpath("//button[@id='determine']").click()
sleep(1)
print "add {} end.".format(kwargs['smtp'])
except Exception as e:
print e
print "add {} failed.".format(kwargs['smtp'])
def add_hdk_18(driver):
'''添加互动课'''
driver.refresh()
driver.find_element_by_link_text(u"课堂管理").click()
sleep(0.5)
driver.find_element_by_link_text(u"互动教学").click()
sleep(0.5)
driver.find_element_by_id("addclassroom").click()
sleep(1)
driver.find_element_by_xpath("(//button[@type='button'])[13]").click()
driver.find_element_by_xpath("//div[@id='main-container']/div/div[2]/div/div[2]/div/div[2]/div/div/div/ul/li[3]/a/span").click()
driver.find_element_by_xpath("(//button[@type='button'])[14]").click()
driver.find_element_by_xpath("//div[@id='classOrTeacher']/div/div/ul/li[2]/a/span").click()
driver.find_element_by_id("teachLesson_input_text").clear()
driver.find_element_by_id("teachLesson_input_text").send_keys("hdk_long")
driver.find_element_by_xpath("(//button[@type='button'])[16]").click()
driver.find_element_by_link_text(u"一年级").click()
driver.find_element_by_xpath("(//button[@type='button'])[17]").click()
driver.find_element_by_link_text(u"语文").click()
driver.find_element_by_xpath("(//button[@type='button'])[18]").click()
driver.find_element_by_xpath("//div[@id='lesson_infor']/div[3]/div/ul/li[2]/a/span").click()
driver.find_element_by_id("ptlive_true").click()
driver.find_element_by_xpath("(//button[@type='button'])[23]").click()
sleep(0.5)
driver.find_element_by_link_text(u"周日").click()
driver.find_element_by_xpath("(//button[@type='button'])[24]").click()
sleep(0.5)
driver.find_element_by_link_text(u"第七节").click()
driver.find_element_by_xpath("//div[@id='class_table_seedClassroom']/button").click()
driver.find_element_by_xpath("(//button[@type='button'])[25]").click()
driver.find_element_by_xpath("//tbody[@id='theclassroom_value']/tr/td/div/div/ul/li[2]/a/span").click()
driver.find_element_by_xpath("(//button[@type='button'])[26]").click()
driver.find_element_by_xpath("//tbody[@id='theclassroom_value']/tr/td[2]/div/div/ul/li[2]/a/span").click()
driver.find_element_by_xpath("//div[@id='class_table_seedClassroom']/button").click()
driver.find_element_by_xpath("(//button[@type='button'])[27]").click()
driver.find_element_by_xpath("//tbody[@id='theclassroom_value']/tr[2]/td/div/div/ul/li[2]/a/span").click()
driver.find_element_by_xpath("(//button[@type='button'])[28]").click()
driver.find_element_by_xpath("//tbody[@id='theclassroom_value']/tr[2]/td[2]/div/div/ul/li[3]/a").click()
driver.find_element_by_xpath("//div[@id='class_table_seedClassroom']/button").click()
driver.find_element_by_xpath("(//button[@type='button'])[29]").click()
driver.find_element_by_xpath("//tbody[@id='theclassroom_value']/tr[3]/td/div/div/ul/li[2]/a").click()
driver.find_element_by_xpath("(//button[@type='button'])[30]").click()
driver.find_element_by_xpath("//tbody[@id='theclassroom_value']/tr[3]/td[2]/div/div/ul/li[4]/a/span").click()
driver.find_element_by_xpath("//div[@id='class_table_seedClassroom']/button").click()
driver.find_element_by_xpath("(//button[@type='button'])[31]").click()
driver.find_element_by_xpath("//tbody[@id='theclassroom_value']/tr[4]/td/div/div/ul/li[2]/a").click()
driver.find_element_by_xpath("(//button[@type='button'])[32]").click()
driver.find_element_by_xpath("//tbody[@id='theclassroom_value']/tr[4]/td[2]/div/div/ul/li[5]/a/span").click()
driver.find_element_by_xpath("//div[@id='class_table_seedClassroom']/button").click()
driver.find_element_by_xpath("(//button[@type='button'])[33]").click()
driver.find_element_by_xpath("//tbody[@id='theclassroom_value']/tr[5]/td/div/div/ul/li[2]/a").click()
driver.find_element_by_xpath("(//button[@type='button'])[34]").click()
driver.find_element_by_xpath("//tbody[@id='theclassroom_value']/tr[5]/td[2]/div/div/ul/li[6]/a/span").click()
driver.find_element_by_xpath("//div[@id='class_table_seedClassroom']/button").click()
driver.find_element_by_xpath("(//button[@type='button'])[35]").click()
driver.find_element_by_xpath("//tbody[@id='theclassroom_value']/tr[6]/td/div/div/ul/li[2]/a/span").click()
driver.find_element_by_xpath("(//button[@type='button'])[36]").click()
driver.find_element_by_xpath("//tbody[@id='theclassroom_value']/tr[6]/td[2]/div/div/ul/li[7]/a").click()
driver.find_element_by_xpath("//div[@id='class_table_seedClassroom']/button").click()
driver.find_element_by_xpath("(//button[@type='button'])[37]").click()
driver.find_element_by_xpath("//tbody[@id='theclassroom_value']/tr[7]/td/div/div/ul/li[2]/a").click()
driver.find_element_by_xpath("(//button[@type='button'])[38]").click()
driver.find_element_by_xpath("//tbody[@id='theclassroom_value']/tr[7]/td[2]/div/div/ul/li[8]/a/span").click()
sleep(0.5)
driver.find_element_by_css_selector("div.middle_content.finalast > button.btn.btn-success").click()
sleep(2)
def add_hdk(driver):
'''添加互动课'''
driver.refresh()
driver.find_element_by_link_text(u"课堂管理").click()
sleep(0.5)
driver.find_element_by_link_text(u"互动教学").click()
sleep(0.5)
driver.find_element_by_id("addclassroom").click()
sleep(1)
# 第二个选项
driver.find_element_by_xpath("(//button[@type='button'])[13]").click()
driver.find_element_by_xpath("//div[@id='main-container']/div/div[2]/div/div[2]/div/div/div/div/div/ul/li[3]/a/span").click()
# 第一个选项
# driver.find_element_by_xpath("(//button[@type='button'])[13]").click()
# driver.find_element_by_xpath("//div[@id='main-container']/div/div[2]/div/div[2]/div/div/div/div/div/ul/li[2]/a/span").click()
# 选择主讲教室
driver.find_element_by_xpath("(//button[@type='button'])[14]").click()
driver.find_element_by_xpath("//div[@id='main-container']/div/div[2]/div/div[2]/div/div[2]/div/div/ul/li[2]/a/span").click()
# add lesson name
driver.find_element_by_id("teachLesson_input_text").clear()
driver.find_element_by_id("teachLesson_input_text").send_keys("hdk_long")
# 选择年级
driver.find_element_by_xpath("(//button[@type='button'])[15]").click()
driver.find_element_by_link_text(u"一年级").click()
# 选择科目
driver.find_element_by_xpath("(//button[@type='button'])[16]").click()
driver.find_element_by_link_text(u"语文").click()
# 选择老师
driver.find_element_by_xpath("(//button[@type='button'])[17]").click()
driver.find_element_by_xpath("//div[@id='main-container']/div/div[2]/div/div[2]/div/div[4]/div[3]/div/ul/li[2]/a/span").click()
# 打开平台直播开关
driver.find_element_by_xpath("//input[@id='ptlive_true']").click()
# 添加起止时间
driver.find_element_by_xpath("(//button[@type='button'])[22]").click()
driver.find_element_by_link_text(u"周日").click()
driver.find_element_by_xpath("(//button[@type='button'])[23]").click()
driver.find_element_by_link_text(u"第七节").click()
# 添加接收教室
driver.find_element_by_xpath("//div[@id='class_table_seedClassroom']/button").click()
driver.find_element_by_xpath("(//button[@type='button'])[24]").click()
driver.find_element_by_xpath("//tbody[@id='theclassroom_value']/tr/td/div/div/ul/li[2]/a").click()
driver.find_element_by_xpath("(//button[@type='button'])[25]").click()
# 选择第一个学校
# driver.find_element_by_link_text(u"132教室").click()
driver.find_element_by_xpath("//tbody[@id='theclassroom_value']/tr/td[2]/div/div/ul/li[2]/a").click()
# 选择第二个学校
# driver.find_element_by_xpath("//tbody[@id='theclassroom_value']/tr[2]/td[2]/div/div/ul/li[3]/a").click()
driver.find_element_by_xpath("//button[@onclick='addClassroomByCheck(null,$(this));']").click()
driver.find_element_by_xpath("(//button[@type='button'])[26]").click()
driver.find_element_by_xpath("//tbody[@id='theclassroom_value']/tr[2]/td/div/div/ul/li[2]/a/span").click()
driver.find_element_by_xpath("(//button[@type='button'])[27]").click()
# 选择第二个学校
driver.find_element_by_xpath("//tbody[@id='theclassroom_value']/tr[2]/td[2]/div/div/ul/li[3]/a").click()
# 添加教室
driver.find_element_by_xpath("//button[@onclick='addClassroomByCheck(null,$(this));']").click()
driver.find_element_by_xpath("(//button[@type='button'])[28]").click()
driver.find_element_by_xpath("//tbody[@id='theclassroom_value']/tr[3]/td/div/div/ul/li[2]/a/span").click()
driver.find_element_by_xpath("(//button[@type='button'])[29]").click()
driver.find_element_by_xpath("//tbody[@id='theclassroom_value']/tr[3]/td[2]/div/div/ul/li[4]/a/span").click()
# 添加教室
driver.find_element_by_xpath("//button[@onclick='addClassroomByCheck(null,$(this));']").click()
driver.find_element_by_xpath("(//button[@type='button'])[30]").click()
driver.find_element_by_xpath("//tbody[@id='theclassroom_value']/tr[4]/td/div/div/ul/li[2]/a").click()
driver.find_element_by_xpath("(//button[@type='button'])[31]").click()
driver.find_element_by_xpath("//tbody[@id='theclassroom_value']/tr[4]/td[2]/div/div/ul/li[5]/a").click()
# 添加教室
driver.find_element_by_xpath("//button[@onclick='addClassroomByCheck(null,$(this));']").click()
driver.find_element_by_xpath("(//button[@type='button'])[32]").click()
driver.find_element_by_xpath("//tbody[@id='theclassroom_value']/tr[5]/td/div/div/ul/li[2]/a/span").click()
driver.find_element_by_xpath("(//button[@type='button'])[33]").click()
driver.find_element_by_xpath("//tbody[@id='theclassroom_value']/tr[5]/td[2]/div/div/ul/li[6]/a/span").click()
# 添加教室
driver.find_element_by_xpath("//button[@onclick='addClassroomByCheck(null,$(this));']").click()
driver.find_element_by_xpath("(//button[@type='button'])[34]").click()
driver.find_element_by_xpath("//tbody[@id='theclassroom_value']/tr[6]/td/div/div/ul/li[2]/a/span").click()
driver.find_element_by_xpath("(//button[@type='button'])[35]").click()
driver.find_element_by_xpath("//tbody[@id='theclassroom_value']/tr[6]/td[2]/div/div/ul/li[7]/a/span").click()
# 添加教室
driver.find_element_by_xpath("//button[@onclick='addClassroomByCheck(null,$(this));']").click()
driver.find_element_by_xpath("(//button[@type='button'])[36]").click()
# 选择学校下拉框第一个
driver.find_element_by_xpath("//tbody[@id='theclassroom_value']/tr[7]/td/div/div/ul/li[2]/a").click()
driver.find_element_by_xpath("(//button[@type='button'])[37]").click()
driver.find_element_by_xpath("//tbody[@id='theclassroom_value']/tr[7]/td[2]/div/div/ul/li[8]/a/span").click()
# 添加教室
# driver.find_element_by_xpath("//button[@onclick='addClassroomByCheck(null,$(this));']").click()
# driver.find_element_by_xpath("(//button[@type='button'])[38]").click()
# 选择学校下拉框第二个
# driver.find_element_by_xpath("//tbody[@id='theclassroom_value']/tr[8]/td/div/div/ul/li[3]/a").click()
# driver.find_element_by_xpath("(//button[@type='button'])[39]").click()
# driver.find_element_by_xpath("//tbody[@id='theclassroom_value']/tr[8]/td[2]/div/div/ul/li[3]/a").click()
# click ok btn
sleep(0.5)
driver.find_element_by_css_selector("div.middle_content.finalast > button.btn.btn-success").click()
sleep(2)
def add_lesson(driver):
"""
Func desc
Args:
-
Usage:
"""
'''添加互动课'''
driver.refresh()
driver.find_element_by_link_text(u"课堂管理").click()
sleep(0.5)
driver.find_element_by_link_text(u"互动教学").click()
sleep(0.5)
driver.find_element_by_id("addclassroom").click()
sleep(0.5)
driver.find_element_by_xpath("(//button[@type='button'])[13]").click()
sleep(0.5)
driver.find_element_by_xpath(
"//div[@id='main-container']/div/div[2]/div/div[2]/div/div/div/div/div/ul/li[2]/a/span"
).click()
sleep(0.5)
driver.find_element_by_xpath("(//button[@type='button'])[14]").click()
sleep(0.5)
driver.find_element_by_xpath(
"//div[@id='main-container']/div/div[2]/div/div[2]/div/div[2]/div/div/ul/li[4]/a/span"
).click()
sleep(0.5)
driver.find_element_by_id("teachLesson_input_text").clear()
driver.find_element_by_id("teachLesson_input_text").send_keys("hdk_long")
sleep(0.5)
driver.find_element_by_xpath("(//button[@type='button'])[15]").click()
sleep(0.5)
driver.find_element_by_link_text(u"一年级").click()
sleep(0.5)
driver.find_element_by_xpath("(//button[@type='button'])[16]").click()
sleep(0.5)
driver.find_element_by_link_text(u"语文").click()
sleep(0.5)
driver.find_element_by_xpath("(//button[@type='button'])[17]").click()
sleep(0.5)
driver.find_element_by_xpath(
"//div[@id='main-container']/div/div[2]/div/div[2]/div/div[4]/div[3]/div/ul/li[2]/a/span"
).click()
sleep(0.5)
driver.find_element_by_xpath("(//button[@type='button'])[22]").click()
sleep(0.5)
driver.find_element_by_link_text(u"每天").click()
sleep(0.5)
driver.find_element_by_id("jinjie_false").click()
sleep(0.5)
driver.find_element_by_xpath("(//button[@type='button'])[23]").click()
sleep(0.5)
driver.find_element_by_link_text(u"第八节").click()
sleep(0.5)
driver.find_element_by_xpath(
"//div[@id='day_startTime_and_endTime']/div/span[2]").click()
sleep(2)
# 选择时间
# driver.find_element_by_xpath("//div[11]/div[3]/table/tbody/tr[4]/td[7]").click()
driver.find_element_by_xpath("//div[11]/div[3]/table/tfoot/tr/th").click()
# driver.find_element_by_xpath("//div[13]/div[3]/table/tfoot/tr/th").click()
sleep(2)
driver.find_element_by_xpath(
"//div[@id='day_startTime_and_endTime']/div[3]/span[2]/span").click()
sleep(2)
# 选择时间
# driver.find_element_by_xpath("//div[19]/div[3]/table/tbody/tr[5]/td[6]").click()
# driver.find_element_by_xpath("//div[12]/div[3]/table/tbody/tr[4]/td[6]").click()
# driver.find_element_by_xpath("//div[12]/div[3]/table/tbody/tr[4]/td[7]").click()
driver.find_element_by_xpath("//div[12]/div[3]/table/tfoot/tr/th").click()
sleep(0.5)
driver.find_element_by_xpath(
"//button[@onclick='addClassroomByCheck(null,$(this));']").click()
sleep(0.5)
driver.find_element_by_xpath("(//button[@type='button'])[24]").click()
sleep(0.5)
driver.find_element_by_xpath(
"//tbody[@id='theclassroom_value']/tr/td/div/div/ul/li[2]/a/span"
).click()
sleep(0.5)
driver.find_element_by_xpath("(//button[@type='button'])[25]").click()
sleep(0.5)
driver.find_element_by_xpath(
"//tbody[@id='theclassroom_value']/tr/td[2]/div/div/ul/li[2]/a/span"
).click()
sleep(0.5)
driver.find_element_by_xpath(
"//button[@onclick='addClassroomByCheck(null,$(this));']").click()
sleep(0.5)
driver.find_element_by_xpath("(//button[@type='button'])[26]").click()
sleep(0.5)
driver.find_element_by_xpath(
"//tbody[@id='theclassroom_value']/tr[2]/td/div/div/ul/li[2]/a").click(
)
sleep(0.5)
driver.find_element_by_xpath("(//button[@type='button'])[27]").click()
sleep(0.5)
driver.find_element_by_xpath(
"//tbody[@id='theclassroom_value']/tr[2]/td[2]/div/div/ul/li[3]/a/span"
).click()
sleep(0.5)
driver.find_element_by_css_selector(
"div.middle_content.finalast > button.btn.btn-success").click()
sleep(3)
def add_jpk_18(driver):
driver.refresh()
driver.find_element_by_link_text(u"课堂管理").click()
driver.find_element_by_link_text(u"精品课堂").click()
sleep(0.5)
driver.find_element_by_id("addclassroom").click()
sleep(0.5)
driver.find_element_by_xpath("(//button[@type='button'])[13]").click()
sleep(0.5)
driver.find_element_by_xpath("//div[@id='main-container']/div/div[2]/div/div[2]/div/div[2]/div/div/div/ul/li[3]/a/span").click()
driver.find_element_by_xpath("(//button[@type='button'])[14]").click()
# driver.find_element_by_link_text(u"81教室").click()
driver.find_element_by_xpath("//div[@id='classOrTeacher']/div/div/ul/li[2]/a").click()
driver.find_element_by_id("teachLesson_input_text").clear()
driver.find_element_by_id("teachLesson_input_text").send_keys("jpk_long")
driver.find_element_by_xpath("(//button[@type='button'])[16]").click()
driver.find_element_by_link_text(u"一年级").click()
driver.find_element_by_xpath("(//button[@type='button'])[17]").click()
driver.find_element_by_link_text(u"语文").click()
driver.find_element_by_xpath("(//button[@type='button'])[18]").click()
driver.find_element_by_xpath("//div[@id='lesson_infor']/div[3]/div/ul/li[2]/a/span").click()
driver.find_element_by_id("ptlive_true").click()
driver.find_element_by_xpath("(//button[@type='button'])[23]").click()
driver.find_element_by_link_text(u"周日").click()
driver.find_element_by_xpath("(//button[@type='button'])[24]").click()
driver.find_element_by_link_text(u"第八节").click()
sleep(1)
# driver.find_element_by_css_selector("div.middle_content.finalast > button.btn.btn-success").click()
driver.find_element_by_xpath("//button[@onclick='saveClick();']").click()
sleep(2)
def add_excellentClass(driver):
"""
Func descriptions: add jpk
Args: add_excellentClass()
Return: None
Usage: add_excellentClass(drvier)
Author: wangfm
Date: 2016-11-03 10:10:25
"""
print "add jpk."
try:
driver.refresh()
driver.find_element_by_link_text(u"课堂管理").click()
driver.find_element_by_link_text(u"精品课堂").click()
sleep(0.5)
driver.find_element_by_id("addclassroom").click()
sleep(0.5)
# select school btn
driver.find_element_by_xpath("(//button[@type='button'])[13]").click()
sleep(0.5)
driver.find_element_by_link_text(u"郑州一中").click()
sleep(0.5)
# select classroom
driver.find_element_by_xpath("(//button[@type='button'])[14]").click()
sleep(0.5)
# driver.find_element_by_link_text(u"130教室").click()
driver.find_element_by_xpath("//div[@id='classOrTeacher']/div/div/ul/li[2]/a").click()
# sleep(0.5)
# second class
# driver.find_element_by_xpath("(//button[@type='button'])[14]").click()
# sleep(0.5)
# driver.find_element_by_link_text(u"131教室").click()
sleep(0.5)
# input lesson name
driver.find_element_by_id("teachLesson_input_text").clear()
sleep(0.5)
driver.find_element_by_id("teachLesson_input_text").send_keys("jpk")
sleep(0.5)
# lesson info
driver.find_element_by_xpath("(//button[@type='button'])[15]").click()
sleep(0.5)
driver.find_element_by_link_text(u"一年级").click()
sleep(0.5)
driver.find_element_by_xpath("(//button[@type='button'])[16]").click()
sleep(0.5)
driver.find_element_by_link_text(u"语文").click()
sleep(0.5)
driver.find_element_by_xpath("(//button[@type='button'])[17]").click()
sleep(0.5)
driver.find_element_by_xpath("//div[3]/div/ul/li[2]/a/span").click()
sleep(0.5)
# platform live
driver.find_element_by_xpath("//input[@id='ptlive_true']").click()
sleep(0.5)
# select time
driver.find_element_by_xpath("(//button[@type='button'])[22]").click()
sleep(0.5)
driver.find_element_by_link_text(u"周日").click()
sleep(0.5)
driver.find_element_by_xpath("(//button[@type='button'])[23]").click()
sleep(0.5)
driver.find_element_by_link_text(u"第八节").click()
sleep(0.5)
# commit btn
driver.find_element_by_xpath(
"//button[@onclick='saveClick();']").click()
sleep(2)
except NoSuchElementException as e:
print e
print "add jpk failed."
announcementData = [{
"add_title":u"测试公告",
"noticeType_select":u"网站公告",
"schoolName_select":u"河南省教育局",
'disk': 'Z:\\testResource\py\pic',
'fileNames': 'banner01.jpg'
}]
def add_announcement(driver, **kwargs):
driver.refresh()
driver.find_element_by_link_text(u"网站管理").click()
sleep(0.5)
driver.find_element_by_link_text(u"公告管理").click()
sleep(0.5)
driver.find_element_by_id("addNotice").click()
sleep(0.5)
driver.find_element_by_id("add_title").clear()
driver.find_element_by_id("add_title").send_keys(kwargs["add_title"])
Select(driver.find_element_by_id("noticeType_select")).select_by_visible_text(kwargs["noticeType_select"])
# Select(driver.find_element_by_id("schoolName_select")).select_by_visible_text(kwargs["schoolName_select"])
driver.find_element_by_id("file").click()
sleep(0.5)
file_upload(kwargs["disk"],kwargs["fileNames"])
sleep(0.5)
driver.find_element_by_id("clipBtn").click()
driver.find_element_by_id("add_sure").click()
#文件上传方法
def file_upload(disk,fileNames):
sleep(1)
################################点击文件操作######################################
#shift+alt
# win32api.keybd_event(16, 0, 0, 0) # shift
# win32api.keybd_event(18, 0, 0, 0) # L键位码是73
# win32api.keybd_event(18, 0, win32con.KEYEVENTF_KEYUP, 0) # 释放按键
# win32api.keybd_event(16,0,win32con.KEYEVENTF_KEYUP,0)
# sleep(2)
# ctrl+L
win32api.keybd_event(17, 0, 0, 0) # ctrl键位码是17
win32api.keybd_event(76, 0, 0, 0) # L键位码是73
win32api.keybd_event(76, 0, win32con.KEYEVENTF_KEYUP, 0) # 释放按键
win32api.keybd_event(17, 0, win32con.KEYEVENTF_KEYUP, 0)
SendKeys.SendKeys(disk) # 输入磁盘
SendKeys.SendKeys('{ENTER}') # 发送回车键
sleep(4)
# ALT+N
win32api.keybd_event(18, 0, 0, 0) # ALT键位码是18
win32api.keybd_event(78, 0, 0, 0) # N键位码是78
win32api.keybd_event(78, 0, win32con.KEYEVENTF_KEYUP, 0) # 释放按键
win32api.keybd_event(18, 0, win32con.KEYEVENTF_KEYUP, 0)
SendKeys.SendKeys(fileNames) # 发送文件地址
SendKeys.SendKeys('{ENTER}') # 发送回车键
################################点击文件操作########################################
columnData = [{
"navigationName_add":u"测试栏目名",
"url_add":"10.1.0.19",
"navTypeAdd":u"页眉导航",
'sort_add': '10',
'remark_add': '测试描述'
}]
def add_column(driver, **kwargs):
driver.refresh()
driver.find_element_by_link_text(u"网站管理").click()
sleep(0.5)
driver.find_element_by_link_text(u"栏目管理").click()
sleep(0.5)
driver.find_element_by_id("addBtn").click()
sleep(0.5)
driver.find_element_by_id("navigationName_add").clear()
driver.find_element_by_id("navigationName_add").send_keys(kwargs["navigationName_add"])
driver.find_element_by_id("url_add").clear()
driver.find_element_by_id("url_add").send_keys(kwargs["url_add"])
Select(driver.find_element_by_id("navTypeAdd")).select_by_visible_text(kwargs["navTypeAdd"])
driver.find_element_by_xpath("sort_add").clear()
driver.find_element_by_xpath("sort_add").send_keys(kwargs["sort_add"])
driver.find_element_by_id("add_sure").click()
modelData = [{
"addname":u"测试名称",
"addurl":u"测试地址",
"addremark":u"测试描述",
'addnId': u'在线课堂'
}]
def add_model(driver, **kwargs):
driver.refresh()
driver.find_element_by_link_text(u"网站管理").click()
sleep(0.5)
driver.find_element_by_link_text(u"模板管理").click()
sleep(0.5)
driver.find_element_by_id("addschool").click()
sleep(0.5)
driver.find_element_by_xpath("//input[@name='addname']").clear()
driver.find_element_by_xpath("//input[@name='addname']").send_keys(kwargs["addname"])
driver.find_element_by_xpath("//input[@name='addurl']").clear()
driver.find_element_by_xpath("//input[@name='addurl']").send_keys(kwargs["addurl"])
driver.find_element_by_xpath("//input[@name='addremark']").clear()
driver.find_element_by_xpath("//input[@name='addremark']").send_keys(kwargs["addremark"])
Select(driver.find_element_by_id("addnId")).select_by_visible_text(kwargs["addnId"])
driver.find_element_by_xpath("//div[6]/button").click()
liveData = [{
"endDate":u"2017-12-06 23:50",
"pd_lessionId":u"测试直播标题",
"pd_sd":"480",
'pd_hd': '820',
"pd_uhd":"1280",
'pd_classroom': u'测试主讲教室',
"subject_all_option":"数学",
"pd_order":u"第二节",
"pd_lessionType":u"视频会议",
"pd_province":u"安徽省",
"pd_city":u"芜湖市",
"pd_area":u"镜湖区",
'disk': 'Z:\\testResource\\py\\pic',
'fileNames': 'banner01.png'
}]
class win32Doc:
_public_methods_ = ['write']
def write(self, s):
print s
def add_live(driver, **kwargs):
'''添加直播管理'''
driver.refresh()
driver.find_element_by_link_text(u"内容管理").click()
sleep(0.5)
driver.find_element_by_link_text(u"直播管理").click()
sleep(0.5)
driver.find_element_by_xpath("//div[@id='main-container']/div/div[2]/div/div[2]/div/button[3]").click()
driver.find_element_by_id("addList").click()
sleep(0.5)
# driver.find_element_by_id("startDate").clear()
#获取当前时间
dataTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
# driver.find_element_by_id("startDate").send_keys(startdataTime)
startTime="$(\"#startDate\").removeAttr('readonly');$(\"#startDate\").val('"+dataTime+"')"
stopTime="$(\"#endDate\").removeAttr('readonly');$(\"#endDate\").val('"+kwargs["endDate"]+"')"
driver.execute_script(startTime)
driver.execute_script(stopTime)
driver.find_element_by_id("pdLession_id").clear()
driver.find_element_by_id("pdLession_id").send_keys(kwargs["pd_lessionId"])
driver.find_element_by_id("sd_url").clear()
driver.find_element_by_id("sd_url").send_keys(kwargs["pd_sd"])
driver.find_element_by_id("hd_url").clear()
driver.find_element_by_id("hd_url").send_keys(kwargs["hd_url"])
driver.find_element_by_id("uhd_url").clear()
driver.find_element_by_id("uhd_url").send_keys(kwargs["pd_uhd"])
driver.find_element_by_id("file_1").click()
file_upload(kwargs["disk"],kwargs["fileNames"])
sleep(0.5)
driver.find_element_by_id("clipBtn_1").click()
driver.find_element_by_id("classroom_name").clear()
driver.find_element_by_id("classroom_name").send_keys(kwargs["pd_classroom"])
Select(driver.find_element_by_id("school_name")).select_by_visible_text(kwargs["pd_schoolName"])
Select(driver.find_element_by_id("subject_all_option")).select_by_visible_text(kwargs["subject_all_option"])
Select(driver.find_element_by_id("order_name_option")).select_by_visible_text(kwargs["pd_order"])
Select(driver.find_element_by_id("class_type_option")).select_by_visible_text(kwargs["pd_lessionType"])
Select(driver.find_element_by_id("province_option")).select_by_visible_text(kwargs["pd_province"])
sleep(0.5)
Select(driver.find_element_by_id("city_option")).select_by_visible_text(kwargs["pd_city"])
sleep(0.5)
Select(driver.find_element_by_id("area_option")).select_by_visible_text(kwargs["pd_area"])
sleep(10)
driver.find_element_by_id("sureAdd").click()
sleep(10)
# driver.find_element_by_id("pd_lessionId").clear()
# driver.find_element_by_id("pd_lessionId").send_keys(kwargs["pd_lessionId"])
# driver.find_element_by_id("pd_sd").clear()
# driver.find_element_by_id("pd_sd").send_keys(kwargs["pd_sd"])
# driver.find_element_by_id("pd_hd").clear()
# driver.find_element_by_id("pd_hd").send_keys(kwargs["pd_hd"])
# driver.find_element_by_id("pd_uhd").clear()
# driver.find_element_by_id("pd_uhd").send_keys(kwargs["pd_uhd"])
# driver.find_element_by_id("file_2").click()
# file_upload(kwargs["disk"],kwargs["fileNames"])
# driver.find_element_by_id("clipBtn_2").click()
# driver.find_element_by_id("pd_classroom").clear()
# driver.find_element_by_id("pd_classroom").send_keys(kwargs["pd_classroom"])
# Select(driver.find_element_by_id("pd_schoolName")).select_by_visible_text(kwargs["pd_schoolName"])
# Select(driver.find_element_by_id("pd_order")).select_by_visible_text(kwargs["pd_order"])
# Select(driver.find_element_by_id("pd_lessionType")).select_by_visible_text(kwargs["pd_lessionType"])
# Select(driver.find_element_by_id("pd_province")).select_by_visible_text(kwargs["pd_province"])
# Select(driver.find_element_by_id("pd_city")).select_by_visible_text(kwargs["pd_city"])
# Select(driver.find_element_by_id("pd_area")).select_by_visible_text(kwargs["pd_area"])
#
# driver.find_element_by_id("sureUpdate").click()
#文件上传方法
def file_upload(disk,fileNames):
sleep(1)
################################点击文件操作######################################
#shift+alt
# win32api.keybd_event(16, 0, 0, 0) # shift
# win32api.keybd_event(18, 0, 0, 0) # L键位码是73
# win32api.keybd_event(18, 0, win32con.KEYEVENTF_KEYUP, 0) # 释放按键
# win32api.keybd_event(16,0,win32con.KEYEVENTF_KEYUP,0)
# sleep(2)
# ctrl+L
win32api.keybd_event(17, 0, 0, 0) # ctrl键位码是17
win32api.keybd_event(76, 0, 0, 0) # L键位码是73
win32api.keybd_event(76, 0, win32con.KEYEVENTF_KEYUP, 0) # 释放按键
win32api.keybd_event(17, 0, win32con.KEYEVENTF_KEYUP, 0)
SendKeys.SendKeys(disk) # 输入磁盘
SendKeys.SendKeys('{ENTER}') # 发送回车键
sleep(4)
# ALT+N
win32api.keybd_event(18, 0, 0, 0) # ALT键位码是18
win32api.keybd_event(78, 0, 0, 0) # N键位码是78
win32api.keybd_event(78, 0, win32con.KEYEVENTF_KEYUP, 0) # 释放按键
win32api.keybd_event(18, 0, win32con.KEYEVENTF_KEYUP, 0)
SendKeys.SendKeys(fileNames) # 发送文件地址
SendKeys.SendKeys('{ENTER}') # 发送回车键
################################点击文件操作########################################
if __name__ == '__main__':
driver = webdriver.Chrome()
user_login(driver, **loginInfo)
# conf_child_interact(driver, '10.1.0.45', '10.1.0.56')
# conf_mcu(driver)
# conf_drivers_local(driver)
for terminal in announcementData:
add_announcement(driver, ** terminal)
|
class MinStack(object):
def __init__(self):
"""
initialize your data structure here.
"""
self.data = []
self.minstack = []
def push(self, x):
"""
:type x: int
:rtype: nothing
"""
self.data.append(x)
if (not self.minstack) or(x <= self.minstack[-1]):
self.minstack.append(x)
def pop(self):
"""
:rtype: nothing
"""
top = self.data.pop()
if top<=self.minstack[-1]:
self.minstack.pop()
return top
def top(self):
"""
:rtype: int
"""
return self.data[-1]
def getMin(self):
"""
:rtype: int
"""
#print self.data
#print self.minstack
return self.minstack[-1]
if __name__=='__main__':
ms = MinStack()
ms.push(-2)
ms.push(0)
ms.push(-1)
print ms.getMin()
print ms.top()
ms.pop()
print ms.getMin()
|
# Copyright 2017 Google Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless 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.
"""Library for computing the parallization and routing for streaming queries.
The client computes the keyranges to parallelize over
based on the desired parallization and shard count.
Please note that the shard count maybe greater than equal
to actual shards. It is suggested to keep this value
at the upsharded count in case a resharding event is planned.
These keyranges can then be used to derived the routing
information. The routing information object is supposed to
be opaque to the client but VTGate uses it to route queries.
It is also used to compute the associated where clause to be added
to the query, wich is needed to prevent returning duplicate result
from two parallelized queries running over the same shard.
API usage -
task_map = vtrouting.create_parallel_task_keyrange_map(num_tasks, shard_count)
keyrange_list = task_map.keyrange_list
for db_keyrange in keyrange_list:
vt_routing_info = vtrouting.create_vt_routing_info(db_keyrange, 'ruser')
During query construction -
where_clause, bind_vars = vt_routing_info.update_where_clause(
where_clause, bind_vars)
"""
from vtdb import dbexceptions
from vtdb import keyrange
from vtdb import keyrange_constants
from vtdb import topology
class TaskKeyrangeMap(object):
"""Class for computing keyranges for parallel tasks.
Attributes:
num_tasks: number of parallel queries.
"""
def __init__(self, num_tasks):
self.num_tasks = num_tasks
self.keyrange_list = []
self.compute_kr_list()
def compute_kr_list(self):
"""compute the keyrange list for parallel queries.
"""
kr_chunks = []
# we only support 256 shards for now
min_key_hex = int('00', base=16)
max_key_hex = int('100', base=16)
kr = min_key_hex
span = (max_key_hex - min_key_hex)/self.num_tasks
kr_chunks.append('')
for i in xrange(self.num_tasks):
kr += span
kr_chunks.append('%.2x' % kr)
kr_chunks[-1] = ''
for i in xrange(len(kr_chunks) - 1):
start = kr_chunks[i]
end = kr_chunks[i+1]
kr = keyrange.KeyRange((start, end,))
self.keyrange_list.append(str(kr))
class VTRoutingInfo(object):
"""Class to encompass the keyrange and compute the where clause with the same.
Attributes:
db_keyrange: the keyrange to route the query to.
extra_where_clause: where clause with the sharding key for the keyspace.
extra_bind_vars: bind var dictionary with the sharding key for the keyspace.
"""
def __init__(self, db_keyrange, where_clause, bind_vars):
self.db_keyrange = db_keyrange
self.extra_where_clause = where_clause
self.extra_bind_vars = bind_vars
def update_where_clause(self, where_clause, bind_vars):
"""Updates the existing where clause of the query with the routing info.
Args:
where_clause: the where_clause of the query being constructed.
bind_vars: bind_vars of the query being constructed.
Returns:
updated where_clause and bind_vars with the sharding key
of the keyspace and the db_keyrange.
Example -
Assuming sharding key of keyspace 'test_keyspace' is
'keyspace_id'.
returned_where_clause = where_clause AND keyspace_id <= <db_keyrange>
returned_bind_vars = {'keyspace_id': <db_keyrange>}
"""
if self.extra_where_clause:
if where_clause:
where_clause += ' AND ' + self.extra_where_clause
else:
where_clause = self.extra_where_clause
if self.extra_bind_vars:
bind_vars.update(self.extra_bind_vars)
return where_clause, bind_vars
def create_parallel_task_keyrange_map(num_tasks, shard_count):
"""Compute the task map for a streaming query.
Args:
num_tasks: desired parallelization of queries.
shard_count: configurable global shard count for keyspace.
This can be greater than actual shards and should be set to
the desired upsharded value before a resharding event.
This is so that the keyrange->shard map for an inflight
query is always unique.
Returns:
TaskKeyrangeMap object
"""
if num_tasks % shard_count != 0:
raise dbexceptions.ProgrammingError(
'tasks %d should be multiple of shard_count %d' % (num_tasks,
shard_count))
return TaskKeyrangeMap(num_tasks)
def create_vt_routing_info(key_range, keyspace_name):
"""Creates VTRoutingInfo object for the given key_range in keyspace.
Args:
key_range: keyrange for query routing.
keyspace_name: target keyspace for the query. This is used to derive
sharding column type and column name information for the where clause.
Returns:
VTRoutingInfo object.
"""
col_name, col_type = topology.get_sharding_col(keyspace_name)
if not col_name or col_type == keyrange_constants.KIT_UNSET:
return VTRoutingInfo(key_range, '', {})
where_clause, bind_vars = _create_where_clause_for_keyrange(key_range,
col_name,
col_type)
return VTRoutingInfo(key_range, where_clause, bind_vars)
def _true_int_kr_value(kr_value):
"""This returns the true value of keyrange for comparison with keyspace_id.
We abbreviate the keyranges for ease of use.
To obtain true value for comparison with keyspace id,
create true hex value for that keyrange by right padding and conversion.
Args:
kr_value: short keyranges as used by vitess.
Returns:
complete hex value of keyrange.
"""
if kr_value == '':
return None
kr_value += (16-len(kr_value))*'0'
if not kr_value.startswith('0x'):
kr_value = '0x' + kr_value
return int(kr_value, base=16)
def _create_where_clause_for_keyrange(
key_range, keyspace_col_name='keyspace_id',
keyspace_col_type=keyrange_constants.KIT_UINT64):
"""Compute the where clause and bind_vars for a given keyrange.
Args:
key_range: keyrange for the query.
keyspace_col_name: keyspace column name of keyspace.
keyspace_col_type: keyspace column type of keyspace.
Returns:
where clause for the keyrange.
"""
if isinstance(key_range, str):
# If the key_range is for unsharded db, there is no
# where clause to add to or bind_vars to add to.
if key_range == keyrange_constants.NON_PARTIAL_KEYRANGE:
return '', {}
key_range = key_range.split('-')
if (not isinstance(key_range, tuple) and not isinstance(key_range, list) or
len(key_range) != 2):
raise dbexceptions.ProgrammingError(
'key_range must be list or tuple or \'-\' separated str %s' % key_range)
if keyspace_col_type == keyrange_constants.KIT_UINT64:
return _create_where_clause_for_int_keyspace(key_range, keyspace_col_name)
elif keyspace_col_type == keyrange_constants.KIT_BYTES:
return _create_where_clause_for_str_keyspace(key_range, keyspace_col_name)
else:
raise dbexceptions.ProgrammingError(
'Illegal type for keyspace_col_type %d' % keyspace_col_type)
def _create_where_clause_for_str_keyspace(key_range, keyspace_col_name):
"""This creates the where clause and bind_vars if keyspace_id col is a str.
The comparison is done using mysql hex function and byte level comparison
with the key_range values.
Args:
key_range: keyrange for the query.
keyspace_col_name: keyspace column name for the keyspace.
Returns:
This returns the where clause when the keyspace column type is string.
"""
kr_min = key_range[0].strip()
kr_max = key_range[1].strip()
where_clause = ''
bind_vars = {}
i = 0
if kr_min != keyrange_constants.MIN_KEY:
bind_name = '%s%d' % (keyspace_col_name, i)
where_clause = 'hex(%s) >= ' % keyspace_col_name + '%(' + bind_name + ')s'
i += 1
bind_vars[bind_name] = kr_min
if kr_max != keyrange_constants.MAX_KEY:
if where_clause:
where_clause += ' AND '
bind_name = '%s%d' % (keyspace_col_name, i)
where_clause += 'hex(%s) < ' % keyspace_col_name + '%(' + bind_name + ')s'
bind_vars[bind_name] = kr_max
return where_clause, bind_vars
def _create_where_clause_for_int_keyspace(key_range, keyspace_col_name):
"""This creates the where clause and bind_vars if keyspace_id col is a int.
The comparison is done using numeric comparison on the int values hence
the true 64-bit int values are generated for the key_range in the bind_vars.
Args:
key_range: keyrange for the query.
keyspace_col_name: keyspace column name for the keyspace.
Returns:
This returns the where clause when the keyspace column type is uint64.
"""
kr_min = _true_int_kr_value(key_range[0])
kr_max = _true_int_kr_value(key_range[1])
where_clause = ''
bind_vars = {}
i = 0
if kr_min is not None:
bind_name = '%s%d' % (keyspace_col_name, i)
where_clause = '%s >= ' % keyspace_col_name + '%(' + bind_name + ')s'
i += 1
bind_vars[bind_name] = kr_min
if kr_max is not None:
if where_clause:
where_clause += ' AND '
bind_name = '%s%d' % (keyspace_col_name, i)
where_clause += '%s < ' % keyspace_col_name + '%(' + bind_name + ')s'
bind_vars[bind_name] = kr_max
return where_clause, bind_vars
|
import numpy as np
import lasagne
from copy import deepcopy
def combine_temporal_spatial_weights(temporal_weights, spatial_weights):
# Compute combined the weights.
# We have to reverse them with ::-1 to change convolution to cross-correlation
temporal_weights = temporal_weights[:,:,::-1,::-1]
spat_filt_weights = spatial_weights[:,:,::-1,::-1]
combined_weights = np.tensordot(spat_filt_weights, temporal_weights, axes=(1,0))
combined_weights = combined_weights.squeeze()
return combined_weights
def transform_to_combined_weights(model, i_temp_layer=2):
new_model = deepcopy(model)
all_layers = lasagne.layers.get_all_layers(new_model)
temp_layer = all_layers[i_temp_layer]
spat_layer = all_layers[i_temp_layer+1]
after_conv_layer = all_layers[i_temp_layer+2]
temp_weights = temp_layer.W.get_value()
spat_filt_weights = spat_layer.W.get_value()
combined_weights = combine_temporal_spatial_weights(temp_weights,
spat_filt_weights)
temp_biases = temp_layer.b.get_value()
# Take care to multiply along correct axis (second, not first)
temp_biases_weighted = temp_biases[np.newaxis, :, np.newaxis, np.newaxis] * spat_filt_weights
spat_biases = spat_layer.b.get_value()
combined_biases = np.sum(temp_biases_weighted, axis=(1,2,3)) + spat_biases
combined_layer = lasagne.layers.Conv2DLayer(all_layers[i_temp_layer - 2],
num_filters = combined_weights.shape[0],
filter_size=[combined_weights.shape[2], 1],
nonlinearity=spat_layer.nonlinearity)
combined_layer.W.set_value(combined_weights[:,:,::-1,np.newaxis])
combined_layer.b.set_value(combined_biases)
after_conv_layer.input_layer = combined_layer
new_model = all_layers[-1]
return new_model |
import sys
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import MultipleLocator
majorLocatorX = MultipleLocator(2)
minorLocatorX = MultipleLocator(1)
majorLocatorY = MultipleLocator(0.5)
minorLocatorY = MultipleLocator(0.25)
filename = 'PR_final.dat'
filename2 = 'EOM_IMSRG_FEI_HAM_particle_removed.dat'
x = [[] for i in range(3)]
y = [[] for i in range(3)]
x2 = [[] for i in range(3)]
y2 = [[] for i in range(3)]
shells = int(sys.argv[1])
hw = float(sys.argv[2])
with open(filename) as f:
data = f.read()
data = data.split('\n')
for num in range(2,len(data)):
line = data[num].split()
if(int(line[1]) == shells and float(line[4]) == hw):
ind = int(line[2])
x[ind].append(float(line[0]))
y[ind].append(float(line[6]))
with open(filename2) as f2:
data2 = f2.read()
data2 = data2.split('\n')
for num in range(2,len(data2)):
line = data2[num].split()
if(int(line[1]) == shells and float(line[4]) == hw):
ind = int(line[2])
x2[ind].append(float(line[0]))
y2[ind].append(float(line[6]))
plt.rc('font', family='serif')
fig, ax = plt.subplots()
ax.plot(x[0], y[0], '-', marker='o', color='k', label='$\mathrm{CCSD: m_{l}=0}$')
ax.plot(x[1], y[1], '--', marker='s', color='k', label='$\mathrm{CCSD: m_{l}=1}$')
ax.plot(x[2], y[2], ':', marker='^', color='k', label='$\mathrm{CCSD: m_{l}=2}$')
ax.plot(x2[0], y2[0], '-', marker='o', color='r', label='$\mathrm{IM-SRG: m_{l}=0}$')
ax.plot(x2[1], y2[1], '--', marker='s', color='r', label='$\mathrm{IM-SRG: m_{l}=1}$')
ax.plot(x2[2], y2[2], ':', marker='^', color='r', label='$\mathrm{IM-SRG: m_{l}=2}$')
ax.legend(loc='lower right')
plt.xlabel(r'$\mathrm{Total Shells}$', fontsize=15)
plt.ylabel(r'$\mathrm{\Delta E_{k}}$', fontsize=15)
plt.axis([5, 21, -13.75, -12])
annotation_string = r'$\mathrm{\hbar\omega=1.00}$'
annotation_string += '\n'
annotation_string += r'$\mathrm{20\ particles}$'
ax.annotate(annotation_string, fontsize=15, xy=(6, -12.25))
ax.xaxis.set_major_locator(majorLocatorX)
ax.xaxis.set_minor_locator(minorLocatorX)
ax.yaxis.set_major_locator(majorLocatorY)
ax.yaxis.set_minor_locator(minorLocatorY)
plt.savefig('PRfig_'+str(shells)+'_'+str(hw)+'.pdf', format='pdf', bbox_inches='tight')
plt.show()
|
programmer = True
if programmer is True:
print('You are awesome!')
is_programmer = False
if is_programmer is True:
print('You are awesome!')
else:
print('Learn some programming!')
if is_programmer:
print('You are awesome!')
if is_programmer is False:
print('Learn some programming!')
else:
print('You are awesome!')
if is_programmer is not True:
print('Learn some programming!')
if not is_programmer:
print('Learn some programming!')
is_programmer = False
is_awesome = True
if is_programmer:
print("You're the best!")
elif is_awesome:
print("Not the best, but still awesome.")
else:
print('Be awesome!')
|
"""
Game Development basic project. A character stays in the centre of the screen and the environment moves around him.
Author : Pranay Venkatesh
"""
import pygame
# Basic pygame parameters
pygame.init()
win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("pranay.io")
# Background parameters
bg = pygame.image.load('bg.png')
imgposx = 0
imgposy = 0
# Character Parameters
posx = 250
posy = 250
velocity = 3
def refresh():
win.fill((0,0,0))
win.blit(bg, (imgposx, imgposy))
pygame.draw.circle(win, (255, 0, 0), (250, 250), 10)
pygame.display.update()
run = True
while run:
refresh()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
break
pressed = pygame.key.get_pressed()
if pressed[pygame.K_UP]:
if posy > 0:
posy -= velocity
imgposy += velocity
if pressed[pygame.K_DOWN]:
if posy < 1200:
posy += velocity
imgposy -= velocity
if pressed[pygame.K_LEFT]:
if posx > 0:
posx -= velocity
imgposx += velocity
if pressed[pygame.K_RIGHT]:
if posx < 1920:
posx += velocity
imgposx -= velocity
exit()
|
import unittest
from katas.kyu_8.count_the_monkeys import monkey_count
class MonkeyCountTestCase(unittest.TestCase):
def test_equals(self):
self.assertEqual(monkey_count(5), [1, 2, 3, 4, 5])
def test_equals_2(self):
self.assertEqual(monkey_count(3), [1, 2, 3])
def test_equals_3(self):
self.assertEqual(monkey_count(9), [1, 2, 3, 4, 5, 6, 7, 8, 9])
def test_equals_4(self):
self.assertEqual(monkey_count(10), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])
def test_equals_5(self):
self.assertEqual(
monkey_count(20), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
14, 15, 16, 17, 18, 19, 20]
)
|
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import tensorflow as tf
def tensors_filter(tensors, filters, combine_type='or'):
assert isinstance(tensors, (list, tuple)), '`tensors` shoule be a list or tuple!'
assert isinstance(filters, (str, list, tuple)), '`filters` should be a string or a list(tuple) of strings!'
assert combine_type == 'or' or combine_type == 'and', "`combine_type` should be 'or' or 'and'!"
if isinstance(filters, str):
filters = [filters]
f_tens = []
for ten in tensors:
if combine_type == 'or':
for filt in filters:
if filt in ten.name:
f_tens.append(ten)
break
elif combine_type == 'and':
all_pass = True
for filt in filters:
if filt not in ten.name:
all_pass = False
break
if all_pass:
f_tens.append(ten)
return f_tens
def global_variables(filters=None, combine_type='or'):
global_vars = tf.global_variables()
if filters is None:
return global_vars
else:
return tensors_filter(global_vars, filters, combine_type)
def trainable_variables(filters=None, combine_type='or'):
t_var = tf.trainable_variables()
if filters is None:
return t_var
else:
return tensors_filter(t_var, filters, combine_type)
|
from django.conf.urls import include, url, patterns
import sentiment.views as view
urlpatterns = patterns('',
url(r'^yahoo/(?P<symbol>[a-zA-Z]+)/$', view.YahooArticleListView.as_view(), name='search'),
url(r'^article_sentiment/$', view.ArticleSentiment.as_view(), name='sentiment'),
url(r'^text/$', view.TextSentimentView.as_view(), name='text'),
url(r'^search/random$', view.SearchView.as_view(), name ='postsearch'),
url(r'^search/lists$', view.SearchListView.as_view(), name ='listsearch'),
url(r'^oauth/$', view.AppView.as_view(), name='oauth'),
url(r'^callback/$', view.CallbackView.as_view(), name ='index')
) |
from rest_framework import routers
from django.urls import path
from . import views
ROUTER = routers.SimpleRouter()
ROUTER.register(r"logs", views.ApiLogViewSet)
urlpatterns = ROUTER.urls + [
path(r"login/", views.ObtainTokenView.as_view(), name="login"),
path(r"workerlog/", views.CeleryDebugTaskView.as_view(), name="workerlog"),
]
|
#!/usr/bin/python3
#Auth: Kube, James
#AuthDate: 20200705
# --------------------------------------------------------------------------
# |Purpose: |
# |--------------------------------------------------------------------------|
# |Check Kubra outage map for last update time to ensure that the last |
# |uploaded file was successfully consumed by Kubra and updated on the |
# |outage map page. |
# --------------------------------------------------------------------------
# --------------------------------------------------------------------------
# |Note: |
# |--------------------------------------------------------------------------|
# |Kubra.com currently consumes files, and updates the map, every 15 minutes.|
# --------------------------------------------------------------------------
import json
import requests
import time
if __name__ == '__main__':
print("...for the modules")
def getTheData(kubra_base_url,kubra_cust_base,kubra_cust_site):
"""
Construct target URL and return the JSON
"""
myURL = kubra_base_url+kubra_cust_base+'/views/'+kubra_cust_site+\
'/currentState?preview=false'
myRequest = requests.get(myURL)
myReturnDict = json.loads(myRequest.text)
return myReturnDict
def parseTheData(kubra_output_data_json2Dict):
"""
Parse the provided dict and return the epoch timestamp
"""
if 'updatedAt' in kubra_output_data_json2Dict.keys():
return kubra_output_data_json2Dict['updatedAt']
else:
return 0
def timeStampComparison(lastUpdatedEpochTimeStamp,desiredInterval=30):
"""
Consume the provided epoch timestamp and compare tor our desired update
interval.
Use 30 minutes as the default desired update interval to account for lagl
return 0 if unexpected 'last update' timestamp, 1 otherwise
"""
currEpochTime = time.time()
epochDelta = int(currEpochTime - lastUpdatedEpochTimeStamp)
#epochDeltaMinutes = epochDelta/60
epochDeltaMinutes = epochDelta
if epochDeltaMinutes <= desiredInterval:
print("Here's our currEpochTime ",currEpochTime)
print("Here's our lastUpdatedEpochTimeStamp ",lastUpdatedEpochTimeStamp)
print("Here's our epochDeltaMinutes ",epochDeltaMinutes)
return 1
else:
return 0
|
from django.urls import path
from .views import CategoriesView,CategoriesViewDetail,CategoriesAdd,CategoriesUpdate,CategoriesDelete
urlpatterns = [
path('view/', CategoriesView.as_view()),
path('viewDetail/', CategoriesViewDetail.as_view()),
path('create/' ,CategoriesAdd.as_view()),
path('update/<str:pk>/' ,CategoriesUpdate.as_view()),
path('delete/<str:pk>/' ,CategoriesDelete.as_view()),
]
|
from django.shortcuts import render
from django.template import RequestContext
from .models import data_locality
def BeersAll(request):
beers = data_locality.objects.all().order_by('name')
#beers = Beer.description.maketrans().order_by('name')
context = {'data': data_locality}
return render(request, 'beersall.html', context)
return render(request, 'beersall.html', context)
return render(request, 'beersall.html', context) |
# Copyright 2014 Google.
#
# 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.
"""X264 codec definition.
This file defines how to run encode and decode for the x264 implementation
of H.264.
"""
import encoder
import file_codec
class X264Codec(file_codec.FileCodec):
def __init__(self, name='x264', formatter=None):
super(X264Codec, self).__init__(
name,
formatter=(formatter or encoder.OptionFormatter(prefix='--', infix=' ')))
self.extension = 'mkv'
self.option_set = encoder.OptionSet(
encoder.Option('preset', ['ultrafast', 'superfast', 'veryfast',
'faster', 'fast', 'medium', 'slow', 'slower',
'veryslow', 'placebo']),
encoder.Option('rc-lookahead', ['0', '30', '60']),
encoder.Option('vbv-init', ['0.5', '0.8', '0.9']),
encoder.Option('ref', ['1', '2', '3', '16']),
encoder.ChoiceOption(['use-vbv-maxrate']),
encoder.Option('profile', ['baseline', 'main', 'high']),
encoder.Option('tune', ['psnr', 'ssim']),
encoder.DummyOption('vbv-maxrate'),
encoder.DummyOption('vbv-bufsize'),
)
def StartEncoder(self, context):
return encoder.Encoder(context, encoder.OptionValueSet(
self.option_set,
'--preset slow --tune psnr',
formatter=self.option_formatter))
def EncodeCommandLine(self, parameters, bitrate, videofile, encodedfile):
# The use-vbv-maxrate flag controls whether vbv-maxrate/vbv-bufsize
# are used. They may be unneeded.
# Still no opinion: '--no-scenecut --keyint infinite '
if parameters.HasValue('use-vbv-maxrate'):
parameters = parameters.RemoveValue('use-vbv-maxrate')
parameters = parameters.ChangeValue('vbv-maxrate', str(bitrate))
parameters = parameters.ChangeValue('vbv-bufsize', str(bitrate))
commandline = ('%(x264)s '
'--bitrate %(bitrate)d --fps %(framerate)d '
'--threads 1 '
'--input-res %(width)dx%(height)d '
'--quiet '
'%(parameters)s '
'-o %(outputfile)s %(inputfile)s') % {
'x264': encoder.Tool('x264'),
'bitrate': bitrate,
'framerate': videofile.framerate,
'width': videofile.width,
'height': videofile.height,
'outputfile': encodedfile,
'inputfile': videofile.filename,
'parameters': parameters.ToString()}
return commandline
def DecodeCommandLine(self, videofile, encodedfile, yuvfile):
commandline = '%s -loglevel error -i %s %s' % (encoder.Tool("ffmpeg"),
encodedfile, yuvfile)
return commandline
def ResultData(self, encodedfile):
more_results = {}
more_results['frame'] = file_codec.MatroskaFrameInfo(encodedfile)
return more_results
|
# -*- coding: utf-8 -*-
# @Time : 2019-12-20
# @Author : mizxc
# @Email : xiangxianjiao@163.com
import os
from flask import current_app, request, flash, render_template, redirect, url_for
from flask_login import login_required, current_user
from . import bpHome
from project.model.blog import *
from project.common.dataPreprocess import getPagingParameters
@bpHome.route("/blog")
@bpHome.route("/blog/<page>")
def blog(page=0,columnId=None,tag=None):
page = int(page)
sk = getPagingParameters(page)
ps = Post.objects().order_by('-isTop','-id')[sk[0]:sk[1]]
return render_template('%s/blog.html' % current_user.getCustom()['homeTemplate'],
ps=ps,page=page,mark='blog')
@bpHome.route("/blogColumn/<columnId>")
@bpHome.route("/blogColumn/<columnId>/<page>")
def blogColumn(columnId,page=0):
page = int(page)
sk = getPagingParameters(page)
c = Column.objects(id=columnId).first()
ps = Post.objects(column=c).order_by('-isTop', '-id')[sk[0]:sk[1]]
return render_template('%s/blog.html' % current_user.getCustom()['homeTemplate'],
ps=ps,page=page,mark='blog',c=c)
@bpHome.route("/blogTag/<tag>")
@bpHome.route("/blogTag/<tag>/<page>")
def blogTag(tag,page=0):
page = int(page)
sk = getPagingParameters(page)
ps = Post.objects(tags=tag).order_by('-isTop', '-id')[sk[0]:sk[1]]
return render_template('%s/blog.html' % current_user.getCustom()['homeTemplate'],
ps=ps,page=page,mark='blog',tag=tag)
@bpHome.route("/blogSearch",methods=['GET','POST'])
@bpHome.route("/blogSearch/<search>/<page>",methods=['GET','POST'])
def blogSearch(search=None,page=0):
if not search:
search = request.form['search']
page = int(page)
sk = getPagingParameters(page)
ps = Post.objects.search_text(search)[sk[0]:sk[1]]
return render_template('%s/blog.html' % current_user.getCustom()['homeTemplate'],
ps=ps,page=page,mark='blog',search=search)
@bpHome.route("/blogShow/<id>")
def blogShow(id):
p = Post.objects(id=id).first()
p.pv += 1
p.save()
return render_template('%s/blogShow.html' % current_user.getCustom()['homeTemplate'],
p=p,mark='blog')
|
#!/usr/bin/env python27
#-*- coding:utf-8 -*-
#print 'hello,%s!welcome my house'%'jack'
#r=72
#print '%d' % r
# arr=['zhangsanfeng','lisinan']
# arr.append('jiangyuan') #末尾追加
# print arr
# arr.insert(1,'zhaowu') #指定位置追加
# print arr
# arr.pop(1) #删除指定位置
# print len(arr)#长度
# str="1111111111"
# print len(str)
# tuple=([1,2],)
# tuple[0][1]=3
# print tuple
#test
# L = [
# ['Apple', 'Google', 'Microsoft'],
# ['Java', 'Python', 'Ruby', 'PHP'],
# ['Adam', 'Bart', 'Lisa']
# ]
# print 'Apple=%s' % L[0][0]
# print 'Python=%s' % L[1][1]
# print 'Lisa=%s' % L[2][2]
# a=-100
# print abs(a) #绝对值
# arr=[5,5,2,6,5]
# print max(arr)
# n1=255
# n2=1000
# print hex(n1)
# print hex(n2)
#定义一个函数
# def my_abs(x):
# if x>=0:
# return x
# else:
# return -x
# a=my_abs(-1)
# print a
# def my_abs(x):
# #isinstance(a,type) 检测输入的字符是否合法
# if not isinstance(x,int):
# raise TypeError(u'请输入数字')
# if x>0:
# return x
# else:
# return -x
# a=input()
# print my_abs(a)
#导入模块
# import math
# #横坐标、纵、步、角度
# def move(x,y,step,angle=0):
# nx=x+step*math.cos(angle)
# ny=y-step*math.sin(angle)
# return nx,ny
# x,y=move(1000,500,60,math.pi/6)
# print (x,y) #返回值为 tuple 类型
# t=(1,2,3)
# for i in t:
# print i
# import math
# a*x^2+b*x+c=0
# def quadratic(a,b,c):
# r=b*b-4*a*c
# x1=0
# x2=0
# if r<0:
# print 'no result'
# pass
# elif r==0:
# x1=-(b+math.sqrt(b*b-4*a*c))/2*a
# else:
# x1=-(b+math.sqrt(b*b-4*a*c))/2*a
# x2=-(b-math.sqrt(b*b-4*a*c))/2*a
# return x1,x2
# a=quadratic(1,-5,6)
# print a
# def calc(*numbers):
# sum=0
# for n in numbers:
# sum+=n*n
# return sum
# t=(1,5,6)
# a=calc(*t)
# print a
#关键字参数
# def person(name,age,**kw):
# print 'name:',name,'age:',age,'other:',kw
# person('zhangsanfeng',20,sex='man')
#递归函数
# def fn(n=1):
# if n<=1:
# return 1
# else:
# return fn(n-1)*(n)
# print fn(1000) #栈溢出
# print fn(0)
# def fn(n,p):
# if n<=1:
# return p
# else:
# return fn(n-1,n*p)
# def fn_iter(m):
# return fn(m,1)
# print fn_iter(1000)
#汉诺塔实现
# def move_to(fromm,to):
# print (fromm,'->',to)
# def move(n,a,b,c):
# if n==1:
# move_to(a,c)
# else:
# move(n-1,a,b,c)
# move_to(a,c)
# move(n-1,c,a,b)
# move(3,'A','B','C')
|
from operator import attrgetter,itemgetter, methodcaller
from sets import Set
class Edge():
def __init__(self,source,dest,weight):
self.source=source
self.dest=dest
self.weight=weight
def __repr__(self):
return str(self.source)+" "+str(self.dest)+" "+str(self.weight)
def connects(edge, mst):
source, dest, _ = edge
node = []
for i in range(len(mst)):
if not mst[i][0] in node:
node.append(mst[i][0])
if not mst[i][1] in node:
node.append(mst[i][1])
if ((source in node) and (not dest in node)) or ((not source in node) and (dest in node)):
return True
# for s, d, _ in mst:
# if source == s or source == d or \
# dest == s or dest == d:
# return True
#
return False
def min_connecting_edge(mst,edges):
min_edge = None
for edge in edges:
if connects(edge, mst) and (not min_edge or edge[2] < min_edge[2]):
min_edge=edge
return min_edge
def prim_mst(graph):
mst=[]
edges=[]
for v in graph.keys():
for adjacent in graph[v].keys():
edges.append((v,adjacent,graph[v][adjacent]))
edges=sorted(edges, key=lambda (i,j,k):k, reverse=True)
mst = [edges.pop()]
# #len(graph)=499, since the last node won't have any point connect to it.
# print len(graph)
while len(mst) < len(graph):
min_edge = min_connecting_edge(mst,edges)
edges.remove(min_edge)
mst.append(min_edge)
return mst
def kruskal_mst(edges):
mst=[]
edges=sorted(edges, key=attrgetter('weight','source','dest'))
edge_count=0
nodes_set={}
for node in range(1,501):
nodes_set[node]=[]
nodes_set[node].append(node)
for edge in edges:
if not edge.source in nodes_set[edge.dest]:
nodes_set[edge.source]= nodes_set[edge.source]+nodes_set[edge.dest]
## every list will be updated.
for mid in nodes_set[edge.source]:
nodes_set[mid]=nodes_set[edge.source]
edge_count = edge_count+1
if edge_count == 497:
#print len(mst)
#print "hello2"
#for node in range(1,501):
# print node,nodes_set[node]
#for i in mst:
# print i
print edge
return mst
mst.append(edge)
#print len(mst)
#print edge_count
return mst
if __name__ == '__main__':
f=open("clustering1.txt",'r')
line=f.readline()
numbers=map(int,line.split())
edges=[]
mst=[]
for line in f.readlines():
num=map(int,line.split())
edges.append(Edge(num[0],num[1],num[2]))
mst=kruskal_mst(edges)
sum = 0
#for edge in mst:
# sum = sum + edge.weight
#print mst
print sum
|
import re
from subprocess import Popen, PIPE
from django.http import HttpResponseRedirect, JsonResponse
from django.shortcuts import render
from django.views import View
from django.views.generic import TemplateView
from jyutping.jyutping import get_jyutping
from synthesizer.models import Transcript
from .forms import TranscriptForm
import json
from django.http import HttpResponse, Http404, StreamingHttpResponse
# import json
# from django.http import HttpResponse
# # Create your views here.
# from django.views.decorators.csrf import csrf_exempt
# @csrf_exempt
# def my_api(request):
# dic = {}
# if request.method == 'GET':
# dic['message'] = 0
# return HttpResponse(json.dumps(dic))
# else:
# dic['message'] = '方法错误'
# return HttpResponse(json.dumps(dic, ensure_ascii=False))
class SendDataToFrontEndProView(View):
"""专门从后端传递所需数据给前端
method: Post
access_url: http://ip:port/senddata
"""
def get(self, request):
"""处理post请求
Args:
NA
Returns:
NA
"""
status = "ok"
data = [{"data0":"A"}, {"data1":"B"}, {"data2":"C"},]
return HttpResponse(json.dumps({
"status": status,
"data":data,
}))
# def post(self, request):
# """处理post请求
# Args:
# NA
# Returns:
# NA
# """
# status = "ok"
# data = [{"data0":"A"}, {"data1":"B"}, {"data2":"C"},]
# return HttpResponse(json.dumps({
# "status": status,
# "data":data,
# }))
# Create your views here.
class IndexView(TemplateView):
# print("i am here 0")
template_name = "index.html"
class TranscriptView(View):
form = TranscriptForm
# print("origin form:",form)
template_name = "transcript.html"
# print("i am TranscriptView")
def get(self, request):
form = self.form(request.POST)
print("get form:",form)
return render(self.request, self.template_name, {"form": form})
def post(self, *args, **kwargs):
pk = "/media/wav/cn.wav"
# if self.request.method == "POST" and self.request.is_ajax(): # 异步的时候
if self.request.method == "POST":
form = self.form(self.request.POST)
print("post form:",form)
if form.is_valid():
transcript = str(form.cleaned_data['transcript'])
transcript = str(re.sub("[,。, . ]+", "", transcript))
print("transcript:",transcript)
jyutping = str(" ".join(get_jyutping(transcript)))
print("jyutping:",jyutping)
model = Transcript(transcript=transcript, jyutping=jyutping)
model.save()
pk = str(model.id)
# subprocess.call(['./ossian.sh', str(pk), jyutping], shell=True)
process = Popen(['sudo', './ossian.sh', pk, jyutping], stdin=PIPE, stdout=PIPE,
stderr=PIPE, shell=False)
# output = process.communicate()[0]
output = process.wait()
pk = pk + ".wav"
print("pk:",pk)
return JsonResponse({"success": True, "path": str("/media/wav/{}".format(pk))}, status=200)
return JsonResponse({"success": False}, status=400)
|
def find_runner_up_score():
number_of_scores = int(input())
set_of_scores = set()
scores = input().split(' ')
for index in range(len(scores)):
set_of_scores.add(int(scores[index]))
list_of_scores = sorted(set_of_scores, reverse=True)
return list_of_scores[1]
print(find_runner_up_score())
|
import treadmill
from treadmill.infra.setup import base_provision
from treadmill.infra import configuration, constants
import polling
import logging
_LOGGER = logging.getLogger(__name__)
class IPA(base_provision.BaseProvision):
def __init__(self, *args, **kwargs):
self._instances = None
super().__init__(*args, **kwargs)
@property
def instances(self):
if not self._instances:
self.subnet.refresh()
self.subnet.get_instances(
refresh=True,
role=constants.ROLES['IPA']
)
self._instances = self.subnet.instances
return self._instances
def setup(
self,
image,
count,
cidr_block,
ipa_admin_password,
tm_release,
key,
instance_type,
proid,
subnet_name,
):
treadmill.infra.get_iam_role(
name=constants.IPA_EC2_IAM_ROLE,
create=True
)
secgroup_id = self.vpc.create_security_group(
constants.IPA_SEC_GRP, 'IPA Security Group'
)
ip_permissions = [{
'IpProtocol': 'tcp',
'FromPort': constants.IPA_API_PORT,
'ToPort': constants.IPA_API_PORT,
'IpRanges': [{'CidrIp': '0.0.0.0/0'}]
}]
self.vpc.add_secgrp_rules(ip_permissions, secgroup_id)
_ipa_hostnames = self._hostname_cluster(count=count)
for _idx in _ipa_hostnames.keys():
_ipa_h = _ipa_hostnames[_idx]
self.name = _ipa_h
self.configuration = configuration.IPA(
hostname=_ipa_h,
vpc=self.vpc,
ipa_admin_password=ipa_admin_password,
tm_release=tm_release,
proid=proid
)
super().setup(
image=image,
count=count,
cidr_block=cidr_block,
key=key,
instance_type=instance_type,
subnet_name=subnet_name,
sg_names=[constants.COMMON_SEC_GRP, constants.IPA_SEC_GRP],
)
def check_passed_status():
_LOGGER.info('Checking IPA server running status...')
return all(
map(
lambda i: i.running_status(refresh=True) == 'passed',
self.instances.instances
)
)
polling.poll(
check_passed_status,
step=10,
timeout=600
)
self.vpc.associate_dhcp_options(default=True)
try:
self.vpc.delete_dhcp_options()
except Exception:
pass
self.vpc.associate_dhcp_options([
{
'Key': 'domain-name-servers',
'Values': [
i.metadata['PrivateIpAddress']
for i in self.instances.instances
]
}
])
def destroy(self, subnet_name):
super().destroy(
subnet_name=subnet_name
)
self.vpc.delete_security_groups(sg_names=[constants.IPA_SEC_GRP])
|
t = int(input())
while t > 0:
n = int(input())
arr = [0] + list(map(int,input().strip().split()))[:n]
stor = []
f = [1 for i in range(n+1)]
for i in range(1,n+1,+1):
for j in range(i*2,n+1,+i):
if arr[j] > arr[i]:
f[j] = max(f[j],f[i]+1)
stor.append(f[j])
if len(stor) == 0:
print(1)
else:
print(max(stor))
t = t-1
|
#!/usr/bin/env python
# -*- py-indent-offset: 2; indent-tabs-mode: nil; coding: utf-8 -*-
import pocketsphinx as ps
decoder = ps.Decoder(lm="../model/lm/en_US/hub4.5000.DMP")
nsamps = decoder.decode_raw(file("../test/data/goforward.raw", "rb"))
(segments, score) = decoder.segments()
for seg in segments:
word = seg.word()
sf, ef = seg.frames()
print "%d %s %d" % (sf, word, ef)
|
#tipe data skalar => tipe data sederhana
print('tipe data skalar => tipe data sederhana')
anak1 = 'Eko'
anak2 = 'Dwi'
anak3 = 'Tri'
anak4 = 'Catur'
print (anak1)
print (anak2)
print (anak3)
print (anak4)
#tipe data list/array/daftar
print('\ntipe data list/array/daftar')
anak = ['Eko', 'Dwi', 'Tri', 'Catur']
print (anak)
anak.append('Limo')
print(anak)
#sapa anak ke-2
print('\nsapa anak ke-2')
print(f'Hai {anak[1]}!')
#sapa semua anak
print('\nsapa semua anak')
for a in anak:
print(f'Hai {a}')
#sapa semua anak: cara ribet
print('\nsapa semua anak: cara ribet')
for a in range(0,len(anak)):
print(f'{a+1}. Hai {anak[a]}') |
from __future__ import division
import numpy as np
import pandas as pd
import itertools
import pickle
from mypipeline import MultinomialNaiveBayesLogProbs, CleanTable, test_pipeline
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LogisticRegression
from tqdm import tqdm
mnb_lr_pipe = Pipeline(steps=[('log_probs', MultinomialNaiveBayesLogProbs()),
('clean', CleanTable()),
('lr', LogisticRegression())])
df = pd.read_pickle("talks_norm_pos.pdpkl")
# Random Forest
param_grid = [['text', 'lemmatized_text'], # text column
['standard'], # count weighting
[1,5,10,15], #min_df
[10**i for i in xrange(-2,3)]] # C
results = []
for params in tqdm(itertools.product(*param_grid), total=np.product([len(g) for g in param_grid])):
text_column, count_weighting, min_df, C = params
print params,
accs = test_pipeline(df, mnb_lr_pipe.set_params(log_probs__text_column = text_column,
log_probs__count_weighting = count_weighting,
log_probs__min_df = min_df,
lr__C = C))
results.append((params, accs))
with open("lr_results.pypkl", 'w') as f:
pickle.dump(results, f)
|
from django.test import TestCase
from django.shortcuts import reverse
from . import create_question
class QuestionDetailViewTests(TestCase):
def test_detail_view_should_return_404_when_question_in_future_is_requested(self):
# Given
future_question = create_question(question_text='Future question', days=5)
# When
url = reverse('polls:detail', args=(future_question.id,))
response = self.client.get(url)
# Then
self.assertEqual(response.status_code, 404)
def test_detail_view_should_return_questions_when_question_in_past_is_requested(self):
# Given
past_question = create_question(question_text='Past Question.', days=-5)
# When
url = reverse('polls:detail', args=(past_question.id,))
response = self.client.get(url)
# Then
self.assertContains(response, past_question.question_text)
self.assertEqual(response.status_code, 200)
|
import unittest
import groupcheck
class TestUserIsValidMethod(unittest.TestCase):
def setUp(self):
self.valid = ["1", "2", "3"]
def testTrue(self):
user = groupcheck.User("ellen", "1")
self.assertTrue(user.is_valid(self.valid))
def testFalseString(self):
user = groupcheck.User("bob", "14")
self.assertFalse(user.is_valid(self.valid))
def testTrueInt(self):
user = groupcheck.User("Mr. Number", 2)
self.assertTrue(user.is_valid(self.valid))
def testFalseInt(self):
user = groupcheck.User("Mr. Number", 4)
self.assertFalse(user.is_valid(self.valid))
def testFalseNone(self):
user = groupcheck.User("jerkface", None)
self.assertFalse(user.is_valid(self.valid))
class TestGetUser(unittest.TestCase):
def setUp(self):
with open('testdata/passwd.txt', 'r') as f:
self.passwd = f.read()
self.result = [
groupcheck.User("root", "0"),
groupcheck.User("daemon", "1"),
groupcheck.User("bin", "2"),
groupcheck.User("sys", "3"),
groupcheck.User("sync", "4")
]
def testGetUserOutput(self):
userlist = []
for i in groupcheck.get_users(users=self.passwd):
userlist.append(i)
for i in xrange(5):
self.assertEqual(self.result[i].username, userlist[i].username)
self.assertEqual(self.result[i].gid, userlist[i].gid)
class TestGetValid(unittest.TestCase):
def setUp(self):
with open('testdata/group.txt', 'r') as f:
self.group = f.read()
self.result = [
"0",
"1",
"2",
"3",
"4"
]
def testGetValidOutput(self):
self.assertEqual(groupcheck.get_valid(self.group), self.result)
if __name__ == "__main__":
unittest.main()
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
__version__ = '1.0.1'
'''
NOT USABLE CODE STATE CALCULATED ON POSTGRESQL SIDE
update_hw_module_command_state_element_query = """
UPDATE public.hw_module_command_state AS hmcs
SET hw_module_id = COALESCE($2, hw_module_id),
sound_buzzer_state = COALESCE($3::BOOLEAN, sound_buzzer_state),
sound_buzzer_lock = COALESCE($4::BOOLEAN, sound_buzzer_lock),
stop_engine_state = COALESCE($5::BOOLEAN, stop_engine_state),
stop_engine_lock = COALESCE($6::BOOLEAN, stop_engine_lock),
disable_engine_start_state = COALESCE($7::BOOLEAN, disable_engine_start_state),
disable_engine_start_lock = COALESCE($8::BOOLEAN, disable_engine_start_lock),
active = $9::BOOLEAN,
updated_on = now()
WHERE hmcs.id = $1::BIGINT
--AND (
-- param_1 IS NOT NULL AND param_1 IS DISTINCT FROM column_1 OR
-- param_2 IS NOT NULL AND param_2 IS DISTINCT FROM column_2 OR
-- )
RETURNING *;
"""
update_hw_module_command_state_sound_buzzer_by_hw_module_id_query = """
UPDATE public.hw_module_command_state AS hmcs
SET
sound_buzzer_state = COALESCE($2::BOOLEAN, sound_buzzer_state),
sound_buzzer_lock = COALESCE($3::BOOLEAN, sound_buzzer_lock),
updated_on = now()
WHERE hmcs.hw_module_id = $1::BIGINT RETURNING *;
"""
update_hw_module_command_state_stop_engine_by_hw_module_id_query = """
UPDATE public.hw_module_command_state AS hmcs
SET
stop_engine_state = COALESCE($2::BOOLEAN, stop_engine_state),
stop_engine_lock = COALESCE($3::BOOLEAN, stop_engine_lock),
updated_on = now()
WHERE hmcs.hw_module_id = $1::BIGINT RETURNING *;
"""
update_hw_module_command_state_disable_engine_start_by_hw_module_id_query = """
UPDATE public.hw_module_command_state AS hmcs
SET
disable_engine_start_state = COALESCE($2::BOOLEAN, disable_engine_start_state),
disable_engine_start_lock = COALESCE($3::BOOLEAN, disable_engine_start_lock),
updated_on = now()
WHERE hmcs.hw_module_id = $1::BIGINT RETURNING *;
"""
''' |
import sqlite3
import time
import datetime
import random
def create_table():
## c.execute('DROP TABLE stuffToPlot')
c.execute('CREATE TABLE IF NOT EXISTS stuffToPlot(unix REAL,datestamp TEXT,keyword TEXT,value REAL)')
def data_entry():
c.execute("INSERT INTO stuffToPlot VALUES(145123542,'2016-01-01','Python',5)")
conn.commit()
def dynamic_data_entry():
unix = int(time.time())
date = str(datetime.datetime.fromtimestamp(unix).strftime('%Y-%m-%d %H:%M:%S'))
keyword = 'Python'
value = random.randrange(0,10)
c.execute("INSERT INTO stuffToPlot (unix,datestamp,keyword,value) VALUES (?,?,?,?)",(unix,date,keyword,value))
conn.commit()
def read_from_db():
# c.execute("SELECT * FROM stuffToPlot WHERE value=5 AND keyword='Python'")
c.execute("SELECT * FROM stuffToPlot")
for row in c.fetchall():
print(row)
try:
conn = sqlite3.connect('test.db')
c=conn.cursor()
create_table()
for i in range(10):
dynamic_data_entry()
time.sleep(0.5)
read_from_db()
graph_data()
except Exception as e:
print(e)
finally:
c.close()
conn.close()
|
from game_master import GameMaster
from read import *
from util import *
import pdb
class TowerOfHanoiGame(GameMaster):
def __init__(self):
super().__init__()
def produceMovableQuery(self):
"""
See overridden parent class method for more information.
Returns:
A Fact object that could be used to query the currently available moves
"""
return parse_input('fact: (movable ?disk ?init ?target)')
def getGameState(self):
"""
Returns a representation of the game in the current state.
The output should be a Tuple of three Tuples. Each inner tuple should
represent a peg, and its content the disks on the peg. Disks
should be represented by integers, with the smallest disk
represented by 1, and the second smallest 2, etc.
Within each inner Tuple, the integers should be sorted in ascending order,
indicating the smallest disk stacked on top of the larger ones.
For example, the output should adopt the following format:
((1,2,5),(),(3, 4))
Returns:
A Tuple of Tuples that represent the game state
"""
### student code goes here
# State is the Tuple of Tuples being returned
state = []
# peg1's tuple
diskson1 = []
# Ask kb which disks bind to ?disk as being on peg1
matches = self.kb.kb_ask(parse_input('fact: (on ?disk peg1)'))
# If peg1 isn't empty
if matches != False:
for m in matches:
string = m.bindings_dict['?disk']
diskson1.append(int(string[-1:]))
#print(diskson1)
diskson1.sort()
#print(diskson1)
state.append(tuple(diskson1))
# If empty, add in empty tuple
else:
state.append(())
# Check if peg2 empty
diskson2 = []
matches = self.kb.kb_ask(parse_input('fact: (on ?disk peg2)'))
if matches != False:
for m in matches:
string = m.bindings_dict['?disk']
diskson2.append(int(string[-1:]))
#print(diskson2)
diskson2.sort()
state.append(tuple(diskson2))
# If empty, add in empty tuple
else:
state.append(())
# Check if peg3 empty
diskson3 = []
matches = self.kb.kb_ask(parse_input('fact: (on ?disk peg3)'))
if matches != False:
for m in matches:
string = m.bindings_dict['?disk']
diskson3.append(int(string[-1:]))
#print(diskson3)
diskson3.sort()
state.append(tuple(diskson3))
# If empty, add in empty tuple
else:
state.append(())
# Return the tuple of tuples
return tuple(state)
def makeMove(self, movable_statement):
"""
Takes a MOVABLE statement and makes the corresponding move. This will
result in a change of the game state, and therefore requires updating
the KB in the Game Master.
The statement should come directly from the result of the MOVABLE query
issued to the KB, in the following format:
(movable disk1 peg1 peg3)
Args:
movable_statement: A Statement object that contains one of the currently viable moves
Returns:
None
"""
### Student code goes here
if self.isMovableLegal(movable_statement) == True:
# Extract variables/constants from terms in the statement
#pdb.set_trace()
sl = movable_statement.terms
# Store disk the one being moved is on top of
matches = self.kb.kb_ask(parse_input('fact: (ontopof '+str(sl[0])+' ?disk)'))
if matches:
disk_under = matches[0].bindings_dict['?disk']
self.kb.kb_retract(parse_input('fact: (ontopof '+str(sl[0])+' '+disk_under+')'))
#pdb.set_trace()
#print(disk_under)
# Store top disk of target peg to retract if any
matches2 = self.kb.kb_ask(parse_input('fact: (topdiskof '+str(sl[2])+' ?disk)'))
if matches2:
target_top = matches2[0].bindings_dict['?disk']
self.kb.kb_retract(parse_input('fact: (topdiskof '+str(sl[2])+' '+target_top+')'))
else:
self.kb.kb_retract(parse_input('fact: (empty '+str(sl[2])+')'))
# Disk no longer on initial peg - retract the on and topdiskof facts
self.kb.kb_retract(parse_input('fact: (on '+str(sl[0])+' '+str(sl[1])+')'))
self.kb.kb_retract(parse_input('fact: (topdiskof '+str(sl[1])+' '+str(sl[0])+')'))
# Facts to assert
self.kb.kb_assert(parse_input('fact: (on '+str(sl[0])+' '+str(sl[2])+')'))
self.kb.kb_assert(parse_input('fact: (topdiskof '+str(sl[2])+' '+str(sl[0])+')'))
if matches:
disk_under = matches[0].bindings_dict['?disk']
self.kb.kb_assert(parse_input('fact: (topdiskof '+str(sl[1])+' '+disk_under+')'))
if matches2:
target_top = matches2[0].bindings_dict['?disk']
self.kb.kb_assert(parse_input('fact: (ontopof '+str(sl[0])+' '+target_top+')'))
checker = self.kb.kb_ask(parse_input('fact: (on ?disk '+str(sl[1])+')'))
if checker == False:
self.kb.kb_assert(parse_input('fact: (empty '+str(sl[1])+')'))
def reverseMove(self, movable_statement):
"""
See overridden parent class method for more information.
Args:
movable_statement: A Statement object that contains one of the previously viable moves
Returns:
None
"""
pred = movable_statement.predicate
sl = movable_statement.terms
newList = [pred, sl[0], sl[2], sl[1]]
self.makeMove(Statement(newList))
class Puzzle8Game(GameMaster):
def __init__(self):
super().__init__()
def produceMovableQuery(self):
"""
Create the Fact object that could be used to query
the KB of the presently available moves. This function
is called once per game.
Returns:
A Fact object that could be used to query the currently available moves
"""
return parse_input('fact: (movable ?piece ?initX ?initY ?targetX ?targetY)')
def getGameState(self):
"""
Returns a representation of the the game board in the current state.
The output should be a Tuple of Three Tuples. Each inner tuple should
represent a row of tiles on the board. Each tile should be represented
with an integer; the empty space should be represented with -1.
For example, the output should adopt the following format:
((1, 2, 3), (4, 5, 6), (7, 8, -1))
Returns:
A Tuple of Tuples that represent the game state
"""
### Student code goes here
state = []
# Row 1
row1 = ['a', 'a', 'a', 'a']
matches = self.kb.kb_ask(parse_input('fact: (coord ?tile pos1 pos1'))
num1 = matches[0].bindings_dict['?tile']
if num1 != 'empty':
row1.insert(3, int(num1[-1:]))
else:
row1.insert(3, -1)
matches = self.kb.kb_ask(parse_input('fact: (coord ?tile pos2 pos1'))
num2 = matches[0].bindings_dict['?tile']
if num2 != 'empty':
row1.insert(4, int(num2[-1:]))
else:
row1.insert(4, -1)
matches = self.kb.kb_ask(parse_input('fact: (coord ?tile pos3 pos1'))
num3 = matches[0].bindings_dict['?tile']
if num3 != 'empty':
row1.insert(5, int(num3[-1:]))
else:
row1.insert(5, -1)
row1 = [x for x in row1 if x != 'a']
row1 = tuple(row1)
# Row 2
row2 = ['a', 'a', 'a', 'a']
matches = self.kb.kb_ask(parse_input('fact: (coord ?tile pos1 pos2'))
num4 = matches[0].bindings_dict['?tile']
if num4 != 'empty':
row2.insert(3, int(num4[-1:]))
else:
row2.insert(3, -1)
matches = self.kb.kb_ask(parse_input('fact: (coord ?tile pos2 pos2'))
num5 = matches[0].bindings_dict['?tile']
if num5 != 'empty':
row2.insert(4, int(num5[-1:]))
else:
row2.insert(4, -1)
matches = self.kb.kb_ask(parse_input('fact: (coord ?tile pos3 pos2'))
num6 = matches[0].bindings_dict['?tile']
if num6 != 'empty':
row2.insert(5, int(num6[-1:]))
else:
row2.insert(5, -1)
row2 = [x for x in row2 if x != 'a']
row2 = tuple(row2)
# Row 3
row3 = ['a', 'a', 'a', 'a']
matches = self.kb.kb_ask(parse_input('fact: (coord ?tile pos1 pos3'))
num7 = matches[0].bindings_dict['?tile']
if num7 != 'empty':
row3.insert(3, int(num7[-1:]))
else:
row3.insert(3, -1)
matches = self.kb.kb_ask(parse_input('fact: (coord ?tile pos2 pos3'))
num8 = matches[0].bindings_dict['?tile']
if num8 != 'empty':
row3.insert(4, int(num8[-1:]))
else:
row3.insert(4, -1)
matches = self.kb.kb_ask(parse_input('fact: (coord ?tile pos3 pos3'))
num9 = matches[0].bindings_dict['?tile']
if num9 != 'empty':
row3.insert(5, int(num9[-1:]))
else:
row3.insert(5, -1)
#print(row3)
row3 = [x for x in row3 if x != 'a']
row3 = tuple(row3)
state = (row1, row2, row3)
return state
def makeMove(self, movable_statement):
"""
Takes a MOVABLE statement and makes the corresponding move. This will
result in a change of the game state, and therefore requires updating
the KB in the Game Master.
The statement should come directly from the result of the MOVABLE query
issued to the KB, in the following format:
(movable tile3 pos1 pos3 pos2 pos3)
Args:
movable_statement: A Statement object that contains one of the currently viable moves
Returns:
None
"""
### Student code goes here
#if self.isMovableLegal(movable_statement) == True and movable_statement.predicate == 'movable':
tilem = movable_statement.terms[0]
old_x = movable_statement.terms[1]
old_y = movable_statement.terms[2]
new_x = movable_statement.terms[3]
new_y = movable_statement.terms[4]
# Retract old position
self.kb.kb_retract(Fact(Statement(["coord", tilem, old_x, old_y])))
self.kb.kb_retract(Fact(Statement(["coord", "empty", new_x, new_y])))
# Assert new position
self.kb.kb_assert(Fact(Statement(["coord", tilem, new_x, new_y])))
self.kb.kb_assert(Fact(Statement(["coord", "empty", old_x, old_y])))
return
def reverseMove(self, movable_statement):
"""
See overridden parent class method for more information.
Args:
movable_statement: A Statement object that contains one of the previously viable moves
Returns:
None
"""
pred = movable_statement.predicate
sl = movable_statement.terms
newList = [pred, sl[0], sl[3], sl[4], sl[1], sl[2]]
self.makeMove(Statement(newList)) |
from django.db import models
from django.contrib.auth import get_user_model
User = get_user_model()
class Category(models.Model):
category_title = models.CharField('Заголовок', max_length=50)
class Meta:
verbose_name = 'Категория'
verbose_name_plural = 'Категории'
def __str__(self):
return self.category_title
class Tag(models.Model):
tag_title = models.CharField('Тег', max_length=50)
class Meta:
verbose_name = 'Тег'
verbose_name_plural = 'Теги'
def __str__(self):
return self.tag_title
class News(models.Model):
news_author = models.ForeignKey(
User,
verbose_name='Автор',
on_delete=models.CASCADE)
news_category = models.ForeignKey(
Category,
verbose_name='Категория',
on_delete=models.SET_NULL, null=True)
news_title = models.CharField('Заголовок', max_length=150)
news_preview = models.TextField('Аннотация', max_length=350)
news_text = models.TextField('Текст')
news_tag = models.ManyToManyField(Tag, verbose_name='Теги')
created_date = models.DateTimeField('Дата', auto_now_add=True)
news_description = models.CharField('Описание', max_length=100)
news_keywords = models.CharField('Ключевые слова', max_length=50)
class Meta:
verbose_name = 'Статья'
verbose_name_plural = 'Статьи'
def __str__(self):
return self.news_title
class Comment(models.Model):
comment_user = models.ForeignKey(
User,
verbose_name="Пользователь",
on_delete=models.CASCADE
)
comment_news = models.ForeignKey(
News,
verbose_name="Новость",
on_delete=models.CASCADE,
)
comment_text = models.TextField()
class Meta:
verbose_name = 'Статья'
verbose_name_plural = 'Статьи'
def __str__(self):
return "{}".format(self.comment_user)
|
# Library imports
import pyautogui
import time
import json
import sys
import os
# Execute one mouse event
def execute_mouse_event(event):
# If down direction
if event['direction'] == 'down':
# Pause python
time.sleep(2)
pyautogui.mouseDown(button=event['button'], x=event['position'][0], y=event['position'][1])
# If up direction
if event['direction'] == 'up':
pyautogui.mouseUp(button=event['button'], x=event['position'][0], y=event['position'][1])
# Execute one mouse event
def execute_keyboard_event(event):
# If ctrl/shift
if event['key'] == 'shiftleft' or event['key'] == 'ctrlleft':
# Press special key
pyautogui.keyDown(event['key'])
# Loop through nextKeys
for next_key in event['nextKeys']:
pyautogui.press(next_key)
# For any other key, just press
pyautogui.press(event['key'])
# Get bot_file_path from electron
bot_name = sys.argv[1]
bot_file_path = os.path.join(os.getcwd(), bot_name + '.json')
# Load bot (passed in as argument by electron)
with open(bot_file_path) as bot_file:
bot = json.load(bot_file)
# Execute bot
for event in bot['events']:
# For mouse events
if event['type'] == 'mouse':
execute_mouse_event(event)
# For keyboard events
if event['type'] == 'keyboard':
execute_keyboard_event(event)
# Exit program
exit(0)
|
import os
import glob
import subprocess
import shlex
# pyfr import couette_flow_2d.msh couette_flow_2d.pyfrm
def msh2pyfrm(filename=None):
input_msh = os.path.join('mesh', filename)
name = os.path.splitext(input_msh)[0]
output_msh = name + '.pyfrm'
os.system("pyfr import " + input_msh +" " + output_msh)
res_name = os.path.splitext(filename)[0]
return res_name
# pyfr run -b cuda -p couette_flow_2d.pyfrm config.ini
def pyfr_run(mesh_filename=None, config_path="config/config.ini"):
pyfrm = os.path.join('mesh', mesh_filename) + '.pyfrm'
run_command("pyfr run -b openmp -p " + pyfrm +" " + config_path)
return
# pyfr export couette_flow_2d.pyfrm couette_flow_2d-040.pyfrs couette_flow_2d-040.vtu -d 4
def pyfr_export(mesh_filename=None, config_path="config/config.ini"):
pyfrm = os.path.join('mesh', mesh_filename) + '.pyfrm'
pyfrs = mesh_filename + '-040.pyfrs'
vtu = mesh_filename + '-040.vtu'
run_command("pyfr export " + pyfrm + " " + pyfrs + " " + vtu + " -d 4")
for filename in glob.glob(mesh_filename+"*"):
if filename.endswith(".pyfrs"):
os.remove(filename)
return
def run_command(command):
process = subprocess.Popen(shlex.split(command), stdout=subprocess.PIPE)
while True:
output = process.stdout.readline()
if output == '' and process.poll() is not None:
break
if output:
print(output.strip())
break
rc = process.poll()
return rc |
#!/usr/bin/env python
import hashlib
data = 'hi'
h = hashlib.md5()
h.update(data)
print h.hexdigest()
print hashlib.md5(data).hexdigest()
|
from OFS.DTMLMethod import DTMLMethod
from Products.Five import BrowserView
from zope.interface import Interface
from topp.featurelets.base import BaseFeaturelet
success = "SUCCESS!!"
class IDummyFeatureletInstalled(Interface):
"""
Signifies that a dummy featurelet has been installed.
"""
class ObjectsFeaturelet(BaseFeaturelet):
id = 'objects_featurelet'
_info = {'objects': ({'id': 'foo', 'class': DTMLMethod},
{'id': 'bar', 'class': DTMLMethod},
),
}
class ContentFeaturelet(BaseFeaturelet):
id = 'objects_featurelet'
_info = {'content': ({'id': 'foo', 'title': 'Foo',
'portal_type': 'Document'},
{'id': 'bar', 'title': 'Bar',
'portal_type': 'Document'},
),
}
class ConfigFeaturelet(BaseFeaturelet):
id = 'config_featurelet'
_info = {}
config_view = 'dummy_config'
installed_marker = IDummyFeatureletInstalled
class DummyConfigView(BrowserView):
def __call__(self):
return success
|
from __future__ import division
import numpy as np
import os
import warnings
warnings.filterwarnings("ignore")
import sklearn.datasets as datasets
import scipy.io as spio
import RewardProcess
from sklearn.model_selection import train_test_split
import sklearn.metrics.pairwise as Kern
import KernelCalculation.GaussianKernels as GK
from numpy import genfromtxt
def TrainDataCollect(data_flag_multiclass,N_valid,N,RandomSeedNumber,Main_Program_flag, bw_x, gamma, NCV_train, NCV_validate, NEV_train, NEV_test):
rng = np.random.RandomState(RandomSeedNumber)
DataXY = dict()
if data_flag_multiclass == 'synthetic':
DataXY['TDependentLoss'] = 0
T = 6100
A = 20
np.random.seed(seed=0)
Features = 2.0*np.pi*np.random.rand(T,1)
'''
#Used this during dependent syntehtic data experiments
Features = np.linspace(0,2*np.pi,T)
Features = Features[:,np.newaxis]
'''
Labels_full = np.zeros((T,))
for i in range(0,T):
Labels_full[i] = np.argmax([np.sin(j*Features[i]) for j in range(0,A)])
elif data_flag_multiclass == 'spacecraft_synthetic':
DataXY['IPFileName']='./Datasets/synthetic_sc_lbeqn_5d.mat'
sc_synth = spio.loadmat(DataXY['IPFileName'])
context_full = sc_synth['context'] # contexts not related to loss function are handled outside
context_full = context_full # + 0.00001*(np.random.rand(context_full.shape[0], context_full.shape[1]) - 0.5)
bs = sc_synth['B_s']*1e-4 # convert to 1e-5 Tesla
br = sc_synth['B_ref']*1e-4
RP = RewardProcess.RewardProcess('spacecraft')
dataset_type = '3-axis-norot'
br_uhc, bs_uhc = RP.InitializeDataset(dataset_type, bs, br)
T = br.shape[1]
A = bs.shape[1]
# context = np.zeros((T,9*A))
# context[:,0::3] = np.absolute(context_full[0].T)
# context[:,1::3] = np.absolute(context_full[1].T)
# context[:,2::3] = np.absolute(context_full[2].T)
# context = np.zeros((T,A))
context = context_full.T
# context = np.concatenate((np.absolute(context_full.T)/3000, np.sign(context_full.T)), axis=1)
# modifications to context
Cstd = np.std(context, axis=0)
Cmax = context.max(axis=0)
# contextmin = context.min(axis=0)
# context = (context - context.min(axis=0))
# contextcube = context.max(axis=0)
context = context/np.amin(context.max(axis=0))
# context = context/4998.5418
# context = context / np.concatenate((Cmax[0:A * A], Cstd[A * A:]))
# context = context / np.concatenate(((np.ones((A*A,)), Cstd[A*A:])))
Tvec = np.arange(T)
Features = np.concatenate((context, Tvec[:, np.newaxis]), axis=1)
# Features = context
Labels_full = np.zeros((T,))
for tt in range(0,T):
B_S = bs_uhc[:,:,tt]
B_R = br_uhc[:,tt]
rewarr = -10*(np.linalg.norm(B_R[:,np.newaxis] - B_S, axis=0))**2
# Labels_full[tt] = np.argmax(rewarr)
Labels_full[tt] = np.amax(rewarr)
# Labels = 1.0*(Labels_full == 0)
# Labels = Labels_full
DataXY['TDependentLoss'] = 1
elif data_flag_multiclass == 'spacecraft_labexperimental':
DataXY['IPFileName'] = './Datasets/largecoil_postproc.mat'
sc_synth = spio.loadmat(DataXY['IPFileName'])
context_full = sc_synth['telMat'] # contexts not related to loss function are handled outside
bNoise = sc_synth['bNorm'].T
context_full = context_full[:,:bNoise.shape[0]]
# context_full = context_full # + 0.00001*(np.random.rand(context_full.shape[0], context_full.shape[1]) - 0.5)
RP = RewardProcess.RewardProcess('spacecraft_labbased')
dataset_type = '3-axis-labbased'
br = np.zeros((1, bNoise.shape[0]))
br_uhc, bs_uhc = RP.InitializeDataset(dataset_type, bNoise, br)
T = br.shape[1]
A = bNoise.shape[1]
# context = np.zeros((T,9*A))
# context[:,0::3] = np.absolute(context_full[0].T)
# context[:,1::3] = np.absolute(context_full[1].T)
# context[:,2::3] = np.absolute(context_full[2].T)
# context = np.zeros((T,A))
context = context_full.T
# context = np.concatenate((np.absolute(context_full.T)/3000, np.sign(context_full.T)), axis=1)
# modifications to context
Cstd = np.std(context, axis=0)
Cmax = context.max(axis=0)
# contextmin = context.min(axis=0)
# context = (context - context.min(axis=0))
# contextcube = context.max(axis=0)
context = context / np.amin(context.max(axis=0))
# context = context/4998.5418
# context = context / np.concatenate((Cmax[0:A * A], Cstd[A * A:]))
# context = context / np.concatenate(((np.ones((A*A,)), Cstd[A*A:])))
Tvec = np.arange(T)
Features = np.concatenate((context, Tvec[:, np.newaxis]), axis=1)
# Features = context
Labels_full = np.zeros((T,))
for tt in range(0, T):
rewarr = -bNoise[tt,:]
# Labels_full[tt] = np.argmax(rewarr)
Labels_full[tt] = np.amax(rewarr)
# Labels = 1.0*(Labels_full == 0)
# Labels = Labels_full
DataXY['TDependentLoss'] = 1
elif data_flag_multiclass =='spacecraft_experimental':
sc_exp = spio.loadmat('./Datasets/MAB_DATASET_GRIFEX3_2p.mat')
context = sc_exp['context'] # contexts not related to loss function are handled outside
bs = sc_exp['B_s']*1e-4 # convert to 1e-5 Tesla
br = sc_exp['B_ref']*1e-4
RP = RewardProcess.RewardProcess('spacecraft')
dataset_type = '1-axis-norot'
br_uhc, bs_uhc = RP.InitializeDataset(dataset_type, bs, br)
T = br.shape[0]
A = bs.shape[1]
contextmin = context.min(axis=0)
context = (context - context.min(axis=0))
contextcube = context.max(axis=0)
context = context / context.max(axis=0)
Tvec = np.arange(T)
Features = np.concatenate((context[:, (0,1,2,3,4,5,6,7,8,9)], Tvec[:,np.newaxis] ), axis=1)
TDataset = T
Labels = np.zeros((T,))
for tt in range(0,T):
B_S = bs_uhc[tt,:]
B_R = br_uhc[tt,0]
rewarr = -np.absolute((B_R**2 - B_S**2))/1e-10 + 5
Labels[tt] = np.argmax(rewarr)
# Labels[tt] = np.max(rewarr)
DataXY['TDependentLoss'] = 1
if np.min(Labels_full) == 1:
Labels_full = Labels_full - 1
elif np.min(Labels_full) == -1:
Labels_full = Labels_full + 1
# A = np.unique(Labels).shape[0] # number of classes
# Features_valid, Features_train_test, Labels_valid, Labels_train_test = train_test_split(Features, Labels,
# train_size=int(A * N_valid),
# shuffle=False,
# stratify=None) # Labels
# splitting manually as sklearn 0.18 doesn't have shuffle=false option
if Main_Program_flag == 0:
Features = Features[:NCV_train + NCV_validate+A*N,:]
Labels = Labels_full[:NCV_train + NCV_validate+A*N]
else:
Features = Features[(NCV_train+NCV_validate+A*N):(NCV_train+NCV_validate+NEV_train + NEV_test+2*A*N),:]
Labels = Labels_full[(NCV_train + NCV_validate+A*N) : (NCV_train + NCV_validate + NEV_train + NEV_test+2*A*N)]
if Main_Program_flag == 0:
Features_valid = Features[0:int(A * N_valid), :]
Labels_valid = Labels[0:int(A * N_valid)]
Features_train_test = Features[int(A * N_valid):, :]
Labels_train_test = Labels[int(A * N_valid):]
Features_train = np.copy(Features_valid)
Features_test = np.copy(Features_train_test)
Labels_train = np.copy(Labels_valid)
Labels_test = np.copy(Labels_train_test)
else:
Features_train_test = np.copy(Features)
Labels_train_test = np.copy(Labels)
Features_train, Features_test, Labels_train, Labels_test = train_test_split(Features_train_test,
Labels_train_test,
train_size=int(
A * N),
random_state=RandomSeedNumber + 17,
stratify=None) # Labels_train_test
'''
# Used this during dependent synthetic data experiments
Features_train = Features_train_test[0:int(A*N),:]
Labels_train = Labels_train_test[0:int(A*N)]
Features_test = Features_train_test[int(A * N):, :]
Labels_test = Labels_train_test[int(A * N):]
'''
# Features_train.shape, Features_test.shape, A*N, Labels_train
if Main_Program_flag == 0:
M = N_valid
else:
M = N
idx = rng.permutation(A * M)
Features_train = Features_train[idx, :]
Labels_train = Labels_train[idx]
#
# Labels_test_hist = np.histogram(Labels_test, A)
# minimum_number_label = np.min(Labels_test_hist[0])
# Features_test_dummy = np.zeros([A * minimum_number_label, Features_test.shape[1]])
# Labels_test_dummy = np.zeros([A * minimum_number_label])
#
# for aa in range(0, A):
# idx = np.where(Labels_test == aa)[0]
# # idx = np.asarray(idx)
# # idx = idx[0,:]
# # idx.astype(int)
# Features_test_dummy[aa * minimum_number_label:(aa + 1) * minimum_number_label, :] = Features_test[
# idx[:minimum_number_label],
# :]
# Labels_test_dummy[aa * minimum_number_label:(aa + 1) * minimum_number_label] = Labels_test[
# idx[:minimum_number_label]]
# idx = rng.permutation(A * minimum_number_label)
# Features_test = Features_test_dummy[idx, :]
# Labels_test = Labels_test_dummy[idx]
for aa in range(0, A):
XTrain = Features_train[aa * M:(aa + 1) * M, :]
LabelsTrain = Labels_train[aa * M:(aa + 1) * M]
# TTrain = Time_train[aa * M:(aa + 1) * M]
YTrain = np.zeros([M])
YTrain[LabelsTrain == aa] = 1
Total_Features = np.copy(XTrain)
Arm_rewards = np.copy(YTrain)
KMatrix = np.zeros((M,M))
if(DataXY['TDependentLoss']==0):
KMatrix[:,:] = Kern.rbf_kernel(Total_Features, Total_Features, bw_x)
elif(DataXY['TDependentLoss']==1):
KMatrix[:, :] = Kern.rbf_kernel(Total_Features[:,:-1], Total_Features[:,:-1], bw_x)
KInvMatrix = np.linalg.inv(KMatrix + gamma * np.identity(KMatrix.shape[0]))
AInvMatrix = (1/gamma)*np.eye(Features_train.shape[1])
# Time_stamps = np.copy(TTrain)
# # Save training data for KTL UCB
# train_datasetKTLUCB = 'Train_Datasets_KTLUCB' + str(int(aa))
# DataXY[train_datasetKTLUCB] = np.copy(Total_Features)
#
# train_labelsKTLUCB = 'Train_Labels_KTLUCB' + str(int(aa))
# DataXY[train_labelsKTLUCB] = np.copy(Arm_rewards)
#
# # Save training data for KTLEst UCB
# train_datasetKTLEstUCB = 'Train_Datasets_KTLEstUCB' + str(int(aa))
# DataXY[train_datasetKTLEstUCB] = np.copy(Total_Features)
#
# train_labelsKTLEstUCB = 'Train_Labels_KTLEstUCB' + str(int(aa))
# DataXY[train_labelsKTLEstUCB] = np.copy(Arm_rewards)
# Save training data for Lin UCB
train_datasetLinUCB = 'Train_Datasets_LinUCB' + str(int(aa))
DataXY[train_datasetLinUCB] = np.copy(Total_Features)
train_labelsLinUCB = 'Train_Labels_LinUCB' + str(int(aa))
DataXY[train_labelsLinUCB] = np.copy(Arm_rewards)
# train_timeLinUCB = 'Train_Labels'
# Save training data for Pool UCB
train_datasetPoolUCB = 'Train_Datasets_PoolUCB' + str(int(aa))
DataXY[train_datasetPoolUCB] = np.copy(Total_Features)
train_labelsPoolUCB = 'Train_Labels_PoolUCB' + str(int(aa))
DataXY[train_labelsPoolUCB] = np.copy(Arm_rewards)
# Save balanced training data for Lin UCB Balanced
train_datasetBalUCB = 'Train_Datasets_BalUCB' + str(int(aa))
DataXY[train_datasetBalUCB] = np.copy(Total_Features)
train_labelsBalUCB = 'Train_Labels_BalUCB' + str(int(aa))
DataXY[train_labelsBalUCB] = np.copy(Arm_rewards)
# Kernel Matrix
# train_KMatrix = 'Train_KMatrix' + str(int(aa))
# DataXY[train_KMatrix] = KMatrix
# Inverse Kernel Matrix
train_KInvMatrix = 'Train_KInvMatrix' + str(int(aa))
DataXY[train_KInvMatrix] = KInvMatrix
# Thompson sampling parameters
train_AInvMatrix = 'Train_AInvMatrix' + str(int(aa))
DataXY[train_AInvMatrix] = AInvMatrix
train_bVector = 'Train_bVector' + str(int(aa))
DataXY[train_bVector] = np.zeros((1,Features_train.shape[1]))
DataXY['Testfeatures'] = np.copy(Features_test)
DataXY['armTest'] = np.copy(Labels_test)
DataXY['NoOfArms'] = A
DataXY['DatasetName'] = data_flag_multiclass
return DataXY
def AllDataCollect(DataXY,algorithm_flag):
# Get total samples and samples in each dataset
A = DataXY['NoOfArms']
total_samples = 0
samples_per_task = np.zeros([A, 1])
for i in range(0, A):
if algorithm_flag == 'Lin-UCB-Ind':
train_dataset = 'Train_Datasets_LinUCB' + str(i)
train_dataset_bal = 'Train_Datasets_BalUCB' + str(i)
elif algorithm_flag == 'Lin-UCB-Pool':
train_dataset = 'Train_Datasets_PoolUCB' + str(i)
elif algorithm_flag == 'Thompson-Sampling':
train_dataset = 'Train_Datasets_LinUCB' + str(i)
#print DataXY.keys()
if(DataXY['TDependentLoss']==0):
X = np.copy(DataXY[train_dataset])
elif(DataXY['TDependentLoss']==1):
XT = np.copy(DataXY[train_dataset])
X=XT[:,:-1]
total_samples = total_samples + X.shape[0]
samples_per_task[i] = X.shape[0]
# Collect all labels and all features
y = np.zeros(total_samples)
X_total = np.zeros([total_samples, X.shape[1]])
# KMatrices = []
KInvMatrices = []
rr = 0
for i in range(0, A):
if algorithm_flag == 'Lin-UCB-Ind':
train_labels = 'Train_Labels_LinUCB' + str(i)
train_dataset = 'Train_Datasets_LinUCB' + str(i)
train_labels_bal = 'Train_Labels_BalUCB' + str(i)
train_dataset_bal = 'Train_Datasets_BalUCB' + str(i)
# train_KMatrix = 'Train_KMatrix' + str(i)
train_KInvMatrix = 'Train_KInvMatrix' + str(i)
KInvMatrices.append(DataXY[train_KInvMatrix])
elif algorithm_flag == 'Lin-UCB-Pool':
train_labels = 'Train_Labels_PoolUCB' + str(i)
train_dataset = 'Train_Datasets_PoolUCB' + str(i)
train_KInvMatrix = 'Train_KInvMatrix' + str(i)
KInvMatrices.append(DataXY[train_KInvMatrix])
elif algorithm_flag == 'Thompson-Sampling':
train_labels = 'Train_Labels_LinUCB' + str(i)
train_dataset = 'Train_Datasets_LinUCB' + str(i)
train_AInvMatrix = 'Train_AInvMatrix' + str(i)
train_bVector = 'Train_bVector' + str(i)
KInvMatrices.append([DataXY[train_AInvMatrix], DataXY[train_bVector]])
labels = np.copy(DataXY[train_labels])
y[rr:rr + labels.shape[0]] = np.copy(DataXY[train_labels])
if(DataXY['TDependentLoss']==0):
X_total[rr:rr + labels.shape[0], :] = np.copy(DataXY[train_dataset])
elif(DataXY['TDependentLoss']==1):
XT_total = np.copy(DataXY[train_dataset])
X_total[rr:rr + labels.shape[0], :] = XT_total[:,:-1]
rr = rr + labels.shape[0]
return total_samples, samples_per_task, y, X_total, KInvMatrices
def AddData(DataXY,arm_tt,algorithm_flag,X_test,reward_test,tt, bw_x, gamma):
if algorithm_flag == 'Lin-UCB-Ind':
train_labels = 'Train_Labels_LinUCB' + str(arm_tt)
train_dataset = 'Train_Datasets_LinUCB' + str(arm_tt)
test_label = 'Test_Labels_LinUCB'
last_roundXTest = 'Test_Datasets_LinUCB'
train_labels_bal = 'Train_Labels_BalUCB' + str(arm_tt)
train_dataset_bal = 'Train_Datasets_BalUCB' + str(arm_tt)
# train_KMatrix = 'Train_KMatrix' + str(arm_tt)
train_KInvMatrix = 'Train_KInvMatrix' + str(arm_tt)
Total_Features = np.copy(DataXY[train_dataset])
Arm_rewards = np.copy(DataXY[train_labels])
if (DataXY['TDependentLoss'] == 0):
KInvMatrix = GK.UpdateKernelMatrix(DataXY[train_KInvMatrix], Total_Features, X_test, bw_x, gamma)
elif (DataXY['TDependentLoss'] == 1):
KInvMatrix = GK.UpdateKernelMatrix(DataXY[train_KInvMatrix], Total_Features[:, :-1], X_test[:, :-1], bw_x,
gamma)
DataXY[train_KInvMatrix] = np.copy(KInvMatrix)
elif algorithm_flag == 'Lin-UCB-Pool':
train_labels = 'Train_Labels_PoolUCB' + str(arm_tt)
train_dataset = 'Train_Datasets_PoolUCB' + str(arm_tt)
test_label = 'Test_Labels_PoolUCB'
last_roundXTest = 'Test_Datasets_PoolUCB'
Total_Features = np.copy(DataXY[train_dataset])
Arm_rewards = np.copy(DataXY[train_labels])
elif algorithm_flag == 'Thompson-Sampling':
train_labels = 'Train_Labels_LinUCB' + str(arm_tt)
train_dataset = 'Train_Datasets_LinUCB' + str(arm_tt)
test_label = 'Test_Labels_LinUCB'
last_roundXTest = 'Test_Datasets_LinUCB'
train_AInvMatrix = 'Train_AInvMatrix' + str(arm_tt)
train_bVector = 'Train_bVector' + str(arm_tt)
Total_Features = np.copy(DataXY[train_dataset])
Arm_rewards = np.copy(DataXY[train_labels])
if (DataXY['TDependentLoss'] == 0):
Xtemp = X_test
elif (DataXY['TDependentLoss'] == 1):
Xtemp = X_test[:,:-1]
# rank one update to inverse
AIX = (DataXY[train_AInvMatrix]).dot(Xtemp.T)
AXscale = 1/(1 + Xtemp.dot(AIX))
AInvMatrix = DataXY[train_AInvMatrix] - AXscale*np.outer(AIX,AIX)
bVector = DataXY[train_bVector] + reward_test * X_test
DataXY[train_AInvMatrix] = np.copy(AInvMatrix)
DataXY[train_bVector] = np.copy(bVector)
Total_Features = np.append(Total_Features, X_test, axis=0)
reward_test = np.ones([1])*reward_test
Arm_rewards = np.append(Arm_rewards, reward_test, axis=0)
DataXY[train_dataset] = np.copy(Total_Features)
DataXY[train_labels] = np.copy(Arm_rewards)
DataXY[last_roundXTest] = np.copy(X_test)
if tt == 0:
armSelectedTT = np.ones([1])*arm_tt #np.empty([0])
else:
armSelectedTT = np.copy(DataXY[test_label])
armSelectedTT = np.append(armSelectedTT, np.ones([1])*arm_tt, axis=0)
armSelectedTT = armSelectedTT.astype(int)
DataXY[test_label] = np.copy(armSelectedTT)
# # Balanced dataset accounting: works only for binary 0-1 rewards
# Arm_rewards_bal = np.copy(DataXY[train_labels_bal])
# Total_Features_bal = np.copy(DataXY[train_dataset_bal])
# Nones = np.sum(Arm_rewards_bal)
# Nzeros = np.sum(1.0 - Arm_rewards_bal)
# RewBal = Nones - Nzeros
# if (RewBal >= 0 and reward_test == 0 ):
# # KInvMatrix = GK.UpdateKernelMatrix(DataXY[train_KInvMatrix], Total_Features_bal, X_test, bw_x, gamma)
# Arm_rewards_bal = np.append(Arm_rewards_bal, reward_test, axis=0)
# Total_Features_bal = np.append(Total_Features_bal, X_test, axis=0)
# DataXY[train_dataset_bal] = np.copy(Total_Features_bal)
# DataXY[train_labels_bal] = np.copy(Arm_rewards_bal)
# # DataXY[train_KMatrix] = np.copy(KMatrix)
# # DataXY[train_KInvMatrix] = np.copy(KInvMatrix)
# elif (RewBal <= 0 and reward_test == 1):
# # KInvMatrix = GK.UpdateKernelMatrix(DataXY[train_KInvMatrix], Total_Features_bal, X_test, bw_x, gamma)
# Arm_rewards_bal = np.append(Arm_rewards_bal, reward_test, axis=0)
# Total_Features_bal = np.append(Total_Features_bal, X_test, axis=0)
# DataXY[train_dataset_bal] = np.copy(Total_Features_bal)
# DataXY[train_labels_bal] = np.copy(Arm_rewards_bal)
# # DataXY[train_KMatrix] = np.copy(KMatrix)
# # DataXY[train_KInvMatrix] = np.copy(KInvMatrix)
return DataXY
|
# -*- coding: utf-8 -*-
import xmlrpclib
import base64
url = "http://127.0.0.1:8069"
db = "rim"
uid = 1
password = "Antonio230"
sock = xmlrpclib.ServerProxy('http://127.0.0.1:8069/xmlrpc/object')
model = "product.template"
products_ids = sock.execute(db, uid, password, model, 'search', [])
products = sock.execute(db, uid, password, model, 'read', products_ids, ["name"])
i = open('neumaticos.jpg', 'rb').read()
base_img = base64.b64encode(i)
count = 0
for product in products:
count += 1
if product["name"].startswith("U-PLT"):
try:
result = sock.execute(db, uid, password, model, 'write', product["id"], {"image_medium": base_img})
print count, result
except:
print "error"
|
#coding=utf-8
'''
# The modules contains PiApp's models
# Any issues or improvements please contact jacob-chen@iotwrt.com
'''
from django.db import models
from django.contrib.auth.models import AbstractUser
import os
class Applist(models.Model):
id = models.IntegerField(primary_key=True)
title = models.CharField(max_length=100)
url = models.URLField()
|
import urllib2
import pprint
import pandas as pd
import json
def get_data(url):
"""
Get html file from url
:param url: string
:return: string (json)
"""
response = urllib2.urlopen(url)
json = response.read().decode('latin-1')
return json
def parse(json):
json.dumps(json)
print json.keys()
if __name__ == '__main__':
json = get_data('http://www1.camara.sp.gov.br/agenda_json.asp')
parse(json) |
import threading
import socket
import sys
import struct
import random
lock = threading.Lock()
def checkchecksum(checksum,data):
tempdata=0
newchcksum = 0
i=0
n = len(data) % 2
for i in range(0, len(data) - n, 2):
tempdata += ord(data[i]) + (ord(data[i + 1]) << 8)
if n:
tempdata += ord(data[i + 1])
while tempdata >> 16:
# sumcarry = sumcarry + tempdata
newchcksum = (tempdata & 0xffff) + (tempdata >> 16)
break
result = newchcksum & checksum
if result==0:
return True
else:
return False
def makeacks(seqnum):
sequence = struct.pack('=I', seqnum)
paddingzeros=struct.pack('=H',0)
ackindicator=struct.pack('=H',43690)
ackpacket = sequence+paddingzeros+ackindicator
return ackpacket
def main():
port = int(sys.argv[1])
filename = sys.argv[2]
prob= float(sys.argv[3])
buffer = {}
file =open(filename,'a')
file.flush()
serversockt = socket.socket( socket.AF_INET, socket.SOCK_DGRAM )
serversockt.bind(('', socket.htons(port)))
while True:
receivepacket, clientaddr=serversockt.recvfrom(4096)
headerpacket=receivepacket[0:8]
datapacket=receivepacket[8:]
seqnum=struct.unpack("=I",headerpacket[0:4])
seqnum=int(seqnum[0])
checksum =struct.unpack("=H",headerpacket[4:6])
checksum=int(checksum[0])
dataidentifier =struct.unpack("=H",headerpacket[6:8])
dataidentifier=int(dataidentifier[0])
data = datapacket.decode("ISO-8859-1","ignore")
randomprob=random.uniform(0,1)
if randomprob > prob:
checksumflag = checkchecksum(checksum,data)
if dataidentifier== 21845 and checksumflag==True:
if data !="00000end111111":
ackpacket=makeacks(seqnum)
buffer[seqnum]=data
file.write(buffer[seqnum])
serversockt.sendto(ackpacket, clientaddr)
else:
break
else:
print("PACKET LOST SEQNUM %d" %seqnum)
file.close()
print("File received successfully")
#serversockt.close()
main()
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 16/4/27 下午7:42
# @Author : ZHZ
line1 = raw_input()
n = line1.strip().split()[0]
K = line1.strip().split()[1]
string_list = []
all_str_list = []
count = 0
#得到所有字符串字典
for i in range(0,int(n)):
line = raw_input().strip()
string_list.append(line.strip())
#递归全排列,start 为全排列开始的下标, length 为str数组的长度
def AllRange(str,str_list,start,length):
if start == length-1:
all_str_list.append(str+str_list[start])
else:
for i in range(start,length):
(str_list[i],str_list[start]) = (str_list[start],str_list[i])
AllRange(str+str_list[start],str_list,start+1,length)
(str_list[i],str_list[start]) = (str_list[start],str_list[i])
AllRange("",string_list,0,int(n))
all_str_set = set(all_str_list)
def leftString(string):
string = string[1:-1]+string[-1]+string[0]
return string
for str in all_str_list:
temp_count = 0
temp_str = str
for i in range(1,len(temp_str)+1):
temp_str = leftString(temp_str)
if temp_str==str:
temp_count = temp_count+1
if temp_count==int(K):
count = count+1
print count
'''
3 2
AB
RAAB
RA
''' |
capets={
'name': 'Элегия',
'size': '120x80',
'color': 'Серый',
'stock': 1
}
print (capets)
capets ['stock']=2
capets ['price']=7900
print (capets)
print (capets ['name'])
print (capets.get('place', 'Москва')) # .get используем,чтобы не получить ошибку,
# если запрашиваем несуществующий ключ. После ключа можно добавить, то значение, которое хотим, чтобы
# выводилось для этого ключа. Если ничего не добавить будет выводиться None
del capets ['color']
print (capets)
|
from django.shortcuts import render
# Create your views here.
from .serializers import *
from .models import *
from film.models import categories_film
from film.serializers import FilmSerializer,FilmOneSerializer,FilmTilte
from film.models import actors
# Create your views here.
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated,IsAdminUser
from rest_framework import status
from django.core.exceptions import ObjectDoesNotExist
class CategoriesFilmView(APIView):
def get(self, request):
try:
#movie=acotors_film.objects.filter(actor=actors.objects.get(id=actors))
movies = categories_film.objects.all()
except categories_film.DoesNotExist:
return Response(status=status.HTTP_404_NOT_FOUND)
if request.method == "GET":
serializer_class = categoriesSerializer(movies, many=True)
return Response(serializer_class.data)
class FilmCategories(APIView):
def get(self, request, pk):
#print(pk)
movies =categories_film.objects.filter(films=pk).filter(actors=pk)
print(movies)
serializers =categoriesSerializer(movies,many=True)
return Response(serializers.data)
class CategoriesFilmAdd(APIView):
permission_classes = [IsAdminUser]
def post(self, request):
try:
serializer = categoriesSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
except ObjectDoesNotExist as e:
return Response({'error': str(e)}, safe=False, status=status.HTTP_404_NOT_FOUND)
except Exception:
return Response({'error': 'Something terrible went wrong'}, safe=False,
status=status.HTTP_500_INTERNAL_SERVER_ERROR)
class CategoriesFilmUpdate(APIView):
permission_classes = [IsAdminUser]
def post(self, request,pk):
try:
movies = categories_film.objects.get(id=pk)
serializer = categoriesSerializer(instance=movies, data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data)
except ObjectDoesNotExist as e:
return Response({'error': str(e)}, safe=False, status=status.HTTP_404_NOT_FOUND)
except Exception:
return Response({'error': 'Something terrible went wrong'}, safe=False,
status=status.HTTP_500_INTERNAL_SERVER_ERROR)
class CategoriesFilmDelete(APIView):
permission_classes = [IsAdminUser]
def post(self, request, pk):
try:
movies = categories_film.objects.get(id=pk)
movies.delete()
return Response("Item succsesfully Delete")
except ObjectDoesNotExist as e:
return Response({'error': str(e)}, safe=False, status=status.HTTP_404_NOT_FOUND)
except Exception:
return Response({'error': 'Something went wrong'}, safe=False, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
|
import unittest
from katas.beta.denumerate_string import denumerate
class DenumerateTestCase(unittest.TestCase):
def test_equal_1(self):
self.assertEqual(denumerate([
(4, 'y'), (1, 'o'), (3, 't'), (0, 'm'), (2, 'n')
]), 'monty')
def test_equal_2(self):
self.assertEqual(denumerate([
(1, '3'), (2, 'l'), (4, 'o'), (3, 'l'), (0, 'h')
]), 'h3llo')
def test_false_1(self):
self.assertFalse(denumerate([(0, '%')]))
def test_false_2(self):
self.assertFalse(denumerate([(1, 'a'), (2, 'b')]))
|
import tkinter as tk
from tkinter import ttk
win=tk.Tk()
win.title('Label Frame')
label_frame=ttk.Labelframe(win,text="Enter your details below: ", )
label_frame.grid(row=0,column=0)
labels=["What is your name: ","What is your age: ","What is your gender: ","Country:","state:","city:","address:"]
#labels
for i in range(len(labels)):
cur_label="label"+str(i)
cur_label=ttk.Label(label_frame,text=labels[i])
cur_label.grid(row=i,column=0,sticky=tk.W)
user_info={
"name": tk.StringVar(),
'age': tk.StringVar(),
'gender': tk.StringVar(),
'country': tk.StringVar(),
'state': tk.StringVar(),
'city': tk.StringVar(),
'address':tk.StringVar()
}
counter=0
for i in user_info:
cur_entrybox='entry'+i
cur_entry = ttk.Entry(label_frame, width=16, textvariable=user_info[i])
cur_entry.grid(row=counter, column=1)
counter+=1
def submit():
print(user_info['name'].get())
print(user_info.get('age').get())
print(user_info.get('gender').get())
print(user_info.get('country').get())
print(user_info.get('state').get())
print(user_info.get('city').get())
print(user_info.get('address').get())
submit_btn=ttk.Button(win,text="Submit",command=submit)
submit_btn.grid(row=1,column=0)
for child in label_frame.winfo_children():
child.grid_configure(padx=4,pady=4)
win.mainloop()
|
from distutils.core import setup
setup(
name="pykefcontrol",
packages=["pykefcontrol"],
version="0.6.2",
license="MIT",
description="Python library for controling the KEF LS50 Wireless II",
long_description="Python library for controling the KEF LS50 Wireless II. It supports basic commands for setting the volume, the source, and getting the media playing informations",
author="Robin Dupont",
author_email="robin.dpnt@gmail.com",
url="https://github.com/rodupont/pykefcontrol",
keywords=["Kef", "KEF", "Speaker", "LS50", "LS50W2", "Wireless II", "Wireless 2"],
install_requires=["requests>=2.26.0", "aiohttp>=3.7.4"],
classifiers=[
"Development Status :: 4 - Beta", # Chose either "3 - Alpha", "4 - Beta" or "5 - Production/Stable" as the current state of your package
"Topic :: Home Automation",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.4",
"Programming Language :: Python :: 3.5",
"Programming Language :: Python :: 3.6",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
"Programming Language :: Python :: 3.10",
],
)
|
from pynamodb.models import Model
from pynamodb.attributes import UnicodeAttribute, NumberAttribute, BooleanAttribute, UTCDateTimeAttribute
from weibo import get_config
config = get_config()
class UserModel(Model):
"""
A DynamoDB User
"""
class Meta:
table_name = "weibo-user"
aws_access_key_id = config['aws_access_key_id']
aws_secret_access_key = config['aws_secret_access_key']
id = UnicodeAttribute(hash_key=True)
screen_name = UnicodeAttribute(null=True)
gender = UnicodeAttribute(null=True)
statuses_count = NumberAttribute(null=True)
followers_count = NumberAttribute(null=True)
follow_count = NumberAttribute(null=True)
registration_time = UnicodeAttribute(null=True)
sunshine = UnicodeAttribute(null=True)
birthday = UnicodeAttribute(null=True)
location = UnicodeAttribute(null=True)
education = UnicodeAttribute(null=True)
company = UnicodeAttribute(null=True)
description = UnicodeAttribute(null=True)
profile_url = UnicodeAttribute(null=True)
profile_image_url = UnicodeAttribute(null=True)
avatar_hd = UnicodeAttribute(null=True)
urank = NumberAttribute(null=True)
mbrank = NumberAttribute(null=True)
verified = BooleanAttribute(null=True)
verified_type = NumberAttribute(null=True)
verified_reason = UnicodeAttribute(null=True)
class WeiboModel(Model):
class Meta:
table_name = "weibo-post"
aws_access_key_id = config['aws_access_key_id']
aws_secret_access_key = config['aws_secret_access_key']
id = NumberAttribute(hash_key=True)
bid = UnicodeAttribute(range_key=True)
user_id = NumberAttribute(null=True)
screen_name = UnicodeAttribute(null=True)
text = UnicodeAttribute(null=True)
article_url = UnicodeAttribute(null=True)
topics = UnicodeAttribute(null=True)
at_users = UnicodeAttribute(null=True)
pics = UnicodeAttribute(null=True)
video_url = UnicodeAttribute(null=True)
location = UnicodeAttribute(null=True)
created_at = UnicodeAttribute(null=True)
source = UnicodeAttribute(null=True)
attitudes_count = NumberAttribute(null=True)
comments_count = NumberAttribute(null=True)
reposts_count = NumberAttribute(null=True)
|
from jinja2 import FileSystemLoader, StrictUndefined
from jinja2.environment import Environment
env = Environment(undefined=StrictUndefined)
env.loader = FileSystemLoader('.')
nxos1 = {
"interface": "Ethernet1/1",
"ip_address": "10.1.100.1/24"
}
nxos2 = {
"interface": "Ethernet1/1",
"ip_address": "10.1.100.2/24"
}
template_file = 'ex2a.j2'
template = env.get_template(template_file)
nxos1_output = template.render(**nxos1)
nxos2_output = template.render(**nxos2)
print(nxos1_output)
print(nxos2_output)
|
from abc import ABC, abstractmethod
from pygame import key
class Button(ABC):
@abstractmethod
def check_pressed(self):
pass
# We'll have a general controller with only the buttons we need
# That can be checked uniformly across the code
class Controller:
# Buttons that can be pressed (and checked)
buttons_pressed = {}
button_mappings = {}
# Button_name (String) should specify our abstract buttons to bind to
# button (Button) should be an object that implements the Button interface
def register_button(self, button_name, button):
if button_name in self.button_mappings.keys():
self.button_mappings[button_name].add(button)
else:
self.button_mappings[button_name] = [button]
# Takes in a button name and looks through all the actual hardware buttons mapped to it
# Note that if the keyname doesn't exist, it returns a NoneType (as opposed to a bool)
def check_button_pressed(self, button_name):
button_pressed = False
if button_name in self.button_mappings.keys():
for button in self.button_mappings[button_name]:
if button.check_pressed():
button_pressed = True
return button_pressed
# Buttons from the keyboard (specifically)
class KeyboardButton(Button):
whichKey = None
def __init__(self, whichKey):
self.whichKey= whichKey
def check_pressed(self):
if key.get_pressed()[self.whichKey]:
return True
else:
return False
|
"""
Admin panel for CardControl Django application.
"""
from django.contrib import admin
from .models import Message
admin.site.register(Message)
|
import unittest
from jousting.player.knight import Knight
from jousting.util.rps import SHIELD
class KnightTest(unittest.TestCase):
def setUp(self):
self.knight = Knight("Lancelot")
def test_move(self):
knight = self.knight
self.assertEquals(0, knight.get_current_position())
knight.move(5)
self.assertEquals(5, knight.get_current_position())
def test_bruises(self):
knight = self.knight
self.assertEquals(0, knight.get_bruises())
knight.add_bruise()
self.assertEquals(1, knight.get_bruises())
def test_tactical_card(self):
knight = self.knight
self.assertEquals(-1, knight.get_tactical_card())
knight.set_tactical_card(SHIELD)
self.assertEquals(0, knight.get_tactical_card())
def test_accept_heavy_blows(self):
knight = self.knight
self.assertTrue(knight.get_accept_heavy_blows())
knight.set_accept_heavy_blows(False)
self.assertFalse(knight.get_accept_heavy_blows())
def test_disqualification(self):
knight = self.knight
self.assertFalse(knight.get_disqualified())
knight.add_fail_start()
self.assertFalse(knight.get_disqualified())
knight.add_fail_start()
self.assertTrue(knight.get_disqualified())
def test_points(self):
knight = self.knight
self.assertEquals(0, knight.get_points())
knight.add_points(5)
self.assertEquals(5, knight.get_points())
def test_unhorsed(self):
knight = self.knight
self.assertFalse(knight.get_unhorsed())
knight.set_unhorsed(True)
self.assertTrue(knight.get_unhorsed())
def test_strike_modifier(self):
knight = self.knight
self.assertEquals(0, knight.get_strike_modifier())
knight.set_strike_modifier(5)
self.assertEquals(5, knight.get_strike_modifier())
def test_failure_to_start(self):
knight = self.knight
self.assertFalse(knight.get_failed_to_start())
knight.move(6)
knight.determine_failed_to_start()
self.assertTrue(knight.get_failed_to_start())
knight.reset_for_round()
knight.move(7)
knight.determine_failed_to_start()
self.assertFalse(knight.get_failed_to_start())
def test_get_name(self):
name = self.knight.get_name()
self.assertEquals("Sir Lancelot", name)
|
from tkinter import Tk
from hello_view2 import HelloView
# HelloView 的 Controller 類別
class HelloController:
# 設定初值
def __init__(self):
self.app = HelloView(master=Tk())
self.app.button["command"] = self.action
self.app.mainloop()
# 按下按鈕的事件
def action(self):
self.app.result["text"] = "按鈕被按"
# GUI 執行部分
if __name__ == '__main__':
app = HelloController()
# 檔名: hello_controller.py
# 作者: Kaiching Chang
# 時間: June, 2018
|
class Currency(object):
def __init__(self, name, low, high):
self.name = name
self.low = low
self.high = high
#enter any new coinmarket cap listed currency in the following format: Currency(name of currency, low limit (integer), high limit (integer))
ethereum = Currency('ethereum', 280, 290)
neo = Currency('neo', 18, 20)
currency_array = []
currency_array.append(ethereum)
currency_array.append(neo)
#program sleep duration. units = seconds
time_inverval = 1800
#must be gmail email address. If you use two step authentification, you will need to use an app password: https://support.google.com/accounts/answer/185833
email_address = ''
password = ''
|
from flask_script import Manager
from exts import db
from flask_migrate import Migrate,MigrateCommand
from manage_run import app
#迁移的话必须导入 models下的
from models import User,Question,Answer
manager=Manager(app)
#使用migrte绑定app,db
migrate=Migrate(app=app,db=db)
#添加迁移脚本的命令到manager中
manager.add_command('db',MigrateCommand)
if __name__ == '__main__':
manager.run() |
# SPDX-License-Identifier: BSD-3-Clause
# Copyright (C) 2017-2020, SCANOSS Ltd. All rights reserved.
# Use of this source code is governed by a BSD-style
# license that can be found in the LICENSE file.
import hashlib
def parse_diff(src):
"""
Parse a commit diff.
This function parses a diff string and generates an output dictionary containing as keys the filenames in the changeset.
Each value is an array with the strings representing additions (starting with a '+').
There are only entries for changesets with additions, as these are the only
ones that we are interested in.
Parameters
----------
src : str
The contents of the diff in raw format.
"""
output = {}
currentfile = ""
currentlines = []
all_lines = ""
for line in src.splitlines():
if line.startswith("+++"):
# We are only interested in additions
if currentfile and currentlines:
output[currentfile] = currentlines
currentlines = []
# Typically a file line starts with "+++ b/...."
currentfile = line[6:] if line.startswith('+++ b/') else line[:4]
# Other lines starting with '+' are additions
elif line.startswith('+'):
currentlines.append(line[1:])
all_lines += line[1:]
# Wrap
if currentfile and currentlines:
output[currentfile] = currentlines
return output, hashlib.md5(all_lines.encode('utf-8')).hexdigest()
|
##
# wrapping: A program making it easy to use hyperparameter
# optimization software.
# Copyright (C) 2013 Katharina Eggensperger and Matthias Feurer
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import ast
from functools import partial
import types
import numpy as np
import os
from hpnnet.skdata_learning_algo import eval_fn, PyllLearningAlgo
import hpnnet.nnet # -- load scope with nnet symbols
import hyperopt
from skdata.base import Task
import HPOlib.data_util as data_util
__authors__ = ["Katharina Eggensperger", "Matthias Feurer"]
__contact__ = "automl.org"
def fetch_data(dataset, data_name, **kwargs):
dataset.fetch(True)
print os.path.join(dataset.home(), "convex_inputs.npy")
convex_labels = data_util.load_file(os.path.join(dataset.home(),
data_name + "_labels.npy"), "numpy", 100)
convex_inputs = data_util.load_file(os.path.join(dataset.home(),
data_name + "_inputs.npy"), "numpy", 100)
descr = dataset.descr
n_train = descr['n_train']
n_valid = descr['n_valid']
n_test = descr['n_test']
fold = int(kwargs['fold'])
folds = int(kwargs['folds'])
if folds == 1:
train = convex_inputs[:n_train]
valid = convex_inputs[n_train:n_train+n_valid]
test = convex_inputs[n_train+n_valid:]
train_targets = convex_labels[:n_train]
valid_targets = convex_labels[n_train:n_train+n_valid]
test_targets = convex_labels[n_train+n_valid:]
elif folds > 1:
cv_data = np.copy(convex_inputs[:n_train+n_valid])
train, valid = data_util.prepare_cv_for_fold(cv_data, fold, folds)
cv_labels = np.copy(convex_labels[:n_train+n_valid])
train_targets, valid_targets = data_util.prepare_cv_for_fold(cv_labels,
fold, folds)
test = convex_inputs[n_train+n_valid:]
test_targets = convex_labels[n_train+n_valid:]
else:
raise ValueError("Folds cannot be less than 1")
return train, valid, test, train_targets, valid_targets, test_targets
def custom_split_protocol(self, algo, train, train_targets, valid,
valid_targets, test, test_targets):
"""
This is modification from skdata/larochelle_et_al_2007/view.py and will be
injected in there instead of the original protocol
"""
ds = self.dataset
ds.fetch(True)
ds.build_meta()
n_cv = ds.descr['n_train'] + ds.descr['n_valid']
n_test = ds.descr['n_test']
print ds.descr['n_train'], ds.descr['n_valid'], ds.descr['n_test']
print "Split assertion 1", len(train), len(valid), n_cv
assert(len(train) + len(valid) == n_cv)
print "Split assertion 2", len(train_targets), len(valid_targets), n_cv
assert(len(train_targets) + len(valid_targets) == n_cv)
print "Split assertion 3", len(test), n_test
assert(len(test) == n_test)
print "Split assertion 4", len(test_targets), n_test
assert(len(test_targets) == n_test)
train_task = Task('vector_classification',
name='train',
x=train.reshape(train.shape[0], -1),
y=train_targets,
n_classes=ds.descr['n_classes'])
valid_task = Task('vector_classification',
name='valid',
x=valid.reshape(valid.shape[0], -1),
y=valid_targets,
n_classes=ds.descr['n_classes'])
test_task = Task('vector_classification',
name='test',
x=test.reshape(test.shape[0], -1),
y=test_targets,
n_classes=ds.descr['n_classes'])
model = algo.best_model(train=train_task, valid=valid_task)
algo.loss(model, train_task)
algo.loss(model, valid_task)
algo.loss(model, test_task)
def wrapping_nnet_split_decorator(params, space, protocol_class, mode='train',
**kwargs):
"""
This function changes the protocol_class and injects the cv_protocol.
"""
# Prepare the custom_split_protocol with the data for the data split
protocol = partial(custom_split_protocol, train=kwargs['train'],
train_targets=kwargs['train_targets'],
valid=kwargs['valid'], valid_targets=
kwargs['valid_targets'], test=kwargs['test'],
test_targets=kwargs['test_targets'])
# by only using functools.partial, the method is unbound, meaning it does
# not belong to the respective Protocol class. The next line adds the method
# to the protocol class
protocol_class.protocol = types.MethodType(protocol, None, protocol_class)
return wrapping_nnet(params, space, protocol_class, mode, **kwargs)
def wrapping_nnet(params, space, protocol_class, mode='train', **kwargs):
"""
This function takes a protocol class and uses the skdata_learning_algo to
train the neural network. Protocol_class can either be the one specified at
the top of this script or the original one from skdata
"""
dataset_eval_fn = partial(eval_fn, protocol_cls=protocol_class)
# Get the unevaluated search space from arguments,, extract all hyper-
# parameters and create a memo object. This contains the random expression
# as a key and the new pyll Literal as a value. The random expression will
# then be replaced with the Literal by the dataset_eval_fn
# This is only for testing purposes
#space = hpnnet.nips2011.nnet1_preproc_space(sup_min_epochs = 10,
# sup_max_epochs = 100)
hps = {}
if type(space) == tuple:
hpspace = space[0]
else:
hpspace = space
hyperopt.pyll_utils.expr_to_config(hpspace, (), hps)
memo = {}
for param in params:
node = hps[param]['node']
# print "###"
# print "Label:", hps[param]['label']
# print "Node:", node
# We have to convert the parameter back to a string so literal eval can
# actually work with it
try:
value = ast.literal_eval(str(params[param]))
except ValueError as e:
print "Malformed String:", params[param]
raise e
memo[node] = hyperopt.pyll.Literal(value)
# print "Memo[node]:", memo[node]
# print "Value", value
hpspace = hyperopt.pyll.stochastic.recursive_set_rng_kwarg(hpspace)
if type(space) == tuple:
space = (hpspace, space[1])
space = hyperopt.pyll.as_apply(space)
else:
space = hpspace
print "Evaluation mode", mode
if mode == 'train':
rval = dataset_eval_fn(space, memo, None)
return rval['loss']
elif mode == 'test':
"""
Ad-hoc implementation for testing a configuration.
"""
import hpnnet.nnet as nnet # -- ensure pyll symbols are loaded
assert 'time' in hyperopt.pyll.scope._impls
protocol = protocol_class()
algo = PyllLearningAlgo(space, memo, None)
protocol.protocol(algo)
true_loss = None
print algo.results
for dct in algo.results['loss']:
if dct['task_name'] == 'test':
true_loss = dct['err_rate']
return true_loss
else:
raise Exception("No evaluation mode specified") |
####################################################################################################
# game_of_three.py #
# ------------------------------------------------------------------------------------------------ #
# Takes a number and displays all the steps of the game of three. The game of three takes a number #
# and then divides the number by three or add one or subtracts one to make the number divisable #
# by the number three. The game ends when the number 1 is reached. #
# From the follow /r/DailyProgrammer post: #
# #
# ------------------------------------------------------------------------------------------------ #
# #
# Author: Sejson #
# Date: January 3 2016 #
####################################################################################################
def game_of_three():
"""
game_of_three()
---------------
Description:
All the steps of the game are printed out.
------------
"""
# Enables the program to be reran
running = True
# Prompt for a number to play the game with.
# Placed outside of loop to avoid do while loop.
number = int(input("Please enter a number:\n"))
while(running):
# Divide or add or subtract from the number until the value of number
# is equal to 1.
while (number > 1):
# Determine if the number has to have one added or subtract or if it
# can be divided by 3
if (number % 3) == 0:
print(str(number) + " 0")
number /= 3
elif ((number + 1) % 3) == 0:
print(str(number) + " +1")
number += 1
number /= 3
elif ((number - 1) % 3) == 0:
print(str(number) + " -1")
number -= 1
number /= 3
else:
# Print the final value - should be 1 - to indicate that its done.
print(number)
# Findout if the user would like to try another number
answer = input("Enter another numbrer or \" End \" to stop.\n")
if "end" in answer.lower():
running = False
print("Goodbye...")
else:
number = answer
# Set game_of_three as the main function.
if __name__ == "__main__":
game_of_three()
|
class Parametrization(object):
BASEPT_AND_DIR_VECTORS_MUST_BE_IN_SAME_DIM_MSG = (
'the basepoint and direction vectors should all live in the same dimension')
def __init__(self,basepoint,direction_vectors):
self.basepoint = basepoint
self.direction_vectors = direction_vectors
self.dimension = self.basepoint.dimension
try:
for v in direction_vectors:
assert v.dimension == self.dimension
except AssertionError:
raise Exception(self.BASEPT_AND_DIR_VECTORS_MUST_BE_IN_SAME_DIM_MSG)
def __str__(self):
output = ''
for coord in range(self.dimension):
output += 'x_{} = {} '.format(coord + 1,round(self.basepoint.coordinates[coord],3))
for free_var,vector in enumerate(self.direction_vectors):
output += '+ {} t_{}'.format(round(vector.coordinates[coord],3),free_var+1)
output +='\n'
return output
|
import numpy
import statsmodels.sandbox.stats.multicomp
import scipy.stats
import sys
ifile = open("gene_names")
gene_names=[]
for line in ifile:
gene_names.append(line.replace("\n",""))
ifile.close()
file_name="TE_result_all.csv"
ifile = open(file_name)
cutOff=0
source=[]
TE=[]
target=[]
for line in ifile:
temp = line.replace("\n","").split(",")
if float(temp[1])>cutOff:
source.append(int(temp[0]))
TE.append(float(temp[2]))
target.append(int(temp[1]))
ifile.close()
TEzscore=(TE-numpy.mean(TE))/numpy.std(TE)
TEpvalue=1-scipy.stats.norm.cdf(TEzscore)
TEfdr=statsmodels.sandbox.stats.multicomp.multipletests(TEpvalue,alpha=0.05,method='fdr_bh')
fdrCutoff=float(sys.argv[1])
ofile = open(file_name.replace(".csv",".fdr")+str(fdrCutoff)+".sif","w")
for i in range(len(source)):
if TEfdr[1][i]<fdrCutoff:
ofile.write(gene_names[source[i]-1]+"\t"+str(TE[i])+"\t"+gene_names[target[i]-1]+"\n")
ofile.close()
|
"""
This file is used for storage of database credentials.
"""
DATABASE = {
'host': '127.0.0.1',
'user': 'demouser',
'passwd': 'demopassword',
'database': 'blueairdb',
'table': 'airdata'
}
|
import socket
target_host = "192.168.0.12"
target_port = 80
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client.sendto("AAABBBCCC", (target_host, target_port))
data, addr = client.recvfrom(4096)
print data |
n = float(input("Enter a first number: "))
n1 = float(input("Enter a second number: "))
print(n ** n1) |
import sys
import re
def consolidate_CSV(csv_path, outputFile):
""" Takes the csv file located at csv_path that was downloaded from
https://api.bitcoincharts.com/v1/csv/ and consolidates the duplicate
timestamps into one entry with the price and volume values being the
average of all entries with that timestamp. It is required that the
csv file located at csv_path has the form:
[timestamp], [price], [volume]
"""
print("beginning consolidation of " + csv_path + " to output file " + \
outputFile + "...\nthis may take a while...\n")
with open(csv_path) as input:
first_line = input.readline().split(",")
current_time_stamp = first_line[0]
price_sum = float(first_line[1])
volume_sum = float(first_line[2])
with open(outputFile, "w") as output:
n_lines_since_reset = 1
for i in input:
current_line = i.split(",")
if current_line[0] != current_time_stamp:
output.write(current_time_stamp + "," \
+ str(price_sum / n_lines_since_reset) + "," \
+ str(volume_sum / n_lines_since_reset) + "\n")
current_time_stamp = current_line[0]
price_sum = float(current_line[1])
volume_sum = float(current_line[2])
n_lines_since_reset = 1
else:
price_sum += float(current_line[1])
volume_sum += float(current_line[2])
n_lines_since_reset += 1
output.write(current_time_stamp + "," \
+ str(price_sum / n_lines_since_reset) + "," \
+ str(volume_sum / n_lines_since_reset) + "\n")
print("consolidation completed successfully.\n")
def is_valid_input_CSV(csv_path):
""" Analyzes the first line in the given csv path and checks to see if
it is in the expected format.
"""
csv_line_regex = r"^\d+,\d+\.\d+,\d+\.\d+$"
with open(csv_path) as input:
first_line = input.readline()
if re.match(csv_line_regex, first_line):
return True
return False
if len(sys.argv) != 3:
print("Incorrect command line arguments. The correct format is " + \
"\"python3 [csv_path] [outputFile]\"")
elif not is_valid_input_CSV(sys.argv[1]):
print("Input file is not in the format [timestamp],[price],[volume]. Make " \
+ "sure that the CSV file was downloaded from " \
+ "https://api.bitcoincharts.com/v1/csv/ and try again")
else:
consolidate_CSV(sys.argv[1], sys.argv[2])
|
import socket
from pynput import keyboard
from threading import Thread
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = socket.gethostname()
print("Hostname:",host)
port = 8184
coordinates = []#player locations
bullets = []#bullet locations
serversocket.bind((host, port))
No_Clients = 0
clientsockets = {}
print("Once all users have connected, press SPACE to continue/play.")
def break_loop(key, abortKey='space'):
try:
k = key.char
except:
k = key.name
if k == abortKey:
return False
def infiniloop():
global No_Clients,clientsockets,serversocket
while True:
clientsocket, addr = serversocket.accept()
clientsockets[No_Clients] = clientsocket
print("Got a connection from %s" % str(addr))
No_Clients += 1
serversocket.listen()
listener = keyboard.Listener(on_press=break_loop, abortKey='space')
listener.start()
Thread(target=infiniloop, args=(), name='infiniloop', daemon=True).start()
listener.join()
print("Starting session...")
for turn in range(No_Clients):
coordinates.append("")
for turn in range(No_Clients):
bullets.append("")
clientSkip = []
running = True
while running:
#checking players are alive and cutting connections
#receiving locations from players
for clientKey in clientsockets.keys():
message = clientsockets[clientKey].recv(8192).decode()
if message != "True":
coordinates[clientKey] = message
else:
coordinates[clientKey] = "empty,"
bullets[clientKey] = "empty,"
clientsockets[clientKey].close()
clientSkip.append(clientKey)
for clientSkipped in clientSkip:
clientsockets.pop(clientSkipped, None)
clientSkip = []
#sending player the locations of others
for clientKey in clientsockets.keys():
word = ""
for coord in coordinates:
word += coord
clientsockets[clientKey].send(word.encode())
#receiving bullet locations from players
for clientKey in clientsockets.keys():
something = clientsockets[clientKey].recv(8192).decode()
if something == "empty":
bullets[clientKey] = "empty,"
else:
bullets[clientKey] = something
#sending player the locations of others' bullets
for clientKey in clientsockets.keys():
word = ""
for coord in bullets:
word += coord
clientsockets[clientKey].send(word.encode())
if len(clientsockets) == 0:
running = False
print("Server shutting down...")
serversocket.close() |
#!/usr/bin/env python3
# Copyright (c) 2011, the Dart project authors. Please see the AUTHORS file
# for details. All rights reserved. Use of this source code is governed by a
# BSD-style license that can be found in the LICENSE file.
# Template loader and preprocessor.
#
# Preprocessor language:
#
# //$ Comment line removed by preprocessor
# $if VAR
# $else
# $endif
#
# VAR must be defined in the conditions dictionary.
import os
class TemplateLoader(object):
"""Loads template files from a path."""
def __init__(self, root, subpaths, conditions={}):
"""Initializes loader.
Args:
root - a string, the directory under which the templates are stored.
subpaths - a list of strings, subpaths of root in search order.
conditions - a dictionary from strings to booleans. Any conditional
expression must be a key in the map.
"""
self._root = root
self._subpaths = subpaths
self._conditions = conditions
self._cache = {}
def TryLoad(self, name, more_conditions={}):
"""Returns content of template file as a string, or None of not found."""
conditions = dict(self._conditions, **more_conditions)
cache_key = (name, tuple(sorted(conditions.items())))
if cache_key in self._cache:
return self._cache[cache_key]
for subpath in self._subpaths:
template_file = os.path.join(self._root, subpath, name)
if os.path.exists(template_file):
template = ''.join(open(template_file).readlines())
template = self._Preprocess(template, template_file, conditions)
self._cache[cache_key] = template
return template
return None
def Load(self, name, more_conditions={}):
"""Returns contents of template file as a string, or raises an exception."""
template = self.TryLoad(name, more_conditions)
if template is not None: # Can be empty string
return template
raise Exception("Could not find template '%s' on %s / %s" %
(name, self._root, self._subpaths))
def _Preprocess(self, template, filename, conditions):
def error(lineno, message):
raise Exception('%s:%s: %s' % (filename, lineno, message))
lines = template.splitlines(True)
out = []
condition_stack = []
active = True
seen_else = False
for (lineno, full_line) in enumerate(lines):
line = full_line.strip()
if line.startswith('$'):
words = line.split()
directive = words[0]
if directive == '$if':
if len(words) != 2:
error(lineno, '$if does not have single variable')
variable = words[1]
if variable in conditions:
condition_stack.append((active, seen_else))
active = active and conditions[variable]
seen_else = False
else:
error(lineno, "Unknown $if variable '%s'" % variable)
elif directive == '$else':
if not condition_stack:
error(lineno, '$else without $if')
if seen_else:
raise error(lineno, 'Double $else')
seen_else = True
(parentactive,
_) = condition_stack[len(condition_stack) - 1]
active = not active and parentactive
elif directive == '$endif':
if not condition_stack:
error(lineno, '$endif without $if')
(active, seen_else) = condition_stack.pop()
else:
# Something else, like '$!MEMBERS'
if active:
out.append(full_line)
elif line.startswith('//$'):
pass # Ignore pre-processor comment.
else:
if active:
out.append(full_line)
continue
if condition_stack:
error(len(lines), 'Unterminated $if')
return ''.join(out)
|
# Copyright 2023 Pants project contributors (see CONTRIBUTORS.md).
# Licensed under the Apache License, Version 2.0 (see LICENSE).
from __future__ import annotations
import json
import pytest
from pants.backend.javascript import resolve
from pants.backend.javascript.package_json import NodeThirdPartyPackageTarget, PackageJsonTarget
from pants.backend.javascript.resolve import ChosenNodeResolve, RequestNodeResolve
from pants.build_graph.address import Address
from pants.core.target_types import TargetGeneratorSourcesHelperTarget
from pants.engine.rules import QueryRule
from pants.testutil.rule_runner import RuleRunner
@pytest.fixture
def rule_runner() -> RuleRunner:
return RuleRunner(
rules=[
*resolve.rules(),
QueryRule(ChosenNodeResolve, (RequestNodeResolve,)),
],
target_types=[
PackageJsonTarget,
NodeThirdPartyPackageTarget,
TargetGeneratorSourcesHelperTarget,
],
)
def test_gets_expected_resolve_for_standalone_packages(
rule_runner: RuleRunner,
) -> None:
rule_runner.write_files(
{
"src/js/a/BUILD": "package_json()",
"src/js/a/package.json": json.dumps({"name": "ham", "version": "0.0.1"}),
"src/js/b/BUILD": "package_json()",
"src/js/b/package.json": json.dumps({"name": "spam", "version": "0.0.1"}),
}
)
a_tgt = rule_runner.get_target(Address("src/js/a", generated_name="ham"))
b_tgt = rule_runner.get_target(Address("src/js/b", generated_name="spam"))
a_result = rule_runner.request(ChosenNodeResolve, [RequestNodeResolve(a_tgt.address)])
b_result = rule_runner.request(ChosenNodeResolve, [RequestNodeResolve(b_tgt.address)])
assert a_result.resolve_name == "js.a"
assert a_result.file_path == "src/js/a/package-lock.json"
assert b_result.resolve_name == "js.b"
assert b_result.file_path == "src/js/b/package-lock.json"
def test_gets_expected_resolve_for_workspace_packages(
rule_runner: RuleRunner,
) -> None:
rule_runner.write_files(
{
"src/js/BUILD": "package_json()",
"src/js/package.json": json.dumps(
{"name": "ham", "version": "0.0.1", "workspaces": ["./child"]}
),
"src/js/child/BUILD": "package_json()",
"src/js/child/package.json": json.dumps({"name": "spam", "version": "0.0.1"}),
}
)
tgt = rule_runner.get_target(Address("src/js", generated_name="ham"))
result = rule_runner.request(ChosenNodeResolve, [RequestNodeResolve(tgt.address)])
child_tgt = rule_runner.get_target(Address("src/js/child", generated_name="spam"))
child_result = rule_runner.request(ChosenNodeResolve, [RequestNodeResolve(child_tgt.address)])
assert child_result == result
assert child_result.resolve_name == "js"
assert child_result.file_path == "src/js/package-lock.json"
|
import os
import z
from shutil import copyfile, copytree
dest = "/mnt/c/Users/Zoe/Documents/dest/split"
#z.gsavedir = dest
z.getp("dates")
path = z.getPath("split")
try:
copytree(path, dest)
except:
pass
print ("finished split")
dest = "/mnt/c/Users/Zoe/Documents/dest"
getpd = z.getp("getpd")
for name in getpd:
path = z.getPath("{}/{}.pkl".format("pkl", name))
newpath = "{}/{}.pkl".format(dest, name)
if not os.path.exists(newpath):
print("newpath : {}".format( newpath ))
copyfile(path, newpath)
|
from django.urls import path
from .views import (
ProducersList,
ProducerDetails
)
urlpatterns = [
path('', ProducersList.as_view()),
path('<int:pk>/', ProducerDetails.as_view())
]
|
from tkinter import *
from tkinter.filedialog import askopenfilename
# from tkinter import ttk
from PIL import Image, ImageTk#import Image, ImageTk
calibUnitChoices = {
'um': 1e6,
'mm': 1e3,
'cm': 1e2,
'm': 1,
'km': 1e-3,
'in': 39.3701,
'ft': 3.28084,
'mi': 0.000621371,
}
def calibrateBtn():
print('Button Pressed')
calibBtn(gui, text='Calibrate', state=DISABLED)
if __name__ == "__main__":
# https://stackoverflow.com/questions/34276663/tkinter-gui-layout-using-frames-and-grid
root = Tk()
root.title('Model Definition')
root.geometry('{}x{}'.format(460, 350))
# create all of the main containers
top_frame = Frame(root, bg='cyan', width=450, height=50, pady=3)
center = Frame(root, bg='gray2', width=50, height=40, padx=3, pady=3)
btm_frame = Frame(root, bg='white', width=450, height=45, pady=3)
btm_frame2 = Frame(root, bg='lavender', width=450, height=60, pady=3)
# layout all of the main containers
root.grid_rowconfigure(1, weight=1)
root.grid_columnconfigure(0, weight=1)
top_frame.grid(row=0, sticky="ew")
center.grid(row=1, sticky="nsew")
btm_frame.grid(row=3, sticky="ew")
btm_frame2.grid(row=4, sticky="ew")
# create the widgets for the top frame
model_label = Label(top_frame, text='Model Dimensions')
width_label = Label(top_frame, text='Width:')
length_label = Label(top_frame, text='Length:')
entry_W = Entry(top_frame, background="pink")
entry_L = Entry(top_frame, background="orange")
# layout the widgets in the top frame
model_label.grid(row=0, columnspan=3)
width_label.grid(row=1, column=0)
length_label.grid(row=1, column=2)
entry_W.grid(row=1, column=1)
entry_L.grid(row=1, column=3)
# create the center widgets
center.grid_rowconfigure(0, weight=1)
center.grid_columnconfigure(1, weight=1)
ctr_left = Frame(center, bg='blue', width=100, height=190)
ctr_mid = Frame(center, bg='yellow', width=250, height=190, padx=3, pady=3)
ctr_right = Frame(center, bg='green', width=100, height=190, padx=3, pady=3)
ctr_left.grid(row=0, column=0, sticky="ns")
ctr_mid.grid(row=0, column=1, sticky="nsew")
ctr_right.grid(row=0, column=2, sticky="ns")
root.mainloop()
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9.2 on 2016-05-20 03:01
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('backend', '0007_auto_20160520_0110'),
]
operations = [
migrations.AlterField(
model_name='customuser',
name='new_user',
field=models.BooleanField(default=True),
),
]
|
import cgi
form = cgi.FieldStorage()
# send to server instead
print form["username"] |
class Node:
def __init__(self, data):
self.data = data
self.nextreference = None
self.previousreference = None
class DoublyLinkedList:
def __init__(self):
self.head = None
def print_LL(self):
print()
if (self.head is None):
print('Linked List Is Empty!')
else:
n = self.head
while(n is not None):
print(n.data, '-->', end=" ")
n = n.nextreference
def print_LL_reverse(self):
print()
if (self.head is None):
print('Linked List Is Empty!')
else:
n = self.head
while(n.nextreference is not None):
n = n.nextreference
while(n is not None):
print(n.data, '-->', end=" ")
n = n.previousreference
def insert_LinkedListEmpty(self, data):
if (self.head is None):
new_node = Node(data)
self.head = new_node
else:
('Linked List is not empty!')
def add_beginning(self, data):
new_node = Node(data)
if (self.head is None):
self.head = new_node
else:
new_node.nextreference = self.head
self.head.previousreference = new_node
self.head = new_node
def add_end(self, data):
new_node = Node(data)
if (self.head is None):
self.head = new_node
else:
n = self.head
while(n.nextreference is not None):
n = n.nextreference
n.nextreference = new_node
new_node.previousreference = n
def add_after(self,data,x):
if(self.head is None):
print('Linked list is empty')
else:
n = self.head
while (n is not None):
if(x==n.data):
break
n = n.nextreference
if (n is None):
print('Given Node is not present in the given Linked List')
else:
new_node = Node(data)
new_node.nextreference = n.nextreference
new_node.previousreference = n
if (n.nextreference is not None):
n.nextreference.previousreference = new_node
n.nextreference = new_node
|
from oauth2helper.version import __version__
from oauth2helper._token import validate, decode
from oauth2helper._content import user_name, get
|
v = int(input('Qual a velocidade atual do carro? '))
if v > 80:
m = 7 * (v - 80)
print('MULTADO! você excedeu o limite de 80km/h'
'\nVocê deve pagar uma multa de R${}.'.format(m))
print('Tenha um bom dia! Dirija com segurança.')
else:
print('Tenha um bom dia! Dirija com segurança.') |
import dash_bootstrap_components as dbc
from dash import Input, Output, State, html
alert = html.Div(
[
dbc.Button(
"Toggle alert with fade",
id="alert-toggle-fade",
className="me-1",
n_clicks=0,
),
dbc.Button(
"Toggle alert without fade", id="alert-toggle-no-fade", n_clicks=0
),
html.Hr(),
dbc.Alert(
"Hello! I am an alert",
id="alert-fade",
dismissable=True,
is_open=True,
),
dbc.Alert(
"Hello! I am an alert that doesn't fade in or out",
id="alert-no-fade",
dismissable=True,
fade=False,
is_open=True,
),
]
)
@app.callback(
Output("alert-fade", "is_open"),
[Input("alert-toggle-fade", "n_clicks")],
[State("alert-fade", "is_open")],
)
def toggle_alert(n, is_open):
if n:
return not is_open
return is_open
@app.callback(
Output("alert-no-fade", "is_open"),
[Input("alert-toggle-no-fade", "n_clicks")],
[State("alert-no-fade", "is_open")],
)
def toggle_alert_no_fade(n, is_open):
if n:
return not is_open
return is_open
|
# -*- coding: utf-8 -*-
from __future__ import unicode_literals
from django.db import models, migrations
class Migration(migrations.Migration):
dependencies = [
('categories', '0002_auto_20160205_2046'),
]
operations = [
migrations.CreateModel(
name='Good',
fields=[
('id', models.AutoField(primary_key=True, verbose_name='ID', auto_created=True, serialize=False)),
('name', models.CharField(max_length=50, verbose_name='Назва', db_index=True, unique=True)),
('description', models.TextField(verbose_name='Скарочанае апісанне')),
('content', models.TextField(verbose_name='Поўнае апісанне')),
('price', models.FloatField(verbose_name='Кошт, Br.', db_index=True)),
('price_acc', models.FloatField(null=True, verbose_name='Кошт са зніжкай, Br.', blank=True)),
('in_stock', models.BooleanField(verbose_name='У наяўнасці', default=True, db_index=True)),
('featured', models.BooleanField(verbose_name='Прапануемы', default=False, db_index=True)),
('image', models.ImageField(verbose_name='Асноўная выява', upload_to='goods/list')),
('category', models.ForeignKey(verbose_name='Катэгорыя', to='categories.Category')),
],
options={
'verbose_name': 'тавар',
'verbose_name_plural': 'тавары',
},
),
migrations.CreateModel(
name='GoodImage',
fields=[
('id', models.AutoField(primary_key=True, verbose_name='ID', auto_created=True, serialize=False)),
('image', models.ImageField(verbose_name='Дадатковая выява', upload_to='goods/detail')),
('good', models.ForeignKey(to='goods.Good')),
],
options={
'verbose_name': 'выява да тавару',
'verbose_name_plural': 'выявы да тавару',
},
),
]
|
#!coding:utf-8
from django.shortcuts import render
# Create your views here.
from Web.models import *
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse
from django.shortcuts import render
from django.core import serializers
from django.views.decorators.csrf import csrf_exempt
from Web.cookiecheck import authcheck
def login(request):
return render(request,'login.html')
def index(request):
if request.method =="POST":
username = request.POST["username"]
password = request.POST["password"]
docheck = user.objects.filter(user=username,password=password)
if request.method =="POST" and docheck:
request.session['user']=username
rsp = render(request,'query.html',context={'username':username})
rsp.set_signed_cookie('user',username,salt="hehehe")
rsp.set_signed_cookie('logined','True',salt="hehehe")
return rsp
else:
return render(request,'login.html')
else:
return HttpResponseRedirect("/")
@csrf_exempt
@authcheck
def getcommit(request):
querylist = commit.objects.all()
data = serializers.serialize("json",querylist)
tempdata =str(data)
final = tempdata.replace('\\\\','\\')
return JsonResponse(final,safe=False)
def logout(request):
rsp = render(request,'login.html')
rsp.delete_cookie('user')
rsp.delete_cookie('logined')
return rsp
@csrf_exempt
@authcheck
def comment(request):
text = request.POST["commit"]
user = request.session['user']
print user
commit.objects.create(user=user,commit=text)
return render(request,'query.html')
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import rospy
import serial
from math import sin, pi
from std_msgs.msg import Float64
from nav_msgs.msg import Odometry
from Lab1.msg import GPS
import utm
def parse_gps(line_split):
'''
Given pressure (in m fresh) and latitude (in radians) returns ocean depth (in m.). Uses the formula discovered and presented by Leroy and Parthiot in: Claude C. Leroy and Francois Parthiot, 'Depth-pressure relationships in the oceans and seas', J. Acoustic Society of America, March 1998, p1346-.
'''
gps_message = {"latitude" : 0.0,
"longitude" : 0.0,
"altitude" : 0.0,
"utm_easting" : 0.0,
"utm_northing" : 0.0,
"zone" : 0,
"letter" : "U"}
gps_message["latitude"] = float(line_split[2]) // 100 + float(line_split[2]) % 100 / 60
gps_message["longitude"] = float(line_split[4]) // 100 + float(line_split[4]) % 100 / 60
if line_split[3] == 'S':
gps_message["latitude"] = -1 * gps_message["latitude"]
if line_split[5] == 'W':
gps_message["longitude"] = -1 * gps_message["longitude"]
gps_message["altitude"] = float(line_split[9])
utm_result = utm.from_latlon(gps_message["latitude"], gps_message["longitude"])
gps_message["utm_easting"] = utm_result[0]
gps_message["utm_northing"] = utm_result[1]
gps_message["zone"] = utm_result[2]
gps_message["letter"] = utm_result[3]
return gps_message
if __name__ == '__main__':
SENSOR_NAME = "GPS"
rospy.init_node('parse',anonymous=True)
serial_port = rospy.get_param('~port','/dev/ttyUSB3')
serial_baud = rospy.get_param('~baudrate',4800)
sampling_rate = rospy.get_param('~sampling_rate',5.0)
port = serial.Serial(serial_port, serial_baud, timeout=3.)
rospy.loginfo("Using GPS on port "+serial_port+" at "+str(serial_baud))
rospy.sleep(0.2)
line = port.readline()
gps_pub = rospy.Publisher(SENSOR_NAME, GPS, queue_size=5)
rospy.logdebug("Initialization complete")
rospy.loginfo("Publishing GPS messages.")
sleep_time = 1/sampling_rate - 0.025
try:
while not rospy.is_shutdown():
line = port.readline()
if line == '':
rospy.logwarn("GPS: No data")
else:
if line.startswith('$GPGGA'):
try:
line_split = line.split(",")
rospy.loginfo(line_split)
if_null = 0
for field in line_split[0:13]:
if field == '':
if_null = 1
break
if if_null == 1:
continue
else:
gps_message = parse_gps(line_split)
gps_pub.publish(latitude=gps_message["latitude"],longitude=gps_message["longitude"],altitude=gps_message["altitude"],utm_easting=gps_message["utm_easting"],utm_northing=gps_message["utm_northing"],zone=gps_message["zone"],letter=gps_message["letter"])
rospy.loginfo(gps_message)
except:
rospy.logwarn("Data exception: "+line)
continue
rospy.sleep(sleep_time)
except rospy.ROSInterruptException:
port.close()
except serial.serialutil.SerialException:
rospy.loginfo("Shutting down paro_depth node...") |
def maker(n):
def action(x):
return x**n;
return action
f = maker(2)
print(f(3))
print(f(4))
|
'''
Created on Nov 9, 2013
@author: surendra
requirement: python 3
'''
import random
import time
def empty_board():
board = []
for i in range(0,3):
row = []
for j in range(0,3):
row.append("")
board.append(row)
return board
def board_copyof(board):
newboard = []
for i in board:
row = []
for j in range(0, 3):
row.append(i[j])
newboard.append(row)
return newboard
def show_board(board):
ofirst = " __ "
osecond = "| |"
othird = "|__|"
xfirst =' '
xsecond =' \/ '
xthird =' /\ '
for i in range(0, 3):
row = board[i]
row_display = []
for j in range(0, 3):
charcter = []
if row[j] == "O":
charcter.append(ofirst)
charcter.append(osecond)
charcter.append(othird)
elif row[j] == "X":
charcter.append(xfirst)
charcter.append(xsecond)
charcter.append(xthird)
else:
charcter.append(" ")
charcter.append(" ")
charcter.append(" ")
row_display.append(charcter)
print('----------------------------')
print('| %s | %s | %s |'%(row_display[0][0],row_display[1][0],row_display[2][0]))
print('| %s | %s | %s |'%(row_display[0][1],row_display[1][1],row_display[2][1]))
print('| %s | %s | %s |'%(row_display[0][2],row_display[1][2],row_display[2][2]))
print('| | | |')
print('----------------------------')
def gameover(board):
if (board[0][0] == board[1][0]) and (board[1][0] == board[2][0]) :
return board[0][0]
elif (board[0][0] == board[0][1]) and (board[0][1] == board[0][2]) :
return board[0][0]
elif (board[0][0] == board[1][1]) and (board[1][1] == board[2][2]) :
return board[0][0]
elif (board[1][0] == board[1][1]) and (board[1][1] == board[1][2]) :
return board[1][0]
elif (board[2][0] == board[2][1]) and (board[2][1] == board[2][2]) :
return board[2][0]
elif (board[2][0] == board[1][1]) and (board[1][1] == board[0][2]) :
return board[2][0]
elif (board[0][1] == board[1][1]) and (board[1][1] == board[2][1]) :
return board[0][1]
elif (board[0][2] == board[1][2]) and (board[1][2] == board[2][2]) :
return board[0][2]
else:
full = True
for i in range(0, 3):
for j in range(0, 3):
if board[i][j] == "":
full = False
break
if full:
return "F"
else:
return ""
def write_onboard(board, symbol, point):
if not validate_move(board, point):
return board
if board[int(point[0])][int(point[1])] == "":
board[int(point[0])][int(point[1])] = symbol
return board
else:
return board
def validate_move(board, point):
if board[int(point[0])][int(point[1])] == "":
return True
else:
return False
def get_input(player):
text = "Player " + player + " , Enter your move > "
choice = input(text)
if len(choice) > 2 or len(choice) == 0:
return get_input(player)
try:
coord = int(choice)
except ValueError:
return get_input(player)
x = (coord / 10)
y = (coord % 10)
if x >= 4 or x == 0 or y >= 4 or y == 0:
print("Invalid point")
return get_input(player)
return [(x-1), (y-1)]
def human_player(board, player):
move = get_input(player)
valid = validate_move(board, move)
if not valid :
print("illegal move")
human_player(board, player)
else:
return move
def crazy_robot(board, player):
time.sleep(1)
blank_squares = get_blank_tiles(board)
random_choice = random.randint(0, (len(blank_squares) - 1))
#print("Length: %d Random: %d"%(len(blank_squares),random_choice))
return blank_squares[random_choice]
def get_blank_tiles(board):
blank_squares = []
for i in range(0, 3):
for j in range(0, 3):
if board[i][j] == "":
blank_squares.append([i, j])
return blank_squares
def intelligent_robot(board, player):
time.sleep(1)
blank_squares = get_blank_tiles(board)
def intelligent_robot_evalute(board, player):
if gameover(board) == player:
return 1
else:
return 0
def intelligent_robot_max(board, player, depth):
if depth == 0 :
return intelligent_robot_evalute(board, player)
blank_tiles = get_blank_tiles(board)
max = -1
for blank_tiles in blank_tiles:
max = -1
def human_robot_choice():
print("H -> Human R -> Robot")
player1 = input("Player X : H/R > ")
player2 = input("Player O : H/R > ")
if (player1 == 'R' or player1 == 'H') and (player2 == 'R' or player2 == 'H') :
player_function = {}
player_function["X"] = {True: crazy_robot, False: human_player}[player1 == "R"]
player_function["O"] = {True: crazy_robot, False: human_player}[player2 == "R"]
return player_function
else:
return human_robot_choice()
def main():
board = empty_board()
current_player = "X"
player_function = human_robot_choice()
while 1:
show_board(board)
winner = gameover(board)
if winner != "":
break;
move = player_function[current_player](board, current_player)
board = write_onboard(board, current_player, move)
print("Player %s moves %d,%d"%(current_player, move[0]+1, move[1]+1))
if current_player == "O":
current_player = "X"
else:
current_player = "O"
if winner=="F":
print("Game draw")
else:
print("Player %s wins"%winner)
main() |
#from temporario import *
from resolucao import *
from gabarito import *
from criar import *
from exibir import *
from listar import * |
from timsort import timsort
import random
# Emtpy array
lst1 = []
# Single element
lst2 = [1]
# Two elements
lst3 = [1, 2]
# Alternating elements
lst4 = [-1,2] * 1000
# Ordered elements with pos and neg values
lst5 = [i for i in range(-1000, 1000)]
# Inversely ordered elements with pos and neg values
lst6 = [i for i in range(1000, -1000, -1)]
# Even number of random ints
lst7 = [random.randint(-10000, 10000) for i in range(1000)]
# Odd number of random ints
lst8 = [random.randint(-10000, 10000) for i in range(999)]
# More alternating elements
lst9 = [-1,2,-3,4,5]*1000
# Floats
lst10 = [(i + 0.2) for i in range(10000)]
# Ordered even numbers
lst11 = [i for i in range(1000, 2)]
# Full of zeros
lst12 = [0 for i in range(1000)]
# Inversely ordered odd numbers
lst13 = [i for i in range(9999, -1, -2)]
test_cases = [lst1, lst2, lst3, lst4, lst5, lst6, lst7,
lst8, lst9, lst10, lst11, lst12, lst13]
test_cases_alt = [lst1, lst2, lst3, lst4, lst5, lst6, lst7,
lst8, lst9, lst10, lst11, lst12, lst13]
def test_sort():
"""Test accuracy of algorithm"""
for lst in test_cases:
# Make a copy of the case
sortable = lst.copy()
# Make another copy of the case
sortable_copy = lst.copy()
sorted_copy = timsort(sortable_copy)
assert sorted_copy is sortable_copy
assert sorted_copy == sorted(sortable)
return "No error"
def test_sort_alt():
for lst in test_cases_alt:
# Create a copy of the list
copy = lst.copy()
timsort(lst)
# Compare each element to the next element
for i in range(len(lst) - 1):
assert lst[i] <= lst[i + 1]
# Assure that the lengths are the same
assert len(copy) == len(lst)
# Sort the copy using default
copy.sort()
# Every element in lst is in copy
for i in range(len(lst)):
assert copy[i] == lst[i]
return 'No error'
test_sort_alt(), test_sort() |
from models import Item, Label, update_label, BagCount, Setting
from django.db.models import Count
from django.http import Http404, HttpResponse, HttpResponseBadRequest
from django.core.paginator import Paginator, EmptyPage
from django.core.paginator import InvalidPage, PageNotAnInteger
from django.template import RequestContext
from django.shortcuts import render_to_response, get_object_or_404
from datetime import datetime
from collections import Counter, OrderedDict
import json
def lookup_label(request):
if request.method != 'GET':
return HttpResponseBadRequest(
json.dumps({'error':'Only GET method supported.'}),
content_type='application/javascript; charset=utf8')
code = request.GET.get('code')
if code is None:
return HttpResponseBadRequest(
json.dumps({'error':'Missing request parameter: code'}),
content_type='application/javascript; charset=utf8')
result = dict(name='', category='', subcategory='')
try:
label = Label.objects.get(code=code)
result['name'] = label.name
result['category'] = label.category
result['subcategory'] = label.subcategory
except Label.DoesNotExist:
pass
return HttpResponse(json.dumps(result))
def item_new(request):
if request.method != 'POST':
return HttpResponseBadRequest(
json.dumps({'error':'Only POST method supported.'}),
content_type='application/javascript; charset=utf8')
code = request.POST.get("code")
name = request.POST.get("name")
donor = request.POST.get("donor")
acquire_date = request.POST.get("acquire_date")
category = request.POST.get("category")
subcategory = request.POST.get("subcategory")
if code != '':
try:
label = Label.objects.get(code=code)
update = label.merge(name=name, category=category,
subcategory=subcategory)
name = label.name
category = label.category
subcategory = label.subcategory
except Label.DoesNotExist:
if name == '':
return HttpResponseBadRequest(
json.dumps({'error':'Name is a required field.'}),
content_type='application/javascript; charset=utf8')
Label.objects.create(name=name, code=code, category=category,
subcategory=subcategory)
if name == '':
return HttpResponseBadRequest(
json.dumps({'error':'Name is a required field.'}),
content_type='application/javascript; charset=utf8')
if acquire_date:
try:
acquire_date = datetime.strptime(acquire_date, '%b %d, %Y').date()
except ValueError:
return HttpResponseBadRequest(
json.dumps({'error':'Failed to parse date.'}),
content_type='application/javascript; charset=utf8')
else:
acquire_date = None
item = Item.objects.create(code=code, name=name, donor=donor,
acquire_date=acquire_date,
release_date=None,
category=category, subcategory=subcategory)
return HttpResponse(json.dumps(item.toJSON()))
def item_release(request):
if request.method != 'POST':
return HttpResponseBadRequest(
json.dumps({'error':'Only POST method supported.'}),
content_type='application/javascript; charset=utf8')
code = request.POST.get("code", None)
if code is None:
return HttpResponseBadRequest(
json.dumps({'error':'Missing request parameter: code'}),
content_type='application/javascript; charset=utf8')
try:
item = Item.objects.filter(code=code, release_date=None)
if len(item) == 0:
return HttpResponseBadRequest(
json.dumps({'error':'Item not found in inventory.'}),
content_type='application/javascript; charset=utf8')
item = item[:1][0]
today = datetime.now().date()
item.release_date = today
item.save()
return HttpResponse(json.dumps(item.toJSON()))
except Exception as ex:
return HttpResponseBadRequest(
json.dumps({'error':str(ex)}),
content_type='application/javascript; charset=utf8')
def item_update(request):
if request.method != 'POST':
return HttpResponseBadRequest(
json.dumps({'error':'Only POST method supported.'}),
content_type='application/javascript; charset=utf8')
num = request.POST.get("num", None)
field = request.POST.get("field", None)
value = request.POST.get("value", None)
if field not in ('name', 'code', 'donor', 'acquire_date', 'release_date',
'release_date', 'category', 'subcategory'):
return HttpResponseBadRequest(
json.dumps({'error':'Field not recognized.'}),
content_type='application/javascript; charset=utf8')
if field == 'name' and value == '':
return HttpResponseBadRequest(
json.dumps({'error':'Name is a required field.'}),
content_type='application/javascript; charset=utf8')
if field in ('acquire_date', 'release_date'):
try:
value = datetime.strptime(value, '%b %d, %Y').date()
except ValueError:
return HttpResponseBadRequest(
json.dumps({'error':'Failed to parse date.'}),
content_type='application/javascript; charset=utf8')
num = int(num)
item = get_object_or_404(Item, pk=num)
setattr(item, field, value)
if field == 'code':
try:
label = Label.objects.get(code=value)
item.name = label.name
item.category = label.category
item.subcategory = label.subcategory
except Label.DoesNotExist:
Label.objects.create(name=item.name, code=value,
category=item.category,
subcategory=item.subcategory)
item.save()
code = item.code
if code is not None and field in ('name', 'category', 'subcategory'):
update = update_label(code, field, value)
if field == 'category':
update |= update_label(code, 'subcategory', '')
else:
update = False
result = dict(update=update, item=item.toJSON())
return HttpResponse(json.dumps(result))
def item_delete(request):
if request.method != 'POST':
return HttpResponseBadRequest(
json.dumps({'error':'Only POST method supported.'}),
content_type='application/javascript; charset=utf8')
num = request.POST.get("num", None)
num = int(num)
try:
item = Item.objects.get(pk=num)
except Item.DoesNotExist:
return HttpResponseBadRequest(
json.dumps({'error':'Item not found.'}),
content_type='application/javascript; charset=utf8')
item.delete()
return HttpResponse()
def dashboard(request):
items = Item.objects.filter(release_date=None)
categories = items.values_list('category').annotate(Count('id'))
categories = categories.order_by('category')
bagcounts = OrderedDict((bag.category.name, bag.count)
for bag in BagCount.objects.order_by('category'))
bagsperweek = int(Setting.objects.get(key='count/bags/week').value)
categories = [(category,
count,
count / bagcounts[category],
count / bagcounts[category] / bagsperweek)
for category, count in categories]
subcategories = items.values('subcategory').annotate(Count('id'))
subcategories = subcategories.order_by('subcategory')
low_inventory = int(Setting.objects.get(key='count/low/inventory').value)
watchlist = filter(lambda tup: tup[3] <= low_inventory, categories)
watchlist.sort(key=lambda tup: tup[2])
return render_to_response('core/dashboard.html',
{'categories':categories,
'subcategories':subcategories,
'bagcounts':bagcounts,
'bagsperweek':bagsperweek,
'watchlist':watchlist},
context_instance=RequestContext(request))
def inventory(request, page=1):
"""List items from inventory."""
items = Item.objects.filter(release_date=None).order_by('-id')
items_paginator = Paginator(items, 20)
try:
items_page = items_paginator.page(page)
except (PageNotAnInteger, EmptyPage, InvalidPage):
raise Http404
return render_to_response('core/inventory.html', {'items_page':items_page},
context_instance=RequestContext(request))
def receiving(request):
return render_to_response('core/receiving.html', {},
context_instance=RequestContext(request))
def distribution(request):
return render_to_response('core/distribution.html', {},
context_instance=RequestContext(request))
def history(request):
donor = request.GET.get('donor')
try:
year = int(request.GET.get('year'))
except (ValueError, TypeError):
year = None
donations = Item.objects.values('donor', 'acquire_date')
if donor is not None: donations = donations.filter(donor=donor)
if year is not None: donations = donations.filter(acquire_date__year=year)
donations = donations.annotate(Count('id'))
donations = donations.order_by('-acquire_date')
donors = set()
years = set()
for donation in donations:
donors.add(donation['donor'])
years.add(donation['acquire_date'].year)
donors = sorted(donors)
years = sorted(years)
return render_to_response('core/history.html',
{'donations':donations,
'curr_donor':donor,
'curr_year':year,
'donors':donors,
'years':years},
context_instance=RequestContext(request))
def receipt(request):
donor = request.GET.get('donor')
acquire_date = request.GET.get('acquire_date')
if donor is None or acquire_date is None:
data = {'error': 'Please specify donor and date.'}
return render_to_response('core/receipt.html', { 'action': 'steps' },
context_instance=RequestContext(request))
try:
acquire_date = datetime.strptime(acquire_date, '%b %d, %Y').date()
except ValueError:
return render_to_response('core/receipt.html',
{'action':'steps',
'error':'Error: Failed to parse date.'},
context_instance=RequestContext(request))
items = Item.objects.filter(donor=donor, acquire_date=acquire_date)
subcategories = items.values('subcategory').annotate(Count('id'))
subcategories = subcategories.order_by('subcategory')
total = sum(subcategory['id__count'] for subcategory in subcategories)
# Group by code with quantity.
result = dict(groups=subcategories, donor=donor,
acquire_date=acquire_date, total=total, action='display')
return render_to_response('core/receipt.html', result,
context_instance=RequestContext(request))
def version(request):
import settings
return HttpResponse(settings.VERSION,
content_type='text/plain; charset=utf8')
def shutdown(request):
def call_exit():
import os
import time
time.sleep(1)
os._exit(0)
from threading import Thread
thread = Thread(target=call_exit)
thread.start()
return HttpResponse('Terminating server process ...',
content_type='text/plain; charset=utf8')
|
from action import Action
import kodi_baselibrary as kodi
class LoadSharedLanguageAction(Action):
def __init__(self):
super().__init__(
name = "Load Kodi (shared) language file",
function = self.loadsharedlanguagefile,
description = "Load the Kodi standard (shared) language file",
arguments = ['sharedlanguagefile'])
self.language = None
def loadsharedlanguagefile(self, messagecallback, arguments):
messagecallback("action", "\nLoading Kodi standard language file...")
sharedlanguagefile = arguments['sharedlanguagefile']
messagecallback("info", "- Kodi standard (shared) language file: " + sharedlanguagefile)
if sharedlanguagefile:
try:
self.language = kodi.readlanguagefile(sharedlanguagefile)
except OSError as error:
messagecallback("error", "- Failed to load the shared language file:" + str(error))
else:
messagecallback("warning", "- The shared language file is not specified")
|
from app import app
from flask import render_template, request
from ..controllers import users
import helper
@app.route('/login', methods = ('GET', 'POST'))
def login():
if request.method == 'GET': return users.log_out()
elif request.method == 'POST': return users.log_in()
@app.route('/create', methods = ('GET', 'POST'))
def create():
if request.method == 'GET': return render_template('create.html', dar = helper.dar())
elif request.method == 'POST': return users.create_user()
@app.route('/profile/<user>', methods = ('GET', 'POST'))
def prifile(user):
if request.method == 'GET': return users.get_profile(user)
return users.save_bio()
@app.route('/profile')
def get_select_data():
return users.get_select_data()
|
# try tries to run a code and if an error (of a certain type) occured the program runs except
print("How funny are we?")
m = "default"
n = 0
m = str(input("Input name: "))
try:
n = int(input("Input number: "))
except(ValueError):
print("not a number ValueError")
pwrmsg = ""
try:
pwrmsg = "{0}s power level is {1}". format(m,n)
except(NameError):
print("variable cannot be assigned bc didn't input a number NameError") # this isn't printed because n is assigned to a default
try:
print(pwrmsg)
if n > int(9000):
print("IT'S OVER 9000!!!")
except(NameError):
print("function cannot run bc didn't input a number NameError") # this isn't printed because n is assigned to a default
print("the truth")
names = "manu", "raffi", "johnny", "karin"
levels = 9001, 9000, 9000, 9000
lvl = {names[0]: levels[0], names[1]:levels[1], names[2]: levels[2], names[3]: levels[3]}
print("power level of {0} is {1}". format(names[0],lvl["manu"]))
try:
print("{0} and {1} and {2} are on the same lvl". format(names[1], names[2], names[3]))
except:
print("error")
try:
print(names[4])
except(IndexError):
print("ryan is on another lvl IndexError")
try:
print(lvl["ryan"])
except(KeyError):
print("ryan is on another lvl KeyError")
try:
print("hello" + 123 + "world")
except(TypeError):
print("can't do that TypeError")
### assertion
one = 1
two = 2
three = "3"
def goodmath(x,y):
try:
assert type(x) is int, "x not int"
assert type(y) is int, "y not int"
result = x + y
return print(result)
except:
print("AssertionError")
goodmath(one,two)
goodmath(one,three)
|
def scratch(lottery):
return sum(int(x[-x[::-1].index(' '):]) for x in lottery if len(set(x.split()))==2)
'''
Task
You got a scratch lottery, you want to know how much money you win.
There are 6 sets of characters on the lottery. Each set of characters represents a chance to win.
The text has a coating on it. When you buy the lottery ticket and then blow it off, you can see
the text information below the coating.
Each set of characters contains three animal names and a number, like this: "tiger tiger tiger 100".
If the three animal names are the same, Congratulations, you won the prize. You will win the same
bonus as the last number.
Given the lottery, returns the total amount of the bonus.
Input/Output
[input] string array lottery
A string array that contains six sets of characters.
[output] an integer
the total amount of the bonus.
Example
For
lottery = [
"tiger tiger tiger 100",
"rabbit dragon snake 100",
"rat ox pig 1000",
"dog cock sheep 10",
"horse monkey rat 5",
"dog dog dog 1000"
]```
the output should be `1100`.
`"tiger tiger tiger 100"` win $100, and `"dog dog dog 1000"` win $1000.
`100 + 1000 = 1100`
''' |
import cv2
import numpy as np
import imutils
def crop_and_rotate(im):
ROTATE_ANGLE = -9
rotated = imutils.rotate(im, angle=ROTATE_ANGLE) # rotate
return rotated[810:950, 680:2000] # clip
def read_road_image(path):
im = cv2.imread(path)
if im is None:
return None
flipped = cv2.flip(im, -1)
cropped = crop_and_rotate(flipped)
return cropped
def nothing(x):
pass
# Creating a window for later use
cv2.namedWindow('result')
# Starting with 100's to prevent error while masking
h,s,v = 100,100,100
hsv = ['h', 's', 'v']
lows = [l + "_low" for l in hsv]
his = [l + "_hi" for l in hsv]
def read_values(labels):
return np.array([cv2.getTrackbarPos(l,'result') for l in labels])
def update_filter(t=None):
frame = read_road_image('test-images/2018-12-27T17:08:00.704668.jpg')
#converting to HSV
hsv = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)
# get info from track bar and appy to result
lower = read_values(lows)
upper = read_values(his)
# masking algorithm
road_mask = cv2.inRange(hsv,lower, upper)
# not_road_mask = cv2.bitwise_not(road_mask)
result = cv2.bitwise_and(frame, frame, mask = road_mask)
cv2.imshow('result', result)
print(lower)
print(upper)
# Creating track bar
for v in lows:
cv2.createTrackbar(v, 'result', 0, 255, update_filter)
for v in his:
cv2.createTrackbar(v, 'result', 255, 255, update_filter)
update_filter()
cv2.waitKey() |
#!/usr/bin/env python3
import io
import csv
import openpyxl
import utils
def download():
utils.download_file('https://doi.org/10.1371/journal.pone.0058321.s001',
'../data/pmid_23520498/journal.pone.0058321.s001.XLSX')
def convert_to_csv():
workbook = openpyxl.load_workbook('../data/pmid_23520498/journal.pone.0058321.s001.xlsx')
sheet = workbook.get_active_sheet()
with io.open('../data/pmid_23520498/journal.pone.0058321.s001.csv', 'w', newline='', encoding='utf-8') as f:
c = csv.writer(f)
row_iter = iter(sheet.rows)
# Skip first three rows
next(row_iter)
next(row_iter)
next(row_iter)
for r in row_iter:
c.writerow([cell.value for cell in r][0:6])
def map_to_drugbank():
matched_pairs = []
matched_triples = []
existing_pairs = set()
unmapped_names = set()
total = 0
duplicated = 0
with io.open('../data/pmid_23520498/journal.pone.0058321.s001.csv', 'r', encoding='utf-8') as f:
reader = csv.reader(f, delimiter=',', quotechar='"')
next(reader, None)
# 0 - Number
# 1 - DrugA
# 2 - DrugC: similar to DrugA
# 3 - DrugB
# 4 - TC
# 5 - Effect drugC-drugB (the effect drugA-drugB is similar to drugC-drugB according to the model.
# To interpret the interaction drugC should be substituted by drugA)
for row in reader:
row = [x.strip() for x in row]
total += 1
id1 = utils.name_to_drugbank_id(row[1])
id2 = utils.name_to_drugbank_id(row[2])
id3 = utils.name_to_drugbank_id(row[3])
if id1 is None and len(row[1]) > 0:
unmapped_names.add(row[1])
if id2 is None and len(row[2]) > 0:
unmapped_names.add(row[2])
if id3 is None and len(row[3]) > 0:
unmapped_names.add(row[3])
if id1 is not None and id3 is not None:
# 0 - Number
# 1 - DrugbankA
# 2 - DrugbankC
# 3 - DrugbankB
# 4 - DrugA
# 5 - DrugC: similar to DrugA
# 6 - DrugB
# 7 - TC
# 8 - Effect drugC-drugB
output = [row[0], id1, id2, id3, row[1], row[2], row[3], row[4], row[5]]
id_key = utils.get_id_pair_id(id1, id3)
if id_key in existing_pairs:
duplicated += 1
continue
existing_pairs.add(id_key)
matched_pairs.append(output)
if id2 is not None:
matched_triples.append(output)
header = ['Number', 'DrugbankA', 'DrugbankC', 'DrugbankB', 'DrugA', 'DrugC: similar to DrugA', 'DrugB', 'TC',
'Effect drugC-drugB']
with io.open('../data/pmid_23520498/journal.pone.0058321.s001_pairs.csv', 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f, delimiter=',', quotechar='"')
writer.writerow(header)
for row in matched_pairs:
writer.writerow(row)
with io.open('../data/pmid_23520498/journal.pone.0058321.s001_triplets.csv', 'w', newline='',
encoding='utf-8') as f:
writer = csv.writer(f, delimiter=',', quotechar='"')
writer.writerow(header)
for row in matched_triples:
writer.writerow(row)
with io.open('../data/pmid_23520498/unmapped_names.csv', 'w', newline='', encoding='utf-8') as f:
writer = csv.writer(f, delimiter=',', quotechar='"')
for row in unmapped_names:
writer.writerow([row])
# Matched, Duplicated, Unmatched
return [len(matched_pairs), duplicated, total - duplicated - len(matched_pairs)]
def process() -> [int]:
convert_to_csv()
return map_to_drugbank()
def get_all_interaction_pairs() -> []:
result = []
with io.open('../data/pmid_23520498/journal.pone.0058321.s001_pairs.csv', 'r', encoding='utf-8') as f:
reader = csv.reader(f, delimiter=',', quotechar='"')
next(reader, None)
for row in reader:
result.append([row[1], row[4], row[3], row[6], float(row[7])])
return result
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.