text:
package com.icegreen.greenmail.test;

import com.icegreen.greenmail.junit.GreenMailRule;
import com.icegreen.greenmail.util.GreenMailUtil;
import com.icegreen.greenmail.util.Retriever;
import com.icegreen.greenmail.util.ServerSetup;
import com.icegreen.greenmail.util.ServerSetupTest;
import com.sun.mail.imap.AppendUID;
import com.sun.mail.imap.IMAPFolder;
import com.sun.mail.imap.IMAPStore;
import jakarta.mail.*;
import jakarta.mail.event.MessageCountEvent;
import jakarta.mail.event.MessageCountListener;
import jakarta.mail.internet.MimeMessage;
import jakarta.mail.internet.MimeMultipart;
import org.junit.Rule;
import org.junit.Test;

import java.io.ByteArrayOutputStream;
import java.util.Date;

import static jakarta.mail.Flags.Flag.DELETED;
import static org.assertj.core.api.Assertions.*;

public class ImapServerTest {
    private static final String UMLAUTS = "öäü \u00c4 \u00e4";
    @Rule
    public final GreenMailRule greenMail = new GreenMailRule(new ServerSetup[]{
        ServerSetupTest.IMAP,
        ServerSetupTest.IMAPS,
        ServerSetupTest.SMTP,
        ServerSetupTest.SMTPS
    });

    /**
     * Tests simple send and retrieve, including umlauts.
     *
     * @throws Exception on error.
     */
    @Test
    public void testRetrieveSimple() throws Exception {
        assertThat(greenMail.getImap()).isNotNull();
        final String subject = GreenMailUtil.random() + UMLAUTS;
        final String body = GreenMailUtil.random()
            + "\r\n" + " öäü \u00c4 \u00e4"
            + "\r\n" + GreenMailUtil.random();
        final String to = "test@localhost";
        MimeMessage mimeMessage = new MimeMessage(greenMail.getSmtp().createSession());
        mimeMessage.setSentDate(new Date());
        mimeMessage.setFrom("from@localhost");
        mimeMessage.setRecipients(Message.RecipientType.TO, to);

        mimeMessage.setSubject(subject, "UTF-8"); // Need to explicitly set encoding
        mimeMessage.setText(body, "UTF-8");
        Transport.send(mimeMessage);

        greenMail.waitForIncomingEmail(5000, 1);

        try (Retriever retriever = new Retriever(greenMail.getImap())) {
            Message[] messages = retriever.getMessages(to);
            assertThat(messages.length).isEqualTo(1);
            assertThat(messages[0].getSubject()).isEqualTo(subject);
            assertThat(((String) messages[0].getContent())).isEqualTo(body);
        }
    }

    @Test
    public void testImapsReceive() throws Throwable {
        assertThat(greenMail.getImaps()).isNotNull();
        final String subject = GreenMailUtil.random();
        final String body = GreenMailUtil.random();
        String to = "test@localhost";
        GreenMailUtil.sendTextEmailSecureTest(to, "from@localhost", subject, body);
        greenMail.waitForIncomingEmail(5000, 1);

        try (Retriever retriever = new Retriever(greenMail.getImaps())) {
            Message[] messages = retriever.getMessages(to);
            assertThat(messages.length).isEqualTo(1);
            assertThat(messages[0].getSubject()).isEqualTo(subject);
            assertThat(((String) messages[0].getContent())).isEqualTo(body);
        }
    }

    @Test
    public void testRetrieveSimpleWithNonDefaultPassword() throws Exception {
        assertThat(greenMail.getImap()).isNotNull();
        final String to = "test@localhost";
        final String password = "donotharmanddontrecipricateharm";
        greenMail.setUser(to, password);
        final String subject = GreenMailUtil.random();
        final String body = GreenMailUtil.random();
        GreenMailUtil.sendTextEmailTest(to, "from@localhost", subject, body);
        greenMail.waitForIncomingEmail(5000, 1);

        try (Retriever retriever = new Retriever(greenMail.getImap())) {
            assertThatThrownBy(() -> retriever.getMessages(to, "wrongpassword"))
                .isInstanceOf(RuntimeException.class)
                .hasCauseInstanceOf(AuthenticationFailedException.class);

            Message[] messages = retriever.getMessages(to, password);
            assertThat(messages.length).isEqualTo(1);
            assertThat(messages[0].getSubject()).isEqualTo(subject);
            assertThat(((String) messages[0].getContent())).isEqualTo(body);
        }
    }

    @Test
    public void testRetrieveMultipart() throws Exception {
        assertThat(greenMail.getImap()).isNotNull();

        String subject = GreenMailUtil.random();
        String body = GreenMailUtil.random();
        String to = "test@localhost";
        GreenMailUtil.sendAttachmentEmail(to, "from@localhost", subject, body, new byte[]{0, 1, 2}, "image/gif", "testimage_filename", "testimage_description", ServerSetupTest.SMTP);
        greenMail.waitForIncomingEmail(5000, 1);

        try (Retriever retriever = new Retriever(greenMail.getImap())) {
            Message[] messages = retriever.getMessages(to);

            Object o = messages[0].getContent();
            assertThat(o instanceof MimeMultipart).isTrue();
            MimeMultipart mp = (MimeMultipart) o;
            assertThat(mp.getCount()).isEqualTo(2);
            BodyPart bp;
            bp = mp.getBodyPart(0);
            assertThat(bp.getContent()).isEqualTo(body);

            bp = mp.getBodyPart(1);
            assertThat(GreenMailUtil.getBody(bp)).isEqualTo("AAEC");

            ByteArrayOutputStream bout = new ByteArrayOutputStream();
            GreenMailUtil.copyStream(bp.getInputStream(), bout);
            byte[] gif = bout.toByteArray();
            for (int i = 0; i < gif.length; i++) {
                assertThat((int) gif[i]).isEqualTo(i);
            }
        }
    }

    @Test
    public void testQuota() throws Exception {
        greenMail.setUser("foo@localhost", "pwd");
        GreenMailUtil.sendTextEmail("foo@localhost", "bar@localhost", "Test subject", "Test message", ServerSetupTest.SMTP);
        greenMail.waitForIncomingEmail(1);

        final IMAPStore store = greenMail.getImap().createStore();
        store.connect("foo@localhost", "pwd");
        try {
            IMAPFolder folder = (IMAPFolder) store.getFolder("INBOX");
            folder.open(Folder.READ_ONLY);
            Message[] msgs = folder.getMessages();
            assertThat(null != msgs && msgs.length == 1).isTrue();

            Quota testQuota = new Quota("INBOX");
            testQuota.setResourceLimit("STORAGE", 1024L * 42L);
            testQuota.setResourceLimit("MESSAGES", 5L);

            store.setQuota(testQuota);

            Quota[] quotas = store.getQuota("INBOX");
            assertThat(quotas).isNotNull();
            assertThat(quotas.length).isEqualTo(1);
            assertThat(quotas[0].resources).isNotNull();
            assertThat(quotas[0].resources.length).isEqualTo(2);
            assertThat(quotas[0].quotaRoot).isEqualTo(testQuota.quotaRoot);
            assertThat(testQuota.resources[0].limit).isEqualTo(quotas[0].resources[0].limit);
            assertThat(testQuota.resources[1].limit).isEqualTo(quotas[0].resources[1].limit);
            assertThat(1).isEqualTo(quotas[0].resources[1].usage);
//            assertThat(m.getSize()).isEqualTo(quotas[0].resources[0].usage);

            quotas = store.getQuota("");
            assertThat(quotas).isNotNull();
            assertThat(quotas.length).isEqualTo(0);
            // TODO: Quota on ""
        } finally {
            store.close();
        }
    }

    @Test
    public void testQuotaCapability() throws MessagingException {
        greenMail.setUser("foo@localhost", "pwd");
        greenMail.setQuotaSupported(false);
        try (IMAPStore store = greenMail.getImap().createStore()) {
            store.connect("foo@localhost", "pwd");

            try {
                Quota testQuota = new Quota("INBOX");
                testQuota.setResourceLimit("STORAGE", 1024L * 42L);
                testQuota.setResourceLimit("MESSAGES", 5L);
                store.setQuota(testQuota);
                fail("Excepted MessageException since quota capability is turned off");
            } catch (MessagingException ex) {
                assertThat("QUOTA not supported").isEqualTo(ex.getMessage());
            }
        }
    }

    @Test
    public void testSetGetFlags() throws MessagingException {
        greenMail.setUser("foo@localhost", "pwd");
        GreenMailUtil.sendTextEmail("foo@localhost", "bar@localhost", "Test subject", "Test message", ServerSetupTest.SMTP);
        greenMail.waitForIncomingEmail(1);

        final IMAPStore store = greenMail.getImap().createStore();
        store.connect("foo@localhost", "pwd");
        try {

            // Set some flags
            IMAPFolder folder = (IMAPFolder) store.getFolder("INBOX");
            folder.open(Folder.READ_ONLY);
            try {
                Message[] msgs = folder.getMessages();
                assertThat(null != msgs && msgs.length == 1).isTrue();

                Message m = msgs[0];

                Flags f = m.getFlags();
                assertThat(f.contains(Flags.Flag.DRAFT)).isFalse();
                assertThat(f.contains("foobar")).isFalse();
                m.setFlag(Flags.Flag.DRAFT, true);
                final Flags foobar = new Flags("foobar");
                m.setFlags(foobar, true);
                assertThat(m.getFlags().contains(Flags.Flag.DRAFT)).isTrue();
                assertThat(m.getFlags().contains("foobar")).isTrue();
            } finally {
                folder.close(true);
            }

            // Re-read and validate
            folder = (IMAPFolder) store.getFolder("INBOX");
            folder.open(Folder.READ_ONLY);
            try {
                Message[] msgs = folder.getMessages();
                assertThat(null != msgs && msgs.length == 1).isTrue();
                Message m = msgs[0];
                Flags f = m.getFlags();
                assertThat(f.contains(Flags.Flag.DRAFT)).isTrue();
                assertThat(f.contains("foobar")).isTrue();
            } finally {
                folder.close(true);
            }
        } finally {
            store.close();
        }
    }

