Ensure data is serializable.
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)
1170402
def serialize
      {
        name: name,
        value: serialized_ingredient,
        link: essence.try(:link)
      }.delete_if { |_k, v| v.blank? }
    end
1152852
protected void checkJavaSerialization(String variableName, TypedValue value) {
    ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();
    if (value instanceof SerializableValue && !processEngineConfiguration.isJavaSerializationFormatEnabled()) {

      SerializableValue serializableValue = (SerializableValue) value;

      // if Java serialization is prohibited
      if (!serializableValue.isDeserialized()) {

        String javaSerializationDataFormat = Variables.SerializationDataFormats.JAVA.getName();
        String requestedDataFormat = serializableValue.getSerializationDataFormat();

        if (requestedDataFormat == null) {
          // check if Java serializer will be used
          final TypedValueSerializer serializerForValue = TypedValueField.getSerializers()
              .findSerializerForValue(serializableValue, processEngineConfiguration.getFallbackSerializerFactory());
          if (serializerForValue != null) {
            requestedDataFormat = serializerForValue.getSerializationDataformat();
          }
        }

        if (javaSerializationDataFormat.equals(requestedDataFormat)) {
          throw ProcessEngineLogger.CORE_LOGGER.javaSerializationProhibitedException(variableName);
        }
      }
    }
  }
266570
def serialize_list(self, data):
        
        if data is None:
            return ''

        # Check for a ``Data``-like object. We should assume ``True`` (all
        # data gets prepared) unless it's explicitly marked as not.
        if not getattr(data, 'should_prepare', True):
            prepped_data = data.value
        else:
            prepped_data = [self.prepare(item) for item in data]

        final_data = self.wrap_list_response(prepped_data)
        return self.serializer.serialize(final_data)
17559
def _ReferenceFromSerialized(serialized):
  """"""
  if not isinstance(serialized, basestring):
    raise TypeError('serialized must be a string; received %r' % serialized)
  elif isinstance(serialized, unicode):
    serialized = serialized.encode('utf8')
  return entity_pb.Reference(serialized)
444625
def _serialize(self, value, *args, **kwargs):
        """"""
        if value is not None:
            value = super(MSTimestamp, self)._serialize(value, *args) * 1e3
        return value
830817
def serialize_bytes(data):
        """"""
        if not isinstance(data, bytes):
            if isinstance(data, str):
                data = data.encode('utf-8')
            else:
                raise TypeError(
                    'bytes or str expected, not {}'.format(type(data)))

        r = []
        if len(data) < 254:
            padding = (len(data) + 1) % 4
            if padding != 0:
                padding = 4 - padding

            r.append(bytes([len(data)]))
            r.append(data)

        else:
            padding = len(data) % 4
            if padding != 0:
                padding = 4 - padding

            r.append(bytes([
                254,
                len(data) % 256,
                (len(data) >> 8) % 256,
                (len(data) >> 16) % 256
            ]))
            r.append(data)

        r.append(bytes(padding))
        return b''.join(r)
62431
def check_serializable(cls):
    
    if is_named_tuple(cls):
        # This case works.
        return
    if not hasattr(cls, "__new__"):
        print("The class {} does not have a '__new__' attribute and is "
              "probably an old-stye class. Please make it a new-style class "
              "by inheriting from 'object'.")
        raise RayNotDictionarySerializable("The class {} does not have a "
                                           "'__new__' attribute and is "
                                           "probably an old-style class. We "
                                           "do not support this. Please make "
                                           "it a new-style class by "
                                           "inheriting from 'object'."
                                           .format(cls))
    try:
        obj = cls.__new__(cls)
    except Exception:
        raise RayNotDictionarySerializable("The class {} has overridden "
                                           "'__new__', so Ray may not be able "
                                           "to serialize it efficiently."
                                           .format(cls))
    if not hasattr(obj, "__dict__"):
        raise RayNotDictionarySerializable("Objects of the class {} do not "
                                           "have a '__dict__' attribute, so "
                                           "Ray cannot serialize it "
                                           "efficiently.".format(cls))
    if hasattr(obj, "__slots__"):
        raise RayNotDictionarySerializable("The class {} uses '__slots__', so "
                                           "Ray may not be able to serialize "
                                           "it efficiently.".format(cls))
