Esempio n. 1
0
def define_commands(dictionary):
    print "Ipython detected - magicing commands"
    magiced_names = []
    commands = hkl_commands_for_help + ub_commands_for_help  # @UndefinedVariable
    commands += [pos, scan]  # @UndefinedVariable
    ipython.GLOBAL_NAMESPACE_DICT = dictionary
    for f in commands:
        # Skip section headers like 'Motion'
        if not hasattr(f, '__call__'):
            continue
        
        # magic the function and remove from namespace (otherwise it would
        # shadow the magiced command)
        register_line_magic(parse_line(f))
        del dictionary[f.__name__]
        command_map[f.__name__] = f
        magiced_names.append(f.__name__)
    
    print "Magiced commands: " + ' '.join(magiced_names) 
    
    # because the functions have gone from namespace we need to override
    pythons_help = __builtins__.help
    del __builtins__.help
    
    register_line_magic(help)
    del help
Esempio n. 2
0
def reload_kedro(path, line=None):
    """"Line magic which reloads all Kedro default variables."""
    global startup_error
    global context
    global io

    try:
        import kedro.config.default_logger
        from kedro.context import load_context
        from kedro.cli.jupyter import collect_line_magic
    except ImportError:
        logging.error(
            "Kedro appears not to be installed in your current environment "
            "or your current IPython session was not started in a valid Kedro project."
        )
        raise

    try:
        path = path or project_path
        logging.debug("Loading the context from %s", str(path))

        context = load_context(path)
        io = context.catalog
        logging.info("** Kedro project %s", str(context.project_name))
        logging.info("Defined global variable `context` and `catalog`")

        for line_magic in collect_line_magic():
            register_line_magic(line_magic)
            logging.info("Registered line magic `%s`", line_magic.__name__)
    except Exception as err:
        startup_error = err
        logging.exception("Kedro's ipython session startup script failed:\n%s",
                          str(err))
        raise err
Esempio n. 3
0
def magic_commands(global_namespace_dict):
    """Magic commands left in global_namespace_dict by previous import from
    diffcalc.
    
    Also creates a help command. NOTE that calling this will
    remove the original commands from the global namespace as otherwise these
    would shadow the ipython magiced versions.
    
    Depends on hkl_commands_for_help & ub_commands_for_help list having been
    left in the global namespace and assumes there is pos and scan command.
    """
    gnd = global_namespace_dict
    global GLOBAL_NAMESPACE_DICT
    GLOBAL_NAMESPACE_DICT = gnd

    ### Magic commands in namespace ###
    commands = list(gnd['hkl_commands_for_help'])
    commands += gnd['ub_commands_for_help']
    commands.append(gnd['pos'])
    commands.append(gnd['scan'])
    command_map = {}
    for f in commands:
        # Skip section headers like 'Motion'
        if not hasattr(f, '__call__'):
            continue
        # magic the function and remove from namespace (otherwise it would
        # shadow the magiced command)
        register_line_magic(parse_line(f, gnd))
        del gnd[f.__name__]
        command_map[f.__name__] = f

    ### Create help function ###
    #Expects python's original help to be named pythons_help and to be
    #available in the top-level global namespace (where non-diffcalc
    #objects may have help called from).
    def help(s):  # @ReservedAssignment
        """Diffcalc help for iPython
        """
        if s == '':
            print _DEFAULT_HELP
        elif s == 'hkl':
            # Use help injected into hkl object
            print Hkl.dynamic_docstring
        elif s == 'ub':
            # Use help injected into ub command
            print command_map['ub'].__doc__
        elif s in command_map:
            print "%s (diffcalc command):" % s
            print command_map[s].__doc__
        else:
            exec('pythons_help(%s)' % s, gnd)

    ### Setup help command ###
    gnd['pythons_help'] = ORIGINAL_PYTHON_HELP
    register_line_magic(help)
    # Remove builtin help
    # (otherwise it would shadow magiced command
    if 'help' in __builtins__:
        del __builtins__['help']
