How to use _on_event method in Playwright Python

Best Python code snippet using playwright-python

helper.py

Source:helper.py Github

copy

Full Screen

...50 def decorator(f):51 self.add_handler(event, f, *args, **kwargs)52 return f53 return decorator54 def _on_event(self, event, *event_args, **event_kwargs):55 if event in self._event_handlers:56 for handler, args, kwargs in self._event_handlers[event]:57 handler(self, *args, *event_args, **kwargs, **event_kwargs)58 59 def set_train_routine(self, routine):60 self._train_routine = routine61 def set_test_routine(self, routine):62 self._test_routine = routine63 @property64 def train_routine(self):65 def decorator(f):66 self.set_train_routine(f)67 return f68 return decorator69 70 @property71 def test_routine(self):72 def decorator(f):73 self.set_test_routine(f)74 return f75 return decorator76 def train(self, dataloader, epochs=200):77 ''' helps the training process 78 Args: 79 dataloader (DataLoader): dataloader to use 80 epochs (int): number of epochs81 ''' 82 try:83 logger.info('[*] training started with max epochs of {}'.format(epochs))84 start = time.time()85 self._on_event(Events.STARTED)86 for epoch in range(epochs):87 self._on_event(Events.EPOCH_STARTED)88 train_loss = 089 for i, (data, label) in enumerate(dataloader): 90 self._on_event(Events.ITR_STARTED)91 train_loss += self._train_routine(self, data, label)92 self._on_event(Events.ITR_COMPLETED)93 progressbar(i, len(dataloader), 'epoch: {}/{} train loss:{:.4f} '.format(epoch+1, epochs, train_loss/(i+1)), '(time: {})'.format(str(timedelta(seconds=time.time()-start))))94 logger.debug('epoch: {}/{} train loss:{:.4f} '.format(epoch+1, epochs, train_loss/len(dataloader)))95 self._on_event(Events.EPOCH_COMPLETED, epoch=epoch)96 self._on_event(Events.COMPLETED)97 except BaseException as e:98 logger.error('[*] training terminated due to exception: {}'.format(str(e)))99 self._on_event(Events.EXCEPTION_RAISED, e) 100 def test(self, dataloader, weights=None):101 ''' helps the testing process102 Args: 103 dataloader (DataLoader): dataloader to use 104 weights (str): path to pretrained weights105 ''' 106 self.model.eval()107 if weights is not None:108 if os.path.exists(filename):109 self.model.load(filename)110 else:111 logger.error('[*] file not found: {}'.format(weights))112 raise FileNotFoundError113 try:114 logger.info('[*] testing started.')115 start = time.time()116 self._on_event(Events.STARTED)117 for i, (data, label) in enumerate(dataloader): 118 self._on_event(Events.ITR_STARTED)119 self._test_routine(self, data, label)120 self._on_event(Events.ITR_COMPLETED)121 progressbar(i, len(dataloader), )122 self._on_event(Events.COMPLETED)123 except BaseException as e:124 logger.error('[*] training terminated due to exception: {}'.format(str(e)))125 self._on_event(Events.EXCEPTION_RAISED, e) 126 def get_accuracy(self, data, label):127 output = self.model(data) 128 out = np.argmax(output.data, axis=1) 129 ans = np.argmax(label.data, axis=1)130 return sum(out == ans)/label.shape[0]131 def plot(self, losses, filename=None):132 plt.plot([i for i in range(len(losses))], losses)133 plt.title('training losses of {} in {}'.format(self.model_name, self.data_name))134 plt.ylabel('training loss')135 plt.xlabel('epochs')136 if filename is not None:137 plt.savefig(filename)138 else: 139 plt.show()

Full Screen

Full Screen

led.py

Source:led.py Github

copy

Full Screen

