This function is run inside the weirdo casapy IPython environment! A
    strange set of modules is available, and the
    `pwkit.environments.casa.scripting` system sets up a very particular
    environment to allow encapsulated scripting.
350226
def in_casapy (helper, asdm=None, ms=None, tbuff=None):
    
    if asdm is None:
        raise ValueError ('asdm')
    if ms is None:
        raise ValueError ('ms')
    if tbuff is None:
        raise ValueError ('tbuff')

    helper.casans.importevla (asdm=asdm, vis=ms, ocorr_mode='co', online=True,
                              tbuff=tbuff, flagpol=False, tolerance=1.3,
                              applyflags=True, flagbackup=False)
178376
function Module(options) {
    var module = this;
    options = options || {};

    /**
     * Whether the module is initialized.
     * @property {Boolean} [initialized=false]
     */
    module.initialized = false;
    /**
     * Whether the module is running.
     * @property {Boolean} [running=false]
     */
    module.running = false;

    ['init', 'start', 'stop', 'exit'].forEach(function(name) {
        var method = options[name];
        if (method) {
            var setMethod = 'set' + name[0].toUpperCase() + name.slice(1) + 'Method';
            module[setMethod](method);
        }
    });
}
124893
def is_in_ipython():
    ""

    program_name = os.path.basename(os.getenv('_', ''))

    if ('jupyter-notebook' in program_name or # jupyter-notebook
        'ipython'          in program_name or # ipython
        'JPY_PARENT_PID'   in os.environ):    # ipython-notebook
        return True
    else:
        return False
1044229
def run_script(self, filename, wdir, args, debug, post_mortem,
                   current_client, clear_variables):
        """"""
        norm = lambda text: remove_backslashes(to_text_string(text))

        # Run Cython files in a dedicated console
        is_cython = osp.splitext(filename)[1] == '.pyx'
        if is_cython:
            current_client = False

        # Select client to execute code on it
        is_new_client = False
        if current_client:
            client = self.get_current_client()
        else:
            client = self.get_client_for_file(filename)
            if client is None:
                self.create_client_for_file(filename, is_cython=is_cython)
                client = self.get_current_client()
                is_new_client = True

        if client is not None:
            # Internal kernels, use runfile
            if client.get_kernel() is not None:
                line = "%s('%s'" % ('debugfile' if debug else 'runfile',
                                    norm(filename))
                if args:
                    line += ", args='%s'" % norm(args)
                if wdir:
                    line += ", wdir='%s'" % norm(wdir)
                if post_mortem:
                    line += ", post_mortem=True"
                line += ")"
            else: # External kernels, use %run
                line = "%run "
                if debug:
                    line += "-d "
                line += "\"%s\"" % to_text_string(filename)
                if args:
                    line += " %s" % norm(args)

            try:
                if client.shellwidget._executing:
                    # Don't allow multiple executions when there's
                    # still an execution taking place
                    # Fixes issue 7293
                    pass
                elif client.shellwidget._reading:
                    client.shellwidget._append_html(
                        _("<br><b>Please exit from debugging before trying to "
                          "run a file in this console.</b>\n<hr><br>"),
                        before_prompt=True)
                    return
                elif current_client:
                    self.execute_code(line, current_client, clear_variables)
                else:
                    if is_new_client:
                        client.shellwidget.silent_execute('%clear')
                    else:
                        client.shellwidget.execute('%clear')
                    client.shellwidget.sig_prompt_ready.connect(
                            lambda: self.execute_code(line, current_client,
                                                      clear_variables))
            except AttributeError:
                pass
            self.switch_to_plugin()
        else:
            #XXX: not sure it can really happen
            QMessageBox.warning(self, _('Warning'),
                _("No IPython console is currently available to run <b>%s</b>."
                  "<br><br>Please open a new one and try again."
                  ) % osp.basename(filename), QMessageBox.Ok)
1325952
def exec_python_rc(*args, **kwargs):
    
    cmdargs, kwargs = __wrap_python(args, kwargs)
    return exec_command_rc(*cmdargs, **kwargs)
