< sys. python examples

sys. - python examples

Here are the examples of the python api sys. taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

126 Examples 7

5 View Complete Implementation : dev.py , under MIT License , by intel
    async def run(self):
        async with self.config(BaseConfig()) as configloader:
            async with configloader() as loader:
                for obj in load(self.export, relative=os.getcwd()):
                    self.logger.debug("Loaded %s: %s", self.export, obj)
                    if isinstance(obj, DataFlow):
                        sys.stdout.buffer.write(
                            await loader.dumpb(
                                obj.export(linked=not self.not_linked)
                            )
                        )
                    elif hasattr(obj, "export"):
                        sys.stdout.buffer.write(
                            await loader.dumpb(obj.export())
                        )
                    elif hasattr(obj, "_asdict"):
                        sys.stdout.buffer.write(
                            await loader.dumpb(obj._asdict())
                        )

5 View Complete Implementation : corrections_metrics.py , under Apache License 2.0 , by sidewalklabs
def main(geocodes_json_path, truth_csv_path, incorrect_file):
    geocodes = json.load(open(geocodes_json_path))
    with open(truth_csv_path) as csv_file:
        truth = csv.DictReader(csv_file, ['image_id', 'lat', 'lng'])
        corrected_ids, incorrect_geocodes = check_against_truth_data(geocodes, truth)
        with open(incorrect_file, 'w') as csv_file:
            writer = csv.writer(csv_file)
            for incorrect in incorrect_geocodes:
                writer.writerow(incorrect)
        for correct in corrected_ids:
            sys.stderr.write(f'{correct}\n')
        sys.stderr.write('\n\n\n\n\n')
        total_ids = len(corrected_ids) + len(incorrect_geocodes)
        sys.stderr.write(f'corrected ids: {len(corrected_ids)} / {total_ids}\n')
        sys.stderr.write(f'inncorrect ids: {len(incorrect_geocodes)} / {total_ids}\n')

5 View Complete Implementation : __init__.py , under MIT License , by michalwols
def progress(it, num=None):
  if not num:
    try:
      num = len(it)
    except:
      num = None

  if num:
    for n, x in enumerate(it, 1):
      sys.stdout.write(f"\r{n} / {num}")
      sys.stdout.flush()
      yield x
  else:
    for n, x in enumerate(it, 1):
      sys.stdout.write(f"\r{n}")
      sys.stdout.flush()
      yield x

5 View Complete Implementation : pplacer.py , under GNU General Public License v3.0 , by Ecogenomics
    def _disp_progress(self, line):
        """Calculates the progress and writes it to stdout.

        Parameters
        ----------
        line : str
            The line passed from pplacer stdout.
        """
        if not line.startswith('working on '):
            sys.stdout.write(f'\rInitialising pplacer [{line[0:50].center(50)}]')
            sys.stdout.flush()
        else:
            re_hits = re.search(r'\((\d+)\/(\d+)\)', line)
            current = int(re_hits.group(1))
            total = int(re_hits.group(2))
            sys.stdout.write('\r{}'.format(self._get_progress_str(current,
                                                                  total)))
            sys.stdout.flush()

3 View Complete Implementation : utils.py , under Apache License 2.0 , by hyperconnect
def wait(message, stop_checker_closure):
    assert callable(stop_checker_closure)
    st = time.time()
    while True:
        try:
            time_pass = hf.format_timespan(int(time.time() - st))
            sys.stdout.write(colored((
                f"{message}. Do you wanna wait? If not, then ctrl+c! :: waiting time: {time_pass}\r"
            ), "yellow", attrs=["bold"]))
            sys.stdout.flush()
            time.sleep(1)
            if stop_checker_closure():
                break
        except KeyboardInterrupt:
            break

3 View Complete Implementation : stranger_handler.py , under GNU Affero General Public License v3.0 , by quasiyoke
    def __init__(self, seed_tuple, *args, **kwargs):
        super(StrangerHandler, self).__init__(seed_tuple, *args, **kwargs)
        bot, initial_msg, unused_seed = seed_tuple
        self._from_id = initial_msg['from']['id']

        try:
            self._stranger = StrangerService.get_instance() \
                .get_or_create_stranger(self._from_id)
        except StrangerServiceError as err:
            LOGGER.exception('Problems with StrangerHandler construction')
            sys.exit(f'Problems with StrangerHandler construction. {err}')

        self._sender = StrangerSenderService.get_instance(bot) \
            .get_or_create_stranger_sender(self._stranger)
        self._stranger_setup_wizard = StrangerSetupWizard(self._stranger)
        self._deferred_advertising = None

