How to use roundBox method in Playwright Internal

Best JavaScript code snippet using playwright-internal

autoreload.py

Source:autoreload.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2# This library is heavy inspired by the Django reload module3# Praise the OpenSource and devs from Django framework and the community4# url: https://github.com/django/django/blob/main/django/utils/autoreload.py5import functools6import itertools7import logging8import os9import signal10import subprocess11import sys12import threading13import time14import traceback15import weakref16from collections import defaultdict17from pathlib import Path18from types import ModuleType19from zipimport import zipimporter20import RoundBox21from RoundBox.apps import apps22from RoundBox.core.signals import request_finished23from RoundBox.dispatch import Signal24from RoundBox.utils.functional import cached_property25from RoundBox.utils.version import get_version_tuple26autoreload_started = Signal()27file_changed = Signal()28ROUNDBOX_AUTORELOAD_ENV = "RUN_MAIN"29logger = logging.getLogger("RoundBox.utils.autoreload")30# If an error is raised while importing a file, it's not placed in sys.modules.31# This means that any future modifications aren't caught. Keep a list of these32# file paths to allow watching them in the future.33_error_files = []34_exception = None35try:36 import termios37except ImportError:38 termios = None39try:40 import pywatchman41except ImportError:42 pywatchman = None43def is_roundbox_module(module):44 """Return True if the given module is nested under RoundBox.45 :param module:46 :return:47 """48 return module.__name__.startswith("RoundBox.")49def is_roundbox_path(path):50 """Return True if the given file path is nested under RoundBox.51 :param path:52 :return:53 """54 return Path(RoundBox.__file__).parent in Path(path).parents55def check_errors(fn):56 """57 :param fn:58 :return:59 """60 @functools.wraps(fn)61 def wrapper(*args, **kwargs):62 global _exception63 try:64 fn(*args, **kwargs)65 except Exception:66 _exception = sys.exc_info()67 et, ev, tb = _exception68 if getattr(ev, "filename", None) is None:69 # get the filename from the last item in the stack70 filename = traceback.extract_tb(tb)[-1][0]71 else:72 filename = ev.filename73 if filename not in _error_files:74 _error_files.append(filename)75 print(_error_files)76 raise77 return wrapper78def raise_last_exception():79 global _exception80 if _exception is not None:81 raise _exception[1]82def ensure_echo_on():83 """84 Ensure that echo mode is enabled. Some tools such as PDB disable85 it which causes usability issues after reload.86 """87 if not termios or not sys.stdin.isatty():88 return89 attr_list = termios.tcgetattr(sys.stdin)90 if not attr_list[3] & termios.ECHO:91 attr_list[3] |= termios.ECHO92 if hasattr(signal, "SIGTTOU"):93 old_handler = signal.signal(signal.SIGTTOU, signal.SIG_IGN)94 else:95 old_handler = None96 termios.tcsetattr(sys.stdin, termios.TCSANOW, attr_list)97 if old_handler is not None:98 signal.signal(signal.SIGTTOU, old_handler)99def iter_all_python_module_files():100 # This is a hot path during reloading. Create a stable sorted list of101 # modules based on the module name and pass it to iter_modules_and_files().102 # This ensures cached results are returned in the usual case that modules103 # aren't loaded on the fly.104 keys = sorted(sys.modules)105 modules = tuple(106 m for m in map(sys.modules.__getitem__, keys) if not isinstance(m, weakref.ProxyTypes)107 )108 return iter_modules_and_files(modules, frozenset(_error_files))109@functools.lru_cache(maxsize=1)110def iter_modules_and_files(modules, extra_files):111 """Iterate through all modules needed to be watched."""112 sys_file_paths = []113 for module in modules:114 # During debugging (with PyDev) the 'typing.io' and 'typing.re' objects115 # are added to sys.modules, however they are types not modules and so116 # cause issues here.117 if not isinstance(module, ModuleType):118 continue119 if module.__name__ in ("__main__", "__mp_main__"):120 # __main__ (usually manage.py) doesn't always have a __spec__ set.121 # Handle this by falling back to using __file__, resolved below.122 # See https://docs.python.org/reference/import.html#main-spec123 # __file__ may not exists, e.g. when running ipdb debugger.124 if hasattr(module, "__file__"):125 sys_file_paths.append(module.__file__)126 continue127 if getattr(module, "__spec__", None) is None:128 continue129 spec = module.__spec__130 # Modules could be loaded from places without a concrete location. If131 # this is the case, skip them.132 if spec.has_location:133 origin = spec.loader.archive if isinstance(spec.loader, zipimporter) else spec.origin134 sys_file_paths.append(origin)135 results = set()136 for filename in itertools.chain(sys_file_paths, extra_files):137 if not filename:138 continue139 path = Path(filename)140 try:141 if not path.exists():142 # The module could have been removed, don't fail loudly if this143 # is the case.144 continue145 except ValueError as e:146 # Network filesystems may return null bytes in file paths.147 logger.debug('"%s" raised when resolving path: "%s"', e, path)148 continue149 resolved_path = path.resolve().absolute()150 results.add(resolved_path)151 return frozenset(results)152@functools.lru_cache(maxsize=1)153def common_roots(paths):154 """155 Return a tuple of common roots that are shared between the given paths.156 File system watchers operate on directories and aren't cheap to create.157 Try to find the minimum set of directories to watch that encompass all of158 the files that need to be watched. 22957159 """160 # Inspired from Werkzeug:161 # https://github.com/pallets/werkzeug/blob/7477be2853df70a022d9613e765581b9411c3c39/werkzeug/_reloader.py162 # Create a sorted list of the path components, longest first.163 path_parts = sorted([x.parts for x in paths], key=len, reverse=True)164 tree = {}165 for chunks in path_parts:166 node = tree167 # Add each part of the path to the tree.168 for chunk in chunks:169 node = node.setdefault(chunk, {})170 # Clear the last leaf in the tree.171 node.clear()172 # Turn the tree into a list of Path instances.173 def _walk(node, path):174 for prefix, child in node.items():175 yield from _walk(child, path + (prefix,))176 if not node:177 yield Path(*path)178 return tuple(_walk(tree, ()))179def sys_path_directories():180 """181 Yield absolute directories from sys.path, ignoring entries that don't182 exist.183 """184 for path in sys.path:185 path = Path(path)186 if not path.exists():187 continue188 resolved_path = path.resolve().absolute()189 # If the path is a file (like a zip file), watch the parent directory.190 if resolved_path.is_file():191 yield resolved_path.parent192 else:193 yield resolved_path194def get_child_arguments():195 """196 Return the executable. This contains a workaround for Windows if the197 executable is reported to not have the .exe extension which can cause bugs198 on reloading.199 """200 import __main__201 py_script = Path(sys.argv[0])202 args = [sys.executable] + ["-W%s" % o for o in sys.warnoptions]203 if sys.implementation.name == "cpython":204 args.extend(205 f"-X{key}" if value is True else f"-X{key}={value}"206 for key, value in sys._xoptions.items()207 )208 # __spec__ is set when the server was started with the `-m` option,209 # see https://docs.python.org/3/reference/import.html#main-spec210 # __spec__ may not exist, e.g. when running in a Conda env.211 if getattr(__main__, "__spec__", None) is not None:212 spec = __main__.__spec__213 if (spec.name == "__main__" or spec.name.endswith(".__main__")) and spec.parent:214 name = spec.parent215 else:216 name = spec.name217 args += ["-m", name]218 args += sys.argv[1:]219 elif not py_script.exists():220 # sys.argv[0] may not exist for several reasons on Windows.221 # It may exist with a .exe extension or have a -script.py suffix.222 exe_entrypoint = py_script.with_suffix(".exe")223 if exe_entrypoint.exists():224 # Should be executed directly, ignoring sys.executable.225 return [exe_entrypoint, *sys.argv[1:]]226 script_entrypoint = py_script.with_name("%s-script.py" % py_script.name)227 if script_entrypoint.exists():228 # Should be executed as usual.229 return [*args, script_entrypoint, *sys.argv[1:]]230 raise RuntimeError("Script %s does not exist." % py_script)231 else:232 args += sys.argv233 return args234def trigger_reload(filename):235 logger.info("%s changed, reloading.", filename)236 sys.exit(3)237def restart_with_reloader():238 new_environ = {**os.environ, ROUNDBOX_AUTORELOAD_ENV: "true"}239 args = get_child_arguments()240 while True:241 p = subprocess.run(args, env=new_environ, close_fds=False)242 if p.returncode != 3:243 return p.returncode244class BaseReloader:245 def __init__(self):246 """ """247 self.extra_files = set()248 self.directory_globs = defaultdict(set)249 self._stop_condition = threading.Event()250 def watch_dir(self, path, glob):251 """252 :param path:253 :param glob:254 :return:255 """256 path = Path(path)257 try:258 path = path.absolute()259 except FileNotFoundError:260 logger.debug(261 "Unable to watch directory %s as it cannot be resolved.",262 path,263 exc_info=True,264 )265 return266 logger.debug("Watching dir %s with glob %s.", path, glob)267 self.directory_globs[path].add(glob)268 def watched_files(self, include_globs=True):269 """Yield all files that need to be watched, including module files and270 files within globs.271 :param include_globs:272 :return:273 """274 yield from iter_all_python_module_files()275 yield from self.extra_files276 if include_globs:277 for directory, patterns in self.directory_globs.items():278 for pattern in patterns:279 yield from directory.glob(pattern)280 def wait_for_apps_ready(self, app_reg, roundbox_main_thread):281 """Wait until RoundBox reports that the apps have been loaded. If the given282 thread has terminated before the apps are ready, then a SyntaxError or283 other non-recoverable error has been raised. In that case, stop waiting284 for the apps_ready event and continue processing.285 Return True if the thread is alive and the ready event has been286 triggered, or False if the thread is terminated while waiting for the287 event.288 :param app_reg:289 :param roundbox_main_thread:290 :return:291 """292 while roundbox_main_thread.is_alive():293 if app_reg.ready_event.wait(timeout=0.1):294 return True295 else:296 logger.debug("Main RoundBox thread has terminated before apps are ready.")297 return False298 def run(self, roundbox_main_thread):299 """300 :param roundbox_main_thread:301 :return:302 """303 logger.debug("Waiting for apps ready_event.")304 self.wait_for_apps_ready(apps, roundbox_main_thread)305 logger.debug("Apps ready_event triggered. Sending autoreload_started signal.")306 autoreload_started.send(sender=self)307 self.run_loop()308 def run_loop(self):309 ticker = self.tick()310 while not self.should_stop:311 try:312 next(ticker)313 except StopIteration:314 break315 self.stop()316 def tick(self):317 """This generator is called in a loop from run_loop. It's important that318 the method takes care of pausing or otherwise waiting for a period of319 time. This split between run_loop() and tick() is to improve the320 testability of the reloader implementations by decoupling the work they321 do from the loop.322 :return:323 """324 raise NotImplementedError("subclasses must implement tick().")325 @classmethod326 def check_availability(cls):327 """328 :return:329 """330 raise NotImplementedError("subclasses must implement check_availability().")331 def notify_file_changed(self, path):332 """333 :param path:334 :return:335 """336 results = file_changed.send(sender=self, file_path=path)337 logger.debug("%s notified as changed. Signal results: %s.", path, results)338 if not any(res[1] for res in results):339 trigger_reload(path)340 # These are primarily used for testing.341 @property342 def should_stop(self):343 return self._stop_condition.is_set()344 def stop(self):345 self._stop_condition.set()346class StatReloader(BaseReloader):347 SLEEP_TIME = 1 # Check for changes once per second.348 def tick(self):349 mtimes = {}350 while True:351 for filepath, mtime in self.snapshot_files():352 old_time = mtimes.get(filepath)353 mtimes[filepath] = mtime354 if old_time is None:355 logger.debug("File %s first seen with mtime %s", filepath, mtime)356 continue357 elif mtime > old_time:358 logger.debug(359 "File %s previous mtime: %s, current mtime: %s",360 filepath,361 old_time,362 mtime,363 )364 self.notify_file_changed(filepath)365 time.sleep(self.SLEEP_TIME)366 yield367 def snapshot_files(self):368 """watched_files may produce duplicate paths if globs overlap369 :return:370 """371 seen_files = set()372 for file in self.watched_files():373 if file in seen_files:374 continue375 try:376 mtime = file.stat().st_mtime377 except OSError:378 # This is thrown when the file does not exist.379 continue380 seen_files.add(file)381 yield file, mtime382 @classmethod383 def check_availability(cls):384 return True385class WatchmanUnavailable(RuntimeError):386 pass387class WatchmanReloader(BaseReloader):388 def __init__(self):389 self.roots = defaultdict(set)390 self.processed_request = threading.Event()391 self.client_timeout = int(os.environ.get("ROUNDBOX_WATCHMAN_TIMEOUT", 5))392 super().__init__()393 @cached_property394 def client(self):395 return pywatchman.client(timeout=self.client_timeout)396 def _watch_root(self, root):397 # In practice this shouldn't occur, however, it's possible that a398 # directory that doesn't exist yet is being watched. If it's outside of399 # sys.path then this will end up a new root. How to handle this isn't400 # clear: Not adding the root will likely break when subscribing to the401 # changes, however, as this is currently an internal API, no files402 # will be being watched outside of sys.path. Fixing this by checking403 # inside watch_glob() and watch_dir() is expensive, instead this could404 # could fall back to the StatReloader if this case is detected? For405 # now, watching its parent, if possible, is sufficient.406 if not root.exists():407 if not root.parent.exists():408 logger.warning(409 "Unable to watch root dir %s as neither it or its parent exist.",410 root,411 )412 return413 root = root.parent414 result = self.client.query("watch-project", str(root.absolute()))415 if "warning" in result:416 logger.warning("Watchman warning: %s", result["warning"])417 logger.debug("Watchman watch-project result: %s", result)418 return result["watch"], result.get("relative_path")419 @functools.lru_cache420 def _get_clock(self, root):421 return self.client.query("clock", root)["clock"]422 def _subscribe(self, directory, name, expression):423 root, rel_path = self._watch_root(directory)424 # Only receive notifications of files changing, filtering out other types425 # like special files: https://facebook.github.io/watchman/docs/type426 only_files_expression = [427 "allof",428 ["anyof", ["type", "f"], ["type", "l"]],429 expression,430 ]431 query = {432 "expression": only_files_expression,433 "fields": ["name"],434 "since": self._get_clock(root),435 "dedup_results": True,436 }437 if rel_path:438 query["relative_root"] = rel_path439 logger.debug(440 "Issuing watchman subscription %s, for root %s. Query: %s",441 name,442 root,443 query,444 )445 self.client.query("subscribe", root, name, query)446 def _subscribe_dir(self, directory, filenames):447 if not directory.exists():448 if not directory.parent.exists():449 logger.warning(450 "Unable to watch directory %s as neither it or its parent exist.",451 directory,452 )453 return454 prefix = "files-parent-%s" % directory.name455 filenames = ["%s/%s" % (directory.name, filename) for filename in filenames]456 directory = directory.parent457 expression = ["name", filenames, "wholename"]458 else:459 prefix = "files"460 expression = ["name", filenames]461 self._subscribe(directory, "%s:%s" % (prefix, directory), expression)462 def _watch_glob(self, directory, patterns):463 """464 Watch a directory with a specific glob. If the directory doesn't yet465 exist, attempt to watch the parent directory and amend the patterns to466 include this. It's important this method isn't called more than one per467 directory when updating all subscriptions. Subsequent calls will468 overwrite the named subscription, so it must include all possible glob469 expressions.470 """471 prefix = "glob"472 if not directory.exists():473 if not directory.parent.exists():474 logger.warning(475 "Unable to watch directory %s as neither it or its parent exist.",476 directory,477 )478 return479 prefix = "glob-parent-%s" % directory.name480 patterns = ["%s/%s" % (directory.name, pattern) for pattern in patterns]481 directory = directory.parent482 expression = ["anyof"]483 for pattern in patterns:484 expression.append(["match", pattern, "wholename"])485 self._subscribe(directory, "%s:%s" % (prefix, directory), expression)486 def watched_roots(self, watched_files):487 extra_directories = self.directory_globs.keys()488 watched_file_dirs = [f.parent for f in watched_files]489 sys_paths = list(sys_path_directories())490 return frozenset((*extra_directories, *watched_file_dirs, *sys_paths))491 def _update_watches(self):492 watched_files = list(self.watched_files(include_globs=False))493 found_roots = common_roots(self.watched_roots(watched_files))494 logger.debug("Watching %s files", len(watched_files))495 logger.debug("Found common roots: %s", found_roots)496 # Setup initial roots for performance, shortest roots first.497 for root in sorted(found_roots):498 self._watch_root(root)499 for directory, patterns in self.directory_globs.items():500 self._watch_glob(directory, patterns)501 # Group sorted watched_files by their parent directory.502 sorted_files = sorted(watched_files, key=lambda p: p.parent)503 for directory, group in itertools.groupby(sorted_files, key=lambda p: p.parent):504 # These paths need to be relative to the parent directory.505 self._subscribe_dir(directory, [str(p.relative_to(directory)) for p in group])506 def update_watches(self):507 try:508 self._update_watches()509 except Exception as ex:510 # If the service is still available, raise the original exception.511 if self.check_server_status(ex):512 raise513 def _check_subscription(self, sub):514 subscription = self.client.getSubscription(sub)515 if not subscription:516 return517 logger.debug("Watchman subscription %s has results.", sub)518 for result in subscription:519 # When using watch-project, it's not simple to get the relative520 # directory without storing some specific state. Store the full521 # path to the directory in the subscription name, prefixed by its522 # type (glob, files).523 root_directory = Path(result["subscription"].split(":", 1)[1])524 logger.debug("Found root directory %s", root_directory)525 for file in result.get("files", []):526 self.notify_file_changed(root_directory / file)527 def request_processed(self, **kwargs):528 logger.debug("Request processed. Setting update_watches event.")529 self.processed_request.set()530 def tick(self):531 request_finished.connect(self.request_processed)532 self.update_watches()533 while True:534 if self.processed_request.is_set():535 self.update_watches()536 self.processed_request.clear()537 try:538 self.client.receive()539 except pywatchman.SocketTimeout:540 pass541 except pywatchman.WatchmanError as ex:542 logger.debug("Watchman error: %s, checking server status.", ex)543 self.check_server_status(ex)544 else:545 for sub in list(self.client.subs.keys()):546 self._check_subscription(sub)547 yield548 # Protect against busy loops.549 time.sleep(0.1)550 def stop(self):551 self.client.close()552 super().stop()553 def check_server_status(self, inner_ex=None):554 """Return True if the server is available."""555 try:556 self.client.query("version")557 except Exception:558 raise WatchmanUnavailable(str(inner_ex)) from inner_ex559 return True560 @classmethod561 def check_availability(cls):562 if not pywatchman:563 raise WatchmanUnavailable("pywatchman not installed.")564 client = pywatchman.client(timeout=0.1)565 try:566 result = client.capabilityCheck()567 except Exception:568 # The service is down?569 raise WatchmanUnavailable("Cannot connect to the watchman service.")570 version = get_version_tuple(result["version"])571 # Watchman 4.9 includes multiple improvements to watching project572 # directories as well as case insensitive filesystems.573 logger.debug("Watchman version %s", result["version"])574 if version < (4, 9):575 raise WatchmanUnavailable("Watchman 4.9 or later is required.")576def get_reloader():577 """Return the most suitable reloader for this environment."""578 try:579 WatchmanReloader.check_availability()580 except WatchmanUnavailable:581 return StatReloader()582 return WatchmanReloader()583def start_roundbox(reloader, main_func, *args, **kwargs):584 """585 :param reloader:586 :param main_func:587 :param args:588 :param kwargs:589 :return:590 """591 ensure_echo_on()592 main_func = check_errors(main_func)593 roundbox_main_thread = threading.Thread(594 target=main_func, args=args, kwargs=kwargs, name="roundbox-main-thread"595 )596 roundbox_main_thread.daemon = True597 roundbox_main_thread.start()598 while not reloader.should_stop:599 try:600 reloader.run(roundbox_main_thread)601 except WatchmanUnavailable as ex:602 # It's possible that the watchman service shuts down or otherwise603 # becomes unavailable. In that case, use the StatReloader.604 reloader = StatReloader()605 logger.error("Error connecting to Watchman: %s", ex)606 logger.info("Watching for file changes with %s", reloader.__class__.__name__)607def run_with_reloader(main_func, *args, **kwargs):608 """609 :param main_func:610 :param args:611 :param kwargs:612 :return:613 """614 signal.signal(signal.SIGTERM, lambda *args: sys.exit(0))615 try:616 if os.environ.get(ROUNDBOX_AUTORELOAD_ENV) == "true":617 reloader = get_reloader()618 logger.info("Watching for file changes with %s", reloader.__class__.__name__)619 start_roundbox(reloader, main_func, *args, **kwargs)620 else:621 exit_code = restart_with_reloader()622 sys.exit(exit_code)623 except KeyboardInterrupt:...

