<commit_before>/**
* this file contains tests for rbTree
*/
import prettyFormat from 'pretty-format'
import RbTree from "../src/rbTree";
import Node from '../src/treeNode'
import nodeColor from '../src/color'

let rbTree;

beforeEach(() => {
  rbTree = new RbTree();
  return rbTree;
})

test('rbTree constructor', () => {
  expect(rbTree).toMatchObject({ root: null });
});

test('rbTree find() non existing key', () => {
  expect(rbTree.find(1)).toBe(null);
});

test('rbTree emptyTree() non existing key', () => {
  rbTree.insert(1, "abc");
  rbTree.insert(2, "foo");
  rbTree.emptyTree();
  expect(rbTree.root).toBe(null);
});

test('rbTree find() existing key right side', () => {
  rbTree.insert(1, "abc");
  rbTree.insert(2, "foo");
  expect(rbTree.find(2)).toBe("foo");
});

test('rbTree find() existing key left side', () => {
  rbTree.insert(1, "abc");
  rbTree.insert(2, "foo");
  rbTree.insert(3, "bar");
  expect(rbTree.find(3)).toBe("bar");
});

test('rbTree find() existing key root', () => {
  rbTree.insert(1, "abc");
  rbTree.insert(2, "foo");
  rbTree.insert(3, "bar");
  expect(rbTree.find(1)).toBe("abc");
});

test('rbTree clone()', () => {
  let node_1 = new Node(1, "abc")
  expect(rbTree.clone(node_1)).toMatchObject(node_1);
});

test('rbTree min() non-null case', () => {
  rbTree.insert(1, "abc");
  rbTree.insert(2, "foo");
  rbTree.insert(3, "bar");
  expect(rbTree.min(rbTree.root).key).toBe(1);
});

test('rbTree min() null case', () => {
  expect(rbTree.min(null)).toMatchObject({});
  expect(rbTree.min()).toMatchObject({});
});

test('rbTree insert() root', () => {
  rbTree.insert(1, "abc");

  expect(rbTree.root.key).toBe(1);
  expect(rbTree.root.value).toBe("abc");

  expect(rbTree.root.left.key).toBe(null);
  expect(rbTree.root.left.value).toBe(null);
  expect(rbTree.root.left.color).toBe(nodeColor.BLACK);
  expect(rbTree.root.left.left).toBe(null);
  expect(rbTree.root.left.right).toBe(null);

  expect(rbTree.root.right.key).toBe(null);
  expect(rbTree.root.right.value).toBe(null);
  expect(rbTree.root.right.color).toBe(nodeColor.BLACK);
  expect(rbTree.root.right.left).toBe(null);
  expect(rbTree.root.right.right).toBe(null);
});

test('rbTree insert() five nodes', () => {

  for (var i = 1; i < 8; i++) {
    rbTree.insert(i, i + " red");
  }

  //check if keys are in the right place
  expect(rbTree.root.key).toBe(2);
  expect(rbTree.root.left.key).toBe(1);
  expect(rbTree.root.left.left.key).toBe(null);
  expect(rbTree.root.left.right.key).toBe(null);
  expect(rbTree.root.right.key).toBe(4);
  expect(rbTree.root.right.left.key).toBe(3);
  expect(rbTree.root.right.right.key).toBe(6);
  expect(rbTree.root.right.right.left.key).toBe(5);
  expect(rbTree.root.right.right.right.key).toBe(7);

  //check if values are in the right place
  expect(rbTree.root.color).toBe(nodeColor.BLACK);
  expect(rbTree.root.left.color).toBe(nodeColor.BLACK);
  expect(rbTree.root.right.color).toBe(nodeColor.RED);
  expect(rbTree.root.right.left.color).toBe(nodeColor.BLACK);
  expect(rbTree.root.right.right.color).toBe(nodeColor.BLACK);
  expect(rbTree.root.right.right.left.color).toBe(nodeColor.RED);
  expect(rbTree.root.right.right.right.color).toBe(nodeColor.RED);
});
//
test('rbTree insert() right rotate', () => {

  rbTree.insert(12, "abc");
  rbTree.insert(7, "foo");
  rbTree.insert(1, "bar");
  rbTree.insert(0, "bar");
  rbTree.insert(2, "bar");
  rbTree.insert(3, "bar");
  rbTree.insert(4, "bar");
  rbTree.insert(5, "bar");
  rbTree.insert(6, "bar");
  rbTree.insert(11, "bar");
  rbTree.insert(10, "bar");
  rbTree.insert(9, "bar");
  rbTree.insert(8, "bar");

  expect(rbTree.root.key).toBe(3);
  expect(rbTree.root.left.key).toBe(1);
  expect(rbTree.root.left.left.key).toBe(0);
  expect(rbTree.root.left.right.key).toBe(2);

  expect(rbTree.root.right.key).toBe(7);
  expect(rbTree.root.right.left.key).toBe(5);
  expect(rbTree.root.right.left.left.key).toBe(4);
  expect(rbTree.root.right.left.right.key).toBe(6);
  expect(rbTree.root.right.right.key).toBe(11);
  expect(rbTree.root.right.right.left.key).toBe(9);
  expect(rbTree.root.right.right.right.key).toBe(12);
  expect(rbTree.root.right.right.left.left.key).toBe(8);
  expect(rbTree.root.right.right.left.right.key).toBe(10);

});

//right left case
test('rbTree insert()', () => {

  rbTree.insert(10, "abc");
  rbTree.insert(9, "foo");
  rbTree.insert(27, "bar");
  rbTree.insert(25, "bar");
  rbTree.insert(28, "bar");
  rbTree.insert(29, "bar");
  rbTree.insert(24, "bar");
  rbTree.insert(26, "bar");
  rbTree.insert(23, "bar");

  expect(rbTree.root.key).toBe(25);
  expect(rbTree.root.left.key).toBe(10);
  expect(rbTree.root.left.left.key).toBe(9);
  expect(rbTree.root.left.right.key).toBe(24);
  expect(rbTree.root.left.right.left.key).toBe(23);

  expect(rbTree.root.right.key).toBe(27);
  expect(rbTree.root.right.left.key).toBe(26);
  expect(rbTree.root.right.right.key).toBe(28);
  expect(rbTree.root.right.right.right.key).toBe(29);
});

test('rbTree delete() case 1', () => {

  rbTree.insert(30, "abc");
  rbTree.insert(20, "foo");
  rbTree.insert(40, "bar");
  rbTree.insert(31, "bar");
  rbTree.insert(50, "bar");
  rbTree.insert(32, "bar");

  rbTree.remove(40);

  expect(rbTree.root.key).toBe(30);
  expect(rbTree.root.left.key).toBe(20);
  expect(rbTree.root.right.key).toBe(32);
  expect(rbTree.root.right.left.key).toBe(31);
  expect(rbTree.root.right.right.key).toBe(50);
});

test('rbTree findNode() by key ', () => {

  rbTree.insert(30, "abc");
  rbTree.insert(20, "foo");
  rbTree.insert(40, "bar");
  rbTree.insert(31, "bar");
  rbTree.insert(50, "bar");
  rbTree.insert(32, "bar");

  expect(rbTree.findNode(40).key).toBe(40);
  expect(rbTree.findNode(30).key).toBe(30);
  expect(rbTree.findNode(20).key).toBe(20);
  expect(rbTree.findNode(100)).toBe(null);
});

test('rbTree delete() non-existing node', () => {
  rbTree.insert(30, "abc");
  rbTree.remove(0);
  expect(rbTree.root.key).toBe(30);
});

test('rbTree delete() simple case', () => {
  rbTree.insert(30, "abc");
  rbTree.remove(30);
  expect(rbTree.root.key).toBe(null);
});

test('rbTree delete() left side simple case ', () => {
  rbTree.insert(30, "abc");
  rbTree.insert(20, "abc");
  rbTree.remove(20);
  expect(rbTree.root.left.key).toBe(null);
  expect(rbTree.root.right.key).toBe(null);
});

test('rbTree delete() right side simple case ', () => {
  rbTree.insert(30, "abc");
  rbTree.insert(40, "abc");
  rbTree.remove(40);
  expect(rbTree.root.left.key).toBe(null);
  expect(rbTree.root.right.key).toBe(null);
});

test('rbTree delete() simple case', () => {

  rbTree.insert(30, "abc");
  rbTree.insert(20, "foo");
  rbTree.insert(40, "bar");
  rbTree.insert(10, "bar");
  rbTree.remove(20);

  expect(rbTree.root.key).toBe(30);
  expect(rbTree.root.left.key).toBe(10);
  expect(rbTree.root.right.key).toBe(40);
});

test('rbTree delete() current node u is double black and it is not root', () => {

  rbTree.insert(30, "abc");
  rbTree.insert(20, "foo");
  rbTree.insert(40, "bar");
  rbTree.insert(35, "bar");
  rbTree.insert(50, "bar");

  rbTree.remove(20);
  expect(rbTree.root.key).toBe(40);
  expect(rbTree.root.left.key).toBe(30);
  expect(rbTree.root.right.key).toBe(50);
  expect(rbTree.root.left.right.key).toBe(35);
});

test('rbTree delete() another case', () => {

  rbTree.insert(6, "abc");
  rbTree.insert(4, "foo");
  rbTree.insert(7, "bar");
  rbTree.insert(2, "bar");
  rbTree.insert(5, "bar");

  rbTree.remove(7);
  rbTree.print();

});

// test('rbTree delete() case', () => {
//
//   rbTree.insert(10, "abc");
//   rbTree.insert(9, "foo");
//   rbTree.insert(27, "bar");
//   rbTree.insert(25, "bar");
//   rbTree.insert(28, "bar");
//   rbTree.insert(29, "bar");
//   rbTree.insert(24, "bar");
//   rbTree.insert(26, "bar");
//   rbTree.insert(23, "bar");
//
//   rbTree.remove(25);
//   rbTree.print();
// });

// test('rbTree delete() more case', () => {
//
//   rbTree.insert(12, "abc");
//   rbTree.insert(7, "foo");
//   rbTree.insert(1, "bar");
//   rbTree.insert(0, "bar");
//   rbTree.insert(2, "bar");
//   rbTree.insert(3, "bar");
//   rbTree.insert(4, "bar");
//   rbTree.insert(5, "bar");
//   rbTree.insert(6, "bar");
//   rbTree.insert(11, "bar");
//   rbTree.insert(10, "bar");
//   rbTree.insert(9, "bar");
//   rbTree.insert(8, "bar");
//
//   rbTree.remove(12);
//   rbTree.remove(7);
//   rbTree.remove(1);
//   rbTree.remove(0);
//   rbTree.remove(2);
//   rbTree.remove(3);
//   rbTree.remove(8);
//   rbTree.remove(11);
//
//   rbTree.print();
//
// });
<commit_msg>comment out some test, will fix them later<commit_after>/**
* this file contains tests for rbTree
*/
import prettyFormat from 'pretty-format'
import RbTree from "../src/rbTree";
import Node from '../src/treeNode'
import nodeColor from '../src/color'

let rbTree;

beforeEach(() => {
  rbTree = new RbTree();
  return rbTree;
})

test('rbTree constructor', () => {
  expect(rbTree).toMatchObject({ root: null });
});

test('rbTree find() non existing key', () => {
  expect(rbTree.find(1)).toBe(null);
});

test('rbTree emptyTree() non existing key', () => {
  rbTree.insert(1, "abc");
  rbTree.insert(2, "foo");
  rbTree.emptyTree();
  expect(rbTree.root).toBe(null);
});

test('rbTree find() existing key right side', () => {
  rbTree.insert(1, "abc");
  rbTree.insert(2, "foo");
  expect(rbTree.find(2)).toBe("foo");
});

test('rbTree find() existing key left side', () => {
  rbTree.insert(1, "abc");
  rbTree.insert(2, "foo");
  rbTree.insert(3, "bar");
  expect(rbTree.find(3)).toBe("bar");
});

test('rbTree find() existing key root', () => {
  rbTree.insert(1, "abc");
  rbTree.insert(2, "foo");
  rbTree.insert(3, "bar");
  expect(rbTree.find(1)).toBe("abc");
});

test('rbTree clone()', () => {
  let node_1 = new Node(1, "abc")
  expect(rbTree.clone(node_1)).toMatchObject(node_1);
});

