text:
const isTravis = process.env.TRAVIS || false;

const testLogin = (isTravis ? {
    "email": process.env.EMAIL,
    "password": process.env.PASSWORD,
    "room": process.env.ROOM,
    "usernameToBuy": "",
    "parse": true
} : require("./test.json"));

// id needed for ban test
let _id = null;
// playlist id
let _playlist = null;
let _media = null;
let _room = null;
let _store = null;

const Plugged = require("../plugged");
const Query = require("../query");
const types = require("../types");

const helper = require("./helper");
const objects = require("./objects");
const functions = require("./functions");

const chai = require("chai");
const expect = chai.expect;
const client = new Plugged({
    test: !testLogin.parse,
    verbosity: 5,
    log: (msg) => {
        console.log(msg);
    }
});

client.cacheChat(true);
client.cacheUser(true);

// gets all users that are not you
function getUsers() {
    const users = client.getUsers();
    const filtered = [];

    for(let i = 0, l = users.length; i < l; i++) {
        if(users[i].role < client.getSelf().role) {
            filtered.push(users[i]);
        }
    }

    return filtered;
}

function extendedTestCheck(requiredUsers = 0, done) {
    const users = getUsers();

    if (!users || users.length < requiredUsers) {
        console.log(`could not run test since it requires ${requiredUsers} \
        ${requiredUsers > 1 ? "users" : "user"} for this to pass. skipping.`);
        if (done)
            done();

        return false;
    }

    return true;
}

function skipIfTravis(travis) {
    return travis ? describe.skip : describe;
}

describe("Check basic functions", () => {
    describe("#Utils", () => {
        describe("#waterfall", () => {
            it("should call functions asynchronously one after another", done => {
                functions.testWaterfall(() => {
                    done();
                });
            });
        });

        describe("#splitTitle", () => {
            it("should split a string into two, defining an author and a title", () => {
                functions.testSplitTitle();
            });
        });

        describe("#convertPlugTimeToDate", () => {
            it("should convert the time given by the plug servers to unix standard time", () => {
                functions.testConvertPlugTimeToDate();
            });
        });

        describe("#decode", () => {
            it("should decode a message", () => {
                functions.testDecode();
            });
        });
    });

    describe("#types", () => {
        describe("#RequestError", () => {
            it("should accept a message, a status code and an error code", () => {
                const msg = "example error message";
                const err = new types.RequestError(msg, 0, -1);

                expect(err.code).to.be.a("number").and.equal(-1);
                expect(err.status).to.be.a("number").and.equal(0);
                expect(err.message).to.be.a("string").and.equal(msg);
                expect(err.name).to.be.a("string").and.equal("RequestError");
            });

            it("should be able to create an empty error", () => {
                const err = new types.RequestError();

                expect(err.code).to.be.a("null").and.equal(null);
                expect(err.status).to.be.a("null").and.equal(null);
                expect(err.message).to.be.a("string").and.equal("no data returned");
                expect(err.name).to.be.a("string").and.equal("RequestError");
            });
        });
    });

    describe("#query", () => {
        const query = new Query();
        describe("#setEncoding", () => {
            it("should default to utf-8 when calling setEncoding without a parameter", () => {
                query.setEncoding();

                expect(query.getEncoding()).to.be.a("string").and.equal("utf8");
            });

            it ("should be able to accept any encoding as a string parameter", () => {
                query.setEncoding("pseudo");
                expect(query.getEncoding()).to.be.a("string").and.equal("pseudo");

                query.setEncoding("utf8");
                expect(query.getEncoding()).to.be.a("string").and.equal("utf8");
            });
        });

        describe("#getEncoding", () => {
            it("should return the saved encoding", () => {
                expect(query.getEncoding()).to.be.a("string").and.equal("utf8");
            });
        });

        describe("#setJar", () => {
            it("should accept a cookie jar given by request", () => {
                query.setJar(null, null);

                expect(query.getJar()).to.be.an("object");
            });

            it("should accept a storage like FileCookieStore", () => {
                query.setJar(null, null);

                expect(query.getJar()).to.be.an("object");
            });
        });

        describe("#getJar", () => {
            it("should return the saved jar", () => {
                expect(query.getJar()).to.be.an("object");
            });
        });

        describe("#setAccept", () => {
            it("should set the accepting type of content", () => {
                let accept = query.getAccept();

                query.setAccept("application/text");
                expect(query.getAccept()).to.be.equal("application/text");
                query.setAccept(accept);
            });
        });

        describe("#getAccept", () => {
            it("should get the accepting type of content", () => {
                expect(query.getAccept().indexOf("application/json")).to.not.equal(-1);
            });
        });

        describe("#setContentType", () => {
            it("should set the content type awaited for the response", () => {
                let type = query.getContentType();

                query.setContentType("application/text");
                expect(query.getContentType()).to.equal("application/text");
                query.setContentType(type);
            });
        });

        describe("#getContentType", () => {
            it("should get the content type awaited for the response", () => {
                expect(query.getContentType().indexOf("application/json")).to.not.equal(-1);
            });
        });

        describe("#query", () => {
            it("should be able to retrieve a message from a server", done => {
                let accept = query.getAccept();
                let type = query.getContentType();

                query.setAccept("text/html");
                query.setContentType("text/html");

                query.query(types.VERBS.GET, "https://www.google.com", null, (err, ret) => {
                    expect(err).to.equal(null);

                    query.setAccept(accept);
                    query.setContentType(type);
                    done();
                });
            });

            it("should be able to query multiple requests", done => {
                done();
            });
        });

        describe("#flush", () => {
            it("should be able to clear the queue", () => {
                query.flushQueue();
            });
        });
    });
});

describe("Login", () => {
    describe("#_getCSRF", () => {
        it("should retrieve the cross site request forgery token", done => {
            client._getCSRF(null, (err, c, csrf) => {
                expect(err).to.be.equal(null);
                expect(csrf).to.be.a("string").and.have.length.above(0);

                done();
            });
        });
    });

    describe("#login", () => {
        it("should return an error when called without credentials", done => {
            client.login(null, (err, self) => {
                expect(err).to.be.an("Error");
                expect(err.message).to.equal("credentials has to be of type object");
                done();
            });
        });

        it("should return an error when given mixed credentials", () => {
            try {
                client.login({
                    email: "examplemail@examplehost.com",
                    clientID: 0
                });
            } catch (err) {
                expect(err).to.be.an("Error");
                expect(err.message).to.be.equal("password missing");
            }
        });

        it("should log into plug without any issues", done => {
            client.login({email: testLogin.email, password: testLogin.password}, (err, self) => {
                expect(err).to.equal(null);
                expect(self).to.be.an("object");
                objects.testSelf(testLogin.parse, self);

                done();
            });
        });
    });
});

describe("Joining a room", () => {
    it("should return an error when given no room", done => {
        client.connect(null, (err, room) => {
            expect(err).to.not.equal(null);
            expect(err.message).to.equal("slug has to be defined");
            expect(room).to.equal(null);
            done();
        });
    });

    it("should return a room object with the current stats", done => {
        client.connect(testLogin.room, (err, room) => {
            expect(err).to.equal(null);
            expect(room).to.be.an("object");
            done();
        });
    });
});

describe("Chat", () => {
    // used to keep a reference so we can delete it in another test
    let _message;

    describe("#sendChat", () => {
        it("should send a message with the text 'test'", done => {

            const func = (msg) => {
                expect(msg).to.be.an("object");

                if(!testLogin.parse) {
                    expect(msg).to.have.all.keys([
                        "message",
                        "cid",
                        "uid",
                        "sub",
                        "un"
                    ]);

                    expect(msg.message).to.be.a("string");
                    expect(msg.cid).to.be.a("string");
                    expect(msg.uid).to.be.a("number");
                    expect(msg.sub).to.be.a("number");
                    expect(msg.un).to.be.a("string");
                } else {
                    expect(msg).to.have.all.keys([
                        "username",
                        "message",
                        "cid",
                        "sub",
                        "id"
                    ]);

                    expect(msg.username).to.be.a("string");
                    expect(msg.cid).to.be.a("string");
                    expect(msg.id).to.be.a("number");
                    expect(msg.message).to.be.a("string").and.equal("test");
                }

                _message = msg;

                client.removeListener(client.CHAT, func);
                done();
            };

            client.on(client.CHAT, func);
            client.sendChat("test");
        });
    });

    describe("#deleteChat", () => {
        it("should delete a message", done => {
            const funcDel = (msg) => {
                expect(msg).to.be.an("object");

                if(!testLogin.parse) {
                    expect(msg).to.have.all.keys([
                        "c",
                        "mi"
                    ]);
                    expect(msg.c).to.be.a("string");
                    expect(msg.mi).to.be.a("number");
                } else {
                    expect(msg).to.have.all.keys([
                        "cid",
                        "moderatorID"
                    ]);
                    expect(msg.cid).to.be.a("string");
                    expect(msg.moderatorID).to.be.a("number").and.not.equal(-1);
                }

                client.removeListener(client.CHAT_DELETE, funcDel);
                done();
            };

            client.on(client.CHAT_DELETE, funcDel);
            client.deleteMessage(_message.cid);
        });
    });
});