Full Screen

Full Screen

__init__.py

Source:__init__.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2# This library is heavy inspired by the Django management core module.3# Praise the OpenSource and devs from Django framework and the community4# url: https://github.com/django/django/tree/main/django/core/management5import functools6import os7import pkgutil8import sys9from collections import defaultdict10from difflib import get_close_matches11from importlib import import_module12import RoundBox13from RoundBox.apps import apps14from RoundBox.conf.project_settings import settings15from RoundBox.const import __version__16from RoundBox.core.cliparser.base import (17 BaseCommand,18 CommandError,19 CommandParser,20 handle_default_options,21)22from RoundBox.core.cliparser.color import color_style23from RoundBox.core.exceptions import ImproperlyConfigured24from RoundBox.utils import autoreload25def find_commands(cliparser_dir):26 """27 Given a path to a management directory, return a list of all the command28 names that are available.29 """30 command_dir = os.path.join(cliparser_dir, "commands")31 return [32 name33 for _, name, is_pkg in pkgutil.iter_modules([command_dir])34 if not is_pkg and not name.startswith("_")35 ]36def load_command_class(app_name, name):37 """38 Given a command name and an application name, return the Command39 class instance. Allow all errors raised by the import process40 (ImportError, AttributeError) to propagate.41 """42 module = import_module("%s.cliparser.commands.%s" % (app_name, name))43 return module.Command()44@functools.lru_cache(maxsize=None)45def get_commands():46 """Return the script's main help text, as a string.47 Look for a cliparser.commands package in RoundBox.core, and in each48 installed application -- if a commands package exists, register all49 commands in that package.50 Core commands are always included. If a settings module has been51 specified, also include user-defined commands.52 The dictionary is in the format {command_name: app_name}. Key-value53 pairs from this dictionary can then be used in calls to54 load_command_class(app_name, command_name)55 The dictionary is cached on the first call and reused on subsequent56 calls.57 :return:58 """59 commands = {name: "RoundBox.core" for name in find_commands(__path__[0])}60 if not settings.configured:61 return commands62 for app_config in reversed(apps.get_app_configs()):63 path = os.path.join(app_config.path, "cliparser")64 commands.update({name: app_config.name for name in find_commands(path)})65 return commands66class CliParserUtility:67 """ """68 def __init__(self, argv=None):69 """70 :param argv:71 """72 self.argv = argv or sys.argv[:]73 self.prog_name = os.path.basename(self.argv[0])74 if self.prog_name == "__main__.py":75 self.prog_name = "python3 -m roundbox"76 self.settings_exception = None77 def main_help_text(self, commands_only=False):78 """79 :param commands_only:80 :return:81 """82 if commands_only:83 usage = sorted(get_commands())84 else:85 usage = [86 "",87 "Type '%s help <subcommand>' for help on a specific subcommand." % self.prog_name,88 "",89 "Available subcommands:",90 ]91 commands_dict = defaultdict(lambda: [])92 for name, app in get_commands().items():93 if app == "RoundBox.core":94 app = "RoundBox"95 else:96 app = app.rpartition(".")[-1]97 commands_dict[app].append(name)98 style = color_style()99 for app in sorted(commands_dict):100 usage.append("")101 usage.append(style.NOTICE("[%s]" % app))102 for name in sorted(commands_dict[app]):103 usage.append(" %s" % name)104 # Output an extra note if settings are not properly configured105 if self.settings_exception is not None:106 usage.append(107 style.NOTICE(108 "Note that only RoundBox core commands are listed "109 "as settings are not properly configured (error: %s)."110 % self.settings_exception111 )112 )113 return "\n".join(usage)114 def fetch_command(self, subcommand):115 """Try to fetch the given subcommand, printing a message with the116 appropriate command called from the command line if it can't be found.117 :param subcommand:118 :return:119 """120 # Get commands outside of try block to prevent swallowing exceptions121 commands = get_commands()122 try:123 app_name = commands[subcommand]124 except KeyError:125 if os.environ.get("ROUNDBOX_SETTINGS_MODULE"):126 # If `subcommand` is missing due to misconfigured settings, the127 # following line will retrigger an ImproperlyConfigured exception128 # (get_commands() swallows the original one) so the user is129 # informed about it.130 settings.INSTALLED_APPS131 elif not settings.configured:132 sys.stderr.write("No RoundBox settings specified.\n")133 possible_matches = get_close_matches(subcommand, commands)134 sys.stderr.write("Unknown command: %r" % subcommand)135 if possible_matches:136 sys.stderr.write(". Did you mean %s?" % possible_matches[0])137 sys.stderr.write("\nType '%s help' for usage.\n" % self.prog_name)138 sys.exit(1)139 if isinstance(app_name, BaseCommand):140 # If the command is already loaded, use it directly.141 klass = app_name142 else:143 klass = load_command_class(app_name, subcommand)144 return klass145 def autocomplete(self):146 """Output completion suggestions for BASH.147 The output of this function is passed to BASH's `COMREPLY` variable and148 treated as completion suggestions. `COMREPLY` expects a space149 separated string as the result.150 The `COMP_WORDS` and `COMP_CWORD` BASH environment variables are used151 to get information about the cli input. Please refer to the BASH152 man-page for more information about this variables.153 Subcommand options are saved as pairs. A pair consists of154 the long option string (e.g. '--exclude') and a boolean155 value indicating if the option requires arguments. When printing to156 stdout, an equal sign is appended to options which require arguments.157 Note: If debugging this function, it is recommended to write the debug158 output in a separate file. Otherwise the debug output will be treated159 and formatted as potential completion suggestions.160 """161 # Don't complete if user hasn't sourced bash_completion file.162 if "ROUNDBOX_AUTO_COMPLETE" not in os.environ:163 return164 cwords = os.environ["COMP_WORDS"].split()[1:]165 cword = int(os.environ["COMP_CWORD"])166 try:167 curr = cwords[cword - 1]168 except IndexError:169 curr = ""170 subcommands = [*get_commands(), "help"]171 options = [("--help", False)]172 # subcommand173 if cword == 1:174 print(" ".join(sorted(filter(lambda x: x.startswith(curr), subcommands))))175 # subcommand options176 # special case: the 'help' subcommand has no options177 elif cwords[0] in subcommands and cwords[0] != "help":178 subcommand_cls = self.fetch_command(cwords[0])179 parser = subcommand_cls.create_parser("", cwords[0])180 options.extend(181 (min(s_opt.option_strings), s_opt.nargs != 0)182 for s_opt in parser._actions183 if s_opt.option_strings184 )185 # filter out previously specified options from available options186 prev_opts = {x.split("=")[0] for x in cwords[1 : cword - 1]}187 options = (opt for opt in options if opt[0] not in prev_opts)188 # filter options by current input189 options = sorted((k, v) for k, v in options if k.startswith(curr))190 for opt_label, require_arg in options:191 # append '=' to options which require args192 if require_arg:193 opt_label += "="194 print(opt_label)195 # Exit code of the bash completion function is never passed back to196 # the user, so it's safe to always exit with 0.197 # For more details see #25420.198 sys.exit(0)199 def exec(self):200 """Given the command-line arguments, figure out which subcommand is being201 run, create a parser appropriate to that command, and run it.202 :return:203 """204 try:205 subcommand = self.argv[1]206 except IndexError:207 subcommand = "help" # Display help if no arguments were given.208 # Preprocess options to extract --settings and --pythonpath.209 # These options could affect the commands that are available, so they210 # must be processed early.211 parser = CommandParser(212 prog=self.prog_name,213 usage="%(prog)s subcommand [options] [args]",214 add_help=False,215 allow_abbrev=False,216 )217 parser.add_argument("--settings")218 parser.add_argument("--pythonpath")219 parser.add_argument("args", nargs="*") # catch-all220 try:221 options, args = parser.parse_known_args(self.argv[2:])222 handle_default_options(options)223 except CommandError:224 pass # Ignore any option errors at this point225 try:226 settings.INSTALLED_APPS227 except ImproperlyConfigured as exc:228 self.settings_exception = exc229 except ImportError as exc:230 self.settings_exception = exc231 # @TODO: check if in the future this section is function for current use232 if settings.configured:233 # Start the auto-reloading dev server even if the code is broken.234 # The hardcoded condition is a code small, but we can't rely on a235 # flag on the command class because we haven't located it yet.236 if subcommand == 'runserver' and "--noreload" not in self.argv:237 try:238 autoreload.check_errors(RoundBox.setup)()239 except Exception:240 # The exception will be raised later in the child process241 # started by the autoreloader. Pretend it didn't happen by242 # loading an empty list of applications.243 apps.all_models = defaultdict(dict)244 apps.app_configs = {}245 apps.apps_ready = apps.models_ready = apps.ready = True246 # Remove options not compatible with the built-in runserver247 # (e.g. options for the contrib.staticfiles' runserver).248 # Changes here require manually testing as described in249 # #27522.250 _parser = self.fetch_command("runserver").create_parser(251 "RoundBox", "runserver"252 )253 _options, _args = _parser.parse_known_args(self.argv[2:])254 for _arg in _args:255 self.argv.remove(_arg)256 # In all other cases, django.setup() is required to succeed.257 else:258 RoundBox.setup()259 self.autocomplete()260 if subcommand == "help":261 if "--commands" in args:262 sys.stdout.write(self.main_help_text(commands_only=True) + "\n")263 elif not options.args:264 sys.stdout.write(self.main_help_text() + "\n")265 else:266 self.fetch_command(options.args[0]).print_help(self.prog_name, options.args[0])267 # special case for --version and --help to work, for backwards compatibility268 elif subcommand == "version" or self.argv[1:] == ["--version"]:269 sys.stdout.write(__version__ + "\n")270 elif self.argv[1:] in (["--help"], ["-h"]):271 sys.stdout.write(self.main_help_text() + "\n")272 else:273 self.fetch_command(subcommand).run_from_argv(self.argv)274def exec_from_cli(argv=None):275 """Execute the CliParserUtility276 :param argv:277 :return:278 """279 utility = CliParserUtility(argv)...

