create kernel manager from IPKernelApp string
    such as '--shell=47378 --iopub=39859 --stdin=36778 --hb=52668' for IPython 0.11
    or just 'kernel-12345.json' for IPython 0.12
351161
def km_from_string(s=''):
    
    try:
        import IPython
    except ImportError:
        raise ImportError("Could not find IPython. " + _install_instructions)
    # Modified by BoPeng
    #
    #from IPython.config.loader import KeyValueConfigLoader
    from traitlets.config.loader import KeyValueConfigLoader
    try:
        # Updated by Bo Peng for module names
        from jupyter_client.manager import  KernelManager
        from jupyter_client import find_connection_file
    except ImportError:
        #  IPython < 1.0
        from IPython.zmq.blockingkernelmanager import BlockingKernelManager as KernelManager
        from IPython.zmq.kernelapp import kernel_aliases
        try:
            from IPython.lib.kernel import find_connection_file
        except ImportError:
            # < 0.12, no find_connection_file
            pass

    global km, kc, send

    s = s.replace('--existing', '')
    if 'connection_file' in KernelManager.class_trait_names():
        # 0.12 uses files instead of a collection of ports
        # include default IPython search path
        # filefind also allows for absolute paths, in which case the search
        # is ignored
        try:
            # XXX: the following approach will be brittle, depending on what
            # connection strings will end up looking like in the future, and
            # whether or not they are allowed to have spaces. I'll have to sync
            # up with the IPython team to address these issues -pi
            if '--profile' in s:
                k,p = s.split('--profile')
                k = k.lstrip().rstrip() # kernel part of the string
                p = p.lstrip().rstrip() # profile part of the string
                fullpath = find_connection_file(k,p)
            else:
                fullpath = find_connection_file(s.lstrip().rstrip())
        except IOError as e:
            echo(":IPython " + s + " failed", "Info")
            echo("^-- failed '" + s + "' not found", "Error")
            return
        km = KernelManager(connection_file = fullpath)
        km.load_connection_file()
    else:
        if s == '':
            echo(":IPython 0.11 requires the full connection string")
            return
        loader = KeyValueConfigLoader(s.split(), aliases=kernel_aliases)
        cfg = loader.load_config()['KernelApp']
        try:
            km = KernelManager(
                shell_address=(ip, cfg['shell_port']),
                sub_address=(ip, cfg['iopub_port']),
                stdin_address=(ip, cfg['stdin_port']),
                hb_address=(ip, cfg['hb_port']))
        except KeyError as e:
            echo(":IPython " +s + " failed", "Info")
            echo("^-- failed --"+e.message.replace('_port','')+" not specified", "Error")
            return

    try:
        kc = km.client()
    except AttributeError:
        # 0.13
        kc = km
    kc.start_channels()

    try:
        send = kc.execute
    except AttributeError:
        # < 3.0
        send = kc.shell_channel.execute

    #XXX: backwards compatibility for IPython < 0.13
    try:
        import inspect
        sc = kc.shell_channel
        num_oinfo_args = len(inspect.getargspec(sc.object_info).args)
        if num_oinfo_args == 2:
            # patch the object_info method which used to only take one argument
            klass = sc.__class__
            klass._oinfo_orig = klass.object_info
            klass.object_info = lambda s,x,y: s._oinfo_orig(x)
    except Exception:
        pass

    #XXX: backwards compatibility for IPython < 1.0
    if not hasattr(kc, 'iopub_channel'):
        kc.iopub_channel = kc.sub_channel

    # now that we're connect to an ipython kernel, activate completion
    # machinery, but do so only for the local buffer if the user added the
    # following line the vimrc:
    #   let g:ipy_completefunc = 'local'
    vim.command("""
        if g:ipy_completefunc == 'global'
            set completefunc=CompleteIPython
        elseif g:ipy_completefunc == 'local'
            setl completefunc=CompleteIPython
        endif
        """)
    # also activate GUI doc balloons if in gvim
    vim.command("""
        if has('balloon_eval')
            set bexpr=IPythonBalloonExpr()
        endif
        """)
    set_pid()
    return km
722906
def _ppid():
    '''
    
    '''
    ret = {}
    if __grains__['kernel'] == 'SunOS':
        cmd = 'ps -a -o pid,ppid | tail +2'
    else:
        cmd = 'ps -ax -o pid,ppid | tail -n+2'
    out = __salt__['cmd.run'](cmd, python_shell=True)
    for line in out.splitlines():
        pid, ppid = line.split()
        ret[pid] = ppid
    return ret
658690
def _hw_addr_aix(iface):
    '''
    
    '''
    cmd = subprocess.Popen(
        'entstat -d {0} | grep \'Hardware Address\''.format(iface),
        shell=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT).communicate()[0]

    if cmd:
        comps = cmd.split(' ')
        if len(comps) == 3:
            mac_addr = comps[2].strip('\'').strip()
            return mac_addr

    error_msg = ('Interface "{0}" either not available or does not contain a hardware address'.format(iface))
    log.error(error_msg)
    return error_msg