Esempio n. 4
0
def reload_kedro(path, line=None):
    """Line magic which reloads all Kedro default variables."""
    global startup_error
    global context
    global catalog
    global session

    try:
        import kedro.config.default_logger
        from kedro.framework.hooks import get_hook_manager
        from kedro.framework.project import configure_project
        from kedro.framework.session import KedroSession
        from kedro.framework.session.session import _activate_session
        from kedro.framework.cli.jupyter import collect_line_magic
    except ImportError:
        logging.error(
            "Kedro appears not to be installed in your current environment "
            "or your current IPython session was not started in a valid Kedro project."
        )
        raise

    try:
        path = path or project_path

        # clear hook manager
        hook_manager = get_hook_manager()
        name_plugin_pairs = hook_manager.list_name_plugin()
        for name, plugin in name_plugin_pairs:
            hook_manager.unregister(name=name, plugin=plugin)

        # remove cached user modules
        metadata = _get_project_metadata(path)
        to_remove = [
            mod for mod in sys.modules if mod.startswith(metadata.package_name)
        ]
        # `del` is used instead of `reload()` because: If the new version of a module does not
        # define a name that was defined by the old version, the old definition remains.
        for module in to_remove:
            del sys.modules[module]

        configure_project(metadata.package_name)
        session = KedroSession.create(metadata.package_name, path)
        _activate_session(session, force=True)
        logging.debug("Loading the context from %s", str(path))
        context = session.load_context()
        catalog = context.catalog

        logging.info("** Kedro project %s", str(metadata.project_name))
        logging.info("Defined global variable `context` and `catalog`")

        for line_magic in collect_line_magic():
            register_line_magic(needs_local_scope(line_magic))
            logging.info("Registered line magic `%s`", line_magic.__name__)
    except Exception as err:
        startup_error = err
        logging.exception("Kedro's ipython session startup script failed:\n%s",
                          str(err))
        raise err
Esempio n. 5
0
def _new_test_flag_fn(flag):
    "Create a new test flag function and magic"
    # don't create "empty" test flags if tst_flags is not set, set to whitespace, has trailing | etc
    if not flag.strip(): return
    def _(line): _validate_param(line, f'nbdev_{flag}_test', fixed_value='all')
    _.__doc__ = f"""Put an `%nbdev_{flag}_test` magic on each "{flag}" test cell that you do not want to be run by default.
    To apply this flag to all tests in a notebook, one cell should contain: `%nbdev_{flag}_test all`
    These tests can be executed with the command line tool: `nbdev_test_nbs --flags {flag}`'."""
    register_line_magic(f'nbdev_{flag}_test')(_)
def reload_kedro(path, line=None):
    """Line magic which reloads all Kedro default variables."""
    global startup_error
    global context
    global catalog

    try:
        import kedro.config.default_logger  # noqa
        from kedro.framework.cli.jupyter import collect_line_magic
        from kedro.framework.context import load_context
    except ImportError:
        logging.error(
            "Kedro appears not to be installed in your current environment "
            "or your current IPython session was not started in a valid Kedro project."
        )
        raise

    try:
        path = path or project_path

        # remove cached user modules
        context = load_context(path)
        to_remove = [
            mod for mod in sys.modules if mod.startswith(context.package_name)
        ]
        # `del` is used instead of `reload()` because: If the new version of a module does not
        # define a name that was defined by the old version, the old definition remains.
        for module in to_remove:
            del sys.modules[module]

        # clear hook manager; hook implementations will be re-registered when the
        # context is instantiated again in `load_context()` below
        hook_manager = get_hook_manager()
        name_plugin_pairs = hook_manager.list_name_plugin()
        for name, plugin in name_plugin_pairs:
            hook_manager.unregister(name=name, plugin=plugin)

        logging.debug("Loading the context from %s", str(path))
        # Reload context to fix `pickle` related error (it is unable to serialize reloaded objects)
        # Some details can be found here:
        # https://modwsgi.readthedocs.io/en/develop/user-guides/issues-with-pickle-module.html#packing-and-script-reloading
        context = load_context(path)
        catalog = context.catalog

        logging.info("** Kedro project %s", str(context.project_name))
        logging.info("Defined global variable `context` and `catalog`")

        for line_magic in collect_line_magic():
            register_line_magic(needs_local_scope(line_magic))
            logging.info("Registered line magic `%s`", line_magic.__name__)
    except Exception as err:
        startup_error = err
        logging.exception("Kedro's ipython session startup script failed:\n%s",
                          str(err))
        raise err
