Пример #1
0
def main():
    judgeenv.load_env(cli=True, testsuite=True)

    # Emulate ANSI colors with colorama
    if os.name == 'nt' and not judgeenv.no_ansi_emu:
        try:
            from colorama import init
            init()
        except ImportError:
            pass

    logging.basicConfig(
        filename=judgeenv.log_file,
        level=logging.INFO,
        format='%(levelname)s %(asctime)s %(module)s %(message)s')

    executors.load_executors()

    tester = Tester(judgeenv.problem_regex, judgeenv.case_regex)
    fails = tester.test_all()
    print()
    print('Test complete')
    if fails:
        print(
            ansi_style('#ansi[A total of %d case(s) failed](red|bold).') %
            fails)
    else:
        print(ansi_style('#ansi[All cases passed.](green|bold)'))
    raise SystemExit(int(fails != 0))
Пример #2
0
def main():  # pragma: no cover
    sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
    if not sanity_check():
        return 1

    from dmoj import judgeenv, executors

    judgeenv.load_env()

    # Emulate ANSI colors with colorama
    if os.name == 'nt' and not judgeenv.no_ansi_emu:
        try:
            from colorama import init
            init()
        except ImportError:
            pass

    executors.load_executors()

    print 'Running live judge...'

    for warning in judgeenv.startup_warnings:
        print ansi_style('#ansi[Warning: %s](yellow)' % warning)
    del judgeenv.startup_warnings

    if os.name == 'posix' and 'judges' in env:
        if env.pidfile:
            with open(env.pidfile) as f:
                f.write(str(os.getpid()))
        manager = JudgeManager(env.judges)
        manager.run()
    else:
        return judge_proc(need_monitor=True)
Пример #3
0
def main():
    logging.basicConfig(level=logging.INFO)

    sys.stdout = codecs.getwriter('utf-8')(os.fdopen(sys.stdout.fileno(), 'w',
                                                     0))
    sys.stderr = codecs.getwriter('utf-8')(os.fdopen(sys.stderr.fileno(), 'w',
                                                     0))

    judgeenv.load_env(cli=True, testsuite=True)
    executors.load_executors()

    executor_fail = not all(name in executors.executors
                            for name in required_executors)
    if executor_fail:
        print(
            ansi_style('#ansi[A required executor failed to load.](red|bold)'))
    else:
        print(
            ansi_style(
                '#ansi[All required executors loaded successfully.](green|bold)'
            ))
    print()

    tester = Tester(judgeenv.problem_regex, judgeenv.case_regex)
    fails = tester.test_all()
    print()
    print('Test complete')
    if fails:
        print(
            ansi_style('#ansi[A total of %d case(s) failed](red|bold).') %
            fails)
    else:
        print(ansi_style('#ansi[All cases passed.](green|bold)'))
    raise SystemExit(int(executor_fail or fails != 0))
Пример #4
0
def main():
    logging.basicConfig(level=logging.INFO)

    sys.stdout = codecs.getwriter('utf-8')(os.fdopen(sys.stdout.fileno(), 'w', 0))
    sys.stderr = codecs.getwriter('utf-8')(os.fdopen(sys.stderr.fileno(), 'w', 0))

    judgeenv.load_env(cli=True, testsuite=True)
    judgeenv.env['id'] = 'testsuite'
    executors.load_executors()

    executor_fail = not all(name in executors.executors for name in required_executors)
    if executor_fail:
        print(ansi_style('#ansi[A required executor failed to load.](red|bold)'))
    else:
        print(ansi_style('#ansi[All required executors loaded successfully.](green|bold)'))
    print()

    tester = Tester(judgeenv.problem_regex, judgeenv.case_regex)
    fails = tester.test_all()
    print()
    print('Test complete')
    if fails:
        print(ansi_style('#ansi[A total of %d case(s) failed](red|bold).') % fails)
    else:
        print(ansi_style('#ansi[All cases passed.](green|bold)'))
    raise SystemExit(int(executor_fail or fails != 0))