test('rbTree min() non-null case', () => {
  rbTree.insert(1, "abc");
  rbTree.insert(2, "foo");
  rbTree.insert(3, "bar");
  expect(rbTree.min(rbTree.root).key).toBe(1);
});

test('rbTree min() null case', () => {
  expect(rbTree.min(null)).toMatchObject({});
  expect(rbTree.min()).toMatchObject({});
});

test('rbTree insert() root', () => {
  rbTree.insert(1, "abc");

  expect(rbTree.root.key).toBe(1);
  expect(rbTree.root.value).toBe("abc");

  expect(rbTree.root.left.key).toBe(null);
  expect(rbTree.root.left.value).toBe(null);
  expect(rbTree.root.left.color).toBe(nodeColor.BLACK);
  expect(rbTree.root.left.left).toBe(null);
  expect(rbTree.root.left.right).toBe(null);

  expect(rbTree.root.right.key).toBe(null);
  expect(rbTree.root.right.value).toBe(null);
  expect(rbTree.root.right.color).toBe(nodeColor.BLACK);
  expect(rbTree.root.right.left).toBe(null);
  expect(rbTree.root.right.right).toBe(null);
});

test('rbTree insert() five nodes', () => {

  for (var i = 1; i < 8; i++) {
    rbTree.insert(i, i + " red");
  }

  //check if keys are in the right place
  expect(rbTree.root.key).toBe(2);
  expect(rbTree.root.left.key).toBe(1);
  expect(rbTree.root.left.left.key).toBe(null);
  expect(rbTree.root.left.right.key).toBe(null);
  expect(rbTree.root.right.key).toBe(4);
  expect(rbTree.root.right.left.key).toBe(3);
  expect(rbTree.root.right.right.key).toBe(6);
  expect(rbTree.root.right.right.left.key).toBe(5);
  expect(rbTree.root.right.right.right.key).toBe(7);

  //check if values are in the right place
  expect(rbTree.root.color).toBe(nodeColor.BLACK);
  expect(rbTree.root.left.color).toBe(nodeColor.BLACK);
  expect(rbTree.root.right.color).toBe(nodeColor.RED);
  expect(rbTree.root.right.left.color).toBe(nodeColor.BLACK);
  expect(rbTree.root.right.right.color).toBe(nodeColor.BLACK);
  expect(rbTree.root.right.right.left.color).toBe(nodeColor.RED);
  expect(rbTree.root.right.right.right.color).toBe(nodeColor.RED);
});
//
test('rbTree insert() right rotate', () => {

  rbTree.insert(12, "abc");
  rbTree.insert(7, "foo");
  rbTree.insert(1, "bar");
  rbTree.insert(0, "bar");
  rbTree.insert(2, "bar");
  rbTree.insert(3, "bar");
  rbTree.insert(4, "bar");
  rbTree.insert(5, "bar");
  rbTree.insert(6, "bar");
  rbTree.insert(11, "bar");
  rbTree.insert(10, "bar");
  rbTree.insert(9, "bar");
  rbTree.insert(8, "bar");

  expect(rbTree.root.key).toBe(3);
  expect(rbTree.root.left.key).toBe(1);
  expect(rbTree.root.left.left.key).toBe(0);
  expect(rbTree.root.left.right.key).toBe(2);

  expect(rbTree.root.right.key).toBe(7);
  expect(rbTree.root.right.left.key).toBe(5);
  expect(rbTree.root.right.left.left.key).toBe(4);
  expect(rbTree.root.right.left.right.key).toBe(6);
  expect(rbTree.root.right.right.key).toBe(11);
  expect(rbTree.root.right.right.left.key).toBe(9);
  expect(rbTree.root.right.right.right.key).toBe(12);
  expect(rbTree.root.right.right.left.left.key).toBe(8);
  expect(rbTree.root.right.right.left.right.key).toBe(10);

});

//right left case
test('rbTree insert()', () => {

  rbTree.insert(10, "abc");
  rbTree.insert(9, "foo");
  rbTree.insert(27, "bar");
  rbTree.insert(25, "bar");
  rbTree.insert(28, "bar");
  rbTree.insert(29, "bar");
  rbTree.insert(24, "bar");
  rbTree.insert(26, "bar");
  rbTree.insert(23, "bar");

  expect(rbTree.root.key).toBe(25);
  expect(rbTree.root.left.key).toBe(10);
  expect(rbTree.root.left.left.key).toBe(9);
  expect(rbTree.root.left.right.key).toBe(24);
  expect(rbTree.root.left.right.left.key).toBe(23);

  expect(rbTree.root.right.key).toBe(27);
  expect(rbTree.root.right.left.key).toBe(26);
  expect(rbTree.root.right.right.key).toBe(28);
  expect(rbTree.root.right.right.right.key).toBe(29);
});

test('rbTree delete() case 1', () => {

  rbTree.insert(30, "abc");
  rbTree.insert(20, "foo");
  rbTree.insert(40, "bar");
  rbTree.insert(31, "bar");
  rbTree.insert(50, "bar");
  rbTree.insert(32, "bar");

  rbTree.remove(40);

  expect(rbTree.root.key).toBe(30);
  expect(rbTree.root.left.key).toBe(20);
  expect(rbTree.root.right.key).toBe(32);
  expect(rbTree.root.right.left.key).toBe(31);
  expect(rbTree.root.right.right.key).toBe(50);
});

test('rbTree findNode() by key ', () => {

  rbTree.insert(30, "abc");
  rbTree.insert(20, "foo");
  rbTree.insert(40, "bar");
  rbTree.insert(31, "bar");
  rbTree.insert(50, "bar");
  rbTree.insert(32, "bar");

  expect(rbTree.findNode(40).key).toBe(40);
  expect(rbTree.findNode(30).key).toBe(30);
  expect(rbTree.findNode(20).key).toBe(20);
  expect(rbTree.findNode(100)).toBe(null);
});

test('rbTree delete() non-existing node', () => {
  rbTree.insert(30, "abc");
  rbTree.remove(0);
  expect(rbTree.root.key).toBe(30);
});

test('rbTree delete() simple case', () => {
  rbTree.insert(30, "abc");
  rbTree.remove(30);
  expect(rbTree.root.key).toBe(null);
});

test('rbTree delete() left side simple case ', () => {
  rbTree.insert(30, "abc");
  rbTree.insert(20, "abc");
  rbTree.remove(20);
  expect(rbTree.root.left.key).toBe(null);
  expect(rbTree.root.right.key).toBe(null);
});

test('rbTree delete() right side simple case ', () => {
  rbTree.insert(30, "abc");
  rbTree.insert(40, "abc");
  rbTree.remove(40);
  expect(rbTree.root.left.key).toBe(null);
  expect(rbTree.root.right.key).toBe(null);
});

test('rbTree delete() simple case', () => {

  rbTree.insert(30, "abc");
  rbTree.insert(20, "foo");
  rbTree.insert(40, "bar");
  rbTree.insert(10, "bar");
  rbTree.remove(20);

  expect(rbTree.root.key).toBe(30);
  expect(rbTree.root.left.key).toBe(10);
  expect(rbTree.root.right.key).toBe(40);
});

test('rbTree delete() current node u is double black and it is not root', () => {

  rbTree.insert(30, "abc");
  rbTree.insert(20, "foo");
  rbTree.insert(40, "bar");
  rbTree.insert(35, "bar");
  rbTree.insert(50, "bar");

  rbTree.remove(20);
  expect(rbTree.root.key).toBe(40);
  expect(rbTree.root.left.key).toBe(30);
  expect(rbTree.root.right.key).toBe(50);
  expect(rbTree.root.left.right.key).toBe(35);
});

test('rbTree delete() another case', () => {

  rbTree.insert(6, "abc");
  rbTree.insert(4, "foo");
  rbTree.insert(7, "bar");
  rbTree.insert(2, "bar");
  rbTree.insert(5, "bar");

  rbTree.remove(7);
  rbTree.print();

});

// test('rbTree delete() case 1 left', () => {
//
//   rbTree.insert(30, "abc");
//   rbTree.insert(20, "foo");
//   rbTree.insert(40, "bar");
//   rbTree.insert(17, "bar");
//   rbTree.insert(26, "bar");
//   rbTree.insert(18, "bar");
//
//   rbTree.remove(40);
//
//   rbTree.print();
//
// });

// test('rbTree delete() case', () => {
//
//   rbTree.insert(10, "abc");
//   rbTree.insert(9, "foo");
//   rbTree.insert(27, "bar");
//   rbTree.insert(25, "bar");
//   rbTree.insert(28, "bar");
//   rbTree.insert(29, "bar");
//   rbTree.insert(24, "bar");
//   rbTree.insert(26, "bar");
//   rbTree.insert(23, "bar");
//
//   rbTree.remove(25);
//   rbTree.print();
// });

// test('rbTree delete() more case', () => {
//
//   rbTree.insert(12, "abc");
//   rbTree.insert(7, "foo");
//   rbTree.insert(1, "bar");
//   rbTree.insert(0, "bar");
//   rbTree.insert(2, "bar");
//   rbTree.insert(3, "bar");
//   rbTree.insert(4, "bar");
//   rbTree.insert(5, "bar");
//   rbTree.insert(6, "bar");
//   rbTree.insert(11, "bar");
//   rbTree.insert(10, "bar");
//   rbTree.insert(9, "bar");
//   rbTree.insert(8, "bar");
//
//   rbTree.remove(12);
//   rbTree.remove(7);
//   rbTree.remove(1);
//   rbTree.remove(0);
//   rbTree.remove(2);
//   rbTree.remove(3);
//   rbTree.remove(8);
//   rbTree.remove(11);
//
//   rbTree.print();
//
// });
<|endoftext|>


<commit_before>/*!
 * qwebs
 * Copyright(c) 2016 Benoît Claveau
 * MIT Licensed
 */
"use strict";

const http = require("http");
const Qwebs = require("../lib/qwebs");
const Router = require('../lib/router');
const Injector = require("../lib/injector");