describe("REST", () => {
    describe("#getNews", () => {
        it("should get an array of news objects", done => {
            client.getNews((err, news) => {
                expect(err).to.be.equal(null);
                expect(news).to.be.an("array");

                if(news.length > 0) {
                    expect(news[0]).to.be.an("object");
                    expect(news[0]).to.have.all.keys([
                        "desc",
                        "href",
                        "title"
                    ]);

                    expect(news[0].desc).to.be.a("string");
                    expect(news[0].href).to.be.a("string");
                    expect(news[0].title).to.be.a("string");
                }
                done();
            });
        });
    });

    describe("#getAuthToken", () => {
        it("should retrieve the authentication token", done => {
            client.getAuthToken((err, token) => {
                expect(err).to.be.equal(null);
                expect(token).to.be.a("string");
                expect(token.length).to.be.above(0);
                done();
            });
        });
    });

    describe("#getRoomStats", () => {
        it("should return the room object of the currently joined room", done => {
            client.getRoomStats((err, room) => {
                expect(err).to.be.equal(null);
                objects.testRoom(testLogin.parse, room);
                _room = room;

                done();
            });
        });
    });

    describe("#findRooms", () => {
        it("should retrieve an array of room objects filtered by a keyword", done => {
            client.findRooms("", 0, 1, (err, rooms) => {
                expect(err).to.be.equal(null);
                expect(rooms).to.be.an("array");
                expect(rooms.length).to.be.equal(1);

                if (rooms.length > 0) {
                    expect(rooms[0]).to.be.an("object");
                    objects.testExtendedRoom(testLogin.parse, rooms[0]);
                }

                done();
            });
        });
    });

    describe("#getRoomList", () => {
        it("should retrieve an array of rooms objects", done => {
            client.getRoomList(0, 10, (err, rooms) => {
                expect(err).to.be.equal(null);
                expect(rooms).to.be.an("array");
                // server does not always return 10 rooms
                expect(rooms.length).to.be.greaterThan(0);

                if(rooms.length > 0) {
                    expect(rooms[0]).to.be.an("object");
                    objects.testExtendedRoom(testLogin.parse, rooms[0]);
                }

                done();
            });
        });
    });

    describe("#getStaff", () => {
        it("should retrieve all users online or not with a role > 0", done => {
            client.getStaff((err, staff) => {
                expect(err).to.be.equal(null);
                expect(staff).to.be.an("array").and.to.have.length.above(0);
                objects.testUser(testLogin.parse, staff[0]);

                expect(staff[0]).to.contain.key("role");
                expect(staff[0].role).to.be.a("number");

                done();
            });
        });
    });

    skipIfTravis(isTravis)("#getUser", () => {
        it("should retrieve the user object for a user", done => {
            if (!extendedTestCheck(1, done))
                return;

            let user = getUsers()[0];

            client.getUser(user.id, (err, user) => {
                expect(err).to.be.equal(null);
                expect(user).to.be.an("object");
                objects.testUser(testLogin.parse, user);

                done();
            });
        });
    });

    describe("#getRoomHistory", () => {
        it("should return an array of history objects", done => {
            client.getRoomHistory((err, history) => {
                expect(err).to.be.equal(null);
                expect(history).to.be.an("array");

                if(history.length > 0)
                    objects.testHistoryEntry(testLogin.parse, history[0]);

                done();
            });
        });
    });

    describe("#validateRoomName", () => {
        it("should return a validated room name based on the input", done => {
            client.validateRoomName("test!-_||%22D", (err, name) => {
                expect(err).to.be.equal(null);
                expect(name).to.be.a("string").and.have.length.above(0);
                done();
            });
        });
    });

    describe("#validateUsername", () => {
        it("should return a validated username based on the input", done => {
            client.validateUsername("test!-_||%22D", (err, name) => {
                expect(err).to.be.equal(null);
                expect(name).to.be.a("string").and.have.length.above(0);
                done();
            });
        });
    });

    describe("#saveSettings", () => {
        it("should save the settings object on the server", done => {
            client.saveSettings(err => {
                expect(err).to.be.equal(null);
                done();
            });
        });
    });

    describe("#setLock", () => {
        it("should unlock the waitlist", done => {
            client.setLock(false, false, done);
        });
    });

    describe("#setCycle", () => {
        it("should set if the waitlist should cycle", done => {
            client.setCycle(true, done);
        });
    });

    skipIfTravis(isTravis)("#addToWaitlist", () => {
        it("should add a user by their ID to the waitlist", done => {
            if (!extendedTestCheck(1, done))
                return;

            const user = getUsers()[0];

            client.addToWaitlist(user.id, err => {

                if(err) {
                    if(err.code === 403)
                        expect(err.message).to.equal("This request was understood but is forbidden.");
                }

                done();
            });
        });
    });

    skipIfTravis(isTravis)("#meh", () => {
        it("should meh a song", done => {
            client.meh(done);
        });
    });

    skipIfTravis(isTravis)("#woot", () => {
        it("should woot a song", done => {
            client.woot(done);
        });
    });

    describe("#addPlaylist", () => {
        it("should create a new playlist", done => {
            client.addPlaylist("testPlaylist", (err, playlist) => {
                expect(err).to.be.equal(null);
                expect(playlist).to.be.an("object");

                objects.testPlaylist(testLogin.parse, playlist);

                if(!err)
                    _playlist = playlist.id;
                else
                    console.log("couldn't assign playlist, all functions which require a playlist won't be tested");

                done();
            });
        });
    });

    skipIfTravis(isTravis)("#grab", () => {
        it("should grab a song", done => {
            if (!extendedTestCheck(1, done))
                return;

            if (_playlist)
                client.grab(_playlist, done);
            else
                console.log("playlist not set, skipping grab");
        });
    });

    describe("#addMedia", () => {
        it("a media file from youtube and soundcloud", done => {
            const ytObj = {
                "title": "Nightstep - Army Of Two",
                "id": "6DSOGA9HQM4",
                "thumbnails": {
                    "default": {
                        "url": "https://i.ytimg.com/vi/6DSOGA9HQM4/default.jpg"
                    }
                }
            };

            const sndObj = {
                "title": "Smosh - Legend of Zelda rap",
                "id": 30271545,
                "duration": 213475,
                "artwork_url": "https://i1.sndcdn.com/artworks-000015183915-7m8l9z-large.jpg"
            };

            if (_playlist)
                client.addMedia(_playlist, [ytObj, sndObj], true, done);
            else
                console.log("playlist not set, skipping addMedia");
        });
    });

    skipIfTravis(isTravis)("#skipDJ", () => {
        it("should skip the current DJ", done => {
            if (!extendedTestCheck(1, done))
                return;

            client.skipDJ(testLogin.parse ? client.getBooth().dj : client.getBooth().currentDJ, done);
        });
    });

    skipIfTravis(isTravis)("#moveDJ", () => {
        it("should move a DJ to a new position in the waitlist", done => {
            if (!extendedTestCheck(2, done))
                return;

            let waitlist = client.getWaitlist();
            client.moveDJ(waitlist[waitlist.length - 1], 0, done);
        });
    });

    describe("#createRoom", () => {
        it("should create a new room with a timestamp as the name", done => {
            const date = Date.now().toString();
            client.createRoom(date, true, (err, room) => {
                if(err) {
                    if(err.code === 403)
                        expect(err.message).to.equal("Host limit reached");
                } else {

                    expect(err).to.be.equal(null);
                    expect(room).to.be.an("object");
                    expect(room).to.have.all.keys([
                        "id",
                        "name",
                        "slug"
                    ]);

                    expect(room.id).to.be.a("number");
                    expect(room.name).to.be.a("string").and.to.equal(date);
                    expect(room.slug).to.be.a("string");
                }

                done();
            });
        });
    });

    describe("#updateRoomInfo", () => {
        it("should update the room description and welcome message", done => {
            client.updateRoomInfo("testName", "testDesc", "testWelcome", err => {
                const meta = client.getRoomMeta();

                expect(meta.description).to.be.equal("testDesc");
                expect(meta.welcome).to.be.equal("testWelcome");
                done();
            });
        });
    });

    skipIfTravis(isTravis)("#muteUser", () => {
        it("should mute a user", done => {
            if (!extendedTestCheck(1, done))
                return;

            const user = getUsers()[0];

            if (user) {
                client.muteUser(user.id, client.MUTEDURATION.SHORT, client.BANREASON.VIOLATING_COMMUNITY_RULES, err => {

                    if(err) {
                        if(err.code === 403)
                            expect(err.message).to.equal("This user cannot be muted");
                    } else {
                        expect(err).to.equal(null);
                    }

                    done();
                });
            }
        });
    });

    describe("#getMutes", () => {
        it("should retrieve an array of mute objects", done => {
            client.getMutes((err, mutes) => {
                expect(err).to.be.equal(null);
                expect(mutes).to.be.an("array");

                if (mutes.length > 0)
                    objects.testMute(testLogin.parse, mutes[0]);

                done();
            });
        });
    });

    describe("#setMinChatLevel", () => {
        it("should set the minimum chat level", done => {
            client.setMinChatLevel(3, () => {
                expect(client.getMinChatLevel()).to.be.a("number").and.equal(3);
                done();
            });
        });
    });

    skipIfTravis(isTravis)("#addStaff", () => {
        it("should add a user as staff", done => {
            if (!extendedTestCheck(1, done))
                return;

            const user = getUsers()[0];
            client.addStaff(user.id, client.USERROLE.BOUNCER, done);
        });
    });

    skipIfTravis(isTravis)("#ignoreUser", () => {
        it("should ignore a user", done => {
            if (!extendedTestCheck(1, done))
                return;

            const user = getUsers()[0];
            client.ignoreUser(user.id, done);
        });
    });

    describe("#getIgnores", () => {
        it("should get all ignored users", done => {
            client.getIgnores((err, ignores) => {
                expect(err).to.be.equal(null);
                expect(ignores).to.be.an("array");

                if(ignores.length > 0) {
                    expect(ignores[0]).to.be.an("object");
                    expect(ignores[0]).to.have.all.keys([
                        "id",
                        "username"
                    ]);

                    expect(ignores[0].id).to.be.a("number");
                    expect(ignores[0].username).to.be.a("string");
                }

                done();
            });
        });
    });

    skipIfTravis(isTravis)("#removeIgnore", () => {
        it("should remove the previously ignored user", done => {
            if (!extendedTestCheck(1, done))
                return;

            const user = getUsers()[0];

            client.removeIgnore(user.id, (err, ignore) => {
                expect(err).to.be.equal(null);

                expect(ignore).to.be.an("object");
                expect(ignore).to.have.all.keys([
                    "id",
                    "username"
                ]);

                expect(ignore.id).to.be.a("number");
                expect(ignore.username).to.be.a("string");

                done();
            });
        });
    });

    skipIfTravis(isTravis)("#removeStaff", () => {
        it("should remove the previously added staff member", done => {
            if (!extendedTestCheck(1, done))
                return;

            const user = getUsers()[0];

            client.removeStaff(user.id, err => {

                if(err) {
                    if(err.code === 403)
                        expect(err.message).to.equal("Cannot change the permissions for a higher ranking user");
                }

                done();
            });
        });
    });

    skipIfTravis(isTravis)("#removeDJ", () => {
        it("should remove a DJ from the waitlist", done => {
            if (!extendedTestCheck(1, done))
                return;

            const users = getUsers();

            client.removeDJ(users[0].id, err => {
                expect(err).to.be.equal(null);
                done();
            });
        });
    });

    skipIfTravis(isTravis)("#unmuteUser", () => {
        it("should unmute the previously muted user", done => {
            if (!extendedTestCheck(1, done))
                return;

            const user = getUsers()[0];
            client.unmuteUser(user.id, done);
        });
    });

    skipIfTravis(isTravis)("#banUser", () => {
        it("should ban a user", done => {
            if (!extendedTestCheck(1, done))
                return;

            _id = getUsers()[0].id;
            expect(_id).to.be.a("number");

            client.banUser(_id, client.BANDURATION.SHORT, client.BANREASON.VIOLATING_COMMUNITY_RULES, err => {

                if(err) {
                    if(err.code === 403)
                        expect(err.message).to.equal("Cannot ban a higher ranking user");
                }

                done();
            });
        });
    });

    skipIfTravis(isTravis)("#unbanUser", () => {
        it("should unban the previously banned user", done => {
            if (!extendedTestCheck(1, done))
                return;

            client.unbanUser(_id, done);
        });
    });

    describe("#requestSelf", () => {
        it("should request its own user state from the server", done => {
            client.requestSelf((err, self) => {
                expect(err).to.be.equal(null);
                objects.testSelf(testLogin.parse, self);

                done();
            });
        });
    });

    describe("#getMyHistory", () => {
        it("should request its own history", done => {
            client.getMyHistory((err, history) => {
                expect(err).to.be.equal(null);
                expect(history).to.be.an("array");

                if(history.length > 0)
                    objects.testHistoryEntry(testLogin.parse, history[0]);

                done();
            });
        });
    });

    describe("#getFriends", () => {
        it("should request all friends from the server", done => {
            client.getFriends((err, friends) => {
                expect(err).to.be.equal(null);
                expect(friends).to.be.an("array");

                if(friends.length > 0)
                    objects.testUser(testLogin.parse, friends[0]);

                done();
            });
        });
    });

    describe("#findPlaylist", () => {
        it("should search for playlists by their name", done => {
            client.findPlaylist("a", (err, playlists) => {
                expect(err).to.be.equal(null);
                expect(playlists).to.be.an("array");

                if(playlists.length > 0)
                    objects.testPlaylist(testLogin.parse, playlists[0]);

                done();
            });
        });
    });

    describe("#findMediaPlaylist", () => {
        it("should search for media in a playlist filtered by a keyword", done => {
            if (_playlist) {
                client.findMediaPlaylist(_playlist, "a", (err, media) => {
                    expect(err).to.be.equal(null);
                    expect(media).to.be.an("array");

                    if(media.length > 0) {
                        objects.testMedia(testLogin.parse, media[0]);
                        _media = media[0];
                    }

                    done();
                });
            } else {
                console.log("playlist not set, skipping findMediaPlaylist");
            }
        });
    });

    describe("#getPlaylists", () => {
        it("should get all playlists", done => {
            client.getPlaylists((err, playlists) => {
                expect(err).to.be.equal(null);
                expect(playlists).to.be.an("array");

                if (playlists.length > 0)
                    objects.testPlaylist(testLogin.parse, playlists[0]);

                done();
            });
        });
    });

    describe("#getPlaylist", () => {
        it("should return a playlist", done => {
            if(_playlist) {
                client.getPlaylist(_playlist, (err, playlist) => {
                    expect(err).to.be.equal(null);
                    expect(playlist).to.be.an("array");

                    if(playlist.length > 0)
                        objects.testMedia(testLogin.parse, playlist[0]);

                    done();
                });
            } else {
                console.log("playlist not set, skipping getPlaylist");
            }
        });
    });

    describe("#getFavoriteRooms", () => {
        it("should get all favorited rooms", done => {
            client.getFavoriteRooms((err, rooms) => {
                expect(err).to.be.equal(null);
                expect(rooms).to.be.an("array");

                if(rooms.length > 0) {
                    expect(rooms[0]).to.be.an("object");
                    objects.testExtendedRoom(testLogin.parse, rooms[0]);
                }

                done();
            });
        });
    });

    describe("#setProfileMessage", () => {
        it("should change its profile message", done => {
            client.setProfileMessage("testProfileMessage", done);
        });
    });

    describe("#renamePlaylist", () => {
        it("should rename a playlist", done => {
            if (_playlist)
                client.renamePlaylist(_playlist, "testName", done);
            else
                console.log("playlist not set, skipping grab");
        });
    });

    describe("#setAvatar", () => {
        it("should set the avatar of itself to base01", done => {
            client.setAvatar("base01", done);
        });
    });

    skipIfTravis(isTravis)("#setBadge", () => {
        it("should set the badge of itself to bt-g", done => {
            client.setBadge("bt-g", done);
        });
    });

    describe("#setLanguage", () => {
        it("should set the language of itself to english (en)", done => {
            client.setLanguage("en", done);
        });
    });

    {
        let _request = null;

        skipIfTravis(isTravis)("#getFriendRequests", () => {
            it("should request all friend requests from the server", done => {
                client.getFriendRequests((err, requests) => {
                    expect(err).to.be.equal(null);
                    expect(requests).to.be.an("array");

                    if(requests.length > 0) {
                        _request = requests[0].id;
                        objects.testFriendRequest(testLogin.parse, requests[0]);
                    }

                    done();
                });
            });
        });

        skipIfTravis(isTravis)("#rejectFriendRequest", () => {
            it("should reject a friend request", done => {
                if (_request !== null) {
                    client.rejectFriendRequest(_request, err => {
                        expect(err).to.be.equal(null);
                        // plug doesn't reallyID check if stated ID ever sent you a request
                        // so we will just check if this endpoint is still available

                        done();
                    });
                } else {
                    console.log("no friend requests to reject");
                    done();
                }
            });
        });
    }

    describe("#activatePlaylist", () => {
        it("should activate a playlist", done => {
            if (_playlist) {
                client.activatePlaylist(_playlist, (err, status) => {
                    expect(err).to.be.equal(null);
                    expect(status).to.be.an("number");

                    done();
                });
            } else {
                console.log("playlist not set, skipping activatePlaylist");
            }
        });
    });

    describe("#joinWaitlist", () => {
        it("should join the waitlist", done => {
            client.joinWaitlist((err, waitlist) => {
                expect(err).to.be.equal(null);

                done();
            });
        });
    });

    describe("#leaveWaitlist", () => {
        it("should leave the waitlist", done => {
            client.leaveWaitlist((err, waitlist) => {
                expect(err).to.be.equal(null);

                done();
            });
        });
    });

    describe("#moveMedia", () => {
        it("should move a media entry to another position", done => {
            if (_playlist) {
                client.moveMedia(_playlist, [_media.id], _media.id, (err, playlist) => {

                    if(err) {
                        if(err.code === 400)
                            expect(err.message).to.equal("ids is required");
                    } else {
                        objects.testMedia(testLogin.parse, playlist[0]);
                    }

                    done();
                });
            } else {
                console.log("playlist not set, skipping moveMedia");
            }
        });
    });

    describe("#updateMedia", () => {
        it("should update the media title and author with testTitle and testAuthor", done => {
            if (_playlist)
                client.updateMedia(_playlist, _media.id, "testAuthor", "testTitle", done);
            else
                console.log("playlist not set, skipping updateMedia");
        });
    });

    describe("#shufflePlaylist", () => {
        it("should shuffle a playlist", done => {
            if (_playlist) {
                client.shufflePlaylist(_playlist, (err, playlist) => {
                    expect(err).to.be.equal(null);
                    expect(playlist).to.be.an("array");

                    if(playlist.length > 0)
                        objects.testMedia(testLogin.parse, playlist[0]);

                    done();
                });
            } else {
                console.log("playlist not set, skipping shufflePlaylist");
            }
        });
    });

    skipIfTravis(isTravis)("#addFriend", () => {
        it("should add a user as a friend", done => {
            if (!extendedTestCheck(1, done))
                return;

            const user = client.getUsers()[0];

            if (user)
                client.addFriend(user.id, done);
            else
                client._log(0, "could not test addFriend since user was not found in room");
        });
    });

    describe("#deleteMedia", () => {
        it("should delete a media object from a playlist", done => {
            if (_playlist) {
                client.deleteMedia(_playlist, [_media.id], (err, media) => {
                    expect(err).to.be.equal(null);
                    expect(media).to.be.an("array");

                    if(media.length > 0)
                        objects.testMedia(testLogin.parse, media[0]);

                    done();
                });
            } else {
                console.log("playlist not set, skipping deleteMedia");
            }
        });
    });

    describe("#deletePlaylist", () => {
        it("should delete a playlist", done => {
            if (_playlist)
                client.deletePlaylist(_playlist, done);
            else
                console.log("playlist not set, skipping deletePlaylist");
        });
    });

    describe("#favoriteRoom", () => {
        it("should favorite a room", done => {
            client.favoriteRoom(_room.meta.id, done);
        });
    });

    describe("#deleteNotification", () => {
        it("should delete a notification or error if no notification is available", done => {
            client.deleteNotification(329048, err => {
                expect(err).to.be.equal(null);
                // again plug doesn't tell us if that was successful or not
                // so we just check for the endpoint

                done();
            });
        });
    });

    skipIfTravis(isTravis)("#removeFriend", () => {
        it("should remove a user as a friend", done => {
            if (!extendedTestCheck(1, done))
                return;

            const user = client.getUsers()[0];

            if (user)
                client.removeFriend(user.id, done);
            else
                client._log(0, "could not test removeFriend since user was not found in room");
        });
    });

    describe("#getInventory", () => {
        it("should retrieve the inventory", done => {
            client.getInventory((err, inventory) => {
                expect(err).to.be.equal(null);
                expect(inventory).to.be.an("array");

                if(inventory.length > 0) {
                    expect(inventory[0]).to.have.all.keys([
                        "category",
                        "id",
                        "type"
                    ]);

                    expect(inventory[0].category).to.be.a("string");
                    expect(inventory[0].id).to.be.a("string");
                    expect(inventory[0].type).to.be.a("string");
                }

                done();
            });
        });
    });

    describe("#getProducts", () => {
        it("should retrieve all the products of the base category", done => {
            client.getProducts("avatars", "base", (err, base) => {
                expect(err).to.be.equal(null);
                expect(base).to.be.an("array");

                if(base.length > 0) {
                    expect(base[0]).to.have.all.keys([
                        "category",
                        "id",
                        "level",
                        "name",
                        "pp",
                        "tier_name",
                        "type"
                    ]);

                    expect(base[0].category).to.be.a("string");
                    expect(base[0].id).to.be.a("number");
                    expect(base[0].level).to.be.a("number");
                    expect(base[0].name).to.be.a("string");
                    expect(base[0].pp).to.be.a("number");
                    expect(base[0].tier_name).to.be.a("string");
                    expect(base[0].type).to.be.a("string");

                    _store = base[0];
                }

                done();
            });
        });
    });

    describe("#getTransactions", () => {
        it("should retrieve an array of transactions", done => {
            client.getTransactions((err, transactions) => {
                expect(err).to.be.equal(null);
                expect(transactions).to.be.an("array");

                if(transactions.length > 0)
                    objects.testTransaction(testLogin.parse, transactions[0]);

                done();
            });
        });
    });

    describe("#purchaseUsername", () => {
        it("should purchase a new username", done => {
            client.purchaseUsername(testLogin.usernameToBuy, (err, item) => {
                if(item) {
                    expect(item).to.be.an("object");
                    expect(item).to.have.all.keys([
                        "count",
                        "name",
                        "pp"
                    ]);

                    expect(item.count).to.be.a("number");
                    expect(item.name).to.be.a("string").and.equal("username");
                    expect(item.pp).to.be.a("number");
                }

                done();
            });
        });
    });

    describe("#purchaseItem", () => {
        it("should buy an item from the store", done => {
            client.purchaseItem(_store.id, (err, item) => {
                if(err) {
                    expect(err.message).to.equal("owned");
                } else {
                    if(item) {
                        expect(item).to.be.an("object");
                        expect(item).to.have.all.keys([
                            "count",
                            "name",
                            "pp"
                        ]);

                        expect(item.count).to.be.a("number");
                        expect(item.name).to.be.a("string").and.equal(_store.name);
                        expect(item.pp).to.be.a("number");
                    }
                }

                done();
            });
        });
    });
});

