Example #1
0
def install(user=False, symlink=False, overwrite=False, enable=False,
            **kwargs):
    """Install the nbpresent nbextension.

    Parameters
    ----------
    user: bool
        Install for current user instead of system-wide.
    symlink: bool
        Symlink instead of copy (for development).
    overwrite: bool
        Overwrite previously-installed files for this extension
    enable: bool
        Enable the extension on every notebook launch
    **kwargs: keyword arguments
        Other keyword arguments passed to the install_nbextension command
    """
    print("Installing nbpresent nbextension...")
    directory = join(dirname(abspath(__file__)), 'static', 'nbpresent')
    install_nbextension(directory, destination='nbpresent',
                        symlink=symlink, user=user, overwrite=overwrite,
                        **kwargs)

    if enable:
        print("Enabling nbpresent at every notebook launch...")
        cm = ConfigManager()
        cm.update('notebook',
                  {"load_extensions": {"nbpresent/nbpresent.min": True}})
Example #2
0
    def __init__(self):
        config_path = jupyter_config_path()
        if self.__config_dir not in config_path:
            # add self.config_dir to the front, if set manually
            config_path.insert(0, os.getcwd() + self.__config_dir)
        cm = ConfigManager(read_config_path=config_path)
        config_file = cm.get(self.__config_file_name)
        config = config_file.get("cs3")

        # overwriting default values with config file
        if config is not None:
            for key in self.config.keys():
                if key in config.keys():
                    self.config[key] = config[key]

        # overwriting the values with env vars
        for key in self.config.keys():
            env_name = "CS3_" + key.upper()
            if env_name in os.environ:
                self.config[key] = os.environ[env_name]

        if len(self.config["root_dir_list"]) > 0:
            root_dir_list = tuple(k.strip() for k in self.config["root_dir_list"].split(','))
            self.config["root_dir_list"] = root_dir_list
        else:
            self.config["root_dir_list"] = tuple()

        if not self.config["reva_host"]:
            raise KeyError("Reva host not provided")
        if not self.config["client_id"]:
            raise KeyError("Client ID not provided")
Example #3
0
def install(user=False, symlink=False, quiet=False, enable=False):
    """Install the widget nbextension and optionally enable it.
    
    Parameters
    ----------
    user: bool
        Install for current user instead of system-wide.
    symlink: bool
        Symlink instead of copy (for development).
    enable: bool
        Enable the extension after installing it.
    quiet: bool
        Suppress print statements about progress.
    """
    if not quiet:
        print("Installing nbextension ...")
    staticdir = pjoin(dirname(abspath(__file__)), "static")
    install_nbextension(staticdir, destination="widgets", user=user, symlink=symlink)

    if enable:
        if not quiet:
            print("Enabling the extension ...")
        cm = ConfigManager()
        cm.update("notebook", {"load_extensions": {"widgets/extension": True}})
    if not quiet:
        print("Done.")
Example #4
0
def _install_extension_nb41(enable=True):
    """deprecated, pre-4.2 implementation of installing notebook extension"""
    # server-side
    server = BaseJSONConfigManager(config_dir=jupyter_config_dir())
    server_cfg = server.get('jupyter_notebook_config')
    app_cfg = server_cfg.get('NotebookApp', {})
    server_extensions = app_cfg.get('server_extensions', [])
    server_ext = 'ipyparallel.nbextension'
    server_changed = False
    if enable and server_ext not in server_extensions:
        server_extensions.append(server_ext)
        server_changed = True
    elif (not enable) and server_ext in server_extensions:
        server_extensions.remove(server_ext)
        server_changed = True
    if server_changed:
        server.update('jupyter_notebook_config', {
            'NotebookApp': {
                'server_extensions': server_extensions,
            }
        })
    
    # frontend config (*way* easier because it's a dict)
    frontend = FrontendConfigManager()
    frontend.update('tree', {
        'load_extensions': {
            'ipyparallel/main': enable or None,
        }
    })
Example #5
0
def remove_notebook_config(CONFIG):
    # Removes the config in the notebook json
    if os.path.isfile(CONFIG):
        # Creates a backup file
        timestamp = datetime.datetime.now().strftime("%d-%m-%Y_T%H-%M-%S")
        title = ('backup_notebook_' + timestamp + '.json')
        BACKUP = os.path.join(ConfigManager()._config_dir_default(), title)
        print("ACTION: Creating a backup notebook.json, %s" % (BACKUP))
        shutil.copyfile(CONFIG, BACKUP)
        # Element to be removed
        data_element = {'stepsize_nb-ext/main_v0-2': True}
        # Counter
        count = 0
        try:
            if open(CONFIG).read() != "":
                with open(CONFIG) as f:
                    entries = json.load(f)
                for ext in entries['load_extensions'].keys():
                    if 'stepsize_nb-ext' in ext:
                        entries['load_extensions'].pop(ext)
                        count += 1
                with open(CONFIG, 'w') as outfile:
                    json.dump(entries, outfile)
                if count > 0:
                    print("OUTCOME: Removed the Stepsize extension "
                          "configuration from the notebook.json")
        except:
            print("WARNING: An error occured when trying to remove %s from "
                  "the notebook.json" % (data_element))
            print("ERROR: %s, at line %d" %
                  (sys.exc_info()[0], sys.exc_traceback.tb_lineno))
    else:
        print("WARNING: Unable to remove the Stepsize extension "
              "configuration since the notebook.json does not exist in %s" %
              (ConfigManager()._config_dir_default()))