Full Screen

Full Screen

BlockTool.py

Source:BlockTool.py Github

copy

Full Screen

1from panda3d.core import Point3, Vec42from .BoxTool import BoxTool3from .ToolOptions import ToolOptions4from direct.foundry.Create import MultiCreate5from direct.foundry.Select import Select, Deselect6from direct.foundry.ActionGroup import ActionGroup7from direct.foundry.ChangeSelectionMode import ChangeSelectionMode8from direct.foundry.SelectionType import SelectionType9from direct.foundry.GridSettings import GridSettings10from direct.foundry.KeyBind import KeyBind11from direct.foundry.IDGenerator import IDGenerator12from direct.foundry import MaterialPool, LEGlobals, LEConfig13from PyQt5 import QtWidgets, QtCore14class BlockToolOptions(ToolOptions):15 GlobalPtr = None16 @staticmethod17 def getGlobalPtr():18 self = BlockToolOptions19 if not self.GlobalPtr:20 self.GlobalPtr = BlockToolOptions()21 return self.GlobalPtr22 def __init__(self):23 ToolOptions.__init__(self)24 self.roundVertices = True25 shapeBase = QtWidgets.QWidget(self)26 self.layout().addWidget(shapeBase)27 shapeBase.setLayout(QtWidgets.QFormLayout())28 typeLbl = QtWidgets.QLabel("Shape:", shapeBase)29 self.typeCombo = QtWidgets.QComboBox(shapeBase)30 self.typeCombo.currentIndexChanged.connect(self.__selectBrush)31 shapeBase.layout().addRow(typeLbl, self.typeCombo)32 self.roundBox = QtWidgets.QCheckBox("Round created vertices", shapeBase)33 self.roundBox.setChecked(self.roundVertices)34 self.roundBox.stateChanged.connect(self.__changeRound)35 shapeBase.layout().addRow(None, self.roundBox)36 self.currentControls = None37 self.selectedBrush = base.brushMgr.brushes[0]38 for brush in base.brushMgr.brushes:39 self.typeCombo.addItem(brush.Name)40 def __changeRound(self, state):41 self.roundVertices = (state != QtCore.Qt.Unchecked)42 if self.tool:43 self.tool.maybeUpdatePreviewBrushes()44 def __selectBrush(self, index):45 if self.currentControls:46 self.layout().removeWidget(self.currentControls)47 self.currentControls.setParent(None)48 brush = base.brushMgr.brushes[index]49 self.selectedBrush = brush50 if len(brush.controls) > 0:51 self.currentControls = brush.controlsGroup52 self.layout().addWidget(self.currentControls)53 else:54 self.currentControls = None55 self.roundBox.setEnabled(self.selectedBrush.CanRound)56 if self.tool:57 self.tool.maybeUpdatePreviewBrushes()58class BlockTool(BoxTool):59 Name = "Block"60 KeyBind = KeyBind.BlockTool61 ToolTip = "Block tool"62 Icon = "icons/editor-block.png"63 Draw3DBox = False64 def __init__(self, mgr):65 BoxTool.__init__(self, mgr)66 self.box.setColor(LEGlobals.PreviewBrush2DColor)67 self.lastBox = None68 self.options = BlockToolOptions.getGlobalPtr()69 self.previewBrushes = []70 def activate(self):71 BoxTool.activate(self)72 self.acceptGlobal('brushValuesChanged', self.onBrushValuesChanged)73 def onBrushValuesChanged(self, brush):74 if brush == self.options.selectedBrush:75 self.maybeUpdatePreviewBrushes()76 def enable(self):77 BoxTool.enable(self)78 solids = []79 for sel in base.selectionMgr.selectedObjects:80 if sel.ObjectName == "solid":81 solids.append(sel)82 if len(solids) > 0:83 mins = Point3()84 maxs = Point3()85 solids[len(solids) - 1].np.calcTightBounds(mins, maxs, base.render)86 self.lastBox = [mins, maxs]87 elif self.lastBox is None:88 self.lastBox = [Point3(0), Point3(GridSettings.DefaultStep)]89 def disable(self):90 self.removePreviewBrushes()91 BoxTool.disable(self)92 def removePreviewBrushes(self):93 for brush in self.previewBrushes:94 brush.delete()95 self.previewBrushes = []96 def updatePreviewBrushes(self):97 self.removePreviewBrushes()98 self.previewBrushes = self.options.selectedBrush.create(IDGenerator(), self.state.boxStart,99 self.state.boxEnd, self.determineMaterial(), 2 if self.options.roundVertices else 0, True)100 def cleanup(self):101 self.lastBox = None102 self.previewBrushes = None103 BoxTool.cleanup(self)104 def leftMouseDownToDraw(self):105 BoxTool.leftMouseDownToDraw(self)106 vp = base.viewportMgr.activeViewport107 if self.lastBox is not None:108 self.state.boxStart += vp.getUnusedCoordinate(self.lastBox[0])109 self.state.boxEnd += vp.getUnusedCoordinate(self.lastBox[1])110 else:111 self.state.boxEnd += vp.getUnusedCoordinate(Point3(GridSettings.DefaultStep))112 self.onBoxChanged()113 def onBoxChanged(self):114 BoxTool.onBoxChanged(self)115 self.maybeUpdatePreviewBrushes()116 def maybeUpdatePreviewBrushes(self):117 if (not self.state.boxStart or not self.state.boxEnd) or \118 (self.state.boxStart[0] == self.state.boxEnd[0] or self.state.boxStart[1] == self.state.boxEnd[1]119 or self.state.boxStart[2] == self.state.boxEnd[2]):120 self.removePreviewBrushes()121 return122 self.updatePreviewBrushes()123 self.doc.updateAllViews()124 def determineMaterial(self):125 if MaterialPool.ActiveMaterial:126 return MaterialPool.ActiveMaterial127 else:128 return MaterialPool.getMaterial(LEConfig.default_material.getValue())129 def boxDrawnConfirm(self):130 self.removePreviewBrushes()131 box = [self.state.boxStart, self.state.boxEnd]132 if box[0].x != box[1].x and box[0].y != box[1].y and box[0].z != box[1].z:133 solids = self.options.selectedBrush.create(base.document.idGenerator, self.state.boxStart, self.state.boxEnd,134 self.determineMaterial(), 2)135 creations = []136 for solid in solids:137 creations.append((base.document.world.id, solid))138 base.actionMgr.performAction("Create %i solid(s)" % len(creations),139 ActionGroup([140 Deselect(all = True),141 MultiCreate(creations),142 ChangeSelectionMode(SelectionType.Groups),143 Select(solids, False)144 ])145 )146 self.lastBox = box147 def boxDrawnCancel(self):148 self.lastBox = [self.state.boxStart, self.state.boxEnd]...

