Example #1
0
    def stop_command(self, index, command, returncode):
        """
        Indicate that a command stopped.

        :param index: The index of the command.
        :param command: The command that was executed, as an unicode string.
        :param returncode: The exit status.
        """
        self.stream.write(
            self.format_output(
                "{}\t[{}]\n",
                " " * (self.longest_len - len(command)),
                success("success") if returncode == 0 else error("failed"),
            ))

        if returncode != 0:
            self.binary_stream.write(self.output_map[index].getvalue())
            self.stream.write(
                self.format_output(
                    "{}) {} {}\n",
                    warning(important(index + 1)),
                    error("Command exited with"),
                    important(error(returncode)),
                ))

        del self.output_map[index]
Example #2
0
 def prepare(self, timeout = 6.0):
     time_left = timeout
     while True:
         try:
             self.dev = self._prepare()
         except usb.core.USBError as e:
             if e.errno == 13:
                 logger.warning('Access denied, configure udev or run as root')
                 raise
         if self.dev is None:
             if timeout == 0:
                 return False
             elif timeout == None:
                 sleep(3.0)
             else:
                 time_left = time_left - 3.0
                 if time_left <= 0:
                     break
                 sleep(3.0)
         else:
             break
     if self.dev == None:
         logger.warning("Giving up waiting")
         return False
     else:
         logger.info("EV2300: %s", success("READY"))
         return True
Example #3
0
    def on_process_queue_item_received(self, item):
        exit_status, output = item

        if exit_status is None:
            # process produced output and is still running
            self.adapter.info('%s', output.strip())
        else:
            if exit_status == 0:
                self.adapter.info('### END PROCESS - exit status %s ###',
                                  success(exit_status))
            else:
                self.adapter.info('### END PROCESS - exit status %s ###',
                                  error(exit_status))

            self.p = None
Example #4
0
def main():
    try:
        log.info("%s", success(
            """
                ##############>>>>>>>>>>^^<<<<<<<<<<##############
                #               ***Preetify***                   #
                #                 By Ethical                     #
                #                July 16th, 2017                 #
                #    This Script uses the bs4's BeautifulSoup    #
                #    preetify function to clean a html file      #
                ##############>>>>>>>>>>^^<<<<<<<<<<##############
               """))
        req()
    except KeyboardInterrupt:
        log.info("%s", warn("Going to shutdown..."+"\n"))
    except Exception, e:
        log.info("%s", warn(e + ": Shutting down..."+"\n"))
Example #5
0
def preety(file_list):
    try:
        if not os.path.exists(os.getcwd()+r"/pretty"):
            os.mkdir("pretty")
        for file in file_list:
            with open(file, "r") as fp:
                soup = bs(fp, 'html.parser')
                clean_file = soup.prettify("utf-8")
                os.chdir("pretty")
            with open(file, "w") as f:
                f.write(clean_file)
                os.chdir("..")
        log.info("%s", success("\n"+"Files have been successfully cleaned...exiting..."+"\n"))
        exit()
    except IndexError:
        log.info("%s", red("\n"+"at least on of the file numbers you picked is Incorrect...check your inputs..."))
    except Exception,e:
        error(e)
import logging
import chromalog

from chromalog.mark.helpers.simple import success, error, important

chromalog.basicConfig(format="%(message)s", level=logging.INFO)
logger = logging.getLogger()

filename = r'/var/lib/status'

logger.info("Booting up system: %s", success("OK"))
logger.info("Booting up network: %s", error("FAIL"))
logger.info("Reading file at %s: %s", important(filename), success("OK"))
if not os.path.exists(directory):
    logger.info("Creating directory")
    os.makedirs(directory)

