Console script for tplink.
963390
def main(host, password, username):
    """"""
    client = tplink.TpLinkClient(password)
    devices = client.get_connected_devices()
    click.echo(json.dumps(devices, indent=4))
    return 0
366839
def tee_output_python():
    """"""
    buffer = StringIO()
    out = CapturedStdout(buffer)
    orig_stdout, orig_stderr = sys.stdout, sys.stderr
    flush()
    sys.stdout = TeeingStreamProxy(sys.stdout, buffer)
    sys.stderr = TeeingStreamProxy(sys.stderr, buffer)
    try:
        yield out
    finally:
        flush()
        out.finalize()
        sys.stdout, sys.stderr = orig_stdout, orig_stderr
1025553
def console_script(fsroot=''):
    '''
        
    '''

    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter, description='Administration for the OpenSubmit web application.')
    parser.add_argument('-c', '--config', default='/etc/opensubmit/settings.ini', help='OpenSubmit configuration file.')
    subparsers = parser.add_subparsers(dest='command', help='Supported administrative actions.')
    parser_configcreate = subparsers.add_parser('configcreate', help='Create initial config files for the OpenSubmit web server.')
    parser_configcreate.add_argument('--debug', default=is_str_true(os.environ.get('OPENSUBMIT_DEBUG', 'False')), action='store_true', help='Enable debug mode, not for production systems.')
    parser_configcreate.add_argument('--server_url', default=os.environ.get('OPENSUBMIT_SERVER_URL', 'http://localhost:8000'), help='The main URL of the OpenSubmit installation, including sub-directories.')
    parser_configcreate.add_argument('--server_mediaroot', default=os.environ.get('OPENSUBMIT_SERVER_MEDIAROOT', '/tmp/'), help='Storage path for uploadeded files.')
    parser_configcreate.add_argument('--server_hostaliases', default=os.environ.get('OPENSUBMIT_SERVER_HOSTALIASES', '127.0.0.1'), help='Comma-separated list of alternative host names for the web server.')
    parser_configcreate.add_argument('--server_logfile', default=os.environ.get('OPENSUBMIT_SERVER_LOGFILE', '/tmp/opensubmit.log'), help='Log file for the OpenSubmit application.')
    parser_configcreate.add_argument('--server_timezone', default=os.environ.get('OPENSUBMIT_SERVER_TIMEZONE', 'Europe/Berlin'), help='Time zone for all dates and deadlines.')
    parser_configcreate.add_argument('--database_name', default=os.environ.get('OPENSUBMIT_DATABASE_NAME', '/tmp/database.sqlite'), help='Name of the database (file).'),
    parser_configcreate.add_argument('--database_engine', default=os.environ.get('OPENSUBMIT_DATABASE_ENGINE', 'sqlite3'), choices=['postgresql', 'mysql', 'sqlite3', 'oracle'])
    parser_configcreate.add_argument('--database_user', default=os.environ.get('OPENSUBMIT_DATABASE_USER', ''), help='The user name for accessing the database. Not needed for SQLite.')
    parser_configcreate.add_argument('--database_password', default=os.environ.get('OPENSUBMIT_DATABASE_PASSWORD', ''), help='The user password for accessing the database. Not needed for SQLite.')
    parser_configcreate.add_argument('--database_host', default=os.environ.get('OPENSUBMIT_DATABASE_HOST', ''), help='The host name for accessing the database. Not needed for SQLite. Default is localhost.')
    parser_configcreate.add_argument('--database_port', default=os.environ.get('OPENSUBMIT_DATABASE_PORT', ''), help='The port number for accessing the database. Not needed for SQLite.')
    parser_configcreate.add_argument('--login_google_oauth_key', default=os.environ.get('OPENSUBMIT_LOGIN_GOOGLE_OAUTH_KEY', ''), help='Google OAuth client key.')
    parser_configcreate.add_argument('--login_google_oauth_secret', default=os.environ.get('OPENSUBMIT_LOGIN_GOOGLE_OAUTH_SECRET', ''), help='Google OAuth client secret.')
    parser_configcreate.add_argument('--login_twitter_oauth_key', default=os.environ.get('OPENSUBMIT_LOGIN_TWITTER_OAUTH_KEY', ''), help='Twitter OAuth client key.')
    parser_configcreate.add_argument('--login_twitter_oauth_secret', default=os.environ.get('OPENSUBMIT_LOGIN_TWITTER_OAUTH_SECRET', ''), help='Twitter OAuth client secret.')
    parser_configcreate.add_argument('--login_github_oauth_key', default=os.environ.get('OPENSUBMIT_LOGIN_GITHUB_OAUTH_KEY', ''), help='GitHub OAuth client key.')
    parser_configcreate.add_argument('--login_github_oauth_secret', default=os.environ.get('OPENSUBMIT_LOGIN_GITHUB_OAUTH_SECRET', ''), help='GitHUb OAuth client secret.')
    parser_configcreate.add_argument('--login_gitlab_description', default=os.environ.get('OPENSUBMIT_LOGIN_GITLAB_DESCRIPTION', ''), help='Title of the GitLab login button.')
    parser_configcreate.add_argument('--login_gitlab_oauth_key', default=os.environ.get('OPENSUBMIT_LOGIN_GITLAB_OAUTH_KEY', ''), help='GitLab OAuth client key.')
    parser_configcreate.add_argument('--login_gitlab_oauth_secret', default=os.environ.get('OPENSUBMIT_LOGIN_GITLAB_OAUTH_SECRET', ''), help='GitLab OAuth client secret.')
    parser_configcreate.add_argument('--login_gitlab_url', default=os.environ.get('OPENSUBMIT_LOGIN_GITLAB_URL', ''), help='GitLab URL.')
    parser_configcreate.add_argument('--login_openid_description', default=os.environ.get('OPENSUBMIT_LOGIN_OPENID_DESCRIPTION', 'StackExchange'), help='Title of the OpenID login button.')
    parser_configcreate.add_argument('--login_openid_provider', default=os.environ.get('OPENSUBMIT_LOGIN_OPENID_PROVIDER', 'https://openid.stackexchange.com'), help='URL of the OpenID provider.')
    parser_configcreate.add_argument('--login_oidc_description', default=os.environ.get('OPENSUBMIT_LOGIN_OIDC_DESCRIPTION', ''), help='Title of the OpenID Connect login button.')
    parser_configcreate.add_argument('--login_oidc_endpoint', default=os.environ.get('OPENSUBMIT_LOGIN_OIDC_ENDPOINT', ''), help='URL of the OpenID Connect endpoint.')
    parser_configcreate.add_argument('--login_oidc_client_id', default=os.environ.get('OPENSUBMIT_LOGIN_OIDC_CLIENT_ID', ''), help='OpenID Connect client id.')
    parser_configcreate.add_argument('--login_oidc_client_secret', default=os.environ.get('OPENSUBMIT_LOGIN_OIDC_CLIENT_SECRET', ''), help='OpenID Connect client secret.')
    parser_configcreate.add_argument('--login_shib_description', default=os.environ.get('OPENSUBMIT_LOGIN_SHIB_DESCRIPTION', ''), help='Title of the Shibboleth login button.')
    parser_configcreate.add_argument('--login_demo', default=is_str_true(os.environ.get('OPENSUBMIT_LOGIN_DEMO', 'False')), action='store_true', help='Offer demo login options.')
    parser_configcreate.add_argument('--admin_name', default=os.environ.get('OPENSUBMIT_ADMIN_NAME', 'OpenSubmit Administrator'), help='Name of the administrator, shown in privacy policy, impress and backend.')
    parser_configcreate.add_argument('--admin_email', default=os.environ.get('OPENSUBMIT_ADMIN_EMAIL', 'root@localhost'), help='eMail of the administrator, shown in privacy policy, impress and backend.')
    parser_configcreate.add_argument('--admin_address', default=os.environ.get('OPENSUBMIT_ADMIN_ADDRESS', '(address available by eMail)'), help='Address of the administrator, shown in privacy policy and impress.')
    parser_configcreate.add_argument('--admin_impress_page', default=os.environ.get('OPENSUBMIT_IMPRESS_PAGE', ''), help='Link to alternative impress page.')
    parser_configcreate.add_argument('--admin_privacy_page', default=os.environ.get('OPENSUBMIT_PRIVACY_PAGE', ''), help='Link to alternative privacy policy page.')
    parser_configcreate.add_argument('--whitelist_openid', default=os.environ.get('OPENSUBMIT_WHITELIST_OPENID', ''), help='Comma-separated list of allowed email addresses for OpenID login.')
    parser_configcreate.add_argument('--whitelist_twitter', default=os.environ.get('OPENSUBMIT_WHITELIST_TWITTER', ''), help='Comma-separated list of allowed email addresses for Twitter login.')
    parser_configcreate.add_argument('--whitelist_google', default=os.environ.get('OPENSUBMIT_WHITELIST_GOOGLE', ''), help='Comma-separated list of allowed email addresses for Google login.')
    parser_configcreate.add_argument('--whitelist_github', default=os.environ.get('OPENSUBMIT_WHITELIST_GITHUB', ''), help='Comma-separated list of allowed email addresses for GitHub login.')
    parser_configcreate.add_argument('--whitelist_gitlab', default=os.environ.get('OPENSUBMIT_WHITELIST_GITLAB', ''), help='Comma-separated list of allowed email addresses for GitLab login.')
    parser_configcreate.add_argument('--whitelist_oidc', default=os.environ.get('OPENSUBMIT_WHITELIST_OIDC', ''), help='Comma-separated list of allowed email addresses for OpenID connect login.')
    parser_configcreate.add_argument('--whitelist_shib', default=os.environ.get('OPENSUBMIT_WHITELIST_SHIB', ''), help='Comma-separated list of allowed email addresses for Shibboleth login.')

    subparsers.add_parser('configtest', aliases=['configure'], help='Check config files and database for correct installation of the OpenSubmit web server.')
    subparsers.add_parser('democreate', aliases=['createdemo'], help='Install some test data (courses, assignments, users).')
    subparsers.add_parser('apachecreate', help='Create config file snippet for Apache 2.4.')
    subparsers.add_parser('fixperms', help='Check and fix student and tutor permissions.')
    subparsers.add_parser('configdump', aliases=['dumpconfig'], help='Show effective OpenSubmit configuration at run-time.')
    subparsers.add_parser('fixchecksums', help='Re-create all student file checksums (for duplicate detection).')

    parser_makeadmin = subparsers.add_parser('makeadmin', help='Make this user an admin with backend rights.')
    parser_makeadmin.add_argument('email')
    parser_makeowner = subparsers.add_parser('makeowner', help='Make this user a course owner with backend rights.')
    parser_makeowner.add_argument('email')
    parser_maketutor = subparsers.add_parser('maketutor', help='Make this user a course tutor with backend rights.')
    parser_maketutor.add_argument('email')
    parser_makestudent = subparsers.add_parser('makestudent', help='Make this user a student without backend rights.')
    parser_makestudent.add_argument('email')
    args = parser.parse_args()

    config_file = fsroot + args.config

    if args.command == 'apachecreate':
        config = check_web_config(config_file)
        if config:
            apache_config(config, os.path.dirname(config_file) + os.sep + 'apache24.conf')
        return

    if args.command == 'configcreate':
        configcreate(config_file, vars(args))
        return

    if args.command == 'configtest':
        configtest(config_file)
        return

    if args.command in ['fixperms', 'fixchecksums', 'democreate', 'createdemo', 'dumpconfig', 'configdump']:
        django_admin([args.command])
        return

    if args.command in ['makeadmin', 'makeowner', 'maketutor', 'makestudent']:
        django_admin([args.command, args.email])
        return
