jiahuimbzuai/CoQuIR huggingface dataset:
// _ensure_vdisk_no_fc_mappings [python]
    def _ensure_vdisk_no_fc_mappings(self, name, allow_snaps=True):
        # Ensure vdisk has no FlashCopy mappings
        mapping_ids = self._get_vdisk_fc_mappings(name)
        while len(mapping_ids):
            wait_for_copy = False
            for map_id in mapping_ids:
                attrs = self._get_flashcopy_mapping_attributes(map_id)
                if not attrs:
                    continue
                source = attrs['source_vdisk_name']
                target = attrs['target_vdisk_name']
                copy_rate = attrs['copy_rate']
                status = attrs['status']

                if copy_rate == '0':
                    # Case #2: A vdisk that has snapshots
                    if source == name:
                        if not allow_snaps:
                            return False
                        ssh_cmd = ('svctask chfcmap -copyrate 50 '
                                   '-autodelete on %s' % map_id)
                        out, err = self._run_ssh(ssh_cmd)
                        wait_for_copy = True
                    # Case #3: A snapshot
                    else:
                        msg = (_('Vdisk %(name)s not involved in '
                                 'mapping %(src)s -> %(tgt)s') %
                               {'name': name, 'src': source, 'tgt': target})
                        self._driver_assert(target == name, msg)
                        if status in ['copying', 'prepared']:
                            self._run_ssh('svctask stopfcmap %s' % map_id)
                        elif status in ['stopping', 'preparing']:
                            wait_for_copy = True
                        else:
                            self._run_ssh('svctask rmfcmap -force %s' % map_id)
                # Case 4: Copy in progress - wait and will autodelete
                else:
                    if status == 'prepared':
                        self._run_ssh('svctask stopfcmap %s' % map_id)
                        self._run_ssh('svctask rmfcmap -force %s' % map_id)
                    elif status == 'idle_or_copied':
                        # Prepare failed
                        self._run_ssh('svctask rmfcmap -force %s' % map_id)
                    else:
                        wait_for_copy = True
            if wait_for_copy:
                time.sleep(5)
            mapping_ids = self._get_vdisk_fc_mappings(name)
        return True
// tcp_forward [python]
    def tcp_forward(self, host_port, device_port):
        """Starts tcp forwarding.

        Args:
            host_port: Port number to use on the computer.
            device_port: Port number to use on the android device.
        """
        self.forward(['tcp:%d' % host_port, 'tcp:%d' % device_port])
// tcp_forward [python]
    def tcp_forward(self, host_port, device_port):
        """Starts tcp forwarding.

        Args:
            host_port: Port number to use on the computer.
            device_port: Port number to use on the android device.
        """
        self.forward('tcp:%d tcp:%d' % (host_port, device_port))
// repack [python]
def repack(host, targets, channel='stable'):
  print("Repacking rust for %s..." % host)
  url = 'https://static.rust-lang.org/dist/channel-rust-' + channel + '.toml'
  req = requests.get(url)
  req.raise_for_status()
  manifest = toml.loads(req.content)
  if manifest['manifest-version'] != '2':
    print('ERROR: unrecognized manifest version %s.' % manifest['manifest-version'])
    return
  print('Using manifest for rust %s as of %s.' % (channel, manifest['date']))
  rustc_version, rustc = package(manifest, 'rustc', host)
  if rustc['available']:
    print('rustc %s\n  %s\n  %s' % (rustc_version, rustc['url'], rustc['hash']))
    fetch(rustc['url'])
  cargo_version, cargo = package(manifest, 'cargo', host)
  if cargo['available']:
    print('cargo %s\n  %s\n  %s' % (cargo_version, cargo['url'], cargo['hash']))
    fetch(cargo['url'])
  stds = []
  for target in targets:
      version, info = package(manifest, 'rust-std', target)
      if info['available']:
        print('rust-std %s\n  %s\n  %s' % (version, info['url'], info['hash']))
        fetch(info['url'])
        stds.append(info)
  print('Installing packages...')
  tar_basename = 'rustc-%s-repack' % host
  install_dir = 'rustc'
  subprocess.check_call(['rm', '-rf', install_dir])
  install(os.path.basename(rustc['url']), install_dir)
  install(os.path.basename(cargo['url']), install_dir)
  for std in stds:
    install(os.path.basename(std['url']), install_dir)
  print('Tarring %s...' % tar_basename)
  subprocess.check_call(['tar', 'cjf', tar_basename + '.tar.bz2', install_dir])
  subprocess.check_call(['rm', '-rf', install_dir])
// repack [python]
def repack(host, targets, channel='stable'):
  url = 'https://static.rust-lang.org/dist/channel-rust-' + channel + '.toml'
  req = requests.get(url)
  req.raise_for_status()
  manifest = toml.loads(req.content)
  if manifest['manifest-version'] != '2':
    print('ERROR: unrecognized manifest version %s.' % manifest['manifest-version'])
    return
  print('Using manifest for rust %s as of %s.' % (channel, manifest['date']))
  rustc_version, rustc = package(manifest, 'rustc', host)
  if rustc['available']:
    print('rustc %s\n  %s\n  %s' % (rustc_version, rustc['url'], rustc['hash']))
    fetch(rustc['url'])
  cargo_version, cargo = package(manifest, 'cargo', host)
  if cargo['available']:
    print('cargo %s\n  %s\n  %s' % (cargo_version, cargo['url'], cargo['hash']))
    fetch(cargo['url'])
  stds = []
  for target in targets:
      version, info = package(manifest, 'rust-std', target)
      if info['available']:
        print('rust-std %s\n  %s\n  %s' % (version, info['url'], info['hash']))
        fetch(info['url'])
        stds.append(info)
  print('Installing packages...')
  tar_basename = 'rustc-%s-repack' % host
  install_dir = 'rustc'
  os.system('rm -rf %s' % install_dir)
  install(os.path.basename(rustc['url']), install_dir)
  install(os.path.basename(cargo['url']), install_dir)
  for std in stds:
    install(os.path.basename(std['url']), install_dir)
  print('Tarring %s...' % tar_basename)
  os.system('tar cjf %s.tar.bz2 %s/*' % (tar_basename, install_dir))
  os.system('rm -rf %s' % install_dir)