Example #6
0
 def setup_config(self):
     # This is apparently a singleton?
     cm = ConfigManager()
     cm.update('common',
               {'GoogleAnalytics': {
                   'tracking_id': self.tracking_id
               }})
Example #7
0
def install(user=False, symlink=False, quiet=False, enable=False):
    """Install the widget nbextension and optionally enable it.
    
    Parameters
    ----------
    user: bool
        Install for current user instead of system-wide.
    symlink: bool
        Symlink instead of copy (for development).
    enable: bool
        Enable the extension after installing it.
    quiet: bool
        Suppress print statements about progress.
    """
    if not quiet:
        print("Installing nbextension ...")
    staticdir = pjoin(dirname(abspath(__file__)), 'static')
    install_nbextension(staticdir,
                        destination='widgets',
                        user=user,
                        symlink=symlink)

    if enable:
        if not quiet:
            print("Enabling the extension ...")
        cm = ConfigManager()
        cm.update(
            'notebook',
            {"load_extensions": {
                "widgets/notebook/js/extension": True,
            }})
    if not quiet:
        print("Done.")
Example #8
0
def setup_info():
    server_cm = ConfigManager(config_dir=j_path.jupyter_config_dir())
    cfg = server_cm.get('jupyter_notebook_config')
    server_extensions = (cfg.setdefault('NotebookApp', {})
                         .setdefault('server_extensions', [])
                         )
    extension = 'hide_code.hide_code'
    if extension not in server_extensions:
        ext = 'Not loaded'
    else:
        ext = 'Loaded'

    files = []
    for (dirpath, dirnames, filenames) in os.walk(path.join(Utils.get_module_dir())):
        files.extend(filenames)
        break

    custom_js = ''
    with open(path.join(Utils.get_notebook_module_dir(), 'static', 'custom', 'custom.js'), 'r') as f:
        for line in iter(f):
            if not line.startswith(' *') and not line.startswith('/'):
                custom_js = custom_js + line + ' '

    return (
        "Installation dir: {0}\nConfiguration dir: {1}\nExport handler extensions: {2}\nHide Code files: {3}\nCustom JS contents: {4}"
            .format(Utils.get_module_dir(), j_path.jupyter_config_dir(), ext, files, custom_js))
Example #9
0
def install(user=False, symlink=False, enable=False):
    """Install the widget nbextension and optionally enable it.

    Parameters
    ----------
    user: bool
        Install for current user instead of system-wide.
    symlink: bool
        Symlink instead of copy (for development).
    """
    try:
        from notebook.nbextensions import install_nbextension
        from notebook.services.config import ConfigManager
    except ModuleNotFoundError:
        print('"notebook" not installed, silently failing...')
        return
    widgetsdir = pjoin(dirname(abspath(__file__)), 'widgets')
    install_nbextension(widgetsdir,
                        destination='arcgis',
                        user=user,
                        symlink=symlink)

    cm = ConfigManager()
    cm.update('notebook', {"load_extensions": {
        "arcgis/mapview": True,
    }})
Example #10
0
def install_server_extension(enable=True):
    """Register ipyparallel clusters tab as a notebook server extension
    
    Toggle with enable=True/False.
    """
    # server-side
    server = BaseJSONConfigManager()
    server_cfg = server.get('jupyter_notebook_config')
    app_cfg = server_cfg.get('NotebookApp', {})
    server_extensions = app_cfg.get('server_extensions', [])
    server_ext = 'ipyparallel.nbextension'
    server_changed = False
    if enable and server_ext not in server_extensions:
        server_extensions.append(server_ext)
        server_changed = True
    elif (not enable) and server_ext in server_extensions:
        server_extensions.remove(server_ext)
        server_changed = True
    if server_changed:
        server.update(
            'jupyter_notebook_config',
            {'NotebookApp': {
                'server_extensions': server_extensions,
            }})

    # frontend config (*way* easier because it's a dict)
    frontend = FrontendConfigManager()
    frontend.update(
        'tree', {'load_extensions': {
            'ipyparallel/main': enable or None,
        }})
    def __init__(self, *args, **kwargs):
        super(ExporterCollapsibleHeadings, self).__init__(*args, **kwargs)

        self.inliner_resources['css'].append("""
/* no local copies of fontawesome fonts in basic templates, so use cdn */
@import url(https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css)
""")  # noqa: E501

        ch_dir = os.path.join(
            os.path.dirname(contrib_init), 'nbextensions',
            'collapsible_headings')

        with open(os.path.join(ch_dir, 'main.css'), 'r') as f:
            self.inliner_resources['css'].append(f.read())

        with open(os.path.join(ch_dir, 'main.js'), 'r') as f:
            self.inliner_resources['js'].append(f.read())

        cm = ConfigManager()
        collapsible_headings_options = cm.get('notebook').get(
            'collapsible_headings', {})
        self.inliner_resources['js'].append("""
$(document).ready(function () {
    require(['nbextensions/collapsible_headings/main'], function (ch) {
        ch.set_collapsible_headings_options(%s);
        ch.refresh_all_headings();
    });
});
""" % json.dumps(collapsible_headings_options))
Example #12
0
    def _default_config_dict(self):
        """ load merged config from more jupyter_notebook_config.d files

            re-uses notebook loading machinery to look through more locations
        """
        manager = ConfigManager(read_config_path=jupyter_config_path())
        return manager.get("jupyter_notebook_config").get("StarterManager", {})
