text:
package tests.api.java.io;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.Externalizable;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.NotActiveException;
import java.io.NotSerializableException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;
import java.io.ObjectStreamException;
import java.io.ObjectStreamField;
import java.io.OutputStream;
import java.io.Serializable;
import java.io.SerializablePermission;
import java.io.WriteAbortedException;
import java.security.Permission;
import java.util.Arrays;

import tests.support.Support_ASimpleOutputStream;
import tests.support.Support_IOTestSecurityManager;
import tests.support.Support_OutputStream;
import dalvik.annotation.TestLevel;
import dalvik.annotation.TestTargetClass;
import dalvik.annotation.TestTargetNew;
import dalvik.annotation.TestTargets;

@TestTargetClass(
        value = ObjectOutputStream.class,
        untestedMethods = {
            @TestTargetNew(
                    method = "annotateClass",
                    args = {Class.class},
                    level = TestLevel.NOT_NECESSARY,
                    notes = "According to specification, the implementation " +
                            "does nothing."
            ),
            @TestTargetNew(
                    method = "annotateProxyClass",
                    args = {Class.class},
                    level = TestLevel.NOT_NECESSARY,
                    notes = "According to specification, the implementation " +
                            "does nothing."
            )
        }
)
public class ObjectOutputStreamTest extends junit.framework.TestCase implements
        Serializable {

    static final long serialVersionUID = 1L;

    java.io.File f;

    public class SerializableTestHelper implements Serializable {
        public String aField1;

        public String aField2;

        SerializableTestHelper() {
            aField1 = null;
            aField2 = null;
        }

        SerializableTestHelper(String s, String t) {
            aField1 = s;
            aField2 = t;
        }

        private void readObject(ObjectInputStream ois) throws IOException {
            // note aField2 is not read
            try {
                ObjectInputStream.GetField fields = ois.readFields();
                aField1 = (String) fields.get("aField1", "Zap");
            } catch (Exception e) {
            }
        }

        private void writeObject(ObjectOutputStream oos) throws IOException {
            // note aField2 is not written
            ObjectOutputStream.PutField fields = oos.putFields();
            fields.put("aField1", aField1);
            oos.writeFields();
        }

        public String getText1() {
            return aField1;
        }

        public void setText1(String s) {
            aField1 = s;
        }

        public String getText2() {
            return aField2;
        }

        public void setText2(String s) {
            aField2 = s;
        }
    }

    private static class SpecTestSuperClass implements Runnable, Serializable {
        static final long serialVersionUID = 1L;
        protected java.lang.String instVar;

        public void run() {
        }
    }

    private static class SpecTest extends SpecTestSuperClass implements
            Cloneable, Serializable {
        static final long serialVersionUID = 1L;

        public java.lang.String instVar1;

        public static java.lang.String staticVar1;

        public static java.lang.String staticVar2;
        {
            instVar1 = "NonStaticInitialValue";
        }
        static {
            staticVar1 = "StaticInitialValue";
            staticVar1 = new String(staticVar1);
        }

        public Object method(Object objParam, Object objParam2) {
            return new Object();
        }

        public boolean method(boolean bParam, Object objParam) {
            return true;
        }

        public boolean method(boolean bParam, Object objParam, Object objParam2) {
            return true;
        }

    }

    private static class SpecTestSubclass extends SpecTest implements
            Serializable {
        static final long serialVersionUID = 1L;
        public transient java.lang.String transientInstVar = "transientValue";
    }

    private static class ReadWriteObject implements java.io.Serializable {
        static final long serialVersionUID = 1L;

        public boolean calledWriteObject = false;

        public boolean calledReadObject = false;

        public ReadWriteObject() {
            super();
        }

        private void readObject(java.io.ObjectInputStream in)
                throws java.io.IOException, ClassNotFoundException {
            calledReadObject = true;
            in.readObject();
        }

        private void writeObject(java.io.ObjectOutputStream out)
                throws java.io.IOException {
            calledWriteObject = true;
            out.writeObject(FOO);
        }
    }

    private static class PublicReadWriteObject implements java.io.Serializable {
        public boolean calledWriteObject = false;

        public boolean calledReadObject = false;

        public PublicReadWriteObject() {
            super();
        }

        public void readObject(java.io.ObjectInputStream in)
                throws java.io.IOException, ClassNotFoundException {
            calledReadObject = true;
            in.readObject();
        }

        public void writeObject(java.io.ObjectOutputStream out)
                throws java.io.IOException {
            calledWriteObject = true;
            out.writeObject(FOO);
        }
    }

    private static class FieldOrder implements Serializable {
        String aaa1NonPrimitive = "aaa1";

        int bbb1PrimitiveInt = 5;

        boolean aaa2PrimitiveBoolean = true;

        String bbb2NonPrimitive = "bbb2";
    }

    private static class JustReadObject implements java.io.Serializable {
        public boolean calledReadObject = false;

        public JustReadObject() {
            super();
        }

        private void readObject(java.io.ObjectInputStream in)
                throws java.io.IOException, ClassNotFoundException {
            calledReadObject = true;
            in.defaultReadObject();
        }
    }

    private static class JustWriteObject implements java.io.Serializable {
        static final long serialVersionUID = 1L;
        public boolean calledWriteObject = false;

        public JustWriteObject() {
            super();
        }

        private void writeObject(java.io.ObjectOutputStream out)
                throws java.io.IOException, ClassNotFoundException {
            calledWriteObject = true;
            out.defaultWriteObject();
        }
    }

    private static class ClassBasedReplacementWhenDumping implements
            java.io.Serializable {
        public boolean calledReplacement = false;

        public ClassBasedReplacementWhenDumping() {
            super();
        }

        private Object writeReplace() {
            calledReplacement = true;
            return FOO; // Replacement is a String
        }
    }

    private static class MultipleClassBasedReplacementWhenDumping implements
            java.io.Serializable {
        private static class C1 implements java.io.Serializable {
            private Object writeReplace() {
                return new C2();
            }
        }

        private static class C2 implements java.io.Serializable {
            private Object writeReplace() {
                return new C3();
            }
        }

        private static class C3 implements java.io.Serializable {
            private Object writeReplace() {
                return FOO;
            }
        }

        public MultipleClassBasedReplacementWhenDumping() {
            super();
        }

        private Object writeReplace() {
            return new C1();
        }
    }

    private static class ClassBasedReplacementWhenLoading implements
            java.io.Serializable {
        public ClassBasedReplacementWhenLoading() {
            super();
        }

        private Object readResolve() {
            return FOO; // Replacement is a String
        }
    }

    private static class ClassBasedReplacementWhenLoadingViolatesFieldType
            implements java.io.Serializable {
        public ClassBasedReplacementWhenLoading classBasedReplacementWhenLoading = new ClassBasedReplacementWhenLoading();

        public ClassBasedReplacementWhenLoadingViolatesFieldType() {
            super();
        }
    }

    private static class MyExceptionWhenDumping implements java.io.Serializable {
        private static class MyException extends java.io.IOException {
        };

        public boolean anInstanceVar = false;

        public MyExceptionWhenDumping() {
            super();
        }

        private void readObject(java.io.ObjectInputStream in)
                throws java.io.IOException, ClassNotFoundException {
            in.defaultReadObject();
        }

        private void writeObject(java.io.ObjectOutputStream out)
                throws java.io.IOException, ClassNotFoundException {
            throw new MyException();
        }
    }

    private static class NonSerializableExceptionWhenDumping implements
            java.io.Serializable {
        public Object anInstanceVar = new Object();

        public NonSerializableExceptionWhenDumping() {
            super();
        }
    }

    private static class MyUnserializableExceptionWhenDumping implements
            java.io.Serializable {
        private static class MyException extends java.io.IOException {
            private Object notSerializable = new Object();
        };

        public boolean anInstanceVar = false;

        public MyUnserializableExceptionWhenDumping() {
            super();
        }

        private void readObject(java.io.ObjectInputStream in)
                throws java.io.IOException, ClassNotFoundException {
            in.defaultReadObject();
        }

        private void writeObject(java.io.ObjectOutputStream out)
                throws java.io.IOException, ClassNotFoundException {
            throw new MyException();
        }
    }

    private static class WithUnmatchingSerialPersistentFields implements
            java.io.Serializable {
        private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField(
                "value", String.class) };

        public int anInstanceVar = 5;

        public WithUnmatchingSerialPersistentFields() {
            super();
        }
    }

    private static class WithMatchingSerialPersistentFields implements
            java.io.Serializable {
        private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField(
                "anInstanceVar", String.class) };

        public String anInstanceVar = FOO + FOO;

        public WithMatchingSerialPersistentFields() {
            super();
        }
    }

    private static class SerialPersistentFields implements java.io.Serializable {
        private static final String SIMULATED_FIELD_NAME = "text";

        private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField(
                SIMULATED_FIELD_NAME, String.class) };

        public int anInstanceVar = 5;

        public SerialPersistentFields() {
            super();
        }

        private void readObject(java.io.ObjectInputStream in)
                throws java.io.IOException, ClassNotFoundException {
            ObjectInputStream.GetField fields = in.readFields();
            anInstanceVar = Integer.parseInt((String) fields.get(
                    SIMULATED_FIELD_NAME, "-5"));
        }

        private void writeObject(java.io.ObjectOutputStream out)
                throws java.io.IOException, ClassNotFoundException {
            ObjectOutputStream.PutField fields = out.putFields();
            fields.put(SIMULATED_FIELD_NAME, Integer.toString(anInstanceVar));
            out.writeFields();
        }
    }

    private static class WriteFieldsWithoutFetchingPutFields implements
            java.io.Serializable {
        private static final String SIMULATED_FIELD_NAME = "text";

        private static final ObjectStreamField[] serialPersistentFields = { new ObjectStreamField(
                SIMULATED_FIELD_NAME, String.class) };

        public int anInstanceVar = 5;

        public WriteFieldsWithoutFetchingPutFields() {
            super();
        }

        private void readObject(java.io.ObjectInputStream in)
                throws java.io.IOException, ClassNotFoundException {
            in.readFields();
        }

        private void writeObject(java.io.ObjectOutputStream out)
                throws java.io.IOException, ClassNotFoundException {
            out.writeFields();
        }
    }

    private static class SerialPersistentFieldsWithoutField implements
            java.io.Serializable {
        public int anInstanceVar = 5;

        public SerialPersistentFieldsWithoutField() {
            super();
        }

        private void readObject(java.io.ObjectInputStream in)
                throws java.io.IOException, ClassNotFoundException {
            in.readFields();
        }

        private void writeObject(java.io.ObjectOutputStream out)
                throws java.io.IOException, ClassNotFoundException {
            out.putFields();
            out.writeFields();
        }
    }

    private static class NotSerializable {
        private int foo;

        public NotSerializable() {
        }

        protected Object writeReplace() throws ObjectStreamException {
            return new Integer(42);
        }
    }

    private static class WriteReplaceObject implements Serializable {
        private Object replaceObject;

        private static enum Color {
            red, blue, green
        };

        public WriteReplaceObject(Object o) {
            replaceObject = o;
        }

        protected Object writeReplace() throws ObjectStreamException {
            return replaceObject;
        }
    }

    private static class ExternalizableWithReplace implements Externalizable {
        private int foo;

        public ExternalizableWithReplace() {
        }

        protected Object writeReplace() throws ObjectStreamException {
            return new Integer(42);
        }

        public void writeExternal(ObjectOutput out) {
        }

        public void readExternal(ObjectInput in) {
        }
    }

    private static class ObjectOutputStreamWithReplace extends ObjectOutputStream {
        public ObjectOutputStreamWithReplace(OutputStream out) throws IOException {
            super(out);
            enableReplaceObject(true);
        }

        protected Object replaceObject(Object obj) throws IOException {
            if (obj instanceof NotSerializable) {
                return new Long(10);
            } else if (obj instanceof Integer) {
                return new Long(((Integer) obj).longValue());
            } else {
                return obj;
            }
        }
    }

    private static class ObjectOutputStreamWithReplace2 extends
            ObjectOutputStream {
        public ObjectOutputStreamWithReplace2(OutputStream out)
                throws IOException {
            super(out);
            enableReplaceObject(true);
        }

        protected Object replaceObject(Object obj) throws IOException {
            return new Long(10);
        }
    }

    private static class BasicObjectOutputStream extends ObjectOutputStream {
        public boolean writeStreamHeaderCalled;

        public BasicObjectOutputStream() throws IOException, SecurityException {
            super();
            writeStreamHeaderCalled = false;
        }

        public BasicObjectOutputStream(OutputStream output) throws IOException {
            super(output);
        }

        public void drain() throws IOException {
            super.drain();
        }

        public boolean enableReplaceObject(boolean enable)
                throws SecurityException {
            return super.enableReplaceObject(enable);
        }

        public void writeObjectOverride(Object object) throws IOException {
            super.writeObjectOverride(object);
        }

        public void writeStreamHeader() throws IOException {
            super.writeStreamHeader();
            writeStreamHeaderCalled = true;
        }
}

    private static class NoFlushTestOutputStream extends ByteArrayOutputStream {
        public boolean flushCalled;

        public NoFlushTestOutputStream() {
            super();
            flushCalled = false;
        }

        public void flush() throws IOException {
            super.flush();
            flushCalled = true;
        }
    }

    protected static final String MODE_XLOAD = "xload";

    protected static final String MODE_XDUMP = "xdump";

    static final String FOO = "foo";

    static final String MSG_WITE_FAILED = "Failed to write: ";

    private static final boolean DEBUG = false;

    protected static boolean xload = false;

    protected static boolean xdump = false;

    protected static String xFileName = null;

    protected ObjectInputStream ois;

    protected ObjectOutputStream oos;

    protected ObjectOutputStream oos_ioe;

    protected Support_OutputStream sos;

    protected ByteArrayOutputStream bao;

    static final int INIT_INT_VALUE = 7;

    static final String INIT_STR_VALUE = "a string that is blortz";

    /**
     * @tests java.io.ObjectOutputStream#ObjectOutputStream(java.io.OutputStream)
     */
    @TestTargetNew(
        level = TestLevel.PARTIAL_COMPLETE,
        notes = "Checks valid construction, NullPointerException and IOException.",
        method = "ObjectOutputStream",
        args = {java.io.OutputStream.class}
    )
    public void test_ConstructorLjava_io_OutputStream() throws IOException {
        oos.close();
        oos = new ObjectOutputStream(new ByteArrayOutputStream());
        oos.close();

        try {
            oos = new ObjectOutputStream(null);
            fail("Test 1: NullPointerException expected.");
        } catch (NullPointerException e) {
            // Expected.
        }

        Support_ASimpleOutputStream sos = new Support_ASimpleOutputStream(true);
        try {
            oos = new ObjectOutputStream(sos);
            fail("Test 2: IOException expected.");
        } catch (IOException e) {
            // Expected.
        }
    }

    /**
     * @tests java.io.ObjectOutputStream#close()
     */
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        method = "close",
        args = {}
    )
    public void test_close() throws IOException {
        int outputSize = bao.size();
        // Writing of a primitive type should be buffered.
        oos.writeInt(42);
        assertTrue("Test 1: Primitive data unexpectedly written to the target stream.",
                bao.size() == outputSize);
        // Closing should write the buffered data to the target stream.
        oos.close();
        assertTrue("Test 2: Primitive data has not been written to the the target stream.",
                bao.size() > outputSize);

        try {
            oos_ioe.close();
            fail("Test 3: IOException expected.");
        } catch (IOException e) {
            // Expected.
        }
    }

    /**
     * @tests java.io.ObjectOutputStream#drain()
     */
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        method = "drain",
        args = {}
    )
    public void test_drain() throws IOException {
        NoFlushTestOutputStream target = new NoFlushTestOutputStream();
        BasicObjectOutputStream boos = new BasicObjectOutputStream(target);
        int initialSize = target.size();
        boolean written = false;

        boos.writeBytes("Lorem ipsum");
        // If there is no buffer then the bytes have already been written.
        written = (target.size() > initialSize);

        boos.drain();
        assertTrue("Content has not been written to the target.",
                written || (target.size() > initialSize));
        assertFalse("flush() has been called on the target.",
                target.flushCalled);
    }

    /**
     * @tests java.io.ObjectOutputStream#defaultWriteObject()
     */
    @TestTargetNew(
        level = TestLevel.SUFFICIENT,
        notes = "IOException can not be tested because this method" +
                "always throws a NotActiveException if called directly.",
        method = "defaultWriteObject",
        args = {}
    )
    public void test_defaultWriteObject() throws IOException {
        try {
            oos.defaultWriteObject();
            fail("Test 1: NotActiveException expected.");
        } catch (NotActiveException e) {
            // Expected.
        }
    }

    /**
     * @tests java.io.ObjectOutputStream#enableReplaceObject(boolean)
     */
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        method = "enableReplaceObject",
        args = {boolean.class}
    )
    public void test_enableReplaceObjectB() throws IOException {
        // Start testing without a SecurityManager.
        BasicObjectOutputStream boos = new BasicObjectOutputStream();
        assertFalse("Test 1: Object resolving must be disabled by default.",
                boos.enableReplaceObject(true));

        assertTrue("Test 2: enableReplaceObject did not return the previous value.",
                boos.enableReplaceObject(false));
    }

    /**
     * @tests java.io.ObjectOutputStream#flush()
     */
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        method = "flush",
        args = {}
    )
    public void test_flush() throws Exception {
        // Test for method void java.io.ObjectOutputStream.flush()
        int size = bao.size();
        oos.writeByte(127);
        assertTrue("Test 1: Data already flushed.", bao.size() == size);
        oos.flush();
        assertTrue("Test 2: Failed to flush data.", bao.size() > size);

        try {
            oos_ioe.flush();
            fail("Test 3: IOException expected.");
        } catch (IOException e) {
            // Expected.
        }
    }

    /**
     * @tests java.io.ObjectOutputStream#putFields()
     */
    @TestTargetNew(
        level = TestLevel.SUFFICIENT,
        notes = "IOException can not be tested because this method" +
                "always throws a NotActiveException if called directly.",
        method = "putFields",
        args = {}
    )
    public void test_putFields() throws Exception {
        /*
         * "SerializableTestHelper" is an object created for these tests with
         * two fields (Strings) and simple implementations of readObject and
         * writeObject which simply read and write the first field but not the
         * second one.
         */
        SerializableTestHelper sth;

        try {
            oos.putFields();
            fail("Test 1: NotActiveException expected.");
        } catch (NotActiveException e) {
            // Expected.
        }

        oos.writeObject(new SerializableTestHelper("Gabba", "Jabba"));
        oos.flush();
        ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
        sth = (SerializableTestHelper) (ois.readObject());
        assertEquals("Test 2: readFields or writeFields failed; first field not set.",
                "Gabba", sth.getText1());
        assertNull("Test 3: readFields or writeFields failed; second field should not have been set.",
                sth.getText2());
    }

    /**
     * @tests java.io.ObjectOutputStream#reset()
     */
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        method = "reset",
        args = {}
    )
    public void test_reset() throws Exception {
        String o = "HelloWorld";
        sos = new Support_OutputStream(200);
        oos.close();
        oos = new ObjectOutputStream(sos);
        oos.writeObject(o);
        oos.writeObject(o);
        oos.reset();
        oos.writeObject(o);

        sos.setThrowsException(true);
        try {
            oos.reset();
            fail("Test 1: IOException expected.");
        } catch (IOException e) {
            // Expected.
        }
        sos.setThrowsException(false);

        ois = new ObjectInputStream(new ByteArrayInputStream(sos.toByteArray()));
        assertEquals("Test 2: Incorrect object read.", o, ois.readObject());
        assertEquals("Test 3: Incorrect object read.", o, ois.readObject());
        assertEquals("Test 4: Incorrect object read.", o, ois.readObject());
        ois.close();
    }

    private static class ExternalTest implements Externalizable {
        public String value;

        public ExternalTest() {
        }

        public void setValue(String val) {
            value = val;
        }

        public String getValue() {
            return value;
        }

        public void writeExternal(ObjectOutput output) {
            try {
                output.writeUTF(value);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        public void readExternal(ObjectInput input) {
            try {
                value = input.readUTF();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * @tests java.io.ObjectOutputStream#useProtocolVersion(int)
     */
    @TestTargetNew(
        level = TestLevel.SUFFICIENT,
        notes = "IOException seems to be never thrown, therefore there is no such test.",
        method = "useProtocolVersion",
        args = {int.class}
    )
    public void test_useProtocolVersionI() throws Exception {

        oos.useProtocolVersion(ObjectOutputStream.PROTOCOL_VERSION_1);
        ExternalTest t1 = new ExternalTest();
        t1.setValue("hello1");
        oos.writeObject(t1);
        oos.close();
        ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
        ExternalTest t2 = (ExternalTest) ois.readObject();
        ois.close();
        assertTrue(
                "Cannot read/write PROTOCAL_VERSION_1 Externalizable objects: "
                        + t2.getValue(), t1.getValue().equals(t2.getValue()));
    }

    /**
     * @tests java.io.ObjectOutputStream#write(byte[])
     */
    @TestTargetNew(
            level = TestLevel.SUFFICIENT,
            notes = "Tests against golden file missing. IOException can " +
                    "not be checked since is never thrown (primitive data " +
                    "is written into a self-expanding buffer).",
            method = "write",
            args = {byte[].class}
    )
    public void test_write$B() throws Exception {
        // Test for method void java.io.ObjectOutputStream.write(byte [])
        byte[] buf = new byte[10];
        oos.write("HelloWorld".getBytes());
        oos.close();
        ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
        ois.read(buf, 0, 10);
        ois.close();
        assertEquals("Read incorrect bytes", "HelloWorld", new String(buf, 0,
                10));
    }

    /**
     * @tests java.io.ObjectOutputStream#write(byte[], int, int)
     */
    @TestTargetNew(
            level = TestLevel.SUFFICIENT,
            notes = "Tests against golden file missing. IOException can " +
                    "not be checked since is never thrown (primitive data " +
                    "is written into a self-expanding buffer).",
            method = "write",
            args = {byte[].class, int.class, int.class}
    )
    public void test_write$BII() throws Exception {
        // Test for method void java.io.ObjectOutputStream.write(byte [], int,
        // int)
        byte[] buf = new byte[10];
        oos.write("HelloWorld".getBytes(), 0, 10);
        oos.close();
        ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
        ois.read(buf, 0, 10);
        ois.close();
        assertEquals("Read incorrect bytes", "HelloWorld", new String(buf, 0,
                10));

        ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
        try {
            ois.read(buf, 0, -1);
            fail("IndexOutOfBoundsException not thrown");
        } catch (IndexOutOfBoundsException e) {
            // Expected
        }
        try {
            ois.read(buf, -1, 1);
            fail("IndexOutOfBoundsException not thrown");
        } catch (IndexOutOfBoundsException e) {
            // Expected
        }
        try {
            ois.read(buf, 10, 1);
            fail("IndexOutOfBoundsException not thrown");
        } catch (IndexOutOfBoundsException e) {
            // Expected
        }
        ois.close();

    }

    /**
     * @tests java.io.ObjectOutputStream#write(int)
     */
    @TestTargetNew(
            level = TestLevel.SUFFICIENT,
            notes = "Tests against golden file missing. IOException can " +
                    "not be checked since is never thrown (primitive data " +
                    "is written into a self-expanding buffer).",
            method = "write",
            args = {int.class}
    )
    public void test_writeI() throws Exception {
        // Test for method void java.io.ObjectOutputStream.write(int)
        oos.write('T');
        oos.close();
        ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
        assertEquals("Read incorrect byte", 'T', ois.read());
        ois.close();
    }

    /**
     * @tests java.io.ObjectOutputStream#writeBytes(java.lang.String)
     */
    @TestTargetNew(
            level = TestLevel.SUFFICIENT,
            notes = "Tests against golden file missing. IOException can " +
                    "not be checked since is never thrown (primitive data " +
                    "is written into a self-expanding buffer).",
            method = "writeBytes",
            args = {java.lang.String.class}
    )
    public void test_writeBytesLjava_lang_String() throws Exception {
        // Test for method void
        // java.io.ObjectOutputStream.writeBytes(java.lang.String)
        byte[] buf = new byte[10];
        oos.writeBytes("HelloWorld");
        oos.close();
        ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
        ois.readFully(buf);
        ois.close();
        assertEquals("Wrote incorrect bytes value", "HelloWorld", new String(
                buf, 0, 10));
    }

    /**
     * @tests java.io.ObjectOutputStream#writeChars(java.lang.String)
     */
    @TestTargetNew(
            level = TestLevel.SUFFICIENT,
            notes = "Tests against golden file missing. IOException can " +
                    "not be checked since is never thrown (primitive data " +
                    "is written into a self-expanding buffer).",
            method = "writeChars",
            args = {java.lang.String.class}
    )
    public void test_writeCharsLjava_lang_String() throws Exception {
        // Test for method void
        // java.io.ObjectOutputStream.writeChars(java.lang.String)
        int avail = 0;
        char[] buf = new char[10];
        oos.writeChars("HelloWorld");
        oos.close();
        ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
        // Number of prim data bytes in stream / 2 to give char index
        avail = ois.available() / 2;
        for (int i = 0; i < avail; ++i)
            buf[i] = ois.readChar();
        ois.close();
        assertEquals("Wrote incorrect chars", "HelloWorld", new String(buf, 0,
                10));
    }

    /**
     * @tests java.io.ObjectOutputStream#writeObject(java.lang.Object)
     */
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "",
        method = "writeObject",
        args = {java.lang.Object.class}
    )
    public void test_writeObjectLjava_lang_Object() throws Exception {
        // Test for method void
        // java.io.ObjectOutputStream.writeObject(java.lang.Object)

        Object objToSave = null;
        Object objLoaded;

        SerialPersistentFieldsWithoutField spf = new SerialPersistentFieldsWithoutField();
        final int CONST = -500;
        spf.anInstanceVar = CONST;
        objToSave = spf;
        if (DEBUG)
            System.out.println("Obj = " + objToSave);
        objLoaded = dumpAndReload(objToSave);
        assertTrue(
                "serialPersistentFields do not work properly in this implementation",
                ((SerialPersistentFieldsWithoutField) objLoaded).anInstanceVar != CONST);

    }

    /**
     * @tests java.io.ObjectOutputStream#writeObject(java.lang.Object)
     */
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "",
        method = "writeObject",
        args = {java.lang.Object.class}
    )
    public void test_writeObject_NotSerializable() throws Exception {
        ObjectOutput out = null;
        try {
            out = new ObjectOutputStream(new ByteArrayOutputStream());
            out.writeObject(new NotSerializable());
            fail("Expected NotSerializableException");
        } catch (NotSerializableException e) {}
        out.writeObject(new ExternalizableWithReplace());
    }

    /**
     * @tests java.io.ObjectOutputStream#writeObjectOverride(Object)
     */
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "Verifies that writeObjectOverride() throws an IOException.",
        method = "writeObjectOverride",
        args = {java.lang.Object.class}
    )
    public void test_writeObjectOverrideLjava_lang_Object() throws IOException {
        BasicObjectOutputStream boos =
                new BasicObjectOutputStream(new ByteArrayOutputStream());

        try {
            boos.writeObjectOverride(new Object());
            fail("IOException expected.");
        }
        catch (IOException e) {
        }
        finally {
            boos.close();
        }
    }

    /**
     * @tests java.io.ObjectOutputStream#writeStreamHeader()
     */
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "Verifies writeStreamHeader().",
        method = "writeStreamHeader",
        args = {}
    )
    public void test_writeStreamHeader() throws IOException {
        BasicObjectOutputStream boos;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        short s;
        byte[] buffer;

        // Test 1: Make sure that writeStreamHeader() has been called.
        boos = new BasicObjectOutputStream(baos);
        try {
            assertTrue("Test 1: writeStreamHeader() has not been called.",
                         boos.writeStreamHeaderCalled);

            // Test 2: Check that at least four bytes have been written.
            buffer = baos.toByteArray();
            assertTrue("Test 2: At least four bytes should have been written",
                        buffer.length >= 4);

            // Test 3: Check the magic number.
            s = buffer[0];
            s <<= 8;
            s += ((short) buffer[1] & 0x00ff);
            assertEquals("Test 3: Invalid magic number written.",
                        java.io.ObjectStreamConstants.STREAM_MAGIC, s);

            // Test 4: Check the stream version number.
            s = buffer[2];
            s <<= 8;
            s += ((short) buffer[3] & 0x00ff);
            assertEquals("Invalid stream version number written.",
                        java.io.ObjectStreamConstants.STREAM_VERSION, s);
        }
        finally {
            boos.close();
        }
    }

    /**
     * @tests java.io.ObjectOutputStream#writeUTF(java.lang.String)
     */
    @TestTargetNew(
        level = TestLevel.PARTIAL,
        notes = "IOException checking missed.",
        method = "writeUTF",
        args = {java.lang.String.class}
    )
    public void test_writeUTFLjava_lang_String() throws Exception {
        // Test for method void
        // java.io.ObjectOutputStream.writeUTF(java.lang.String)
        oos.writeUTF("HelloWorld");
        oos.close();
        ois = new ObjectInputStream(new ByteArrayInputStream(bao.toByteArray()));
        assertEquals("Wrote incorrect UTF value", "HelloWorld", ois.readUTF());
    }

    /**
     * @tests java.io.ObjectOutputStream#writeObject(java.lang.Object)
     */
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "",
        method = "writeObject",
        args = {java.lang.Object.class}
    )
    public void test_writeObject_Exception() throws ClassNotFoundException, IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
        ObjectOutputStream oos = new ObjectOutputStream(baos);

        try {
            oos.writeObject(new Object());
            fail("should throw ObjectStreamException");
        } catch (ObjectStreamException e) {
            // expected
        } finally {
            oos.close();
            baos.close();
        }

        byte[] bytes = baos.toByteArray();
        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(
                bytes));
        try {
            ois.readObject();
            fail("should throw WriteAbortedException");
        } catch (WriteAbortedException e) {
            // expected
        } finally {
            ois.close();
        }
    }

    /**
     * Sets up the fixture, for example, open a network connection. This method
     * is called before a test is executed.
     */
    protected void setUp() throws Exception {
        super.setUp();
        oos = new ObjectOutputStream(bao = new ByteArrayOutputStream());
        oos_ioe = new ObjectOutputStream(sos = new Support_OutputStream());
        sos.setThrowsException(true);
    }

    /**
     * Tears down the fixture, for example, close a network connection. This
     * method is called after a test is executed.
     */
    protected void tearDown() throws Exception {
        super.tearDown();
        if (oos != null) {
            try {
                oos.close();
            } catch (Exception e) {}
        }
        if (oos_ioe != null) {
            try {
                oos_ioe.close();
            } catch (Exception e) {}
        }
        if (f != null && f.exists()) {
            if (!f.delete()) {
                fail("Error cleaning up files during teardown");
            }
        }
    }

    protected Object reload() throws IOException, ClassNotFoundException {

        // Choose the load stream
        if (xload || xdump) {
            // Load from pre-existing file
            ois = new ObjectInputStream(new FileInputStream(xFileName + "-"
                    + getName() + ".ser"));
        } else {
            // Just load from memory, we dumped to memory
            ois = new ObjectInputStream(new ByteArrayInputStream(bao
                    .toByteArray()));
        }

        try {
            return ois.readObject();
        } finally {
            ois.close();
        }
    }

    protected void dump(Object o) throws IOException, ClassNotFoundException {

        // Choose the dump stream
        if (xdump) {
            oos = new ObjectOutputStream(new FileOutputStream(
                    f = new java.io.File(xFileName + "-" + getName() + ".ser")));
        } else {
            oos = new ObjectOutputStream(bao = new ByteArrayOutputStream());
        }

        // Dump the object
        try {
            oos.writeObject(o);
        } finally {
            oos.close();
        }
    }

    /**
     * @tests java.io.ObjectOutputStream#writeInt(int)
     * @tests java.io.ObjectOutputStream#writeObject(java.lang.Object)
     * @tests java.io.ObjectOutputStream#writeUTF(java.lang.String)
     */
    @TestTargets({
        @TestTargetNew(
            level = TestLevel.PARTIAL,
            notes = "",
            method = "writeInt",
            args = {int.class}
        ),
        @TestTargetNew(
            level = TestLevel.PARTIAL,
            notes = "",
            method = "writeObject",
            args = {java.lang.Object.class}
        ),
        @TestTargetNew(
            level = TestLevel.PARTIAL,
            notes = "",
            method = "writeUTF",
            args = {java.lang.String.class}
        )
    })
    public void testMixPrimitivesAndObjects() throws Exception {
        int i = 7;
        String s1 = "string 1";
        String s2 = "string 2";
        byte[] bytes = { 1, 2, 3 };
        try {
            oos = new ObjectOutputStream(bao = new ByteArrayOutputStream());
            oos.writeInt(i);
            oos.writeObject(s1);
            oos.writeUTF(s2);
            oos.writeObject(bytes);
            oos.close();

            ois = new ObjectInputStream(new ByteArrayInputStream(bao
                    .toByteArray()));

            int j = ois.readInt();
            assertTrue("Wrong int :" + j, i == j);

            String l1 = (String) ois.readObject();
            assertTrue("Wrong obj String :" + l1, s1.equals(l1));

            String l2 = ois.readUTF();
            assertTrue("Wrong UTF String :" + l2, s2.equals(l2));

            byte[] bytes2 = (byte[]) ois.readObject();
            assertTrue("Wrong byte[]", Arrays.equals(bytes, bytes2));
        } finally {
            try {
                if (oos != null)
                    oos.close();
                if (ois != null)
                    ois.close();
            } catch (IOException e) {}
        }
    }

    /**
     * @tests java.io.ObjectOutputStream#writeUnshared(java.lang.Object)
     */
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "",
        method = "writeUnshared",
        args = {java.lang.Object.class}
    )
    public void test_writeUnshared() throws Exception {
        //Regression for HARMONY-187
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);

        Object o = "foobar";
        oos.writeObject(o);
        oos.writeUnshared(o);
        oos.writeObject(o);
        oos.flush();

        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream (baos.toByteArray()));

        Object[] oa = new Object[3];
        for (int i = 0; i < oa.length; i++) {
            oa[i] = ois.readObject();
        }

        oos.close();
        ois.close();

        // All three conditions must be met
        assertNotSame("oa[0] != oa[1]", oa[0], oa[1]);
        assertNotSame("oa[1] != oa[2]", oa[1], oa[2]);
        assertSame("oa[0] == oa[2]", oa[0], oa[2]);
    }

    /**
     * @tests java.io.ObjectOutputStream#writeUnshared(java.lang.Object)
     */
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "",
        method = "writeUnshared",
        args = {java.lang.Object.class}
    )
    public void test_writeUnshared2() throws Exception {
        //Regression for HARMONY-187
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);

        Object o = new Object[1];
        oos.writeObject(o);
        oos.writeUnshared(o);
        oos.writeObject(o);
        oos.flush();

        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream (baos.toByteArray()));

        Object[] oa = new Object[3];
        for (int i = 0; i < oa.length; i++) {
            oa[i] = ois.readObject();
        }

        oos.close();
        ois.close();

        // All three conditions must be met
        assertNotSame("oa[0] != oa[1]", oa[0], oa[1]);
        assertNotSame("oa[1] != oa[2]", oa[1], oa[2]);
        assertSame("oa[0] == oa[2]", oa[0], oa[2]);
    }

    protected Object dumpAndReload(Object o) throws IOException,
            ClassNotFoundException {
        dump(o);
        return reload();
    }

    /**
     * @tests java.io.ObjectOutputStream#useProtocolVersion(int)
     */
    @TestTargetNew(
        level = TestLevel.PARTIAL,
        notes = "IOException & IllegalStateException checking missed.",
        method = "useProtocolVersion",
        args = {int.class}
    )
    public void test_useProtocolVersionI_2() throws Exception {
        ObjectOutputStream oos = new ObjectOutputStream(
                new ByteArrayOutputStream());

        oos.useProtocolVersion(ObjectOutputStream.PROTOCOL_VERSION_1);
        oos.useProtocolVersion(ObjectOutputStream.PROTOCOL_VERSION_2);
        try {
            oos.useProtocolVersion(3);
            fail("Protocol 3 should not be accepted");
        } catch (IllegalArgumentException e) {
            // expected
        } finally {
            oos.close();
        }
    }

    /**
     * @tests java.io.ObjectOutputStream#replaceObject(java.lang.Object)
     */
    @TestTargetNew(
        level = TestLevel.COMPLETE,
        notes = "",
        method = "replaceObject",
        args = {java.lang.Object.class}
    )
    public void test_replaceObject() throws Exception {
        //Regression for HARMONY-1429
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStreamWithReplace oos = new ObjectOutputStreamWithReplace(baos);

        oos.writeObject(new NotSerializable());
        oos.flush();
        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream (baos.toByteArray()));
        Object obj = ois.readObject();
        oos.close();
        ois.close();
        assertTrue("replaceObject has not been called", (obj instanceof Long));

        //Regression for HARMONY-2239
        Object replaceObject = int.class;
        baos = new ByteArrayOutputStream();
        ObjectOutputStreamWithReplace2 oos2 = new ObjectOutputStreamWithReplace2(
                baos);
        oos2.writeObject(new WriteReplaceObject(replaceObject));
        oos2.flush();
        ois = new ObjectInputStream(
                new ByteArrayInputStream(baos.toByteArray()));
        obj = ois.readObject();
        oos.close();
        ois.close();
        assertTrue("replaceObject has not been called", (obj instanceof Long));

        replaceObject = ObjectStreamClass.lookup(Integer.class);
        baos = new ByteArrayOutputStream();
        oos2 = new ObjectOutputStreamWithReplace2(baos);
        oos2.writeObject(new WriteReplaceObject(replaceObject));
        oos2.flush();
        ois = new ObjectInputStream(
                new ByteArrayInputStream(baos.toByteArray()));
        obj = ois.readObject();
        oos.close();
        ois.close();
        assertTrue("replaceObject has not been called", (obj instanceof Long));

        replaceObject = WriteReplaceObject.Color.red;
        baos = new ByteArrayOutputStream();
        oos2 = new ObjectOutputStreamWithReplace2(baos);
        oos2.writeObject(new WriteReplaceObject(replaceObject));
        oos2.flush();
        ois = new ObjectInputStream(
                new ByteArrayInputStream(baos.toByteArray()));
        obj = ois.readObject();
        oos.close();
        ois.close();
        assertTrue("replaceObject has not been called", (obj instanceof Long));

        // Regression for HARMONY-3158
        Object obj1;
        Object obj2;
        Object obj3;

        baos = new ByteArrayOutputStream();
        oos = new ObjectOutputStreamWithReplace(baos);

        oos.writeObject(new Integer(99));
        oos.writeObject(Integer.class);
        oos.writeObject(ObjectStreamClass.lookup(Integer.class));
        oos.flush();

        ois = new ObjectInputStream(new ByteArrayInputStream (baos.toByteArray()));
        obj1 = ois.readObject();
        obj2 = ois.readObject();
        obj3 = ois.readObject();
        oos.close();
        ois.close();

        assertTrue("1st replaceObject worked incorrectly", obj1 instanceof Long);
        assertEquals("1st replaceObject worked incorrectly",
                99, ((Long) obj1).longValue());
        assertEquals("2nd replaceObject worked incorrectly", Integer.class, obj2);
        assertEquals("3rd replaceObject worked incorrectly",
                ObjectStreamClass.class, obj3.getClass());
    }
}


text:
1. Create the deploy user
=========================
In the remote server:

adduser deploy
passwd -l deploy

Add this line to the /etc/sudoers file:

%deploy ALL=(ALL) NOPASSWD: ALL

chmod 440 /etc/sudoers

2. For each user that will use the deploy user:
===============================================

Add the public SSH key to the deploy user authorized_keys file, /home/deploy/.ssh/authorized_keys

chmod 600 /home/deploy/.ssh/authorized_keys
chmod 700 /home/deploy/.ssh
chown -R deploy:deploy /home/deploy/.ssh

3. Run bootstrap task:
======================

bundle exec cap development deploy:bootstrap
bundle exec cap development puppet:run

4. Deploy app:
==============

bundle exec cap development deploy
bundle exec cap development deploy:release

redpajama_set_name: RedPajamaGithub


text:
package org.snmp4j.smi;

/**
 * The AssignableFromIntArray interface describes objects whose
 * value can be set from an int array and converted back to an int array.
 *
 * @author Frank Fock
 * @version 1.10.1
 * @since 1.10.1
 */
public interface AssignableFromIntArray {

  /**
   * Sets the value of this object from the supplied int array.
   * @param value
   *    an int array.
   */
  void setValue(int[] value);

  /**
   * Returns the value of this object as an int array.
   * @return
   *    an int array.
   */
  int[] toIntArray();
}


text:
using System;
using System.Collections.Generic;
using System.Globalization;
using Xunit;

namespace System.Globalization.Tests
{
    public class DateTimeFormatInfoReadOnly
    {
        public static IEnumerable<object[]> ReadOnly_TestData()
        {
            yield return new object[] { DateTimeFormatInfo.InvariantInfo, true };
            yield return new object[] { new DateTimeFormatInfo(), false };
            yield return new object[] { new CultureInfo("en-US").DateTimeFormat, false };
        }

        [Theory]
        [MemberData(nameof(ReadOnly_TestData))]
        public void ReadOnly(DateTimeFormatInfo format, bool expected)
        {
            Assert.Equal(expected, format.IsReadOnly);

            DateTimeFormatInfo readOnlyFormat = DateTimeFormatInfo.ReadOnly(format);
            Assert.True(readOnlyFormat.IsReadOnly);
        }

        [Fact]
        public void ReadOnly_Invalid()
        {
            Assert.Throws<ArgumentNullException>(() => DateTimeFormatInfo.ReadOnly(null)); // Dtfi is null
        }
    }
}


text:
import functools
import os
import re
import urlparse

import webob
from xml.dom import minidom

from traffic.api.openstack import wsgi
from traffic.api.openstack import xmlutil
from traffic.compute import utils as compute_utils
from traffic import exception
from traffic import flags
from traffic.openstack.common import log as logging

LOG = logging.getLogger(__name__)
FLAGS = flags.FLAGS

XML_NS_V11 = 'http://docs.openstack.org/compute/api/v1.1'

def get_pagination_params(request):
    """Return marker, limit tuple from request.

    :param request: `wsgi.Request` possibly containing 'marker' and 'limit'
                    GET variables. 'marker' is the id of the last element
                    the client has seen, and 'limit' is the maximum number
                    of items to return. If 'limit' is not specified, 0, or
                    > max_limit, we default to max_limit. Negative values
                    for either marker or limit will cause
                    exc.HTTPBadRequest() exceptions to be raised.

    """
    params = {}
    if 'limit' in request.GET:
        params['limit'] = _get_limit_param(request)
    if 'marker' in request.GET:
        params['marker'] = _get_marker_param(request)
    if 'page_index' in request.GET:
        params['page_index'] = _get_page_index_param(request)
    return params

#add by weiyuanke@cnic.cn
def _get_page_index_param(request):
    """Extract integer page_index from request or fail"""
    try:
        page_index = int(request.GET['page_index'])
    except ValueError:
        msg = _('page_index param must be an integer')
        raise webob.exc.HTTPBadRequest(explanation=msg)
    if page_index < 0:
        msg = _('page_index param must be positive')
        raise webob.exc.HTTPBadRequest(explanation=msg)
    return page_index

def _get_limit_param(request):
    """Extract integer limit from request or fail"""
    try:
        limit = int(request.GET['limit'])
    except ValueError:
        msg = _('limit param must be an integer')
        raise webob.exc.HTTPBadRequest(explanation=msg)
    if limit < 0:
        msg = _('limit param must be positive')
        raise webob.exc.HTTPBadRequest(explanation=msg)
    return limit

def _get_marker_param(request):
    """Extract marker id from request or fail"""
    return request.GET['marker']

#added by weiyuanke@cnic.cn
def get_page_index(request):
    params = get_pagination_params(request)
    page_index = params.get('page_index')
    return page_index

def get_id_from_href(href):
    """Return the id or uuid portion of a url.

    Given: 'http://www.foo.com/bar/123?q=4'
    Returns: '123'

    Given: 'http://www.foo.com/bar/abc123?q=4'
    Returns: 'abc123'

    """
    return urlparse.urlsplit("%s" % href).path.split('/')[-1]

def remove_version_from_href(href):
    """Removes the first api version from the href.

    Given: 'http://www.traffic.com/v1.1/123'
    Returns: 'http://www.traffic.com/123'

    Given: 'http://www.traffic.com/v1.1'
    Returns: 'http://www.traffic.com'

    """
    parsed_url = urlparse.urlsplit(href)
    url_parts = parsed_url.path.split('/', 2)

    # NOTE: this should match vX.X or vX
    expression = re.compile(r'^v([0-9]+|[0-9]+\.[0-9]+)(/.*|$)')
    if expression.match(url_parts[1]):
        del url_parts[1]

    new_path = '/'.join(url_parts)

    if new_path == parsed_url.path:
        msg = _('href %s does not contain version') % href
        LOG.debug(msg)
        raise ValueError(msg)

    parsed_url = list(parsed_url)
    parsed_url[2] = new_path
    return urlparse.urlunsplit(parsed_url)

def dict_to_query_str(params):
    # TODO(throughnothing): we should just use urllib.urlencode instead of this
    # But currently we don't work with urlencoded url's
    param_str = ""
    for key, val in params.iteritems():
        param_str = param_str + '='.join([str(key), str(val)]) + '&'

    return param_str.rstrip('&')

def get_networks_for_instance_from_nw_info(nw_info):
    networks = {}
    for vif in nw_info:
        ips = vif.fixed_ips()
        floaters = vif.floating_ips()
        label = vif['network']['label']
        if label not in networks:
            networks[label] = {'ips': [], 'floating_ips': []}

        networks[label]['ips'].extend(ips)
        networks[label]['floating_ips'].extend(floaters)
    return networks

def raise_http_conflict_for_instance_invalid_state(exc, action):
    """Return a webob.exc.HTTPConflict instance containing a message
    appropriate to return via the API based on the original
    InstanceInvalidState exception.
    """
    attr = exc.kwargs.get('attr')
    state = exc.kwargs.get('state')
    if attr and state:
        msg = _("Cannot '%(action)s' while instance is in %(attr)s %(state)s")
    else:
        # At least give some meaningful message
        msg = _("Instance is in an invalid state for '%(action)s'")
    raise webob.exc.HTTPConflict(explanation=msg % locals())

class MetadataDeserializer(wsgi.MetadataXMLDeserializer):
    def deserialize(self, text):
        dom = minidom.parseString(text)
        metadata_node = self.find_first_child_named(dom, "metadata")
        metadata = self.extract_metadata(metadata_node)
        return {'body': {'metadata': metadata}}

class MetaItemDeserializer(wsgi.MetadataXMLDeserializer):
    def deserialize(self, text):
        dom = minidom.parseString(text)
        metadata_item = self.extract_metadata(dom)
        return {'body': {'meta': metadata_item}}

class MetadataXMLDeserializer(wsgi.XMLDeserializer):

    def extract_metadata(self, metadata_node):
        """Marshal the metadata attribute of a parsed request"""
        if metadata_node is None:
            return {}
        metadata = {}
        for meta_node in self.find_children_named(metadata_node, "meta"):
            key = meta_node.getAttribute("key")
            metadata[key] = self.extract_text(meta_node)
        return metadata

    def _extract_metadata_container(self, datastring):
        dom = minidom.parseString(datastring)
        metadata_node = self.find_first_child_named(dom, "metadata")
        metadata = self.extract_metadata(metadata_node)
        return {'body': {'metadata': metadata}}

    def create(self, datastring):
        return self._extract_metadata_container(datastring)

    def update_all(self, datastring):
        return self._extract_metadata_container(datastring)

    def update(self, datastring):
        dom = minidom.parseString(datastring)
        metadata_item = self.extract_metadata(dom)
        return {'body': {'meta': metadata_item}}

metadata_nsmap = {None: xmlutil.XMLNS_V11}

class MetaItemTemplate(xmlutil.TemplateBuilder):
    def construct(self):
        sel = xmlutil.Selector('meta', xmlutil.get_items, 0)
        root = xmlutil.TemplateElement('meta', selector=sel)
        root.set('key', 0)
        root.text = 1
        return xmlutil.MasterTemplate(root, 1, nsmap=metadata_nsmap)

class MetadataTemplateElement(xmlutil.TemplateElement):
    def will_render(self, datum):
        return True

class MetadataTemplate(xmlutil.TemplateBuilder):
    def construct(self):
        root = MetadataTemplateElement('metadata', selector='metadata')
        elem = xmlutil.SubTemplateElement(root, 'meta',
                                          selector=xmlutil.get_items)
        elem.set('key', 0)
        elem.text = 1
        return xmlutil.MasterTemplate(root, 1, nsmap=metadata_nsmap)

def check_snapshots_enabled(f):
    @functools.wraps(f)
    def inner(*args, **kwargs):
        if not FLAGS.allow_instance_snapshots:
            LOG.warn(_('Rejecting snapshot request, snapshots currently'
                       ' disabled'))
            msg = _("Instance snapshots are not permitted at this time.")
            raise webob.exc.HTTPBadRequest(explanation=msg)
        return f(*args, **kwargs)
    return inner

class ViewBuilder(object):
    """Model API responses as dictionaries."""

    def _get_links(self, request, identifier, collection_name):
        return [{
            "rel": "self",
            "href": self._get_href_link(request, identifier, collection_name),
        },
        {
            "rel": "bookmark",
            "href": self._get_bookmark_link(request,
                                            identifier,
                                            collection_name),
        }]

    def _get_next_link(self, request, identifier, collection_name):
        """Return href string with proper limit and marker params."""
        params = request.params.copy()
        params["marker"] = identifier
        prefix = self._update_link_prefix(request.application_url,
                                          FLAGS.osapi_compute_link_prefix)
        url = os.path.join(prefix,
                           request.environ["traffic.context"].project_id,
                           collection_name)
        return "%s?%s" % (url, dict_to_query_str(params))

    def _get_href_link(self, request, identifier, collection_name):
        """Return an href string pointing to this object."""
        prefix = self._update_link_prefix(request.application_url,
                                          FLAGS.osapi_compute_link_prefix)
        return os.path.join(prefix,
                            request.environ["traffic.context"].project_id,
                            collection_name,
                            str(identifier))

    def _get_bookmark_link(self, request, identifier, collection_name):
        """Create a URL that refers to a specific resource."""
        base_url = remove_version_from_href(request.application_url)
        base_url = self._update_link_prefix(base_url,
                                            FLAGS.osapi_compute_link_prefix)
        return os.path.join(base_url,
                            request.environ["traffic.context"].project_id,
                            collection_name,
                            str(identifier))

    def _get_collection_links(self,
                              request,
                              items,
                              collection_name,
                              id_key="uuid"):
        """Retrieve 'next' link, if applicable."""
        links = []
        limit = int(request.params.get("limit", 0))
        if limit and limit == len(items):
            last_item = items[-1]
            if id_key in last_item:
                last_item_id = last_item[id_key]
            elif 'id' in last_item:
                last_item_id = last_item["id"]
            else:
                last_item_id = last_item["flavorid"]
            links.append({
                "rel": "next",
                "href": self._get_next_link(request,
                                            last_item_id,
                                            collection_name),
            })
        return links

    def _update_link_prefix(self, orig_url, prefix):
        if not prefix:
            return orig_url
        url_parts = list(urlparse.urlsplit(orig_url))
        prefix_parts = list(urlparse.urlsplit(prefix))
        url_parts[0:2] = prefix_parts[0:2]
        return urlparse.urlunsplit(url_parts)


text:
All notable changes to the docker containers will be documented in this file.

### 2022-11-07
 - Updated packaged scans to use full path to `zap-x.sh`.

### 2022-11-04
  - Fixed `zap-x.sh` to return the exit code from `zap.sh` instead of `rm -f`

### 2022-10-27
 - Updated to use Webswing 22.2

### 2022-10-07
 - Changed stable image to use debian:unstable-slim.
 - Changed bare image to use eclipse-temurin:11-jre-alpine.
 - Removed zap-cli from stable.
 - Updated to use Webswing 22.1.5.
 - Alert_on_Unexpected_Content_Types.js > Added Content-Type application/x-ndjson to the list of expected types.

### 2022-09-28
 - Removed zap-cli from weekly/live.

### 2022-09-27
 - Fixed problem where python-owasp-zap-v2.4 was getting an older version.
 - Use curl for the weekly/live health checks.

### 2022-09-26
 - Changed weekly image to use debian:unstable-slim.

### 2022-09-20
 - Changed live image to use debian:unstable-slim.

### 2022-09-15
 - No longer include depreciated addOns job.

### 2022-08-10
 - The packaged scans will no longer warn if the default hooks file is not found.

### 2022-08-05
 - Alert_on_Unexpected_Content_Types.js > Added Content-Type text/plain to the list of expected types.

### 2022-07-30
 - Updated to use Webswing 22.1.3.

### 2022-06-06
 - Updated to use Webswing 22.1.2

### 2022-06-03
 - Add support for absolute file path in all scan options which require a file.

### 2022-04-11
 - Updated to use Webswing 21.2.8

### 2022-03-28
 - Added awscli to all of the docker images except 'bare'.

### 2021-12-27
 - Updated to use Webswing 21.2.5

### 2021-12-16
 - Updated to use Webswing 21.2.4

### 2021-11-03
 - Fixed issue with automation updates by install updates in a separate ZAP inline call.

### 2021-10-08
 - Changed the packaged scans to always update all add-ons on start up to avoid a bug in the automation framework breaking plans

### 2021-10-05
 - Fixed bug which caused the baseline scan to fail if a read-only mapped drive was used.

### 2021-09-21
 - Updated the Baseline scan to use the Automation Framework for the "-c config_file" and "-u config_url" options.

### 2021-09-16
 - Updated to use Webswing 21.1.5

### 2021-09-15
 - Added /zap/container file to make it easier to detect if we are running in a container like docker.

### 2021-08-11
 - Changed to enable integration tests, inc enabling the AF for the baseline `-c` option if the `--auto` flag is used before it.
 - Added Automation Framework support for * OUTOFSCOPE baseline config file option.

### 2021-07-08
 - Changed to use user's home directory for the Automation Framework files so it will work for any user

### 2021-07-05
 - Updated the baseline to use the Automation Framework by default for common options

### 2021-06-11
 - Updated the baseline to optionally use the Automation Framework for common options

### 2021-05-05
 - Updated to use Webswing 21.1

### 2021-04-30
 - Alert_on_Unexpected_Content_Types.js > Added Content-Type text/yaml to the list of expected types.

### 2021-02-10
 - Check if messages being analyzed by API scan scripts are globally excluded or not.

### 2021-02-01
 - Allow more flexibility to specify ZAP command line options when using Webswing:
  - The default options stay as `-host 0.0.0.0 -port 8090` unless
  - You specify an env var `ZAP_WEBSWING_OPTS` in which case that replaces the defaults
  - If not then if a `/zap/wrk/owasp_zap_root_ca.key` file exists then this is loaded as the ZAP root cert
  - If not then if the `/zap/wrk` is writable then ZAP will output the public and private ZAP cert into that directory

### 2021-01-19
 - Python 3.5 is no longer supported.

### 2020-12-23
 - Update Webswing to download prod version if valid key supplied.

### 2020-12-16
 - Update Webswing to latest version (20.2.1) to work with newer Java versions.
 - Update Java in stable image to version 11.

### 2020-12-11
 - Add `target` parameter to `ajaxSpider.scan_as_user` call. Without it ajaxSpider crawls first included in a context URL and not a target which is set.

### 2020-12-02
 - Use `ARG` command (for `DEBIAN_FRONTEND`) instead of `ENV` so that the parameter does not persist after the build process has been completed.

### 2020-11-27
 - Move logging level of Params from `info` to `debug`, as it can contain sensitive data when authenticated scans are run.

### 2020-11-24
 - Add support for authenticated scans.

### 2020-11-19
 - Add zap_tune function (disable all tags and limit pscan alerts to 10), zap_tuned hook and disable recovery log.

### 2020-11-16
 - Update zap-api-scan.py to add support for GraphQL.

### 2020-10-13
 - Alert_on_Unexpected_Content_Types.js > Added Content-Type application/health+json to the list of expected types.

### 2020-09-18
 - Fail immediately if the spider scans were not started to provide better error message.

###  2020-08-28
 - Packaged scans will use the provided context when spidering and active scanning.

###  2020-08-27
 - Updated to use webswing 2.5.12

###  2020-08-03
 - Add `IS_CONTAINERIZED` environment variable to the container image, used in the python script to check for containerized environments (e.g. containerd) without relying on container runtime specific files.

###  2020-07-17
 - Make podman compatible

###  2020-05-20
 - Make docker stable use ubuntu 20.04

###  2020-05-13
 - Make `python` command use Python 3.

### 2020-05-12
 - Removed python 2, only python 3 will be supported going forward.

### 2020-04-27
- Add `application/vnd.api+json` to the list of expected API content types.

### 2020-04-08
- Changed zap-full-scan.py and zap-api-scan.py to include the -I option to ignore only warning used by zap-baseline-scan.py

### 2020-04-06
- Make API scan policy available to the root user, otherwise it would fail to start the active scan.

### 2020-04-01
- Changed live and weekly images to use Java 11.

### 2020-02-21
 - Changed zap-full-scan.py, zap-api-scan.py, and zap-baseline-scan.py to include the missing check for markdown file.

### 2020-02-07
 - Change zap-full-scan.py and zap-api-scan.py to be Python3 compatible

### 2020-01-22
 - Change `live`, `stable`, and `weekly` images to set the locale and lang to `C.UTF-8`,
 to improve interoperability with Python 3 (e.g. `zap-cli`).

### 2019-10-16
 - Added response code after each URL reported on standard out:

```
WARN-NEW: Web Browser XSS Protection Not Enabled [10016] x 4
	https://www.example.com/ (200 OK)
	https://www.example.com/robots.txt (404 Not Found)
	https://www.example.com (200 OK)
	https://www.example.com/sitemap.xml (404 Not Found)
```

### 2019-10-01
 - Added Python3 and the pip3 version of ZAP in preparation for Python 2 EOL: https://www.python.org/dev/peps/pep-0373/

### 2019-09-05
 - Changed zap-full-scan.py to ignore example ascan rules

### 2019-06-18
 - Changed zap-full-scan.py to always include the active scan beta rules
 - Changed zap-full-scan.py to include the active scan alpha rules when the -a switch is used
 - Fixed ownership of all files in the /zap directory
 - Added this changelog


text:
This document overviews how to use the markov chain data structure
as contained within
[markov_chain.h](https://github.com/sjsimps/Markov-Chain/blob/master/Markov_Chain/markov_chain.h)

### Adding Nodes and Events:

```C++
//Adds a single node without any events
void Add_Node(T node);

//Adds a sequence of events to the chain through a vector of nodes
void Add_Event_Sequence(std::vector<T> node_sequence);

//Adds an event to the chain from last_node to next_node
//The 'num_events' parameter determines the weight of the event
void Add_Event(T last_node, T next_node, unsigned int num_events = 1);

//Removes all events between two nodes
void Remove_Event(T last_event, T current_event);

//Adding events between nodes that do not exist will automatically create the appropriate nodes
```

### Markov Chain Visualization:

```C++
//Writes markov chain to [.dot] format for visualization
void Export_To_Graphviz(std::string filename);
```

### Randomized Output:

```C++
//Outputs randomized node sequence
std::vector<T> Output_Random_Sequence (int output_length, T start_node, bool random_start);
```

### Sample Code:

The following code snippet shows how to create and visualize a
markov chain of type std::string:

```C++
//Construct new chain
Markov_Chain<std::string>* chain = new Markov_Chain<std::string>();

//Create nodes and edges
chain->Add_Event("a", "b", 3);
chain->Add_Event("b", "c", 1);
chain->Add_Event("c", "a", 1);
chain->Add_Event("c", "b", 2);

//Print status to console
chain->Print_To_Console();

//Produce Graphviz file
chain->Export_To_Graphviz("abc.dot");

//Delete chain
delete chain;
```

Visual Output:

![alt_tag](https://github.com/sjsimps/Markov-Chain/blob/master/Test/abc.png)

Console Output:

```
Format:         [Node / #Events]

Current Node:   [a / 3]
Next Nodes:     [b / 3]

Current Node:   [b / 1]
Next Nodes:     [c / 1]

Current Node:   [c / 3]
Next Nodes:     [a / 1]
                [b / 2]
```


text:
package mdb;
import Jakarta.util.*;
import java.io.*;
import java.util.*;

abstract public class Decl_ind extends Ddl_stmt {

    public void execute () {

        super.execute();
    }

}


text:
#import <UIKit/UIKit.h>

#import "MaterialFlexibleHeader.h"
#import "MaterialPalettes.h"
#import "MaterialProgressView.h"
#import "supplemental/ThemerTypicalUseSupplemental.h"

@interface ThemerTypicalUseViewController ()

@end

@implementation ThemerTypicalUseViewController

- (void)viewDidLoad {
  [super viewDidLoad];

  // Apply color scheme to material design components using component themers.
  [MDCActivityIndicatorColorThemer applyColorScheme:self.colorScheme
                                toActivityIndicator:[MDCActivityIndicator appearance]];
  [MDCAlertColorThemer applyColorScheme:self.colorScheme];
  [MDCButtonBarColorThemer applyColorScheme:self.colorScheme toButtonBar:[MDCButtonBar appearance]];
  [MDCButtonColorThemer applyColorScheme:self.colorScheme toButton:[MDCButton appearance]];
  [MDCFeatureHighlightColorThemer applyColorScheme:self.colorScheme
                            toFeatureHighlightView:[MDCFeatureHighlightView appearance]];
  [MDCFlexibleHeaderColorThemer applyColorScheme:self.colorScheme
                            toFlexibleHeaderView:[MDCFlexibleHeaderView appearance]];
  [MDCHeaderStackViewColorThemer applyColorScheme:self.colorScheme
                                toHeaderStackView:[MDCHeaderStackView appearance]];
  [MDCNavigationBarColorThemer applyColorScheme:self.colorScheme
                                toNavigationBar:[MDCNavigationBar appearance]];
  [MDCPageControlColorThemer applyColorScheme:self.colorScheme
                                toPageControl:[MDCPageControl appearance]];
  [MDCProgressViewColorThemer applyColorScheme:self.colorScheme
                                toProgressView:[MDCProgressView appearance]];
  [MDCSliderColorThemer applyColorScheme:self.colorScheme toSlider:[MDCSlider appearance]];
  [MDCTabBarColorThemer applyColorScheme:self.colorScheme toTabBar:[MDCTabBar appearance]];

  [MDCTextFieldColorThemer applyColorScheme:self.colorScheme
           toAllTextInputControllersOfClass:[MDCTextInputControllerUnderline class]];
  [MDCTextFieldColorThemer applyColorScheme:self.colorScheme
           toAllTextInputControllersOfClass:[MDCTextInputControllerLegacyDefault class]];
  [MDCTextFieldColorThemer applyColorScheme:self.colorScheme
           toAllTextInputControllersOfClass:[MDCTextInputControllerFilled class]];
  [MDCTextFieldColorThemer applyColorScheme:self.colorScheme
           toAllTextInputControllersOfClass:[MDCTextInputControllerOutlined class]];
  [MDCTextFieldColorThemer applyColorScheme:self.colorScheme
           toAllTextInputControllersOfClass:[MDCTextInputControllerOutlinedTextArea class]];

  // Apply color scheme to UIKit components.
  [UISlider appearance].tintColor = self.colorScheme.primaryColor;
  [UISwitch appearance].onTintColor = self.colorScheme.primaryColor;

  // Send notification that color scheme has changed so existing components can update if necessary.
  NSDictionary *userInfo = @{ @"colorScheme" : self.colorScheme };
  [[NSNotificationCenter defaultCenter] postNotificationName:@"ColorThemeChangeNotification"
                                                      object:self
                                                    userInfo:userInfo];

  [self setupExampleViews];
}

@end


text:
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;

namespace InventoryExpress.Model
{
    /// <summary>
    /// Datenbankkonfiguration der Sachkonto-Entität
    /// </summary>
    class LedgerAccountEntityConfiguration : IEntityTypeConfiguration<LedgerAccount>
    {
        public void Configure(EntityTypeBuilder<LedgerAccount> builder)
        {
            builder.ToTable("LedgerAccount");
            builder.HasKey(key => new { key.Id });

            //entity.HasIndex(e => e.Guid, "IX_LedgerAccount_Guid")
            //    .IsUnique();

            //entity.HasIndex(e => e.Name, "IX_LedgerAccount_Name")
            //    .IsUnique();

            builder.Property(e => e.Id)
                   .HasColumnName("ID");

            builder.Property(e => e.MediaId)
                   .HasColumnName("MediaID");

            builder.Property(e => e.Name)
                   .HasColumnName("Name")
                   .IsRequired()
                   .HasColumnType("VARCHAR (64)");

            builder.Property(e => e.Tag)
                   .HasColumnName("Tag")
                   .HasColumnType("VARCHAR (256)");

            builder.Property(e => e.Created)
                   .HasColumnName("Created")
                   .IsRequired()
                   .HasColumnType("TIMESTAMP")
                   .HasDefaultValueSql("CURRENT_TIMESTAMP");

            builder.Property(e => e.Updated)
                   .HasColumnName("Updated")
                   .IsRequired()
                   .HasColumnType("TIMESTAMP")
                   .HasDefaultValueSql("CURRENT_TIMESTAMP");

            builder.Property(e => e.Guid)
                   .HasColumnName("Guid")
                   .IsRequired()
                   .HasColumnType("CHAR (36)");

            builder.HasOne(d => d.Media)
                   .WithMany(p => p.LedgerAccounts)
                   .HasForeignKey(d => d.MediaId)
                   .OnDelete(DeleteBehavior.SetNull);
        }
    }
}


text:
#ifndef RBX_VM_OBJECT_UTILS_HPP
#define RBX_VM_OBJECT_UTILS_HPP

#include <stdint.h>
#include <sys/types.h>
#include <sstream>
#include <string.h>
#include <assert.h>
#include <vector>

#include "builtin/object.hpp"
#include "vm/exception.hpp"

/**
 *  @file   object_utils.hpp
 *
 *  Defines all the most common operations for dealing with
 *  objects, such as type checking and casting.
 */

// A stupid work around for g++ changing it's behavior on 4.3

#if __GNUC__ >= 4 && __GNUC_MINOR__ >= 3
  #define SPECIALIZATION_STORAGE
#else
  #define SPECIALIZATION_STORAGE static inline
#endif

namespace rubinius {

#define sassert(cond) if(!(cond)) Assertion::raise(#cond)

  /**
   *  Ruby type system subtype check.
   *
   *  Given builtin-class +T+, return true if +obj+ is of class +T+
   */
  template <class T>
    static inline bool kind_of(const Object* obj) {
      if(REFERENCE_P(obj)) {
        return obj->type_id() == T::type;
      }
      return false;
    }

  /**
   * A specialized version for completeness.
   */
  template <>
    SPECIALIZATION_STORAGE bool kind_of<Object>(const Object* obj) {
      return true;
    }

  /**
   *  Ruby type system class check.
   *
   *  Another version of kind_of that shouldn't be specialized for subtype
   *  compatibility. I.e., only whether object's class is this specific
   *  one.
   */
  template <class T>
    static inline bool instance_of(const Object* obj) {
      if(REFERENCE_P(obj)) {
        return obj->type_id() == T::type;
      }
      return false;
    }

  /**
   * A specialized version for completeness.
   */
  template <>
    SPECIALIZATION_STORAGE bool instance_of<Object>(const Object* obj) {
      return obj->reference_p() && (obj->type_id() == ObjectType);
    }

  /*
   *  There is NO reason why as() or try_as() should be getting
   *  NULL arguments. That means something has not been properly
   *  initialised (to Qnil if nothing else.)
   */

  /**
   *  Cast Object* into builtin T*.
   *
   *  Given builtin class +T+, return +obj+ cast as type +T*+. If
   *  +obj+ is not of type +T+, throw's a TypeError exception.
   *
   *  @see  builtin/object.cpp has specialised versions.
   */
  template <class T>
    static inline T* as(Object* obj) {
      if(!kind_of<T>(obj)) {
        TypeError::raise(T::type, obj);
      }

      return static_cast<T*>(obj);
    }

  /**
   *  Cast const Object* into builtin const T*.
   *
   *  Given builtin class +T+, return +obj+ cast as type +T*+. If
   *  +obj+ is not of type +T+, throw's a TypeError exception.
   *
   *  @see  builtin/object.cpp has specialised versions.
   */
  template <class T>
    static inline const T* as(const Object* obj) {
      if(!kind_of<T>(obj)) {
        TypeError::raise(T::type, obj);
      }

      return static_cast<const T*>(obj);
    }

  /**
   * A specialized version for completeness.
   */
  template <>
    SPECIALIZATION_STORAGE Object* as<Object>(Object* obj) {
      return obj;
    }

  /**
   * A specialized version for completeness.
   */
  template <>
    SPECIALIZATION_STORAGE const Object* as<Object>(const Object* obj) {
      return obj;
    }

  /**
   *  Cast Object* into builtin T*.
   *
   *  Given builtin class +T+, return +obj+ cast as type +T*+. If
   *  +obj+ is not exactly of type +T+, throw's a TypeError exception.
   *
   *  @see  builtin/object.cpp has specialised versions.
   */
  template <class T>
    static inline T* as_instance(Object* obj) {
      if(!instance_of<T>(obj)) {
        TypeError::raise(T::type, obj);
      }

      return static_cast<T*>(obj);
    }

  /**
   *  Cast const Object* into builtin const T*.
   *
   *  Given builtin class +T+, return +obj+ cast as type +T*+. If
   *  +obj+ is not exactly of type +T+, throw's a TypeError exception.
   *
   *  @see  builtin/object.cpp has specialised versions.
   */
  template <class T>
    static inline const T* as_instance(const Object* obj) {
      if(!instance_of<T>(obj)) {
        TypeError::raise(T::type, obj);
      }

      return static_cast<const T*>(obj);
    }

  /**
   *  Non-raising version of as().
   *
   *  Similar to as<>, but returns NULL if the type is invalid. ONLY
   *  use this when doing a conditional cast.
   *
   *  @see  builtin/object.cpp has specialised versions.
   */
  template <class T>
    static inline T* try_as(Object* obj) {
      if(!kind_of<T>(obj)) {
        return NULL;
      }

      return static_cast<T*>(obj);
    }

  /**
   *  Non-raising version of as(), for const objects.
   *
   *  Similar to as<>, but returns NULL if the type is invalid. ONLY
   *  use this when doing a conditional cast.
   *
   *  @see  builtin/object.cpp has specialised versions.
   */
  template <class T>
    static inline const T* try_as(const Object* obj) {
      if(!kind_of<T>(obj)) {
        return NULL;
      }

      return static_cast<const T*>(obj);
    }

  /**
   *  Non-raising version of as_instance().
   *
   *  Similar to as_instance<>, but returns NULL if the type is invalid. ONLY
   *  use this when doing a conditional cast.
   *
   *  @see  builtin/object.cpp has specialised versions.
   */
  template <class T>
    static inline T* try_as_instance(Object* obj) {
      if(!instance_of<T>(obj)) {
        return NULL;
      }

      return static_cast<T*>(obj);
    }

  /**
   *  Non-raising version of as(), for const objects.
   *
   *  Similar to as<>, but returns NULL if the type is invalid. ONLY
   *  use this when doing a conditional cast.
   *
   *  @see  builtin/object.cpp has specialised versions.
   */
  template <class T>
    static inline const T* try_as_instance(const Object* obj) {
      if(!instance_of<T>(obj)) {
        return NULL;
      }

      return static_cast<const T*>(obj);
    }

  /**
   *  Returns Qnil cast to another type of rubinius::Object. Useful in
   *  cases where e.g. a String* would be returned but Qnil is returned
   *  as an exceptional value.
   *
   */
  template <class T>
    static inline T* nil() { return static_cast<T*>(Qnil); }

  /**
   *  Converts one type into another without a type check. This is
   *  like reinterprete_cast<>(), but we use it so we can easily
   *  find where we're doing explicit force casts.
   */
  template <class T>
    static inline T* force_as(ObjectHeader* obj) {
      return reinterpret_cast<T*>(obj);
    }

  template <class T>
    static inline const T* force_as(const ObjectHeader* obj) {
      return reinterpret_cast<const T*>(obj);
    }

  void type_assert(STATE, Object* obj, object_type type, const char* reason);

  /*
   * A rubinius object can be followed by:
   * - a series of fields, possibly including an ivar
   * - a series of bytes (ByteArray)
   * - a fast_context pointer
   */

  /* HACK: refactor this to use the state_setup_type code path. */
  struct wraps_struct {
    void *ptr;
    void (*mark)(void*);
    void (*free)(void*);
  };

#define MARK_WRAPPED_STRUCT(obj) do { \
  struct wraps_struct *s = (struct wraps_struct *)BYTES_OF(obj); \
  if(s->mark != NULL) { s->mark(s->ptr); } \
} while (0)

#define FREE_WRAPPED_STRUCT(obj) do { \
  struct wraps_struct *s = (struct wraps_struct *)BYTES_OF(obj); \
  if(s->free != NULL) { s->free(s->ptr); } \
} while (0)

#include "gen/kind_of.hpp"

}

#endif


text:
import datetime
import time
import os

prev_year = datetime.datetime.now().year
prev_month = datetime.datetime.now().month
prev_day = datetime.datetime.now().day

while True:

	tfile = open("/sys/bus/w1/devices/28-0000058dcbf0/w1_slave")
	text = tfile.read()
	tfile.close()

	secondline = text.split("\n")[1]
	temperaturedata = secondline.split(" ")[9]
	temperature = float(temperaturedata[2:])
	temperature = temperature / 1000

	year = datetime.datetime.now().year
	month = datetime.datetime.now().month
	day = datetime.datetime.now().day

	folder =  '/home/pi/temps/temps/'+str(year)+'/'+str(month)
	file = folder+'/'+str(day)+'.temp'

	#Checks if folder exists
	if not os.path.exists(folder):
		os.makedirs(folder)

	#Write history file
	ofile = open (file, "a")
	text = "%s %.3f\n"  % (datetime.datetime.now(), temperature)
	ofile.write(text)
	ofile.close()

	#Write realtime file
	ofile = open('/home/pi/temps/realtime.temp', "w")
	ofile.write(text[:-1])
	ofile.close()

	if (prev_day != day):

		i=0
		factor = 10

		resampleFilename = '/home/pi/temps/temps/'+str(prev_year)+'/'+str(prev_month)+'/'+str(prev_day)+'_resampled.temp'
		dailyFilename = '/home/pi/temps/temps/'+str(prev_year)+'/'+str(prev_month)+'/'+str(prev_day)+'.temp'

		resampleFile = open (resampleFilename, "w")

		for line in open(dailyFilename):
			if (i%factor==0):
				text = "%s"  % (line)
				resampleFile.write(text)
			i+=1

		resampleFile.close()

		#Remove old file and rename the new one
		os.remove(dailyFilename)
		os.rename(resampleFilename, dailyFilename)

		prev_year = year
		prev_month = month
		prev_day = day

	time.sleep(60)


text:
package uk.dangrew.nuts.graphics.database;

import uk.dangrew.nuts.food.Food;
import uk.dangrew.nuts.meal.FoodHolder;

public class RecipeShareControllerImpl {

   private final RecipeSummaryWindow recipeWindow;

   public RecipeShareControllerImpl() {
      this( new RecipeSummaryWindow() );
   }//End Constructor

   RecipeShareControllerImpl( RecipeSummaryWindow window ) {
      this.recipeWindow = window;
   }//End Method

   public void share( Food selection ) {
      if ( selection == null ) {
         return;
      }

      if ( selection instanceof FoodHolder ) {
         recipeWindow.show( ( FoodHolder )selection );
      }
   }//End Method

}//End Class


text:
#include <string.h>

#include "NodeStore.h"
#include "Trace.h"

NodeStore::NodeStore()
{
}

NodeStore::~NodeStore()
{
	int n = 0;

	while (!empty()) {
		NodeRecord *nr = front();
		nr->node->setStored(false);
		pop_front();
		delete nr;
		n++;
	}
	HAGGLE_DBG("Deleted %d node records in node store\n", n);
}

bool NodeStore::_stored(const NodeRef &node, bool mustBeNeighbor)
{
	for (NodeStore::iterator it = begin(); it != end(); it++) {
		NodeRecord *nr = *it;

		if (mustBeNeighbor && !nr->node->isNeighbor())
			continue;

		if (nr->node == node) {
			return true;
		}
	}
	return false;
}
bool NodeStore::_stored(const Node &node, bool mustBeNeighbor)
{

	for (NodeStore::iterator it = begin(); it != end(); it++) {
		NodeRecord *nr = *it;

		if (mustBeNeighbor && !nr->node->isNeighbor())
			continue;

		if (nr->node == node) {
			return true;
		}
	}
	return false;
}

bool NodeStore::_stored(const Node::Id_t id, bool mustBeNeighbor)
{
	for (NodeStore::iterator it = begin(); it != end(); it++) {
		NodeRecord *nr = *it;

		if (mustBeNeighbor && !nr->node->isNeighbor())
			continue;

		if (memcmp(id, nr->node->getId(), NODE_ID_LEN) == 0) {
			return true;
		}
	}
	return false;
}

bool NodeStore::_stored(const string idStr, bool mustBeNeighbor)
{
	for (NodeStore::iterator it = begin(); it != end(); it++) {
		NodeRecord *nr = *it;

		if (mustBeNeighbor && !nr->node->isNeighbor())
			continue;

		if (strcmp(idStr.c_str(), nr->node->getIdStr()) == 0) {
			return true;
		}
	}
	return false;
}

bool NodeStore::stored(const NodeRef& node, bool mustBeNeighbor)
{
        Mutex::AutoLocker l(mutex);

	bool ret;

	if (!node)
		return false;

	node.lock();
	ret = _stored(node, mustBeNeighbor);
	node.unlock();

	return ret;
}

bool NodeStore::stored(const Node &node, bool mustBeNeighbor)
{
        Mutex::AutoLocker l(mutex);

	return _stored(node, mustBeNeighbor);
}

bool NodeStore::stored(const Node::Id_t id, bool mustBeNeighbor)
{
        Mutex::AutoLocker l(mutex);

	return (id ? _stored(id, mustBeNeighbor) : false);
}

bool NodeStore::stored(const string idStr, bool mustBeNeighbor)
{
        Mutex::AutoLocker l(mutex);

	return _stored(idStr, mustBeNeighbor);
}

bool NodeStore::add(NodeRef &node)
{
        Mutex::AutoLocker l(mutex);

	if (!node)
		return false;;

	if (_stored(node)) {
		HAGGLE_DBG("Node %s is already in node store\n", node->getIdStr());
		return false;
	}

	HAGGLE_DBG("Adding new node to node store %s\n", node->getIdStr());
	node->setStored();
	push_back(new NodeRecord(node));

	return true;
}

NodeRef NodeStore::add(Node *node)
{
        Mutex::AutoLocker l(mutex);

	if (!node)
		return NULL;

	if (_stored(*node)) {
		HAGGLE_DBG("Node %s is already in node store\n", node->getIdStr());
		return NULL;
	}

	HAGGLE_DBG("Adding new node to node store %s\n", node->getIdStr());

	NodeRef nodeRef(node);
	nodeRef->setStored();
	push_back(new NodeRecord(nodeRef));

	return nodeRef;
}

NodeRef NodeStore::retrieve(const NodeRef &node, bool mustBeNeighbor)
{
        Mutex::AutoLocker l(mutex);

	if (!node)
		return NULL;

	for (NodeStore::iterator it = begin(); it != end(); it++) {
		NodeRecord *nr = *it;

		if (mustBeNeighbor && !nr->node->isNeighbor())
			continue;

		if (nr->node == node)
			return nr->node;
	}

	return NULL;
}

NodeRef NodeStore::retrieve(const Node& node, bool mustBeNeighbor)
{
        Mutex::AutoLocker l(mutex);

	for (NodeStore::iterator it = begin(); it != end(); it++) {
		NodeRecord *nr = *it;

		if (mustBeNeighbor && !nr->node->isNeighbor())
			continue;

		if (nr->node == node)
			return nr->node;
	}

	return NULL;
}

NodeRef NodeStore::retrieve(const Node::Id_t id, bool mustBeNeighbor)
{
        Mutex::AutoLocker l(mutex);

	for (NodeStore::iterator it = begin(); it != end(); it++) {
		NodeRecord *nr = *it;
		NodeRef node = nr->node;

		if (mustBeNeighbor && !node->isNeighbor())
			continue;

		if (memcmp(id, node->getId(), NODE_ID_LEN) == 0)
			return node;
	}

	return NULL;
}

NodeRef NodeStore::retrieve(const string &id, bool mustBeNeighbor)
{
        Mutex::AutoLocker l(mutex);

	for (NodeStore::iterator it = begin(); it != end(); it++) {
		NodeRecord *nr = *it;
		NodeRef node = nr->node;

		if (mustBeNeighbor && !node->isNeighbor())
			continue;

		if (memcmp(id.c_str(), node->getIdStr(), MAX_NODE_ID_STR_LEN) == 0)
			return node;
	}

	return NULL;
}

NodeRef NodeStore::retrieve(const InterfaceRef &iface, bool mustBeNeighbor)
{
        Mutex::AutoLocker l(mutex);

        if (!iface)
	        return NULL;

	for (NodeStore::iterator it = begin(); it != end(); it++) {
		NodeRecord *nr = *it;
		NodeRef node = nr->node;

		if (mustBeNeighbor && !node->isNeighbor())
			continue;

		if (node->hasInterface(iface))
			return node;
	}

	return NULL;
}

NodeStore::size_type NodeStore::retrieve(Node::Type_t type, NodeRefList& nl)
{
        Mutex::AutoLocker l(mutex);
	size_type n = 0;

	for (NodeStore::iterator it = begin(); it != end(); it++) {
		const NodeRecord *nr = *it;

		if (nr->node->getType() == type) {
                        n++;
			nl.add(nr->node);
		}
	}

	return n;
}

NodeStore::size_type NodeStore::retrieve(const Criteria& crit, NodeRefList& nl)
{
        Mutex::AutoLocker l(mutex);
	size_type n = 0;

	for (NodeStore::iterator it = begin(); it != end(); it++) {
		const NodeRecord *nr = *it;

		if (crit(nr->node)) {
                        n++;
			nl.add(nr->node);
		}
	}

	return n;
}

NodeStore::size_type NodeStore::retrieveNeighbors(NodeRefList& nl)
{
        Mutex::AutoLocker l(mutex);
	size_type n = 0;

	for (NodeStore::iterator it = begin(); it != end(); it++) {
		const NodeRecord *nr = *it;

		if (nr->node->isNeighbor()) {
                        n++;
			nl.add(nr->node);
		}
	}

	return n;
}

NodeStore::size_type NodeStore::numNeighbors()
{
        Mutex::AutoLocker l(mutex);
	size_type n = 0;

	for (NodeStore::iterator it = begin(); it != end(); it++) {
		const NodeRecord *nr = *it;

		if (nr->node->isNeighbor()) {
                        n++;
		}
	}

	return n;
}

bool NodeStore::update(NodeRef &node, NodeRefList *nl)
{
        Mutex::AutoLocker l(mutex);
	bool found = false;

	if (!node)
		return false;

	// There may be undefined nodes in the node store that should
	// be removed/merged with a 'defined' node that we create from a
	// node description. We loop through all nodes in the store and
	// compare their interface lists with the one in the 'defined' node.
	// If any interfaces match, we remove the matching nodes in the store
	// and eventually replace them with the new one.
	for (NodeStore::iterator it = begin(); it != end();) {
		NodeRecord *nr = *it;
		bool found_now = false;

		nr->node.lock();

		const InterfaceRefList *ifaces = nr->node->getInterfaces();

		for (InterfaceRefList::const_iterator it2 = ifaces->begin(); it2 != ifaces->end(); it2++) {
			InterfaceRef iface = *it2;

			if (node->hasInterface(iface)) {
				// Transfer all the "up" interface states to the updated node
				if (iface->isUp())
					node->setInterfaceUp(iface);

				found_now = true;
			}
		}
		nr->node.unlock();

		if (found_now) {
			if (nl)
				nl->push_back(nr->node);

			nr->node->setStored(false);

			node->setExchangedNodeDescription(nr->node->hasExchangedNodeDescription());

			it = erase(it);
			delete nr;
			found = true;
		} else {
			it++;
		}
	}
	if (found) {
		node->setStored(true);
		push_back(new NodeRecord(node));
	}

	return found;
}

// Remove neighbor with a specified interface
NodeRef NodeStore::remove(const InterfaceRef &iface)
{
        Mutex::AutoLocker l(mutex);

	if (!iface)
		return NULL;

	for (NodeStore::iterator it = begin(); it != end(); it++) {
		NodeRecord *nr = *it;

		if (nr->node->hasInterface(iface)) {
			NodeRef node = nr->node;
			erase(it);
			node->setStored(false);
			delete nr;
			return node;
		}
	}

	return NULL;
}

// Remove all nodes of a specific type
int NodeStore::remove(const Node::Type_t type)
{
        Mutex::AutoLocker l(mutex);
	int n = 0;

	NodeStore::iterator it = begin();

	while (it != end()) {
		NodeRecord *nr = *it;

		if (nr->node->getType() == type) {
			it = erase(it);
			n++;
			nr->node->setStored(false);
			delete nr;
			continue;
		}
		it++;
	}

	return n;
}

// Remove neighbor with a specified interface
bool NodeStore::remove(const NodeRef &node)
{
        Mutex::AutoLocker l(mutex);

	if (!node)
		return false;

	for (NodeStore::iterator it = begin(); it != end(); it++) {
		NodeRecord *nr = *it;

		if (nr->node == node) {
			erase(it);
			nr->node->setStored(false);
			delete nr;
			return true;
		}
	}

	return false;
}

#ifdef DEBUG
void NodeStore::print()
{
        Mutex::AutoLocker l(mutex);
	int n = 0;

	printf("======== Node store list ========\n\n");

	if (empty()) {
		printf("No nodes in store\n");
		return;
	}
	for (NodeStore::iterator it = begin(); it != end(); it++) {
		const NodeRecord *nr = *it;

                printf("Node: %d type=\'%s\' name=\'%s\' - %s stored=%s\n",
                       n++, nr->node->getTypeStr(),
                       nr->node->getName().c_str(),
                       (nr->node->isAvailable() && (nr->node->getType() == Node::TYPE_PEER || nr->node->getType() == Node::TYPE_UNDEFINED)) ? "Neighbor" : "Unconfirmed neighbor",
                       nr->node->isStored() ? "Yes" : "No");
		printf("Num objects in bloomfilter=%lu\n", nr->node->getBloomfilter()->numObjects());
                printf("id=%s\n", nr->node->getIdStr());
                printf("");
		nr->node->printInterfaces();

		const Attributes *attrs = nr->node->getAttributes();

		if (attrs->size()) {
			printf("Interests:\n");
			for (Attributes::const_iterator itt = attrs->begin(); itt != attrs->end(); itt++) {
				printf("\t\t%s\n", (*itt).second.getString().c_str());
			}
		}
	}

	printf("===============================\n\n");
}
#endif


text:
require 'spec_helper'

describe 'glance::client' do
  it { should contain_package('python-glance').with_ensure('present') }
end