// extend_volume [python]
    def extend_volume(self, volume, new_size):
        volume_name = self._get_3par_vol_name(volume['id'])
        old_size = volume.size
        growth_size = int(new_size) - old_size
        LOG.debug("Extending Volume %s from %s to %s, by %s GB." %
                  (volume_name, old_size, new_size, growth_size))
        try:
            self._cli_run(['growvv', '-f', volume_name, '%dg' % growth_size])
        except Exception:
            with excutils.save_and_reraise_exception():
                LOG.error(_("Error extending volume %s") % volume)
// extend_volume [python]
    def extend_volume(self, volume, new_size):
        volume_name = self._get_3par_vol_name(volume['id'])
        old_size = volume.size
        growth_size = int(new_size) - old_size
        LOG.debug("Extending Volume %s from %s to %s, by %s GB." %
                  (volume_name, old_size, new_size, growth_size))
        try:
            self._cli_run("growvv -f %s %sg" % (volume_name, growth_size),
                          None)
        except Exception:
            with excutils.save_and_reraise_exception():
                LOG.error(_("Error extending volume %s") % volume)
// _remove_volume_set [python]
    def _remove_volume_set(self, vvs_name):
        # Must first clear the QoS rules before removing the volume set
        self._cli_run(['setqos', '-clear', 'vvset:%s' % (vvs_name)])
        self._cli_run(['removevvset', '-f', vvs_name])
// _remove_volume_set [python]
    def _remove_volume_set(self, vvs_name):
        # Must first clear the QoS rules before removing the volume set
        self._cli_run('setqos -clear vvset:%s' % (vvs_name), None)
        self._cli_run('removevvset -f %s' % (vvs_name), None)
// _get_3par_hostname_from_wwn_iqn [python]
    def _get_3par_hostname_from_wwn_iqn(self, wwns_iqn):
        out = self._cli_run(['showhost', '-d'])
        # wwns_iqn may be a list of strings or a single
        # string. So, if necessary, create a list to loop.
        if not isinstance(wwns_iqn, list):
            wwn_iqn_list = [wwns_iqn]
        else:
            wwn_iqn_list = wwns_iqn

        for wwn_iqn in wwn_iqn_list:
            for showhost in out:
                if (wwn_iqn.upper() in showhost.upper()):
                    return showhost.split(',')[1]
// _get_3par_hostname_from_wwn_iqn [python]
    def _get_3par_hostname_from_wwn_iqn(self, wwns_iqn):
        out = self._cli_run('showhost -d', None)
        # wwns_iqn may be a list of strings or a single
        # string. So, if necessary, create a list to loop.
        if not isinstance(wwns_iqn, list):
            wwn_iqn_list = [wwns_iqn]
        else:
            wwn_iqn_list = wwns_iqn

        for wwn_iqn in wwn_iqn_list:
            for showhost in out:
                if (wwn_iqn.upper() in showhost.upper()):
                    return showhost.split(',')[1]
// get_ports [python]
    def get_ports(self):
        # First get the active FC ports
        out = self._cli_run(['showport'])

        # strip out header
        # N:S:P,Mode,State,----Node_WWN----,-Port_WWN/HW_Addr-,Type,
        # Protocol,Label,Partner,FailoverState
        out = out[1:len(out) - 2]

        ports = {'FC': [], 'iSCSI': {}}
        for line in out:
            tmp = line.split(',')

            if tmp:
                if tmp[1] == 'target' and tmp[2] == 'ready':
                    if tmp[6] == 'FC':
                        ports['FC'].append(tmp[4])

        # now get the active iSCSI ports
        out = self._cli_run(['showport', '-iscsi'])

        # strip out header
        # N:S:P,State,IPAddr,Netmask,Gateway,
        # TPGT,MTU,Rate,DHCP,iSNS_Addr,iSNS_Port
        out = out[1:len(out) - 2]
        for line in out:
            tmp = line.split(',')

            if tmp and len(tmp) > 2:
                if tmp[1] == 'ready':
                    ports['iSCSI'][tmp[2]] = {}

        # now get the nsp and iqn
        result = self._cli_run(['showport', '-iscsiname'])
        if result:
            # first line is header
            # nsp, ip,iqn
            result = result[1:]
            for line in result:
                info = line.split(",")
                if info and len(info) > 2:
                    if info[1] in ports['iSCSI']:
                        nsp = info[0]
                        ip_addr = info[1]
                        iqn = info[2]
                        ports['iSCSI'][ip_addr] = {'nsp': nsp,
                                                   'iqn': iqn
                                                   }

        LOG.debug("PORTS = %s" % pprint.pformat(ports))
        return ports