    @Test
    public void testNestedFolders() throws MessagingException {
        greenMail.setUser("foo@localhost", "pwd");
        final IMAPStore store = greenMail.getImap().createStore();
        store.connect("foo@localhost", "pwd");
        try {
            // Create some folders
            IMAPFolder folder = (IMAPFolder) store.getFolder("INBOX");
            IMAPFolder newFolder = (IMAPFolder) folder.getFolder("foo-folder");
            assertThat(newFolder.exists()).isFalse();

            assertThat(newFolder.create(Folder.HOLDS_FOLDERS | Folder.HOLDS_MESSAGES)).isTrue();
            assertThat(newFolder.create(Folder.HOLDS_FOLDERS | Folder.HOLDS_MESSAGES)).isFalse();

            // Re-read and validate
            folder = (IMAPFolder) store.getFolder("INBOX");
            newFolder = (IMAPFolder) folder.getFolder("foo-folder");
            assertThat(newFolder.exists()).isTrue();
        } finally {
            store.close();
        }
    }

    /**
     * https://tools.ietf.org/html/rfc3501#page-37 :
     * <q>
     * Renaming INBOX is permitted, and has special behavior.  It moves
     * all messages in INBOX to a new mailbox with the given name,
     * leaving INBOX empty.  If the server implementation supports
     * inferior hierarchical names of INBOX, these are unaffected by a
     * rename of INBOX.
     * </q>
     */
    @Test
    public void testRenameINBOXFolder() throws MessagingException {
        greenMail.setUser("foo@localhost", "pwd");
        GreenMailUtil.sendTextEmail("foo@localhost", "bar@localhost", "Test subject",
            "Test message", greenMail.getSmtp().getServerSetup());

        final IMAPStore store = greenMail.getImap().createStore();
        store.connect("foo@localhost", "pwd");
        try {

            // Create some folders
            Folder inboxFolder = store.getFolder("INBOX");
            assertThat(inboxFolder.exists()).isTrue();
            inboxFolder.open(Folder.READ_ONLY);
            assertThat(inboxFolder.getMessages().length).isEqualTo(1);

            Folder inboxRenamedFolder = store.getFolder("INBOX-renamed");
            assertThat(inboxRenamedFolder.exists()).isFalse();

            inboxFolder.close(true);
            inboxFolder.renameTo(inboxRenamedFolder);
            assertThat(inboxRenamedFolder.exists()).isTrue();
            inboxRenamedFolder.open(Folder.READ_ONLY);
            assertThat(inboxRenamedFolder.getMessages().length).isEqualTo(1);

            inboxFolder = store.getFolder("INBOX");
            assertThat(inboxFolder.exists()).isTrue();
            inboxFolder.open(Folder.READ_ONLY);
            assertThat(inboxFolder.getMessages().length).isEqualTo(0);
        } finally {
            store.close();
        }
    }

    @Test
    public void testRenameFolder() throws MessagingException {
        greenMail.setUser("foo@localhost", "pwd");

        final IMAPStore store = greenMail.getImap().createStore();
        store.connect("foo@localhost", "pwd");
        try {

            // Create some folders
            Folder inboxFolder = store.getFolder("INBOX");
            Folder newFolder = inboxFolder.getFolder("foo-folder");
            assertThat(newFolder.create(Folder.HOLDS_FOLDERS | Folder.HOLDS_MESSAGES)).isTrue();
            assertThat(newFolder.exists()).isTrue();

            Folder renamedFolder = inboxFolder.getFolder("foo-folder-renamed");
            assertThat(renamedFolder.exists()).isFalse();

            // Rename
            assertThat(newFolder.renameTo(renamedFolder)).isTrue();
            assertThat(newFolder.exists()).isFalse();
            assertThat(renamedFolder.exists()).isTrue();

            // Rename with sub folder
            Folder subFolder = renamedFolder.getFolder("bar");
            assertThat(subFolder.create(Folder.HOLDS_FOLDERS | Folder.HOLDS_MESSAGES)).isTrue();
            assertThat(subFolder.exists()).isTrue();

            Folder renamedFolder2 = inboxFolder.getFolder("foo-folder-renamed-again");
            assertThat(renamedFolder.renameTo(renamedFolder2)).isTrue();
            assertThat(renamedFolder.exists()).isFalse();
            assertThat(renamedFolder2.exists()).isTrue();
            assertThat(renamedFolder2.getFolder("bar").exists()).isTrue(); // check that sub folder still exists

            // Rename to a different parent folder
            // INBOX.foo-folder-renamed-again -> INBOX.foo2.foo3
            Folder foo2Folder = inboxFolder.getFolder("foo2");
            assertThat(foo2Folder.create(Folder.HOLDS_FOLDERS | Folder.HOLDS_MESSAGES)).isTrue();
            assertThat(foo2Folder.exists()).isTrue();
            Folder foo3Folder = foo2Folder.getFolder("foo3");
            assertThat(foo3Folder.exists()).isFalse();

            renamedFolder2.renameTo(foo3Folder);
            assertThat(inboxFolder.getFolder("foo2.foo3").exists()).isTrue();
            assertThat(inboxFolder.getFolder("foo-folder-renamed-again").exists()).isFalse();
        } finally {
            store.close();
        }
    }

    @Test
    public void testFolderMoveMessages() throws MessagingException {
        int msgCount = 3;
        sendMessages(msgCount);

        final IMAPStore store = greenMail.getImap().createStore();
        store.connect("foo@localhost", "pwd");
        try {
            IMAPFolder inboxFolder = (IMAPFolder) store.getFolder("INBOX");

            // Target folder
            IMAPFolder targetFolder = (IMAPFolder) inboxFolder.getFolder("target-folder");
            assertThat(targetFolder.create(Folder.HOLDS_FOLDERS | Folder.HOLDS_MESSAGES)).isTrue();
            assertThat(targetFolder.exists()).isTrue();

            inboxFolder.open(Folder.READ_WRITE);
            try {
                final Message[] messages = inboxFolder.getMessages();
                assertThat(messages).hasSize(msgCount);
                assertThat(targetFolder.getMessageCount()).isEqualTo(0);
                inboxFolder.moveMessages(messages, targetFolder);
            } finally {
                inboxFolder.close();
            }

            targetFolder.open(Folder.READ_ONLY); // Refresh for new messages
            try {
                assertThat(targetFolder.getMessageCount()).isEqualTo(msgCount);
            } finally {
                targetFolder.close();
            }
        } finally {
            store.close();
        }
    }

    @Test
    public void testFolderMoveMessagesBasedOnUid() throws MessagingException {
        int msgCount = 3;
        sendMessages(msgCount);
        IMAPStore store = greenMail.getImap().createStore();
        store.connect("foo@localhost", "pwd");
        try {
            IMAPFolder inboxFolder = (IMAPFolder) store.getFolder("INBOX");

            // Target folder
            IMAPFolder targetFolder = (IMAPFolder) inboxFolder.getFolder("target-folder");
            assertThat(targetFolder.create(Folder.HOLDS_FOLDERS | Folder.HOLDS_MESSAGES)).isTrue();
            assertThat(targetFolder.exists()).isTrue();

            inboxFolder.open(Folder.READ_WRITE);

            Message[] existingMessages = inboxFolder.getMessages();
            assertThat(existingMessages.length).isEqualTo(3);
            for (int i = 0; i < 3; i++) {
                final int uid = i + 1;
                Message[] messages = inboxFolder.getMessagesByUID(
                    new long[]{uid});
                assertThat(messages).hasSize(1);
                inboxFolder.moveMessages(messages, targetFolder);
            }
            targetFolder.open(Folder.READ_ONLY); // Refresh for new messages
            try {
                assertThat(targetFolder.getMessageCount()).isEqualTo(msgCount);
            } finally {
                targetFolder.close();
            }
        } finally {
            store.close();
        }
    }

    private void sendMessages(int n) {
        greenMail.setUser("foo@localhost", "pwd");

        int msgCount = n;
        for (int i = 0; i < n; i++) {
            GreenMailUtil.sendTextEmail("foo@localhost", "bar@localhost", "Test subject #" + i,
                "Test message", ServerSetupTest.SMTP);
        }
        greenMail.waitForIncomingEmail(msgCount);

    }

    @Test
    public void testFolderMoveUIDMessages() throws MessagingException {
        greenMail.setUser("foo@localhost", "pwd");

        int msgCount = 3;
        for (int i = 0; i < 3; i++) {
            GreenMailUtil.sendTextEmail("foo@localhost", "bar@localhost", "Test subject #" + i,
                "Test message", ServerSetupTest.SMTP);
        }
        greenMail.waitForIncomingEmail(msgCount);

        final IMAPStore store = greenMail.getImap().createStore();
        store.connect("foo@localhost", "pwd");
        try {
            IMAPFolder inboxFolder = (IMAPFolder) store.getFolder("INBOX");

            // Target folder
            IMAPFolder targetFolder = (IMAPFolder) inboxFolder.getFolder("target-folder");
            assertThat(targetFolder.create(Folder.HOLDS_FOLDERS | Folder.HOLDS_MESSAGES)).isTrue();
            assertThat(targetFolder.exists()).isTrue();

            inboxFolder.open(Folder.READ_WRITE);
            try {
                final Message[] messages = inboxFolder.getMessages();
                assertThat(messages).hasSize(msgCount);
                assertThat(targetFolder.getMessageCount()).isEqualTo(0);
                inboxFolder.moveUIDMessages(messages, targetFolder);
            } finally {
                inboxFolder.close();
            }

            targetFolder.open(Folder.READ_ONLY); // Refresh for new messages
            try {
                assertThat(targetFolder.getMessageCount()).isEqualTo(msgCount);
            } finally {
                targetFolder.close();
            }
        } finally {
            store.close();
        }
    }