602753
def start_console(local_vars={}):
    ''''''
    transforms.CONSOLE_ACTIVE = True
    transforms.remove_not_allowed_in_console()
    sys.ps1 = prompt
    console = ExperimentalInteractiveConsole(locals=local_vars)
    console.interact(banner=banner)
925341
def run(self):
        """"""
        self.console.load(self.lines, setup=self.setup, teardown=self.teardown)
        return self.console.interpret()
649568
def main():
    """"""
    WIDTH, HEIGHT = 120, 60
    TITLE = None

    with tcod.console_init_root(WIDTH, HEIGHT, TITLE, order="F",
                                renderer=tcod.RENDERER_SDL) as console:
        tcod.sys_set_fps(24)
        while True:
            tcod.console_flush()
            for event in tcod.event.wait():
                print(event)
                if event.type == "QUIT":
                    raise SystemExit()
                elif event.type == "MOUSEMOTION":
                    console.ch[:, -1] = 0
                    console.print_(0, HEIGHT - 1, str(event))
                else:
                    console.blit(console, 0, 0, 0, 1, WIDTH, HEIGHT - 2)
                    console.ch[:, -3] = 0
                    console.print_(0, HEIGHT - 3, str(event))
156488
def do_cat(self, path):
        """"""
        path = path[0]
        tmp_file_path = self.TMP_PATH + 'tmp'

        if not os.path.exists(self.TMP_PATH):
            os.makedirs(self.TMP_PATH)

        f = self.n.downloadFile(self.current_path + path, tmp_file_path)
        f = open(tmp_file_path, 'r')

        self.stdout.write(f.read())
        self.stdout.write("\n")