describe("router", () => {

    let init = () => {
        return Promise.resolve().then(() => {
            let injector = new Injector();
            let mockQwebs = {
                root: __dirname,
                loaded: true,
                injector: injector,
                resolve: name => {
                    return injector.resolve(name);
                }
            };

            let router = new Router(mockQwebs);

            injector.inject("$qwebs", mockQwebs);
            injector.inject("$injector", injector);

            return {
                router: router,
                injector: injector,
                request: {
                    url: "/",
                    method: "GET"
                },
                response: {
                }
            };
        });
    };

    it("single route", done => {
        let server = null;
        return Promise.resolve().then(() => {
            let $qwebs = new Qwebs({ dirname: __dirname, config: {}});

            $qwebs.inject("$info", "./services/info");
            $qwebs.get("/get", "$info", "getInfo");

            return $qwebs.load().then(() => {
                let promise = new Promise((resolve, reject) => {
                    server = http.createServer((request, response) => {
                        return $qwebs.invoke(request, response).then(res => {
                            resolve();
                        }).catch(error => {
                            reject(error);
                        });
                    }).listen(1337);
                });

                let $client = $qwebs.resolve("$client");
                let request = $client.get({ url: "http://localhost:1337/get" }).then(res => {
                    expect(res.body.whoiam).toBe("I'm Info service.");
                });
                return Promise.all([promise, request]);
            });
        }).catch(error => {
            expect(error.stack + JSON.stringify(error.data)).toBeNull();
        }).then(() => {
            if (server) server.close();
            done();
        });
    });

    it("route *", done => {
        let server = null;
        return Promise.resolve().then(() => {
            let $qwebs = new Qwebs({ dirname: __dirname, config: {}});

            $qwebs.inject("$info", "./services/info");
            $qwebs.get("/*", "$info", "getInfo");

            return $qwebs.load().then(() => {
                let promise = new Promise((resolve, reject) => {
                    server = http.createServer((request, response) => {
                        return $qwebs.invoke(request, response).then(res => {
                            resolve();
                        }).catch(error => {
                            reject(error);
                        });
                    }).listen(1337);
                });

                let $client = $qwebs.resolve("$client");
                let request = $client.get({ url: "http://localhost:1337/info" }).then(res => {
                    expect(res.body.whoiam).toBe("I'm Info service.");
                });
                return Promise.all([promise, request]);
            });
        }).catch(error => {
            expect(error.stack + JSON.stringify(error.data)).toBeNull();
        }).then(() => {
            if (server) server.close();
            done();
        });
    });

    it("multiple", done => {
        let server = null;
        return Promise.resolve().then(() => {
            let $qwebs = new Qwebs({ dirname: __dirname, config: {}});

            $qwebs.inject("$info", "./services/info");
            $qwebs.get("/info", "$info", "getInfo");
            $qwebs.get("/*", "$info", "getMessages");

            return $qwebs.load().then(() => {
                let promise = new Promise((resolve, reject) => {
                    server = http.createServer((request, response) => {
                        return $qwebs.invoke(request, response).then(res => {
                            resolve();
                        }).catch(error => {
                            reject(error);
                        });
                    }).listen(1337);
                });

                let $client = $qwebs.resolve("$client");
                let request = $client.get({ url: "http://localhost:1337/info" }).then(res => {
                    expect(res.body.whoiam).toBe("I'm Info service.");
                });
                return Promise.all([promise, request]);
            });
        }).catch(error => {
            expect(error.stack + JSON.stringify(error.data)).toBeNull();
        }).then(() => {
            if (server) server.close();
            done();
        });
    });

    it("multiple invert declaration", done => {
        let server = null;
        return Promise.resolve().then(() => {
            let $qwebs = new Qwebs({ dirname: __dirname, config: {}});

            $qwebs.inject("$info", "./services/info");
            $qwebs.get("/*", "$info", "getMessages");
            $qwebs.get("/info", "$info", "getInfo");

            return $qwebs.load().then(() => {
                let promise = new Promise((resolve, reject) => {
                    server = http.createServer((request, response) => {
                        return $qwebs.invoke(request, response).then(res => {
                            resolve();
                        }).catch(error => {
                            reject(error);
                        });
                    }).listen(1337);
                });

                let $client = $qwebs.resolve("$client");
                let request = $client.get({ url: "http://localhost:1337/info" }).then(res => {
                    expect(res.body.whoiam).toBe("I'm Info service.");
                });
                return Promise.all([promise, request]);
            });
        }).catch(error => {
            expect(error.stack + JSON.stringify(error.data)).toBeNull();
        }).then(() => {
            if (server) server.close();
            done();
        });
    });

    it("multiple redirection", done => {
        return init().then(mock => {
            mock.injector.inject("$info", "./services/info.js");

            let item = mock.router.get("/*");
            item.register("$info", "whoiam");
            item.load(mock.injector.resolve("$qwebs"));

            item = mock.router.get("/info");
            item.register("$info", "getInfo");
            item.load(mock.injector.resolve("$qwebs"));

            mock.request.url = "/info";

            return mock.router.invoke(mock.request, mock.response, "/test").then(res => {
                expect(res).toBe("I'm Info service.");
            });

        }).catch(error => {
            expect(error.stack).toBeNull();
        }).then(() => {
            done();
        });
    });

    it("multiple token", done => {
        return init().then(mock => {
            mock.injector.inject("$info", "./services/info.js");

            let item = mock.router.get("/*");
            item.register("$info", "getMessages");
            item.load(mock.injector.resolve("$qwebs"));

            item = mock.router.get("/*/*");
            item.register("$info", "whoiam");
            item.load(mock.injector.resolve("$qwebs"));

            mock.request.url = "/test/3";

            return mock.router.invoke(mock.request, mock.response).then(res => {
                expect(res).toBe("I'm Info service.");
            });

        }).catch(error => {
            expect(error.stack).toBeNull();
        }).then(() => {
            done();
        });
    });

    it("multiple end route", done => {
        return init().then(mock => {
            mock.injector.inject("$info", "./services/info.js");

            let item = mock.router.get("/info");
            item.register("$info", "getMessages");

            item = mock.router.get("/info");
            item.register("$info", "getInfo");

            fail();
        }).catch(error => {
            expect(error.message).toEqual("Multiple end route.");
        }).then(() => {
            done();
        });
    });

    it("option", done => {
        return init().then(mock => {
            mock.injector.inject("$info", "./services/info.js");

            let item = mock.router.get("/*");
            item.register("$info", "getMessages");
            item.load(mock.injector.resolve("$qwebs"));

            mock.request.url = "/";
            mock.request.method = "OPTIONS";
            mock.response.send = function(options) {
                return options;
            }

            return mock.router.invoke(mock.request, mock.response).then(res => {
                console.log(res);
                expect(res).toBe("I'm Info service.");
            });
        }).catch(error => {
            expect(error.stack).toBeNull();
        }).then(() => {
            done();
        });
    });
});
<commit_msg>Update router.spec.js<commit_after>/*!
 * qwebs
 * Copyright(c) 2016 Benoît Claveau
 * MIT Licensed
 */
"use strict";

const http = require("http");
const Qwebs = require("../lib/qwebs");
const Router = require('../lib/router');
const Injector = require("../lib/injector");

describe("router", () => {

    let init = () => {
        return Promise.resolve().then(() => {
            let injector = new Injector();
            let mockQwebs = {
                root: __dirname,
                loaded: true,
                injector: injector,
                resolve: name => {
                    return injector.resolve(name);
                }
            };

            let router = new Router(mockQwebs);

            injector.inject("$qwebs", mockQwebs);
            injector.inject("$injector", injector);

            return {
                router: router,
                injector: injector,
                request: {
                    url: "/",
                    method: "GET"
                },
                response: {
                }
            };
        });
    };

    it("single route", done => {
        let server = null;
        return Promise.resolve().then(() => {
            let $qwebs = new Qwebs({ dirname: __dirname, config: {}});

            $qwebs.inject("$info", "./services/info");
            $qwebs.get("/get", "$info", "getInfo");

            return $qwebs.load().then(() => {
                let promise = new Promise((resolve, reject) => {
                    server = http.createServer((request, response) => {
                        return $qwebs.invoke(request, response).then(res => {
                            resolve();
                        }).catch(error => {
                            reject(error);
                        });
                    }).listen(1337);
                });

                let $client = $qwebs.resolve("$client");
                let request = $client.get({ url: "http://localhost:1337/get" }).then(res => {
                    expect(res.body.whoiam).toBe("I'm Info service.");
                });
                return Promise.all([promise, request]);
            });
        }).catch(error => {
            expect(error.stack + JSON.stringify(error.data)).toBeNull();
        }).then(() => {
            if (server) server.close();
            done();
        });
    });

    it("route *", done => {
        let server = null;
        return Promise.resolve().then(() => {
            let $qwebs = new Qwebs({ dirname: __dirname, config: {}});

            $qwebs.inject("$info", "./services/info");
            $qwebs.get("/*", "$info", "getInfo");

            return $qwebs.load().then(() => {
                let promise = new Promise((resolve, reject) => {
                    server = http.createServer((request, response) => {
                        return $qwebs.invoke(request, response).then(res => {
                            resolve();
                        }).catch(error => {
                            reject(error);
                        });
                    }).listen(1337);
                });

                let $client = $qwebs.resolve("$client");
                let request = $client.get({ url: "http://localhost:1337/info" }).then(res => {
                    expect(res.body.whoiam).toBe("I'm Info service.");
                });
                return Promise.all([promise, request]);
            });
        }).catch(error => {
            expect(error.stack + JSON.stringify(error.data)).toBeNull();
        }).then(() => {
            if (server) server.close();
            done();
        });
    });

    it("multiple", done => {
        let server = null;
        return Promise.resolve().then(() => {
            let $qwebs = new Qwebs({ dirname: __dirname, config: {}});

            $qwebs.inject("$info", "./services/info");
            $qwebs.get("/info", "$info", "getInfo");
            $qwebs.get("/*", "$info", "getMessages");

            return $qwebs.load().then(() => {
                let promise = new Promise((resolve, reject) => {
                    server = http.createServer((request, response) => {
                        return $qwebs.invoke(request, response).then(res => {
                            resolve();
                        }).catch(error => {
                            reject(error);
                        });
                    }).listen(1337);
                });

                let $client = $qwebs.resolve("$client");
                let request = $client.get({ url: "http://localhost:1337/info" }).then(res => {
                    expect(res.body.whoiam).toBe("I'm Info service.");
                });
                return Promise.all([promise, request]);
            });
        }).catch(error => {
            expect(error.stack + JSON.stringify(error.data)).toBeNull();
        }).then(() => {
            if (server) server.close();
            done();
        });
    });

    it("multiple invert declaration", done => {
        let server = null;
        return Promise.resolve().then(() => {
            let $qwebs = new Qwebs({ dirname: __dirname, config: {}});

            $qwebs.inject("$info", "./services/info");
            $qwebs.get("/*", "$info", "getMessages");
            $qwebs.get("/info", "$info", "getInfo");

            return $qwebs.load().then(() => {
                let promise = new Promise((resolve, reject) => {
                    server = http.createServer((request, response) => {
                        return $qwebs.invoke(request, response).then(res => {
                            resolve();
                        }).catch(error => {
                            reject(error);
                        });
                    }).listen(1337);
                });

                let $client = $qwebs.resolve("$client");
                let request = $client.get({ url: "http://localhost:1337/info" }).then(res => {
                    expect(res.body.whoiam).toBe("I'm Info service.");
                });
                return Promise.all([promise, request]);
            });
        }).catch(error => {
            expect(error.stack + JSON.stringify(error.data)).toBeNull();
        }).then(() => {
            if (server) server.close();
            done();
        });
    });

    it("multiple redirection", done => {
        return init().then(mock => {
            mock.injector.inject("$info", "./services/info.js");

            let item = mock.router.get("/*");
            item.register("$info", "whoiam");
            item.load(mock.injector.resolve("$qwebs"));

            item = mock.router.get("/info");
            item.register("$info", "getInfo");
            item.load(mock.injector.resolve("$qwebs"));

            mock.request.url = "/info";

            return mock.router.invoke(mock.request, mock.response, "/test").then(res => {
                expect(res).toBe("I'm Info service.");
            });

        }).catch(error => {
            expect(error.stack).toBeNull();
        }).then(() => {
            done();
        });
    });

    it("multiple token", done => {
        return init().then(mock => {
            mock.injector.inject("$info", "./services/info.js");

            let item = mock.router.get("/*");
            item.register("$info", "getMessages");
            item.load(mock.injector.resolve("$qwebs"));

            item = mock.router.get("/*/*");
            item.register("$info", "whoiam");
            item.load(mock.injector.resolve("$qwebs"));

            mock.request.url = "/test/3";

            return mock.router.invoke(mock.request, mock.response).then(res => {
                expect(res).toBe("I'm Info service.");
            });

        }).catch(error => {
            expect(error.stack).toBeNull();
        }).then(() => {
            done();
        });
    });

    it("multiple end route", done => {
        return init().then(mock => {
            mock.injector.inject("$info", "./services/info.js");

            let item = mock.router.get("/info");
            item.register("$info", "getMessages");

            item = mock.router.get("/info");
            item.register("$info", "getInfo");

            fail();
        }).catch(error => {
            expect(error.message).toEqual("Multiple end route.");
        }).then(() => {
            done();
        });
    });

    it("option", done => {
        return init().then(mock => {
            mock.injector.inject("$info", "./services/info.js");

            let item = mock.router.get("/*");
            item.register("$info", "getMessages");
            item.load(mock.injector.resolve("$qwebs"));

            mock.request.url = "/";
            mock.request.method = "OPTIONS";
            mock.response.send = function(options) {
                return options;
            }

            return mock.router.invoke(mock.request, mock.response).then(res => {
                expect(res.statusCode).toBe(200);
                expect(res.header.Allow).toBe("GET");
            });
        }).catch(error => {
            expect(error.stack).toBeNull();
        }).then(() => {
            done();
        });
    });
});
<|endoftext|>


<commit_before>/*global HTMLElement: true */

"use strict";

const _ = require("lodash");
const floorc = require("../common/floorc");
const message_action = require("../common/message_action");
const Pane = require("../../templates/pane");

const Proto = Object.create(HTMLElement.prototype);

Proto.createdCallback = function () {
  const frame = document.createElement("iframe");
  frame.allowtransparency = "on";
  frame.id = "asdfifiafjfj";
  frame.style.border = "0 none";
  frame.style.width = "100%";
  frame.style.height = "100%";
  this.frame = frame;
};