    @Test
    public void testFolderRequiringEscaping() throws MessagingException {
        greenMail.setUser("foo@localhost", "pwd");
        GreenMailUtil.sendTextEmail("foo@localhost", "foo@localhost", "test subject", "", greenMail.getSmtp().getServerSetup());

        final IMAPStore store = greenMail.getImap().createStore();
        store.connect("foo@localhost", "pwd");
        try {

            // Create some folders
            Folder inboxFolder = store.getFolder("INBOX");
            inboxFolder.open(Folder.READ_ONLY);

            final Folder folderRequiringEscaping = inboxFolder.getFolder("requires escaping Ä");
            assertThat(folderRequiringEscaping.create(Folder.HOLDS_FOLDERS | Folder.HOLDS_MESSAGES)).isTrue();
            folderRequiringEscaping.open(Folder.READ_WRITE);

            assertThat(folderRequiringEscaping.getMessageCount()).isEqualTo(0);
            assertThat(inboxFolder.getMessageCount()).isEqualTo(1);

            inboxFolder.copyMessages(inboxFolder.getMessages(), folderRequiringEscaping);

            folderRequiringEscaping.expunge(); // invalidates folder cache
            assertThat(folderRequiringEscaping.getMessageCount()).isEqualTo(1);
        } finally {
            store.close();
        }
    }

    @Test
    public void testUIDFolder() throws MessagingException {
        greenMail.setUser("foo@localhost", "pwd");

        GreenMailUtil.sendTextEmail("foo@localhost", "bar@localhost", "Test UIDFolder",
            "Test message", greenMail.getSmtp().getServerSetup());
        final IMAPStore store = greenMail.getImap().createStore();
        store.connect("foo@localhost", "pwd");
        try {
            Folder inboxFolder = store.getFolder("INBOX");
            inboxFolder.open(Folder.READ_WRITE);

            Message[] messages = inboxFolder.getMessages();
            assertThat(messages.length).isEqualTo(1);
            Message message = messages[0];

            assert inboxFolder instanceof UIDFolder;
            UIDFolder uidFolder = (UIDFolder) inboxFolder;
            long uid = uidFolder.getUID(message);
            assertThat(uidFolder.getMessageByUID(uid)).isEqualTo(message);
            Message[] uidMessages = uidFolder.getMessagesByUID(new long[]{uid});
            assertThat(uidMessages.length).isEqualTo(1);
            assertThat(uidMessages[0]).isEqualTo(message);
            uidMessages = uidFolder.getMessagesByUID(uid, uid);
            assertThat(uidMessages.length).isEqualTo(1);
            assertThat(uidMessages[0]).isEqualTo(message);
        } finally {
            store.close();
        }
    }

    @Test
    public void testUIDExpunge() throws MessagingException {
        greenMail.setUser("foo@localhost", "pwd");

        // Create some test emails
        int numberOfEmails = 10;
        long[] uids = new long[numberOfEmails];
        for (int i = 0; i < numberOfEmails; i++) {
            GreenMailUtil.sendTextEmail("foo@localhost", "bar@localhost", "Test UID expunge #" + i,
                "Test message", greenMail.getSmtp().getServerSetup());
        }

        final IMAPStore store = greenMail.getImap().createStore();
        store.connect("foo@localhost", "pwd");
        try {
            IMAPFolder folder = (IMAPFolder) store.getFolder("INBOX");
            folder.open(Folder.READ_WRITE);

            Message[] messages = folder.getMessages();
            assertThat(messages.length).isEqualTo(numberOfEmails);

            // Mark even as deleted ...
            Message[] msgsForDeletion = new Message[uids.length / 2];
            for (int i = 0; i < messages.length; i++) {
                assertThat(messages[i].getFlags().contains(Flags.Flag.DELETED)).isFalse();
                uids[i] = folder.getUID(messages[i]);
                if (i % 2 == 0) { // Deleted
                    messages[i].setFlag(Flags.Flag.DELETED, true);
                    msgsForDeletion[i / 2] = messages[i];
                }
            }

            // ... and expunge (with UID)
            folder.expunge(msgsForDeletion);

            // Check
            for (int i = 0; i < uids.length; i++) {
                final Message message = folder.getMessageByUID(uids[i]);
                if (i % 2 == 0) { // Deleted
                    assertThat(message).isNull();
                } else {
                    assertThat(message.isExpunged()).as("" + i).isFalse();
                    assertThat(message.getFlags().contains(DELETED)).as("" + i).isFalse();
                }
            }
        } finally {
            store.close();
        }
    }

    @Test
    public void testAppend() throws MessagingException {
        greenMail.setUser("foo@localhost", "pwd");

        GreenMailUtil.sendTextEmail("foo@localhost", "bar@localhost", "Test Append",
            "Test message", greenMail.getSmtp().getServerSetup());

        final IMAPStore store = greenMail.getImap().createStore();
        store.connect("foo@localhost", "pwd");
        try {
            IMAPFolder inboxFolder = (IMAPFolder) store.getFolder("INBOX");
            inboxFolder.open(Folder.READ_WRITE);

            Message[] messages = inboxFolder.getMessages();
            assertThat(messages.length).isEqualTo(1);
            Message message = messages[0];

            Message[] toBeAppended = new Message[]{
                new MimeMessage((MimeMessage) message) // Copy
            };
            toBeAppended[0].setSubject("testAppend#1");

            inboxFolder.appendMessages(toBeAppended);
            messages = inboxFolder.getMessages();
            assertThat(messages.length).isEqualTo(2);

            // UIDPLUS
            toBeAppended[0] = new MimeMessage((MimeMessage) message);
            toBeAppended[0].setSubject("testAppend#2");

            final AppendUID[] appendUIDs = inboxFolder.appendUIDMessages(toBeAppended); // Copy again
            long uid = appendUIDs[0].uid;
            Message newMsg = inboxFolder.getMessageByUID(uid);
            assertThat(newMsg.getSubject()).isEqualTo(toBeAppended[0].getSubject());
            assertThat(inboxFolder.getUIDValidity()).isEqualTo(appendUIDs[0].uidvalidity);
            messages = inboxFolder.getMessages();
            assertThat(messages.length).isEqualTo(3);
        } finally {
            store.close();
        }
    }

    @Test
    public void testUIDFetchWithWildcard() throws MessagingException {
        greenMail.setUser("foo@localhost", "pwd");

        GreenMailUtil.sendTextEmail("foo@localhost", "bar@localhost", "Test UIDFolder",
            "Test message", ServerSetupTest.SMTP);

        GreenMailUtil.sendTextEmail("foo@localhost", "bar@localhost", "Test UIDFolder 2",
            "Test message 2", ServerSetupTest.SMTP);
        final IMAPStore store = greenMail.getImap().createStore();
        store.connect("foo@localhost", "pwd");
        try {
            Folder inboxFolder = store.getFolder("INBOX");
            inboxFolder.open(Folder.READ_WRITE);

            Message[] messages = inboxFolder.getMessages();
            assertThat(messages.length).isEqualTo(2);
            Message message = messages[1];

            assert inboxFolder instanceof UIDFolder;
            UIDFolder uidFolder = (UIDFolder) inboxFolder;
            long uid = uidFolder.getUID(message);
            assertThat(uidFolder.getMessageByUID(uid)).isEqualTo(message);
            Message[] uidMessages = uidFolder.getMessagesByUID(uid, UIDFolder.LASTUID);
            assertThat(uidMessages.length).isEqualTo(1);
            assertThat(uidMessages[0]).isEqualTo(message);
            uidMessages = uidFolder.getMessagesByUID(uid + 1, UIDFolder.LASTUID);
            assertThat(uidMessages.length).isEqualTo(1);
            assertThat(uidMessages[0]).isEqualTo(message);
        } finally {
            store.close();
        }
    }

    @Test
    public void testExpunge() throws MessagingException {
        greenMail.setUser("foo@localhost", "pwd");

        for (int i = 0; i < 6; i++) {
            GreenMailUtil.sendTextEmail("foo@localhost", "bar@localhost", "Test subject #" + i,
                "Test message", ServerSetupTest.SMTP);
        }
        final IMAPStore store = greenMail.getImap().createStore();
        store.connect("foo@localhost", "pwd");
        try {
            Folder inboxFolder = store.getFolder("INBOX");
            inboxFolder.open(Folder.READ_WRITE);

            Message[] messages = inboxFolder.getMessages();
            assertThat(messages.length).isEqualTo(6);
            inboxFolder.setFlags(new int[]{2, 3}, new Flags(DELETED), true); // 1 and 2, offset is not zero-based

            assertThat(inboxFolder.getMessage(1).isSet(DELETED)).isFalse();
            assertThat(inboxFolder.getMessage(2).isSet(DELETED)).isTrue();
            assertThat(inboxFolder.getMessage(3).isSet(DELETED)).isTrue();
            assertThat(inboxFolder.getMessage(4).isSet(DELETED)).isFalse();
            assertThat(inboxFolder.getMessage(5).isSet(DELETED)).isFalse();
            assertThat(inboxFolder.getMessage(6).isSet(DELETED)).isFalse();
            assertThat(inboxFolder.getDeletedMessageCount()).isEqualTo(2);
            Message[] expunged = inboxFolder.expunge();
            assertThat(expunged.length).isEqualTo(2);

            messages = inboxFolder.getMessages();
            assertThat(messages.length).isEqualTo(4);
            assertThat(messages[0].getSubject()).isEqualTo("Test subject #0");
            assertThat(messages[1].getSubject()).isEqualTo("Test subject #3");
            assertThat(messages[2].getSubject()).isEqualTo("Test subject #4");
            assertThat(messages[3].getSubject()).isEqualTo("Test subject #5");
        } finally {
            store.close();
        }
    }

    @Test(timeout = 10000)
    public void testIdle() throws MessagingException {
        greenMail.setUser("foo@localhost", "pwd");

        final IMAPStore store = greenMail.getImap().createStore();
        store.connect("foo@localhost", "pwd");
        try {
            Folder inboxFolder = store.getFolder("INBOX");
            inboxFolder.open(Folder.READ_ONLY);
            int[] messages = new int[]{0};
            MessageCountListener listener = new MessageCountListener() {
                @Override
                public void messagesRemoved(MessageCountEvent e) {
                }

                @Override
                public void messagesAdded(MessageCountEvent e) {
                    messages[0] = e.getMessages()[0].getMessageNumber();
                }
            };
            inboxFolder.addMessageCountListener(listener);
            new Thread(() -> {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e1) {
                    // Ignore
                }
                GreenMailUtil.sendTextEmail("foo@localhost", "bar@localhost", "Test subject", "Test message",
                    ServerSetupTest.SMTP);
            }).start();
            ((IMAPFolder) inboxFolder).idle(true);
            assertThat(messages).hasSize(1);
            assertThat(messages[0]).isGreaterThan(0);
            inboxFolder.close();
        } finally {
            store.close();
        }
    }
}