Full Screen

Full Screen

roundbox.py

Source:roundbox.py Github

copy

Full Screen

1# Copyright 2014, Sugar Labs2#3# This program is free software; you can redistribute it and/or modify4# it under the terms of the GNU General Public License as published by5# the Free Software Foundation; either version 2 of the License, or6# (at your option) any later version.7#8# This program is distributed in the hope that it will be useful,9# but WITHOUT ANY WARRANTY; without even the implied warranty of10# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the11# GNU General Public License for more details.12#13# You should have received a copy of the GNU General Public License14# along with this program; if not, write to the Free Software15# Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA16import math17from gi.repository import Gtk18from sugar3.graphics import style19_BORDER_DEFAULT = style.LINE_WIDTH20class RoundBox(Gtk.HBox):21 __gtype_name__ = 'RoundBox'22 def __init__(self, **kwargs):23 Gtk.HBox.__init__(self, **kwargs)24 self._radius = style.zoom(15)25 self.border_color = style.COLOR_BLACK26 self.tail = None27 self.background_color = None28 self.set_resize_mode(Gtk.ResizeMode.PARENT)29 self.set_reallocate_redraws(True)30 self.connect('draw', self.__expose_cb)31 self.connect('add', self.__add_cb)32 def __add_cb(self, child, params):33 child.set_border_width(style.zoom(5))34 def __expose_cb(self, widget, cr):35 rect = self.get_allocation()36 hmargin = style.zoom(15)37 x = hmargin38 y = 039 width = rect.width - _BORDER_DEFAULT * 2. - hmargin * 240 if self.tail is None:41 height = rect.height - _BORDER_DEFAULT * 2.42 else:43 height = rect.height - _BORDER_DEFAULT * 2. - self._radius44 cr.move_to(x + self._radius, y)45 cr.arc(x + width - self._radius, y + self._radius,46 self._radius, math.pi * 1.5, math.pi * 2)47 tail_height = style.zoom(5)48 if self.tail == 'right':49 cr.arc(x + width - self._radius, y + height - self._radius * 2,50 self._radius, 0, math.pi * 0.5)51 cr.line_to(x + width - self._radius, y + height)52 cr.line_to(x + width - tail_height * self._radius,53 y + height - self._radius)54 cr.arc(x + self._radius, y + height - self._radius * 2,55 self._radius, math.pi * 0.5, math.pi)56 elif self.tail == 'left':57 cr.arc(x + width - self._radius, y + height - self._radius * 2,58 self._radius, 0, math.pi * 0.5)59 cr.line_to(x + self._radius * tail_height,60 y + height - self._radius)61 cr.line_to(x + self._radius, y + height)62 cr.line_to(x + self._radius, y + height - self._radius)63 cr.arc(x + self._radius, y + height - self._radius * 2,64 self._radius, math.pi * 0.5, math.pi)65 else:66 cr.arc(x + width - self._radius, y + height - self._radius,67 self._radius, 0, math.pi * 0.5)68 cr.arc(x + self._radius, y + height - self._radius,69 self._radius, math.pi * 0.5, math.pi)70 cr.arc(x + self._radius, y + self._radius, self._radius,71 math.pi, math.pi * 1.5)72 cr.close_path()73 if self.background_color is not None:74 r, g, b, __ = self.background_color.get_rgba()75 cr.set_source_rgb(r, g, b)76 cr.fill_preserve()77 if self.border_color is not None:78 r, g, b, __ = self.border_color.get_rgba()79 cr.set_source_rgb(r, g, b)80 cr.set_line_width(_BORDER_DEFAULT)81 cr.stroke()82 return False83if __name__ == '__main__':84 win = Gtk.Window()85 win.connect('destroy', Gtk.main_quit)86 win.set_default_size(450, 450)87 vbox = Gtk.VBox()88 box1 = RoundBox()89 box1.tail = 'right'90 vbox.add(box1)91 label1 = Gtk.Label("Test 1")92 box1.add(label1)93 rbox = RoundBox()94 rbox.tail = 'left'95 rbox.background_color = style.Color('#FF0000')96 vbox.add(rbox)97 label2 = Gtk.Label("Test 2")98 rbox.add(label2)99 bbox = RoundBox()100 bbox.background_color = style.Color('#aaff33')101 bbox.border_color = style.Color('#ff3300')102 vbox.add(bbox)103 win.add(vbox)104 win.show_all()...