3 View Complete Implementation : root_commands.py , under MIT License , by thiagofigueiro
def cmd_upload(nexus_client, args):
    """Performs ``nexus3 upload``"""
    source = args['<from_src>']
    destination = args['<to_repository>']

    sys.stderr.write(f'Uploading {source} to {destination}\n')

    upload_count = nexus_client.upload(
                    source, destination,
                    flatten=args.get('--flatten'),
                    recurse=(not args.get('--norecurse')))

    _cmd_up_down_errors(upload_count, 'upload')

    file = PLURAL('file', upload_count)
    sys.stderr.write(f'Uploaded {upload_count} {file} to {destination}\n')
    return errors.CliReturnCode.SUCCESS.value

3 View Complete Implementation : execute_local.py , under GNU Lesser General Public License v3.0 , by UCL-CCS
    def act_on_dir(self, target_dir):
        """
        Executes `self.run_cmd` in the shell in `target_dir`.

        target_dir : str
            Directory in which to execute command.

        """

        if self.interpreter is None:
            full_cmd = f'cd {target_dir}\n{self.run_cmd}\n'
        else:
            full_cmd = f'cd {target_dir}\n{self.interpreter} {self.run_cmd}\n'
        result = os.system(full_cmd)
        if result != 0:
            sys.exit(f'Non-zero exit code from command "{full_cmd}"\n')

3 View Complete Implementation : twitter.py , under MIT License , by catleeball
def getTwitterCredentials(keyfile=KEY_PATH):
    # TOODO: Use better config file format, better parsing logic
    try:
        with open(keyfile, "r") as f:
            keys = f.read()
    except Exception as e:
        sys.stderr.write(f"Exception fetching Twitter keys: {e}")
        sys.exit(1)

    keys = keys.split()
    keys = [key.strip() for key in keys]

    return TwitterAuth(
        consumer_key=keys[0],
        consumer_secret=keys[1],
        access_token=keys[2],
        access_token_secret=keys[3],
    )

3 View Complete Implementation : preprocess.py , under MIT License , by jadore801120
def encode_files(bpe, src_in_file, trg_in_file, data_dir, prefix):
    src_out_file = os.path.join(data_dir, f"{prefix}.src")
    trg_out_file = os.path.join(data_dir, f"{prefix}.trg")

    if os.path.isfile(src_out_file) and os.path.isfile(trg_out_file):
        sys.stderr.write(f"Encoded files found, skip the encoding process ...\n")

    encode_file(bpe, src_in_file, src_out_file)
    encode_file(bpe, trg_in_file, trg_out_file)
    return src_out_file, trg_out_file

3 View Complete Implementation : supreme.py , under MIT License , by zweed4u
    def find_product(self):
        while self.product_found == 0:
            current_mobile_json = self.fetch_mobile_stock()
            for category in list(current_mobile_json['products_and_categories'].values()):
                for item in category:
                    if self.item_name.lower() in item['name'].lower():
                        self.product_found = 1
                        listed_product_name = item['name']
                        listed_product_id = item['id']
                        sys.stdout.write(f'[[ {self.thread_text_color}{str(threading.current_thread().getName())}{COLOR_END} ]] {utc_to_est()} :: [[ {self.thread_text_color}{listed_product_name}{COLOR_END} ]] {str(listed_product_id)} found ( MATCHING ITEM DETECTED )\n')
            if self.product_found != 1:
                sys.stdout.write(f'[[ {self.thread_text_color}{str(threading.current_thread().getName())}{COLOR_END} ]] {utc_to_est()} :: Reloading and reparsing page...\n')
                time.sleep(user_config.poll)
            else:
                color_id, size_id = self.find_product_variant(listed_product_name, listed_product_id)
                self.add_to_cart(listed_product_name, listed_product_id, color_id, size_id)

