Parse the query reply from VDP daemon to get the VLAN value.
974666
def get_vlan_from_query_reply(self, reply, vsiid, mac):
        
        hints_ret, fail_reason = self.check_hints(reply)
        if not hints_ret:
            LOG.error("Incorrect hints found %s", reply)
            return constants.INVALID_VLAN, fail_reason
        check_filter, fail_reason = self.check_filter_validity(reply, "filter")
        if not check_filter:
            return constants.INVALID_VLAN, fail_reason
        try:
            verify_flag, fail_reason = self.crosscheck_query_vsiid_mac(
                reply, vsiid, mac)
            if not verify_flag:
                return constants.INVALID_VLAN, fail_reason
            filter_val = reply.partition("filter")[2]
            len_fil = len(filter_val)
            vlan_val = filter_val[4:len_fil].split('-')[0]
            vlan = int(vlan_val)
        except ValueError:
            fail_reason = vdp_const.format_failure_reason % (reply)
            LOG.error("%s", fail_reason)
            return constants.INVALID_VLAN, fail_reason
        return vlan, None
1017284
def query(self, queryString):
    '''
    
    '''
    self._setHeaders('query')
    return self._sforce.service.query(queryString)
1256943
def get_vlan_brief_request(last_vlan_id):
        

        request_interface = ET.Element(
            'get-vlan-brief',
            xmlns="urn:brocade.com:mgmt:brocade-interface-ext"
        )
        if last_vlan_id != '':
            last_received_int_el = ET.SubElement(request_interface,
                                                 "last-rcvd-vlan-id")
            last_received_int_el.text = last_vlan_id
        return request_interface
1128374
def _parse_request_reply(self):
        ""
        # we need at least 6 bytes of data: 4 for the "header", such
        # as it is, and 2 more if it's DOMAINNAME (for the size) or 4
        # or 16 more if it's an IPv4/6 address reply. plus there's 2
        # bytes on the end for the bound port.
        if len(self._data) < 8:
            return
        msg = self._data[:4]

        # not changing self._data yet, in case we've not got
        # enough bytes so far.
        (version, reply, _, typ) = struct.unpack('BBBB', msg)

        if version != 5:
            self.reply_error(SocksError(
                "Expected version 5, got {}".format(version)))
            return

        if reply != self.SUCCEEDED:
            self.reply_error(_create_socks_error(reply))
            return

        reply_dispatcher = {
            self.REPLY_IPV4: self._parse_ipv4_reply,
            self.REPLY_HOST: self._parse_domain_name_reply,
            self.REPLY_IPV6: self._parse_ipv6_reply,
        }
        try:
            method = reply_dispatcher[typ]
        except KeyError:
            self.reply_error(SocksError(
                "Unexpected response type {}".format(typ)))
            return
        method()
164681
def parse_response(resp):
    
    host_id, msg, code = None, None, None
    try:
        content = resp.content
        root = ET.fromstring(content)
        code = root.find('./Code').text
        msg = root.find('./Message').text
        request_id = root.find('./RequestId').text
        host_id = root.find('./HostId').text
    except ETParseError:
        request_id = resp.headers.get('x-odps-request-id', None)
        if len(resp.content) > 0:
            obj = json.loads(resp.text)
            msg = obj['Message']
            code = obj.get('Code')
            host_id = obj.get('HostId')
            if request_id is None:
                request_id = obj.get('RequestId')
        else:
            return
    clz = globals().get(code, ODPSError)
    return clz(msg, request_id=request_id, code=code, host_id=host_id)
1208498
def parse(self):
        
        if self.target.endswith("/"):
            self.target = self.target[:-1]

        if self._is_proto(self.target):
            try:
                self.protocol, self.target = self.target.split("://")
                self.logger.info("{} Protocol detected: {}".format(COLORED_COMBOS.NOTIFY, self.protocol))
                if self.protocol.lower() == "https" and self.port == 80:
                    self.port = 443
            except ValueError:
                raise HostHandlerException("Could not make domain and protocol from host")

        if ":" in self.target:
            self._extract_port(self.target)

        if self.validate_ip(self.target):
            self.logger.info("{} Detected {} as an IP address.".format(COLORED_COMBOS.NOTIFY, self.target))
            self.is_ip = True
        else:
            domains = []
            if self.target.startswith("www."):
                # Obviously an FQDN
                domains.extend((self.target, self.target.split("www.")[1]))
                self.fqdn = self.target
                self.naked = ".".join(self.fqdn.split('.')[1:])
            else:
                domains.append(self.target)
                domain_levels = self.target.split(".")
                if len(domain_levels) == 2 or (len(domain_levels) == 3 and domain_levels[1] == "co"):
                    self.logger.info("{} Found {} to be a naked domain".format(COLORED_COMBOS.NOTIFY, self.target))
                    self.naked = self.target

            try:
                self.dns_results = DNSHandler.query_dns(domains, self.dns_records)
            except Timeout:
                raise HostHandlerException("DNS Query timed out. Maybe target has DNS protection ?")

            if self.dns_results.get("CNAME"):
                # Naked domains shouldn't hold CNAME records according to RFC regulations
                self.logger.info("{} Found {} to be an FQDN by CNAME presence in DNS records".format(
                    COLORED_COMBOS.NOTIFY, self.target))

                self.fqdn = self.target
                self.naked = ".".join(self.fqdn.split('.')[1:])
        self.create_host_dir_and_set_file_logger()
        self.write_up()