describe("Local", () => {

    describe("#getJar", () => {
        it("should return the jar used for http requests", () => {
            expect(client.getJar()).to.be.an("object");
        });
    });

    describe("#setJar", () => {
        it("should set the jar that is used for http requests", () => {
            const jar = client.getJar();
            client.setJar(jar);
            expect(client.getJar()).to.equal(jar);
        });
    });

    skipIfTravis(isTravis)("#getChatByUsername", () => {
        it("should get the messages written by a user", () => {
            const user = client.getSelf();

            let messages = client.getChatByUsername(user.username);

            expect(messages).to.be.an("array");

            if(messages.length > 0) {
                expect(messages[0]).to.be.an("object");
                expect(messages[0]).to.have.all.keys([
                    "message",
                    "username",
                    "cid",
                    "id",
                    "sub"
                ]);

                expect(messages[0].message).to.be.a("string");
                expect(messages[0].username).to.be.a("string");
                expect(messages[0].cid).to.be.a("string");
                expect(messages[0].id).to.be.a("number");
                expect(messages[0].sub).to.be.a("number");
            }
        });
    });

    describe("#getChat", () => {
        it("should get the whole chat", () => {
            expect(client.getChat()).to.be.an("array");
        });
    });

    skipIfTravis(isTravis)("#removeChatMessage", () => {
        it("should remove a chat message", () => {
            let chat = client.getChat();
            let length = chat.length;

            if(chat.length > 0) {
                client.removeChatMessage(chat[0].cid, false);
                expect(length).to.not.equal(chat.length);
            }
        });
    });

    skipIfTravis(isTravis)("#removeChatMessagesByUser", () => {
        it("should delete all messages of a user", () => {
            client.sendChat("test");
            const user = client.getSelf();

            if (user) {
                client.removeChatMessagesByUser(user.username, true);
                expect(client.getChatByUsername(user.username)).to.be.an("array").and.have.length(0);
            } else {
                client._log("could not test removeChatMessagesByUser since user was not found in room");
            }
        });
    });

    describe("#clearChatCache", () => {
        it("should clear the chat cache", () => {
            client.clearChatCache();
            expect(client.getChat()).to.have.length(0);
        });
    });

    describe("#watchUserCache", () => {
        it("should activate the user cache", () => {
            client.watchUserCache(true);
            expect(client.cleanCacheInterval).to.not.equal(-1);
        });
    });

    describe("#cacheChat", () => {
        it("should activate the chat cache", () => {
            client.cacheChat(true);
            expect(client.isChatCached()).to.equal(true);
        });
    });

    describe("#setChatCacheSize", () => {
        it("should set the chat cache size to 128", () => {
            expect(client.setChatCacheSize(128)).to.equal(128);
        });
    });

    describe("#cacheUserOnLeave", () => {
        it("should enable user caching for those who leave", () => {
            client.cacheUserOnLeave(true);
            expect(client.isUserCachedOnLeave()).to.equal(true);
        });
    });

    skipIfTravis(isTravis)("#clearUserFromLists", () => {
        it("should clear the user from the vote and grab list", () => {
            const user = client.getUsers()[0];

            if (user) {
                client.clearUserFromLists(user.id);
                let done = true;

                for(let i = 0, l = client.state.room.votes.length; i < l; i++) {
                    if(user.id == client.state.room.votes[i]) {
                        done = false;
                        break;
                    }
                }

                expect(done).to.equal(true);
            } else {
                client._log(0, "could not test clearUserFromLists since no user was found in room");
            }
        });
    });

    describe("#invokeLogger", () => {
        it("should invoke a logging function", () => {
            const logger = msg => {
                console.log(msg);
            };

            client.invokeLogger(logger);
            expect(client.log).to.equal(logger);
        });
    });

    describe("#getRoom", () => {
        it("should get the current room's stats", () => {
            const room = client.getRoom();

            objects.testRoom(testLogin.parse, room);
        });
    });

    skipIfTravis(isTravis)("#getUserByName", () => {
        it("should get a user by name", () => {
            if (!extendedTestCheck(1))
                return;

            const user = client.getUsers()[0];
            objects.testUser(testLogin.parse, client.getUserByName(user.username));
        });
    });

    skipIfTravis(isTravis)("#getUserById", () => {
        it("should get a user by their ID", () => {
            if (!extendedTestCheck(1))
                return;

            const user = client.getUsers()[0];
            objects.testUser(testLogin.parse, client.getUserById(user.id));
        });
    });

    skipIfTravis(isTravis)("#getUserRole", () => {
        it("should get a user's role", () => {
            if (!extendedTestCheck(1))
                return;

            const user = client.getUsers()[0];
            expect(client.getUserRole(user.id)).to.equal(user.role);
        });
    });

    describe("#getUsers", () => {
        it("should get all users that are currently in the room", () => {
            const users = client.getUsers();

            expect(users).to.be.an("array");

            if(users.length > 0)
                objects.testUser(testLogin.parse, users[0]);
        });
    });

    describe("#getSelf", () => {
        it("should get a representation of itself", () => {
            objects.testUser(testLogin.parse, client.getSelf());
        });
    });

    describe("#setSetting", () => {
        it("should change a setting and save it", done => {
            const chatImages = client.getSetting("chatImages");
            client.setSetting("chatImages", !chatImages, err => {
                expect(err).to.be.equal(null);
                expect(chatImages).to.not.equal(client.getSetting("chatImages"));
                done();
            });
        });
    });

    describe("#getSetting", () => {
        it("should return one setting (exp: chatImages)", () => {
            expect(client.getSetting("chatImages")).to.be.a("boolean");
        });
    });

    skipIfTravis(isTravis)("#isFriend", () => {
        it("should indicate whether a user is a friend or not", () => {
            if (!extendedTestCheck(1))
                return;

            const user = getUsers()[0];
            expect(client.isFriend(user.id)).to.be.a("boolean");
        });
    });

    skipIfTravis(isTravis)("#getDJ", () => {
        it("should get the current DJ playing", () => {
            const dj = client.getDJ();

            if(dj)
                objects.testUser(testLogin.parse, dj);
        });
    });

    skipIfTravis(isTravis)("#getMedia", () => {
        it("should return the current media object", () => {
            objects.testMedia(testLogin.parse, client.getMedia());
        });
    });

    describe("#getPlayback", () => {
        it("should get the playback object", () => {
            const playback = client.getPlayback();
            objects.testPlayback(testLogin.parse, playback);
        });
    });

    describe("getStartTime", () => {
        it("should get the start time from the playback object", () => {
            expect(client.getStartTime()).to.be.a("string");
        });
    });

    describe("#getBooth", () => {
        it("should get the booth", () => {
            const booth = client.getBooth();
            objects.testBooth(testLogin.parse, booth);
        });
    });

    describe("#getRoomMeta", () => {
        it("should get the metadata of the room", () => {
            const meta = client.getRoomMeta();
            objects.testMeta(testLogin.parse, meta);
        });
    });

    describe("#getFX", () => {
        it("should get the fx settings of the room", () => {
            expect(client.getFX()).to.be.an("array");
        });
    });

    skipIfTravis(isTravis)("#checkGlobalRole", () => {
        it("should give back the global role of a user", () => {
            if (!extendedTestCheck(1))
                return;

            const user = client.getUsers()[0];
            expect(client.checkGlobalRole(user.gRole)).to.be.a("number");
        });
    });

    describe("#getHostName", () => {
        it("should get the name of the host of the room", () => {
            expect(client.getHostName()).to.be.a("string");
        });
    });

    describe("#getHostID", () => {
        it("should get the ID of the host of the room", () => {
            expect(client.getHostID()).to.be.a("number");
        });
    });

    describe("#getPopulation", () => {
        it("should return the population of the room", () => {
            expect(client.getPopulation()).to.be.a("number").and.be.above(0);
        });
    });

    describe("#getGuests", () => {
        it("should return the amount of guests in the room", () => {
            expect(client.getGuests()).to.be.a("number");
        });
    });

    describe("#getMinChatLevel", () => {
        it("should return the minimum chat level needed to communicate", () => {
            expect(client.getMinChatLevel()).to.be.a("number");
        });
    });

    describe("#isFavorite", () => {
        it("should return if the current room is favorited", () => {
            expect(client.isFavorite()).to.be.a("boolean");
        });
    });

    describe("#getRoomName", () => {
        it("should return the room name", () => {
            expect(client.getRoomName()).to.be.a("string");
        });
    });

    describe("#getDescription", () => {
        it("should return the room description", () => {
            expect(client.getDescription()).to.be.a("string");
        });
    });

    describe("#getWelcomeMessage", () => {
        it("should return the welcome message of the room", () => {
            expect(client.getWelcomeMessage()).to.be.a("string");
        });
    });

    describe("#getSlug", () => {
        it("should return the URL conform name of the room", () => {
            expect(client.getSlug()).to.be.a("string");
        });
    });

    describe("#getWaitlist", () => {
        it("should return an array with IDs representing the waitlist", () => {
            expect(client.getWaitlist()).to.be.an("array");
        });
    });

    describe("#isWaitlistLocked", () => {
        it("should return a boolean indicating whether the waitlist is locked or not", () => {
            expect(client.isWaitlistLocked()).to.be.a("boolean");
        });
    });

    describe("#doesWaitlistCycle", () => {
        it("should return a boolean indicating whether the waitlist cycle is enabled or not", () => {
            expect(client.doesWaitlistCycle()).to.be.a("boolean");
        });
    });

    describe("#getVotes", () => {
        describe("withUserObject", () => {
            it("should return an array representing the current votes from their respective users", () => {
                const votes = client.getVotes(true);

                expect(votes).to.be.an("array");

                if (votes.length > 0) {
                    expect(votes[0]).to.be.an("object");
                    expect(votes[0]).to.have.all.keys([
                        "direction",
                        "user"
                    ]);

                    expect(votes[0].direction).to.be.a("number");
                    expect(votes[0].user).to.be.an("object");
                    objects.testUser(testLogin.parse, votes[0].user);
                }
            });
        });

        describe("withIDs", () => {
            it("should return an array representing the current votes", function() {
                const votes = client.getVotes();

                expect(votes).to.be.an("array");

                if (votes.length > 0) {
                    expect(votes[0]).to.be.an("object");
                    expect(votes[0]).to.have.all.keys([
                        "direction",
                        "id"
                    ]);

                    expect(votes[0].direction).to.be.a("number");
                    expect(votes[0].id).to.be.a("number");
                }
            });
        });
    });

    describe("#getGrabs", () => {
        describe("withUserObject", () => {
            it("should return an array representing the grabs with their respective users", () => {
                const grabs = client.getGrabs(true);

                expect(grabs).to.be.an("array");

                if(grabs.length > 0) {
                    expect(grabs[0]).to.be.an("object");
                    objects.testUser(testLogin.parse, grabs[0]);
                }
            });
        });

        describe("withoutUserObjects", () => {
            it("should return an array representing the grabs", () => {
                const grabs = client.getGrabs();

                expect(grabs).to.be.an("array");

                if(grabs.length > 0)
                    expect(grabs[0]).to.be.a("number");
            });
        });
    });

    skipIfTravis(isTravis)("#cacheUser", () => {
        it("should cache a user", () => {
            if (!extendedTestCheck(1))
                return;

            const user = getUsers()[0];
            const cache = client.getUserById(user.id, client.CACHE.ONLY);

            if (cache) {
                expect(cache.id).to.be.equal(user.id);
                expect(client.cacheUser(user)).to.be.a("boolean").and.equal(false);
            } else {
                expect(client.cacheUser(user)).to.be.a("boolean").and.equal(true);
            }
        });
    });

    skipIfTravis(isTravis)("#removeCachedUserById", () => {
        it("should remove a cached user by their ID", () => {
            if (!extendedTestCheck(1))
                return;

            const user = getUsers()[0];
            const cache = client.getUserById(user.id, client.CACHE.ONLY);

            if (cache)
                expect(client.cacheUser(user)).to.be.a("boolean").and.equal(true);

            expect(client.removeCachedUserById(user.id)).to.be.a("boolean").and.equal(true);
        });
    });

    skipIfTravis(isTravis)("#removeCachedUserByUsername", () => {
        it("should remove a cached user by their Name", () => {
            if (!extendedTestCheck(1))
                return;

            const user = getUsers()[0];
            const cache = client.getUserById(user.id, client.CACHE.ONLY);

            if (!cache)
                expect(client.cacheUser(user)).to.be.a("boolean").and.equal(true);

            expect(client.removeCachedUserByUsername(user.username)).to.be.a("boolean").and.equal(true);
        });
    });

    describe("#getStaffOnline", () => {
        it("should get the staff that is currently online", () => {
            const staff = client.getStaffOnline();

            expect(staff).to.be.an("array");

            if(staff.length > 0) {
                expect(staff[0]).to.be.an("object");
                objects.testUser(testLogin.parse, staff[0]);
            }
        });
    });

    describe("#getStaffOnlineByRole", () => {
        it("should get the staff with a rank higher or equal that of a co-host", () => {
            const staff = client.getStaffOnlineByRole(client.USERROLE.COHOST);

            expect(staff).to.be.an("array");

            if(staff.length > 0) {
                expect(staff[0]).to.be.an("object");
                objects.testUser(testLogin.parse, staff[0]);
            }
        });
    });

    describe("#getStaffByRole", () => {
        it("should get the staff filtered by a certain role (exp: CO-HOST)", done => {
            client.getStaffByRole(client.USERROLE.COHOST, (err, staff) => {
                expect(staff).to.be.an("array");

                if(staff.length > 0) {
                    expect(staff[0]).to.be.an("object");
                    expect(staff[0].role).to.be.equal(client.USERROLE.COHOST);
                    objects.testUser(testLogin.parse, staff[0]);
                }

                done();
            });
        });
    });

    describe("#logout", () => {
        it("should log out after being done with the test", done => {
            client.logout(err => {
                expect(err).to.equal(null);
                done();
            });
        });
    });
});


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <dimen name="home_logo_hei">45.0dip</dimen>
    <dimen name="home_logo_wid">209.0dip</dimen>
    <dimen name="home_space_hei">8.0dip</dimen>
    <dimen name="home_tab_hei">50.0dip</dimen>
    <dimen name="new_function_btn_margin_bottom">35.0dip</dimen>