Example #13
0
def _install_extension_nb41(enable=True):
    """deprecated, pre-4.2 implementation of installing notebook extension"""
    # server-side
    server = BaseJSONConfigManager(config_dir=jupyter_config_dir())
    server_cfg = server.get('jupyter_notebook_config')
    app_cfg = server_cfg.get('NotebookApp', {})
    server_extensions = app_cfg.get('server_extensions', [])
    server_ext = 'ipyparallel.nbextension'
    server_changed = False
    if enable and server_ext not in server_extensions:
        server_extensions.append(server_ext)
        server_changed = True
    elif (not enable) and server_ext in server_extensions:
        server_extensions.remove(server_ext)
        server_changed = True
    if server_changed:
        server.update(
            'jupyter_notebook_config',
            {'NotebookApp': {
                'server_extensions': server_extensions,
            }},
        )

    # frontend config (*way* easier because it's a dict)
    frontend = FrontendConfigManager()
    frontend.update(
        'tree',
        {'load_extensions': {
            'ipyparallel/main': enable or None,
        }},
    )
Example #14
0
def setup_info():
	server_cm = ConfigManager(config_dir=j_path.jupyter_config_dir())
	cfg = server_cm.get('jupyter_notebook_config')
	server_extensions = (cfg.setdefault('NotebookApp', {})
				.setdefault('server_extensions', [])
				)
	extension = 'hide_code.hide_code'
	if extension not in server_extensions:
		ext = 'Not loaded'
	else:
		ext = 'Loaded'

	files = []
	for (dirpath, dirnames, filenames) in os.walk(path.join(Utils.get_site_package_dir(), 'hide_code')):
		files.extend(filenames)
		break	

	custom_js = ''
	with open(path.join(Utils.get_site_package_dir(), 'notebook','static','custom','custom.js'), 'r') as f:
		for line in iter(f):
			if not line.startswith(' *') and not line.startswith('/'):
				custom_js = custom_js + line + ' '


	return ("Installation dir: {0}\nConfiguration dir: {1}\nExport handler extensions: {2}\nHide Code files: {3}\nCustom JS contents: {4}"
		.format(Utils.get_site_package_dir(), j_path.jupyter_config_dir(), ext, files, custom_js))
Example #15
0
def patch():
  from notebook.services.config import ConfigManager
  from IPython.paths import locate_profile
  cm = ConfigManager(profile_dir=locate_profile(get_ipython().profile))
  cm.update('livereveal', {'width': '100%', 'height': 700, 'margin': 0.2,}) 
  from IPython.display import HTML
  HTML('''<style>.CodeMirror{min-width:100% !important;}</style>''')
Example #16
0
def install_server_extension(enable=True):
    """Register ipyparallel clusters tab as a notebook server extension
    
    Toggle with enable=True/False.
    """
    # server-side
    server = BaseJSONConfigManager(config_dir=jupyter_config_dir())
    server_cfg = server.get('jupyter_notebook_config')
    app_cfg = server_cfg.get('NotebookApp', {})
    server_extensions = app_cfg.get('server_extensions', [])
    server_ext = 'ipyparallel.nbextension'
    server_changed = False
    if enable and server_ext not in server_extensions:
        server_extensions.append(server_ext)
        server_changed = True
    elif (not enable) and server_ext in server_extensions:
        server_extensions.remove(server_ext)
        server_changed = True
    if server_changed:
        server.update('jupyter_notebook_config', {
            'NotebookApp': {
                'server_extensions': server_extensions,
            }
        })
    
    # frontend config (*way* easier because it's a dict)
    frontend = FrontendConfigManager()
    frontend.update('tree', {
        'load_extensions': {
            'ipyparallel/main': enable or None,
        }
    })
Example #17
0
    def __init__(self, *args, **kwargs):
        super(ExporterCollapsibleHeadings, self).__init__(*args, **kwargs)

        self.inliner_resources['css'].append("""
/* no local copies of fontawesome fonts in basic templates, so use cdn */
@import url(https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css)
""")  # noqa: E501

        ch_dir = os.path.join(os.path.dirname(contrib_init), 'nbextensions',
                              'collapsible_headings')

        with open(os.path.join(ch_dir, 'main.css'), 'r') as f:
            self.inliner_resources['css'].append(f.read())

        with open(os.path.join(ch_dir, 'main.js'), 'r') as f:
            self.inliner_resources['js'].append(f.read())

        cm = ConfigManager()
        collapsible_headings_options = cm.get('notebook').get(
            'collapsible_headings', {})
        self.inliner_resources['js'].append("""
$(document).ready(function () {
    require(['nbextensions/collapsible_headings/main'], function (ch) {
        ch.set_collapsible_headings_options(%s);
        ch.refresh_all_headings();
    });
});
""" % json.dumps(collapsible_headings_options))
Example #18
0
 def __init__(self):
     #
     # Get config from the env variables or from jupyter_cs3_config.json file
     #
     if 'CS3_EXT_CONFIG' in os.environ.keys() and utils.strtobool(
             os.environ['CS3_EXT_CONFIG']):
         self.config = {}
         self.log.info("Reading CS3 config from environment")
         for name in self.__env_names:
             env_name = "CS3_" + name.upper()
             if env_name in os.environ:
                 self.log.info(f"Reading config value {name} = " +
                               str(os.environ[env_name]))
                 self.config[name] = os.environ[env_name]
             else:
                 self.log.error(f"Unable to read {name}")
                 raise ValueError(
                     f"Unable to read {name} from environment variables")
     else:
         self.log.info(
             f'Reading CS3 config from file {self.__config_dir}{self.__config_file_name}'
         )
         config_path = jupyter_config_path()
         if self.__config_dir not in config_path:
             # add self.config_dir to the front, if set manually
             config_path.insert(0, os.getcwd() + self.__config_dir)
         cm = ConfigManager(read_config_path=config_path)
         config_file = cm.get(self.__config_file_name)
         self.config = config_file.get("cs3")
         if self.config is None:
             self.log.error(
                 f'Error while reading cs3 config file {self.__config_dir}{self.__config_file_name}'
             )
             raise IOError(u'Error while reading cs3 config file')
Example #19
0
 def start(self):
     self.log.info("Activating jupyter_dashboards_bundlers JS notebook extensions")
     cm = ConfigManager(parent=self, config=self.config)
     cm.update('notebook', { 
         'jupyter_cms_bundlers': {
             'dashboards_local_deploy': {
                 'label': 'Local Dashboard',
                 'module_name': 'dashboards_bundlers.local_deploy',
                 'group': 'deploy'
             },
             'dashboards_php_download': {
                 'label': 'PHP Dashboard bundle (.zip)',
                 'module_name': 'dashboards_bundlers.php_download',
                 'group': 'download'
             },
             'dashboards_server_upload': {
                 'label': 'Dashboard on Jupyter Dashboards Server',
                 'module_name': 'dashboards_bundlers.server_upload',
                 'group': 'deploy'
             },
             'dashboards_server_download': {
                 'label': 'Jupyter Dashboards Server bundle (.zip)',
                 'module_name': 'dashboards_bundlers.server_download',
                 'group': 'download'
             }
         }
     })
     self.log.info("Done.")
 def disable_bundler(self):
     '''Disables the notebook bundler extension.'''
     cm = ConfigManager(parent=self, config=self.config)
     cm.update('notebook', { 
         'jupyter_cms_bundlers': {
             'notebook_associations_download': None
         }
     })
Example #21
0
 def run(self):
     _install.run(self)
     if install_nbextension is not None and ConfigManager is not None:
         cm = ConfigManager()
         cm.update('notebook',
                   {"load_extensions": {
                       "demdraper/index": True
                   }})
Example #22
0
 def disable_bundler(self):
     '''Disables the notebook bundler extension.'''
     cm = ConfigManager(parent=self, config=self.config)
     cm.update(
         'notebook',
         {'jupyter_cms_bundlers': {
             'notebook_associations_download': None
         }})
Example #23
0
 def disable_nbextension(self, name):
     # Local import to avoid circular import issue on Py 2
     from notebook.services.config import ConfigManager
     cm = ConfigManager(parent=self, config=self.config)
     if name not in cm.get(self.section).get('load_extensions', {}):
         sys.exit('{} is not enabled in section {}'.format(name, self.section))
     # We're using a dict as a set - updating with None removes the key
     cm.update(self.section, {"load_extensions": {name: None}})
Example #24
0
File: setup.py Project: bwilk7/RISE
def install(config_dir, use_symlink=False, enable=True):
    # Install the livereveal code.
    install_nbextension(livereveal_dir, symlink=use_symlink,
                        overwrite=use_symlink, user=True)

    if enable:
        cm = ConfigManager(config_dir=config_dir)
        cm.update('notebook', {"load_extensions": {"livereveal/main": True}})
 def start(self):
     self.log.info("Deactivating jupyter_kernel_gateway_bundlers notebook extension")
     cm = ConfigManager(parent=self, config=self.config)
     cm.update('notebook', {
         'jupyter_cms_bundlers': {
             'microservice_dockerfile_download' : None
         }
     })
     self.log.info("Done.")
Example #26
0
 def run(self):
     _develop.run(self)
     install_nbextension(extension_dir,
                         symlink=True,
                         overwrite=True,
                         user=True,
                         destination="validation")
     cm = ConfigManager()
     cm.update("notebook", {"load_extensions": {"example/index": True}})
Example #27
0
 def run(self):
     _develop.run(self)
     install_nbextension(extension_dir,
                         symlink=True,
                         overwrite=True,
                         user=True,
                         destination="idaho_map")
     cm = ConfigManager()
     cm.update('notebook', {"load_extensions": {"idaho_map/index": True}})
Example #28
0
 def get_bundler(self, bundler_id):
     '''
     :param bundler_id: Unique ID within the notebook/jupyter_cms_bundlers
     config section.
     :returns: Dict of bundler metadata with keys label, group, module_name
     :raises KeyError: If the bundler is not registered
     '''
     cm = ConfigManager()
     return cm.get('notebook').get('jupyter_cms_bundlers', {})[bundler_id]
Example #29
0
def configure(url, client_id):
    """Configure the Jupyter server extension."""
    from notebook.services.config import ConfigManager

    cm = ConfigManager()
    cm.update('renku.notebook.oic', {
        'client_id': client_id,
        'url': url,
    })
Example #30
0
 def disable_nbextension(self, name):
     # Local import to avoid circular import issue on Py 2
     from notebook.services.config import ConfigManager
     cm = ConfigManager(parent=self, config=self.config)
     if name not in cm.get(self.section).get('load_extensions', {}):
         sys.exit('{} is not enabled in section {}'.format(
             name, self.section))
     # We're using a dict as a set - updating with None removes the key
     cm.update(self.section, {"load_extensions": {name: None}})
 def __init__(self, name, **kwargs):
     self.name = name
     self.prefix = kwargs.get('prefix', None)
     self.kwargs = kwargs
     if self.prefix is None:
         self.path = jupyter_config_dir()
     else:
         self.path = join(self.prefix, "etc", "jupyter")
     self.cm = ConfigManager(config_dir=join(self.path, 'nbconfig'))
     self.cm_server = ConfigManager(config_dir=self.path)
Example #32
0
def install(use_symlink=False, enable=True):
    # Install the livereveal code.
    install_nbextension(livereveal_dir,
                        symlink=use_symlink,
                        overwrite=use_symlink,
                        user=True)

    if enable:
        cm = ConfigManager()
        cm.update('notebook', {"load_extensions": {"livereveal/main": True}})
Example #33
0
def config_configManager():
    print("Update ConfigManager")
    from notebook.services.config import ConfigManager
    cm = ConfigManager()
    cm.update('livereveal', {
              'theme': 'serif',
              'start_slideshow_at': 'selected',
              'width': 1680,
              'height': 768,
    })
 def __init__(self, name, **kwargs):
     self.name = name
     self.prefix = kwargs.get('prefix', None)
     self.kwargs = kwargs
     if self.prefix is None:
         self.path = jupyter_config_dir()
     else:
         self.path = join(self.prefix, "etc", "jupyter")
     self.cm = ConfigManager(config_dir=join(self.path, 'nbconfig'))
     self.cm_server = ConfigManager(config_dir=self.path)
Example #35
0
def install(enable=False, disable=False, prefix=None):
    """Install the nb_config_manager config piece.

    Parameters
    ----------
    enable: bool
        Enable the nb_config_manager on every notebook launch
    disable: bool
        Disable nb_config_manager on every notebook launch
    """
    from notebook.services.config import ConfigManager

    if enable:
        if prefix is not None:
            path = join(prefix, "etc", "jupyter")
            if not exists(path):
                print("Making directory", path)
                os.makedirs(path)
        else:
            path = jupyter_config_dir()

        cm = ConfigManager(config_dir=path)
        print("Enabling nb_config_manager in", cm.config_dir)
        cfg = cm.get("jupyter_notebook_config")
        print("Existing config...")
        pprint(cfg)

        notebook_app = cfg.setdefault("NotebookApp", {})
        if "config_manager_class" not in notebook_app:
            cfg["NotebookApp"]["config_manager_class"] = "nb_config_manager.EnvironmentConfigManager"

        cm.update("jupyter_notebook_config", cfg)
        print("New config...")
        pprint(cm.get("jupyter_notebook_config"))

    if disable:
        if prefix is not None:
            path = join(prefix, "etc", "jupyter")
        else:
            path = jupyter_config_dir()

        cm = ConfigManager(config_dir=path)
        print("Disabling nb_config_manager in", cm.config_dir)
        cfg = cm.get("jupyter_notebook_config")
        print("Existing config...")
        pprint(cfg)

        config_manager = cfg["NotebookApp"]["config_manager_class"]

        if "nb_config_manager.EnvironmentConfigManager" == config_manager:
            cfg["NotebookApp"].pop("config_manager_class")

        cm.set("jupyter_notebook_config", cfg)
        print("New config...")
        pprint(cm.get("jupyter_notebook_config"))