text:
import logging
import ntpath
import os
import random
import tempfile
import time
from contextlib import contextmanager
from functools import wraps

import luigi.format
from luigi.target import FileSystem, FileSystemTarget, AtomicLocalFile

logger = logging.getLogger('luigi-interface')

try:
    import dropbox.dropbox
    import dropbox.exceptions
    import dropbox.files
except ImportError:
    logger.warning("Loading Dropbox module without the python package dropbox (https://pypi.org/project/dropbox/). "
                   "Will crash at runtime if Dropbox functionality is used.")

def accept_trailing_slash_in_existing_dirpaths(func):
    @wraps(func)
    def wrapped(self, path, *args, **kwargs):
        if path != '/' and path.endswith('/'):
            logger.warning("Dropbox paths should NOT have trailing slashes. This causes additional API calls")
            logger.warning("Consider modifying your calls to {}, so that they don't use paths than end with '/'".format(func.__name__))

            if self._exists_and_is_dir(path[:-1]):
                path = path[:-1]

        return func(self, path, *args, **kwargs)

    return wrapped

def accept_trailing_slash(func):
    @wraps(func)
    def wrapped(self, path, *args, **kwargs):
        if path != '/' and path.endswith('/'):
            path = path[:-1]
        return func(self, path, *args, **kwargs)

    return wrapped

class DropboxClient(FileSystem):
    """
    Dropbox client for authentication, designed to be used by the :py:class:`DropboxTarget` class.
    """

    def __init__(self, token, user_agent="Luigi"):
        """
        :param str token: Dropbox Oauth2 Token. See :class:`DropboxTarget` for more information about generating a token
        """
        if not token:
            raise ValueError("The token parameter must contain a valid Dropbox Oauth2 Token")

        try:
            conn = dropbox.dropbox.Dropbox(oauth2_access_token=token, user_agent=user_agent)
        except Exception as e:
            raise Exception("Cannot connect to Dropbox. Check your Internet connection and the token. \n" + repr(e))

        self.token = token
        self.conn = conn

    @accept_trailing_slash_in_existing_dirpaths
    def exists(self, path):
        if path == '/':
            return True
        if path.endswith('/'):
            path = path[:-1]
            return self._exists_and_is_dir(path)

        try:
            self.conn.files_get_metadata(path)
            return True
        except dropbox.exceptions.ApiError as e:
            if isinstance(e.error.get_path(), dropbox.files.LookupError):
                return False
            else:
                raise e

    @accept_trailing_slash_in_existing_dirpaths
    def remove(self, path, recursive=True, skip_trash=True):
        if not self.exists(path):
            return False
        self.conn.files_delete_v2(path)
        return True

    @accept_trailing_slash
    def mkdir(self, path, parents=True, raise_if_exists=False):
        if self.exists(path):
            if not self.isdir(path):
                raise luigi.target.NotADirectory()
            elif raise_if_exists:
                raise luigi.target.FileAlreadyExists()
            else:
                return

        self.conn.files_create_folder_v2(path)

    @accept_trailing_slash_in_existing_dirpaths
    def isdir(self, path):
        if path == '/':
            return True
        try:
            md = self.conn.files_get_metadata(path)
            return isinstance(md, dropbox.files.FolderMetadata)
        except dropbox.exceptions.ApiError as e:
            if isinstance(e.error.get_path(), dropbox.files.LookupError):
                return False
            else:
                raise e

    @accept_trailing_slash_in_existing_dirpaths
    def listdir(self, path, **kwargs):
        dirs = []
        lister = self.conn.files_list_folder(path, recursive=True, **kwargs)
        dirs.extend(lister.entries)
        while lister.has_more:
            lister = self.conn.files_list_folder_continue(lister.cursor)
            dirs.extend(lister.entries)
        return [d.path_display for d in dirs]

    @accept_trailing_slash_in_existing_dirpaths
    def move(self, path, dest):
        self.conn.files_move_v2(from_path=path, to_path=dest)

    @accept_trailing_slash_in_existing_dirpaths
    def copy(self, path, dest):
        self.conn.files_copy_v2(from_path=path, to_path=dest)

    def download_as_bytes(self, path):
        metadata, response = self.conn.files_download(path)
        return response.content

    def upload(self, tmp_path, dest_path):
        with open(tmp_path, 'rb') as f:
            file_size = os.path.getsize(tmp_path)

            CHUNK_SIZE = 4 * 1000 * 1000
            upload_session_start_result = self.conn.files_upload_session_start(f.read(CHUNK_SIZE))
            commit = dropbox.files.CommitInfo(path=dest_path)
            cursor = dropbox.files.UploadSessionCursor(session_id=upload_session_start_result.session_id,
                                                       offset=f.tell())

            if f.tell() >= file_size:
                self.conn.files_upload_session_finish(f.read(CHUNK_SIZE), cursor, commit)
                return

            while f.tell() < file_size:
                if (file_size - f.tell()) <= CHUNK_SIZE:
                    self.conn.files_upload_session_finish(f.read(CHUNK_SIZE), cursor, commit)
                else:
                    self.conn.files_upload_session_append_v2(f.read(CHUNK_SIZE), cursor)
                    cursor.offset = f.tell()

    def _exists_and_is_dir(self, path):
        """
        Auxiliary method, used by the 'accept_trailing_slash' and 'accept_trailing_slash_in_existing_dirpaths' decorators
        :param path: a Dropbox path that does NOT ends with a '/' (even if it is a directory)
        """
        if path == '/':
            return True
        try:
            md = self.conn.files_get_metadata(path)
            is_dir = isinstance(md, dropbox.files.FolderMetadata)
            return is_dir
        except dropbox.exceptions.ApiError:
            return False

class ReadableDropboxFile:
    def __init__(self, path, client):
        """
        Represents a file inside the Dropbox cloud which will be read

        :param str path: Dropbpx path of the file to be read (always starting with /)
        :param DropboxClient client: a DropboxClient object (initialized with a valid token)

        """
        self.path = path
        self.client = client
        self.download_file_location = os.path.join(tempfile.mkdtemp(prefix=str(time.time())),
                                                   ntpath.basename(path))
        self.fid = None
        self.closed = False

    def read(self):
        return self.client.download_as_bytes(self.path)

    def __enter__(self):
        return self

    def __exit__(self, exc_type, exc, traceback):
        self.close()

    def __del__(self):
        self.close()
        if os.path.exists(self.download_file_location):
            os.remove(self.download_file_location)

    def close(self):
        self.closed = True

    def readable(self):
        return True

    def writable(self):
        return False

    def seekable(self):
        return False

class AtomicWritableDropboxFile(AtomicLocalFile):
    def __init__(self, path, client):
        """
        Represents a file that will be created inside the Dropbox cloud

        :param str path: Destination path inside Dropbox
        :param DropboxClient client: a DropboxClient object (initialized with a valid token, for the desired account)
        """
        super(AtomicWritableDropboxFile, self).__init__(path)
        self.path = path
        self.client = client

    def move_to_final_destination(self):
        """
        After editing the file locally, this function uploads it to the Dropbox cloud
        """
        self.client.upload(self.tmp_path, self.path)

class DropboxTarget(FileSystemTarget):
    """
    A Dropbox filesystem target.
    """

    def __init__(self, path, token, format=None, user_agent="Luigi"):
        """
        Create an Dropbox Target for storing data in a dropbox.com account

        **About the path parameter**

        The path must start with '/' and should not end with '/' (even if it is a directory).
        The path must not contain adjacent slashes ('/files//img.jpg' is an invalid path)

        If the app has 'App folder' access, then / will refer to this app folder (which
        mean that there is no need to prepend the name of the app to the path)
        Otherwise, if the app has 'full access', then / will refer to the root of the Dropbox folder

        **About the token parameter:**

        The Dropbox target requires a valid OAuth2 token as a parameter (which means that a `Dropbox API app
        <https://www.dropbox.com/developers/apps>`_ must be created. This app can have 'App folder' access
        or 'Full Dropbox', as desired).

        Information about generating the token can be read here:

        - https://dropbox-sdk-python.readthedocs.io/en/latest/api/oauth.html#dropbox.oauth.DropboxOAuth2Flow
        - https://blogs.dropbox.com/developers/2014/05/generate-an-access-token-for-your-own-account/

        :param str path: Remote path in Dropbox (starting with '/').
        :param str token: a valid OAuth2 Dropbox token.
        :param luigi.Format format: the luigi format to use (e.g. `luigi.format.Nop`)

        """
        super(DropboxTarget, self).__init__(path)

        if not token:
            raise ValueError("The token parameter must contain a valid Dropbox Oauth2 Token")

        self.path = path
        self.token = token
        self.client = DropboxClient(token, user_agent)
        self.format = format or luigi.format.get_default_format()

    @property
    def fs(self):
        return self.client

    @contextmanager
    def temporary_path(self):
        tmp_dir = tempfile.mkdtemp()
        num = random.randrange(0, 10_000_000_000)
        temp_path = '{}{}luigi-tmp-{:010}{}'.format(
            tmp_dir, os.sep,
            num, ntpath.basename(self.path))

        yield temp_path
        # We won't reach here if there was an user exception.
        self.fs.upload(temp_path, self.path)

    def open(self, mode):
        if mode not in ('r', 'w'):
            raise ValueError("Unsupported open mode '%s'" % mode)
        if mode == 'r':
            return self.format.pipe_reader(ReadableDropboxFile(self.path, self.client))
        else:
            return self.format.pipe_writer(AtomicWritableDropboxFile(self.path, self.client))

redpajama_set_name: RedPajamaGithub


text:
<?php

use NoreSources\XML\XSH\ScriptBuilder;
use PHPUnit\Framework\TestCase;

class ScriptBuilderTest extends TestCase
{

	public function testShebang()
	{
		$b = new ScriptBuilder();
		foreach ([[false, false],
			'bash' => '#!/usb/bin/env bash',
			'my-interpreter' => '#!/usb/bin/env my-interpreter',
			'/full/path' => '#!/full/path',
			'#!/unnecessary/path' => '#!/unnecessary/path'
		] as $k => $test) {
			if (\is_array($test))
			{
				$value = $test[0];
				$expected = $test[1];
			}
			else
			{
				$value = $k;
				$expected = $test;
			}
			$b->shebang($value);
			$this->assertEquals($expected, $b->getShebang(),
				'Shebang for ' . \strval($value));
		}
	}

	public function testRender()
	{
		$expectedFile = $this->getExpectedFile(__METHOD__);
		$builder = new ScriptBuilder();
		$builder->shebang("#!/foo/bar")
			->search(\preg_replace('/\.php$/', '', __FILE__))
			->functions("wtf")
			->body("echo 'Calling the imported function function'")
			->body("ns_wtf");
		$actual = \trim($builder->render());
		$expected = file_get_contents($expectedFile);
		$expected = \trim(\str_replace("\r\n", "\n", $expected));
		$this->assertEquals($expected, $actual, 'Render');
	}

	public function getExpectedFile($method)
	{
		return __DIR__ . '/'
			. \preg_replace ('/.*\\\\/', '', static::class)
			. '.' . \preg_replace('/.*::/', '', $method) . '.expected';
	}
}


