Serializes NRRD fields
426428
function serializeField(prop, value, dimension, spaceDimension) {
    var line;
    var propNRRD = mapJavascriptToNRRD(prop);
    switch(prop) {
    // nrrd-js stuff: skip
    case 'data':
    case 'buffer':
    case 'keys':
    case 'version':
        break;
    // Literal (uninterpreted) fields
    case 'content':
    case 'number':
    case 'sampleUnits':
    case 'space':
        line = propNRRD + ": " + value;
        break;
    // Integers (no infinity or whatever, just a plain integer, so the default serialization is good enough)
    case 'blockSize':
    case 'lineSkip':
    case 'byteSkip':
    case 'dimension':
    case 'spaceDimension':
        assert((typeof value) == "number" || value instanceof Number, "Field " + prop + " should at least contain a number!");
        line = propNRRD + ": " + value;
        break;
    // Floats (default serialization is good enough, as NaN contains nan, ignoring case, and similarly for Infinity inf)
    case 'min':
    case 'max':
    case 'oldMin':
    case 'oldMax':
        assert((typeof value) == "number" || value instanceof Number, "Field " + prop + " should contain a number!");
        line = propNRRD + ": " + value;
        break;
    // Vectors
    case 'spaceOrigin':
        assert(value.length === spaceDimension, "Field " + prop + " should be a list with length equal to the space dimension!");
        value.forEach(function (val) { assert((typeof val) == "number" || val instanceof Number, "Field " + prop + " should be a list of numbers!"); });
        line = propNRRD + ": (" + value.join(",") + ")";
        break;
    // Lists of strings
    case 'labels':
    case 'units':
    case 'spaceUnits':
        assert(value.length !== undefined && value.length == dimension, "Field " + prop + " should be a list with length equal to the dimension!");
        value.forEach(function (val) { assert((typeof val) == "string" || val instanceof String, "Field " + prop + " should be a list of numbers!"); });
        line = propNRRD + ": " + value.map(serializeNRRDQuotedString).join(" ");
        break;
    // Lists of integers
    case 'sizes':
        assert(value.length !== undefined && value.length == dimension, "Field " + prop + " should be a list with length equal to the dimension!");
        value.forEach(function (val) { assert((typeof val) == "number" || val instanceof Number, "Field " + prop + " should be a list of numbers!"); });
        line = propNRRD + ": " + value.join(" ");
        break;
    // Lists of floats
    case 'spacings':
    case 'thicknesses':
    case 'axisMins':
    case 'axisMaxs':
        assert(value.length !== undefined && value.length == dimension, "Field " + prop + " should be a list with length equal to the dimension!");
        value.forEach(function (val) { assert((typeof val) == "number" || val instanceof Number, "Field " + prop + " should be a list of numbers!"); });
        line = propNRRD + ": " + value.join(" ");
        break;
    // Lists of vectors (dimension sized)
    case 'spaceDirections':
        assert(value.length !== undefined && value.length === dimension, "Field " + prop + " should be a list with length equal to the dimension!");
        value.forEach(function (vec) {
          assert(vec === null || (vec.length !== undefined && vec.length === spaceDimension), "The elements of field " + prop + " should be lists with length equal to the space dimension!");
          if (vec !== null) vec.forEach(function (val) { assert((typeof val) == "number" || val instanceof Number, "The elements of field " + prop + " should be lists of numbers!"); });
        });
        line = propNRRD + ": " + value.map(function(vec) { return vec === null ? "none" : ("(" + vec.join(",") + ")"); }).join(" ");
        break;
    // Lists of vectors (space dimension sized)
    case 'measurementFrame':
        assert(value.length !== undefined && value.length === spaceDimension, "Field " + prop + " should be a list with length equal to the space dimension!");
        value.forEach(function (vec) {
          assert(vec === null || (vec.length !== undefined && vec.length === spaceDimension), "The elements of field " + prop + " should be lists with length equal to the space dimension!");
          if (vec !== null) vec.forEach(function (val) { assert((typeof val) == "number" || val instanceof Number, "The elements of field " + prop + " should be lists of numbers!"); });
        });
        line = propNRRD + ": " + value.map(function(vec) { return vec === null ? "none" : ("(" + vec.join(",") + ")"); }).join(" ");
        break;
    // One-of-a-kind fields
    case 'type':
        assert((typeof value) == "string" || value instanceof String, "Field " + prop + " should contain a string!");
        line = propNRRD + ": " + value;
        break;
    case 'encoding':
        assert((typeof value) == "string" || value instanceof String, "Field " + prop + " should contain a string!");
        line = propNRRD + ": " + value;
        break;
    case 'endian':
        assert((typeof value) == "string" || value instanceof String, "Field " + prop + " should contain a string!");
        line = propNRRD + ": " + value;
        break;
    case 'dataFile':
        if (value.length || (value.files && 'subdim' in value)) {
            // List of data files: skip for now
        } else {
            line = propNRRD + ": " + serializeNRRDDataFile(value);
        }
        break;
    case 'centers':
        assert(value.length !== undefined && value.length == dimension, "Field " + prop + " should be a list with length equal to the dimension!");
        line = propNRRD + ": " + value.map(serializeNRRDOptional).join(" ");
        break;
    case 'kinds':
        assert(value.length !== undefined && value.length == dimension, "Field " + prop + " should be a list with length equal to the dimension!");
        line = propNRRD + ": " + value.map(serializeNRRDOptional).join(" ");
        break;
    // Something unknown
    default:
        console.warn("Unrecognized NRRD field: " + prop + ", skipping.");
    }
    return line;
}
1080880
def serialize(self):
        """"""
        res = []
        for _sort in self.sort_orders:
            res.append(_sort.serialize())
        return res or None