...18 def on_loaded(self):19 self._led_file = "/sys/class/leds/led%d/brightness" % self.options['led']20 self._delay = int(self.options['delay'])21 logging.info("[led] plugin loaded for %s" % self._led_file)22 self._on_event('loaded')23 _thread.start_new_thread(self._worker, ())24 def _on_event(self, event):25 if not self._is_busy:26 self._event_name = event27 self._event.set()28 logging.debug("[led] event '%s' set", event)29 else:30 logging.debug("[led] skipping event '%s' because the worker is busy", event)31 def _led(self, on):32 with open(self._led_file, 'wt') as fp:33 fp.write(str(on))34 def _blink(self, pattern):35 logging.debug("[led] using pattern '%s' ..." % pattern)36 for c in pattern:37 if c == ' ':38 self._led(1)39 else:40 self._led(0)41 time.sleep(self._delay / 1000.0)42 # reset43 self._led(0)44 def _worker(self):45 while True:46 self._event.wait()47 self._event.clear()48 self._is_busy = True49 try:50 if self._event_name in self.options['patterns']:51 pattern = self.options['patterns'][self._event_name]52 self._blink(pattern)53 else:54 logging.debug("[led] no pattern defined for %s" % self._event_name)55 except Exception as e:56 logging.exception("[led] error while blinking")57 finally:58 self._is_busy = False59 # called when the unit is updating its software60 def on_updating(self):61 self._on_event('updating')62 # called when there's one or more unread pwnmail messages63 def on_unread_inbox(self, num_unread):64 self._on_event('unread_inbox')65 # called when there's internet connectivity66 def on_internet_available(self, agent):67 self._on_event('internet_available')68 # called when everything is ready and the main loop is about to start69 def on_ready(self, agent):70 self._on_event('ready')71 # called when the AI finished loading72 def on_ai_ready(self, agent):73 self._on_event('ai_ready')74 # called when the AI starts training for a given number of epochs75 def on_ai_training_start(self, agent, epochs):76 self._on_event('ai_training_start')77 # called when the AI got the best reward so far78 def on_ai_best_reward(self, agent, reward):79 self._on_event('ai_best_reward')80 # called when the AI got the worst reward so far81 def on_ai_worst_reward(self, agent, reward):82 self._on_event('ai_worst_reward')83 # called when the status is set to bored84 def on_bored(self, agent):85 self._on_event('bored')86 # called when the status is set to sad87 def on_sad(self, agent):88 self._on_event('sad')89 # called when the status is set to excited90 def on_excited(self, agent):91 self._on_event('excited')92 # called when the status is set to lonely93 def on_lonely(self, agent):94 self._on_event('lonely')95 # called when the agent is rebooting the board96 def on_rebooting(self, agent):97 self._on_event('rebooting')98 # called when the agent is waiting for t seconds99 def on_wait(self, agent, t):100 self._on_event('wait')101 # called when the agent is sleeping for t seconds102 def on_sleep(self, agent, t):103 self._on_event('sleep')104 # called when the agent refreshed its access points list105 def on_wifi_update(self, agent, access_points):106 self._on_event('wifi_update')107 # called when the agent is sending an association frame108 def on_association(self, agent, access_point):109 self._on_event('association')110 # called when the agent is deauthenticating a client station from an AP111 def on_deauthentication(self, agent, access_point, client_station):112 self._on_event('deauthentication')113 # called when a new handshake is captured, access_point and client_station are json objects114 # if the agent could match the BSSIDs to the current list, otherwise they are just the strings of the BSSIDs115 def on_handshake(self, agent, filename, access_point, client_station):116 self._on_event('handshake')117 # called when an epoch is over (where an epoch is a single loop of the main algorithm)118 def on_epoch(self, agent, epoch, epoch_data):119 self._on_event('epoch')120 # called when a new peer is detected121 def on_peer_detected(self, agent, peer):122 self._on_event('peer_detected')123 # called when a known peer is lost124 def on_peer_lost(self, agent, peer):...

Full Screen

Full Screen

updatewindow.py

Source:updatewindow.py Github

copy

Full Screen

...40 def _disconnect_events(self):41 gdb.events.stop.disconnect(self._on_event)42 gui.event.frame_changed.disconnect(self._on_event)43 @in_gdb_thread44 def _on_event(self, *args):45 self.on_event()46 @in_gtk_thread47 def deleted(self, *args):48 gdb.post_event(self._disconnect_events)...

Full Screen

Full Screen

events.py

Source:events.py Github

copy

Full Screen

...24 index = handlers.index(handler_fn)25 handlers.pop(index)26 except ValueError:27 pass28def _on_event(typ, target, **kw):29 _check_type(typ)30 ref = target31 for handler in _event_handlers[typ]:32 result = handler(ref, **kw)33 if result is False:34 return False35 ref = result36 return ref37# Add/remove event handlers38def add_exception_info_handler(handler_fn, pos=None):39 _add_handler(EXCEPTION_INFO, handler_fn, pos)40def remove_exception_info_handler(handler_fn):41 _remove_handler(EXCEPTION_INFO, handler_fn)42def add_message_handler(handler_fn, pos=None):43 _add_handler(MESSAGE, handler_fn, pos)44def remove_message_handler(handler_fn):45 _remove_handler(MESSAGE, handler_fn)46def add_payload_handler(handler_fn, pos=None):47 _add_handler(PAYLOAD, handler_fn, pos)48def remove_payload_handler(handler_fn):49 _remove_handler(PAYLOAD, handler_fn)50# Event handler processing51def on_exception_info(exc_info, **kw):52 return _on_event(EXCEPTION_INFO, exc_info, **kw)53def on_message(message, **kw):54 return _on_event(MESSAGE, message, **kw)55def on_payload(payload, **kw):56 return _on_event(PAYLOAD, payload, **kw)57# Misc58def reset():59 for handlers in _event_handlers.values():...

Full Screen

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Python automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful