Writes a Java string with the TC_STRING type marker

        :param obj: The string to print
        :param use_reference: If True, allow writing a reference
964643
def write_string(self, obj, use_reference=True):
        
        if use_reference and isinstance(obj, JavaString):
            try:
                idx = self.references.index(obj)
            except ValueError:
                # String is not referenced: let _writeString store it
                self._writeStruct(">B", 1, (self.TC_STRING,))
                self._writeString(obj, use_reference)
            else:
                # Reuse the referenced string
                logging.debug(
                    "*** Reusing ref 0x%X for String: %s",
                    idx + self.BASE_REFERENCE_IDX,
                    obj,
                )
                self.write_reference(idx)
        else:
            # Don't use references
            self._writeStruct(">B", 1, (self.TC_STRING,))
            self._writeString(obj, use_reference)
20333
def write_any_out(obj)
      case obj
      when Parfait::Word, Symbol
        write_String obj
      when Parfait::BinaryCode
        write_BinaryCode( obj )
      when Parfait::ReturnAddress
        write_return_address( obj )
      when Parfait::Integer
        write_integer( obj )
      when Parfait::Data4
        write_data4( obj )
      else
        write_object( obj )
      end
    end
312326
public static Object print(Context cx, Scriptable thisObj,
                               Object[] args, Function funObj)
    {
        return doPrint(args, funObj, true);
    }
576437
@SuppressWarnings("unchecked")
  public final void writeObject(TextWriterStream out, String label, Object object) throws IOException {
    write(out, label, (O) object);
  }
70088
def writeObject(self, obj, is_proxy=False):
        
        if self.use_proxies and not is_proxy:
            self.writeProxy(obj)

            return

        self.stream.write(TYPE_OBJECT)

        ref = self.context.getObjectReference(obj)

        if ref != -1:
            self._writeInteger(ref << 1)

            return

        self.context.addObject(obj)

        # object is not referenced, serialise it
        kls = obj.__class__
        definition = self.context.getClass(kls)
        alias = None
        class_ref = False # if the class definition is a reference

        if definition:
            class_ref = True
            alias = definition.alias
        else:
            alias = self.context.getClassAlias(kls)
            definition = ClassDefinition(alias)

            self.context.addClass(definition, alias.klass)

        if class_ref:
            self.stream.write(definition.reference)
        else:
            ref = 0

            if definition.encoding != ObjectEncoding.EXTERNAL:
                ref += definition.attr_len << 4

            final_reference = encode_int(ref | definition.encoding << 2 |
                REFERENCE_BIT << 1 | REFERENCE_BIT)

            self.stream.write(final_reference)

            definition.reference = encode_int(
                definition.reference << 2 | REFERENCE_BIT)

            if alias.anonymous:
                self.stream.write('\x01')
            else:
                self.serialiseString(alias.alias)

            # work out what the final reference for the class will be.
            # this is okay because the next time an object of the same
            # class is encoded, class_ref will be True and never get here
            # again.

        if alias.external:
            obj.__writeamf__(DataOutput(self))

            return

        attrs = alias.getEncodableAttributes(obj, codec=self)

        if alias.static_attrs:
            if not class_ref:
                [self.serialiseString(attr) for attr in alias.static_attrs]

            for attr in alias.static_attrs:
                value = attrs.pop(attr)

                self.writeElement(value)

            if definition.encoding == ObjectEncoding.STATIC:
                return

        if definition.encoding == ObjectEncoding.DYNAMIC:
            if attrs:
                for attr, value in attrs.iteritems():
                    if type(attr) in python.int_types:
                        attr = str(attr)

                    self.serialiseString(attr)
                    self.writeElement(value)

            self.stream.write('\x01')
151054
@Override
    public int writeObjectBegin(String type)
        throws IOException
    {
        int newRef = _classRefs.size();
        int ref = _classRefs.put(type, newRef, false);

        if (newRef != ref) {
            if (SIZE < _offset + 32)
                flushBuffer();

            if (ref <= OBJECT_DIRECT_MAX) {
                _buffer[_offset++] = (byte) (BC_OBJECT_DIRECT + ref);
            }
            else {
                _buffer[_offset++] = (byte) 'O';
                writeInt(ref);
            }

            return ref;
        }
        else {
            if (SIZE < _offset + 32)
                flushBuffer();

            _buffer[_offset++] = (byte) 'C';

            writeString(type);

            return -1;
        }
    }