3 View Complete Implementation : main.py , under Apache License 2.0 , by pymedphys
def main(args):
    get_build()

    queue = multiprocessing.Queue()

    server_process = multiprocessing.Process(
        target=launch_server, args=(queue, args.working_directory)
    )
    server_process.start()

    port, token = queue.get()
    url = f"http://{IP}:{port}/?token={token}"

    sys.stdout.write(f'\n{{"url": "{url}"}}\n')
    sys.stdout.flush()

3 View Complete Implementation : bmex.py , under MIT License , by dxflores
def _validate_symbols(symbols: set):
    """
    Validates that each symbol/index exists/existed on BitMEX.
    """

    r = requests.get(
        "https://www.bitmex.com/api/v1/instrument?count=500&reverse=false"
    ).json()

    valid = [x["symbol"] for x in r]
    not_valid = [symb for symb in symbols if symb not in valid]

    if not_valid:
        sys.exit(f"\nError: Not valid symbol(s): {not_valid}.\n")

    return symbols

3 View Complete Implementation : conftest.py , under MIT License , by raiden-network
@pytest.fixture(autouse=True, scope="session")
def check_parity_version_for_tests(blockchain_type):
    if blockchain_type != "parity":
        return

    parity_version_string, _ = subprocess.Popen(
        ["parity", "--version"], stdout=subprocess.PIPE, stderr=subprocess.PIPE
    ).communicate()
    supported, _, our_version = is_supported_client(parity_version_string.decode())
    if not supported:
        sys.exit(
            f"You are trying to run tests with an unsupported PARITY version. "
            f"Your Version: {our_version} "
            f"Min Supported Version {LOWEST_SUPPORTED_PARITY_VERSION} "
            f"Max Supported Version {HIGHEST_SUPPORTED_PARITY_VERSION}"
        )

3 View Complete Implementation : images.py , under MIT License , by catleeball
def _compressPng(path):
    cmd = f"/usr/bin/zopflipng -m -y --lossy_8bit --lossy_transparent {path} {path}"
    retcode = subprocess.run(cmd, shell=True).returncode
    if retcode != 0:
        sys.stderr.write(f"zopfli subprocess exited with code {retcode}")
    return True

3 View Complete Implementation : root_commands.py , under MIT License , by thiagofigueiro
def cmd_delete(nexus_client, options):
    """Performs ``nexus3 delete``"""
    repository_path = options['<repository_path>']
    delete_count = nexus_client.delete(repository_path)

    _cmd_up_down_errors(delete_count, 'delete')

    file_word = PLURAL('file', delete_count)
    sys.stderr.write(f'Deleted {delete_count} {file_word}\n')
    return errors.CliReturnCode.SUCCESS.value

3 View Complete Implementation : preprocess.py , under MIT License , by jadore801120
def _download_file(download_dir, url):
    filename = url.split("/")[-1]
    if file_exist(download_dir, filename):
        sys.stderr.write(f"Already downloaded: {url} (at {filename}).\n")
    else:
        sys.stderr.write(f"Downloading from {url} to {filename}.\n")
        with TqdmUpTo(unit='B', unit_scale=True, miniters=1, desc=filename) as t:
            urllib.request.urlretrieve(url, filename=filename, reporthook=t.update_to)
    return filename

3 View Complete Implementation : compile.py , under Apache License 2.0 , by wsb310
def main():

    result = 0

    parser = argparse.ArgumentParser()

    parser.add_argument(r'-i', r'--input', default=r'./', dest=r'input')
    parser.add_argument(r'-o', r'--output', default=None, dest=r'output')
    parser.add_argument(r'-e', r'--exclude', default=None, dest=r'exclude')

    args = parser.parse_args()

    try:
        compile(args.input, args.output, args.exclude)
    except Exception as error:
        sys.stderr.write(f'{error}\n')

    return result

3 View Complete Implementation : h2buster.py , under GNU General Public License v3.0 , by 00xc
def parse_target(target):
	try:
		p = UrlParser(default_secure=DEFAULT_TLS, default_port=DEFAULT_PORT)
		p.parse(target)
		return p.secure, p.host, p.port, p.path
	except ValueError as error:
		sys.exit(colorstring(f"[-] {error}", status="red"))

3 View Complete Implementation : cmdlib.py , under Apache License 2.0 , by coreos
def info(msg):
    """
    Prints info messages.

    :param msg: The message to show to output
    :type msg: str
    """
    sys.stderr.write(f"info: {msg}")

3 View Complete Implementation : supreme_3.py , under MIT License , by zweed4u
    def find_product(self):
        while self.product_found == 0:
            current_mobile_json = self.fetch_mobile_stock()
            for category in list(current_mobile_json['products_and_categories'].values()):
                for item in category:
                    if self.item_name.lower() in item['name'].lower():
                        self.product_found = 1
                        listed_product_name = item['name']
                        listed_product_id = item['id']
                        sys.stdout.write(f'[[ {self.thread_text_color}{str(threading.current_thread().getName())}{COLOR_END} ]] {utc_to_est()} :: [[{self.thread_text_color}{listed_product_name}{COLOR_END} ]] {str(listed_product_id)} found ( MATCHING ITEM DETECTED )\n')
            if self.product_found != 1:
                sys.stdout.write(f'[[ {self.thread_text_color}{str(threading.current_thread().getName())}{COLOR_END} ]] {utc_to_est()} :: Reloading and reparsing page...\n')
                time.sleep(self.poll)
            else:
                color_id, size_id = self.find_product_variant(listed_product_name, listed_product_id)
                self.add_to_cart(listed_product_name, listed_product_id, color_id, size_id)

3 View Complete Implementation : polybar_ws.py , under GNU Lesser General Public License v3.0 , by neg-serg
    async def update_status(self):
        """ Print workspace information here. Event-based.
        """
        workspace = self.ws_name
        if not workspace[0].isalpha():
            workspace = polybar_ws.colorize(
                workspace[0], color=self.ws_color
            ) + workspace[1:]
        sys.stdout.write(f"{self.binding_mode + workspace}\n")
        await asyncio.sleep(0)

3 View Complete Implementation : submodules.py , under MIT License , by NephyProject
def importModule(name: str) -> ModuleType:
    for directory in os.listdir(submodulesDir):
        sys.path.append(f"{submodulesDir}/{directory}")

    try:
        submodule: ModuleType = importlib.import_module(name)
        return submodule
    except:
        raise ImportError(f"No named submodule {name}")

3 View Complete Implementation : usb.py , under MIT License , by cortexm
    def print_debug_data(self, msg, data, level=0):
        """Print info string with hexadecimal representation of data"""
        if self._debug >= level:
            if data is None:
                _sys.stderr.write(f"{msg}\n")
            else:
                _sys.stderr.write(
                    f"{msg}: {' '.join([f'{i:02x}' for i in data])}\n")

3 View Complete Implementation : base.py , under MIT License , by obestwalter
def i3configger_excepthook(type_, value, traceback):
    """Make own exceptions look like a friendly error message :)"""
    if DEBUG or not isinstance(value, exc.I3configgerException):
        _REAL_EXCEPTHOOK(type_, value, traceback)
    else:
        sys.exit(f"[FATAL] {type(value).__name__}: {value}")

3 View Complete Implementation : cli.py , under MIT License , by obestwalter
def main():
    """Wrap main to show own exceptions wo traceback in normal use."""
    args = process_command_line()
    try:
        _main(args)
    except exc.I3configgerException as e:
        if args.v > 2:
            raise
        sys.exit(f"[FATAL] {e}")

3 View Complete Implementation : test_all.py , under MIT License , by PacktPublishing
def run_pytest_suite(pkg_mod_iter: Iterable[Tuple[Path, Iterable[Path]]]) -> None:
    """Pytest each module's modules.
    """
    for package, module_iter in pkg_mod_iter:
        print()
        print(package.name)
        print("="*len(package.name))
        print()
        names = [f"{m.parent.name}/{m.name}" for m in (module_iter)]
        print(names)
        status = pytest.main(names)
        if status not in (PytestExit.Success, PytestExit.NoTests):
            sys.exit(f"Failure {PytestExit(status)!r} in {names}")

3 View Complete Implementation : bmex.py , under MIT License , by dxflores
def _validate_dates(start: dt, end: dt):
    """
    Validates start and end dates prior to polling data from BitMEX servers.
    """

    # Earliest date of data available.
    min_date = dt(2014, 11, 22)
    today = dt.today()

    if start < min_date:
        sys.exit(f"\nError: Start-date can't be earlier than {min_date.date()}\n")

    if end < start:
        sys.exit("\nError: End-date can't be earlier than start-date.\n")

    if end > today:
        end = today

    return start, end