page = 1
count = 0
while not isEnd:
    isEnd = True
    url = "http://unsplash.com/?page=" + str(page)
    content = urllib.urlopen(url).read()

    for s in re.findall(pattern,content):
        pic = "http://unsplash.com/photos/" + s + "/download"
        filename = directory + "/" + s + ".jpeg"

        logger.info("Loading:\t %s", s)

        if not os.path.exists(filename):
            urllib.urlretrieve(pic, filename)

            logger.info("Loaded:\t %s (%d)", success(s), count)

            count += 1
            isEnd = False
        else:
            logger.warning(s + " Exists")

    page += 1

logger.info("%s %d %s", success("Successfully downloaded"), count, success("pictures"))
Example #8
0
def main():
    # check dependencies are available
    check_exe_available('latexpand')

    # setup docopt and logging
    args = docopt(__doc__, version='0.1.1')

    logger_format = '%(asctime)s [%(levelname)s] - %(message)s'
    chromalog.basicConfig(
        level=logging.DEBUG if args['--verbose'] else logging.INFO,
        format=logger_format)
    logger = logging.getLogger('texstrip')

    # disable parser logger
    logging.getLogger('strip_comments').setLevel(logging.INFO)

    # the main TeX input file
    main_file = args['<main>']
    logger.info('using {} as the main file'.format(main_file))

    # create the target dir
    output_dir = os.path.join(os.getcwd(), args['--outdir'])
    os.makedirs(output_dir, exist_ok=True)

    logger.info("using {} as the output dir".format(output_dir))

    # 1) expand the main file
    target_main_file = os.path.join(output_dir, os.path.basename(main_file))
    # names for intermediate files
    expanded_main_file = os.path.join(output_dir, 'expanded.tex.strip')
    stripped_main_file = os.path.join(output_dir, 'stripped.tex.strip')

    if target_main_file == main_file:
        raise Exception('target main file is the same as the source')

    cmd = 'latexpand --empty-comments -o {} {}'.format(expanded_main_file,
                                                       main_file)
    subprocess.run(cmd, shell=True, check=True)
    logger.debug('Finished: {}'.format(cmd))

    if args['<extra>']:
        for extra in args['<extra>']:
            # detect files outside working tree
            path = pathlib.Path(extra)
            logging.info("copying %s", path)
            if str(path.relative_to('.')).startswith('..'):
                logging.fatal("can't copy files outside current dir %s", extra)
                sys.exit(1)
            if path.parent == '.':
                shutil.copy(path, output_dir)
            else:
                new_dir = pathlib.Path(output_dir) / path.parent
                new_dir.mkdir(parents=True, exist_ok=True)

                shutil.copy(path, new_dir)

    # 2) remove comments
    strip_comments.strip_comments_from_files(expanded_main_file,
                                             stripped_main_file)

    # 3) clean up
    shutil.copyfile(stripped_main_file, target_main_file)
    # remove intermediate files unless --keep
    if not args['--keep']:
        os.remove(expanded_main_file)
        os.remove(stripped_main_file)

    if args['--build']:
        os.chdir(output_dir)
        build_cmd = "latexmk -pdf {}".format(target_main_file)
        subprocess.run(build_cmd, shell=True, check=True)
        build_cmd = "latexmk -C {}".format(target_main_file)
        subprocess.run(build_cmd, shell=True, check=True)

    from chromalog.mark.helpers.simple import success, important

    logger.info("%s The stripped version is at %s" %
                (success("Done!"), important(target_main_file)))
formatter = ColorizingFormatter('[%(levelname)s] %(message)s')

handler = ColorizingStreamHandler()
handler.setFormatter(formatter)

logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
logger.addHandler(handler)

logger.info("This is a regular info log message.")
logger.info(
    "Trying to read user information from %s using a json parser.",
    important(r'/usr/local/mylib/user-info.json'),
)
logger.warning(
    "Unable to read the file at %s ! Something is wrong.",
    important(r'/usr/local/mylib/user-info.json'),
)
logger.error("Something went really wrong !")
logger.info(
    "This is a %s and this is an %s.",
    success("success"),
    error("error"),
)
logger.info(
    "You can combine %s and %s to get an %s !",
    success("success"),
    important("important"),
    important(success("important-success")),
)
Example #10
0
            if idx == PERSON_INDEX:
                logger.debug("found a person in range. calculating offset...")
                box = detections[0, 0, i, 3:7] * np.array([w, h, w, h])
                (startX, startY, endX, endY) = box.astype("int")

                middleX = endX - (endX - startX) / 2
                middleY = (
                    # endY - (endY - startY)
                    startY
                    + (endY - startY) / 4
                )  # we want to focus face, not stomach

                offsetX = w / 2 - middleX
                offsetY = h / 2 - middleY

                logger.debug("offset: X: %s Y: %s", success(offsetX), success(offsetY))
                if abs(offsetY) < 5 and abs(offsetX) < 5:
                    logger.debug("position is perfect!")
                else:
                    # rotate here
                    logger.debug("adjusting position...")
                    speed = 40
                    try:
                        if offsetY > 0:
                            vertical.turn(-speed, abs(offsetY))
                        else:
                            vertical.turn(speed, abs(offsetY))

                        if offsetX > 0:
                            horizontal.turn(-speed, abs(offsetX))
                        else:
Example #11
0
def info(ctx, fetch):
    debug = ctx.obj['debug']
    loop = ctx.obj['loop']
    plm = ctx.obj['plm']
    database = ctx.obj['database']

    try:
        logger.info(
            "Device information for PowerLine Modem on serial port: %s",
            important(plm.serial_port_url),
        )
        logger.info(
            "Device category: %s (%s)",
            important(plm.device_category.title),
            plm.device_category.examples,
        )
        logger.info(
            "Device subcategory: %s",
            important(plm.device_subcategory.title),
        )
        logger.info("Identity: %s", important(plm.identity))
        logger.info("Firmware version: %s", important(plm.firmware_version))

        controllers, responders = loop.run_until_complete(
            plm.get_all_link_records(),
        )

        devices = database.get_devices()

        if fetch:
            missing_device_identities = {
                record.identity for record in chain(controllers, responders)
                if devices.get(record.identity) is None
            }

            if missing_device_identities:
                logger.info(
                    "Fetching missing device information for %d device(s)...",
                    len(missing_device_identities),
                )

                for index, identity in enumerate(
                    missing_device_identities,
                    start=1,
                ):
                    logger.info(
                        "[%d/%d] %s...",
                        index,
                        len(missing_device_identities),
                        identity,
                    )

                    try:
                        device_info = loop.run_until_complete(
                            asyncio.wait_for(
                                plm.id_request(identity),
                                2,
                            ),
                        )
                    except asyncio.TimeoutError:
                        logger.info(
                            "[%d/%d] %s: %s",
                            index,
                            len(missing_device_identities),
                            identity,
                            error("timed out"),
                        )
                    else:
                        devices[identity] = database.set_device(
                            identity=device_info['identity'],
                            alias=None,
                            description=None,
                            category=device_info['category'],
                            subcategory=device_info['subcategory'],
                            firmware_version=device_info['firmware_version'],
                        )
                        logger.info(
                            "[%d/%d] %s: %s",
                            index,
                            len(missing_device_identities),
                            identity,
                            success("success"),
                        )

                logger.info("Done fetching missing device information.")

        if controllers:
            logger.info("Controllers:")

            for controller in controllers:
                device = devices.get(controller.identity)

                if device:
                    logger.info("%s - %s", controller, success(device))
                else:
                    logger.info("%s", controller)

        if responders:
            logger.info("Responders:")

            for responder in responders:
                device = devices.get(responder.identity)

                if device:
                    logger.info("%s - %s", responder, success(device))
                else:
                    logger.info("%s", responder)

    except Exception as ex:
        if debug:
            logger.exception("Unexpected error.")
        else:
            logger.error("Unexpected error: %s.", ex)