Пример #5
0
def main():
    judgeenv.load_env(cli=True, testsuite=True)

    # Emulate ANSI colors with colorama
    if os.name == 'nt' and not judgeenv.no_ansi_emu:
        try:
            from colorama import init
            init()
        except ImportError:
            pass

    logging.basicConfig(filename=judgeenv.log_file, level=logging.INFO,
                        format='%(levelname)s %(asctime)s %(module)s %(message)s')

    executors.load_executors()

    tester = Tester(judgeenv.problem_regex, judgeenv.case_regex)
    fails = tester.test_all()
    print()
    print('Test complete')
    if fails:
        print(ansi_style('#ansi[A total of %d case(s) failed](red|bold).') % fails)
    else:
        print(ansi_style('#ansi[All cases passed.](green|bold)'))
    raise SystemExit(int(fails != 0))
Пример #6
0
def main():
    # setup judge
    judgeenv.load_env(cli=True)
    executors.load_executors()
    print('Running grpc judge server ...')
    logging.basicConfig(
        filename=judgeenv.log_file,
        level=logging.INFO,
        format='%(levelname)s %(asctime)s %(module)s %(message)s')
    for warning in judgeenv.startup_warnings:
        print(ansi_style('#ansi[Warning: %s](yellow)' % warning))
    del judgeenv.startup_warnings
    print()

    judge = LocalJudge()

    loop = asyncio.get_event_loop()

    server = Server([DmojService(judge)], loop=loop)

    host, port = '127.0.0.1', 5001
    loop.run_until_complete(server.start(host, port))
    print('Serving on {}:{}'.format(host, port))
    try:
        loop.run_forever()
    except KeyboardInterrupt:
        pass
    server.close()
    loop.run_until_complete(server.wait_closed())
    loop.close()
def main():
    sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
    sys.stderr = os.fdopen(sys.stderr.fileno(), 'w', 0)

    judgeenv.load_env(cli=True, testsuite=True)
    executors.load_executors()

    executor_fail = not all(name in executors.executors
                            for name in required_executors)
    if executor_fail:
        print ansi_style(
            '#ansi[A required executor failed to load.](red|bold)')
    else:
        print ansi_style(
            '#ansi[All required executors loaded successfully.](green|bold)')
    print

    tester = Tester(judgeenv.problem_regex, judgeenv.case_regex)
    fails = tester.test_all()
    print
    print 'Test complete'
    if fails:
        print ansi_style(
            '#ansi[A total of %d case(s) failed](red|bold).') % fails
    else:
        print ansi_style('#ansi[All cases passed.](green|bold)')
    raise SystemExit(int(executor_fail or fails != 0))
Пример #8
0
def main():
    global commands
    import logging
    from dmoj import judgeenv, executors

    judgeenv.load_env(cli=True)

    # Emulate ANSI colors with colorama
    if os.name == 'nt' and not judgeenv.no_ansi_emu:
        try:
            from colorama import init
            init()
        except ImportError as ignored:
            pass

    executors.load_executors()

    print 'Running local judge...'

    logging.basicConfig(
        filename=judgeenv.log_file,
        level=logging.INFO,
        format='%(levelname)s %(asctime)s %(module)s %(message)s')

    judge = LocalJudge()

    for warning in judgeenv.startup_warnings:
        print ansi_style('#ansi[Warning: %s](yellow)' % warning)
    del judgeenv.startup_warnings
    print

    for command in [
            ListProblemsCommand, ListSubmissionsCommand, SubmitCommand,
            ResubmitCommand, RejudgeCommand, HelpCommand, QuitCommand
    ]:
        register(command(judge))

    with judge:
        try:
            judge.listen()
        except:
            traceback.print_exc()
        finally:
            judge.murder()

    while True:
        command = raw_input(
            ansi_style("#ansi[dmoj](magenta)#ansi[>](green) ")).strip()

        line = command.split(' ')
        if line[0] in commands:
            cmd = commands[line[0]]
            try:
                cmd.execute(line[1:])
            except InvalidCommandException:
                print
        else:
            print ansi_style('#ansi[Unrecognized command %s](red|bold)' %
                             line[0])
            print
