Serialize an NDEF record to a file-like object.
545831
def _write(self, f):
        """"""
        log.debug("writing ndef record at offset {0}".format(f.tell()))

        record_type = self.type
        record_name = self.name
        record_data = self.data
        
        if record_type == '':
            header_flags = 0; record_name = ''; record_data = ''
        elif record_type.startswith("urn:nfc:wkt:"):
            header_flags = 1; record_type = record_type[12:]
        elif re.match(r'[a-zA-Z0-9-]+/[a-zA-Z0-9-+.]+', record_type):
            header_flags = 2; record_type = record_type
        elif re.match(r'[a-zA-Z][a-zA-Z0-9+-.]*://', record_type):
            header_flags = 3; record_type = record_type
        elif record_type.startswith("urn:nfc:ext:"):
            header_flags = 4; record_type = record_type[12:]
        elif record_type == 'unknown':
            header_flags = 5; record_type = ''
        elif record_type == 'unchanged':
            header_flags = 6; record_type = ''

        type_length = len(record_type)
        data_length = len(record_data)
        name_length = len(record_name)

        if self._message_begin:
            header_flags |= 0x80
        if self._message_end:
            header_flags |= 0x40
        if data_length < 256:
            header_flags |= 0x10
        if name_length > 0:
            header_flags |= 0x08

        if data_length < 256:
            f.write(struct.pack(">BBB", header_flags, type_length, data_length))
        else:
            f.write(struct.pack(">BBL", header_flags, type_length, data_length))
        if name_length > 0:
            f.write(struct.pack(">B", name_length))

        f.write(record_type)
        f.write(record_name)
        f.write(record_data)
68405
def _FieldToJsonObject(self, field, value):
    """"""
    if field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_MESSAGE:
      return self._MessageToJsonObject(value)
    elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_ENUM:
      enum_value = field.enum_type.values_by_number.get(value, None)
      if enum_value is not None:
        return enum_value.name
      else:
        raise SerializeToJsonError('Enum field contains an integer value '
                                   'which can not mapped to an enum value.')
    elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_STRING:
      if field.type == descriptor.FieldDescriptor.TYPE_BYTES:
        # Use base64 Data encoding for bytes
        return base64.b64encode(value).decode('utf-8')
      else:
        return value
    elif field.cpp_type == descriptor.FieldDescriptor.CPPTYPE_BOOL:
      return bool(value)
    elif field.cpp_type in _INT64_TYPES:
      return str(value)
    elif field.cpp_type in _FLOAT_TYPES:
      if math.isinf(value):
        if value < 0.0:
          return _NEG_INFINITY
        else:
          return _INFINITY
      if math.isnan(value):
        return _NAN
    return value
1143532
def dumpf(obj, path, encoding=None):
    """"""
    path = str(path)
    if path.endswith('.gz'):
        with gzip.open(path, mode='wt', encoding=encoding) as f:
            return dump(obj, f)
    else:
        with open(path, mode='wt', encoding=encoding) as f:
            dump(obj, f)
536845
def read_record(self, dtype, shape=1, byteorder=None):
        """"""
        rec = numpy.rec
        try:
            record = rec.fromfile(self._fh, dtype, shape, byteorder=byteorder)
        except Exception:
            dtype = numpy.dtype(dtype)
            if shape is None:
                shape = self._size // dtype.itemsize
            size = product(sequence(shape)) * dtype.itemsize
            data = self._fh.read(size)
            record = rec.fromstring(data, dtype, shape, byteorder=byteorder)
        return record[0] if shape == 1 else record
666263
def __record(self):
        """"""
        f = self.__getFileObj(self.dbf)
        recFmt = self.__recordFmt()
        recordContents = unpack(recFmt[0], f.read(recFmt[1]))
        if recordContents[0] != b(' '):
            # deleted record
            return None
        record = []
        for (name, typ, size, deci), value in zip(self.fields,
                                                                                                recordContents):
            if name == 'DeletionFlag':
                continue
            elif not value.strip():
                record.append(value)
                continue
            elif typ == "N":
                value = value.replace(b('\0'), b('')).strip()
                if value == b(''):
                    value = 0
                elif deci:
                    try:
                        value = float(value)
                    except ValueError:
                        value = 0
                else:
                    value = int(value)
            elif typ == b('D'):
                try:
                    y, m, d = int(value[:4]), int(value[4:6]), int(value[6:8])
                    value = [y, m, d]
                except:
                    value = value.strip()
            elif typ == b('L'):
                value = (value in b('YyTt') and b('T')) or \
                                        (value in b('NnFf') and b('F')) or b('?')
            else:
                value = u(value)
                value = value.strip()
            record.append(value)
        return record
76760
def serialize(self, buf, offset):
        
        fields = [ofproto.oxs_from_user(k, uv) for (k, uv)
                  in self.fields]

        hdr_pack_str = '!HH'
        field_offset = offset + struct.calcsize(hdr_pack_str)
        for (n, value, _) in fields:
            # No mask
            field_offset += ofproto.oxs_serialize(n, value, None, buf,
                                                  field_offset)

        reserved = 0
        length = field_offset - offset
        msg_pack_into(hdr_pack_str, buf, offset, reserved, length)
        self.length = length

        pad_len = utils.round_up(length, 8) - length
        msg_pack_into("%dx" % pad_len, buf, field_offset)

        return length + pad_len
583454
def serialize(self, cls, record):
        
        return json.dumps(record, cls=self.encoder)