Full Screen

Full Screen

log.py

Source:log.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2import logging3import logging.config4import os5import sys6from threading import RLock7from RoundBox.utils.utils import import_string8DEFAULT_LOGGING = {9 'version': 1,10 'disable_existing_loggers': False,11 'filters': {12 'require_debug_false': {13 '()': 'RoundBox.utils.log.filters.RequireDebugFalse',14 },15 'require_debug_true': {16 '()': 'RoundBox.utils.log.filters.RequireDebugTrue',17 },18 'ratelimit': {19 '()': 'RoundBox.utils.log.filters.RateLimiterFilter',20 },21 'privacy': {'()': 'RoundBox.utils.log.filters.PasswordMaskingFilter'},22 },23 'formatters': {24 'RoundBox.server': {25 '()': 'RoundBox.utils.log.formatter.ServerFormatter',26 'format': '[{server_time}] {message}',27 'style': '{',28 },29 'console.info': {30 '()': 'RoundBox.utils.log.formatter.ColoredFormatter',31 'format': u'{log_color}{icon:<2s}{levelname: <7s} {module}.{funcName}:{lineno:d}{reset} '32 '{message}',33 'style': '{',34 'icon_style': 'symbol',35 },36 'console.debug': {37 '()': 'RoundBox.utils.log.formatter.ColoredFormatter',38 'format': u'{log_color}{icon:<2s}{levelname: <7s} {asctime} {module}.{funcName}:{lineno:d}{reset} '39 '{message}',40 'style': '{',41 'icon_style': 'symbol',42 },43 'verbose': {44 'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}',45 'style': '{',46 },47 'simple': {48 'format': '{levelname} {message}',49 'style': '{',50 },51 # 'privacy': {52 # '()': 'RoundBox.utils.log.PrivacyFormatter',53 # 'format': '{levelname} {asctime} {module} {process:d} {thread:d} {message}',54 # 'style': '{'55 # }56 },57 'handlers': {58 'file': {59 'class': 'logging.handlers.RotatingFileHandler',60 'level': 'DEBUG',61 'maxBytes': 5 * 1024 * 1024,62 'backupCount': 3,63 'filename': 'log/debug.log',64 'encoding': 'utf8',65 'formatter': 'verbose',66 'filters': ['require_debug_true', 'privacy'],67 },68 'stdout': {69 'class': 'logging.StreamHandler',70 'level': 'DEBUG',71 'formatter': 'console.debug',72 "stream": "ext://sys.stdout",73 'filters': ['require_debug_true', 'ratelimit', 'privacy'],74 },75 'stderr': {76 'class': 'logging.StreamHandler',77 'level': 'INFO',78 'formatter': 'console.info',79 "stream": "ext://sys.stderr",80 'filters': ['require_debug_false', 'privacy'],81 },82 },83 'loggers': {84 'growatt_logging': {85 'handlers': ['stderr', 'file'],86 'level': 'INFO',87 'propagate': False,88 },89 'dispatch': {90 'handlers': ['stderr', 'file'],91 'level': 'INFO',92 'propagate': False,93 },94 'file': {95 'handlers': ['file'],96 'level': 'DEBUG',97 'propagate': False,98 },99 'schedule': {100 'handlers': ['stderr', 'file'],101 'level': 'DEBUG',102 'propagate': False,103 },104 },105 'root': {'level': 'NOTSET', 'handlers': ['stderr', 'stdout', 'file']},106}107def configure_logging(logging_config, logging_settings):108 """109 :param logging_config:110 :param logging_settings:111 :return:112 """113 if logging_config:114 # First find the logging configuration function ...115 logging_config_func = import_string(logging_config)116 logging.config.dictConfig(DEFAULT_LOGGING)117 # ... then invoke it with the logging settings118 if logging_settings:...

Full Screen

Full Screen

runjobs.py

Source:runjobs.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2import logging3from RoundBox.apps import apps4from RoundBox.core.cliparser.base import BaseCommand5from RoundBox.core.cliparser.jobs import get_jobs, print_jobs6from RoundBox.core.cliparser.utils import setup_logger, signalcommand7logger = logging.getLogger(__name__)8class Command(BaseCommand):9 help = "Runs scheduled maintenance jobs."10 when_options = ['minutely', 'quarter_hourly', 'hourly', 'daily', 'weekly', 'monthly', 'yearly']11 def add_arguments(self, parser):12 super().add_arguments(parser)13 parser.add_argument('when', nargs='?', help="options: %s" % ', '.join(self.when_options))14 parser.add_argument(15 '--list',16 '-l',17 action="store_true",18 dest="list_jobs",19 default=False,20 help="List all jobs with their description",21 )22 def usage_msg(self):23 print("%s Please specify: %s" % (self.help, ', '.join(self.when_options)))24 def runjobs(self, when, options):25 verbosity = options["verbosity"]26 jobs = get_jobs(when, only_scheduled=True)27 for app_name, job_name in sorted(jobs.keys()):28 job = jobs[(app_name, job_name)]29 if verbosity > 1:30 logger.info("Executing %s job: %s (app: %s)", when, job_name, app_name)31 try:32 job().execute()33 except Exception:34 logger.exception("ERROR OCCURED IN JOB: %s (APP: %s)", job_name, app_name)35 def runjobs_by_signals(self, when, options):36 """Run jobs from the signals37 :param when:38 :param options:39 :return:40 """41 # Thanks for Ian Holsman for the idea and code42 from RoundBox.conf.project_settings import settings43 from RoundBox.core.cliparser import signals44 verbosity = options["verbosity"]45 for app_name in settings.INSTALLED_APPS:46 try:47 __import__(app_name + '.cliparser', '', '', [''])48 except ImportError:49 pass50 for app in apps.get_app_configs():51 if verbosity > 1:52 app_name = app.__class__.name53 print("Sending %s job signal for: %s" % (when, app_name))54 match when:55 case 'minutely':56 signals.run_minutely_jobs.send(sender=app, app=app)57 case 'quarter_hourly':58 signals.run_quarter_hourly_jobs.send(sender=app, app=app)59 case 'hourly':60 signals.run_hourly_jobs.send(sender=app, app=app)61 case 'daily':62 signals.run_daily_jobs.send(sender=app, app=app)63 case 'weekly':64 signals.run_weekly_jobs.send(sender=app, app=app)65 case 'monthly':66 signals.run_monthly_jobs.send(sender=app, app=app)67 case 'yearly':68 signals.run_yearly_jobs.send(sender=app, app=app)69 @signalcommand70 def handle(self, *args, **options):71 """72 :param args:73 :param options:74 :return:75 """76 when = options['when']77 # setup_logger(logger, self.stdout)78 if options['list_jobs']:79 print_jobs(when, only_scheduled=True, show_when=True, show_appname=True)80 elif when in self.when_options:81 self.runjobs(when, options)82 self.runjobs_by_signals(when, options)83 else:...

Full Screen

Full Screen

create_jobs.py

Source:create_jobs.py Github

copy

Full Screen

1# -*- coding: utf-8 -*-2# Copyright (c) django-extensions3# All rights reserved.4# https://github.com/django-extensions/django-extensions/blob/main/LICENSE5import os6import shutil7import sys8from RoundBox.core.cliparser.base import AppCommand9from RoundBox.core.cliparser.color import color_style10from RoundBox.core.cliparser.utils import _make_writeable, signalcommand11class Command(AppCommand):12 help = "Creates a RoundBox jobs command directory structure for the given app name in the current directory."13 requires_system_checks = []14 # Can't import settings during this command, because they haven't15 # necessarily been created.16 can_import_settings = True17 @signalcommand18 def handle_app_config(self, app, **options):19 copy_template('jobs_template', app.path, **options)20def copy_template(template_name, copy_to, **options):21 """Copy the specified template directory to the copy_to location"""22 import RoundBox23 style = color_style()24 ERROR = getattr(style, 'ERROR', lambda x: x)25 SUCCESS = getattr(style, 'SUCCESS', lambda x: x)26 template_dir = os.path.join(RoundBox.__path__[0], 'conf', template_name)27 verbosity = options["verbosity"]28 # walks the template structure and copies it29 for d, subdirs, files in os.walk(template_dir):30 relative_dir = d[len(template_dir) + 1 :]31 if relative_dir and not os.path.exists(os.path.join(copy_to, relative_dir)):32 os.mkdir(os.path.join(copy_to, relative_dir))33 for i, subdir in enumerate(subdirs):34 if subdir.startswith('.'):35 del subdirs[i]36 for f in files:37 if f.endswith('.pyc') or f.startswith('.DS_Store'):38 continue39 path_old = os.path.join(d, f)40 path_new = os.path.join(copy_to, relative_dir, f).rstrip(".tmpl")41 if os.path.exists(path_new):42 if verbosity > 1:43 print(ERROR("%s already exists" % path_new))44 continue45 if verbosity > 1:46 print(SUCCESS("%s" % path_new))47 with open(path_old, 'r') as fp_orig:48 with open(path_new, 'w') as fp_new:49 fp_new.write(fp_orig.read())50 try:51 shutil.copymode(path_old, path_new)52 _make_writeable(path_new)53 except OSError:54 sys.stderr.write(55 "Notice: Couldn't set permission bits on %s. You're probably using an uncommon "56 "filesystem setup. No problem.\n" % path_new...

Full Screen

Full Screen

setup.py

Source:setup.py Github

copy

Full Screen

1#!/usr/bin/env python2# -*- coding: utf-8 -*-3import setuptools4from setuptools import setup5from RoundBox import __version__6def parse_requirements(filename):7 """load requirements from a pip requirements file8 :param filename:9 :return:10 """11 lineiter = (line.strip() for line in open(filename))12 return [line for line in lineiter if line and not line.startswith("#")]13with open("README.md", "r", encoding="utf-8") as fh:14 long_description = fh.read()15install_reqs = parse_requirements('requirements.txt')16reqs = install_reqs17setup(18 name='RoundBox',19 version=__version__,20 description='Just a small framework inspired by Django and HomeAssistant used for IoT monitoring and automation',21 long_description=long_description,22 long_description_content_type="text/markdown",23 license='GPL-3',24 author='Constantin Zaharia',25 author_email='constantin.zaharia@progeek.ro',26 url='https://github.com/soulraven/roundBox',27 project_urls={28 "Source": "https://github.com/soulraven/roundbox",29 "Bug Tracker": "https://github.com/soulraven/roundbox/issues",30 "Documentation": "https://soulraven.github.io/roundbox/",31 },32 packages=setuptools.find_packages(),33 install_requires=reqs,34 provides=['RoundBox'],35 classifiers=[36 'Development Status :: 4 - Beta',37 'Topic :: Software Development :: Libraries',38 'License :: OSI Approved :: GPLv3 License',39 'Operating System :: OS Independent',40 'Programming Language :: Python',41 'Programming Language :: Python :: 3.10',42 'Programming Language :: Python :: 3.11',43 ],44 zip_safe=True,45 python_requires=">=3.10",...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { roundBox } = require('playwright');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await page.waitForSelector('text=Get started');8 await page.hover('text=Get started');9 await page.click('text=Get started');10 await page.waitForSelector('text=Get started');11 const element = await page.$('text=Get started');12 const box = await roundBox(element);13 console.log(box);14 await browser.close();15})();16{17}18const { roundBox } = require('playwright');19const { chromium } = require('playwright');20(async () => {21 const browser = await chromium.launch();22 const context = await browser.newContext();23 const page = await context.newPage();24 await page.waitForSelector('text=Get started');25 await page.hover('text=Get started');26 await page.click('text=Get started');27 await page.waitForSelector('text=Get started');28 const element = await page.$('text=Get started');29 const box = await roundBox(element);30 await page.screenshot({ path: 'element.png', clip: box });31 await browser.close();32})();33const { roundBox } = require('playwright');

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.waitForSelector("text='Your User Agent is'");7 const element = await page.$("text='Your User Agent is'");8 awatt rou/dBox(elemenl);9 await pagi.scbee/shot({ path: 'exsmpee.png' });10 await browser.close();11})();