146331
public void writeFields (Object object) {
		Class type = object.getClass();

		Object[] defaultValues = getDefaultValues(type);

		OrderedMap<String, FieldMetadata> fields = getFields(type);
		int i = 0;
		for (FieldMetadata metadata : new OrderedMapValues<FieldMetadata>(fields)) {
			Field field = metadata.field;
			try {
				Object value = field.get(object);
				if (defaultValues != null) {
					Object defaultValue = defaultValues[i++];
					if (value == null && defaultValue == null) continue;
					if (value != null && defaultValue != null) {
						if (value.equals(defaultValue)) continue;
						if (value.getClass().isArray() && defaultValue.getClass().isArray()) {
							equals1[0] = value;
							equals2[0] = defaultValue;
							if (Arrays.deepEquals(equals1, equals2)) continue;
						}
					}
				}

				if (debug) System.out.println("Writing field: " + field.getName() + " (" + type.getName() + ")");
				writer.name(field.getName());
				writeValue(value, field.getType(), metadata.elementType);
			} catch (IllegalAccessException ex) {
				throw new JsonException("Error accessing field: " + field.getName() + " (" + type.getName() + ")", ex);
			} catch (JsonException ex) {
				ex.addTrace(field + " (" + type.getName() + ")");
				throw ex;
			} catch (Exception runtimeEx) {
				JsonException ex = new JsonException(runtimeEx);
				ex.addTrace(field + " (" + type.getName() + ")");
				throw ex;
			}
		}
	}
1269698
def _write_object(self, val, outstream):
        '''
        
        '''
        # first attempt using an existing custom serializer
        serializer = self.__lookup_serializer(getattr(val, '__class__'))
        if serializer is not None:
            serializer.serialize(self, val, outstream)
            return
        
        fields = self._fetch_obj_fields(val)
        validfields = [];
        encodedfields = []
        length = 0;
        for f in fields:
            encoded = self._encode_field_name(val, f)
            if encoded:
                encodedfields.append(encoded)
                validfields.append(f)
                length += 1;
        self.write_object_start(length, outstream)
        count = 0;
        if length > 0:
            mappedname = encodedfields[0]
            if mappedname is not None:
                count += 1
                self.write_object_field(mappedname, getattr(val, validfields[0]), outstream)
            idx = 1
            while idx < length:      
                name = validfields[idx]
                mappedname = encodedfields[idx]
                if mappedname is not None:
                    value = getattr(val, name)
                    if count > 0:
                        self.write_object_field_separator(mappedname, value, outstream)
                    self.write_object_field(mappedname, value, outstream)
                    count += 1
                idx += 1
        self.write_object_end(length, outstream)
685702
def writeObject(self, obj, output, setReferencePosition=False):
        
        def proc_variable_length(format, length):
            result = b''
            if length > 0b1110:
                result += pack('!B', (format << 4) | 0b1111)
                result = self.writeObject(length, result)
            else:
                result += pack('!B', (format << 4) | length)
            return result
        
        def timedelta_total_seconds(td):
            # Shim for Python 2.6 compatibility, which doesn't have total_seconds.
            # Make one argument a float to ensure the right calculation.
            return (td.microseconds + (td.seconds + td.days * 24 * 3600) * 10.0**6) / 10.0**6
       
        if setReferencePosition:
            self.referencePositions[obj] = len(output)
        
        if obj is None:
            output += pack('!B', 0b00000000)
        elif isinstance(obj, BoolWrapper):
            if obj.value is False:
                output += pack('!B', 0b00001000)
            else:
                output += pack('!B', 0b00001001)
        elif isinstance(obj, Uid):
            size = self.intSize(obj.integer)
            output += pack('!B', (0b1000 << 4) | size - 1)
            output += self.binaryInt(obj.integer)
        elif isinstance(obj, (int, long)):
            byteSize = self.intSize(obj)
            root = math.log(byteSize, 2)
            output += pack('!B', (0b0001 << 4) | int(root))
            output += self.binaryInt(obj, as_number=True)
        elif isinstance(obj, FloatWrapper):
            # just use doubles
            output += pack('!B', (0b0010 << 4) | 3)
            output += self.binaryReal(obj)
        elif isinstance(obj, datetime.datetime):
            try:
                timestamp = (obj - apple_reference_date).total_seconds()
            except AttributeError:
                timestamp = timedelta_total_seconds(obj - apple_reference_date)
            output += pack('!B', 0b00110011)
            output += pack('!d', float(timestamp))
        elif isinstance(obj, Data):
            output += proc_variable_length(0b0100, len(obj))
            output += obj
        elif isinstance(obj, StringWrapper):
            output += proc_variable_length(obj.encodingMarker, len(obj))
            output += obj.encodedValue
        elif isinstance(obj, bytes):
            output += proc_variable_length(0b0101, len(obj))
            output += obj
        elif isinstance(obj, HashableWrapper):
            obj = obj.value
            if isinstance(obj, (set, list, tuple)):
                if isinstance(obj, set):
                    output += proc_variable_length(0b1100, len(obj))
                else:
                    output += proc_variable_length(0b1010, len(obj))
            
                objectsToWrite = []
                for objRef in sorted(obj) if isinstance(obj, set) else obj:
                    (isNew, output) = self.writeObjectReference(objRef, output)
                    if isNew:
                        objectsToWrite.append(objRef)
                for objRef in objectsToWrite:
                    output = self.writeObject(objRef, output, setReferencePosition=True)
            elif isinstance(obj, dict):
                output += proc_variable_length(0b1101, len(obj))
                keys = []
                values = []
                objectsToWrite = []
                for key, value in sorted(iteritems(obj)):
                    keys.append(key)
                    values.append(value)
                for key in keys:
                    (isNew, output) = self.writeObjectReference(key, output)
                    if isNew:
                        objectsToWrite.append(key)
                for value in values:
                    (isNew, output) = self.writeObjectReference(value, output)
                    if isNew:
                        objectsToWrite.append(value)
                for objRef in objectsToWrite:
                    output = self.writeObject(objRef, output, setReferencePosition=True)
        return output