</resources>

redpajama_set_name: RedPajamaGithub


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 *
 * @author lukemcnemee
 */
public class CrossRoad {
    private TrafficLight left;
    private TrafficLight right;
    private TrafficLight up;
    private TrafficLight down;

    public CrossRoad() {
        left = new TrafficLight(true);
        right = new TrafficLight(true);
        up = new TrafficLight(false);
        down = new TrafficLight(false);
    }

    public void change(){
        left.switchLight();
        right.switchLight();
        up.switchLight();
        down.switchLight();
    }

    public void show(){
        System.out.println("   |   |   ");
        System.out.println("___| "+ up.getLight()+" |___");
        System.out.println("");
        System.out.println("  "+left.getLight() + "     " + right.getLight()+"  ");
        System.out.println("___     ___");
        System.out.println("   | "+ down.getLight()+" |  ");
        System.out.println("   |   |   ");
        System.out.println("");
    }
}

/*
        System.out.println("   |   |   ");
        System.out.println("___| "+ up.getLight()+" |___");
        System.out.println("");
        System.out.println("  "+left.getLight() + "     " + right.getLight()+"  ");
        System.out.println("___     ___");
        System.out.println("   | "+ down.getLight()+" |  ");
        System.out.println("   |   |   ");
        System.out.println("");
*/