5750
def _serialize(self, value, attr, obj, **kwargs):
        """"""
        if value is None:
            return None

        return int(datetime_to_timestamp(value))
434371
async def serialize(self, value, native=False):
        '''
        
        '''
        if native:
            return self.to_python(value)
        return self.to_data(value)
341979
def _setbytes_safe(self, data, length=None, offset=0):
        """"""
        data = bytearray(data)
        if length is None:
            # Use to the end of the data
            length = len(data)*8 - offset
            self._datastore = ByteStore(data, length, offset)
        else:
            if length + offset > len(data) * 8:
                msg = "Not enough data present. Need {0} bits, have {1}."
                raise CreationError(msg, length + offset, len(data) * 8)
            if length == 0:
                self._datastore = ByteStore(bytearray(0))
            else:
                self._datastore = ByteStore(data, length, offset)
565912
def validate(self, raw_data, **kwargs):
        """"""

        super(DateTimeField, self).validate(raw_data, **kwargs)
        try:
            if isinstance(raw_data, datetime.datetime):
                self.converted = raw_data
            elif self.serial_format is None:
                # parse as iso8601
                self.converted = parse(raw_data)
            else:
                self.converted = datetime.datetime.strptime(raw_data,
                                                            self.serial_format)
            return raw_data
        except (ParseError, ValueError) as e:
            msg = self.messages['parse'] % dict(cls=self.__class__.__name__,
                                                data=raw_data,
                                                format=self.serial_format)
            raise ValidationException(msg, raw_data)
606889
@Override
	protected void serializeTo(RawDataBuffer out)
    {
    	super.serializeTo(out);
        out.writeInt(browserId.asInt());
    }
874453
private void checkSerialize(final HttpServletRequest request) {
    String reqpar = request.getParameter("serialize");

    if (reqpar == null) {
      return;
    }

    HttpSession sess = request.getSession(false);
    Enumeration en = sess.getAttributeNames();

    while (en.hasMoreElements()) {
      String attrname = (String)en.nextElement();
      ObjectOutputStream oo = null;

      info("Attempt to serialize attr " + attrname);
      Object o = sess.getAttribute(attrname);

      try {
        ByteArrayOutputStream bo = new ByteArrayOutputStream();
        oo = new ObjectOutputStream(bo);
        oo.writeObject(o);
        oo.flush();

        info("Serialized object " + attrname + " has size: " + bo.size());
      } catch (Throwable t) {
        t.printStackTrace();
      } finally {
        if (oo != null) {
          try {
            oo.close();
          } catch (Throwable t) {}
        }
      }
    }
  }
804049
def json_serial(obj):
    """"""
    if isinstance(obj, datetime):
        serial = obj.isoformat()
        return serial
    raise TypeError("Type not serializable")
13658
def serialize(obj):
    """"""
    # Record class and module information for deserialization
    result = {'__class__': obj.__class__.__name__}
    try:
        result['__module__'] = obj.__module__
    except AttributeError:
        pass
    # Convert objects to dictionary representation based on type
    if isinstance(obj, datetime.datetime):
        result['year'] = obj.year
        result['month'] = obj.month
        result['day'] = obj.day
        result['hour'] = obj.hour
        result['minute'] = obj.minute
        result['second'] = obj.second
        result['microsecond'] = obj.microsecond
        return result
    if isinstance(obj, StreamingBody):
        result['body'] = obj.read()
        obj._raw_stream = StringIO(result['body'])
        obj._amount_read = 0
        return result
    # Raise a TypeError if the object isn't recognized
    raise TypeError("Type not serializable")
793404
public static void serializeCopyableDataset(State state, CopyableDatasetMetadata copyableDataset) {
    state.setProp(SERIALIZED_COPYABLE_DATASET, copyableDataset.serialize());
  }