Load attribute values from Plex XML response.
961991
def _loadData(self, data):
        
        self._data = data
        for elem in data:
            id = utils.lowerFirst(elem.attrib['id'])
            if id in self._settings:
                self._settings[id]._loadData(elem)
                continue
            self._settings[id] = Setting(self._server, elem, self._initpath)
556148
def getAttribute(self):
        """"""
        data = self.data
        # Step 1 (skip chars)
        c = data.skip(spaceCharactersBytes | frozenset([b"/"]))
        assert c is None or len(c) == 1
        # Step 2
        if c in (b">", None):
            return None
        # Step 3
        attrName = []
        attrValue = []
        # Step 4 attribute name
        while True:
            if c == b"=" and attrName:
                break
            elif c in spaceCharactersBytes:
                # Step 6!
                c = data.skip()
                break
            elif c in (b"/", b">"):
                return b"".join(attrName), b""
            elif c in asciiUppercaseBytes:
                attrName.append(c.lower())
            elif c is None:
                return None
            else:
                attrName.append(c)
            # Step 5
            c = next(data)
        # Step 7
        if c != b"=":
            data.previous()
            return b"".join(attrName), b""
        # Step 8
        next(data)
        # Step 9
        c = data.skip()
        # Step 10
        if c in (b"'", b'"'):
            # 10.1
            quoteChar = c
            while True:
                # 10.2
                c = next(data)
                # 10.3
                if c == quoteChar:
                    next(data)
                    return b"".join(attrName), b"".join(attrValue)
                # 10.4
                elif c in asciiUppercaseBytes:
                    attrValue.append(c.lower())
                # 10.5
                else:
                    attrValue.append(c)
        elif c == b">":
            return b"".join(attrName), b""
        elif c in asciiUppercaseBytes:
            attrValue.append(c.lower())
        elif c is None:
            return None
        else:
            attrValue.append(c)
        # Step 11
        while True:
            c = next(data)
            if c in spacesAngleBrackets:
                return b"".join(attrName), b"".join(attrValue)
            elif c in asciiUppercaseBytes:
                attrValue.append(c.lower())
            elif c is None:
                return None
            else:
                attrValue.append(c)
155671
def parseresponse(self, xml, localroot = False):
        """"""
        root = parsexmlstring(xml)
        if root.tag != 'clam':
            raise FormatError("CLAM root tag not found")

        self.system_id = root.attrib['id']
        self.system_name = root.attrib['name']
        if 'project' in root.attrib:
            self.project = root.attrib['project']
        else:
            self.project = None
        if 'baseurl' in root.attrib:
            self.baseurl = root.attrib['baseurl']
            if self.project:
                if localroot is True: #implicit, assume CWD
                    self.remote = False
                    self.projecturl = '' #relative directory (assume CWD is project directory, as is the case when wrapper scripts are called)
                elif localroot: #explicit
                    self.remote = False
                    self.projecturl = localroot + '/' + self.project + '/' #explicit directory
                else:
                    self.remote = True #no directory: remote URL
                    self.projecturl = self.baseurl + '/' + self.project + '/'

        if 'user' in root.attrib:
            self.user = root.attrib['user']
        else:
            self.user = None

        self.oauth_access_token = ""
        if 'oauth_access_token' in root.attrib:
            self.oauth_access_token = root.attrib['oauth_access_token']

        for node in root: #pylint: disable=too-many-nested-blocks
            if node.tag == "description":
                self.description = node.text
            elif node.tag == "version":
                self.system_version = node.text
            elif node.tag == "email":
                self.system_email = node.text
            elif node.tag == 'status':
                self.status = int(node.attrib['code'])
                self.statusmessage  = node.attrib['message']
                self.completion  = node.attrib['completion']
                if 'errors' in node.attrib:
                    self.errors = ((node.attrib['errors'] == 'yes') or (node.attrib['errors'] == '1'))
                if 'errormsg' in node.attrib:
                    self.errormsg = node.attrib['errormsg']
            elif node.tag == 'parameters':
                for parametergroupnode in node:
                    if parametergroupnode.tag == 'parametergroup':
                        parameterlist = []
                        for parameternode in parametergroupnode:
                            if parameternode.tag in vars(clam.common.parameters):
                                parameterlist.append(vars(clam.common.parameters)[parameternode.tag].fromxml(parameternode))
                            else:
                                raise Exception("Expected parameter class '" + parameternode.tag + "', but not defined!")
                        self.parameters.append( (parametergroupnode.attrib['name'], parameterlist) )
            elif node.tag == 'corpora':
                for corpusnode in node:
                    if corpusnode.tag == 'corpus':
                        self.corpora.append(corpusnode.value)
            elif node.tag == 'profiles':
                for subnode in node:
                    if subnode.tag == 'profile':
                        self.profiles.append(Profile.fromxml(subnode))
            elif node.tag == 'input':
                for filenode in node:
                    if filenode.tag == 'file':
                        for n in filenode:
                            if n.tag == 'name':
                                self.input.append( CLAMInputFile( self.projecturl, n.text, self.loadmetadata, self.client,True) )
            elif node.tag == 'output':
                for filenode in node:
                    if filenode.tag == 'file':
                        for n in filenode:
                            if n.tag == 'name':
                                self.output.append( CLAMOutputFile( self.projecturl, n.text, self.loadmetadata, self.client ) )
            elif node.tag == 'projects':
                self.projects = []
                for projectnode in node:
                    if projectnode.tag == 'project':
                        self.projects.append(projectnode.text)
            elif node.tag == 'program':
                self.program = Program(self.projecturl, [ int(i) for i in node.attrib['matchedprofiles'].split(',') ] )
                for outputfilenode in node:
                    if outputfilenode.tag == 'outputfile':
                        inputfound = False
                        for inputfilenode in outputfilenode:
                            if inputfilenode.tag == 'inputfile':
                                inputfound = True
                                self.program.add(outputfilenode.attrib['name'],outputfilenode.attrib['template'],inputfilenode.attrib['name'], inputfilenode.attrib['template'])
                        if not inputfound:
                            self.program.add(outputfilenode.attrib['name'],outputfilenode.attrib['template'])