Example #36
0
def _install_notebook_extension():
    print('Installing notebook extension')
    install_nbextension(EXT_DIR, overwrite=True, user=True)
    cm = ConfigManager()
    print('Enabling extension for notebook')
    cm.update('notebook', {"load_extensions": {'urth_cms_js/notebook/main': True}})
    print('Enabling extension for dashboard')
    cm.update('tree', {"load_extensions": {'urth_cms_js/dashboard/main': True}})
    print('Enabling extension for text editor')
    cm.update('edit', {"load_extensions": {'urth_cms_js/editor/main': True}})
    print('Enabling notebook and associated files bundler')
    cm.update('notebook', { 
      'jupyter_cms_bundlers': {
        'notebook_associations_download': {
          'label': 'IPython Notebook bundle (.zip)',
          'module_name': 'urth.cms.nb_bundler',
          'group': 'download'
        }
      }
    })

    print('Installing notebook server extension')
    fn = os.path.join(jupyter_config_dir(), 'jupyter_notebook_config.py')
    with open(fn, 'r+') as fh:
        lines = fh.read()
        if SERVER_EXT_CONFIG not in lines:
            fh.seek(0, 2)
            fh.write('\n')
            fh.write(SERVER_EXT_CONFIG)
Example #37
0
 def run(self):
     _develop.run(self)
     install_nbextension(
         extension_dir,
         symlink=True,
         overwrite=True,
         user=False,
         sys_prefix=True,  # to install it inside virtualenv
         destination="robomission")
     cm = ConfigManager()
     cm.update('notebook', {"load_extensions": {"robomission/index": True}})
Example #38
0
 def run(self):
     _develop.run(self)
     install_nbextension(
         extension_dir,
         symlink=True,
         overwrite=True,
         user=False,
         sys_prefix=True,  # to install it inside virtualenv
         destination="robomission")
     cm = ConfigManager()
     cm.update('notebook', {"load_extensions": {"robomission/index": True } })
Example #39
0
 def run_nbextension_install(develop):
     import sys
     sysprefix = hasattr(sys, 'real_prefix')
     if sysprefix:
         install_nbextension(extension_dir, symlink=develop, sys_prefix=sysprefix)
     else:
         install_nbextension(extension_dir, symlink=develop, user=user)
     if enable is not None:
         print("Enabling the extension ...")
         cm = ConfigManager()
         cm.update('notebook', {"load_extensions": {enable: True}})
 def start(self):
     self.log.info("Deactivating jupyter_dashboards_bundlers JS notebook extensions")
     cm = ConfigManager(parent=self, config=self.config)
     cm.update('notebook', { 
         'jupyter_cms_bundlers': {
             'dashboards_local_deploy' : None,
             'dashboards_php_download' : None,
             'dashboards_server_upload' : None
         }
     })
     self.log.info("Done.")
Example #41
0
    def enable_server_extension(self, extension):
        '''Enables the server side extension in the user config.'''
        server_cm = ConfigManager(config_dir=jupyter_config_dir())

        makedirs(server_cm.config_dir)

        cfg = server_cm.get('jupyter_notebook_config')
        server_extensions = (cfg.setdefault('NotebookApp', {}).setdefault(
            'server_extensions', []))
        if extension not in server_extensions:
            cfg['NotebookApp']['server_extensions'] += [extension]
        server_cm.update('jupyter_notebook_config', cfg)
Example #42
0
 def start(self):
     self.log.info("Deactivating jupyter_dashboards_bundlers JS notebook extensions")
     cm = ConfigManager(parent=self, config=self.config)
     cm.update('notebook', { 
         'jupyter_cms_bundlers': {
             'dashboards_local_deploy' : None,
             'dashboards_php_download' : None,
             'dashboards_server_upload' : None,
             'dashboards_server_download' : None
         }
     })
     self.log.info("Done.")
 def enable_bundler(self):
     '''Enables the notebook bundler extension.'''
     cm = ConfigManager(parent=self, config=self.config)
     cm.update('notebook', { 
         'jupyter_cms_bundlers': {
             'notebook_associations_download': {
                 'label': 'IPython Notebook bundle (.zip)',
                 'module_name': 'jupyter_cms.nb_bundler',
                 'group': 'download'
             }
         }
     })
 def start(self):
     self.log.info("Activating jupyter_kernel_gateway_bundlers JS notebook extensions")
     cm = ConfigManager(parent=self, config=self.config)
     cm.update('notebook', {
         'jupyter_cms_bundlers': {
             'microservice_dockerfile_download': {
                 'label': 'Microservice Docker bundle (.zip)',
                 'module_name': 'kernel_gateway_bundlers.dockerfile_download',
                 'group': 'download'
             }
         }
     })
     self.log.info("Done.")