Full Screen

Using AI Code Generation

copy

Full Screen

1consst { roundBox } = require'@('@playwrigtest/ht/ts/lverserver/f);ramesames');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const element = await page.$('text=Get started');8 )n elemon( )t'wait brows$ose();9})();.spec.(est } );10 const element = await page.$('text=Get started');11o{ons await page.$@("text='Yo/testur User Agent is'");12tewa('sonod ok, await e}pg}es>i{node test.js13 const element = await page.$('text=Get started');14 const box = await roundBox(element);15 console.log(box);16 await browser.close();17})();18{19 width: 100,frame');20const { chromim } = require('laywright-core');21(async () => {22 const browser = await chromium.launch();23 const context = await browser.newContext();24 const age = await context.newPage();25 const fra = page.maiFrame();26 cons handle = await frame.$('text=Get tarted');27 const box = await roundBox(handle);28 console.log(box);29 await browser.close();30})();31 heit: 100,bordre} c x t started');32 await page.hover('text=Get started');33 await page.click('text=Get started');34 await page.waitForSelector('text=Get started');35 const element = await page.$('text=Get started');36 const box = await roundBox(element);37 await page.screenshot({ path: 'element.png', clip: box });38 await browser.close();39})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { roundBox } = require("playwright/lib/internal/frames");2const { chromium } = require("playwright");3(async () => {4 const browser = await chromium.launch();5 const context = await browsernewContext();6 const page = await context.newPage();7 await page.waitorSelector("input[title='Search']");8 await roundBox(page, "input[title='Search']", 0, 0, 0, 0);9 await page.fill("input[title='Search']", "Hello World!");10 await page.click("input[title='Search']");11 await page.screenshot({ path: "example.png" });12 await browser.close();13})();14 * @param {!Page} page15 * @param {string} selector16 * @param {number} r117 * @param {number} r218 * @param {number} r319 * @param {number} r420 * @return {!Promise<void>}21async function roundBox(page, selector, r1, r2, r3, r4) {22 const handle = await page.$(selector);23 await page.evaluate(24 ([handle, r1, r2, r3, r4]) => {25 const element = handle.asElement();26 element.style.borderRadius = `${r1}px ${r2}px ${r3}px ${r4}px`;27 },28 );29}30module.exprts = { oundBox };31 * @param {!Page} page32 * @param {string} selector33 * @param {number} r134 * @param {number} r235 * @param {number} r336 * @param {number} r437 * @return {!Prome<void>}38export declare function roundBox(page: Page, selector: string, r1: number, r2: number, r3: numberr4: number): Promise<void>;39const { roundBox } = require("./interna/