878489
def serialize(self, queryset, **options):
        
        self.options = options

        self.stream = options.pop("stream", six.StringIO())
        self.selected_fields = options.pop("fields", None)
        self.use_natural_foreign_keys = options.pop('use_natural_foreign_keys', False)
        self.use_natural_primary_keys = options.pop('use_natural_primary_keys', False)
        progress_bar = self.progress_class(
            options.pop('progress_output', None), options.pop('object_count', 0)
        )

        self.start_serialization()
        self.first = True
        for count, obj in enumerate(queryset, start=1):
            self.start_object(obj)
            # Use the concrete parent class' _meta instead of the object's _meta
            # This is to avoid local_fields problems for proxy models. Refs #17717.
            concrete_model = obj._meta.concrete_model
            for field in self.get_local_fields(concrete_model):
                if field.serialize:
                    if field.remote_field is None:
                        if self.selected_fields is None or field.attname in self.selected_fields:
                            self.handle_field(obj, field)
                    else:
                        if self.selected_fields is None or field.attname[:-3] in self.selected_fields:
                            self.handle_fk_field(obj, field)
            for field in self.get_local_m2m_fields(concrete_model):
                if field.serialize:
                    if self.selected_fields is None or field.attname in self.selected_fields:
                        self.handle_m2m_field(obj, field)
            self.end_object(obj)
            progress_bar.update(count)
            if self.first:
                self.first = False
        self.end_serialization()
        return self.getvalue()
766886
def serialize(self, pid, record, links_factory=None):
        
        return simpledc.tostring(
            self.transform_record(pid, record, links_factory))
1064709
def _serialize(self, value, key, obj):
        
        param_values = {}
        for name, attr_tpl in iteritems(self.params):
            attr_name = _tpl(str(attr_tpl))
            if attr_name:
                attribute_value = _get_value(obj, attr_name, default=missing)
                if attribute_value is None:
                    return None
                if attribute_value is not missing:
                    param_values[name] = attribute_value
                else:
                    raise AttributeError(
                        "{attr_name!r} is not a valid "
                        "attribute of {obj!r}".format(attr_name=attr_name, obj=obj)
                    )
            else:
                param_values[name] = attr_tpl
        return url_for(self.endpoint, **param_values)