1343827
def serialize(self, as_dict=False, sort=None):
        
        files = getattr(self, 'files', self.run())

        if as_dict:
            return dict((fn, p.to_dict()) for fn, p in files.items())

        # generate a list
        data = (p.to_dict() for p in files.values())

        if callable(sort):
            return sorted(data, key=sort)

        elif sort is True:
            return sorted(data)

        return list(data)
1042014
def _encode_data(data):
        """"""
        data = data if data is not None else {}
        data = to_nested_php_args(data)
        files = dict([
            (key, value) for key, value in
            data.items() if isinstance(value, file_type)])
        for fname in files:
            del data[fname]
        return data, files or None, None
528776
def serialize(self, pid, record, links_factory=None, **kwargs):
        
        data = self.serializer.serialize(pid, record, links_factory)
        source = self._get_source(data)
        style = CitationStylesStyle(validate=False, **self._get_args(**kwargs))
        bib = CitationStylesBibliography(style, source, formatter.plain)
        citation = Citation([CitationItem(pid.pid_value)])
        bib.register(citation)

        return self._clean_result(''.join(bib.bibliography()[0]))
1141411
def pif_to_mdf_record(pif_obj, dataset_hit, mdf_acl):
    """"""
    res = {}
    res["mdf"] = _to_meta_data(pif_obj, dataset_hit, mdf_acl)
    res[res["mdf"]["source_name"]] = _to_user_defined(pif_obj)
    return dumps(res)
833704
def __record(self, oid=None):
        """"""
        f = self.__getFileObj(self.dbf)
        recordContents = self.__recStruct.unpack(f.read(self.__recStruct.size))
        if recordContents[0] != b' ':
            # deleted record
            return None
        record = []
        for (name, typ, size, deci), value in zip(self.fields, recordContents):
            if name == 'DeletionFlag':
                continue
            elif typ in ("N","F"):
                # numeric or float: number stored as a string, right justified, and padded with blanks to the width of the field. 
                value = value.split(b'\0')[0]
                value = value.replace(b'*', b'')  # QGIS NULL is all '*' chars
                if value == b'':
                    value = None
                elif deci:
                    try:
                        value = float(value)
                    except ValueError:
                        #not parseable as float, set to None
                        value = None
                else:
                    # force to int
                    try:
                        # first try to force directly to int.
                        # forcing a large int to float and back to int
                        # will lose information and result in wrong nr.
                        value = int(value) 
                    except ValueError:
                        # forcing directly to int failed, so was probably a float.
                        try:
                            value = int(float(value))
                        except ValueError:
                            #not parseable as int, set to None
                            value = None
            elif typ == 'D':
                # date: 8 bytes - date stored as a string in the format YYYYMMDD.
                if value.count(b'0') == len(value):  # QGIS NULL is all '0' chars
                    value = None
                else:
                    try:
                        y, m, d = int(value[:4]), int(value[4:6]), int(value[6:8])
                        value = date(y, m, d)
                    except:
                        value = value.strip()
            elif typ == 'L':
                # logical: 1 byte - initialized to 0x20 (space) otherwise T or F.
                if value == b" ":
                    value = None # space means missing or not yet set
                else:
                    if value in b'YyTt1':
                        value = True
                    elif value in b'NnFf0':
                        value = False
                    else:
                        value = None # unknown value is set to missing
            else:
                # anything else is forced to string/unicode
                value = u(value, self.encoding, self.encodingErrors)
                value = value.strip()
            record.append(value)

        return _Record(self.__fieldposition_lookup, record, oid)
77419
def encode_example(self, image_or_path_or_fobj):
    """"""
    if isinstance(image_or_path_or_fobj, np.ndarray):
      encoded_image = self._encode_image(image_or_path_or_fobj)
    elif isinstance(image_or_path_or_fobj, six.string_types):
      with tf.io.gfile.GFile(image_or_path_or_fobj, 'rb') as image_f:
        encoded_image = image_f.read()
    else:
      encoded_image = image_or_path_or_fobj.read()
    return encoded_image
429515
def make_serializable(data):
    """"""
    if is_serializable(data):
        return data

    # if numpy array convert to list
    try:
        return data.tolist()
    except AttributeError:
        pass
    except Exception as e:
        logger.debug('{} exception ({}): {}'.format(type(e).__name__, e, data))

    # try serializing each child element
    if isinstance(data, dict):
        return {key: make_serializable(value) for key, value in data.items()}
    try:
        return [make_serializable(element) for element in data]
    except TypeError:  # not iterable
        pass
    except Exception:
        logger.debug('Could not serialize {}; converting to string'.format(data))

    # last resort: convert to string
    return str(data)
1128983
def preprocess_record(self, pid, record, links_factory=None, **kwargs):
        """"""
        links_factory = links_factory or (lambda x, record=None, **k: dict())
        metadata = copy.deepcopy(record.replace_refs()) if self.replace_refs \
            else record.dumps()
        return dict(
            pid=pid,
            metadata=metadata,
            links=links_factory(pid, record=record, **kwargs),
            revision=record.revision_id,
            created=(pytz.utc.localize(record.created).isoformat()
                     if record.created else None),
            updated=(pytz.utc.localize(record.updated).isoformat()
                     if record.updated else None),
        )
210342
def from_record(cls, record, crs):
        """"""
        if 'type' not in record:
            raise TypeError("The data isn't a valid record.")

        return cls(to_shape(record), crs)
802068
def get_data_blob(self, rawtx):
        """"""
        tx = deserialize.tx(rawtx)
        data = control.get_data_blob(tx)
        return serialize.data(data)