806905
def parse_url(self):
        
        self.scheme = None
        self.resource = None
        self.host = None
        self.port = None

        if self.url is None:
            return

        scheme, url = self.url.split(":", 1)
        parsed = urlsplit(url, scheme="http")
        if parsed.hostname:
            self.host = parsed.hostname
        elif '+unix' in scheme:
            self.host = 'localhost'
        else:
            raise ValueError("Invalid hostname from: %s", self.url)

        if parsed.port:
            self.port = parsed.port

        if scheme == "ws":
            if not self.port:
                self.port = 8080
        elif scheme == "wss":
            if not self.port:
                self.port = 443
        elif scheme in ('ws+unix', 'wss+unix'):
            pass
        else:
            raise ValueError("Invalid scheme: %s" % scheme)

        if parsed.path:
            resource = parsed.path
        else:
            resource = "/"

        if '+unix' in scheme:
            self.unix_socket_path = resource
            resource = '/'

        if parsed.query:
            resource += "?" + parsed.query

        self.scheme = scheme
        self.resource = resource
557938
function parseOutput(str, callback) {
  var err   = null;
  var wifis = [];

  try {
    var blocks = str.split(cellRegex);

    blocks.forEach(block => {
      var network = {};
      var lines   = block.split('\n');
      if (macRegex.exec(lines[0])) {
        // First line is the mac address (always! (?))
        network.mac = lines[0].trim();

        lines.forEach(line => {
          // SSID
          if (line.indexOf('ESSID:') > 0) {
            network.ssid = _.trim(line.split(':')[1], '"');
            if (_.startsWith(network.ssid, '\\x00')) {
              // The raspi 3 interprets a string terminator as character, it's an empty SSID
              network.ssid = '';
            }
          }

          // Channel, an ugly thing to get it
          else if (_.startsWith(line.trim(), 'Frequency:')) {
            network.channel = parseInt(_.trim(line, ' )').split(/Channel/)[1], 10);
          }
            
          // Another ugly thing, the signal which can have different formats, even worse als
          // having different identifiers
          else if (line.indexOf('Signal level') > -1) {
            if (line.indexOf('Quality') > -1) {
              // This is a "Quality=40/70  Signal level=-70 dBm" line
              network.rssi = parseInt(line.substr(line.indexOf('Signal level') + 13), 10);
            }
            else {
              // This is a "Signal level=60/100" line
              var elements = line.split('=');
              elements.forEach(e => {
                if (e.indexOf('/') > 0) {
                  // that's our part
                  var parts    = e.split('/');
                  var level    = Math.floor(100 * parseInt(parts[0], 10) / parseInt(parts[1], 10));
                  network.rssi = level / 2 - 100;
                }
              })
            }
          }
        });
        wifis.push(network);
      }
    });
  }
  catch (ex) {
    err = ex;
  }

  callback(err, wifis);
}
411015
protected boolean parse(final byte[] pSelectResponse, final Application pApplication) throws CommunicationException {
		boolean ret = false;
		// Get TLV log entry
		byte[] logEntry = getLogEntry(pSelectResponse);
		// Get PDOL
		byte[] pdol = TlvUtil.getValue(pSelectResponse, EmvTags.PDOL);
		// Send GPO Command
		byte[] gpo = getGetProcessingOptions(pdol);
		// Extract Bank data
		extractBankData(pSelectResponse);

		// Check empty PDOL
		if (!ResponseUtils.isSucceed(gpo)) {
			if (pdol != null) {
				gpo = getGetProcessingOptions(null);
			}

			// Check response
			if (pdol == null || !ResponseUtils.isSucceed(gpo)) {
				// Try to read EF 1 and record 1
				gpo = template.get().getProvider().transceive(new CommandApdu(CommandEnum.READ_RECORD, 1, 0x0C, 0).toBytes());
				if (!ResponseUtils.isSucceed(gpo)) {
					return false;
				}
			}
		}
		// Update Reading state
		pApplication.setReadingStep(ApplicationStepEnum.READ);

		// Extract commons card data (number, expire date, ...)
		if (extractCommonsCardData(gpo)) {
			// Extract log entry
			pApplication.setListTransactions(extractLogEntry(logEntry));
			ret = true;
		}

		return ret;
	}