Proto.load = function (host) {
  this.host = host;
  this.frame.src = "https://" + host + "/signup/atom?next=/dash/settings/atom/complete";
  this.pane = new Pane("Floobits", "", this);
  atom.workspace.getActivePane().activateItem(this.pane);
};

Proto.handle_login = function (auth) {
  const host = _.keys(auth)[0];
  auth = auth[host];

  if (!_.has(floorc, "auth")) {
    floorc.auth = {};
  }

  if (!_.has(floorc.auth, host)) {
    floorc.auth[host] = {};
  }
  const floorc_auth = floorc.auth[host];
  const username = auth.username;
  if (floorc_auth.username && floorc_auth.username !== username) {
    console.error("username changed?", auth.username, username);
  }
  floorc_auth.username = username;
  floorc_auth.api_key = auth.api_key;
  floorc_auth.secret = auth.secret;
  try {
    floorc.__write();
  } catch (e) {
    return message_action.error(e);
  }
};

Proto.attachedCallback = function () {
  this.appendChild(this.frame);
  const that = this;
  window.addEventListener("message", function (e) {
    console.log("message2", e.origin, e.data);
    const data = JSON.parse(e.data);
    if (!data.auth) {
      return;
    }
    return that.handle_login(data.auth);
  });
};

Proto.detachedCallback = function () {
  this.destroy();
};

Proto.destroy = function () {
  if (!this.pane) {
    return;
  }
  try {
    this.pane.destroy();
  } catch (e) {
    console.warn(e);
  }
  this.pane = null;
};

module.exports = document.registerElement("floobits-welcome_web_view", {prototype: Proto});
<commit_msg>fixes #48<commit_after>/*global HTMLElement: true */

"use strict";

const _ = require("lodash");
const floorc = require("../common/floorc");
const message_action = require("../common/message_action");
const Pane = require("../../templates/pane");

const Proto = Object.create(HTMLElement.prototype);

Proto.createdCallback = function () {
  const frame = document.createElement("iframe");
  frame.allowtransparency = "on";
  frame.id = "asdfifiafjfj";
  frame.style.border = "0 none";
  frame.style.width = "100%";
  frame.style.height = "100%";
  frame.className = "native-key-bindings";
  this.frame = frame;
};

Proto.load = function (host) {
  this.host = host;
  this.frame.src = "https://" + host + "/signup/atom?next=/dash/settings/atom/complete";
  this.pane = new Pane("Floobits", "", this);
  atom.workspace.getActivePane().activateItem(this.pane);
};

Proto.handle_login = function (auth) {
  const host = _.keys(auth)[0];
  auth = auth[host];

  if (!_.has(floorc, "auth")) {
    floorc.auth = {};
  }

  if (!_.has(floorc.auth, host)) {
    floorc.auth[host] = {};
  }
  const floorc_auth = floorc.auth[host];
  const username = auth.username;
  if (floorc_auth.username && floorc_auth.username !== username) {
    console.error("username changed?", auth.username, username);
  }
  floorc_auth.username = username;
  floorc_auth.api_key = auth.api_key;
  floorc_auth.secret = auth.secret;
  try {
    floorc.__write();
  } catch (e) {
    return message_action.error(e);
  }
};

Proto.attachedCallback = function () {
  this.appendChild(this.frame);
  const that = this;
  window.addEventListener("message", function (e) {
    console.log("message2", e.origin, e.data);
    const data = JSON.parse(e.data);
    if (!data.auth) {
      return;
    }
    return that.handle_login(data.auth);
  });
};

Proto.detachedCallback = function () {
  this.destroy();
};

Proto.destroy = function () {
  if (!this.pane) {
    return;
  }
  try {
    this.pane.destroy();
  } catch (e) {
    console.warn(e);
  }
  this.pane = null;
};

module.exports = document.registerElement("floobits-welcome_web_view", {prototype: Proto});
<|endoftext|>


<commit_before>function ModalWindow(content, movable) {
    var context = this;

    this.locked = false;

    // these are the cursor's coordinates of
    // last drag n drop

    this.cursorX = 0;
    this.cursorY = 0;

    this.movable = (movable === undefined) ? false : movable;

    // some of working with DOM has been put into
    // closures to separate different logic

    this.overlay = (function () {
        var overlay = document.createElement('div');

        overlay.className = 'modal-overlay';

        overlay.addEventListener('click', function () {
            context.close();
        });

        return overlay;
    })();

    this.content = (function () {
        var content = document.createElement('div');

        content.className = 'modal-content';

        return content;
    })();

    this.window = (function () {
        var window = document.createElement('div');

        window.className = 'modal-window';

        var tempHandler = null;

        window.addEventListener('mousedown', function (e) {
            if (!context.movable) {
                return false;
            }

            window.classList.add('modal-moving');

            var offsetX = e.clientX - window.offsetLeft;
            var offsetY = e.clientY - window.offsetTop;

            tempHandler = function (e) {
                window.style.left = e.clientX - offsetX + 'px';
                window.style.top = e.clientY - offsetY + 'px';
            };

            document.addEventListener('mousemove', tempHandler);
        });

        window.addEventListener('mouseup', function (e) {
            if (!context.movable) {
                return false;
            }

            window.classList.remove('modal-moving');

            context.cursorX = e.clientX;
            context.cursorY = e.clientY;

            document.removeEventListener('mousemove', tempHandler);
        });

        window.appendChild(context.content);

        return window;
    })();

    // it contains all the elements of a ModalWindow
    this.layout = (function () {
        var layout = document.createElement('div');

        layout.appendChild(context.overlay);

        layout.appendChild(context.window);

        return layout;
    })();

    document.body.appendChild(this.layout);

    this.setContent(content, true);

    window.addEventListener('resize', function () {
        if (!context.movable) {
            context.centralize();
        }
    });
}

ModalWindow.prototype.show = function () {
    this.layout.style.display = 'block';

    this.centralize();

    return this;
};

ModalWindow.prototype.hide = function () {
    this.layout.style.display = 'none';

    return this;
};

ModalWindow.prototype.lock = function () {
    this.locked = true;

    return this;
};

ModalWindow.prototype.unlock = function () {
    this.locked = false;

    return this;
};

ModalWindow.prototype.allowMoving = function () {
    this.movable = true;
};

ModalWindow.prototype.denyMoving = function () {
    this.movable = false;
};

ModalWindow.prototype.close = function () {
    if (!this.locked) {
        this.layout.parentNode.removeChild(this.layout);

        this.onCloseCallback();
    }
};

ModalWindow.prototype.centralize = function () {
    var left = (document.documentElement.clientWidth - this.window.offsetWidth) / 2;

    var top = (document.documentElement.clientHeight - this.window.offsetHeight) / 2;

    this.window.style.left = left + 'px';

    this.window.style.top = top + 'px';
};

ModalWindow.prototype.setContent = function (content, centralizeMovable, keepMovablesRation) {
    if (centralizeMovable === undefined) {
        centralizeMovable = false;
    }

    if (keepMovablesRation === undefined) {
        keepMovablesRation = true;
    }

    // we don't centralize a movable window until it's been asked
    if (!this.movable || this.movable && centralizeMovable) {
        this.content.innerHTML = content;

        // we unset the width to get actual content's
        // width, not the one we've set before
        this.window.style.width = '';

        this.window.style.width = this.window.clientWidth + 'px';

        this.centralize();
    } else {
        if (keepMovablesRation) {
            // here, we determine what percent of the window's is
            // in the left and in the top of the cursor to keep that
            // ratio when setting new content

            var percentInLeft = (this.cursorX - this.window.offsetLeft) / this.window.clientWidth * 100;

            var percentInTop = (this.cursorY - this.window.offsetTop) / this.window.clientHeight * 100;

            this.content.innerHTML = content;

            this.window.style.left = (this.cursorX - this.window.clientWidth / 100 * percentInLeft) + 'px';

            this.window.style.top = (this.cursorY - this.window.clientHeight / 100 * percentInTop) + 'px';
        } else {
            // similarly, we keep the ration until it's been asked to not
            this.content.innerHTML = content;
        }

        this.window.style.width = '';

        this.window.style.width = this.window.clientWidth + 'px';
    }
};

ModalWindow.prototype.onCloseCallback = function () {
};

// here is the interface of setting onClose callbacks
ModalWindow.prototype.onClose = function (callback) {
    this.onCloseCallback = callback;
};<commit_msg>Fixes #7<commit_after>function ModalWindow(content, movable) {
    var context = this;

    this.locked = false;

    // these are the cursor's coordinates of
    // last drag n drop

    this.cursorX = 0;
    this.cursorY = 0;

    this.movable = (movable === undefined) ? false : movable;

    // some of working with DOM has been put into
    // closures to separate different logic

    this.overlay = (function () {
        var overlay = document.createElement('div');

        overlay.className = 'modal-overlay';

        overlay.addEventListener('click', function () {
            context.close();
        });

        return overlay;
    })();

    this.content = (function () {
        var content = document.createElement('div');

        content.className = 'modal-content';

        return content;
    })();

    this.window = (function () {
        var window = document.createElement('div');

        window.className = 'modal-window';

        var tempHandler = null;

        window.addEventListener('mousedown', function (e) {
            if (!context.movable) {
                return false;
            }

            window.classList.add('modal-moving');

            var offsetX = e.clientX - window.offsetLeft;
            var offsetY = e.clientY - window.offsetTop;

            tempHandler = function (e) {
                window.style.left = e.clientX - offsetX + 'px';
                window.style.top = e.clientY - offsetY + 'px';
            };

            document.addEventListener('mousemove', tempHandler);
        });

        window.addEventListener('mouseup', function (e) {
            if (!context.movable) {
                return false;
            }

            window.classList.remove('modal-moving');

            context.cursorX = e.clientX;
            context.cursorY = e.clientY;

            document.removeEventListener('mousemove', tempHandler);
        });

        window.appendChild(context.content);

        return window;
    })();

    // it contains all the elements of a ModalWindow
    this.layout = (function () {
        var layout = document.createElement('div');

        layout.appendChild(context.overlay);

        layout.appendChild(context.window);

        return layout;
    })();

    document.body.appendChild(this.layout);

    this.setContent(content, true);

    window.addEventListener('resize', function () {
        if (!context.movable) {
            context.centralize();
        }
    });
}

ModalWindow.prototype.show = function () {
    this.layout.style.display = 'block';

    this.centralize();

    return this;
};

ModalWindow.prototype.hide = function () {
    this.layout.style.display = 'none';

    return this;
};

ModalWindow.prototype.lock = function () {
    this.locked = true;

    return this;
};

ModalWindow.prototype.unlock = function () {
    this.locked = false;

    return this;
};

ModalWindow.prototype.allowMoving = function () {
    this.movable = true;
};

ModalWindow.prototype.denyMoving = function () {
    this.movable = false;
};

ModalWindow.prototype.close = function () {
    if (!this.locked) {
        this.layout.parentNode.removeChild(this.layout);

        this.onCloseCallback();
    }
};

ModalWindow.prototype.centralize = function () {
    var left = (document.documentElement.clientWidth - this.window.offsetWidth) / 2;

    var top = (document.documentElement.clientHeight - this.window.offsetHeight) / 2;

    this.window.style.left = left + 'px';

    this.window.style.top = top + 'px';
};

ModalWindow.prototype.setContent = function (content, centralizeMovable, keepMovablesRation) {
    if (centralizeMovable === undefined) {
        centralizeMovable = false;
    }

    if (keepMovablesRation === undefined) {
        keepMovablesRation = true;
    }

    // we don't centralize a movable window until it's been asked
    if (!this.movable || this.movable && centralizeMovable) {
        this.content.innerHTML = content;

        // we unset the width to get actual content's
        // width, not the one we've set before
        this.window.style.width = '';

        this.window.style.width = this.window.getBoundingClientRect().width + 'px';

        this.centralize();
    } else {
        if (keepMovablesRation) {
            // here, we determine what percent of the window's is
            // in the left and in the top of the cursor to keep that
            // ratio when setting new content

            var percentInLeft = (this.cursorX - this.window.offsetLeft) / this.window.clientWidth * 100;

            var percentInTop = (this.cursorY - this.window.offsetTop) / this.window.clientHeight * 100;

            this.content.innerHTML = content;

            this.window.style.left = (this.cursorX - this.window.clientWidth / 100 * percentInLeft) + 'px';

            this.window.style.top = (this.cursorY - this.window.clientHeight / 100 * percentInTop) + 'px';
        } else {
            // similarly, we keep the ration until it's been asked to not
            this.content.innerHTML = content;
        }

        this.window.style.width = '';

        this.window.style.width = this.window.getBoundingClientRect().width + 'px';
    }
};

ModalWindow.prototype.onCloseCallback = function () {
};

// here is the interface of setting onClose callbacks
ModalWindow.prototype.onClose = function (callback) {
    this.onCloseCallback = callback;
};<|endoftext|>


<commit_before>var server = require('../server');
var should = require('should');

var request = require('supertest');

describe('Status', function() {
	describe('GET /grid/api/proxy', function() {
		it('responds with an unknown node if the node is polling this without registering first', function(done) {
		  request(server)
			.get('/grid/api/proxy?id=http://10.0.0.1:5554')
			.end(function(err, res) {
				var body = res.body;
				res.body.should.be.an.instanceOf(Object)
				res.body.success.should.be.false
				done();
			});
		});
	});

	describe('GET /grid/api/proxy register', function() {
		var postData = '{"class":"org.openqa.grid.common.RegistrationRequest","capabilities":[{"platform":"WINDOWS","seleniumProtocol":"Selenium","browserName":"iexplore","maxInstances":1,"version":"9"}],"configuration":{"port":5560,"nodeConfig":"config.json","host":"10.0.1.15","cleanUpCycle":10000,"browserTimeout":20000,"hubHost":"10.0.1.6","registerCycle":5000,"debug":"","hub":"http://10.0.1.6:4444/grid/register","log":"test.log","url":"http://10.0.1.15:5560","remoteHost":"http://10.0.1.15:5560","register":true,"proxy":"org.openqa.grid.selenium.proxy.DefaultRemoteProxy","maxSession":1,"role":"node","hubPort":4444}}';

		beforeEach(function(d) {
			request(server)
				.post('/grid/register')
				.send(postData)
				.end(function(err, res) {
					res.statusCode.should.equal(200);
					res.text.should.equal("OK - Welcome");
					d();
				});
		});

		it('responds with an ok if the node polling has been registered before', function(done) {
		  	request(server)
				.get('/grid/api/proxy?id=http://10.0.1.15:5560')
				.end(function(err, res) {
					var body = res.body;
					res.body.should.be.an.instanceOf(Object)
					res.body.success.should.be.true
					done();
				});
		});
	});

	describe('GET /grid/api/proxy timeout', function() {
		var postData = '{"class":"org.openqa.grid.common.RegistrationRequest","capabilities":[{"platform":"WINDOWS","seleniumProtocol":"Selenium","browserName":"iexplore","maxInstances":1,"version":"9"}],"configuration":{"port":5560,"nodeConfig":"config.json","host":"10.0.1.16","cleanUpCycle":10000,"browserTimeout":20000,"hubHost":"10.0.1.6","registerCycle":5000,"debug":"","hub":"http://10.0.1.6:4444/grid/register","log":"test.log","url":"http://10.0.1.16:5560","remoteHost":"http://10.0.1.16:5560","register":true,"proxy":"org.openqa.grid.selenium.proxy.DefaultRemoteProxy","maxSession":1,"role":"node","hubPort":4444}}';

		beforeEach(function(d) {
			request(server)
				.post('/grid/register')
				.send(postData)
				.end(function(err, res) {
					res.statusCode.should.equal(200);
					res.text.should.equal("OK - Welcome");
					d();
				});
		});

		it('should return a not found response if the node has not responded in the nodeTimeout time', function(done) {
			this.timeout(20000);
			setTimeout(function() {
				request(server)
				.get('/grid/api/proxy?id=http://10.0.1.16:5560')
				.end(function(err, res) {
					var body = res.body;
					res.body.should.be.an.instanceOf(Object)
					res.body.success.should.be.false
					done();
				});
			}, 16000);
		});

		it('should be possible to register the node again after it has failed to respond in nodeTimeout time', function(done) {
			this.timeout(20000);
			setTimeout(function() {
				request(server)
				.get('/grid/api/proxy?id=http://10.0.1.16:5560')
				.end(function(err, res) {
					var body = res.body;
					res.body.should.be.an.instanceOf(Object)
					res.body.success.should.be.false
					request(server)
						.post('/grid/register')
						.send(postData)
						.end(function(err, res) {
							res.statusCode.should.equal(200);
							res.text.should.equal("OK - Welcome");
							done();
						});
				});
			}, 16000);
		});
	});
});
<commit_msg>Make status_test work<commit_after>var server = require('../server'),
    should = require('should'),
    request = require('supertest');

describe('Status', function() {

    var app;
    before(function() {
        app = server();
    });

    after(function() {
        app.close();
    });

	describe('GET /grid/api/proxy', function() {
		it('responds with an unknown node if the node is polling this without registering first', function(done) {
		  request(app)
			.get('/grid/api/proxy?id=http://10.0.0.1:5554')
			.end(function(err, res) {
				res.body.should.be.an.instanceOf(Object);
				res.body.success.should.be.false;
				done();
			});
		});
	});

	describe('GET /grid/api/proxy register', function() {
		var postData = '{"class":"org.openqa.grid.common.RegistrationRequest","capabilities":[{"platform":"WINDOWS","seleniumProtocol":"Selenium","browserName":"iexplore","maxInstances":1,"version":"9"}],"configuration":{"port":5560,"nodeConfig":"config.json","host":"10.0.1.15","cleanUpCycle":10000,"browserTimeout":20000,"hubHost":"10.0.1.6","registerCycle":5000,"debug":"","hub":"http://10.0.1.6:4444/grid/register","log":"test.log","url":"http://10.0.1.15:5560","remoteHost":"http://10.0.1.15:5560","register":true,"proxy":"org.openqa.grid.selenium.proxy.DefaultRemoteProxy","maxSession":1,"role":"node","hubPort":4444}}';

		beforeEach(function(d) {
			request(app)
				.post('/grid/register')
				.send(postData)
				.end(function(err, res) {
					res.statusCode.should.equal(200);
					res.text.should.equal("OK - Welcome");
					d();
				});
		});

		it('responds with an ok if the node polling has been registered before', function(done) {
		  	request(app)
				.get('/grid/api/proxy?id=http://10.0.1.15:5560')
				.end(function(err, res) {
					res.body.should.be.an.instanceOf(Object);
					res.body.success.should.be.true;
					done();
				});
		});
	});

	describe('GET /grid/api/proxy timeout', function() {
		var postData = '{"class":"org.openqa.grid.common.RegistrationRequest","capabilities":[{"platform":"WINDOWS","seleniumProtocol":"Selenium","browserName":"iexplore","maxInstances":1,"version":"9"}],"configuration":{"port":5560,"nodeConfig":"config.json","host":"10.0.1.16","cleanUpCycle":10000,"browserTimeout":20000,"hubHost":"10.0.1.6","registerCycle":5000,"debug":"","hub":"http://10.0.1.6:4444/grid/register","log":"test.log","url":"http://10.0.1.16:5560","remoteHost":"http://10.0.1.16:5560","register":true,"proxy":"org.openqa.grid.selenium.proxy.DefaultRemoteProxy","maxSession":1,"role":"node","hubPort":4444}}';

		beforeEach(function(d) {
			request(app)
				.post('/grid/register')
				.send(postData)
				.end(function(err, res) {
					res.statusCode.should.equal(200);
					res.text.should.equal("OK - Welcome");
					d();
				});
		});

		it('should return a not found response if the node has not responded in the nodeTimeout time', function(done) {
			this.timeout(20000);
			setTimeout(function() {
				request(app)
				.get('/grid/api/proxy?id=http://10.0.1.16:5560')
				.end(function(err, res) {
					res.body.should.be.an.instanceOf(Object);
					res.body.success.should.be.false;
					done();
				});
			}, 16000);
		});

		it('should be possible to register the node again after it has failed to respond in nodeTimeout time', function(done) {
			this.timeout(20000);
			setTimeout(function() {
				request(app)
				.get('/grid/api/proxy?id=http://10.0.1.16:5560')
				.end(function(err, res) {
					res.body.should.be.an.instanceOf(Object);
					res.body.success.should.be.false;
					request(app)
						.post('/grid/register')
						.send(postData)
						.end(function(err, res) {
							res.statusCode.should.equal(200);
							res.text.should.equal("OK - Welcome");
							done();
						});
				});
			}, 16000);
		});
	});
});
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux'
import { Router, Route, browserHistory } from 'react-router'
import { syncHistoryWithStore } from 'react-router-redux'

import HomeContainer from './routes/Home/HomeContainer';
import LoginContainer from './routes/Login/LoginContainer';
import SignUpContainer from './routes/SignUp/SignUpContainer';

import requiresAuth from './shared/components/requiresAuth/requiresAuth'

import configureStore from './store/configureStore'

import './index.css';

const store = configureStore();
const history = syncHistoryWithStore(browserHistory, store)

ReactDOM.render(
  <Provider store={store}>
     <Router history={history}>
      <Route path="/login" component={LoginContainer} />
      <Route path="/signup" component={SignUpContainer} />
      <Route path="/" component={HomeContainer} />
    </Router>
  </Provider>,
  document.getElementById('root')
);<commit_msg>Add authentication to Home route<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux'
import { Router, Route, browserHistory } from 'react-router'
import { syncHistoryWithStore } from 'react-router-redux'

import Home from './routes/Home/HomeContainer';
import Login from './routes/Login/LoginContainer';
import SignUp from './routes/SignUp/SignUpContainer';

import requiresAuth from './shared/components/requiresAuth/requiresAuth'

import configureStore from './store/configureStore'

import './index.css';

const store = configureStore();
const history = syncHistoryWithStore(browserHistory, store)

ReactDOM.render(
  <Provider store={store}>
     <Router history={history}>
      <Route path="/login" component={Login} />
      <Route path="/signup" component={SignUp} />
      <Route path="/" component={requiresAuth(Home)} />
    </Router>
  </Provider>,
  document.getElementById('root')
);<|endoftext|>


<commit_before>var mongoose = require('mongoose');

var voteSchema = new mongoose.Schema({
  type: { type: String, lowercase: true },
  event_id: mongoose.Schema.Types.ObjectId,
  phoneNumber: String
});

var voteModel = mongoose.model('Vote', voteSchema, 'events_votes_collection');

module.exports = eventModel;
<commit_msg>Fixing misspel in vote model.<commit_after>var mongoose = require('mongoose');

var voteSchema = new mongoose.Schema({
  type: { type: String, lowercase: true },
  event_id: mongoose.Schema.Types.ObjectId,
  phoneNumber: String
});

var voteModel = mongoose.model('Vote', voteSchema, 'events_votes_collection');

module.exports = voteModel;
<|endoftext|>


<commit_before>import Ember from 'ember';
import resolver from './helpers/resolver';
import QUnit from 'qunit';
import {
  setResolver
} from 'ember-qunit';
import { start } from 'ember-cli-qunit';

setResolver(resolver);
start();

const TESTS_WITH_LEAKY_ASYNC = [];
const { run } = Ember;

QUnit.testDone(({ module, name }) => {
  if (run.hasScheduledTimers()) {
    TESTS_WITH_LEAKY_ASYNC.push(`${module}: ${name}`);
    run.cancelTimers();
  }
});

QUnit.done(() => {
  if (TESTS_WITH_LEAKY_ASYNC.length > 0) {
    throw new Error(`*****ASYNC LEAKAGE DETECTED!!!!***** The following (${TESTS_WITH_LEAKY_ASYNC.length}) tests setup a timer that was never torn down: \n${TESTS_WITH_LEAKY_ASYNC.join('\n')}`);
  }
});
<commit_msg>Fixing issue with broken CI - force setting Ember.testing<commit_after>import Ember from 'ember';
import resolver from './helpers/resolver';
import QUnit from 'qunit';
import {
  setResolver
} from 'ember-qunit';
import { start } from 'ember-cli-qunit';

setResolver(resolver);
start();