1300373
public void serialize(@Nonnull Iterable<QueryResult> results, @Nonnull OutputStream out) throws IOException {
		JsonGenerator g = jsonFactory.createGenerator(out, JsonEncoding.UTF8);
		g.writeStartObject();
		g.writeNumberField("timestamp", System.currentTimeMillis() / 1000);
		g.writeNumberField("proto_version", STACKDRIVER_PROTOCOL_VERSION);
		g.writeArrayFieldStart("data");

		for (QueryResult metric : results) {
			g.writeStartObject();
			g.writeStringField("name", metric.getName());
			if (instanceId != null && !instanceId.isEmpty()) {
				g.writeStringField("instance", instanceId);
			}
			g.writeNumberField("collected_at", metric.getEpoch(TimeUnit.SECONDS));
			if (metric.getValue() instanceof Integer) {
				g.writeNumberField("value", (Integer) metric.getValue());
			} else if (metric.getValue() instanceof Long) {
				g.writeNumberField("value", (Long) metric.getValue());
			} else if (metric.getValue() instanceof Float) {
				g.writeNumberField("value", (Float) metric.getValue());
			} else if (metric.getValue() instanceof Double) {
				g.writeNumberField("value", (Double) metric.getValue());
			}
			g.writeEndObject();
		}

		g.writeEndArray();
		g.writeEndObject();
		g.flush();
		g.close();
	}
887895
def serialize(self, pid, record, links_factory=None, **kwargs):
        
        return json.dumps(
            self.transform_record(pid, record, links_factory, **kwargs),
            **self._format_args())
664244
def dump_to_rsb(params: dict, times: np.ndarray, data: np.ndarray) -> bytes:
    
    assert isinstance(times, np.ndarray)
    assert times.ndim == 1
    assert isinstance(data, np.ndarray)
    assert data.ndim == 2
    assert len(data) == len(times)

    params['b_size'] = data.shape[1]
    params['events_num'] = data.shape[0]

    start = int(times.min() * 1e-9)
    end = int(times.max() * 1e-9)

    if 'start_time' not in params:
        params['start_time'] = datetime.fromtimestamp(start).isoformat()

    if 'end_time' not in params:
        params['end_time'] = datetime.fromtimestamp(end).isoformat()

    text_header = bytearray(5120)
    text = serialise_to_rsh(params).encode('cp1251')
    text_header[:len(text)] = text

    params['text_header_size'] = len(text)

    binary_header = serialize_to_rsb(params)

    bin_data = b''

    ch_num = params['channel_number']
    ev_size = params['b_size']
    for i, event_data in enumerate(data):
        event = bytearray(
            np.zeros(96 + 2 * ch_num * ev_size, np.byte).tostring())
        text_hdr = datetime.fromtimestamp(int(times[i] * 10e-9)).isoformat()

        event[:len(text_hdr)] = text_hdr.encode('cp1251')
        event[64:68] = struct.pack('I', i)
        event[72:80] = struct.pack('Q', int(times[i] * 10e-9))
        event[80:88] = struct.pack('Q', int(times[i]))

        event[96:] = event_data.astype(np.int16).tostring()
        bin_data += event

    return bytes(text_header + binary_header + bin_data)
1030408
public void serializePrimitive(S rec, String fieldName, boolean value) {
        serializePrimitive(rec, fieldName, Boolean.valueOf(value));
    }
68565
@Deprecated
    @Override
    @SuppressWarnings({ "unchecked", "rawtypes" })
    public void serializeObject(JsonWriteGenericRecord record, String fieldName, String typeName, Object obj) {
        try {
            if (obj == null) {
                record.getGenerator().writeObjectField(fieldName, null);
                return;
            }
            if (isPrimitive(obj.getClass())) {
                serializePrimitive(record, fieldName, obj);
                return;
            }
            record.getGenerator().writeFieldName(fieldName);
            record.getGenerator().writeStartObject();

            NFTypeSerializer fieldSerializer = getSerializer(typeName);
            JsonWriteGenericRecord fieldRecord = new JsonWriteGenericRecord(record.getGenerator());
            fieldSerializer.serialize(obj, fieldRecord);
            record.getGenerator().writeEndObject();
        } catch (Exception ex) {
            throw new RuntimeException(ex);
        }
    }
1227699
private final void serializeObjectNoSCO(Object v, ZooFieldDef def) {
        // Write class/null info
        if (v == null) {
            writeClassInfo(null, null);
            out.skipWrite(def.getLength()-1);
            if (def.isString()) {
            	scos.add(null);
                return;
            }
            return;
        }
        
        //Persistent capable objects do not need to be serialized here.
        //If they should be serialized, then it will happen in serializeFields()
        Class<? extends Object> cls = v.getClass();
        writeClassInfo(cls, v);

        if (isPersistentCapable(cls)) {
            serializeOid((ZooPC) v);
            return;
        } else if (String.class == cls) {
        	scos.add(v);
        	String s = (String)v; 
        	out.writeLong(BitTools.toSortableLong(s));
            return;
        } else if (Date.class == cls) {
            out.writeLong(((Date) v).getTime());
            return;
        } else if (GenericObject.class.isAssignableFrom(cls)) {
        	serializeOid((GenericObject)v);
        	return;
        } else if (GOProxy.class.isAssignableFrom(cls)) {
        	serializeOid(((GOProxy)v).getGenericObject());
        	return;
        }
        
        throw new IllegalArgumentException("Illegal class: " + cls + " from " + def);
    }