3 View Complete Implementation : juanita.py , under GNU General Public License v3.0 , by python-discord
def _mock_syntax_error(message, line_no):
    """
    Output an error which is visually similar to a regular
    SyntaxError. This will refer to a line in the main script.
    """

    # fetch the exact erroneous line of the script.
    with open(__main__.__file__) as script:
        for line in range(line_no - 1):
            script.readline()

        error_line = script.readline().strip()

    sys.stderr.write(textwrap.dedent(f"""\
      File "{__main__.__file__}", line {line_no}
        {error_line}

    SyntaxError: {message}
    """))

3 View Complete Implementation : test.py , under BSD 3-Clause "New" or "Revised" License , by broadinstitute
def main():
    """Run unit tests."""

    tester = TestConsole()

    passed_tests = 0

    passed_tests += tester.test_data_simulation_and_write_and_read()
    passed_tests += tester.test_inference()

    sys.stdout.write(f'Passed {passed_tests} of 2 tests.\n\n')

3 View Complete Implementation : conftest.py , under MIT License , by raiden-network
@pytest.fixture(autouse=True, scope="session")
def check_geth_version_for_tests(blockchain_type):
    if blockchain_type != "geth":
        return

    geth_version_string, _ = subprocess.Popen(
        ["geth", "version"], stdout=subprocess.PIPE, stderr=subprocess.PIPE
    ).communicate()
    supported, _, our_version = is_supported_client(geth_version_string.decode())
    if not supported:
        sys.exit(
            f"You are trying to run tests with an unsupported GETH version. "
            f"Your Version: {our_version} "
            f"Min Supported Version {LOWEST_SUPPORTED_GETH_VERSION} "
            f"Max Supported Version {HIGHEST_SUPPORTED_GETH_VERSION}"
        )

3 View Complete Implementation : cli.py , under GNU General Public License v3.0 , by erik
def show_rule(name):
    """Print information about rule named ``name``."""
    color = {
        'bold': Style.BRIGHT,
        'reset': Style.RESET_ALL,
    }

    try:
        meta = rule.Registry.get_meta(name)
    except squabble.UnknownRuleException:
        sys.exit('{bold}Unknown rule:{reset} {name}'.format(**{
            'name': name,
            **color
        }))

    print('{bold}{name}{reset} - {description}\n\n{help}'.format(**{
        **meta,
        **color
    }))

3 View Complete Implementation : misc.py , under GNU General Public License v3.0 , by rrwick
def check_alignment_matches_read_and_refs(a, reads, refs):
    if a.read_name not in reads:
        sys.exit(f'\nError: could not find read {a.read_name}\n'
                 f'are you sure your read file and alignment file match?')
    if a.ref_name not in refs:
        sys.exit(f'\nError: could not find reference {a.ref_name}\nare you sure your '
                 f'reference file and alignment file match?')

3 View Complete Implementation : symportal_utils.py , under GNU General Public License v3.0 , by didillysquat
    def _pcr_validate_attributes_are_set(self):
        sys.stdout.write(f'\nValidating PCR attributes are set\n')
        if self.fasta_path is None:
            raise RuntimeError('Fasta_path is None. A valid fasta_path is required to perform the pcr method.')
        if self.pcr_fwd_primer is None or self.pcr_rev_primer is None:
            if self.pcr_fwd_primer is None and self.pcr_rev_primer is None:
                raise RuntimeError('Please set fwd_primer and rev_primer: ')
            elif self.pcr_fwd_primer is None:
                raise RuntimeError('Please set fwd_primer.')
            elif self.pcr_rev_primer is None:
                raise RuntimeError('Please set fwd_primer.')
        sys.stdout.write(f'\nPCR attributes: OK\n')

