def testCodeGoogleRedirect(self): response = Handler( Request('chrome/extensions/storage.html', 'http://code.google.com', {})).Get() self.assertEqual(302, response.status) self.assertEqual('http://developer.chrome.com/extensions/storage.html', response.headers.get('Location'))
def init_bot(config, lang, token): global db global handler global bc # Initilizing db = Database(config) handler = Handler(lang) updater = Updater(token['botToken']) dp = updater.dispatcher bc = Broadcaster(db, updater.bot) print('Dating Bot started.') # Add message handlers dp.add_handler(CommandHandler('start', start)) dp.add_handler(CommandHandler('help', help)) dp.add_handler(MessageHandler(Filters.all, process)) dp.add_handler(CallbackQueryHandler(callback)) dp.add_error_handler(error) # Start broadcasting thread #bc.start() # Start bot updater.start_polling() updater.idle()
def predict_fn(data, model): if os.getenv(INFERENCE_ACCELERATOR_PRESENT_ENV) == "true": with torch.no_grad(): device = torch.device("cpu") model = model.to(device) input_data = data.to(device) model.eval() with torch.jit.optimized_execution(True, {"target_device": "eia:0"}): output = model(input_data) else: from handler import Handler hdlr = Handler() if not hdlr.initialized: hdlr.initialize(model=model) if data is None: return None output = hdlr.inference(data['noises'], data['labels']) return output
def _RunPublicTemplatesTest(self): base_path = os.path.join(BASE_PATH, 'docs', 'templates', 'public') if EXPLICIT_TEST_FILES is None: test_files = [] for path, dirs, files in os.walk(base_path): for dir_ in dirs: if dir_.startswith('.'): dirs.remove(dir_) for name in files: if name.startswith('.') or name == '404.html': continue test_files.append(os.path.join(path, name)[len(base_path + os.sep):]) else: test_files = EXPLICIT_TEST_FILES test_files = [f.replace(os.sep, '/') for f in test_files] failures = [] for filename in test_files: request = _MockRequest(filename) response = _MockResponse() try: Handler(request, response).get() if 200 != response.status: failures.append('%s does not have 200 status. Status was %d.' % (filename, response.status)) if not response.out.getvalue(): failures.append('Rendering %s produced no output.' % filename) if filename.endswith('samples.html'): self._TestSamplesLocales(filename, failures) except Exception as e: failures.append('Error rendering %s: %s' % (filename, e)) if failures: self.fail('\n'.join(failures))
def send_request(self): """Sends a request for connection with another computer, Initially sends the data to the database to obtain ip. Then creates a connection and starts the process""" try: iden = self.id_customer_text.toPlainText() pass_iden = self.id_customer_pass_text.toPlainText() server_connection = "Could Not Connect To Client" no_user = "******" invalid_input = "Invalid Input Given" db = IdBase() con, cust = db.get_id(iden, pass_iden) if con: try: self.socket.sendto(self.ip.encode('utf-8'), (cust, self.port)) handler = Handler(self.ip, self.new_port, cust, self.new_port, pass_iden) handler_thread = threading.Thread(target=handler.run) handler_thread.daemon = True handler_thread.start() self.close() except: self.dialog_window(server_connection, "Connection Failed") else: self.dialog_window(no_user, "Invalid User") except: self.dialog_window(invalid_input, "Invalid Input")
def get(self): profile_mode = self.request.get('profile') if profile_mode: import cProfile, pstats, StringIO pr = cProfile.Profile() pr.enable() try: request = Request(self.request.path, self.request.url[:-len(self.request.path)], self.request.headers) response = Handler(request).Get() finally: if profile_mode: pr.disable() s = StringIO.StringIO() pstats.Stats(pr, stream=s).sort_stats(profile_mode).print_stats() self.response.out.write(s.getvalue()) self.response.headers['Content-Type'] = 'text/plain' self.response.status = 200 else: self.response.out.write(response.content.ToString()) self.response.headers.update(response.headers) self.response.status = response.status
def __init__(self): super().__init__() self.__windowTitle = "Firepost VA" self.__defaultSize = QtCore.QSize(1080, 720) self.thumbnailDisplay = ThumbnailDisplay() self.detailDisplay = DetailDisplay() self.controlPanel = ControlPanel() self.handler = Handler() self.watcher = Watcher(["./stream_0"], self.handler) # connect handler to thumbnail display self.handler.tx_sendpathtime.connect(self.watcher.SendImage) self.watcher.sendImage.connect(self.thumbnailDisplay.rx_put_thumbnail) self.setup_mainWidget() # connect handler to detail display self.handler.tx_sendpathtime.connect( self.detailDisplay.rx_write_details) # connect controlPanel button to watcher self.controlPanel.toggle_monitor_button.clicked.connect( self.watcher.rxToggleObserver) # this should be the last step self.setup_dashboard()
def __init__(self): wx.Frame.__init__(self, parent=None, title='Multimeter', size=(1080, 720), pos=(243, 56), style=wx.DEFAULT_FRAME_STYLE ^ wx.RESIZE_BORDER) # ^ wx.MAXIMIZE_BOX) self.splitter = MultiSplitterWindow(self) self.splitter.SetOrientation(wx.VERTICAL) self.buttons = ButtonPanel(self.splitter) self.table_panel = TablePanel(self.splitter, self.buttons) self.input_panel = InputPanel(self.splitter) self.table_panel.Hide() self.input_panel.Hide() self.panel_handler = None self.graph_panel = False self.handler = Handler(self) self.buttons.handler = self.handler self.cont_measurement = True self.timer = wx.Timer(self) self.bind_buttons() self.buttons.get_button('Zastaviť meranie').Bind( wx.EVT_KILL_FOCUS, self.to_grid) self.buttons.get_button('Načítať meranie').Bind( wx.EVT_KILL_FOCUS, self.to_grid) self.ppg = None self.thread = None
def main(): app = BotCreator(os.environ["X_BOT_TOKEN"]) handler = Handler(logger=app.logger) app.config_handlers(handler) print("Running!") app.run()
def start(self): print('Server start') server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_socket.bind((config.HOST, config.PORT)) server_socket.listen(config.LISTENERS) for worker in range(self.ncpu): pid = os.fork() if pid: self.workers.append(pid) else: print('Run worker: {}'.format(os.getpid())) while True: client_socket, client_address = server_socket.accept() request = client_socket.recv(config.REQ_SIZE) if request.strip() == 0: client_socket.close() continue handler = Handler(self.root, request) response = handler.get_response() client_socket.sendall(response) client_socket.close() server_socket.close() for pid in self.workers: os.waitpid(pid, 0)
def input_fn(input_data, content_type): from handler import Handler hdlr = Handler() noises, labels = hdlr.preprocess(input_data, content_type) return {'noises': noises, 'labels': labels}
def __init__(self, settings): self.handler = Handler(self.handle_message) self.settings = settings self._prefix_re = re.compile( "(?P<nick>[^!]+)!(?P<user>[^@]+)@(?P<host>.+)") self._jid_re = re.compile( "(?P<node>[^@]+)@(?P<domain>[^/]+)(/(?P<resource>.+))?") self.jjc = JircJabberClient(settings.JABBER_JID, settings.JABBER_PASSWORD, server=settings.JABBER_SERVER, port=self.settings.get( 'JABBER_PORT', 5222)) self.jjc.set_handler(self.handler) self.jic = JircIrcClient() self.jic.set_handler(self.handler) self.jabber_channels = {} self.irc_channels = {} self.irc_users = {} self.jabber_users = {} self.irc_connected = False self.jabber_connected = False self.greenlets = [] for channel in self.settings.CHANNELS: self.jabber_channels[channel['irc']] = channel['jabber'] self.irc_channels[channel['jabber']] = channel['irc']
def _HandleRequest(self): profile_mode = self.request.get('profile') if profile_mode: import cProfile, pstats, StringIO pr = cProfile.Profile() pr.enable() try: response = None arguments = {} for argument in self.request.arguments(): arguments[argument] = self.request.get(argument) request = Request(self.request.path, self.request.host, self.request.headers, arguments) response = Handler(request).Get() except Exception as e: logging.exception(e) finally: if profile_mode: pr.disable() s = StringIO.StringIO() pstats.Stats(pr, stream=s).sort_stats(profile_mode).print_stats() self.response.out.write(s.getvalue()) self.response.headers['Content-Type'] = 'text/plain' self.response.status = 200 elif response: self.response.out.write(response.content.ToString()) self.response.headers.update(response.headers) self.response.status = response.status else: self.response.out.write('Internal server error') self.response.status = 500
def __init__(self): '''Initialises the game object: Creates game window Creates game locations Creates player objects Sets current player''' self.__training = False ###~~~Creating a file handler~~~### self.__handler = Handler() ###~~~Settings up the game~~~### center = [(x, y) for x in range(-4, 5) for y in range(-4, 5)] triangle1 = [(x - 4, y + 5) for x in range(0, 5) for y in range(4 - x)] triangle3 = [(x + 5, y - 4) for x in range(0, 5) for y in range(4 - x)] triangle5 = [(x - 4, y - 4) for x in range(0, 5) for y in range(4 - x)] triangle2 = [(-x + 4, y + 1) for x in range(0, 4) for y in range(x, 4)] triangle4 = [(-x + 4, y - 8) for x in range(0, 4) for y in range(x, 4)] triangle6 = [(-x - 5, y + 1) for x in range(0, 4) for y in range(x, 4)] self.__locations = center + triangle1 + triangle3 + triangle4 + triangle6 #Triangles 2 and 5 are contained in the centre self.__ending_triangles = [ triangle4, triangle5, triangle6, triangle1, triangle2, triangle3 ] #Triangle 1 aims for triangle 4 and so on self.__triangle_order = [ triangle1, triangle2, triangle3, triangle4, triangle5, triangle6 ] self.__mouse_location = None
def init_app(root, logger): abs_root = abspath(root) node = root_node(abs_root) URLS = ('/(.*)', 'handler') return application(URLS, {'handler': Handler(node, logger)})
def run(addr, port, root_dir, worker, maxbuff): workers = [] server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) server_socket.bind((addr, port)) server_socket.listen() for i in range(worker): pid = os.fork() if pid != 0: workers.append(pid) else: while True: try: client_socket, addr = server_socket.accept() except IOError as e: if e.errno == errno.EINTR: continue raise request = read_all(client_socket, maxbuff) if len(request.strip()) == 0: client_socket.close() continue handler = Handler(request, root_dir) if request: response = handler.generate_response(request.decode()) client_socket.sendall(response) client_socket.close() server_socket.close() for pid in workers: os.waitpid(pid, 0)
def output_fn(prediction, accept): from handler import Handler hdlr = Handler() encoded_prediction = hdlr.postprocess(prediction, accept) return encoded_prediction
def testCronAndPublicFiles(self): '''Runs cron then requests every public file. Cron needs to be run first because the public file requests are offline. ''' if _EXPLICIT_TEST_FILES is not None: return print('Running cron...') start_time = time.time() try: response = Handler(Request.ForTest('/_cron/stable')).Get() self.assertEqual(200, response.status) self.assertEqual('Success', response.content.ToString()) finally: print('Took %s seconds' % (time.time() - start_time)) public_files = _GetPublicFiles() print('Rendering %s public files...' % len(public_files.keys())) start_time = time.time() try: for path, content in public_files.iteritems(): def check_result(response): self.assertEqual( 200, response.status, 'Got %s when rendering %s' % (response.status, path)) # This is reaaaaally rough since usually these will be tiny templates # that render large files. At least it'll catch zero-length responses. self.assertTrue( len(response.content) >= len(content), 'Content was "%s" when rendering %s' % (response.content, path)) check_result(Handler(Request.ForTest(path)).Get()) # Samples are internationalized, test some locales. if path.endswith('/samples.html'): for lang in ['en-US', 'es', 'ar']: check_result( Handler( Request.ForTest(path, headers={ 'Accept-Language': '%s;q=0.8' % lang })).Get()) finally: print('Took %s seconds' % (time.time() - start_time))
def main(): global CURRENT_UNHANDLER_TRAJECTORY values.TRAJECTORIES = load_trajectories(PICKLED_TRAJECTORIES_FILE) for i in range(HANDLERS_COUNT): values.HANDLERS.append( Handler( first_node= values.TRAJECTORIES[i].get_first_node(), nodes_per_time=NODES_PER_TIME, update=first_update, average=first_average, with_cache=True, ), ) values.TRAJECTORIES[i].is_handled = True CURRENT_UNHANDLER_TRAJECTORY += 1 ## main loop print("trajectories before %s" % len(values.TRAJECTORIES)) for k in range(100): i = 0 while i < len(values.HANDLERS): h: Handler = values.HANDLERS[i] h.handle() i += 1 # filter out the hanlders you need to delete after handling a trajectory values.HANDLERS = list(filter(lambda x: not x.delete_after_trajectory, values.HANDLERS)) for i in values.HANDLERS: if i.blocked and CURRENT_UNHANDLER_TRAJECTORY < len(values.TRAJECTORIES): i.start_new_trajectory(values.TRAJECTORIES[CURRENT_UNHANDLER_TRAJECTORY].get_first_node()) CURRENT_UNHANDLER_TRAJECTORY += 1 cnt = 0 for i in values.TRAJECTORIES: if type(i) is Trajectory: cnt += 1 print("trajectories after %s" % cnt) print('Exchanges count %s' % values.COUNT_EXCHANGED) print('Merges count %s ' % values.COUNT_MERGES) print('Created handlers %s' % values.COUNT_CREATED_HANDLERS) t = filter(lambda x: type(x) is Trajectory, values.TRAJECTORIES) pagerank = find_page_rank(t) print("PAGERANK") errors = find_mean_error(pagerank) print(errors) print("DEVIATION") d = 0 for i in errors: d += abs(1 - i[1]) d /= len(errors) print(d)
def setUpClass(cls): os.environ[ "GOOGLE_APPLICATION_CREDENTIALS"] = "../src/firebase_creds.json" os.environ["DB_HOST"] = properties.db_host os.environ["DB_USERNAME"] = properties.db_username os.environ["DB_PASSWORD"] = properties.db_password os.environ["DB_DATABASE_NAME"] = properties.db_database_name cls.handler = Handler(ManagerImpl(FirebaseClientImpl(), DaoImpl()))
def get(self): request = Request(self.request.path, self.request.url[:-len(self.request.path)], self.request.headers) response = Handler(request).Get() self.response.out.write(response.content.ToString()) self.response.headers.update(response.headers) self.response.status = response.status
def controller(request): try: handler = Handler(request) return handler.apply() except Exception as e: logger.exception('GET: Inventories Exception: {}'.format(e)) raise e
def stdin(ctx): """Get email for Bounced Email Service from stdin""" from handler import Handler lines = sys.stdin.readlines() body = "".join(lines).strip().encode('utf-8') handler = Handler(ctx.obj) handler.handle_message(body)
def __init__(self): directories = { "English": "data/lang/English/", "German": "data/lang/German/", "Polish": "data/lang/Polish/" } self.handler = Handler(directories) self.initializeMenu()
async def numbers(request): number = request.match_info.get('number') if number is not None and (not number.isdigit() or int(number) < 50 or int(number) > 1000): raise web.HTTPBadRequest() numbers = list(range(50, 1001)) if request.match_info.get('number') is None else [request.match_info.get('number')] handler = Handler(API_URL, asyncio.get_event_loop(), request.method) await handler.handle(numbers) return web.Response(text=''.join([str(item) for item in handler.output]))
def __init__(self): """ MultiJob constructor """ self._jobs = {} self.client = APIClient(opts=MASTER_OPTIONS) self.handler = Handler()
def main(): if not is_root(): print("Rescuezilla must run as root.") exit(0) gettext_translation_search_path = sys.base_prefix + "/share/locale/{LANGUAGE,LC_ALL,LC_MESSAGES,LANG}/LC_MESSAGES/rescuezilla.mo" print("Setting GTK translation domain by searching: " + gettext_translation_search_path) # Set the translation domain folder: gettext.bindtextdomain('rescuezilla') # Query the translation gettext.textdomain('rescuezilla') builder = Gtk.Builder() builder.set_translation_domain('rescuezilla') # Use the GTKBuilder to dynamically construct all the UI widget objects as defined in the GTKBuilder .glade XML # file. This file may be edited using the Glade UI widget editor. It is sometimes required to edit the XML # directly a text editor, because Glade occasionally has some user-interface limitations. builder.add_from_file("/usr/share/rescuezilla/rescuezilla.glade") handler = Handler(builder) # Connect the handler object for the GUI callbacks. This handler manages the entire application state. builder.connect_signals(handler) # Do not show the GTKNotebook tab menu. For each mode (including mode selection), the pages of the wizard are # achieved through a GTKNotebook, which is a tabbed container that provides a function to switch between pages in # the wizard. The tab menu itself is useful when viewing and editing the GUI with Glade, but should not be # displayed to end-users because the application design relies on users not being able to skip steps. builder.get_object("mode_tabs").set_show_tabs(False) builder.get_object("backup_tabs").set_show_tabs(False) builder.get_object("restore_tabs").set_show_tabs(False) builder.get_object("verify_tabs").set_show_tabs(False) builder.get_object("clone_tabs").set_show_tabs(False) builder.get_object("image_explorer_tabs").set_show_tabs(False) # Display the main GTK window win = builder.get_object("main_window") win.show() nbd_module_missing_msg = "The 'nbd' (Network Block Device) kernel module is not loaded.\n\nRescuezilla will load it with modprobe, but it appears to take time to fully initialize.\n\nFor the best experience, add 'nbd' to /etc/modules and reboot before using Rescuezilla." process, flat_command_string, fail_description = Utility.run("Querying for NBD module", ["lsmod"], use_c_locale=True) if "nbd" not in process.stdout: GLib.idle_add(ErrorMessageModalPopup.display_nonfatal_warning_message, builder, nbd_module_missing_msg) # Set the background color of the Rescuezilla banner box (using CSS) [1] to the same dark blue background color # used by the fixed-sized banner image, so that the banner looks good even when resizing the window. # [1] Adapted from: https://github.com/zim-desktop-wiki/zim-desktop-wiki/blob/master/zim/gui/widgets.py banner_image_eventbox = builder.get_object("banner_image_eventbox") # Set the custom CSS using the GTK 'name' attribute (note this is different to the 'id' attribute) css_text = '#banner { background-color: #345278; }' css_provider = Gtk.CssProvider() css_provider.load_from_data(css_text.encode('UTF-8')) banner_style = banner_image_eventbox.get_style_context() banner_style.add_provider(css_provider, Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION) # Starts the GTK event loop. As with other user-interface libraries, the GTK event loop is single-threaded. This # GTK loop simply reads a queue of events (mouse click on button, timeout of a countdown timer), and executes the # handler functions that were registered earlier. To exit the main loop, a handler function can run Gtk.main_quit(). Gtk.main()
def run(self, portNumber = 9090): handler = Handler() processor = GraphCRUD.Processor(handler) transport = TSocket.TServerSocket(port=portNumber) tfactory = TTransport.TBufferedTransportFactory() pfactory = TBinaryProtocol.TBinaryProtocolFactory() server = TServer.TThreadPoolServer(processor, transport, tfactory, pfactory) server.serve()
def run(self): while True: try: self.stats['connections'] += 1 client, address = self.server.accept() Handler(client, self.queue_collection, self.stats).start() self.stats['connections'] -= 1 except socket.error, e: sys.exit(1)
def __init__(self): self.__schedule = Schedule() self.__vk = vk_api.VkApi(token=token) self.__vk_api = self.__vk.get_api() self.__longpoll = VkLongPoll(self.__vk) self.__database = Database() self.__handler = Handler(self.__database, self.__schedule)