text:
<?xml version="1.0" encoding="UTF-8" ?>
<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wikidot="http://www.wikidot.com/rss-namespace">

	<channel>
		<title>New Village Needs People!</title>
		<link>http://bvs.wikidot.com/forum/t-228252/new-village-needs-people</link>
		<description>Posts in the discussion thread "New Village Needs People!" - New Village looking for people who want to play!</description>
				<copyright></copyright>
		<lastBuildDate>Sun, 10 Jul 2022 04:12:40 +0000</lastBuildDate>

					<item>
				<guid>http://bvs.wikidot.com/forum/t-228252#post-728753</guid>
				<title>New Village Needs People!</title>
				<link>http://bvs.wikidot.com/forum/t-228252/new-village-needs-people#post-728753</link>
				<description></description>
				<pubDate>Fri, 19 Mar 2010 17:49:48 +0000</pubDate>
				<wikidot:authorName>Jason Gregory</wikidot:authorName>								<content:encoded>
					<![CDATA[

I've been a long time Billy player and now I've taken the plunge into Kageship! Please come and join this new and exciting village!
 Starting out small but I plan to grow quickly.
 Please join Data Village, the Village hidden in the Matrix.

				 	]]>
				</content:encoded>							</item>
				</channel>
</rss>


text:
package poprepo

import (
	"bytes"
	"context"
	"fmt"
	"io/ioutil"
	"net/url"
	"path/filepath"
	"strconv"
	"strings"

	"go.skia.org/infra/go/exec"
	"go.skia.org/infra/go/git"
	"go.skia.org/infra/go/skerr"
	"go.skia.org/infra/go/sklog"
)

const (
	BUILDID_FILENAME = "BUILDID"
)

// PopRepoI is the interface that PopRepo supports.
//
// It supports adding and reading BuildIDs from a git repo.
type PopRepoI interface {
	// GetLast returns the last committed buildid, its timestamp, and git hash.
	GetLast(ctx context.Context) (int64, int64, string, error)

	// Add a new buildid to the repo.
	Add(ctx context.Context, buildid, ts int64) error

	// LookupBuildID looks up a buildid and branch from the git hash.
	LookupBuildID(ctx context.Context, hash string) (int64, error)
}

// PopRepo implements PopRepoI.
type PopRepo struct {
	checkout  *git.Checkout
	workdir   string
	local     bool
	subdomain string
}

// NewPopRepo returns a *PopRepo that writes and reads BuildIds into the
// 'checkout'.
//
// If not 'local' then the HOME environment variable is set for running on the
// server.
func NewPopRepo(checkout *git.Checkout, local bool, subdomain string) *PopRepo {
	return &PopRepo{
		checkout:  checkout,
		workdir:   checkout.Dir(),
		local:     local,
		subdomain: subdomain,
	}
}

// GetLast returns the last buildid, the timestamp of when that buildid was
// added, and the git hash.
//
// The timestamp is seconds since the Unix epoch.
func (p *PopRepo) GetLast(ctx context.Context) (int64, int64, string, error) {
	fullpath := filepath.Join(p.checkout.Dir(), BUILDID_FILENAME)
	b, err := ioutil.ReadFile(fullpath)
	if err != nil {
		return 0, 0, "", fmt.Errorf("Unable to read file %q: %s", fullpath, err)
	}
	s := strings.TrimSpace(string(b))
	parts := strings.Split(s, " ")
	if len(parts) != 2 {
		return 0, 0, "", fmt.Errorf("Unable to find just buildid and timestamp in: %q", s)
	}
	ts, err := strconv.ParseInt(parts[1], 10, 64)
	if err != nil {
		return 0, 0, "", fmt.Errorf("Timestamp is invalid in %q: %s", s, err)
	}
	buildid, err := strconv.ParseInt(parts[0], 10, 64)
	if err != nil {
		return 0, 0, "", fmt.Errorf("BuildID is invalid in %q: %s", s, err)
	}
	hash, err := p.checkout.RevParse(ctx, "HEAD")
	if err != nil {
		return 0, 0, "", fmt.Errorf("Unable to retrieve git hash: %s", err)
	}
	return buildid, ts, hash, nil
}

// See PopRepoI.
func (p *PopRepo) LookupBuildID(ctx context.Context, hash string) (int64, error) {
	commit, err := p.checkout.Details(ctx, hash)
	if err != nil {
		return -1, fmt.Errorf("Failed looking up buildid: %s", err)
	}
	u, err := url.Parse(commit.Subject)
	if err != nil {
		return -1, fmt.Errorf("Commit subject was not a valid URL: %s", err)
	}
	id, err := strconv.ParseInt(filepath.Base(u.Path), 10, 64)
	return id, err
}

// Add a new buildid and its assocatied Unix timestamp to the repo.
//
func (p *PopRepo) Add(ctx context.Context, buildid int64, ts int64) error {
	rollback := false
	defer func() {
		if !rollback {
			return
		}
		if err := p.checkout.UpdateBranch(ctx, git.MainBranch); err != nil {
			sklog.Errorf("While rolling back failed Add(): Unable to update the checkout at %q: %s", p.checkout.Dir(), err)
		}
	}()

	// Need to set GIT_COMMITTER_DATE with commit call.
	gitExec, err := git.Executable(ctx)
	if err != nil {
		return skerr.Wrap(err)
	}
	output := bytes.Buffer{}
	cmd := exec.Command{
		Name: gitExec,
		// If this commit message changes, also change Cache.parseLog.
		Args:           []string{"commit", "-m", fmt.Sprintf("https://android-build.googleplex.com/builds/jump-to-build/%d", buildid), fmt.Sprintf("--date=%d", ts)},
		Env:            []string{fmt.Sprintf("GIT_COMMITTER_DATE=%d", ts)},
		Dir:            p.checkout.Dir(),
		InheritEnv:     true,
		CombinedOutput: &output,
	}
	if !p.local {
		// Should be set by server.
		cmd.Env = append(cmd.Env, fmt.Sprintf("HOME=/home/skia"))
	}

	// Also needs to confirm that the buildids are ascending, which means they should be ints.
	lastBuildID, _, _, err := p.GetLast(ctx)
	if err != nil {
		return fmt.Errorf("Couldn't get last buildid: %s", err)
	}
	if buildid <= lastBuildID {
		return fmt.Errorf("Error: buildid=%d <= lastBuildID=%d, buildid added in wrong order.", buildid, lastBuildID)
	}
	if err := ioutil.WriteFile(filepath.Join(p.checkout.Dir(), BUILDID_FILENAME), []byte(fmt.Sprintf("%d %d", buildid, ts)), 0644); err != nil {
		rollback = true
		return fmt.Errorf("Failed to write updated buildid: %s", err)
	}
	if msg, err := p.checkout.Git(ctx, "add", BUILDID_FILENAME); err != nil {
		rollback = true
		return fmt.Errorf("Failed to add updated file %q: %s", msg, err)
	}
	if err := exec.Run(ctx, &cmd); err != nil {
		rollback = true
		return fmt.Errorf("Failed to commit updated file %q: %s", output.String(), err)
	}
	fmt.Printf("git commit: %q", output.String())
	if msg, err := p.checkout.Git(ctx, "push", git.DefaultRemote, git.MainBranch); err != nil {
		rollback = true
		return fmt.Errorf("Failed to push updated checkout %q: %s", msg, err)
	}

	return nil
}

// Verify that PopRepo implements PopRepoI.
var _ PopRepoI = (*PopRepo)(nil)


text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <title>shortCSS jQuery Plugin example 2 : Bootstrap</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">

	<link href="http://cdn.jsdelivr.net/bootstrap/3.0.0/css/bootstrap-theme.min.css" rel="stylesheet">
	<link href="http://cdn.jsdelivr.net/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet">

Hello, world!

This is a template for a simple marketing or informational website. It includes a large callout called the hero unit and three supporting pieces of content. Use it as a starting point to create something more unique.

Learn more »

Heading

Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui.

View details »

Heading

Donec id elit non mi porta gravida at eget metus. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui.

View details »

Heading

Donec sed odio dui. Cras justo odio, dapibus ac facilisis in, egestas eget quam. Vestibulum id ligula porta felis euismod semper. Fusce dapibus, tellus ac cursus commodo, tortor mauris condimentum nibh, ut fermentum massa justo sit amet risus.

View details »

 icon-glass

 icon-music

 icon-search

 icon-envelope

 icon-heart

 icon-star

 icon-star-empty

 icon-user

 icon-film

 icon-th-large

 icon-th

 icon-th-list

 icon-ok

 icon-remove

 icon-zoom-in

 icon-zoom-out

 icon-off

 icon-signal

 icon-cog

 icon-trash

 icon-home

 icon-file

 icon-time

 icon-road

 icon-download-alt

 icon-download

 icon-upload

 icon-inbox

© Company 2013


text:
package main

import (
	"bufio"
	"fmt"
	"math"
	"os"
	"strconv"
	"strings"
)

var min, leaf int

type node struct {
	value       int
	left, right *node
}

func split(line string) []int {
	tokens := strings.Split(line, " ")
	nodes := make([]int, len(tokens))
	for i := range nodes {
		nodes[i], _ = strconv.Atoi(tokens[i])
	}
	return nodes
}

func locate(inOrder []int, root int) int {
	for i, node := range inOrder {
		if node == root {
			return i
		}
	}
	return -1
}

func buildTree(inOrder, postOrder []int) *node {
	l := len(postOrder)
	if l == 0 {
		return nil
	}
	v := postOrder[l-1]
	idx := locate(inOrder, v)
	return &node{v, buildTree(inOrder[:idx], postOrder[:idx]), buildTree(inOrder[idx+1:], postOrder[idx:l-1])}
}

func dfs(root *node, sum int) {
	if root == nil {
		return
	}
	if root.left == nil && root.right == nil {
		switch newSum := sum + root.value; {
		case newSum < min:
			min = sum + root.value
			leaf = root.value
		case newSum == min && root.value < leaf:
			leaf = root.value
		}
		return
	}
	dfs(root.left, sum+root.value)
	dfs(root.right, sum+root.value)
}

func solve(inOrder, postOrder string) int {
	min = math.MaxInt32
	dfs(buildTree(split(inOrder), split(postOrder)), 0)
	return leaf
}

func main() {
	in, _ := os.Open("548.in")
	defer in.Close()
	out, _ := os.Create("548.out")
	defer out.Close()

	s := bufio.NewScanner(in)
	s.Split(bufio.ScanLines)

	var inOrder string
	for s.Scan() {
		inOrder = s.Text()
		s.Scan()
		fmt.Fprintln(out, solve(inOrder, s.Text()))
	}
}


text:
import React from 'react'
import { inject, observer } from 'mobx-react'

import { Grid, Row } from 'react-bootstrap'

import TestPage from '../components/exam/test-page'
import TestSelector from '../components/exam/test-selector'

@inject('examStore')
@observer
export default class Exam extends React.Component {

  render() {
    const { words } = this.props.examStore
    let page

    if (words && words.length !== 0) {
      page = <TestPage />
    } else {
      page = <TestSelector />
    }

    return page
  }
}


text:
package com.example.qinggong.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

import com.example.qinggong.R;

/**
 * Created by ZJGJK03 on 2014/12/3.
 */
public class StartActivity extends BaseActivity {
    Button btn_start;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.start);
        btn_start=(Button)findViewById(R.id.start_btn_start);
        if(btn_start!=null)
        {
            btn_start.setOnClickListener(listener);
        }
    }
    View.OnClickListener listener=new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent=new Intent(StartActivity.this,MainActivity.class);
            startActivity(intent);
        }
    };
}


text:
namespace net {

// Class that manages the order in which streams are written using the SPDY
// priority scheme described at:
// https://www.chromium.org/spdy/spdy-protocol/spdy-protocol-draft3-1#TOC-2.3.3-Stream-priority
//
// Callers must first register a stream with the PriorityWriteScheduler (by
// calling RegisterStream(), which informs the PriorityWriteScheduler of the
// stream's priority) before calling other methods referencing that stream,
// which may implicitly use the stream's priority. When the stream is
// eventually closed, the caller should unregister it from the
// PriorityWriteScheduler (by calling UnregisterStream()), to free data
// structures associated with it.
//
// Each stream can be in one of two states: ready or not ready (for writing).
// Ready state is changed by calling the MarkStreamReady() and
// MarkStreamNotReady() methods. Only streams in the ready state can be
// returned by PopNextReadyStream(); when returned by that method, the stream's
// state changes to not ready.
//
// Internally, PriorityWriteScheduler consists of 8 per-priority sublists, one
// for each priority value.  The elements (if any) of each sublist are streams
// that are ready to write and have that priority.
template <typename StreamIdType>
class PriorityWriteScheduler {
 public:
  // Creates scheduler with no streams.
  PriorityWriteScheduler() = default;

  // Registers the given stream with the scheduler, which will now track its
  // priority and ready state. If the stream was already registered, logs
  // SPDY_BUG and does nothing.
  void RegisterStream(StreamIdType stream_id, SpdyPriority priority) {
    priority = ClampPriority(priority);
    StreamInfo stream_info = {priority, false};
    bool inserted =
        stream_infos_.insert(std::make_pair(stream_id, stream_info)).second;
    SPDY_BUG_IF(!inserted) << "Stream " << stream_id << " already registered";
  }

  // Unregisters the given stream from the scheduler, which will no
  // longer keep track of its priority and ready state. If the stream
  // was not previously registered, logs SPDY_BUG and does nothing.
  void UnregisterStream(StreamIdType stream_id) {
    auto it = stream_infos_.find(stream_id);
    if (it == stream_infos_.end()) {
      SPDY_BUG << "Stream " << stream_id << " not registered";
      return;
    }
    StreamInfo& stream_info = it->second;
    if (stream_info.ready) {
      bool erased =
          Erase(&priority_infos_[stream_info.priority].ready_list, stream_id);
      DCHECK(erased);
    }
    stream_infos_.erase(it);
  }

  // Returns the priority value for the specified stream. If the stream is not
  // registered, logs SPDY_BUG and returns the lowest priority.
  SpdyPriority GetStreamPriority(StreamIdType stream_id) const {
    auto it = stream_infos_.find(stream_id);
    if (it == stream_infos_.end()) {
      SPDY_BUG << "Stream " << stream_id << " not registered";
      return kV3LowestPriority;
    }
    return it->second.priority;
  }

  // Updates the priority of the given stream. If the stream is not registered,
  // logs SPDY_BUG and does nothing.
  void UpdateStreamPriority(StreamIdType stream_id, SpdyPriority priority) {
    auto it = stream_infos_.find(stream_id);
    if (it == stream_infos_.end()) {
      SPDY_BUG << "Stream " << stream_id << " not registered";
      return;
    }
    StreamInfo& stream_info = it->second;
    if (stream_info.priority == priority) {
      return;
    }
    if (stream_info.ready) {
      bool erased =
          Erase(&priority_infos_[stream_info.priority].ready_list, stream_id);
      DCHECK(erased);
      priority_infos_[priority].ready_list.push_back(stream_id);
    }
    stream_info.priority = priority;
  }

  // Records time (in microseconds) of a read/write event for the given
  // stream. If the stream is not registered, logs SPDY_BUG and does nothing.
  void RecordStreamEventTime(StreamIdType stream_id, int64_t now_in_usec) {
    auto it = stream_infos_.find(stream_id);
    if (it == stream_infos_.end()) {
      SPDY_BUG << "Stream " << stream_id << " not registered";
      return;
    }
    PriorityInfo& priority_info = priority_infos_[it->second.priority];
    priority_info.last_event_time =
        std::max(priority_info.last_event_time, now_in_usec);
  }

  // Returns time (in microseconds) of the last read/write event for a stream
  // with higher priority than the priority of the given stream, or 0 if there
  // is no such event.
  int64_t GetLatestEventWithPrecedence(StreamIdType stream_id) const {
    auto it = stream_infos_.find(stream_id);
    if (it == stream_infos_.end()) {
      SPDY_BUG << "Stream " << stream_id << " not registered";
      return 0;
    }
    int64_t last_event_time = 0;
    const StreamInfo& stream_info = it->second;
    for (SpdyPriority p = kV3HighestPriority; p < stream_info.priority; ++p) {
      last_event_time =
          std::max(last_event_time, priority_infos_[p].last_event_time);
    }
    return last_event_time;
  }

  // If the scheduler has any ready streams, pops the next stream ID from the
  // highest priority non-empty ready list and returns it, transitioning the
  // stream from ready to not ready. If the scheduler doesn't have any ready
  // streams, logs SPDY_BUG and returns 0.
  StreamIdType PopNextReadyStream() {
    StreamIdType stream_id = 0;
    for (SpdyPriority p = kV3HighestPriority; p <= kV3LowestPriority; ++p) {
      StreamIdList& ready_list = priority_infos_[p].ready_list;
      if (!ready_list.empty()) {
        stream_id = ready_list.front();
        ready_list.pop_front();

        auto it = stream_infos_.find(stream_id);
        if (it == stream_infos_.end()) {
          SPDY_BUG << "Missing StreamInfo for stream " << stream_id;
        } else {
          it->second.ready = false;
        }
        return stream_id;
      }
    }
    SPDY_BUG << "No ready streams available";
    return stream_id;
  }

  // Returns true if there's another stream of greater or equal priority ahead
  // of |stream_id| in the queue.  This function can be called to see if
  // |stream_id| should yield work to another stream.
  bool ShouldYield(StreamIdType stream_id) const {
    // If there's a higher priority stream, this stream should yield.
    if (HasHigherPriorityReadyStream(stream_id)) {
      return true;
    }

    auto it = stream_infos_.find(stream_id);
    if (it == stream_infos_.end()) {
      SPDY_BUG << "Stream " << stream_id << " not registered";
      return false;
    }

    // If this priority level is empty, or this stream is the next up, there's
    // no need to yield.
    auto ready_list = priority_infos_[it->second.priority].ready_list;
    if (ready_list.empty() || ready_list.front() == stream_id) {
      return false;
    }

    // There are other streams in this priority level which take precedence.
    // Yield.
    return true;
  }

  // Returns true if the scheduler has any ready streams with a higher priority
  // than that of the specified stream. If the stream is not registered, logs
  // SPDY_BUG and returns false.
  bool HasHigherPriorityReadyStream(StreamIdType stream_id) const {
    auto it = stream_infos_.find(stream_id);
    if (it == stream_infos_.end()) {
      SPDY_BUG << "Stream " << stream_id << " not registered";
      return false;
    }
    const StreamInfo& stream_info = it->second;
    for (SpdyPriority p = kV3HighestPriority; p < stream_info.priority; ++p) {
      if (!priority_infos_[p].ready_list.empty()) {
        return true;
      }
    }
    return false;
  }

  // Marks the given stream as ready to write. If stream was already ready,
  // does nothing. If stream was not registered, logs SPDY_BUG and does
  // nothing. If |add_to_front| is true, adds stream to the front of its
  // per-priority ready list, otherwise adds it to the back.
  void MarkStreamReady(StreamIdType stream_id, bool add_to_front) {
    auto it = stream_infos_.find(stream_id);
    if (it == stream_infos_.end()) {
      SPDY_BUG << "Stream " << stream_id << " not registered";
      return;
    }
    StreamInfo& stream_info = it->second;
    if (stream_info.ready) {
      return;
    }
    StreamIdList& ready_list = priority_infos_[stream_info.priority].ready_list;
    if (add_to_front) {
      ready_list.push_front(stream_id);
    } else {
      ready_list.push_back(stream_id);
    }
    stream_info.ready = true;
  }

  // Marks the given stream as not ready to write, removing it from the ready
  // list for its priority. If stream was already not ready, does nothing. If
  // stream was not registered, logs SPDY_BUG and does nothing.
  void MarkStreamNotReady(StreamIdType stream_id) {
    auto it = stream_infos_.find(stream_id);
    if (it == stream_infos_.end()) {
      SPDY_BUG << "Stream " << stream_id << " not registered";
      return;
    }
    StreamInfo& stream_info = it->second;
    if (!stream_info.ready) {
      return;
    }
    bool erased =
        Erase(&priority_infos_[stream_info.priority].ready_list, stream_id);
    DCHECK(erased);
    stream_info.ready = false;
  }

  // Returns true iff the number of ready streams is non-zero.
  bool HasReadyStreams() const {
    for (SpdyPriority i = kV3HighestPriority; i <= kV3LowestPriority; ++i) {
      if (!priority_infos_[i].ready_list.empty()) {
        return true;
      }
    }
    return false;
  }

  // Returns the number of ready streams.
  size_t NumReadyStreams() const {
    size_t n = 0;
    for (SpdyPriority i = kV3HighestPriority; i <= kV3LowestPriority; ++i) {
      n += priority_infos_[i].ready_list.size();
    }
    return n;
  }

  // Returns the number of ready streams with the given priority.
  size_t NumReadyStreams(SpdyPriority priority) const {
    priority = ClampPriority(priority);
    return priority_infos_[priority].ready_list.size();
  }

 private:
  // 0(1) size lookup, 0(1) insert at front or back.
  typedef std::deque<StreamIdType> StreamIdList;

  // State kept for all registered streams. All ready streams have ready = true
  // and should be present in priority_infos_[priority].ready_list.
  struct StreamInfo {
    SpdyPriority priority;
    bool ready;
  };

  // State kept for each priority level.
  struct PriorityInfo {
    // IDs of streams that are ready to write.
    StreamIdList ready_list;
    // Time of latest write event for stream of this priority, in microseconds.
    int64_t last_event_time = 0;
  };

  typedef std::unordered_map<StreamIdType, StreamInfo> StreamInfoMap;

  static SpdyPriority ClampPriority(SpdyPriority priority) {
    if (priority < kV3HighestPriority) {
      SPDY_BUG << "Invalid priority: " << static_cast<int>(priority);
      return kV3HighestPriority;
    }
    if (priority > kV3LowestPriority) {
      SPDY_BUG << "Invalid priority: " << static_cast<int>(priority);
      return kV3LowestPriority;
    }
    return priority;
  }

  // Erases first occurrence (which should be the only one) of |stream_id| in
  // |ready_list|, returning true if found (and erased), or false otherwise.
  bool Erase(StreamIdList* ready_list, StreamIdType stream_id) {
    auto it = std::find(ready_list->begin(), ready_list->end(), stream_id);
    if (it == ready_list->end()) {
      return false;
    }
    ready_list->erase(it);
    return true;
  }

  // Per-priority state, including ready lists.
  PriorityInfo priority_infos_[kV3LowestPriority + 1];
  // StreamInfos for all registered streams.
  StreamInfoMap stream_infos_;
};

}  // namespace net

#endif  // NET_SPDY_PRIORITY_WRITE_SCHEDULER_H_


text:
SET(PROJECT_NAME TribitsHelloWorld)
# This project does not use Fortran so disable it by default
SET(${PROJECT_NAME}_ENABLE_Fortran_DEFAULT OFF)


text:
package org.wikidata.wdtk.examples;

import java.io.BufferedReader;
import java.io.FileReader;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class SentenceBounds
{

	 public static void main(String[] args) throws Exception
	    {

		 	String manipulate_file = "/home/matthias/Workbench/SUTD/nytimes_corpus/18/CoreNLP/stanford-corenlp-full-2015-01-29/1638673_output.txt.xml";

		 	BufferedReader br = new BufferedReader( new FileReader( manipulate_file ) );

		 	try
		 	{
		 		StringBuilder sb = new StringBuilder();
		 		String line = br.readLine();

		 		while (line != null)
		 		{
		 			sb.append(line);
		 			sb.append(System.lineSeparator());
		 			line = br.readLine();
		 		}
		 		String everything = sb.toString();
		 		//System.out.println(everything);
		 		Document doc = Jsoup.parse(everything);

		 		int index = 0;

		 	   for( Element item : doc.select("sentence") )
		 	   {
		 		   System.out.println("<sentence> " + index );

		 		   String word = item.select("word").text();

		 		   System.out.println(word);

		 		  System.out.println("</sentence>" + "\n");

		 		   index++;
		 	   }

		 	}
		 	finally
		 	{
		 		br.close();
		 	}
	    }

}


text:
package org.sana.api;

/**
 * Declares the behavior for an observation.
 *
 * @author Sana Development
 *
 */