Esempio n. 7
0
def load_ipython_extension(ipython):
    """Load bg extension"""
    global ip, old_run_code, ext_state

    if ext_state == "never loaded":
        ip = ipython
        ip.input_transformers_post.append(bgtransform)
        for magic in bgmagics:
            register_line_magic(magic)

        old_run_code = ip.run_code
        ip.run_code = new_run_code

    ext_state = "enabled"
    new_thread()
def _declare_line_magic(name, module, magic_module_loader):
    """Declare a line magic called name in module."""
    # If the module or extension has already been imported, don't overwrite the
    # existing definition.
    if module in sys.modules or module in get_ipython(
    ).extension_manager.loaded:
        return

    def impl(line, **kwargs):
        return _get_extension_magic(name, module, 'line',
                                    magic_module_loader)(line, **kwargs)

    # pylint: disable=g-long-lambda
    impl.getdoc = lambda: _get_extension_magic(name, module, 'line',
                                               magic_module_loader).__doc__
    magic.register_line_magic(name)(impl)
Esempio n. 9
0
    def _make_line_magic(self):
        line_magic_names = [f[0] for f in inspect.getmembers(line_magics) if inspect.isfunction(f[1])]

        def _safety(line_: str):
            # this is to avoid capturing `self` and creating an extra reference to the singleton
            try:
                cmd, line = line_.split(' ', 1)
            except ValueError:
                cmd, line = line_, ''
            if cmd in ('deps', 'show_deps', 'show_dependency', 'show_dependencies'):
                return line_magics.show_deps(line)
            elif cmd in ('stale', 'show_stale'):
                return line_magics.show_stale(line)
            elif cmd == 'trace_messages':
                return line_magics.trace_messages(line)
            elif cmd in ('hls', 'nohls', 'highlight', 'highlights'):
                return line_magics.set_highlights(cmd, line)
            elif cmd in ('slice', 'make_slice', 'gather_slice'):
                return line_magics.make_slice(line)
            elif cmd == 'remove_dependency':
                return line_magics.remove_dep(line)
            elif cmd in ('add_dependency', 'add_dep'):
                return line_magics.add_dep(line)
            elif cmd == 'turn_off_warnings_for':
                return line_magics.turn_off_warnings_for(line)
            elif cmd == 'turn_on_warnings_for':
                return line_magics.turn_on_warnings_for(line)
            elif cmd in line_magic_names:
                print('We have a magic for %s, but have not yet registered it' % cmd)
            else:
                print(line_magics.USAGE)

        # FIXME (smacke): probably not a great idea to rely on this
        _safety.__name__ = _SAFETY_LINE_MAGIC
        return register_line_magic(_safety)
Esempio n. 10
0
    def _make_line_magic(self):
        line_magic_names = [
            f[0] for f in inspect.getmembers(line_magics)
            if inspect.isfunction(f[1])
        ]

        def _safety(line_: str):
            line = line_.split()
            if not line or line[0] not in line_magic_names:
                print(line_magics.USAGE)
                return
            elif line[0] in ("show_deps", "show_dependency",
                             "show_dependencies"):
                return line_magics.show_deps(self, line)
            elif line[0] == "show_stale":
                return line_magics.show_stale(self, line)
            elif line[0] == "set_propagation":
                return line_magics.set_propagation(self, line)
            elif line[0] == "trace_messages":
                return line_magics.trace_messages(self, line)
            elif line[0] == "remove_dependency":
                return line_magics.remove_dep(self, line)
            elif line[0] in ("add_dependency", "add_dep"):
                return line_magics.add_dep(self, line)
            elif line[0] == "turn_off_warnings_for":
                return line_magics.turn_off_warnings_for(self, line)
            elif line[0] == "turn_on_warnings_for":
                return line_magics.turn_on_warnings_for(self, line)

        # FIXME (smacke): probably not a great idea to rely on this
        _safety.__name__ = _SAFETY_LINE_MAGIC
        return register_line_magic(_safety)