620243
def run(self):
    """"""
    if platform.system() == 'Windows':
      # Windows doesn't support file-like objects for select(), so fall back
      # to raw_input().
      response = input(''.join((self._message,
                                os.linesep,
                                PROMPT)))
      self._answered = True
      self._callback(response)
      return

    # First, display the prompt to the console.
    console_output.cli_print(self._message, color=self._color,
                             end=os.linesep, logger=None)
    console_output.cli_print(PROMPT, color=self._color, end='', logger=None)
    sys.stdout.flush()

    # Before reading, clear any lingering buffered terminal input.
    termios.tcflush(sys.stdin, termios.TCIFLUSH)

    line = ''
    while not self._stop_event.is_set():
      inputs, _, _ = select.select([sys.stdin], [], [], 0.001)
      if sys.stdin in inputs:
        new = os.read(sys.stdin.fileno(), 1024)
        if not new:
          # Hit EOF!
          # They hit ^D (to insert EOF). Tell them to hit ^C if they
          # want to actually quit.
          print('Hit ^C (Ctrl+c) to exit.')
          break
        line += new.decode('utf-8')
        if '\n' in line:
          response = line[:line.find('\n')]
          self._answered = True
          self._callback(response)
          return
1170188
public static void main(String[] args) {
        ConsoleWrapper console = new ConsoleWrapper(System.console(), System.err);

        // Create / obtain the collaborators
        DefaultSSLCertificateCreator certCreator = DefaultSSLCertificateFactory.getDefaultSSLCertificateCreator();
        LTPAKeyFileUtility ltpaKeyFileCreator = new LTPAKeyFileUtilityImpl();

        // Create the SecurityUtility and register tasks
        SecurityUtility util = new SecurityUtility(console, System.out, System.err);
        IFileUtility fileUtil = new FileUtility(util.getUserDir(), util.getOutputDir(null));
        util.registerTask(new EncodeTask(SCRIPT_NAME));
        util.registerTask(new CreateSSLCertificateTask(certCreator, fileUtil, SCRIPT_NAME));
        util.registerTask(new CreateLTPAKeysTask(ltpaKeyFileCreator, fileUtil, SCRIPT_NAME));

        // Kick everything off
        int rc = util.runProgram(args).getReturnCode();
        System.exit(rc);
    }
