build an object given its tag and a byte stream to construct it
from.
973528
protected DERObject buildObject(
        int       tag,
        byte[]    bytes)
        throws IOException
    {
        if ((tag & APPLICATION) != 0)
        {
            return new DERApplicationSpecific(tag, bytes);
        }

        switch (tag)
        {
        case NULL:
            return new DERNull();
        case SEQUENCE | CONSTRUCTED:
            ByteArrayInputStream    bIn = new ByteArrayInputStream(bytes);
            ASN1InputStream         aIn = new ASN1InputStream(bIn);
            ASN1EncodableVector     v = new ASN1EncodableVector();

            DERObject   obj = aIn.readObject();

            while (obj != null)
            {
                v.add(obj);
                obj = aIn.readObject();
            }

            return new DERSequence(v);
        case SET | CONSTRUCTED:
            bIn = new ByteArrayInputStream(bytes);
            aIn = new ASN1InputStream(bIn);
            v = new ASN1EncodableVector();

            obj = aIn.readObject();

            while (obj != null)
            {
                v.add(obj);
                obj = aIn.readObject();
            }

            return new DERSet(v, false);
        case BOOLEAN:
            return new DERBoolean(bytes);
        case INTEGER:
            return new DERInteger(bytes);
        case ENUMERATED:
            return new DEREnumerated(bytes);
        case OBJECT_IDENTIFIER:
            return new DERObjectIdentifier(bytes);
        case BIT_STRING:
            int     padBits = bytes[0];
            byte[]  data = new byte[bytes.length - 1];

            System.arraycopy(bytes, 1, data, 0, bytes.length - 1);

            return new DERBitString(data, padBits);
        case NUMERIC_STRING:
            return new DERNumericString(bytes);
        case UTF8_STRING:
            return new DERUTF8String(bytes);
        case PRINTABLE_STRING:
            return new DERPrintableString(bytes);
        case IA5_STRING:
            return new DERIA5String(bytes);
        case T61_STRING:
            return new DERT61String(bytes);
        case VISIBLE_STRING:
            return new DERVisibleString(bytes);
        case GENERAL_STRING:
            return new DERGeneralString(bytes);
        case UNIVERSAL_STRING:
            return new DERUniversalString(bytes);
        case BMP_STRING:
            return new DERBMPString(bytes);
        case OCTET_STRING:
            return new DEROctetString(bytes);
        case UTC_TIME:
            return new DERUTCTime(bytes);
        case GENERALIZED_TIME:
            return new DERGeneralizedTime(bytes);
        default:
            //
            // with tagged object tag number is bottom 5 bits
            //
            if ((tag & TAGGED) != 0)
            {
                int tagNo = tag & 0x1f;

                if (tagNo == 0x1f)
                {
                    int idx = 0;

                    tagNo = 0;

                    while ((bytes[idx] & 0x80) != 0)
                    {
                        tagNo |= (bytes[idx++] & 0x7f);
                        tagNo <<= 7;
                    }

                    tagNo |= (bytes[idx] & 0x7f);

                    byte[]  tmp = bytes;

                    bytes = new byte[tmp.length - (idx + 1)];
                    System.arraycopy(tmp, idx + 1, bytes, 0, bytes.length);
                }

                if (bytes.length == 0)        // empty tag!
                {
                    if ((tag & CONSTRUCTED) == 0)
                    {
                        return new DERTaggedObject(false, tagNo, new DERNull());
                    }
                    else
                    {
                        return new DERTaggedObject(false, tagNo, new DERSequence());
                    }
                }

                //
                // simple type - implicit... return an octet string
                //
                if ((tag & CONSTRUCTED) == 0)
                {
                    return new DERTaggedObject(false, tagNo, new DEROctetString(bytes));
                }

                bIn = new ByteArrayInputStream(bytes);
                aIn = new ASN1InputStream(bIn);

                DEREncodable dObj = aIn.readObject();

                //
                // explicitly tagged (probably!) - if it isn't we'd have to
                // tell from the context
                //
                if (aIn.available() == 0)
                {
                    return new DERTaggedObject(tagNo, dObj);
                }

                //
                // another implicit object, we'll create a sequence...
                //
                v = new ASN1EncodableVector();

                while (dObj != null)
                {
                    v.add(dObj);
                    dObj = aIn.readObject();
                }

                return new DERTaggedObject(false, tagNo, new DERSequence(v));
            }

            return new DERUnknownTag(tag, bytes);
        }
    }