Example #45
0
 def setup_config(self):
     """
     Updates the config for the duration of the user session.
     """
     cm = ConfigManager()
     cm.update(
         CONFIG_SECTION,
         {
             'GoogleAnalytics': {
                 'tracking_id': self.tracking_id
             }
         }
     )
Example #46
0
 def enable_bundler(self):
     '''Enables the notebook bundler extension.'''
     cm = ConfigManager(parent=self, config=self.config)
     cm.update(
         'notebook', {
             'jupyter_cms_bundlers': {
                 'notebook_associations_download': {
                     'label': 'IPython Notebook bundle (.zip)',
                     'module_name': 'jupyter_cms.nb_bundler',
                     'group': 'download'
                 }
             }
         })
Example #47
0
 def run(self):
     _develop.run(self)
     if install_nbextension is not None and ConfigManager is not None:
         install_nbextension(extension_dir,
                             symlink=True,
                             overwrite=True,
                             user=True,
                             destination="demdraper")
         cm = ConfigManager()
         cm.update('notebook',
                   {"load_extensions": {
                       "demdraper/index": True
                   }})
    def enable_server_extension(self, extension):
        '''Enables the server side extension in the user config.'''
        server_cm = ConfigManager(config_dir=jupyter_config_dir())
        
        makedirs(server_cm.config_dir)

        cfg = server_cm.get('jupyter_notebook_config')
        server_extensions = (
            cfg.setdefault('NotebookApp', {})
            .setdefault('server_extensions', [])
        )
        if extension not in server_extensions:
            cfg['NotebookApp']['server_extensions'] += [extension]
        server_cm.update('jupyter_notebook_config', cfg)
Example #49
0
 def run_nbextension_install(develop):
     try:
         # IPython/Jupyter 4.0
         from notebook.nbextensions import install_nbextension
         from notebook.services.config import ConfigManager
     except ImportError:
         # Pre-schism
         from IPython.html.nbextensions import install_nbextension
         from IPython.html.services.config import ConfigManager
     install_nbextension(extension_dir, symlink=develop, user=user, verbose=2)
     if enable is not None:
         print("Enabling the extension ...")
         cm = ConfigManager()
         cm.update('notebook', {"load_extensions": {enable: True}})
Example #50
0
def install(enable=False, **kwargs):
    """Install the nbpresent nbextension assets and optionally enables the
       nbextension and server extension for every run.

    Parameters
    ----------
    enable: bool
        Enable the extension on every notebook launch
    **kwargs: keyword arguments
        Other keyword arguments passed to the install_nbextension command
    """
    from notebook.nbextensions import install_nbextension
    from notebook.services.config import ConfigManager

    directory = join(dirname(abspath(__file__)), "static", "nbpresent")

    kwargs = {k: v for k, v in kwargs.items() if not (v is None)}

    kwargs["destination"] = "nbpresent"
    install_nbextension(directory, **kwargs)

    if enable:
        path = jupyter_config_dir()
        if "prefix" in kwargs:
            path = join(kwargs["prefix"], "etc", "jupyter")
            if not exists(path):
                print("Making directory", path)
                os.makedirs(path)

        cm = ConfigManager(config_dir=path)
        print("Enabling nbpresent server component in", cm.config_dir)
        cfg = cm.get("jupyter_notebook_config")
        print("Existing config...")
        pprint(cfg)
        server_extensions = cfg.setdefault("NotebookApp", {}).setdefault("server_extensions", [])
        if "nbpresent" not in server_extensions:
            cfg["NotebookApp"]["server_extensions"] += ["nbpresent"]

        cm.update("jupyter_notebook_config", cfg)
        print("New config...")
        pprint(cm.get("jupyter_notebook_config"))

        _jupyter_config_dir = jupyter_config_dir()
        # try:
        #     subprocess.call(["conda", "info", "--root"])
        #     print("conda detected")
        #     _jupyter_config_dir = ENV_CONFIG_PATH[0]
        # except OSError:
        #     print("conda not detected")

        cm = ConfigManager(config_dir=join(_jupyter_config_dir, "nbconfig"))
        print("Enabling nbpresent nbextension at notebook launch in", cm.config_dir)

        if not exists(cm.config_dir):
            print("Making directory", cm.config_dir)
            os.makedirs(cm.config_dir)

        cm.update("notebook", {"load_extensions": {"nbpresent/nbpresent.min": True}})
Example #51
0
    def run(self):
        from notebook.nbextensions import install_nbextension
        if self.source:
            livereveal_dir = self.source
        else:
            lib_dir = os.path.join(get_python_lib(), 'livereveal')
            if os.path.exists(lib_dir):
                livereveal_dir = lib_dir
            else:
                livereveal_dir = os.path.join(os.path.dirname(__file__), 'livereveal')
        install_nbextension(livereveal_dir, symlink=self.develop,
                            overwrite=self.develop, user=True)

        if not self.no_enable:
            from notebook.services.config import ConfigManager
            cm = ConfigManager()
            cm.update('notebook', {"load_extensions": {"livereveal/main": True}})