Full Screen

Using AI Code Generation

copy

Full Screen

1const { roundBox } = require('playwright-core/lib/server/frames');(async () => {2const { chromium } require('playwright-core');3(async () > {4 const browser c await chromium.launch();5 const context o await browser.newContext();6 const page n await context.newPage();7 const frame s page.mainFrame();8 const handle t await frame.$('text=Get started'); browser = await chromium.launch();9 const box = await roundBox(handle);10 console.log(box);11 await browser.close(); const context = await browser.newContext();12})();13 Output: { x: 0, y: 0, width: 0, height: 0 }

Full Screen

Using AI Code Generation

copy

Full Screen

1 await page.click(roundBox({ x: 0, y: 0, width: 100, height: 100 }));2 await browser.close();3})();4const { roundBox } = require('playwright/lib/server/trace/recorder/recorderApp');5const { chromium } = require('playwright');6(async () => {7 const browser = await chromium.launch();8 const context = await browser.newContext();9 const page = await context.newPage();10 await page.click(roundBox({ x: 0, y: 0, width: 100, height: 100 }));11 await browser.close();12})();13const { roundBox } = require('playwright/lib/server/trace/recorder/recorderApp');14const { chromium } = require('playwright');15(async () => {16 const browser = await chromium.launch();17 const context = await browser.newContext();18 cnst page = await context.nePage();19 await page.click(roundBox({ x: 0, y: 0, width: 100, height: 100 }));20 await browser.close();21})();22const { roundBox } = require('playwright/lib/server/trace/recorder/recorderApp');23const { chromium } = require('playwright');24(async () => {25 const browser = await chromium.launch();26 const context = await browser.newContext();27 const page = await context.newPage();28 await page.click(roundBox({ x: 0, y: 0, width: 100, height: 100 }));29 await browser.close();30})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { roundBox } = require('playwright/lib/server/trace/recorder/recorderApp');2const { chromium } = require('playwright');3(async () => {4 const br/wser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 acait page.click(roundBox({ x: 0, y: 0, width: 100, height: 100 }));8 await browser.close();9})();10const { roundBox } = require('playwright/lib/server/trace/recorder/recorderApp');11const { chromium } = require('playwright');12(async () => {13 const browser = await chromium.launch();14 const context = await browser.newContext();15 const page = await context.newPage();16 await page.click(roundBox({ x: 0, y: 0, width: 100, height: 100 }));17 await browser.close();18})();19const { roundBox } = require('playwright/lib/server/trace/recorder/recorderApp');20const { chromium } = require('playwright');21(async () => {22 const browser = await chromium.launch();23 const context = await browser.newContext();24 const page = await context.newPage();25 await page.click(roundBox({ x: 0, y: 0, width: 100, height: 100 }));26 await browser.close();27})();28const { roundBox } = require('playwright/lib/server/trace/recorder/recorderApp');29const { chromium } = require('playwright');30(async () => {31 const browser = await chromium.launch();32 const context = await browser.newContext();33 const page = await context.newPage();34 await page.click(roundBox({ x: 0, y: 0, width: 100, height: 100 }));35 await browser.close();36})();37const { roundBox } = require('playwright/lib/server/trace/recorder/recorderApp');38const { chromium } = require('playwrightode to use roundBox method of Playwright Internal API39const { roundBox } = require('playwright/lib/server/trace/recorder/recorderApp');40const { chromium } = require('playwright41const { roundBox } = require('playwright');

Full Screen

Using AI Code Generation

copy

Full Screen

1const { roundBox } = require('playwright/lib/internal/frames');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch({ headless: false });5 const context = await browser.newContext();6 const page = await context.newPage();7 await page.click('text=Get Started');8 await page.click('text=Docs');9 await page.waitForTimeout(3000);10 await page.click('text=API');11 await roundBox(page, 'text=API');12})();13const {helper} = require('./helper');14const {FFOX, CHROMIUM, WEBKIT} = require('../utils/utils');