525241
def console_script():
    '''
        
    '''
    if len(sys.argv) == 1:
        print("opensubmit-exec [configcreate <server_url>|configtest|run|test <dir>|unlock|help] [-c config_file]")
        return 0

    if "help" in sys.argv[1]:
        print("configcreate <server_url>:  Create initial config file for the OpenSubmit executor.")
        print("configtest:                 Check config file for correct installation of the OpenSubmit executor.")
        print("run:                        Fetch and run code to be tested from the OpenSubmit web server. Suitable for crontab.")
        print("test <dir>:                 Run test script from a local folder for testing purposes.")
        print("unlock:                     Break the script lock, because of crashed script.")
        print("help:                       Print this help")
        print(
            "-c config_file    Configuration file to be used (default: {0})".format(CONFIG_FILE_DEFAULT))
        return 0

    # Translate legacy commands
    if sys.argv[1] == "configure":
        sys.argv[1] = 'configtest'

    config_fname = get_config_fname(sys.argv)

    if "configcreate" in sys.argv[1]:
        print("Creating config file at " + config_fname)

        server_url = sys.argv[2]

        if create_config(config_fname, override_url=server_url):
            print("Config file created, fetching jobs from " + server_url)
            return 0
        else:
            return 1

    if "configtest" in sys.argv[1]:
        print("Testing config file at " + config_fname)

        if has_config(config_fname):
            config = read_config(config_fname)
            if not check_config(config):
                return 1
        else:
            print("ERROR: Seems like the config file %s does not exist. Call 'opensubmit-exec configcreate <server_url>' first." %
                  config_fname)
            return 1

        print("Sending host information update to server ...")
        send_hostinfo(config)
        return 0

    if "unlock" in sys.argv[1]:
        config = read_config(config_fname)
        break_lock(config)
        return 0

    if "run" in sys.argv[1]:
        config = read_config(config_fname)
        # Perform additional precautions for unattended mode in cron
        kill_longrunning(config)
        with ScriptLock(config):
            download_and_run(config)
        return 0

    if "test" in sys.argv[1]:
        config = read_config(config_fname)
        copy_and_run(config, sys.argv[2])
        return 0
1199676
def setup(interactive, not_relative, dry_run, reset, root_dir, testuser):
    """"""

    click.echo("[cellpy] (setup)")

    # generate variables
    init_filename = create_custom_init_filename()
    userdir, dst_file = get_user_dir_and_dst(init_filename)

    if testuser:
        if not root_dir:
            root_dir = os.getcwd()

        click.echo(f"[cellpy] (setup) DEV-MODE testuser: {testuser}")
        init_filename = create_custom_init_filename(testuser)
        userdir = root_dir
        dst_file = get_dst_file(userdir, init_filename)
        click.echo(f"[cellpy] (setup) DEV-MODE userdir: {userdir}")
        click.echo(f"[cellpy] (setup) DEV-MODE dst_file: {dst_file}")

    if not pathlib.Path(dst_file).is_file():
        reset = True

    if interactive:
        click.echo(" interactive mode ".center(80, "-"))
        _update_paths(root_dir, not not_relative, dry_run=dry_run, reset=reset)
        _write_config_file(
            userdir, dst_file,
            init_filename, dry_run,
        )
        _check()

    else:
        _write_config_file(userdir, dst_file, init_filename, dry_run)
        _check()
566469
function( name, testEnvironment, executeNow ) {
		var module, moduleFns;
		var currentModule = config.currentModule;

		if ( arguments.length === 2 ) {
			if ( testEnvironment instanceof Function ) {
				executeNow = testEnvironment;
				testEnvironment = undefined;
			}
		}

		// DEPRECATED: handles setup/teardown functions,
		// beforeEach and afterEach should be used instead
		if ( testEnvironment && testEnvironment.setup ) {
			testEnvironment.beforeEach = testEnvironment.setup;
			delete testEnvironment.setup;
		}
		if ( testEnvironment && testEnvironment.teardown ) {
			testEnvironment.afterEach = testEnvironment.teardown;
			delete testEnvironment.teardown;
		}

		module = createModule();

		moduleFns = {
			beforeEach: setHook( module, "beforeEach" ),
			afterEach: setHook( module, "afterEach" )
		};

		if ( executeNow instanceof Function ) {
			config.moduleStack.push( module );
			setCurrentModule( module );
			executeNow.call( module.testEnvironment, moduleFns );
			config.moduleStack.pop();
			module = module.parentModule || currentModule;
		}

		setCurrentModule( module );

		function createModule() {
			var parentModule = config.moduleStack.length ?
				config.moduleStack.slice( -1 )[ 0 ] : null;
			var moduleName = parentModule !== null ?
				[ parentModule.name, name ].join( " > " ) : name;
			var module = {
				name: moduleName,
				parentModule: parentModule,
				tests: []
			};

			var env = {};
			if ( parentModule ) {
				extend( env, parentModule.testEnvironment );
				delete env.beforeEach;
				delete env.afterEach;
			}
			extend( env, testEnvironment );
			module.testEnvironment = env;

			config.modules.push( module );
			return module;
		}

		function setCurrentModule( module ) {
			config.currentModule = module;
		}

	}