262801
def _prep_cmd(cmd, tx_out_file):
    
    cmd = " ".join(cmd) if isinstance(cmd, (list, tuple)) else cmd
    return "export TMPDIR=%s && %s" % (os.path.dirname(tx_out_file), cmd)
548209
def run(q_prompt=False):
    """"""
    lines, columns = console_size()
    q(r'\c %d %d' % (lines, columns))
    if len(sys.argv) > 1:
        try:
            q(r'\l %s' % sys.argv[1])
        except kerr as e:
            print(e)
            raise SystemExit(1)
        else:
            del sys.argv[1]
    if q_prompt:
        q()
    ptp.run()
796415
def take_control(self):
        

        if has_termios:
            # Get attributes of the shell you were in before going to the
            # new one
            original_tty = termios.tcgetattr(sys.stdin)
            try:
                tty.setraw(sys.stdin.fileno())
                tty.setcbreak(sys.stdin.fileno())

                # We must set the timeout to 0 so that we can bypass times when
                # there is no available text to receive
                self.channel.settimeout(0)

                # Loop forever until the user exits (i.e. read buffer is empty)
                while True:
                    select_read, select_write, select_exception = (
                        select.select([self.channel, sys.stdin], [], [])
                    )
                    # Read any output from the terminal and print it to the
                    # screen.  With timeout set to 0, we just can ignore times
                    # when there's nothing to receive.
                    if self.channel in select_read:
                        try:
                            buffer = self.channel.recv(self.buffer_size)
                            if len(buffer) == 0:
                                break
                            sys.stdout.write(buffer.decode(self.encoding))
                            sys.stdout.flush()
                        except socket.timeout:
                            pass
                    # Send any keyboard input to the terminal one byte at a
                    # time
                    if sys.stdin in select_read:
                        buffer = sys.stdin.read(1)
                        if len(buffer) == 0:
                            break
                        self.channel.send(buffer)
            finally:
                # Restore the attributes of the shell you were in
                termios.tcsetattr(sys.stdin, termios.TCSADRAIN, original_tty)
        else:
            def writeall(sock):
                while True:
                    buffer = sock.recv(self.buffer_size)
                    if len(buffer) == 0:
                        break
                    sys.stdout.write(buffer.decode(self.encoding))
                    sys.stdout.flush()

            writer = threading.Thread(target=writeall, args=(self.channel,))
            writer.start()

            try:
                while True:
                    buffer = sys.stdin.read(1)
                    if len(buffer) == 0:
                        break
                    self.channel.send(buffer)
            # User has hit Ctrl+Z or F6
            except EOFError:
                pass