Пример #9
0
def cli_main():
    import logging
    from dmoj import judgeenv, executors

    judgeenv.load_env(cli=True)
    executors.load_executors()

    print('Running local judge...')

    logging.basicConfig(
        filename=judgeenv.log_file,
        level=logging.INFO,
        format='%(levelname)s %(asctime)s %(module)s %(message)s')

    judge = LocalJudge()

    for warning in judgeenv.startup_warnings:
        print_ansi('#ansi[Warning: %s](yellow)' % warning)
    del judgeenv.startup_warnings
    print()

    from dmoj.commands import all_commands, commands, register_command
    for command in all_commands:
        register_command(command(judge))

    def run_command(line):
        if not line:
            return 127

        if line[0] in commands:
            cmd = commands[line[0]]
            try:
                return cmd.execute(line[1:])
            except InvalidCommandException as e:
                if e.message:
                    print_ansi("#ansi[%s](red|bold)\n" % e.message)
                print()
                return 1
        else:
            print_ansi('#ansi[Unrecognized command %s](red|bold)' % line[0])
            print()
            return 127

    with judge:
        try:
            judge.listen()

            if judgeenv.cli_command:
                return run_command(judgeenv.cli_command)
            else:
                while True:
                    command = input(
                        ansi_style(
                            "#ansi[dmoj](magenta)#ansi[>](green) ")).strip()
                    run_command(shlex.split(command))
        except (EOFError, KeyboardInterrupt):
            print()
        finally:
            judge.murder()
Пример #10
0
def main():  # pragma: no cover
    if six.PY2:
        sys.stdout = codecs.getwriter('utf-8')(os.fdopen(
            sys.stdout.fileno(), 'w', 0))
        sys.stderr = codecs.getwriter('utf-8')(sys.stderr)
    else:
        sys.stdout = codecs.getwriter('utf-8')(open(sys.stdout.fileno(),
                                                    'wb',
                                                    0,
                                                    closefd=False))
        sys.stderr = codecs.getwriter('utf-8')(sys.stderr.detach())

    if not sanity_check():
        return 1

    from dmoj import judgeenv, executors

    judgeenv.load_env()

    # Emulate ANSI colors with colorama
    if os.name == 'nt' and not judgeenv.no_ansi_emu:
        try:
            from colorama import init
            init()
        except ImportError:
            pass

    executors.load_executors()

    if hasattr(signal, 'SIGUSR2'):
        signal.signal(signal.SIGUSR2, signal.SIG_IGN)

    print('Running live judge...')

    for warning in judgeenv.startup_warnings:
        print(ansi_style('#ansi[Warning: %s](yellow)' % warning))
    del judgeenv.startup_warnings

    if os.name == 'posix' and 'judges' in env:
        logfile = judgeenv.log_file
        try:
            logfile = logfile % 'master'
        except TypeError:
            pass
        logging.basicConfig(
            filename=logfile,
            level=logging.INFO,
            format='%(levelname)s %(asctime)s %(process)d %(name)s %(message)s'
        )
        if env.pidfile:
            with open(env.pidfile) as f:
                f.write(str(os.getpid()))
        manager = JudgeManager(env.judges)
        manager.run()
    else:
        return judge_proc(need_monitor=True)