1190674
def run_python_script(package=None, module=None, args=[], p_args=[]):
    
    assert module is not None
    assert isinstance(args, (tuple, list)) and isinstance(p_args, (tuple, list))
    path = python_script_exists(package, module)
    run_program(sys.executable, p_args + [path] + args)
1051701
def main(self, configuration):
    
    _custom_func_arguments = {"conf"}
    filename = os.path.basename(os.path.abspath(sys.argv[0]))

    default_arg_list = [item for item in configuration.get("default") if len(item.strip()) != 0]
    if len(default_arg_list) == 0:
      sys.stdout.write(self.generate_help(filename=filename))
      return

    command_name = default_arg_list.pop(0)
    if command_name not in self._modules.keys():
      sys.stdout.write(self.generate_help(filename=filename))
      return

    command = self._modules[command_name]
    entry_point = command["entry_point"]
    class_path = command["classpath"]
    metainfo = command["metainfo"]
    """:type metainfo ModuleMetaInfo"""

    try:
      args = metainfo.parse_default_arguments(default_arg_list)
      args.update(metainfo.parse_arguments(configuration))

      f_args = entry_point.__code__.co_varnames[:entry_point.__code__.co_argcount]

      if len(f_args) - len(set(f_args) & _custom_func_arguments) != len(set(args.keys()) & set(f_args)):
        raise ArgumentException("Function \"{}\" from module {} doesn't implement all arguments in the signature".format(
          entry_point.__name__, class_path
        ))

      if "conf" in f_args:
        args["conf"] = configuration

      entry_point(**args)
    except ArgumentException as e:
      sys.stdout.write("Application arguments exception: {}\n".format(str(e)))
      return
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
726328
def python(code, show=True):
    
    setup = "import os;" \
            "os.environ[\'DJANGO_SETTINGS_MODULE\']=\'%s.settings\';" \
            "import django;" \
            "django.setup();" % env.proj_app
    full_code = 'python -c "%s%s"' % (setup, code.replace("`", "\\\`"))
    with project():
        if show:
            print_command(code)
        result = run(full_code, show=False)
    return result