text:
This file contains high-level info about how ChromeDriver works and how to
contribute. If you are looking for information on how to use ChromeDriver,
please see the [ChromeDriver user site](https://chromedriver.chromium.org/).

ChromeDriver is an implementation of the
[WebDriver standard](https://w3c.github.io/webdriver/),
which allows users to automate testing of their website across browsers.

## Getting Started

Build ChromeDriver by building the `chromedriver` target, e.g.,

```
ninja -C out/Default chromedriver
```

This will create an executable binary in the build folder named
`chromedriver[.exe]`.

Once built, ChromeDriver can be used with various third-party libraries that
support WebDriver protocol, including language bindings provided by Selenium.

For testing purposes, ChromeDriver can be used interactively with python.
The following code uses our own testing API, not the commonly used Python
binding provided by Selenium.

```python
$ export PYTHONPATH=<THIS_DIR>/server:<THIS_DIR>/client
$ python
>>> import server
>>> import chromedriver
>>> cd_server = server.Server('/path/to/chromedriver/executable')
>>> driver = chromedriver.ChromeDriver(cd_server.GetUrl())
>>> driver.Load('http://www.google.com')
>>> driver.Quit()
>>> cd_server.Kill()
```

By default, ChromeDriver will look in its own directory for Chrome to use.
If Chrome is not found there, it will use the system installed Chrome.

To use ChromeDriver with Chrome on Android pass the Android package name in the
chromeOptions.androidPackage capability when creating the driver. The path to
adb_commands.py and the adb tool from the Android SDK must be set in PATH. For
more detailed instructions see the user site.

## Architecture

ChromeDriver is shipped separately from Chrome. It controls Chrome out of
process through [DevTools](https://chromedevtools.github.io/devtools-protocol/).
ChromeDriver is a standalone server which
communicates with the WebDriver client via the WebDriver wire protocol, which
is essentially synchronous JSON commands over HTTP. WebDriver clients are
available in many languages, and many are available from the open source
[Selenium WebDriver project](https://www.selenium.dev/).
ChromeDriver uses the webserver from
[net/server](https://source.chromium.org/chromium/chromium/src/+/master:net/server/).

Additional information is available on the following pages:
* [Threading](docs/threading.md): ChromeDriver threading model.
* [Chrome Connection](docs/chrome_connection.md):
  How ChromeDriver connects to Chrome and controls it.
* [DevTools Event Listener](docs/event_listener.md):
  How ChromeDriver responds to events from Chrome DevTools.
* [Run JavaScript Code](docs/run_javascript.md):
  How ChromeDriver sends JavaScript code to Chrome for execution.

## Code structure (relative to this file)

* [(this directory)](.):
Implements chromedriver commands.

* [chrome/](chrome/):
A basic interface for controlling Chrome. Should not depend on or reference
WebDriver-related code or concepts.

* [js/](js/):
Javascript helper scripts.

* [net/](net/):
Code to deal with network communication, such as connection to DevTools.

* [client/](client/):
Code for a python client.

* [server/](server/):
Code for the chromedriver server.
A python wrapper to the chromedriver server.

* [extension/](extension/):
An extension used for automating the desktop browser.

* [test/](test/):
Integration tests.

## Testing

There are several test suites for verifying ChromeDriver's correctness.
For details, see the [testing page](docs/testing.md).

## Contributing

Find an open issue and submit a patch for review by an individual listed in
the `OWNERS` file in this directory. Issues are tracked in
[ChromeDriver issue tracker](https://crbug.com/chromedriver).


text:
define(function (require) {
    'use strict';

    // TODO: use prototypes for creating options objects (automatically traverse up prototype chain, when necessary etc.)
    return function root(options) {
        return options.parent ? root(options.parent) : options;
    };
});


text:
<?php namespace Arcanedev\LogViewer\Tests\Utilities;

use Arcanedev\LogViewer\Tests\TestCase;
use Arcanedev\LogViewer\Utilities\LogChecker;

/**
 * Class     LogCheckerTest
 *
 * @package  Arcanedev\LogViewer\Tests\Utilities
 * @author   ARCANEDEV <arcanedev.maroc@gmail.com>
 */
class LogCheckerTest extends TestCase
{
    /* ------------------------------------------------------------------------------------------------
     |  Properties
     | ------------------------------------------------------------------------------------------------
     */
    /** @var LogChecker */
    private $checker;

    /* ------------------------------------------------------------------------------------------------
     |  Main Functions
     | ------------------------------------------------------------------------------------------------
     */
    public function setUp()
    {
        parent::setUp();

        $this->checker = app('arcanedev.log-viewer.checker');
    }

    public function tearDown()
    {
        unset($this->checker);

        parent::tearDown();
    }

    /* ------------------------------------------------------------------------------------------------
     |  Test Functions
     | ------------------------------------------------------------------------------------------------
     */
    /** @test */
    public function it_can_be_instantiated()
    {
        $this->assertInstanceOf(LogChecker::class, $this->checker);
    }

    /** @test */
    public function it_must_fails()
    {
        $this->assertFalse($this->checker->passes());
        $this->assertTrue($this->checker->fails());
    }

    /** @test */
    public function it_can_get_messages()
    {
        $messages = $this->checker->messages();

        $this->assertArrayHasKey('handler', $messages);
        $this->assertArrayHasKey('files', $messages);
        $this->assertEmpty($messages['handler']);
        $this->assertCount(3, $messages['files']);
        $this->assertArrayHasKey('laravel.log', $messages['files']);
    }

    /** @test */
    public function it_can_get_requirements()
    {
        $requirements = $this->checker->requirements();

        $this->assertArrayHasKey('status', $requirements);
        $this->assertEquals($requirements['status'], 'success');
        $this->assertArrayHasKey('header', $requirements);
        $this->assertEquals($requirements['header'], 'Application requirements fulfilled.');
    }

    /** @test */
    public function it_must_fail_the_requirements_on_handler()
    {
        config()->set('app.log', 'single');

        $requirements = $this->checker->requirements();

        $this->assertArrayHasKey('status', $requirements);
        $this->assertEquals($requirements['status'], 'failed');
        $this->assertArrayHasKey('header', $requirements);
        $this->assertEquals($requirements['header'], 'Application requirements failed.');
    }
}


text:
/**
 *
 */
package pt.ul.fc.di.lasige.simhs.core.domain.workload;

import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

/**
 * @author jcraveiro
 *
 */
public class Workload  implements Iterable<IAbsSchedulable> {

	private Set<IAbsSchedulable> taskset;

	public Workload() {
		this.taskset = new TreeSet<IAbsSchedulable>();
	}

	public void add(IAbsSchedulable abs){
		this.taskset.add(abs);
	}

	public void addTaskSet(Set<IAbsSchedulable> abs){
		this.taskset=abs;
	}

	public Iterator<IAbsSchedulable> iterator() {
		return this.taskset.iterator();
	}

	public int size(){
		return this.taskset.size();
	}

}


text:
package io.spring.gradle.convention;

import io.spring.gradle.IncludeRepoTask;
import org.apache.commons.io.FileUtils;
import org.gradle.api.Project;
import org.gradle.api.tasks.GradleBuild;
import org.gradle.testfixtures.ProjectBuilder;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.Test;

import java.util.Arrays;

import static org.assertj.core.api.Assertions.assertThat;

class IncludeCheckRemotePluginTest {

	Project rootProject;

	@AfterEach
	public void cleanup() throws Exception {
		if (rootProject != null) {
			FileUtils.deleteDirectory(rootProject.getProjectDir());
		}
	}

	@Test
	void applyWhenExtensionPropertiesNoTasksThenCreateCheckRemoteTaskWithDefaultTask() {
		this.rootProject = ProjectBuilder.builder().build();
		this.rootProject.getPluginManager().apply(IncludeCheckRemotePlugin.class);
		this.rootProject.getExtensions().configure(IncludeCheckRemotePlugin.IncludeCheckRemoteExtension.class,
				(includeCheckRemoteExtension) -> {
					includeCheckRemoteExtension.setProperty("repository", "my-project/my-repository");
					includeCheckRemoteExtension.setProperty("ref", "main");
				});

		GradleBuild checkRemote = (GradleBuild) this.rootProject.getTasks().named("checkRemote").get();
		assertThat(checkRemote.getTasks()).containsExactly("check");
	}

	@Test
	void applyWhenExtensionPropertiesTasksThenCreateCheckRemoteWithProvidedTasks() {
		this.rootProject = ProjectBuilder.builder().build();
		this.rootProject.getPluginManager().apply(IncludeCheckRemotePlugin.class);
		this.rootProject.getExtensions().configure(IncludeCheckRemotePlugin.IncludeCheckRemoteExtension.class,
				(includeCheckRemoteExtension) -> {
					includeCheckRemoteExtension.setProperty("repository", "my-project/my-repository");
					includeCheckRemoteExtension.setProperty("ref", "main");
					includeCheckRemoteExtension.setProperty("tasks", Arrays.asList("clean", "build", "test"));
				});

		GradleBuild checkRemote = (GradleBuild) this.rootProject.getTasks().named("checkRemote").get();
		assertThat(checkRemote.getTasks()).containsExactly("clean", "build", "test");
	}

	@Test
	void applyWhenExtensionPropertiesThenRegisterIncludeRepoTaskWithExtensionProperties() {
		this.rootProject = ProjectBuilder.builder().build();
		this.rootProject.getPluginManager().apply(IncludeCheckRemotePlugin.class);
		this.rootProject.getExtensions().configure(IncludeCheckRemotePlugin.IncludeCheckRemoteExtension.class,
				(includeCheckRemoteExtension) -> {
					includeCheckRemoteExtension.setProperty("repository", "my-project/my-repository");
					includeCheckRemoteExtension.setProperty("ref", "main");
				});

		IncludeRepoTask includeRepo = (IncludeRepoTask) this.rootProject.getTasks().named("includeRepo").get();
		assertThat(includeRepo).isNotNull();
		assertThat(includeRepo.getRepository().get()).isEqualTo("my-project/my-repository");
		assertThat(includeRepo.getRef().get()).isEqualTo("main");
	}

	@Test
	void applyWhenRegisterTasksThenCheckRemoteDirSameAsIncludeRepoOutputDir() {
		this.rootProject = ProjectBuilder.builder().build();
		this.rootProject.getPluginManager().apply(IncludeCheckRemotePlugin.class);
		this.rootProject.getExtensions().configure(IncludeCheckRemotePlugin.IncludeCheckRemoteExtension.class,
				(includeCheckRemoteExtension) -> {
					includeCheckRemoteExtension.setProperty("repository", "my-project/my-repository");
					includeCheckRemoteExtension.setProperty("ref", "main");
				});
		IncludeRepoTask includeRepo = (IncludeRepoTask) this.rootProject.getTasks().named("includeRepo").get();
		GradleBuild checkRemote = (GradleBuild) this.rootProject.getTasks().named("checkRemote").get();
		assertThat(checkRemote.getDir()).isEqualTo(includeRepo.getOutputDirectory());
	}

	@Test
	void applyWhenNoExtensionPropertiesThenRegisterTasks() {
		this.rootProject = ProjectBuilder.builder().build();
		this.rootProject.getPluginManager().apply(IncludeCheckRemotePlugin.class);
		IncludeRepoTask includeRepo = (IncludeRepoTask) this.rootProject.getTasks().named("includeRepo").get();
		GradleBuild checkRemote = (GradleBuild) this.rootProject.getTasks().named("checkRemote").get();
		assertThat(includeRepo).isNotNull();
		assertThat(checkRemote).isNotNull();
	}

}


text:
require 'spec_helper'

RSpec.describe Gitlab::BackgroundMigration::ResetMergeStatus do
  let(:namespaces) { table(:namespaces) }
  let(:projects) { table(:projects) }
  let(:namespace) { namespaces.create(name: 'gitlab', path: 'gitlab-org') }
  let(:project) { projects.create(namespace_id: namespace.id, name: 'foo') }
  let(:merge_requests) { table(:merge_requests) }

  def create_merge_request(id, extra_params = {})
    params = {
      id: id,
      target_project_id: project.id,
      target_branch: 'master',
      source_project_id: project.id,
      source_branch: 'mr name',
      title: "mr name#{id}"
    }.merge(extra_params)

    merge_requests.create!(params)
  end

  it 'correctly updates opened mergeable MRs to unchecked' do
    create_merge_request(1, state_id: MergeRequest.available_states[:opened], merge_status: 'can_be_merged')
    create_merge_request(2, state_id: MergeRequest.available_states[:opened], merge_status: 'can_be_merged')
    create_merge_request(3, state_id: MergeRequest.available_states[:opened], merge_status: 'can_be_merged')
    create_merge_request(4, state_id: MergeRequest.available_states[:merged], merge_status: 'can_be_merged')
    create_merge_request(5, state_id: MergeRequest.available_states[:opened], merge_status: 'cannot_be_merged')

    subject.perform(1, 5)

    expected_rows = [
      { id: 1, state_id: MergeRequest.available_states[:opened], merge_status: 'unchecked' },
      { id: 2, state_id: MergeRequest.available_states[:opened], merge_status: 'unchecked' },
      { id: 3, state_id: MergeRequest.available_states[:opened], merge_status: 'unchecked' },
      { id: 4, state_id: MergeRequest.available_states[:merged], merge_status: 'can_be_merged' },
      { id: 5, state_id: MergeRequest.available_states[:opened], merge_status: 'cannot_be_merged' }
    ]

    rows = merge_requests.order(:id).map do |row|
      row.attributes.slice('id', 'state_id', 'merge_status').symbolize_keys
    end

    expect(rows).to eq(expected_rows)
  end
end


text:
cask 'avocode' do
  version '3.9.6'
  sha256 '399ef82b4fb2735659a2d41bee4442311239926d2cf87c6bf88ce0b88e3857fd'

  url "https://media.avocode.com/download/avocode-app/#{version}/Avocode-#{version}-mac.zip"
  appcast 'https://macupdater.net/cgi-bin/check_urls/check_url_redirect.cgi?url=https://manager.avocode.com/download/avocode-app/mac-dmg/'
  name 'Avocode'
  homepage 'https://avocode.com/'

  auto_updates true

  app 'Avocode.app'

  zap trash: [
               '~/.avocode',
               '~/Library/Application Support/Avocode',
               '~/Library/Caches/com.madebysource.avocode',
               '~/Library/Caches/com.madebysource.avocode.ShipIt',
               '~/Library/Preferences/com.madebysource.avocode.helper.plist',
               '~/Library/Preferences/com.madebysource.avocode.plist',
               '~/Library/Saved Application State/com.madebysource.avocode.savedState',
             ]
end


text:
package tw.edu.nccu.cs.vipl.fun.mpo;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;

public class FileChannelReader {

    private ByteBuffer mStrBuffer = ByteBuffer.allocate(4);
    private ByteBuffer mShortBuffer = ByteBuffer.allocate(2);
    private ByteBuffer mIntBuffer = ByteBuffer.allocate(4);
    private ByteBuffer mLongBuffer = ByteBuffer.allocate(8);
    private FileChannel mFileChannel;

    public FileChannelReader(FileChannel fileChannel) {
        this.mStrBuffer = ByteBuffer.allocate(4);
        this.mShortBuffer = ByteBuffer.allocate(2);
        this.mIntBuffer = ByteBuffer.allocate(4);
        this.mLongBuffer = ByteBuffer.allocate(8);
        this.mFileChannel = fileChannel;
    }

    public short readShort() {
        return readShort(false);
    }

    public short readShort(boolean isLittleEndian) {
        mShortBuffer.clear();
        mShortBuffer.order(isLittleEndian ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN);
        try {
            mFileChannel.read(mShortBuffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
        mShortBuffer.flip();
        return mShortBuffer.getShort();
    }

    public int readInt() {
        return readInt(false);
    }

    public int readInt(boolean isLittleEndian) {
        mIntBuffer.order(isLittleEndian ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN);
        mIntBuffer.clear();
        try {
            mFileChannel.read(mIntBuffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
        mIntBuffer.flip();
        return mIntBuffer.getInt();
    }

    public long readLone() {
        return readLone(false);
    }

    public long readLone(boolean isLittleEndian) {
        mLongBuffer.order(isLittleEndian ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN);
        mLongBuffer.clear();
        try {
            mFileChannel.read(mLongBuffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
        mLongBuffer.flip();
        return mLongBuffer.getLong();
    }

    public String readString() {
        try {
            mFileChannel.read(mStrBuffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
        mStrBuffer.flip();
        return new String(mStrBuffer.array());
    }

    public long position() {
        try {
            return mFileChannel.position();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return 0;
    }

    public long size() {
        try {
            return mFileChannel.size();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return 0;
    }

    public void position(long offset) {
        try {
            mFileChannel.position(offset);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public byte[] readBytes(int imageSize) {
        ByteBuffer buffer = ByteBuffer.allocate(imageSize);
        try {
            mFileChannel.read(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer.array();
    }

}


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace Arke.Net.Tests
{
    public static class TestData
    {
        public static byte[] TestBytes = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
        public static string TestString = "Hello World!";
        public static int TestInt = 12345678;
        public static double TestDouble = 1234.5678;
        public static TestObject TestObject = new TestObject { TestBytes = TestBytes, TestDouble = TestDouble, TestInteger = TestInt, TestString = TestString };

    }

    [Serializable]
    public class TestObject
    {
        public string TestString { get; set; }
        public byte[] TestBytes { get; set; }
        public int TestInteger { get; set; }
        public double TestDouble { get; set; }
    }
}


text:
package org.apache.felix.metatype.internal;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.*;

import org.apache.felix.metatype.AD;
import org.apache.felix.metatype.OCD;
import org.apache.felix.metatype.internal.l10n.Resources;
import org.osgi.framework.Bundle;
import org.osgi.service.metatype.AttributeDefinition;
import org.osgi.service.metatype.ObjectClassDefinition;

/**
 * The LocalizedObjectClassDefinition class is the implementation
 * of the ObjectClassDefinition interface. This class delegates
 * calls to the underlying {@link OCD} localizing the results of the following
 * methods: {@link #getName()}, {@link #getDescription()}, and
 * {@link #getIcon(int)}.
 *
 * @author Felix Project Team
 */
public class LocalizedObjectClassDefinition extends LocalizedBase implements ObjectClassDefinition
{

    private Bundle bundle;

    private OCD ocd;

    /**
     * Creates and instance of this localizing facade.
     *
     * @param bundle The Bundle providing this object class
     *            definition.
     * @param ocd The {@link OCD} to which calls are delegated.
     * @param resources The {@link Resources} used to localize return values of
     * localizable methods.
     */
    public LocalizedObjectClassDefinition( Bundle bundle, OCD ocd, Resources resources )
    {
        super( resources );
        this.bundle = bundle;
        this.ocd = ocd;
    }

    /**
     * @param filter
     * @see org.osgi.service.metatype.ObjectClassDefinition#getAttributeDefinitions(int)
     */
    public AttributeDefinition[] getAttributeDefinitions( int filter )
    {
        if ( ocd.getAttributeDefinitions() == null )
        {
            return null;
        }

        Iterator adhIter = ocd.getAttributeDefinitions().values().iterator();
        if ( filter == ObjectClassDefinition.OPTIONAL || filter == ObjectClassDefinition.REQUIRED )
        {
            boolean required = ( filter == ObjectClassDefinition.REQUIRED );
            adhIter = new RequiredFilterIterator( adhIter, required );
        }
        else if ( filter != ObjectClassDefinition.ALL )
        {
            return null;
        }

        if ( !adhIter.hasNext() )
        {
            return null;
        }

        List result = new ArrayList();
        while ( adhIter.hasNext() )
        {
            result.add( new LocalizedAttributeDefinition( ( AD ) adhIter.next(), getResources() ) );
        }

        return ( AttributeDefinition[] ) result.toArray( new AttributeDefinition[result.size()] );
    }

    /**
     * @see org.osgi.service.metatype.ObjectClassDefinition#getDescription()
     */
    public String getDescription()
    {
        return localize( ocd.getDescription() );
    }

    /**
     * @see org.osgi.service.metatype.ObjectClassDefinition#getIcon(int)
     */
    public InputStream getIcon( int desiredSize ) throws IOException
    {
        // nothing if no icons are defined
        Map icons = ocd.getIcons();
        if ( icons == null )
        {
            return null;
        }

        // get exact size
        String iconPath = ( String ) icons.get( new Integer( desiredSize ) );

        if ( iconPath == null )
        {
            // approximate size: largest icon smaller than requested
            Integer selectedSize = new Integer( Integer.MIN_VALUE );
            for ( Iterator ei = icons.keySet().iterator(); ei.hasNext(); )
            {
                Integer iconSize = ( Integer ) ei.next();
                if ( iconSize.intValue() <= desiredSize && selectedSize.compareTo( iconSize ) < 0 )
                {
                    selectedSize = iconSize;
                }
            }
            // get the raw path, fail if no path can be found
            iconPath = ( String ) icons.get( selectedSize );
        }

        // localize the path
        iconPath = localize( iconPath );

        // fail if no icon could be found (or localization returned null)
        if ( iconPath == null )
        {
            return null;
        }

        // just create an URL based on the source of the metadata
        // see FELIX2868
        URL url = this.bundle.getResource( iconPath );
        if ( url == null )
        {
            url = new URL( this.ocd.getMetadata().getSource(), iconPath );
        }
        return url.openStream();
    }

    /**
     * @see org.osgi.service.metatype.ObjectClassDefinition#getID()
     */
    public String getID()
    {
        return ocd.getID();
    }

    /**
     * @see org.osgi.service.metatype.ObjectClassDefinition#getName()
     */
    public String getName()
    {
        return localize( ocd.getName() );
    }

    private static class RequiredFilterIterator implements Iterator
    {

        private final Iterator base;

        private final boolean required;

        private AD next;

        private RequiredFilterIterator( Iterator base, boolean required )
        {
            this.base = base;
            this.required = required;
            this.next = seek();
        }

        public boolean hasNext()
        {
            return next != null;
        }

        public Object next()
        {
            if ( !hasNext() )
            {
                throw new NoSuchElementException();
            }

            AD toReturn = next;
            next = seek();
            return toReturn;
        }

        public void remove()
        {
            throw new UnsupportedOperationException( "remove" );
        }

        private AD seek()
        {
            if ( base.hasNext() )
            {
                AD next;
                do
                {
                    next = ( AD ) base.next();
                }
                while ( next.isRequired() != required && base.hasNext() );

                if ( next.isRequired() == required )
                {
                    return next;
                }
            }

            // nothing found any more
            return null;
        }

    }
}


text:
class op_inv
  {
  public:

  template<typename eT>
  inline static void apply(Mat<eT>& out, const Mat<eT>& A, const bool slow = false);

  template<typename T1>
  inline static void apply(Mat<typename T1::elem_type>& out, const Op<T1,op_inv>& in);

  template<typename T1>
  inline static bool apply_diagmat(Mat<typename T1::elem_type>& out, const T1& X);
  };

//! 'invert matrix' operation (triangular matrices)
class op_inv_tr
  {
  public:

  template<typename T1>
  inline static void apply(Mat<typename T1::elem_type>& out, const Op<T1,op_inv_tr>& in);
  };

//! 'invert matrix' operation (symmetric positive definite matrices)
class op_inv_sympd
  {
  public:

  template<typename T1>
  inline static void apply(Mat<typename T1::elem_type>& out, const Op<T1,op_inv_sympd>& in);
  };

//! @}


text:
launchctl unload -F /Library/LaunchDaemons/com.dustinrue.ControlPlane.plist
rm /Library/LaunchDaemons/com.dustinrue.ControlPlane.plist
rm /Library/PrivilegedHelperTools/com.dustinrue.ControlPlane

# newer version
launchctl unload -F /Library/LaunchDaemons/com.dustinrue.CPHelperTool.plist
rm /Library/LaunchDaemons/com.dustinrue.CPHelperTool.plist
rm /Library/PrivilegedHelperTools/com.dustinrue.CPHelperTool


text:
DEFAULT_HOSTS = [
    'dataverse.harvard.edu',            # Harvard PRODUCTION server
    'dataverse.lib.virginia.edu'        # University of Virginia server
]


text:
// FormatDect.cpp : Defines the entry point for the console application.
//

#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <string.h>

#include "TSnative.h"

#ifdef __cplusplus
extern "C" {
#endif
extern int GetAVInf( char* FileName, unsigned long CheckSize, bool bLiveFile, int RequestedTSProgram,
			   char* FormatBuf, int FormatSize, char* DurationBuf, int DurationSize, int* Program );
#ifdef __cplusplus
}

#else
extern int GetAVInf( char* FileName, unsigned long CheckSize, bool bLiveFile, int RequestedTSProgram,
			   char* FormatBuf, int FormatSize, char* DurationBuf, int DurationSize, int* Program );

#endif

int  main(int argc, char* argv[])
{
	//TS_PARSER* ts = TSParserOpen();
	char Format[512]={0}, Duration[32];
	int ProgramNum = 0;
	int channel = 0;
	int SearchSize = 1207959552;///10;
	int ret;
	if ( argc < 2 )
	{
		puts( "Usage: FormatDect filename" );
		return 0;
	}

	//retreve programs av information from TS/PS info
	do {
		ret = GetAVInf( argv[1], SearchSize, false, channel, Format, sizeof(Format), Duration, sizeof(Duration), &ProgramNum );
		if ( ret < 0 ) break;
		channel++;
		printf( "File:%s\n%d. Format:%s Duration:%s Program Num:%d\n", argv[1], channel, Format, Duration, ProgramNum );
	}
	while ( channel < ProgramNum );

	if ( ret < 0 )
		printf( "%s is not found\n", argv[1] );
	return 0;
}

#ifdef __cplusplus
}
#endif


text:
class QAmqpChannel;
class QAmqpClient;
class QAmqpClientPrivate;
class QAmqpChannelPrivate : public QAmqpMethodFrameHandler
{
public:
    enum MethodId {
        METHOD_ID_ENUM(miOpen, 10),
        METHOD_ID_ENUM(miFlow, 20),
        METHOD_ID_ENUM(miClose, 40)
    };

    enum BasicMethod {
        METHOD_ID_ENUM(bmQos, 10),
        METHOD_ID_ENUM(bmConsume, 20),
        METHOD_ID_ENUM(bmCancel, 30),
        bmPublish = 40,
        bmReturn = 50,
        bmDeliver = 60,
        METHOD_ID_ENUM(bmGet, 70),
        bmGetEmpty = 72,
        bmAck = 80,
        bmReject = 90,
        bmRecoverAsync = 100,
        METHOD_ID_ENUM(bmRecover, 110),
        bmNack = 120
    };

    QAmqpChannelPrivate(QAmqpChannel *q);
    virtual ~QAmqpChannelPrivate();

    void init(int channel, QAmqpClient *client);
    void sendFrame(const QAmqpFrame &frame);

    void open();
    void flow(bool active);
    void flowOk();
    void close(int code, const QString &text, int classId, int methodId);

    // reimp MethodHandler
    virtual bool _q_method(const QAmqpMethodFrame &frame);
    void openOk(const QAmqpMethodFrame &frame);
    void flow(const QAmqpMethodFrame &frame);
    void flowOk(const QAmqpMethodFrame &frame);
    void close(const QAmqpMethodFrame &frame);
    void closeOk(const QAmqpMethodFrame &frame);
    void qosOk(const QAmqpMethodFrame &frame);

    // private slots
    virtual void _q_disconnected();
    void _q_open();

    QPointer<QAmqpClient> client;
    QString name;
    quint16 channelNumber;
    static quint16 nextChannelNumber;
    bool opened;
    bool needOpen;

    qint32 prefetchSize;
    qint32 requestedPrefetchSize;
    qint16 prefetchCount;
    qint16 requestedPrefetchCount;

    QAMQP::Error error;
    QString errorString;

    Q_DECLARE_PUBLIC(QAmqpChannel)
    QAmqpChannel * const q_ptr;
};

#endif // QAMQPCHANNEL_P_H


text:
import logging

from django.conf.urls import include
from django.conf.urls import url

from kolibri.core.device.translation import i18n_patterns
from kolibri.plugins.registry import registered_plugins

logger = logging.getLogger(__name__)

def normalize_slug(url_slug):
    return url_slug.lstrip("^").rstrip("/") + "/"

def find_duplicate_slugs():
    # First look for conflicting slugs
    slugs = {}
    for plugin in registered_plugins:
        slug = normalize_slug(plugin.url_slug)
        if slug in slugs:
            slugs[slug].append(plugin.module_path)
        else:
            slugs[slug] = [plugin.module_path]
    duplicate_slugs = {}
    for key, value in slugs.items():
        if len(value) > 1:
            if all(map(lambda x: x.startswith("kolibri.plugins"), value)):
                # If we have multiple kolibri core plugins setting the same url slug, we should error out.
                # This is not acceptable.
                raise RuntimeError(
                    "Multiple core kolibri plugins define the same top level URL slug: {}".format(
                        key
                    )
                )
            duplicate_slugs[key] = value
    return duplicate_slugs

def get_urls():
    duplicate_slugs = find_duplicate_slugs()
    urlpatterns = []
    for plugin_instance in registered_plugins:
        url_module = plugin_instance.url_module
        api_url_module = plugin_instance.api_url_module
        instance_patterns = []
        # Normalize slug
        slug = normalize_slug(plugin_instance.url_slug)
        # If we have a collision, and one of the plugins is a kolibri core plugin, we let it take precedence.
        # If both are Kolibri core plugins, we have raised a RuntimeError already when checking for
        # duplicate slugs.
        if slug in duplicate_slugs and not plugin_instance.module_path.startswith(
            "kolibri.plugins"
        ):
            other_modules = ", ".join(
                filter(
                    lambda x: x != plugin_instance.module_path, duplicate_slugs[slug]
                )
            )
            logger.warn(
                "Plugin {} defines a top level URL slug that clashes with other plugins: {}".format(
                    plugin_instance.module_path, other_modules
                )
            )
            slug = normalize_slug(plugin_instance.module_path.replace(".", ""))
        if url_module:
            instance_patterns += i18n_patterns(url_module.urlpatterns, prefix=slug)
        if api_url_module:
            instance_patterns.append(url(slug + "api/", include(api_url_module)))
        if instance_patterns:
            urlpatterns.append(
                url(
                    "",
                    include(instance_patterns, namespace=plugin_instance.module_path),
                )
            )

    return urlpatterns

def get_root_urls():
    urlpatterns = []
    for plugin_instance in registered_plugins:
        root_url_module = plugin_instance.root_url_module
        if root_url_module:
            urlpatterns.append(url("", include(root_url_module)))

    return urlpatterns


text:
var app = angular.module("ethics-app");

// Document review controller
app.controller("documentReviewController", function($scope, $rootScope, $routeParams, $filter, $translate, $location, config, $window, $q, $timeout, $authenticationService, $documentService, $commentService, $noteService) {

    /*************************************************
        FUNCTIONS
     *************************************************/

    /**
     * [redirect description]
     * @param  {[type]} path [description]
     * @return {[type]}      [description]
     */
    $scope.redirect = function(path){
        $location.url(path);
    };

    /**
     * [toggleConcernHistory description]
     * @param  {[type]} language [description]
     * @return {[type]}          [description]
     */
    $scope.toggle = function(category, property, language){
        switch (category) {
            case 'general': {
                switch (property){
                    case 'display': {
                        $scope.status.general.display = !$scope.status.general.display;
                        break;
                    }
                    case 'history': {
                        $scope.status.general.history = !$scope.status.general.history;
                        if($scope.status.general.history){
                            $scope.status.general.limit = $scope.document.revisions.length;
                        } else {
                            $scope.status.general.limit = 1;
                        }
                        break;
                    }
                }
                break;
            }
            case 'descriptions': {
                switch (property) {
                    case 'language': {
                        switch (language) {
                            case 'en': {
                                $scope.status.descriptions.language.en = !$scope.status.descriptions.language.en;
                                break;
                            }
                            case 'de': {
                                $scope.status.descriptions.language.de = !$scope.status.descriptions.language.de;
                                break;
                            }
                            case 'pt': {
                                $scope.status.descriptions.language.pt = !$scope.status.descriptions.language.pt;
                                break;
                            }
                        }
                        break;
                    }
                    case 'history': {
                        switch (language) {
                            case 'en': {
                                $scope.status.descriptions.history.en.display = !$scope.status.descriptions.history.en.display;

                                if($scope.status.descriptions.history.en.display){
                                    $scope.status.descriptions.history.en.limit = $scope.document.revisions.length;
                                } else {
                                    $scope.status.descriptions.history.en.limit = 1;
                                }
                                break;
                            }
                            case 'de': {
                                $scope.status.descriptions.history.de.display = !$scope.status.descriptions.history.de.display;

                                if($scope.status.descriptions.history.de.display){
                                    $scope.status.descriptions.history.de.limit = $scope.document.revisions.length;
                                } else {
                                    $scope.status.descriptions.history.de.limit = 1;
                                }
                                break;
                            }
                            case 'pt': {
                                $scope.status.descriptions.history.pt.display = !$scope.status.descriptions.history.pt.display;

                                if($scope.status.descriptions.history.pt.display){
                                    $scope.status.descriptions.history.pt.limit = $scope.document.revisions.length;
                                } else {
                                    $scope.status.descriptions.history.pt.limit = 1;
                                }
                                break;
                            }
                        }
                        break;
                    }
                    case 'comments': {
                        switch (language) {
                            case 'en': {
                                $scope.status.descriptions.comments.en = !$scope.status.descriptions.comments.en;
                                break;
                            }
                            case 'de': {
                                $scope.status.descriptions.comments.de = !$scope.status.descriptions.comments.de;
                                break;
                            }
                            case 'pt': {
                                $scope.status.descriptions.comments.pt = !$scope.status.descriptions.comments.pt;
                                break;
                            }
                        }
                    }
                }
                break;
            }
            case 'concerns': {
                switch (property) {
                    case 'display': {
                        $scope.status.concerns.display = !$scope.status.concerns.display;
                        break;
                    }
                    case 'history': {
                        $scope.status.concerns.history = !$scope.status.concerns.history;

                        if($scope.status.concerns.history){
                            $scope.status.concerns.limit = $scope.document.revisions.length;
                        } else {
                            $scope.status.concerns.limit = 1;
                        }

                        break;
                    }
                    case 'comments': {
                        $scope.status.concerns.comments = !$scope.status.concerns.comments;
                        break;
                    }
                }
                break;
            }
        }
    };

    /**
     * [submitReview description]
     * @return {[type]} [description]
     */
    $scope.saveReview = function(){
        $scope.$parent.loading = { status: true, message: $filter('translate')('SAVING_REVIEW') };

        // Save notes
        $noteService.save($scope.document.note_id, { "note": $scope.document.note })
        .then(function onSuccess(response) {

            // Save comments
            $commentService.edit($scope.latest_revision.comments.comment_id, $scope.latest_revision.comments)
            .then(function onSuccess(response) {
                $scope.$parent.loading = { status: false, message: "" };

                // Reset navbar
                $scope.$parent.document = false;

                // Redirect
                $scope.redirect("/documents");
            })
            .catch(function onError(response) {
                $window.alert(response.data);

                // Reset navbar
                $scope.$parent.document = false;

                // Redirect
                $scope.redirect("/documents");
            });
        })
        .catch(function onError(response) {
            $window.alert(response.data);

            // Reset navbar
            $scope.$parent.document = false;

            // Redirect
            $scope.redirect("/documents");
        });
    };

    /**
     * [submitReview description]
     * @return {[type]} [description]
     */
    $scope.publish = function(){
        // Save notes
        $noteService.save($scope.document.note_id, { "note": $scope.document.note })
        .then(function onSuccess(response) {

            if($scope.review_status !== null){
                $scope.$parent.loading = { status: true, message: $filter('translate')('SAVING_REVIEW') };

                // Publish comments for user
                $scope.latest_revision.comments.published = true;

                // Save comments
                $commentService.edit($scope.latest_revision.comments.comment_id, $scope.latest_revision.comments)
                .then(function onSuccess(response) {
                    $scope.$parent.loading = { status: true, message: $filter('translate')('PUBLISHING_REVIEW') };

                    // Change status of document
                    $documentService.changeStatus($routeParams.document_id, {
                        status: $scope.review_status
                    })
                    .then(function onSuccess(response) {
                        $scope.$parent.loading = { status: false, message: "" };

                        // Redirect
                        $scope.redirect("/documents");
                    })
                    .catch(function onError(response) {
                        $window.alert(response.data);

                        // Reset navbar
                        $scope.$parent.document = false;

                        // Redirect
                        $scope.redirect("/documents");
                    });
                })
                .catch(function onError(response) {
                    $window.alert(response.data);

                    // Reset navbar
                    $scope.$parent.document = false;

                    // Redirect
                    $scope.redirect("/documents");
                });
            }
        })
        .catch(function onError(response) {
            $window.alert(response.data);

            // Reset navbar
            $scope.$parent.document = false;

            // Redirect
            $scope.redirect("/documents");
        });
    };

    /*************************************************
        EVENTS
     *************************************************/
    $scope.$on("$destroy", function() {
        // Reset navbar
        delete $scope.document;
        delete $scope.$parent.document;
    });

    /*************************************************
        INIT
     *************************************************/
    $scope.$parent.loading = { status: true, message: $filter('translate')('LOADING_REVIEW') };
    $scope.review_status = null;
    $scope.authenticated_member = $authenticationService.get();
    $scope.document = $documentService.get();
    $scope.latest_revision = $documentService.getLatestRevision();

    //TODO Add concerns to make filepath available in review.html

    // Update navbar
    $scope.$parent.document = $documentService.get();

    // Show/hide comments and history
    $scope.status = {
        general: {
            display: true,
            history: false,
            limit: 1
        },
        descriptions: {
            language: {
                en: true,
                de: false,
                pt: false
            },
            history: {
                en: {
                    display: false,
                    limit: 1
                },
                de: {
                    display: false,
                    limit: 1
                },
                pt: {
                    display: false,
                    limit: 1
                }
            },
            comments: {
                en: true,
                de: true,
                pt: true
            }
        },
        concerns: {
            display: true,
            history: false,
            limit: 1,
            comments: true
        }
    };

    // Show all comments and history
    $scope.toggle('general', 'history');
    $scope.toggle('descriptions', 'history', 'en');
    $scope.toggle('descriptions', 'history', 'de');
    $scope.toggle('descriptions', 'language', 'de');
    $scope.toggle('descriptions', 'history', 'pt');
    $scope.toggle('descriptions', 'language', 'de');
    $scope.toggle('concerns', 'history');

    $scope.$parent.loading = { status: false, message: "" };
});