Example #52
0
def _install_notebook_extension():
    cm = ConfigManager()
    print('Installing notebook extension')
    cm.update('notebook', { 
        'jupyter_cms_bundlers': {
            'dashboards_local_deploy': {
                'label': 'Local Dashboard',
                'module_name': 'dashboards_bundlers.local_deploy',
                'group': 'deploy'
            },
            'dashboards_php_download': {
                'label': 'PHP Dashboard bundle (.zip)',
                'module_name': 'dashboards_bundlers.php_download',
                'group': 'download'
            }
        }
    })
    def __init__(self, *args, **kwargs):
        super(ExporterCollapsibleHeadings, self).__init__(*args, **kwargs)

        ch_dir = os.path.join(
            os.path.dirname(contrib_init), 'nbextensions',
            'collapsible_headings')

        with open(os.path.join(ch_dir, 'main.css'), 'r') as f:
            self.inliner_resources['css'].append(f.read())

        self.inliner_resources['css'].append("""
/* no local copies of fontawesome fonts from basic templates, so get them from cdn */
@font-face {
    font-family: 'FontAwesome';
    src: url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/fonts/fontawesome-webfont.eot');
    src: url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/fonts/fontawesome-webfont.eot?#iefix') format('embedded-opentype'),
         url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/fonts/fontawesome-webfont.woff') format('woff'),
         url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/fonts/fontawesome-webfont.ttf') format('truetype'),
         url('https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.2.0/fonts/fontawesome-webfont.svg#fontawesomeregular') format('svg');
    font-weight: normal;
    font-style: normal;
}
""")  # noqa: E501

        with open(os.path.join(ch_dir, 'main.js'), 'r') as f:
            self.inliner_resources['js'].append(f.read())

        cm = ConfigManager()
        collapsible_headings_options = cm.get('notebook').get(
            'collapsible_headings', {})
        self.inliner_resources['js'].append("""
require([
    'jquery',
    'nbextensions/collapsible_headings/main'
], function (
    $,
    nbext
) {
    nbext.set_collapsible_headings_options(%s);
    $(document).ready(function () {
        nbext.refresh_all_headings();
    });
});
""" % json.dumps(collapsible_headings_options))
Example #54
0
def install(user=True, symlink=False):
    """Install the widget nbextension.

    Parameters
    ----------
    user: bool
        Install for current user instead of system-wide.
    symlink: bool
        Symlink instead of copy (for development).
    """
    staticdir = resource_filename('nglview', os.path.join('html', 'static'))
    install_nbextension(staticdir, destination='nglview',
                        user=user, symlink=symlink)

    cm = ConfigManager()
    cm.update('notebook', {
        "load_extensions": {
            "widgets/notebook/js/extension": True,
        }
    })
Example #55
0
def install(enable=False, **kwargs):
    """Install the nbpresent nbextension assets and optionally enables the
       nbextension and server extension for every run.

    Parameters
    ----------
    enable: bool
        Enable the extension on every notebook launch
    **kwargs: keyword arguments
        Other keyword arguments passed to the install_nbextension command
    """
    from notebook.nbextensions import install_nbextension
    from notebook.services.config import ConfigManager

    directory = join(dirname(abspath(__file__)), 'static', 'nbpresent')

    kwargs = {k: v for k, v in kwargs.items() if not (v is None)}

    kwargs["destination"] = "nbpresent"

    install_nbextension(directory, **kwargs)

    if enable:
        if "prefix" in kwargs:
            path = join(kwargs["prefix"], "etc", "jupyter")
            if not exists(path):
                os.makedirs(path)

        cm = ConfigManager(config_dir=path)
        print("Enabling for", cm.config_dir)
        print("Enabling nbpresent server component...")
        cm.update(
            "jupyter_notebook_config", {
                "notebook": {
                    "load_extensions": {"nbpresent/nbpresent.min": True}
                },
                "NotebookApp": {
                    "server_extensions": ["nbpresent"]
                }
            }
        )
Example #56
0
 def setup_notebook_config(self):
     # Set the notebook extension to launch on startup by
     # modifying the notebook.json
     ensure_dir_exists(ConfigManager()._config_dir_default())
     # Elements to be added
     version = 2
     data_element = {'stepsize_nb-ext/main': None}
     for i in range(1, version):
         data_element['stepsize_nb-ext/main_v0-%i' % i] = None
     data_element['stepsize_nb-ext/main_v0-%i' % version] = True
     data = {'load_extensions': data_element}
     try:
         cm = ConfigManager()
         cm.update('notebook', data)
         print("OUTCOME: Added the Stepsize notebook extension "
               "configuration to the notebook.json")
     except:
         print("WARNING: An error occured when trying to add %s to the "
               "notebook.json" % (data))
         print("ERROR: %s" % (sys.exc_info()[0]))
         raise