323802
def __parse_xml_response(self, response):
        
        # get xml from response
        xml_response = response[response.find('<?xml'):].replace(' encoding=""', '')
        xml_content = xml.dom.minidom.parseString(xml_response)
        return xml_content.getElementsByTagName('ProcessTextResult')[0].firstChild.nodeValue
849008
def _parse_attributes(self, value):
        """"""
        from zigpy.zcl import foundation as f
        attributes = {}
        attribute_names = {
            1: BATTERY_VOLTAGE_MV,
            3: TEMPERATURE,
            4: XIAOMI_ATTR_4,
            5: XIAOMI_ATTR_5,
            6: XIAOMI_ATTR_6,
            10: PATH
        }
        result = {}
        while value:
            skey = int(value[0])
            svalue, value = f.TypeValue.deserialize(value[1:])
            result[skey] = svalue.value
        for item, value in result.items():
            key = attribute_names[item] \
                if item in attribute_names else "0xff01-" + str(item)
            attributes[key] = value
        if BATTERY_VOLTAGE_MV in attributes:
            attributes[BATTERY_LEVEL] = int(
                self._calculate_remaining_battery_percentage(
                    attributes[BATTERY_VOLTAGE_MV]
                )
            )
        return attributes
898189
def load_xml(self, filepath):
        """"""
        from os import path
        import xml.etree.ElementTree as ET
        #Make sure the file exists and then import it as XML and read the values out.
        uxpath = path.expanduser(filepath)
        if path.isfile(uxpath):
            tree = ET.parse(uxpath)
            vms("Parsing global settings from {}.".format(uxpath))
            root = tree.getroot()

            for child in root:
                if child.tag == "var":
                    self._vardict[child.attrib["name"]] = child.attrib["value"]