1131950
def _parse_zebra_family_prefix(buf):
    
    (family,) = struct.unpack_from(_ZEBRA_FAMILY_FMT, buf)
    rest = buf[_ZEBRA_FAMILY_SIZE:]

    if socket.AF_INET == family:
        (prefix, p_len) = struct.unpack_from(_ZEBRA_IPV4_PREFIX_FMT, rest)
        prefix = '%s/%d' % (addrconv.ipv4.bin_to_text(prefix), p_len)
        rest = rest[_ZEBRA_IPV4_PREFIX_SIZE:]
    elif socket.AF_INET6 == family:
        (prefix, p_len) = struct.unpack_from(_ZEBRA_IPV6_PREFIX_FMT, rest)
        prefix = '%s/%d' % (addrconv.ipv6.bin_to_text(prefix), p_len)
        rest = rest[_ZEBRA_IPV6_PREFIX_SIZE:]
    else:
        raise struct.error('Unsupported family: %d' % family)

    return family, prefix, rest
518043
def get_kernel_data(self):
        """"""
        return {
            'nmsimplex_scratch': LocalMemory(
                'mot_float_type', self._nmr_parameters * 2 + (self._nmr_parameters + 1) ** 2 + 1),
            'initial_simplex_scale': LocalMemory('mot_float_type', self._nmr_parameters)
        }
987573
def i2m(self, pkt, i):
        """""""  # noqa: E501
        mask, ip = i
        ip = pton_ntop.inet_pton(socket.AF_INET6, ip)
        return struct.pack(">B", mask) + ip[:self.mask2iplen(mask)]
599214
def _string_from_ip_int(self, ip_int):
        
        octets = []
        for _ in xrange(4):
            octets.insert(0, str(ip_int & 0xFF))
            ip_int >>= 8
        return '.'.join(octets)
124642
def create_kernel_spec(self, is_cython=False,
                           is_pylab=False, is_sympy=False):
        """"""
        # Before creating our kernel spec, we always need to
        # set this value in spyder.ini
        CONF.set('main', 'spyder_pythonpath',
                 self.main.get_spyder_pythonpath())
        return SpyderKernelSpec(is_cython=is_cython,
                                is_pylab=is_pylab,
                                is_sympy=is_sympy)
335688
def connect_external_kernel(self, shellwidget):
        
        sw = shellwidget
        kc = shellwidget.kernel_client
        if self.main.help is not None:
            self.main.help.set_shell(sw)
        if self.main.variableexplorer is not None:
            self.main.variableexplorer.add_shellwidget(sw)
            sw.set_namespace_view_settings()
            sw.refresh_namespacebrowser()
            kc.stopped_channels.connect(lambda :
                self.main.variableexplorer.remove_shellwidget(id(sw)))
764696
def kernel_version(self):
        
        result = self.shell.execute(self.commands.kernel_version.value)
        stdout = self.shell.decode(result['stdout'])
        stderr = self.shell.decode(result['stderr'])
        return stdout
161293
def set_pid():
    
    global pid
    lines = '\n'.join(['import os', '_pid = os.getpid()'])

    try:
        msg_id = send(lines, silent=True, user_variables=['_pid'])
    except TypeError: # change in IPython 3.0+
        msg_id = send(lines, silent=True, user_expressions={'_pid':'_pid'})

    # wait to get message back from kernel
    try:
        child = get_child_msg(msg_id)
    except Empty:
        echo("no reply from IPython kernel")
        return
    try:
        pid = int(child['content']['user_variables']['_pid'])
    except TypeError: # change in IPython 1.0.dev moved this out
        pid = int(child['content']['user_variables']['_pid']['data']['text/plain'])
    except KeyError:    # change in IPython 3.0+
        pid = int(
            child['content']['user_expressions']['_pid']['data']['text/plain'])
    except KeyError: # change in IPython 1.0.dev moved this out
        echo("Could not get PID information, kernel not running Python?")
    return pid
896602
def find_kernel_specs(self):
        """"""
        # let real installed kernels overwrite envs with the same name:
        # this is the same order as the get_kernel_spec way, which also prefers
        # kernels from the jupyter dir over env kernels.
        specs = self.find_kernel_specs_for_envs()
        specs.update(super(EnvironmentKernelSpecManager,
                           self).find_kernel_specs())
        return specs
915962
def get_kernel_id(self):
        
        sessions_url = self.get_session_url()
        sessions_req = requests.get(sessions_url).content.decode()
        sessions = json.loads(sessions_req)

        if os.name == 'nt':
            path = self.path.replace('\\', '/')
        else:
            path = self.path

        for session in sessions:
            notebook_path = session.get('notebook', {}).get('path')
            if notebook_path is not None and notebook_path == path:
                kernel_id = session['kernel']['id']
                return kernel_id