// get_ports [python]
    def get_ports(self):
        # First get the active FC ports
        out = self._cli_run('showport', None)

        # strip out header
        # N:S:P,Mode,State,----Node_WWN----,-Port_WWN/HW_Addr-,Type,
        # Protocol,Label,Partner,FailoverState
        out = out[1:len(out) - 2]

        ports = {'FC': [], 'iSCSI': {}}
        for line in out:
            tmp = line.split(',')

            if tmp:
                if tmp[1] == 'target' and tmp[2] == 'ready':
                    if tmp[6] == 'FC':
                        ports['FC'].append(tmp[4])

        # now get the active iSCSI ports
        out = self._cli_run('showport -iscsi', None)

        # strip out header
        # N:S:P,State,IPAddr,Netmask,Gateway,
        # TPGT,MTU,Rate,DHCP,iSNS_Addr,iSNS_Port
        out = out[1:len(out) - 2]
        for line in out:
            tmp = line.split(',')

            if tmp and len(tmp) > 2:
                if tmp[1] == 'ready':
                    ports['iSCSI'][tmp[2]] = {}

        # now get the nsp and iqn
        result = self._cli_run('showport -iscsiname', None)
        if result:
            # first line is header
            # nsp, ip,iqn
            result = result[1:]
            for line in result:
                info = line.split(",")
                if info and len(info) > 2:
                    if info[1] in ports['iSCSI']:
                        nsp = info[0]
                        ip_addr = info[1]
                        iqn = info[2]
                        ports['iSCSI'][ip_addr] = {'nsp': nsp,
                                                   'iqn': iqn
                                                   }

        LOG.debug("PORTS = %s" % pprint.pformat(ports))
        return ports
// test_get_least_used_nsp [python]
    def test_get_least_used_nsp(self):
        self.flags(lock_path=self.tempdir)

        #record
        self.clear_mox()
        _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)
        self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "_run_ssh", _run_ssh)

        show_vlun_cmd = ['showvlun', '-a', '-showcols', 'Port']
        _run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN_NONE), ''])
        _run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN_NONE), ''])
        _run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN_NONE), ''])

        self.mox.ReplayAll()
        # in use count                           11       12
        nsp = self.driver._get_least_used_nsp(['0:2:1', '1:8:1'])
        self.assertEqual(nsp, '0:2:1')

        # in use count                            11       10
        nsp = self.driver._get_least_used_nsp(['0:2:1', '1:2:1'])
        self.assertEqual(nsp, '1:2:1')

        # in use count                            0       10
        nsp = self.driver._get_least_used_nsp(['1:1:1', '1:2:1'])
        self.assertEqual(nsp, '1:1:1')
// test_get_least_used_nsp [python]
    def test_get_least_used_nsp(self):
        self.flags(lock_path=self.tempdir)

        #record
        self.clear_mox()
        _run_ssh = self.mox.CreateMock(hpdriver.hpcommon.HP3PARCommon._run_ssh)
        self.stubs.Set(hpdriver.hpcommon.HP3PARCommon, "_run_ssh", _run_ssh)

        show_vlun_cmd = 'showvlun -a -showcols Port'
        _run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN_NONE), ''])
        _run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN_NONE), ''])
        _run_ssh(show_vlun_cmd, False).AndReturn([pack(SHOW_VLUN_NONE), ''])

        self.mox.ReplayAll()
        # in use count                           11       12
        nsp = self.driver._get_least_used_nsp(['0:2:1', '1:8:1'])
        self.assertEqual(nsp, '0:2:1')

        # in use count                            11       10
        nsp = self.driver._get_least_used_nsp(['0:2:1', '1:2:1'])
        self.assertEqual(nsp, '1:2:1')

        # in use count                            0       10
        nsp = self.driver._get_least_used_nsp(['1:1:1', '1:2:1'])
        self.assertEqual(nsp, '1:1:1')
// _cmd_to_dict [python]
    def _cmd_to_dict(self, arg_list):
        no_param_args = [
            'autodelete',
            'autoexpand',
            'bytes',
            'compressed',
            'force',
            'nohdr',
        ]
        one_param_args = [
            'chapsecret',
            'cleanrate',
            'copyrate',
            'delim',
            'filtervalue',
            'grainsize',
            'hbawwpn',
            'host',
            'iogrp',
            'iscsiname',
            'mdiskgrp',
            'name',
            'rsize',
            'scsi',
            'size',
            'source',
            'target',
            'unit',
            'easytier',
            'warning',
            'wwpn',
        ]

        # Handle the special case of lsnode which is a two-word command
        # Use the one word version of the command internally
        if arg_list[0] in ('svcinfo', 'svctask'):
            if arg_list[1] == 'lsnode':
                if len(arg_list) > 4:  # e.g. svcinfo lsnode -delim ! <node id>
                    ret = {'cmd': 'lsnode', 'node_id': arg_list[-1]}
                else:
                    ret = {'cmd': 'lsnodecanister'}
            else:
                ret = {'cmd': arg_list[1]}
            arg_list.pop(0)
        else:
            ret = {'cmd': arg_list[0]}

        skip = False
        for i in range(1, len(arg_list)):
            if skip:
                skip = False
                continue
            if arg_list[i][0] == '-':
                if arg_list[i][1:] in no_param_args:
                    ret[arg_list[i][1:]] = True
                elif arg_list[i][1:] in one_param_args:
                    ret[arg_list[i][1:]] = arg_list[i + 1]
                    skip = True
                else:
                    raise exception.InvalidInput(
                        reason=_('unrecognized argument %s') % arg_list[i])
            else:
                ret['obj'] = arg_list[i]
        return ret
// _cmd_to_dict [python]
    def _cmd_to_dict(self, cmd):
        arg_list = cmd.split()
        no_param_args = [
            'autodelete',
            'autoexpand',
            'bytes',
            'compressed',
            'force',
            'nohdr',
        ]
        one_param_args = [
            'chapsecret',
            'cleanrate',
            'copyrate',
            'delim',
            'filtervalue',
            'grainsize',
            'hbawwpn',
            'host',
            'iogrp',
            'iscsiname',
            'mdiskgrp',
            'name',
            'rsize',
            'scsi',
            'size',
            'source',
            'target',
            'unit',
            'easytier',
            'warning',
            'wwpn',
        ]

        # Handle the special case of lsnode which is a two-word command
        # Use the one word version of the command internally
        if arg_list[0] in ('svcinfo', 'svctask'):
            if arg_list[1] == 'lsnode':
                if len(arg_list) > 4:  # e.g. svcinfo lsnode -delim ! <node id>
                    ret = {'cmd': 'lsnode', 'node_id': arg_list[-1]}
                else:
                    ret = {'cmd': 'lsnodecanister'}
            else:
                ret = {'cmd': arg_list[1]}
            arg_list.pop(0)
        else:
            ret = {'cmd': arg_list[0]}

        skip = False
        for i in range(1, len(arg_list)):
            if skip:
                skip = False
                continue
            if arg_list[i][0] == '-':
                if arg_list[i][1:] in no_param_args:
                    ret[arg_list[i][1:]] = True
                elif arg_list[i][1:] in one_param_args:
                    ret[arg_list[i][1:]] = arg_list[i + 1]
                    skip = True
                else:
                    raise exception.InvalidInput(
                        reason=_('unrecognized argument %s') % arg_list[i])
            else:
                ret['obj'] = arg_list[i]
        return ret