3 View Complete Implementation : peer_fcs.py , under GNU General Public License v3.0 , by P2PSP
    def receive_public_endpoint(self):
        msg_length = struct.calcsize("!Ii")
        msg = self.splitter_socket.recv(msg_length)
        pe = struct.unpack("!Ii", msg)
        self.public_endpoint = (IP_tools.int2ip(pe[0]), pe[1])
        self.lg.info(f"{self.id}: public_endpoint={self.public_endpoint}")

        #self.peer_number = self.number_of_peers
        self.ext_id = ("%03d" % self.peer_index_in_team, self.public_endpoint[0], "%5d" % self.public_endpoint[1])
        self.lg.info(f"{self.ext_id}: peer_index_in_team={self.peer_index_in_team}")
        sys.stderr.write(f"{self.name} {self.ext_id} alive :-)\n")

3 View Complete Implementation : root_commands.py , under MIT License , by thiagofigueiro
def cmd_download(nexus_client, args):
    """Performs ``nexus3 download``"""
    source = args['<from_repository>']
    destination = args['<to_dst>']

    sys.stderr.write(f'Downloading {source} to {destination}\n')

    download_count = nexus_client.download(
                        source, destination,
                        flatten=args.get('--flatten'),
                        nocache=args.get('--nocache'))

    _cmd_up_down_errors(download_count, 'download')

    file_word = PLURAL('file', download_count)
    sys.stderr.write(
        f'Downloaded {download_count} {file_word} to {destination}\n')
    return errors.CliReturnCode.SUCCESS.value

3 View Complete Implementation : config.py , under MIT License , by intel
    async def run(self):
        original_path = pathlib.Path(self.original)
        config_out = self.config_out.withconfig(self.extra_config)
        # Load input configloader
        config_in = self.config_in
        if config_in is None:
            config_type = original_path.suffix.replace(".", "")
            config_in = BaseConfigLoader.load(config_type)
        config_in = config_in.withconfig(self.extra_config)
        async with config_in as cl_in, config_out as cl_out:
            async with cl_in() as loader_in, cl_out() as loader_out:
                imported = await loader_in.loadb(original_path.read_bytes())
                sys.stdout.buffer.write(await loader_out.dumpb(imported))

3 View Complete Implementation : client.py , under MIT License , by tryexceptpass
    def __init__(self, host='localhost', port=8022, client_keys=None, known_hosts=None, max_packet_size=32768):
        self.max_packet_size = max_packet_size

        self._loop = asyncio.new_event_loop()
        asyncio.set_event_loop(self._loop)
        self._session = asyncio.get_event_loop().run_until_complete(self.__connect(host, port, known_hosts, client_keys))

        try:
            t = Thread(target=self.__start_loop, args=(self._loop,))
            t.start()
            # asyncio.run_coroutine_threadsafe(self.__connect(), self._loop)

        except (OSError, asyncssh.Error) as exc:
            sys.exit(f'SSH connection failed: {exc}')

3 View Complete Implementation : images.py , under MIT License , by catleeball
def _convertToWebp(path):
    cwebp_cmd = f"/usr/bin/cwebp -q 60 -mt -m 6 -af {path} -o {path}.webp"
    retcode = subprocess.run(cwebp_cmd, shell=True).returncode
    if retcode != 0:
        sys.stderr.write(f"cwebp subprocess exited with code {retcode}")
        # Not a critical error, just return the png
        return path

    logo_path = f"{path}.webp"
    sys.stderr.write(f"path is {logo_path}")
    return logo_path

3 View Complete Implementation : base_client.py , under MIT License , by willcl-ark
    @property
    def macaroon(self):
        """
        try to open the macaroon and return it as a byte string
        """
        try:
            with open(self.macaroon_path, "rb") as f:
                macaroon_bytes = f.read()
                macaroon = codecs.encode(macaroon_bytes, "hex")
                return macaroon
        except FileNotFoundError:
            sys.stderr.write(
                f"Could not find macaroon in {self.macaroon_path}. This might happen"
                f"in versions of lnd < v0.5-beta or those not using default"
                f"installation path. Set client object's macaroon_path attribute"
                f"manually."
            )

3 View Complete Implementation : preprocess.py , under MIT License , by jadore801120
def encode_file(bpe, in_file, out_file):
    sys.stderr.write(f"Read raw content from {in_file} and \n"\
            f"Write encoded content to {out_file}\n")
    
    with codecs.open(in_file, encoding='utf-8') as in_f:
        with codecs.open(out_file, 'w', encoding='utf-8') as out_f:
            for line in in_f:
                out_f.write(bpe.process_line(line))