const TESTS_WITH_LEAKY_ASYNC = [];
const { run } = Ember;

QUnit.testStart(() => {
  Ember.testing = true;
});

QUnit.testDone(({ module, name }) => {
  if (run.hasScheduledTimers()) {
    TESTS_WITH_LEAKY_ASYNC.push(`${module}: ${name}`);
    run.cancelTimers();
  }

  Ember.testing = false;
});

QUnit.done(() => {
  if (TESTS_WITH_LEAKY_ASYNC.length > 0) {
    throw new Error(`*****ASYNC LEAKAGE DETECTED!!!!***** The following (${TESTS_WITH_LEAKY_ASYNC.length}) tests setup a timer that was never torn down: \n${TESTS_WITH_LEAKY_ASYNC.join('\n')}`);
  }
});
<|endoftext|>


<commit_before>import Ember from 'ember';
import QUnit from 'qunit';
import Application from '../app';
import config from '../config/environment';
import { setApplication } from '@ember/test-helpers';
import { start } from 'ember-cli-qunit';

setApplication(Application.create(config.APP));
start();

const TESTS_WITH_LEAKY_ASYNC = [];
const { run } = Ember;

QUnit.testStart(() => {
  performance.mark('test-start');
  Ember.testing = true;
});

QUnit.testDone(({ module, name }) => {
  performance.mark('test-end');
  if (run.hasScheduledTimers()) {
    TESTS_WITH_LEAKY_ASYNC.push(`${module}: ${name}`);
    run.cancelTimers();
  }

  performance.measure('test', 'test-start', 'test-end');

  Ember.testing = false;
});

QUnit.done(() => {
  if (TESTS_WITH_LEAKY_ASYNC.length > 0) {
    throw new Error(
      `*****ASYNC LEAKAGE DETECTED!!!!***** The following (${
        TESTS_WITH_LEAKY_ASYNC.length
      }) tests setup a timer that was never torn down: \n${TESTS_WITH_LEAKY_ASYNC.join(
        '\n'
      )}`
    );
  }
});
<commit_msg>Removing performance.mark<commit_after>import Ember from 'ember';
import QUnit from 'qunit';
import Application from '../app';
import config from '../config/environment';
import { setApplication } from '@ember/test-helpers';
import { start } from 'ember-cli-qunit';

setApplication(Application.create(config.APP));
start();

const TESTS_WITH_LEAKY_ASYNC = [];
const { run } = Ember;

QUnit.testStart(() => {
  Ember.testing = true;
});

QUnit.testDone(({ module, name }) => {
  if (run.hasScheduledTimers()) {
    TESTS_WITH_LEAKY_ASYNC.push(`${module}: ${name}`);
    run.cancelTimers();
  }

  Ember.testing = false;
});

QUnit.done(() => {
  if (TESTS_WITH_LEAKY_ASYNC.length > 0) {
    throw new Error(
      `*****ASYNC LEAKAGE DETECTED!!!!***** The following (${
        TESTS_WITH_LEAKY_ASYNC.length
      }) tests setup a timer that was never torn down: \n${TESTS_WITH_LEAKY_ASYNC.join(
        '\n'
      )}`
    );
  }
});
<|endoftext|>


<commit_before>'use strict'

module.exports = function (sequelize, DataTypes) {
  const File = sequelize.define('File', {
    id: { type: DataTypes.STRING, primaryKey: true },
    caption: { type: DataTypes.JSON, defaultValue: '{"en":""}'},
    mime: { type: DataTypes.STRING },
    filename: { type: DataTypes.STRING }
  }, {
    paranoid: true,
    underscored: true,
    tableName: 'file',
    instanceMethods: {
      setCaption (text, lang) {
        this.caption[lang] = text
      },
      getCaption (lang) {
        return this.caption[lang]
      },
      toJSON () {
        return this.get({ plain: true })
      }
    }
  })

  return File
}
<commit_msg>Add features<commit_after>'use strict'

module.exports = function (sequelize, DataTypes) {
  const File = sequelize.define('File', {
    id: { type: DataTypes.STRING, primaryKey: true },
    caption: { type: DataTypes.JSON, defaultValue: '{"en":""}'},
    mimetype: { type: DataTypes.STRING, defaultValue: 'application/octet-stream'},
    filename: { type: DataTypes.STRING }
  }, {
    paranoid: true,
    underscored: true,
    tableName: 'file',
    instanceMethods: {
      setCaption (text, lang) {
        this.caption[lang] = text
      },
      getCaption (lang) {
        return this.caption[lang]
      },
      toJSON () {
        return this.get({ plain: true })
      }
    }
  })

  return File
}
<|endoftext|>


<commit_before>import {BIGINT, STRING} from 'sequelize';
import sequelize from './';
import Status from './status';
import Photo from './photo';

const User = sequelize.define('user', {
  id: {type: BIGINT, primaryKey: true},
  username: {type: STRING},
  thumbnail: {type: STRING},
  token: {type: STRING},
  tokenSecret: {type: STRING},
});

User.hasMany(Status, {as: 'statuses'});

User.prototype.saveStatus = async function (list, obj) {
  const status = await Status.create({
    userId: this.id,
    list: list,
    idStr: obj.idStr,
    text: obj.text,
    url: obj.url,
    datetime: obj.datetime,
    uploaderId: obj.user.id,
    uploaderName: obj.user.name,
    uploaderScreenName: obj.user.screenName,
    uploaderProfileImage: obj.user.profileImage
  });

  return Promise.all(obj.photos.map(photo => Photo.save(status, photo)));
};

User.prototype.listArchives = async function () {
  const raw = await Status.aggregate('list', 'DISTINCT', {
    plain: false,
    where: { userId: this.id },
  });
  return raw.map(obj => obj.DISTINCT);
};

User.prototype.listStatuses = async function (list, to) {
  const where = { userId: this.id, list: list };

  if (to) {
    where.id = { $lt: to };
  }

  const statuses = await Status.findAll({
    where,
    include: [{ model: Photo, as: 'photos' }],
    order: 'id DESC',
    limit: 20,
  });

  return statuses.map(status => status.toObj());
};

User.prototype.hasArchived = async function (list, idStr) {
  const status = await Status.findOne({
    where: { userId: this.id, list, idStr }
  });
  return !!status;
};

export default User;
<commit_msg>Fix typo in listStatuses<commit_after>import {BIGINT, STRING} from 'sequelize';
import sequelize from './';
import Status from './status';
import Photo from './photo';

const User = sequelize.define('user', {
  id: {type: BIGINT, primaryKey: true},
  username: {type: STRING},
  thumbnail: {type: STRING},
  token: {type: STRING},
  tokenSecret: {type: STRING},
});

User.hasMany(Status, {as: 'statuses'});

User.prototype.saveStatus = async function (list, obj) {
  const status = await Status.create({
    userId: this.id,
    list: list,
    idStr: obj.idStr,
    text: obj.text,
    url: obj.url,
    datetime: obj.datetime,
    uploaderId: obj.user.id,
    uploaderName: obj.user.name,
    uploaderScreenName: obj.user.screenName,
    uploaderProfileImage: obj.user.profileImage
  });

  return Promise.all(obj.photos.map(photo => Photo.save(status, photo)));
};

User.prototype.listArchives = async function () {
  const raw = await Status.aggregate('list', 'DISTINCT', {
    plain: false,
    where: { userId: this.id },
  });
  return raw.map(obj => obj.DISTINCT);
};

User.prototype.listStatuses = async function (list, to) {
  const where = { userId: this.id, list: list };

  if (to) {
    where.idStr = { $lt: to };
  }

  const statuses = await Status.findAll({
    where,
    include: [{ model: Photo, as: 'photos' }],
    order: 'id DESC',
    limit: 20,
  });

  return statuses.map(status => status.toObj());
};

User.prototype.hasArchived = async function (list, idStr) {
  const status = await Status.findOne({
    where: { userId: this.id, list, idStr }
  });
  return !!status;
};

export default User;
<|endoftext|>


<commit_before>var mongoose = require("mongoose"),
    Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId,

    common = require('./common'),
    utils = require('./../utils'),
    async = require('async'),
    _ = require('underscore');

var MinLengthValidator = function (min) {
    return [function (value) {
        return value && value.length >= min;
    }, 'Name must contain at least ' + min + ' letters'];
};

var RegexValidator = function (regex) {
    return [function (value) {
        return value && regex.exec(value)
    }, 'Value is not at the correct pattern'];
};

var User = module.exports = new Schema({

    //this is for validation
    is_activated: {type: Boolean, 'default': true},
    is_suspended: {type: Boolean, 'default': false},
    identity_provider:{type:String, "enum":['facebook', 'register'], 'default': 'register'},
    facebook_id: {type: String, editable:false},
    access_token: {type: String, editable:false},
    first_name:{type:String, required:true, validate:MinLengthValidator(2)},
    last_name:{type:String, required:false},
    email:{type:String, required:true},//, match:/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/},
    gender:{type:String, "enum":['male', 'female']},
    age:{type:Number, min:0},
    last_visit:{type:Date,'default':Date.now},
    address: String,
    occupation: String,
    biography: String,
    invitation_code: {type: String, editable:false},
    //followers - in the redesign it is the same as discussion.users
    discussions:[
        new Schema({
            discussion_id:{type:ObjectId, ref:'Discussion', limit: 1000},
            join_date: {type:Date, 'default':Date.now},
            get_alert: {type: Boolean, 'default': true},
            time_of_alert: {type:String, "enum":['now', 'today', 'this_week'], 'default': 'now'},
            get_alert_of_comments: {type: Boolean, 'default': true},
            get_alert_of_suggestions: {type: Boolean, 'default': true},
            get_alert_of_approved_suggestions: {type: Boolean, 'default': true}
        })
    ],
// List of subject ref ids, that the user is authorized to view
    subjects:[{type:ObjectId, ref:'Subject',query:common.SUBJECT_QUERY,help:'Add subject that this user is authorized to view'}],

    password: {type: String, editable:false},
    validation_code: {type: String, editable:false},

    updates: {type:Schema.Types.Mixed,editable:false},

    avatar : Schema.Types.File,
    sent_mail: {type:Date,editable:false},
    actions_done_by_user:{
        create_object:false,
        post_on_object:false,
        suggestion_on_object:false,
        grade_object:false,
        vote_on_object:false,
        join_to_object:false
    },
    no_mail_notifications: {type : Boolean, "default": true},
    mail_notification_configuration: {

        // general
        get_mails: {type: Boolean, 'default': true},
        get_uru_updates: {type: Boolean, 'default': true},
        get_weekly_mails: {type: Boolean, 'default': true},

        // by default no subject is selected
        new_discussion: [ new Schema(
           {
               subject_id: {type: ObjectId, ref: 'Subject'},
               get_alert: {type: Boolean}
           }
        )],

        //general discussions
        get_alert_of_comments_for_all_discussions: {type: Boolean, 'default': true},
        get_alert_of_suggestions_for_all_discussions: {type: Boolean, 'default': true},
        get_alert_of_approved_suggestions_for_all_discussions: {type: Boolean, 'default': true}
    }
}, {strict:false});

User.methods.toString = function()
{
    return this.first_name + ' ' + this.last_name;
};

User.methods.avatar_url = function()
{
    if(this.avatar && this.avatar.url)
        return this.avatar.url;
    else
        return this.facebook_id ? 'http://graph.facebook.com/' + this.facebook_id + '/picture/?type=large' : "/images/default_user_img.gif";
};

/**
 * Post-init hook - save a copy of subject list
 */
User.post('init',function(){
    this._lastSubjects = (this.subjects || []).map(function(subject) { return subject + ''; });
});

/**
 * Pre-save hook - check is subject list was changed.
 * If so, collect new subjects and notify user
 */