998164
def build_object(self, obj):
        """"""
        try:
            build_path = self.get_build_path(obj)
            self.request = self.create_request(build_path)
            self.request.user = AnonymousUser()
            self.set_kwargs(obj)
            self.build_file(build_path, self.get_content())
        except Http404:
            # cleanup directory
            self.unbuild_object(obj)
133470
@Override
    public final Object fromBytes(Class targetClass, byte[] bytes)
    {
        try
        {
            if (bytes == null)
            {
                return null;
            }
            if (targetClass != null && targetClass.equals(byte[].class))
            {
                return bytes;
            }
            ObjectInputStream ois;
            ois = new ObjectInputStream(new ByteArrayInputStream(bytes));
            Object o = ois.readObject();
            ois.close();
            return o;
        }
        catch (IOException e)
        {
            log.error("IO exception, Caused by {}.", e);
            throw new PropertyAccessException(e);
        }
        catch (ClassNotFoundException e)
        {
            log.error("Class not found exception, Caused by {}.", e);
            throw new PropertyAccessException(e);
        }

    }
502526
def from_tag(cls, tag, schemas, ext='.rnc'):
        """"""
        return cls(fn=cls.filename(tag, schemas, ext=ext))
320479
public ByteSource buildWrappedByteSource(URL url, int startIndex, int numberResults)
      throws IOException, XMLStreamException, TransformerException {
    Preconditions.checkArgument(startIndex >= 0, "startIndex must not be negative");
    Preconditions.checkArgument(numberResults > 0, "numberResults must be positive");

    StringWriter stringWriter = new StringWriter();

    XMLEventReader xmlEventReader = xmlInputFactory.createXMLEventReader(url.openStream());
    XMLEventWriter xmlEventWriter = xmlOutputFactory.createXMLEventWriter(stringWriter);

    int index = 0;
    boolean included = false;

    while (xmlEventReader.hasNext()) {
      XMLEvent event = xmlEventReader.nextEvent();

      if (event.isStartElement()) {
        String name = ((StartElement) event).getName().getLocalPart();
        if (name.equals(TAG_MUTATE_RESPONSE)) {
          // Write the <mutateResponse> tag.
          xmlEventWriter.add(event);
          continue;
        } else if (name.equals(TAG_RVAL) && ++index > startIndex) {
          // Included the eligible <rval> tags and sub tags by setting the 'included' flag.
          included = true;
        }
      } else if (event.isEndElement()) {
        String name = ((EndElement) event).getName().getLocalPart();
        if (name.equals(TAG_MUTATE_RESPONSE)) {
          // Write the </mutateResponse> tag.
          xmlEventWriter.add(event);
          break;
        } else if (included && name.equals(TAG_RVAL) && index == startIndex + numberResults) {
          // Write the last </rval> tag and append a </mutateResponse> tag, if this has written
          // the specified number of results.
          xmlEventWriter.add(event);
          xmlEventWriter.add(xmlEventFactory.createEndElement("", "", TAG_MUTATE_RESPONSE));
          break;
        }
      }

      if (included) {
        // Write the included tags and events.
        xmlEventWriter.add(event);
      }
    }
    xmlEventReader.close();
    xmlEventWriter.close();

    InputStream truncatedInputStream =
        ByteSource.wrap(stringWriter.toString().getBytes(UTF_8)).openStream();

    // Pass the input stream through a Transformer that removes the XML
    // declaration.
    Transformer transformer = transformerSupplier.get();
    transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
    StreamResult streamResult = new StreamResult(outputStream);
    Source xmlSource = new StreamSource(truncatedInputStream);
    transformer.transform(xmlSource, streamResult);

    return ByteSource.wrap(outputStream.toByteArray());
  }
1002768
def construct_chunk(cls, chunk_type, payload, encoding='utf-8'):
    """"""
    if isinstance(payload, str):
      payload = payload.encode(encoding)
    elif not isinstance(payload, bytes):
      raise TypeError('cannot encode type: {}'.format(type(payload)))

    header = struct.pack(cls.HEADER_FMT, len(payload), chunk_type)
    return header + payload
346223
def process_byte(self, tag):
        """"""
        tag.set_address(self.normal_register.current_address)
        # each address needs 1 byte
        self.normal_register.move_to_next_address(1)