// _cli_run [python]
    def _cli_run(self, cmd):
        """Runs a CLI command over SSH, without doing any result parsing."""
        LOG.debug("SSH CMD = %s " % cmd)

        (stdout, stderr) = self._run_ssh(cmd, False)

        # we have to strip out the input and exit lines
        tmp = stdout.split("\r\n")
        out = tmp[5:len(tmp) - 2]
        return out
// _cli_run [python]
    def _cli_run(self, verb, cli_args):
        """Runs a CLI command over SSH, without doing any result parsing."""
        cli_arg_strings = []
        if cli_args:
            for k, v in cli_args.items():
                if k == '':
                    cli_arg_strings.append(" %s" % k)
                else:
                    cli_arg_strings.append(" %s=%s" % (k, v))

        cmd = verb + ''.join(cli_arg_strings)
        LOG.debug("SSH CMD = %s " % cmd)

        (stdout, stderr) = self._run_ssh(cmd, False)

        # we have to strip out the input and exit lines
        tmp = stdout.split("\r\n")
        out = tmp[5:len(tmp) - 2]
        return out
// _call_external_zip [python]
def _call_external_zip(base_dir, zip_filename, verbose, dry_run, logger):
    # XXX see if we want to keep an external call here
    if verbose:
        zipoptions = "-r"
    else:
        zipoptions = "-rq"
    cmd = ["zip", zipoptions, zip_filename, base_dir]
    if logger is not None:
        logger.info(' '.join(cmd))
    if dry_run:
        return
    import subprocess
    try:
        subprocess.check_call(cmd)
    except subprocess.CalledProcessError:
        # XXX really should distinguish between "couldn't find
        # external 'zip' command" and "zip failed".
        raise ExecError, \
            ("unable to create zip file '%s': "
            "could neither import the 'zipfile' module nor "
            "find a standalone zip utility") % zip_filename
// _call_external_zip [python]
def _call_external_zip(base_dir, zip_filename, verbose=False, dry_run=False):
    # XXX see if we want to keep an external call here
    if verbose:
        zipoptions = "-r"
    else:
        zipoptions = "-rq"
    from distutils.errors import DistutilsExecError
    from distutils.spawn import spawn
    try:
        spawn(["zip", zipoptions, zip_filename, base_dir], dry_run=dry_run)
    except DistutilsExecError:
        # XXX really should distinguish between "couldn't find
        # external 'zip' command" and "zip failed".
        raise ExecError, \
            ("unable to create zip file '%s': "
            "could neither import the 'zipfile' module nor "
            "find a standalone zip utility") % zip_filename
// _create_host [python]
    def _create_host(self, connector):
        """Create a new host on the storage system.

        We create a host name and associate it with the given connection
        information.

        """

        LOG.debug(_('enter: _create_host: host %s') % connector['host'])

        rand_id = str(random.randint(0, 99999999)).zfill(8)
        host_name = '%s-%s' % (self._connector_to_hostname_prefix(connector),
                               rand_id)

        # Get all port information from the connector
        ports = []
        if 'initiator' in connector:
            ports.append('-iscsiname %s' % connector['initiator'])
        if 'wwpns' in connector:
            for wwpn in connector['wwpns']:
                ports.append('-hbawwpn %s' % wwpn)

        # When creating a host, we need one port
        self._driver_assert(len(ports), _('_create_host: No connector ports'))
        port1 = ports.pop(0)
        arg_name, arg_val = port1.split()
        ssh_cmd = ['svctask', 'mkhost', '-force', arg_name, arg_val, '-name',
                   '"%s"' % host_name]
        out, err = self._run_ssh(ssh_cmd)
        self._assert_ssh_return('successfully created' in out,
                                '_create_host', ssh_cmd, out, err)

        # Add any additional ports to the host
        for port in ports:
            arg_name, arg_val = port.split()
            ssh_cmd = ['svctask', 'addhostport', '-force', arg_name, arg_val,
                       host_name]
            out, err = self._run_ssh(ssh_cmd)

        LOG.debug(_('leave: _create_host: host %(host)s - %(host_name)s') %
                  {'host': connector['host'], 'host_name': host_name})
        return host_name
// _create_host [python]
    def _create_host(self, connector):
        """Create a new host on the storage system.

        We create a host name and associate it with the given connection
        information.

        """

        LOG.debug(_('enter: _create_host: host %s') % connector['host'])

        rand_id = str(random.randint(0, 99999999)).zfill(8)
        host_name = '%s-%s' % (self._connector_to_hostname_prefix(connector),
                               rand_id)

        # Get all port information from the connector
        ports = []
        if 'initiator' in connector:
            ports.append('-iscsiname %s' % connector['initiator'])
        if 'wwpns' in connector:
            for wwpn in connector['wwpns']:
                ports.append('-hbawwpn %s' % wwpn)

        # When creating a host, we need one port
        self._driver_assert(len(ports), _('_create_host: No connector ports'))
        port1 = ports.pop(0)
        ssh_cmd = ('svctask mkhost -force %(port1)s -name "%(host_name)s"' %
                   {'port1': port1, 'host_name': host_name})
        out, err = self._run_ssh(ssh_cmd)
        self._assert_ssh_return('successfully created' in out,
                                '_create_host', ssh_cmd, out, err)

        # Add any additional ports to the host
        for port in ports:
            ssh_cmd = ('svctask addhostport -force %s %s' % (port, host_name))
            out, err = self._run_ssh(ssh_cmd)

        LOG.debug(_('leave: _create_host: host %(host)s - %(host_name)s') %
                  {'host': connector['host'], 'host_name': host_name})
        return host_name