1288202
def console_main():
    
    setproctitle('image-scraper')
    scraper = ImageScraper()
    scraper.get_arguments()
    print("\nImageScraper\n============\nRequesting page....\n")
    try:
        scraper.get_html()
    except PageLoadError as err:
        if err.status_code is None:
            print("ImageScraper is unable to acces the internet.")
        else:
            print("Page failed to load. Status code: {0}".format(err.status_code))
        sys.exit()

    scraper.get_img_list()

    if len(scraper.images) == 0:
        sys.exit("Sorry, no images found.")
    if scraper.no_to_download is None:
        scraper.no_to_download = len(scraper.images)

    print("Found {0} images: ".format(len(scraper.images)))

    try:
        scraper.process_download_path()
    except DirectoryAccessError:
        print("Sorry, the directory can't be accessed.")
        sys.exit()
    except DirectoryCreateError:
        print("Sorry, the directory can't be created.")
        sys.exit()

    if scraper.dump_urls:
        for img_url in scraper.images:
            print(img_url)

    status_flags = {'count': 0, 'percent': 0.0, 'failed': 0, 'under_min_or_over_max_filesize': 0}
    widgets = ['Progress: ', Percentage(), ' ', Bar(marker=RotatingMarker()),
               ' ', ETA(), ' ', FileTransferSpeed()]
    pbar = ProgressBar(widgets=widgets, maxval=100).start()
    pool = ThreadPoolExecutor(max_workers=scraper.nthreads)
    status_lock = threading.Lock()
    for img_url in scraper.images:
        if status_flags['count'] == scraper.no_to_download:
            break
        pool.submit(download_worker_fn, scraper, img_url, pbar, status_flags, status_lock)
        status_flags['count'] += 1
    pool.shutdown(wait=True)
    pbar.finish()
    print("\nDone!\nDownloaded {0} images\nFailed: {1}\n".format(
        status_flags['count']-status_flags['failed']-status_flags['under_min_or_over_max_filesize'],
        status_flags['failed']))
    return
1095274
def _run_cmd(cmd):
    """"""
    if not os.path.exists(cmd[0]):
        cmd[0] = shutil.which(cmd[0])
        assert cmd[0] is not None

    shebang_parts = parseshebang.parse(cmd[0])

    proc = subprocess.Popen(shebang_parts + cmd,
                            stdout=subprocess.PIPE,
                            stderr=subprocess.PIPE)
    stdout, stderr = proc.communicate()
    return {
        "stdout": stdout,
        "stderr": stderr,
        "code": proc.returncode
    }