500353
def _from_bytes(bytes, byteorder="big", signed=False):
    """"""
    return int.from_bytes(bytes, byteorder=byteorder, signed=signed)
94593
def from_obj(cls, container, file_obj):
        """"""
        # RFC 1123: Thu, 07 Jun 2007 18:57:07 GMT
        return cls(container,
                   name=file_obj.name,
                   size=file_obj.size,
                   content_type=file_obj.content_type,
                   last_modified=dt_from_header(file_obj.last_modified),
                   obj_type=cls.choose_type(file_obj.content_type))
900152
public Object readObject(Class expectedClass)
        throws IOException
    {
        int tag = is.read();

        switch (tag) {
            case 'N':
                return null;

            case 'T':
                return new Boolean(true);

            case 'F':
                return new Boolean(false);

            case 'I': {
                int b32 = is.read();
                int b24 = is.read();
                int b16 = is.read();
                int b8 = is.read();

                return new Integer((b32 << 24) + (b24 << 16) + (b16 << 8) + b8);
            }

            case 'L': {
                long b64 = is.read();
                long b56 = is.read();
                long b48 = is.read();
                long b40 = is.read();
                long b32 = is.read();
                long b24 = is.read();
                long b16 = is.read();
                long b8 = is.read();

                return new Long((b64 << 56) +
                    (b56 << 48) +
                    (b48 << 40) +
                    (b40 << 32) +
                    (b32 << 24) +
                    (b24 << 16) +
                    (b16 << 8) +
                    b8);
            }

            case 'd': {
                long b64 = is.read();
                long b56 = is.read();
                long b48 = is.read();
                long b40 = is.read();
                long b32 = is.read();
                long b24 = is.read();
                long b16 = is.read();
                long b8 = is.read();

                return new Date((b64 << 56) +
                    (b56 << 48) +
                    (b48 << 40) +
                    (b40 << 32) +
                    (b32 << 24) +
                    (b24 << 16) +
                    (b16 << 8) +
                    b8);
            }

            case 'S':
            case 'X': {
                int b16 = is.read();
                int b8 = is.read();

                int len = (b16 << 8) + b8;

                return readStringImpl(len);
            }

            case 'B': {
                if (tag != 'B')
                    throw expect("bytes", tag);

                int b16 = is.read();
                int b8 = is.read();

                int len = (b16 << 8) + b8;

                ByteArrayOutputStream bos = new ByteArrayOutputStream();

                for (int i = 0; i < len; i++)
                    bos.write(is.read());

                return bos.toByteArray();
            }
            default:
                throw new IOException("unknown code:" + (char) tag);
        }
    }
615507
def build(client, repository_tag, docker_file, tag=None, use_cache=False):
        
        if not isinstance(client, docker.Client):
            raise TypeError("client needs to be of type docker.Client.")

        if not isinstance(docker_file, six.string_types) or not os.path.exists(docker_file):
            # TODO: need to add path stuff for git and http etc.
            raise Exception("docker file path doesn't exist: {0}".format(docker_file))

        if not isinstance(repository_tag, six.string_types):
            raise TypeError('repository must be a string')

        if not tag:
            tag = 'latest'

        if not isinstance(use_cache, bool):
            raise TypeError("use_cache must be a bool. {0} was passed.".format(use_cache))

        no_cache = not use_cache

        if ':' not in repository_tag:
            repository_tag = "{0}:{1}".format(repository_tag, tag)
        file_obj = None
        try:
            if os.path.isfile(docker_file):
                path = os.getcwd()
                docker_file = "./{0}".format(os.path.relpath(docker_file))

                # TODO: support using file_obj in the future. Needed for post pre hooks and the injector.
                # with open(docker_file) as Dockerfile:
                #     testing = Dockerfile.read()
                #     file_obj = BytesIO(testing.encode('utf-8'))

                response = client.build(
                    path=path,
                    nocache=no_cache,
                    # custom_context=True,
                    dockerfile=docker_file,
                    # fileobj=file_obj,
                    tag=repository_tag,
                    rm=True,
                    stream=True
                )
            else:
                response = client.build(path=docker_file, tag=repository_tag, rm=True, nocache=no_cache, stream=True)
        except Exception as e:
            raise e
        finally:
            if file_obj:
                file_obj.close()

        parse_stream(response)
        client.close()

        return Image(client, repository_tag)