1242436
def kernel_config():
    """"""
    import ipykernel
    from IPython.core.application import get_ipython_dir
    from traitlets.config.loader import Config, load_pyconfig_files

    # ---- IPython config ----
    try:
        profile_path = osp.join(get_ipython_dir(), 'profile_default')
        cfg = load_pyconfig_files(['ipython_config.py',
                                   'ipython_kernel_config.py'],
                                  profile_path)
    except:
        cfg = Config()

    # ---- Spyder config ----
    spy_cfg = Config()

    # Enable/disable certain features for testing
    testing = os.environ.get('SPY_TESTING') == 'True'
    if testing:
        # Don't load nor save history in our IPython consoles.
        spy_cfg.HistoryAccessor.enabled = False

    # Until we implement Issue 1052
    spy_cfg.InteractiveShell.xmode = 'Plain'

    # Jedi completer. It's only available in Python 3
    jedi_o = os.environ.get('SPY_JEDI_O') == 'True'
    if not PY2:
        spy_cfg.IPCompleter.use_jedi = jedi_o

    # Run lines of code at startup
    run_lines_o = os.environ.get('SPY_RUN_LINES_O')
    if run_lines_o is not None:
        spy_cfg.IPKernelApp.exec_lines = [x.strip() for x in run_lines_o.split(';')]
    else:
        spy_cfg.IPKernelApp.exec_lines = []

    # Clean terminal arguments input
    clear_argv = "import sys;sys.argv = [''];del sys"
    spy_cfg.IPKernelApp.exec_lines.append(clear_argv)

    # Load %autoreload magic
    spy_cfg.IPKernelApp.exec_lines.append(
        "get_ipython().kernel._load_autoreload_magic()")

    # Load wurlitzer extension
    spy_cfg.IPKernelApp.exec_lines.append(
        "get_ipython().kernel._load_wurlitzer()")

    # Default inline backend configuration
    # This is useful to have when people doesn't
    # use our config system to configure the
    # inline backend but want to use
    # '%matplotlib inline' at runtime
    if LooseVersion(ipykernel.__version__) < LooseVersion('4.5'):
        dpi_option = 'savefig.dpi'
    else:
        dpi_option = 'figure.dpi'

    spy_cfg.InlineBackend.rc = {'figure.figsize': (6.0, 4.0),
                                dpi_option: 72,
                                'font.size': 10,
                                'figure.subplot.bottom': .125,
                                'figure.facecolor': 'white',
                                'figure.edgecolor': 'white'}

    # Pylab configuration
    mpl_backend = None
    if is_module_installed('matplotlib'):
        # Set Matplotlib backend with Spyder options
        pylab_o = os.environ.get('SPY_PYLAB_O')
        backend_o = os.environ.get('SPY_BACKEND_O')
        if pylab_o == 'True' and backend_o is not None:
            # Select the automatic backend
            if backend_o == '1':
                if is_module_installed('PyQt5'):
                    auto_backend = 'qt5'
                elif is_module_installed('PyQt4'):
                    auto_backend = 'qt4'
                elif is_module_installed('_tkinter'):
                    auto_backend = 'tk'
                else:
                    auto_backend = 'inline'
            else:
                auto_backend = ''

            # Mapping of Spyder options to backends
            backends = {'0': 'inline',
                        '1': auto_backend,
                        '2': 'qt5',
                        '3': 'qt4',
                        '4': 'osx',
                        '5': 'gtk3',
                        '6': 'gtk',
                        '7': 'wx',
                        '8': 'tk'}

            # Select backend
            mpl_backend = backends[backend_o]

            # Inline backend configuration
            if mpl_backend == 'inline':
                # Figure format
                format_o = os.environ.get('SPY_FORMAT_O')
                formats = {'0': 'png',
                           '1': 'svg'}
                if format_o is not None:
                    spy_cfg.InlineBackend.figure_format = formats[format_o]

                # Resolution
                resolution_o = os.environ.get('SPY_RESOLUTION_O')
                if resolution_o is not None:
                    spy_cfg.InlineBackend.rc[dpi_option] = float(resolution_o)

                # Figure size
                width_o = float(os.environ.get('SPY_WIDTH_O'))
                height_o = float(os.environ.get('SPY_HEIGHT_O'))
                if width_o is not None and height_o is not None:
                    spy_cfg.InlineBackend.rc['figure.figsize'] = (width_o,
                                                                  height_o)

                # Print figure kwargs
                bbox_inches_o = os.environ.get('SPY_BBOX_INCHES_O')
                bbox_inches = 'tight' if bbox_inches_o == 'True' else None
                spy_cfg.InlineBackend.print_figure_kwargs.update(
                    {'bbox_inches': bbox_inches})
        else:
            # Set Matplotlib backend to inline for external kernels.
            # Fixes issue 108
            mpl_backend = 'inline'

        # Automatically load Pylab and Numpy, or only set Matplotlib
        # backend
        autoload_pylab_o = os.environ.get('SPY_AUTOLOAD_PYLAB_O') == 'True'
        command = "get_ipython().kernel._set_mpl_backend('{0}', {1})"
        spy_cfg.IPKernelApp.exec_lines.append(
            command.format(mpl_backend, autoload_pylab_o))

    # Enable Cython magic
    run_cython = os.environ.get('SPY_RUN_CYTHON') == 'True'
    if run_cython and is_module_installed('Cython'):
        spy_cfg.IPKernelApp.exec_lines.append('%reload_ext Cython')

    # Run a file at startup
    use_file_o = os.environ.get('SPY_USE_FILE_O')
    run_file_o = os.environ.get('SPY_RUN_FILE_O')
    if use_file_o == 'True' and run_file_o is not None:
        spy_cfg.IPKernelApp.file_to_run = run_file_o

    # Autocall
    autocall_o = os.environ.get('SPY_AUTOCALL_O')
    if autocall_o is not None:
        spy_cfg.ZMQInteractiveShell.autocall = int(autocall_o)

    # To handle the banner by ourselves in IPython 3+
    spy_cfg.ZMQInteractiveShell.banner1 = ''

    # Greedy completer
    greedy_o = os.environ.get('SPY_GREEDY_O') == 'True'
    spy_cfg.IPCompleter.greedy = greedy_o

    # Sympy loading
    sympy_o = os.environ.get('SPY_SYMPY_O') == 'True'
    if sympy_o and is_module_installed('sympy'):
        lines = sympy_config(mpl_backend)
        spy_cfg.IPKernelApp.exec_lines.append(lines)

    # Merge IPython and Spyder configs. Spyder prefs will have prevalence
    # over IPython ones
    cfg._merge(spy_cfg)
    return cfg