322463
def _yum_pkginfo(output):
    '''
    
    '''
    cur = {}
    keys = itertools.cycle(('name', 'version', 'repoid'))
    values = salt.utils.itertools.split(_strip_headers(output))
    osarch = __grains__['osarch']
    for (key, value) in zip(keys, values):
        if key == 'name':
            try:
                cur['name'], cur['arch'] = value.rsplit('.', 1)
            except ValueError:
                cur['name'] = value
                cur['arch'] = osarch
            cur['name'] = salt.utils.pkg.rpm.resolve_name(cur['name'],
                                                          cur['arch'],
                                                          osarch)
        else:
            if key == 'version':
                # Suppport packages with no 'Release' parameter
                value = value.rstrip('-')
            elif key == 'repoid':
                # Installed packages show a '@' at the beginning
                value = value.lstrip('@')
            cur[key] = value
            if key == 'repoid':
                # We're done with this package, create the pkginfo namedtuple
                pkginfo = salt.utils.pkg.rpm.pkginfo(**cur)
                # Clear the dict for the next package
                cur = {}
                # Yield the namedtuple
                if pkginfo is not None:
                    yield pkginfo
289218
def create_ipam_config(*pools, **kwargs):
    '''
    
    '''
    kwargs = salt.utils.args.clean_kwargs(**kwargs)

    try:
        # docker-py 2.0 and newer
        pool_args = salt.utils.args.get_function_argspec(
            docker.types.IPAMPool.__init__).args
        create_pool = docker.types.IPAMPool
        create_config = docker.types.IPAMConfig
    except AttributeError:
        # docker-py < 2.0
        pool_args = salt.utils.args.get_function_argspec(
            docker.utils.create_ipam_pool).args
        create_pool = docker.utils.create_ipam_pool
        create_config = docker.utils.create_ipam_config

    for primary_key, alias_key in (('driver', 'ipam_driver'),
                                   ('options', 'ipam_opts')):

        if alias_key in kwargs:
            alias_val = kwargs.pop(alias_key)
            if primary_key in kwargs:
                log.warning(
                    'docker.create_ipam_config: Both \'%s\' and \'%s\' '
                    'passed. Ignoring \'%s\'',
                    alias_key, primary_key, alias_key
                )
            else:
                kwargs[primary_key] = alias_val

    if salt.utils.data.is_dictlist(kwargs.get('options')):
        kwargs['options'] = salt.utils.data.repack_dictlist(kwargs['options'])

    # Get all of the IPAM pool args that were passed as individual kwargs
    # instead of in the *pools tuple
    pool_kwargs = {}
    for key in list(kwargs):
        if key in pool_args:
            pool_kwargs[key] = kwargs.pop(key)

    pool_configs = []
    if pool_kwargs:
        pool_configs.append(create_pool(**pool_kwargs))
    pool_configs.extend([create_pool(**pool) for pool in pools])

    if pool_configs:
        # Sanity check the IPAM pools. docker-py's type/function for creating
        # an IPAM pool will allow you to create a pool with a gateway, IP
        # range, or map of aux addresses, even when no subnet is passed.
        # However, attempting to use this IPAM pool when creating the network
        # will cause the Docker Engine to throw an error.
        if any('Subnet' not in pool for pool in pool_configs):
            raise SaltInvocationError('A subnet is required in each IPAM pool')
        else:
            kwargs['pool_configs'] = pool_configs

    ret = create_config(**kwargs)
    pool_dicts = ret.get('Config')
    if pool_dicts:
        # When you inspect a network with custom IPAM configuration, only
        # arguments which were explictly passed are reflected. By contrast,
        # docker-py will include keys for arguments which were not passed in
        # but set the value to None. Thus, for ease of comparison, the below
        # loop will remove all keys with a value of None from the generated
        # pool configs.
        for idx, _ in enumerate(pool_dicts):
            for key in list(pool_dicts[idx]):
                if pool_dicts[idx][key] is None:
                    del pool_dicts[idx][key]

    return ret
1119941
def start_new_kernel(startup_timeout=60, kernel_name='python', **kwargs):
    """"""
    logger.debug('Starting new kernel: "%s"' % kernel_name)
    km = KernelManager(kernel_name=kernel_name,
                       kernel_spec_manager=NbvalKernelspecManager())
    km.start_kernel(**kwargs)
    kc = km.client()
    kc.start_channels()
    try:
        kc.wait_for_ready(timeout=startup_timeout)
    except RuntimeError:
        logger.exception('Failure starting kernel "%s"', kernel_name)
        kc.stop_channels()
        km.shutdown_kernel()
        raise

    return km, kc
335400
def _build_kernel(self, kernel_source, compile_flags=()):
        
        return cl.Program(self._cl_context, kernel_source).build(' '.join(compile_flags))