Esempio n. 11
0
def reload_kedro(path, env: str = None, extra_params: Dict[str, Any] = None):
    """Line magic which reloads all Kedro default variables."""

    import kedro.config.default_logger  # noqa: F401 # pylint: disable=unused-import
    from kedro.framework.cli import load_entry_points
    from kedro.framework.project import pipelines
    from kedro.framework.session import KedroSession
    from kedro.framework.session.session import _activate_session
    from kedro.framework.startup import bootstrap_project

    _clear_hook_manager()

    path = path or project_path
    metadata = bootstrap_project(path)

    _remove_cached_modules(metadata.package_name)

    session = KedroSession.create(metadata.package_name,
                                  path,
                                  env=env,
                                  extra_params=extra_params)
    _activate_session(session, force=True)
    logging.debug("Loading the context from %s", str(path))
    context = session.load_context()
    catalog = context.catalog

    get_ipython().push(
        variables={
            "context": context,
            "catalog": catalog,
            "session": session,
            "pipelines": pipelines,
        })

    logging.info("** Kedro project %s", str(metadata.project_name))
    logging.info(
        "Defined global variable `context`, `session`, `catalog` and `pipelines`"
    )

    for line_magic in load_entry_points("line_magic"):
        register_line_magic(needs_local_scope(line_magic))
        logging.info("Registered line magic `%s`",
                     line_magic.__name__)  # type: ignore
Esempio n. 12
0
def reload_kedro(path, line=None):
    """"Line magic which reloads all Kedro default variables."""
    global startup_error
    global context
    global catalog

    try:
        import kedro.config.default_logger
        from kedro.context import KEDRO_ENV_VAR, load_context
        from kedro.cli.jupyter import collect_line_magic
    except ImportError:
        logging.error(
            "Kedro appears not to be installed in your current environment "
            "or your current IPython session was not started in a valid Kedro project."
        )
        raise

    try:
        path = path or project_path
        logging.debug("Loading the context from %s", str(path))

        context = load_context(path, env=os.getenv(KEDRO_ENV_VAR))
        catalog = context.catalog

        # remove cached user modules
        package_name = context.__module__.split(".")[0]
        to_remove = [
            mod for mod in sys.modules if mod.startswith(package_name)
        ]
        for module in to_remove:
            del sys.modules[module]

        logging.info("** Kedro project %s", str(context.project_name))
        logging.info("Defined global variable `context` and `catalog`")

        for line_magic in collect_line_magic():
            register_line_magic(line_magic)
            logging.info("Registered line magic `%s`", line_magic.__name__)
    except Exception as err:
        startup_error = err
        logging.exception("Kedro's ipython session startup script failed:\n%s",
                          str(err))
        raise err
Esempio n. 13
0
def load_kedro_objects(path, line=None):  # pylint: disable=unused-argument
    """Line magic which reloads all Kedro default variables."""

    import kedro.config.default_logger  # noqa: F401 # pylint: disable=unused-import
    from kedro.framework.cli import load_entry_points
    from kedro.framework.cli.utils import _add_src_to_path
    from kedro.framework.project import configure_project
    from kedro.framework.session import KedroSession
    from kedro.framework.session.session import _activate_session
    from kedro.framework.startup import _get_project_metadata

    global context
    global catalog
    global session

    path = path or project_path
    metadata = _get_project_metadata(path)
    _add_src_to_path(metadata.source_dir, path)
    configure_project(metadata.package_name)

    _clear_hook_manager()

    _remove_cached_modules(metadata.package_name)

    session = KedroSession.create(metadata.package_name, path)
    _activate_session(session)
    logging.debug("Loading the context from %s", str(path))
    context = session.load_context()
    catalog = context.catalog

    get_ipython().push(variables={
        "context": context,
        "catalog": catalog,
        "session": session
    })

    logging.info("** Kedro project %s", str(metadata.project_name))
    logging.info("Defined global variable `context`, `session` and `catalog`")

    for line_magic in load_entry_points("line_magic"):
        register_line_magic(needs_local_scope(line_magic))
        logging.info("Registered line magic `%s`", line_magic.__name__)