597085
def _parse_ip(addr):
    

    # Parse the IP address
    try:
        address = netaddr.IPAddress(addr.strip())
    except (ValueError, netaddr.AddrFormatError):
        return None

    # Canonicalize it, if possible
    if address.version == 6:
        try:
            return address.ipv4()
        except netaddr.AddrConversionError:
            pass

    return address
387494
def parse_response_adu(resp_adu, req_adu=None):
    
    resp_pdu = resp_adu[7:]
    function = create_function_from_response_pdu(resp_pdu, req_adu)

    return function.data
489699
def parse(self):
        
        status = Status()
        self.expect_line(Status.client_list.label)

        status.updated_at = self.expect_tuple(Status.updated_at.label)
        status.client_list.update({
            text_type(c.real_address): c
            for c in self._parse_fields(Client, Status.routing_table.label)})
        status.routing_table.update({
            text_type(r.virtual_address): r
            for r in self._parse_fields(Routing, Status.global_stats.label)})
        status.global_stats = GlobalStats()
        status.global_stats.max_bcast_mcast_queue_len = self.expect_tuple(
            GlobalStats.max_bcast_mcast_queue_len.label)

        self.expect_line(self.terminator)
        return status
255608
def _parseCusdResponse(self, lines):
        
        if len(lines) > 1:
            # Issue #20: Some modem/network combinations use \r\n as in-message EOL indicators;
            # - join lines to compensate for that (thanks to davidjb for the fix)
            # Also, look for more than one +CUSD response because of certain modems' strange behaviour
            cusdMatches = list(self.CUSD_REGEX.finditer('\r\n'.join(lines)))
        else:
            # Single standard +CUSD response
            cusdMatches = [self.CUSD_REGEX.match(lines[0])]
        message = None
        sessionActive = True
        if len(cusdMatches) > 1:
            self.log.debug('Multiple +CUSD responses received; filtering...')
            # Some modems issue a non-standard "extra" +CUSD notification for releasing the session
            for cusdMatch in cusdMatches:
                if cusdMatch.group(1) == '2':
                    # Set the session to inactive, but ignore the message
                    self.log.debug('Ignoring "session release" message: %s', cusdMatch.group(2))
                    sessionActive = False
                else:
                    # Not a "session release" message
                    message = cusdMatch.group(2)
                    if sessionActive and cusdMatch.group(1) != '1':
                        sessionActive = False
        else:
            sessionActive = cusdMatches[0].group(1) == '1'
            message = cusdMatches[0].group(2)
        return Ussd(self, sessionActive, message)
1275980
def _parse_command_line():
    """"""
    parser = argparse.ArgumentParser()
    parser.add_argument(
        '--portserver_static_pool',
        type=str,
        default='15000-24999',
        help='Comma separated N-P Range(s) of ports to manage (inclusive).')
    parser.add_argument(
        '--portserver_unix_socket_address',
        type=str,
        default='@unittest-portserver',
        help='Address of AF_UNIX socket on which to listen (first @ is a NUL).')
    parser.add_argument('--verbose',
                        action='store_true',
                        default=False,
                        help='Enable verbose messages.')
    parser.add_argument('--debug',
                        action='store_true',
                        default=False,
                        help='Enable full debug messages.')
    return parser.parse_args(sys.argv[1:])
924421
def get_lvid_vdp_vlan(self, net_uuid, port_uuid):
        

        lvm = self.local_vlan_map.get(net_uuid)
        if not lvm:
            LOG.error("lvm not yet created, get_lvid_vdp_lan "
                      "return error")
            return cconstants.INVALID_VLAN, cconstants.INVALID_VLAN
        vdp_vlan = lvm.get_portid_vlan(port_uuid)
        lvid = lvm.lvid
        LOG.info("Return from lvid_vdp_vlan lvid %(lvid)s vdp_vlan %(vdp)s",
                 {'lvid': lvid, 'vdp': vdp_vlan})
        return lvid, vdp_vlan
582717
def _get_vlan_length(buff):
        """"""
        length = 0
        begin = 12

        while(buff[begin:begin+2] in (EtherType.VLAN.to_bytes(2, 'big'),
                                      EtherType.VLAN_QINQ.to_bytes(2, 'big'))):
            length += 4
            begin += 4

        return length
1308267
def value(self):
        
        # XXX This is doing a DNS lookup every time it's queried; should we
        # call gethostbyname in the constructor and ping that instead (good
        # for consistency, but what if the user *expects* the host to change
        # address?)
        with io.open(os.devnull, 'wb') as devnull:
            try:
                subprocess.check_call(
                    ['ping', '-c1', self.host],
                    stdout=devnull, stderr=devnull)
            except subprocess.CalledProcessError:
                return False
            else:
                return True