def execute_graph(filepath, start=None, parameters=None, context=None): """Shortest code path to executing a graph from the nxt package. Creates a 1 off session and executes the graph within that session. Arguments are a direct copy of Session.execute_graph, see there for full details. :param filepath: Path to the graph file. :type filepath: str :param start: Path to the node to begin execution from. :type start: str :param parameters: Dict where key is attr path and value is new attr\ value. :type parameters: dict :param context: Optional name of remote context to execute graph in, \ if none is passed the graph is executed in this interpreter. :type context: str """ if context and context not in contexts.iter_context_names(): logger.info('Valid contexts are: ' '{}'.format(list(contexts.iter_context_names()))) raise NameError('Unknown context: "{}"'.format(context)) one_shot_session = Session() one_shot_session.execute_graph(filepath, start=start, parameters=parameters, context=context)
def change_session(context, change_to_project): pause(context.sessions[context.curr_project]) if not change_to_project in context.sessions: context.sessions[change_to_project] = Session(change_to_project) context.curr_project = change_to_project resume(context.sessions[context.curr_project]) return context
def process_with_request_file(options): session = Session() if options.file is None: method = "GET" headers = None body = "" uri = "" else: parser = RequestFileParser(options.file) if parser.run() is False: return 1 method = getattr(parser, "method", "GET") headers = getattr(parser, "headers", CaseInsensitiveDict()) body = getattr(parser, "body", "") uri = getattr(parser, "uri", "") # If dumy_body_byte is present, add dumy data. body += make_dumy_body(options.dumy_body_byte) session.update_connection_info(method=method) session.update_headers(headers) session.update_body(body) request_url = make_request_url(options.host, options.port, uri) session.send(request_url, verbose_detail=options.verbose) return 0
def open_stream(self): """ Open stream reading in log csv file and creating or updating sessions """ with open(self.input_csv_file_path, newline='') as csvfile: reader = csv.DictReader(csvfile) for idx, row in enumerate(reader): # Read one line at a time without loading entire set into memory try: user_ip_address = row['ip'] current_time = datetime.strptime('{0} {1}'.format(row['date'], row['time']), '%Y-%m-%d %H:%M:%S') except KeyError: logging.warning('Row {0} missing necessary ip address identifier or datetime information to ' 'determine session intervals. Skipping over.'.format(idx + 1)) continue if user_ip_address not in self.current_sessions: # Create a new session for this user self.current_sessions[user_ip_address] = Session(**{ 'inactivity_period': self.inactivity_period, 'ip_address': user_ip_address, 'start_time': current_time, }) else: # A session exists for this user # Update the end time of the session # If time has lapsed, close inactive sessions self.current_sessions[user_ip_address].update_end_time(current_time) if current_time != self.last_recorded_time: self.last_recorded_time = current_time self._close_sessions() # When the end of file is reached, we close out all remaining sessions self._close_sessions(close_all=True)
def update_exchange_ids(own_id, exchange_ids): try: if len(exchange_ids) < 6: with Session() as sess: # ownerの情報を取得 owner = sess.query( models.User).filter_by(id=own_id).first() current_exchanges = [ owner.exchange[i].exchange_id for i in range(len(owner.exchange)) ] ex_ids_not_zero = [ int(ex_id) for ex_id in exchange_ids if int(ex_id) != 0 ] ex_set = set(ex_ids_not_zero) old_set = set(current_exchanges) # 現在のownerが所持するidと送られてきたidで共通のもの common_set = old_set & ex_set # 現在の所持idになく,送られてきたidにはあるもの new_set = ex_set - old_set # 上記二つの和集合 actual_set = common_set | new_set # Exchangeオブジェクトを生成 new_exchange = [ models.Exchange(exchange_id=ex_id) for ex_id in list(actual_set) ] # データベースに追加 sess.add_all(new_exchange) # 更新 owner.exchange = new_exchange sess.commit() except Exception: # めんどいからエラー起こったらスルー pass
def getSession(self, sid, limit=None, name=None, user=None, keep=False, protected=False): u""" <doc> The <code>getSession</code> method answers the <code>Session</code> instance with <attr>sid</attr>. Answer a new instance if the <attr>sid</attr> cannot be found. Store that session in the dict of <code>self</code>. </doc> """ session = self.get(sid) if session is None: sid = self.getNewSessionId() timestamp = self.newTimeStamp() session = self[sid] = Session(sid, timestamp, limit=limit, name=name, user=user, keep=keep, protected=protected) return session
def process(command): global session global initialized """Process commands here""" if not command.startswith("m"): return 0 if command == "mi": sys.path.append("src/") try: from session import Session session = Session(binary, r) initialized = True except Exception as e: print(e) else: try: if initialized: session.run(command[1:]) else: print("r2angr not initialized") except Exception as e: print(e) # Parse arguments #tmp = command.split(" ") #print(str(tmp)) return 1
def handle_command(command, channel): """ Executes bot command if the command is known """ global session # Default response is help text for the user default_response = "Not sure what you mean. Try *{}*.".format( EXAMPLE_COMMAND) # Finds and executes the given command, filling in response response = None if session: response = session.handleInput(command) if not response: response = session.finalize() session = None else: # This is where you start to implement more commands! if command.startswith(EXAMPLE_COMMAND): session = Session(command.replace(EXAMPLE_COMMAND, ""), ["what", "when", "how"]) response = session.nextQuestion() elif command.startswith(VOTE_COMMAND): session = WeightBot(command.replace(VOTE_COMMAND, "")) response = session.welcome() # Sends the response back to the channel slack_client.api_call("chat.postMessage", channel=channel, text=response or default_response)
class Config(object): SECRET_KEY = os.getenv('SECRET_KEY') JWT_SECRET = os.getenv('JWT_SECRET') REDIS_NAME = os.getenv('REDIS_NAME') redis = redis.Redis(REDIS_NAME) session = Session(redis) user = User(redis)
def main(): """ Main function to put the pieces together and run the recipe """ reg = RecipeRegistry() validate() try: ingredients = decode_ingredients(read_ingredients()) session = Session(ingredients['config'], ingredients['input'], ingredients['recipe'], os.path.basename(sys.argv[1]), FileUtil.get_directory_path(sys.argv[1])) reg.run_recipe(session) except RecipeValidationException as re: log.error(str(re)) exit_error() except RuntimeException as re: log.error(str(re)) exit_error() except WCSTException as re: log.error(str(re)) exit_error() except Exception as ex: log.error("An error has occured in the execution of the program. Error Message: " + str( ex) + "\nStack Trace: " + traceback.format_exc()) exit_error()
def make_kernel(namespace, kernel_factory, out_stream_factory=None, display_hook_factory=None): """ Creates a kernel, redirects stdout/stderr, and installs a display hook and exception handler. """ # If running under pythonw.exe, the interpreter will crash if more than 4KB # of data is written to stdout or stderr. This is a bug that has been with # Python for a very long time; see http://bugs.python.org/issue706263. if sys.executable.endswith('pythonw.exe'): blackhole = file(os.devnull, 'w') sys.stdout = sys.stderr = blackhole sys.__stdout__ = sys.__stderr__ = blackhole # Install minimal exception handling sys.excepthook = FormattedTB(mode='Verbose', color_scheme='NoColor', ostream=sys.__stdout__) # Create a context, a session, and the kernel sockets. io.raw_print("Starting the kernel at pid:", os.getpid()) context = zmq.Context() # Uncomment this to try closing the context. # atexit.register(context.close) session = Session(username=u'kernel') reply_socket = context.socket(zmq.XREP) xrep_port = bind_port(reply_socket, namespace.ip, namespace.xrep) io.raw_print("XREP Channel on port", xrep_port) pub_socket = context.socket(zmq.PUB) pub_port = bind_port(pub_socket, namespace.ip, namespace.pub) io.raw_print("PUB Channel on port", pub_port) req_socket = context.socket(zmq.XREQ) req_port = bind_port(req_socket, namespace.ip, namespace.req) io.raw_print("REQ Channel on port", req_port) hb = Heartbeat(context, (namespace.ip, namespace.hb)) hb.start() hb_port = hb.port io.raw_print("Heartbeat REP Channel on port", hb_port) # Helper to make it easier to connect to an existing kernel, until we have # single-port connection negotiation fully implemented. io.raw_print("To connect another client to this kernel, use:") io.raw_print("-e --xreq {0} --sub {1} --rep {2} --hb {3}".format( xrep_port, pub_port, req_port, hb_port)) # Redirect input streams and set a display hook. if out_stream_factory: sys.stdout = out_stream_factory(session, pub_socket, u'stdout') sys.stderr = out_stream_factory(session, pub_socket, u'stderr') if display_hook_factory: sys.displayhook = display_hook_factory(session, pub_socket) # Create the kernel. kernel = kernel_factory(session=session, reply_socket=reply_socket, pub_socket=pub_socket, req_socket=req_socket) kernel.record_ports(xrep_port=xrep_port, pub_port=pub_port, req_port=req_port, hb_port=hb_port) return kernel
def login(self, nickname, password, shelve_db=None): """ >>> import shelve >>> import os >>> shelve_db = shelve.open(r'db/users') >>> user = User('*****@*****.**', 'pass', 'nick') >>> user.register('pass', shelve_db) User successfully registered Save User to db >>> user.login('nick', 'pass', shelve_db) # doctest: +ELLIPSIS User nick logged in <__main__.User object at ...> >>> user.login('nick_', 'pass', shelve_db) User doesn't exist in db >>> os.remove(r'db/users') """ if nickname in shelve_db.keys( ) and shelve_db[nickname].password == password: print('{} {} logged in'.format(self.__class__.__name__, self.nickname)) logged_user = shelve_db[nickname] logged_user.session.append(Session()) return logged_user else: print('{} doesn\'t exist in db'.format(self.__class__.__name__))
def getData(self, formatstr: str = 'tkmphrw*') -> Session: """ :param formatstr: Type 't' to get Temperature (Cels), 'k' to get Temperature (K), 'p' - Pressure (hPa), 'm' - Pressure (mmHg), 'h' - relative humidity (%), 'r' - absolute humidity (g/m3), 'w' - wind speed (m/s), '*' - precipitation amount (mm). Example: 'tprw*'. :return: Session of weather data. """ WDATA = Session() for wfile in self.wfiles: wfile.parse() wfile.cutData(self.start_t, self.stop_t) for char in formatstr: if char == 't': WDATA.add(wfile.WDATA.get_series(p.weather.labels.T_C)) if char == 'k': WDATA.add(wfile.WDATA.get_series(p.weather.labels.T_K)) if char == 'm': WDATA.add(wfile.WDATA.get_series(p.weather.labels.P_mm)) if char == 'p': WDATA.add(wfile.WDATA.get_series(p.weather.labels.P_hpa)) if char == 'h': WDATA.add(wfile.WDATA.get_series(p.weather.labels.rho_rel)) if char == 'r': WDATA.add(wfile.WDATA.get_series(p.weather.labels.rho_abs)) if char == 'w': WDATA.add(wfile.WDATA.get_series(p.weather.labels.Vwind)) if char == '*': WDATA.add(wfile.WDATA.get_series(p.weather.labels.RainRt)) WDATA.time_sorting() return WDATA
def create_session(self): task = self.parent.get_current_task() if task == self.parent.DEFAULT_TASK: return task_time = self.task_time session = Session(task, task_time, self.start_time, self.start_date) return session
def make_kernel(namespace, kernel_factory, out_stream_factory=None, display_hook_factory=None): """ Creates a kernel, redirects stdout/stderr, and installs a display hook and exception handler. """ # Re-direct stdout/stderr, if necessary. if namespace.no_stdout or namespace.no_stderr: blackhole = file(os.devnull, 'w') if namespace.no_stdout: sys.stdout = sys.__stdout__ = blackhole if namespace.no_stderr: sys.stderr = sys.__stderr__ = blackhole # Install minimal exception handling sys.excepthook = FormattedTB(mode='Verbose', color_scheme='NoColor', ostream=sys.__stdout__) # Create a context, a session, and the kernel sockets. io.raw_print("Starting the kernel at pid:", os.getpid()) context = zmq.Context() # Uncomment this to try closing the context. # atexit.register(context.close) session = Session(username=u'kernel') reply_socket = context.socket(zmq.XREP) xrep_port = bind_port(reply_socket, namespace.ip, namespace.xrep) io.raw_print("XREP Channel on port", xrep_port) pub_socket = context.socket(zmq.PUB) pub_port = bind_port(pub_socket, namespace.ip, namespace.pub) io.raw_print("PUB Channel on port", pub_port) req_socket = context.socket(zmq.XREQ) req_port = bind_port(req_socket, namespace.ip, namespace.req) io.raw_print("REQ Channel on port", req_port) hb = Heartbeat(context, (namespace.ip, namespace.hb)) hb.start() hb_port = hb.port io.raw_print("Heartbeat REP Channel on port", hb_port) # Helper to make it easier to connect to an existing kernel, until we have # single-port connection negotiation fully implemented. io.raw_print("To connect another client to this kernel, use:") io.raw_print("-e --xreq {0} --sub {1} --rep {2} --hb {3}".format( xrep_port, pub_port, req_port, hb_port)) # Redirect input streams and set a display hook. if out_stream_factory: sys.stdout = out_stream_factory(session, pub_socket, u'stdout') sys.stderr = out_stream_factory(session, pub_socket, u'stderr') if display_hook_factory: sys.displayhook = display_hook_factory(session, pub_socket) # Create the kernel. kernel = kernel_factory(session=session, reply_socket=reply_socket, pub_socket=pub_socket, req_socket=req_socket) kernel.record_ports(xrep_port=xrep_port, pub_port=pub_port, req_port=req_port, hb_port=hb_port) return kernel
def notes_list_api(request): if request.user is None: return Response('unauthenticated', status=status.HTTP_401_UNAUTHORIZED) """ List all code snippets, or create a new snippet. """ if request.method == 'GET': notes = r.lrange('notes', 0, 100) decoded = [] if (len(notes) > 0): for n in notes: decoded.append(json.loads(n)) serializer = NoteOutputSerializer(decoded, many=True) #if(serializer.is_valid()): return Response(serializer.data) #return Response(serializer.errors, status=status.HTTP_500_INTERNAL_SERVER_ERROR) elif request.method == 'POST': serializer = NoteInputSerializer(data=request.data, context={'request': request}) if serializer.is_valid(): logging.warning('serializer:%s', serializer.data) #json = serializers.serialize('json', serializer.data) r.lpush('notes', json.dumps(serializer.data)) Session().add(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
def bratLogin(request, response, server_path="/var/www/html/brat/server/src", session_path="/var/www/html/brat/work/sessions/", user="******"): import os if not os.path.isdir(server_path): raise Exception('Invalid server_path') if not os.path.isdir(session_path): raise Exception('Invalid session_path') os.sys.path.append(server_path) from session import SessionCookie, Session from hashlib import sha224 from datetime import datetime, timedelta import pickle from ipware.ip import get_ip ip = get_ip(request) sid = sha224('%s-%s' % (ip, datetime.utcnow())).hexdigest() cookie = SessionCookie(sid) current_session = Session(cookie) current_session['user'] = user ppath = os.path.join(session_path, sid + '.pickle') with open(ppath, 'wb') as f: pickle.dump(current_session, f) try: os.chown(ppath, 33, 33) except: raise Exception('If you\'re using "RUNSERVER", do it with root!') exp = (datetime.utcnow() + timedelta(30)).strftime('%a, %d %b %Y %H:%M:%S') response.set_cookie('sid', sid, path='/brat/', expires=exp) return response
def log_out(self): ending = Session() self.session = ending any_key = raw_input("...please enter to exit session") print u'User has logged out: {}'.format(self.session.end()), '\n' print u'Elapsed time of session: {}'.format( self.session.get_elapse_time())
def load_log_file(self, file_name): self.scene = Graphics_scene(self) self.visualizer_view.setScene(self.scene) self.session = Session() self.road_network = Network() self.animator = Animator(self.scene) self.city = City(self.animator) if file_name.endswith(".gz"): input_file = GzipFile(file_name) elif file_name.endswith(".bz2"): input_file = BZ2File(file_name) else: input_file = open(file_name, 'r') for line in input_file: if self.session.parse(line): continue if self.road_network.parse(line): continue if self.city.parse(line): continue input_file.close() self.road_network.resolve() self.scene.draw_road_network(self.road_network) self.set_ready_to_run(file_name)
def handleLoginRequest(self, user, legacyName, password, extra): self.logger.debug("handleLoginRequest(user=%s, legacyName=%s)", user, legacyName) if user not in self.sessions: self.sessions[user] = Session(self, user, legacyName, extra) self.sessions[user].login(password)
def log_in(self): starting = Session() self.session = starting user = str(raw_input("Please input username: "******"Please input password: "******"You need to enter login and password!..." return False if not passw: print "You need to enter login and password!..." return False file = open("users.txt", "r") for line in file.readlines(): us, pw, rp = line.strip().split("|") if ('banned_' + user) in us: print 'User was banned!' return False if (int(rp) >= reports_limit): print 'User has been reported many times and banned!' return False if (user in us) and (passw in pw) and (int(rp) < reports_limit): print "Login successful!" print u"Starting of game session: {}".format(self.session.start()), '\n' return True else: print "Wrong username/password" return False
async def handle_update(self, update_json: dict): room_id = update_json["EventData"]["RoomId"] session_id = update_json["EventData"]["SessionId"] event_timestamp = dateutil.parser.isoparse( update_json["EventTimestamp"]) if update_json["EventType"] == "SessionStarted": for session in self.sessions.values(): if session.room_id == room_id and \ (event_timestamp - session.end_time).total_seconds() / 60 < CONTINUE_SESSION_MINUTES: self.sessions[session_id] = session if session.upload_task is not None: session.upload_task.cancel() return self.sessions[session_id] = Session(update_json) else: if session_id not in self.sessions: print(f"Cannot find {room_id}/{session_id} for: {update_json}") return current_session: Session = self.sessions[session_id] current_session.process_update(update_json) if update_json["EventType"] == "FileClosed": new_video = Video(update_json) await current_session.add_video(new_video) elif update_json["EventType"] == "SessionEnded": current_session.upload_task = \ asyncio.run_coroutine_threadsafe(self.upload_video(current_session), self.video_processing_loop)
def run(): args = NGCF_Args(parse_args()) # 获取训练集的dataloader形式 data = DATA(args.data_path, args.dataset_name) train_set, train_U2I, test_U2I, edge_indices, edge_weight, n_users, n_items = data.load( ) train_dl = get_loader(train_set, train_U2I, n_items, args.batch_size, args.cores) # 获取归一化的拉普拉斯矩阵 laplace_graph = Graph(edge_indices, edge_weight) laplace_graph.add_self_loop() laplace_graph.norm() norm_adj = laplace_graph.mat.cuda() # 定义网络 model = NGCF(n_users, n_items, norm_adj, args) model = model.cuda() optimizer = optim.Adam(model.parameters(), lr=args.lr) # 定义会话 sess = Session(model) for epoch in range(args.num_epochs): loss, mf_loss, emb_loss = sess.train(train_dl, optimizer) print("epoch: {:d}, loss = [{:.6f} == {:.6f} + {:.6f}]".format( epoch, loss, mf_loss, emb_loss)) perf_info = evaluate(model, n_users, n_items, train_U2I, test_U2I, args) print("precision: [{:.6f}] recall: [{:.6f}] ndcg: [{:.6f}]".format( perf_info[0], perf_info[1], perf_info[2]))
def __init__(self, update: Update) -> None: self.event = Event(update) self.session = Session(session_id=self.event.chat['id']) self.state = self.session.state self.setState = self.session.setState self.resetState = self.session.resetState self.chatId: str | int = self.event.chat['id']
def main(): """ Main function to put the pieces together and run the recipe """ # NOTE: not allow GDAL to create auxilary file which causes problem when no permission on the input data folder command = "export GDAL_PAM_ENABLED=NO" os.system(command) reg = RecipeRegistry() validate() try: ingredients = decode_ingredients(read_ingredients()) hooks = ingredients["hooks"] if "hooks" in ingredients else None session = Session(ingredients['config'], ingredients['input'], ingredients['recipe'], hooks, os.path.basename(sys.argv[1]), FileUtil.get_directory_path(sys.argv[1])) reg.run_recipe(session) except RecipeValidationException as re: log.error(str(re)) exit_error() except RuntimeException as re: log.error(str(re)) exit_error() except WCSTException as re: log.error(str(re)) exit_error() except Exception as ex: log.error( "An error has occured in the execution of the program. Error Message: " + str(ex) + "\nStack Trace: " + traceback.format_exc()) exit_error()
def post_data(): # Because the data is limited in 2016, assume the current timestamp is 12/1/2016 # now = datetime.now() now = datetime(2016, 12, 1) if request.method == 'POST': json = request.get_json() data_list = json["Data"] ret_str = "" if data_list: for _data in data_list: # If data ts is within a year then we keep record ts = datetime.strptime(_data["ts"], '%Y-%m-%dT%H:%M:%S') if now <= (ts + timedelta(days=365)): try: # handle json that doesn't have country if "country" not in _data: _data["country"] = None session = Session(player_id=_data["player_id"], country=_data["country"], event=_data["event"], session_id=_data["session_id"], ts=_data["ts"]) db.session.add(session) db.session.commit() ret_str = ret_str + "Session added. {} session id={}\r\n".format( _data["event"], _data["session_id"]) except Exception as e: return str(e) else: ret_str = ret_str + "Data is older than a year. Discarded.\r\n" return ret_str else: return 'No Data Provided' else: return 'get-data'
def login(self, user, password_hash): """ Login function authenticate the user and creates a new session Args: user (str): login user name. password_hash (str): hashed password of the user. Returns: A session if successful, None otherwise. """ server_nonce = self.__get_server_nonce__(user) client_nonce = self.__generate_client_nonce__() sha256password = ''.join([ self.root, server_nonce, client_nonce, user, password_hash, ]).encode() sha256password = hashlib.sha256(sha256password).hexdigest().upper() url = "{}/{}/Auth?Username={}&Password={}&ClientNonce={}".format( self.base_url, self.root, user, sha256password, client_nonce) resp = requests.get(url) if resp.status_code == 200: self.session = Session(resp.json()['result'], password_hash) return self.session return None
def __init__(self, game): self.game = game # core variables # self.running = False # no point, is there? we have is_connected() and is_alive() # self.thread = None # instances are updated by their Game or Server if no game has been found yet self.session = Session() self.buffer = Buffer() # game information self.name = 'Test' #''.join([random.choice('0123456789abcdefghijlkmnopqrstuvwxyz') for i in range(8)]) self.last_x = 0 # last sent mouse X coordinate self.last_y = 0 # last sent mouse Y coordinate self.view_x = 0 # viewport x self.view_y = 0 # viewport y self.view_w = 0 # viewport width self.view_h = 0 # viewport height # our state self.has_sent_init = False self.last_sent_spawn = 0 self.last_update = 0 # cell information self.ids = [] # list of ids (to get cell, query id in all_cells) # no longer track cell ids self.ladder = [] self.mode = 'ffa'
def process_with_pcap_file(options): pcap = PcapHandler(options.pcap) ret = pcap.prepare_comparison_response() if ret is False: return 1 response_data = [] for stream in getattr(pcap, "request_data", []): parser = RequestParser(stream[PAYLOAD]) if parser.run() is False: return 1 session = Session() session.update_connection_info(method=getattr(parser, "method", "GET")) headers = getattr(parser, "headers", CaseInsensitiveDict()) session.update_headers(headers) session.update_body(getattr(parser, "body", "")) host = make_host(headers, stream[DST_IP]) request_url = make_request_url(host, 80, getattr(parser, "uri", "")) if session.send(request_url, verbose=False) is False: continue response = getattr(session, "response", None) start_line = ["HTTP/1.1", response.status_code] start_line += response.reason.split(" ") response_data.append((stream[DST_IP], stream[SRC_IP], start_line, response.headers, response.text)) pcap.comparison_response(response_data, options.verbose) return 0
def get_user(): sessao = Session() return jsonify({'success': "sucesso", 'usuarios': list(map(lambda x: x.to_json(), sessao.get_all_logged_user())), 'mensagens': [], 'status': 'Online' })