1194533
def run_module(mod_name, init_globals=None,
               run_name=None, alter_sys=False):
    
    mod_name, loader, code, fname = _get_module_details(mod_name)
    if run_name is None:
        run_name = mod_name
    pkg_name = mod_name.rpartition('.')[0]
    if alter_sys:
        return _run_module_code(code, init_globals, run_name,
                                fname, loader, pkg_name)
    else:
        # Leave the sys module alone
        return _run_code(code, {}, init_globals, run_name,
                         fname, loader, pkg_name)
895035
def do_py(self, args: argparse.Namespace) -> bool:
        """"""
        from .pyscript_bridge import PyscriptBridge
        if self._in_py:
            err = "Recursively entering interactive Python consoles is not allowed."
            self.perror(err, traceback_war=False)
            return False

        try:
            self._in_py = True

            # Support the run command even if called prior to invoking an interactive interpreter
            def py_run(filename: str):
                """Run a Python script file in the interactive console.
                :param filename: filename of *.py script file to run
                """
                expanded_filename = os.path.expanduser(filename)

                # cmd_echo defaults to False for scripts. The user can always toggle this value in their script.
                bridge.cmd_echo = False

                try:
                    with open(expanded_filename) as f:
                        interp.runcode(f.read())
                except OSError as ex:
                    error_msg = "Error opening script file '{}': {}".format(expanded_filename, ex)
                    self.perror(error_msg, traceback_war=False)

            def py_quit():
                """Function callable from the interactive Python console to exit that environment"""
                raise EmbeddedConsoleExit

            # Set up Python environment
            bridge = PyscriptBridge(self)
            self.pystate[self.pyscript_name] = bridge
            self.pystate['run'] = py_run
            self.pystate['quit'] = py_quit
            self.pystate['exit'] = py_quit

            if self.locals_in_py:
                self.pystate['self'] = self
            elif 'self' in self.pystate:
                del self.pystate['self']

            localvars = self.pystate
            from code import InteractiveConsole
            interp = InteractiveConsole(locals=localvars)
            interp.runcode('import sys, os;sys.path.insert(0, os.getcwd())')

            # Check if the user is running a Python statement on the command line
            if args.command:
                full_command = args.command
                if args.remainder:
                    full_command += ' ' + ' '.join(args.remainder)

                # Set cmd_echo to True so PyscriptBridge statements like: py app('help')
                # run at the command line will print their output.
                bridge.cmd_echo = True

                # noinspection PyBroadException
                try:
                    interp.runcode(full_command)
                except BaseException:
                    # We don't care about any exception that happened in the interactive console
                    pass

            # If there are no args, then we will open an interactive Python console
            else:
                # Set up readline for Python console
                if rl_type != RlType.NONE:
                    # Save cmd2 history
                    saved_cmd2_history = []
                    for i in range(1, readline.get_current_history_length() + 1):
                        # noinspection PyArgumentList
                        saved_cmd2_history.append(readline.get_history_item(i))

                    readline.clear_history()

                    # Restore py's history
                    for item in self.py_history:
                        readline.add_history(item)

                    if self.use_rawinput and self.completekey:
                        # Set up tab completion for the Python console
                        # rlcompleter relies on the default settings of the Python readline module
                        if rl_type == RlType.GNU:
                            saved_basic_quotes = ctypes.cast(rl_basic_quote_characters, ctypes.c_void_p).value
                            rl_basic_quote_characters.value = orig_rl_basic_quotes

                            if 'gnureadline' in sys.modules:
                                # rlcompleter imports readline by name, so it won't use gnureadline
                                # Force rlcompleter to use gnureadline instead so it has our settings and history
                                saved_readline = None
                                if 'readline' in sys.modules:
                                    saved_readline = sys.modules['readline']

                                sys.modules['readline'] = sys.modules['gnureadline']

                        saved_delims = readline.get_completer_delims()
                        readline.set_completer_delims(orig_rl_delims)

                        # rlcompleter will not need cmd2's custom display function
                        # This will be restored by cmd2 the next time complete() is called
                        if rl_type == RlType.GNU:
                            readline.set_completion_display_matches_hook(None)
                        elif rl_type == RlType.PYREADLINE:
                            # noinspection PyUnresolvedReferences
                            readline.rl.mode._display_completions = self._display_matches_pyreadline

                        # Save off the current completer and set a new one in the Python console
                        # Make sure it tab completes from its locals() dictionary
                        saved_completer = readline.get_completer()
                        interp.runcode("from rlcompleter import Completer")
                        interp.runcode("import readline")
                        interp.runcode("readline.set_completer(Completer(locals()).complete)")

                # Set up sys module for the Python console
                self._reset_py_display()

                saved_sys_stdout = sys.stdout
                sys.stdout = self.stdout

                saved_sys_stdin = sys.stdin
                sys.stdin = self.stdin

                cprt = 'Type "help", "copyright", "credits" or "license" for more information.'
                instructions = ('End with `Ctrl-D` (Unix) / `Ctrl-Z` (Windows), `quit()`, `exit()`.\n'
                                'Non-Python commands can be issued with: {}("your command")\n'
                                'Run Python code from external script files with: run("script.py")'
                                .format(self.pyscript_name))

                # noinspection PyBroadException
                try:
                    interp.interact(banner="Python {} on {}\n{}\n\n{}\n".
                                    format(sys.version, sys.platform, cprt, instructions))
                except BaseException:
                    # We don't care about any exception that happened in the interactive console
                    pass

                finally:
                    sys.stdout = saved_sys_stdout
                    sys.stdin = saved_sys_stdin

                    # Set up readline for cmd2
                    if rl_type != RlType.NONE:
                        # Save py's history
                        self.py_history.clear()
                        for i in range(1, readline.get_current_history_length() + 1):
                            # noinspection PyArgumentList
                            self.py_history.append(readline.get_history_item(i))

                        readline.clear_history()

                        # Restore cmd2's history
                        for item in saved_cmd2_history:
                            readline.add_history(item)

                        if self.use_rawinput and self.completekey:
                            # Restore cmd2's tab completion settings
                            readline.set_completer(saved_completer)
                            readline.set_completer_delims(saved_delims)

                            if rl_type == RlType.GNU:
                                rl_basic_quote_characters.value = saved_basic_quotes

                                if 'gnureadline' in sys.modules:
                                    # Restore what the readline module pointed to
                                    if saved_readline is None:
                                        del(sys.modules['readline'])
                                    else:
                                        sys.modules['readline'] = saved_readline

        except KeyboardInterrupt:
            pass

        finally:
            self._in_py = False

        return self._should_quit
