def cart_pole(replay=True): randomness = 0.5 env = gym.make('CartPole-v1') action_space_size = env.action_space.n state_space_size = env.observation_space.shape[0] model = load_model(model_file) if replay else make_nn( state_space_size, action_space_size) model.compile(optimizer=tf.keras.optimizers.Adam(lr=0.001), loss='mean_squared_error') actor = QActor(q_learning_model=model, state_space_size=state_space_size, action_space_size=action_space_size, gamma=0.9999) if replay: randomness = 0.0 session(env=env, actor=actor, episodes=2000, stop_f=cart_pole_end, reward_manip_f=cart_pole_reward_manip, save_f=simple_saver, trainer=random_cp_trainer, solved_f=cartpole_solved, train=(not replay), rand_decay=0.992, randomness=randomness, alter_actor_action=cartpole_actor_action_alter)
def pendulum(replay=True, load_net=True): randomness = 0.5 env = gym.make('Pendulum-v0') action_space_size = 2 state_space_size = env.observation_space.shape[0] model = load_model(model_file) if load_net else make_nn( state_space_size, action_space_size) model.compile(optimizer=tf.keras.optimizers.Adam(lr=0.0008), loss="mean_squared_error") actor = QActor(q_learning_model=model, state_space_size=state_space_size, action_space_size=action_space_size, gamma=0.95) if replay: randomness = 0.0 session(env=env, actor=actor, episodes=13, stop_f=pendulum_end, reward_manip_f=pendulum_reward_manip, save_f=simple_saver, trainer=random_pd_trainer, solved_f=pendulum_solved, train=(not replay), rand_decay=0.99, randomness=randomness, alter_actor_action=pendulum_actor_action, action_prepare_to_save=pendulum_action_discretize)
def main(): logger.info("Initializing") args = parser_args() tf.compat.v1.set_random_seed(args.seed) random.seed(args.seed) with open(args.config) as f: config = json.load(f) if args.mode == 'download': from data.download_data import DataDownloader data_downloader = DataDownloader(config) data_downloader.save_data() else: session(config, args)
def submit_request (self, agent, community='public',\ type='GETREQUEST',\ encoded_oids=[], encoded_vals=[]): """ submit_request(agent[, community[, type[,\ encoded_oids[, encoded_vals]]]]): Create SNMP message of specified "type" (default is GETREQUEST) to be sent to "agent" with SNMP community name "community" (default is public) and loaded with encoded Object IDs "encoded_oids" along with their associated values "encoded_values" (default is empty lists). New SNMP message will be added to a queue of SNMP requests to be transmitted to their destinations (see dispatch()). """ # Create new SNMP session ses = session.session(agent, community) # Pass options to this session ses.iface = self.iface # Build a SNMP message message = ses.encode_request(type, encoded_oids, encoded_vals) # Store the message to be sent in the session object ses.store(message) # Add it to the list of active sessions self.sessions.append(ses)
def submit_request (self, agent, community='public',\ type='GETREQUEST',\ encoded_oids=[], encoded_vals=[]): """ submit_request(agent[, community[, type[,\ encoded_oids[, encoded_vals]]]]): Create SNMP message of specified "type" (default is GETREQUEST) to be sent to "agent" with SNMP community name "community" (default is public) and loaded with encoded Object IDs "encoded_oids" along with their associated values "encoded_values" (default is empty lists). New SNMP message will be added to a queue of SNMP requests to be transmitted to their destinations (see dispatch()). """ # Create new SNMP session ses = session.session (agent, community) # Pass options to this session ses.iface = self.iface # Build a SNMP message message = ses.encode_request(type, encoded_oids, encoded_vals) # Store the message to be sent in the session object ses.store (message) # Add it to the list of active sessions self.sessions.append(ses)
def errormessage(): s=session.session() error=s.get('error') if 'error' in s: del s['error'] return error
def test_write(self): print 'Sending communiaction' s = session.session() r = write( json.loads('{"addr":"7","baud":"9600","st":"300","val":"1023"}'), s) print r sleep(30)
def test_complete_20_strokes_with_0pt01_seconds_between_each_ir(self): s = session() self.add_n_strokes_with_n_seconds_between_ir(20, 0.01) session_start_time = datetime.datetime.now() session_end_time = session_start_time + datetime.timedelta(seconds = 1) display_sample = 50 retval = s.run(flywheel_q, gui_q, session_start_time, session_end_time, display_sample) self.assertEquals(retval,SESSION_COMPLETED) self.assertEquals(len(s.get_ir_ary()),60)
def test_add_200_spins_with_0pt02_seconds_between_spins(self): s = session() self.add_n_spins_with_n_seconds_between_spins(200, 0.02) session_start_time = datetime.datetime.now() session_end_time = session_start_time + datetime.timedelta(seconds = 5) display_sample = 50 retval = s.run(flywheel_q, gui_q, session_start_time, session_end_time, display_sample) self.assertEquals(retval,SESSION_COMPLETED) self.assertEquals(len(s.get_ts_ary()),200)
def compress_json_file(input_file, output_file): enumerator = 0 with open(input_file) as reader, open(output_file, 'w') as writer: for line in reader: enumerator += 1 if (enumerator%10**4 == 0): print enumerator compressed = compress_json(line) decompressed = session(compressed) writer.write(compressed) writer.write('\n') pass
def test(request): global SESSION # print "~main_fid|" print "O_STATUS.test", request SESSION = session.session() #'oosmpnn7777') if SESSION: print "<pre>SESSION:", interrogate( SESSION ), "\nSESSION.ssident:", SESSION.ssident, SESSION.is_new, "</pre>" # SESSION.set_obj ('test_key', {'TEST': 'object'}) # SESSION.del_obj ('test_key') for k in SESSION.objpkl: print '<dt>', k, ':</dt><dt>', SESSION.objpkl[k], "</dt>" sso = SESSION.start() # print "<pre>SESSION interrogate:", interrogate (sso), "\nsso:", sso, interrogate (SESSION.objpkl), "</pre>" else: print "<pre>SESSION:", SESSION SESSION = session.session() print "SESSION.ssident:", SESSION.ssident print "</pre>"
def compress_json_file(input_file, output_file): enumerator = 0 with open(input_file) as reader, open(output_file, 'w') as writer: for line in reader: enumerator += 1 if (enumerator % 10**4 == 0): print enumerator compressed = compress_json(line) decompressed = session(compressed) writer.write(compressed) writer.write('\n') pass
def check_user(request, session_id): us_row, message = get_usconf(dboo, request) if us_row: SESSION = SS.session(session_id) # del us_row['ip_loc'] del us_row['passwd'] del us_row['login'] # del us_row['tm_upd'] del us_row['options'] SESSION.sset({'us_row': us_row}) SESSION.stop() print "Set-Cookie: CPYSESSID=" + session_id return us_row, message
def get_user(): if "current_user" in web.ctx: return web.ctx.current_user session = session_manager.session() if "user_id" in session and session.user_id: users = model.Users(id=session.user_id) users.annotate_by_groups() try: web.ctx.current_user = user = users.list()[0] return user except: pass del users
def disp_03(request): global SESSION SESSION = session.session() # print "~main_fid|" print "<div class='green'>" # style='height: 300px; overflow: auto;'>" ptit_box("Статистика диспетчера 03") if SESSION.objpkl.has_key('us_row'): us_row = SESSION.objpkl['us_row'] # for k in us_row: print '<dt>', k, ':</dt><dt>', us_row[k], "</dt>" list_calls(where='AND subst IN (1,12)') # list_calls ('cfind') print "</div>" print "~eval| mark_table('call');" print "~debug|"
def view_oo(request): global SESSION SESSION = session.session() print "<div class='green'>" # print "<div>" ptit_box("Оперативная Обстановка", ctime=True, cdate=True) if SESSION.objpkl.has_key('us_row'): us_row = SESSION.objpkl['us_row'] list_calls() print "</div>" print "~eval| mark_table('call');" print "~debug|"
def post_index(): uuid=session.session()['upload_uuid'] uploadSet=UploadSet(uuid) count=0 for name in CSV_FILE_NAMES: if name in request.files: f = request.files[name] if f.filename!=name: session.setErrorMessage("'%s' is probably not the file you mean"%f.filename) redirect('/') uploadSet.ensureDirectoryExists() path=os.path.join(config.UPLOAD_DIRECTORY,str(uuid), name) f.save(file(path,'wc')) count+=1 session.setInfoMessage(str(count) + " files provided") redirect('/')
def addToWaitQueue(self, u): """Add a user to queue for a room""" self.waitqueue.append(u) #Can the waiting queue now form a room if len(self.waitqueue) < self.minRoom: return #waiting queue forms room newroom = self.roomNo self.roomNo += 1 #print "new room",newroom sess = session.session(newroom) for w in self.waitqueue: self.usermap[w] = newroom sess.addUser(w) self.sessionmap[newroom] = sess self.waitqueue = [] #Will the newly formed room be full if self.minRoom < self.maxRoom: self.spacesessions.append(newroom)
def addToWaitQueue(self,u): """Add a user to queue for a room""" self.waitqueue.append(u) #Can the waiting queue now form a room if len(self.waitqueue) < self.minRoom: return #waiting queue forms room newroom= self.roomNo self.roomNo+= 1 #print "new room",newroom sess= session.session(newroom) for w in self.waitqueue: self.usermap[w]= newroom sess.addUser(w) self.sessionmap[newroom]=sess self.waitqueue= [] #Will the newly formed room be full if self.minRoom < self.maxRoom: self.spacesessions.append(newroom)
def import_data(self): """Load new sessions as session class instances.""" old_files = [session.file_name for session in self.sessions] files = os.listdir(self.data_path) new_files = [ f for f in files if f[0] == "m" and f not in old_files and int(f.split("-", 1)[0][1:]) in self.subject_IDs ] if len(new_files) > 0: print "Loading new data files..." new_sessions = [ss.session(file_name, self.data_path, self.IDs) for file_name in new_files] ## Assign day to each session. # for session in new_sessions: # session.day = ut.get_day_number(session.date, self.start_date) self.sessions = self.sessions + new_sessions self.assign_session_numbers() self.n_subjects = len(np.unique([session.subject_ID for session in self.sessions])) self.n_days = max([int(session.day) for session in self.sessions]) self.dates = set([s.date for s in self.sessions])
def main(request, conf): global CONFIG CONFIG = conf # print """<html xmlns="http://www.w3.org/1999/xhtml">""" try: print "<head> <meta name='Author' content='V.Smirnov'> <title>%s</title>" % CONFIG.get( 'System', 'title') rel_css((r'/css/style.css', r'/css/calendar.css', r'/css/font-awesome/css/font-awesome.min.css')) jscripts((r'/jq/jquery.onajax_answer.js', r'/jq/jquery.js', r'/js/calendar.js', r'/js/check_forms.js')) print jslocal, "</head>" print """<body>""" SS = session.session() # cglob.ppobj(SS.objpkl) USER = SS.get_key('USER') if USER and USER['user_id']: print """<form name='myForm' action='/cgi/index.cgi' method='post'><fieldset class='hidd'> <input name='orderby' type='hidden' value='' /> <input name='stat' type='hidden' value='' /> </fieldset>""" out_head(SS, USER, CONFIG.get('System', 'name')) print "<div id='dbody' class='hidd'>" # print "### DEBUG CDB_DESC:", CDB_DESC # cglob.ppobj(request) subsystem = SS.get_key('subsystem') ROLE = SS.get_key('role') if not subsystem: cglob.wdgwarnn( "Внимание", "<center><br /><span class='tit'>Нужно выбрать рабочую подсистему.</span><br /></center>", obj=SS.objpkl) elif not ROLE: cglob.wdgwarnn( "Внимание", "<center><br /><span class='tit'>Нужно выбрать роль пользователя в подстсиеме.</span><br /></center>", obj=SS.objpkl) else: if subsystem[ 'label'] == 'RUSERS': # Ведение пользователей РНИЦ import rusers rusers.out_users(SS, USER) elif subsystem['label'] == 'WORK_TS': # Работа ТС # print "<h2>Работа ТС</h2>" import tranport tranport.main(SS, conf, request) elif subsystem['label'] == 'CONTRCT': import conract conract.main(SS, request) else: cglob.wdgwarnn("out_users", obj=SS.objpkl) # else: cglob.ppobj(SS.objpkl) print "</div><!-- dbody -->" else: if request.has_key('message'): authorize(request['message']) else: authorize() # print 'main', request, CONFIG.get('System', 'version'), CONFIG.get('System', 'copy') if request.has_key('message'): print "<div id='message' style='text-align:center;'>%s</div>" % request[ 'message'] else: print "<div id='message' style='text-align:center;'>message</div>" print """<script language="JavaScript">setTimeout ("set_message ('')", 10000);</script>""" print """<table><tr><td><div id='shadow'>shadow</div></td><td><div id='shadow2'>shadow2</div></td><td> <div id='widget'>widget</div></td><td><div id='error'>error</div></td><td><div id='warnn'>warnn</div></td></tr></table>""" print os.environ['REMOTE_ADDR'] ggg = globals() if ggg.has_key('LIBRARY_DIR'): print ggg['LIBRARY_DIR'] else: cglob.wdgwarnn('globals', ggg) except: exc_type, exc_value = sys.exc_info()[:2] perror( "EXCEPT main_page", " ".join([ "<pre>", str(exc_type).replace('<', '# '), str(exc_value), "</pre>" ])) print "<span style='background-color: #ffa; color: #a00; padding: 4px;'> EXCEPT main_page:", exc_type, exc_value, "</span>" finally: print "</form></body></html>"
def __init__(self): """Initialise the poker model""" self.session = session.session(1) self.changed = True self.datacentres = []
def __init__(self): """Initialise the poker model""" self.session= session.session(1) self.changed=True self.datacentres= []
def new_widow(request, conf): global CONFIG CONFIG = conf try: print "<head> <meta name='Author' content='V.Smirnov'> <title>%s</title>" % CONFIG.get( 'titWindows', request['wname']) rel_css( (r'/css/style.css', r'/css/calendar.css', r'/css/new_widow.css')) jscripts((r'/jq/jquery.onajax_answer.js', r'/jq/jquery.js', r'/js/calendar.js', r'/js/check_forms.js')) print jslocal, "</head>" if request['wname'] == 'listalarms': bgc = '#fa6' elif request['wname'] == 'blank_arm': bgc = '#fff' else: bgc = '#440' print """<body id='id_body' style='background-color: %s; padding: 0px;'> <form name='myForm' action='/cgi/index.cgi' method='post'><fieldset class='hidd'> <input name='orderby' type='hidden' value='' /> <input name='valid' type='hidden' value='' /> <input name='fform' type='hidden' value='new_widow' />""" % bgc import conract import dbtools idb = dbtools.dbtools(CDB_DESC) #CONFIG.get('dbNames', 'contracts')) SS = session.session() if request['wname'] == 'new_contr': stat = 'new' print """<input name='stable' type='hidden' value='vcontracts' /> <input name='npkey' type='hidden' value='id_contr' /></fieldset>""" row = idb.get_row("SELECT * FROM vcontracts WHERE id_contr = 0;") cdict = idb.desc #conract.DICT_TABS['vcontracts'] if request.has_key('id_org') and request['id_org'].isdigit(): conract.out_vcontracts(SS, idb, row, cdict, stat, int(request['id_org'])) else: conract.out_vcontracts(SS, idb, row, cdict, stat) elif request['wname'] == 'new_org': stat = 'new' print """<input name='stable' type='hidden' value='vorganizations' /> <input name='npkey' type='hidden' value='id_org' /></fieldset>""" row = idb.get_row("SELECT * FROM vorganizations WHERE id_org = 0;") cdict = idb.desc conract.out_vorganizations(SS, idb, row, cdict, stat) elif request['wname'] == 'transport': cglob.ppobj(request) elif request['wname'] == 'blank_arm': print "</fieldset>" import arms arms.blank(SS, idb, request) elif request['wname'] == 'listalarms': print "</fieldset>" import alarms alarms.alist(SS, idb, request) elif request['wname'] == 'view' and request.has_key('table'): print "<div id='widget'>" # class='wform' style='background-color: #989;'>" conract.out_tform(SS, request['table'], request['pkname'], request['idrow']) print "</div>" else: # pass print "<div class='wform'>" cglob.ppobj(request) cglob.ppobj(SS.objpkl) print "</div><!-- wform -->" # print request, CONFIG , CONFIG.get('dbNames', 'contracts') # print "<table><tr><td><div", "></div></td><td><div ".join(["id='shadow'","id='shadow2'", "id='widget'", "id='error'", "id='warnn'"]), "></div></td></tr></table>" print "<table><tr><td><div", "></div></td><td><div ".join( ["id='shadow'", "id='shadow2'", "id='error'", "id='warnn'"]), "></div></td></tr></table>" if request['wname'] == 'new_contr' and request.has_key( 'id_org') and request['id_org'].isdigit(): print "id_org:", request['id_org'] except: exc_type, exc_value = sys.exc_info()[:2] perror( "EXCEPT new_widow", " ".join([ "<pre>", str(exc_type).replace('<', '# '), str(exc_value), "</pre>" ])) print "<span style='background-color: #ffa; color: #a00; padding: 4px;'> EXCEPT new_widow:", exc_type, exc_value, "</span>" finally: # print """</fieldset>""" print "</form></body></html>"
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, String, Integer, ForeignKey, create_engine from sqlalchemy.orm import relationship, sessionmaker from session import session from collections import Counter from sqlalchemy.exc import IntegrityError #my session object S = session() SESSION = S[0] ENGINE = S[1] class User(declarative_base()): __tablename__ = "user" id = Column(Integer, primary_key=True) screen_name = Column(String) user_id = Column(Integer) number_of_followers = Column(Integer, default=0) follower_id = Column(Integer, ForeignKey(id)) follower = relationship("User") @classmethod def add_new_user(cls, screen_name, id, user_id): if not (cls.get_user(id) is None or \ cls.get_user(user_id) is None or \ cls.get_user(screen_name) is None): print("user present") return user = User(screen_name=screen_name, id=id, user_id=user_id)
#!/usr/bin/python from session import session import sys, glob, pprint fileList = glob.glob(sys.argv[1] + '/*RING*.txt') sessions = [] dateDict = {} for fileName in fileList: if '$0.10-$0.25' in fileName: p = session(fileName) print 'Parsing hand history file', fileName p.parseHands() sessions.append(p) rakePaidByMe = 0.0 amountWonByMe = 0.0 numHands = 0 numAces = 0 numKings = 0 numQueens = 0 amountWonWithAces = 0.0 amountWonWithKings = 0.0 amountWonWithQueens = 0.0 for session in sessions: date = session.hands[0].date if date not in dateDict: dateDict[date] = len(session.hands) else: dateDict[date] += len(session.hands) for hand in session.hands:
def error(): return 'error' in session.session()
def info(): return 'info' in session.session()
def user_location(): session_info = session.session() return session_info.get("lat", ""), session_info.get("lon", "")
def test_write(self): print 'Sending communiaction' s=session.session() r=write(json.loads('{"addr":"7","baud":"9600","st":"300","val":"1023"}'),s) print r sleep(30)
signal.signal(signal.SIGALRM, alarmHandler) signal.setitimer(signal.ITIMER_REAL, timeout) try: text = getch()() signal.alarm(0) return text except AlarmException: pass signal.signal(signal.SIGALRM, signal.SIG_IGN) return '' def pos(x, y): return '\x1b[%d;%dH' % (y, x) init_session = session() init_session.addobject(mand()) printframe = init_session.printFrame shieldinc = init_session.shieldinc activateshield = init_session.ac_shield checksh = init_session.check_c decsh = init_session.decshield while(True): prev = datetime.now() t_cop = prev checksh() decsh() sp = init_session.retboost() if(sp==1):
def infomessage(): s=session.session() info=s.get('info') if 'info' in s: del s['info'] return info
import socket import sys import time import threading from random import randint import util from session import session CLIENT_ADDR = util.getClientAddress(str(sys.argv[1])) print(CLIENT_ADDR) s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) s.bind(CLIENT_ADDR) session_lock = threading.Lock() _session_ = session() curctr = 1 def recclient(): while True: time.sleep(0.5) data, addr = s.recvfrom(1024) length = 9 + int(data[3]) if data[0] != util.MYINIT_1 or data[1] != util.MYINIT_2: print('\t\t\t\t\t\t\tHeader Unknown format.') continue if data[2] == util.OPCODE_LOGIN_ACK:
def data(): uuid=session.session()['upload_uuid'] uploadSet=UploadSet(uuid) return uploadSet.transactions()['Total(BTC)'].to_json(orient='values')
def index(): assert os.path.isdir(config.UPLOAD_DIRECTORY) uuid=session.session()['upload_uuid'] uploadSet=UploadSet(uuid) return locals()
def main(request): global SESSION if request.has_key('disp'): session_id = "oosmpnn" + request['disp'] # is_session (session_id) # if not os.environ.has_key('HTTP_COOKIE') or os.environ['HTTP_COOKIE'].find(request['disp']) < 0: # iss = is_session (session_id) if request.has_key('stat'): if request['stat'] == 'us_ident': us_row, message = check_user(request, session_id) if us_row: # and is_in_work (dboo, us_row): pass else: session_id = "" elif request['stat'] == 'exit': dboo.qexecute( "UPDATE loc_addr_user SET cod_disp=NULL WHERE ip_addr = '%s';" % REMOTE_ADDR) session_id = "" message = 'Введите код пользователя.' else: iss = is_session(session_id) if iss <= 0: session_id = "" message = "Долгое отсутствие. %d<br />Введите код пользователя." % iss else: # ss = session.session (session_id) message = request['disp'] # print "QQQ" else: session_id = "" message = 'Введите код пользователя.' print '\n<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">' print """<html xmlns="http://www.w3.org/1999/xhtml">""" try: get_config() print "<head> <meta name='Author' content='V.Smirnov' /><title>%s</title>" % config.get( 'System', 'title') print "<meta name='viewport' content='width=device-width, initial-scale=0.9, minimum-scale=0.8' />" rel_css((r'/smp/css/style.css', )) jscripts( (r'/jq/jquery.onajax_answer.js', r'/jq/jquery.js', r'/smp/js/oopy.js', r'/smp/js/new_call.js', r'/smp/js/tree.js')) print jslocal, "</head>" print """<body><center>""" # print request # is_session ('oosmpnn7777') # print os.environ.has_key('HTTP_COOKIE') # print os.environ['HTTP_COOKIE'], os.environ['HTTP_COOKIE'].find(request['disp']) if os.environ.has_key('SCRIPT_NAME'): print "<form name='mainForm' action='%s' method='post'>" % os.environ[ 'SCRIPT_NAME'] else: print "<form name='mainForm' action='%s' method='post'>" % 'SCRIPT_NAME' print """<fieldset class='hidd'> <input type='hidden' name='stat' value='' /> <input type='hidden' name='cpoint' value='' /> <input type='hidden' name='screen' value='' /> </fieldset>""" if session_id: #request.has_key('disp'): SESSION = session.session(session_id) if request.has_key('stat') and request['stat'] == 'us_ident': SESSION.set_obj('us_row', us_row) if os.environ['SCRIPT_NAME'] == '/03/alb/oo.cgi': woke_alb(request, SESSION, us_row) elif os.environ['SCRIPT_NAME'] == '/03/oopy/oo.cgi': woke_page(request, SESSION, us_row) else: print "SCRIPT_NAME:", os.environ['SCRIPT_NAME'] elif SESSION.objpkl.has_key('us_row'): us_row = SESSION.objpkl['us_row'] if os.environ['SCRIPT_NAME'] == '/03/alb/oo.cgi': woke_alb(request, SESSION, us_row) elif os.environ['SCRIPT_NAME'] == '/03/oopy/oo.cgi': woke_page(request, SESSION, us_row) else: print "SCRIPT_NAME:", os.environ['SCRIPT_NAME'] else: print "<hr />", session_id, "<hr />", SESSION.objpkl, "<hr />", locals( ).has_key('us_row') # print "<hr />SESSION", SESSION.start() in_work = is_in_work(dboo, us_row) woke_page(request, SESSION, us_row) #session_id) else: authorize(message) # print 'main', request, config.get('System', 'version'), config.get('System', 'copy') print "<div id='shadow'>shadow</div>" print "</form>" # print "<img src='img/nn10.png' />" # width='128px' height='128px' />" if os.environ['SCRIPT_NAME'] != '/03/alb/oo.cgi': print "<div id='shreslt'>shreslt</div>" print "<div id='message'>message</div>" print "<div id='debug'>debug</div>" except: exc_type, exc_value = sys.exc_info()[:2] print "<span style='background-color: #ffa; color: #a00; padding: 4px;'><pre> EXCEPT main_page:", exc_value, "</pre></span>" finally: # if SESSION: SESSION.stop() print "</center></body></html>"
#!/bin/env python from session import session sess1 = session('184.105.247.71') sess1.connect('pyclass','88newclass') for line in sess1.sendCmd('config t'): print line.rstrip() for line in sess1.sendCmd('logging buffer 10000'): print line for line in sess1.sendCmd('end'): print line for line in sess1.sendCmd('sho run | i logging'): print line sess1.disco()
def test_read2(self): s=session.session() r=read(json.loads('{"addr":"7","baud":"9600","st":"100","reg":"1"}'),s) print r
def connectSSH(self): self._ssh_session = session(self._ip, self._username, self._password) self.config['HOSTS'][self._name]['ssh_session'] = self._ssh_session return self._ssh_session
def main(script_name, request, referer): global SESSION label = 'main' try: if request.has_key('disp'): session_id = "oosmpnn" + request['disp'] SESSION = session.session(session_id) if request.has_key('main_fid'): # print "shadow|" if request['main_fid'] == 'GET_CALL': # Прием вызова if request.has_key('reasn') and request['reasn']: label = 'new_call' reasn = upper_ru(request['reasn'].strip() ) #.decode ("UTF-8").encode("KOI8-R")) call_handling.new_call(reasn, request) print "~set_reasn|" ''' if request.has_key('reasn_comment') and request['reasn_comment']: print "~rcomment|<div class='grey'>", ptit_box ("Коментарий к поводу вызова") print request['reasn_comment'].decode ("UTF-8").encode("KOI8-R"), "</div>" ''' else: import opros # Опрос НОВЫЙ opros.start(request) ''' if request.has_key('change_reasn'): # Прием вызова СТАРЫЙ # SESSION.set_obj ('new_call', request) # print "~eval| alert ('change_reasn');" del request['reasn'] del request['stack'] label = 'change_reasn.set_reasn' print "~shadow|" print "~set_reasn|", label, request import tree_reasn tree_reasn.set_reasn ({}) elif request.has_key('reasn') and request['reasn'] != '': label = 'new_call' reasn = upper_ru (request['reasn'].strip().decode ("UTF-8").encode("KOI8-R")) call_handling.new_call (reasn, request) print "~set_reasn|" else: label = 'tree_reasn.set_reasn' import tree_reasn print "~set_reasn|" SESSION.del_obj('GET_CALL') tree_reasn.set_reasn (request) ''' elif request[ 'main_fid'] == 'CLL_OPER': # Все Вызова в Оперативной Обстановке import O_STATUS print "~main_fid|" O_STATUS.view_oo(request) elif request['main_fid'] == 'O_STATUS': # Статистика import O_STATUS print "~main_fid|" O_STATUS.disp_03(request) O_STATUS.test(request) elif request['main_fid'] == 'VIEW_MSG': print "~main_fid|VIEW_MSG", request # import opros # opros.start (request) else: print "~shadow|", request['main_fid'] if request.has_key('stat'): print "~message| stat:", request['stat'] print "~eval| document.mainForm.stat.value='';" elif request.has_key('shstat'): # Опрос НОВЫЙ продолжение import opros # print "~message|", request opros.nnext(request) else: print "message|", script_name, request, referer conf = get_config() except SystemExit: pass except: exc_type, exc_value = sys.exc_info()[:2] print "~message|EXCEPT ajax", label, escape(str(exc_type)), exc_value finally: pass '''
def test_read2(self): s = session.session() r = read(json.loads('{"addr":"7","baud":"9600","st":"100","reg":"1"}'), s) print r
def input_to(timeout=1): signal.signal(signal.SIGALRM, alarmHandler) signal.setitimer(signal.ITIMER_REAL, timeout) try: text = getch() signal.alarm(0) return text except AlarmException: pass signal.signal(signal.SIGALRM, signal.SIG_IGN) return '' if __name__ == "__main__": newSession = session() newSession.addobject(Mando()) newSession.getInitialFrame() input() while (1): prev = datetime.now() c = input_to(0.04) if c == 'q': break newSession.setInput(c) newSession.renderNextFrame() now = datetime.now() while (now - prev).total_seconds() < 0.05: now = datetime.now() if newSession.endGame(): break
def delete_uploads(): uuid=session.session()['upload_uuid'] uploadSet=UploadSet(uuid) uploadSet.deleteAllFiles() session.setErrorMessage("Files Deleted") redirect('/')
def upload_uuid(): return session.session().get('upload_uuid')
def returning_user(upload_uuid): session.setInfoMessage("Hello, welcome back") session.session()['upload_uuid']=upload_uuid redirect('/')
def initconfig(): with open(r"setting.json", "r", encoding="utf-8") as f: f.seek(0) global config config = json.load(f) #print(config) def saveconfig(): with open(r"setting.json", "w", encoding="utf-8") as f: f.seek(0) #print(json.dumps(config, indent=4)) f.write(json.dumps(config, indent=4)) def insertSession(config, session): ss = config["sessions"] s = {} s["ip"] = session.ip s["user"] = session.user s["passwd"] = session.passwd ss.append(s) if __name__ == '__main__': # global config initconfig() s = session.session("192.168.1.5", "root", "dddd") insertSession(config, s) saveconfig()