3 View Complete Implementation : supreme.py , under MIT License , by zweed4u
    def find_product_variant(self, product_name, product_id):
        sys.stdout.write(f'[[ {self.thread_text_color}{str(threading.current_thread().getName())}{COLOR_END} ]] {utc_to_est()} :: Selecting [[ {self.thread_text_color}{product_name}{COLOR_END} ]] ( {str(product_id)} )\n')
        product_info = self.get_product_information(product_id)
        for listed_product_colors in product_info['styles']:
            if self.item_color.lower() in listed_product_colors['name'].lower():
                self.product_color_found = 1
                product_color_specific_id = listed_product_colors['id']
                for size in listed_product_colors['sizes']:
                    if self.item_size.lower() == size['name'].lower():
                        self.product_size_found = 1
                        product_size_color_specific_id = size['id']
                        sys.stdout.write(f'[[ {self.thread_text_color}{str(threading.current_thread().getName())}{COLOR_END} ]] {utc_to_est()} :: Selecting size for [[ {self.thread_text_color}{product_name}{COLOR_END} ]] - {self.item_size} ( {self.item_color} )  ( {str(product_size_color_specific_id)} )\n')
                if self.product_size_found != 1:
                    # Add functionality to add default size on matching color product
                    pass
        if self.product_color_found != 1:
            # Add functionality to add default color AND size on matching product model
            pass
        return product_color_specific_id, product_size_color_specific_id

3 View Complete Implementation : supreme_3.py , under MIT License , by zweed4u
    def find_product_variant(self, product_name, product_id):
        sys.stdout.write(f'[[ {self.thread_text_color}{str(threading.current_thread().getName())}{COLOR_END} ]] {utc_to_est()} :: Selecting [[{self.thread_text_color}{product_name}{COLOR_END}]] ( {str(product_id)} )\n')
        product_info = self.get_product_information(product_id)
        for listed_product_colors in product_info['styles']:
            if self.item_color.lower() in listed_product_colors['name'].lower():
                self.product_color_found = 1
                product_color_specific_id = listed_product_colors['id']
                for size in listed_product_colors['sizes']:
                    if self.item_size.lower() == size['name'].lower():
                        self.product_size_found = 1
                        product_size_color_specific_id = size['id']
                        sys.stdout.write(f'[[ {self.thread_text_color}{str(threading.current_thread().getName())}{COLOR_END} ]] {utc_to_est()} :: Selecting size for [[ {self.thread_text_color}{product_name}{COLOR_END} ]] - {self.item_size} ( {self.item_color} )  ( {str(product_size_color_specific_id)} )\n')
                if self.product_size_found != 1:
                    # Add functionality to add default size on matching color product
                    pass
        if self.product_color_found != 1:
            # Add functionality to add default color AND size on matching product model
            pass
        return product_color_specific_id, product_size_color_specific_id

3 View Complete Implementation : main.py , under BSD 3-Clause "New" or "Revised" License , by johnramsden
    def get_command(self, ctx, name):
        ns = {}
        fn = os.path.join(command_modules_folder, name + '.py')
        if not os.path.isfile(fn):
            sys.exit(f"Command '{name}' doesn't exist, run 'zedenv --help'")
        with open(fn) as f:
            code = compile(f.read(), fn, 'exec')
            eval(code, ns, ns)
        return ns['cli']

3 View Complete Implementation : inspect.py , under Apache License 2.0 , by adamcharnock
    def compare(self, comparator: str, left_value, right_value):
        """Utility for performing arbitrary comparisons"""
        lookup = {
            "=": lambda: left_value == right_value,
            "!=": lambda: left_value != right_value,
            "<": lambda: left_value < right_value,
            ">": lambda: left_value > right_value,
            "<=": lambda: left_value <= right_value,
            ">=": lambda: left_value >= right_value,
        }

        if comparator not in lookup:
            sys.stderr.write(f"Unknown comparator '{comparator}'\n")
            sys.exit(1)

        return lookup[comparator]()

3 View Complete Implementation : test_all.py , under MIT License , by PacktPublishing
def run(pkg_mod_iter: Iterable[Tuple[Path, Iterable[Path]]]) -> None:
    """Run each module, with a few exclusions."""
    for package, module_iter in pkg_mod_iter:
        print()
        print(package.name)
        print("="*len(package.name))
        print()
        for module in module_iter:
            if module.stem in DOCTEST_EXCLUDE:
                print(f"Excluding {module}")
                continue
            status = runpy.run_path(module, run_name="__main__")
            if status != 0:
                sys.exit(f"Failure: {module}")