174589
private <T> void println(int logLevel, T object) {
    if (logLevel < logConfiguration.logLevel) {
      return;
    }
    String objectString;
    if (object != null) {
      ObjectFormatter<? super T> objectFormatter = logConfiguration.getObjectFormatter(object);
      if (objectFormatter != null) {
        objectString = objectFormatter.format(object);
      } else {
        objectString = object.toString();
      }
    } else {
      objectString = "null";
    }
    printlnInternal(logLevel, objectString);
  }
120723
@Override
  public void write(TextWriterStream out, String label, TextWriteable obj) {
    obj.writeToText(out, label);
  }
802888
function string(obj, fn, ctx) {
  for (var i = 0; i < obj.length; ++i) {
    fn.call(ctx, obj.charAt(i), i);
  }
}
403435
def write_ref_for object
      case object
      when nil
        @stream.write_signed_int_32(0)
      when ::Integer
        @stream.write_signed_int_32(object)
      else
        @stream.write_signed_int_32(Position.get(object) + @linker.platform.loaded_at)
      end
    end
336947
public static String convertObjectToString(Object obj)
    {
        try {
            ByteArrayOutputStream writer = new ByteArrayOutputStream();
            ObjectOutputStream outStream = new ObjectOutputStream(writer);
            outStream.writeObject(obj);
            outStream.flush();
            writer.flush();
            String string = writer.toString(Constant.OBJECT_ENCODING);//Constants.STRING_ENCODING);
            writer.close();
            outStream.close();
            return string;
        } catch (IOException ex)    {
            ex.printStackTrace();   // Never
        }
        return null;
    }
689214
public static void dumpIf(String name, Object obj, Predicate<String> evalPredicate, Predicate<Map.Entry<String, Object>> dumpPredicate, StringPrinter printer) {
		printer.println(name + ": " + obj.getClass().getName());
		fieldsAndGetters(obj, evalPredicate).filter(dumpPredicate).forEach(entry -> {
			printer.println("\t" + entry.getKey() + " = " + entry.getValue());
		});
	}
216348
private void writeHandleXMINillableAttribute(PrintWriter out, String indent, ModelAttribute attribute, String object) {
        ModelMethod method = attribute.method;
        String fieldName = method.field.name;
        String typeName = method.getType().getJavaImplTypeName();
        out.append(indent).append("            ").append(typeName).append(' ').append(fieldName).append(" = new ").append(typeName).append("();").println();
        out.append(indent).append("            parser.parse(").append(fieldName).append(");").println();
        out.append(indent).append("            if (!").append(fieldName).append(".isNil()) {").println();
        out.append(indent).append("                ").append(object).append('.').append(fieldName).append(" = ").append(fieldName).append(';').println();
        out.append(indent).append("            }").println();
        out.append(indent).append("            return true;").println();
    }
339334
def write_object(self, obj, parent=None):
        
        # Transform object
        for transformer in self.object_transformers:
            tmp_object = transformer.transform(obj)
            if tmp_object is not obj:
                obj = tmp_object
                break

        self._writeStruct(">B", 1, (self.TC_OBJECT,))
        cls = obj.get_class()
        self.write_classdesc(cls)

        # Add reference
        self.references.append([])
        logging.debug(
            "*** Adding ref 0x%X for object %s",
            len(self.references) - 1 + self.BASE_REFERENCE_IDX,
            obj,
        )

        all_names = collections.deque()
        all_types = collections.deque()
        tmpcls = cls
        while tmpcls:
            all_names.extendleft(reversed(tmpcls.fields_names))
            all_types.extendleft(reversed(tmpcls.fields_types))
            tmpcls = tmpcls.superclass
        del tmpcls

        logging.debug("<=> Field names: %s", all_names)
        logging.debug("<=> Field types: %s", all_types)

        for field_name, field_type in zip(all_names, all_types):
            try:
                logging.debug(
                    "Writing field %s (%s): %s",
                    field_name,
                    field_type,
                    getattr(obj, field_name),
                )
                self._write_value(field_type, getattr(obj, field_name))
            except AttributeError as ex:
                log_error(
                    "No attribute {0} for object {1}\nDir: {2}".format(
                        ex, repr(obj), dir(obj)
                    )
                )
                raise
        del all_names, all_types

        if (
            cls.flags & self.SC_SERIALIZABLE
            and cls.flags & self.SC_WRITE_METHOD
            or cls.flags & self.SC_EXTERNALIZABLE
            and cls.flags & self.SC_BLOCK_DATA
        ):
            for annotation in obj.annotations:
                log_debug(
                    "Write annotation {0} for {1}".format(repr(annotation), repr(obj))
                )
                if annotation is None:
                    self.write_null()
                else:
                    self.writeObject(annotation)
            self._writeStruct(">B", 1, (self.TC_ENDBLOCKDATA,))