Пример #11
0
def main():
    result = {}

    if os.name == 'nt':
        judgeenv.load_env(cli=True)
        if not judgeenv.no_ansi_emu:
            try:
                from colorama import init
                init()
            except ImportError:
                pass

    judgeenv.env['runtime'] = {}

    for name in get_available():
        executor = load_executor(name)

        if executor is None or not hasattr(executor, 'Executor'):
            continue

        if hasattr(executor.Executor, 'autoconfig'):
            print ansi_style(
                '%-43s%s' %
                ('Auto-configuring #ansi[%s](|underline):' % name, '')),
            try:
                data = executor.Executor.autoconfig()
                config = data[0]
                success = data[1]
                feedback = data[2]
                errors = '' if len(data) < 4 else data[3]
            except Exception:
                print ansi_style('#ansi[Not supported](red|bold)')
                traceback.print_exc()
            else:
                print ansi_style(
                    ['#ansi[%s](red|bold)', '#ansi[%s](green|bold)'][success] %
                    (feedback or ['Failed', 'Success'][success]))

                if not success:
                    if config:
                        print '  Attempted:'
                        print '   ', yaml.dump(
                            config, default_flow_style=False).rstrip().replace(
                                '\n', '\n' + ' ' * 4)

                    if errors:
                        print '  Errors:'
                        print '   ', errors.replace('\n', '\n' + ' ' * 4)

                if success:
                    result.update(config)

    print
    print ansi_style('#ansi[Configuration result](green|bold|underline):')
    print yaml.dump({'runtime': result}, default_flow_style=False).rstrip()
Пример #12
0
def main():
    global commands
    import logging
    from dmoj import judgeenv, executors

    judgeenv.load_env(cli=True)

    # Emulate ANSI colors with colorama
    if os.name == 'nt' and not judgeenv.no_ansi_emu:
        try:
            from colorama import init
            init()
        except ImportError:
            pass

    executors.load_executors()

    print 'Running local judge...'

    logging.basicConfig(filename=judgeenv.log_file, level=logging.INFO,
                        format='%(levelname)s %(asctime)s %(module)s %(message)s')

    judge = LocalJudge()

    for warning in judgeenv.startup_warnings:
        print ansi_style('#ansi[Warning: %s](yellow)' % warning)
    del judgeenv.startup_warnings
    print

    for command in [ListProblemsCommand, ListSubmissionsCommand, SubmitCommand, ResubmitCommand, RejudgeCommand,
                    HelpCommand, QuitCommand]:
        register(command(judge))

    with judge:
        try:
            judge.listen()

            while True:
                command = raw_input(ansi_style("#ansi[dmoj](magenta)#ansi[>](green) ")).strip()

                line = command.split(' ')
                if line[0] in commands:
                    cmd = commands[line[0]]
                    try:
                        cmd.execute(line[1:])
                    except InvalidCommandException:
                        print
                else:
                    print ansi_style('#ansi[Unrecognized command %s](red|bold)' % line[0])
                    print
        except (EOFError, KeyboardInterrupt):
            print
        finally:
            judge.murder()
Пример #13
0
def main():
    result = {}

    if os.name == 'nt':
        judgeenv.load_env(cli=True)
        if not judgeenv.no_ansi_emu:
            try:
                from colorama import init
                init()
            except ImportError:
                pass

    judgeenv.env['runtime'] = {}

    for name in get_available():
        executor = load_executor(name)

        if executor is None or not hasattr(executor, 'Executor'):
            continue

        if hasattr(executor.Executor, 'autoconfig'):
            print ansi_style('%-43s%s' % ('Auto-configuring #ansi[%s](|underline):' % name, '')),
            try:
                data = executor.Executor.autoconfig()
                config = data[0]
                success = data[1]
                feedback = data[2]
                errors = '' if len(data) < 4 else data[3]
            except Exception:
                print ansi_style('#ansi[Not supported](red|bold)')
                traceback.print_exc()
            else:
                print ansi_style(['#ansi[%s](red|bold)', '#ansi[%s](green|bold)'][success] %
                                 (feedback or ['Failed', 'Success'][success]))

                if not success:
                    if config:
                        print '  Attempted:'
                        print '   ', yaml.dump(config, default_flow_style=False).rstrip().replace('\n', '\n' + ' ' * 4)

                    if errors:
                        print '  Errors:'
                        print '   ', errors.replace('\n', '\n' + ' ' * 4)

                if success:
                    result.update(config)

    print
    print ansi_style('#ansi[Configuration result](green|bold|underline):')
    print yaml.dump({'runtime': result}, default_flow_style=False).rstrip()
Пример #14
0
def main():
    judgeenv.load_env(cli=True, testsuite=True)

    logging.basicConfig(filename=judgeenv.log_file, level=logging.INFO,
                        format='%(levelname)s %(asctime)s %(module)s %(message)s')

    executors.load_executors()
    contrib.load_contrib_modules()

    tester = Tester(judgeenv.problem_regex, judgeenv.case_regex)
    fails = tester.test_all()
    print()
    print('Test complete')
    if fails:
        print_ansi('#ansi[A total of %d case(s) failed](red|bold).' % fails)
    else:
        print_ansi('#ansi[All cases passed.](green|bold)')
    raise SystemExit(int(fails != 0))
Пример #15
0
def main():
    judgeenv.load_env(cli=True)
    executors.load_executors()

    logging.basicConfig(filename=judgeenv.log_file, level=logging.INFO,
                        format='%(levelname)s %(asctime)s %(module)s %(message)s')

    for warning in judgeenv.startup_warnings:
        print(ansi_style('#ansi[Warning: %s](yellow)' % warning))
    del judgeenv.startup_warnings
    print()
    
    server = connexion.FlaskApp(__name__, specification_dir='api/')
    with server.app.app_context():
        judge = get_judge()
        judge.listen()
        server.add_api('api.yaml')
        server.run(port=8080)
Пример #16
0
def main():  # pragma: no cover
    unicode_stdout_stderr()

    if not sanity_check():
        return 1

    from dmoj import judgeenv, executors

    judgeenv.load_env()

    # Emulate ANSI colors with colorama
    if os.name == 'nt' and not judgeenv.no_ansi_emu:
        try:
            from colorama import init
            init()
        except ImportError:
            pass

    executors.load_executors()

    if hasattr(signal, 'SIGUSR2'):
        signal.signal(signal.SIGUSR2, signal.SIG_IGN)

    print('Running live judge...')

    for warning in judgeenv.startup_warnings:
        print(ansi_style('#ansi[Warning: %s](yellow)' % warning))
    del judgeenv.startup_warnings

    if os.name == 'posix' and 'judges' in env:
        logfile = judgeenv.log_file
        try:
            logfile = logfile % 'master'
        except TypeError:
            pass
        logging.basicConfig(filename=logfile, level=logging.INFO,
                            format='%(levelname)s %(asctime)s %(process)d %(name)s %(message)s')
        if env.pidfile:
            with open(env.pidfile) as f:
                f.write(str(os.getpid()))
        manager = JudgeManager(env.judges)
        manager.run()
    else:
        return judge_proc(need_monitor=True)
Пример #17
0
def main():
    sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
    if not sanity_check():
        return 1

    import logging
    from dmoj import judgeenv, executors

    judgeenv.load_env()

    # Emulate ANSI colors with colorama
    if os.name == 'nt' and not judgeenv.no_ansi_emu:
        try:
            from colorama import init
            init()
        except ImportError as ignored:
            pass

    executors.load_executors()

    print 'Running live judge...'

    logging.basicConfig(
        filename=judgeenv.log_file,
        level=logging.INFO,
        format='%(levelname)s %(asctime)s %(module)s %(message)s')

    judge = ClassicJudge(judgeenv.server_host, judgeenv.server_port)

    for warning in judgeenv.startup_warnings:
        print ansi_style('#ansi[Warning: %s](yellow)' % warning)
    del judgeenv.startup_warnings
    print

    with judge:
        try:
            judge.listen()
        except KeyboardInterrupt:
            pass
        except:
            traceback.print_exc()
        finally:
            judge.murder()
Пример #18
0
def main():
    sys.stdout = os.fdopen(sys.stdout.fileno(), 'w', 0)
    if not sanity_check():
        return 1

    import logging
    from dmoj import judgeenv, executors

    judgeenv.load_env()

    # Emulate ANSI colors with colorama
    if os.name == 'nt' and not judgeenv.no_ansi_emu:
        try:
            from colorama import init
            init()
        except ImportError:
            pass

    executors.load_executors()

    print 'Running live judge...'

    logging.basicConfig(filename=judgeenv.log_file, level=logging.INFO,
                        format='%(levelname)s %(asctime)s %(module)s %(message)s')

    judge = ClassicJudge(judgeenv.server_host, judgeenv.server_port)

    for warning in judgeenv.startup_warnings:
        print ansi_style('#ansi[Warning: %s](yellow)' % warning)
    del judgeenv.startup_warnings
    print

    with judge:
        try:
            judge.listen()
        except KeyboardInterrupt:
            pass
        except:
            traceback.print_exc()
        finally:
            judge.murder()
Пример #19
0
def main():  # pragma: no cover
    unicode_stdout_stderr()

    if not sanity_check():
        return 1

    from dmoj import judgeenv, contrib, executors

    judgeenv.load_env()

    executors.load_executors()
    contrib.load_contrib_modules()

    if hasattr(signal, 'SIGUSR2'):
        signal.signal(signal.SIGUSR2, signal.SIG_IGN)

    print('Running live judge...')

    for warning in judgeenv.startup_warnings:
        print_ansi('#ansi[Warning: %s](yellow)' % warning)
    del judgeenv.startup_warnings

    if 'judges' in env:
        logfile = judgeenv.log_file
        try:
            logfile = logfile % 'master'
        except TypeError:
            pass
        logging.basicConfig(
            filename=logfile,
            level=logging.INFO,
            format='%(levelname)s %(asctime)s %(process)d %(name)s %(message)s'
        )
        if env.pidfile:
            with open(env.pidfile) as f:
                f.write(str(os.getpid()))
        manager = JudgeManager(env.judges)
        manager.run()
    else:
        return judge_proc(need_monitor=True)
Пример #20
0
def main():
    judgeenv.load_env(cli=True, testsuite=True)

    # Emulate ANSI colors with colorama
    if os.name == 'nt' and not judgeenv.no_ansi_emu:
        try:
            from colorama import init
            init()
        except ImportError:
            pass

    executors.load_executors()

    tester = Tester(judgeenv.problem_regex, judgeenv.case_regex)
    fails = tester.test_all()
    print
    print 'Test complete'
    if fails:
        print ansi_style(
            '#ansi[A total of %d case(s) failed](red|bold).') % fails
    else:
        print ansi_style('#ansi[All cases passed.](green|bold)')
    raise SystemExit(int(fails != 0))
Пример #21
0
def main():
    load_env(cli=True)
    load_executors()
Пример #22
0
def main():  # pragma: no cover
    unicode_stdout_stderr()

    if not sanity_check():
        return 1

    from dmoj import judgeenv, contrib, executors

    judgeenv.load_env()

    executors.load_executors()
    contrib.load_contrib_modules()

    print('Running live judge...')

    for warning in judgeenv.startup_warnings:
        print_ansi('#ansi[Warning: %s](yellow)' % warning)
    del judgeenv.startup_warnings

    logfile = judgeenv.log_file

    try:
        logfile = logfile % env['id']
    except TypeError:
        pass

    logging.basicConfig(
        filename=logfile,
        level=logging.INFO,
        format='%(levelname)s %(asctime)s %(process)d %(module)s %(message)s')

    setproctitle('DMOJ Judge %s on %s' % (env['id'], make_host_port(judgeenv)))

    judge = ClassicJudge(
        judgeenv.server_host,
        judgeenv.server_port,
        secure=judgeenv.secure,
        no_cert_check=judgeenv.no_cert_check,
        cert_store=judgeenv.cert_store,
    )
    monitor = Monitor()
    monitor.callback = judge.update_problems

    if hasattr(signal, 'SIGUSR2'):

        def update_problem_signal(signum, frame):
            judge.update_problems()

        signal.signal(signal.SIGUSR2, update_problem_signal)

    if judgeenv.api_listen:
        judge_instance = judge

        class Handler(JudgeControlRequestHandler):
            judge = judge_instance

        api_server = HTTPServer(judgeenv.api_listen, Handler)
        thread = threading.Thread(target=api_server.serve_forever)
        thread.daemon = True
        thread.start()
    else:
        api_server = None

    print()
    with monitor:
        try:
            judge.listen()
        except KeyboardInterrupt:
            pass
        except Exception:
            traceback.print_exc()
        finally:
            judge.murder()
            if api_server:
                api_server.shutdown()
Пример #23
0
def main():
    parser = argparse.ArgumentParser(
        description='Automatically configures runtimes')
    output_conf = parser.add_mutually_exclusive_group()
    output_conf.add_argument('-s',
                             '--silent',
                             action='store_true',
                             help='silent mode')
    output_conf.add_argument('-V',
                             '--verbose',
                             action='store_true',
                             help='verbose mode')
    args = parser.parse_args()

    if not args.silent:
        logging.basicConfig(
            level=logging.DEBUG if args.verbose else logging.WARNING,
            format='%(message)s')

    result = {}

    if os.name == 'nt':
        judgeenv.load_env(cli=True)
        if not judgeenv.no_ansi_emu:
            try:
                from colorama import init
                init()
            except ImportError:
                pass

    judgeenv.env['runtime'] = {}

    if args.silent:
        sys.stderr = open(os.devnull, 'w')

    for name in get_available():
        executor = load_executor(name)

        if executor is None or not hasattr(executor, 'Executor'):
            continue

        Executor = executor.Executor
        if not args.verbose and not issubclass(Executor, NullStdoutMixin):
            # if you are printing errors into stdout, you may do so in your own blood
            # *cough* Racket *cough*
            Executor = type('Executor', (NullStdoutMixin, Executor), {})

        if hasattr(Executor, 'autoconfig'):
            if not args.silent:
                print(ansi_style(
                    '%-43s%s' %
                    ('Auto-configuring #ansi[%s](|underline):' % name, '')),
                      end=' ',
                      file=sys.stderr)
                sys.stdout.flush()

            try:
                data = Executor.autoconfig()
                config = data[0]
                success = data[1]
                feedback = data[2]
                errors = '' if len(data) < 4 else data[3]
            except Exception:
                if not args.silent:
                    print(ansi_style('#ansi[Not supported](red|bold)'),
                          file=sys.stderr)
                    traceback.print_exc()
            else:
                if not args.silent:
                    print(ansi_style(
                        ['#ansi[%s](red|bold)', '#ansi[%s](green|bold)'
                         ][success] %
                        (feedback or ['Failed', 'Success'][success])),
                          file=sys.stderr)

                if not success and args.verbose:
                    if config:
                        print('  Attempted:', file=sys.stderr)
                        print('   ',
                              yaml.safe_dump(
                                  config,
                                  default_flow_style=False).rstrip().replace(
                                      '\n', '\n' + ' ' * 4),
                              file=sys.stderr)

                    if errors:
                        print('  Errors:', file=sys.stderr)
                        print('   ',
                              errors.replace('\n', '\n' + ' ' * 4),
                              file=sys.stderr)

                if success:
                    result.update(config)

    if not args.silent and sys.stdout.isatty():
        print(file=sys.stderr)

    if result:
        if not args.silent and sys.stdout.isatty():
            print(ansi_style(
                '#ansi[Configuration result](green|bold|underline):'),
                  file=sys.stderr)
    else:
        print(ansi_style('#ansi[No runtimes configured.](red|bold)'),
              file=sys.__stderr__)
        if not args.verbose:
            print(ansi_style(
                'Run #ansi[%s -V](|underline) to see why this is the case.') %
                  (parser.prog, ),
                  file=sys.__stderr__)

    print(
        yaml.safe_dump({
            'runtime': result
        }, default_flow_style=False).rstrip())
Пример #24
0
def main():
    global commands
    import logging
    from dmoj import judgeenv, executors

    judgeenv.load_env(cli=True)

    # Emulate ANSI colors with colorama
    if os.name == 'nt' and not judgeenv.no_ansi_emu:
        try:
            from colorama import init
            init()
        except ImportError:
            pass

    executors.load_executors()

    print('Running local judge...')

    logging.basicConfig(
        filename=judgeenv.log_file,
        level=logging.INFO,
        format='%(levelname)s %(asctime)s %(module)s %(message)s')

    judge = LocalJudge()

    for warning in judgeenv.startup_warnings:
        print(ansi_style('#ansi[Warning: %s](yellow)' % warning))
    del judgeenv.startup_warnings
    print()

    from dmoj.commands import all_commands
    for command in all_commands:
        register(command(judge))

    with judge:
        try:
            judge.listen()

            while True:
                command = input(
                    ansi_style(
                        "#ansi[dmoj](magenta)#ansi[>](green) ")).strip()

                line = command.split(' ')
                if line[0] in commands:
                    cmd = commands[line[0]]
                    try:
                        cmd.execute(line[1:])
                    except InvalidCommandException as e:
                        if e.message:
                            print(
                                ansi_style("#ansi[%s](red|bold)\n" %
                                           e.message))
                        print()
                else:
                    print(
                        ansi_style('#ansi[Unrecognized command %s](red|bold)' %
                                   line[0]))
                    print()
        except (EOFError, KeyboardInterrupt):
            print()
        finally:
            judge.murder()
Пример #25
0
def main():
    load_env(cli=True)
    load_executors()
Пример #26
0
def main():
    parser = argparse.ArgumentParser(
        description='Automatically configures runtimes')
    parser.add_argument('-s',
                        '--silent',
                        action='store_true',
                        help='silent mode')
    silent = parser.parse_args().silent

    result = {}

    if os.name == 'nt':
        judgeenv.load_env(cli=True)
        if not judgeenv.no_ansi_emu:
            try:
                from colorama import init
                init()
            except ImportError:
                pass

    judgeenv.env['runtime'] = {}

    if silent:
        sys.stderr = open(os.devnull, 'w')

    for name in get_available():
        executor = load_executor(name)

        if executor is None or not hasattr(executor, 'Executor'):
            continue

        Executor = executor.Executor
        if silent and not issubclass(Executor, NullStdoutMixin):
            # if you are printing errors into stdout, you may do so in your own blood
            # *cough* Racket *cough*
            Executor = type('Executor', (NullStdoutMixin, Executor), {})

        if hasattr(Executor, 'autoconfig'):
            if not silent:
                print ansi_style(
                    '%-43s%s' %
                    ('Auto-configuring #ansi[%s](|underline):' % name, '')),
            try:
                data = Executor.autoconfig()
                config = data[0]
                success = data[1]
                feedback = data[2]
                errors = '' if len(data) < 4 else data[3]
            except Exception:
                if not silent:
                    print ansi_style('#ansi[Not supported](red|bold)')
                    traceback.print_exc()
            else:
                if not silent:
                    print ansi_style(
                        ['#ansi[%s](red|bold)', '#ansi[%s](green|bold)'
                         ][success] %
                        (feedback or ['Failed', 'Success'][success]))

                if not success:
                    if not silent:
                        if config:
                            print '  Attempted:'
                            print '   ', yaml.dump(
                                config,
                                default_flow_style=False).rstrip().replace(
                                    '\n', '\n' + ' ' * 4)

                        if errors:
                            print '  Errors:'
                            print '   ', errors.replace('\n', '\n' + ' ' * 4)

                if success:
                    result.update(config)

    if not silent:
        print
        print ansi_style('#ansi[Configuration result](green|bold|underline):')
    print yaml.dump({'runtime': result}, default_flow_style=False).rstrip()