3 View Complete Implementation : data_utils.py , under Apache License 2.0 , by asyml
def _download(url: str, filename: str, path: str) -> str:
    def _progress_hook(count, block_size, total_size):
        percent = float(count * block_size) / float(total_size) * 100.
        sys.stdout.write(f'\r>> Downloading {filename} {percent:.1f}%')
        sys.stdout.flush()

    filepath = os.path.join(path, filename)
    filepath, _ = urllib.request.urlretrieve(url, filepath, _progress_hook)
    print()
    statinfo = os.stat(filepath)
    print(f'Successfully downloaded {filename} {statinfo.st_size} bytes')

    return filepath

3 View Complete Implementation : virtual_objects.py , under GNU General Public License v3.0 , by didillysquat
    def _populate_virtual_dss_manager_from_db(self):
        print('\nInstantiating VirtualDataSetSamples')
        list_of_data_set_samples_of_analysis = self._chunk_query_dss_objs_from_dss_uids()

        for dss in list_of_data_set_samples_of_analysis:
            sys.stdout.write(f'\r{dss.name}')
            new_vdss = self.VirtualDataSetSample(
                uid=dss.id, data_set_id=dss.data_submission_from.id,
                list_of_cc_uids=[cc.id for cc in CladeCollection.objects.filter(data_set_sample_from=dss)],
                name=dss.name,list_of_cladal_abundances=[int(_) for _ in json.loads(dss.cladal_seq_totals)])
            self.vdss_dict[new_vdss.uid] = new_vdss

3 View Complete Implementation : test_all.py , under MIT License , by PacktPublishing
def run_doctest_suite(pkg_mod_iter: Iterable[Tuple[Path, Iterable[Path]]]) -> None:
    """Doctest each module individually. With a few exclusions.

    Might be simpler to use doctest.testfile()? However, the examples aren't laid out for this.
    """
    for package, module_iter in pkg_mod_iter:
        print()
        print(package.name)
        print("="*len(package.name))
        print()
        for module_path in module_iter:
            if module_path.stem in DOCTEST_EXCLUDE:
                print(f"Excluding {module_path}")
                continue
            result = subprocess.run(['python3', '-m', 'doctest', str(module_path)])
            if result.returncode != 0:
                sys.exit(f"Failure {result!r} in {module_path}")

2 View Complete Implementation : inspect.py , under Apache License 2.0 , by adamcharnock
    def handle(self, args, config, plugin_registry: PluginRegistry):
        """Entrypoint for the inspect command"""
        command_utilities.setup_logging(args.log_level or "warning", config)
        bus_module, bus = command_utilities.import_bus(args)
        api_names: List[str]

        block(bus.client.lazy_load_now())

        # Locally registered APIs
        api_names = [api.meta.name for api in bus.client.api_registry.all()]

        # APIs registered to other services on the bus
        for api_name in bus.client.schema.api_names:
            if api_name not in api_names:
                api_names.append(api_name)

        if not args.internal and not args.api:
            # Hide internal APIs if we don't want them
            api_names = [api_name for api_name in api_names if not api_name.startswith("internal.")]

        if args.api and args.api not in api_names:
            sys.stderr.write(
                f"Specified API was not found locally or within the schema on the bus.\n"
                f"Ensure a Lightbus worker is running for this API.\n"
                f"Cannot continue.\n"
            )
            sys.exit(1)

        api_names_to_inspect = []
        for api_name in api_names:
            if not args.api or self.wildcard_match(args.api, api_name):
                api_names_to_inspect.append(api_name)

        if len(api_names_to_inspect) != 1 and args.follow:
            sys.stderr.write(
                f"The --follow option is only available when following a single API.\n"
                f"Please specify the --api option to select a single API to follow.\n"
            )
            sys.exit(1)

        try:
            for api_name in api_names_to_inspect:
                if not args.api or self.wildcard_match(args.api, api_name):
                    logger.debug(f"Inspecting {api_name}")
                    block(self.search_in_api(args, api_name, bus))
                else: