text stringlengths 38 1.54M |
|---|
from flask import Blueprint
from flask_restplus import Api
from .authToken import api as ns1
from .getPackageList import api as ns2
from .activePackageCall import api as ns3
#blueprint_api = Blueprint('api', __name__, url_prefix="/api")
api = Api(
title='Digital Agency APP',
version='1.0',
description='Digital Agency is gonna sell/active Bongo Packages for a user !'
# ALl API Metadata
)
api.add_namespace(ns1, path='/api/v1/auth/token')
api.add_namespace(ns2, path='/api/v1/getPackageList')
api.add_namespace(ns3, path='/api/v1/activePackage')
|
# This file is part of Mylar.
#
# Mylar 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.
#
# Mylar 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 Mylar. If not, see <http://www.gnu.org/licenses/>.
import re
import os
import requests
from bencode import bencode, bdecode
from hashlib import sha1
from cStringIO import StringIO
import mylar
from mylar import logger
class utorrentclient(object):
def __init__(self):
host = mylar.UTORRENT_HOST #has to be in the format of URL:PORT
if not host.startswith('http'):
host = 'http://' + host
if host.endswith('/'):
host = host[:-1]
if host.endswith('/gui'):
host = host[:-4]
self.base_url = host
self.username = mylar.UTORRENT_USERNAME
self.password = mylar.UTORRENT_PASSWORD
self.utorrent_url = '%s/gui/' % (self.base_url)
self.auth = requests.auth.HTTPBasicAuth(self.username, self.password)
self.token, self.cookies = self._get_token()
def _get_token(self):
TOKEN_REGEX = r'<div[^>]*id=[\"\']token[\"\'][^>]*>([^<]*)</div>'
utorrent_url_token = '%stoken.html' % self.utorrent_url
try:
r = requests.get(utorrent_url_token, auth=self.auth)
except requests.exceptions.RequestException as err:
logger.debug('URL: ' + str(utorrent_url_token))
logger.debug('Error getting Token. uTorrent responded with error: ' + str(err))
return 'fail'
token = re.search(TOKEN_REGEX, r.text).group(1)
guid = r.cookies['GUID']
cookies = dict(GUID = guid)
return token, cookies
def addfile(self, filepath=None, filename=None, bytes=None):
params = {'action': 'add-file', 'token': self.token}
try:
d = open(filepath, 'rb')
tordata = d.read()
d.close()
except:
logger.warn('Unable to load torrent file. Aborting at this time.')
return 'fail'
files = {'torrent_file': tordata}
try:
r = requests.post(url=self.utorrent_url, auth=self.auth, cookies=self.cookies, params=params, files=files)
except requests.exceptions.RequestException as err:
logger.debug('URL: ' + str(self.utorrent_url))
logger.debug('Error sending to uTorrent Client. uTorrent responded with error: ' + str(err))
return 'fail'
# (to-do) verify the hash in order to ensure it's loaded here
if str(r.status_code) == '200':
logger.info('Successfully added torrent to uTorrent client.')
if mylar.UTORRENT_LABEL:
try:
hash = self.calculate_torrent_hash(data=tordata)
self.setlabel(hash)
except:
logger.warn('Unable to set label for torrent.')
return 'pass'
else:
return 'fail'
def setlabel(self, hash):
params = {'token': self.token, 'action': 'setprops', 'hash': hash, 's': 'label', 'v': str(mylar.UTORRENT_LABEL)}
r = requests.post(url=self.utorrent_url, auth=self.auth, cookies=self.cookies, params=params)
if str(r.status_code) == '200':
logger.info('label ' + str(mylar.UTORRENT_LABEL) + ' successfully applied')
else:
logger.info('Unable to label torrent')
return
def calculate_torrent_hash(link=None, filepath=None, data=None):
thehash = None
if not link:
if filepath:
torrent_file = open(filepath, "rb")
metainfo = bdecode(torrent_file.read())
else:
metainfo = bdecode(data)
info = metainfo['info']
thehash = hashlib.sha1(bencode(info)).hexdigest().upper()
logger.info('Hash: ' + thehash)
else:
if link.startswith("magnet:"):
torrent_hash = re.findall("urn:btih:([\w]{32,40})", link)[0]
if len(torrent_hash) == 32:
torrent_hash = b16encode(b32decode(torrent_hash)).lower()
thehash = torrent_hash.upper()
if thehash is None:
logger.warn('Cannot calculate torrent hash without magnet link or data')
return thehash
# not implemented yet #
# def load_torrent(self, filepath):
# start = bool(mylar.UTORRENT_STARTONLOAD)
# logger.info('filepath to torrent file set to : ' + filepath)
#
# torrent = self.addfile(filepath, verify_load=True)
#torrent should return the hash if it's valid and loaded (verify_load checks)
# if not torrent:
# return False
# if mylar.UTORRENT_LABEL:
# self.setlabel(torrent)
# logger.info('Setting label for torrent to : ' + mylar.UTORRENT_LABEL)
# logger.info('Successfully loaded torrent.')
# #note that if set_directory is enabled, the torrent has to be started AFTER it's loaded or else it will give chunk errors and not seed
# if start:
# logger.info('[' + str(start) + '] Now starting torrent.')
# torrent.start()
# else:
# logger.info('[' + str(start) + '] Not starting torrent due to configuration setting.')
# return True
|
'''
match a control xform to a joint
first select a joint, then the control
'''
import pymel.all as pm
def match_ctrl(jnt, ctrl):
control_name = ctrl.name(long = None)
control_shape = ctrl.getShape()
transform = pm.group(parent = jnt, empty = True)
transform.zeroTransformPivots()
pm.parent(transform, world = True)
pm.parent(control_shape, transform, absolute = True, shape = True)
new_trans = pm.listRelatives(control_shape, parent = True)
pm.makeIdentity(new_trans, s = True, r = True, t = True, apply = True)
pm.parent(control_shape, transform, relative = True, shape = True)
pm.delete(new_trans, ctrl)
transform.rename(control_name)
pm.delete(transform, constructionHistory = True)
sel = pm.ls(os=True)
match_ctrl(sel[0], sel[1]) |
from .widgets import CropForeignKeyWidget
class ImageCroppingAdmin(object):
def formfield_for_dbfield(self, db_field, **kwargs):
formfield = super(ImageCroppingAdmin, self).formfield_for_dbfield(db_field, **kwargs)
if hasattr(db_field, 'related') and db_field.name in self.model.crop_fk_fields.keys():
formfield.widget = CropForeignKeyWidget(db_field.rel,
field_name=self.model.crop_fk_fields[db_field.name],
admin_site=self.admin_site)
return formfield
|
import os
import petl
from django.shortcuts import redirect
from django.views.generic import DetailView, ListView
from swapi.downloader import download_new_snapshot
from swapi.models import PeopleDownload
class PeopleDownloadListView(ListView):
queryset = PeopleDownload.objects.all().order_by("-created_timestamp")
template_name = "swapi/download_list.html"
def post(self, request):
download_new_snapshot()
return redirect("people-download-list", permanent=False)
class PeopleDownloadDetailView(DetailView):
count_increment = 10
count_query_kwarg = "show"
object: PeopleDownload
model = PeopleDownload
template_name = "swapi/people.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["filename"] = self.object.downloaded_file.name.split(os.path.sep)[-1]
context["count_query_kwarg"] = self.count_query_kwarg
table = petl.fromcsv(self.object.downloaded_file)
context["header"] = petl.header(table)
try:
record_count_to_show = int(self.request.GET.get(self.count_query_kwarg))
except (TypeError, ValueError):
record_count_to_show = self.count_increment
# Potentially expensive, cache / save in database for dataset
if petl.nrows(table) > record_count_to_show:
context[
"load_more_url"
] = f"{self.request.path}?{self.count_query_kwarg}={record_count_to_show+self.count_increment}"
context["rows"] = petl.records(petl.head(table, record_count_to_show))
return context
class PeopleDownloadAggregateView(DetailView):
columns_query_kwarg = "columns"
object: PeopleDownload
model = PeopleDownload
template_name = "swapi/aggregate.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["filename"] = self.object.downloaded_file.name.split(os.path.sep)[-1]
context["columns_query_kwarg"] = self.columns_query_kwarg
table = petl.fromcsv(self.object.downloaded_file)
full_table_header = list(petl.header(table))
context["column_options"] = full_table_header
selected_columns = [c for c in self.request.GET.getlist(self.columns_query_kwarg) if c in full_table_header]
context["selected_columns"] = selected_columns
if selected_columns:
context["header"] = selected_columns + ["Count"]
context["rows"] = petl.records(
petl.aggregate(table, selected_columns[0] if len(selected_columns) == 1 else selected_columns, len)
)
return context
|
"""
A model of the solar system.
Created by Zella Henderson
December 2011
"""
from OpenGL.GLUT import *
from OpenGL.GLU import *
from OpenGL.GL import *
import sys
import time
import imageLoader
"""
Notes:
This program requires 10 gifs and imageLoader.py.
This is a mostly-to-scale replica of our solar system.
The planets' relative sizes, distances from the sun, and
orbit speeds and direction are roughly accurate.
The sun has been shrunk so that the small inner planets are visible.
To aid in visibility, final_inner displays only the inner 4 planets,
whereas final_system displays all the planets (zoomed farther out).
This displays texture mapping to a sphere and a luminescent object
(light source inside the sun). Shadows proved too complex to be worthile.
Known problems:
The texture mapped to the moons' surfaces doesn't display properly
due to the moons' small sizes- the same texture map works fine on the
larger planets.
Texture mapping to the large planets worked poorly- the loaded image
seems to be set up as a 1x1 image regardless of its original size,
and
I haven't rendered Jupiter's rings.
The moons all rotate at the same rate, which isn't strictly accurate.
Sources:
http://www.opengl.org/sdk/docs/man/xhtml/glColorMaterial.xml
http://www.cse.msu.edu/~cse872/tutorial4.html
http://www.blitzmax.com/Community/posts.php?topic=43543
http://www.opengl.org/discussion_boards/ubbthreads.php?ubb=showflat&Number=234880
http://en.wikipedia.org/wiki/Solar_System and related
"""
# A global variable storing our window ID
# (not very pythonic by standard practice for OpenGL)
window = 0
ESCAPE = '\033' # The esc character
def keyPressed(*args):
if args[0] == ESCAPE: # If escape is pressed, kill everything.
glutDestroyWindow(window)
sys.exit()
def SolarSystem():
global angle
angle += .05
#sets up radiant light from the sun at the origin
#without emission, the light source will be dark because it'll be inside the sun
glColorMaterial(GL_FRONT_AND_BACK, GL_EMISSION)
#sets up texture mapping
glEnable(GL_TEXTURE_2D)
glEnable(GL_TEXTURE_GEN_S)
glEnable(GL_TEXTURE_GEN_T)
#glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE)
glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR)
glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR)
glBindTexture(GL_TEXTURE_2D, textures[0])
#the sun
Planet(12, 1, .9, .4, PlanetType.SUN)
#glColorMaterial(GL_FRONT_AND_BACK, GL_DIFFUSE)
#Mercury
glPushMatrix()
glRotate(15*angle, 0, 1, 0)
#move so orbit has r=4
glTranslate(12+4,0,0)
glBindTexture(GL_TEXTURE_2D, textures[1])
#radius 0.6, color (.52, .52, .52)
Planet(.6, .52, .52, .52, PlanetType.MERCURY)
glPopMatrix()
#Venus
glPushMatrix()
glRotate(2.5*angle, 0, 1, 0)
#move so orbit has r=7
glTranslate(12+7,0,0)
glBindTexture(GL_TEXTURE_2D, textures[2])
#planet has radius 1, color (.7, .7, 0)
Planet(1, .72, .45, .12, PlanetType.VENUS)
glPopMatrix()
#Earth
glPushMatrix()
glRotate(angle, 0, 1, 0)
#move so orbit has r=10
glTranslate(12+10,0,0)
glBindTexture(GL_TEXTURE_2D, textures[3])
Planet(1.2, .37, .4, 0.6, PlanetType.EARTH)
glPopMatrix()
#Mars
glPushMatrix()
glRotate(1.03*angle, 0, 1, 0)
#move so orbit has r=15
glTranslate(12+15,0,0)
glBindTexture(GL_TEXTURE_2D, textures[4])
Planet(.8, .8, .55, .32, PlanetType.MARS)
glPopMatrix()
#Jupiter
glPushMatrix()
glRotate(0.4*angle, 0, 1, 0)
#move so orbit has r=52
glTranslate(12+52,0,0)
glBindTexture(GL_TEXTURE_2D, textures[5])
Planet(10, .52, .42, .35, PlanetType.JUPITER)
glPopMatrix()
#Saturn
glPushMatrix()
glRotate(0.45*angle, 0, 1, 0)
#move so orbit has r=95
glTranslate(12+95,0,0)
glBindTexture(GL_TEXTURE_2D, textures[6])
Planet(9, .92, .77, .51, PlanetType.SATURN)
glPopMatrix()
#Uranus
glPushMatrix()
glRotate(-0.71*angle, 0, 1, 0)
#move so orbit has r=196
glTranslate(12+196,0,0)
glBindTexture(GL_TEXTURE_2D, textures[7])
Planet(5, .73, .88, .88, PlanetType.URANUS)
glPopMatrix()
#Neptune
glPushMatrix()
glRotate(0.71*angle, 0, 1, 0)
#move so orbit has r=300
glTranslate(12+300,0,0)
glBindTexture(GL_TEXTURE_2D, textures[8])
Planet(4, .45, .65, 1, PlanetType.NEPTUNE)
glPopMatrix()
class PlanetType(object):
SUN = 0
MERCURY = 1
VENUS = 2
EARTH = 3
MARS = 4
JUPITER = 5
SATURN = 6
URANUS = 7
NEPTUNE = 8
def Planet(r, c1, c2, c3, planet_type):
glColor3f(c1, c2, c3)
glutSolidSphere(r, 20, 20)
if planet_type == 3:
#Earth has one moon
Moon(0,0,1)
if planet_type == 4:
#Mars has two moons, Phobos and Deimos
glPushMatrix()
#moon that starts above the planet
Moon(0,0,1)
glPopMatrix()
#moon with a satellite that starts right of the planet
Moon(1,0,0)
if planet_type >= 5:
#Jupiter has 64 moons, Saturn 62, Uranus unknown Neptune 12.
#I'm rendering 6 in all cases.
glPushMatrix()
Moon(0,0,4)
glPopMatrix()
glPushMatrix()
Moon(4,0,0)
glPopMatrix()
glPushMatrix()
Moon(0,0,4)
glPopMatrix()
glPushMatrix()
Moon(0,4,4)
glPopMatrix()
glPushMatrix()
Moon(4,0,4)
glPopMatrix()
glPushMatrix()
Moon(4,4,0)
glPopMatrix()
def Moon(x, y, z):
glRotate(angle*8, x,y,z)
#Translate (in a different direction than the axis of rotation)
## to move out of the planet's center
glTranslate(y*2, z*2, x*2)
glBindTexture(GL_TEXTURE_2D, textures[4])
glColor3f(.5, .5, .5)
glutSolidSphere(.2, 10, 10)
def mydisplay() :
global angle
global framecount
global start
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
glLoadIdentity()
SolarSystem()
glutSwapBuffers()
def drawSolarSystem():
global window
global angle
global framecount
global start
start = time.time()
framecount = 0
angle = 0
glutInit(sys.argv)
glutInitDisplayMode(GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH)
glutInitWindowSize(800,800)
window = glutCreateWindow("Inner planets")
glutKeyboardFunc(keyPressed)
glClearColor(0,0,0,1)
glShadeModel(GL_SMOOTH)
glutDisplayFunc(mydisplay)
glEnable(GL_DEPTH_TEST)
glDepthFunc(GL_LEQUAL)
glutIdleFunc(mydisplay)
#Lighting
glEnable(GL_LIGHTING)
glEnable(GL_LIGHT0)
glEnable(GL_COLOR_MATERIAL)
glLightfv(GL_LIGHT0, GL_DIFFUSE, (.3,.3,.3, 1))
glLightfv(GL_LIGHT0, GL_POSITION, (0,0,0,1))
#glLightfv(GL_LIGHT0, GL_SPOT_DIRECTION, (-2,-2,-4))
#Texture
global textures
textures= glGenTextures(10); # number of textures to generate
glBindTexture(GL_TEXTURE_2D, textures[0])
glPixelStorei(GL_UNPACK_ALIGNMENT,1)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
img0 = imageLoader.loadImage("sun.gif")
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img0.width, img0.height, 0,
GL_RGB, GL_UNSIGNED_BYTE, img0.data)
glBindTexture(GL_TEXTURE_2D, textures[1])
glPixelStorei(GL_UNPACK_ALIGNMENT,1)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
img1 = imageLoader.loadImage("mercury.gif")
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img1.width, img1.height, 0,
GL_RGB, GL_UNSIGNED_BYTE, img1.data)
glBindTexture(GL_TEXTURE_2D, textures[2])
glPixelStorei(GL_UNPACK_ALIGNMENT,1)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
img2 = imageLoader.loadImage("venus.gif")
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img2.width, img2.height, 0,
GL_RGB, GL_UNSIGNED_BYTE, img2.data)
glBindTexture(GL_TEXTURE_2D, textures[3])
glPixelStorei(GL_UNPACK_ALIGNMENT,1)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
img3 = imageLoader.loadImage("earth.gif")
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img3.width, img3.height, 0,
GL_RGB, GL_UNSIGNED_BYTE, img3.data)
glBindTexture(GL_TEXTURE_2D, textures[4])
glPixelStorei(GL_UNPACK_ALIGNMENT,1)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
img4 = imageLoader.loadImage("mars.gif")
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img4.width, img4.height, 0,
GL_RGB, GL_UNSIGNED_BYTE, img4.data)
glBindTexture(GL_TEXTURE_2D, textures[5])
glPixelStorei(GL_UNPACK_ALIGNMENT,1)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
img5 = imageLoader.loadImage("jupiter.gif")
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img5.width, img5.height, 0,
GL_RGB, GL_UNSIGNED_BYTE, img5.data)
glBindTexture(GL_TEXTURE_2D, textures[6])
glPixelStorei(GL_UNPACK_ALIGNMENT,1)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
img6 = imageLoader.loadImage("saturn.gif")
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img6.width, img6.height, 0,
GL_RGB, GL_UNSIGNED_BYTE, img6.data)
glBindTexture(GL_TEXTURE_2D, textures[7])
glPixelStorei(GL_UNPACK_ALIGNMENT,1)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
img7 = imageLoader.loadImage("uranus.gif")
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img7.width, img7.height, 0,
GL_RGB, GL_UNSIGNED_BYTE, img7.data)
glBindTexture(GL_TEXTURE_2D, textures[8])
glPixelStorei(GL_UNPACK_ALIGNMENT,1)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
img8 = imageLoader.loadImage("neptune.gif")
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img8.width, img8.height, 0,
GL_RGB, GL_UNSIGNED_BYTE, img8.data)
glBindTexture(GL_TEXTURE_2D, textures[9])
glPixelStorei(GL_UNPACK_ALIGNMENT,1)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR)
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR)
img9 = imageLoader.loadImage("moon.gif")
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img9.width, img9.height, 0,
GL_RGB, GL_UNSIGNED_BYTE, img9.data)
glMatrixMode(GL_PROJECTION)
glLoadIdentity()
gluPerspective(45, 1, 0.1, 400)
gluLookAt(0, 40, 80, 0, 0, 0, 0, 1, 0)
glMatrixMode(GL_MODELVIEW)
glLoadIdentity()
glutMainLoop()
drawSolarSystem()
|
from subprocess import check_call
from time import strftime
def make_report_dirs():
global history, acct, google
timestamp = strftime("\%m%d%Y")
rep_dir = "Reports" + timestamp
history = rep_dir + '\History'
acct = rep_dir + '\Account'
google = rep_dir + '\Google'
try:
check_call('mkdir ' + google, shell=True)
except:
pass
try:
check_call('mkdir ' + acct, shell=True)
except:
pass
try:
check_call('mkdir ' + history, shell=True)
except:
return
def write_chrome_history(chrome):
with open(google + '\chrome_history.txt', 'w') as f:
if chrome == 1:
f.write('No Chrome browser history found.')
else:
for i in range(0,int(chrome['count'])):
f.write('Page Title: ' + chrome['title'][i] + '\n')
f.write('URL: ' + chrome['url'][i] + '\n')
f.write('Visited: ' + chrome['last'][i] + '\n')
f.write('\n')
f.close()
def write_chrome_downloads(chrome):
with open(google + '\chrome_downloads.txt', 'w') as f:
if chrome == 1:
f.write('No Chrome download history found.')
else:
for i in range(0,int(chrome['count'])):
f.write('URL: ' + chrome['url'][i] + '\n')
f.write('Download Path: ' + chrome['path'][i] + '\n')
f.write('Download Size: ' + chrome['size'][i] + '\n' )
f.write('Start Time: ' + chrome['start'][i] + '\n')
f.write('End Time: ' + chrome['end'][i] + '\n')
f.write('\n')
f.close()
def write_calls(calls):
with open(history + '\call_history.txt', 'w') as f:
if calls == 1:
f.write('No call history found.')
else:
for i in range(0,int(calls['count'])):
if '1' in calls['type'][i]:
f.write('Type: Incoming\n')
if '2' in calls['type'][i]:
f.write('Type: Missed\n')
if '3' in calls['type'][i]:
f.write('Type: Outgoing\n')
if len(calls['name'][i]) <= 2:
f.write('Name: N/A\n')
else:
f.write('Name: ' + calls['name'][i] + '\n')
f.write('Number: ' + calls['num'][i] + '\n')
f.write('Date/Time: ' + calls['time'][i] + '\n')
f.write('Duration: ' + calls['dur'][i] + 's\n')
f.write('Location: ' + calls['geo'][i] + ', ' + calls['ctry'][i] + '\n')
f.write('\n')
f.close()
def write_sms(sms):
with open(history + '\sms_history.txt', 'w') as f:
if sms == 1:
f.write('No SMS history found.')
else:
for i in range(0,int(sms['count'])):
if len(sms['name'][i]) <= 2:
f.write('Name: N/A\n')
else:
f.write('Name: ' + sms['name'][i] + '\n')
f.write('Number: ' + sms['num'][i] + '\n')
if len(sms['subj'][i]) <= 2:
pass
else:
f.write('Subject: ' + sms['subj'][i] + '\n')
f.write('Body: ' + sms['body'][i] + '\n')
f.write('Date/Time: ' + sms['time'][i] + '\n')
f.write('\n')
f.close()
def write_browser(brow):
with open(history + r'\browser_history.txt', 'w') as f:
if brow == 1:
f.write('No Android browser history found.')
else:
for i in range(0,int(brow['count'])):
f.write('Page Title: ' + brow['title'][i] + '\n')
f.write('URL: ' + brow['url'][i] + '\n')
f.write('Visited: ' + brow['last'][i] + '\n')
f.write('\n')
f.close()
def write_contacts(con):
with open(acct + '\contact_list.txt', 'w') as f:
if con == 1:
f.write('No contacts found.')
else:
for i in range(0,int(con['count'])):
f.write('Name: ' + con['name'][i])
f.write('Number: ' + con['num'][i])
f.write('\n\n')
f.close()
|
#Functions are blocks of code that begin with the def keyword
def fun_a(): #function declaration
print("I have been called")
fun_a() #calling the function
#passing arguments to functions
def fun_a(a,b):
print(a+b)
fun_a(1,4)
#functions that take in keyword arguments
def fun_a(a=6,b=7):
print(a+b)
fun_a()
#creating an empty function
def fun_a():
pass
#functions with return values
def fun_a(a,b):
return a + b
sum = fun_a(4,5)
print(sum)
|
import numpy as np
import cv2
from matplotlib import pyplot as plt
import torch
import torch.nn as nn
import csv
import os
# No ball bearing
# 221-308 inclusive
# 341 - 368 inclusive
WIDTH = 512
HEIGHT = 384
with open("Ball Bearing Position Data.csv", 'r') as csvfile:
csvreader = csv.reader(csvfile,delimiter=',')
lineCount = 0
ballBearingPositions = []
for row in csvreader:
if (lineCount < 221) or (308 < lineCount < 341) or (368 < lineCount < 600):
xint = float(row[1])
yint = float(row[2])
ballBearingPositions.append([xint,yint])
lineCount = lineCount + 1
ballArray = np.array(ballBearingPositions)
ballArray.reshape((len(ballBearingPositions),2))
Ytrain = ballArray
# This section of code can be used to check if the ball bearing pointer is in the correct location
"""count = 0
from IPython import display
for filepath in os.listdir('vid 1/'):
if count % 3 == 0:
image = cv2.imread('vid 1/{0}'.format(filepath),1)
imageResized = cv2.resize(image,(WIDTH,HEIGHT))
plt.imshow(imageResized)
plt.plot(ballBearingPositions[count][0],ballBearingPositions[count][1],'bo')
plt.show()
count = count + 1
"""
# Load in the train images automatically
imageSetTrain = []
counterTrain = 0
for filepath in os.listdir('vid 1/'):
if (counterTrain < 221) or (308 < counterTrain < 341) or (368 < counterTrain < 600):
image = cv2.imread('vid 1/{0}'.format(filepath),1)
imageResized = cv2.resize(image,(WIDTH,HEIGHT))
imageSetTrain.append(imageResized)
counterTrain = counterTrain + 1
imagesTrain = np.array(imageSetTrain)
Xtrain = imagesTrain
print(Xtrain.shape)
# load in the test images automatically
# no ball bearing 726-927
imageSetTest = []
counterTest = 0
for filepath in os.listdir('vid 1/'):
if (599 < counterTest < 726) or (927 < counterTest < 1286):
image = cv2.imread('vid 1/{0}'.format(filepath), 1)
imageResized = cv2.resize(image, (WIDTH, HEIGHT))
imageSetTest.append(imageResized)
counterTest = counterTest + 1
imagesTest = np.array(imageSetTest)
Xtest = imagesTest
print(Xtest.shape)
print(Ytrain.shape)
# Define a simple CNN
class Flatten(nn.Module):
def forward(self, input):
return input.view(input.size(0), -1)
# The Detector class will be our detection model
class Detector(nn.Module):
def __init__(self, output_dim, image_channels):
super().__init__()
self.encoder = nn.Sequential(
nn.Conv2d(image_channels, 3, 3, stride=2, padding=1),
nn.ReLU(),
nn.Conv2d(3, 3, 3, stride=2, padding=1),
nn.ReLU(),
nn.Conv2d(3, 3, 3, stride=2, padding=1),
nn.ReLU(),
Flatten(),
nn.Linear(9216, 128), # The first number here changes based on the size. Use the errors when it runs to pick the number
nn.ReLU(),
nn.Linear(128, output_dim),
nn.Tanh()
)
def forward(self, x):
positions = self.encoder(x)
return positions
network = Detector(output_dim=2, image_channels=3)
Nepochs = 100
Nbatch = 8
optimizer = torch.optim.Adam(network.parameters(), lr=1e-4)
losses = []
for j in range(Nepochs):
# Shuffle our training data after each epoch
idxs = np.arange(Xtrain.shape[0])
np.random.shuffle(idxs)
Xtrain = Xtrain[idxs, :, :, :]
Ytrain = Ytrain[idxs, :]
# Loop over training data in batches of images
batch_losses = []
for k in range(int(Xtrain.shape[0] / Nbatch)):
# Scale images and positions to be between 0 and 1 and convert to tensors for pytorch
Xbatch = torch.from_numpy(Xtrain[Nbatch * k:Nbatch * (k + 1), :, :, :]).float().transpose(1, 3) / 255
Ybatch = torch.from_numpy(Ytrain[Nbatch * k:Nbatch * (k + 1), :]).float()
# The following code normalises the size of the image to be between 0-1
size = np.array([[1 / HEIGHT, 1 / WIDTH]])
size = torch.from_numpy(size).float()
Ybatch = (Ybatch * size) - 0.5
# Predict positions using neural network
Ypred = network(Xbatch)
# Calulate the loss (error between predictions and true values)
loss = torch.sum((Ypred - Ybatch) ** 2)
# Zero existing gradients
optimizer.zero_grad()
# Adjust neural network weights and biases by taken a step in a direction that reduces the loss
loss.backward()
optimizer.step()
batch_losses.append(loss.item())
losses.append(np.mean(batch_losses))
plt.clf()
plt.plot(losses)
plt.ylabel('Loss (mean squared error)')
plt.xlabel('Epochs')
plt.grid()
plt.show()
# testing the model - code not yet tested
k = np.random.randint(Xtest.shape[0] / Nbatch)
test_ims = torch.from_numpy(Xtest[Nbatch * k:Nbatch * (k + 1), :, :, :]).float().transpose(1, 3) / 255
Ypred = network(test_ims).detach().numpy()
print(Ypred)
plt.figure(figsize=(15, 5))
for j in range(Nbatch):
plt.subplot(2, 4, j + 1)
plt.imshow(Xtest[Nbatch * k + j, :, :, :].squeeze(), extent=[0, WIDTH, HEIGHT, 0])
size = np.array([HEIGHT, WIDTH])
pos_pred = (Ypred + 0.5) * size # Scale predictions to pixel coordinates
print(pos_pred)
# Show predicted marker positions in image
plt.plot([pos_pred[j, 0]], [pos_pred[j, 1]], 'bo', markersize=5)
plt.show() |
# -*- coding:utf-8 -*-
from BeautifulReport import BeautifulReport
from base.mail import sendEmai
import unittest
import xlrd
import os
class boyunshikongTestRunner(object):
# 遍历找出以Test.py 结尾的文件,导入
@staticmethod
def find_pyfile_and_import(rootDir):
list_dirs = os.walk(rootDir)
for dirName, subdirlist, filelist in list_dirs:
for f in filelist:
file_name = f
if file_name[-7:] == "Test.py":
if dirName[-1:] != "/":
impath = dirName.replace("/", ".")[2:].replace("\\", ".")
else:
impath = dirName.replace("/", ".")[2:-1].replace("\\", ".")
if impath != "":
exe_str = "from " + impath + "." + file_name[0:-3] + " import " + file_name[0:-7] + "UnitTest"
else:
exe_str = "import" + file_name[0:-3]
print(exe_str)
exec(exe_str, globals())
# 读取文件,组装测试用例
@staticmethod
def get_xls_case_by_index(sheet_name_list):
xls_path = "./excelFile/case_management.xls"
file = xlrd.open_workbook(xls_path)
caseList = []
for sheet_name in sheet_name_list:
sheet = file.sheet_by_name(sheet_name)
nrows = sheet.nrows
for i in range(nrows):
if sheet.row_values(i)[0].strip().upper() == 'YES' and sheet.row_values(i)[5] <= 2:
ClassName = sheet.cell_value(i, 2)
caseName = sheet.cell_value(i, 3)
# 组装测试用例格式 类名.("方法名")
case = '%s("%s")' % (ClassName.strip(), caseName.strip())
caseList.append(case)
return caseList
# 将测试用例添加到测试套件中
def get_test_suite(self, testDir, sheet_name_list):
"""
:param testDir: 为所有脚本的顶层目录
:param sheet_name_list: 想要读取的表名
"""
test_suite = unittest.TestSuite()
self.find_pyfile_and_import(testDir)
testCaseList = self.get_xls_case_by_index(sheet_name_list)
for test_case in testCaseList:
test_suite.addTest(eval(test_case))
return test_suite
if __name__ == "__main__":
# "登录", "用户管理", "车辆管理", "批量导入", "车辆授权", "实时报警", "综合报表", "指令",
# "车辆显示"
Run = boyunshikongTestRunner()
sheet_list = ["综合报表"]
suite = Run.get_test_suite("./test_case", sheet_list)
result = BeautifulReport(suite)
result.report(filename='test_result', description='博云视控自动化测试报告', log_path='./report')
sendEmai(['1531996630@qq.com', '3003521126@qq.com', '852240095@qq.com'])
# os.system("shutdown -s -t 60")
|
def rot13_letter(inLetter):
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
inLetter = inLetter.upper()
if inLetter in alphabet:
letterIndex = alphabet.find(inLetter)
letterIndex = (letterIndex + 13)%26
return alphabet[letterIndex]
else:
return inLetter
def rot13(inString):
# basic accumulation string pattern.
outString = ""
for oldLetter in inString:
# convert each letter one at a time.
newLetter = rot13_letter(oldLetter)
# add the new letter to the output string and store result
outString = outString + newLetter
return outString
print("apples to apples")
print(rot13("apples to apples"))
print(rot13(rot13("apples to apples")))
|
n, m = [int(x) for x in input().split()]
i = 0
while n != 0:
n -= 1
i += 1
if i % m == 0:
n += 1
print(i) |
from tools import *
from variables import m_Bu, nbin_Bu
from cuts import cuts_Bu, prntCuts, mctrue
from histograms import h1, h2
from model import model_Bu_mc as model_Bu
from data import mc_Pythia6, mc_Pythia8, mc_total
cuts_Bu += mctrue
tBu = mc_total.data
logger.info('DATA chain name is %s ' % (tBu.GetName()))
for i in prntCuts(cuts_Bu, " CUTS B+ "):
logger.info(i)
# logger.info('Fill control B+ histogram (takes some time)')
# with timing():
# tBu.Project(h1.GetName(), 'DTFm_b', cuts_Bu)
# model_Bu.b.fix(0)
# with rooSilent():
# logger.info('Fit Bc+ & B+ histogram (check the model)')
# r, f = model_Bu.fitHisto(h1)
from PyPAW.Selectors import SelectorWithVars
from variables import selector_variables
sel_Bu = SelectorWithVars(
variables=selector_variables,
selection=cuts_Bu
)
logger.info(
'Build RooFit dataset for B+ , it could take as long as 3-5 minutes')
tBu.process(sel_Bu)
ds_Bu = sel_Bu.dataset()
ds_Bu.Print('v')
logger.info('Make unbinned fit for B+')
#
model_Bu.s.setMax(1.2 * len(ds_Bu))
ru, fu = model_Bu.fitTo(ds_Bu, draw=True, nbins=nbin_Bu)
model_Bu.signal.sigma.release()
model_Bu.signal.mean.release()
ru, fu = model_Bu.fitTo(ds_Bu, draw=True, nbins=nbin_Bu)
model_Bu.signal.aR.release()
model_Bu.signal.aL.release()
ru, fu = model_Bu.fitTo(ds_Bu, draw=True, nbins=nbin_Bu)
model_Bu.signal.nR.release()
model_Bu.signal.nL.release()
ru, fu = model_Bu.fitTo(ds_Bu, draw=True, nbins=nbin_Bu)
# logger.info('running sPlot')
# model_Bu.sPlot(ds_Bu)
# ===============================================
# Drawing
# ===============================================
# h_1 = ROOT.TH1F("h_1", '', 30, 5.16, 5.45)
# h_1.Sumw2()
# h_2 = ROOT.TH1F("h_2", '', 30, 5.16, 5.45)
# h_2.Sumw2()
# h_1.SetXTitle('#Inv.\,mass(J/\psi\,K^+\,K^-\,K^+) \,\, with \,\, misid, GeV/c^2')
# h_2.SetXTitle('#Inv.\,mass(J/\psi\,K^+\,K^-\,K^+) \,\, with \,\, misid, GeV/c^2')
# ds_Bu.project(h_1, "mass_k1aspi", "SBu_sw && ann_kaon_PI_2 > 0.1")# && ann_kaon0 > 0.3")
# ds_Bu.project(h_2, "mass_k3aspi", "SBu_sw && ann_kaon_PI_0 > 0.1")# && ann_kaon2 > 0.3")
# h_1.red()
# h_2.blue()
# for j in xrange(0, h_1.GetNbinsX()):
# if h_1.GetBinContent(j) < 0:
# h_1.SetBinContent(j, 0)
# for j in xrange(0, h_2.GetNbinsX()):
# if h_2.GetBinContent(j) < 0:
# h_2.SetBinContent(j, 0)
# h_1.Scale(1.0/h_1.Integral())
# h_2.Scale(1.0/h_2.Integral())
# h_1.Draw("")
# h_2.Draw("same")
|
#! /usr/bin/env python
#coding=utf-8
import rpy2.robjects as robj
from rpy2.robjects.packages import importr
from rpy2.rinterface import RRuntimeError
import sys
import os
import time
import getopt
from zipfile import ZipFile, ZIP_DEFLATED
import cPickle
def drawRHist(Motif_Pos,outpath):
grdevices = importr('grDevices')
graphics = importr('graphics')
xlim=robj.IntVector([-3000,0])
for motif in Motif_Pos.keys():
print motif
if not Motif_Pos[motif]:
print "empty"
continue
dist=-robj.IntVector(Motif_Pos[motif]).ro
motif=motif.replace('/','_')
grdevices.png(file="%s/%s.png" % (outpath,motif), width=512, height=512)
graphics.hist(dist,breaks=50,main=motif,xlab="Distribution",xlim=xlim)
#robj.r('hist(0-%s, xlab="x", main="hist(x)")' %dist.r_repr())
grdevices.dev_off()
def drawRDensity(Motif_Pos,outpath):
grdevices = importr('grDevices')
graphics = importr('graphics')
xlim=robj.IntVector([-3000,0])
for motif in Motif_Pos.keys():
print motif
if not Motif_Pos[motif]:
print "empty"
continue
dist=-robj.IntVector(Motif_Pos[motif]).ro
try:
density=robj.r.density(dist)
except RRuntimeError:
continue
motif=motif.replace('/','_')
grdevices.png(file="%s/%s.png" % (outpath,motif), width=512, height=512)
graphics.plot(density,main=motif,xlab="Distribution",xlim=xlim)
grdevices.dev_off()
def drawRmultidensity(Motif_Pos,outpath,col=False,top=None):
grdevices = importr('grDevices')
graphics = importr('graphics')
geneplotter = importr('geneplotter')
RColorBrewer = importr('RColorBrewer')
grdevices.png(file="%s.png" % outpath, width=512, height=512)
Pos={}
if not top:
top=len(Motif_Pos)
for motif in Motif_Pos.keys():
Pos[motif]=-robj.IntVector(Motif_Pos[motif]).ro
Pos=robj.ListVector(Pos)
names=robj.r('names(sort(sapply(%s,length),decreasing=T))' % Pos.r_repr())
if col:
colors=robj.r('colorRampPalette(brewer.pal(9,"BrBG"))')
colors=robj.r.rev(colors(top))
geneplotter.multidensity(Pos.rx(names[:top]),col=colors,lwd=3,xlab="Location")
else:
geneplotter.multidensity(Pos.rx(names[:top]),lwd=3,xlab="Location")
grdevices.dev_off()
def drawRGraph(motif_dist,enriched,outpath):
'''
motif_dist[motif][MotifSeq]={'+':dist,'-':dist}
'''
grdevices = importr('grDevices')
graphics = importr('graphics')
geneplotter = importr('geneplotter')
RColorBrewer = importr('RColorBrewer')
xlim=robj.IntVector([-3000,0])
ylim=robj.FloatVector([0,0.002])
for motif in enriched.keys():
print motif
if not motif_dist[motif]:
print "empty"
continue
motif_seq={}
#画multidensity
for MotifSeq in motif_dist[motif]:
#merge+,-
pos=mergeList(motif_dist[motif][MotifSeq])
if len(pos)>1:
motif_seq[MotifSeq]=-robj.IntVector(pos).ro
#merge MotifSeq
dist=mergeList(motif_seq)
#print motif_seq
if not motif_seq:
print "empty"
continue
motif_seq=robj.ListVector(motif_seq)
names=robj.r('names(sort(sapply(%s,length),decreasing=T))' % motif_seq.r_repr())
#print motif_seq.r_repr(),names.r_repr()
motif=motif.replace('/','_')
grdevices.png(file="%s/%s.png" % (outpath,motif), width=512, height=512)
dist=robj.IntVector(dist)
density=robj.r.density(dist)
if len(motif_seq)>1:
geneplotter.multidensity(motif_seq.rx(names),lwd=3,xlab="Distribution",main=motif,xlim=xlim,ylim=ylim)
else:
graphics.plot(density,lty='dashed',lwd=3,main=motif,xlab="Distribution",xlim=xlim,ylim=ylim)
#graphics.hist(dist,add=True,breaks=50)
graphics.rug(dist)
graphics.lines(density,lty='dashed',lwd='4')
grdevices.dev_off()
return
def mergeList(motif_dict):
'''
motif_dict={'...':[],'...':[]}
'''
pos=[]
[pos.extend(v) for v in motif_dict.values()]
return pos
def drawRbarplot(SeqName_counts,enriched,output,top=25):
if not enriched:
return
grdevices = importr('grDevices')
graphics = importr('graphics')
#SeqName_counts=robj.ListVector(SeqName_counts)
counts=robj.IntVector(SeqName_counts.values())
counts.names=robj.StrVector(SeqName_counts.keys())
#counts=robj.r.sort(counts)
p=robj.FloatVector([enriched[motif]['p'] for motif in enriched.keys()])
p.names=robj.StrVector(enriched.keys())
#enriched_names=robj.StrVector(enriched.keys())
p=robj.r.sort(p,decreasing=True)
enriched_counts=counts.rx(p.names)
#top_counts=robj.r.tail(counts,n=top)
#print top_counts.r_repr()
grdevices.png(file="%s/%s_bar.png" % (output,output), width=512, height=512)
margin=robj.IntVector([3,9,4,2])
graphics.par(mar=margin)
bar=graphics.barplot(enriched_counts,main="Enriched motifs counts",horiz=True,las=1,col='lightblue')
graphics.text(x=enriched_counts,y=bar,label=robj.r.signif(p,digits=2),po=2)
#graphics.text(bar,labels=top_counts,pos=4,offset=10)
grdevices.dev_off()
def drawRboxplot(Merged_dist,enriched,output):
grdevices = importr('grDevices')
graphics = importr('graphics')
#Merged_dist=dict([(k,list(v)) for k,v in Merged_dist.items()])
for motif in Merged_dist.keys():
Merged_dist[motif]=-robj.IntVector(Merged_dist[motif]).ro
Merged_dist=robj.ListVector(Merged_dist)
names=robj.r('names(sort(sapply(%s,length),decreasing=T))' % Merged_dist.r_repr())
enriched_names=robj.StrVector(enriched.keys())
grdevices.png(file="%s/%s_box.png" % (output,output), width=512, height=512)
margin=robj.IntVector([3,9,4,2])
graphics.par(mar=margin)
graphics.boxplot(Merged_dist.rx(enriched_names),main="Boxplot of Motif Positions",horizontal=True,las=1,col='lightblue')
grdevices.dev_off()
def drawRCoocur(co_Occur,outpath):
'''
co_Occur[(motifa,motifb)][REF_SeqName]={(motifa_pos,motifb_pos):distance}
'''
for motif_pair in co_Occur.keys():
print motif_pair,len(co_Occur[motif_pair])
drawRdistance(co_Occur[motif_pair],outpath,motif_pair)
drawRCoDistibution(co_Occur[motif_pair],outpath,motif_pair)
def drawRdistance(motif_pair,outpath,pair_name):
distances=[]
filename="&".join(pair_name).replace('/','_')
for REF_SeqName in motif_pair.keys():
distances.extend(motif_pair[REF_SeqName].values())
dist=robj.IntVector(distances)
grdevices = importr('grDevices')
graphics = importr('graphics')
grdevices.png(file="%s/%s_distance.png" % (outpath,filename), width=512, height=512)
graphics.hist(dist,breaks=50,border=4,main="Distance Histogram of \n%s" % "&".join(pair_name),xlab="Distances")
grdevices.dev_off()
def drawRCoDistibution(motif_pair,outpath,pair_name):
motifA_pos=[]
motifB_pos=[]
filename="&".join(pair_name).replace('/','_')
(motifa,motifb)=pair_name
for REF_SeqName in motif_pair.keys():
#print motif_pair[REF_SeqName].keys()
for motifa_pos,motifb_pos in motif_pair[REF_SeqName].keys():
motifA_pos.append(motifa_pos)
motifB_pos.append(motifb_pos)
#print motifa_pos,motifb_pos
grdevices = importr('grDevices')
graphics = importr('graphics')
geneplotter = importr('geneplotter')
motifA_pos=-robj.IntVector(motifA_pos).ro
motifB_pos=-robj.IntVector(motifB_pos).ro
Pos={motifa:motifA_pos,motifb:motifB_pos}
Pos=robj.ListVector(Pos)
grdevices.png(file="%s/%s_distribution.png" % (outpath,filename), width=512, height=512)
geneplotter.multidensity(Pos.rx(),lwd=3,xlab="Distribution",main="Distribution of \n%s" % filename)
graphics.rug(motifA_pos,col=4)
graphics.rug(motifB_pos,col=2)
grdevices.dev_off()
#Scatter plot
grdevices.png(file="%s/%s_Scatter.png" % (outpath,filename), width=512, height=512)
limit=robj.IntVector([-3000,0])
graphics.plot(motifA_pos,motifB_pos,main="Position Scatter Plot of\n%s&%s" % (motifa,motifb), \
xlab="Positions of %s" % motifa, \
ylab="Positions of %s" % motifb, \
xlim=limit,ylim=limit)
graphics.abline(1,1)
grdevices.dev_off()
def usage():
print "CAREdb.py -z <zpkl> [-o] <output>"
def has_file(filename):
if not os.path.exists(filename):
raise Exception,"There is no %s here" % filename
if __name__ == '__main__':
co_dist_range=(10,300)
try:
opts, args = getopt.getopt(sys.argv[1:], "hz:o:t:r:", ["help","zpklfile=","output=","top=","co_dist_range="])
except getopt.GetoptError:
usage()
sys.exit(2)
for opt, arg in opts:
if opt in ("-h", "--help"):
usage()
sys.exit()
elif opt in ("-z", "--zpklfile"):
zpklfile=arg
has_file(zpklfile)
output=zpklfile.split('.')[0]
top=25
elif opt in ("-o", "--output"):
output=arg
elif opt in ("-t", "--top="):
top=arg
elif opt in ("-r", "--co_dist_range"):
#arg=lower#higer
co_dist_range=tuple(map(int,arg.split("#")))
if not 'zpklfile' in dir():
print "tell me filename please"
usage()
sys.exit(2)
if not os.path.exists(output):
os.makedirs(output)
if not os.path.exists("%s/Enriched" % output):
os.makedirs("%s/Enriched" % output)
if not os.path.exists("%s/CoOccur" % output):
os.makedirs("%s/CoOccur" % output)
timestamp=time.time()
zf = ZipFile(zpklfile, 'r')
Merged_MotifSeq_dist = cPickle.loads(zf.open('Merged_MotifSeq_dist.pkl').read())
SeqName_counts = cPickle.loads(zf.open('SeqName_counts.pkl').read())
Merged_dist=cPickle.loads(zf.open('Merged_dist.pkl').read())
enriched=cPickle.loads(zf.open('Enriched.pkl').read())
try:
co_Occur=cPickle.loads(zf.open('co_Occur_%s#%s.pkl' % co_dist_range).read())
except KeyError:
co_Occur=None
zf.close()
#drawRHist(Motif_Pos,outpath="%s/hist" % basename)
#drawRDensity(Motif_Pos,outpath="%s/density" % basename)
#drawRmultidensity(Motif_Pos,outpath=basename,top=5)
drawRGraph(Merged_MotifSeq_dist,enriched,"%s/Enriched" % output)
drawRbarplot(SeqName_counts,enriched,output,top)
drawRboxplot(Merged_dist,enriched,output)
if co_Occur:
drawRCoocur(co_Occur,"%s/CoOccur" % output)
print time.time()-timestamp
|
#!/usr/bin/env python
# encoding: utf-8
"""
@author: skyxyz-lang
@file: 1512.py
@time: 2020/10/10 14:49
@desc:
"""
class Solution(object):
def numIdenticalPairs(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
dic = {}
ans = 0
for num in nums:
if not dic.get(num):
dic[num] = 1
else:
ans += dic[num]
dic[num] = dic[num] + 1
return ans
|
import pygame
from pygame.locals import *
import sys
import time
import random
# import requests
from urllib.request import urlopen
# from BeautifulSoup import BeautifulSoup4 as BS
from bs4 import BeautifulSoup as BS
from urllib.parse import urlparse, urlsplit
# import pandas as pd
# from PIL import Image
class Game:
def __init__(self):
self.w = 750
self.h = 500
self.reset = True
self.active = False
self.input_text = ""
self.word = ""
self.time_start = 0
self.total_time = 0
self.accuracy = "0%"
self.results = "Time: 0 Accuracy: 0% WPM: 0"
self.wpm = 0
self.end = False
self.HEAD_C = (255, 213, 102)
self.TEXT_C = (240, 240, 240)
self.RESULT_C = (255, 70, 70)
pygame.init()
self.open_img = pygame.image.load("type-speed-open1.png")
self.open_img = pygame.transform.scale(self.open_img, (self.w, self.h))
self.bg = pygame.image.load("background.jpg")
self.bg = pygame.transform.scale(self.bg, (500, 750))
self.screen = pygame.display.set_mode((self.w, self.h))
pygame.display.set_caption("Type Racer")
def draw_text(self, screen, msg, y ,fsize, color):
font = pygame.font.Font(None, fsize)
text = font.render(msg, 1,color)
text_rect = text.get_rect(center=(int(self.w/2), int(y)))
screen.blit(text, text_rect)
pygame.display.update()
def get_sentence(self):
# website_page = "https://genius.com/#top-songs"
# page = urlopen(website_page)
# soup = BS(page)
# soup
# title_links = soup.find_all('h3', class_="ChartSongdesktop__Lyrics-sc-18658hh-4 ksRthp")
# print("title links" + title_links)
# title_links
# links = {}
# for i in range(0, len(title_links)):
# URL = ""
# PARAMS = {}
# r = requests.get(url = URL, params = PARAMS)
# data = r.json()
f = open("sentences1.txt").read()
sentences = f.split(".")
sentence = random.choice(sentences)
return sentence
def show_results(self, screen):
if (not self.end):
#Calculate time
self.total_time = time.time() - self.time_start
#Calculate accuracy
count = 0
for i,c in enumerate(self.word):
try:
if self.input_text[i] == c:
count += 1
except:
pass
self.accuracy = count / len(self.word) * 100
#Calculate words per minute
self.wpm = len(self.input_text) * 60 / (5 * self.total_time)
self.end = True
self.results = "Time:"+str(round(self.total_time)) +" secs Accuracy:"+ str(round(self.accuracy)) + "%" + " Wpm: " + str(round(self.wpm))
# draw icon image
self.time_img = pygame.image.load("icon.png")
self.time_img = pygame.transform.scale(self.time_img, (150, 150))
screen.blit(self.time_img, (int(self.w/2-75), int(self.h - 140)))
self.draw_text(screen, "Reset", self.h - 70, 26, (100, 100, 100))
pygame.display.update()
def run(self):
self.reset_game()
self.running = True
while (self.running):
clock = pygame.time.Clock()
self.screen.fill((0, 0, 0), (50, 250, 650, 50))
pygame.draw.rect(self.screen,self.HEAD_C, (50, 250, 650, 50), 2)
# update the text of user input
self.draw_text(self.screen, self.input_text, 274, 26, (250, 250, 250))
pygame.display.update()
for event in pygame.event.get():
if event.type == QUIT:
self.running = False
sys.exit()
elif event.type == pygame.MOUSEBUTTONUP:
x, y = pygame.mouse.get_pos()
# position of input box
if (x >= 50 and x <= 650 and y >= 250 and y <= 300):
self.active = True
self.input_text = ""
self.time_start = time.time()
# position of reset box
if (x >= 310 and x <= 510 and y >= 390 and self.end):
self.reset_game()
x, y = pygame.mouse.get_pos()
elif event.type == pygame.KEYDOWN:
if self.active and not self.end:
if event.key == pygame.K_RETURN:
self.show_results(self.screen)
self.draw_text(self.screen, self.results, 350, 28, self.RESULT_C)
self.end = True
elif event.key == pygame.K_BACKSPACE:
self.input_text = self.input_text[:-1]
else:
try:
self.input_text += event.unicode
except:
pass
pygame.display.update()
clock.tick(60)
def reset_game(self):
self.screen.blit(self.open_img, (0,0))
pygame.display.update()
time.sleep(1)
self.reset = False
self.end = False
self.input_text = ""
self.word = ""
self.time_start = 0
self.total_time = 0
self.wpm = 0
# Get random sentence
self.word = self.get_sentence()
if (not self.word): self.reset_game()
#drawing heading
self.screen.fill((0, 0, 0))
self.screen.blit(self.bg, (0, 0))
msg = "Type Racer"
self.draw_text(self.screen, msg, 80, 80, self.HEAD_C)
# draw the rectangle for input box
pygame.draw.rect(self.screen, (255, 192, 25), (50, 250, 650, 50), 2)
# draw the sentence string
self.draw_text(self.screen, self.word, 200, 28, self.TEXT_C)
pygame.display.update()
Game().run()
|
#
# Proposal parser. A proposal follows this structure:
#
# <Proposal>
# <Observation>
# <Visit>
# <VisitGroup>
# <ParallelSequenceID>
# <Activity>
# <Exposure>
# <Detector>
# <base></base>
# <subarray></subarray>
# <exp_type></exp_type>
# </Detector>
# </Exposure>
# </Activity>
# </ParallelSequenceID>
# </VisitGroup>
# </Visit>
# </Observation>
# </Proposal>
#
# Each element can occur 1 or more times.
#
import xml.etree.ElementTree as et
def get_detectors(filename):
tree = et.parse(filename)
proposal = tree.getroot()
ObservationNum = 0
detectors = []
ProposalNum = filename.split('.')[0]
for observation in proposal:
ObservationNum = ObservationNum + 1
VisitNum = 0
for visit in observation:
VisitNum = VisitNum + 1
VisitGroupNum = 0
for visitgroup in visit:
VisitGroupNum = VisitGroupNum + 1
ParallelSequenceIDNum = 0
for parallelsequenceid in visitgroup:
ParallelSequenceIDNum = ParallelSequenceIDNum + 1
ActivityNum = 0
for activity in parallelsequenceid:
ActivityNum = ActivityNum + 1
ExposureNum = 0
for exposure in activity:
ExposureNum = ExposureNum + 1
DetectorNum = 0
for detector in exposure:
subarray = detector.find('subarray').text
base = detector.find('base').text
exp_type = detector.find('exp_type').text
id = ProposalNum + '%03d%03d%02d%d%02d%05d' % (ObservationNum,
VisitNum,
VisitGroupNum,
ParallelSequenceIDNum,
ActivityNum,
ExposureNum)
detectors.append({'base': base,
'subarray': subarray,
'exp_type': exp_type,
'id': id})
return detectors
|
# -*- coding: utf-8 -*-
# Generated by Django 1.9 on 2017-01-05 06:25
from __future__ import unicode_literals
from django.db import migrations
class Migration(migrations.Migration):
dependencies = [
('cform', '0001_initial'),
]
operations = [
migrations.RemoveField(
model_name='cred',
name='date',
),
]
|
import csv
years = []
life = []
with open('data.txt') as csvfile:
reader = csv.reader(csvfile, delimiter = " " )
for row in reader:
years.append(row[0])
life.append(row[10])
str = '['
for age in life:
str += age + ', '
str += ']'
print str |
import asyncio
import logging
from contextlib import _AsyncGeneratorContextManager
from functools import wraps
from typing import AsyncGenerator, Awaitable, Callable, TYPE_CHECKING
if TYPE_CHECKING:
from .stateful import Stateful
log = logging.getLogger(__name__)
_DEFAULT = object()
def retry_with_proxy(*exceptions: Exception, attempts: int = 5):
"""
When the underlying method of a :class:`grobber.stateful.Stateful` object
throws an exceptions that is a subtype of ``exceptions`` it reloads the
:class:`grobber.request.Request` and re-runs the method until it either succeeds,
or the amount of retries exceeds ``attempts``.
Example:
When calling the ``Key.get_key`` method it will re-run when it raises a `KeyError`.
.. code-block:: python
:emphasize-lines: 2
class Key(Stateful):
@retry_with_proxy(KeyError)
async def get_key():
data = await self._req.json
return data["key"]
:return: Decorator which applies the retry logic to the decorated method.
"""
def decorator(func):
@wraps(func)
async def wrapper(self: "Stateful", *args, **kwargs):
last_exception = None
for attempt in range(attempts):
try:
return await func(self, *args, **kwargs)
except exceptions as e:
if last_exception:
e.__origin__ = last_exception
last_exception = e
request = self._req
request._use_proxy = True
request.reset()
log.info(f"{func.__qualname__} failed, trying again with proxy {attempt + 1}/{attempts}")
if last_exception:
raise last_exception
else:
raise ValueError("There wasn't even an attempt lel")
return wrapper
return decorator
def cached_property(func: Callable[..., Awaitable]):
cache_name = f"_{func.__name__}"
lock_name = f"{cache_name}__lock"
def get_lock(self) -> asyncio.Lock:
try:
lock = getattr(self, lock_name)
except AttributeError:
lock = asyncio.Lock()
setattr(self, lock_name, lock)
return lock
@wraps(func)
async def getter(self, *args, **kwargs):
lock = get_lock(self)
async with lock:
val = getattr(self, cache_name, _DEFAULT)
if val is _DEFAULT:
val = await func(self, *args, **kwargs)
setattr(self, cache_name, val)
try:
func.__name__ in self.ATTRS
except AttributeError:
pass
else:
self._dirty = True
return val
def setter(self, value):
lock = get_lock(self)
if lock.locked():
log.warning(f"Lock {lock_name} already acquired for {func}")
setattr(self, cache_name, value)
try:
func.__name__ in self.ATTRS
except AttributeError:
pass
else:
self._dirty = True
def deleter(self):
lock = get_lock(self)
if lock.locked():
log.warning(f"Lock {lock_name} already acquired for {func}")
delattr(self, cache_name)
try:
func.__name__ in self.ATTRS
except AttributeError:
pass
else:
self._dirty = True
return property(getter, setter, deleter)
class _RefCounter(_AsyncGeneratorContextManager):
def __init__(self, func, *args, **kwargs):
super().__init__(func, args, kwargs)
self.ref_count = 1
async def __aenter__(self):
self.ref_count += 1
return await self.value
async def __aexit__(self, exc_type, exc_val, exc_tb):
self.ref_count -= 1
if self.ref_count <= 0:
await super().__aexit__(exc_type, exc_val, exc_tb)
@cached_property
async def value(self):
return await self.gen.__anext__()
def cached_contextmanager(func: Callable[..., AsyncGenerator]) -> property:
ref_name = f"_{func.__name__}_ref"
@wraps(func)
def wrapper(self):
try:
ref = getattr(self, ref_name)
except AttributeError:
ref = _RefCounter(func, self)
setattr(self, ref_name, ref)
return ref
return property(wrapper)
|
# to check the file exists using luigi
# run with a custom command
# python luigiImageContent.py FileImageContent --local-scheduler --fileName macbookResultPage.txt
import luigi
from bs4 import BeautifulSoup
class FileImageContent(luigi.Task):
fileName = luigi.Parameter()
def requires(self):
return []
def output(self):
return luigi.LocalTarget("maccontent.txt")
def run(self):
soup = BeautifulSoup (open(self.fileName), features="lxml")
links = soup.find_all('a')
with self.output().open('w') as fout :
for link in links:
content = link.contents[0]
fullLink = link.get('href')
fout.write("Content:{}, link:{}\n".format(content, fullLink))
if __name__ == '__main__':
luigi.run() |
#!/usr/bin/env python3
from tsdb import TSDBClient
import timeseries as ts
import asyncio
import numpy as np
async def main():
print('&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&')
client = TSDBClient()
await client.add_trigger('KalmanFilter', 'insert_ts', ['sig_epsilon_estimate', 'sig_eta_estimate'], None)#['mean', 'std'], None)#
sigeta = np.random.normal(0,1,2000)
sigeps = np.random.normal(0,10,2000)
mus = np.cumsum(sigeta)+20
y = mus + sigeps
await client.insert_ts('one',ts.TimeSeries(y,np.arange(2000)))
await client.upsert_meta('one', {'order': 1, 'blarg': 1})
print('---------------------')
await client.select(fields=[])
if __name__=='__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
loop.close() |
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from pretrained_model import pretrained_densenetSR
from dataLoader import DIV2K_TrainData, DIV2K_ValidData
import time
import copy
from math import log10
from tqdm import tqdm
use_cuda = torch.cuda.is_available()
# Hyperparameters
batch_size = 1
nr_epochs = 10
momentum = 0.93
learning_rate = 0.01
running_loss = 0.0
gamma = 0.1
milestones = [1, 3, 5, 7, 9]
SRmodel = pretrained_densenetSR(pretrained=True)
if use_cuda:
SRmodel = SRmodel.cuda()
SRmodel = nn.DataParallel(SRmodel)
# Training Data and Dataloader
train_data_set = DIV2K_TrainData()
train_dataloader = DataLoader(train_data_set, batch_size = 1, shuffle = True, num_workers = 10)
# Validation Data and Dataloader
valid_data_set = DIV2K_ValidData()
valid_dataloader = DataLoader(valid_data_set, batch_size = 1, shuffle = True, num_workers = 10)
# Optimization
optimizer = optim.SGD(SRmodel.parameters(), lr = learning_rate, momentum = momentum)
criterion = nn.SmoothL1Loss().cuda() if use_cuda else nn.SmoothL1Loss()
scheduler = optim.lr_scheduler.MultiStepLR(optimizer, milestones, gamma = gamma)
dataloaders_dict = {"train": train_dataloader, "valid": valid_dataloader}
def train_model(cust_model, dataloaders, criterion, optimizer, num_epochs=10, scheduler = None):
start_time = time.time()
val_acc_history = []
best_model_wts = copy.deepcopy(cust_model.state_dict())
best_acc = 0.0
for epoch in range(num_epochs):
print("Epoch {}/{}".format(epoch+1, num_epochs))
print("_"*15)
for phase in ["train", "valid"]:
if phase == "train":
cust_model.train()
elif phase == "valid":
cust_model.eval()
running_loss = 0.0
running_psnr = 0
for input_img, labels in tqdm(dataloaders[phase], total=len(dataloaders[phase])):
input_img = input_img.cuda()
labels = labels.cuda()
optimizer.zero_grad()
with torch.set_grad_enabled(phase=="train"):
outputs = cust_model(input_img)
loss = criterion(outputs, labels)
psnr = 10 * log10(1 / loss.item())
if phase == "train":
loss.backward()
optimizer.step()
running_loss += loss.item() * input_img.size(0)
running_psnr += psnr
epoch_loss = running_loss / len(dataloaders[phase])
epoch_acc = running_psnr / len(dataloaders[phase])
print("{} Loss: {:.4f} Acc PSNR: {:.4f}".format(phase, epoch_loss, epoch_acc))
if scheduler is not None and phase == "train":
scheduler.step()
if phase == 'valid' and epoch_acc > best_acc:
best_acc = epoch_acc
best_model_wts = copy.deepcopy(cust_model.state_dict)
if phase == "valid":
val_acc_history.append(epoch_acc)
print()
time_elapsed = time.time() - start_time
print("Training complete in {:.0f}m {:.0f}s".format(time_elapsed // 60, time_elapsed % 60))
print("Best validation Accuracy: {:4f}".format(best_acc))
best_model_wts = copy.deepcopy(cust_model.state_dict())
cust_model.load_state_dict(best_model_wts)
return cust_model, val_acc_history
def save_model(cust_model, name = "SRmodel.pt"):
torch.save(cust_model.state_dict(), name)
def load_model(cust_model, model_dir = "./SRmodel.pt"):
cust_model.load_state_dict(torch.load(model_dir))
cust_model.eval()
return cust_model
print("Start Training for 2 epochs: ")
print("*"*15)
SRmodel, validation_acc = train_model(SRmodel, dataloaders_dict, criterion, optimizer, nr_epochs, scheduler)
save_model(SRmodel, name = "SRmodel_pretrain.pt")
|
#coding:utf-8
import re
import urllib
import string
import matplotlib.pyplot as plt
import numpy as np
def gethtml(url):
page=urllib.urlopen(url)
html=page.read()
return html
def getdata(html,number):
p=re.compile(r'<td><a href="http://data.eastmoney.com/bbsj/'+number+'.html" target="_blank">(.*)</td>')
datalist=re.findall(p,html)
return datalist
def manage():
number=raw_input('Code:')
web=gethtml('http://quote.eastmoney.com/sz'+number+'.html')
managelist=[]
firstlist=getdata(web,number)
numberlist1=[]
numberlist2=[]
numberlist3=[]
for i in range (1,4):
managelist.append(firstlist[-i])
str1=str(managelist[0])
for i in range (2,10):
if str1[-i]=='\xba':
break
numberlist1.append(str1[-i])
str2=str(managelist[1])
for i in range (2,10):
if str1[-i]=='\xba':
break
numberlist2.append(str2[-i])
str3=str(managelist[2])
for i in range (2,10):
if str3[-i]=='\xba':
break
numberlist3.append(str3[-i])
in_par=string.atof(''.join(numberlist1[::-1]))
win_par=string.atof(''.join(numberlist2[::-1]))
jud_self=string.atof(''.join(numberlist3[::-1]))
plt.title('Company core data of Code'+number)
dict = {'year basis': jud_self, ' gross profit rate;': win_par, 'ROE': in_par}
for i ,key in enumerate(dict): plt.bar(i,dict[key])
plt.xticks(np.arange(len(dict))+0.4,dict.keys())
plt.yticks(dict.values())
plt.show()
if __name__ == '__main__':
manage()
|
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from collections import deque
import json
from odoo import http
from odoo.http import request
from odoo.tools import ustr
from odoo.tools.misc import xlwt
from datetime import datetime
from datetime import date
import ast
import logging
_logger = logging.getLogger(__name__)
class SalesReportByInvoice(http.Controller):
@http.route('/web/export_xls/sales_report_by_invoice', type='http', auth="user")
def export_xls(self, filename, date_from, date_to, **kw):
workbook = xlwt.Workbook()
worksheet = workbook.add_sheet('Sales Report By Invoice')
invoice_ids = request.env['account.invoice'].sudo().search([('date_invoice','>=',date_from),('date_invoice','<=',date_to)],order='date_invoice desc')
# STYLES
style_header_bold = xlwt.easyxf("font: bold on;font: name Calibri;align: wrap no")
style_header_right = xlwt.easyxf("font: name Calibri;align: horiz right, wrap no")
style_table_header_bold = xlwt.easyxf("font: bold on;font: name Calibri;align: horiz centre, vert centre, wrap on;borders: top thin, bottom thin, right thin;")
style_table_row = xlwt.easyxf("font: name Calibri;align: horiz left, wrap no;borders: top thin, bottom thin, right thin;")
style_table_row_amount = xlwt.easyxf("font: name Calibri;align: horiz right, wrap no;borders: top thin, bottom thin, right thin;", num_format_str="#,##0.00")
style_table_total = xlwt.easyxf("pattern: pattern solid, fore_colour pale_blue;font: bold on;font: name Calibri;align: horiz left, wrap no;borders: top thin, bottom medium, right thin;")
style_table_total_value = xlwt.easyxf("pattern: pattern solid, fore_colour pale_blue;font: bold on;font: name Calibri;align: horiz right, wrap no;borders: top thin, bottom medium, right thin;", num_format_str="#,##0.00")
style_end_report = xlwt.easyxf("font: bold on;font: name Calibri;align: horiz left, wrap no;")
worksheet.col(0).width = 300*12
worksheet.col(1).width = 300*12
worksheet.col(2).width = 500*12
worksheet.col(3).width = 500*12
worksheet.col(4).width = 250*12
worksheet.col(5).width = 250*12
worksheet.col(6).width = 250*12
worksheet.col(7).width = 300*12
worksheet.col(8).width = 250*12
# TEMPLATE HEADERS
# TABLE HEADER
worksheet.write(0, 0, 'CITY', style_table_header_bold) # HEADER
worksheet.write(0, 1, 'AREA', style_table_header_bold) # HEADER
worksheet.write(0, 2, 'SALES AGENT', style_table_header_bold) # HEADER
worksheet.write(0, 3, "CLIENT'S NAME", style_table_header_bold) # HEADER
worksheet.write(0, 4, 'TERMS', style_table_header_bold) # HEADER
worksheet.write(0, 5, 'DUE DATE', style_table_header_bold) # HEADER
worksheet.write(0, 6, 'INVOICE DATE', style_table_header_bold) # HEADER
worksheet.write(0, 7, 'INVOICE NO.', style_table_header_bold) # HEADER
worksheet.write(0, 8, 'AMOUNT', style_table_header_bold) # HEADER
row_count = 1
for invoice in invoice_ids:
worksheet.write(row_count, 0, invoice.partner_id.city or '', style_table_row)
worksheet.write(row_count, 1, invoice.partner_id.partner_area_id.name or '', style_table_row)
worksheet.write(row_count, 2, invoice.user_id.name or '', style_table_row)
worksheet.write(row_count, 3, invoice.partner_id.name or '', style_table_row)
worksheet.write(row_count, 4, invoice.payment_term_id.name or '', style_table_row)
worksheet.write(row_count, 5, invoice.date_due or '', style_table_row)
worksheet.write(row_count, 6, invoice.date_invoice or '', style_table_row)
worksheet.write(row_count, 7, invoice.number or '', style_table_row)
worksheet.write(row_count, 8, invoice.amount_total or '', style_table_row_amount)
row_count +=1
response = request.make_response(None,
headers=[('Content-Type', 'application/vnd.ms-excel'),
('Content-Disposition', 'attachment; filename=%s;'%(filename)
)])
workbook.save(response.stream)
return response
|
# import cdsapi
# import cdstoolbox as ct
import numpy as np
import h5py as h5
import matplotlib.pyplot as plt
class Ecosystem():
def __init__(self, model, year):
self.year = year
self.catastrophy = Catastrophy()
self.model = model
# self.client = cdsapi.Client()
self.dict_temp = {'2019': 1.0, '2020': 1.1, '2021':1.2, '2022':1.2, '2023':1.3, '2024':1.5, '2025':1.6, '2026':1.9}
self.co2_concentration = self.init_CO2_concentration()
self.path = 'data_copernicus.h5'
def get_cds_data(self):
if self.model == 0:
temp = self.dict_temp[str(self.year)]
self.catastrophy.check_catastrophy(temp)
def perform_timestep(self, model, year):
self.year = year
if self.model != model:
self.model = model
self.get_cds_data()
def init_CO2_concentration(self):
years_diff = int(self.year) - 1970
print(years_diff)
return 326.675+1.48262*((years_diff/10)**(2.3))
def temp_from_currentCO2(self):
temp = 285.8 - 273.15 + 3.92 * 0.3 * 5.35 *np.log(self.co2_concentration/278)
return temp
def update_co2(self, faction_emission):
#per year
self.co2_concentration += faction_emission
return self.co2_concentration
def compare_copernicus_data(self, first_year,end_year, year,temp_diff, temperatures):
data = h5.File(self.path, 'r')
year = year - 2006
diff = np.zeros(4)
i = 0
key_m = {'min':None}
plotdata = np.zeros(end_year - first_year)
temperatures = np.append(temperatures,temperatures[-1] + temp_diff)
time = np.arange(first_year,end_year)
fig, ax = plt.subplots(figsize=(12,8))
for keys in data:
if year == first_year:
diff[i] = 0
else:
diff[i] = data[keys][1, year] - data[keys][1, year-1]
if (np.abs(diff[i] - temp_diff) < np.abs(diff[i-1] - temp_diff) and i > 0 ):
key_m['min'] = keys
for j in range(end_year - first_year):
plotdata[j] = data[keys][1,j] - 273.15
i = i + 1
ax.plot(time,plotdata,label=keys)
ax.plot(time[0:len(temperatures)],temperatures[0:len(temperatures)],'k-',label='your trajectory')
ax.set_xlabel('time in years',fontsize=14)
ax.set_ylabel(r'temperature in $^{\circ} \ C $',fontsize=14)
plt.xticks(fontsize=14)
plt.yticks(fontsize=14)
ax.legend(fontsize=14)
plt.title('mean surface temperature per year',fontsize=14)
fig.savefig('static/img/plot.png')
# print(data[keys][1, year] - 273.15)
class Catastrophy():
def __init__(self):
pass
def check_catastrophy(self, temp):
# proba = 1/(1+ np.exp(-10 (temp - 1.8) ))
proba = 1/(1+np.exp(-10 *(temp -1.8 ) ))
is_happening = np.random.uniform() < proba
# print(proba, is_happening)
# return proba, is_happening
def check_ExtremeWeather(self, temp):
proba = 0.1+ temp*0.4/15
is_happening = np.randum.uniform() < probas
|
# coding: utf-8
from copy import copy
class ComponentHtml(object):
"""
<TAG></TAG>
"""
def __init__(self, tag_name, innerHtml='', **kwargs):
self.tag_name = tag_name
self.innerHtml = innerHtml
self.kwargs = kwargs
# Every component may have associated scripts.
self.css_libraries = []
self.javascript_libraries = []
self._script = ''
self.jquery_init_code = ''
self.propagate_scripts(innerHtml)
def __str__(self):
return self.as_html()
def as_html(self):
return ComponentHtml.tag(self.tag_name, self.innerHtml, **self.kwargs)
def add_component(self, component):
"""
@component must be a ComponentHtml or a unicode string.
"""
self.innerHtml += unicode(component)
self.propagate_scripts(component)
def propagate_scripts(self, component):
if isinstance(component, ComponentHtml):
# avoid replicated libraries ('set' function does not preserve order)
for css_lib in component.css_libraries:
self.css_libraries.append(css_lib)
for js_lib in component.javascript_libraries:
self.javascript_libraries.append(js_lib)
self.add_javascript_code(component._script)
self.add_jquery_init_code(component.jquery_init_code)
def get(self, attr):
try:
return self.kwargs[attr]
except KeyError:
return None
def set(self, attr, value):
self.kwargs[attr] = value
def clone(self):
return copy(self)
# Scripts Methods
def add_css_library(self, href):
self.css_libraries.append(href)
def add_javascript_library(self, src):
self.javascript_libraries.append(src)
def add_javascript_code(self, src):
self._script += src
def add_jquery_init_code(self, src):
self.jquery_init_code += src
# Global methods
@classmethod
def attribute_conversion(cls, name):
if name == 'clazz': return u'class'
if name == 'xml_lang': return u'xml:lang'
if name == 'http_equiv': return u'http-equiv'
return name
@classmethod
def tag(cls, tag_name, innerHtml, **kwargs):
attr_function = lambda key, value: u' %s="%s"' % (cls.attribute_conversion(key), value) if value else u''
attributes_string = u''.join(attr_function(key, value) for key, value in kwargs.iteritems()) if kwargs else u''
return u'<%s%s>%s</%s>' % (tag_name, attributes_string, innerHtml, tag_name)
@classmethod
def simple_tag(cls, tag_name, **kwargs):
attr_function = lambda key, value: u' %s="%s"' % (cls.attribute_conversion(key), value) if value else u''
attributes_string = u''.join(attr_function(key, value) for key, value in kwargs.iteritems()) if kwargs else u''
return u'<%s%s/>' % (tag_name, attributes_string)
class SimpleComponentHtml(ComponentHtml):
"""
<TAG/>
"""
def as_html(self):
return ComponentHtml.simple_tag(self.tag_name, **self.kwargs)
class Image(SimpleComponentHtml):
"""
<img>
"""
def __init__(self, src, **kwargs):
super(Image, self).__init__(u'img', src=src, **kwargs)
class Link(ComponentHtml):
"""
<a>
"""
def __init__(self, href, innerHtml, target=None, **kwargs):
super(Link, self).__init__(u'a', href=href, innerHtml=innerHtml, target=target, **kwargs)
class Paragraph(ComponentHtml):
"""
<p>
"""
def __init__(self, innerHtml, **kwargs):
super(Paragraph, self).__init__(u'p', innerHtml=innerHtml, **kwargs)
class UnorderedList(ComponentHtml):
"""
<ul>
"""
def __init__(self, **kwargs):
super(UnorderedList, self).__init__(u'ul', **kwargs)
#override
def add_component(self, component):
if isinstance(component, (str, unicode)):
super(UnorderedList, self).add_component(ComponentHtml.tag(u'li', component))
else:
if component.tag_name == 'li':
super(UnorderedList, self).add_component(component)
else:
super(UnorderedList, self).add_component(ComponentHtml.tag(u'li', component))
class OrderedList(ComponentHtml):
"""
<ol>
"""
def __init__(self, **kwargs):
super(OrderedList, self).__init__(u'ol', **kwargs)
#override
def add_component(self, component):
if isinstance(component, (str, unicode)):
super(OrderedList, self).add_component(ComponentHtml.tag(u'li', component))
else:
if component.tag_name == 'li':
super(UnorderedList, self).add_component(component)
else:
super(UnorderedList, self).add_component(ComponentHtml.tag(u'li', component))
class Chunk(ComponentHtml):
"""
<span>
"""
def __init__(self, innerHtml=u'', **kwargs):
super(Chunk, self).__init__(u'span', innerHtml=innerHtml, **kwargs)
class Panel(ComponentHtml):
"""
<div>
"""
def __init__(self, innerHtml=u'', **kwargs):
super(Panel, self).__init__(u'div', innerHtml=innerHtml, **kwargs)
class InformationPanel(Panel):
"""
<div><span class="label"><span><span class="value"><span></div>
"""
def __init__(self, innerHtml=u'', label_class='', value_class='value', **kwargs):
super(Panel, self).__init__(u'div', innerHtml=innerHtml, **kwargs)
self.label_class = label_class
self.value_class = value_class
def add_info(self, label, value):
self.add_component(Chunk(label, clazz=self.label_class))
self.add_component(Chunk(value, clazz=self.value_class))
self.add_component('<br/>')
class Table(ComponentHtml):
"""
<table>
"""
LINE_CLASSES = (u'odd', u'even')
def __init__(self, **kwargs):
super(Table, self).__init__(u'table', **kwargs)
self._header = ComponentHtml(u'thead', u'')
self._header_line = None
self._body = ComponentHtml(u'tbody', u'')
self._body_line = None
self._line_index = 0
def start_header_line(self):
if self._header_line is not None:
self._header.add_component(self._header_line)
self._header_line = ComponentHtml(u'tr', u'')
def add_cell_on_header(self, content, **kwargs):
# FIXME: it must propagate libraries
self.propagate_scripts(content)
if self._header_line is None:
self.start_header_line()
if isinstance(content, (str, unicode)):
content = ComponentHtml(u'th', content, **kwargs)
self._header_line.add_component(content)
def start_line(self):
if self._body_line is not None:
self._body.add_component(self._body_line)
self._body_line = ComponentHtml(u'tr', '', clazz=Table.LINE_CLASSES[self._line_index % 2])
self._line_index += 1
def add_cell(self, content, **kwargs):
# FIXME: it must propagate libraries
self.propagate_scripts(content)
if self._body_line is None:
self.start_line()
content = ComponentHtml(u'td', content, **kwargs)
self._body_line.add_component(content)
#override
def as_html(self):
self.start_header_line()
self.start_line()
self.innerHtml = self._header.as_html()
self.innerHtml += self._body.as_html()
return super(Table, self).as_html()
class Form(ComponentHtml):
"""
<form>
"""
def __init__(self, action, method=u'post', **kwargs):
super(Form, self).__init__(u'form', action=action, method=method, **kwargs)
def add_component_with_label(self, label, component):
panel = ComponentHtml(u'div', '', clazz=u'form-label-field')
panel.add_component(ComponentHtml.tag(u'div', ComponentHtml.tag(u'span', label), clazz=u'form-label'))
panel.add_component(ComponentHtml.tag(u'div', component, clazz=u'form-field'))
self.add_component(panel)
def include_file_upload(self):
self.set('enctype', 'multipart/form-data')
class TextBox(SimpleComponentHtml):
"""
<input type="text">
"""
def __init__(self, name, value, maxlength=100, **kwargs):
super(TextBox, self).__init__(u'input', type=u'text', name=name, value=value, maxlength=maxlength, **kwargs)
class TextArea(ComponentHtml):
"""
<textarea>
"""
def __init__(self, name, value, maxlength=500, **kwargs):
super(TextArea, self).__init__(u'textarea', name=name, value=value, maxlength=maxlength, **kwargs)
class CheckBox(SimpleComponentHtml):
"""
<input type="checkbox">
"""
def __init__(self, name, **kwargs):
super(CheckBox, self).__init__(u'input', type=u'checkbox', name=name, **kwargs)
#override
def set(self, attr, value):
"Checkbox should have value attribute too. We need a trustable and solid standard"
if attr == u'value':
if value in [True, 'True', 'true', 'on']:
super(CheckBox, self).set(u'checked', u'checked')
else:
super(CheckBox, self).set(u'checked', u'')
else:
super(CheckBox, self).set(attr, value)
def get(self, attr):
if attr == 'value':
return True if super(CheckBox, self).get(u'checked') else False
else:
return super(CheckBox, self).get(attr)
class UploadBox(SimpleComponentHtml):
"""
<input type="file">
"""
def __init__(self, name, value, **kwargs):
super(UploadBox, self).__init__(u'input', type=u'file', name=name, value=value, **kwargs)
class Select(ComponentHtml):
"""
<select>
"""
def __init__(self, name, multiple=False, **kwargs):
if multiple:
multiple = u'multiple'
else:
multiple = u''
super(Select, self).__init__(u'select', name=name, multiple=multiple, **kwargs)
self.options = []
def add_option(self, label, value, selected=False):
if selected:
option = ComponentHtml(u'option', innerHtml=label, value=value, selected=u'selected')
else:
option = ComponentHtml(u'option', innerHtml=label, value=value)
self.options.append(option)
def set(self, attr, value):
"Select should have value attribute too. We need a trustable and solid standard"
if attr == u'value':
if isinstance(value, list):
for v in value:
for option in self.options:
if unicode(option.get(u'value')) == v:
option.set(u'selected', u'selected')
break
else: # only one value
for option in self.options:
if option.get(u'value') == value:
option.set(u'selected', u'selected')
else:
super(Select, self).set(attr, value)
def get(self, attr):
if attr == u'value':
if self.get(u'multiple') == u'multiple':
values = []
for option in self.options:
if option.get(u'selected') == u'selected':
values.append(option.get(u'value'))
return values
else:
for option in self.options:
if option.get(u'selected') == u'selected':
return option.get(u'value')
return None
else:
return super(Select, self).get(attr)
#override
def as_html(self):
self.innerHtml = ''.join([option.as_html() for option in self.options])
return super(Select, self).as_html()
class SubmitButton(SimpleComponentHtml):
"""
<input type="submit">
"""
def __init__(self, id, value, **kwargs):
super(SubmitButton, self).__init__(u'input', type=u'submit', id=id, value=value, **kwargs)
class HiddenField(SimpleComponentHtml):
"""
<input type="submit">
"""
def __init__(self, id, value, **kwargs):
super(HiddenField, self).__init__(u'input', type=u'hidden', id=id, value=value, **kwargs)
class Button(ComponentHtml):
"""
<button>
"""
def __init__(self, id, **kwargs):
super(Button, self).__init__(u'button', id=id, **kwargs)
class Head(ComponentHtml):
"""
<head>
"""
def __init__(self, title, description, keywords, favicon, **kwargs):
super(Head, self).__init__(u'head', **kwargs)
self.title = title
self.description = description
self.keywords = keywords
self.favicon = favicon
#override
def as_html(self):
self.innerHtml = ComponentHtml.tag(u'title', self.title)
self.innerHtml += ComponentHtml.simple_tag(u'meta', name=u'description', content=self.description)
self.innerHtml += ComponentHtml.simple_tag(u'meta', name=u'keywords', content=self.keywords)
self.innerHtml += ComponentHtml.simple_tag(u'meta', http_equiv=u'Content-Type', content=u'text/html;charset=UTF-8')
if self.favicon:
self.innerHtml += ComponentHtml.simple_tag(u'link', rel=u'shortcut', href=self.favicon)
for href in self.css_libraries:
self.innerHtml += ComponentHtml.simple_tag(u'link', type=u'text/css', rel=u'stylesheet', href=href)
for src in self.javascript_libraries:
self.innerHtml += ComponentHtml.tag(u'script', '', type=u'text/javascript', src=src)
script = ComponentHtml(u'script', '', type=u'text/javascript')
if self.jquery_init_code:
script.add_component(u'$(document).ready(function() { %s });' % self.jquery_init_code);
self.innerHtml += script.as_html()
return super(Head, self).as_html()
class Body(ComponentHtml):
"""
<body>
"""
def __init__(self, **kwargs):
super(Body, self).__init__(u'body', **kwargs)
class Page(ComponentHtml):
"""
<html>
"""
TRANSITIONAL_401 = u'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">\n'
STRICT_401 = u'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">\n'
HTML5_DOCTYPE = u'<!DOCTYPE html>\n'
def __init__(self, title, description, keywords, favicon=None, doc_type=TRANSITIONAL_401, lang=u'en'):
super(Page, self).__init__(u'html', xmlns=u'http://www.w3.org/1999/xhtml', xml_lang=lang, lang=lang)
self.doc_type = doc_type
self.head = Head(title, description, keywords, favicon)
self.body = Body()
#override
def as_html(self):
self.head.propagate_scripts(self)
self.head.propagate_scripts(self.body)
self.innerHtml = self.head.as_html()
self.innerHtml += self.body.as_html()
return self.doc_type + super(Page, self).as_html()
|
while True:
try:
# 输入直接转列表,方便map
s = [i for i in input()]
# 只要不是字母,统统换成空格
s = ''.join(list(map(lambda x: x if x == ' ' or x.isalpha() else ' ', s)))
# 倒序合并
print(' '.join(reversed(s.split())))
except:
break
|
import numpy as np
from keras import backend as K
# tag one-hot化
def vec2one_hot(tags, vec_size):
value = tags[0]
temp = np.zeros(vec_size, dtype=np.int16) # 省内存
temp[value] = 1
return temp
# one_hots = []
# for value in tags:
# temp = np.zeros(vec_size, dtype=np.int16) # 省内存
# temp[value] = 1
# one_hots.append(temp)
# return one_hots
# tag向量化
def tag2vec(tags, vec_size):
one_hots = np.zeros(vec_size, dtype=np.int16) # 省内存
for value in tags:
one_hots[int(value)] = 1
return one_hots
# 损失函数(交叉损失)
def mean_negative_log_probs(y_true, y_pred):
log_probs = -K.log(y_pred)
log_probs *= y_true
# return K.sum(log_probs)
return K.sum(log_probs) / K.sum(y_true)
# 损失函数(二元交叉熵)
def mean_binary_crossentropy(y_true, y_pred):
temp = y_true * K.log(y_pred + K.epsilon()) + (1-y_true) * K.log(1-y_pred+K.epsilon())
return K.sum(-temp) / K.sum(y_true)
# 准确度函数
def compute_precision(y_true, y_pred):
true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) # 计算真值1且预测1
predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1))) # 预测总数
precision = true_positives / (predicted_positives + K.epsilon()) # K.epsilon():极小量
return precision
# 召回率计算
def compute_recall(y_true, y_pred):
true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1))) # 计算真值1且预测1
possible_positives = K.sum(K.round(K.clip(y_true, 0, 1))) # 真值总数
recall = true_positives / (possible_positives + K.epsilon())
return recall |
from FindFiles import FindFiles
from SetLegend import SetLegend
from Fill_mg import Fill_mg
#from ERDict import ERDict
from ROOT import *
from array import array
def SepCan(params):
from ER_Dict import ER_Dict # I'm not sure why this needs to be in definition and doesn't work in header.
print'In SepCan'
paths = FindFiles(params[1],params[2])
# Want to plot avg. b vs. ts for each #\eta_{R} and save as separate canvases.
plot_type = str(paths[0].split('/')[-1].split('_')[-8])
#gStyle.SetOptStat(0); # no stats box
#l1 = SetLegend(params[3])
# Order by eta range
# Need this for plotting avg bias vs. #\eta_{R} for given timeshift, so that x entries are in order.
temp_list = []
for i in range(len(paths)):
current_min = 1000
for path in paths:
emi = float(path.split('/')[-1].split('_')[-6])
if (emi < current_min):
current_min = emi
for path in paths:
emi = float(path.split('/')[-1].split('_')[-6])
if emi == current_min:
temp_list.append(path)
paths.remove(path)
paths = temp_list
# for plotting all eta ranges on separate bias vs ts plots:
i = 0
gROOT.SetBatch(kTRUE)
for path in paths:
print'Plotting ',path
l1 = SetLegend(params[3]) # Reset legend
#can = eval('c' + str(i))
#can = TCanvas('can','can',800,600)
#mg_str = 'mg' + str(i)
#mg = eval('TMultiGraph(' + mg_str + ', ' + mg_str + ', 800, 600)')
#eval('' + mg_str + ' = TMultiGraph' + mg_str + ', ' + mg_str + ', 800, 600)')
#mg = TMultiGraph('mg','mg') # For plotting error bands on same plot
mg = TMultiGraph() # If you want to access root file later, need to give this a name
#mga = eval(mg_tsr)
x = array('d',[])
y = array('d',[])
xe = array('d',[])
ye = array('d',[])
h = TH1F()
f = TFile().Open(path)
if plot_type == 'EC':
h = f.Get("EC")
else:
print'Plot Type not recognized. Should be EC'
counter = 1
value = 0
ts = 0
dt = h.GetXaxis().GetBinLowEdge(3) - h.GetXaxis().GetBinLowEdge(2)
found = False
while( (h.GetBinContent(counter) != 0) and (found == False)):
ts = h.GetXaxis().GetBinLowEdge(counter)
# if hts == ts:
# found = True
# x.append()
value = h.GetBinContent(counter)
#print'value = ',value
x.append(ts)
xe.append(0)
ye.append(h.GetBinError(counter))
y.append(value)
ts += dt
counter += 1
g = TGraphErrors(counter - 1, x, y, xe, ye) # x, y, x errors, y errors
# Have tgrapherrors for plot path_{i}
gne = TGraph(counter - 1, x, y) # Graph with no errors
gne.SetName("gne")
gne.SetMarkerStyle(7)
WT = paths[0].split('_')[-3] # Weights Type
if WT == 'online': WT = 'Online'
PD = path.split('_')[-2]
min_eta = float(path.split('_')[-7]) # min is -7 when there's a note. With no note, one less '_'
max_eta = float(path.split('_')[-6])
#print'1sig errors = ',ye
# Fill multigraph
num_points_ = counter - 1
#print'counter = ',counter
mg = Fill_mg(mg,l1,num_points_,x,y,xe,ye,gne,g)
if WT == '1':
WT = 'Ideal' # Eventually Have Ideal1, Ideal2, .. for diff. weights configurations. Online1, Online2, ..
#if plot_type == 'EC':
mg.SetTitle(WT + ' Weights, ' + PD + ' Parameters, [#eta_{min},#eta_{max}) = [' + str(min_eta) + ', ' + str(max_eta) + ')')
#gROOT.SetBatch(kTRUE)
can = TCanvas('can','can',800,600)
#print'i = ',i
#can_str = ''
#can_str = 'c' + str(i)
#eval('c' + str(i) + ' = TCanvas(' + can_str + ', ' + can_str + ', 800, 600)')
#can = eval('c' + str(i))
#can = TCanvas('can','can',800,600)
#can = eval('TCanvas(' + can_str + ', ' + can_str + ', 800, 600)')
#gROOT.SetBatch(kTRUE)
# Set equal for automatic range
ymin = float(params[4])
ymax = float(params[5])
mg.Draw("A")
#mg.SetTitleSize(0.04)
#mg.GetYaxis().SetTitle("#bar{b}") # rotate this. Maybe with ttext or tlatex. Don't set title just place latex or text at correct position.
#mg.GetYaxis().SetTitleFont(61)
mg.GetYaxis().SetTitle("#it{#bar{#Beta}}")
#mg.GetYaxis().SetTitleFont(61)
mg.GetYaxis().SetTitleSize(0.04)
mg.GetYaxis().SetTitleOffset(1.2) # This doesn't work when ymin=ymax=0
mg.GetXaxis().SetTitle("ts (ns)")
#mg.GetXaxis().SetTitleSize(0.04)
if (ymin == ymax):
lymin = can.GetUymin()
lymax = can.GetUymax()
else:
mg.GetYaxis().SetRangeUser(ymin,ymax)
lymin = ymin
lymax = ymax
xline = TLine(can.GetUxmin(),0,can.GetUxmax(),0)
xline.SetLineColor(kBlack)
xline.SetLineStyle(1)
yline = TLine(0,lymin,0,lymax)
yline.SetLineColor(kBlack)
yline.SetLineStyle(1)
l1.Draw("SAME")
xline.Draw("SAME")
yline.Draw("SAME")
yTitle = TLatex()
yTitle.SetNDC()
yTitle.SetTextAngle(0)
yTitle.SetTextColor(kBlack)
yTitle.SetTextFont(53) #63
yTitle.SetTextAlign(11)
yTitle.SetTextSize(26) #22
#yTitle.DrawLatex(0.02,0.87,"#bar{b}") #0.8625
#yTitle.SetTextFont(53)
ER = ER_Dict(min_eta)
save_title = "/afs/cern.ch/work/a/atishelm/CMSSW_9_0_1/src/ECAL_Weights/Plot/bin/tmp/ABvsts_" + ER + "_" + WT + "_" + PD
Save_Title_root = save_title + ".root"
Save_Title_pdf = save_title + ".pdf"
Save_Title_png = save_title + ".png"
#print'save title = ',save_title
#print'Save_Title_pdf = ',Save_Title_pdf
mg.SaveAs(Save_Title_root)
can.SaveAs(Save_Title_pdf)
can.SaveAs(Save_Title_png)
#mg.Delete()
#gPad.Clear()
i += 1
#os.system('evince ' + Save_Title_pdf)
#os.system('scp ' + Save_Title + ' ${ssh%% *}/home/abe/Documents/Papers/Weights/Images')
# Should create function for all of this code that's also in SameCan.py
print'I must have been in a coma, because I\'m out of the loop'
|
from uuid import uuid4
from django.db import models
from django_paranoid.models import ParanoidModel
class Section(ParanoidModel):
uuid = models.UUIDField(default=uuid4, editable=False, primary_key=True)
name = models.CharField(max_length=50, default='NOT INCLUDED')
icon = models.CharField(max_length=50, default='far fa-folder')
description = models.TextField(default='NOT INCLUDED')
def __str__(self):
return self.name
|
import random
import bisect
import numpy as np
import pandas as pd
#FROM THESIS
#'Create Cumulative Distribution'
def cdf(weights):
total=sum(weights); result=[]; cumsum=0
for w in weights:
cumsum+=w
result.append(cumsum/total)
return result
#FROM THESIS
def assignActivityPattern(distribution):
'Revise Traveler Type, In the event of no school assigned (incredibly fringe population < 0.001%)'
"""
if person[len(person) - 3] == 'NA' and (travelerType == 3 or travelerType == 4 or travelerType == 2 or travelerType == 1):
travelerType = 6
"""
dist = distribution #allDistributions[travelerType]
weights = cdf(dist)
split = random.random()
idx = bisect.bisect(weights, split)
return idx
x = 0.06768567336390681 #TODO from collectif ATTENTION pourcentage !!!!!
i = 0.225 - x #29 % ATTENTION au divisé par 100
a = 1 - i
"""
all_distributions = {0: [0, 1, 0, 0, 0, 0, 0, 0], 1: [0.05, 0.175, 0.25, 0.2, 0, 0.2, 0.075, 0.05], 2: [0.025, 0.15, 0.2, 0.275, 0, 0.2, 0.1, 0.05],
3: [0.025, 0.05, 0.2, 0.225, 0.05, 0.25, 0.15, 0.05], 4: [0.3, 0.3, 0.2, 0.1, 0, 0.04, 0.04, 0.02], 5: [0.05, 0.075, 0.25, 0.225, 0, 0.15, 0.15, 0.1],
6: [0.01, 0.05, 0.1, 0.15, 0.15, 0.25, 0.2, 0.09], 7: [0.1, 0.3, 0.2, 0.15, 0, 0.1, 0.1, 0.05], 8: [1, 0, 0, 0, 0, 0, 0, 0], 9: [1, 0, 0, 0, 0, 0, 0, 0],
10: [1, 0, 0, 0, 0, 0, 0, 0]}
"""
all_distributions = {"immobile": [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
"worker": [i, a*0.575, a*0.139, a*0.085, a*0.037, a*0.036, a*0.026, a*0.024, a*0.015, a*0.013, a*0.011, a*0.011, a*0.009, a*0.009, a*0.007, a*0.002, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
"activity": [i, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, a*0.51, a*0.107, a*0.103, a*0.069, a*0.067, a*0.037, a*0.02, a*0.016, a*0.015, a*0.014, a*0.014, a*0.01, a*0.006, a*0.005, a*0.005, a*0.002]}
#worker_from_out = [i, a*0.773, a*0.157, 0, 0, a*0.045, 0, a*0.024, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
#all_pers = pd.read_csv('all_workplace.csv') #TODO load
all_pers = pd.read_csv('foreign_tourists_workplace.csv')
print(all_pers)
all_pers["TripChainType"]=np.zeros(len(all_pers))
for pers in all_pers.index: #TODO adapt
print(pers)
worker_id = all_pers.loc[pers, "WorkerID"]
if worker_id == 8 or worker_id == 9 or worker_id == 10:
chain_key = "immobile"
elif worker_id == 0 or worker_id == 1 or worker_id == 2 or worker_id == 3 or worker_id == 4 or worker_id == 5 or worker_id == 6:
chain_key = "worker"
elif worker_id == 7 or worker_id == 11:
chain_key = "activity"
else:
print(worker_id)
errorWorkerID
dist = all_distributions[chain_key]
TripChainType = assignActivityPattern(dist)
all_pers.loc[pers, "TripChainType"]=TripChainType
print(all_pers)
all_pers.to_csv("all_pers_tripchaintype.csv")
|
# Diffk
# Given an array 'A' of sorted integers and another non negative integer k, find if there exists 2 indices i and j such that A[i] - A[j] = k, i != j.
# Example:
# Input :
# A : [1 3 5]
# k : 4
# Output : YES as 5 - 1 = 4
# Return 0 / 1 ( 0 for false, 1 for true ) for this problem
# Try doing this in less than linear space complexity.
class Solution:
# @param A : list of integers
# @param B : integer
# @return an integer
def diffPossible(self, A, B):
i = 0
j = 1
while i<j and j<len(A):
diff = A[j]-A[i]
if diff > B:
i+=1
elif diff < B:
j+=1
elif diff == B:
return 1
if i == j:
j+=1
return 0 |
from django.conf.urls import url, include
from django.views.generic.base import RedirectView
from rest_framework.urlpatterns import format_suffix_patterns
from django.views.generic.base import RedirectView
from rest_framework_jwt.views import obtain_jwt_token
from . import views
app_name = 'manager'
urlpatterns = [
# url(r'^/$', views.ProjectDetail.as_view()),
url(r'^projects/$', views.ProjectList.as_view()),
url(r'^projects/(?P<pk>[0-9]+)/$', views.ProjectDetail.as_view()),
url(r'^projects/(?P<username>[a-z0-9]+)/$', views.ProjectDetail.as_view()),
# url(r'^developers/$', views.developer_list),
url(r'^developers/(?P<user_id>[a-z0-9]+)', views.DeveloperDetail.as_view()),
url(r'^leads/$', views.Leads.as_view()),
url(r'^devmembership/$', views.DevMembership.as_view()),
url(r'^devmembership/(?P<project_id>[0-9])+/$', views.DevMembership.as_view()),
url(r'^devmembershipdevid/(?P<developer_id>[0-9])+/$', views.DevMembership.as_view()),
url(r'^users/$', views.Users.as_view()),
url(r'^users/(?P<id>[0-9]+)$', views.SingleUser.as_view()),
url(r'^users/(?P<username>[a-z]+)$', views.SingleUser.as_view()),
url(r'^clients/(?P<id>[0-9]+)', views.Clients.as_view()),
url(r'^clients/$', views.Clients.as_view()),
url(r'^billables/(?P<id>[0-9]+)', views.Billables.as_view()),
url(r'^billables/$', views.Billables.as_view()),
url(r'^devbillables/(?P<dev_id>[0-9]+)/$', views.DevBillableList.as_view()),
url(r'^payments/$', views.Payment.as_view()),
url(r'^payments/(?P<id>[0-9]+)/$', views.Payment.as_view()),
url(r'^projpayments/(?P<project_id>[0-9]+)/$', views.Payments.as_view()),
url(r'^accounts/profile/$', RedirectView.as_view(url='<url_to_home_view>', permanent=False), name='index'),
url(r'^api-token-auth/', obtain_jwt_token),
]
urlpatterns += [
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
]
urlpatterns = format_suffix_patterns(urlpatterns) |
import scrapy
from scrapy import *
import os
import sys
import hashlib
#from CevaShipmentTrackItem.items import *
#import pdb;pdb.set_trace()
print(sys.path)
import datetime
sys.path.insert(0,os.getcwd()+'/xpath')
import xpath
class CEVA_shipment_track(Spider):
name="ceva_shipment"
start_urls=["https://etracking.cevalogistics.com/eTracking.aspx?uid="]
def __init__(self):
self.input_array=[]
def parse(self,response):
input_id=str(input("Enter the bill number:"))
self.input_array.append(input_id)
#import pdb;pdb.set_trace()
self.viewstate=response.xpath(xpath.viewstate_xpath).extract()[0]
self.viewstategenerator=''.join(response.xpath(xpath.viewstategenerator_xpath).extract())
cookies=response.headers.get('Set-Cookie').decode('utf-8').split(";")[0]
headers = {
'Connection': 'keep-alive',
'Cache-Control': 'max-age=0',
'Origin': 'https://etracking.cevalogistics.com',
'Upgrade-Insecure-Requests': '1',
'Content-Type': 'application/x-www-form-urlencoded',
'Sec-Fetch-User': '?1',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',
'Sec-Fetch-Site': 'same-origin',
'Sec-Fetch-Mode': 'navigate',
'Referer': self.start_urls[0],
'Accept-Encoding': 'gzip, deflate, br',
'Accept-Language': 'en-US,en;q=0.9,hi;q=0.8,la;q=0.7',
'Set-Cookie':cookies,
}
for _id in self.input_array:
data = {
'__EVENTTARGET': '',
'__EVENTARGUMENT': '',
'__LASTFOCUS': '',
'__VIEWSTATE': self.viewstate,
'__VIEWSTATEGENERATOR': self.viewstategenerator,
'ModeList': '1',
'lstbasics': 'House Waybill',
'txtairWayBillNumber': _id,
'btnSearch': 'Track'
}
yield FormRequest(url=response.url,method='POST',headers=headers,formdata=data
,callback=self.extract_data,dont_filter=True)
def extract_data(self,response):
import pdb;pdb.set_trace()
print (response.body)
"""
ceva,EC90008855
ceva,EC90009003
ceva,EC90009014
ceva,EC90008803
ceva,EC90009210
ceva,EC90009356
""" |
#!/home/dippouch/bin/python
print 'Content-type: text/html\n'
##import cgi, os
##try: from data import data
##except: data = {}
##form = cgi.FieldStorage()
##answer = form.has_key('vote') and form['vote'].value or None
##if answer != None:
## list = data.get(os.environ['REMOTE_ADDR'], [])
## list.append(answer)
## data[os.environ['REMOTE_ADDR']] = list
## file = open('data.py', 'w')
## file.write('data = %s\n' % `data`)
## file.close()
print (
"""
<HEAD>
<TITLE>DP F1999R: Paradox Resolved</TITLE>
</HEAD>
<BODY bgcolor=white>
<A HREF="../.."><IMG align=left SRC="../../Common/DPbutton.gif" border=0></A>
<A HREF=".."><IMG align=right SRC="../../Common/toF1999R.gif" border=0></A>
<BR clear=both><HR>
<H1 align=center>Paradox Resolved!</H1>
<H2 align=center><i>By Simon Szykman and Manus Hand</i></h2>
<HR>
<H3>Thanks Again!</H3>
Manus (who proposes rule 1) and Simon (who proposes rule 2) wish to
thank you for your responses. Simon also has a geeky postscript to
his proposal. Feel free to <a href=postscript.html>read it here</a>
if you are interested in going off on a slight (yet related) tangent.
<P>
<blockquote>
<i>By the way, you can see Manus's rule in action (and yes, Simon's rule is
implemented too as an option called <tt>SAFE_CONVOYS</tt>) at the
<a href=../Hand/dpjudge.html>DPjudge</a>, the Pouch's Web-based Diplomacy
adjudicator that is unveiled elsewhere in this issue.
</i></blockquote>
<P>
<table>
<tr valign="bottom">
<td><A HREF="mailto:manus@diplom.org"><IMG src="../../Common/letter.gif" border="0"></A>
</td>
<td>
<strong>Manus Hand<br>
(manus@diplom.org)</strong>
</td>
</tr>
<tr valign="bottom">
<td><A HREF="mailto:simon@diplom.org"><IMG src="../../Common/letter.gif" border="0"></A>
</td>
<td>
<strong>Simon Szykman<br>
(simon@diplom.org)</strong>
</td>
</tr>
</table>
<p>
<i>If you wish to e-mail feedback on this article to the author, and clicking
on the envelope above does not work for you, feel free to use the
<A HREF="../Common/DearDP.html">
"<b>Dear DP...</b>"</A> mail interface.</i>
<p>
<HR>
<A HREF="../.."><IMG align=left SRC="../../Common/DPbutton.gif" border=0></A>
<A HREF=".."><IMG align=right SRC="../../Common/toF1999R.gif" border=0></A>
<BR clear=both>
</BODY>
</HTML>
""")
|
"""
Matching polynomials for a sequence of random regular bipartite graphs.
Sequence of regular bipartite graphs constructed in the following way.
Let $G_0$ be a cycle with $k$ vertices, with $k$ even.
Add another cycle with $k$ vertices;
the odd (even) vertices of this cycle are linked respectively
to the even (odd) vertices of the
previous cycle in a random way, obtaining $G_1$;
continue adding cycles in this way, obtaining the sequence ${G_i}$.
The sequence of the corresponding regular bipartite graphs
is obtained linking the vertices of the first and last cycle.
"""
import sys
sys.path.insert(0,'../src')
from copy import deepcopy
from hobj import Hobj
from densearith import dup_add
from random import randint, seed
from active_nodes import d_from_links
from itertools import permutations, product
from domains import ZZ
from compatibility import itervalues
def sum_values(p, K):
"""
sum the values in ``p``
"""
nv = []
for v in itervalues(p):
nv = dup_add(nv, v, K)
nv.reverse()
return nv
def rand_reg6_gen():
K = ZZ
p = {0: [K.one]}
hb = Hobj()
# first vertical line
for i in range(6):
p = hb.iadd_object(p, 1, [i, (i + 1)%6], [], K)
n = 6
# vector of allowed permutations
v = list(product([[0,2,4], [0,4,2]], list(permutations([1,3,5]))))
v = [[i0,i3,i1,i4,i2,i5] for (i0,i1,i2),(i3,i4,i5) in v]
N = 10000
for ii in range(N):
# add horizontal lines of a strip
#sys.stderr.write('ii=%d\n' %ii)
for i in range(6):
if ii == 0:
p = hb.iadd_object(p, 1, [n - 6 + i, n + i], [], K)
else:
p = hb.iadd_object(p, 1, [n - 6 + i, n + i], [n - 6 + i], K)
# add a random vertical line
a = v[randint(0,len(v) - 1)]
#a = list(range(6))
for i in range(6):
p = hb.iadd_object(p, 1, [n + a[i], n + a[(i + 1)%6]], [], K)
n += 6
n1 = n // 6
if n1 == 2 or n1 % 2 == 1:
continue
# closure
# it is not necessary to copy `p` since `free` is not empty in the
# first call of iadd_object
p2 = p
hb2 = deepcopy(hb)
for i in range(6):
p2 = hb2.iadd_object(p2, 1, [i, n - 6 + i], [i, n - 6 + i], K)
assert len(p2) == 1
nv = sum_values(p2, K)
assert len(hb2.links) == len(set(hb2.links))
d = d_from_links(hb2.links)
yield n1, dict(d), nv
if __name__ == '__main__':
try:
N = int(sys.argv[1])
except:
print('prog N')
sys.exit()
print('rand_reg6:')
for n1, d, nv in rand_reg6_gen():
if n1 > N:
break
print('n1=%d sum(nv)=%s' %(n1, sum(nv)))
|
import unittest
from day4 import *
class Day4Tests(unittest.TestCase):
test_passport = {
"byr": 100,
"iyr": 100,
"eyr": 100,
"hgt": 100,
"hcl": 100,
"ecl": 100,
"pid": 100
}
def test_passport_is_valid_part1(self):
for key in self.test_passport:
bad_passport = self.test_passport.copy()
bad_passport.pop(key)
self.assertFalse(passport_is_valid_p1(bad_passport))
self.assertTrue(passport_is_valid_p1(self.test_passport))
def test_birth_year(self):
self.assertFalse(byr_is_valid("2003"))
self.assertTrue(byr_is_valid("2000"))
def test_issue_year(self):
self.assertFalse(iyr_is_valid("2009"))
self.assertTrue(iyr_is_valid("2015"))
def test_expire_year(self):
self.assertFalse(eyr_is_valid("2019"))
self.assertTrue(eyr_is_valid("2030"))
def test_field_height(self):
self.assertFalse(hgt_is_valid("160in"))
self.assertTrue(hgt_is_valid("160cm"))
self.assertTrue(hgt_is_valid("60in"))
self.assertFalse(hgt_is_valid("60cm"))
self.assertFalse(hgt_is_valid("60"))
def test_field_hair_color(self):
self.assertTrue(hcl_is_valid("#123abc"))
self.assertFalse(hcl_is_valid("#123abz"))
self.assertFalse(hcl_is_valid("123abc"))
def test_field_eye_color(self):
eye_colors = [
"amb",
"blu",
"brn",
"gry",
"grn",
"hzl",
"oth"
]
for color in eye_colors:
self.assertTrue(ecl_is_valid(color))
self.assertFalse(ecl_is_valid("foo"))
def test_field_pid(self):
# their test cases
self.assertTrue(pid_is_valid("000000001"))
self.assertFalse(pid_is_valid("0123456789"))
# added test cases
self.assertFalse(pid_is_valid("foobar123"))
self.assertFalse(pid_is_valid("012345"))
def test_passport_is_valid_part2(self):
for passport in parse_passports("../inputs/day4_invalid_passports.txt"):
self.assertFalse(passport_is_valid_p2(passport), "passport invalid" + str(passport))
def test_part1_example(self):
self.assertEqual(2, part1("../inputs/day4_example.txt"))
def test_part1(self):
self.assertEqual(208, part1("../inputs/day4.txt"))
def test_part2_example(self):
self.assertEqual(2, part2("../inputs/day4_example.txt"))
def test_part2(self):
self.assertEqual(167, part2("../inputs/day4.txt"))
if __name__ == '__main__':
unittest.main()
|
# coding= utf-8
"""
=====================================================================
Main UI for VI - Vehicle Performance Test&Validation
=====================================================================
Open Souce at https://github.com/huisedetest/VI_Project_Main
Author: SAIC VP Team
>
"""
from PyQt5.QtWidgets import *
from PyQt5 import QtCore, QtGui, QtWidgets
from test_ui import Ui_MainWindow # 界面与逻辑分离
from Calculation_Functions import * # 算法逻辑
import sys
import warnings
warnings.filterwarnings("ignore")
class LoginDlg(QMainWindow, Ui_MainWindow):
"""
==================
Main UI Dialogue
==================
__author__ = 'Lu chao'
__revised__ = 20171012
>
"""
def __init__(self, parent=None):
super(LoginDlg, self).__init__(parent)
self.setupUi(self)
self.menu_InputData.triggered.connect(self.open_data) # 继承图形界面的主菜单Menu_plot的QAction,绑定回调函数
self.menu_CalData.triggered.connect(self.cal_data)
self.open_DBC.clicked.connect(self.push_DBC_Index_file)
self.open_CAR.clicked.connect(self.push_CAR_Index_file)
self.open_DRIVER.clicked.connect(self.push_Driver_Index_file)
self.pushButton_2.clicked.connect(self.graphicview_show)
self.DatatableView.clicked.connect(self.graphicview_show)
self.filepath_fulldata = './AS24_predict_data.csv'
self.filepath_DBC = './DBC_index.csv' # 默认值
self.filepath_Car = './Car_index.csv'
self.filepath_Driver = './Driver_index.csv'
# -------------------------------- 回调函数------------------------------------------
def open_data(self):
"""
Callback function of menu 'InputData' clicked
Transfer raw date to organized form, using Function 'Main_process(Process_type=input_data)'
:param : -
:return: -
__author__ = 'Lu chao'
__revised__ = 20171012
"""
self.statusbar.showMessage('测试数据导入中……')
filepath = QFileDialog.getExistingDirectory(self)
filepath_full = filepath + '/*.txt'
self.main_process_thread = Main_process(filepath_full, self.filepath_DBC, self.filepath_Car,
self.filepath_Driver, Process_type='input_data')
self.main_process_thread.Message_Signal.connect(self.thread_message) # 传递参数不用写出来,对应好接口函数即可
self.main_process_thread.Message_Finish.connect(self.thread_message)
self.main_process_thread.start()
def cal_data(self):
"""
Callback function of menu 'CalData' clicked
Calculate the organized data , using Function 'Main_process(Process_type=cal_data)',
and save the result to .csv data, also save the trajectory pictures in ./Image/
:param : -
:return: -
__author__ = 'Lu chao'
__revised__ = 20171012
"""
self.statusbar.showMessage('计算中……')
self.main_process_thread = Main_process(self.filepath_fulldata, Save_name=self.plainTextEdit_4.toPlainText(),
Process_type='cal_data')
self.main_process_thread.Message_Signal.connect(self.thread_message)
self.main_process_thread.Message_Data.connect(self.datatableview_show)
self.main_process_thread.start()
def thread_message(self, mes_str):
"""
Function of showing message on StatusBar
:param : mes_str message to show (str)
:return: -
__author__ = 'Lu chao'
__revised__ = 20171012
"""
self.statusbar.showMessage(mes_str)
self.filepath_fulldata = './' + mes_str[6::]
def datatableview_show(self, data_list):
"""
Function of showing calculation results in data_table
:param : data_list List of result data to show (list)
:return: -
__author__ = 'Lu chao'
__revised__ = 20171012
"""
self.model = QtGui.QStandardItemModel(self.DatatableView)
# self.model.setHeaderData(1, QtCore.Qt.Horizontal, QtCore.QVariant('HH'))
# self.model.setHeaderData(2, QtCore.Qt.Horizontal, QtCore.QVariant("FF"))
for i in range(data_list.__len__()):
for j in range(data_list[0].__len__()):
self.model.setItem(i, j, QtGui.QStandardItem(data_list[i][j]))
self.DatatableView.setModel(self.model)
self.DatatableView.resizeColumnsToContents()
def graphicview_show(self):
"""
Function of showing the trajectory of the test data in graphic_view,
we choose the test data which was clicked by user in data_table and find the real index of it,
the routine pictures are stored in ./Image/, which have already been prepared using function
'Main_process(Process_type=cal_data)'
:param : -
:return: -
__author__ = 'Lu chao'
__revised__ = 20171012
"""
Current_index = self.DatatableView.currentIndex()
Dri_ID = self.model.data(self.model.index(Current_index.row(), 0))
Date = self.model.data(self.model.index(Current_index.row(), 1))
Time = self.model.data(self.model.index(Current_index.row(), 2))
self.scene = QtWidgets.QGraphicsScene()
try:
self.routine_pic = QtGui.QPixmap('./RoutinePic/AS24_'+str(int(float(Dri_ID)))+'_'+str(int(float(Date))) +
'_'+str(int(float(Time)))+'.png') # 车型问题没定义好 待解决 2017/9/30
self.scene.addPixmap(self.routine_pic)
self.graphicsView.setScene(self.scene)
except:
pass
def accept(self):
# QMessageBox.warning(self, 'chenggong', 'heh', QMessageBox.Yes)
self.pushButton.setHidden(True)
def messlistview(self):
# self.MessagelistView.setWindowTitle('显示')
# model = QtGui.QStandardItemModel(self.MessagelistView)
# self.MessagelistView.setModel(model)
# self.MessagelistView.show()
# message_item = QtGui.QStandardItem(mes[0][0]) # 只接受string
# model.appendRow(message_item)
pass
def push_DBC_Index_file(self):
"""
Callback function of Button 'file_path_DBC' clicked
save the DBC file location you want to refer to
:param : -
:return: -
__author__ = 'Lu chao'
__revised__ = 20171012
"""
filepath = QFileDialog.getOpenFileName(self)
self.plainTextEdit.setPlainText(filepath[0])
self.filepath_DBC = filepath[0]
def push_CAR_Index_file(self):
"""
Callback function of Button 'file_path_Car' clicked
save the Car data file location you want to refer to
:param : -
:return: -
__author__ = 'Lu chao'
__revised__ = 20171012
"""
filepath = QFileDialog.getOpenFileName(self)
self.plainTextEdit_2.setPlainText(filepath[0])
self.filepath_Car = filepath[0]
def push_Driver_Index_file(self):
"""
Callback function of Button 'file_path_Driver' clicked
save the Driver data file location you want to refer to
:param : -
:return: -
__author__ = 'Lu chao'
__revised__ = 20171012
"""
filepath = QFileDialog.getOpenFileName(self)
self.plainTextEdit_3.setPlainText(filepath[0])
self.filepath_Driver = filepath[0]
class Main_process(QtCore.QThread): # 务必不要继承主窗口,并在线程里面更改主窗口的界面,会莫名其妙的出问题
"""
=======================
Main Processing Thread
=======================
__author__ = 'Lu chao'
__revised__ = 20171012
>
"""
Message_Signal = QtCore.pyqtSignal(str)
Message_Finish = QtCore.pyqtSignal(str)
Message_Data = QtCore.pyqtSignal(list)
def __init__(self, filepath, DBC_path='', Car_path='', Driver_path='', Save_name='', Process_type='input_data'):
super(Main_process, self).__init__()
self.file_path = filepath
self.DBC_path = DBC_path
self.Car_path = Car_path
self.Driver_path = Driver_path
self.Save_name = Save_name
self.Process_type = Process_type
self.output_data = []
def run(self): # 重写进程函数
"""
Main thread running function
Cases: input_data
cal_data
.......
:param : -
:return: -
__author__ = 'Lu chao'
__revised__ = 20171010
"""
if self.Process_type == 'input_data':
message = read_file(self.file_path, self.DBC_path, self.Car_path, self.Driver_path)
k = 1
while k:
try:
mes = message.__next__() # generator [消息,总任务数]
# self.progressBar.setValue(int(k / mes[1]) * 100)
# self.progressBar.show()
# self.statusbar.showMessage('测试数据导入' + str(k))
self.Message_Signal.emit("测试数据 " + mes[0][0] + "导入中……")
k = k + 1
except:
self.Message_Signal.emit("导入完成……")
k = 0
try:
self.Message_Finish.emit("存储文件名:" + mes[2])
except:
self.Message_Finish.emit("导入失败")
elif self.Process_type == 'cal_data':
self.out_putdata = data_process(self.file_path, self.Save_name)
self.Message_Signal.emit("计算完成!")
self.Message_Data.emit(self.out_putdata)
if __name__ == '__main__':
app = QApplication(sys.argv)
dlg = LoginDlg()
dlg.show()
sys.exit(app.exec())
|
# coding: utf-8
# References: Bare bones fireworks algorithm. by Junzhi Li (ljz@pku.edu.cn)
# https://www.sciencedirect.com/science/article/pii/S1568494617306609
import numpy as np
from numpy import *
import matplotlib.pyplot as plt
class BBFWA:
def __init__(self,dim,maxeval,n,Cr,Ca,mapping_rule,plot_episode,run_episode):
self.dim = dim
self.maxeval = maxeval
self.n = n
self.Cr = Cr
self.Ca = Ca
self.mapping_rule = mapping_rule
self.plot_episode = plot_episode
self.run_episode = run_episode
# sphere function
def sphere(self,x,r):
return sum((x - r) * (x - r), 0)
def cigar(self,individual,r):
individual = individual - r
return individual[0] ** 2 + 1e6 * sum(gene * gene for gene in individual)
def discus(self,individual,r):
individual = individual - r
return 1e6 * (individual[0] ** 2) + sum(gene * gene for gene in individual)
def schaffer(self,individual, r):
individual = individual - r
return sum(((x ** 2 + x1 ** 2) ** 0.25 * ((sin(50 * (x ** 2 + x1 ** 2) ** 0.1)) ** 2 + 1.0)
for x, x1 in zip(individual[:-1], individual[1:])), 0)
def rosenbrock(self,individual, r):
individual = individual - r
return sum(100 * (x * x - y) ** 2 + (1. - x) ** 2 \
for x, y in zip(individual[:-1], individual[1:]))
def schwefel(self,individual,r): # ub = 500,lb = -500 two places
individual = individual - r
N = len(individual)
return 418.9828872724339 * N - sum(x * sin(sqrt(abs(x))) for x in individual)
def step(self,x,r):
x = x - r
return sum((floor(x + 0.5)) ** 2)
def optimal(self,r):
lb = -100 * ones((self.dim,1)) #将其变为30维
ub = 100 * ones((self.dim,1))
A = ub - lb
x = random.rand(self.dim, 1) * (ub - lb) + lb
fx = self.cigar(x,r)
result = []
result.append(fx[0])
eval = 1
while eval < self.maxeval:
s = (random.rand(self.dim,self.n) * 2 - 1) * tile(A,(1,self.n)) + tile(x,(1,self.n))
# boundary handling
if self.mapping_rule == 'delete':
temn = self.n
j = 0
for i in range(self.dim):
while j < temn:
if s[i,j] > ub[0] or s[i,j] < lb[0] :
s = delete(s,j,1) # 删除第j列
temn -= 1
j -= 1
j += 1
else:
for i in range(self.dim):
index = logical_or(s[i, :] > ub[i],s[i, :] < lb[i]) # print(len(index),len(ub[i])) 300 * 1 ub[i] 100
ubdex = s[i, :] > ub[i]
lbdex = s[i, :] < lb[i]
if self.mapping_rule == 'random':
s[i, index] = random.rand(1, sum(index)) * (ub[i] - lb[i]) + lb[i]
if self.mapping_rule == 'origin':
s[i, index] = abs(s[i, index]) % (ub[i] - lb[i]) + lb[i]
if self.mapping_rule == 'boundary':
s[i, ubdex] = ub[i]
s[i, lbdex] = lb[i]
if self.mapping_rule == 'mirror':
s[i, ubdex] = ub[i] - (s[i, ubdex] - ub[i])
s[i, lbdex] = lb[i] + (lb[i] - s[i, lbdex])
if self.mapping_rule == 'nothing':
pass
if self.mapping_rule == 'mixture':
if eval < 3000:
s[i, index] = random.rand(1, sum(index)) * (ub[i] - lb[i]) + lb[i]
else:
s[i, ubdex] = ub[i] - (s[i, ubdex] - ub[i])
s[i, lbdex] = lb[i] + (lb[i] - s[i, lbdex])
fs = ones((len(s[0]))) #300 * 1
for i in range(len(s[0])): # 对每个点计算 x - r,一列为一个点
tems = s[:, i]
tems = tems.reshape(self.dim, 1) # 转为列向量
fs[i] = self.cigar(tems, r)
eval = eval + self.n
if min(fs) < fx:
x = s[:, argmin(fs)].reshape(self.dim, 1) # x:30*1
fx = min(fs.tolist())
A = A * self.Ca
else:
A = A * self.Cr
if self.plot_episode == 1001:
if eval <= 30000: # plot_episode change to 502 存前500次的结果
result.append(fx)
else:
result.append(fx) # 存每轮迭代结果
print(fx)
return fx,result
|
from django.db import models
from django.urls import reverse
from datetime import datetime
class Key(models.Model):
key = models.CharField(max_length=15)
# keys = [
# 'Ab Major', 'A Major', 'Bb Major', 'B Major', 'C Major', 'Db Major', 'D Major', 'Eb Major', 'E Major', 'F Major', 'Gb Major', 'G Major',
# 'A Minor', 'Bb Minor', 'B Minor', 'C Minor', 'C# Minor', 'D Minor', 'Eb Minor', 'E Minor', 'F Minor', 'F# Minor', 'G Minor', 'G# Minor'
# ]
def __str__(self):
return self.key
#
class Session(models.Model):
# %Y-%M-%D
title = models.CharField(max_length=255)
date = models.CharField(max_length=255, blank=True)
# date = models.DateField(blank=True)
location = models.TextField(blank=True)
personnel = models.TextField(blank=True)
# album_release = models.ForeignKey(Album, on_delete=models.CASCADE)
album_releases = models.TextField(blank=True)
def __str__(self):
return f"{self.title} - {self.date}"
def get_absolute_url(self):
return reverse('blog:list_session')
class SongForm(models.Model):
song_form = models.CharField(max_length=255, unique=True)
def __str__(self):
return self.song_form
def get_absolute_url(self):
return reverse('blog:list_songform')
class Song(models.Model):
title = models.CharField(max_length=255, unique=True)
song_form = models.ForeignKey(SongForm, on_delete=models.PROTECT)
key = models.ForeignKey(Key, on_delete=models.PROTECT)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('blog:list_song')
#
# class Album(models.Model):
# title = models.TextField()
# release_date = models.DateField()
class Version(models.Model): # New version
song = models.ForeignKey(Song, on_delete=models.PROTECT, blank=True, null=True)
session = models.ForeignKey(Session, on_delete=models.PROTECT)
session_song_number = models.CharField(max_length=255, blank=True, null=True)
releases = models.CharField(max_length=2000, default="")
version_title = models.CharField(max_length=255)
notes = models.TextField(blank=True)
transcription_pdf = models.FileField(upload_to='transcriptions_pdf', blank=True)
sibelius_file = models.FileField(upload_to='sibelius_files', blank=True)
sound_file = models.FileField(upload_to='sound_files', blank=True)
youtube_link = models.URLField(blank=True)
# midi_file = models.URLField(blank=True)
# where to buy
# could send profits to charlie parker estate
def __str__(self):
return f"{self.version_title} | Date: {self.session.date}"
def get_absolute_url(self):
return reverse('blog:list_version')
# class Version(models.Model): # old version
# song = models.ForeignKey(Song, on_delete=models.PROTECT)
# session = models.ForeignKey(Session, on_delete=models.PROTECT)
# version_title = models.CharField(max_length=255)
# notes = models.TextField(blank=True)
# transcription_pdf = models.FileField(upload_to='transcriptions_pdf', blank=True)
# sibelius_file = models.FileField(upload_to='sibelius_files', blank=True)
# youtube_link = models.URLField(blank=True)
# # midi_file = models.URLField(blank=True)
# # where to buy
# # could send profits to charlie parker estate
#
# def __str__(self):
# return f"Version: {self.version_title} Date: {self.session}"
#
# def get_absolute_url(self):
# return reverse('blog:list_version')
# -----------------------------------------------------------------------
# class Track(models.Model):
# title = models.ForeignKey(required=True, on_delete=models.CASCADE)
# song_form = models.ForeignKey(on_delete=models.CASCADE)
# key_signature = models.ForeignKey(on_delete=models.CASCADE)
# location = models.CharField(max_length=200)
# date = models.DateField(required=True) # python datetime.date
# # duration = models.DurationField()
# personnel = models.TextArea()
# tempo_choices = [
# ("b", "Ballad"),
# ("m", "Medium"),
# ("mu", "Medium Up"),
# ("u", "Up"),
# ("f", "Fast"),
# ]
# tempo = models.CharField(max_length=2, choices=tempo_choices, default="Medium")
# transcription_upload = models.FileField(upload_to='transcriptions/') # file will be uploaded to MEDIA_ROOT/uploads
#
# def get_absolute_url(self):
# # once done creating post (after hitting publication)
# # go to post_detail, using primary key of post just created
# return reverse("post_detail",kwargs={'pk':self.pk})
#
# def __str__(self):
# return self.title, self.date
#
#
# from django.db import models
# from django.utils import timezone
# from django.urls import reverse
#
# # Create your models here.
# class Post(models.Model):
# author = models.ForeignKey('auth.User',on_delete=models.CASCADE)
# title = models.CharField(max_length=200)
# text = models.TextField()
# create_date = models.DateTimeField(default=timezone.now)
# published_date = models.DateTimeField(blank=True,null=True)
#
# def publish(self):
# self.published_date = timezone.now()
# self.save()
#
# def approve_comments(self):
# return self.comments.filter(approved_comment=True)
#
# def get_absolute_url(self):
# # once done creating post (after hitting publication)
# # go to post_detail, using primary key of post just created
# return reverse("post_detail",kwargs={'pk':self.pk})
#
# def __str__(self):
# return self.title
|
'''
Owner - Rawal Shree
Email - rawalshreepal000@gmail.com
Github - https://github.com/rawalshree
'''
from caesar import *
from hillCipher import *
from rowTransposition import *
from railfence import *
from vigenre import *
from playfair import *
from monoalphabetic import *
from threerotorenigma import *
import sys
cc = Caesar()
rt = RowTransposition()
rf = Railfence()
vg = Vigenre()
pf = PlayFair()
mc = Monoalphabetic()
hc = HillCipher()
tre = ThreeRotorEnigma()
def cipher(cipher_name, secret_key, enc_dec, input_file, output_file):
intext = ""
outtext = ""
print("The cipher name is :", cipher_name)
print("The secret key is :", secret_key)
print("The operation is :", enc_dec)
print("The input file is :", input_file)
print("The output file is :", output_file)
options = {"CES" : (cc.setKey, {"ENC" : cc.encryption, "DEC" : cc.decryption}),
"PLF" : (pf.setKey, {"ENC" : pf.encryption, "DEC" : pf.decryption}),
"RFC" : (rf.setKey, {"ENC" : rf.encryption, "DEC" : rf.decryption}),
"VIG" : (vg.setKey, {"ENC" : vg.encryption, "DEC" : vg.decryption}),
"RTS" : (rt.setKey, {"ENC" : rt.encryption, "DEC" : rt.decryption}),
"MAC" : (mc.setKey, {"ENC" : mc.encryption, "DEC" : mc.decryption}),
"HLC" : (hc.setKey, {"ENC" : hc.encryption, "DEC" : hc.decryption}),
"TRE" : (tre.setKey, {"ENC" : tre.encryption, "DEC" : tre.decryption})}
file = open(input_file, "r")
for line in file:
intext += line
file.close()
options[cipher_name][0](secret_key)
outtext = options[cipher_name][1][enc_dec](intext)
file = open(output_file, "w+")
file.write(outtext)
file.close
if __name__ == "__main__":
a = str(sys.argv[1])
b = str(sys.argv[2])
c = str(sys.argv[3])
d = str(sys.argv[4])
e = str(sys.argv[5])
cipher(a, b, c, d, e)
|
nilai =0
a = 0
while True:
jumlah = int(input('Masukkan total bilangan yang akan anda input:'))
for a in range(1,jumlah+1):
nilai2 = int(input('Masukkan bilangan ke-%d :' % a))
nilai += nilai2
mean = nilai / jumlah
print('rata-rata bilangan tersebut = ',mean)
break
|
"""
Copyright John Persano 2017
File name: log.py
Description: A log utility for colored Python printing.
Commit history:
- 03/19/2017: Initial version
"""
class Log:
"""
Log utility that will print messages according to a message level.
"""
class Colors:
"""
Color palette for the Log class.
This should not be used directly.
"""
RED = '\x1b[31m'
YELLOW = '\x1b[33m'
BLUE = '\x1b[34m'
NORMAL = '\x1b[0m'
@staticmethod
def warning(text):
"""
Prints yellow colored text.
:param text: The text to print
:return: None
"""
print(Log.Colors.YELLOW + "WARNING: " + str(text) + Log.Colors.NORMAL)
@staticmethod
def error(text):
"""
Prints red colored text.
:param text: The text to print
:return: None
"""
print(Log.Colors.RED + "ERROR: " + str(text) + Log.Colors.NORMAL)
@staticmethod
def debug(text):
"""
Prints red colored text.
:param text: The text to print
:return: None
"""
print(Log.Colors.BLUE + "DEBUG: " + str(text) + Log.Colors.NORMAL)
@staticmethod
def info(text):
"""
Prints white colored text.
:param text: The text to print
:return: None
"""
print(str(text))
|
if 'ef' not in dir():
execfile('go')
basedir = '/Users/dcollins/scratch/Paper42_NewForcing/r01_test'
if 'frame' not in dir():
frame = 0
for frame in [0,5]:
ds = yt.load('%s/DD%04d/data%04d'%(basedir,frame,frame))
g0 = ds.index.grids[0]
d= g0['density'].v
db=g0['DivB'].v
stat(db,frame)
#v0 = v[0,0,0]
#stat(v-v[0], frame)
#print "v0", v0
#frame+=1
#print yt.ProjectionPlot(ds,0,'x-velocity').save()
|
""" Rest api urls v1 for domain """
from django.conf.urls import url
from rest_framework import routers
from .models.race_data.views import RaceDataViewSet, RaceDataReplayViewSet
from .models.race.views import (RaceViewSet, TournamentRacesViewSet, RaceOnlineViewSet, RaceDoneViewSet,
RaceUpcomingViewSet, OwnRaceViewSet)
from .models.race_type.views import RaceTypeViewSet, OwnRaceTypeViewSet
from .models.sport_type.views import SportTypeViewSet, TournamentInSportType
from .models.track.views import TrackViewSet, OwnTrackViewSet
from .models.tournament.views import TournamentViewSet, OwnTournamentViewSet
from .models.racer.views import RacerViewSet
from .models.projection.views import ProjectionViewSet
from .models.search.views import SearchViewSet
from .models.racer_in_race.views import RacerFinishedRace, RacerRacingRace, RacerUpcomingRace, ParticipantsRaceView
from .models.field_type.views import FieldTypeViewSet
from .models.token.views import AuthTokenView
router = routers.SimpleRouter()
router.register(
r'races/(?P<race_pk>\d+)/data',
RaceDataViewSet,
base_name="racedata",
)
router.register(
r'races/(?P<race_pk>\d+)/replay',
RaceDataReplayViewSet,
base_name="racereplay",
)
router.register(
r'races',
RaceViewSet,
base_name="race",
)
router.register(
r'races/online',
RaceOnlineViewSet,
base_name="online-race",
)
router.register(
r'races/finished',
RaceDoneViewSet,
base_name="finished-race",
)
router.register(
r'races/upcoming',
RaceUpcomingViewSet,
base_name="upcoming-race",
)
router.register(
r'own/races',
OwnRaceViewSet,
base_name="own-race",
)
router.register(
r'race-types',
RaceTypeViewSet,
base_name="racetype",
)
router.register(
r'own/race-types',
OwnRaceTypeViewSet,
base_name="own-racetype",
)
router.register(
r'sport-types',
SportTypeViewSet,
base_name="sporttype",
)
router.register(
r'sport-types/(?P<sport_slug>[-_\w]+)/tournaments',
TournamentInSportType,
base_name="sport-tournaments",
)
router.register(
r'tracks',
TrackViewSet,
base_name="track",
)
router.register(
r'own/tracks',
OwnTrackViewSet,
base_name="own-track",
)
router.register(
r'tournaments',
TournamentViewSet,
base_name="tournament",
)
router.register(
r'own/tournaments',
OwnTournamentViewSet,
base_name="own-tournament",
)
router.register(
r'racers',
RacerViewSet,
base_name="racer",
)
router.register(
r'projections',
ProjectionViewSet,
base_name="projection",
)
router.register(
r'tournaments/(?P<id>[\d]+)/races',
TournamentRacesViewSet,
base_name="tournament-races",
)
router.register(
r'search',
SearchViewSet,
base_name="search",
)
router.register(
r'races/racer/(?P<racer_id>[\d]+)/finished',
RacerFinishedRace,
base_name="races-racer-finished",
)
router.register(
r'races/racer/(?P<racer_id>[\d]+)/active',
RacerRacingRace,
base_name="races-racer-active",
)
router.register(
r'races/racer/(?P<racer_id>[\d]+)/upcoming',
RacerUpcomingRace,
base_name="races-racer-upcoming",
)
router.register(
r'field-types',
FieldTypeViewSet,
base_name="field-types",
)
urlpatterns = router.urls
urlpatterns += [
url(r'^races/(?P<pk>\d+)/participants/$',
view=ParticipantsRaceView.as_view(),
name=ParticipantsRaceView.name
),
url(r'^api-key/$',
view=AuthTokenView.as_view(),
name=AuthTokenView.name
)
]
|
import numpy as np
from scipy import interpolate
import matplotlib.pyplot as plt
data1 = np.loadtxt("y2.dat")
def analytical1(x):
return np.cos(x)/2 + np.exp(-x)*(x/2 + 1/2)
def analytical2(t):
return -(np.exp(t) * np.sin(t) + t) / (2 * np.exp(t))
x = np.arange(0,2,0.01)
fig1 = plt.figure()
fig2 = plt.figure()
fig3 = plt.figure()
ax1 = fig1.add_subplot()
ax2 = fig2.add_subplot()
ax3 = fig3.add_subplot()
ax1.plot(x,data1[:,0], marker = "*",label = 'y(x)')
ax1.plot(x,analytical1(x), label = 'y(x)')
ax1.plot(x,data1[:,1], marker = "*",label = 'y*(x)')
ax1.plot(x,analytical2(x), label = 'y*(x)')
ax1.legend()
ax2.plot(data1[:,0],data1[:,1],color = 'red',lw = 2, label = 'y*(y) phase trajectory')
ax2.legend()
ax3=plt.subplot('121')
ax3.plot(x,data1[:,0]-analytical1(x),label = ' ')
ax3=plt.subplot('122')
ax3.plot(x,data1[:,1]-analytical2(x),label = ' ')
ax3.legend()
|
TOKEN = 'NDQ0NjI2NTM3ODgzNTAwNTY0.Dd_CcQ.ddcRM8iauw9I4VkNgyNUQ3cElEM'
LOOKUP_ALL = 2
LOOKUP_SEASON = 3
SEASONS = {'season3', 'season4'}
INVALID_COMMAND = "**ERROR** Invalid command" |
#!/usr/bin/env python3
"""Calculate Shannon entropies ."""
import numpy as np
def HP(Di, beta):
"""Calculate hp function"""
exponent = np.exp(-Di/beta)
Pi = exponent / exponent.sum()
Hi = -(Pi*np.log2(Pi)).sum()
return Hi, Pi
|
# Author: Jenna Kwon
"""
LU factorization subroutine
input: .dat file containing an input matrix A
Output: A, L, U, error
"""
import numpy as np
import sys
import os
# Subroutine to output A, L, U, and error by taking in input file from cmd line
def lu_fact(file_name):
array = np.loadtxt(file_name)
# Dimension, #row
dims = array.shape
n = dims[0] # row
m = dims[1] # col
if m != n:
A = array[:, :-1] # slice out the last column! called from solve_lu_b
m -= 1
else:
A = array # called from command line
# Initialize L & U as L = I, U = A for Doolittle algorithm
L = np.identity(n, dtype='d')
U = A
# LU fact without partial pivoting
# Pseudo code was referred from a cited source below:
# "LU factorization: Lecture 20 in "Numerical Linear Algebra" by Trefethen and Bau, SIAM, Philadelphia, 1997"
#
# This algorithm assumes that factorization exists
# Idea is to introduce 0s in U below the diagonal and to fill in L
# Fill in U above the diagonal
for i in range(0, n - 1):
for j in range(i + 1, n):
L[j, i] = U[j, i] / U[i, i]
U[j, i:n] = U[j, i:] - (L[j, i] * U[i, i:n])
# Error, max norm, is defined as the maximum sum of the absolute values of each row
error = max(np.sum(abs(np.asmatrix(L)*np.asmatrix(U)-A), axis=1, dtype='d'))
return A, L, U, error
# This is only or when lu_fact is used as a stand-alone module
# Read command line argument. Must be exactly one argument.
# It outputs on the console
if __name__ == '__main__':
A, L, U, max_norm = lu_fact(sys.argv[1])
np.set_printoptions(precision=6, suppress=True)
print 'Your original matrix A:'
print A
print '\nL solved with LU factorization:'
print L
print '\nU solved with LU factorization:'
print U
np.set_printoptions(precision=15, suppress=False)
print '\nError ||LU-A||inf:'
print max_norm
print '\n' |
"""Routines for numerical differentiation."""
from __future__ import division
import numpy as np
from numpy.linalg import norm
from scipy.sparse.linalg import LinearOperator
from ..sparse import issparse, csc_matrix, csr_matrix, coo_matrix, find
from ._group_columns import group_dense, group_sparse
EPS = np.finfo(np.float64).eps
def _adjust_scheme_to_bounds(x0, h, num_steps, scheme, lb, ub):
"""Adjust final difference scheme to the presence of bounds.
Parameters
----------
x0 : ndarray, shape (n,)
Point at which we wish to estimate derivative.
h : ndarray, shape (n,)
Desired finite difference steps.
num_steps : int
Number of `h` steps in one direction required to implement finite
difference scheme. For example, 2 means that we need to evaluate
f(x0 + 2 * h) or f(x0 - 2 * h)
scheme : {'1-sided', '2-sided'}
Whether steps in one or both directions are required. In other
words '1-sided' applies to forward and backward schemes, '2-sided'
applies to center schemes.
lb : ndarray, shape (n,)
Lower bounds on independent variables.
ub : ndarray, shape (n,)
Upper bounds on independent variables.
Returns
-------
h_adjusted : ndarray, shape (n,)
Adjusted step sizes. Step size decreases only if a sign flip or
switching to one-sided scheme doesn't allow to take a full step.
use_one_sided : ndarray of bool, shape (n,)
Whether to switch to one-sided scheme. Informative only for
``scheme='2-sided'``.
"""
if scheme == '1-sided':
use_one_sided = np.ones_like(h, dtype=bool)
elif scheme == '2-sided':
h = np.abs(h)
use_one_sided = np.zeros_like(h, dtype=bool)
else:
raise ValueError("`scheme` must be '1-sided' or '2-sided'.")
if np.all((lb == -np.inf) & (ub == np.inf)):
return h, use_one_sided
h_total = h * num_steps
h_adjusted = h.copy()
lower_dist = x0 - lb
upper_dist = ub - x0
if scheme == '1-sided':
x = x0 + h_total
violated = (x < lb) | (x > ub)
fitting = np.abs(h_total) <= np.maximum(lower_dist, upper_dist)
h_adjusted[violated & fitting] *= -1
forward = (upper_dist >= lower_dist) & ~fitting
h_adjusted[forward] = upper_dist[forward] / num_steps
backward = (upper_dist < lower_dist) & ~fitting
h_adjusted[backward] = -lower_dist[backward] / num_steps
elif scheme == '2-sided':
central = (lower_dist >= h_total) & (upper_dist >= h_total)
forward = (upper_dist >= lower_dist) & ~central
h_adjusted[forward] = np.minimum(
h[forward], 0.5 * upper_dist[forward] / num_steps)
use_one_sided[forward] = True
backward = (upper_dist < lower_dist) & ~central
h_adjusted[backward] = -np.minimum(
h[backward], 0.5 * lower_dist[backward] / num_steps)
use_one_sided[backward] = True
min_dist = np.minimum(upper_dist, lower_dist) / num_steps
adjusted_central = (~central & (np.abs(h_adjusted) <= min_dist))
h_adjusted[adjusted_central] = min_dist[adjusted_central]
use_one_sided[adjusted_central] = False
return h_adjusted, use_one_sided
relative_step = {"2-point": EPS**0.5,
"3-point": EPS**(1/3),
"cs": EPS**0.5}
def _compute_absolute_step(rel_step, x0, method):
if rel_step is None:
rel_step = relative_step[method]
sign_x0 = (x0 >= 0).astype(float) * 2 - 1
return rel_step * sign_x0 * np.maximum(1.0, np.abs(x0))
def _prepare_bounds(bounds, x0):
lb, ub = [np.asarray(b, dtype=float) for b in bounds]
if lb.ndim == 0:
lb = np.resize(lb, x0.shape)
if ub.ndim == 0:
ub = np.resize(ub, x0.shape)
return lb, ub
def group_columns(A, order=0):
"""Group columns of a 2-d matrix for sparse finite differencing [1]_.
Two columns are in the same group if in each row at least one of them
has zero. A greedy sequential algorithm is used to construct groups.
Parameters
----------
A : array_like or sparse matrix, shape (m, n)
Matrix of which to group columns.
order : int, iterable of int with shape (n,) or None
Permutation array which defines the order of columns enumeration.
If int or None, a random permutation is used with `order` used as
a random seed. Default is 0, that is use a random permutation but
guarantee repeatability.
Returns
-------
groups : ndarray of int, shape (n,)
Contains values from 0 to n_groups-1, where n_groups is the number
of found groups. Each value ``groups[i]`` is an index of a group to
which i-th column assigned. The procedure was helpful only if
n_groups is significantly less than n.
References
----------
.. [1] A. Curtis, M. J. D. Powell, and J. Reid, "On the estimation of
sparse Jacobian matrices", Journal of the Institute of Mathematics
and its Applications, 13 (1974), pp. 117-120.
"""
if issparse(A):
A = csc_matrix(A)
else:
A = np.atleast_2d(A)
A = (A != 0).astype(np.int32)
if A.ndim != 2:
raise ValueError("`A` must be 2-dimensional.")
m, n = A.shape
if order is None or np.isscalar(order):
rng = np.random.RandomState(order)
order = rng.permutation(n)
else:
order = np.asarray(order)
if order.shape != (n,):
raise ValueError("`order` has incorrect shape.")
A = A[:, order]
if issparse(A):
groups = group_sparse(m, n, A.indices, A.indptr)
else:
groups = group_dense(m, n, A)
groups[order] = groups.copy()
return groups
def approx_derivative(fun, x0, method='3-point', rel_step=None, f0=None,
bounds=(-np.inf, np.inf), sparsity=None,
as_linear_operator=False, args=(), kwargs={}):
"""Compute finite difference approximation of the derivatives of a
vector-valued function.
If a function maps from R^n to R^m, its derivatives form m-by-n matrix
called the Jacobian, where an element (i, j) is a partial derivative of
f[i] with respect to x[j].
Parameters
----------
fun : callable
Function of which to estimate the derivatives. The argument x
passed to this function is ndarray of shape (n,) (never a scalar
even if n=1). It must return 1-d array_like of shape (m,) or a scalar.
x0 : array_like of shape (n,) or float
Point at which to estimate the derivatives. Float will be converted
to a 1-d array.
method : {'3-point', '2-point', 'cs'}, optional
Finite difference method to use:
- '2-point' - use the first order accuracy forward or backward
difference.
- '3-point' - use central difference in interior points and the
second order accuracy forward or backward difference
near the boundary.
- 'cs' - use a complex-step finite difference scheme. This assumes
that the user function is real-valued and can be
analytically continued to the complex plane. Otherwise,
produces bogus results.
rel_step : None or array_like, optional
Relative step size to use. The absolute step size is computed as
``h = rel_step * sign(x0) * max(1, abs(x0))``, possibly adjusted to
fit into the bounds. For ``method='3-point'`` the sign of `h` is
ignored. If None (default) then step is selected automatically,
see Notes.
f0 : None or array_like, optional
If not None it is assumed to be equal to ``fun(x0)``, in this case
the ``fun(x0)`` is not called. Default is None.
bounds : tuple of array_like, optional
Lower and upper bounds on independent variables. Defaults to no bounds.
Each bound must match the size of `x0` or be a scalar, in the latter
case the bound will be the same for all variables. Use it to limit the
range of function evaluation. Bounds checking is not implemented
when `as_linear_operator` is True.
sparsity : {None, array_like, sparse matrix, 2-tuple}, optional
Defines a sparsity structure of the Jacobian matrix. If the Jacobian
matrix is known to have only few non-zero elements in each row, then
it's possible to estimate its several columns by a single function
evaluation [3]_. To perform such economic computations two ingredients
are required:
* structure : array_like or sparse matrix of shape (m, n). A zero
element means that a corresponding element of the Jacobian
identically equals to zero.
* groups : array_like of shape (n,). A column grouping for a given
sparsity structure, use `group_columns` to obtain it.
A single array or a sparse matrix is interpreted as a sparsity
structure, and groups are computed inside the function. A tuple is
interpreted as (structure, groups). If None (default), a standard
dense differencing will be used.
Note, that sparse differencing makes sense only for large Jacobian
matrices where each row contains few non-zero elements.
as_linear_operator : bool, optional
When True the function returns an `scipy.sparse.linalg.LinearOperator`.
Otherwise it returns a dense array or a sparse matrix depending on
`sparsity`. The linear operator provides an efficient way of computing
``J.dot(p)`` for any vector ``p`` of shape (n,), but does not allow
direct access to individual elements of the matrix. By default
`as_linear_operator` is False.
args, kwargs : tuple and dict, optional
Additional arguments passed to `fun`. Both empty by default.
The calling signature is ``fun(x, *args, **kwargs)``.
Returns
-------
J : {ndarray, sparse matrix, LinearOperator}
Finite difference approximation of the Jacobian matrix.
If `as_linear_operator` is True returns a LinearOperator
with shape (m, n). Otherwise it returns a dense array or sparse
matrix depending on how `sparsity` is defined. If `sparsity`
is None then a ndarray with shape (m, n) is returned. If
`sparsity` is not None returns a csr_matrix with shape (m, n).
For sparse matrices and linear operators it is always returned as
a 2-dimensional structure, for ndarrays, if m=1 it is returned
as a 1-dimensional gradient array with shape (n,).
See Also
--------
check_derivative : Check correctness of a function computing derivatives.
Notes
-----
If `rel_step` is not provided, it assigned to ``EPS**(1/s)``, where EPS is
machine epsilon for float64 numbers, s=2 for '2-point' method and s=3 for
'3-point' method. Such relative step approximately minimizes a sum of
truncation and round-off errors, see [1]_.
A finite difference scheme for '3-point' method is selected automatically.
The well-known central difference scheme is used for points sufficiently
far from the boundary, and 3-point forward or backward scheme is used for
points near the boundary. Both schemes have the second-order accuracy in
terms of Taylor expansion. Refer to [2]_ for the formulas of 3-point
forward and backward difference schemes.
For dense differencing when m=1 Jacobian is returned with a shape (n,),
on the other hand when n=1 Jacobian is returned with a shape (m, 1).
Our motivation is the following: a) It handles a case of gradient
computation (m=1) in a conventional way. b) It clearly separates these two
different cases. b) In all cases np.atleast_2d can be called to get 2-d
Jacobian with correct dimensions.
References
----------
.. [1] W. H. Press et. al. "Numerical Recipes. The Art of Scientific
Computing. 3rd edition", sec. 5.7.
.. [2] A. Curtis, M. J. D. Powell, and J. Reid, "On the estimation of
sparse Jacobian matrices", Journal of the Institute of Mathematics
and its Applications, 13 (1974), pp. 117-120.
.. [3] B. Fornberg, "Generation of Finite Difference Formulas on
Arbitrarily Spaced Grids", Mathematics of Computation 51, 1988.
Examples
--------
>>> import numpy as np
>>> from scipy.optimize import approx_derivative
>>>
>>> def f(x, c1, c2):
... return np.array([x[0] * np.sin(c1 * x[1]),
... x[0] * np.cos(c2 * x[1])])
...
>>> x0 = np.array([1.0, 0.5 * np.pi])
>>> approx_derivative(f, x0, args=(1, 2))
array([[ 1., 0.],
[-1., 0.]])
Bounds can be used to limit the region of function evaluation.
In the example below we compute left and right derivative at point 1.0.
>>> def g(x):
... return x**2 if x >= 1 else x
...
>>> x0 = 1.0
>>> approx_derivative(g, x0, bounds=(-np.inf, 1.0))
array([ 1.])
>>> approx_derivative(g, x0, bounds=(1.0, np.inf))
array([ 2.])
"""
if method not in ['2-point', '3-point', 'cs']:
raise ValueError("Unknown method '%s'. " % method)
x0 = np.atleast_1d(x0)
if x0.ndim > 1:
raise ValueError("`x0` must have at most 1 dimension.")
lb, ub = _prepare_bounds(bounds, x0)
if lb.shape != x0.shape or ub.shape != x0.shape:
raise ValueError("Inconsistent shapes between bounds and `x0`.")
if as_linear_operator and not (np.all(np.isinf(lb))
and np.all(np.isinf(ub))):
raise ValueError("Bounds not supported when "
"`as_linear_operator` is True.")
def fun_wrapped(x):
f = np.atleast_1d(fun(x, *args, **kwargs))
if f.ndim > 1:
raise RuntimeError("`fun` return value has "
"more than 1 dimension.")
return f
if f0 is None:
f0 = fun_wrapped(x0)
else:
f0 = np.atleast_1d(f0)
if f0.ndim > 1:
raise ValueError("`f0` passed has more than 1 dimension.")
if np.any((x0 < lb) | (x0 > ub)):
raise ValueError("`x0` violates bound constraints.")
if as_linear_operator:
if rel_step is None:
rel_step = relative_step[method]
return _linear_operator_difference(fun_wrapped, x0,
f0, rel_step, method)
else:
h = _compute_absolute_step(rel_step, x0, method)
if method == '2-point':
h, use_one_sided = _adjust_scheme_to_bounds(
x0, h, 1, '1-sided', lb, ub)
elif method == '3-point':
h, use_one_sided = _adjust_scheme_to_bounds(
x0, h, 1, '2-sided', lb, ub)
elif method == 'cs':
use_one_sided = False
if sparsity is None:
return _dense_difference(fun_wrapped, x0, f0, h,
use_one_sided, method)
else:
if not issparse(sparsity) and len(sparsity) == 2:
structure, groups = sparsity
else:
structure = sparsity
groups = group_columns(sparsity)
if issparse(structure):
structure = csc_matrix(structure)
else:
structure = np.atleast_2d(structure)
groups = np.atleast_1d(groups)
return _sparse_difference(fun_wrapped, x0, f0, h,
use_one_sided, structure,
groups, method)
def _linear_operator_difference(fun, x0, f0, h, method):
m = f0.size
n = x0.size
if method == '2-point':
def matvec(p):
if np.array_equal(p, np.zeros_like(p)):
return np.zeros(m)
dx = h / norm(p)
x = x0 + dx*p
df = fun(x) - f0
return df / dx
elif method == '3-point':
def matvec(p):
if np.array_equal(p, np.zeros_like(p)):
return np.zeros(m)
dx = 2*h / norm(p)
x1 = x0 - (dx/2)*p
x2 = x0 + (dx/2)*p
f1 = fun(x1)
f2 = fun(x2)
df = f2 - f1
return df / dx
elif method == 'cs':
def matvec(p):
if np.array_equal(p, np.zeros_like(p)):
return np.zeros(m)
dx = h / norm(p)
x = x0 + dx*p*1.j
f1 = fun(x)
df = f1.imag
return df / dx
else:
raise RuntimeError("Never be here.")
return LinearOperator((m, n), matvec)
def _dense_difference(fun, x0, f0, h, use_one_sided, method):
m = f0.size
n = x0.size
J_transposed = np.empty((n, m))
h_vecs = np.diag(h)
for i in range(h.size):
if method == '2-point':
x = x0 + h_vecs[i]
dx = x[i] - x0[i] # Recompute dx as exactly representable number.
df = fun(x) - f0
elif method == '3-point' and use_one_sided[i]:
x1 = x0 + h_vecs[i]
x2 = x0 + 2 * h_vecs[i]
dx = x2[i] - x0[i]
f1 = fun(x1)
f2 = fun(x2)
df = -3.0 * f0 + 4 * f1 - f2
elif method == '3-point' and not use_one_sided[i]:
x1 = x0 - h_vecs[i]
x2 = x0 + h_vecs[i]
dx = x2[i] - x1[i]
f1 = fun(x1)
f2 = fun(x2)
df = f2 - f1
elif method == 'cs':
f1 = fun(x0 + h_vecs[i]*1.j)
df = f1.imag
dx = h_vecs[i, i]
else:
raise RuntimeError("Never be here.")
J_transposed[i] = df / dx
if m == 1:
J_transposed = np.ravel(J_transposed)
return J_transposed.T
def _sparse_difference(fun, x0, f0, h, use_one_sided,
structure, groups, method):
m = f0.size
n = x0.size
row_indices = []
col_indices = []
fractions = []
n_groups = np.max(groups) + 1
for group in range(n_groups):
# Perturb variables which are in the same group simultaneously.
e = np.equal(group, groups)
h_vec = h * e
if method == '2-point':
x = x0 + h_vec
dx = x - x0
df = fun(x) - f0
# The result is written to columns which correspond to perturbed
# variables.
cols, = np.nonzero(e)
# Find all non-zero elements in selected columns of Jacobian.
i, j, _ = find(structure[:, cols])
# Restore column indices in the full array.
j = cols[j]
elif method == '3-point':
# Here we do conceptually the same but separate one-sided
# and two-sided schemes.
x1 = x0.copy()
x2 = x0.copy()
mask_1 = use_one_sided & e
x1[mask_1] += h_vec[mask_1]
x2[mask_1] += 2 * h_vec[mask_1]
mask_2 = ~use_one_sided & e
x1[mask_2] -= h_vec[mask_2]
x2[mask_2] += h_vec[mask_2]
dx = np.zeros(n)
dx[mask_1] = x2[mask_1] - x0[mask_1]
dx[mask_2] = x2[mask_2] - x1[mask_2]
f1 = fun(x1)
f2 = fun(x2)
cols, = np.nonzero(e)
i, j, _ = find(structure[:, cols])
j = cols[j]
mask = use_one_sided[j]
df = np.empty(m)
rows = i[mask]
df[rows] = -3 * f0[rows] + 4 * f1[rows] - f2[rows]
rows = i[~mask]
df[rows] = f2[rows] - f1[rows]
elif method == 'cs':
f1 = fun(x0 + h_vec*1.j)
df = f1.imag
dx = h_vec
cols, = np.nonzero(e)
i, j, _ = find(structure[:, cols])
j = cols[j]
else:
raise ValueError("Never be here.")
# All that's left is to compute the fraction. We store i, j and
# fractions as separate arrays and later construct coo_matrix.
row_indices.append(i)
col_indices.append(j)
fractions.append(df[i] / dx[j])
row_indices = np.hstack(row_indices)
col_indices = np.hstack(col_indices)
fractions = np.hstack(fractions)
J = coo_matrix((fractions, (row_indices, col_indices)), shape=(m, n))
return csr_matrix(J)
def check_derivative(fun, jac, x0, bounds=(-np.inf, np.inf), args=(),
kwargs={}):
"""Check correctness of a function computing derivatives (Jacobian or
gradient) by comparison with a finite difference approximation.
Parameters
----------
fun : callable
Function of which to estimate the derivatives. The argument x
passed to this function is ndarray of shape (n,) (never a scalar
even if n=1). It must return 1-d array_like of shape (m,) or a scalar.
jac : callable
Function which computes Jacobian matrix of `fun`. It must work with
argument x the same way as `fun`. The return value must be array_like
or sparse matrix with an appropriate shape.
x0 : array_like of shape (n,) or float
Point at which to estimate the derivatives. Float will be converted
to 1-d array.
bounds : 2-tuple of array_like, optional
Lower and upper bounds on independent variables. Defaults to no bounds.
Each bound must match the size of `x0` or be a scalar, in the latter
case the bound will be the same for all variables. Use it to limit the
range of function evaluation.
args, kwargs : tuple and dict, optional
Additional arguments passed to `fun` and `jac`. Both empty by default.
The calling signature is ``fun(x, *args, **kwargs)`` and the same
for `jac`.
Returns
-------
accuracy : float
The maximum among all relative errors for elements with absolute values
higher than 1 and absolute errors for elements with absolute values
less or equal than 1. If `accuracy` is on the order of 1e-6 or lower,
then it is likely that your `jac` implementation is correct.
See Also
--------
approx_derivative : Compute finite difference approximation of derivative.
Examples
--------
>>> import numpy as np
>>> from scipy.optimize import check_derivative
>>>
>>>
>>> def f(x, c1, c2):
... return np.array([x[0] * np.sin(c1 * x[1]),
... x[0] * np.cos(c2 * x[1])])
...
>>> def jac(x, c1, c2):
... return np.array([
... [np.sin(c1 * x[1]), c1 * x[0] * np.cos(c1 * x[1])],
... [np.cos(c2 * x[1]), -c2 * x[0] * np.sin(c2 * x[1])]
... ])
...
>>>
>>> x0 = np.array([1.0, 0.5 * np.pi])
>>> check_derivative(f, jac, x0, args=(1, 2))
2.4492935982947064e-16
"""
J_to_test = jac(x0, *args, **kwargs)
if issparse(J_to_test):
J_diff = approx_derivative(fun, x0, bounds=bounds, sparsity=J_to_test,
args=args, kwargs=kwargs)
J_to_test = csr_matrix(J_to_test)
abs_err = J_to_test - J_diff
i, j, abs_err_data = find(abs_err)
J_diff_data = np.asarray(J_diff[i, j]).ravel()
return np.max(np.abs(abs_err_data) /
np.maximum(1, np.abs(J_diff_data)))
else:
J_diff = approx_derivative(fun, x0, bounds=bounds,
args=args, kwargs=kwargs)
abs_err = np.abs(J_to_test - J_diff)
return np.max(abs_err / np.maximum(1, np.abs(J_diff)))
|
from IPython.nbformat.current import reads, read
from runipy.notebook_runner import NotebookRunner
import json
import ast
import os
def convert_to_endpoint(string, is_filename=True):
# remove extension
if is_filename:
string = string.partition('.')[0]
''.join(e for e in string if e.isalnum())
string = string.replace('_', '-').lower()
string = string.replace(' ', '-').lower()
return string
def nb_config_list(nb_dir):
# get list of available notebooks to populate navbar
config_list = []
for nb_filename in os.listdir(nb_dir):
if '.ipynb' in nb_filename and 'ipynb_checkpoints' not in nb_filename:
nb = NotebookObject(nb_dir + nb_filename)
config_dict = nb.get_nb_config()
if config_dict:
config_dict['nb_endpoint'] = convert_to_endpoint(config_dict['nb_filename'])
config_list.append(config_dict)
return config_list
class NotebookObject(object):
"""
Represents a ipython notebook (.ipynb file)
"""
def __init__(self, nb_file):
self.nb_file = nb_file
self.nb_obj = read(open(nb_file), 'json')
NotebookObject.refresh(self)
def save(self, save_path=None):
"""
Saves the notebook to a given path
"""
with open(save_path, "w") as f:
f.write(json.dumps(self.nb_obj))
def refresh(self):
"""
Updates the nb object after any modifications
"""
self.cells = self.nb_obj['worksheets'][0]['cells']
self.cells_inputs = []
for cell in self.cells:
try:
self.cells_inputs.append(cell['input'])
except KeyError:
self.cells_inputs.append(cell['source'])
self.cells_outputs = []
for cell in self.cells:
try:
if cell['outputs']:
if len(cell['outputs']) > 1: # sloppy way to infer that cell output is a plot
self.cells_outputs.append('<img src="data:image/png;base64,' + cell['outputs'][1]['png'] + '"/>')
else:
try:
self.cells_outputs.append(cell['outputs'][0]['text'])
except KeyError:
self.cells_outputs.append("Error: {}: {}".format(cell['outputs'][0]['ename'],
cell['outputs'][0]['evalue']))
except KeyError:
continue
def get_nb_config(self):
"""
Checks first cell to see if nb_config is present. Will return None if not
"""
nb_config = self.cells[0]['input']
try:
self.config_dict = ast.literal_eval(nb_config)
except SyntaxError:
self.config_dict = None
if not isinstance(self.config_dict, dict):
self.config_dict = None
return self.config_dict
def insert_cell(self, content, cell_position=0):
insert_dict = {
u'cell_type': u'code',
u'input': unicode(content),
u'language': u'python',
u'outputs': []
}
self.cells.insert(cell_position, insert_dict)
self.nb_obj['worksheets'][0]['cells'] = self.cells
self.nb_obj = reads(json.dumps(self.nb_obj), 'json')
# self.cells_inputs = [cell['input'] for cell in self.cells]
self.cells_inputs = []
for cell in self.cells:
if 'input' in cell:
self.cells_inputs.append(cell['input'])
def insert_nb_params(self, params):
"""
Inserts params required to execute the nb
:param params: list of dicts, where dict is {'param_name':'param_value'}
ie: [{'member_id':1234}, {'campaign_id':987654}]
"""
param_str = ''
for key in params.keys():
if isinstance(params[key], basestring):
param_str += '{} = "{}"\n'.format(key, params[key])
else:
param_str += '{} = {}\n'.format(key, params[key])
NotebookObject.insert_cell(self, param_str, cell_position=1)
def run(self):
r = NotebookRunner(self.nb_obj, pylab=True)
r.run_notebook()
self.nb_obj = r.nb
NotebookObject.refresh(self)
|
#!/usr/bin/env python
# Import necessary module
import os
from sqlalchemy import create_engine, MetaData, Table, select
print(engine.table_names()) # ['Person', 'Site', 'Survey', 'Visited']
"""
survey = Table('Survey', metadata, autoload=True, autoload_with=engine)
ssmt = select([survey])
print(ssmt)
results = connection.execute(ssmt).fetchall()
print(results)
print(results[0])
print(results[0].keys())
# Get the first row of the results by using an index: first_row
first_row = results[0]
# Print the first row of the results
print(first_row)
# Print the first column of the first row by using an index
print(first_row[0])
# Print the 'family' column of the first row by using its name
print(first_row['quant'])
# Add a where clause to filter the results to only those for lake
ssmt = ssmt.where(survey.columns.person == 'lake')
# Execute the query to retrieve all the data returned: results
results = connection.execute(ssmt).fetchall()
print(results)
""" |
from rest_framework import serializers
from .models import College, Students, Professors
class Collegeserializer(serializers.ModelSerializer):
class Meta:
model= College
fields = '__all__'
class Studentserializer(serializers.ModelSerializer):
class Meta:
model= Students
fields = '__all__'
class Professorserializer(serializers.ModelSerializer):
class Meta:
model= Professors
fields = '__all__' |
__all__ = ['BaseCipher', 'aes_gcm', 'plain']
import os
from typing import Tuple
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
class BaseCipher():
is_aead = False
class Key():
def __init__(self, key: bytes):
pass
def export(self) -> bytes:
return b''
@staticmethod
def encrypt(key: 'Key', data: bytes) -> Tuple[bytes, bytes]:
return (b'', b'')
@staticmethod
def decrypt(key: 'Key', nonce: bytes, data: bytes) -> bytes:
return b''
class aes_gcm(BaseCipher):
is_aead = True
class Key(BaseCipher.Key):
def __init__(self, key: bytes):
self.key = key if key else os.urandom(128 // 8)
self.a = AESGCM(self.key)
def export(self) -> bytes:
return self.key
@staticmethod
def encrypt(key, data):
nonce = os.urandom(12)
return (nonce, key.a.encrypt(nonce, data, associated_data=None))
@staticmethod
def decrypt(key, nonce, data):
return key.a.decrypt(nonce, data, associated_data=None)
class plain(BaseCipher):
is_aead = False
class Key(BaseCipher.Key):
def export(self) -> bytes:
return b''
@staticmethod
def encrypt(key, data):
return (b'', data)
@staticmethod
def decrypt(key, nonce, data):
return data
|
## http://developer.tobiipro.com/python/python-step-by-step-guide.html
import tobii_research as tr
import time
import pandas as pd
import keyboard
from datetime import datetime
output_dir = 'C:/github/ORCL_VR_EyeTracking/Data/EyeTrakcing/TobiiProPython/'
# 1. Find the Eye Tracker
found_eyetrackers = tr.find_all_eyetrackers()
my_eyetracker = found_eyetrackers[0]
print("Address: " + my_eyetracker.address)
print("Model: " + my_eyetracker.model)
print("Name (It's OK if this is empty): " + my_eyetracker.device_name)
print("Serial number: " + my_eyetracker.serial_number)
'''
columns = ['device_time_stamp', 'system_time_stamp', 'left_gaze_direction_unit_vector',
'left_gaze_direction_validity', 'left_gaze_origin_position_in_hmd_coordinates',
'left_gaze_origin_validity', 'left_pupil_diameter', 'left_pupil_validity',
'left_pupil_position_in_tracking_area', 'left_pupil_position_validity',
'right_gaze_direction_unit_vector', 'right_gaze_direction_validity',
'right_gaze_origin_position_in_hmd_coordinates', 'right_gaze_origin_validity',
'right_pupil_diameter', 'right_pupil_validity', 'right_pupil_position_in_tracking_area',
'right_pupil_position_validity']
'''
global_gaze_data = []
def gaze_data_callback(gaze_data):
global global_gaze_data
global_gaze_data.append(gaze_data)
'''
## detect for 3 seconds
def gaze_data(my_eyetracker):
global global_gaze_data
print("Subscribing to gaze data for eye tracker with serial number {0}.".format(my_eyetracker.serial_number))
my_eyetracker.subscribe_to(tr.EYETRACKER_HMD_GAZE_DATA, gaze_data_callback, as_dictionary=True)
time.sleep(3)
my_eyetracker.unsubscribe_from(tr.EYETRACKER_HMD_GAZE_DATA, gaze_data_callback)
print("Unsubscribed from gaze data.")
print("Last received gaze package:")
#print(global_gaze_data)
gaze_data(my_eyetracker)
df = pd.DataFrame(global_gaze_data)
df.to_csv('C:/Users/ORCL/Documents/Xiang/eye_tracking_data_python/df.csv', index = False)
'''
### Detect until user press a key
def gaze_data(my_eyetracker):
global global_gaze_data
print("Subscribing to gaze data for eye tracker with serial number {0}.".format(my_eyetracker.serial_number))
my_eyetracker.subscribe_to(tr.EYETRACKER_HMD_GAZE_DATA, gaze_data_callback, as_dictionary=True)
while True:
if keyboard.is_pressed('q'):
my_eyetracker.unsubscribe_from(tr.EYETRACKER_HMD_GAZE_DATA, gaze_data_callback)
print("Unsubscribed from gaze data.")
print("q pressed:")
break
#print(global_gaze_data)
start_time_stamp = time.time()
start_datetime = datetime.now()
gaze_data(my_eyetracker)
df = pd.DataFrame(global_gaze_data)
end_time = time.time()
# file_name = str(start_time_stamp) + '-' + str(end_time) + '.csv'
file_name = str(start_datetime).replace(':','-') + '.csv'
df.to_csv(output_dir + file_name, index = False)
|
"""
ID: ten.to.1
TASK: fact4
LANG: PYTHON3
"""
#!/usr/bin/python
#Naive solution seems to work!
import math
file_in = open("fact4.in", "r")
file_out = open("fact4.out", "w")
N = int(file_in.read())
factorial = str(math.factorial(N))
for n in range(len(factorial) - 1, 0, -1):
if(factorial[n] != "0"):
file_out.write(factorial[n] + "\n")
break
if(len(factorial) == 1):
file_out.write(factorial + "\n")
|
Import('*')
env = env.Clone()
env.PrependUnique(delete_existing=1, CPPPATH = [
'#/src/gallium/drivers',
])
nvfx = env.ConvenienceLibrary(
target = 'nvfx',
source = env.ParseSourceList('Makefile.sources', 'C_SOURCES')
)
Export('nvfx')
|
from PySimpleGUI import PySimpleGUI as sg
from docx import Document
from docx.shared import Inches
from datetime import datetime
from docx.shared import Pt
from docx.enum.text import WD_ALIGN_PARAGRAPH
import os
def doc(cliente, img=0):
now = datetime.today()
today = f'{now.day}{now.month}{now.year}--{now.hour}-{now.minute}-{now.second}'
print(cliente)
vr = cliente
document = Document()
document.add_paragraph(f'Cliente: {vr[0]}')
font = document.styles['Normal'].font
font.name = 'Arial'
font.size = Pt(8)
for v in vr:
if v == vr[0]: pass
else:
check = 0
print('v = ', v)
for i in v:
if check < 1:
content = f'''Ficha: {v[0]}
{"Ref.:":<0} {v[1]} / Ref. Salto: {v[2]}'''
document.add_paragraph(content)
if(v[-1] != 0 and v[-1].strip() != ''):
my_image = document.add_picture(v[-1], width=Inches(1.5))
last_paragraph = document.paragraphs[-1]
last_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER
elif check >= 3:
if i != v[-1]:
content = f'''
{"Cor:":<0} {i[0]}
{"Grade:":<0} {"33":>10}\t{"34":>10}\t{"35":>10}\t{"36":>10}\t{"37":>10}\t{"38":>10}\t{"39":>10}\t{"40":>10}\t{"Total":>10}
{i[1]:>10}\t{i[2]:>10}\t{i[3]:>10}\t{i[4]:>10}\t{i[5]:>10}\t{i[6]:>10}\t{i[7]:>10}\t{i[8]:>10}\t{i[9]:>10}
{"-"*133}'''
document.add_paragraph(content)
check += 1
desktop = os.path.join(os.path.join(os.environ['USERPROFILE']), 'Desktop')
arq = f'{vr[0]}--{today}.docx'
caminho = f'{desktop}\{arq}'
document.save(caminho)
# funções de uso =======================================================================================================
def adicionar(val):
soma = 0
if val == 0:
ficha.append(str(value['ficha']) + '/' + str(value['ficha1']))
ficha.append(value['ref'])
if value['refSalto'].split() == ''.split():
ficha.append('0')
else:
ficha.append(value['refSalto'])
val = 1
cor.append(value['cor'])
for i in range(33, 41):
if value[f'{i}'].split() == ''.split():
cor.append(0)
else:
cor.append(value[f'{i}'])
for k, v in enumerate(cor):
if v == '':
v = 0
if k > 0:
soma += int(v)
cor.append(soma)
ficha.append(cor.copy())
cor.clear()
sg.popup('Adicionado com sucesso')
return val
# Layout ===========================================================================================================
def janela_cliente():
sg.theme('Reddit')
layout = [
[sg.Text('Cliente'), sg.Input(key='cliente')],
[sg.Button('Continuar')]
]
return sg.Window('Cliente', layout=layout, finalize=True)
def janela_info(nome, reference='', refsalt='', fich='', fich1=''):
sg.theme('Reddit')
layout = [
[sg.Text(f'------------{nome}------------')],
[sg.Text('Referência:'), sg.Input(default_text=reference, key='ref', size=(10, 1)), sg.Text('Ref. Salto:'), sg.Input(default_text=reference, key='refSalto', size=(10, 1)), sg.Text('Ficha'),
sg.Input(default_text=fich, key='ficha', size=(5, 1)), sg.Text('/'), sg.Input(default_text=fich1, key='ficha1', size=(5, 1))],
[sg.Text('Imagem: '), sg.Button('Foto')],
[sg.Text('-'*118)],
[sg.Text('Cor: '), sg.Input(key='cor', size=(56, 1))],
[sg.Text('Tamanho: 33 34 35 36 37 38 39 40')],
[sg.Text('Quatidade: '), sg.Input(key='33', size=(3, 1)), sg.Input(key='34', size=(3, 1)), sg.Input(key='35', size=(3, 1)),
sg.Input(key='36', size=(3, 1)), sg.Input(key='37', size=(3, 1)), sg.Input(key='38', size=(3, 1)),
sg.Input(key='39', size=(3, 1)), sg.Input(key='40', size=(3, 1)), sg.Button('Adicionar')],
[sg.Button('Nova Referência'), sg.Button('Finalizar')]
]
return sg.Window('Informações', layout=layout, finalize=True)
def janela_fim():
sg.theme('Reddit')
layout = [
[sg.Button('Novo Cliente'), sg.Button('Fechar')]
]
return sg.Window('Encerrar', layout=layout, finalize=True)
# Janelas =======================================================================================================
janela1, janela3, janela2, janela4 = janela_cliente(), None, None, None
# Loop de Eventos ===============================================================================================
cliente = []
ficha = []
cor = []
val = 0
while True:
imagem = ''.strip()
window, event, value = sg.read_all_windows()
# fechando
if event == sg.WINDOW_CLOSED:
break
# proxima janela
if window == janela1 and event == 'Continuar':
if value['cliente'].strip() == '':
pass
else:
cliente.append(value['cliente'])
janela2 = janela_info(cliente[0])
janela1.Close()
if window == janela2:
while True:
window, event, value = sg.read_all_windows()
if event == sg.WINDOW_CLOSED:
break
if event == 'Foto':
imagem = sg.popup_get_file('Selecione onde está a foto')
if event == 'Adicionar':
val = adicionar(val)
janela2.Close()
janela2 = janela_info(cliente[0], ficha[1], ficha[2], ficha[0][0], ficha[0][2])
if event == 'Nova Referência':
if (imagem == ''.strip() or imagem == None or imagem == 0):
try:
imagem = sg.popup_get_file('Selecione onde está a foto (deixe vazio para não ter foto)', BaseException=False)
except:
imagem = ''.strip()
ficha.append(imagem)
cliente.append(ficha.copy())
ficha.clear()
val = 0
janela2.Close()
janela2 = janela_info(cliente[0])
imagem = ''
cor.clear()
if event == 'Finalizar':
if(imagem == ''.strip() or imagem == None or imagem == 0):
try:
imagem = sg.popup_get_file('Selecione onde está a foto (deixe vazio para não ter foto)', BaseException=False)
except:
imagem = ''.strip()
ficha.append(imagem)
cliente.append(ficha.copy())
ficha.clear()
doc(cliente, imagem)
janela4 = janela_fim()
janela2.Close()
break
if window == janela4:
if event == 'Novo Cliente':
janela1 = janela_cliente()
cliente.clear()
janela4.Close()
val = 0
if event == 'Fechar':
break
|
'''
王者荣耀五杀
'''
import time
hero = '诸葛亮'
action = '团灭'
enemy = '敌方'
number = 5
unit = '人'
gain = '获得'
achieve = '五连绝世'
#-------------击杀信息-------------------
print(hero+action+enemy+str(number)+unit)
time.sleep(1)
#-------------获得成就-------------------
print(gain+achieve)
|
import datetime
import random
import pika
from pvs.utils import write_report, config
class PVReport(object):
def __init__(self, meter_value):
"""Init params:
meter_value (int) incoming value from meter
pv_value (int) generated photovoltaic (PV) value
result_value (int) sum if meter_value and pv_value
"""
self.pv_value = self._get_simulated_photovoltaic_value()
self.meter_value = meter_value
self.result_value = self._calc_result()
def _calc_result(self):
"""Calculate incoming meter_value supposed to be negative *(-1)
because it is about consumption
"""
return self.pv_value + self.meter_value*(-1)
def _get_simulated_photovoltaic_value(self):
"""Provide generated photovoltaic value"""
return random.randint(5000,9000)
class PVSimulator(object):
"""Interact with the meter and generate simulated PV power"""
def __init__(self):
"""Init params:
all_result (list) accumulated (total) amount of generated power (Watt)
minus consumption obtained from meter
"""
self.all_results = list()
self.connection = pika.BlockingConnection(
pika.ConnectionParameters(host=config.HOST, port=config.PORT))
self.channel = self.connection.channel()
self.dt_tmp_checkpoint = datetime.datetime.now()
def consume(self):
"""Connect, bind and consume data from meter"""
self.channel.exchange_declare(exchange='pv', exchange_type='fanout')
result = self.channel.queue_declare(queue='', exclusive=True)
queue_name = result.method.queue
self.channel.queue_bind(exchange='pv', queue=queue_name)
print(' [*] Waiting for messages. To exit press CTRL+C')
def callback(ch, method, properties, body):
"""Ger obtained data from sender/publisher"""
pv_report = PVReport(meter_value=int(body))
self.all_results.append(pv_report.result_value)
if (datetime.datetime.now() - self.dt_tmp_checkpoint).seconds >= 2:
write_report(pv_report.__dict__,
total_value=sum(self.all_results))
self.dt_tmp_checkpoint = datetime.datetime.now()
self.channel.basic_consume(
queue=queue_name, on_message_callback=callback, auto_ack=True)
self.channel.start_consuming()
def stop_consume(self):
"""Give up to consume data"""
self.channel.stop_consuming()
self.connection.close()
def main():
"""Run the consume method of PVSimulator"""
pv_simulator = PVSimulator()
pv_simulator.consume()
if __name__ == "__main__":
"""Start the PVSimulator from here"""
main()
|
import voxelocc
import numpy as np
import numpy.testing as npt
import time
import os
import numpy.testing as npt
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
def load_pc_file(filename):
# returns Nx3 matrix
pc = np.fromfile(os.path.join("./", filename), dtype=np.float64)
if(pc.shape[0] != 4096*3):
print("Error in pointcloud shape")
return np.array([])
pc = np.reshape(pc,(pc.shape[0]//3, 3))
return pc
#### Test
test_data = load_pc_file("test.bin")
x = test_data[...,0]
y = test_data[...,1]
z = test_data[...,2]
fig = plt.figure()
ax = Axes3D(fig)
ax.scatter(x, y, z)
plt.show()
plt.pause(0.1)
plt.close()
test_data = test_data.astype(np.float32)
test_data = test_data[np.newaxis,:,...]
#### Settings
num_points = 4096
size = num_points
num_y = 120
num_x = 40
num_height = 20
max_height = 1 # max height
max_length = 1 # max_length in xy direction (same for x and y)
num_in_voxel = 1 # Num points in a voxel, no use for occupied information
#### Usage for voxelization
test_data = test_data.transpose()
test_data = test_data.flatten()
transer = voxelocc.GPUTransformer(test_data, size, max_length, max_height, num_x, num_y, num_height, num_in_voxel)
transer.transform()
point_t = transer.retreive()
point_t = point_t.reshape(-1,3)
point_t = point_t.reshape(num_height, num_x, num_y, 3)
#### Visualization
for i in range(num_height):
plt.imshow(point_t[i,:,:,2])
plt.show()
plt.pause(0.3)
|
from django.contrib import admin
from .models import UserService
# Register your models here.
admin.site.register(UserService)
|
def bright(fn, x, lo, hi):
"""
lo から hi-1 のうち、fn の結果が x 以下となる、最も右の値 + 1
:param callable fn:
:param x:
:param int lo: 最小値
:param int hi: 最大値 + 1
:return: lo <= ret <= hi
"""
while lo < hi:
mid = (lo + hi) // 2
if x < fn(mid):
hi = mid
else:
lo = mid + 1
return lo
def bleft(fn, x, lo, hi):
"""
lo から hi-1 のうち、fn の結果が x 以上となる、最も左の値
:param callable fn:
:param x:
:param int lo: 最小値
:param int hi: 最大値 + 1
:return: lo <= ret <= hi
"""
while lo < hi:
mid = (lo + hi) // 2
if fn(mid) < x:
lo = mid + 1
else:
hi = mid
return lo
def tleft(fn, lo, hi):
"""
fn の結果が最も小さくなるインデックスを三分探索する
:param callable fn:
:param int lo: 最小のインデックス
:param int hi: 最大のインデックス + 1
:return: lo <= ret < hi
"""
left = lo
right = hi
while abs(right - left) >= 3:
r1 = (left * 2 + right) // 3
r2 = (left + right * 2) // 3
if fn(r1) <= fn(r2):
right = r2
else:
left = r1
if left + 1 >= hi or fn(left) <= fn(left + 1):
return left
if left + 2 >= hi or fn(left + 1) <= fn(left + 2):
return left + 1
return left + 2
|
import pytube
if __name__ == "__main__":
video_url = "https://www.youtube.com/watch?v=Qma7wnicDnk"
youtube = pytube.YouTube(video_url)
video = youtube.streams.first()
video.download('./video')
|
from phonenumber_field.serializerfields import PhoneNumberField
from rest_framework import serializers
from .models import User
class UserProfileSerializer(serializers.ModelSerializer):
avatar = serializers.ImageField()
phone = PhoneNumberField()
class Meta:
model = User
fields = ('url', 'id', 'username', 'email', 'first_name', 'last_name',
'avatar', 'phone')
def get_full_name(self, obj):
request = self.context['request']
return request.user.get_full_name()
def update(self, instance, validated_data):
for attr, value in validated_data.items():
setattr(instance, attr, value)
instance.save()
return instance
class PasswordSerializer(serializers.Serializer):
old_password=serializers.CharField(required=True)
new_password=serializers.CharField(required=True)
|
import os
#Comentario
"""
Para la colocaion de
de encerrar algo largo en
comentarios utilizamos comillas
"""
os.system('cls')
print('-'*15) #Porque no se pueden poner mas???
print('\tPrograma de tipo de datos',end=' ',sep= ' ')
print("\tSEGUNDO PROGRAMA")
#Tipo de datos
#cadenas, caractere,etc...
####COMO IMPRIMIR EN LA PANTALLA#####
"""
x=70
y=1.55
z=True
a="Una cadena"
b='Segunda cadena'
print(type(x)) #Para saber el tipo de dato, me lo escribe cuando lo ejecuto.
print(0o2276) #en octal, y tambien se puede en hexadecimal con 0
print (a)
print (b)
print("Un \"mensaje\" con comillas") #Imprime una parte del mensaje en comillas
####COMO LEER UN DATO####
"""
nombre=input ('Dame un nombre: ')
edad=int(input('Ingresa tu edad: '))
estatura=float(input('Ingresa tu estatura: '))
x=int ('21') #conversion de entero
print("***Tu nombre es: ", nombre)
print("***Tu edad es: ",edad,',con una estatura de: ',estatura)
#print("***Tu edad es: ",str(edad),',con una estatura de: ',estatura)
# "+" sirve para sumar o concatenar
print('Juan'*4) #Imprime cuatro veces Juan |
# -*- mode: python -*-
# vi: set ft=python :
"""
Downloads a precompiled version of buildifier and makes it available to the
WORKSPACE.
Example:
WORKSPACE:
load("@drake//tools/workspace:mirrors.bzl", "DEFAULT_MIRRORS")
load("@drake//tools/workspace/buildifier:repository.bzl", "buildifier_repository") # noqa
buildifier_repository(name = "foo", mirrors = DEFAULT_MIRRORS)
BUILD:
sh_binary(
name = "foobar",
srcs = ["bar.sh"],
data = ["@foo//:buildifier"],
)
Argument:
name: A unique name for this rule.
"""
load("@drake//tools/workspace:os.bzl", "determine_os")
load(
"@drake//tools/workspace:metadata.bzl",
"generate_repository_metadata",
)
def _impl(repository_ctx):
# Enumerate the possible binaries. Note that the buildifier binaries are
# fully statically linked, so the particular distribution doesn't matter,
# only the kernel.
version = "4.2.0"
darwin_urls = [
x.format(version = version, filename = "buildifier-darwin-amd64")
for x in repository_ctx.attr.mirrors.get("buildifier")
]
darwin_sha256 = "c46ce67b2d98837ec0bdc38cc1032709499c2907fbae874c0bcdda5f1dd1450b" # noqa
linux_urls = [
x.format(version = version, filename = "buildifier-linux-amd64")
for x in repository_ctx.attr.mirrors.get("buildifier")
]
linux_sha256 = "3426f28d817ee5f4c5eba88bfa7c93b0cb9ab7784dd0d065d1e8e64a3fe9f680" # noqa
# Choose which binary to use.
os_result = determine_os(repository_ctx)
if os_result.is_macos:
urls = darwin_urls
sha256 = darwin_sha256
elif os_result.is_ubuntu or os_result.is_manylinux:
urls = linux_urls
sha256 = linux_sha256
else:
fail("Operating system is NOT supported {}".format(os_result))
# Fetch the binary from mirrors.
output = repository_ctx.path("buildifier")
repository_ctx.download(urls, output, sha256, executable = True)
# Add the BUILD file.
repository_ctx.symlink(
Label("@drake//tools/workspace/buildifier:package.BUILD.bazel"),
"BUILD.bazel",
)
# Create a summary file for Drake maintainers. We need to list all
# possible binaries so Drake's mirroring scripts will fetch everything.
generate_repository_metadata(
repository_ctx,
repository_rule_type = "manual",
version = version,
downloads = [
{
"urls": darwin_urls,
"sha256": darwin_sha256,
},
{
"urls": linux_urls,
"sha256": linux_sha256,
},
],
)
buildifier_repository = repository_rule(
attrs = {
"mirrors": attr.string_list_dict(),
},
implementation = _impl,
)
|
import FWCore.ParameterSet.Config as cms
HFRecalParameterBlock = cms.PSet(
HFdepthOneParameterA = cms.vdouble(
0.004123, 0.00602, 0.008201, 0.010489, 0.013379,
0.016997, 0.021464, 0.027371, 0.034195, 0.044807,
0.058939, 0.125497
),
HFdepthOneParameterB = cms.vdouble(
-4e-06, -2e-06, 0.0, 4e-06, 1.5e-05,
2.6e-05, 6.3e-05, 8.4e-05, 0.00016, 0.000107,
0.000425, 0.000209
),
HFdepthTwoParameterA = cms.vdouble(
0.002861, 0.004168, 0.0064, 0.008388, 0.011601,
0.014425, 0.018633, 0.023232, 0.028274, 0.035447,
0.051579, 0.086593
),
HFdepthTwoParameterB = cms.vdouble(
-2e-06, -0.0, -7e-06, -6e-06, -2e-06,
1e-06, 1.9e-05, 3.1e-05, 6.7e-05, 1.2e-05,
0.000157, -3e-06
)
)
|
import struct
class Disk:
BLOCK_SIZE_BYTES = 512 # 4096
ENCODING = 'utf8'
# a row is a block
@classmethod
def disk_init(cls, diskname, nbrOfBlocks=32):
blank_block = bytearray(Disk.BLOCK_SIZE_BYTES)
with open('data/{}'.format(diskname), 'wb+') as f:
[ f.write(blank_block) for _ in range(int(nbrOfBlocks)) ]
@classmethod
def disk_open(cls, diskname):
fl = open('data/{}'.format(diskname), 'rb+')
return fl
@classmethod
def disk_read_int(cls, open_file, blockNumber, offset):
start_address = Disk.BLOCK_SIZE_BYTES * blockNumber
int_val = []
open_file.seek(start_address + offset)
int_val = struct.unpack('i', open_file.read(4))[0]
return int_val
@classmethod
def disk_read_str(cls, open_file, blockNumber, offset):
start_address = Disk.BLOCK_SIZE_BYTES * blockNumber
str_val = []
open_file.seek(start_address + offset)
for _ in range(28):
byte = open_file.read(1)
str_temp = byte.decode('utf8')
if str_temp != '\x00':
str_val.append(str_temp)
# str_val1 = open_file.read(28)
# str_val = str_val1.decode('utf8')
return ''.join(str_val)
@classmethod
def disk_read(cls, open_file, blockNumber):
start_address = Disk.BLOCK_SIZE_BYTES * blockNumber
block_data = []
open_file.seek(start_address)
for _ in range(Disk.BLOCK_SIZE_BYTES // 4):
block_data.append(struct.unpack('i', open_file.read(4))[0])
return block_data
@classmethod
def disk_write(cls, open_file, blockNumber, data, start_address=None):
if start_address == None:
start_address = Disk.BLOCK_SIZE_BYTES * blockNumber
open_file.seek(start_address)
if type(data) == list:
for item in data:
open_file.seek(start_address)
if type(item) == str:
open_file.write(item.encode('utf8'))
start_address += 28
else:
temp = bytes([item])
open_file.write(temp[:])
start_address += 4
else:
# Check the data type to determine how to convert to binary
if type(data) == str:
byte_data = bytearray(data, Disk.ENCODING)
else:
byte_data = bytearray(data)
open_file.write(byte_data[:])
# for debugging
for i in range(10):
print('Block ', i)
print(Disk.disk_read(open_file, i))
@classmethod
def disk_size(cls, open_file):
superblock = Disk.disk_read(open_file, 0)
return superblock[1]
@classmethod
def disk_status(cls, ):
print('The disk is doing GREAT!!')
@classmethod
def disk_close(cls, open_file):
open_file.close()
|
nomeAtleta = True
numAtleta = 0
while nomeAtleta != '':
notaJurado = []
nomeAtleta = input("Nome do atleta: ")
if nomeAtleta == '':
break
else:
nota = 1
for i in range(7):
jurNota = float(input("{}° jurado: ".format(nota)))
notaJurado.append(jurNota)
nota += 1
print("Nome do Atleta: {}".format(nomeAtleta))
nota = 1
cont = 0
for i in range(5):
print("{}° nota: {}".format(nota,notaJurado[cont]))
nota += 1
cont += 1
print("Melhor nota: {}".format(max(notaJurado)))
print("Pior nota: {}".format(min(notaJurado)))
notaJurado.remove(max(notaJurado))
notaJurado.remove(min(notaJurado))
mediaNota = sum(notaJurado) / len(notaJurado)
print("Media das notas: {}".format(round(mediaNota, 2)))
print("\nResultado")
print("Atleta: {} teve uma media de {}!".format(nomeAtleta,round(mediaNota, 2))) |
"""
write the function of pop() or pop(index) in the DynamicArray,
and also decreases 50% of the size when element numbers decreases to N//4
"""
from example_dynamic_array import DynamicArray
class DynamicArray2(DynamicArray):
"""dynamic array, add pop and associated resizing method"""
def pop(self, index=None):
"""
default method: pop the last element and return
but user can also pop index any index in the valid range,
supports negative index
"""
if index is None: index = self._n - 1
if index < 0: index += self._n
if not (index >= 0 and index < self._n):
raise IndexError("invalid index")
returnV = self._A[index]
if index == self._n:
self._n -= 1
else:
# the index is around the middle
B = self._make_array(self._capacity)
B[:index] = self._A[:index]
B[index:self._n-1] = self._A[index+1:self._n] # careful about the index
self._n -= 1
self._A = B
# now check if need to decreases the capacity
if self._n <= self._capacity // 4:
# need to downgrade the size
self._capacity = self._capacity // 4
B = self._make_array(self._capacity)
B[:self._n] = self._A[:self._n]
self._A = B
return returnV
def __str__(self):
"""use in the str(xxx)"""
return " ".join(str(self._A[i]) for i in range(self._n))
if __name__ == '__main__':
a = DynamicArray2()
for i in range(20):
a.append(i)
print(str(a))
print(a.pop(19))
print(str(a))
print(a.pop(5))
print(str(a))
print(a.pop(0))
print(str(a))
for i in range(15, -1, -1):
a.pop(i)
print(str(a))
|
# Copyright 2002-2018 MarkLogic Corporation. All Rights Reserved.
import boto3
import logging
import hashlib
log = logging.getLogger()
log.setLevel(logging.INFO)
# global variables
ec2_client = boto3.client('ec2')
def get_physical_resource_id(request_id):
return hashlib.md5(request_id.encode()).hexdigest()
def get_network_interface_by_id(eni_id):
"""
Use describe network interfaces function instead of ec2_resource.NetworkInterface
:param eni_id:
:return:
"""
response = ec2_client.describe_network_interfaces(
Filters=[{
"Name": "network-interface-id",
"Values": [eni_id]
}]
)
if len(response["NetworkInterfaces"]) == 1:
return response["NetworkInterfaces"][0]
else:
log.error("Get network interface by id %s failed: %s" % (eni_id, str(response)))
def cfn_success_response(event, reuse_physical_id=False, data=None):
return {
"Status": "SUCCESS",
"RequestId": event["RequestId"],
"LogicalResourceId": event["LogicalResourceId"],
"StackId": event["StackId"],
"PhysicalResourceId":
event["PhysicalResourceId"]
if reuse_physical_id
else get_physical_resource_id(event["RequestId"]),
"Data": {} if not data else data
}
def cfn_failure_response(event, reason, data=None):
return {
"Status": "FAILED",
"Reason": reason,
"LogicalResourceId": event["LogicalResourceId"],
"StackId": event["StackId"],
"PhysicalResourceId": get_physical_resource_id(event["RequestId"]),
"Data": {} if not data else data
} |
# Return the number of times that the string "code" appears anywhere in the given string, except we'll accept any letter for the 'd', so "cope" and "cooe" count.
# count_code('aaacodebbb') → 1
# count_code('codexxcode') → 2
# count_code('cozexxcope') → 2
def count_code(str):
n = 0
for i in range(len(str)-3):
if str[i:i+2] + str[i+3] == 'coe': n+= 1
return n
|
import subprocess as proc
_opensslPath = None
def openssl_path():
"""Get full path of the openssl command line tool.
Uses "which" to get the path of the "openssl" command. This can be used to
execute openssl directly without setting shell = True in Popen.
"""
global _opensslPath
if _opensslPath == None:
_opensslPath = proc.check_output("which openssl", shell = True).strip()
return _opensslPath
def call_openssl(args, input = None):
"""Call the openssl command line tool.
"args" should be an array of command line parameters. "input" is an
optional parameter that will be used as standard input to openssl. This
can be used e.g. to quit openssl (input = "Q\n") after it has been startet.
"""
opensslCommandLine = [openssl_path()] + args
openssl = proc.Popen(opensslCommandLine, stdin=proc.PIPE, stdout=proc.PIPE, stderr=proc.PIPE)
(out, err) = openssl.communicate(input)
return {
"out": out,
"err": err,
"code": openssl.returncode
}
|
from flask import Flask, jsonify, request, render_template, redirect, url_for, flash, session
from flaskext.mysql import MySQL
from flask_cors import CORS, cross_origin
from werkzeug.utils import secure_filename
import os
from flask_mail import Mail, Message
import smtplib
app = Flask(__name__)
CORS(app)
mysql = MySQL()
# MySQL configurations
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = 'landowolf10'
app.config['MYSQL_DATABASE_DB'] = 'minitourist'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
app.config['UPLOAD_FOLDER'] = './static/img'
mysql.init_app(app)
app.secret_key = 'mysecretkey'
app.config['MAIL_SERVER'] = 'smtp.gmail.com'
app.config['MAIL_PORT'] = 587
app.config['MAIL_USERNAME'] = 'minitouristcards@gmail.com'
app.config['MAIL_PASSWORD'] = 'MiniTouristCards2020'
app.config['MAIL_USE_TLS'] = True
app.config['MAIL_USE_SSL'] = False
mail = Mail(app)
clientImage = ''
@app.route('/')
def index():
zihuatanejo_parques = [file for file in os.listdir('./static/img/Zihuatanejo/Frente/parques/') if file.endswith('.jpg')]
zihuatanejo_restaurantes = [file for file in os.listdir('./static/img/Zihuatanejo/Frente/restaurantes/') if file.endswith('.jpg')]
zihuatanejo_lugares = [file for file in os.listdir('./static/img/Zihuatanejo/Frente/lugares/') if file.endswith('.jpg')]
zihuatanejo_tiendas = [file for file in os.listdir('./static/img/Zihuatanejo/Frente/tiendas/') if file.endswith('.jpg')]
zihuatanejo_servicios = [file for file in os.listdir('./static/img/Zihuatanejo/Frente/servicios/') if file.endswith('.jpg')]
zihuatanejo_parques_atras = [file for file in os.listdir('./static/img/Zihuatanejo/Atras/parques/') if file.endswith('.jpg')]
zihuatanejo_restaurantes_atras = [file for file in os.listdir('./static/img/Zihuatanejo/Atras/restaurantes/') if file.endswith('.jpg')]
zihuatanejo_lugares_atras = [file for file in os.listdir('./static/img/Zihuatanejo/Atras/lugares/') if file.endswith('.jpg')]
zihuatanejo_tiendas_atras = [file for file in os.listdir('./static/img/Zihuatanejo/Atras/tiendas/') if file.endswith('.jpg')]
zihuatanejo_servicios_atras = [file for file in os.listdir('./static/img/Zihuatanejo/Atras/servicios/') if file.endswith('.jpg')]
print('zihuatanejo_lugares_atras: ' + str(zihuatanejo_lugares_atras))
acapulco_parques = [file for file in os.listdir('./static/img/Acapulco/Frente/parques/') if file.endswith('.jpg')]
acapulco_restaurantes = [file for file in os.listdir('./static/img/Acapulco/Frente/restaurantes/') if file.endswith('.jpg')]
acapulco_lugares = [file for file in os.listdir('./static/img/Acapulco/Frente/lugares/') if file.endswith('.jpg')]
acapulco_tiendas = [file for file in os.listdir('./static/img/Acapulco/Frente/tiendas/') if file.endswith('.jpg')]
acapulco_servicios = [file for file in os.listdir('./static/img/Acapulco/Frente/servicios/') if file.endswith('.jpg')]
sessionInitialized = False
tipoUsuario = ''
if 'user' in session:
sessionInitialized = True
else:
sessionInitialized = False
print('Session: ' + str(sessionInitialized))
return render_template('index.html', zihuatanejo_parques = zihuatanejo_parques, zihuatanejo_restaurantes = zihuatanejo_restaurantes,
zihuatanejo_lugares = zihuatanejo_lugares, zihuatanejo_tiendas = zihuatanejo_tiendas, zihuatanejo_servicios = zihuatanejo_servicios,
acapulco_parques = acapulco_parques, acapulco_restaurantes = acapulco_restaurantes, acapulco_lugares = acapulco_lugares,
acapulco_tiendas = acapulco_tiendas, acapulco_servicios = acapulco_servicios, logged_in = sessionInitialized)
@app.route('/quienes')
def quienesSomos():
sessionInitialized = False
if 'user' in session:
sessionInitialized = True
else:
sessionInitialized = False
print('Session: ' + str(sessionInitialized))
return render_template('quienes_somos.html', logged_in = sessionInitialized)
@app.route('/mt')
def queSonLasMTC():
sessionInitialized = False
if 'user' in session:
sessionInitialized = True
else:
sessionInitialized = False
print('Session: ' + str(sessionInitialized))
return render_template('que_son_las_mtc.html', logged_in = sessionInitialized)
@app.route('/contacto')
def contacto():
sessionInitialized = False
if 'user' in session:
sessionInitialized = True
else:
sessionInitialized = False
print('Session: ' + str(sessionInitialized))
return render_template('contacto.html', logged_in = sessionInitialized)
@app.route('/login')
def login():
sessionInitialized = False
if 'user' in session:
sessionInitialized = True
else:
sessionInitialized = False
print('Session: ' + str(sessionInitialized))
return render_template('login.html', logged_in = sessionInitialized)
@app.route('/clients')
def clientForm():
getAllClients()
sessionInitialized = False
if 'user' in session:
sessionInitialized = True
else:
sessionInitialized = False
print('Session: ' + str(sessionInitialized))
return render_template('add_client.html', client_data = getAllClients(), logged_in = sessionInitialized)
@app.route('/add_clients', methods=['POST'])
def insertClient():
try:
nombre = request.form['name']
direccion = request.form['direction']
telefono = request.form['phone']
email = request.form['email']
psw = request.form['pass']
location = request.form['location']
card_type = request.form['card-type']
front_image = request.files['front_image']
back_image = request.files['back_image']
fileNameFront = secure_filename(front_image.filename)
fileNameBack = secure_filename(back_image.filename)
if location == 'Zihuatanejo':
if card_type == 'lugares':
front_image.save(os.path.join('./static/img/Zihuatanejo/Frente/lugares', fileNameFront))
back_image.save(os.path.join('./static/img/Zihuatanejo/Atras/lugares', fileNameBack))
os.rename('../MinitouristCardsFinal/static/img/Zihuatanejo/Atras/lugares/' + str(fileNameBack),
'../MinitouristCardsFinal/static/img/Zihuatanejo/Atras/lugares/' + str(fileNameFront))
elif card_type == 'parques':
front_image.save(os.path.join('./static/img/Zihuatanejo/Frente/parques', fileNameFront))
back_image.save(os.path.join('./static/img/Zihuatanejo/Atras/parques', fileNameBack))
os.rename('../MinitouristCardsFinal/static/img/Zihuatanejo/Atras/parques/' + str(fileNameBack),
'../MinitouristCardsFinal/static/img/Zihuatanejo/Atras/parques/' + str(fileNameFront))
elif card_type == 'restaurantes':
front_image.save(os.path.join('./static/img/Zihuatanejo/Frente/restaurantes', fileNameFront))
back_image.save(os.path.join('./static/img/Zihuatanejo/Atras/restaurantes', fileNameBack))
os.rename('../MinitouristCardsFinal/static/img/Zihuatanejo/Atras/restaurantes/' + str(fileNameBack),
'../MinitouristCardsFinal/static/img/Zihuatanejo/Atras/restaurantes/' + str(fileNameFront))
elif card_type == 'servicios':
front_image.save(os.path.join('./static/img/Zihuatanejo/Frente/servicios', fileNameFront))
back_image.save(os.path.join('./static/img/Zihuatanejo/Atras/servicios', fileNameBack))
os.rename('../MinitouristCardsFinal/static/img/Zihuatanejo/Atras/servicios/' + str(fileNameBack),
'../MinitouristCardsFinal/static/img/Zihuatanejo/Atras/servicios/' + str(fileNameFront))
elif card_type == 'tiendas':
front_image.save(os.path.join('./static/img/Zihuatanejo/Frente/tiendas', fileNameFront))
back_image.save(os.path.join('./static/img/Zihuatanejo/Atras/tiendas', fileNameBack))
os.rename('../MinitouristCardsFinal/static/img/Zihuatanejo/Atras/tiendas/' + str(fileNameBack),
'../MinitouristCardsFinal/static/img/Zihuatanejo/Atras/tiendas/' + str(fileNameFront))
elif location == 'Acapulco':
if card_type == 'lugares':
front_image.save(os.path.join('./static/img/Acapulco/Frente/lugares', fileNameFront))
back_image.save(os.path.join('./static/img/Acapulco/Atras/lugares', fileNameBack))
os.rename('../MinitouristCardsFinal/static/img/Acapulco/Atras/lugares/' + str(fileNameBack),
'../MinitouristCardsFinal/static/img/Acapulco/Atras/lugares/' + str(fileNameFront))
elif card_type == 'parques':
front_image.save(os.path.join('./static/img/Acapulco/Frente/parques', fileNameFront))
back_image.save(os.path.join('./static/img/Acapulco/Atras/parques', fileNameBack))
os.rename('../MinitouristCardsFinal/static/img/Acapulco/Atras/parques/' + str(fileNameBack),
'../MinitouristCardsFinal/static/img/Acapulco/Atras/parques/' + str(fileNameFront))
elif card_type == 'restaurantes':
front_image.save(os.path.join('./static/img/Acapulco/Frente/restaurantes', fileNameFront))
back_image.save(os.path.join('./static/img/Acapulco/Atras/restaurantes', fileNameBack))
os.rename('../MinitouristCardsFinal/static/img/Acapulco/Atras/restaurantes/' + str(fileNameBack),
'../MinitouristCardsFinal/static/img/Acapulco/Atras/restaurantes/' + str(fileNameFront))
elif card_type == 'servicios':
front_image.save(os.path.join('./static/img/Acapulco/Frente/servicios', fileNameFront))
back_image.save(os.path.join('./static/img/Acapulco/Atras/servicios', fileNameBack))
os.rename('../MinitouristCardsFinal/static/img/Acapulco/Atras/servicios/' + str(fileNameBack),
'../MinitouristCardsFinal/static/img/Acapulco/Atras/servicios/' + str(fileNameFront))
elif card_type == 'tiendas':
front_image.save(os.path.join('./static/img/Acapulco/Frente/tiendas', fileNameFront))
back_image.save(os.path.join('./static/img/Acapulco/Atras/tiendas', fileNameBack))
os.rename('../MinitouristCardsFinal/static/img/Acapulco/Atras/tiendas/' + str(fileNameBack),
'../MinitouristCardsFinal/static/img/Acapulco/Atras/tiendas/' + str(fileNameFront))
print(nombre)
print(direccion)
print(telefono)
print(email)
print(location)
print(card_type)
print("IMAGE: " + fileNameFront)
conn = mysql.connect()
cursor = conn.cursor()
cursor.callproc('spInsertUser', (nombre, direccion, location, telefono, email, psw, fileNameFront, 'Cliente', card_type))
conn.commit()
flash('Cliente agregado correctamente')
return redirect(url_for('clientForm'))
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
@app.route('/edit/<id>')
def updateClientForm(id):
try:
conn = mysql.connect()
cursor = conn.cursor()
cursor.callproc('spGetClientData', [id])
data = cursor.fetchall()
clientData = data[0]
print(clientData)
return render_template('update_client.html', data = clientData)
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
@app.route('/update/<id>', methods=['POST'])
def updateClient(id):
try:
if request.method == 'POST':
nombre = request.form['client']
direccion = request.form['direction']
location = request.form['location']
telefono = request.form['phone']
email = request.form['email']
oldImage = request.form['old-img']
cardType = request.form['card-type']
newCard = request.form['new-card']
newCardBack = request.form['new-card-back']
f = request.files['front-image']
fileNameBack = request.files['back-image']
print("OLD IMAGE: " + oldImage)
print("LOCATION: " + location)
print("CARD TYPE: " + cardType)
print("NEW CARD: " + newCard)
if oldImage != newCard:
deleteImage(oldImage, location, cardType)
fileName = secure_filename(f.filename)
print('fileName: ' + fileName)
clientLocation = selectClientLocation(id)
newClientImage = newCard.replace(' ', '_')
conn2 = mysql.connect()
cursor2 = conn2.cursor()
cursor2.callproc('spUpdateOldImage', (newClientImage, oldImage, clientLocation[0]))
conn2.commit()
if location == 'Zihuatanejo':
if cardType == 'parques':
f.save(os.path.join('./static/img/Zihuatanejo/Frente/' + cardType, fileName))
os.rename('../MinitouristCardsFinal/static/img/Zihuatanejo/Atras/parques/' + str(oldImage),
'../MinitouristCardsFinal/static/img/Zihuatanejo/Atras/parques/' + str(newClientImage))
elif cardType == 'restaurantes':
f.save(os.path.join('./static/img/Zihuatanejo/Frente/' + cardType, fileName))
os.rename('../MinitouristCardsFinal/static/img/Zihuatanejo/Atras/restaurantes/' + str(oldImage),
'../MinitouristCardsFinal/static/img/Zihuatanejo/Atras/restaurantes/' + str(newClientImage))
elif cardType == 'lugares':
f.save(os.path.join('./static/img/Zihuatanejo/Frente/' + cardType, fileName))
os.rename('../MinitouristCardsFinal/static/img/Zihuatanejo/Atras/lugares/' + str(oldImage),
'../MinitouristCardsFinal/static/img/Zihuatanejo/Atras/lugares/' + str(newClientImage))
elif cardType == 'tiendas':
f.save(os.path.join('./static/img/Zihuatanejo/Frente/' + cardType, fileName))
os.rename('../MinitouristCardsFinal/static/img/Zihuatanejo/Atras/tiendas/' + str(oldImage),
'../MinitouristCardsFinal/static/img/Zihuatanejo/Atras/tiendas/' + str(newClientImage))
elif cardType == 'servicios':
f.save(os.path.join('./static/img/Zihuatanejo/Frente/' + cardType, fileName))
os.rename('../MinitouristCardsFinal/static/img/Zihuatanejo/Atras/servicios/' + str(oldImage),
'../MinitouristCardsFinal/static/img/Zihuatanejo/Atras/servicios/' + str(newClientImage))
elif location == 'Acapulco':
if cardType == 'parques':
f.save(os.path.join('./static/img/Acapulco/Frente/' + cardType, fileName))
os.rename('../MinitouristCardsFinal/static/img/Acapulco/Atras/parques/' + str(oldImage),
'../MinitouristCardsFinal/static/img/Acapulco/Atras/parques/' + str(newClientImage))
elif cardType == 'restaurantes':
f.save(os.path.join('./static/img/Acapulco/Frente/' + cardType, fileName))
os.rename('../MinitouristCardsFinal/static/img/Acapulco/Atras/restaurantes/' + str(oldImage),
'../MinitouristCardsFinal/static/img/Acapulco/Atras/restaurantes/' + str(newClientImage))
elif cardType == 'lugares':
f.save(os.path.join('./static/img/Acapulco/Frente/' + cardType, fileName))
os.rename('../MinitouristCardsFinal/static/img/Acapulco/Atras/lugares/' + str(oldImage),
'../MinitouristCardsFinal/static/img/Acapulco/Atras/lugares/' + str(newClientImage))
elif cardType == 'tiendas':
f.save(os.path.join('./static/img/Acapulco/Frente/' + cardType, fileName))
os.rename('../MinitouristCardsFinal/static/img/Acapulco/Atras/tiendas/' + str(oldImage),
'../MinitouristCardsFinal/static/img/Acapulco/Atras/tiendas/' + str(newClientImage))
elif cardType == 'servicios':
f.save(os.path.join('./static/img/Acapulco/Frente/' + cardType, fileName))
os.rename('../MinitouristCardsFinal/static/img/Acapulco/Atras/servicios/' + str(oldImage),
'../MinitouristCardsFinal/static/img/Acapulco/Atras/servicios/' + str(newClientImage))
if oldImage != newCardBack:
deleteImageBack(oldImage, location, cardType)
fileNameBackOld = secure_filename(fileNameBack.filename)
print('fileNameBackOld: ' + fileNameBackOld)
newClientImageBack = oldImage.replace(' ', '_')
if location == 'Zihuatanejo':
if cardType == 'parques':
fileNameBack.save(os.path.join('./static/img/Zihuatanejo/Atras/' + cardType, fileNameBackOld))
os.rename('../MinitouristCardsFinal/static/img/Zihuatanejo/Atras/parques/' + str(fileNameBackOld),
'../MinitouristCardsFinal/static/img/Zihuatanejo/Atras/parques/' + str(newClientImageBack))
elif cardType == 'restaurantes':
fileNameBack.save(os.path.join('./static/img/Zihuatanejo/Atras/' + cardType, fileNameBackOld))
elif cardType == 'lugares':
fileNameBack.save(os.path.join('./static/img/Zihuatanejo/Atras/' + cardType, fileNameBackOld))
os.rename('../MinitouristCardsFinal/static/img/Zihuatanejo/Atras/lugares/' + str(fileNameBackOld),
'../MinitouristCardsFinal/static/img/Zihuatanejo/Atras/lugares/' + str(newClientImageBack))
elif cardType == 'tiendas':
fileNameBack.save(os.path.join('./static/img/Zihuatanejo/Atras/' + cardType, fileNameBackOld))
os.rename('../MinitouristCardsFinal/static/img/Zihuatanejo/Atras/tiendas/' + str(fileNameBackOld),
'../MinitouristCardsFinal/static/img/Zihuatanejo/Atras/tiendas/' + str(newClientImageBack))
elif cardType == 'servicios':
fileNameBack.save(os.path.join('./static/img/Zihuatanejo/Atras/' + cardType, fileNameBackOld))
os.rename('../MinitouristCardsFinal/static/img/Zihuatanejo/Atras/servicios/' + str(fileNameBackOld),
'../MinitouristCardsFinal/static/img/Zihuatanejo/Atras/servicios/' + str(newClientImageBack))
elif location == 'Acapulco':
if cardType == 'parques':
fileNameBack.save(os.path.join('./static/img/Acapulco/Atras/' + cardType, fileNameBackOld))
os.rename('../MinitouristCardsFinal/static/img/Acapulco/Atras/parques/' + str(fileNameBackOld),
'../MinitouristCardsFinal/static/img/Acapulco/Atras/parques/' + str(newClientImageBack))
elif cardType == 'restaurantes':
fileNameBack.save(os.path.join('./static/img/Acapulco/Atras/' + cardType, fileNameBackOld))
os.rename('../MinitouristCardsFinal/static/img/Acapulco/Atras/restaurantes/' + str(fileNameBackOld),
'../MinitouristCardsFinal/static/img/Acapulco/Atras/restaurantes/' + str(newClientImageBack))
elif cardType == 'lugares':
fileNameBack.save(os.path.join('./static/img/Acapulco/Atras/' + cardType, fileNameBackOld))
os.rename('../MinitouristCardsFinal/static/img/Acapulco/Atras/lugares/' + str(fileNameBackOld),
'../MinitouristCardsFinal/static/img/Acapulco/Atras/lugares/' + str(newClientImageBack))
elif cardType == 'tiendas':
fileNameBack.save(os.path.join('./static/img/Acapulco/Atras/' + cardType, fileNameBackOld))
os.rename('../MinitouristCardsFinal/static/img/Acapulco/Atras/tiendas/' + str(fileNameBackOld),
'../MinitouristCardsFinal/static/img/Acapulco/Atras/tiendas/' + str(newClientImageBack))
elif cardType == 'servicios':
fileNameBack.save(os.path.join('./static/img/Acapulco/Atras/' + cardType, fileNameBackOld))
os.rename('../MinitouristCardsFinal/static/img/Acapulco/Atras/servicios/' + str(fileNameBackOld),
'../MinitouristCardsFinal/static/img/Acapulco/Atras/servicios/' + str(newClientImageBack))
conn = mysql.connect()
cursor = conn.cursor()
cursor.callproc('spUpdateClient', (id, nombre, direccion, telefono, email, newCard))
conn.commit()
flash('Cliente actualizado correctamente')
return redirect(url_for('clientForm'))
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
@app.route('/delete/<id>')
def deleteClient(id):
try:
conn = mysql.connect()
cursor = conn.cursor()
image = selectClientImage(id)
clientLocation = selectClientLocation(id)
clientImage = image.replace(' ', '_')
cursor.callproc('spDeleteClient', (id, clientImage, clientLocation[0]))
conn.commit()
print('Image to delete: ' + clientImage)
deleteImage(clientImage, clientLocation[0], clientLocation[1])
deleteImageBack(clientImage, clientLocation[0], clientLocation[1])
flash('Cliente eliminado correctamente')
return redirect(url_for('clientForm'))
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
@app.route('/login_data', methods=['POST'])
def loginData():
try:
msg = ''
correo = request.form['correo']
password = request.form['pass']
conn = mysql.connect()
cursor = conn.cursor()
cursor.callproc('spLogin', (correo, password))
data = cursor.fetchall()
if data:
mail = data[0][5]
psw = data[0][6]
loginData.clientImage = data[0][7]
tipoUsuario = data[0][8]
session["tipo_usuario"] = tipoUsuario
print('Logged user: ' + tipoUsuario)
if tipoUsuario == 'Administrador':
msg = redirect(url_for('clientForm'))
elif tipoUsuario == 'Cliente':
msg = redirect(url_for('tarjetaStatus'))
session["user"] = correo
else:
flash('Usuario y/o contraseña incorrectos')
print('Usuario y/o contraseña incorrectos')
msg = redirect(url_for('login'))
return msg
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
@app.route('/logout')
def logout():
session.pop('user', None)
session.pop('tipo_usuario', None)
return render_template('login.html')
@app.route('/visitas_descargas', methods=['POST'])
def insertarTarjetaVisitaDescarga():
try:
jsonData = request.json
print('JSON DATA: ' + str(jsonData))
nombre = jsonData['nombre']
ciudad = jsonData['ciudad']
tipo = jsonData['tipo']
conn = mysql.connect()
cursor = conn.cursor()
cursor.callproc('spTarjetaStatus', [nombre, ciudad, tipo])
conn.commit()
resp = jsonify('Tarjeta visitada')
resp.status_code = 200
return resp
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
@app.route('/tarjeta_status')
def tarjetaStatus():
dashboardRedirect = ''
if "user" in session:
getAllClients()
status = getCardStatus()
sessionInitialized = False
if 'user' in session:
sessionInitialized = True
else:
sessionInitialized = False
print('Session: ' + str(sessionInitialized))
tipoUsuario = session['tipo_usuario']
print('tipoUsuario: ' + tipoUsuario)
if 'tipo_usuario' in session:
if tipoUsuario == 'Administrador':
print('Admin')
getAllClients()
dashboardRedirect = render_template('add_client.html', client_data = getAllClients(), logged_in = sessionInitialized)
elif tipoUsuario == 'Cliente':
print('Client')
dashboardRedirect = render_template('client_view.html', visitas = status[0], descargas = status[1], logged_in = sessionInitialized)
return dashboardRedirect
else:
return render_template('login.html')
def getAllClients():
try:
conn = mysql.connect()
cursor = conn.cursor()
cursor.callproc('spShowClients')
data = cursor.fetchall()
return data
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
@app.route('/show_all', methods=['POST'])
def getCardStatus():
try:
clientImage = loginData.clientImage.replace(' ', '_')
print('clientImage: ' + clientImage)
conn = mysql.connect()
cursor = conn.cursor()
cursor.callproc('spMostrarVisitas', [clientImage])
data = cursor.fetchall()
cursor2 = conn.cursor()
cursor2.callproc('spMostrarDescargas', [clientImage])
data2 = cursor2.fetchall()
visitas = data[0][0]
descargas = data2[0][0]
print('VISITAS: ' + str(visitas))
print('DESCARGAS: ' + str(descargas))
return visitas, descargas
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
@app.route('/show_card_info_date', methods=['POST'])
def getCardStatusDate():
try:
clientImage = loginData.clientImage.replace(' ', '_')
date = request.get_json()
fecha = date['fecha'].replace('/', '-')
print(fecha)
conn = mysql.connect()
cursor = conn.cursor()
cursor.callproc('spMostrarDescargasFecha', [clientImage, fecha])
data = cursor.fetchall()
cursor2 = conn.cursor()
cursor2.callproc('spMostrarVisitasFecha', [clientImage, fecha])
data2 = cursor2.fetchall()
descargas = data[0][0]
visitas = data2[0][0]
print('VISITAS: ' + str(visitas))
print('DESCARGAS: ' + str(descargas))
cardInfo = {
'visitas': visitas,
'descargas': descargas
}
print(cardInfo)
return cardInfo
except Exception as e:
print(e)
@app.route('/show_card_info_range', methods=['POST'])
def getCardStatusRangeDate():
try:
clientImage = loginData.clientImage.replace(' ', '_')
date = request.get_json()
fecha_inicio = date['fecha_inicio'].replace('/', '-')
fecha_fin = date['fecha_fin'].replace('/', '-')
conn = mysql.connect()
cursor = conn.cursor()
cursor.callproc('spMostrarDescargasRangoFecha', [clientImage, fecha_inicio, fecha_fin])
data = cursor.fetchall()
cursor2 = conn.cursor()
cursor2.callproc('spMostrarVisitasRangoFecha', [clientImage, fecha_inicio, fecha_fin])
data2 = cursor2.fetchall()
descargas = data[0][0]
visitas = data2[0][0]
print('VISITAS: ' + str(visitas))
print('DESCARGAS: ' + str(descargas))
cardInfo = {
'visitas': visitas,
'descargas': descargas
}
print(cardInfo)
return cardInfo
except Exception as e:
print(e)
def selectClientImage(id):
try:
conn = mysql.connect()
cursor = conn.cursor()
cursor.callproc('spSelectClientData', [id])
data = cursor.fetchall()
imageName = data[0][1]
print('imageName: ' + str(imageName))
return imageName
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
def selectOldClientImage(imageName, clientLocation):
try:
conn = mysql.connect()
cursor = conn.cursor()
cursor.callproc('spSelectOldImage', [imageName, clientLocation])
data = cursor.fetchall()
imageName = data[0][1]
print('imageName: ' + str(imageName))
return imageName
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
def selectClientLocation(id):
try:
conn = mysql.connect()
cursor = conn.cursor()
cursor.callproc('spSelectClientLocation', [id])
data = cursor.fetchall()
clientLocation = data[0][0]
cardType = data[0][1]
print(clientLocation)
print(cardType)
return clientLocation, cardType
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
def deleteImage(image, location, cardType):
imageToDelete = image.replace(' ', '_')
print('IMAGE TO DELETE: ' + imageToDelete)
print('LOCATION: ' + location)
print('CARD TYPE: ' + cardType)
if location == 'Zihuatanejo':
if cardType == 'lugares':
if os.path.exists('./static/img/Zihuatanejo/Frente/' + cardType + '/' + imageToDelete):
os.remove('./static/img/Zihuatanejo/Frente/' + cardType + '/' + imageToDelete)
message = "Cliente eliminado"
else:
message = 'El archivo no existe'
elif cardType == 'parques':
if os.path.exists('./static/img/Zihuatanejo/Frente/' + cardType + '/' + imageToDelete):
os.remove('./static/img/Zihuatanejo/Frente/' + cardType + '/' + imageToDelete)
message = "Cliente eliminado"
else:
message = 'El archivo no existe'
elif cardType == 'restaurantes':
if os.path.exists('./static/img/Zihuatanejo/Frente/' + cardType + '/' + imageToDelete):
os.remove('./static/img/Zihuatanejo/Frente/' + cardType + '/' + imageToDelete)
message = "Cliente eliminado"
else:
message = 'El archivo no existe'
elif cardType == 'servicios':
if os.path.exists('./static/img/Zihuatanejo/Frente/' + cardType + '/' + imageToDelete):
os.remove('./static/img/Zihuatanejo/Frente/' + cardType + '/' + imageToDelete)
message = "Cliente eliminado"
else:
message = 'El archivo no existe'
elif cardType == 'tiendas':
if os.path.exists('./static/img/Zihuatanejo/Frente/' + cardType + '/' + imageToDelete):
os.remove('./static/img/Zihuatanejo/Frente/' + cardType + '/' + imageToDelete)
message = "Cliente eliminado"
else:
message = 'El archivo no existe'
elif location == 'Acapulco':
if cardType == 'lugares':
if os.path.exists('./static/img/Acapulco/Frente/' + cardType + '/' + imageToDelete):
os.remove('./static/img/Acapulco/Frente/' + cardType + '/' + imageToDelete)
message = "Cliente eliminado"
else:
message = 'El archivo no existe'
elif cardType == 'parques':
if os.path.exists('./static/img/Acapulco/Frente/' + cardType + '/' + imageToDelete):
os.remove('./static/img/Acapulco/Frente/' + cardType + '/' + imageToDelete)
message = "Cliente eliminado"
else:
message = 'El archivo no existe'
elif cardType == 'restaurantes':
if os.path.exists('./static/img/Acapulco/Frente/' + cardType + '/' + imageToDelete):
os.remove('./static/img/Acapulco/Frente/' + cardType + '/' + imageToDelete)
message = "Cliente eliminado"
else:
message = 'El archivo no existe'
elif cardType == 'servicios':
if os.path.exists('./static/img/Acapulco/Frente/' + cardType + '/' + imageToDelete):
os.remove('./static/img/Acapulco/Frente/' + cardType + '/' + imageToDelete)
message = "Cliente eliminado"
else:
message = 'El archivo no existe'
elif cardType == 'tiendas':
if os.path.exists('./static/img/Acapulco/Frente/' + cardType + '/' + imageToDelete):
os.remove('./static/img/Acapulco/Frente/' + cardType + '/' + imageToDelete)
message = "Cliente eliminado"
else:
message = 'El archivo no existe'
print(message)
def deleteImageBack(image, location, cardType):
imageToDelete = image.replace(' ', '_')
print('IMAGE TO DELETE BACK: ' + imageToDelete)
print('LOCATION BACK: ' + location)
print('CARD TYPE BACK: ' + cardType)
if location == 'Zihuatanejo':
if cardType == 'lugares':
if os.path.exists('./static/img/Zihuatanejo/Atras/' + cardType + '/' + imageToDelete):
os.remove('./static/img/Zihuatanejo/Atras/' + cardType + '/' + imageToDelete)
message = "Cliente eliminado"
else:
message = 'El archivo no existe'
elif cardType == 'parques':
if os.path.exists('./static/img/Zihuatanejo/Atras/' + cardType + '/' + imageToDelete):
os.remove('./static/img/Zihuatanejo/Atras/' + cardType + '/' + imageToDelete)
message = "Cliente eliminado"
else:
message = 'El archivo no existe'
elif cardType == 'restaurantes':
if os.path.exists('./static/img/Zihuatanejo/Atras/' + cardType + '/' + imageToDelete):
os.remove('./static/img/Zihuatanejo/Atras/' + cardType + '/' + imageToDelete)
message = "Cliente eliminado"
else:
message = 'El archivo no existe'
elif cardType == 'servicios':
if os.path.exists('./static/img/Zihuatanejo/Atras/' + cardType + '/' + imageToDelete):
os.remove('./static/img/Zihuatanejo/Atras/' + cardType + '/' + imageToDelete)
message = "Cliente eliminado"
else:
message = 'El archivo no existe'
elif cardType == 'tiendas':
if os.path.exists('./static/img/Zihuatanejo/Atras/' + cardType + '/' + imageToDelete):
os.remove('./static/img/Zihuatanejo/Atras/' + cardType + '/' + imageToDelete)
message = "Cliente eliminado"
else:
message = 'El archivo no existe'
elif location == 'Acapulco':
if cardType == 'lugares':
if os.path.exists('./static/img/Acapulco/Atras/' + cardType + '/' + imageToDelete):
os.remove('./static/img/Acapulco/Atras/' + cardType + '/' + imageToDelete)
message = "Cliente eliminado"
else:
message = 'El archivo no existe'
elif cardType == 'parques':
if os.path.exists('./static/img/Acapulco/Atras/' + cardType + '/' + imageToDelete):
os.remove('./static/img/Acapulco/Atras/' + cardType + '/' + imageToDelete)
message = "Cliente eliminado"
else:
message = 'El archivo no existe'
elif cardType == 'restaurantes':
if os.path.exists('./static/img/Acapulco/Atras/' + cardType + '/' + imageToDelete):
os.remove('./static/img/Acapulco/Atras/' + cardType + '/' + imageToDelete)
message = "Cliente eliminado"
else:
message = 'El archivo no existe'
elif cardType == 'servicios':
if os.path.exists('./static/img/Acapulco/Atras/' + cardType + '/' + imageToDelete):
os.remove('./static/img/Acapulco/Atras/' + cardType + '/' + imageToDelete)
message = "Cliente eliminado"
else:
message = 'El archivo no existe'
elif cardType == 'tiendas':
if os.path.exists('./static/img/Acapulco/Atras/' + cardType + '/' + imageToDelete):
os.remove('./static/img/Acapulco/Atras/' + cardType + '/' + imageToDelete)
message = "Cliente eliminado"
else:
message = 'El archivo no existe'
print(message)
@app.route('/send_email', methods=['POST'])
def sendEmail():
if request.method == 'POST':
nombre = request.form['name']
email = request.form['email']
telefono = request.form['phone']
asunto = request.form['asunto']
mensaje = request.form['mensaje']
msg = Message(asunto, sender='minitouristcards@gmail.com', recipients=['minitouristcards@gmail.com'])
msg.body = 'Mensaje de ' + nombre + '\n' + 'Email: ' + email + '\n' + 'Teléfono: ' + telefono + '\n\n\n' + mensaje
mail.send(msg)
flash('Mensaje enviado correctamente')
return redirect(url_for('contacto'))
@app.route('/tarjetas_lugares_zihua', methods=['GET'])
def zihuaCardsLugares():
try:
conn = mysql.connect()
cursor = conn.cursor()
cursor.callproc('spContarTarjetasLugaresZihua')
data = cursor.fetchall()
print('spContarTarjetasLugaresZihua: ' + str(data[0][0]))
return str(data[0][0])
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
@app.route('/tarjetas_restaurantes_zihua', methods=['GET'])
def zihuaCardsRestaurantes():
try:
conn = mysql.connect()
cursor = conn.cursor()
cursor.callproc('spContarTarjetasRestZihua')
data = cursor.fetchall()
print(data[0][0])
return str(data[0][0])
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
@app.route('/tarjetas_parques_zihua', methods=['GET'])
def zihuaCardsParques():
try:
conn = mysql.connect()
cursor = conn.cursor()
cursor.callproc('spContarTarjetasParquesZihua')
data = cursor.fetchall()
print(data[0][0])
return str(data[0][0])
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
@app.route('/tarjetas_tiendas_zihua', methods=['GET'])
def zihuaCardsTiendas():
try:
conn = mysql.connect()
cursor = conn.cursor()
cursor.callproc('spContarTarjetasTiendasZihua')
data = cursor.fetchall()
print(data[0][0])
return str(data[0][0])
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
@app.route('/tarjetas_servicios_zihua', methods=['GET'])
def zihuaCardsServicios():
try:
conn = mysql.connect()
cursor = conn.cursor()
cursor.callproc('spContarTarjetasServiciosZihua')
data = cursor.fetchall()
print(data[0][0])
return str(data[0][0])
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
@app.route('/tarjetas_lugares_acapulco', methods=['GET'])
def acapulcoCardsLugares():
try:
conn = mysql.connect()
cursor = conn.cursor()
cursor.callproc('spContarTarjetasLugaresAcapulco')
data = cursor.fetchall()
print('spContarTarjetasLugaresAcapulco: ' + str(data[0][0]))
return str(data[0][0])
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
@app.route('/tarjetas_restaurantes_acapulco', methods=['GET'])
def acapulcoCardsRestaurantes():
try:
conn = mysql.connect()
cursor = conn.cursor()
cursor.callproc('spContarTarjetasRestAcapulco')
data = cursor.fetchall()
print(data[0][0])
return str(data[0][0])
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
@app.route('/tarjetas_parques_acapulco', methods=['GET'])
def acapulcoCardsParques():
try:
conn = mysql.connect()
cursor = conn.cursor()
cursor.callproc('spContarTarjetasParquesAcapulco')
data = cursor.fetchall()
print(data[0][0])
return str(data[0][0])
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
@app.route('/tarjetas_tiendas_acapulco', methods=['GET'])
def acapulcoCardsTiendas():
try:
conn = mysql.connect()
cursor = conn.cursor()
cursor.callproc('spContarTarjetasTiendasAcapulco')
data = cursor.fetchall()
print(data[0][0])
return str(data[0][0])
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
@app.route('/tarjetas_servicios_acapulco', methods=['GET'])
def acapulcoCardsServicios():
try:
conn = mysql.connect()
cursor = conn.cursor()
cursor.callproc('spContarTarjetasServiciosAcapulco')
data = cursor.fetchall()
print(data[0][0])
return str(data[0][0])
except Exception as e:
print(e)
finally:
cursor.close()
conn.close()
if __name__ == '__main__':
app.run(host= '0.0.0.0', port = 5000) |
import os
class PathDataRaw:
"""
class generated for reading data
"""
data = 'data'
data_abreviacion = os.path.join(data, 'abreviacion_estados.csv')
class PathOutput:
"""
class generated for output data
"""
output = 'output'
output_EDA_tables = os.path.join(output, 'tables_EDA')
output_data_core = os.path.join(output, 'data_core')
output_map = os.path.join(output, 'maps')
|
import pycxsimulator
from pylab import *
import networkx as nx
functioning = 1
failed = 0
capacity = 1.0
maxInitialLoad = 0.6
def initialize():
global time, network, positions
time = 0
network = nx.watts_strogatz_graph(200, 4, 0.02)
for nd in network.nodes:
network.nodes[nd]['state'] = functioning
network.nodes[nd]['load'] = random() * maxInitialLoad
network.nodes[choice(list(network.nodes))]['load'] = 2.0 * capacity
positions = nx.circular_layout(network)
def observe():
cla()
nx.draw(network, with_labels = False, pos = positions,
cmap = cm.jet, vmin = 0, vmax = capacity,
node_color = [network.nodes[nd]['load'] for nd in network.nodes])
axis('image')
title('t = ' + str(time))
def update():
global time, network
time += 1
node_IDs = list(network.nodes)
shuffle(node_IDs)
for nd in node_IDs:
if network.nodes[nd]['state'] == functioning:
ld = network.nodes[nd]['load']
if ld > capacity:
network.nodes[nd]['state'] = failed
nbs = [nb for nb in network.neighbors(nd) if network.nodes[nb]['state'] == functioning]
if len(nbs) > 0:
loadDistributed = ld / len(nbs)
for nb in nbs:
network.nodes[nb]['load'] += loadDistributed
pycxsimulator.GUI().start(func=[initialize, observe, update])
|
#!/usr/bin/env python3
import os
import sys
import subprocess
from typing import TextIO
import jsonpickle # python3 -m pip install jsonpickle
import argparse
#######################################################################################################################
##Class Definitions
#######################################################################################################################
class GitRepository:
# absolutePath = "" //We dont use absolute paths anymore, since this should work "portable" on different machines
repoName = ""
branchName = ""
commitID = ""
upstreamPath= ""
detachedHead = False
cleanState = False
def __init__(self, path):
#self.absolutePath = os.path.abspath(path)
#As this is a git repository, I assume it contains a ".git" folder ;)
self.repoName = os.path.basename(path)
def __str__(self):
#return "relativePath = " + self.relativePath +
# "branchName = " + self.branchName + ", commitID = " + self.commitID
return "relativePath = %-*s branchName = %-*s commitID = %*s" % \
(35, self.repoName, 20, self.branchName, 20, self.commitID)
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
#######################################################################################################################
##Function Definitions
#######################################################################################################################
def identifyGitRepositories(out_ListOfFoundRepos, absolutePathToSearch, printInformation: bool):
"""
Searches for git repositories within an given absolute path
:param out_ListOfFoundRepos: A list of found repositories of type GitRepository
:param absolutePathToSearch: Directory which will be scanned (one level) for git repositories
:param printInformation: True: Print which directory is used and its Content
"""
dirContent = os.listdir(absolutePathToSearch)
if(printInformation):
print("Given searchDirectory: " + absolutePathToSearch)
print("Content of this directory: " + str(dirContent))
#Search for git repositories (contain .git) and save them in gitRepositories
for item in dirContent:
absoluteItemPath = os.path.join(absolutePathToSearch, item)
if(os.path.isdir(absoluteItemPath)):
if(os.listdir(absoluteItemPath).count(".git")):
#print("Git repository found in " + relativeDirPath)
out_ListOfFoundRepos.append(GitRepository(absoluteItemPath))
out_ListOfFoundRepos.sort(key=lambda x: x.repoName)
#We need to know for each repository the branch name, revision id and upstream url
currentDir = os.curdir
for repo in out_ListOfFoundRepos: # type: GitRepository
#os.chdir(os.path.abspath(repoDir))
# p1 = subprocess.Popen(["git", "branch"], cwd=os.path.abspath(repoDir), stdout=subprocess.PIPE)
# p2 = subprocess.Popen(["grep", "\*"], cwd=os.path.abspath(repoDir), stdin=p1.stdout, stdout=subprocess.PIPE)
# p3 = subprocess.Popen(["cut", "-d ' ' -f2-"], cwd=os.path.abspath(repoDir), stdin=p2.stdout, stdout=subprocess.PIPE)
# p1.stdout.close()
# p2.stdout.close()
# output,err = p3.communicate()
# print(output)
# print(err)
#stdout argument is required to store the stdout-output in a variable
#universal_newlines is required to get a "string" not byte-values from stdout
#TODO: Check for detached head
absoluteRepoPath = os.path.join(absolutePathToSearch, repo.repoName)
p1 = subprocess.run(["git", "rev-parse", "--abbrev-ref", "HEAD"], cwd=absoluteRepoPath, stdout=subprocess.PIPE, universal_newlines=True)
repo.branchName = p1.stdout.strip() # remove the trailing newline \n
p2 = subprocess.run(["git", "rev-parse", "HEAD"], cwd=absoluteRepoPath, stdout=subprocess.PIPE, universal_newlines=True)
repo.commitID = p2.stdout.strip() # remove the trailing newline \n
p3 = subprocess.run(["git", "ls-remote", "--get-url"], cwd=absoluteRepoPath, stdout=subprocess.PIPE, universal_newlines=True)
repo.upstreamPath = p3.stdout.strip() # remove the trailing newline \n
def checkIfRepoIsClean(repo: GitRepository, absolutePathToSearch):
"""
Checks a given repository if the working directory is "clean".
:param repo: Git Repository to check
:param absolutePathToSearch: Absolute Path where repo should be inside
:return: True: If repository is in a CLEAN state (No changes, nothing in stage), False otherwise
"""
p1 = subprocess.run(["git", "status", "--porcelain"], cwd=os.path.join(absolutePathToSearch, repo.repoName),
stdout=subprocess.PIPE, universal_newlines=True)
status = p1.stdout.strip() # remove the trailing newline \n
if(status == ""):
print("%-*s is in CLEAR state" % (35, repo.repoName))
return True
else:
print(bcolors.FAIL + "%-*s is in NOT CLEAR state" % (35, repo.repoName) + bcolors.ENDC)
return False
def checkoutCommit(repo: GitRepository, absolutePathToSearch):
"""
Try to checkout the working directory of given Git Repository to specific commitID
:param repo: Git repository to work on
:param absolutePathToSearch: Absolute Path where repo should be inside
"""
#First fetch everything, to be able to checkout commits which are still on remote
p0 = subprocess.run(["git", "fetch", "--all"], cwd=os.path.join(absolutePathToSearch, repo.repoName),
stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
universal_newlines=True)
print("{0}: {1})".format(repo.repoName, p0.stdout.strip()))
p1 = subprocess.run(["git", "checkout", repo.commitID], cwd=os.path.join(absolutePathToSearch, repo.repoName),
stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
universal_newlines=True)
status = p1.stdout.strip() # remove the trailing newline \n
print("{0}: {1}".format(repo.repoName, status))
def cloneRepo(repo: GitRepository, absolutePathToSearch):
"""
:param repo: Git repository to clone
:return: True: It seems to have worked successfully, False: Clone failed
"""
p0 = subprocess.run(["git", "clone", repo.upstreamPath, repo.repoName], cwd=absolutePathToSearch,
stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
universal_newlines=True)
print("{0}: {1})".format(repo.repoName, p0.stdout.strip()))
#Check if it was successfull
return checkIfRepoIsClean(repo, absolutePathToSearch)
########################################################################################################################
## Main Definition
########################################################################################################################
def main():
#Execute the main git functionality of this script
parser = argparse.ArgumentParser()
parser.add_argument("-d", required=True, help="Specify relative or absolute directory which holds git repositories")
parser.add_argument("-list", action="store_true", help="Just prints a list of found repositories and their state")
parser.add_argument("-save", help="Save the found repositories and their state into FILENAME.json file. This can be used to restore the repos state")
parser.add_argument("-restore", help="Restore repositories according given file FILENAME.json")
parser.add_argument("-force", action="store_true", help="Force to restore repositories, even if exiting ones are not in clean state")
parser.add_argument("-update", action="store_true", help="Effects only with -save option: Just updates repositories, which are defined within the specified output file if it exists already")
args = parser.parse_args()
searchDirectoryAbsolute = os.path.abspath(args.d)
gitRepositories = []
gitRepositoriesReadFromFile = []
print("") # Just formating (Newline)
identifyGitRepositories(gitRepositories, searchDirectoryAbsolute, True)
if(args.list or args.save):
print(*gitRepositories, sep="\n")
print("") #Just formating (Newline)
if(args.save):
if(args.update):
#Only update git repos, which were previously defined within the given json.file
try:
with open(args.save, "r") as jsonFile: # type: TextIO
gitRepositoriesReadFromFile = jsonpickle.decode(jsonFile.read())
except (IOError):
print("Could not open file " + args.restore)
sys.exit(-1)
#foo
gitRepositoriesCleaned = gitRepositories.copy()
for repo in gitRepositories:
found = False
for repoFile in gitRepositoriesReadFromFile:
if repo.repoName == repoFile.repoName:
found = True
break
if found == False:
gitRepositoriesCleaned.remove(repo)
#End clean list of gitRepositories
gitRepositories = gitRepositoriesCleaned
#We want human readable format, not everything in one line
#See https://stackoverflow.com/questions/2664818/serializing-json-files-with-newlines-in-python
jsonpickle.set_encoder_options('json', indent=4)
frozen = jsonpickle.encode(gitRepositories)
with open(args.save, "w") as jsonFile:
jsonFile.write(frozen)
print("Saved repository states to " + args.save)
if(args.restore):
try:
with open(args.restore, "r") as jsonFile: # type: TextIO
gitRepositoriesToRestore = jsonpickle.decode(jsonFile.read())
except (IOError):
print("Could not open file " + args.restore)
sys.exit(-1)
#Check which repositories already exists in given path. If they exists, check if they are in clean state
#If they are in clean state, I assume its save to checkout another changeset
#If they are not in clean state, and -force flag was given, restore it anyway
print("") #Just formating (Newline)
print("Restore already existent repositories. Need to check if this is clean. If not, stop here!")
for repoToRestore in gitRepositoriesToRestore: #type: GitRepository
repoFound = False
for alreadyExitentRepo in gitRepositories: #type: GitRepository
if alreadyExitentRepo.repoName == repoToRestore.repoName:
repoFound = True
if checkIfRepoIsClean(alreadyExitentRepo, searchDirectoryAbsolute) == False:
if(args.force is None):
sys.exit(-1)
break
else:
print("Ignoring not clean repo because of forced mode")
if(repoFound == False and args.force is None):
#Repo seems not to exist. stop here:
print("Repository {0} not found! Stopped here!".format(repoToRestore.repoName))
sys.exit(-1)
if(repoFound == False and args.force is not None):
#Repo seems not to exist, but force mode detected. So its gonna get cloned.
print("Repository {0} not found! Try to clone it!".format(repoToRestore.repoName))
success = cloneRepo(repoToRestore, searchDirectoryAbsolute)
if(success is False):
print("Repository {0} could not get cloned successfully! Stopped here!".format(repoToRestore.repoName))
sys.exit(-1)
#Every repo to restore has a clear state. Checkout desired commit
print("") #Just formating (Newline)
for repoToRestore in gitRepositoriesToRestore: #type: GitRepository
checkoutCommit(repoToRestore, searchDirectoryAbsolute)
#Last step is a final check: But only check repos which are got restored by this!
restoredRepos = []
identifyGitRepositories(restoredRepos, searchDirectoryAbsolute, False)
repositoriesAreEqual = True
#restoredRepos could have more repos, since there could been already git repositories.
#Therefore, we remove all not known repos before proceed with our checks
for repoToRestore in gitRepositoriesToRestore:
if any(x.repoName == repoToRestore.repoName for x in restoredRepos ) == False:
repositoriesAreEqual = False
print("Repository to restore {0} was not found in target directory".format(repoToRestore.repoName))
else:
#Find that element and test the commit ID
for restoredRepository in enumerate(restoredRepos):
if(restoredRepository[1].repoName == repoToRestore.repoName):
if(restoredRepository[1].commitID != repoToRestore.commitID):
print("{0}Final check failed at Repository {1}: CommitID is {2} but should be {3}{4}".format(
bcolors.FAIL, restoredRepository[1].repoName, restoredRepository[1].commitID,
repoToRestore.commitID, bcolors.ENDC))
repositoriesAreEqual = False
else:
#Seems fine, so abort the enumerate loop. We found what we are looking for
break
print("") #Just formating (Newline)
if(repositoriesAreEqual):
print(bcolors.OKGREEN + "Restored Repositories successfully!" + bcolors.ENDC)
print(*gitRepositoriesToRestore, sep="\n")
print("") # Just formating (Newline)
else:
print(bcolors.FAIL + "Restored Repositories NOT successfully!" + bcolors.ENDC)
########################################################################################################################
## Execute main, if this script is not just imported
########################################################################################################################
if __name__ == "__main__":
main()
|
from Errors.Exceptions import RepoError
class Repository:
def __init__(self):
self._entities = []
def add(self, elem):
if elem in self._entities:
raise RepoError("Id already exists!\n")
self._entities.append(elem)
def get_all(self):
return self._entities[:]
class FileRepository(Repository):
def __init__(self, filename, read_object, write_object):
self.__filename = filename
self.__read_object = read_object
self.__write_object = write_object
Repository.__init__(self)
def __read_all_from_file(self):
self._entities = []
with open(self.__filename, "r") as f:
lines = f.readlines()
for line in lines:
line = line.strip()
if line != "":
obj = self.__read_object(line)
self._entities.append(obj)
def __write_all_to_file(self):
with open(self.__filename, "w") as f:
for obj in self._entities:
line = self.__write_object(obj)
f.write(line + "\n")
def add(self, elem):
self.__read_all_from_file()
Repository.add(self, elem)
self.__write_all_to_file()
def get_all(self):
self.__read_all_from_file()
return Repository.get_all(self)
|
class GuseeGame:
def guessing(self,number):
if number<=100:
low=0
high=100
mid=0
while low<=high:
mid=(low+high)//2
c = int(input("enter 1 if number b/w "+str(low)+" -- "+str(mid)+" enter 2 if number b/w "+str(mid+1)+" -- "+str(high)))
if c == 1:
high=mid
return GuseeGame().guessing(high)
else:
low = mid + 1
return low
return low,high
else:
return 0
g=GuseeGame()
number=(int(input("enter the number b/w 1 to 100: ")))
number1=g.guessing(number)
if number1==0:
print("enter the correct number: ")
else:
print("your number is: ",number1) |
import sys
# print( "Name of the script: ", sys.argv[0])
eps_current = int(sys.argv[1])
print ("Input eps =" , int(sys.argv[1]))
import tensorflow as tf
import numpy as np
import os
# Import MNIST data
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/tmp/data/", one_hot=True)
def attack_success_rate(xts, xts_new, yts):
prediction_old = tf.argmax(pred,1)
prediction_old = prediction_old.eval({x: xts})
correct_prediction = tf.equal(prediction_old, tf.argmax(yts, 1))
correct_prediction = correct_prediction.eval({x: xts})
correct_prediction_index = np.where(correct_prediction)
xts_correct = xts_new[correct_prediction_index,:]
xts_correct = xts_correct[0,:,:]
correct_prediction = correct_prediction[correct_prediction_index]
prediction_old = prediction_old[correct_prediction_index]
# Result of new test data
prediction_new = tf.argmax(pred,1)
prediction_new = prediction_new.eval({x:xts_correct})
# Vind out which index of correct_predictions are changed after perturb
attack_success_index = np.not_equal(prediction_old, prediction_new)
# Calculate attack ratio
attack_success_no = np.count_nonzero(attack_success_index)
correct_prediction_no = np.count_nonzero(correct_prediction)
attack_success_rate = attack_success_no/correct_prediction_no
return attack_success_rate
# Parameters
learning_rate = 0.001
training_epochs = 20
batch_size = 100
display_step = 1
# tf Graph Input
x = tf.placeholder(tf.float32, [None, 784]) # mnist data image of shape 28*28=784
y = tf.placeholder(tf.float32, [None, 10]) # 0-9 digits recognition => 10 classes
# grads = tf.placeholder(tf.float32, [None, 784])
# Set model weights
W1 = tf.Variable(tf.random_normal([784, 300], mean=0, stddev=1))
b1 = tf.Variable(tf.random_normal([300], mean=0, stddev = 1))
# #W2 = tf.Variable(tf.random_normal([300, 100], mean=0, stddev= 1))
# #b2 = tf.Variable(tf.random_normal([100], mean=0, stddev= 1))
W3 = tf.Variable(tf.zeros([300, 10]))
b3 = tf.Variable(tf.zeros([10]))
# Construct model
hidden1 = tf.nn.relu(tf.matmul(x, W1) + b1); #first hidden layer
#hidden2 = tf.nn.relu(tf.matmul(hidden1, W2) + b2); #second hidden layer
pred = tf.nn.softmax(tf.matmul(hidden1, W3) + b3) # Softmax layer outputs prediction probabilities
# Minimize error using cross entropy
cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(pred), reduction_indices=1))
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
yt = mnist.test.labels
xt = mnist.test.images
def shift(l, n):
return l[-1:] + l[:-1]
yt_shifted = np.empty_like(yt)
for i in range (np.shape(yt)[0]):
yt_shifted[i, :] = (shift(yt[i,:].tolist(),1))
# grad_W, grad_b = tf.gradients(xs=[W1, b1], ys=cost)
eps = [1, 5, 10, 20, 30, 40, 50]
grad_x = tf.gradients(xs=x, ys=cost)
x_prime1 = tf.clip_by_value(x - eps[0] * tf.sign(grad_x)/256,0,1)
x_prime5 = tf.clip_by_value(x - eps[1] * tf.sign(grad_x)/256,0,1)
x_prime10 = tf.clip_by_value(x - eps[2] * tf.sign(grad_x)/256,0,1)
x_prime20 = tf.clip_by_value(x - eps[3] * tf.sign(grad_x)/256,0,1)
x_prime30 = tf.clip_by_value(x - eps[4] * tf.sign(grad_x)/256,0,1)
x_prime40 = tf.clip_by_value(x - eps[5] * tf.sign(grad_x)/256,0,1)
x_prime50 = tf.clip_by_value(x - eps[6] * tf.sign(grad_x)/256,0,1)
saver = tf.train.Saver()
# Start training
with tf.Session() as sess:
saver.restore(sess, "./checkpoints/trained_model.ckpt")
print("Model restored.")
a1, b1 = sess.run([x_prime1 ,cost], feed_dict={x: xt, y: yt_shifted})
a5, b5 = sess.run([x_prime5 ,cost], feed_dict={x: xt, y: yt_shifted})
a10, b10 = sess.run([x_prime10 ,cost], feed_dict={x: xt, y: yt_shifted})
a20, b20 = sess.run([x_prime20 ,cost], feed_dict={x: xt, y: yt_shifted})
a30, b30 = sess.run([x_prime30 ,cost], feed_dict={x: xt, y: yt_shifted})
a40, b40 = sess.run([x_prime40 ,cost], feed_dict={x: xt, y: yt_shifted})
a50, b50 = sess.run([x_prime50 ,cost], feed_dict={x: xt, y: yt_shifted})
x_new1 = a1[0,:,:]
x_new5 = a5[0,:,:]
x_new10 = a10[0,:,:]
x_new20 = a20[0,:,:]
x_new30 = a30[0,:,:]
x_new40 = a40[0,:,:]
x_new50 = a50[0,:,:]
# np.save('./checkpoints/x_new1_p2', x_new1)
# np.save('./checkpoints/x_new5_p2', x_new5)
# np.save('./checkpoints/x_new10_p2', x_new10)
# np.save('./checkpoints/x_new20_p2', x_new20)
# np.save('./checkpoints/x_new30_p2', x_new30)
# np.save('./checkpoints/x_new40_p2', x_new40)
# np.save('./checkpoints/x_new50_p2', x_new50)
# x_new1 = np.load('./checkpoints/x_new1_p2.npy')
# x_new5 = np.load('./checkpoints/x_new5_p2.npy')
# x_new10 = np.load('./checkpoints/x_new10_p2.npy')
# x_new20 = np.load('./checkpoints/x_new20_p2.npy')
# x_new30 = np.load('./checkpoints/x_new30_p2.npy')
# x_new40 = np.load('./checkpoints/x_new40_p2.npy')
# x_new50 = np.load('./checkpoints/x_new50_p2.npy')
with tf.Session() as sess:
saver.restore(sess, "./checkpoints/trained_model.ckpt")
print("Model restored.")
correct_prediction = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
if eps_current == 1:
print ("Eps=1:\t Accuracy:", "{:10.4f}".format(accuracy.eval({x: x_new1[:3000], y: yt[:3000]})),
"\t Attack Success Rate:\t", attack_success_rate(xt,x_new1,yt))
if eps_current == 5:
print ("Eps=5:\t Accuracy:", "{:10.4f}".format(accuracy.eval({x: x_new5[:3000], y: yt[:3000]})),
"\t Attack Success Rate:\t", attack_success_rate(xt,x_new5,yt))
if eps_current == 10:
print ("Eps=10:\t Accuracy:", "{:10.4f}".format(accuracy.eval({x: x_new10[:3000], y: yt[:3000]})),
"\t Attack Success Rate:\t", attack_success_rate(xt,x_new10,yt))
if eps_current == 20:
print ("Eps=20:\t Accuracy:", "{:10.4f}".format(accuracy.eval({x: x_new20[:3000], y: yt[:3000]})),
"\t Attack Success Rate:\t", attack_success_rate(xt,x_new20,yt))
if eps_current == 30:
print ("Eps=30:\t Accuracy:", "{:10.4f}".format(accuracy.eval({x: x_new30[:3000], y: yt[:3000]})),
"\t Attack Success Rate:\t", attack_success_rate(xt,x_new10,yt))
if eps_current == 40:
print ("Eps=40:\t Accuracy:", "{:10.4f}".format(accuracy.eval({x: x_new40[:3000], y: yt[:3000]})),
"\t Attack Success Rate:\t", attack_success_rate(xt,x_new10,yt))
if eps_current == 50:
print ("Eps=50:\t Accuracy:", "{:10.4f}".format(accuracy.eval({x: x_new50[:3000], y: yt[:3000]})),
"\t Attack Success Rate:\t", attack_success_rate(xt,x_new10,yt))
import matplotlib.pyplot as plt
print("Saving 100 images for each eps")
for i in range (0,100):
plt.imsave('./images/part2/eps1_'+str(i)+'.png', x_new1[i].reshape((28,28)))
plt.imsave('./images/part2/eps5_'+str(i)+'.png', x_new5[i].reshape((28,28)))
plt.imsave('./images/part2/eps10_'+str(i)+'.png', x_new10[i].reshape((28,28)))
plt.imsave('./images/part2/eps20_'+str(i)+'.png', x_new20[i].reshape((28,28)))
plt.imsave('./images/part2/eps30_'+str(i)+'.png', x_new30[i].reshape((28,28)))
plt.imsave('./images/part2/eps40_'+str(i)+'.png', x_new40[i].reshape((28,28)))
plt.imsave('./images/part2/eps50_'+str(i)+'.png', x_new50[i].reshape((28,28))) |
from django.shortcuts import render, redirect
from django.views import View
from django.http import HttpResponse
from django.views.generic import CreateView, ListView, TemplateView, View, UpdateView
from django.urls import reverse_lazy, reverse
from accounts.forms import SignUpUserForm, SignUpCompanyForm, UpdateUserForm
from accounts.models import User, UserProfile
from django.contrib.auth import login
from django.contrib.auth.mixins import LoginRequiredMixin
from jobs.models import Job
REDIRECT_FIELD_NAME = 'index.html'
LOGIN_URL = reverse_lazy('login')
class HomePage(View):
def get(self, request, *args, **kwargs):
if self.request.user.is_authenticated:
if self.request.user.is_company:
return redirect("company:dashboard")
elif self.request.user.is_job_seeker:
return redirect("explore")
elif self.request.user.is_superuser:
return redirect("explore")
else:
jobs = Job.objects.order_by('-date')
return render(request, 'index.html', {"jobs": jobs})
class UserSignUp(CreateView):
model = User
form_class = SignUpUserForm
template_name = 'registration/signup_user.html'
def form_valid(self, form):
user = form.save()
login(self.request, user)
return redirect('index')
class CompanySignUp(CreateView):
model = User
form_class = SignUpCompanyForm
template_name = 'registration/signup_company.html'
def form_valid(self, form):
user = form.save()
login(self.request, user)
return redirect('index')
class UpdateUserProfileView(UpdateView,LoginRequiredMixin):
login_url = LOGIN_URL
redirect_field_name = REDIRECT_FIELD_NAME
model = UserProfile
form_class = UpdateUserForm
success_url = reverse_lazy('index')
template_name = 'registration/signup_user.html'
def get_object(self):
return self.request.user.userprofile
|
from bs4 import BeautifulSoup
import requests
string = "Zynerba Pharmaceuticals"
list_1 = string.split()
url="https://news.google.com/search?q=" + list_1[0] + "%20" + list_1[1]+"&hl=en-US&gl=US&ceid=US%3Aen"
print(url)
code=requests.get(url)
print(code.text)
page_soup=BeautifulSoup(code.text,'html.parser')
bio_tech_companies = page_soup.findAll("div",{"class":"ZulkBc qNiaOd"})
for i in range(len(bio_tech_companies)):
query = str(bio_tech_companies[i].text.strip())
if '%' or 'clinical' or 'trial' or 'investment' in query:
print(query)
print("\n") |
from django.urls import path, re_path
from geofr.views import (
MapView,
DepartmentBackersView,
)
urlpatterns = [
path("", MapView.as_view(), name="map_view"),
re_path(
r"^(?P<code>[0-9AB]{2,3})-(?P<slug>[\w-]+)/porteurs/$",
DepartmentBackersView.as_view(),
name="department_backers_view",
),
]
|
#list is a collection of data elements which is ordered and is muttable
lst=[1,5,"hii",0.5]
print(lst)
print(lst[1])
print(lst[-2])
print(lst[:2])
print(len(lst))
lst[2]="hello"
print(lst)
for x in lst:
print(x)
#inserting into the list
lst.append(50)
print(lst)
lst.insert(0,"lup")
print(lst)
#copying a list to another
mylist=lst.copy()
#counting the number of times a particular element is repeated
y= lst.count("lup")
print(y)
#removing element from the specified index
lst.remove(50)
print(lst)
#removing all the elements from the list
lst.clear()
print(lst)
|
import random
import numpy as np
import pandas as pd
from operator import add
import collections
from random import randint
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import copy
DEVICE = 'cpu' # 'cuda' if torch.cuda.is_available() else 'cpu'
class DQNAgent(torch.nn.Module):
def __init__(self, params):
super().__init__()
self.reward = 0
self.gamma = 0.9
self.dataframe = pd.DataFrame()
self.short_memory = np.array([])
self.agent_target = 1
self.agent_predict = 0
self.learning_rate = params['learning_rate']
self.epsilon = 1
self.actual = []
self.first_layer = params['first_layer_size']
self.second_layer = params['second_layer_size']
self.third_layer = params['third_layer_size']
self.memory = collections.deque(maxlen=params['memory_size'])
self.weights = params['weights_path']
self.load_weights = params['load_weights']
self.optimizer = None
self.network()
self.agent_type = params['agent_type']
if params['train']:
supported_agent_types = {
'q_learning': 'Q-Learning',
'sarsa': 'SARSA',
'expected_sarsa': 'Expected SARSA',
}
if self.agent_type in supported_agent_types:
print('Using', supported_agent_types[self.agent_type])
else:
print('Agent "', self.agent_type, '" not found, using default Q-Learning instead', sep='')
self.agent_type = 'q_learning'
def network(self):
# Layers
self.f1 = nn.Linear(11, self.first_layer)
self.f2 = nn.Linear(self.first_layer, self.second_layer)
self.f3 = nn.Linear(self.second_layer, self.third_layer)
self.f4 = nn.Linear(self.third_layer, 3)
# weights
if self.load_weights:
self.model = self.load_state_dict(torch.load(self.weights))
print("weights loaded")
def forward(self, x):
x = F.relu(self.f1(x))
x = F.relu(self.f2(x))
x = F.relu(self.f3(x))
x = F.softmax(self.f4(x), dim=-1)
return x
def get_state(self, game, player, food):
"""
Return the state.
The state is a numpy array of 11 values, representing:
- Danger 1 OR 2 steps ahead
- Danger 1 OR 2 steps on the right
- Danger 1 OR 2 steps on the left
- Snake is moving left
- Snake is moving right
- Snake is moving up
- Snake is moving down
- The food is on the left
- The food is on the right
- The food is on the upper side
- The food is on the lower side
"""
state = [
(player.x_change == 20 and player.y_change == 0 and ((list(map(add, player.position[-1], [20, 0])) in player.position) or
player.position[-1][0] + 20 >= (game.game_width - 20))) or (player.x_change == -20 and player.y_change == 0 and ((list(map(add, player.position[-1], [-20, 0])) in player.position) or
player.position[-1][0] - 20 < 20)) or (player.x_change == 0 and player.y_change == -20 and ((list(map(add, player.position[-1], [0, -20])) in player.position) or
player.position[-1][-1] - 20 < 20)) or (player.x_change == 0 and player.y_change == 20 and ((list(map(add, player.position[-1], [0, 20])) in player.position) or
player.position[-1][-1] + 20 >= (game.game_height-20))), # danger straight
(player.x_change == 0 and player.y_change == -20 and ((list(map(add,player.position[-1],[20, 0])) in player.position) or
player.position[ -1][0] + 20 > (game.game_width-20))) or (player.x_change == 0 and player.y_change == 20 and ((list(map(add,player.position[-1],
[-20,0])) in player.position) or player.position[-1][0] - 20 < 20)) or (player.x_change == -20 and player.y_change == 0 and ((list(map(
add,player.position[-1],[0,-20])) in player.position) or player.position[-1][-1] - 20 < 20)) or (player.x_change == 20 and player.y_change == 0 and (
(list(map(add,player.position[-1],[0,20])) in player.position) or player.position[-1][
-1] + 20 >= (game.game_height-20))), # danger right
(player.x_change == 0 and player.y_change == 20 and ((list(map(add,player.position[-1],[20,0])) in player.position) or
player.position[-1][0] + 20 > (game.game_width-20))) or (player.x_change == 0 and player.y_change == -20 and ((list(map(
add, player.position[-1],[-20,0])) in player.position) or player.position[-1][0] - 20 < 20)) or (player.x_change == 20 and player.y_change == 0 and (
(list(map(add,player.position[-1],[0,-20])) in player.position) or player.position[-1][-1] - 20 < 20)) or (
player.x_change == -20 and player.y_change == 0 and ((list(map(add,player.position[-1],[0,20])) in player.position) or
player.position[-1][-1] + 20 >= (game.game_height-20))), #danger left
player.x_change == -20, # move left
player.x_change == 20, # move right
player.y_change == -20, # move up
player.y_change == 20, # move down
food.x_food < player.x, # food left
food.x_food > player.x, # food right
food.y_food < player.y, # food up
food.y_food > player.y # food down
]
for i in range(len(state)):
if state[i]:
state[i]=1
else:
state[i]=0
return np.asarray(state)
def set_reward(self, player, crash):
"""
Return the reward.
The reward is:
-10 when Snake crashes.
+10 when Snake eats food
0 otherwise
"""
self.reward = 0
if crash:
self.reward = -10
return self.reward
if player.eaten:
self.reward = 10
return self.reward
def remember(self, state, action, reward, next_state, done):
"""
Store the <state, action, reward, next_state, is_done> tuple in a
memory buffer for replay memory.
"""
self.memory.append((state, action, reward, next_state, done))
def replay_mem(self, memory, batch_size):
"""
Replay memory.
"""
if len(memory) > batch_size:
minibatch = random.sample(memory, batch_size)
else:
minibatch = memory
for state, action, reward, next_state, done in minibatch:
self.train_short_memory(state, action, reward, next_state, done)
def get_epsilon_greedy_action(self, state_old):
"""
Return the epsilon-greedy action for state_old.
"""
if random.uniform(0, 1) < self.epsilon:
# return a random action
final_move = np.eye(3)[randint(0,2)]
else:
# choose the best action based on the old state
with torch.no_grad():
state_old_tensor = torch.tensor(state_old.reshape((1, 11)), dtype=torch.float32).to(DEVICE)
prediction = self(state_old_tensor)
final_move = np.eye(3)[np.argmax(prediction.detach().cpu().numpy()[0])]
return final_move
def get_target(self, reward, next_state):
"""
Return the appropriate TD target depending on the type of the
agent (Q-Learning, SARSA or Expected-SARSA).
"""
next_state_tensor = torch.tensor(next_state.reshape((1, 11)), dtype=torch.float32).to(DEVICE)
q_values_next_state = self.forward(next_state_tensor[0])
if self.agent_type == 'q_learning':
target = reward + self.gamma * torch.max(q_values_next_state) # Q-Learning is off-policy
elif self.agent_type == 'sarsa':
next_action = self.get_epsilon_greedy_action(next_state) # SARSA is on-policy
q_value_next_state_action = q_values_next_state[np.argmax(next_action)]
target = reward + self.gamma * q_value_next_state_action
elif self.agent_type == 'expected_sarsa':
probabilities_for_actions = np.array([self.epsilon/3, self.epsilon/3, self.epsilon/3])
q_values_next_state_numpy = q_values_next_state.detach().cpu().numpy()
best_action_index = np.argmax(q_values_next_state_numpy)
probabilities_for_actions[best_action_index] += 1 - self.epsilon
expected_next_q_value = np.dot(probabilities_for_actions, q_values_next_state_numpy)
target = reward + self.gamma * expected_next_q_value
else:
raise ValueError('agent_type in get_target should necessarily be one of the supported agent types')
return target
def train_short_memory(self, state, action, reward, next_state, done):
"""
Train the DQN agent on the <state, action, reward, next_state, is_done>
tuple at the current timestep.
"""
self.train()
torch.set_grad_enabled(True)
target = reward
state_tensor = torch.tensor(state.reshape((1, 11)), dtype=torch.float32, requires_grad=True).to(DEVICE)
if not done:
target = self.get_target(reward, next_state)
output = self.forward(state_tensor)
target_f = output.clone()
target_f[0][np.argmax(action)] = target
target_f.detach()
self.optimizer.zero_grad()
loss = F.mse_loss(output, target_f)
loss.backward()
self.optimizer.step() |
# See `ExecuteExtraPythonCode` in `pydrake_pybind.h` for usage details and
# rationale.
from pydrake.common.cpp_param import List
def _AbstractValue_Make(value):
"""Returns an AbstractValue containing the given ``value``."""
if isinstance(value, list) and len(value) > 0:
inner_cls = type(value[0])
cls = List[inner_cls]
else:
cls = type(value)
value_cls, _ = Value.get_instantiation(cls, throw_error=False)
if value_cls is None:
value_cls = Value[object]
return value_cls(value)
AbstractValue.Make = _AbstractValue_Make
|
'''
Created on Jun 1, 2018
@author: pjdrm
'''
import urllib.request
import json
import wget
def gyms_info():
response = urllib.request.urlopen('https://raw.githubusercontent.com/pjdrm/PgP-Data/master/data/region-map.json')
html = eval(str(response.read()))
print(html)
#region_map_json = json.loads(html)
#print(region_map_json)
gyms_info() |
# -*- coding:UTF-8 -*-
#!/usr/bin/env python3
import json
schema = {
"股权质押信息": ['股东名称', '是否为第一大股东及一致行动人', '质押股数', '质押开始日期', '解除质押日期', '本次质押占其所持股份比例', '质权人', '用途']
}
print(schema)
with open('股东股权质押事件', 'w') as fo:
fo.write(json.dumps(schema, ensure_ascii=False, indent=4)) |
import math #수학 모듈 사용
#절댓값 알고리즘 1 (부호 판단)
#입력 : 실수 a
#출력 : a의 절댓값
def abs_sign(a):
if a >= 0:
return a
else:
return -a
#절댓값 알고리즘 2 (제곱-제곱근)
#입력 : 실수 a
#출력 : a의 절댓값
def abs_square(a) :
b = a * a
return math.sqrt(b) #수학 모듈의 제곱근 함수
print(abs_sign(5))
print(abs_sign(-3))
print()
print(abs_square(5))
print(abs_square(-3)) |
import os
from celery import Celery
from celery.schedules import crontab
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mcdonalds.settings')
app = Celery('mcdonalds')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()
app.conf.beat_schedule = {
'print_every_5_seconds': {
'task': 'board.tasks.printer',
'schedule': 5,
'args': (5,),
},
}
app.conf.beat_schedule = {
'clear_board_every_minute': {
'task': 'board.tasks.clear_board',
'schedule': crontab(),
},
}
app.conf.beat_schedule = {
'action_every_monday_8am': {
'task': 'action',
'schedule': crontab(hour=8, minute=0, day_of_week='monday'),
#'args': (agrs),
},
}
|
import json
import urllib2
from flask import Blueprint, request, Response
from utils.RobinhoodUtil import RobinhoodUtil
robinhood_api = Blueprint('robinhood_api', __name__)
robinhood_service = RobinhoodUtil()
rh_client = robinhood_service.get_client()
@robinhood_api.route("/login", methods=['POST'])
def login():
"""
Login to Robinhood client with credtials
:return: Reponse with message indicating successful or failed login
"""
content = request.get_json(force=True)
robinhood_service.set_logged_in(rh_client.login(username=content['user'], password=content['pass']))
logged_in = robinhood_service.is_logged_in()
if logged_in:
message = "Logged in"
response = Response(message, status=200, mimetype='application/json')
else:
message = "Failed to log in"
response = Response(message, status=401, mimetype='application/json')
response.headers.add('Access-Control-Allow-Origin', '*')
print logged_in
return response
@robinhood_api.route("/logout", methods=['GET'])
def logout():
"""
Logout of Robinhood Client
:return: Response with message indicating successful or failed logout
"""
req = rh_client.logout()
print req
if req.ok:
return Response("Logging out", status=200, mimetype='application/json')
else:
return Response("Not Logged out", status=200, mimetype='application/json')
@robinhood_api.route("/fundamentals", methods=['GET'])
def get_fundamentals():
"""
Retrieves fundamentals for each owned security for logged in user
Requires paramenter "ticker" ex. fundamentals?ticker=MSFT
:return: Response
"""
ticker = request.args.get('ticker')
# Retrieve fundamentals from Robinhood and convert to JSON
fundamentals_data = rh_client.get_fundamentals(stock=ticker)
response = Response(json.dumps(fundamentals_data), status=200, mimetype='application/json')
response.headers.add('Access-Control-Allow-Origin', '*')
print response.get_data()
return response
# Return JSON list of symbols for securities owned by user
@robinhood_api.route("/positions", methods=['GET'])
def get_my_positions():
"""
Retrieves a list of all positions of user in Robinhood
:return:
"""
if robinhood_service.is_logged_in():
user_positions = rh_client.securities_owned()['results']
position_list = list()
for position in user_positions:
# Call URL from original dict of positions and then load JSON string and extract symbol for specific stock
contents = urllib2.urlopen(position['instrument']).read()
contents_dict = json.loads(contents)
position_list.append(contents_dict['symbol'])
# For Testing
position_list = ['MSFT', 'SQ', 'W']
response = Response(json.dumps(position_list), status=200, mimetype='application/json')
response.headers.add('Access-Control-Allow-Origin', '*')
return response
else:
response_msg = "Not logged in"
response = Response(response_msg, status=401, mimetype='application/json')
response.headers.add('Access-Control-Allow-Origin', '*')
return response
# Return last price of given stock ex. price?ticker=MSFT
@robinhood_api.route("/price", methods=['GET'])
def get_last_price():
"""
Retrieves last trade price.
Requires parameter "ticker" ex. price?ticker=MSFT
:return: Last trade price
"""
ticker = request.args.get('ticker')
# Retrieve last trade price from Robinhood
price = robinhood_service.get_last_trade_price(ticker=ticker)[0][0]
response = Response(json.dumps(price), status=200, mimetype='application/json')
response.headers.add('Access-Control-Allow-Origin', '*')
return response
|
from apps.yvr.forms import PledgeLanding, ShareStatus, EmailInvites
from . import YVRRequestHandler
from tipfy import Response, abort, redirect
#### MAIN LANDING
class LandingHandler(YVRRequestHandler):
def get(self):
"""Simply returns a Response object with an enigmatic salutation."""
pledgeSuccess = self.request.args.get('pledgeSuccess', False)
forms = {
'pledgeForm':PledgeLanding(self.request),
'inviteForm':EmailInvites(self.request),
'statusForm':ShareStatus(self.request)
}
return self.render('landing.html', title='2010 Young Voter Revolution', forms=forms, pledgeSuccess=pledgeSuccess)
|
from django.apps import AppConfig
class FirstApp1184077Config(AppConfig):
name = 'first_app_1184077'
|
# -*- coding: utf-8 -*-
"""
Various support functions for NSS work
"""
# Imports
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from sklearn import neighbors
from sklearn.metrics import accuracy_score, confusion_matrix
from sklearn.utils import shuffle
from sklearn.model_selection import StratifiedShuffleSplit, StratifiedKFold
def norm(inp):
"""Takes input and normalizes it to unity"""
out = np.zeros((np.shape(inp)))
sums = np.sum(inp, axis=1)[:, None]
for i in range(len(inp)):
if sums[i] > 0:
out[i] = inp[i] / sums[i]
return out
def least_squares(test, ref):
"""
Lest Squares Reference Table Alogrithm
test - data to perform algoirthm to
ref - reference table
"""
res = np.zeros((len(test), len(ref)))
ls_guess = np.zeros(len(test))
for i in range(len(test)):
for j in range(len(ref)):
res[i, j] = (
(test[i, 0] - ref[j, 0]) ** 2
+ (test[i, 1] - ref[j, 1]) ** 2
+ (test[i, 2] - ref[j, 2]) ** 2
+ (test[i, 3] - ref[j, 3]) ** 2
)
ls_guess[i] = np.argmin(res[i])
return (ls_guess, res)
def error_analysis(predictions, truth):
""" Calculates the errors, accounting for circular statistis
predictions
truth
"""
score = accuracy_score(truth, predictions)
error = 180 - abs(abs(truth - predictions) - 180)
avg_error = np.mean(error)
std_error = np.std(error)
return (score, error, avg_error, std_error)
def distance_analysis(bins, r, error):
""" Calculates error wrt radius
bins - radial buckets to perform analysis
r - radius of trial
error - error of trial
"""
nbins = len(bins) - 1
bin_counter = np.zeros(nbins)
zero_counter = np.zeros(nbins)
total_error = np.zeros(nbins)
bin_error = np.zeros(nbins)
bin_error_std = np.zeros(nbins)
binwise = 0
for i in range(nbins):
for j in range(len(r)):
if bins[i] <= r[j] < bins[i + 1]:
bin_counter[i] += 1
total_error[i] += error[j]
binwise = np.append(binwise, error[j])
if error[j] == 0:
zero_counter[i] += 1
binwise = np.delete(binwise, 0)
bin_error[i] = binwise.mean()
binwise = 0
rad_score = zero_counter / bin_counter
return (rad_score, bin_error)
def analysis(y, y_p):
""" Get score, with circular statists """
score = accuracy_score(y, y_p)
error = np.mean(180 - abs(abs(y - y_p) - 180))
return (score, error)
def analysis_r(y, y_p, r, bins):
""" Analyze results wrt radius
y - trial labels
y - trial predictions
r - radius
bins - radial buckets to perform analysis
"""
nbins = len(bins) - 1
error = 180 - abs(abs(y - y_p) - 180)
bin_counter = np.zeros(nbins)
zero_counter = np.zeros(nbins)
total_error = np.zeros(nbins)
bin_error = np.zeros(nbins)
bin_error_std = np.zeros(nbins)
binwise = 0
for i in range(nbins):
for j in range(len(r)):
if bins[i] <= r[j] < bins[i + 1]:
bin_counter[i] += 1
total_error[i] += error[j]
binwise = np.append(binwise, error[j])
if error[j] == 0:
zero_counter[i] += 1
binwise = np.delete(binwise, 0)
bin_error[i] = binwise.mean()
bin_error_std[i] = binwise.std()
binwise = 0
rad_score = zero_counter / bin_counter
return (rad_score, bin_error, bin_error_std)
def ttKNN(test, train, ref, y, r):
"""
KNN - specify datsets to train/test with
**** labels must be identicle for both datasets! ***
test - test data
train - train dadta
ref - reference table
y - labels
r - radius
"""
nfold_a = 5
knn_a = neighbors.KNeighborsClassifier(n_neighbors=5, n_jobs=-1)
skf_a = StratifiedKFold(n_splits=nfold_a, shuffle=True)
acc_a = np.zeros((nfold_a, 2))
err_a = np.zeros((2, nfold_a, 2))
for fno, (train_index, test_index) in enumerate(skf_a.split(train, y)):
print("folding", fno + 1, "/", nfold_a)
xa_tr, ya_tr, ra_tr = train[train_index], y[train_index], r[train_index]
xa_ts, ya_ts, ra_ts = test[test_index], y[test_index], r[test_index]
knn_a.fit(xa_tr, ya_tr)
pred_a = knn_a.predict(xa_ts)
acc, b, err, s_err = error_analysis(ya_ts, pred_a)
acc_a[fno, 0] = acc
err_a[:, fno, 0] = [err, s_err]
rt_pred, b = least_squares(xa_ts, ref)
rt_acc, bb, rt_err, rt_s_err = error_analysis(ya_ts, rt_pred)
acc_a[fno, 1] = rt_acc
err_a[:, fno, 1] = [rt_err, rt_s_err]
print("KNN/RT Accuracy: ", acc, "/", rt_acc)
print("KN/RT Avg Ang Error: ", err, "+/-", s_err, "/", rt_err, "+/-", rt_s_err)
return (acc_a, err_a)
def make_cmap(colors, position=None, bit=False):
"""
make_cmap takes a list of tuples which contain RGB values. The RGB
values may either be in 8-bit [0 to 255] (in which bit must be set to
True when called) or arithmetic [0 to 1] (default). make_cmap returns
a cmap with equally spaced colors.
Arrange your tuples so that the first color is the lowest value for the
colorbar and the last is the highest.
position contains values from 0 to 1 to dictate the location of each color.
"""
import matplotlib as mpl
import numpy as np
bit_rgb = np.linspace(0, 1, 256)
if position == None:
position = np.linspace(0, 1, len(colors))
else:
if len(position) != len(colors):
sys.exit("position length must be the same as colors")
elif position[0] != 0 or position[-1] != 1:
sys.exit("position must start with 0 and end with 1")
if bit:
for i in range(len(colors)):
colors[i] = (
bit_rgb[colors[i][0]],
bit_rgb[colors[i][1]],
bit_rgb[colors[i][2]],
)
cdict = {"red": [], "green": [], "blue": []}
for pos, color in zip(position, colors):
cdict["red"].append((pos, color[0], color[0]))
cdict["green"].append((pos, color[1], color[1]))
cdict["blue"].append((pos, color[2], color[2]))
cmap = mpl.colors.LinearSegmentedColormap("my_colormap", cdict, 256)
return cmap
def plot_matrix(data, color_map, filename):
"""
NSS Figure/Result Matrix:
Columns: Training dataset/approach
Rows: Testing dataset
data - results to plot
color_map - color map
file name- string to name file (put in quotes)
"""
fs = 15
train = ["$^{60}Co$", "$^{137}Cs$", "$^{192}Ir$", "Combined", "Multi-Step"]
test = ["$^{60}Co$", "$^{137}Cs$", "$^{192}Ir$", "Overall"]
fig, ax = plt.subplots()
ax.matshow(data[:, :, 0], cmap=color_map)
ax.set_xticklabels([""] + train, fontsize=fs)
ax.set_yticklabels([""] + test, fontsize=fs)
cax = ax.matshow(data[:, :, 0], cmap=color_map, interpolation="nearest")
fig.colorbar(cax)
for (i, j), z in np.ndenumerate(data[:, :, 0]):
ax.text(j, i, "{:1.3f}".format(z), ha="center", va="bottom", fontsize=fs)
for (i, j), z in np.ndenumerate(data[:, :, 1]):
ax.text(j, i, "+/-" + "{:1.3f}".format(z), ha="center", va="top", fontsize=fs)
fig.set_size_inches(10, 7)
plt.savefig(filename)
def plot_matrix_na(data, color_map, filename):
"""
NSS Figure/Result Matrix: Na only data
Columns: Training dataset/approach
Rows: Testing dataset
data - results to plot
color_map - color map
file name- string to name file (put in quotes)
"""
fs = 15
train = ["$^{60}Co$", "$^{137}Cs$", "$^{192}Ir$", "Combined", "Multi-Step"]
test = ["KNN", "LSRT"]
fig, ax = plt.subplots()
ax.matshow(data[:, :, 0], cmap=color_map)
ax.set_xticklabels([""] + train, fontsize=fs)
ax.set_yticklabels([""] + test, fontsize=fs)
cax = ax.matshow(data[:, :, 0], cmap=color_map, interpolation="nearest")
fig.colorbar(cax)
for (i, j), z in np.ndenumerate(data[:, :, 0]):
ax.text(j, i, "{:1.3f}".format(z), ha="center", va="bottom", fontsize=fs)
for (i, j), z in np.ndenumerate(data[:, :, 1]):
ax.text(j, i, "+/-" + "{:1.3f}".format(z), ha="center", va="top", fontsize=fs)
fig.set_size_inches(10, 7)
plt.savefig(filename)
|
import discord
from discord.ext import commands
from near.database import get_embeds
from near.database import get_main
from time import time as nowtime
from platform import python_version as cur_python_version
from datetime import timedelta as dttimedelta
class General(commands.Cog):
def __init__(self, client: commands.Bot):
self.client = client
# For custom help
self.client.remove_command('help')
# Bot uptime
self.start_time = None
# This is the please-wait/Loading embed
self.please_wait_emb = discord.Embed(title=get_embeds.PleaseWait.TITLE, description=get_embeds.PleaseWait.DESCRIPTION, color=get_embeds.PleaseWait.COLOR)
self.please_wait_emb.set_author(name=get_embeds.Common.AUTHOR_NAME, icon_url=get_embeds.Common.AUTHOR_URL)
self.please_wait_emb.set_thumbnail(url=get_embeds.PleaseWait.THUMBNAIL)
self.please_wait_emb.set_footer(text=get_embeds.PleaseWait.FOOTER)
@commands.Cog.listener()
async def on_ready(self):
print(f'Logged in as {self.client.user.name}')
print(f'Discord.py API version: {discord.__version__}')
print(f'Python version: {cur_python_version()}')
self.start_time = nowtime()
await self.client.change_presence(activity=discord.Activity(type=discord.ActivityType.watching, name=f"teamsds.net/discord"))
print('Bot is ready!')
@commands.Cog.listener()
async def on_command_error(ctx, error):
if isinstance(error, commands.MissingPermissions):
embed=discord.Embed(title="ERROR", description="`You don't have the permissions required to use this command!`", color=get_embeds.Common.COLOR)
embed.set_author(name="NearBot", icon_url="https://cdn.discordapp.com/attachments/881007500588089404/881046764206039070/unknown.png")
embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/877796755234783273/879298565380386846/sign-red-error-icon-1.png")
await ctx.send(embed=embed)
return
if isinstance(error, commands.MissingRequiredArgument):
embed=discord.Embed(title="Something is wrong!", description="An error has been occured!", color=get_embeds.Common.COLOR)
embed.set_author(name="NearBot", icon_url="https://cdn.discordapp.com/attachments/881007500588089404/881046764206039070/unknown.png")
embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/877796755234783273/879298565380386846/sign-red-error-icon-1.png")
embed.add_field(name="Error", value="You haven't passed the needed arguments for this command to run properly", inline=True)
embed.add_field(name="Possible Fix", value=f"use `{get_main.BotMainDB.MESSAGE_PREFIX}help all` to list out all the command and check the proper usage of the command you used", inline=True)
await ctx.send(embed=embed)
return
@commands.command()
async def ping(self, ctx):
loading_message = await ctx.send(embed=self.please_wait_emb)
try:
embed=discord.Embed(title="Response Time", color=get_embeds.Common.COLOR)
embed.set_author(name=get_embeds.Common.AUTHOR_NAME, icon_url=get_embeds.Common.AUTHOR_URL)
embed.set_thumbnail(url="https://cdn.discordapp.com/attachments/877796755234783273/879311068097290320/PngItem_1526969.png")
embed.add_field(name=f"Ping :timer:", value=f"{round(self.client.latency * 1000)} ms", inline=False)
embed.set_footer(text=f"Requested by {ctx.author.name}")
await loading_message.delete()
await ctx.send(embed=embed)
except Exception as e:
embed3=discord.Embed(title=get_embeds.ErrorEmbeds.TITLE, description=get_embeds.ErrorEmbeds.DESCRIPTION, color=get_embeds.ErrorEmbeds.COLOR)
embed3.set_author(name=get_embeds.Common.AUTHOR_NAME, icon_url=get_embeds.Common.AUTHOR_URL)
embed3.set_thumbnail(url=get_embeds.ErrorEmbeds.THUMBNAIL)
embed3.add_field(name=get_embeds.ErrorEmbeds.FIELD_NAME, value=f"{e}", inline=False)
embed3.set_footer(text=f"Requested by {ctx.author.name}")
await loading_message.delete()
await ctx.send(embed=embed3)
@commands.command()
async def uptime(self, ctx):
loading_message = await ctx.send(embed=self.please_wait_emb)
try:
current_time = nowtime()
difference = int(round(current_time - self.start_time))
text = str(dttimedelta(seconds=difference))
embed=discord.Embed(color=get_embeds.Common.COLOR)
embed.add_field(name="The bot was online for: ", value=f":alarm_clock: {text}", inline=False)
embed.set_footer(text=f"Requested by {ctx.author.name}")
await loading_message.delete()
await ctx.send(embed=embed)
except Exception as e:
embed3=discord.Embed(title=get_embeds.ErrorEmbeds.TITLE, description=get_embeds.ErrorEmbeds.DESCRIPTION, color=get_embeds.ErrorEmbeds.COLOR)
embed3.set_author(name=get_embeds.Common.AUTHOR_NAME, icon_url=get_embeds.Common.AUTHOR_URL)
embed3.set_thumbnail(url=get_embeds.ErrorEmbeds.THUMBNAIL)
embed3.add_field(name=get_embeds.ErrorEmbeds.FIELD_NAME, value=f"{e}", inline=False)
embed3.set_footer(text=f"Requested by {ctx.author.name}")
await loading_message.delete()
await ctx.send(embed=embed3)
@commands.command()
async def help(self, ctx):
loading_message = await ctx.send(embed=self.please_wait_emb)
bp = get_main.BotMainDB.MESSAGE_PREFIX
try:
embed3=discord.Embed(title=":gear: Help", description="The list of all the commands! the might be some eastereggs!?! ", color=get_embeds.Common.COLOR)
embed3.set_author(name="NearBot", icon_url="https://cdn.discordapp.com/attachments/881007500588089404/881046764206039070/unknown.png")
embed3.set_thumbnail(url="https://cdn.discordapp.com/attachments/881007500588089404/881046764206039070/unknown.png")
embed3.add_field(name="Crypto:", value=f"`{bp}bitcoin` - Get the bitcoin rates \n`{bp}doge` - Get the doge coin rates \n`{bp}xmr` - Get the Monero rates \n`{bp}xrp` - Get the ripple rates \n`{bp}eth` - Get the etherium rates", inline=False)
embed3.add_field(name="Encoding", value=f"`{bp}e_b64 [value]` - Encode to Base64 \n`{bp}e_leet [value]` - Encode to leet \n`{bp}e_md5` - Encode to MD5 \n`{bp}e_sha1` - Encode to SHA1 \n`{bp}e_sha224` - Encode to SHA224 \n`{bp}e_sha512` - Encode to SHA512", inline=False)
embed3.add_field(name="Fun", value=f"`{bp}inspire` - Send you an inspirational quote! \n`{bp}bored` - Get some activity to do \n`{bp}meme` - Get a meme to laught ats \n`{bp}dadjoke` - just a Dad Joke \n`{bp}joke` - Laughing is the best medicing \n`{bp}joke2` - Jokes are awesome! \n`{bp}wyr`- Would you rather? \n`{bp}advice` - Advice makes our lives better \n`{bp}chuckjoke` - Get a chuck norris joke` ", inline=False)
embed3.add_field(name="Fake Information", value=f"`{bp}fake help` - List out all the fake information commands! \n`{bp}face [gender:optional]` - Generate a fake face with a name", inline=False)
# OLD MUSIC, COG
# embed3.add_field(name="Music (BETA)", value=f"`{bp}play [song-name]` - Join to Voice Channel and play the song\n`{bp}join` - Join Voice Channel \n`{bp}leave` - Leave Voice Channel \n`{bp}skip` - Skip the current playing song and go to the next \n`{bp}summon [vc-name]` - Make the bot join to a VC (Case Sensitive) \n`{bp}now` - Displays the current playing song \n`{bp}queue` - Send the music queue waiting to be played! \n`{bp}shuffle` - Shuffle the queue \n`{bp}remove [index-from-queue]` - Remove a song from the queue \n`{bp}loop` - Loop the same song, use again to unloop", inline=False)
# NEW MUSIC, LAVA LINK
embed3.add_field(name="Music", value=f"`{bp}connect` - Connect to Voice Channel \n`{bp}disconnect` - Disconnect bot from Voice Channel \n`{bp}play [song-name/link]` - Play the song \n`{bp}skip` - Skip the currently playing song \n`{bp}pause` - Pause the music \n`{bp}resume` - Resume the music \n`{bp}seek [seconds]` - Skip the given seconds of the playing song \n`{bp}volume [number]` - Change the volume of the song \n`{bp}loop [type]` - Play music in a loop \n`{bp}nowplaying` - Show the song which is being played right now \n`{bp}queue` - Diplay the songs waiting to be played \n`{bp}equalizer` - Maybe tune the song to your liking?", inline=False)
embed3.add_field(name="Others", value=f"`{bp}countryinfo [country_code]` - Search for Country Information \n`{bp}hastebin [text]` - Create a hatebin link for the given text \n`{bp}ig_pfp [ig_username]` - Download the Instgram profile picture \n`{bp}ip [ip_addr]` - Find Information of an IP Address \n`{bp}lyrics [song_name]` - Find lyrics of any song \n`{bp}mfp [number]` - Mass fake profile \n`{bp}pwdcheck [password]` - Check for the status of a password \n`{bp}uptime` - Show bot uptime \n ", inline=False)
embed3.set_footer(text=f"Requested by {ctx.author.name}")
await loading_message.delete()
await ctx.send(embed=embed3)
except Exception as e:
embed3=discord.Embed(title=get_embeds.ErrorEmbeds.TITLE, description=get_embeds.ErrorEmbeds.DESCRIPTION, color=get_embeds.ErrorEmbeds.COLOR)
embed3.set_author(name="NearBot", icon_url="https://cdn.discordapp.com/attachments/881007500588089404/881046764206039070/unknown.png")
embed3.set_thumbnail(url="https://cdn.discordapp.com/attachments/877796755234783273/879298565380386846/sign-red-error-icon-1.png")
embed3.add_field(name="Error:", value=f"{e}", inline=False)
embed3.set_footer(text=f"Requested by {ctx.author.name}")
await loading_message.delete()
await ctx.send(embed=embed3)
def setup(client: commands.Bot):
client.add_cog(General(client))
|
"""
Process small MIDI files into a Numpy-Trainingssetfile
Files have to be in seperate folders for train, test and valid -> cli-options
"""
from math import floor
from typing import List, Dict
import numpy as np
from common import *
import click
def get_multiple_number_greater_than(factor: float, target: float):
tmp = target / factor
tmp = floor(tmp)
tmp = tmp * factor
if tmp < target:
return tmp + 1
return tmp
def get_notes_from_instrument(instr: pretty_midi.Instrument, steps: float) -> Dict[float, List[pretty_midi.Note]]:
result: Dict[float, List[pretty_midi.Note]] = {}
for note in instr.notes:
note_time = timespan_from_note(note)
time = get_multiple_number_greater_than(steps, note_time.start)
while note_time.contains(time):
if time not in result:
result[time] = [note]
else:
result[time].append(note)
time += steps
return result
def get_notes_from_midi(mid: pretty_midi.PrettyMIDI, steps: float) -> Dict[float, List[pretty_midi.Note]]:
result: Dict[float, List[pretty_midi.Note]] = {}
for instr in mid.instruments:
extracted_notes = get_notes_from_instrument(instr, steps)
for time, notes in extracted_notes.items():
if time not in result:
result[time] = notes
else:
result[time].extend(notes)
return result
def normalize_notelists(notes: List[int], desired_note_count: int) -> List[int]:
while len(notes) > desired_note_count:
notes.pop(len(notes) - 1)
while len(notes) < desired_note_count:
notes.append(None)
return notes
def get_note_values_from_midi(mid: pretty_midi.PrettyMIDI, steps: float, desired_note_count: int) -> List[List[int]]:
notes = get_notes_from_midi(mid, steps)
result: List[List[int]] = []
time = 0
while len(notes) > 0:
if time in notes:
pretty_notes = notes[time]
result.append(normalize_notelists([note.pitch for note in pretty_notes], desired_note_count))
del notes[time]
else:
result.append(normalize_notelists([], desired_note_count))
time += steps
return result
def get_all_note_values(midis: List[pretty_midi.PrettyMIDI],
steps: float,
desired_note_count: int) -> List[List[List[int]]]:
return [get_note_values_from_midi(mid, steps, desired_note_count) for mid in midis]
def transform_notes(notes: List[List[List[int]]]) -> any:
data = [np.array(piece, dtype=np.float_) for piece in notes]
return np.array(data, dtype=np.object)
def build_training_dict(notes_train: List[List[List[int]]],
notes_test: List[List[List[int]]],
notes_validate: List[List[List[int]]]) -> Dict[str, List[List[List[int]]]]:
return {
"train": notes_train,
"test": notes_test,
"valid": notes_validate
}
def transform_training_dict(notes: Dict[str, List[List[List[int]]]]) -> Dict[str, any]:
return {
"train": transform_notes(notes["train"]),
"test": transform_notes(notes["test"]),
"valid": transform_notes(notes["valid"])
}
def save_notes_with_pickle(notes: Dict[str, List[List[List[int]]]], file: str):
with open(file, "wb") as f:
try:
import cPickle as pickle
pickle.dump(notes, f)
except:
import pickle
pickle.dump(notes, f)
def save_notes_with_numpy(notes: Dict[str, any], file: str):
with open(file, "wb") as f:
np.savez_compressed(f, **notes)
def load_notes_with_pickle(file: str) -> Dict[str, List[List[List[int]]]]:
result = None
with open(file, "rb") as f:
try:
import cPickle as pickle
result = pickle.load(f)
except:
import pickle
result = pickle.load(f)
return result
def load_notes_with_numpy(file: str) -> Dict[str, any]:
result = None
with open(file, "rb") as f:
with np.load(f, allow_pickle=False) as npz:
result = {
"train": npz["train"],
"test": npz["test"],
"valid": npz["valid"]
}
return result
def build_trainingsdata(train_dir: str,
test_dir: str,
valid_dir: str,
steps: float,
desired_note_count: int
) -> Dict[str, List[List[List[int]]]]:
# load midis
click.echo("Loading training files from {}...".format(train_dir))
train_midis = load_midis(train_dir)
click.echo("Loading testing files from {}...".format(test_dir))
test_midis = load_midis(test_dir)
click.echo("Loading validation files from {}...".format(valid_dir))
valid_midis = load_midis(valid_dir)
# extract notes
click.echo("Processing training files...")
train_notes = get_all_note_values(train_midis, steps, desired_note_count)
click.echo("Processing testing files...")
test_notes = get_all_note_values(test_midis, steps, desired_note_count)
click.echo("Processing validation files...")
valid_notes = get_all_note_values(valid_midis, steps, desired_note_count)
click.echo("Combining processed data...")
return build_training_dict(train_notes, test_notes, valid_notes)
def save_trainingsdata(notes: Dict[str, List[List[List[int]]]], filename: str):
click.echo("Saving with pickle...")
save_notes_with_pickle(notes, filename + ".pkl")
click.echo("Saving with numpy...")
save_notes_with_numpy(transform_training_dict(notes), filename + ".npz")
@click.command()
@click.option("train_dir", "--train", type=click.Path(exists=True, file_okay=False), required=True)
@click.option("test_dir", "--test", type=click.Path(exists=True, file_okay=False), required=True)
@click.option("valid_dir", "--valid", type=click.Path(exists=True, file_okay=False), required=True)
@click.option("out", "-o", type=str, required=True)
@click.option("--steps", default=0.125, type=float, show_default=True)
@click.option("--desired_note_count", "--notes", default=4, type=int, show_default=True)
def main(train_dir: str,
test_dir: str,
valid_dir: str,
out: str,
steps: float,
desired_note_count: int):
click.echo("Processing files with steps={} and note_count={}...".format(steps, desired_note_count))
notes = build_trainingsdata(
train_dir,
test_dir,
valid_dir,
steps,
desired_note_count
)
click.echo("Saving data...")
save_trainingsdata(notes, out)
click.echo("Done.")
if __name__ == '__main__':
main()
|
# -*- coding:utf-8 -*-
import unittest
import os
import sys
import traceback
import json
import time
import shutil
sys.path.append('..')
sys.path.append('../..')
testpath = os.path.dirname(os.path.realpath(__file__))
sys.path.append(testpath)
from utils.logger import LoggerInstance as logger
from utils.parametrizedtestcase import ParametrizedTestCase
from utils.error import AssertError, RPCError
from utils.config import Config
from api.apimanager import API
from neo.walletmanager import WalletManager
from neo.wallet import Wallet, Account
from test_config import test_config
######################################################
# test cases
class test_cli(ParametrizedTestCase):
##neo:flag=true gas:flag=false
def return_neo_gas(self,accountstate,flag=False):
if not "balances" in accountstate:
return 0
if len(accountstate["balances"])<=0:
return 0
if flag:
asset_id="0xc56f33fc6ecfcd0c225c4ab356fee59390af8560be0e930faebe74a6daff7c9b"
else:
asset_id="0x602c79718b16e442de58778e148d0b1084e3b2dffd5de6b7b16cee7969282de7"
for tempRes in accountstate["balances"]:
if not "value" in tempRes:
break
if not "asset" in tempRes:
break
else:
if tempRes["asset"]==asset_id:
return tempRes["value"]
return 0
def return_balance(self,balanceRes):
if not "balance" in balanceRes:
return 0
else:
return balanceRes["balance"]
def setUp(self):
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
logger.open("test_cli/" + self._testMethodName + ".log", self._testMethodName)
def tearDown(self):
API.cli().terminate()
logger.close(self.result())
def test_003_createwallet(self):
try:
'''获取当前节点路径'''
fp = open(os.getcwd().split("test/test_cli")[0]+"config.json", 'r', encoding='utf-8')
str=fp.read()
fpath = str.split("\"path\" : \"")[1].split("neo-cli.dll")[0]
'''确保没有wallet_name_json文件'''
if os.path.exists(fpath+test_config.wallet_name_json):
os.remove(fpath+test_config.wallet_name_json)
'''创建并打开钱包'''
API.cli().create_wallet(filepath=fpath+test_config.wallet_name_json, password=test_config.wallet_password, password2=test_config.wallet_password, exceptfunc=(lambda msg: msg.find("address") >= 0))
API.cli().open_wallet(fpath+test_config.wallet_name_json, test_config.wallet_password)
API.cli().list_address(exceptfunc=(lambda msg: msg.find("Standard") >= 0))
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "create wallet failed")
'''钱包是否存在'''
flag0=os.path.exists(fpath+test_config.wallet_name_json)
self.ASSERT(flag0, "wallet not exist")
result1 = climsg.split("address:")[1].split("\n")[0]
'''钱包存在比对地址'''
if flag0:
with open(fpath+test_config.wallet_name_json, mode='r', encoding='utf-8') as f:
str=f.readlines()
str="".join(str).split("\"address\":\"")[1].split("\",\"")[0]
if str.strip()==result1.strip():
flag=True
else:
flag=False
self.ASSERT(flag, "wallet address not match")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_004_createwallet(self):
try:
'''获取当前节点路径'''
fp = open(os.getcwd().split("test/test_cli")[0]+"config.json", 'r', encoding='utf-8')
str=fp.read()
fpath = str.split("\"path\" : \"")[1].split("neo-cli.dll")[0]
'''确保没有test223.db3文件,相对路径下创建test223.db3钱包'''
if os.path.exists(fpath+test_config.wallet_name_db3):
os.remove(fpath+test_config.wallet_name_db3)
API.cli().create_wallet(filepath=test_config.wallet_name_db3, password=test_config.wallet_password,password2=test_config.wallet_password, exceptfunc=lambda msg: msg.find("address") >= 0)
API.cli().open_wallet(test_config.wallet_name_db3, test_config.wallet_password)
API.cli().list_address(exceptfunc=(lambda msg: msg.find("Standard") >= 0))
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "create wallet failed1")
'''查看当前节点路径下是否有该钱包'''
flag=os.path.exists(fpath+test_config.wallet_name_db3)
self.ASSERT(flag, "create wallet failed2")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_005_createwallet(self):
try:
'''获取当前节点路径'''
fp = open(os.getcwd().split("test/test_cli")[0]+"config.json", 'r', encoding='utf-8')
str=fp.read()
fpath = str.split("\"path\" : \"")[1].split("neo-cli.dll")[0]
'''确保没有wallet_name_wrong文件'''
if os.path.exists(fpath+test_config.wallet_name_wrong):
os.remove(fpath+test_config.wallet_name_wrong)
API.cli().create_wallet(filepath=test_config.wallet_name_wrong, password=test_config.wallet_password,password2=test_config.wallet_password, exceptfunc=lambda msg: msg.find("Wallet files in that format are not supported, please use a .json or .db3 file extension.") >= 0)
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "error message not match")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_007_createwallet(self):
try:
'''获取当前节点路径'''
fp = open(os.getcwd().split("test/test_cli")[0]+"config.json", 'r', encoding='utf-8')
str=fp.read()
fpath = str.split("\"path\" : \"")[1].split("neo-cli.dll")[0]
'''确保没有wallet_name_db3文件'''
if os.path.exists(fpath+test_config.wallet_name_db3):
os.remove(fpath+test_config.wallet_name_db3)
'''创建并打开钱包'''
API.cli().create_wallet(filepath=fpath+test_config.wallet_name_db3, password=test_config.wallet_password, password2=test_config.wallet_password, exceptfunc=(lambda msg: msg.find("address") >= 0))
API.cli().open_wallet(fpath+test_config.wallet_name_db3, test_config.wallet_password)
API.cli().list_address(exceptfunc=(lambda msg: msg.find("Standard") >= 0))
'''创建重名的钱包'''
API.cli().create_wallet(filepath=test_config.wallet_name_db3, password=test_config.wallet_password,password2=test_config.wallet_password, clearfirst = False, exceptfunc=lambda msg: msg.find("Existing wallet file,cover it or not?") >= 0)
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "error message not match")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_008_createwallet(self):
try:
API.cli().create_wallet(filepath=None,password=test_config.wallet_password,password2=test_config.wallet_password,exceptfunc = lambda msg: msg.find("error") >= 0)
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "error message not match")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
'''新添加的case,不填密码'''
def test_155_createwallet(self):
try:
'''获取当前节点路径'''
fp = open(os.getcwd().split("test/test_cli")[0]+"config.json", 'r', encoding='utf-8')
str=fp.read()
fpath = str.split("\"path\" : \"")[1].split("neo-cli.dll")[0]
'''确保没有wallet_name_nopws文件'''
if os.path.exists(fpath+test_config.wallet_name_nopws):
os.remove(fpath+test_config.wallet_name_nopws)
API.cli().create_wallet(filepath=test_config.wallet_name_nopws, password = None,password2 = None,exceptfunc = lambda msg: msg.find("cancelled") >= 0)
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "error message not match")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
'''新添加的case,第二遍密码输入错误'''
def test_156_createwallet(self):
try:
'''获取当前节点路径'''
fp = open(os.getcwd().split("test/test_cli")[0]+"config.json", 'r', encoding='utf-8')
str=fp.read()
fpath = str.split("\"path\" : \"")[1].split("neo-cli.dll")[0]
'''确保没有wallet_name_nopws文件'''
if os.path.exists(fpath+test_config.wallet_name_nopws):
os.remove(fpath+test_config.wallet_name_nopws)
API.cli().create_wallet(filepath=test_config.wallet_name_nopws, password=test_config.wallet_password,password2=test_config.wallet_password_wrong, exceptfunc = lambda msg: msg.find("error") >= 0)
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "error message not match")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_009_openwallet(self):
try:
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_password)
API.cli().list_address(exceptfunc = lambda msg: msg.find(test_config.wallet_default_address) >= 0)
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "open wallet failed")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_010_openwallet(self):
try:
API.cli().open_wallet(test_config.wallet_name_db3, test_config.wallet_password)
API.cli().list_address(exceptfunc=(lambda msg: msg.find("Standard") >= 0))
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "open wallet failed")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_011_openwallet(self):
try:
'''获取当前节点路径'''
fp = open(os.getcwd().split("test/test_cli")[0]+"config.json", 'r', encoding='utf-8')
str=fp.read()
fpath = str.split("\"path\" : \"")[1].split("neo-cli.dll")[0]
'''确保没有000test000.json文件'''
if os.path.exists(fpath+test_config.wallet_name_notexist):
os.remove(fpath+test_config.wallet_name_notexist)
API.cli().open_wallet(test_config.wallet_name_notexist, test_config.wallet_password, exceptfunc = lambda msg: msg.find("File does not exist") >= 0)
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "error message not match")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_012_openwallet(self):
try:
'''获取当前节点路径'''
fp = open(os.getcwd().split("test/test_cli")[0]+"config.json", 'r', encoding='utf-8')
str=fp.read()
fpath = str.split("\"path\" : \"")[1].split("neo-cli.dll")[0]
'''新建一个后缀错误的钱包'''
if os.path.exists(fpath+test_config.wallet_name_exist_wrong):
os.remove(fpath+test_config.wallet_name_exist_wrong)
f = open(fpath+test_config.wallet_name_exist_wrong, 'w')
f1 = open(fpath+test_config.wallet_name_json, 'r')
indata = f1.read()
f.write(indata)
f.close()
f1.close()
API.cli().open_wallet(test_config.wallet_name_exist_wrong, test_config.wallet_password, exceptfunc = lambda msg: msg.find("error") >= 0)
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "error message not match")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_014_openwallet(self):
try:
'''获取当前节点路径'''
fp = open(os.getcwd().split("test/test_cli")[0]+"config.json", 'r', encoding='utf-8')
str=fp.read()
fpath = str.split("\"path\" : \"")[1].split("neo-cli.dll")[0]
'''新建一个名称为乱码的钱包'''
if os.path.exists(fpath+test_config.wallet_name_exist_erroecode_json):
os.remove(fpath+test_config.wallet_name_exist_erroecode_json)
f = open(fpath+test_config.wallet_name_exist_erroecode_json, 'w')
f1 = open(fpath+test_config.wallet_name_json, 'r')
indata = f1.read()
f.write(indata)
f.close()
f1.close()
API.cli().open_wallet(test_config.wallet_name_exist_erroecode_json, test_config.wallet_password, exceptfunc = lambda msg: msg.find("File does not exist") >= 0)
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "error message not match")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_015_openwallet(self):
try:
API.cli().open_wallet(test_config.wallet_name_db3, test_config.wallet_password)
API.cli().list_address(exceptfunc=(lambda msg: msg.find("Standard") >= 0))
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "open wallet failed")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_016_openwallet(self):
try:
'''获取当前节点路径'''
fp = open(os.getcwd().split("test/test_cli")[0]+"config.json", 'r', encoding='utf-8')
str=fp.read()
fpath = str.split("\"path\" : \"")[1].split("neo-cli.dll")[0]
'''新建一个内容为空的钱包'''
if os.path.exists(fpath+test_config.wallet_name_null):
os.remove(fpath+test_config.wallet_name_null)
f = open(fpath+test_config.wallet_name_null, 'w')
f.close()
API.cli().open_wallet(test_config.wallet_name_null, test_config.wallet_password, exceptfunc = lambda msg: msg.find("error") >= 0)
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "error message not match")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_018_openwallet(self):
try:
API.cli().open_wallet(filepath=None, exceptfunc = lambda msg: msg.find("error") >= 0)
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "error message not match")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_020_upgradewallet(self):
try:
'''获取当前节点路径'''
fp = open(os.getcwd().split("test/test_cli")[0]+"config.json", 'r', encoding='utf-8')
str=fp.read()
fpath = str.split("\"path\" : \"")[1].split("neo-cli.dll")[0]
'''确保没有wallet_name_db3_upgrade文件'''
if os.path.exists(fpath+test_config.wallet_name_db3_upgrade):
os.remove(fpath+test_config.wallet_name_db3_upgrade)
API.cli().upgrade_wallet(filepath=test_config.wallet_name_db3, password=test_config.wallet_password, exceptfunc = lambda msg: msg.find("Wallet file upgrade complete. New wallet file has been auto-saved at: "+test_config.wallet_name_db3_upgrade) >= 0)
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "upgrade the wallet file failed")
'''判断升级后的钱包文件是否存在'''
if os.path.exists(fpath+test_config.wallet_name_db3_upgrade):
flag = True
else:
flag = False
self.ASSERT(flag, "upgraded files do not exist")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_021_upgradewallet(self):
try:
'''获取当前节点路径'''
fp = open(os.getcwd().split("test/test_cli")[0]+"config.json", 'r', encoding='utf-8')
str=fp.read()
fpath = str.split("\"path\" : \"")[1].split("neo-cli.dll")[0]
'''确保没有000test000.json文件'''
if os.path.exists(fpath+test_config.wallet_name_notexist):
os.remove(fpath+test_config.wallet_name_notexist)
API.cli().upgrade_wallet(filepath=test_config.wallet_name_notexist,exceptfunc = lambda msg: msg.find("File does not exist") >= 0)
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "error message not match")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_022_upgradewallet(self):
try:
'''获取当前节点路径'''
fp = open(os.getcwd().split("test/test_cli")[0]+"config.json", 'r', encoding='utf-8')
str=fp.read()
fpath = str.split("\"path\" : \"")[1].split("neo-cli.dll")[0]
'''新建一个后缀错误的钱包'''
if os.path.exists(fpath+test_config.wallet_name_exist_wrong):
os.remove(fpath+test_config.wallet_name_exist_wrong)
f = open(fpath+test_config.wallet_name_exist_wrong, 'w')
f1 = open(fpath+test_config.wallet_name_json, 'r')
indata = f1.read()
f.write(indata)
f.close()
f1.close()
API.cli().upgrade_wallet(filepath=test_config.wallet_name_exist_wrong,exceptfunc = lambda msg: msg.find("Can't upgrade the wallet file.") >= 0)
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "error message not match")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_024_upgradewallet(self):
try:
# '''获取当前节点路径'''
fp = open(os.getcwd().split("test/test_cli")[0]+"config.json", 'r', encoding='utf-8')
str=fp.read()
fpath = str.split("\"path\" : \"")[1].split("neo-cli.dll")[0]
'''复制一个db3格式的钱包并重命名'''
if os.path.exists(fpath+test_config.wallet_name_exist_erroecode_db3):
os.remove(fpath+test_config.wallet_name_exist_erroecode_db3)
shutil.copy(fpath+test_config.wallet_name_db3,fpath+test_config.wallet_name_exist_erroecode_db3)
API.cli().upgrade_wallet(filepath=test_config.wallet_name_exist_erroecode_db3,password=test_config.wallet_password, exceptfunc = lambda msg: msg.find("File does not exist") >= 0)
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "error message not match")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_025_upgradewallet(self):
try:
API.cli().upgrade_wallet(filepath=test_config.wallet_name_json, exceptfunc = lambda msg: msg.find("Can't upgrade the wallet file.") >= 0)
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "error message not match")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_026_upgradewallet(self):
try:
'''获取当前节点路径'''
fp = open(os.getcwd().split("test/test_cli")[0]+"config.json", 'r', encoding='utf-8')
str=fp.read()
fpath = str.split("\"path\" : \"")[1].split("neo-cli.dll")[0]
'''新建一个内容为空的钱包'''
if os.path.exists(fpath+test_config.wallet_name_null):
os.remove(fpath+test_config.wallet_name_null)
f = open(fpath+test_config.wallet_name_null, 'w')
f.close()
API.cli().upgrade_wallet(filepath=test_config.wallet_name_null,password=test_config.wallet_password, exceptfunc = lambda msg: msg.find("error:Command not found upgrade") >= 0)
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "error message not match")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_028_upgradewallet(self):
try:
API.cli().upgrade_wallet(exceptfunc = lambda msg: msg.find("error") >= 0)
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "error not match")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_029_rebuildindex(self):
try:
API.cli().open_wallet(test_config.wallet_name_json, test_config.wallet_password)
API.cli().rebuild_index()
API.cli().show_state(120)
(result, stepname, climsg) = API.cli().exec(False)
logger.print(climsg)
self.ASSERT(result, "rebuildindex failed")
'''查看区块高度与钱包高度是否一致'''
lastline = climsg[climsg.rfind("block: "):]
blockheight = lastline.split("block: ")[1].split("/")[0]
walletheight = API.rpc().getwalletheight()
if str(blockheight).strip() == str(walletheight).strip():
flag=True
else:
flag=False
self.ASSERT(flag, "rebuildindex failed")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_030_rebuildindex(self):
try:
API.cli().rebuild_index(exceptfunc = lambda msg: msg.find("You have to open the wallet first.") >= 0)
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "error message not match")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_031_listaddress(self):
try:
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_password)
API.cli().list_address(exceptfunc = lambda msg: msg.find(test_config.wallet_default_address) >= 0)
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "list address failed")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_032_listaddress(self):
try:
API.cli().list_address(exceptfunc = lambda msg: msg.find("You have to open the wallet first.") >= 0)
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "error message not match")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_033_listasset(self):
try:
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_password)
'''查看wallet_5.json的Neo资产'''
API.cli().list_asset(exceptfunc = lambda msg: msg.find(test_config.asset_neo_id) >= 0)
(result, stepname, climsg) = API.cli().exec(False)
logger.print(climsg)
self.ASSERT(result, "list asset failed1")
str=climsg.split("name:NEO")[1].split("confirmed:")[0].split("balance:")[1]
'''调用getbalance查看Neo资产,看是否一致'''
asset = API.rpc().getbalance(test_config.asset_neo_id)["balance"]
if str.strip() == asset.strip():
flag=True
else:
flag=False
self.ASSERT(flag, "list asset failed2")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_034_listasset(self):
try:
API.cli().list_asset(exceptfunc = lambda msg: msg.find("You have to open the wallet first.") >= 0)
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "error message not match")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_035_listkey(self):
try:
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_password)
API.cli().list_key(exceptfunc = lambda msg: msg.find(test_config.wallet_default_pubkey) >= 0)
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "list publickey failed")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_036_listkey(self):
try:
API.cli().list_key(exceptfunc = lambda msg: msg.find("You have to open the wallet first.") >= 0)
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "error message not match")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_037_showutxo(self):
try:
'''show utxo , list address'''
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_password)
API.cli().list_address(exceptfunc = lambda msg: msg.find(test_config.wallet_default_address) >= 0)
API.cli().show_utxo(exceptfunc = lambda msg: msg.find("UTXOs") >= 0)
(result, stepname, climsg) = API.cli().exec(False)
logger.print(climsg)
self.ASSERT(result, "show utxo failed1")
'''将所有交易txid存入list,传入gettxout方法,返回的地址信息与list address比对'''
count = int(climsg.split("total: ")[1].split(" UTXOs")[0])
msg = climsg.split("show utxo")[1].split("total")[0].strip().split("\n")
i = 0
str = []
while i < count:
str.append(msg[i])
logger.print(str[i])
i += 1
i = 0
while i < count:
getaddress = API.rpc().gettxout(''.join(str[i]).split(":")[0], ''.join(str[i]).split(":")[1])
i += 1
flag = climsg.find(''.join(getaddress))
if flag ==False:
break
self.ASSERT(flag, "show utxo failed2")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_038_showutxo(self):
try:
API.cli().show_utxo(exceptfunc = lambda msg: msg.find("You have to open the wallet first.") >= 0)
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "error message not match")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_039_showutxo(self):
try:
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_password)
API.cli().list_address(exceptfunc = lambda msg: msg.find(test_config.wallet_default_address) >= 0)
API.cli().show_utxo(test_config.asset_neo_id,exceptfunc = lambda msg: msg.find("UTXOs") >= 0)
(result, stepname, climsg) = API.cli().exec(False)
logger.print(climsg)
self.ASSERT(result, "show utxo failed1")
count = int(climsg.split("total: ")[1].split(" UTXOs")[0])
msg = climsg.split(test_config.asset_neo_id)[1].split("total")[0].strip().split("\n")
i = 0
str = []
while i < count:
str.append(msg[i])
logger.print(str[i])
i += 1
i = 0
while i < count:
getaddress = API.rpc().gettxout(''.join(str[i]).split(":")[0], ''.join(str[i]).split(":")[1])
i += 1
flag = climsg.find(''.join(getaddress))
if flag ==False:
break
self.ASSERT(flag, "show utxo failed2")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_041_showutxo(self):
try:
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_password)
API.cli().show_utxo(test_config.asset_notexist_id,exceptfunc = lambda msg: msg.find("No UTXO exists") >= 0)
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "error message not match")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_042_showutxo(self):
try:
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_password)
API.cli().show_utxo(test_config.asset_wrong_str_id,exceptfunc = lambda msg: msg.find("error") >= 0)
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "error message not match")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_043_showutxo(self):
try:
API.cli().show_utxo(test_config.asset_neo_id,exceptfunc = lambda msg: msg.find("You have to open the wallet first.") >= 0)
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "error message not match")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_044_showutxo(self):
try:
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_password)
API.cli().show_utxo(test_config.alias_right,exceptfunc = lambda msg: msg.find("UTXOs") >= 0)
(result, stepname, climsg) = API.cli().exec(False)
logger.print(climsg)
self.ASSERT(result, "Can't show utxo1")
count = int(climsg.split("total: ")[1].split(" UTXOs")[0])
msg = climsg.split("show utxo neo")[1].split("total")[0].strip().split("\n")
i = 0
str = []
while i < count:
str.append(msg[i])
logger.print(str[i])
i += 1
i = 0
while i < count:
getaddress = API.rpc().gettxout(''.join(str[i]).split(":")[0], ''.join(str[i]).split(":")[1])
i += 1
flag = climsg.find(''.join(getaddress))
if flag ==False:
break
self.ASSERT(flag, "show utxo failed2")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_046_showutxo(self):
try:
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_password)
API.cli().show_utxo(test_config.alias_notexist,exceptfunc = lambda msg: msg.find("error") >= 0)
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "error message not match")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_048_showgas(self):
try:
plus=0
while plus==0:
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_password)
API.cli().show_gas(exceptfunc = lambda msg: msg.find("unavailable") >= 0)
(result, stepname, climsg) = API.cli().exec(False)
logger.print(climsg)
self.ASSERT(result, "show gas failed1")
count1 = API.rpc().getblockcount()
try:
number1 = float(climsg.split("unavailable: ")[1].split("\n")[0].strip())
except:
self.ASSERT(False, "show gas failed2")
API.cli().waitsync()
API.cli().terminate()
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_password)
API.cli().show_gas(exceptfunc = lambda msg: msg.find("unavailable") >= 0)
(result, stepname, climsg) = API.cli().exec(False)
logger.print(climsg)
self.ASSERT(result, "show gas failed3")
count2 = API.rpc().getblockcount()
try:
number2 = float(climsg.split("unavailable: ")[1].split("\n")[0].strip())
except:
self.ASSERT(False, "show gas failed4")
API.cli().waitsync()
API.cli().terminate()
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_password)
API.cli().show_gas(exceptfunc = lambda msg: msg.find("unavailable") >= 0)
(result, stepname, climsg) = API.cli().exec(False)
logger.print(climsg)
self.ASSERT(result, "show gas failed5")
count3 = API.rpc().getblockcount()
try:
number3 = float(climsg.split("unavailable: ")[1].split("\n")[0].strip())
except:
self.ASSERT(False, "show gas failed6")
# logger.print(climsg)
# self.ASSERT(result, "show gas failed1")
print (number1)
print (number2)
print (number3)
if number1 == number2 or number2 == number3:
plus=0
API.cli().terminate()
else:
if round((number2-number1)/(int(count2)-int(count1)),8) == round((number3-number2)/(int(count3)-int(count2)),8):
flag=True
else:
flag=False
self.ASSERT(flag, "gas value not match")
plus=1
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_049_showgas(self):
try:
API.cli().show_gas(exceptfunc = lambda msg: msg.find("You have to open the wallet first.") >= 0)
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "error message not match")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_050_claimgas(self):
try:
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_password)
API.cli().list_asset(exceptfunc = lambda msg: msg.find("balance") >= 0)
###发送一笔交易
API.cli().send(test_config.wallet_password,test_config.asset_neo_id, WalletManager().wallet().account().address() , "10", fee=0,exceptfunc = lambda msg: msg.find("TXID") >= 0)
###等一个区块
API.cli().waitnext(timeout=30)
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "Transaction failure")
str1=climsg.split("name:NeoGas")[1].split("balance:")[1].split("\n")[0]
API.cli().terminate()
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_password)
API.cli().show_gas(exceptfunc = lambda msg: msg.find("unavailable") >= 0)
API.cli().claim_gas(exceptfunc = lambda msg: msg.find("Tranaction") >= 0)
###等一个区块
API.cli().waitnext(timeout=30)
API.cli().list_asset(exceptfunc = lambda msg: msg.find("balance") >= 0)
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "claim gas failed")
str2=climsg.split(" available:")[1].split("\n")[0]
str3=climsg.split("name:NeoGas")[1].split("balance:")[1].split("\n")[0]
logger.print(str1)
logger.print(str2)
logger.print(str3)
if round(float(str3),8) == round(float(str1),8)+round(float(str2),8):
flag=True
else:
flag=False
self.ASSERT(flag, "neoGas not match")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_051_claimgas(self):
try:
API.cli().claim_gas(exceptfunc = lambda msg: msg.find("You have to open the wallet first.") >=0 )
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "error message not match")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
'''批量创建100个地址'''
def test_052_createaddress(self):
try:
API.cli().open_wallet(test_config.wallet_name_db3, test_config.wallet_password)
API.cli().list_address()
API.cli().create_address(test_config.n_right,exceptfunc = lambda msg: msg.find("export addresses to address.txt") >= 0,timeout=200)
API.cli().list_address()
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "create address failed1")
count0 =climsg.split("create address")[0].count("Standard",0,len(climsg))
count1 =climsg.split("create address")[1].count("Standard",0,len(climsg))
fp = open(os.getcwd().split("test/test_cli")[0]+"config.json", 'r', encoding='utf-8')
str=fp.read()
fpath = str.split("\"path\" : \"")[1].split("neo-cli.dll")[0]
fpath2 = open(fpath+"address.txt",'r')
count2 = len(fpath2.readlines())
if count2 == (count1-count0):
flag=True
else:
flag=False
self.ASSERT(flag, "create address failed2")
str1 = climsg.split("Standard")[count0+count1-1]
with open(fpath+"address.txt", 'r') as f:
lines = f.readlines() #####读取所有行
last_line = lines[-1] #####取最后一行
if str1.strip() == last_line.strip():
flag=True
else:
flag=False
self.ASSERT(flag, "create address failed3")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
'''创建1个地址'''
def test_053_createaddress(self):
try:
API.cli().open_wallet(test_config.wallet_name_db3, test_config.wallet_password)
API.cli().list_address()
API.cli().create_address(exceptfunc = lambda msg: msg.find("export addresses to address.txt") >= 0,timeout=5)
API.cli().list_address()
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "create address failed1")
count0 =climsg.split("create address")[0].count("Standard",0,len(climsg))
count1 =climsg.split("create address")[1].count("Standard",0,len(climsg))
fp = open(os.getcwd().split("test/test_cli")[0]+"config.json", 'r', encoding='utf-8')
logger.print(os.getcwd().split("test/test_cli")[0]+"config.json")
str=fp.read()
fpath = str.split("\"path\" : \"")[1].split("neo-cli.dll")[0]
logger.print(fpath)
fpath2 = open(fpath+"address.txt",'r')
count2 = len(fpath2.readlines())
if count2 == (count1-count0):
flag=True
else:
flag=False
self.ASSERT(flag, "create address failed2")
str1 = climsg.split("Standard")[count0+count1-1]
with open(fpath+"address.txt", 'r') as f:
lines = f.readlines() ####读取所有行
last_line = lines[-1] ####取最后一行
if str1.strip() == last_line.strip():
flag=True
else:
flag=False
self.ASSERT(flag, "create address failed3")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_054_createaddress(self):
try:
API.cli().open_wallet(test_config.wallet_name_db3, test_config.wallet_password)
API.cli().create_address(test_config.n_wrong_str,exceptfunc = lambda msg: msg.find("error") >= 0)
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "error message not match")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_056_createaddress(self):
try:
API.cli().open_wallet(test_config.wallet_name_db3, test_config.wallet_password)
API.cli().create_address(test_config.n_zero,exceptfunc = lambda msg: msg.find("export addresses to address.txt") >= 0,timeout=5)
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "Can't create address1")
fp = open(os.getcwd().split("test/test_cli")[0]+"config.json", 'r', encoding='utf-8')
logger.print(os.getcwd().split("test/test_cli")[0]+"config.json")
str=fp.read()
fpath = str.split("\"path\" : \"")[1].split("neo-cli.dll")[0]
logger.print(fpath)
fpath2 = open(fpath+"address.txt",'r')
count2 = len(fpath2.readlines())
if count2 == 0:
flag=True
else:
flag=False
self.ASSERT(flag, "create address failed2")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_057_createaddress(self):
try:
API.cli().create_address(test_config.n_right,exceptfunc = lambda msg: msg.find("You have to open the wallet first.") >=0 )
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "error message not match")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_058_importkey(self):
try:
'''导出wallet_5.json的一个私钥'''
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_password)
API.cli().export_key(test_config.wallet_password,WalletManager().wallet().account().address(),None)
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "export key failed1")
str1 =climsg.split("********")[1].split("neo>")[0].strip()
print(str1)
API.cli().terminate()
'''wallet_5.json的私钥导入test.json'''
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_name_json, test_config.wallet_password)
API.cli().import_key(wif_path=str1,exceptfunc = lambda msg: msg.find(WalletManager().wallet().account().address()) >=0 )
'''导出test.json的私钥,与wallet_5.json的私钥对比'''
API.cli().export_key(test_config.wallet_password,exceptfunc=lambda msg: msg.find(str1)>= 0)
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "import key failed2")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_059_importkey(self):
try:
API.cli().open_wallet(test_config.wallet_name_json, test_config.wallet_password)
API.cli().import_key(test_config.wif_notexist,exceptfunc = lambda msg: msg.find("address") >=0 )
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "Can't import key")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_060_importkey(self):
try:
API.cli().open_wallet(test_config.wallet_name_json, test_config.wallet_password)
API.cli().import_key(test_config.wif_wrong_str,exceptfunc = lambda msg: msg.find("error") >=0 )
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "error message not match")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_061_importkey(self):
try:
API.cli().open_wallet(test_config.wallet_name_json, test_config.wallet_password)
API.cli().import_key(wif_path=None, exceptfunc = lambda msg: msg.find("error") >=0 )
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "error message not match")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_062_importkey(self):
try:
API.cli().import_key(test_config.wif_right,exceptfunc = lambda msg: msg.find("error") >=0 )
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "error message not match")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_063_importkey(self):
try:
'''导出test.json的全部私钥到当前节点的akey.txt文件'''
fp = open(os.getcwd().split("test/test_cli")[0]+"config.json", 'r', encoding='utf-8')
str=fp.read()
fpath = str.split("\"path\" : \"")[1].split("neo-cli.dll")[0]
if os.path.exists(fpath+test_config.pathname):
os.remove(fpath+test_config.pathname)
API.cli().open_wallet(test_config.wallet_name_json, test_config.wallet_password)
API.cli().export_key(test_config.wallet_password,None,fpath+test_config.pathname)
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "export key failed1")
API.cli().terminate()
'''将akey.txt文件中的私钥导入至test223.db3'''
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_name_db3, test_config.wallet_password)
API.cli().import_key(fpath+test_config.pathname)
'''导出test223.db3的私钥'''
API.cli().export_key(test_config.wallet_password)
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "import key failed2")
f = open(fpath+test_config.pathname, mode='r', encoding='utf-8')
line = f.readline()
while line:
flag = climsg.find(line)
line = f.readline()
f.close()
self.ASSERT(flag != -1, "create address failed2")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_064_importkey(self):
try:
'''获取当前节点路径'''
fp = open(os.getcwd().split("test/test_cli")[0]+"config.json", 'r', encoding='utf-8')
str=fp.read()
fpath = str.split("\"path\" : \"")[1].split("neo-cli.dll")[0]
'''确保没有1allkeys1.txt文件'''
if os.path.exists(fpath+test_config.path_notexist):
os.remove(fpath+test_config.path_notexist)
API.cli().open_wallet(test_config.wallet_name_json, test_config.wallet_password)
API.cli().import_key(test_config.path_notexist,exceptfunc = lambda msg: msg.find("error") >=0 )
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "error message not match")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_065_importkey(self):
try:
'''获取当前节点路径'''
fp = open(os.getcwd().split("test/test_cli")[0]+"config.json", 'r', encoding='utf-8')
str=fp.read()
fpath = str.split("\"path\" : \"")[1].split("neo-cli.dll")[0]
'''新建一个后缀错误的path'''
if os.path.exists(fpath+test_config.path_wrong):
os.remove(fpath+test_config.path_wrong)
f = open(fpath+test_config.path_wrong, 'w')
f.close()
API.cli().open_wallet(test_config.wallet_name_json, test_config.wallet_password)
API.cli().import_key(test_config.path_wrong,exceptfunc = lambda msg: msg.find("error") >=0 )
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "error message not match")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
'''新添加的case,测version'''
def test_157_version(self):
try:
API.cli().version()
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
result = str(climsg).find("2.9.3.0")
self.ASSERT(result, "version message not match")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
'''新添加的case,测help'''
def test_158_help(self):
try:
API.cli().help()
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
result = str(climsg).find("create wallet")
self.ASSERT(result, "help message not match")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
'''新添加的case,测clear'''
def test_159_clear(self):
try:
API.cli().clear()
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "clear failed")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
'''新添加的case,测exit'''
'''exec()默认自带exit'''
def test_160_exit(self):
try:
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "exit failed")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
#address和path不填
def test_69_exportkey(self):
try:
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().list_address()
API.cli().export_key(test_config.wallet_pwd, exceptfunc=lambda msg: msg.find(test_config.key) >= 0)
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
#不打开钱包
def test_70_exportkey(self):
try:
API.cli().export_key(test_config.wallet_pwd, exceptfunc=lambda msg: msg.find("You have to open the wallet first") >= 0)
(result, stepname, msg) = API.cli().exec()
logger.print(msg)
self.ASSERT(result, "")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_71_exportkey(self):
try:
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().list_address()
filename=test_config.filename
API.cli().export_key(test_config.wallet_pwd,WalletManager().wallet(0).account().address(),filename)
(result, stepname, climsg) = API.cli().exec()
fp = open(os.getcwd().split("test/test_cli")[0]+"config.json", 'r', encoding='utf-8')
str=fp.read()
fp.close()
fpath = str.split("\"path\" : \"")[1].split("neo-cli.dll")[0]
flag=os.path.exists(fpath+filename)
self.ASSERT(flag, "file not exists")
with open(fpath+filename, mode='r', encoding='utf-8') as f:
str=f.readline()
str=str.split("\n")[0]
if str==test_config.key:
flag=True
else:
flag=False
print (flag)
self.ASSERT(flag, "key not right")
logger.print(climsg)
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_72_exportkey(self):
try:
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().list_address()
filename=test_config.filename
API.cli().export_key(test_config.wallet_pwd,None,filename)
(result, stepname, climsg) = API.cli().exec()
fp = open(os.getcwd().split("test/test_cli")[0]+"config.json", 'r', encoding='utf-8')
str=fp.read()
fp.close()
fpath = str.split("\"path\" : \"")[1].split("neo-cli.dll")[0]
flag=os.path.exists(fpath+filename)
self.ASSERT(flag, "file not exists")
with open(fpath+filename, mode='r', encoding='utf-8') as f:
str=f.readline()
str=str.split("\n")[0]
if str==test_config.key:
flag=True
else:
flag=False
print (flag)
self.ASSERT(flag, "key not right")
logger.print(climsg)
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_73_exportkey(self):
try:
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().list_address()
filename=test_config.filename
API.cli().export_key(test_config.wallet_pwd,test_config.address_notexist,filename,exceptfunc=lambda msg: msg.find("error") >= 0)
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_75_exportkey(self):
try:
API.cli().list_address()
filename=test_config.filename
API.cli().export_key(test_config.wallet_pwd,WalletManager().wallet(0).account().address(),filename,exceptfunc=lambda msg: msg.find("You have to open the wallet first") >= 0)
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_77_exportkey(self):
try:
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().list_address()
API.cli().export_key(test_config.wallet_pwd,WalletManager().wallet(0).account().address(),None, exceptfunc=lambda msg: msg.find(test_config.key)>= 0)
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_78_exportkey(self):
try:
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().list_address()
filename=test_config.filename
API.cli().export_key(test_config.wallet_pwd,WalletManager().wallet(0).account().address(),filename)
(result, stepname, climsg) = API.cli().exec()
fp = open(os.getcwd().split("test/test_cli")[0]+"config.json", 'r', encoding='utf-8')
str=fp.read()
fp.close()
fpath = str.split("\"path\" : \"")[1].split("neo-cli.dll")[0]
flag=os.path.exists(fpath+filename)
self.ASSERT(flag,"file not exists")
with open(fpath+filename, mode='r', encoding='utf-8') as f:
str=f.readline()
str=str.split("\n")[0]
if str==test_config.key:
flag=True
else:
flag=False
print (flag)
self.ASSERT(flag, "assert not equal")
logger.print(climsg)
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
#bug
def test_79_exportkey(self):
try:
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().list_address()
filename=test_config.wrongfilename
API.cli().export_key(test_config.wallet_pwd,WalletManager().wallet(0).account().address(),filename, exceptfunc=lambda msg: msg.find("error")>= 0)
(result, stepname, climsg) = API.cli().exec()
logger.print(climsg)
self.ASSERT(result, "assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_82_send(self):
try:
##事前获取
API.cli().open_wallet(test_config.wallet_default2, "11111111")
API.cli().list_asset()
(result, stepname, msg) = API.cli().exec(False)
res1=API.rpc().getaccountstate(WalletManager().wallet(0).account().address());
res2=API.rpc().getaccountstate(WalletManager().wallet(1).account().address());
self.ASSERT(res1!=None, "get getaccountstate error1!")
addr1Neo=self.return_neo_gas(res1,True)
addr1Gas=self.return_neo_gas(res1,False)
addr2Neo=0
addr2Gas=0
try:
addr2Neo=self.return_neo_gas(res2,True)
except:
addr2Neo=0
try:
addr2Gas=self.return_neo_gas(res2,False)
except:
addr2Gas=0
API.cli().terminate()
#从wallet_5向wallet_6转账10neo
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().list_asset()
API.cli().show_state(times=30)
API.cli().send(test_config.wallet_pwd,test_config.asset_id_right, WalletManager().wallet(1).account().address(), value="10",fee=None)
(result, stepname, msg1) = API.cli().exec(False)
logger.print(msg1)
#等一个block
API.node().wait_gen_block()
##事后获取
res1=API.rpc().getaccountstate(WalletManager().wallet(0).account().address());
res2=API.rpc().getaccountstate(WalletManager().wallet(1).account().address());
self.ASSERT(res1!=None, "get getaccountstate error2!")
self.ASSERT(res2!=None, "get getaccountstate error2!")
addr1Neo2=self.return_neo_gas(res1,True)
addr1Gas2=self.return_neo_gas(res1,False)
addr2Neo2=self.return_neo_gas(res2,True)
addr2Gas2=self.return_neo_gas(res2,False)
#API.cli().terminate()
##计算结果
value=10
gasvalue=0
fee=0
self.ASSERT((float(addr2Neo2)-float(addr2Neo))==value, "arrive address neo check")
self.ASSERT((float(addr1Neo)-float(addr1Neo2))==value, "send address neo check")
self.ASSERT(round(float(addr1Gas)-float(addr1Gas2),8)==round(gasvalue+fee,8), "send address gas check")
self.ASSERT(round(float(addr2Gas2)-float(addr2Gas),8)==gasvalue, "arrive address gas check")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_83_send(self):
try:
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().send(test_config.wallet_pwd,test_config.asset_id_notexist, WalletManager().wallet(0).account().address(), "10",exceptfunc=lambda msg: msg.find("error") >= 0)
(result, stepname, msg) = API.cli().exec()
logger.print(msg)
self.ASSERT(result,"assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_85_send(self):
try:
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().send(test_config.wallet_pwd,None,WalletManager().wallet(0).account().address(), "10",exceptfunc=lambda msg: msg.find("error") >= 0)
(result, stepname, msg) = API.cli().exec()
logger.print(msg)
self.ASSERT(result,"assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_86_send(self):
try:
API.cli().send(test_config.wallet_pwd,test_config.asset_id_notexist,WalletManager().wallet(0).account().address(), "10",exceptfunc=lambda msg: msg.find("You have to open the wallet first") >= 0)
(result, stepname, msg) = API.cli().exec()
logger.print(msg)
self.ASSERT(result,"assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_87_send(self):
try:
##事前获取
API.cli().open_wallet(test_config.wallet_default2, "11111111")
API.cli().list_asset()
(result, stepname, msg) = API.cli().exec(False)
res1=API.rpc().getaccountstate(WalletManager().wallet(0).account().address());
res2=API.rpc().getaccountstate(WalletManager().wallet(1).account().address());
self.ASSERT(res1!=None, "get getaccountstate error1!")
addr1Neo=self.return_neo_gas(res1,True)
addr1Gas=self.return_neo_gas(res1,False)
addr2Neo=0
addr2Gas=0
try:
addr2Neo=self.return_neo_gas(res2,True)
except:
addr2Neo=0
try:
addr2Gas=self.return_neo_gas(res2,False)
except:
addr2Gas=0
API.cli().terminate()
#从wallet_5向wallet_6转账10neo
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().list_asset()
API.cli().show_state(times=30)
API.cli().send(test_config.wallet_pwd,"NEO", WalletManager().wallet(1).account().address(), value="10",fee=None)
(result, stepname, msg1) = API.cli().exec(False)
logger.print(msg1)
#等一个block
API.node().wait_gen_block()
##事后获取
res1=API.rpc().getaccountstate(WalletManager().wallet(0).account().address());
res2=API.rpc().getaccountstate(WalletManager().wallet(1).account().address());
self.ASSERT(res1!=None, "get getaccountstate error2!")
self.ASSERT(res2!=None, "get getaccountstate error2!")
addr1Neo2=self.return_neo_gas(res1,True)
addr1Gas2=self.return_neo_gas(res1,False)
addr2Neo2=self.return_neo_gas(res2,True)
addr2Gas2=self.return_neo_gas(res2,False)
#API.cli().terminate()
##计算结果
value=10
gasvalue=0
fee=0
self.ASSERT((float(addr2Neo2)-float(addr2Neo))==value, "arrive address neo check")
self.ASSERT((float(addr1Neo)-float(addr1Neo2))==value, "send address neo check")
self.ASSERT(round(float(addr1Gas)-float(addr1Gas2),8)==round(gasvalue+fee,8), "send address gas check")
self.ASSERT(round(float(addr2Gas2)-float(addr2Gas),8)==gasvalue, "arrive address gas check")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_88_send(self):
try:
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().send(test_config.wallet_pwd,test_config.wrong_str,WalletManager().wallet(0).account().address(), "10",exceptfunc=lambda msg: msg.find("error") >= 0)
(result, stepname, msg) = API.cli().exec()
logger.print(msg)
self.ASSERT(result,"assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_92_send(self):
try:
#获取wallet_6余额
API.cli().open_wallet(test_config.wallet_default2, "11111111")
API.cli().list_asset()
(result, stepname, msg) = API.cli().exec(False)
logger.print(msg)
w2neobalance1=0
try:
w2neobalance1=msg.split("NEO\n")[1].split("balance:")[1].split("\n")[0]
except:
w2neobalance1=0
API.cli().terminate()
#从wallet_5向wallet_6转账10neo
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().list_asset()
API.cli().show_state(times=30)
API.cli().send(test_config.wallet_pwd,test_config.asset_id_right, WalletManager().wallet(1).account().address(), "10")
(result, stepname, msg1) = API.cli().exec(False)
API.node().wait_gen_block()
API.cli().terminate()
#等一个block
#获取转账后的neo值
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().list_asset()
(result, stepname, msg2) = API.cli().exec(False)
logger.print(msg1)
logger.print(msg2)
API.cli().terminate()
neobalance1=msg1.split("NEO\n")[1].split("balance:")[1].split("\n")[0]
neobalance2=msg2.split("NEO\n")[1].split("balance:")[1].split("\n")[0]
gasbalance1=msg1.split("NeoGas\n")[1].split("balance:")[1].split("\n")[0]
gasbalance2=msg2.split("NeoGas\n")[1].split("balance:")[1].split("\n")[0]
print ("**********************neobalance1:"+neobalance1+"************")
print ("**********************neobalance2:"+neobalance2+"************")
print ("**********************gasbalance1:"+gasbalance1+"************")
print ("**********************gasbalance2:"+gasbalance2+"************")
plus1=float(neobalance1)-float(neobalance2)
plus2=float(gasbalance1)-float(gasbalance2)
#获取钱包2的NEO
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default2, "11111111")
API.cli().list_asset()
(result, stepname, msg) = API.cli().exec()
logger.print(msg)
w2neobalance2=msg.split("NEO\n")[1].split("balance:")[1].split("\n")[0]
print ("**********************w2neobalance1:"+str(w2neobalance1)+"************")
print ("**********************w2neobalance2:"+w2neobalance2+"************")
plus3=float(w2neobalance2)-float(w2neobalance1)
flag=False
if int(plus1)==10 and int(plus2)==0 and int(plus3)==10:
flag=True
self.ASSERT(flag,"assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_93_send(self):
try:
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().send(test_config.wallet_pwd,test_config.asset_id_right,None, "10",exceptfunc=lambda msg: msg.find("error") >= 0)
(result, stepname, msg) = API.cli().exec()
logger.print(msg)
self.ASSERT(result,"assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
###address不存在情况会error
def test_94_send(self):
try:
#获取不存在的地址的余额
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
(result, stepname, msg2) = API.cli().exec(False)
res1=API.rpc().getaccountstate(test_config.address_notexist);
w2neobalance1=0
w2gasbalance1=0
if res1==None:
w2neobalance1=0
w2gasbalance1=0
else:
w2neobalance1=self.return_neo_gas(res1,True)
w2gasbalance1=self.return_neo_gas(res1,False)
API.cli().terminate()
#从wallet_5向不存在的地址转账10neo
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().list_asset()
API.cli().show_state(times=30)
API.cli().send(test_config.wallet_pwd,test_config.asset_id_right, test_config.address_notexist, "10")
(result, stepname, msg1) = API.cli().exec(False)
#等一个block
API.node().wait_gen_block()
API.cli().terminate()
#获取转账后的neo值
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().list_asset()
(result, stepname, msg2) = API.cli().exec(False)
logger.print(msg1)
logger.print(msg2)
API.cli().terminate()
neobalance1=msg1.split("NEO\n")[1].split("balance:")[1].split("\n")[0]
neobalance2=msg2.split("NEO\n")[1].split("balance:")[1].split("\n")[0]
gasbalance1=msg1.split("NeoGas\n")[1].split("balance:")[1].split("\n")[0]
gasbalance2=msg2.split("NeoGas\n")[1].split("balance:")[1].split("\n")[0]
print ("**********************neobalance1:"+neobalance1+"************")
print ("**********************neobalance2:"+neobalance2+"************")
print ("**********************gasbalance1:"+gasbalance1+"************")
print ("**********************gasbalance2:"+gasbalance2+"************")
plus1=float(neobalance1)-float(neobalance2)
plus2=float(gasbalance1)-float(gasbalance2)
#获取不存在的地址的余额
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
(result, stepname, msg2) = API.cli().exec(False)
res1=API.rpc().getaccountstate(test_config.address_notexist);
self.ASSERT(res1!=None, "get getaccountstate error1!")
w2neobalance2=self.return_neo_gas(res1,True)
w2gasbalance2=self.return_neo_gas(res1,False)
# API.cli().terminate()
print ("**********************w2neobalance1:"+str(w2neobalance1)+"************")
print ("**********************w2neobalance2:"+str(w2neobalance2)+"************")
print ("**********************w2neobalance2:"+str(w2gasbalance1)+"************")
print ("**********************w2neobalance2:"+str(w2gasbalance2)+"************")
plus3=float(w2neobalance2)-float(w2neobalance1)
plus4=float(w2gasbalance2)-float(w2gasbalance1)
##计算结果
value=10
gasvalue=0
fee=0
self.ASSERT(plus3==value, "arrive address neo check")
self.ASSERT(plus1==value, "send address neo check")
self.ASSERT(plus2==round(gasvalue+fee,8), "send address gas check")
self.ASSERT(round(plus4)==gasvalue, "arrive address gas check")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_95_send(self):
try:
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().send(test_config.wallet_pwd,test_config.asset_id_right,test_config.wrong_str, "10",exceptfunc=lambda msg: msg.find("error") >= 0)
(result, stepname, msg) = API.cli().exec()
logger.print(msg)
self.ASSERT(result,"assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_98_send(self):
try:
#获取wallet_6余额
API.cli().open_wallet(test_config.wallet_default2, "11111111")
API.cli().list_asset()
(result, stepname, msg) = API.cli().exec(False)
logger.print(msg)
w2neobalance1=0
try:
w2neobalance1=msg.split("NEO\n")[1].split("balance:")[1].split("\n")[0]
except:
w2neobalance1=0
API.cli().terminate()
#从wallet_5向wallet_6转账10neo
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().list_asset()
API.cli().show_state(times=30)
API.cli().send(test_config.wallet_pwd,test_config.asset_id_right, WalletManager().wallet(1).account().address(), "0")
(result, stepname, msg1) = API.cli().exec(False)
API.node().wait_gen_block()
API.cli().terminate()
#等一个block
#获取转账后的neo值
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().list_asset()
(result, stepname, msg2) = API.cli().exec(False)
logger.print(msg1)
logger.print(msg2)
API.cli().terminate()
try:
neobalance1=msg1.split("NEO\n")[1].split("balance:")[1].split("\n")[0]
neobalance2=msg2.split("NEO\n")[1].split("balance:")[1].split("\n")[0]
gasbalance1=msg1.split("NeoGas\n")[1].split("balance:")[1].split("\n")[0]
gasbalance2=msg2.split("NeoGas\n")[1].split("balance:")[1].split("\n")[0]
except:
self.ASSERT(False,"error:get neo balance failed")
print ("**********************neobalance1:"+neobalance1+"************")
print ("**********************neobalance2:"+neobalance2+"************")
print ("**********************gasbalance1:"+gasbalance1+"************")
print ("**********************gasbalance2:"+gasbalance2+"************")
plus1=float(neobalance1)-float(neobalance2)
plus2=float(gasbalance1)-float(gasbalance2)
#获取钱包2的NEO
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default2, "11111111")
API.cli().list_asset()
(result, stepname, msg) = API.cli().exec()
logger.print(msg)
try:
w2neobalance2=msg.split("NEO\n")[1].split("balance:")[1].split("\n")[0]
except:
self.ASSERT(False,"error:get neo balance failed")
print ("**********************w2neobalance1:"+str(w2neobalance1)+"************")
print ("**********************w2neobalance2:"+w2neobalance2+"************")
plus3=float(w2neobalance2)-float(w2neobalance1)
flag=False
if int(plus1)==0 and int(plus2)==0 and int(plus3)==0:
flag=True
self.ASSERT(flag,"assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_99_send(self):
try:
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().list_asset()
API.cli().show_state(times=30)
API.cli().send(test_config.wallet_pwd,test_config.asset_id_right, WalletManager().wallet(1).account().address(), value=None,fee=None,exceptfunc=lambda msg: msg.find("error") >= 0)
(result, stepname, msg) = API.cli().exec(False)
logger.print(msg)
self.ASSERT(result,"assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_100_send(self):
try:
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().list_asset()
API.cli().show_state(times=30)
API.cli().send(test_config.wallet_pwd,test_config.asset_id_right,WalletManager().wallet(1).account().address(), test_config.wrong_str,exceptfunc=lambda msg: msg.find("Incorrect Amount Format") >= 0)
(result, stepname, msg) = API.cli().exec()
logger.print(msg)
self.ASSERT(result,"assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_101_send(self):
try:
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().send(test_config.wallet_pwd,test_config.asset_id_right,WalletManager().wallet(1).account().address(), "1000000000",exceptfunc=lambda msg: msg.find("Insufficient funds") >= 0)
(result, stepname, msg) = API.cli().exec()
logger.print(msg)
self.ASSERT(result,"assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_102_send(self):
try:
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().send(test_config.wallet_pwd,test_config.asset_id_right,WalletManager().wallet(1).account().address(), "-1",exceptfunc=lambda msg: msg.find("Negative values cannot be sent") >= 0)
(result, stepname, msg) = API.cli().exec()
logger.print(msg)
self.ASSERT(result,"assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_104_send(self):
try:
#从钱包5向钱包6转账100neo
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().list_asset()
API.cli().show_state(times=30)
API.cli().send(test_config.wallet_pwd,test_config.asset_id_right, test_config.wallet_default3address, value="100")
(result, stepname, msg1) = API.cli().exec(False)
API.node().wait_gen_block()
API.cli().terminate()
##事前获取
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default3, "11111111")
API.cli().list_asset()
(result, stepname, msg) = API.cli().exec(False)
logger.print(msg)
res1=API.rpc().getaccountstate(test_config.wallet_default3address);
res2=API.rpc().getaccountstate(WalletManager().wallet(1).account().address());
self.ASSERT(res1!=None, "get getaccountstate error1!")
self.ASSERT(res2!=None, "get getaccountstate error1!")
neobalance1=self.return_neo_gas(res1,True)
gasbalance1=self.return_neo_gas(res1,False)
w2neobalance1=0
w2gasbalance1=0
try:
w2neobalance1=self.return_neo_gas(res2,True)
except:
w2neobalance1=0
try:
w2gasbalance1=self.return_neo_gas(res2,False)
except:
w2gasbalance1=0
API.cli().terminate()
#从wallet_7向wallet_6转账所有neo
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default3, test_config.wallet_pwd)
API.cli().list_asset()
API.cli().show_state(times=30)
API.cli().send(test_config.wallet_pwd,test_config.asset_id_right, WalletManager().wallet(1).account().address(), value="all",fee=None)
(result, stepname, msg1) = API.cli().exec(False)
logger.print(msg1)
#等一个block
##事后获取
API.node().wait_gen_block()
res1=API.rpc().getaccountstate(test_config.wallet_default3address);
res2=API.rpc().getaccountstate(WalletManager().wallet(1).account().address());
self.ASSERT(res1!=None, "get getaccountstate error2!")
self.ASSERT(res2!=None, "get getaccountstate error2!")
neobalance2=0
gasbalance2=0
try:
neobalance2=self.return_neo_gas(res1,True)
except:
neobalance2=0
try:
gasbalance2=self.return_neo_gas(res1,False)
except:
gasbalance2=0
w2neobalance2=self.return_neo_gas(res2,True)
w2gasbalance2=self.return_neo_gas(res2,False)
print ("**********************neobalance1:"+str(neobalance1)+"************")
print ("**********************neobalance2:"+str(neobalance2)+"************")
print ("**********************gasbalance1:"+str(gasbalance1)+"************")
print ("**********************gasbalance2:"+str(gasbalance2)+"************")
print ("**********************w2neobalance1:"+str(w2neobalance1)+"************")
print ("**********************w2neobalance2:"+str(w2neobalance2)+"************")
print ("**********************w2neobalance1:"+str(w2gasbalance1)+"************")
print ("**********************w2neobalance2:"+str(w2gasbalance2)+"************")
plus1=float(neobalance1)-float(neobalance2)
plus2=float(gasbalance1)-float(gasbalance2)
plus3=float(w2neobalance2)-float(w2neobalance1)
plus4=float(w2gasbalance2)-float(w2gasbalance1)
#计算结果
value=float(neobalance1)
gasvalue=0
fee=0
self.ASSERT(plus3==value, "arrive address neo check")
self.ASSERT(plus1==value, "send address neo check")
self.ASSERT(plus2==round(gasvalue+fee,8), "send address gas check")
self.ASSERT(plus4==gasvalue, "arrive address gas check")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_105_send(self):
try:
API.cli().send(test_config.wallet_pwd,test_config.asset_id_right,WalletManager().wallet(1).account().address(), "1",exceptfunc=lambda msg: msg.find("You have to open the wallet first") >= 0)
(result, stepname, msg) = API.cli().exec()
logger.print(msg)
self.ASSERT(result,"assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_106_send(self):
try:
#获取wallet_6余额
API.cli().open_wallet(test_config.wallet_default2, "11111111")
API.cli().list_asset()
(result, stepname, msg) = API.cli().exec(False)
logger.print(msg)
w2neobalance1=0
w2gasbalance1=0
try:
w2neobalance1=msg.split("NEO\n")[1].split("balance:")[1].split("\n")[0]
w2gasbalance1=msg.split("NeoGas\n")[1].split("balance:")[1].split("\n")[0]
except:
w2neobalance1=0
w2gasbalance1=0
API.cli().terminate()
#从wallet_5向wallet_6转账10neo
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().list_asset()
API.cli().show_state(times=30)
API.cli().send(test_config.wallet_pwd,test_config.asset_id_right, WalletManager().wallet(1).account().address(), "10","1")
(result, stepname, msg1) = API.cli().exec(False)
API.node().wait_gen_block()
API.cli().terminate()
#等一个block
#获取转账后wallet_5的neo值
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().list_asset()
(result, stepname, msg2) = API.cli().exec(False)
logger.print(msg1)
logger.print(msg2)
API.cli().terminate()
try:
neobalance1=msg1.split("NEO\n")[1].split("balance:")[1].split("\n")[0]
neobalance2=msg2.split("NEO\n")[1].split("balance:")[1].split("\n")[0]
gasbalance1=msg1.split("NeoGas\n")[1].split("balance:")[1].split("\n")[0]
gasbalance2=msg2.split("NeoGas\n")[1].split("balance:")[1].split("\n")[0]
except:
self.ASSERT(False,"error:get neo balance failed")
print ("**********************neobalance1:"+neobalance1+"************")
print ("**********************neobalance2:"+neobalance2+"************")
print ("**********************gasbalance1:"+gasbalance1+"************")
print ("**********************gasbalance2:"+gasbalance2+"************")
plus1=float(neobalance1)-float(neobalance2)
plus2=float(gasbalance1)-float(gasbalance2)
#获取钱包2的NEO
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default2, "11111111")
API.cli().list_asset()
(result, stepname, msg) = API.cli().exec()
logger.print(msg)
try:
w2neobalance2=msg.split("NEO\n")[1].split("balance:")[1].split("\n")[0]
w2gasbalance2=msg.split("NeoGas\n")[1].split("balance:")[1].split("\n")[0]
except:
self.ASSERT(False,"error:get neo balance failed")
print ("**********************w2neobalance1:"+str(w2neobalance1)+"************")
print ("**********************w2neobalance2:"+w2neobalance2+"************")
plus3=float(w2neobalance2)-float(w2neobalance1)
plus4=float(w2gasbalance2)-float(w2gasbalance1)
##计算结果
value=10
gasvalue=0
fee=1
self.ASSERT(plus1==value, "arrive address neo check")
self.ASSERT(plus3==value, "send address neo check")
self.ASSERT(plus2==round(gasvalue+fee,8), "send address gas check")
self.ASSERT(plus4==gasvalue, "arrive address gas check")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_107_send(self):
try:
#获取wallet_6余额
API.cli().open_wallet(test_config.wallet_default2, "11111111")
API.cli().list_asset()
(result, stepname, msg) = API.cli().exec(False)
logger.print(msg)
w2neobalance1=0
w2gasbalance1=0
try:
w2neobalance1=msg.split("NEO\n")[1].split("balance:")[1].split("\n")[0]
w2gasbalance1=msg.split("NeoGas\n")[1].split("balance:")[1].split("\n")[0]
except:
w2neobalance1=0
w2gasbalance1=0
API.cli().terminate()
#从wallet_5向wallet_6转账10neo
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().list_asset()
API.cli().show_state(times=30)
API.cli().send(test_config.wallet_pwd,test_config.asset_id_right, WalletManager().wallet(1).account().address(), "0")
(result, stepname, msg1) = API.cli().exec(False)
API.node().wait_gen_block()
API.cli().terminate()
#等一个block
#获取转账后wallet_5的neo值
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().list_asset()
(result, stepname, msg2) = API.cli().exec(False)
logger.print(msg1)
logger.print(msg2)
API.cli().terminate()
try:
neobalance1=msg1.split("NEO\n")[1].split("balance:")[1].split("\n")[0]
neobalance2=msg2.split("NEO\n")[1].split("balance:")[1].split("\n")[0]
gasbalance1=msg1.split("NeoGas\n")[1].split("balance:")[1].split("\n")[0]
gasbalance2=msg2.split("NeoGas\n")[1].split("balance:")[1].split("\n")[0]
except:
self.ASSERT(False,"error:get neo balance failed")
print ("**********************neobalance1:"+neobalance1+"************")
print ("**********************neobalance2:"+neobalance2+"************")
print ("**********************gasbalance1:"+gasbalance1+"************")
print ("**********************gasbalance2:"+gasbalance2+"************")
plus1=float(neobalance1)-float(neobalance2)
plus2=float(gasbalance1)-float(gasbalance2)
#获取钱包2的NEO
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default2, "11111111")
API.cli().list_asset()
(result, stepname, msg) = API.cli().exec()
logger.print(msg)
try:
w2neobalance2=msg.split("NEO\n")[1].split("balance:")[1].split("\n")[0]
w2gasbalance2=msg.split("NeoGas\n")[1].split("balance:")[1].split("\n")[0]
except:
self.ASSERT(False,"error:get neo balance failed")
print ("**********************w2neobalance1:"+str(w2neobalance1)+"************")
print ("**********************w2neobalance2:"+w2neobalance2+"************")
plus3=float(w2neobalance2)-float(w2neobalance1)
plus4=float(w2gasbalance2)-float(w2gasbalance1)
##计算结果
value=0
gasvalue=0
fee=0
self.ASSERT(plus1==value, "arrive address neo check")
self.ASSERT(plus3==value, "send address neo check")
self.ASSERT(plus2==round(gasvalue+fee,8), "send address gas check")
self.ASSERT(plus4==gasvalue, "arrive address gas check")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_108_send(self):
try:
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().send(test_config.wallet_pwd,test_config.asset_id_right,WalletManager().wallet(1).account().address(), "1",test_config.wrong_str,exceptfunc=lambda msg: msg.find("error") >= 0)
(result, stepname, msg) = API.cli().exec()
logger.print(msg)
self.ASSERT(result,"assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_109_send(self):
try:
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().send(test_config.wallet_pwd,test_config.asset_id_right,WalletManager().wallet(1).account().address(), "1","1000000000",exceptfunc=lambda msg: msg.find("Insufficient funds") >= 0)
(result, stepname, msg) = API.cli().exec()
logger.print(msg)
self.ASSERT(result,"assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_110_send(self):
try:
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().send(test_config.wallet_pwd,test_config.asset_id_right,WalletManager().wallet(1).account().address(), "1","-1",exceptfunc=lambda msg: msg.find("error") >= 0)
(result, stepname, msg) = API.cli().exec()
logger.print(msg)
self.ASSERT(result,"assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_112_import_multisigaddress(self):
try:
# # #从钱包5内默认地址向钱包5内multi地址转10neo(RPC)
# #API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, "11111111")
API.cli().list_address(lambda msg: msg.find(WalletManager().wallet(0).account().address()) >= 0)
API.cli().show_state(30)
(status, info, climsg) = API.cli().exec(False)
logger.print(climsg)
self.ASSERT(status, info)
##事前获取
res1=API.rpc().getaccountstate(WalletManager().wallet(0).account().address());
res2=API.rpc().getaccountstate(test_config.mutiaddress);
self.ASSERT(res1!=None, "get getaccountstate error1!")
addr1Neo=self.return_neo_gas(res1,True)
addr1Gas=self.return_neo_gas(res1,False)
addr2Neo=0
addr2Gas=0
if res2!=None:
addr2Neo=self.return_neo_gas(res2,True)
addr2Gas=self.return_neo_gas(res2,False)
result = API.rpc().sendfrom(test_config.asset_id_right,
WalletManager().wallet(0).account().address(),
test_config.mutiaddress, value=10,fee=0,change_address="empty")
self.ASSERT(result!=None, "")
self.ASSERT(result["net_fee"]=="0", "")
API.node().wait_gen_block()
##事后获取
res1=API.rpc().getaccountstate(WalletManager().wallet(0).account().address());
res2=API.rpc().getaccountstate("Ae5FRbhndo2XKRFqEQ9Mn99bRbeKqHLxWV");
self.ASSERT(res1!=None, "get getaccountstate error2!")
self.ASSERT(res2!=None, "get getaccountstate error2!")
addr1Neo2=self.return_neo_gas(res1,True)
addr1Gas2=self.return_neo_gas(res1,False)
addr2Neo2=self.return_neo_gas(res2,True)
addr2Gas2=self.return_neo_gas(res2,False)
##计算结果
value=10
fee=0
self.ASSERT((float(addr2Neo2)-float(addr2Neo))==value, "arrive address neo check")
self.ASSERT((float(addr1Neo)-float(addr1Neo2))==value, "send address neo check")
self.ASSERT(round(float(addr1Gas)-float(addr1Gas2),8)==fee, "send address gas check")
API.cli().terminate()
#从mutiaddress向钱包5默认地址转5Neo,获取第一次生成的交易json
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.mutiname, test_config.wallet_pwd)
API.cli().show_state(times=30)
(result, stepname, msg) = API.cli().exec(False)
logger.print(msg)
result = API.rpc().sendfrom(test_config.asset_id_right,
test_config.mutiaddress,
WalletManager().wallet(0).account().address(), value=5,fee=0,change_address=test_config.mutiaddress)
self.ASSERT(result!=None, "")
json1=str(result)
print("++++++++++++++:"+json1)
time.sleep(20)
API.cli().terminate()
#确认存在后使用relay方法广播jsonObject(cli,需要检查结果,应该广播不出去)
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().relay(jsonobj=json1)
(result, stepname, msg) = API.cli().exec(False)
API.cli().terminate()
logger.print(msg)
flag1=False
if msg.find("The signature is incomplete.")>=0:
flag1=True
self.ASSERT(flag1, "relay1 failed")
# #先sign交易json,获取输出的json,需要检查,如果没有输出json则报错
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().list_asset()
API.cli().sign(jsonobj=json1)
(result, stepname, msg) = API.cli().exec(False)
logger.print(msg)
self.ASSERT(str(msg).find("Signed Output")>=0, "failed to sign")
#在relay前确认钱包5默认地址余额和mutiaddress内余额
res1=API.rpc().getaccountstate(WalletManager().wallet(0).account().address());
res2=API.rpc().getaccountstate(test_config.mutiaddress);
self.ASSERT(res1!=None, "get getaccountstate error1!")
self.ASSERT(res2!=None, "get getaccountstate error1!")
w5neo1=self.return_neo_gas(res1,True)
muneo1=self.return_neo_gas(res2,True)
API.cli().terminate()
try:
json2=msg.split("Signed Output:\n\n")[1].split("\n")[0]
except:
self.ASSERT(False,"error:unable to get json2")
# #relay输出的交易json,需要检查结果,应该广播成功
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.mutiname, test_config.wallet_pwd)
API.cli().relay(jsonobj=json2)
(result, stepname, msg) = API.cli().exec(False)
logger.print(msg)
flag2=False
if msg.find("success")>=0:
flag2=True
self.ASSERT(flag2, "relay2 failed")
# #等待一个block
API.node().wait_gen_block()
API.cli().terminate()
# #检查钱包5内默认地址的余额是否增加5neo(RPC),mutiaddress内是否减少5neo
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().list_asset()
(result, stepname, msg) = API.cli().exec(False)
logger.print(msg)
API.node().wait_gen_block()
res1=API.rpc().getaccountstate(WalletManager().wallet(0).account().address());
res2=API.rpc().getaccountstate(test_config.mutiaddress);
self.ASSERT(res1!=None, "get getaccountstate error1!")
self.ASSERT(res2!=None, "get getaccountstate error1!")
w5neo2=self.return_neo_gas(res1,True)
muneo2=self.return_neo_gas(res2,True)
plus1=float(w5neo2)-float(w5neo1)
plus2=float(muneo1)-float(muneo2)
print(str(w5neo1)+" "+str(w5neo2)+" "+str(muneo1)+" "+str(muneo2))
self.ASSERT(int(plus1)==5, "send address neo check")
self.ASSERT(int(plus2)==5, "arrive address neo check")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_114_import_multisigaddress(self):
try:
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().import_multisigaddress(None,[test_config.key1,test_config.key2],exceptfunc=lambda msg: msg.find("Error. Use at least 2 public keys to create a multisig address.") >= 0)
(result, stepname, msg) = API.cli().exec()
logger.print(msg)
self.ASSERT(result,"assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_115_import_multisigaddress(self):
try:
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().import_multisigaddress("abc",[test_config.key1,test_config.key2],exceptfunc=lambda msg: msg.find("error") >= 0)
(result, stepname, msg) = API.cli().exec()
logger.print(msg)
self.ASSERT(result,"assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_116_import_multisigaddress(self):
try:
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().import_multisigaddress("3",[test_config.key1,test_config.key2],exceptfunc=lambda msg: msg.find("Error. Invalid parameters") >= 0)
(result, stepname, msg) = API.cli().exec()
logger.print(msg)
self.ASSERT(result,"assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_117_import_multisigaddress(self):
try:
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().import_multisigaddress("0",[test_config.key1,test_config.key2],exceptfunc=lambda msg: msg.find("Error. Invalid parameters") >= 0)
(result, stepname, msg) = API.cli().exec()
logger.print(msg)
self.ASSERT(result,"assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_118_import_multisigaddress(self):
try:
API.cli().import_multisigaddress("2",[test_config.key1,test_config.key2],exceptfunc=lambda msg: msg.find("You have to open the wallet first") >= 0)
(result, stepname, msg) = API.cli().exec()
logger.print(msg)
self.ASSERT(result,"assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_120_import_multisigaddress(self):
try:
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().import_multisigaddress("2",None,exceptfunc=lambda msg: msg.find("Error. Use at least 2 public keys to create a multisig address.") >= 0)
(result, stepname, msg) = API.cli().exec()
logger.print(msg)
self.ASSERT(result,"assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_121_import_multisigaddress(self):
try:
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().import_multisigaddress("2",[test_config.key3,test_config.key2],exceptfunc=lambda msg: msg.find("Multisig. Addr.: APkNTWRpoJCCxn7YR6Jc7ALCExGMGLsrp4") >= 0)
(result, stepname, msg) = API.cli().exec()
logger.print(msg)
self.ASSERT(result,"assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_122_import_multisigaddress(self):
try:
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().import_multisigaddress("2",['abc',test_config.key2],exceptfunc=lambda msg: msg.find("error") >= 0)
(result, stepname, msg) = API.cli().exec()
logger.print(msg)
self.ASSERT(result,"assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_123_import_multisigaddress(self):
try:
API.cli().import_multisigaddress("2",[test_config.key1,test_config.key2],exceptfunc=lambda msg: msg.find("You have to open the wallet first") >= 0)
(result, stepname, msg) = API.cli().exec()
logger.print(msg)
self.ASSERT(result,"assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_124_jsonObjectToSign(self):
try:
# # #从钱包5内默认地址向钱包5内multi地址转10neo(RPC)
# #API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, "11111111")
API.cli().list_address(lambda msg: msg.find(WalletManager().wallet(0).account().address()) >= 0)
API.cli().show_state(30)
(status, info, climsg) = API.cli().exec(False)
logger.print(climsg)
self.ASSERT(status, info)
##事前获取
res1=API.rpc().getaccountstate(WalletManager().wallet(0).account().address());
res2=API.rpc().getaccountstate(test_config.mutiaddress);
self.ASSERT(res1!=None, "get getaccountstate error1!")
addr1Neo=self.return_neo_gas(res1,True)
addr1Gas=self.return_neo_gas(res1,False)
addr2Neo=0
addr2Gas=0
if res2!=None:
addr2Neo=self.return_neo_gas(res2,True)
addr2Gas=self.return_neo_gas(res2,False)
result = API.rpc().sendfrom(test_config.asset_id_right,
WalletManager().wallet(0).account().address(),
test_config.mutiaddress, value=10,fee=0,change_address="empty")
self.ASSERT(result!=None, "sendfrom failed")
self.ASSERT(result["net_fee"]=="0", "")
API.node().wait_gen_block()
##事后获取
res1=API.rpc().getaccountstate(WalletManager().wallet(0).account().address());
res2=API.rpc().getaccountstate("Ae5FRbhndo2XKRFqEQ9Mn99bRbeKqHLxWV");
self.ASSERT(res1!=None, "get getaccountstate error2!")
self.ASSERT(res2!=None, "get getaccountstate error2!")
addr1Neo2=self.return_neo_gas(res1,True)
addr1Gas2=self.return_neo_gas(res1,False)
addr2Neo2=self.return_neo_gas(res2,True)
addr2Gas2=self.return_neo_gas(res2,False)
##计算结果
value=10
fee=0
self.ASSERT((float(addr2Neo2)-float(addr2Neo))==value, "arrive address neo check")
self.ASSERT((float(addr1Neo)-float(addr1Neo2))==value, "send address neo check")
self.ASSERT(round(float(addr1Gas)-float(addr1Gas2),8)==fee, "send address gas check")
API.cli().terminate()
#从mutiaddress向钱包5默认地址转5Neo,获取第一次生成的交易json
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.mutiname, test_config.wallet_pwd)
API.cli().show_state(times=30)
(result, stepname, msg) = API.cli().exec(False)
logger.print(msg)
result = API.rpc().sendfrom(test_config.asset_id_right,
test_config.mutiaddress,
WalletManager().wallet(0).account().address(), value=5,fee=0,change_address=test_config.mutiaddress)
self.ASSERT(result!=None, "sendfrom failed")
json1=str(result)
print("++++++++++++++:"+json1)
time.sleep(20)
API.cli().terminate()
#确认存在后使用relay方法广播jsonObject(cli,需要检查结果,应该广播不出去)
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().relay(jsonobj=json1)
(result, stepname, msg) = API.cli().exec(False)
API.cli().terminate()
logger.print(msg)
flag1=False
if msg.find("The signature is incomplete.")>=0:
flag1=True
self.ASSERT(flag1, "relay1 failed")
# #先sign交易json,获取输出的json,需要检查,如果没有输出json则报错
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().list_asset()
API.cli().sign(jsonobj=json1)
(result, stepname, msg) = API.cli().exec(False)
logger.print(msg)
self.ASSERT(str(msg).find("Signed Output")>=0, "failed to sign")
#在relay前确认钱包5默认地址余额和mutiaddress内余额
res1=API.rpc().getaccountstate(WalletManager().wallet(0).account().address());
res2=API.rpc().getaccountstate(test_config.mutiaddress);
self.ASSERT(res1!=None, "get getaccountstate error1!")
self.ASSERT(res2!=None, "get getaccountstate error1!")
w5neo1=self.return_neo_gas(res1,True)
muneo1=self.return_neo_gas(res2,True)
API.cli().terminate()
try:
json2=msg.split("Signed Output:\n\n")[1].split("\n")[0]
except:
self.ASSERT(False,"error:unable to get json2")
# #relay输出的交易json,需要检查结果,应该广播成功
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.mutiname, test_config.wallet_pwd)
API.cli().relay(jsonobj=json2)
(result, stepname, msg) = API.cli().exec(False)
logger.print(msg)
flag2=False
if msg.find("success")>=0:
flag2=True
self.ASSERT(flag2, "relay2 failed")
# #等待一个block
API.node().wait_gen_block()
API.cli().terminate()
# #检查钱包5内默认地址的余额是否增加5neo(RPC),mutiaddress内是否减少5neo
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().list_asset()
(result, stepname, msg) = API.cli().exec(False)
logger.print(msg)
API.node().wait_gen_block()
res1=API.rpc().getaccountstate(WalletManager().wallet(0).account().address());
res2=API.rpc().getaccountstate(test_config.mutiaddress);
self.ASSERT(res1!=None, "get getaccountstate error1!")
self.ASSERT(res2!=None, "get getaccountstate error1!")
w5neo2=self.return_neo_gas(res1,True)
muneo2=self.return_neo_gas(res2,True)
plus1=float(w5neo2)-float(w5neo1)
plus2=float(muneo1)-float(muneo2)
print(str(w5neo1)+" "+str(w5neo2)+" "+str(muneo1)+" "+str(muneo2))
self.ASSERT(int(plus1)==5, "sign failed")
self.ASSERT(int(plus2)==5, "sign failed")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
#jsonObjectToSign不填
def test_125_jsonObjectToSign(self):
try:
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().list_asset()
API.cli().sign(jsonobj=None)
(result, stepname, msg) = API.cli().exec(False)
logger.print(msg)
self.ASSERT(str(msg).find("You must input JSON object pending signature data.")>=0, "assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
#重复签名
def test_126_jsonObjectToSign(self):
try:
# # #从钱包5内默认地址向钱包5内multi地址转10neo(RPC)
# #API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, "11111111")
API.cli().list_address(lambda msg: msg.find(WalletManager().wallet(0).account().address()) >= 0)
API.cli().show_state(30)
(status, info, climsg) = API.cli().exec(False)
logger.print(climsg)
self.ASSERT(status, info)
##事前获取
res1=API.rpc().getaccountstate(WalletManager().wallet(0).account().address());
res2=API.rpc().getaccountstate(test_config.mutiaddress);
self.ASSERT(res1!=None, "get getaccountstate error1!")
addr1Neo=self.return_neo_gas(res1,True)
addr1Gas=self.return_neo_gas(res1,False)
addr2Neo=0
addr2Gas=0
if res2!=None:
addr2Neo=self.return_neo_gas(res2,True)
addr2Gas=self.return_neo_gas(res2,False)
result = API.rpc().sendfrom(test_config.asset_id_right,
WalletManager().wallet(0).account().address(),
test_config.mutiaddress, value=10,fee=0,change_address="empty")
self.ASSERT(result!=None, "sendfrom failed")
self.ASSERT(result["net_fee"]=="0", "")
API.node().wait_gen_block()
##事后获取
res1=API.rpc().getaccountstate(WalletManager().wallet(0).account().address());
res2=API.rpc().getaccountstate("Ae5FRbhndo2XKRFqEQ9Mn99bRbeKqHLxWV");
self.ASSERT(res1!=None, "get getaccountstate error2!")
self.ASSERT(res2!=None, "get getaccountstate error2!")
addr1Neo2=self.return_neo_gas(res1,True)
addr1Gas2=self.return_neo_gas(res1,False)
addr2Neo2=self.return_neo_gas(res2,True)
addr2Gas2=self.return_neo_gas(res2,False)
##计算结果
value=10
fee=0
self.ASSERT((float(addr2Neo2)-float(addr2Neo))==value, "arrive address neo check")
self.ASSERT((float(addr1Neo)-float(addr1Neo2))==value, "send address neo check")
self.ASSERT(round(float(addr1Gas)-float(addr1Gas2),8)==fee, "send address gas check")
API.cli().terminate()
#从mutiaddress向钱包5默认地址转5Neo,获取第一次生成的交易json
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.mutiname, test_config.wallet_pwd)
API.cli().show_state(times=30)
(result, stepname, msg) = API.cli().exec(False)
logger.print(msg)
result = API.rpc().sendfrom(test_config.asset_id_right,
test_config.mutiaddress,
WalletManager().wallet(0).account().address(), value=5,fee=0,change_address=test_config.mutiaddress)
self.ASSERT(result!=None, "sendfrom failed")
json1=str(result)
print("++++++++++++++:"+json1)
time.sleep(20)
API.cli().terminate()
# #先sign交易json,获取输出的json,需要检查,如果没有输出json则报错
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().list_asset()
API.cli().sign(jsonobj=json1)
(result, stepname, msg) = API.cli().exec(False)
API.cli().terminate()
logger.print(msg)
self.ASSERT(str(msg).find("Signed Output")>=0, "failed to sign")
try:
json2=msg.split("Signed Output:\n\n")[1].split("\n")[0]
except:
self.ASSERT(False, "first sign failed")
##重复sign交易json
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().list_asset()
API.cli().sign(jsonobj=json1)
(result, stepname, msg) = API.cli().exec(False)
API.cli().terminate()
logger.print(msg)
self.ASSERT(str(msg).find("Signed Output")>=0, "failed to sign")
try:
json3=msg.split("Signed Output:\n\n")[1].split("\n")[0]
except:
self.ASSERT(False, "second sign failed")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
#jsonObjectToSign格式错误
def test_127_jsonObjectToSign(self):
try:
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().list_asset()
API.cli().sign(jsonobj="abc")
(result, stepname, msg) = API.cli().exec(False)
logger.print(msg)
self.ASSERT(str(msg).find("One of the identified items was in an invalid format.")>=0, "assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
#未打开钱包
def test_128_jsonObjectToSign(self):
try:
# # #从钱包5内默认地址向钱包5内multi地址转10neo(RPC)
# #API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, "11111111")
API.cli().list_address(lambda msg: msg.find(WalletManager().wallet(0).account().address()) >= 0)
API.cli().show_state(30)
(status, info, climsg) = API.cli().exec(False)
logger.print(climsg)
self.ASSERT(status, info)
##事前获取
res1=API.rpc().getaccountstate(WalletManager().wallet(0).account().address());
res2=API.rpc().getaccountstate(test_config.mutiaddress);
self.ASSERT(res1!=None, "get getaccountstate error1!")
addr1Neo=self.return_neo_gas(res1,True)
addr1Gas=self.return_neo_gas(res1,False)
addr2Neo=0
addr2Gas=0
if res2!=None:
addr2Neo=self.return_neo_gas(res2,True)
addr2Gas=self.return_neo_gas(res2,False)
result = API.rpc().sendfrom(test_config.asset_id_right,
WalletManager().wallet(0).account().address(),
test_config.mutiaddress, value=10,fee=0,change_address="empty")
self.ASSERT(result!=None, "sendfrom failed")
self.ASSERT(result["net_fee"]=="0", "")
API.node().wait_gen_block()
##事后获取
res1=API.rpc().getaccountstate(WalletManager().wallet(0).account().address());
res2=API.rpc().getaccountstate("Ae5FRbhndo2XKRFqEQ9Mn99bRbeKqHLxWV");
self.ASSERT(res1!=None, "get getaccountstate error2!")
self.ASSERT(res2!=None, "get getaccountstate error2!")
addr1Neo2=self.return_neo_gas(res1,True)
addr1Gas2=self.return_neo_gas(res1,False)
addr2Neo2=self.return_neo_gas(res2,True)
addr2Gas2=self.return_neo_gas(res2,False)
##计算结果
value=10
fee=0
self.ASSERT((float(addr2Neo2)-float(addr2Neo))==value, "arrive address neo check")
self.ASSERT((float(addr1Neo)-float(addr1Neo2))==value, "send address neo check")
self.ASSERT(round(float(addr1Gas)-float(addr1Gas2),8)==fee, "send address gas check")
API.cli().terminate()
#从mutiaddress向钱包5默认地址转5Neo,获取第一次生成的交易json
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.mutiname, test_config.wallet_pwd)
API.cli().show_state(times=30)
(result, stepname, msg) = API.cli().exec(False)
logger.print(msg)
result = API.rpc().sendfrom(test_config.asset_id_right,
test_config.mutiaddress,
WalletManager().wallet(0).account().address(), value=5,fee=0,change_address=test_config.mutiaddress)
self.ASSERT(result!=None, "sendfrom failed")
json1=str(result)
print("++++++++++++++:"+json1)
time.sleep(20)
API.cli().terminate()
# #未打开钱包的状态下sign交易json
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().list_asset()
API.cli().sign(jsonobj=json1)
(result, stepname, msg) = API.cli().exec(False)
API.cli().terminate()
logger.print(msg)
self.ASSERT(str(msg).find("You have to open the wallet first.")>=0, "assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_129_relay(self):
try:
# # #从钱包5内默认地址向钱包5内multi地址转10neo(RPC)
# #API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, "11111111")
API.cli().list_address(lambda msg: msg.find(WalletManager().wallet(0).account().address()) >= 0)
API.cli().show_state(30)
(status, info, climsg) = API.cli().exec(False)
logger.print(climsg)
self.ASSERT(status, info)
##事前获取
res1=API.rpc().getaccountstate(WalletManager().wallet(0).account().address());
res2=API.rpc().getaccountstate(test_config.mutiaddress);
self.ASSERT(res1!=None, "get getaccountstate error1!")
addr1Neo=self.return_neo_gas(res1,True)
addr1Gas=self.return_neo_gas(res1,False)
addr2Neo=0
addr2Gas=0
if res2!=None:
addr2Neo=self.return_neo_gas(res2,True)
addr2Gas=self.return_neo_gas(res2,False)
result = API.rpc().sendfrom(test_config.asset_id_right,
WalletManager().wallet(0).account().address(),
test_config.mutiaddress, value=10,fee=0,change_address="empty")
self.ASSERT(result!=None, "sendfrom failed")
self.ASSERT(result["net_fee"]=="0", "net_fee false")
API.node().wait_gen_block()
##事后获取
res1=API.rpc().getaccountstate(WalletManager().wallet(0).account().address());
res2=API.rpc().getaccountstate("Ae5FRbhndo2XKRFqEQ9Mn99bRbeKqHLxWV");
self.ASSERT(res1!=None, "get getaccountstate error2!")
self.ASSERT(res2!=None, "get getaccountstate error2!")
addr1Neo2=self.return_neo_gas(res1,True)
addr1Gas2=self.return_neo_gas(res1,False)
addr2Neo2=self.return_neo_gas(res2,True)
addr2Gas2=self.return_neo_gas(res2,False)
##计算结果
value=10
fee=0
self.ASSERT((float(addr2Neo2)-float(addr2Neo))==value, "arrive address neo check")
self.ASSERT((float(addr1Neo)-float(addr1Neo2))==value, "send address neo check")
self.ASSERT(round(float(addr1Gas)-float(addr1Gas2),8)==fee, "send address gas check")
API.cli().terminate()
#从mutiaddress向钱包5默认地址转5Neo,获取第一次生成的交易json
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.mutiname, test_config.wallet_pwd)
API.cli().show_state(times=30)
(result, stepname, msg) = API.cli().exec(False)
logger.print(msg)
result = API.rpc().sendfrom(test_config.asset_id_right,
test_config.mutiaddress,
WalletManager().wallet(0).account().address(), value=5,fee=0,change_address=test_config.mutiaddress)
self.ASSERT(result!=None, "sendfrom failed")
json1=str(result)
print("++++++++++++++:"+json1)
time.sleep(20)
API.cli().terminate()
#确认存在后使用relay方法广播jsonObject(cli,需要检查结果,应该广播不出去)
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().relay(jsonobj=json1)
(result, stepname, msg) = API.cli().exec(False)
API.cli().terminate()
logger.print(msg)
flag1=False
if msg.find("The signature is incomplete.")>=0:
flag1=True
self.ASSERT(flag1, "relay1 failed")
# #先sign交易json,获取输出的json,需要检查,如果没有输出json则报错
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().list_asset()
API.cli().sign(jsonobj=json1)
(result, stepname, msg) = API.cli().exec(False)
logger.print(msg)
self.ASSERT(str(msg).find("Signed Output")>=0, "failed to sign")
#在relay前确认钱包5默认地址余额和mutiaddress内余额
res1=API.rpc().getaccountstate(WalletManager().wallet(0).account().address());
res2=API.rpc().getaccountstate(test_config.mutiaddress);
self.ASSERT(res1!=None, "get getaccountstate error1!")
self.ASSERT(res2!=None, "get getaccountstate error1!")
w5neo1=self.return_neo_gas(res1,True)
muneo1=self.return_neo_gas(res2,True)
API.cli().terminate()
try:
json2=msg.split("Signed Output:\n\n")[1].split("\n")[0]
except:
self.ASSERT(False,"error:unable to get json2")
# #relay输出的交易json,需要检查结果,应该广播成功
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.mutiname, test_config.wallet_pwd)
API.cli().relay(jsonobj=json2)
(result, stepname, msg) = API.cli().exec(False)
logger.print(msg)
flag2=False
if msg.find("success")>=0:
flag2=True
self.ASSERT(flag2, "relay2 failed")
# #等待一个block
API.node().wait_gen_block()
API.cli().terminate()
# #检查钱包5内默认地址的余额是否增加5neo(RPC),mutiaddress内是否减少5neo
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().list_asset()
(result, stepname, msg) = API.cli().exec(False)
logger.print(msg)
API.node().wait_gen_block()
res1=API.rpc().getaccountstate(WalletManager().wallet(0).account().address());
res2=API.rpc().getaccountstate(test_config.mutiaddress);
self.ASSERT(res1!=None, "get getaccountstate error1!")
self.ASSERT(res2!=None, "get getaccountstate error1!")
w5neo2=self.return_neo_gas(res1,True)
muneo2=self.return_neo_gas(res2,True)
plus1=float(w5neo2)-float(w5neo1)
plus2=float(muneo1)-float(muneo2)
print(str(w5neo1)+" "+str(w5neo2)+" "+str(muneo1)+" "+str(muneo2))
self.ASSERT(int(plus1)==5, "sign failed")
self.ASSERT(int(plus2)==5, "sign failed")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
#jsonObjectToSign不填
def test_130_relay(self):
try:
API.cli().open_wallet(test_config.mutiname, test_config.wallet_pwd)
API.cli().relay(jsonobj=None)
(result, stepname, msg) = API.cli().exec(False)
logger.print(msg)
self.ASSERT(msg.find("You must input JSON object to relay")>=0, "assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
#jsonObjectToSign不完整
def test_131_relay(self):
try:
# # #从钱包5内默认地址向钱包5内multi地址转10neo(RPC)
API.cli().open_wallet(test_config.wallet_default, "11111111")
API.cli().list_address(lambda msg: msg.find(WalletManager().wallet(0).account().address()) >= 0)
API.cli().show_state(30)
(status, info, climsg) = API.cli().exec(False)
logger.print(climsg)
self.ASSERT(status, info)
##事前获取
res1=API.rpc().getaccountstate(WalletManager().wallet(0).account().address());
res2=API.rpc().getaccountstate(test_config.mutiaddress);
self.ASSERT(res1!=None, "get getaccountstate error1!")
addr1Neo=self.return_neo_gas(res1,True)
addr1Gas=self.return_neo_gas(res1,False)
addr2Neo=0
addr2Gas=0
if res2!=None:
addr2Neo=self.return_neo_gas(res2,True)
addr2Gas=self.return_neo_gas(res2,False)
result = API.rpc().sendfrom(test_config.asset_id_right,
WalletManager().wallet(0).account().address(),
test_config.mutiaddress, value=10,fee=0,change_address="empty")
self.ASSERT(result!=None, "sendfrom failed")
self.ASSERT(result["net_fee"]=="0", "net_fee false")
API.node().wait_gen_block()
##事后获取
res1=API.rpc().getaccountstate(WalletManager().wallet(0).account().address());
res2=API.rpc().getaccountstate("Ae5FRbhndo2XKRFqEQ9Mn99bRbeKqHLxWV");
self.ASSERT(res1!=None, "get getaccountstate error2!")
self.ASSERT(res2!=None, "get getaccountstate error2!")
addr1Neo2=self.return_neo_gas(res1,True)
addr1Gas2=self.return_neo_gas(res1,False)
addr2Neo2=self.return_neo_gas(res2,True)
addr2Gas2=self.return_neo_gas(res2,False)
##计算结果
value=10
fee=0
self.ASSERT((float(addr2Neo2)-float(addr2Neo))==value, "arrive address neo check")
self.ASSERT((float(addr1Neo)-float(addr1Neo2))==value, "send address neo check")
self.ASSERT(round(float(addr1Gas)-float(addr1Gas2),8)==fee, "send address gas check")
API.cli().terminate()
#从mutiaddress向钱包5默认地址转5Neo,获取第一次生成的交易json
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.mutiname, test_config.wallet_pwd)
API.cli().show_state(times=30)
(result, stepname, msg) = API.cli().exec(False)
logger.print(msg)
result = API.rpc().sendfrom(test_config.asset_id_right,
test_config.mutiaddress,
WalletManager().wallet(0).account().address(), value=5,fee=0,change_address=test_config.mutiaddress)
self.ASSERT(result!=None, "sendfrom failed")
json1=str(result)
print("++++++++++++++:"+json1)
time.sleep(20)
API.cli().terminate()
#确认存在后使用relay方法广播jsonObject(cli,需要检查结果,应该广播不出去)
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().relay(jsonobj=json1)
(result, stepname, msg) = API.cli().exec(False)
API.cli().terminate()
logger.print(msg)
flag1=False
if msg.find("The signature is incomplete.")>=0:
flag1=True
self.ASSERT(flag1, "assert error")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
#jsonObjectToSign="abc"
def test_132_relay(self):
try:
API.cli().open_wallet(test_config.mutiname, test_config.wallet_pwd)
API.cli().relay(jsonobj=test_config.wrong_str)
(result, stepname, msg) = API.cli().exec(False)
logger.print(msg)
self.ASSERT(msg.find("One of the identified items was in an invalid format.")>=0, "assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
#未打开钱包进行relay
def test_133_relay(self):
try:
# # #从钱包5内默认地址向钱包5内multi地址转10neo(RPC)
# #API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, "11111111")
API.cli().list_address(lambda msg: msg.find(WalletManager().wallet(0).account().address()) >= 0)
API.cli().show_state(30)
(status, info, climsg) = API.cli().exec(False)
logger.print(climsg)
self.ASSERT(status, info)
##事前获取
res1=API.rpc().getaccountstate(WalletManager().wallet(0).account().address());
res2=API.rpc().getaccountstate(test_config.mutiaddress);
self.ASSERT(res1!=None, "get getaccountstate error1!")
addr1Neo=self.return_neo_gas(res1,True)
addr1Gas=self.return_neo_gas(res1,False)
addr2Neo=0
addr2Gas=0
if res2!=None:
addr2Neo=self.return_neo_gas(res2,True)
addr2Gas=self.return_neo_gas(res2,False)
result = API.rpc().sendfrom(test_config.asset_id_right,
WalletManager().wallet(0).account().address(),
test_config.mutiaddress, value=10,fee=0,change_address="empty")
self.ASSERT(result!=None, "sendfrom failed")
self.ASSERT(result["net_fee"]=="0", "")
API.node().wait_gen_block()
##事后获取
res1=API.rpc().getaccountstate(WalletManager().wallet(0).account().address());
res2=API.rpc().getaccountstate("Ae5FRbhndo2XKRFqEQ9Mn99bRbeKqHLxWV");
self.ASSERT(res1!=None, "get getaccountstate error2!")
self.ASSERT(res2!=None, "get getaccountstate error2!")
addr1Neo2=self.return_neo_gas(res1,True)
addr1Gas2=self.return_neo_gas(res1,False)
addr2Neo2=self.return_neo_gas(res2,True)
addr2Gas2=self.return_neo_gas(res2,False)
##计算结果
value=10
fee=0
self.ASSERT((float(addr2Neo2)-float(addr2Neo))==value, "arrive address neo check")
self.ASSERT((float(addr1Neo)-float(addr1Neo2))==value, "send address neo check")
self.ASSERT(round(float(addr1Gas)-float(addr1Gas2),8)==fee, "send address gas check")
API.cli().terminate()
#从mutiaddress向钱包5默认地址转5Neo,获取第一次生成的交易json
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.mutiname, test_config.wallet_pwd)
API.cli().show_state(times=30)
(result, stepname, msg) = API.cli().exec(False)
logger.print(msg)
result = API.rpc().sendfrom(test_config.asset_id_right,
test_config.mutiaddress,
WalletManager().wallet(0).account().address(), value=5,fee=0,change_address=test_config.mutiaddress)
self.ASSERT(result!=None, "sendfrom failed")
json1=str(result)
print("++++++++++++++:"+json1)
time.sleep(20)
API.cli().terminate()
#确认存在后使用relay方法广播jsonObject(cli,需要检查结果,应该广播不出去)
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().relay(jsonobj=json1)
(result, stepname, msg) = API.cli().exec(False)
API.cli().terminate()
logger.print(msg)
flag1=False
if msg.find("The signature is incomplete.")>=0:
flag1=True
self.ASSERT(flag1, "relay1 failed")
# #先sign交易json,获取输出的json,需要检查,如果没有输出json则报错
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().list_asset()
API.cli().sign(jsonobj=json1)
(result, stepname, msg) = API.cli().exec(False)
logger.print(msg)
self.ASSERT(str(msg).find("Signed Output")>=0, "failed to sign")
#在relay前确认钱包5默认地址余额和mutiaddress内余额
res1=API.rpc().getaccountstate(WalletManager().wallet(0).account().address());
res2=API.rpc().getaccountstate(test_config.mutiaddress);
self.ASSERT(res1!=None, "get getaccountstate error1!")
self.ASSERT(res2!=None, "get getaccountstate error1!")
w5neo1=self.return_neo_gas(res1,True)
muneo1=self.return_neo_gas(res2,True)
API.cli().terminate()
try:
json2=msg.split("Signed Output:\n\n")[1].split("\n")[0]
except:
self.ASSERT(False,"error:unable to get json2")
# #不打开前钱包,relay输出的交易json,需要检查结果,应该广播成功
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().relay(jsonobj=json2)
(result, stepname, msg) = API.cli().exec(False)
logger.print(msg)
self.ASSERT(msg.find("success")>=0, "wallet not open")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_134_showstate(self):
try:
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().show_state(2)
(result, stepname, msg) = API.cli().exec(False)
logger.print(msg)
#加一句waitsync,会return true/false,直接作为结果即可
result=API.cli().waitsync()
self.ASSERT(result,"assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_135_shownode(self):
try:
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().show_node()
(result, stepname, msg) = API.cli().exec()
logger.print(msg)
#检查log,有error直接报错
flag=True
if msg.find("error")>=0:
flag=False
self.ASSERT(flag,"assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_136_showpool(self):
try:
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().list_address()
API.cli().show_state(times=30)
API.cli().send(password=test_config.wallet_pwd, id_alias="NEO",address=test_config.address_right, value=10)
API.cli().waitnext(timeout=1, times=1)
API.cli().show_pool()
(result, stepname, msg) = API.cli().exec()
logger.print(msg)
#发完send交易后立即发showpool,total的值应该为1
self.ASSERT(result,"assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_138_export_all_blocks(self):
try:
fp = open(os.getcwd().split("test/test_cli")[0]+"config.json", 'r', encoding='utf-8')
str=fp.read()
fp.close()
fpath = str.split("\"path\" : \"")[1].split("neo-cli.dll")[0]
path=Config.NODES[0]["walletname"]
#删除所有.acc的文件
os.system("rm -rf "+fpath+"*.acc")
print ("Delete ALL ACC FILE")
#导出0to30的区块
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().export_blocks(start="0",count="30",timeout=35)
(result, stepname, msg) = API.cli().exec()
API.cli().terminate()
shutil.copyfile(fpath+"chain.0.acc", test_config.copypath+"0to30.acc")
print ("export 0to30.acc success")
if os.path.exists(fpath+"chain.0.acc"):
os.remove(fpath+"chain.0.acc")
#导入0to30区块
#把protocol.json文件替换为SeedList被删除的文件
shutil.copyfile(test_config.copypath+"protocol_deleted.json", fpath+"protocol.json")
#删除Chain和Index文件夹
for root , dirs, files in os.walk(fpath):
for name in dirs:
if 'Chain_' in name or 'Index_' in name:
print ("delete file:"+name)
filename=fpath+name+"/"
shutil.rmtree(filename)
#复制0to30.acc到当前运行节点文件夹
shutil.copyfile(test_config.copypath+"0to30.acc", fpath+"chain.0.acc")
print ("copy file 0to30.acc success")
#启动节点
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
(result, stepname, msg) = API.cli().exec(False)
result = API.rpc().getblockcount()
API.cli().terminate()
#导出所有区块(0to30)
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().export_all_blocks(path="chainAll.acc",timeout=35)
(result, stepname, msg) = API.cli().exec()
API.cli().terminate()
shutil.copyfile(fpath+"chainAll.acc", test_config.copypath+"chainAll.acc")
print ("export chainAll.acc success")
if os.path.exists(fpath+"chainAll.acc"):
os.remove(fpath+"chainAll.acc")
#复制chainAll.acc到当前运行节点文件夹
shutil.copyfile(test_config.copypath+"chainAll.acc", fpath+"chainAll.acc")
print ("copy file chainAll.acc success")
#删除Chain和Index文件夹
for root , dirs, files in os.walk(fpath):
for name in dirs:
if 'Chain_' in name or 'Index_' in name:
print ("delete file:"+name)
filename=fpath+name+"/"
shutil.rmtree(filename)
#启动节点,判断区块数是否是30
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
(result, stepname, msg) = API.cli().exec(False)
result = API.rpc().getblockcount()
API.cli().terminate()
flag=False
if result==30:
flag=True
#最后还原之前的区块
#删除Chain和Index文件夹
for root , dirs, files in os.walk(fpath):
for name in dirs:
if 'Chain_' in name or 'Index_' in name:
print ("delete file:"+name)
filename=fpath+name+"/"
shutil.rmtree(filename)
#删除所有.acc的文件
os.system("rm -rf "+fpath+"*.acc")
print ("Delete ALL ACC FILE")
#复制chain.acc到当前运行节点文件夹
shutil.copyfile(test_config.copypath+"chain.acc", fpath+"chain.acc")
print ("copy file chain.acc success")
#把protocol.json文件替换为SeedList未被删除的文件
shutil.copyfile(test_config.copypath+"protocol_notdeleted.json", fpath+"protocol.json")
#启动节点
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().list_address()
(result, stepname, msg) = API.cli().exec(False)
logger.print(msg)
result = API.rpc().getblockcount()
self.ASSERT(flag,"export blocks failed")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_139_export_all_blocks(self):
try:
fp = open(os.getcwd().split("test/test_cli")[0]+"config.json", 'r', encoding='utf-8')
str=fp.read()
fp.close()
fpath = str.split("\"path\" : \"")[1].split("neo-cli.dll")[0]
path=Config.NODES[0]["walletname"]
#删除所有.acc的文件
os.system("rm -rf "+fpath+"*.acc")
print ("Delete ALL ACC FILE")
#导出0to30的区块
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().export_blocks(start="0",count="30",timeout=35)
(result, stepname, msg) = API.cli().exec()
API.cli().terminate()
shutil.copyfile(fpath+"chain.0.acc", test_config.copypath+"0to30.acc")
print ("export 0to30.acc success")
if os.path.exists(fpath+"chain.0.acc"):
os.remove(fpath+"chain.0.acc")
#导入0to30区块
#把protocol.json文件替换为SeedList被删除的文件
shutil.copyfile(test_config.copypath+"protocol_deleted.json", fpath+"protocol.json")
#删除Chain和Index文件夹
for root , dirs, files in os.walk(fpath):
for name in dirs:
if 'Chain_' in name or 'Index_' in name:
print ("delete file:"+name)
filename=fpath+name+"/"
shutil.rmtree(filename)
#复制0to30.acc到当前运行节点文件夹
shutil.copyfile(test_config.copypath+"0to30.acc", fpath+"chain.0.acc")
print ("copy file 0to30.acc success")
#启动节点
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
(result, stepname, msg) = API.cli().exec(False)
result = API.rpc().getblockcount()
API.cli().terminate()
#导出所有区块(0to30)
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().export_all_blocks(path="chainAll.acc",timeout=35)
(result, stepname, msg) = API.cli().exec()
API.cli().terminate()
shutil.copyfile(fpath+"chainAll.acc", test_config.copypath+"chainAll.acc")
print ("export chainAll.acc success")
if os.path.exists(fpath+"chainAll.acc"):
os.remove(fpath+"chainAll.acc")
#复制chainAll.acc到当前运行节点文件夹
shutil.copyfile(test_config.copypath+"chainAll.acc", fpath+"chainAll.acc")
print ("copy file chainAll.acc success")
#删除Chain和Index文件夹
for root , dirs, files in os.walk(fpath):
for name in dirs:
if 'Chain_' in name or 'Index_' in name:
print ("delete file:"+name)
filename=fpath+name+"/"
shutil.rmtree(filename)
#启动节点,判断区块数是否是30
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
(result, stepname, msg) = API.cli().exec(False)
result = API.rpc().getblockcount()
API.cli().terminate()
flag=False
if result==30:
flag=True
#最后还原之前的区块
#删除Chain和Index文件夹
for root , dirs, files in os.walk(fpath):
for name in dirs:
if 'Chain_' in name or 'Index_' in name:
print ("delete file:"+name)
filename=fpath+name+"/"
shutil.rmtree(filename)
#删除所有.acc的文件
os.system("rm -rf "+fpath+"*.acc")
print ("Delete ALL ACC FILE")
#复制chain.acc到当前运行节点文件夹
shutil.copyfile(test_config.copypath+"chain.acc", fpath+"chain.acc")
print ("copy file chain.acc success")
#把protocol.json文件替换为SeedList未被删除的文件
shutil.copyfile(test_config.copypath+"protocol_notdeleted.json", fpath+"protocol.json")
#启动节点
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().list_address()
(result, stepname, msg) = API.cli().exec(False)
logger.print(msg)
result = API.rpc().getblockcount()
self.ASSERT(flag,"export blocks failed")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_140_export_all_blocks(self):
try:
fp = open(os.getcwd().split("test/test_cli")[0]+"config.json", 'r', encoding='utf-8')
str=fp.read()
fp.close()
fpath = str.split("\"path\" : \"")[1].split("neo-cli.dll")[0]
path=Config.NODES[0]["walletname"]
#删除所有.acc的文件
os.system("rm -rf "+fpath+"*.acc")
print ("Delete ALL ACC FILE")
#导出0to30的区块
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().export_blocks(start="0",count="30",timeout=35)
(result, stepname, msg) = API.cli().exec()
API.cli().terminate()
shutil.copyfile(fpath+"chain.0.acc", test_config.copypath+"0to30.acc")
print ("export 0to30.acc success")
if os.path.exists(fpath+"chain.0.acc"):
os.remove(fpath+"chain.0.acc")
#导入0to30区块
#把protocol.json文件替换为SeedList被删除的文件
shutil.copyfile(test_config.copypath+"protocol_deleted.json", fpath+"protocol.json")
#删除Chain和Index文件夹
for root , dirs, files in os.walk(fpath):
for name in dirs:
if 'Chain_' in name or 'Index_' in name:
print ("delete file:"+name)
filename=fpath+name+"/"
shutil.rmtree(filename)
#复制0to30.acc到当前运行节点文件夹
shutil.copyfile(test_config.copypath+"0to30.acc", fpath+"chain.0.acc")
print ("copy file 0to30.acc success")
#启动节点
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
(result, stepname, msg) = API.cli().exec(False)
result = API.rpc().getblockcount()
API.cli().terminate()
#删除所有.acc的文件
os.system("rm -rf "+fpath+"*.acc")
print ("Delete ALL ACC FILE")
#导出所有区块(0to30)
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().export_all_blocks(timeout=35)
(result, stepname, msg) = API.cli().exec()
API.cli().terminate()
shutil.copyfile(fpath+"chain.acc", test_config.copypath+"chainAll.acc")
print ("export chainAll.acc success")
if os.path.exists(fpath+"chain.acc"):
os.remove(fpath+"chain.acc")
#复制chainAll.acc到当前运行节点文件夹
shutil.copyfile(test_config.copypath+"chainAll.acc", fpath+"chain.acc")
print ("copy file chainAll.acc success")
#删除Chain和Index文件夹
for root , dirs, files in os.walk(fpath):
for name in dirs:
if 'Chain_' in name or 'Index_' in name:
print ("delete file:"+name)
filename=fpath+name+"/"
shutil.rmtree(filename)
#启动节点,判断区块数是否是30
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
(result, stepname, msg) = API.cli().exec(False)
result = API.rpc().getblockcount()
API.cli().terminate()
flag=False
if result==30:
flag=True
#最后还原之前的区块
#删除Chain和Index文件夹
for root , dirs, files in os.walk(fpath):
for name in dirs:
if 'Chain_' in name or 'Index_' in name:
print ("delete file:"+name)
filename=fpath+name+"/"
shutil.rmtree(filename)
#删除所有.acc的文件
os.system("rm -rf "+fpath+"*.acc")
print ("Delete ALL ACC FILE")
#复制chain.acc到当前运行节点文件夹
shutil.copyfile(test_config.copypath+"chain.acc", fpath+"chain.acc")
print ("copy file chain.acc success")
#把protocol.json文件替换为SeedList未被删除的文件
shutil.copyfile(test_config.copypath+"protocol_notdeleted.json", fpath+"protocol.json")
#启动节点
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().list_address()
(result, stepname, msg) = API.cli().exec(False)
logger.print(msg)
result = API.rpc().getblockcount()
self.ASSERT(flag,"export blocks failed")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_141_export_all_blocks(self):
try:
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().export_all_blocks("wrongpath/chain.acc",exceptfunc=lambda msg: msg.find("error") >= 0)
(result, stepname, msg) = API.cli().exec()
logger.print(msg)
self.ASSERT(result,"assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_142_export_all_blocks(self):
try:
fp = open(os.getcwd().split("test/test_cli")[0]+"config.json", 'r', encoding='utf-8')
str=fp.read()
fp.close()
fpath = str.split("\"path\" : \"")[1].split("neo-cli.dll")[0]
if os.path.exists(fpath+"chain.abc"):
os.remove(fpath+"chain.abc")
print ("file deleted")
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
filename=test_config.filename2
API.cli().export_all_blocks(fpath+"chain.abc")
(result, stepname, msg) = API.cli().exec()
#删除所有.acc的文件
os.system("rm -rf "+fpath+"*.acc")
print ("Delete ALL ACC FILE")
logger.print(msg)
flag=os.path.exists(fpath+"chain.abc")
self.ASSERT(flag,"export blocks failed")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
#ok
def test_144_export_blocks(self):
try:
fp = open(os.getcwd().split("test/test_cli")[0]+"config.json", 'r', encoding='utf-8')
str=fp.read()
fp.close()
fpath = str.split("\"path\" : \"")[1].split("neo-cli.dll")[0]
path=Config.NODES[0]["walletname"]
#删除所有.acc的文件
os.system("rm -rf "+fpath+"*.acc")
print ("Delete ALL ACC FILE")
#导出0to29的区块
API.cli().export_blocks(start="0",count="29",timeout=35)
(result, stepname, msg) = API.cli().exec()
API.cli().terminate()
##copy 时候的路径需要获取了进行split再拼接
##SAMPLE:testpath=NODES["path"].split("/")xxxxxxx
shutil.copyfile(fpath+"chain.0.acc", test_config.copypath+"0to29.acc")
print ("export 0to29.acc success")
if os.path.exists(fpath+"chain.0.acc"):
os.remove(fpath+"chain.0.acc")
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
#导出0to30的区块
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().export_blocks(start="0",count="30",timeout=35)
(result, stepname, msg) = API.cli().exec()
API.cli().terminate()
shutil.copyfile(fpath+"chain.0.acc", test_config.copypath+"0to30.acc")
print ("export 0to30.acc success")
if os.path.exists(fpath+"chain.0.acc"):
os.remove(fpath+"chain.0.acc")
#导出30to50的区块
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().export_blocks(start="30",count="20",timeout=30)
(result, stepname, msg) = API.cli().exec()
API.cli().terminate()
shutil.copyfile(fpath+"chain.30.acc", test_config.copypath+"30to50.acc")
print ("export 30to50.acc success")
if os.path.exists(fpath+"chain.30.acc"):
os.remove(fpath+"chain.30.acc")
#把protocol.json文件替换为SeedList被删除的文件
shutil.copyfile(test_config.copypath+"protocol_deleted.json", fpath+"protocol.json")
print ("change protocol.json success")
#删除Chain和Index文件夹
for root , dirs, files in os.walk(fpath):
for name in dirs:
if 'Chain_' in name or 'Index_' in name:
print ("delete file:"+name)
filename=fpath+name+"/"
shutil.rmtree(filename)
#复制0to29.acc到当前运行节点文件夹
shutil.copyfile(test_config.copypath+"0to29.acc", fpath+"chain.0.acc")
print ("copy file 0to29.acc success")
#启动节点,判断区块数是否为29
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
(result, stepname, msg) = API.cli().exec(False)
logger.print(msg)
result = API.rpc().getblockcount()
API.cli().terminate()
a=0
if result==29:
print("blocks count:29")
a=1
#删除0to29.acc
if os.path.exists(fpath+"chain.0.acc"):
os.remove(fpath+"chain.0.acc")
print ("delete file:0to29.acc")
#复制30to50.acc到当前运行节点文件夹
shutil.copyfile(test_config.copypath+"30to50.acc", fpath+"chain.30.acc")
print ("copy file 30to50.acc success")
#启动节点,判断区块数是否还是29
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
(result, stepname, msg) = API.cli().exec(False)
result = API.rpc().getblockcount()
API.cli().terminate()
b=0
if result==29:
b=1
#删除Chain和Index文件夹
for root , dirs, files in os.walk(fpath):
for name in dirs:
if 'Chain_' in name or 'Index_' in name:
print ("delete file:"+name)
filename=fpath+name+"/"
shutil.rmtree(filename)
#复制0to30.acc到当前运行节点文件夹
shutil.copyfile(test_config.copypath+"0to30.acc", fpath+"chain.0.acc")
print ("copy file 0to30.acc success")
#启动节点,判断区块数是否是50
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
(result, stepname, msg) = API.cli().exec(False)
result = API.rpc().getblockcount()
API.cli().terminate()
c=0
if result==50:
c=1
#最后还原之前的区块
#删除Chain和Index文件夹
for root , dirs, files in os.walk(fpath):
for name in dirs:
if 'Chain_' in name or 'Index_' in name:
print ("delete file:"+name)
filename=fpath+name+"/"
shutil.rmtree(filename)
#删除所有.acc的文件
os.system("rm -rf "+fpath+"*.acc")
print ("Delete ALL ACC FILE")
#复制chain.acc到当前运行节点文件夹
shutil.copyfile(test_config.copypath+"chain.acc", fpath+"chain.acc")
print ("copy file chain.acc success")
#把protocol.json文件替换为SeedList未被删除的文件
shutil.copyfile(test_config.copypath+"protocol_notdeleted.json", fpath+"protocol.json")
#启动节点
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().list_address()
(result, stepname, msg) = API.cli().exec(False)
logger.print(msg)
result = API.rpc().getblockcount()
sum=a+b+c
self.ASSERT(sum==3,"export blocks failed")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_146_export_blocks(self):
try:
fp = open(os.getcwd().split("test/test_cli")[0]+"config.json", 'r', encoding='utf-8')
str=fp.read()
fp.close()
fpath = str.split("\"path\" : \"")[1].split("neo-cli.dll")[0]
#API.cli().export_blocks(start="0",count="31",timeout=35)
API.cli().export_blocks(start="abc",count="10",timeout=5,exceptfunc=lambda msg: msg.find("error") >= 0)
(result, stepname, msg) = API.cli().exec()
logger.print(msg)
#删除所有.acc的文件
os.system("rm -rf "+fpath+"*.acc")
print ("Delete ALL ACC FILE")
self.ASSERT(result,"assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_147_export_blocks(self):
try:
fp = open(os.getcwd().split("test/test_cli")[0]+"config.json", 'r', encoding='utf-8')
str=fp.read()
fp.close()
fpath = str.split("\"path\" : \"")[1].split("neo-cli.dll")[0]
API.cli().export_blocks("100000000","10",exceptfunc=lambda msg: msg.find("error") >= 0)
(result, stepname, msg) = API.cli().exec()
logger.print(msg)
#删除所有.acc的文件
os.system("rm -rf "+fpath+"*.acc")
print ("Delete ALL ACC FILE")
self.ASSERT(result,"assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_148_export_blocks(self):
try:
fp = open(os.getcwd().split("test/test_cli")[0]+"config.json", 'r', encoding='utf-8')
str=fp.read()
fp.close()
fpath = str.split("\"path\" : \"")[1].split("neo-cli.dll")[0]
path=Config.NODES[0]["walletname"]
#删除所有.acc的文件
os.system("rm -rf "+fpath+"*.acc")
print ("Delete ALL ACC FILE")
#导出0to29的区块
API.cli().export_blocks(start="0",count="29",timeout=35)
(result, stepname, msg) = API.cli().exec()
API.cli().terminate()
##copy 时候的路径需要获取了进行split再拼接
##SAMPLE:testpath=NODES["path"].split("/")xxxxxxx
shutil.copyfile(fpath+"chain.0.acc", test_config.copypath+"0to29.acc")
print ("export 0to29.acc success")
if os.path.exists(fpath+"chain.0.acc"):
os.remove(fpath+"chain.0.acc")
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
#导出0to30的区块
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().export_blocks(start="0",count="30",timeout=35)
(result, stepname, msg) = API.cli().exec()
API.cli().terminate()
shutil.copyfile(fpath+"chain.0.acc", test_config.copypath+"0to30.acc")
print ("export 0to30.acc success")
if os.path.exists(fpath+"chain.0.acc"):
os.remove(fpath+"chain.0.acc")
#导出30to50的区块
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().export_blocks(start="30",count="20",timeout=30)
(result, stepname, msg) = API.cli().exec()
API.cli().terminate()
shutil.copyfile(fpath+"chain.30.acc", test_config.copypath+"30to50.acc")
print ("export 30to50.acc success")
if os.path.exists(fpath+"chain.30.acc"):
os.remove(fpath+"chain.30.acc")
#把protocol.json文件替换为SeedList被删除的文件
shutil.copyfile(test_config.copypath+"protocol_deleted.json", fpath+"protocol.json")
print ("change protocol.json success")
#删除Chain和Index文件夹
for root , dirs, files in os.walk(fpath):
for name in dirs:
if 'Chain_' in name or 'Index_' in name:
print ("delete file:"+name)
filename=fpath+name+"/"
shutil.rmtree(filename)
#复制0to29.acc到当前运行节点文件夹
shutil.copyfile(test_config.copypath+"0to29.acc", fpath+"chain.0.acc")
print ("copy file 0to29.acc success")
#启动节点,判断区块数是否为29
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
(result, stepname, msg) = API.cli().exec(False)
logger.print(msg)
result = API.rpc().getblockcount()
API.cli().terminate()
a=0
if result==29:
print("blocks count:29")
a=1
#删除0to29.acc
if os.path.exists(fpath+"chain.0.acc"):
os.remove(fpath+"chain.0.acc")
print ("delete file:0to29.acc")
#复制30to50.acc到当前运行节点文件夹
shutil.copyfile(test_config.copypath+"30to50.acc", fpath+"chain.30.acc")
print ("copy file 30to50.acc success")
#启动节点,判断区块数是否还是29
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
(result, stepname, msg) = API.cli().exec(False)
result = API.rpc().getblockcount()
API.cli().terminate()
b=0
if result==29:
b=1
#删除Chain和Index文件夹
for root , dirs, files in os.walk(fpath):
for name in dirs:
if 'Chain_' in name or 'Index_' in name:
print ("delete file:"+name)
filename=fpath+name+"/"
shutil.rmtree(filename)
#复制0to30.acc到当前运行节点文件夹
shutil.copyfile(test_config.copypath+"0to30.acc", fpath+"chain.0.acc")
print ("copy file 0to30.acc success")
#启动节点,判断区块数是否是50
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
(result, stepname, msg) = API.cli().exec(False)
result = API.rpc().getblockcount()
API.cli().terminate()
c=0
if result==50:
c=1
#最后还原之前的区块
#删除Chain和Index文件夹
for root , dirs, files in os.walk(fpath):
for name in dirs:
if 'Chain_' in name or 'Index_' in name:
print ("delete file:"+name)
filename=fpath+name+"/"
shutil.rmtree(filename)
#删除所有.acc的文件
os.system("rm -rf "+fpath+"*.acc")
print ("Delete ALL ACC FILE")
#复制chain.acc到当前运行节点文件夹
shutil.copyfile(test_config.copypath+"chain.acc", fpath+"chain.acc")
print ("copy file chain.acc success")
#把protocol.json文件替换为SeedList未被删除的文件
shutil.copyfile(test_config.copypath+"protocol_notdeleted.json", fpath+"protocol.json")
#启动节点
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().list_address()
(result, stepname, msg) = API.cli().exec(False)
logger.print(msg)
result = API.rpc().getblockcount()
sum=a+b+c
self.ASSERT(sum==3,"export blocks failed")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_149_export_blocks(self):
try:
fp = open(os.getcwd().split("test/test_cli")[0]+"config.json", 'r', encoding='utf-8')
str=fp.read()
fp.close()
fpath = str.split("\"path\" : \"")[1].split("neo-cli.dll")[0]
path=Config.NODES[0]["walletname"]
#删除所有.acc的文件
os.system("rm -rf "+fpath+"*.acc")
print ("Delete ALL ACC FILE")
#导出0to29的区块
API.cli().export_blocks(start="0",count="29",timeout=35)
(result, stepname, msg) = API.cli().exec()
API.cli().terminate()
##copy 时候的路径需要获取了进行split再拼接
##SAMPLE:testpath=NODES["path"].split("/")xxxxxxx
shutil.copyfile(fpath+"chain.0.acc", test_config.copypath+"0to29.acc")
print ("export 0to29.acc success")
if os.path.exists(fpath+"chain.0.acc"):
os.remove(fpath+"chain.0.acc")
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
#导出0to30的区块
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().export_blocks(start="0",count="30",timeout=35)
(result, stepname, msg) = API.cli().exec()
API.cli().terminate()
shutil.copyfile(fpath+"chain.0.acc", test_config.copypath+"0to30.acc")
print ("export 0to30.acc success")
if os.path.exists(fpath+"chain.0.acc"):
os.remove(fpath+"chain.0.acc")
#导出30to101的区块
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().export_blocks(start="30",count=None,timeout=90)
(result, stepname, msg) = API.cli().exec()
API.cli().terminate()
shutil.copyfile(fpath+"chain.30.acc", test_config.copypath+"30to101.acc")
print ("export 30to101.acc success")
if os.path.exists(fpath+"chain.30.acc"):
os.remove(fpath+"chain.30.acc")
#把protocol.json文件替换为SeedList被删除的文件
shutil.copyfile(test_config.copypath+"protocol_deleted.json", fpath+"protocol.json")
print ("change protocol.json success")
#删除Chain和Index文件夹
for root , dirs, files in os.walk(fpath):
for name in dirs:
if 'Chain_' in name or 'Index_' in name:
print ("delete file:"+name)
filename=fpath+name+"/"
shutil.rmtree(filename)
#复制0to29.acc到当前运行节点文件夹
shutil.copyfile(test_config.copypath+"0to29.acc", fpath+"chain.0.acc")
print ("copy file 0to29.acc success")
#启动节点,判断区块数是否为29
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
(result, stepname, msg) = API.cli().exec(False)
logger.print(msg)
result = API.rpc().getblockcount()
API.cli().terminate()
a=0
if result==29:
print("blocks count:29")
a=1
#删除0to29.acc
if os.path.exists(fpath+"chain.0.acc"):
os.remove(fpath+"chain.0.acc")
print ("delete file:0to29.acc")
#复制30to101.acc到当前运行节点文件夹
shutil.copyfile(test_config.copypath+"30to101.acc", fpath+"chain.30.acc")
print ("copy file 30to101.acc success")
#启动节点,判断区块数是否还是29
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
(result, stepname, msg) = API.cli().exec(False)
result = API.rpc().getblockcount()
API.cli().terminate()
b=0
if result==29:
b=1
#删除Chain和Index文件夹
for root , dirs, files in os.walk(fpath):
for name in dirs:
if 'Chain_' in name or 'Index_' in name:
print ("delete file:"+name)
filename=fpath+name+"/"
shutil.rmtree(filename)
#复制0to30.acc到当前运行节点文件夹
shutil.copyfile(test_config.copypath+"0to30.acc", fpath+"chain.0.acc")
print ("copy file 0to30.acc success")
#启动节点,判断区块数是否是101
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
(result, stepname, msg) = API.cli().exec(False)
result = API.rpc().getblockcount()
API.cli().terminate()
c=0
if result==101:
c=1
#最后还原之前的区块
#删除Chain和Index文件夹
for root , dirs, files in os.walk(fpath):
for name in dirs:
if 'Chain_' in name or 'Index_' in name:
print ("delete file:"+name)
filename=fpath+name+"/"
shutil.rmtree(filename)
#删除所有.acc的文件
os.system("rm -rf "+fpath+"*.acc")
print ("Delete ALL ACC FILE")
#复制chain.acc到当前运行节点文件夹
shutil.copyfile(test_config.copypath+"chain.acc", fpath+"chain.acc")
print ("copy file chain.acc success")
#把protocol.json文件替换为SeedList未被删除的文件
shutil.copyfile(test_config.copypath+"protocol_notdeleted.json", fpath+"protocol.json")
#启动节点
API.cli().init(self._testMethodName, Config.NODES[0]["path"])
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().list_address()
(result, stepname, msg) = API.cli().exec(False)
logger.print(msg)
result = API.rpc().getblockcount()
sum=a+b+c
self.ASSERT(sum==3,"export blocks failed")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_150_export_blocks(self):
try:
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().export_blocks("5","abc",exceptfunc=lambda msg: msg.find("error") >= 0)
(result, stepname, msg) = API.cli().exec()
logger.print(msg)
self.ASSERT(result,"assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_151_export_blocks(self):
try:
fp = open(os.getcwd().split("test/test_cli")[0]+"config.json", 'r', encoding='utf-8')
str=fp.read()
fp.close()
fpath = str.split("\"path\" : \"")[1].split("neo-cli.dll")[0]
if os.path.exists(fpath+"chain.5.acc"):
os.remove(fpath+"chain.5.acc")
print ("file deleted")
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().export_blocks("0","10000000",timeout=10,exceptfunc=lambda msg: msg.find("error") >= 0)
(result, stepname, msg) = API.cli().exec()
logger.print(msg)
#删除所有.acc的文件
os.system("rm -rf "+fpath+"*.acc")
print ("Delete ALL ACC FILE")
self.ASSERT(result,"assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
def test_152_export_blocks(self):
try:
fp = open(os.getcwd().split("test/test_cli")[0]+"config.json", 'r', encoding='utf-8')
str=fp.read()
fp.close()
fp.close()
fpath = str.split("\"path\" : \"")[1].split("neo-cli.dll")[0]
if os.path.exists(fpath+"chain.5.acc"):
os.remove(fpath+"chain.5.acc")
print ("file deleted")
API.cli().export_blocks("5","0",exceptfunc=lambda msg: msg.find("error") >= 0)
(result, stepname, msg) = API.cli().exec()
logger.print(msg)
#删除所有.acc的文件
os.system("rm -rf "+fpath+"*.acc")
print ("Delete ALL ACC FILE")
self.ASSERT(result,"assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
'''
def test_153_start_consensus(self):
try:
#关闭四个共识节点
for node_index in range(len(Config.NODES)):
API.clirpc(node_index).terminate()
time.sleep(10)
# delete files(需要删除区块链及所有.acc文件)
for node_index in range(len(Config.NODES)):
API.node(node_index).clear_block()
time.sleep(10)
# 将protocol.json copy 到所有节点内替换原有的文件
# 启动123节点
# 启动自己,open wallet,start consensus
# 等待一段时间(5个区块),确认是否出现 send prepare response命令
#判断完毕后,不论是否通过,一律需要恢复protocol.json文件,并清空区块链,将原本需要的.acc 文件 copy进去
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
'''
def test_154_start_consensus(self):
try:
#处理方法:开启共识后等待5个区块生成后,检查log里是否存在send prepare response,只要不存在就ok,存在fail
API.cli().open_wallet(test_config.wallet_default, test_config.wallet_pwd)
API.cli().start_consensus(exceptfunc=lambda msg: msg.find("OnStart") >= 0)
API.cli().show_state(30)
(result, stepname, msg) = API.cli().exec()
logger.print(msg)
flag=True
if str(msg).find("send prepare response")>=0:
flag=False
self.ASSERT(flag,"assert not equal")
except AssertError as e:
logger.error(e.msg)
self.ASSERT(False, "error:assert")
except RPCError as e:
logger.error(e.msg)
self.ASSERT(False, "error:rpc")
except Exception as e:
logger.error(traceback.format_exc())
self.ASSERT(False, "error:Exception")
if __name__ == '__main__':
unittest.main()
|
#===============================================================================
# Project Euler: Problem 5 - Smallest multiple
#
# __author__ = "Zenith"
# __copyright__ = "Copyright 2013 by RockStone"
# __license__ = "GPL"
# __email__ = "zenith at rockstone dot me"
#===============================================================================
from time import time
def gcd(a, b):
while (b != 0):
a, b = b, a % b
return a
def factorize(n):
factor = {}
if n == 1: return {1:1}
else:
divisor = 2
while divisor <= n:
power = 0
while (n % divisor) == 0:
n //= divisor
power += 1
if power > 0:
factor.update({divisor: power}) # factor[divisor] = power
divisor += 1
if n > 1:
factor.update({divisor: power})
return factor
def maxfactorize(m):
maxfactor = {}
for i in xrange(1, m):
factor = factorize(i)
for key, value in factor.iteritems():
if maxfactor.get(key) is None: maxfactor.update({key: value})
elif maxfactor.get(key) < value: maxfactor.update({key: value})
return maxfactor
def pe5_factorization(num):
maxfactor = maxfactorize(num)
product = 1
for key, value in maxfactor.iteritems():
product *= key ** value
return product
def pe5_iteration(num):
start = 1
for i in xrange(1, num):
start *= i / gcd(i, start) # LCM
return start
if __name__ == "__main__":
num = 21
t0 = time()
print(pe5_factorization(num))
t1 = time()
print "%.20f" % (t1 - t0)
print(pe5_iteration(num))
t2 = time()
print "%.20f" % (t2 - t1) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.