// _get_iscsi_ip_addrs [python]
    def _get_iscsi_ip_addrs(self):
        generator = self._port_conf_generator(['svcinfo', 'lsportip'])
        header = next(generator, None)
        if not header:
            return

        for port_data in generator:
            try:
                port_node_id = port_data['node_id']
                port_ipv4 = port_data['IP_address']
                port_ipv6 = port_data['IP_address_6']
                state = port_data['state']
            except KeyError:
                self._handle_keyerror('lsportip', header)

            if port_node_id in self._storage_nodes and (
                    state == 'configured' or state == 'online'):
                node = self._storage_nodes[port_node_id]
                if len(port_ipv4):
                    node['ipv4'].append(port_ipv4)
                if len(port_ipv6):
                    node['ipv6'].append(port_ipv6)
// _get_iscsi_ip_addrs [python]
    def _get_iscsi_ip_addrs(self):
        generator = self._port_conf_generator('svcinfo lsportip')
        header = next(generator, None)
        if not header:
            return

        for port_data in generator:
            try:
                port_node_id = port_data['node_id']
                port_ipv4 = port_data['IP_address']
                port_ipv6 = port_data['IP_address_6']
                state = port_data['state']
            except KeyError:
                self._handle_keyerror('lsportip', header)

            if port_node_id in self._storage_nodes and (
                    state == 'configured' or state == 'online'):
                node = self._storage_nodes[port_node_id]
                if len(port_ipv4):
                    node['ipv4'].append(port_ipv4)
                if len(port_ipv6):
                    node['ipv6'].append(port_ipv6)
// talk [python]
def talk(myText):
    if( myText.find( "twitter" ) >= 0 ):
        myText += "0"
        myText = myText[7:-1]
        try:
	    myText = twitter.getTweet( myText )
	except:
	    print( "!!!ERROR: INVALID TWITTER CREDENTIALS. Please read README.md for instructions.")
            return
    
    os.system( "espeak \",...\" 2>/dev/null" ) # Sometimes the beginning of audio can get cut off. Insert silence.
    time.sleep( 0.5 )
    subprocess.call(["espeak", "-w", "speech.wav", myText, "-s", "130"])
    audio.play("speech.wav")
    return myText
// talk [python]
def talk(myText):
    if( myText.find( "twitter" ) >= 0 ):
        myText += "0"
        myText = myText[7:-1]
        try:
	    myText = twitter.getTweet( myText )
	except:
	    print( "!!!ERROR: INVALID TWITTER CREDENTIALS. Please read README.md for instructions.")
            return
    
    os.system( "espeak \",...\" 2>/dev/null" ) # Sometimes the beginning of audio can get cut off. Insert silence.
    time.sleep( 0.5 )
    os.system( "espeak -w speech.wav \"" + myText + "\" -s 130" )
    audio.play("speech.wav")
    return myText
// _exec_cmd [python]
    def _exec_cmd(self, args, shell):
        """Executes adb commands.

        Args:
            args: string or list of strings, program arguments.
                See subprocess.Popen() documentation.
            shell: bool, True to run this command through the system shell,
                False to invoke it directly. See subprocess.Popen() docs.

        Returns:
            The output of the adb command run if exit code is 0.

        Raises:
            AdbError is raised if the adb command exit code is not 0.
        """
        proc = subprocess.Popen(
            args, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=shell)
        (out, err) = proc.communicate()
        ret = proc.returncode
        logging.debug('cmd: %s, stdout: %s, stderr: %s, ret: %s', args, out,
                      err, ret)
        if ret == 0:
            return out
        else:
            raise AdbError(cmd=args, stdout=out, stderr=err, ret_code=ret)