307939
def _from_stream(cls, stream, blob, filename=None):
        
        image_header = _ImageHeaderFactory(stream)
        if filename is None:
            filename = 'image.%s' % image_header.default_ext
        return cls(blob, filename, image_header)
21152
def _construct_node(loader, node, base_tag):
    ""
    node = copy.copy(node) # bypass YAML anti recursion
    best_tag = base_tag
    best_fit = 0
    for key, val in loader.DEFAULT_TAGS.iteritems():
        lenk = len(key)
        if lenk <= best_fit:
            continue
        if base_tag.startswith(key):
            best_tag = val + base_tag[lenk:]
            best_fit = lenk
    node.tag = best_tag
    return loader.construct_object(node, deep=True)
595137
def _buildItem(self, elem, cls=None, initpath=None):
        
        # cls is specified, build the object and return
        initpath = initpath or self._initpath
        if cls is not None:
            return cls(self._server, elem, initpath)
        # cls is not specified, try looking it up in PLEXOBJECTS
        etype = elem.attrib.get('type', elem.attrib.get('streamType'))
        ehash = '%s.%s' % (elem.tag, etype) if etype else elem.tag
        ecls = utils.PLEXOBJECTS.get(ehash, utils.PLEXOBJECTS.get(elem.tag))
        # log.debug('Building %s as %s', elem.tag, ecls.__name__)
        if ecls is not None:
            return ecls(self._server, elem, initpath)
        raise UnknownType("Unknown library type <%s type='%s'../>" % (elem.tag, etype))
880603
def serialize(self, tag):
        """"""
        handler = getattr(self, f'serialize_{tag.serializer}', None)
        if handler is None:
            raise TypeError(f'Can\'t serialize {type(tag)!r} instance')
        return handler(tag)