114420
function serializeToJRD(descriptor) {
  var obj = {};
  if (descriptor.expires) { obj.expires = xsdDateTimeString(descriptor.expires); }
  if (descriptor.subject) { obj.subject = descriptor.subject; }
  if (descriptor.aliases.length > 0) {
    obj.aliases = [];
    descriptor.aliases.forEach(function(alias) {
      obj.aliases.push(alias);
    });
  }
  
  if (descriptor.properties.length > 0) {
    obj.properties = {};
    descriptor.properties.forEach(function(key, value) {
      obj.properties[key] = value;
    }, { flatten: true });
  }
  
  if (descriptor.links.length > 0) {
    obj.links = [];
    descriptor.links.forEach(function(link) {
      var l = {};
      if (link.rel) { l.rel = link.rel; }
      if (link.href) { l.href = link.href; }
      if (link.template) { l.template = link.template; }
      if (link.type) { l.type = link.type; }
      
      if (link.titles.length > 0) {
        l.titles = {};
        link.titles.forEach(function(lang, title) {
          if (lang === '_') {
            l.titles['default'] = title;
          } else {
            l.titles[lang] = title;
          }
        }, { flatten: true });
      }
      
      if (link.properties.length > 0) {
        l.properties = {};
        link.properties.forEach(function(key, value) {
          l.properties[key] = value;
        }, { flatten: true });
      }
      
      obj.links.push(l);
    });
  }
  
  return JSON.stringify(obj);
}
956002
def serialize(self):
        
        return {"hstart": self.hstart, "mstart": self.mstart,
                "hend": self.hend, "mend": self.mend,
                "is_valid": self.is_valid}
605742
@Override
	protected void serializeTo(RawDataBuffer out)
    {
        super.serializeTo(out);
        out.writeInt(sessionId.asInt());
    }
268939
private final void serializeCommonFields (final ByteBuffer byteBuffer, final int index) {
        byteBuffer.position(index);
        byteBuffer.put(descriptorType.getValue());
        byteBuffer.put((byte) additionalLength);
    }
1157182
async def serialize(self, native=False):
        '''
        
        '''
        data = {}
        # iterate through all fields
        for field_name, field in self._fields.items():
            # serialize field data
            raw_data = self._data.get(field_name)
            # add field's data to model data based on projection settings
            if field._projection != None:  # noqa E711
                field_data = await field.serialize(raw_data, native)
                if field_data:
                    data[field_name] = field_data
                elif field._projection == True: # noqa E711
                    data[field_name] = None

        # iterate through all export methods
        for name, func in self._serialize_methods.items():
            data[name] = await func(self)
        return data
706546
function serialize(hrp, data) {
  let chk = 1;
  let i;

  for (i = 0; i < hrp.length; i++) {
    const ch = hrp.charCodeAt(i);

    if ((ch >> 5) === 0)
      throw new Error('Invalid bech32 character.');

    chk = polymod(chk) ^ (ch >> 5);
  }

  if (i + 7 + data.length > 90)
    throw new Error('Invalid bech32 data length.');

  chk = polymod(chk);

  let str = '';

  for (let i = 0; i < hrp.length; i++) {
    const ch = hrp.charCodeAt(i);
    chk = polymod(chk) ^ (ch & 0x1f);
    str += hrp[i];
  }

  str += '1';

  for (let i = 0; i < data.length; i++) {
    const ch = data[i];

    if ((ch >> 5) !== 0)
      throw new Error('Invalid bech32 value.');

    chk = polymod(chk) ^ ch;
    str += CHARSET[ch];
  }

  for (let i = 0; i < 6; i++)
    chk = polymod(chk);

  chk ^= 1;

  for (let i = 0; i < 6; i++)
    str += CHARSET[(chk >>> ((5 - i) * 5)) & 0x1f];

  return str;
}