// _exec_cmd [python]
    def _exec_cmd(self, cmd):
        """Executes adb commands in a new shell.

        This is specific to executing adb binary because stderr is not a good
        indicator of cmd execution status.

        Args:
            cmds: A string that is the adb command to execute.

        Returns:
            The output of the adb command run if exit code is 0.

        Raises:
            AdbError is raised if the adb command exit code is not 0.
        """
        proc = subprocess.Popen(
            cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
        (out, err) = proc.communicate()
        ret = proc.returncode
        logging.debug('cmd: %s, stdout: %s, stderr: %s, ret: %s', cmd, out,
                      err, ret)
        if ret == 0:
            return out
        else:
            raise AdbError(cmd=cmd, stdout=out, stderr=err, ret_code=ret)
// _get_conn_fc_wwpns [python]
    def _get_conn_fc_wwpns(self, host_name):
        wwpns = []
        cmd = ['svcinfo', 'lsfabric', '-host', host_name]
        generator = self._port_conf_generator(cmd)
        header = next(generator, None)
        if not header:
            return wwpns

        for port_data in generator:
            try:
                wwpns.append(port_data['local_wwpn'])
            except KeyError as e:
                self._handle_keyerror('lsfabric', header)

        return wwpns
// _get_conn_fc_wwpns [python]
    def _get_conn_fc_wwpns(self, host_name):
        wwpns = []
        cmd = 'svcinfo lsfabric -host %s' % host_name
        generator = self._port_conf_generator(cmd)
        header = next(generator, None)
        if not header:
            return wwpns

        for port_data in generator:
            try:
                wwpns.append(port_data['local_wwpn'])
            except KeyError as e:
                self._handle_keyerror('lsfabric', header)

        return wwpns
// _create_3par_iscsi_host [python]
    def _create_3par_iscsi_host(self, hostname, iscsi_iqn, domain, persona_id):
        """Create a 3PAR host.

        Create a 3PAR host, if there is already a host on the 3par using
        the same iqn but with a different hostname, return the hostname
        used by 3PAR.
        """
        cmd = ['createhost', '-iscsi', '-persona', persona_id, '-domain',
               domain, hostname, iscsi_iqn]
        out = self.common._cli_run(cmd)
        if out and len(out) > 1:
            return self.common.parse_create_host_error(hostname, out)
        return hostname
// _create_3par_iscsi_host [python]
    def _create_3par_iscsi_host(self, hostname, iscsi_iqn, domain, persona_id):
        """Create a 3PAR host.

        Create a 3PAR host, if there is already a host on the 3par using
        the same iqn but with a different hostname, return the hostname
        used by 3PAR.
        """
        cmd = 'createhost -iscsi -persona %s -domain %s %s %s' % \
              (persona_id, domain, hostname, iscsi_iqn)
        out = self.common._cli_run(cmd, None)
        if out and len(out) > 1:
            return self.common.parse_create_host_error(hostname, out)
        return hostname
// _delete_3par_host [python]
    def _delete_3par_host(self, hostname):
        self._cli_run(['removehost', hostname])
// _delete_3par_host [python]
    def _delete_3par_host(self, hostname):
        self._cli_run('removehost %s' % hostname, None)
// process_statistics [python]
    def process_statistics(self, metadata, _):
        args = [metadata.hostname, '-p', metadata.profile, '-g',
                ':'.join([g for g in metadata.groups])]
        self.debug_log("running triggers")
        for notifier in os.listdir(self.data):
            self.debug_log("running %s" % notifier)
            if ((notifier[-1] == '~') or
                (notifier[:2] == '.#') or
                (notifier[-4:] == '.swp') or
                (notifier in ['SCCS', '.svn', '4913'])):
                continue
            npath = os.path.join(self.data, notifier)
            self.async_run([npath] + args)
// process_statistics [python]
    def process_statistics(self, metadata, _):
        args = [metadata.hostname, '-p', metadata.profile, '-g',
                ':'.join([g for g in metadata.groups])]
        for notifier in os.listdir(self.data):
            if ((notifier[-1] == '~') or
                (notifier[:2] == '.#') or
                (notifier[-4:] == '.swp') or
                (notifier in ['SCCS', '.svn', '4913'])):
                continue
            npath = self.data + '/' + notifier
            self.logger.debug("Running %s %s" % (npath, " ".join(args)))
            async_run(npath, args)
// _delete_host [python]
    def _delete_host(self, host_name):
        """Delete a host on the storage system."""

        LOG.debug(_('enter: _delete_host: host %s ') % host_name)

        ssh_cmd = ['svctask', 'rmhost', host_name]
        out, err = self._run_ssh(ssh_cmd)
        # No output should be returned from rmhost
        self._assert_ssh_return(len(out.strip()) == 0,
                                '_delete_host', ssh_cmd, out, err)

        LOG.debug(_('leave: _delete_host: host %s ') % host_name)
// _delete_host [python]
    def _delete_host(self, host_name):
        """Delete a host on the storage system."""

        LOG.debug(_('enter: _delete_host: host %s ') % host_name)

        ssh_cmd = 'svctask rmhost %s ' % host_name
        out, err = self._run_ssh(ssh_cmd)
        # No output should be returned from rmhost
        self._assert_ssh_return(len(out.strip()) == 0,
                                '_delete_host', ssh_cmd, out, err)

        LOG.debug(_('leave: _delete_host: host %s ') % host_name)
// fetch [python]
def fetch(url):
  '''Download and verify a package url.'''
  base = os.path.basename(url)
  print('Fetching %s...' % base)
  fetch_file(url + '.asc')
  fetch_file(url)
  fetch_file(url + '.sha256')
  fetch_file(url + '.asc.sha256')
  print('Verifying %s...' % base)
  # TODO: check for verification failure.
  subprocess.check_call(['shasum', '-c', base + '.sha256'])
  subprocess.check_call(['shasum', '-c', base + '.asc.sha256'])
  subprocess.check_call(['gpg', '--verify', base + '.asc', base])
  subprocess.check_call(['keybase', 'verify', base + '.asc'])
// fetch [python]
def fetch(url):
  '''Download and verify a package url.'''
  base = os.path.basename(url)
  print('Fetching %s...' % base)
  fetch_file(url + '.asc')
  fetch_file(url)
  fetch_file(url + '.sha256')
  fetch_file(url + '.asc.sha256')
  print('Verifying %s...' % base)
  # TODO: check for verification failure.
  os.system('shasum -c %s.sha256' % base)
  os.system('shasum -c %s.asc.sha256' % base)
  os.system('gpg --verify %s.asc %s' % (base, base))
  os.system('keybase verify %s.asc' % base)
// poll [python]
    def poll(self, poll_input):
        username = poll_input.credentials.username
        password = poll_input.credentials.password
        domain = poll_input.credentials.domain
        
        if domain is None:
            opt_str = '--ignore-certificate --authonly -u \'{}\' -p \'{}\' {}:{}'
            options = opt_str.format(
                    username, password,
                    poll_input.server, poll_input.port)
        else:
            opt_str = '--ignore-certificate --authonly -d {} -u \'{}\' -p \'{}\' {}:{}'
            options = opt_str.format(
                    domain.domain, username, password,
                    poll_input.server, poll_input.port)

        try:
            output = subprocess.check_output('timeout {} xfreerdp {}'.format(poll_input.timeout, options), shell=True, stderr=subprocess.STDOUT)
            result = RdpPollResult(True)
            return result
        except Exception as e:
            if ('connected to' in str(e.output) and 'Authentication failure' not in str(e.output)) or (e.returncode == 131 and 'negotiation' in str(e.output)):
                result = RdpPollResult(True)
                return result
            print("{{{{%s}}}}" % e.output)
            result = RdpPollResult(False, e)
            return result
// poll [python]
    def poll(self, poll_input):
        username = poll_input.credentials.username
        password = poll_input.credentials.password
        domain = poll_input.credentials.domain
        
        if domain is None:
            opt_str = '--ignore-certificate --authonly -u {} -p {} {}:{}'
            options = opt_str.format(
                    username, password,
                    poll_input.server, poll_input.port)
        else:
            opt_str = '--ignore-certificate --authonly -d {} -u {} -p {} {}:{}'
            options = opt_str.format(
                    domain.domain, username, password,
                    poll_input.server, poll_input.port)

        try:
            output = subprocess.check_output('timeout {} xfreerdp {}'.format(poll_input.timeout, options), shell=True, stderr=subprocess.STDOUT)
            result = RdpPollResult(True)
            return result
        except Exception as e:
            if ('connected to' in str(e.output) and 'Authentication failure' not in str(e.output)) or (e.returncode == 131 and 'negotiation' in str(e.output)):
                result = RdpPollResult(True)
                return result
            print("{{{{%s}}}}" % e.output)
            result = RdpPollResult(False, e)
            return result
// terminate_connection [python]
    def terminate_connection(self, volume, connector, **kwargs):
        """Cleanup after an iSCSI connection has been terminated.

        When we clean up a terminated connection between a given connector
        and volume, we:
        1. Translate the given connector to a host name
        2. Remove the volume-to-host mapping if it exists
        3. Delete the host if it has no more mappings (hosts are created
           automatically by this driver when mappings are created)
        """
        LOG.debug(_('enter: terminate_connection: volume %(vol)s with '
                    'connector %(conn)s') % {'vol': str(volume),
                                             'conn': str(connector)})

        vol_name = volume['name']
        host_name = self._get_host_from_connector(connector)
        # Verify that _get_host_from_connector returned the host.
        # This should always succeed as we terminate an existing connection.
        self._driver_assert(
            host_name is not None,
            _('_get_host_from_connector failed to return the host name '
              'for connector'))

        # Check if vdisk-host mapping exists, remove if it does
        mapping_data = self._get_hostvdisk_mappings(host_name)
        if vol_name in mapping_data:
            ssh_cmd = ['svctask', 'rmvdiskhostmap', '-host', host_name,
                       vol_name]
            out, err = self._run_ssh(ssh_cmd)
            # Verify CLI behaviour - no output is returned from
            # rmvdiskhostmap
            self._assert_ssh_return(len(out.strip()) == 0,
                                    'terminate_connection', ssh_cmd, out, err)
            del mapping_data[vol_name]
        else:
            LOG.error(_('terminate_connection: No mapping of volume '
                        '%(vol_name)s to host %(host_name)s found') %
                      {'vol_name': vol_name, 'host_name': host_name})

        # If this host has no more mappings, delete it
        if not mapping_data:
            self._delete_host(host_name)

        LOG.debug(_('leave: terminate_connection: volume %(vol)s with '
                    'connector %(conn)s') % {'vol': str(volume),
                                             'conn': str(connector)})
// terminate_connection [python]
    def terminate_connection(self, volume, connector, **kwargs):
        """Cleanup after an iSCSI connection has been terminated.

        When we clean up a terminated connection between a given connector
        and volume, we:
        1. Translate the given connector to a host name
        2. Remove the volume-to-host mapping if it exists
        3. Delete the host if it has no more mappings (hosts are created
           automatically by this driver when mappings are created)
        """
        LOG.debug(_('enter: terminate_connection: volume %(vol)s with '
                    'connector %(conn)s') % {'vol': str(volume),
                                             'conn': str(connector)})

        vol_name = volume['name']
        host_name = self._get_host_from_connector(connector)
        # Verify that _get_host_from_connector returned the host.
        # This should always succeed as we terminate an existing connection.
        self._driver_assert(
            host_name is not None,
            _('_get_host_from_connector failed to return the host name '
              'for connector'))

        # Check if vdisk-host mapping exists, remove if it does
        mapping_data = self._get_hostvdisk_mappings(host_name)
        if vol_name in mapping_data:
            ssh_cmd = 'svctask rmvdiskhostmap -host %s %s' % \
                (host_name, vol_name)
            out, err = self._run_ssh(ssh_cmd)
            # Verify CLI behaviour - no output is returned from
            # rmvdiskhostmap
            self._assert_ssh_return(len(out.strip()) == 0,
                                    'terminate_connection', ssh_cmd, out, err)
            del mapping_data[vol_name]
        else:
            LOG.error(_('terminate_connection: No mapping of volume '
                        '%(vol_name)s to host %(host_name)s found') %
                      {'vol_name': vol_name, 'host_name': host_name})

        # If this host has no more mappings, delete it
        if not mapping_data:
            self._delete_host(host_name)

        LOG.debug(_('leave: terminate_connection: volume %(vol)s with '
                    'connector %(conn)s') % {'vol': str(volume),
                                             'conn': str(connector)})
// _port_conf_generator [python]
    def _port_conf_generator(self, cmd):
        ssh_cmd = cmd + ['-delim', '!']
        out, err = self._run_ssh(ssh_cmd)

        if not len(out.strip()):
            return
        port_lines = out.strip().split('\n')
        if not len(port_lines):
            return

        header = port_lines.pop(0)
        yield header
        for portip_line in port_lines:
            try:
                port_data = self._get_hdr_dic(header, portip_line, '!')
            except exception.VolumeBackendAPIException:
                with excutils.save_and_reraise_exception():
                    self._log_cli_output_error('_port_conf_generator',
                                               ssh_cmd, out, err)
            yield port_data
// _port_conf_generator [python]
    def _port_conf_generator(self, cmd):
        ssh_cmd = '%s -delim !' % cmd
        out, err = self._run_ssh(ssh_cmd)

        if not len(out.strip()):
            return
        port_lines = out.strip().split('\n')
        if not len(port_lines):
            return

        header = port_lines.pop(0)
        yield header
        for portip_line in port_lines:
            try:
                port_data = self._get_hdr_dic(header, portip_line, '!')
            except exception.VolumeBackendAPIException:
                with excutils.save_and_reraise_exception():
                    self._log_cli_output_error('_port_conf_generator',
                                               ssh_cmd, out, err)
            yield port_data
// r_pkcs7_parse_cms [c]
RCMS *r_pkcs7_parse_cms (const ut8 *buffer, ut32 length) {
	RASN1Object *object;
	RCMS *container;
	if (!buffer || !length) {
		return NULL;
	}
	container = R_NEW0 (RCMS);
	if (!container) {
		return NULL;
	}
	object = r_asn1_create_object (buffer, length);
	if (!object || object->list.length != 2 || !object->list.objects ||
		!object->list.objects[0] || !object->list.objects[1] ||
		object->list.objects[1]->list.length != 1) {
		r_asn1_free_object (object);
		free (container);
		return NULL;
	}
	container->contentType = r_asn1_stringify_oid (object->list.objects[0]->sector, object->list.objects[0]->length);
	r_pkcs7_parse_signeddata (&container->signedData, object->list.objects[1]->list.objects[0]);
	r_asn1_free_object (object);
	return container;
}
// r_pkcs7_parse_cms [c]
RCMS *r_pkcs7_parse_cms (const ut8 *buffer, ut32 length) {
	RASN1Object *object;
	RCMS *container;
	if (!buffer || !length) {
		return NULL;
	}
	container = R_NEW0 (RCMS);
	if (!container) {
		return NULL;
	}
	object = r_asn1_create_object (buffer, length);
	if (!object || object->list.length != 2 || !object->list.objects[0] || object->list.objects[1]->list.length != 1) {
		r_asn1_free_object (object);
		free (container);
		return NULL;
	}
	container->contentType = r_asn1_stringify_oid (object->list.objects[0]->sector, object->list.objects[0]->length);
	r_pkcs7_parse_signeddata (&container->signedData, object->list.objects[1]->list.objects[0]);
	r_asn1_free_object (object);
	return container;
}
// hash_accept [c]
static int hash_accept(struct socket *sock, struct socket *newsock, int flags)
{
	struct sock *sk = sock->sk;
	struct alg_sock *ask = alg_sk(sk);
	struct hash_ctx *ctx = ask->private;
	struct ahash_request *req = &ctx->req;
	char state[crypto_ahash_statesize(crypto_ahash_reqtfm(req))];
	struct sock *sk2;
	struct alg_sock *ask2;
	struct hash_ctx *ctx2;
	bool more;
	int err;

	lock_sock(sk);
	more = ctx->more;
	err = more ? crypto_ahash_export(req, state) : 0;
	release_sock(sk);

	if (err)
		return err;

	err = af_alg_accept(ask->parent, newsock);
	if (err)
		return err;

	sk2 = newsock->sk;
	ask2 = alg_sk(sk2);
	ctx2 = ask2->private;
	ctx2->more = more;

	if (!more)
		return err;

	err = crypto_ahash_import(&ctx2->req, state);
	if (err) {
		sock_orphan(sk2);
		sock_put(sk2);
	}

	return err;
}
// hash_accept [c]
static int hash_accept(struct socket *sock, struct socket *newsock, int flags)
{
	struct sock *sk = sock->sk;
	struct alg_sock *ask = alg_sk(sk);
	struct hash_ctx *ctx = ask->private;
	struct ahash_request *req = &ctx->req;
	char state[crypto_ahash_statesize(crypto_ahash_reqtfm(req))];
	struct sock *sk2;
	struct alg_sock *ask2;
	struct hash_ctx *ctx2;
	int err;

	err = crypto_ahash_export(req, state);
	if (err)
		return err;

	err = af_alg_accept(ask->parent, newsock);
	if (err)
		return err;

	sk2 = newsock->sk;
	ask2 = alg_sk(sk2);
	ctx2 = ask2->private;
	ctx2->more = 1;

	err = crypto_ahash_import(&ctx2->req, state);
	if (err) {
		sock_orphan(sk2);
		sock_put(sk2);
	}

	return err;
}
// prplcb_xfer_new_send_cb [c]
static gboolean prplcb_xfer_new_send_cb(gpointer data, gint fd, b_input_condition cond)
{
	PurpleXfer *xfer = data;
	struct im_connection *ic = purple_ic_by_pa(xfer->account);
	struct prpl_xfer_data *px = xfer->ui_data;
	PurpleBuddy *buddy;
	const char *who;

	buddy = purple_find_buddy(xfer->account, xfer->who);
	who = buddy ? purple_buddy_get_name(buddy) : xfer->who;

	/* TODO(wilmer): After spreading some more const goodness in BitlBee,
	   remove the evil cast below. */
	px->ft = imcb_file_send_start(ic, (char *) who, xfer->filename, xfer->size);

	if (!px->ft) {
		return FALSE;
	}
	px->ft->data = px;

	px->ft->accept = prpl_xfer_accept;
	px->ft->canceled = prpl_xfer_canceled;
	px->ft->free = prpl_xfer_free;
	px->ft->write_request = prpl_xfer_write_request;

	return FALSE;
}