Esempio n. 14
0
#     chi = ScannableAdapter(satilt, 'chi', 90)  # chi = satilt + 90deg
#     phi = ScannableAdapter(saazimuth, 'phi')
    
    def usediode():
        _fourc.delta_scn = diodetth
        setmin(delta, 0)
        setmax(delta, 180)
        
    def usevessel():
        _fourc.delta_scn = m5tth
        setmin(delta, 0)
        setmax(delta, 150)
        
    if IPYTHON:
        from IPython import get_ipython  # @UnresolvedImport @UnusedImport
        register_line_magic(parse_line(usediode, globals()))
        del usediode
        register_line_magic(parse_line(usevessel, globals()))
        del usevessel
        register_line_magic(parse_line(centresample, globals()))
        del centresample
        register_line_magic(parse_line(zerosample, globals()))
        del zerosample
        register_line_magic(parse_line(toolpoint_on, globals()))
        del toolpoint_on
        register_line_magic(parse_line(toolpoint_off, globals()))
        del toolpoint_off

        
print "Created i21 bespoke commands: usediode & usevessel"
Esempio n. 15
0
            'if not root.handlers: '
            'handler = logging.StreamHandler(); '
            'handler.setFormatter(formatter); '
            'root.setLevel(logging.INFO); '
            'root.addHandler(handler)',
        ])
    )


if (
    register_line_magic is not None and
    get_ipython is not None and
    get_ipython() is not None
):
    import_all = register_line_magic(import_all)

__all__ = [
    'analysis',
    'cluster',
    'correlation',
    'data_sets',
    'discoverer',
    'levels',
    'loading',
    'motifs',
    'phosphosite',
    'paths',
    'pathways',
    'pride',
    'species',
Esempio n. 16
0
@contextmanager
def redirect_stdout(out):
    orig_stdout = sys.stdout
    sys.stdout = out
    try:
        yield
    finally:
        sys.stdout = orig_stdout


def trace(line):
    """Usage: %trace (enable|disable) [file pattern] [output path]"""
    args = line.split()
    enable = args[0] in {'enable', 'on'}

    if not enable:
        sys.settrace(None)
        sys.stdout = _ORIGINAL_STDOUT
        return

    pattern = args[1] if len(args) > 1 else None
    sys.stdout = open(args[2], 'a') if len(args) > 2 else sys.stdout
    sys.settrace(partial(trace_line, pattern))


try:
    register_line_magic(trace)
except NameError:
    pass
Esempio n. 17
0
def load_ipython_extension(ipython):
    from IPython.core.magic import register_line_magic
    register_line_magic(nose)
Esempio n. 18
0
def load_ipython_extension(ipython):
    from IPython.core.magic import register_line_magic, register_cell_magic

    register_line_magic(profilegraph)
    register_cell_magic(profilegraph)
Esempio n. 19
0
            "if not root.handlers: "
            "handler = logging.StreamHandler(); "
            "handler.setFormatter(formatter); "
            "root.setLevel(logging.INFO); "
            "root.addHandler(handler)",
        ])
    )


if (
    register_line_magic is not None and
    get_ipython is not None and
    get_ipython() is not None
):
    import_all = register_line_magic(import_all)