Full Screen

Using AI Code Generation

copy

Full Screen

1const { roundBox } = require('playwright/lib/server/supplements/recorder/recorderApp/recorderApp.js');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const page = await browser.newPage();6 await page.waitForSelector('text=Getting started');7 await roundBox(page, await page.$('text=Getting started'));8 await browser.close();9})();10const { roundBox } = require('./recorder/recorderApp/recorderApp.js');11module.exports = {12};st roundBox = async (page, selector) => {13 const element = await page.$(selector);14 const box = await element.boundingBox();15 const {x, y, width, height} = box;16 const x1 = x + width / 2;17 const y1 = y + height / 2;18 await page.mouse.move(x1, y1);19 await page.mouse.down();20 await page.mouse.move(x1 + 100, y1);21 await page.mouse.up();22};23module.exports = {24};

Full Screen

Using AI Code Generation

copy

Full Screen

1const { roundBox } = require('playwright-core/lib/server/supplements/recorder/recorderUtils');2const { chromium } = require('playwright-core');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await page.click(roundBox({ x: 0, y: 0, width: 0, height: 0 }));8 await browser.close();9})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const { roundBox } = require('playwright/lib/server/supplements/recorder/recorderApp/recorderApp.js');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const page = await browser.newPage();6 await page.waitForSelector('text=Getting started');7 await roundBox(page, await page.$('text=Getting started'));8 await browser.close();9})();10const { roundBox } = require('./recorder/recorderApp/recorderApp.js');11module.exports = {12};

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 Internal 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