770514
def object2xml(self, data):
        
        """
        if not self.__options['encoding']:
            self.set_options(encoding=self.__encoding)

        if self.__options['header_declare']:
            self.__tree.append(self.build_xml_header())

        root = self.__options['root']
        if not root:
            assert (isinstance(data, utils.DictTypes) and len(data) == 1), \
                'if root not specified, the data that dict object and length must be one required.'
            root, data = data.items()[0]

        self.build_tree(data, root)
        xml = unicode(''.join(self.__tree).strip())

        if self.__options['encoding'] != self.__encoding:
            xml = xml.encode(self.__options['encoding'], errors=self.__options['errors'])
        return xml
1196852
def on_tick_data(self, ticks):
        """"""
        for tick in XmlHelper.node_iter(ticks):
            names = [str(tick.getElement(_).name()) for _ in range(tick.numElements())]
            tickmap = {n: XmlHelper.get_child_value(tick, n) for n in names}
            self.response.ticks.append(tickmap)
916688
def from_file(filename, serverEndpoint=ServerEndpoint):
    '''
    
    '''
    tarOutput = parse1('unpack', filename, serverEndpoint,
                       responseMimeType='application/x-tar',
                       services={'meta': '/meta', 'text': '/tika',
                                 'all': '/rmeta/xml', 'unpack': '/unpack/all'},
                       rawResponse=True)
    return _parse(tarOutput)
947149
def loadXml(self, xdata, filepath=''):
        
        # build options
        opts = {'platform': sys.platform}

        mkpath = lambda x: _mkpath(filepath, x, **opts)

        # lookup environment variables
        xenv = xdata.find('environment')
        if xenv is not None:
            env = {}
            log.info('loading environment...')
            for xkey in xenv:
                text = xkey.text
                if text:
                    env[xkey.tag] = os.path.expandvars(text)
                else:
                    env[xkey.tag] = ''

            self.setEnvironment(env)

        # lookup general settings
        xsettings = xdata.find('settings')
        if xsettings is not None:
            for xsetting in xsettings:
                key = xsetting.tag
                val = xsetting.text
                attr = '_' + key
                if hasattr(self, attr):
                    setattr(self, attr, val)

        # lookup options
        xoptions = xdata.find('options')
        if xoptions is not None:
            options = 0
            for xopt in xoptions:
                key = xopt.tag
                value = xopt.text

                if value.lower() == 'true':
                    try:
                        options |= Builder.Options[key]
                    except KeyError:
                        continue

            self._options = options

        # lookup path options
        xpaths = xdata.find('paths')
        if xpaths is not None:
            for xpath in xpaths:
                key = xpath.tag
                path = xpath.text

                if key.endswith('Paths'):
                    path = map(mkpath, path.split(';'))
                else:
                    path = mkpath(path)

                setattr(self, '_' + key, path)

        # lookup executable options
        xexe = xdata.find('executable')
        if xexe is not None:
            exe_tags = {'runtime': '_runtime',
                        'exe': '_executableName',
                        'cli': '_executableCliName',
                        'product': '_productName'}

            for tag, prop in exe_tags.items():
                xtag = xexe.find(tag)
                if xtag is not None:
                    value = xtag.text
                    if value.startswith('.'):
                        value = mkpath(value)

                    setattr(self, prop, value)

            # load exclude options
            xexcludes = xexe.find('excludes')
            if xexcludes is not None:
                excludes = []
                for xexclude in xexcludes:
                    excludes.append(xexclude.text)
                self.setExecutableExcludes(excludes)

            # load build data
            xexedata = xexe.find('data')
            if xexedata is not None:
                data = []
                for xentry in xexedata:
                    if xentry.tag == 'tree':
                        path = xentry.get('path', '')
                        if path:
                            path = mkpath(path)
                        else:
                            path = self.sourcePath()

                        prefix = xentry.get('prefix', os.path.basename(path))
                        excludes = xentry.get('excludes', '').split(';')

                        if excludes:
                            data.append(('tree', (path, prefix, excludes)))
                    else:
                        for xitem in xentry:
                            data.append((xentry.tag, xitem.attrs))

                self.setExecutableData(data)

            # load hidden imports
            xhiddenimports = xexe.find('hiddenimports')
            if xhiddenimports is not None:
                imports = []
                for ximport in xhiddenimports:
                    imports.append(ximport.text)
                self.setHiddenImports(imports)

            # load options
            xopts = xexe.find('options')
            if xopts is not None:
                for xopt in xopts:
                    if xopt.text.startswith('.'):
                        value = mkpath(xopt.text)
                    else:
                        value = xopt.text
                    self._executableOptions[xopt.tag] = value

        # lookup installer options
        xinstall = xdata.find('installer')
        if xinstall is not None:
            install_tags = {'name': '_installName'}

            for tag, prop in install_tags.items():
                xtag = xinstall.find(tag)
                if xtag is not None:
                    value = xtag.text
                    if value.startswith('.'):
                        value = mkpath(value)
                    setattr(self, prop, value)

            xopts = xinstall.find('options')
            if xopts is not None:
                for xopt in xopts:
                    if xopt.text.startswith('.'):
                        value = mkpath(xopt.text)
                    else:
                        value = xopt.text

                    self._installerOptions[xopt.tag] = value

            xdirectories = xinstall.find('additional_directories')
            if xdirectories is not None:
                for xdir in xdirectories:
                    self._installDirectories[xdir.get('path')] = xdir.get('source', '')
233451
def load_data(self, idx):
        """"""
        for name in self:
            ndim = getattr(self, '_%s_ndim' % name)
            diskflag = getattr(self, '_%s_diskflag' % name)
            ramflag = getattr(self, '_%s_ramflag' % name)
            if diskflag:
                file_ = getattr(self, '_%s_file' % name)
                length_tot = 1
                shape = []
                for jdx in range(ndim):
                    length = getattr(self, '_%s_length_%s' % (name, jdx))
                    length_tot *= length
                    shape.append(length)
                raw = file_.read(length_tot*8)
                values = struct.unpack(length_tot*'d', raw)
                if ndim:
                    values = numpy.array(values).reshape(shape)
                else:
                    values = values[0]
            elif ramflag:
                array = getattr(self, '_%s_array' % name)
                values = array[idx]
            if diskflag or ramflag:
                if ndim == 0:
                    setattr(self, name, values)
                else:
                    getattr(self, name)[:] = values
399791
def load(attributes)
      raise ArgumentError, "expected an attributes Hash, got #{attributes.inspect}" unless attributes.is_a?(Hash)
      @prefix_options, attributes = split_options(attributes)
      attributes.each do |key, value|
        @attributes[key.to_s] = typecast_attribute_value(key, value)
      end
      self
    end
1007549
def pickdata(self, data):
        
        """
        attrs = data.get(self.__options['attrkey']) or {}
        values = data.get(self.__options['valuekey']) or ''
        return (attrs, values)