__all__ = [
    "analysis",
    "bca",
    "cluster",
    "correlation",
    "data_sets",
    "discoverer",
    "levels",
    "loading",
    "motifs",
    "phosphosite",
    "paths",
    "pathways",
    "pride",
Esempio n. 20
0
    def define_magic(interpreter, function):
        def get_ipython():
            return interpreter

        from IPython.core.magic import register_line_magic
        register_line_magic(function)
Esempio n. 21
0
    except Exception as ex:
        print(f'UsageError: {ex}')


def _new_test_flag_fn(flag):
    "Create a new test flag function and magic"
    # don't create "empty" test flags if tst_flags is not set, set to whitespace, has trailing | etc
    if not flag.strip(): return

    def _(line):
        _validate_param(line, f'nbdev_{flag}_test', fixed_value='all')

    _.__doc__ = f"""Put an `%nbdev_{flag}_test` magic on each "{flag}" test cell that you do not want to be run by default.
    To apply this flag to all tests in a notebook, one cell should contain: `%nbdev_{flag}_test all`
    These tests can be executed with the command line tool: `nbdev_test_nbs --flags {flag}`'."""
    register_line_magic(f'nbdev_{flag}_test')(_)


if IN_IPYTHON:
    from IPython.core.magic import register_line_magic, needs_local_scope
    fns = [
        nbdev_default_export, nbdev_export, nbdev_export_and_show,
        nbdev_export_internal, nbdev_hide, nbdev_hide_input, nbdev_hide_output,
        nbdev_default_class_level, nbdev_collapse_input, nbdev_collapse_output,
        needs_local_scope(nbdev_add2all)
    ]
    for fn in fns:
        register_line_magic(fn)
    for flag in Config().get('tst_flags', '').split('|'):
        _new_test_flag_fn(flag)
def load_ipython_extension(ipython):
    _install_namespace(ipython)
    ipython.register_magics(_PatchedMagics)  # Add warning to timing magics.
    register_line_magic(autoimport)
Esempio n. 23
0
 def define_magic(interpreter, function):
     def get_ipython():
         return interpreter
     from IPython.core.magic import register_line_magic
     register_line_magic(function)
Esempio n. 24
0
def load_ipython_extension(shell):
	"""Load the extension."""
	register_line_magic(copy)
Esempio n. 25
0
 def register_line_magic(f): # noqa
     return magic.register_line_magic(magic.no_var_expand(f))
Esempio n. 26
0
import shlex
import pwny
import pwnypack.main
from IPython.core.magic import register_line_magic

__all__ = []


def wrap_main(func_name):
    def wrapper(line):
        pwnypack.main.main([func_name] + shlex.split(line))

    return wrapper


for f_name, f_dict in pwnypack.main.MAIN_FUNCTIONS.items():
    register_line_magic(f_name)(wrap_main(f_name))


def load_ipython_extension(ipython):
    ipython.push(vars(pwny))


def unload_ipython_extension(ipython):
    ipython.drop_by_id(vars(pwny))
Esempio n. 27
0
    from IPython.core.magic import register_line_magic
    from diffcmd.ipython import parse_line
    delta = ScannableAdapter(diode_tth, 'delta')  # or vessel_tth
    eta = ScannableAdapter(sapol, 'eta')
    chi = ScannableAdapter(satilt, 'chi', 90)  # chi = satilt + 90deg
    phi = ScannableAdapter(saaz, 'phi')
    
    def usediode():
        delta.delegate_scn = diode_tth
    
    def usevessel():
        delta.delegate_scn = vessel_tth
        
    if IPYTHON:
        from IPython import get_ipython
        register_line_magic(parse_line(usediode, globals()))
        del usediode
        register_line_magic(parse_line(usevessel, globals()))
        del usevessel
        
print "Created i21 bespoke commands: usediode & usevessel"
 
_fourc = ScannableGroup('_fourc', (delta, eta, chi, phi))
en = Dummy('en')
en.level = 3
 
 
### Configure and import diffcalc objects ###
ESMTGKeV = 1
settings.hardware = ScannableHardwareAdapter(_fourc, en, ESMTGKeV)
settings.geometry = diffcalc.hkl.you.geometry.FourCircle()  # @UndefinedVariable
Esempio n. 28
0
        `%nbdev_show_doc name_1, name_2, title_level=3`.
    To show doc for a class and some of its members and specify class level:
        `%nbdev_show_doc MyClass . __init__, my_method, default_cls_level=3`
    To show doc for a class and all of its "public" members:
        `%nbdev_show_doc MyClass *`"""
    names, wild_names, kwargs = parse_nbdev_show_doc(line, local_ns)
    for k,v in kwargs.items():
        if not 1 <= v <= 6:
            print(f'UsageError: Invalid {k} "{v}". Usage `%nbdev_show_doc name_1 {k}=[int between 1 and 6]`')
    if not names:
        print(f'UsageError: List of names is missing. Usage `%nbdev_show_doc name_1, name_2`')
    for name in names: show_doc(eval(name,local_ns), name=name, **kwargs)

if IN_IPYTHON:
    from IPython.core.magic import register_line_magic, needs_local_scope
    register_line_magic(needs_local_scope(nbdev_show_doc))

# Cell
def md2html(md):
    "Convert markdown `md` to HTML code"
    import nbconvert
    if nbconvert.__version__ < '5.5.0': return HTMLExporter().markdown2html(md)
    else: return HTMLExporter().markdown2html(collections.defaultdict(lambda: collections.defaultdict(dict)), md)

# Cell
def get_doc_link(func):
    mod = inspect.getmodule(func)
    module = mod.__name__.replace('.', '/') + '.py'
    try:
        nbdev_mod = importlib.import_module(mod.__package__.split('.')[0] + '._nbdev')
        try_pack = source_nb(func, mod=nbdev_mod)
Esempio n. 29
0
def load_ipython_extension(ipython):
    magic.register_line_magic(nose)
Esempio n. 30
0
def nbdev_add2all(line, local_ns):
    """To add something to `__all__` if it's not picked automatically,
    write an exported cell with something like: `%nbdev_add2all name_1, name_2 ...`"""
    if line.strip() == '':
        print(f'UsageError: List of names is missing. Usage `%nbdev_add2all name_1, name_2`')
        return
    try: [eval(s, local_ns) for s in parse_line(line)]
    except Exception as ex: print(f'UsageError: {ex}')

def _new_test_flag_fn(flag):
    "Create a new test flag function and magic"
    # don't create "empty" test flags if tst_flags is not set, set to whitespace, has trailing | etc
    if not flag.strip(): return
    def _(line): _validate_param(line, f'nbdev_{flag}_test', fixed_value='all')
    _.__doc__ = f"""Put an `%nbdev_{flag}_test` magic on each "{flag}" test cell that you do not want to be run by default.
    To apply this flag to all tests in a notebook, one cell should contain: `%nbdev_{flag}_test all`
    These tests can be executed with the command line tool: `nbdev_test_nbs --flags {flag}`'."""
    register_line_magic(f'nbdev_{flag}_test')(_)

if IN_IPYTHON:
    from IPython.core.magic import register_line_magic, needs_local_scope
    fns = [nbdev_default_export, nbdev_export, nbdev_export_and_show, nbdev_export_internal,
           nbdev_hide, nbdev_hide_input, nbdev_hide_output, nbdev_default_class_level,
           nbdev_collapse_input, nbdev_collapse_output, needs_local_scope(nbdev_add2all)]
    for fn in fns: register_line_magic(fn)
    try: 
        for flag in Config().get('tst_flags', '').split('|'): _new_test_flag_fn(flag)
    except: pass # do not fail if we can't find config

def load_ipython_extension(ipython):
    magic.register_line_magic(nose)
Esempio n. 32
0
        from IPython.utils.process import arg_split

        args = arg_split(line)

        path = os.path.abspath(args[0])
        args = args[1:]
        if not os.path.isfile(path):
            from IPython.core.error import UsageError

            raise UsageError("%%pudb: file %s does not exist" % path)

        from pudb import runscript

        runscript(path, args)

    register_line_magic(pudb)

    def debugger(self, force=False):
        """
        Call the PuDB debugger
        """
        from IPython.utils.warn import error

        if not (force or self.call_pdb):
            return

        if not hasattr(sys, "last_traceback"):
            error("No traceback has been produced, nothing to debug.")
            return

        from pudb import pm
Esempio n. 33
0
            print(pudb.__doc__)
            return

        from IPython.utils.process import arg_split
        args = arg_split(line)

        path = os.path.abspath(args[0])
        args = args[1:]
        if not os.path.isfile(path):
            from IPython.core.error import UsageError
            raise UsageError("%%pudb: file %s does not exist" % path)

        from pudb import runscript
        runscript(path, args)

    register_line_magic(pudb)

    def debugger(self, force=False):
        """
        Call the PuDB debugger
        """
        from IPython.utils.warn import error
        if not (force or self.call_pdb):
            return

        if not hasattr(sys, 'last_traceback'):
            error('No traceback has been produced, nothing to debug.')
            return

        from pudb import pm
Esempio n. 34
0
    if args and args[-1].endswith('.pdf'):
        pdf = args[-1]
    else:
        pdf = None

    verbose = '-v' in args
    if '-l' in args:
        pdf_from_latex(pdf, verbose)
    else:
        pdf_from_html(pdf, verbose)


# this is hackery so that CI works.
# it is an error to do this when there is not IPython
try:
    pdf = register_line_magic(pdf)
except:
    pass
##################################################################
# File utilities
##################################################################


def fid_from_url(url):
    '''Return a file ID for a file on GDrive from its url.'''
    u = urlparse(url)

    # This is a typical sharing link
    # https://drive.google.com/file/d/1q_qE9RGdfV_8Vv3zuApf-LqXBwqo8HO2/view?usp=sharing
    if (u.netloc == 'drive.google.com') and (u.path.startswith('/file/d/')):
        return u.path.split('/')[3]
Esempio n. 35
0
    def _make_line_magic(self):
        print_ = print  # to keep the test from failing since this is a legitimate print
        line_magic_names = [
            f[0] for f in inspect.getmembers(line_magics)
            if inspect.isfunction(f[1])
        ]

        def _handle(cmd, line):
            if cmd in ("deps", "show_deps", "show_dependency",
                       "show_dependencies"):
                return line_magics.show_deps(line)
            elif cmd in ("stale", "show_stale"):
                return line_magics.show_stale(line)
            elif cmd == "trace_messages":
                return line_magics.trace_messages(line)
            elif cmd in ("hls", "nohls", "highlight", "highlights"):
                return line_magics.set_highlights(cmd, line)
            elif cmd in ("dag", "make_dag", "cell_dag", "make_cell_dag"):
                return json.dumps(self.create_dag_metadata(), indent=2)
            elif cmd in ("slice", "make_slice", "gather_slice"):
                return line_magics.make_slice(line)
            elif cmd in ("mode", "exec_mode"):
                return line_magics.set_exec_mode(line)
            elif cmd in ("schedule", "exec_schedule", "execution_schedule"):
                return line_magics.set_exec_schedule(line)
            elif cmd in ("flow", "flow_order", "semantics", "flow_semantics"):
                return line_magics.set_flow_order(line)
            elif cmd == "clear":
                self.min_timestamp = self.cell_counter()
                return None
            elif cmd in line_magic_names:
                logger.warning(
                    "We have a magic for %s, but have not yet registered it",
                    cmd)
                return None
            else:
                logger.warning(line_magics.USAGE)
                return None

        def _safety(line: str):
            # this is to avoid capturing `self` and creating an extra reference to the singleton
            try:
                cmd, line = line.split(" ", 1)
                if cmd in ("slice", "make_slice", "gather_slice"):
                    # FIXME: hack to workaround some input transformer
                    line = re.sub(r"--tag +<class '(\w+)'>", r"--tag $\1",
                                  line)
            except ValueError:
                cmd, line = line, ""
            try:
                line, fname = line.split(">", 1)
            except ValueError:
                line, fname = line, None
            line = line.strip()
            if fname is not None:
                fname = fname.strip()

            outstr = _handle(cmd, line)
            if outstr is None:
                return

            if fname is None:
                print_(outstr)
            else:
                with open(fname, "w") as f:
                    f.write(outstr)

        # FIXME (smacke): probably not a great idea to rely on this
        _safety.__name__ = _SAFETY_LINE_MAGIC
        return register_line_magic(_safety)
Esempio n. 36
0
def load_ipython_extension(ipython):
    from IPython.core.magic import register_line_magic
    register_line_magic(nose)
Esempio n. 37
0
    from gda.jython.commands.GeneralCommands import alias  # @UnresolvedImport
    alias("usem5tth")
    alias("uselowq")
    alias("usehighq")
    alias("usedifftth")
    alias("usem5tth_tp")
    alias("uselowq_tp")
    alias("usehighq_tp")
    alias("usedifftth_tp")
    alias("usesim")
else:
    from IPython.core.magic import register_line_magic  # @UnresolvedImport
    from diffcmd.ipython import parse_line
    if IPYTHON:
        from IPython import get_ipython  # @UnresolvedImport @UnusedImport
        register_line_magic(parse_line(usem5tth, globals()))
        del usem5tth
        register_line_magic(parse_line(uselowq, globals()))
        del uselowq
        register_line_magic(parse_line(usehighq, globals()))
        del usehighq
        register_line_magic(parse_line(usedifftth, globals()))
        del usedifftth
        register_line_magic(parse_line(usem5tth_tp, globals()))
        del usem5tth_tp
        register_line_magic(parse_line(uselowq_tp, globals()))
        del uselowq_tp
        register_line_magic(parse_line(usehighq_tp, globals()))
        del usehighq_tp
        register_line_magic(parse_line(usedifftth_tp, globals()))
        del usedifftth_tp