User.pre('save',function(next){

    var is_new = this.isNew;
    if(!this._lastSubjects && !is_new)
        return next();

    // get new subjects ids
    var newSubjectList = (this.subjects || []).map(function(subject) { return subject + '';});
    var newSubjects = _.difference(newSubjectList,this._lastSubjects || []);
    delete this._lastSubjects;
    // continue
    next();
    if(!newSubjects.length && !is_new)
        return;

    var self = this;
    // get subject objects
    mongoose.model('Subject').find()
        .where('_id').in(newSubjects)
        .exec(function(err,subjects){
            if(err) return console.error('Error getting subjects from DB with ids ' + newSubjects,err);

            if(!subjects.length) return;

            var firstSubjectUrl = '/discussions/subject/' + subjects[0].id;

            if(is_new || !self.is_activated){
                // if the user is new, need to send activation mail

                require('../routes/account/activation').sendActivationMail(self,firstSubjectUrl,'inviteNewUserToSubject',{subjects:subjects},function(err){
                    if(err)
                        console.error('Error sending mail to user ' + self,err);
                });
            }
            else {
                // if the user exists, send only activation mail
                async.waterfall([
                    function(cbk){
                        require('../lib/templates').renderTemplate('inviteUserToSubject',{user:self, next:firstSubjectUrl,subjects:subjects},cbk);
                    },
                    function(string,cbk) {
                        require('../lib/mail').sendMailFromTemplate(self.email, string , cbk);
                    }
                ],function(err){
                    if(err)
                        console.error('Error sending mail to user ' + self,err);
                });
            }
        });
});<commit_msg>after first login redirect to default_login_page<commit_after>var mongoose = require("mongoose"),
    Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId,

    common = require('./common'),
    utils = require('./../utils'),
    async = require('async'),
    _ = require('underscore');

var MinLengthValidator = function (min) {
    return [function (value) {
        return value && value.length >= min;
    }, 'Name must contain at least ' + min + ' letters'];
};

var RegexValidator = function (regex) {
    return [function (value) {
        return value && regex.exec(value)
    }, 'Value is not at the correct pattern'];
};

var User = module.exports = new Schema({

    //this is for validation
    is_activated: {type: Boolean, 'default': true},
    is_suspended: {type: Boolean, 'default': false},
    identity_provider:{type:String, "enum":['facebook', 'register'], 'default': 'register'},
    facebook_id: {type: String, editable:false},
    access_token: {type: String, editable:false},
    first_name:{type:String, required:true, validate:MinLengthValidator(2)},
    last_name:{type:String, required:false},
    email:{type:String, required:true},//, match:/^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/},
    gender:{type:String, "enum":['male', 'female']},
    age:{type:Number, min:0},
    last_visit:{type:Date,'default':Date.now},
    address: String,
    occupation: String,
    biography: String,
    invitation_code: {type: String, editable:false},
    //followers - in the redesign it is the same as discussion.users
    discussions:[
        new Schema({
            discussion_id:{type:ObjectId, ref:'Discussion', limit: 1000},
            join_date: {type:Date, 'default':Date.now},
            get_alert: {type: Boolean, 'default': true},
            time_of_alert: {type:String, "enum":['now', 'today', 'this_week'], 'default': 'now'},
            get_alert_of_comments: {type: Boolean, 'default': true},
            get_alert_of_suggestions: {type: Boolean, 'default': true},
            get_alert_of_approved_suggestions: {type: Boolean, 'default': true}
        })
    ],
// List of subject ref ids, that the user is authorized to view
    subjects:[{type:ObjectId, ref:'Subject',query:common.SUBJECT_QUERY,help:'Add subject that this user is authorized to view'}],

    password: {type: String, editable:false},
    validation_code: {type: String, editable:false},

    updates: {type:Schema.Types.Mixed,editable:false},

    avatar : Schema.Types.File,
    sent_mail: {type:Date,editable:false},
    actions_done_by_user:{
        create_object:false,
        post_on_object:false,
        suggestion_on_object:false,
        grade_object:false,
        vote_on_object:false,
        join_to_object:false
    },
    no_mail_notifications: {type : Boolean, "default": true},
    mail_notification_configuration: {

        // general
        get_mails: {type: Boolean, 'default': true},
        get_uru_updates: {type: Boolean, 'default': true},
        get_weekly_mails: {type: Boolean, 'default': true},

        // by default no subject is selected
        new_discussion: [ new Schema(
           {
               subject_id: {type: ObjectId, ref: 'Subject'},
               get_alert: {type: Boolean}
           }
        )],

        //general discussions
        get_alert_of_comments_for_all_discussions: {type: Boolean, 'default': true},
        get_alert_of_suggestions_for_all_discussions: {type: Boolean, 'default': true},
        get_alert_of_approved_suggestions_for_all_discussions: {type: Boolean, 'default': true}
    }
}, {strict:false});

User.methods.toString = function()
{
    return this.first_name + ' ' + this.last_name;
};

User.methods.avatar_url = function()
{
    if(this.avatar && this.avatar.url)
        return this.avatar.url;
    else
        return this.facebook_id ? 'http://graph.facebook.com/' + this.facebook_id + '/picture/?type=large' : "/images/default_user_img.gif";
};

/**
 * Post-init hook - save a copy of subject list
 */
User.post('init',function(){
    this._lastSubjects = (this.subjects || []).map(function(subject) { return subject + ''; });
});

/**
 * Pre-save hook - check is subject list was changed.
 * If so, collect new subjects and notify user
 */
User.pre('save',function(next){

    var is_new = this.isNew;
    if(!this._lastSubjects && !is_new)
        return next();

    // get new subjects ids
    var newSubjectList = (this.subjects || []).map(function(subject) { return subject + '';});
    var newSubjects = _.difference(newSubjectList,this._lastSubjects || []);
    delete this._lastSubjects;
    // continue
    next();
    if(!newSubjects.length && !is_new)
        return;

    var self = this;
    // get subject objects
    mongoose.model('Subject').find()
        .where('_id').in(newSubjects)
        .exec(function(err,subjects){
            if(err) return console.error('Error getting subjects from DB with ids ' + newSubjects,err);

            if(!subjects.length) return;

            var firstSubjectUrl = '/discussions/subject/' + subjects[0].id;
            var redirect_to = require('../routes/account/common').DEFAULT_LOGIN_REDIRECT;

            if(is_new || !self.is_activated){
                // if the user is new, need to send activation mail

                require('../routes/account/activation').sendActivationMail(self, redirect_to/*firstSubjectUrl*/, 'inviteNewUserToSubject',{subjects:subjects},function(err){
                    if(err)
                        console.error('Error sending mail to user ' + self,err);
                });
            }
            else {
                // if the user exists, send only activation mail
                async.waterfall([
                    function(cbk){
                        require('../lib/templates').renderTemplate('inviteUserToSubject',{user:self, next:firstSubjectUrl,subjects:subjects},cbk);
                    },
                    function(string,cbk) {
                        require('../lib/mail').sendMailFromTemplate(self.email, string , cbk);
                    }
                ],function(err){
                    if(err)
                        console.error('Error sending mail to user ' + self,err);
                });
            }
        });
});<|endoftext|>


<commit_before>'use strict'

const {bookshelf} = require('../db/database')
require('./game')
require('./gameWord')

const Word = bookshelf.Model.extend({
  tableName: 'words',
  // sets relationship with games
  games: function () { return this.belongsToMany('Game').through('GameWord')}
}, {
  // gets all games
  getAllWords: function() {
    return this.forge().orderBy('id', 'ASC').fetchAll()
  }
})

module.exports = bookshelf.model('Word', Word)
<commit_msg>added getSingleWord to word model<commit_after>'use strict'

const {bookshelf} = require('../db/database')
require('./game')
require('./gameWord')

const Word = bookshelf.Model.extend({
  tableName: 'words',
  // sets relationship with games
  games: function () { return this.belongsToMany('Game').through('GameWord')}
}, {
  // gets all games
  getAllWords: function() {
    return this.forge().orderBy('id', 'ASC').fetchAll()
  },

  // gets a single word (used to check if word is already in db)
  getSingleWord: function(correct_word) {
    return this.forge({correct_word})
    .fetch()
    .then( (director) => {
      return director
    })
    .catch( (error) => {
      return error
    })
  }

})

module.exports = bookshelf.model('Word', Word)
<|endoftext|>


<commit_before>function parse_304(data) {
	let gear;

	switch (data.msg[0]) {
		case 0xC2 : gear = 'reverse'; break;
		case 0xC3 : gear = 'reverse'; break;

		case 0xC1 : gear = 'shifting'; break;

		case 0xC7 : gear = 'drive'; break;

		case 0xD1 : gear = 'neutral'; break;

		case 0xE1 : gear = 'park'; break;
		case 0xE3 : gear = 'park'; break;

		default : {
			gear = 'unknown';
		}
	}

	if (config.retrofit.nbt === true) {
		switch (gear) {
			case 'reverse' : {
				// If we're now in reverse, but weren't before,
				// Send message to NBT_HU to switch input to reverse camera
				if (status.egs.gear !== 'reverse') {
					bus.data.send({
						bus  : config.kombi.can_intf,
						id   : 0x6F1,
						data : Buffer.from([ 0x63, 0x21, 0x00, 0x00, 0x04, 0x00, 0x00, 0xFF ]),
					});
				}

				break;
			}

			default : {
				// If we're now NOT reverse, but were before,
				// Send message to NBT_HU to reset input switch
				if (status.egs.gear === 'reverse') {
					bus.data.send({
						bus  : config.kombi.can_intf,
						id   : 0x6F1,
						data : Buffer.from([ 0x63, 0x21, 0x00, 0x00, 0x00, 0x00, 0x01, 0xFF ]),
					});
				}
			}
		}
	}

	update.status('egs.gear', gear);
}

// Parse data sent from module
function parse_out(data) {
	data.command = 'bro';

	switch (data.src.id) {
		case 0x304 : parse_304(data); data.value = 'Transmission gear'; break;

		default : data.value = data.src.id.toString(16);
	}
}

module.exports = {
	parse_out : parse_out,
};
<commit_msg>Update<commit_after>function parse_304(data) {
	let gear;

	switch (data.msg[0]) {
		case 0xC2 : gear = 'reverse'; break;
		case 0xC3 : gear = 'reverse'; break;

		case 0xC1 : gear = 'shifting'; break;

		case 0xC7 : gear = 'drive'; break;

		case 0xD1 : gear = 'neutral'; break;

		case 0xE1 : gear = 'park'; break;
		case 0xE3 : gear = 'park'; break;

		default : {
			gear = 'unknown';
		}
	}

	if (config.retrofit.nbt === true) {
		switch (gear) {
			case 'reverse' : {
				// If we're now in reverse, but weren't before,
				// Send message to NBT_HU to switch input to reverse camera
				if (status.egs.gear !== 'reverse') {
					bus.data.send({
						bus  : config.nbt.can_intf,
						id   : 0x6F1,
						data : Buffer.from([ 0x63, 0x21, 0x00, 0x00, 0x04, 0x00, 0x00, 0xFF ]),
					});
				}

				break;
			}

			default : {
				// If we're now NOT reverse, but were before,
				// Send message to NBT_HU to reset input switch
				if (status.egs.gear === 'reverse') {
					bus.data.send({
						bus  : config.nbt.can_intf,
						id   : 0x6F1,
						data : Buffer.from([ 0x63, 0x21, 0x00, 0x00, 0x00, 0x00, 0x01, 0xFF ]),
					});
				}
			}
		}
	}

	update.status('egs.gear', gear);
}

// Parse data sent from module
function parse_out(data) {
	data.command = 'bro';

	switch (data.src.id) {
		case 0x304 : parse_304(data); data.value = 'Transmission gear'; break;

		default : data.value = data.src.id.toString(16);
	}
}

module.exports = {
	parse_out : parse_out,
};
<|endoftext|>


<commit_before>"use strict";

var express = require('express');
var Project = require('../schemas/project.js');

var app = express();

// Allow CORs
app.all('*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
});

app.get('/projects/:id', function (req, res, next) {
  Project.findById(req.params.id).exec().then(function (project) {
    res.send(project);
  }, next);
});

app.get('/projects', function (req, res, next) {
  // filter by user

  Project.find().exec().then(function (projects) {
    res.send(projects);
  }, next);
});

app.put('/projects/:id', function (req, res, next) {
  Project.findById(req.params.id).exec().then(function (project) {
    project.name = req.body.name;

    project.save().exec().then(function () {
      res.send(project);
    }, next);
  }, next);
});

app.post('/projects', function (req, res, next) {
  var project = new Project({
    name: req.body.name
  });

  project.save().exec().then(function () {
    res.send(project);
  }, next);

  // add project_id to user
});