368222
def loadmetadata(self):
        """"""
        if not self.remote:
            metafile = self.projectpath + self.basedir + '/' + self.metafilename()
            if os.path.exists(metafile):
                f = io.open(metafile, 'r',encoding='utf-8')
                xml = "".join(f.readlines())
                f.close()
            else:
                raise IOError(2, "No metadata found, expected " + metafile )
        else:
            if self.client:
                requestparams = self.client.initrequest()
            else:
                requestparams = {}
            response = requests.get(self.projectpath + self.basedir + '/' + self.filename + '/metadata', **requestparams)
            if response.status_code != 200:
                extramsg = ""
                if not self.client: extramsg = "No client was associated with this CLAMFile, associating a client is necessary when authentication is needed"
                raise HTTPError(2, "Can't download metadata for " + self.filename + ". " + extramsg)
            xml = response.text


        #parse metadata
        try:
            self.metadata = CLAMMetaData.fromxml(xml, self) #returns CLAMMetaData object (or child thereof)
        except ElementTree.XMLSyntaxError:
            raise ValueError("Metadata is not XML! Contents: " + xml)
1306701
def load(filename, loader=None, implicit_tuple=True, env={}, schema=None):
  """"""
  with open(filename, 'r') as f:
    return loads(f.read(),
                 filename=filename,
                 loader=loader,
                 implicit_tuple=implicit_tuple,
                 env=env,
                 schema=schema)
161676
def __read_byte_offset(decl, attrs):
        """"""
        offset = attrs.get(XML_AN_OFFSET, 0)
        # Make sure the size is in bytes instead of bits
        decl.byte_offset = int(offset) / 8
814633
def from_response(cls, response, attrs):
        
        proj = response['Projection']
        index = cls(proj['ProjectionType'], response['IndexName'],
                    attrs[response['KeySchema'][1]['AttributeName']],
                    proj.get('NonKeyAttributes'))
        index.response = response
        return index