1180051
def _build_object(self, nm, clsdata, parents,**kw):
        logger.debug(util.lazy_format("Building object {0}", nm))

        # To support circular references, we tag objects that we're
        # currently building as "under construction"
        self.under_construction.add(nm)

        props = {}
        defaults = set()

        properties = {}
        for p in parents:
            properties = util.propmerge(properties, p.__propinfo__)

        if 'properties' in clsdata:
            properties = util.propmerge(properties, clsdata['properties'])

        name_translation = {}

        for prop, detail in properties.items():
            logger.debug(util.lazy_format("Handling property {0}.{1}",nm, prop))
            properties[prop]['raw_name'] = prop
            name_translation[prop] = prop.replace('@', '')
            prop = name_translation[prop]

            if detail.get('default', None) is not None:
                defaults.add(prop)

            if detail.get('type', None) == 'object':
                uri = "{0}/{1}_{2}".format(nm,
                                           prop, "<anonymous>")
                self.resolved[uri] = self.construct(
                    uri,
                    detail,
                    (ProtocolBase,))

                props[prop] = make_property(prop,
                                            {'type': self.resolved[uri]},
                                            self.resolved[uri].__doc__)
                properties[prop]['type'] = self.resolved[uri]

            elif 'type' not in detail and '$ref' in detail:
                ref = detail['$ref']
                uri = util.resolve_ref_uri(self.resolver.resolution_scope, ref)
                logger.debug(util.lazy_format(
                    "Resolving reference {0} for {1}.{2}",
                    ref, nm, prop
                ))
                if uri in self.resolved:
                    typ = self.resolved[uri]
                else:
                    typ = self.construct(uri, detail, (ProtocolBase,))

                props[prop] = make_property(prop,
                                            {'type': typ},
                                            typ.__doc__)
                properties[prop]['$ref'] = uri
                properties[prop]['type'] = typ

            elif 'oneOf' in detail:
                potential = self.resolve_classes(detail['oneOf'])
                logger.debug(util.lazy_format("Designating {0} as oneOf {1}", prop, potential))
                desc = detail[
                    'description'] if 'description' in detail else ""
                props[prop] = make_property(prop,
                                            {'type': potential}, desc
                                            )

            elif 'type' in detail and detail['type'] == 'array':
                if 'items' in detail and isinstance(detail['items'], dict):
                    if '$ref' in detail['items']:
                        uri = util.resolve_ref_uri(
                            self.resolver.resolution_scope,
                            detail['items']['$ref'])
                        typ = self.construct(uri, detail['items'])
                        constraints = copy.copy(detail)
                        constraints['strict'] = kw.get('strict')
                        propdata = {
                            'type': 'array',
                            'validator': python_jsonschema_objects.wrapper_types.ArrayWrapper.create(
                                uri,
                                item_constraint=typ,
                                **constraints)}

                    else:
                        uri = "{0}/{1}_{2}".format(nm,
                                                   prop, "<anonymous_field>")
                        try:
                            if 'oneOf' in detail['items']:
                                typ = TypeProxy([
                                    self.construct(uri + "_%s" % i, item_detail)
                                    if '$ref' not in item_detail else
                                    self.construct(util.resolve_ref_uri(
                                        self.resolver.resolution_scope,
                                        item_detail['$ref']),
                                        item_detail)

                                    for i, item_detail in enumerate(detail['items']['oneOf'])]
                                    )
                            else:
                                typ = self.construct(uri, detail['items'])

                            constraints = copy.copy(detail)
                            constraints['strict'] = kw.get('strict')
                            propdata = {'type': 'array',
                                        'validator': python_jsonschema_objects.wrapper_types.ArrayWrapper.create(
                                            uri,
                                            item_constraint=typ,
                                            **constraints)}

                        except NotImplementedError:
                            typ = detail['items']
                            constraints = copy.copy(detail)
                            constraints['strict'] = kw.get('strict')
                            propdata = {'type': 'array',
                                        'validator': python_jsonschema_objects.wrapper_types.ArrayWrapper.create(
                                            uri,
                                            item_constraint=typ,
                                            **constraints)}

                    props[prop] = make_property(prop,
                                                propdata,
                                                typ.__doc__)
                elif 'items' in detail:
                    typs = []
                    for i, elem in enumerate(detail['items']):
                        uri = "{0}/{1}/<anonymous_{2}>".format(nm, prop, i)
                        typ = self.construct(uri, elem)
                        typs.append(typ)

                    props[prop] = make_property(prop,
                                                {'type': typs},
                                                )

            else:
                desc = detail[
                    'description'] if 'description' in detail else ""
                uri = "{0}/{1}".format(nm, prop)
                typ = self.construct(uri, detail)

                props[prop] = make_property(prop, {'type': typ}, desc)

        
        if 'oneOf' in clsdata:
            klasses = self.resolve_classes(clsdata['oneOf'])
            # Need a validation to check that it meets one of them
            props['__validation__'] = {'type': klasses}

        props['__extensible__'] = pattern_properties.ExtensibleValidator(
            nm,
            clsdata,
            self)

        props['__prop_names__'] = name_translation

        props['__propinfo__'] = properties
        required = set.union(*[p.__required__ for p in parents])

        if 'required' in clsdata:
            for prop in clsdata['required']:
                required.add(prop)

        invalid_requires = [req for req in required if req not in props['__propinfo__']]
        if len(invalid_requires) > 0:
          raise validators.ValidationError("Schema Definition Error: {0} schema requires "
                                           "'{1}', but properties are not defined"
                                           .format(nm, invalid_requires))

        props['__required__'] = required
        props['__has_default__'] = defaults
        if required and kw.get("strict"):
            props['__strict__'] = True

        props['__title__'] = clsdata.get('title')
        cls = type(str(nm.split('/')[-1]), tuple(parents), props)
        self.under_construction.remove(nm)

        return cls
780974
function constructFromObject(instance, source) {
  instance.transmitterId = identifiers.format(source.transmitterId);
  instance.transmitterIdType = source.transmitterIdType;
  instance.rssiSignature = source.rssiSignature || [];

  instance.rssiSignature.forEach(function(entry) {
    entry.receiverIdType = entry.receiverIdType || identifiers.TYPE_UNKNOWN;
    entry.rssi = entry.rssi || -Number.MAX_SAFE_INTEGER;
    entry.numberOfDecodings = entry.numberOfDecodings || 1;
    entry.rssiSum = entry.rssiSum || entry.rssi;
  });

  if(source.hasOwnProperty('packets')) {
    instance.packets = source.packets;
  }
  if(source.hasOwnProperty('timestamp')) {
    instance.timestamp = source.timestamp;
  }
  if(source.hasOwnProperty('events')) {
    instance.events = source.events;
  }
  if(source.hasOwnProperty('earliestDecodingTime')) {
    instance.earliestDecodingTime = source.earliestDecodingTime;
  }
  instance.creationTime = new Date().getTime();
}