public interface IObservation extends IModel {

    /**
     * Gets the unique id within the Encounter.
     * @return the id
     */
    String getId();

    /**
     * Provides the uuid of the encounter.
     *
     * @return the encounter
     */
    String getEncounter();

    /**
     * Provides the uuid of the concept.
     * @return the concept
     */
    String getConcept();

    /**
     * Returns the complex value as a file path or uri.
     *
     * @return the value_complex
     */
    String getValue_complex();

    /**
     * @return the valueText
     */
    String getValue_text();

}


text:
namespace graphics
{
  namespace gl
  {
    const graphics::Color Renderer::s_bgColor(192, 192, 192, 255);

    Renderer::Params::Params()
      : m_isDebugging(false),
        m_renderQueue(0),
        m_threadSlot(-1)
    {}

    Renderer::Renderer(Params const & params)
      : m_isDebugging(params.m_isDebugging),
        m_isRendering(false),
        m_width(0),
        m_height(0),
        m_env(0),
        m_threadSlot(params.m_threadSlot)
    {
      m_renderContext = params.m_renderContext;
      m_frameBuffer = params.m_frameBuffer;
      m_resourceManager = params.m_resourceManager;

      if (m_frameBuffer)
      {
        m_renderTarget = m_frameBuffer->renderTarget();
        m_depthBuffer = m_frameBuffer->depthBuffer();
      }

      m_renderQueue = params.m_renderQueue;
    }

    Renderer::~Renderer()
    {}

    shared_ptr<ResourceManager> const & Renderer::resourceManager() const
    {
      return m_resourceManager;
    }

    void Renderer::beginFrame()
    {
      CHECK(!m_isRendering, ("beginFrame called inside beginFrame/endFrame pair!"));
      m_isRendering = true;

      math::Matrix<float, 4, 4> coordM;
      getOrthoMatrix(coordM,
                     0, m_width,
                     m_height, 0,
                     graphics::minDepth,
                     graphics::maxDepth + 100);

      if (m_frameBuffer)
      {
        m_frameBuffer->setRenderTarget(m_renderTarget);
        m_frameBuffer->setDepthBuffer(m_depthBuffer);

        processCommand(make_shared<ChangeFrameBuffer>(m_frameBuffer));

        if (m_renderTarget != 0)
          m_renderTarget->coordMatrix(coordM);
      }

      processCommand(make_shared<ChangeMatrix>(EProjection, coordM));
      processCommand(make_shared<ChangeMatrix>(EModelView, math::Identity<float, 4>()));
    }

    bool Renderer::isRendering() const
    {
      return m_isRendering;
    }

    Renderer::ChangeMatrix::ChangeMatrix(EMatrix mt, math::Matrix<float, 4, 4> const & m)
      : m_matrixType(mt), m_matrix(m)
    {}

    void Renderer::ChangeMatrix::perform()
    {
      renderContext()->setMatrix(m_matrixType, m_matrix);
    }

    Renderer::DiscardFramebuffer::DiscardFramebuffer(bool doDiscardColor, bool doDiscardDepth)
        : m_doDiscardColor(doDiscardColor), m_doDiscardDepth(doDiscardDepth)
    {}

    void Renderer::DiscardFramebuffer::perform()
    {
      GLenum attachments[2];
      int numAttachments = 0;
      if (m_doDiscardColor)
        attachments[numAttachments++] = GL_COLOR_ATTACHMENT0_MWM;
      if (m_doDiscardDepth)
        attachments[numAttachments++] = GL_DEPTH_ATTACHMENT_MWM;
      glDiscardFramebufferFn(GL_FRAMEBUFFER_MWM, numAttachments, attachments);
    }

    void Renderer::discardFramebuffer(bool doDiscardColor, bool doDiscardDepth)
    {
      static bool firstReport = true;
      if (firstReport)
      {
        if (!glDiscardFramebufferFn)
          LOG(LDEBUG, ("GL_EXT_discard_framebuffer is unsupported"));
        firstReport = false;
      }

      if (glDiscardFramebufferFn)
        processCommand(make_shared<DiscardFramebuffer>(doDiscardColor, doDiscardDepth));
    }

    void Renderer::copyFramebufferToImage(shared_ptr<BaseTexture> target)
    {
      processCommand(make_shared<CopyFramebufferToImage>(target));
    }

    void Renderer::endFrame()
    {
      CHECK(m_isRendering, ("endFrame called outside beginFrame/endFrame pair!"));
      m_isRendering = false;
    }

    shared_ptr<FrameBuffer> const & Renderer::frameBuffer() const
    {
      return m_frameBuffer;
    }

    shared_ptr<RenderTarget> const & Renderer::renderTarget() const
    {
      return m_renderTarget;
    }

    void Renderer::setRenderTarget(shared_ptr<RenderTarget> const & rt)
    {
      CHECK(!isRendering(), ("should call this function only outside beginFrame/endFrame"));
      m_renderTarget = rt;
    }

    void Renderer::resetRenderTarget()
    {
      CHECK(!isRendering(), ("should call this function only outside beginFrame/endFrame"));
      m_renderTarget.reset();
    }

    shared_ptr<RenderBuffer> const & Renderer::depthBuffer() const
    {
      return m_depthBuffer;
    }

    void Renderer::setDepthBuffer(shared_ptr<RenderBuffer> const & rt)
    {
      CHECK(!isRendering(), ("should call this function only outside beginFrame/endFrame"));
      m_depthBuffer = rt;
    }

    void Renderer::resetDepthBuffer()
    {
      CHECK(!isRendering(), ("should call this function only outside beginFrame/endFrame"));
      m_depthBuffer.reset();
    }

    Renderer::ClearCommand::ClearCommand(graphics::Color const & color,
                                         bool clearRT,
                                         float depth,
                                         bool clearDepth)
      : m_color(color),
        m_clearRT(clearRT),
        m_depth(depth),
        m_clearDepth(clearDepth)
    {}

    void Renderer::ClearCommand::perform()
    {
      OGLCHECK(glClearColor(m_color.r / 255.0f,
                            m_color.g / 255.0f,
                            m_color.b / 255.0f,
                            m_color.a / 255.0f));
 #ifdef OMIM_GL_ES
      OGLCHECK(glClearDepthf(m_depth));
 #else
      OGLCHECK(glClearDepth(m_depth));
 #endif

      GLbitfield mask = 0;
      if (m_clearRT)
        mask |= GL_COLOR_BUFFER_BIT;
      if (m_clearDepth)
        mask |= GL_DEPTH_BUFFER_BIT;

      OGLCHECK(glDepthMask(GL_TRUE));

      OGLCHECK(glClear(mask));
    }

    void Renderer::clear(graphics::Color const & c, bool clearRT, float depth, bool clearDepth)
    {
      shared_ptr<ClearCommand> command(new ClearCommand(c, clearRT, depth, clearDepth));
      processCommand(command);
    }

    Renderer::CopyFramebufferToImage::CopyFramebufferToImage(shared_ptr<BaseTexture> target)
      : m_target(target) {}

    void Renderer::CopyFramebufferToImage::perform()
    {
      m_target->makeCurrent();
      OGLCHECK(glCopyTexImage2D(GL_TEXTURE_2D, 0, DATA_TRAITS::gl_pixel_format_type,
                                0, 0, m_target->width(), m_target->height(), 0));
    }

    Renderer::ChangeFrameBuffer::ChangeFrameBuffer(shared_ptr<FrameBuffer> const & fb)
      : m_frameBuffer(fb)
    {}

    void Renderer::ChangeFrameBuffer::perform()
    {
      m_frameBuffer->makeCurrent();

      OGLCHECK(glViewport(0, 0, m_frameBuffer->width(), m_frameBuffer->height()));
    }

    void Renderer::onSize(unsigned int width, unsigned int height)
    {
      if (width < 2) width = 2;
      if (height < 2) height = 2;

      m_width = width;
      m_height = height;

      if (m_frameBuffer)
        m_frameBuffer->onSize(width, height);
    }

    unsigned int Renderer::width() const
    {
      return m_width;
    }

    unsigned int Renderer::height() const
    {
      return m_height;
    }

    bool Renderer::isDebugging() const
    {
      return m_isDebugging;
    }

    void Renderer::processCommand(shared_ptr<Command> const & command, Packet::EType type, bool doForce)
    {
      if (command)
        command->setIsDebugging(renderQueue() && !doForce);

      if (renderQueue() && !doForce)
        renderQueue()->processPacket(Packet(command, type));
      else
        if (command)
        {
          command->setRenderContext(m_renderContext.get());
          command->perform();
        }
    }

    PacketsQueue * Renderer::renderQueue()
    {
      return m_renderQueue;
    }

    void Renderer::addFramePoint()
    {
      if (m_renderQueue)
        m_renderQueue->processPacket(Packet(Packet::EFramePoint));
    }

    void Renderer::addCheckPoint()
    {
      if (m_renderQueue)
        m_renderQueue->processPacket(Packet(Packet::ECheckPoint));
    }

    void Renderer::completeCommands()
    {
      if (m_renderQueue)
        m_renderQueue->completeCommands();
    }

    void Renderer::setEnvironment(core::CommandsQueue::Environment const * env)
    {
      m_env = env;
    }

    bool Renderer::isCancelled() const
    {
      if (m_env)
        return m_env->IsCancelled();
      else
        return false;
    }

    RenderContext * Renderer::renderContext() const
    {
      return m_renderContext.get();
    }

    int Renderer::threadSlot() const
    {
      return m_threadSlot;
    }
  }
}


text:
#import <UIKit/UIKit.h>

@interface UIScrollView (JHExtension)
@property (nonatomic, assign)   CGFloat jh_contentInsetTop;
@property (nonatomic, assign)   CGFloat jh_contentInsetBottom;
@property (nonatomic, assign)   CGFloat jh_contentInsetLeft;
@property (nonatomic, assign)   CGFloat jh_contentInsetRight;

@property (nonatomic, assign)   CGFloat jh_contentSizeWidth;
@property (nonatomic, assign)   CGFloat jh_contentSizeHeight;
@end


text:
package org.cloudfoundry.operations.useradmin;

import org.junit.Test;

public final class ListOrganizationUsersRequestTest {

    @Test(expected = IllegalStateException.class)
    public void noOrganizationName() {
        ListOrganizationUsersRequest.builder()
            .build();
    }

    @Test
    public void valid() {
        ListOrganizationUsersRequest.builder()
            .organizationName("test-organization")
            .build();
    }

}