329226
def mktmpenv_cmd(argv):
    """"""
    parser = mkvirtualenv_argparser()
    env = '.'
    while (workon_home / env).exists():
        env = hex(random.getrandbits(64))[2:-1]

    args, rest = parser.parse_known_args(argv)

    mkvirtualenv(env, args.python, args.packages, requirements=args.requirements,
                 rest=rest)
    print('This is a temporary environment. It will be deleted when you exit')
    try:
        if args.activate:
            # only used for testing on windows
            shell(env)
    finally:
        return rmvirtualenvs([env])
92710
function runScripts() {
  var scripts = [];
  var types = ["text/ecmascript-6", "text/6to5", "text/babel", "module"];
  var index = 0;

  /**
   * Transform and execute script. Ensures correct load order.
   */

  var exec = function exec() {
    var param = scripts[index];
    if (param instanceof Array) {
      transform.run.apply(transform, param);
      index++;
      exec();
    }
  };

  /**
   * Load, transform, and execute all scripts.
   */

  var run = function run(script, i) {
    var opts = {};

    if (script.src) {
      transform.load(script.src, function (param) {
        scripts[i] = param;
        exec();
      }, opts, true);
    } else {
      opts.filename = "embedded";
      scripts[i] = [script.innerHTML, opts];
    }
  };

  // Collect scripts with Babel `types`.

  var _scripts = global.document.getElementsByTagName("script");

  for (var i = 0; i < _scripts.length; ++i) {
    var _script = _scripts[i];
    if (types.indexOf(_script.type) >= 0) scripts.push(_script);
  }

  for (i in scripts) {
    run(scripts[i], i);
  }

  exec();
}