777959
def main():
    
    source_lines = (line.rstrip() for line in sys.stdin)
    console = InteractiveInterpreter()
    console.runsource('import turicreate')
    source = ''
    try:
        while True:
            source = source_lines.next()
            more = console.runsource(source)
            while more:
                next_line = source_lines.next()
                print '...', next_line
                source += '\n' + next_line
                more = console.runsource(source)
    except StopIteration:
        if more:
            print '... '
            more = console.runsource(source + '\n')
1196888
def main(arguments=None):
    
    # setup the command-line util settings
    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="WARNING",
        options_first=False,
        projectName="transientNamer"
    )
    arguments, settings, log, dbConn = su.setup()

    # tab completion for raw_input
    readline.set_completer_delims(' \t\n;')
    readline.parse_and_bind("tab: complete")
    readline.set_completer(tab_complete)

    # unpack remaining cl arguments using `exec` to setup the variable names
    # automatically
    for arg, val in arguments.iteritems():
        if arg[0] == "-":
            varname = arg.replace("-", "") + "Flag"
        else:
            varname = arg.replace("<", "").replace(">", "")
        if isinstance(val, str) or isinstance(val, unicode):
            exec(varname + " = '%s'" % (val,))
        else:
            exec(varname + " = %s" % (val,))
        if arg == "--dbConn":
            dbConn = val
        log.debug('%s = %s' % (varname, val,))

    ## START LOGGING ##
    startTime = times.get_now_sql_datetime()
    log.info(
        '--- STARTING TO RUN THE cl_utils.py AT %s' %
        (startTime,))

    if search or new or cone:
        if ra:
            tns = transientNamer.search(
                log=log,
                ra=ra,
                dec=dec,
                radiusArcsec=arcsecRadius,
                comments=withCommentsFlag
            )
        if name:
            tns = transientNamer.search(
                log=log,
                name=name,
                comments=withCommentsFlag
            )
        if discInLastDays:
            tns = transientNamer.search(
                log=log,
                discInLastDays=discInLastDays,
                comments=withCommentsFlag
            )

        # Recursively create missing directories
        if outputFlag and not os.path.exists(outputFlag):
            os.makedirs(outputFlag)

        if tableNamePrefix:
            sources, phot, spec, files = tns.mysql(
                tableNamePrefix=tableNamePrefix, dirPath=outputFlag)
            numSources = len(sources.split("\n")) - 1
        elif not render or render == "table":
            sources, phot, spec, files = tns.table(dirPath=outputFlag)
            numSources = len(sources.split("\n")) - 4
        elif render == "csv":
            sources, phot, spec, files = tns.csv(dirPath=outputFlag)
            numSources = len(sources.split("\n")) - 1
        elif render == "json":
            sources, phot, spec, files = tns.json(dirPath=outputFlag)
            numSources = len(sources.split("{")) - 1
        elif render == "yaml":
            sources, phot, spec, files = tns.yaml(dirPath=outputFlag)
            numSources = len(sources.split("\n-"))
        elif render == "markdown":
            sources, phot, spec, files = tns.markdown(dirPath=outputFlag)
            numSources = len(sources.split("\n")) - 2

        if numSources == 1:
            print "%(numSources)s transient found" % locals()
        elif numSources > 1:
            print "%(numSources)s transients found" % locals()

        if not outputFlag:
            print "\n# Matched Transients"
            print sources
            print "\n# Transient Photometry"
            print phot
            print "\n# Transient Spectra"
            print spec
            print "\n# Transient Supplementary Files"
            print files
            print "\n# Original TNS Search URL"
            print tns.url
        # CALL FUNCTIONS/OBJECTS

    if "dbConn" in locals() and dbConn:
        dbConn.commit()
        dbConn.close()
    ## FINISH LOGGING ##
    endTime = times.get_now_sql_datetime()
    runningTime = times.calculate_time_difference(startTime, endTime)
    log.info('-- FINISHED ATTEMPT TO RUN THE cl_utils.py AT %s (RUNTIME: %s) --' %
             (endTime, runningTime, ))

    return
192315
function consoleLog(){
    console.log("byllllogl-" + h_p + "-" + p_p + " --- step_p:" 
    + step_p + " --- lockedPhase_p:" + lockedPhase_p + " --- lockedValue_p:" + lockedValue_p  + " --- waitingProposer:" + waitingProposer
    + " --- assocByzantinePhase:"+ JSON.stringify(assocByzantinePhase));
}