app.delete('/projects/:id', function (req, res, next) {
  Project.findById(req.params.id).exec().then(function (project) {
    project.remove().exec().then(function () {
      res.send('');
    }, next)
  }, next);

  // remove project_id from user
});

module.exports = app;
<commit_msg>Wrap object in property<commit_after>"use strict";

var express = require('express');
var Project = require('../schemas/project.js');

var app = express();

// Allow CORs
app.all('*', function (req, res, next) {
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Methods', 'PUT, GET, POST, DELETE, OPTIONS');
  res.header('Access-Control-Allow-Headers', 'Content-Type');
  next();
});

app.get('/projects/:id', function (req, res, next) {
  Project.findById(req.params.id).exec().then(function (project) {
    res.send(project);
  }, next);
});

app.get('/projects', function (req, res, next) {
  // filter by user

  Project.find().exec().then(function (projects) {
    res.json({
      "projects": projects
    });
  }, next);
});

app.put('/projects/:id', function (req, res, next) {
  Project.findById(req.params.id).exec().then(function (project) {
    project.name = req.body.name;

    project.save().exec().then(function () {
      res.send(project);
    }, next);
  }, next);
});

app.post('/projects', function (req, res, next) {
  var project = new Project({
    name: req.body.name
  });

  project.save().exec().then(function () {
    res.send(project);
  }, next);

  // add project_id to user
});

app.delete('/projects/:id', function (req, res, next) {
  Project.findById(req.params.id).exec().then(function (project) {
    project.remove().exec().then(function () {
      res.send('');
    }, next)
  }, next);

  // remove project_id from user
});

module.exports = app;<|endoftext|>


<commit_before>(function() {
	var ThreeWebGLRendererPlugin = E2.plugins.three_webgl_renderer = function(core) {
		this.desc = 'THREE.js WebGL renderer'

		this.input_slots = [
			{
				name: 'camera',
				dt: core.datatypes.CAMERA,
				desc: 'Camera to use for rendering.'
			},
			{
				name: 'scene',
				dt: core.datatypes.SCENE,
				desc: 'Scene to render',
				def: null
			},
			{
				name: 'bgcolor',
				dt: core.datatypes.COLOR,
				desc: 'Background color',
				def: null
			}
		]

		this.output_slots = []

		this.always_update = true
		this.state = { always_update: true }
	}

	ThreeWebGLRendererPlugin.prototype.reset = function() {
		this.domElement = E2.dom.webgl_canvas[0]

		console.log('reset',
			this.domElement.clientWidth,
			this.domElement.clientHeight,
			this.domElement.clientWidth / this.domElement.clientHeight)

		this.scene = new THREE.Scene()

		this.perspectiveCamera = new THREE.PerspectiveCamera(
			90,
			this.domElement.clientWidth / this.domElement.clientHeight,
			0.1,
			1000)
	}

	ThreeWebGLRendererPlugin.prototype.update_input = function(slot, data) {
		switch(slot.index) {
			case 0:
				this.perspectiveCamera = data
				break;
			case 1:
				this.scene = data
				break;
			case 2:
				this.renderer.setClearColor(new THREE.Color(data.r, data.g, data.b))
				break;
		}
	}

	ThreeWebGLRendererPlugin.prototype.update_state = function() {
		if (!this.scene) {
			return
		}

		// Render the scene through the manager.
		this.manager.render(this.scene, this.perspectiveCamera)
	}

	ThreeWebGLRendererPlugin.prototype.pick_object = function(e) {
		if (E2.app.noodlesVisible === true)
			return;

		var mouseVector = new THREE.Vector3()

		var wgl_c = E2.dom.webgl_canvas[0]
		var w = wgl_c.clientWidth
		var h = wgl_c.clientHeight

		mouseVector.x = (((e.pageX - wgl_c.offsetLeft) / w) * 2.0) - 1.0
		mouseVector.y = ((1.0 - ((e.pageY - wgl_c.offsetTop) / h)) * 2.0) - 1.0
		mouseVector.z = 0

		if (this.scene.children && this.scene.children.length > 0) {
			this.raycaster.setFromCamera(mouseVector, this.perspectiveCamera)

			// only intersect scene.children[0] - children [1] is the overlays
			var intersects = this.raycaster.intersectObjects(this.scene.children[0].children)

			for (var i = 0; i < intersects.length; i++) {
				if (intersects[i].object.backReference !== undefined) {
					E2.app.clearSelection()
					E2.app.markNodeAsSelected(intersects[i].object.backReference.parentNode)
				}
			}
		}
	}

	ThreeWebGLRendererPlugin.prototype.setup_object_picking = function() {
		$(document).click(this.pick_object.bind(this))
		this.raycaster = new THREE.Raycaster()
	}

	ThreeWebGLRendererPlugin.prototype.play = function() {
		this.resize()
	}

	ThreeWebGLRendererPlugin.prototype.resize = function() {
		console.log('ThreeWebGLRendererPlugin.resize')

		var isFullscreen = !!(document.mozFullScreenElement || document.webkitFullscreenElement);
		var wh = { width: window.innerWidth, height: window.innerHeight }

		if (!isFullscreen) {
			wh.width = this.domElement.clientWidth
			wh.height = this.domElement.clientHeight

			if (typeof(E2.app.calculateCanvasArea) !== 'undefined')
				wh = E2.app.calculateCanvasArea()
		}

		this.effect.setSize(wh.width, wh.height)
	}

	ThreeWebGLRendererPlugin.prototype.onFullScreenChanged = function() {
		var isFullscreen = !!(document.mozFullScreenElement || document.webkitFullscreenElement)
		console.log('ThreeWebGLRendererPlugin.onFullScreenChanged', isFullscreen)

		if (!isFullscreen)
			this.manager.enterVR()
		else
			this.manager.exitVR()
	}

	ThreeWebGLRendererPlugin.prototype.toggleFullScreen = function() {
		var isFullscreen = !!(document.mozFullScreenElement || document.webkitFullscreenElement)
		console.log('ThreeWebGLRendererPlugin.toggleFullScreen', !isFullscreen)
		this.manager.toggleFullScreen()
	}

	ThreeWebGLRendererPlugin.prototype.state_changed = function(ui) {
		if (!ui) {
			console.log('state_changed')
			this.domElement = E2.dom.webgl_canvas[0]
			this.renderer = new THREE.WebGLRenderer({
				canvas: this.domElement,
				// antialias: true
			})

			this.renderer.setPixelRatio(window.devicePixelRatio)

			this.effect = new THREE.VREffect(this.renderer)
			this.manager = new WebVRManager(this.renderer, this.effect, { hideButton: false })

			E2.core.on('resize', this.resize.bind(this))
			// E2.core.on('fullScreenChanged', this.onFullScreenChanged.bind(this))
			E2.core.on('fullScreenChangeRequested', this.toggleFullScreen.bind(this))

			this.setup_object_picking()

			// resize to initial size
			this.resize()
		}
	}

})()

<commit_msg>clear renderer output on graph stop, fixes #293<commit_after>(function() {
	var ThreeWebGLRendererPlugin = E2.plugins.three_webgl_renderer = function(core) {
		this.desc = 'THREE.js WebGL renderer'

		this.input_slots = [
			{
				name: 'camera',
				dt: core.datatypes.CAMERA,
				desc: 'Camera to use for rendering.'
			},
			{
				name: 'scene',
				dt: core.datatypes.SCENE,
				desc: 'Scene to render',
				def: null
			},
			{
				name: 'bgcolor',
				dt: core.datatypes.COLOR,
				desc: 'Background color',
				def: null
			}
		]

		this.output_slots = []

		this.always_update = true
		this.state = { always_update: true }
	}

	ThreeWebGLRendererPlugin.prototype.stop = function() {
		this.renderer.clear()
	}

	ThreeWebGLRendererPlugin.prototype.reset = function() {
		this.domElement = E2.dom.webgl_canvas[0]

		console.log('reset',
			this.domElement.clientWidth,
			this.domElement.clientHeight,
			this.domElement.clientWidth / this.domElement.clientHeight)

		this.scene = new THREE.Scene()

		this.perspectiveCamera = new THREE.PerspectiveCamera(
			90,
			this.domElement.clientWidth / this.domElement.clientHeight,
			0.1,
			1000)
	}

	ThreeWebGLRendererPlugin.prototype.update_input = function(slot, data) {
		switch(slot.index) {
			case 0:
				this.perspectiveCamera = data
				break;
			case 1:
				this.scene = data
				break;
			case 2:
				this.renderer.setClearColor(new THREE.Color(data.r, data.g, data.b))
				break;
		}
	}

	ThreeWebGLRendererPlugin.prototype.update_state = function() {
		if (!this.scene) {
			return
		}

		// Render the scene through the manager.
		this.manager.render(this.scene, this.perspectiveCamera)
	}

	ThreeWebGLRendererPlugin.prototype.pick_object = function(e) {
		if (E2.app.noodlesVisible === true)
			return;

		var mouseVector = new THREE.Vector3()

		var wgl_c = E2.dom.webgl_canvas[0]
		var w = wgl_c.clientWidth
		var h = wgl_c.clientHeight

		mouseVector.x = (((e.pageX - wgl_c.offsetLeft) / w) * 2.0) - 1.0
		mouseVector.y = ((1.0 - ((e.pageY - wgl_c.offsetTop) / h)) * 2.0) - 1.0
		mouseVector.z = 0

		if (this.scene.children && this.scene.children.length > 0) {
			this.raycaster.setFromCamera(mouseVector, this.perspectiveCamera)

			// only intersect scene.children[0] - children [1] is the overlays
			var intersects = this.raycaster.intersectObjects(this.scene.children[0].children)

			for (var i = 0; i < intersects.length; i++) {
				if (intersects[i].object.backReference !== undefined) {
					E2.app.clearSelection()
					E2.app.markNodeAsSelected(intersects[i].object.backReference.parentNode)
				}
			}
		}
	}

	ThreeWebGLRendererPlugin.prototype.setup_object_picking = function() {
		$(document).click(this.pick_object.bind(this))
		this.raycaster = new THREE.Raycaster()
	}

	ThreeWebGLRendererPlugin.prototype.play = function() {
		this.resize()
	}

	ThreeWebGLRendererPlugin.prototype.resize = function() {
		console.log('ThreeWebGLRendererPlugin.resize')

		var isFullscreen = !!(document.mozFullScreenElement || document.webkitFullscreenElement);
		var wh = { width: window.innerWidth, height: window.innerHeight }

		if (!isFullscreen) {
			wh.width = this.domElement.clientWidth
			wh.height = this.domElement.clientHeight

			if (typeof(E2.app.calculateCanvasArea) !== 'undefined')
				wh = E2.app.calculateCanvasArea()
		}

		this.effect.setSize(wh.width, wh.height)
	}

	ThreeWebGLRendererPlugin.prototype.onFullScreenChanged = function() {
		var isFullscreen = !!(document.mozFullScreenElement || document.webkitFullscreenElement)
		console.log('ThreeWebGLRendererPlugin.onFullScreenChanged', isFullscreen)

		if (!isFullscreen)
			this.manager.enterVR()
		else
			this.manager.exitVR()
	}

	ThreeWebGLRendererPlugin.prototype.toggleFullScreen = function() {
		var isFullscreen = !!(document.mozFullScreenElement || document.webkitFullscreenElement)
		console.log('ThreeWebGLRendererPlugin.toggleFullScreen', !isFullscreen)
		this.manager.toggleFullScreen()
	}

	ThreeWebGLRendererPlugin.prototype.state_changed = function(ui) {
		if (!ui) {
			console.log('state_changed')
			this.domElement = E2.dom.webgl_canvas[0]
			this.renderer = new THREE.WebGLRenderer({
				canvas: this.domElement,
				// antialias: true
			})

			this.renderer.setPixelRatio(window.devicePixelRatio)

			this.effect = new THREE.VREffect(this.renderer)
			this.manager = new WebVRManager(this.renderer, this.effect, { hideButton: false })

			E2.core.on('resize', this.resize.bind(this))
			// E2.core.on('fullScreenChanged', this.onFullScreenChanged.bind(this))
			E2.core.on('fullScreenChangeRequested', this.toggleFullScreen.bind(this))

			this.setup_object_picking()

			// resize to initial size
			this.resize()
		}
	}

})()

<|endoftext|>