<commit_before>var userid;
//arrays gebruikt voor autocompletes en selecteren waarde hiervan.
var studentLists = [];
var studentListsid = [];
var teachers = []
var teachersid = []

function pageViewModel(gvm) {
    gvm.projecttitle = ko.observable("");
    gvm.userId = -1;
    gvm.coupledCount = 0;

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.addBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddBtn")}, gvm);

    gvm.addmoduleBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Addmodule");}, gvm);
    gvm.savePage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm);

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + $("#projectHeader").data('value'), function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };

    gvm.coupledLists = ko.observableArray([]);
    gvm.availableLists = ko.observableArray([]);

    gvm.addCoupledList = function(id, name) {
        // Push data
        var tblOject = {tid: id, tname: name};
        gvm.coupledLists.push(tblOject);

        $("#uncouplebtn-" + id).click(function(){
            showYesNoModal("Bent u zeker dat u dit item wil ontkoppelen?", function(val){
                if(val){
                    $.ajax({
                        url: '/api/project/' + $("#projectHeader").data('value') +'/studentlist/uncouple/' + id,
                        type: "DELETE",
                        success: function() {
                            gvm.coupledCount--;
                            viewModel.coupledLists.remove(tblOject);
                        }
                    });

                }
            });
        });
    }

    gvm.addAvailableLists = function(id, name) {
        var tblOject = {tid: id, tname: name};
        gvm.availableLists.push(tblOject);

        $("#couplebtn-" + id).click(function(){
            if(gvm.coupledCount == 0) {
                $.ajax({
                    url: '/api/project/' + $("#projectHeader").data('value') + '/studentlist/' + id,
                    type: "POST",
                    success: function() {
                        gvm.coupledCount++;
                        viewModel.coupledLists.push(tblOject);
                    }
                });
            } else {
                alert("list already coupled");
            }
        });
    }

    gvm.getCoupledLists = function() {
        $.getJSON('/api/project/' + $("#projectHeader").data('value') + '/coupledlists', function(data) {
            $.each(data, function(i, item) {
                gvm.coupledCount++;
                gvm.addCoupledList(item.id, item.name);
            });
        });
}

    gvm.getAvailableLists = function() {
        $.getJSON('/api/studentlists/' + gvm.userId, function(data) {
            $.each(data, function(i, item) {
                gvm.addAvailableLists(item.id, item.name);
            });
        });
    }

    // The table data observable array
    gvm.tabledata = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(id, studlist, name) {
        console.log("addTableData")
        // Push data
        var tblOject = {tid: id, tstudlist: studlist, tteacher: name};
        gvm.tabledata.push(tblOject);

        // Attach delete handler to delete button
        $('#removebtn-' + id).bind('click', function(event, data){
            // Delete the table item
            deleteTableItem(id, tblOject);
            event.stopPropagation();
        });
            }

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    }

 }

 function getAllTeachers() {
     teachers = [];
     teachersid = [];
     $.getJSON('/api/getteacherrapport', function(data) {
        $.each(data, function(i, item) {
            teachers.push(item.firstname + " " + item.lastname);
            teachersid.push(item.id);
        });
    });
    return teachers;
 }

function getAllStudentLists() {
    studentLists = [];
    studentListsid = [];
    $.getJSON('/api/studentlistsrapporten/' + userid, function (data) {
        $.each(data, function (i, item) {
            studentLists.push(item.name);
            studentListsid.push(item.id);
        });
    });
    return studentLists;
}

function getTeacherid() {

    // functie voor het opsplitsen van naam indien gewenst.
    // console.log(getTeacherID($('#teachersComplete').val().substr(0,$('#teachersComplete').val().indexOf(' ')), $('#teachersComplete').val().substr($('#teachersComplete').val().indexOf(' ')+1)));

    var i = 0;
    var teacher = 0;
    teachers.forEach(function(entry) {
        if (new String(entry).valueOf() == new String($('#teachersComplete').val()).valueOf()) {
            teacher = teachersid[i];
        }
        i+= 1;
    });
    return teacher
}

function getGroupid() {
    var i = 0;
    var studlijst;
    studentLists.forEach(function(entry) {
        if (new String(entry).valueOf() == new String($('#studentListComplete').val()).valueOf()) {
            studlijst = (studentListsid[i]);
        }
        i+= 1;
    });
    return studlijst;
}

 function addGroup(courseid, teacherid, studlijstid) {
     //TODO if teacher or studlijst = 0 dan bestaat deze niet!
     //TODO momenteel nog mogelijk om meer als 1 maal zelfde velden in te voeren.

         $.ajax({
            url: "/api/coursecouple/" + courseid + "/" + studlijstid + "/" + teacherid,
             type: "POST",
             data: {'course': courseid, 'teacher': teacherid, 'studentlist': teacherid},
             success: function(data) {
                 //console.log(data);
                 //callback(true);
             },
             error: function(data) {
                 console.log('Failed to add new student');
                 //callback(false);
             }
         });
 }

/*
 * Load page of the table
 */
function loadTablePage(pagenr,course)
{
    $.getJSON('/api/getStudentGroupTeacherByCourseID/page/' + pagenr + '/' + course, function(data){

        /* Clear current table page */
        viewModel.clearTable();

        // Load table data
        $.each(data.data, function(i, item) {
           viewModel.addTableData(item.studid , item.name , item.firstname + " " + item.lastname);
        });

        /* Let previous en next buttons work */

        if(data.prev == "none"){
            $('#pager-prev-btn').addClass('disabled');
        } else {
            $('#pager-prev-btn').removeClass('disabled');
            $('#pager-prev-btn a').click(function(){
                loadTablePage(data.prev);
            });
        }

        if(data.next == "none"){
            $('#pager-next-btn').addClass('disabled');
        } else {
            $('#pager-next-btn').removeClass('disabled');
            $('#pager-next-btn a').click(function(){
                loadTablePage(data.next);
            });
        }

        // Number of pager buttons
        var numItems = $('.pager-nr-btn').length;

        /* Calculate for the pager buttons */
        var lowPage = Math.floor(pagenr/numItems) + 1;

        $('.pager-nr-btn').each(function() {
            /* calculate current page number */
            var thispagenr = lowPage++;

            /* Add the page number */
            $(this).html('' + thispagenr + '');

            /* Add active class to current page */
            if(thispagenr == pagenr) {
                $(this).addClass('active');
            } else {
                $(this).removeClass('active');
            }

            /* Disable inactive classes and bind handlers to active classes */
            if(thispagenr > data.pagecount) {
                $(this).addClass('disabled');
            } else {
                /* Add click listener for button */
                $(this).click(function() {
                    loadTablePage(thispagenr);
                });
            }
        });
    });
}

/*
 * Delete item from table given the id.
 */
function deleteTableItem(id, tblOject) {
    showYesNoModal("Bent u zeker dat u dit item wil verwijderen? \r\n Let op: verwijderde items blijven in het systeem en kunnen weer actief gezet worden door een administrator. \r\n Gelieve de administrator te contacteren om een vak definitief te verwijderen.", function(val){
        if(val){
            /*
            $.ajax({
                url: "/api/coursedelete/" + id,
                type: "DELETE",
                success: function() {
                    viewModel.tabledata.remove(tblOject);
                }
            });
            */
            console.log(id);
        }
    });
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getCoupledLists();

    //Add Course members

    $('#addGroupForm').hide();

    $('#addCoursemembers').click(function() {
        $("#addGroupForm").show();
        $('#teachersComplete').autocomplete({ source: getAllTeachers() });
        $('#studentListComplete').autocomplete({ source: getAllStudentLists() });
    });

    $('#addGroupBtn').click(function() {
         addGroup($('#projectHeader').attr("data-value"), getTeacherid(), getGroupid());

        $('#studentListComplete').val("");
        $('#teachersComplete').val("");

        loadTablePage(1,$('#projectHeader').attr("data-value"));

        $('addGroupForm').hide();
    });

    $.getJSON('/api/currentuser', function(data) {
        viewModel.userId = data.id;
        userid = data.id;
        viewModel.getAvailableLists(data.id);
    });
    loadTablePage(1,$('#projectHeader').attr("data-value"));
}
<commit_msg>inactief zetten van link<commit_after>var userid;
//arrays gebruikt voor autocompletes en selecteren waarde hiervan.
var studentLists = [];
var studentListsid = [];
var teachers = []
var teachersid = []

function pageViewModel(gvm) {
    gvm.projecttitle = ko.observable("");
    gvm.userId = -1;
    gvm.coupledCount = 0;

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.addBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddBtn")}, gvm);

    gvm.addmoduleBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Addmodule");}, gvm);
    gvm.savePage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm);

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + $("#projectHeader").data('value'), function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };

    gvm.coupledLists = ko.observableArray([]);
    gvm.availableLists = ko.observableArray([]);

    gvm.addCoupledList = function(id, name) {
        // Push data
        var tblOject = {tid: id, tname: name};
        gvm.coupledLists.push(tblOject);

        $("#uncouplebtn-" + id).click(function(){
            showYesNoModal("Bent u zeker dat u dit item wil ontkoppelen?", function(val){
                if(val){
                    $.ajax({
                        url: '/api/project/' + $("#projectHeader").data('value') +'/studentlist/uncouple/' + id,
                        type: "DELETE",
                        success: function() {
                            gvm.coupledCount--;
                            viewModel.coupledLists.remove(tblOject);
                        }
                    });

                }
            });
        });
    }

    gvm.addAvailableLists = function(id, name) {
        var tblOject = {tid: id, tname: name};
        gvm.availableLists.push(tblOject);

        $("#couplebtn-" + id).click(function(){
            if(gvm.coupledCount == 0) {
                $.ajax({
                    url: '/api/project/' + $("#projectHeader").data('value') + '/studentlist/' + id,
                    type: "POST",
                    success: function() {
                        gvm.coupledCount++;
                        viewModel.coupledLists.push(tblOject);
                    }
                });
            } else {
                alert("list already coupled");
            }
        });
    }

    gvm.getCoupledLists = function() {
        $.getJSON('/api/project/' + $("#projectHeader").data('value') + '/coupledlists', function(data) {
            $.each(data, function(i, item) {
                gvm.coupledCount++;
                gvm.addCoupledList(item.id, item.name);
            });
        });
}

    gvm.getAvailableLists = function() {
        $.getJSON('/api/studentlists/' + gvm.userId, function(data) {
            $.each(data, function(i, item) {
                gvm.addAvailableLists(item.id, item.name);
            });
        });
    }

    // The table data observable array
    gvm.tabledata = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(id, studlist, name) {
        // Push data
        var tblOject = {tid: id, tstudlist: studlist, tteacher: name};
        gvm.tabledata.push(tblOject);

        // Attach delete handler to delete button
        $('#removebtn-' + id).bind('click', function(event, data){
            // Delete the table item
            deleteTableItem(id, tblOject);
            event.stopPropagation();
        });
            }

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    }

 }

 function getAllTeachers() {
     teachers = [];
     teachersid = [];
     $.getJSON('/api/getteacherrapport', function(data) {
        $.each(data, function(i, item) {
            teachers.push(item.firstname + " " + item.lastname);
            teachersid.push(item.id);
        });
    });
    return teachers;
 }

function getAllStudentLists() {
    studentLists = [];
    studentListsid = [];
    $.getJSON('/api/studentlistsrapporten/' + userid, function (data) {
        $.each(data, function (i, item) {
            studentLists.push(item.name);
            studentListsid.push(item.id);
        });
    });
    return studentLists;
}

function getTeacherid() {

    // functie voor het opsplitsen van naam indien gewenst.
    // console.log(getTeacherID($('#teachersComplete').val().substr(0,$('#teachersComplete').val().indexOf(' ')), $('#teachersComplete').val().substr($('#teachersComplete').val().indexOf(' ')+1)));

    var i = 0;
    var teacher = 0;
    teachers.forEach(function(entry) {
        if (new String(entry).valueOf() == new String($('#teachersComplete').val()).valueOf()) {
            teacher = teachersid[i];
        }
        i+= 1;
    });
    return teacher
}

function getGroupid() {
    var i = 0;
    var studlijst;
    studentLists.forEach(function(entry) {
        if (new String(entry).valueOf() == new String($('#studentListComplete').val()).valueOf()) {
            studlijst = (studentListsid[i]);
        }
        i+= 1;
    });
    return studlijst;
}

 function addGroup(courseid, teacherid, studlijstid) {
     //TODO if teacher or studlijst = 0 dan bestaat deze niet!
     //TODO momenteel nog mogelijk om meer als 1 maal zelfde velden in te voeren.

         $.ajax({
            url: "/api/coursecouple/" + courseid + "/" + studlijstid + "/" + teacherid,
             type: "POST",
             data: {'course': courseid, 'teacher': teacherid, 'studentlist': teacherid},
             success: function(data) {
                 //console.log(data);
                 //callback(true);
             },
             error: function(data) {
                 console.log('Failed to add new student');
                 //callback(false);
             }
         });
 }

/*
 * Load page of the table
 */
function loadTablePage(pagenr,course)
{
    $.getJSON('/api/getStudentGroupTeacherByCourseID/page/' + pagenr + '/' + course, function(data){

        /* Clear current table page */
        viewModel.clearTable();

        // Load table data
        $.each(data.data, function(i, item) {
            console.log("studid: " + studid + " en userid: " + userid);
           viewModel.addTableData(item.studid , item.name , item.firstname + " " + item.lastname);
        });

        /* Let previous en next buttons work */

        if(data.prev == "none"){
            $('#pager-prev-btn').addClass('disabled');
        } else {
            $('#pager-prev-btn').removeClass('disabled');
            $('#pager-prev-btn a').click(function(){
                loadTablePage(data.prev);
            });
        }

        if(data.next == "none"){
            $('#pager-next-btn').addClass('disabled');
        } else {
            $('#pager-next-btn').removeClass('disabled');
            $('#pager-next-btn a').click(function(){
                loadTablePage(data.next);
            });
        }

        // Number of pager buttons
        var numItems = $('.pager-nr-btn').length;

        /* Calculate for the pager buttons */
        var lowPage = Math.floor(pagenr/numItems) + 1;

        $('.pager-nr-btn').each(function() {
            /* calculate current page number */
            var thispagenr = lowPage++;

            /* Add the page number */
            $(this).html('' + thispagenr + '');

            /* Add active class to current page */
            if(thispagenr == pagenr) {
                $(this).addClass('active');
            } else {
                $(this).removeClass('active');
            }

            /* Disable inactive classes and bind handlers to active classes */
            if(thispagenr > data.pagecount) {
                $(this).addClass('disabled');
            } else {
                /* Add click listener for button */
                $(this).click(function() {
                    loadTablePage(thispagenr);
                });
            }
        });
    });
}

/*
 * Delete item from table given the id.
 */
function deleteTableItem(id, tblOject) {
    showYesNoModal("Bent u zeker dat u dit item wil verwijderen? \r\n Let op: verwijderde items blijven in het systeem en kunnen weer actief gezet worden door een administrator. \r\n Gelieve de administrator te contacteren om een vak definitief te verwijderen.", function(val){
        if(val){
            /*
            $.ajax({
                url: "/api/coursedelete/" + id,
                type: "DELETE",
                success: function() {
                    viewModel.tabledata.remove(tblOject);
                }
            });
            */
            console.log(id);
        }
    });
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getCoupledLists();

    //Add Course members

    $('#addGroupForm').hide();

    $('#addCoursemembers').click(function() {
        $("#addGroupForm").show();
        $('#teachersComplete').autocomplete({ source: getAllTeachers() });
        $('#studentListComplete').autocomplete({ source: getAllStudentLists() });
    });

    $('#addGroupBtn').click(function() {
         addGroup($('#projectHeader').attr("data-value"), getTeacherid(), getGroupid());

        $('#studentListComplete').val("");
        $('#teachersComplete').val("");

        loadTablePage(1,$('#projectHeader').attr("data-value"));

        $('addGroupForm').hide();
    });

    $.getJSON('/api/currentuser', function(data) {
        viewModel.userId = data.id;
        userid = data.id;
        viewModel.getAvailableLists(data.id);
    });
    loadTablePage(1,$('#projectHeader').attr("data-value"));
}
<|endoftext|>


<commit_before>/**
 * 组件
 * 1. 什么是组件
 * 2. 组件和元素的区别和联系是什么？
 * 3. 如何定义组件
 */
/**
 * 1. 什么是组件
 *   1.1. 组成页面的部件
 *   1.1 组件可复用，可嵌套
 */
import React from 'react';
import ReactDOM from 'react-dom';
//Hello类继承自React.Component
/**
 * 1.组件名字必须是以大写字母开头
 * 2.组件内有render方法，返回一个顶级React元素
 * 3.组件的用法和React元素基本一样
 */
class Hello extends React.Component{
  //1. 用来指定此组件长什么样子
  //2. 必须返回一个且只能返回一个顶级React元素
  render(){
    return
12

  }
}
ReactDOM.render(<Hello/>,document.querySelector('#root'));

<commit_msg>配置.babelrc<commit_after>/**
 * 组件
 * 1. 什么是组件
 * 2. 组件和元素的区别和联系是什么？
 * 3. 如何定义组件
 */
/**
 * 1. 什么是组件
 *   1.1. 组成页面的部件
 *   1.1 组件可复用，可嵌套
 */
import React from 'react';
import ReactDOM from 'react-dom';
//Hello类继承自React.Component
/**
 * 1.组件名字必须是以大写字母开头,是为了区分React元素和组件
 * 2.组件内有render方法，返回一个顶级React元素
 * 3.组件的用法和React元素基本一样
 *
 */
class Hello extends React.Component{
  //1. 用来指定此组件长什么样子
  //2. 必须返回一个且只能返回一个顶级React元素
  render(){
    return
12

  }
}
/**
 * 1. 实例化Hello类的实例 let hello = new Hello();
 * 2. 调用实例上的render方法 .  let ele = hello.render(); ele=div
 * 3. 把个ele转成真实的DOM元素并且插入到页面中去
 */
ReactDOM.render(<Hello/>,document.querySelector('#root'));

<|endoftext|>


<commit_before>/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */
'use strict';

const assert = require('assert');
const request = require('supertest');
const app = request(require('../../index'));
const auth = require('../../lib/auth');

const users = require('../fixtures/dnt-users');

const getUserData = auth.getUserData;

describe.only('POST /lister/:liste/blimed', () => {
  before(() => {
    auth.getUserData = () => Promise.resolve(users[1]);
  });

  after(() => {
    auth.getUserData = getUserData;
  });

  const listId = '57974036b565590001a98884';
  // Append `/blimed` or `/meldav` to join or leave a list
  const url = `/api/dev/lister/${listId}`;

  it('returns error for missing user auth', () => (
    app.post(`${url}/blimed`)
      .expect(401)
      .expect({
        code: 401,
        message: 'X-User-Id header is required',
      })
  ));

  it('adds the list id to the users lists array', done => {
    app.post(`${url}/blimed`)
      .set('X-User-Id', '1234')
      .set('X-User-Token', 'abc123')
      .expect(200)
      .end((req, res) => {
        assert.equal(res.body.message, 'Ok');
        assert.notEqual(res.body.data.lister.indexOf(listId), -1);
        done();
      });
  });

  it('removes the list from the users lists array', done => {
    app.post(`${url}/meldav`)
      .set('X-User-Id', '1234')
      .set('X-User-Token', 'abc123')
      .expect(200)
      .end((req, res) => {
        assert.equal(res.body.message, 'Ok');
        assert.equal(res.body.data.lister.indexOf(listId), -1);
        done();
      });
  });
});
<commit_msg>test(list): split endpoints in separate describe<commit_after>/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */
'use strict';

const assert = require('assert');
const request = require('supertest');
const app = request(require('../../index'));
const auth = require('../../lib/auth');

const users = require('../fixtures/dnt-users');

const getUserData = auth.getUserData;

describe('POST /lister/:liste/*', () => {
  before(() => {
    auth.getUserData = () => Promise.resolve(users[1]);
  });

  after(() => {
    auth.getUserData = getUserData;
  });

  const listId = '57974036b565590001a98884';
  // Append `/blimed` or `/meldav` to join or leave a list
  const url = `/api/dev/lister/${listId}`;

  describe('POST /lister/:liste/blimed', () => {
    it('returns error for missing user auth', () => (
      app.post(`${url}/blimed`)
        .expect(401)
        .expect({
          code: 401,
          message: 'X-User-Id header is required',
        })
    ));

    it('adds the list id to the users lists array', done => {
      app.post(`${url}/blimed`)
        .set('X-User-Id', '1234')
        .set('X-User-Token', 'abc123')
        .expect(200)
        .end((req, res) => {
          assert.equal(res.body.message, 'Ok');
          assert.notEqual(res.body.data.lister.indexOf(listId), -1);
          done();
        });
    });
  });

  describe('POST /lister/:liste/meldav', () => {
    it('removes the list from the users lists array', done => {
      app.post(`${url}/meldav`)
        .set('X-User-Id', '1234')
        .set('X-User-Token', 'abc123')
        .expect(200)
        .end((req, res) => {
          assert.equal(res.body.message, 'Ok');
          assert.equal(res.body.data.lister.indexOf(listId), -1);
          done();
        });
    });
  });
});
<|endoftext|>


<commit_before>const Sequelize = require('sequelize');
const fs = require('fs');
const path = require('path');
const TimeUtil = require('../util/TimeUtil.js');

module.exports = class CalendarSequelize {
    constructor(config) {
        this.sequelize = new Sequelize(config);
    }

    async init() {
        const sequelize = this.sequelize;
        await sequelize.authenticate();
        const dbSync = [];

        fs
            .readdirSync(path.join(__dirname, 'models'))
            .forEach(file => {
                var model = sequelize.import(path.join(__dirname, 'models', file));
                this[model.name] = model;
                dbSync.push(model.sync());
            });

        return await Promise.all(dbSync);
    }

    async createEvent(content, tag, guild, startTime) {
        return await this.Event.create({
            content: content,
            tag: tag,
            guild: guild,
            start_time: startTime
        });
    }

    async createEvent(content, tag, guild, startTime, endTime) {
        return await this.Event.create({
            content: content,
            tag: tag,
            guild: guild,
            start_time: startTime,
            end_time: endTime
        });
    }

    async fetchUpcomingEvents(tag, guild) {
        return await this.Event.findAll({
            where: {
                tag: tag,
                guild: guild,
                start_time: {
                    $gte: TimeUtil.getTimeObject()
                }
            }
        });
    }

    async fetchOngoingEvents(tag, guild) {
        let now = TimeUtil.getTimeObject();
        return await this.Event.findAll({
            where: {
                tag: tag,
                guild: guild,
                start_time: {
                    $lt: now
                },
                end_time: {
                    $gte: now
                }
            }
        });
    }

    async fetchActiveEventTags(guild) {
        let now = TimeUtil.getTimeObject();
        let res = await this.Event.findAll({
            attributes: ['tag'],
            where: {
                guild: guild,
                $or: [
                    {
                        start_time: {
                            $gte: now
                        }
                    }, {
                        end_time: {
                            $gte: now
                        }
                    }
                ]
            }
        });

        // Limitation
        let resultSet = new Set();
        let ret = [];
        res.forEach((row) => {
            if (!resultSet.has(row.tag)) {
                resultSet.add(row.tag);
                ret.push(row);
            }
        })
        return ret;
    }

    async deleteEvent(id) {
        return await this.Event.destroy({
            where: {
                id: id
            }
        });
    }

    async addModerator(guild, role) {
        return await this.Moderator.create({
            guild: guild,
            role: role
        });
    }

    async listModerators(guild) {
        return await this.Moderator.findAll({
            where: {
                guild: guild
            }
        });
    }

    async listAllModerators() {
        return await this.Moderator.findAll();
    }

    async removeModerator(guild, role) {
        return await this.Moderator.destroy({
            where: {
                guild: guild,
                role: role
            }
        })
    }
}
<commit_msg>Order event query by start/end time<commit_after>const Sequelize = require('sequelize');
const fs = require('fs');
const path = require('path');
const TimeUtil = require('../util/TimeUtil.js');

module.exports = class CalendarSequelize {
    constructor(config) {
        this.sequelize = new Sequelize(config);
    }

    async init() {
        const sequelize = this.sequelize;
        await sequelize.authenticate();
        const dbSync = [];

        fs
            .readdirSync(path.join(__dirname, 'models'))
            .forEach(file => {
                var model = sequelize.import(path.join(__dirname, 'models', file));
                this[model.name] = model;
                dbSync.push(model.sync());
            });

        return await Promise.all(dbSync);
    }

    async createEvent(content, tag, guild, startTime) {
        return await this.Event.create({
            content: content,
            tag: tag,
            guild: guild,
            start_time: startTime
        });
    }

    async createEvent(content, tag, guild, startTime, endTime) {
        return await this.Event.create({
            content: content,
            tag: tag,
            guild: guild,
            start_time: startTime,
            end_time: endTime
        });
    }

    async fetchUpcomingEvents(tag, guild) {
        return await this.Event.findAll({
            where: {
                tag: tag,
                guild: guild,
                start_time: {
                    $gte: TimeUtil.getTimeObject()
                }
            },
            order: ['start_time']
        });
    }

    async fetchOngoingEvents(tag, guild) {
        let now = TimeUtil.getTimeObject();
        return await this.Event.findAll({
            where: {
                tag: tag,
                guild: guild,
                start_time: {
                    $lt: now
                },
                end_time: {
                    $gte: now
                }
            },
            order: ['end_time']
        });
    }

    async fetchActiveEventTags(guild) {
        let now = TimeUtil.getTimeObject();
        let res = await this.Event.findAll({
            attributes: ['tag'],
            where: {
                guild: guild,
                $or: [
                    {
                        start_time: {
                            $gte: now
                        }
                    }, {
                        end_time: {
                            $gte: now
                        }
                    }
                ]
            }
        });

        // Limitation
        let resultSet = new Set();
        let ret = [];
        res.forEach((row) => {
            if (!resultSet.has(row.tag)) {
                resultSet.add(row.tag);
                ret.push(row);
            }
        })
        return ret;
    }

    async deleteEvent(id) {
        return await this.Event.destroy({
            where: {
                id: id
            }
        });
    }

    async addModerator(guild, role) {
        return await this.Moderator.create({
            guild: guild,
            role: role
        });
    }

    async listModerators(guild) {
        return await this.Moderator.findAll({
            where: {
                guild: guild
            }
        });
    }

    async listAllModerators() {
        return await this.Moderator.findAll();
    }

    async removeModerator(guild, role) {
        return await this.Moderator.destroy({
            where: {
                guild: guild,
                role: role
            }
        })
    }
}
<|endoftext|>


<commit_before>
import React from 'react'

/**
 * Icon SVG
 *
 * All icons are 24px at the moment!
 */
const icons = {
  Person: 'M12 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm0 2c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z',
  Help: 'M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 17h-2v-2h2v2zm2.07-7.75l-.9.92C13.45 12.9 13 13.5 13 15h-2v-.5c0-1.1.45-2.1 1.17-2.83l1.24-1.26c.37-.36.59-.86.59-1.41 0-1.1-.9-2-2-2s-2 .9-2 2H8c0-2.21 1.79-4 4-4s4 1.79 4 4c0 .88-.36 1.68-.93 2.25z',
  Home: 'M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z',
  Assessment: 'M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM9 17H7v-7h2v7zm4 0h-2V7h2v10zm4 0h-2v-4h2v4z',
  Dashboard: 'M3 13h8V3H3v10zm0 8h8v-6H3v6zm10 0h8V11h-8v10zm0-18v6h8V3h-8z',
  List: 'M3 13h2v-2H3v2zm0 4h2v-2H3v2zm0-8h2V7H3v2zm4 4h14v-2H7v2zm0 4h14v-2H7v2zM7 7v2h14V7H7z',
  MoreVert: 'M12 8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm0 2c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z',
  Menu: 'M3 18h18v-2H3v2zm0-5h18v-2H3v2zm0-7v2h18V6H3z',
  Language: 'M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zm6.93 6h-2.95c-.32-1.25-.78-2.45-1.38-3.56 1.84.63 3.37 1.91 4.33 3.56zM12 4.04c.83 1.2 1.48 2.53 1.91 3.96h-3.82c.43-1.43 1.08-2.76 1.91-3.96zM4.26 14C4.1 13.36 4 12.69 4 12s.1-1.36.26-2h3.38c-.08.66-.14 1.32-.14 2 0 .68.06 1.34.14 2H4.26zm.82 2h2.95c.32 1.25.78 2.45 1.38 3.56-1.84-.63-3.37-1.9-4.33-3.56zm2.95-8H5.08c.96-1.66 2.49-2.93 4.33-3.56C8.81 5.55 8.35 6.75 8.03 8zM12 19.96c-.83-1.2-1.48-2.53-1.91-3.96h3.82c-.43 1.43-1.08 2.76-1.91 3.96zM14.34 14H9.66c-.09-.66-.16-1.32-.16-2 0-.68.07-1.35.16-2h4.68c.09.65.16 1.32.16 2 0 .68-.07 1.34-.16 2zm.25 5.56c.6-1.11 1.06-2.31 1.38-3.56h2.95c-.96 1.65-2.49 2.93-4.33 3.56zM16.36 14c.08-.66.14-1.32.14-2 0-.68-.06-1.34-.14-2h3.38c.16.64.26 1.31.26 2s-.1 1.36-.26 2h-3.38z',
  ChevronRight: 'M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z',
  ArrowForward: 'M12 4l-1.41 1.41L16.17 11H4v2h12.17l-5.58 5.59L12 20l8-8z',
  TrendingFlat: 'M22 12l-4-4v3H3v2h15v3z',
  VPNKey: 'M12.65 10C11.83 7.67 9.61 6 7 6c-3.31 0-6 2.69-6 6s2.69 6 6 6c2.61 0 4.83-1.67 5.65-4H17v4h4v-4h2v-4H12.65zM7 14c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z',
  Done: 'M9 16.2L4.8 12l-1.4 1.4L9 19 21 7l-1.4-1.4L9 16.2z'
}

/**
 * Export all icons
 */
Object.keys(icons).forEach(key => {
  let value = icons[key]

  class Icon extends React.Component {

    static propTypes = {
      fill: React.PropTypes.string
    }

    render () {
      return (
        <svg
          width='24'
          height='24'
          viewBox='0 0 24 24'
          fill={this.props.fill}
          className={this.props.className}
        >
          <path
            d={value}
          />
        </svg>
      )
    }

  }

  exports[key] = Icon
})

/**
 * Icon.Button for better touch targets on mobile browsers
 */
class Button extends React.Component {

  static propTypes = {
    onClick: React.PropTypes.func.isRequired
  }

  render () {
    return (
      <button type='button' className='IconButton' {...this.props}>
        {this.props.children}
      </button>
    )
  }

}

/**
 * HBM Logo
 */
class Logo extends React.Component {

  render () {
    var fill = this.props.fill || '#fff'

    var style = {
      maxWidth: '100%',
      maxHeight: '100%'
    }

    return (
      <svg
        width='68'
        height='61'
        viewBox='0 0 68 61'
        style={style}
      >
        <polygon style={{fill}} points='61.9 42.6 68 42.6 68 61 63.3 61 63.3 49.7 57.7 61 53.7 61 48.2 49.7 48.2 61 43.4 61 43.4 42.6 49.6 42.6 55.7 55.1 61.9 42.6 ' />
        <polygon style={{fill}} points='0 61 0 42.6 4.7 42.6 4.7 49.9 13.9 49.9 13.9 42.6 18.7 42.6 18.7 61 13.9 61 13.9 53.7 4.7 53.7 4.7 61 0 61 ' />
        <path style={{fillRule: 'evenodd', clipRule: 'evenodd', fill}} d='M0 0h68v40.4H0V0L0 0zM41.6 36.6c-1.8-2.6-2.9-5.8-2.9-9.2 0-8.9 7.2-16.1 16.1-16.1 3.1 0 6 0.9 8.5 2.4v-10H4.7v32.9L41.6 36.6 41.6 36.6zM43.4 27.4c0-6.3 5.1-11.3 11.3-11.3s11.3 5.1 11.3 11.3c0 6.3-5.1 11.3-11.3 11.3S43.4 33.7 43.4 27.4L43.4 27.4z' />
        <path style={{fill}} d='M38.1 51.1c1.1-0.7 2.3-1.7 2.3-4s-1.4-4-3.7-4.5H22V61h13.9c2.9 0 5.2-2.3 5.2-5.2C41.1 53.8 39.9 51.8 38.1 51.1zM26.1 46.1l7.6 0c1 0 1.6 0.8 1.6 1.8 0 1-0.6 1.8-1.6 1.8h-7.6V46.1zM33.3 57.5h-7.2V53h7.2c1.7-0.1 2.8 0.6 2.8 2.1C36.1 56.5 34.9 57.5 33.3 57.5z' />
      </svg>
    )
  }
}

/**
 * Export components
 */
exports.Button = Button
exports.Logo = Logo
<commit_msg>import svg icons from generated class list<commit_after>import React from 'react'

import classList from './classList'

Object.keys(classList).forEach(function (className) {
  exports[className] = classList[className]
})

/**
 * Icon.Button for better touch targets on mobile browsers
 */
class Button extends React.Component {

  static propTypes = {
    onClick: React.PropTypes.func.isRequired
  }

  render () {
    return (
      <button type='button' className='IconButton' {...this.props}>
        {this.props.children}
      </button>
    )
  }

}

/**
 * HBM Logo
 */
class Logo extends React.Component {

  render () {
    var fill = this.props.fill || '#fff'

    var style = {
      maxWidth: '100%',
      maxHeight: '100%'
    }

    return (
      <svg
        width='68'
        height='61'
        viewBox='0 0 68 61'
        style={style}
      >
        <polygon style={{fill}} points='61.9 42.6 68 42.6 68 61 63.3 61 63.3 49.7 57.7 61 53.7 61 48.2 49.7 48.2 61 43.4 61 43.4 42.6 49.6 42.6 55.7 55.1 61.9 42.6 ' />
        <polygon style={{fill}} points='0 61 0 42.6 4.7 42.6 4.7 49.9 13.9 49.9 13.9 42.6 18.7 42.6 18.7 61 13.9 61 13.9 53.7 4.7 53.7 4.7 61 0 61 ' />
        <path style={{fillRule: 'evenodd', clipRule: 'evenodd', fill}} d='M0 0h68v40.4H0V0L0 0zM41.6 36.6c-1.8-2.6-2.9-5.8-2.9-9.2 0-8.9 7.2-16.1 16.1-16.1 3.1 0 6 0.9 8.5 2.4v-10H4.7v32.9L41.6 36.6 41.6 36.6zM43.4 27.4c0-6.3 5.1-11.3 11.3-11.3s11.3 5.1 11.3 11.3c0 6.3-5.1 11.3-11.3 11.3S43.4 33.7 43.4 27.4L43.4 27.4z' />
        <path style={{fill}} d='M38.1 51.1c1.1-0.7 2.3-1.7 2.3-4s-1.4-4-3.7-4.5H22V61h13.9c2.9 0 5.2-2.3 5.2-5.2C41.1 53.8 39.9 51.8 38.1 51.1zM26.1 46.1l7.6 0c1 0 1.6 0.8 1.6 1.8 0 1-0.6 1.8-1.6 1.8h-7.6V46.1zM33.3 57.5h-7.2V53h7.2c1.7-0.1 2.8 0.6 2.8 2.1C36.1 56.5 34.9 57.5 33.3 57.5z' />
      </svg>
    )
  }
}

/**
 * Export components
 */
exports.Button = Button
exports.Logo = Logo
<|endoftext|>


<commit_before>/* ************************************************************************ */
/*

*/
import React from 'react';
import Recipes from './panels/Recipes.js';

const title = (
Recipes
 Click one to edit);

export default class RecipeList extends React.Component {

    createClick() {
        console.log('create recipe click');
    }

    render() {
        return (

{title}

                                <Recipes/>

                                <button id="DoRecipeCreate" className="btn btn-success" type="button" onClick={this.createClick}>Create a Recipe</button>

        );
    }
}

<commit_msg>on recipe list page removed the "Create" button<commit_after>/* ************************************************************************ */
/*

*/
import React from 'react';
import Recipes from './panels/Recipes.js';

const title = (
Recipes
 Click one to edit);

export default class RecipeList extends React.Component {

    createClick() {
        console.log('create recipe click');
    }

    render() {
        return (

{title}

                                <Recipes/>

        );
    }
}

/*

NOTE: Removed the button from below the panel row, but
kept here in case it's desired again.

                                <button id="DoRecipeCreate" className="btn btn-success" type="button" onClick={this.createClick}>Create a Recipe</button>

*/<|endoftext|>


<commit_before>const express = require('express');
const compression = require('compression');
const app = require('express')();
const bodyParser = require('body-parser');
const http = require('http').Server(app);
const io = require('socket.io')(http);
const request = require('request');

app.use(express.static('dist', {index: 'demo.html'}));
app.use(compression());
app.use(bodyParser.json());

function sendTelegramMessage(chatId, text) {
    console.log("[chat-" + chatId + "] " + text);
    request
        .post('https://api.telegram.org/bot' + process.env.TELEGRAM_TOKEN + '/sendMessage')
        .form({
            "chat_id": chatId,
            "text": text,
            "parse_mode": "Markdown"
        });
}

app.post('/hook', function(req, res){
    const chatId = req.body.message.chat.id;
    const name = req.body.message.chat.first_name || "admin";
    const text = req.body.message.text || "";
    const reply = req.body.message.reply_to_message;

    if (text.startsWith("/start")) {
        sendTelegramMessage(chatId,
            "*Welcome to Intergram* \n" +
            "Your unique chat id is `" + chatId + "`\n" +
            "Use it to link between the embedded chat and this telegram chat");
    } else if (reply){
        let replyText = reply.text || "";
        let userId = replyText.split(':')[0];
        io.emit(chatId + "-" + userId, name + ": " + text);
    } else {
        io.emit(chatId, name + ": " + text);
    }

    res.statusCode = 200;
    res.end();
});

io.on('connection', function(client){

    client.on('register', function(registerMsg){
        let userId = registerMsg.userId;
        let chatId = registerMsg.chatId;

        client.on('message', function(msg) {
            sendTelegramMessage(chatId, userId + ": " + msg);
        });

        client.on('disconnect', function(){
            sendTelegramMessage(chatId, userId + " has left");
        });
    });

});

http.listen(process.env.PORT || 3000, function(){
    console.log('listening on port:' + (process.env.PORT || 3000));
});
<commit_msg>ssl verification<commit_after>const express = require('express');
const compression = require('compression');
const app = require('express')();
const bodyParser = require('body-parser');
const http = require('http').Server(app);
const io = require('socket.io')(http);
const request = require('request');

app.use(express.static('dist', {index: 'demo.html'}));
app.use(compression());
app.use(bodyParser.json());

function sendTelegramMessage(chatId, text) {
    console.log("[chat-" + chatId + "] " + text);
    request
        .post('https://api.telegram.org/bot' + process.env.TELEGRAM_TOKEN + '/sendMessage')
        .form({
            "chat_id": chatId,
            "text": text,
            "parse_mode": "Markdown"
        });
}

app.post('/hook', function(req, res){
    const chatId = req.body.message.chat.id;
    const name = req.body.message.chat.first_name || "admin";
    const text = req.body.message.text || "";
    const reply = req.body.message.reply_to_message;

    if (text.startsWith("/start")) {
        sendTelegramMessage(chatId,
            "*Welcome to Intergram* \n" +
            "Your unique chat id is `" + chatId + "`\n" +
            "Use it to link between the embedded chat and this telegram chat");
    } else if (reply){
        let replyText = reply.text || "";
        let userId = replyText.split(':')[0];
        io.emit(chatId + "-" + userId, name + ": " + text);
    } else {
        io.emit(chatId, name + ": " + text);
    }

    res.statusCode = 200;
    res.end();
});

io.on('connection', function(client){

    client.on('register', function(registerMsg){
        let userId = registerMsg.userId;
        let chatId = registerMsg.chatId;

        client.on('message', function(msg) {
            sendTelegramMessage(chatId, userId + ": " + msg);
        });

        client.on('disconnect', function(){
            sendTelegramMessage(chatId, userId + " has left");
        });
    });

});

http.listen(process.env.PORT || 3000, function(){
    console.log('listening on port:' + (process.env.PORT || 3000));
});

app.get("/acme-challenge/:content", (req, res) => {
    res.send(process.env.CERTBOT_RESPONSE);
});
<|endoftext|>


<commit_before>module.exports = (client, message, args) => {

    { let numArray = args.map(n=> parseFloat(n));  let total = numArray.reduce( (p,c) => p/c>>0); message.channel.sendMessage(total); }

  };<commit_msg><commit_after>module.exports = (client, message, args) => {

    { let numArray = args.map(n=> parseInt(n));  let total = numArray.reduce( (p,c) => p/c>>0); message.channel.sendMessage(total); }

  };<|endoftext|>


<commit_before>var userid;
//arrays gebruikt voor autocompletes en selecteren waarde hiervan.
var studentLists = [];
var studentListsid = [];
var teachers = []
var teachersid = []

function pageViewModel(gvm) {
    gvm.projecttitle = ko.observable("");
    gvm.userId = -1;
    gvm.coupledCount = 0;

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.addBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddBtn")}, gvm);

    gvm.addmoduleBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Addmodule");}, gvm);
    gvm.savePage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm);

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + $("#projectHeader").data('value'), function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };

    gvm.coupledLists = ko.observableArray([]);
    gvm.availableLists = ko.observableArray([]);

    gvm.addCoupledList = function(id, name) {
        // Push data
        var tblOject = {tid: id, tname: name};
        gvm.coupledLists.push(tblOject);

        $("#uncouplebtn-" + id).click(function(){
            showYesNoModal("Bent u zeker dat u dit item wil ontkoppelen?", function(val){
                if(val){
                    $.ajax({
                        url: '/api/project/' + $("#projectHeader").data('value') +'/studentlist/uncouple/' + id,
                        type: "DELETE",
                        success: function() {
                            gvm.coupledCount--;
                            viewModel.coupledLists.remove(tblOject);
                        }
                    });

                }
            });
        });
    }

    gvm.addAvailableLists = function(id, name) {
        var tblOject = {tid: id, tname: name};
        gvm.availableLists.push(tblOject);

        $("#couplebtn-" + id).click(function(){
            if(gvm.coupledCount == 0) {
                $.ajax({
                    url: '/api/project/' + $("#projectHeader").data('value') + '/studentlist/' + id,
                    type: "POST",
                    success: function() {
                        gvm.coupledCount++;
                        viewModel.coupledLists.push(tblOject);
                    }
                });
            } else {
                alert("list already coupled");
            }
        });
    }

    gvm.getCoupledLists = function() {
        $.getJSON('/api/project/' + $("#projectHeader").data('value') + '/coupledlists', function(data) {
            $.each(data, function(i, item) {
                gvm.coupledCount++;
                gvm.addCoupledList(item.id, item.name);
            });
        });
}

    gvm.getAvailableLists = function() {
        $.getJSON('/api/studentlists/' + gvm.userId, function(data) {
            $.each(data, function(i, item) {
                gvm.addAvailableLists(item.id, item.name);
            });
        });
    }

    // The table data observable array
    gvm.tabledata = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(studid, userid, studlist, name) {
        // Push data
        var tblOject = {tid: studid + "-" + userid, tstudlist: studlist, tteacher: name};
        gvm.tabledata.push(tblOject);

        // Attach delete handler to delete button
        $('#removebtn-' + studid + "-" + userid).bind('click', function(event, data){
            // Delete the table item
            deleteTableItem(studid + "-" + userid, tblOject);
            event.stopPropagation();
        });
            }

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    }

 }

 function getAllTeachers() {
     teachers = [];
     teachersid = [];
     $.getJSON('/api/getteacherrapport', function(data) {
        $.each(data, function(i, item) {
            teachers.push(item.firstname + " " + item.lastname);
            teachersid.push(item.id);
        });
    });
    return teachers;
 }

function getAllStudentLists() {
    studentLists = [];
    studentListsid = [];
    $.getJSON('/api/studentlistsrapporten/' + userid, function (data) {
        $.each(data, function (i, item) {
            studentLists.push(item.name);
            studentListsid.push(item.id);
        });
    });
    return studentLists;
}

function getTeacherid() {

    // functie voor het opsplitsen van naam indien gewenst.
    // console.log(getTeacherID($('#teachersComplete').val().substr(0,$('#teachersComplete').val().indexOf(' ')), $('#teachersComplete').val().substr($('#teachersComplete').val().indexOf(' ')+1)));

    var i = 0;
    var teacher = 0;
    teachers.forEach(function(entry) {
        if (new String(entry).valueOf() == new String($('#teachersComplete').val()).valueOf()) {
            teacher = teachersid[i];
        }
        i+= 1;
    });
    return teacher
}

function getGroupid() {
    var i = 0;
    var studlijst;
    studentLists.forEach(function(entry) {
        if (new String(entry).valueOf() == new String($('#studentListComplete').val()).valueOf()) {
            studlijst = (studentListsid[i]);
        }
        i+= 1;
    });
    return studlijst;
}

 function addGroup(courseid, teacherid, studlijstid) {
     //TODO if teacher or studlijst = 0 dan bestaat deze niet!
     //TODO momenteel nog mogelijk om meer als 1 maal zelfde velden in te voeren.

         $.ajax({
            url: "/api/coursecouple/" + courseid + "/" + studlijstid + "/" + teacherid,
             type: "POST",
             data: {'course': courseid, 'teacher': teacherid, 'studentlist': teacherid},
             success: function(data) {
                 //callback(true);
             },
             error: function(data) {
                 console.log('Failed to add new student');
                 //callback(false);
             }
         });
 }

/*
 * Load page of the table
 */
function loadTablePage(pagenr,course)
{
    $.getJSON('/api/getStudentGroupTeacherByCourseID/page/' + pagenr + '/' + course, function(data){

        /* Clear current table page */
        viewModel.clearTable();

        // Load table data
        $.each(data.data, function(i, item) {
            console.log("studid: " + item.studid + " en userid: " + item.userid);
           viewModel.addTableData(item.studid, item.userid , item.name , item.firstname + " " + item.lastname);
        });

        /* Let previous en next buttons work */
        if(data.prev == "none"){
            $('#pager-prev-btn').addClass('disabled');
        } else {
            $('#pager-prev-btn').removeClass('disabled');
            $('#pager-prev-btn a').click(function(){
                loadTablePage(data.prev);
            });
        }

        if(data.next == "none"){
            $('#pager-next-btn').addClass('disabled');
        } else {
            $('#pager-next-btn').removeClass('disabled');
            $('#pager-next-btn a').click(function(){
                loadTablePage(data.next);
            });
        }

        // Number of pager buttons
        var numItems = $('.pager-nr-btn').length;

        /* Calculate for the pager buttons */
        var lowPage = Math.floor(pagenr/numItems) + 1;

        $('.pager-nr-btn').each(function() {
            /* calculate current page number */
            var thispagenr = lowPage++;

            /* Add the page number */
            $(this).html('' + thispagenr + '');

            /* Add active class to current page */
            if(thispagenr == pagenr) {
                $(this).addClass('active');
            } else {
                $(this).removeClass('active');
            }

            /* Disable inactive classes and bind handlers to active classes */
            if(thispagenr > data.pagecount) {
                $(this).addClass('disabled');
            } else {
                /* Add click listener for button */
                $(this).click(function() {
                    loadTablePage(thispagenr);
                });
            }
        });
    });
}

/*
 * Delete item from table given the id.
 */
function deleteTableItem(id, tblOject) {
    showYesNoModal("Bent u zeker dat u dit item wil verwijderen? \r\n Let op: verwijderde items blijven in het systeem en kunnen weer actief gezet worden door een administrator. \r\n Gelieve de administrator te contacteren om een vak definitief te verwijderen.", function(val){
        if(val){
            //courseid = $('#projectHeader').attr("data-value");
            //studielijstid = "studid " + id.substr(0,id.indexOf('-'));
            //teacherid = "userid " + id.substr(id.indexOf('-')+1);

             $.ajax({
             url: "/api/setInactiveCourseStudlistCouple/" + $('#projectHeader').attr("data-value") + '/' + id.substr(0,id.indexOf('-')) + '/' + id.substr(id.indexOf('-')+1),
             type: "DELETE",
             success: function() {
             viewModel.tabledata.remove(tblOject);
             }
             });

            }
    });
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getCoupledLists();

    //Add Course members

    $('#addGroupForm').hide();

    $('#addCoursemembers').click(function() {
        $("#addGroupForm").show();
        $('#teachersComplete').autocomplete({ source: getAllTeachers() });
        $('#studentListComplete').autocomplete({ source: getAllStudentLists() });
    });

    $('#addGroupBtn').click(function() {
         addGroup($('#projectHeader').attr("data-value"), getTeacherid(), getGroupid());

        $('#studentListComplete').val("");
        $('#teachersComplete').val("");

        loadTablePage(1,$('#projectHeader').attr("data-value"));

        $('addGroupForm').hide();
    });

    $.getJSON('/api/currentuser', function(data) {
        viewModel.userId = data.id;
        userid = data.id;
        viewModel.getAvailableLists(data.id);
    });
    loadTablePage(1,$('#projectHeader').attr("data-value"));
}
<commit_msg>pagers doen werken.<commit_after>var userid;
//arrays gebruikt voor autocompletes en selecteren waarde hiervan.
var studentLists = [];
var studentListsid = [];
var teachers = []
var teachersid = []

function pageViewModel(gvm) {
    gvm.projecttitle = ko.observable("");
    gvm.userId = -1;
    gvm.coupledCount = 0;

    // Page specific i18n bindings
    gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
    gvm.pageHeader = ko.observable("Project");
    gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);

    gvm.addBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddBtn")}, gvm);

    gvm.addmoduleBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Addmodule");}, gvm);
    gvm.savePage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm);

    gvm.getProjectInfo = function() {
        $.getJSON('/api/project/' + $("#projectHeader").data('value'), function(data) {
            gvm.pageHeader(data[0].code + ' - ' + data[0].name);
        });
    };

    gvm.coupledLists = ko.observableArray([]);
    gvm.availableLists = ko.observableArray([]);

    gvm.addCoupledList = function(id, name) {
        // Push data
        var tblOject = {tid: id, tname: name};
        gvm.coupledLists.push(tblOject);

        $("#uncouplebtn-" + id).click(function(){
            showYesNoModal("Bent u zeker dat u dit item wil ontkoppelen?", function(val){
                if(val){
                    $.ajax({
                        url: '/api/project/' + $("#projectHeader").data('value') +'/studentlist/uncouple/' + id,
                        type: "DELETE",
                        success: function() {
                            gvm.coupledCount--;
                            viewModel.coupledLists.remove(tblOject);
                        }
                    });

                }
            });
        });
    }

    gvm.addAvailableLists = function(id, name) {
        var tblOject = {tid: id, tname: name};
        gvm.availableLists.push(tblOject);

        $("#couplebtn-" + id).click(function(){
            if(gvm.coupledCount == 0) {
                $.ajax({
                    url: '/api/project/' + $("#projectHeader").data('value') + '/studentlist/' + id,
                    type: "POST",
                    success: function() {
                        gvm.coupledCount++;
                        viewModel.coupledLists.push(tblOject);
                    }
                });
            } else {
                alert("list already coupled");
            }
        });
    }

    gvm.getCoupledLists = function() {
        $.getJSON('/api/project/' + $("#projectHeader").data('value') + '/coupledlists', function(data) {
            $.each(data, function(i, item) {
                gvm.coupledCount++;
                gvm.addCoupledList(item.id, item.name);
            });
        });
}

    gvm.getAvailableLists = function() {
        $.getJSON('/api/studentlists/' + gvm.userId, function(data) {
            $.each(data, function(i, item) {
                gvm.addAvailableLists(item.id, item.name);
            });
        });
    }

    // The table data observable array
    gvm.tabledata = ko.observableArray([]);

    // Add data to the table
    gvm.addTableData = function(studid, userid, studlist, name) {
        // Push data
        var tblOject = {tid: studid + "-" + userid, tstudlist: studlist, tteacher: name};
        gvm.tabledata.push(tblOject);

        // Attach delete handler to delete button
        $('#removebtn-' + studid + "-" + userid).bind('click', function(event, data){
            // Delete the table item
            deleteTableItem(studid + "-" + userid, tblOject);
            event.stopPropagation();
        });
            }

    gvm.clearTable = function() {
        gvm.tabledata.removeAll();
    }

 }

 function getAllTeachers() {
     teachers = [];
     teachersid = [];
     $.getJSON('/api/getteacherrapport', function(data) {
        $.each(data, function(i, item) {
            teachers.push(item.firstname + " " + item.lastname);
            teachersid.push(item.id);
        });
    });
    return teachers;
 }

function getAllStudentLists() {
    studentLists = [];
    studentListsid = [];
    $.getJSON('/api/studentlistsrapporten/' + userid, function (data) {
        $.each(data, function (i, item) {
            studentLists.push(item.name);
            studentListsid.push(item.id);
        });
    });
    return studentLists;
}

function getTeacherid() {

    // functie voor het opsplitsen van naam indien gewenst.
    // console.log(getTeacherID($('#teachersComplete').val().substr(0,$('#teachersComplete').val().indexOf(' ')), $('#teachersComplete').val().substr($('#teachersComplete').val().indexOf(' ')+1)));

    var i = 0;
    var teacher = 0;
    teachers.forEach(function(entry) {
        if (new String(entry).valueOf() == new String($('#teachersComplete').val()).valueOf()) {
            teacher = teachersid[i];
        }
        i+= 1;
    });
    return teacher
}

function getGroupid() {
    var i = 0;
    var studlijst;
    studentLists.forEach(function(entry) {
        if (new String(entry).valueOf() == new String($('#studentListComplete').val()).valueOf()) {
            studlijst = (studentListsid[i]);
        }
        i+= 1;
    });
    return studlijst;
}

 function addGroup(courseid, teacherid, studlijstid) {
     //TODO if teacher or studlijst = 0 dan bestaat deze niet!
     //TODO momenteel nog mogelijk om meer als 1 maal zelfde velden in te voeren.

         $.ajax({
            url: "/api/coursecouple/" + courseid + "/" + studlijstid + "/" + teacherid,
             type: "POST",
             data: {'course': courseid, 'teacher': teacherid, 'studentlist': teacherid},
             success: function(data) {
                 //callback(true);
             },
             error: function(data) {
                 console.log('Failed to add new student');
                 //callback(false);
             }
         });
 }

/*
 * Load page of the table
 */
function loadTablePage(pagenr,course)
{
    $.getJSON('/api/getStudentGroupTeacherByCourseID/page/' + pagenr + '/' + course, function(data){

        /* Clear current table page */
        viewModel.clearTable();

        // Load table data
        $.each(data.data, function(i, item) {
            console.log("studid: " + item.studid + " en userid: " + item.userid);
           viewModel.addTableData(item.studid, item.userid , item.name , item.firstname + " " + item.lastname);
        });

        console.log(data.prev);
        /* Let previous en next buttons work */
        if(data.prev == "none"){
            $('#pager-prev-btn').addClass('disabled');
        } else {
            $('#pager-prev-btn').removeClass('disabled');
            $('#pager-prev-btn a').click(function(){
                loadTablePage(data.prev);
            });
        }

        console.log(data.next);
        if(data.next == "none"){
            $('#pager-next-btn').addClass('disabled');
        } else {
            $('#pager-next-btn').removeClass('disabled');
            $('#pager-next-btn a').click(function(){
                loadTablePage(data.next);
            });
        }

        // Number of pager buttons
        var numItems = $('.pager-nr-btn').length;

        /* Calculate for the pager buttons */
        var lowPage = Math.floor(pagenr/numItems) + 1;

        $('.pager-nr-btn').each(function() {
            /* calculate current page number */
            var thispagenr = lowPage++;

            /* Add the page number */
            $(this).html('' + thispagenr + '');

            /* Add active class to current page */
            if(thispagenr == pagenr) {
                $(this).addClass('active');
            } else {
                $(this).removeClass('active');
            }

            /* Disable inactive classes and bind handlers to active classes */
            if(thispagenr > data.pagecount) {
                $(this).addClass('disabled');
            } else {
                /* Add click listener for button */
                $(this).click(function() {
                    loadTablePage(thispagenr);
                });
            }
        });
    });
}

/*
 * Delete item from table given the id.
 */
function deleteTableItem(id, tblOject) {
    showYesNoModal("Bent u zeker dat u dit item wil verwijderen? \r\n Let op: verwijderde items blijven in het systeem en kunnen weer actief gezet worden door een administrator. \r\n Gelieve de administrator te contacteren om een vak definitief te verwijderen.", function(val){
        if(val){
            //courseid = $('#projectHeader').attr("data-value");
            //studielijstid = "studid " + id.substr(0,id.indexOf('-'));
            //teacherid = "userid " + id.substr(id.indexOf('-')+1);

             $.ajax({
             url: "/api/setInactiveCourseStudlistCouple/" + $('#projectHeader').attr("data-value") + '/' + id.substr(0,id.indexOf('-')) + '/' + id.substr(id.indexOf('-')+1),
             type: "DELETE",
             success: function() {
             viewModel.tabledata.remove(tblOject);
             }
             });

            }
    });
}

function initPage() {
    viewModel.getProjectInfo();
    viewModel.getCoupledLists();

    //Add Course members

    $('#addGroupForm').hide();

    $('#addCoursemembers').click(function() {
        $("#addGroupForm").show();
        $('#teachersComplete').autocomplete({ source: getAllTeachers() });
        $('#studentListComplete').autocomplete({ source: getAllStudentLists() });
    });

    $('#addGroupBtn').click(function() {
         addGroup($('#projectHeader').attr("data-value"), getTeacherid(), getGroupid());

        $('#studentListComplete').val("");
        $('#teachersComplete').val("");

        loadTablePage(1,$('#projectHeader').attr("data-value"));

        $('addGroupForm').hide();
    });

    $.getJSON('/api/currentuser', function(data) {
        viewModel.userId = data.id;
        userid = data.id;
        viewModel.getAvailableLists(data.id);
    });
    loadTablePage(1,$('#projectHeader').attr("data-value"));
}
<|endoftext|>


<commit_before>goog.provide('recoil.db.DatabaseTest');

goog.require('goog.testing.jsunit');
goog.require('recoil.db.Query');
goog.require('recoil.db.DatabaseComms');
goog.require('recoil.db.ReadOnlyDatabase');
goog.require('recoil.db.ReadWriteDatabase');

goog.require('recoil.frp.Frp');

goog.setTestOnly('recoil.db.DatabaseTest');

var VAL_KEY = new recoil.db.BasicType(['key'], 'val');
var HELLO_KEY = new recoil.db.BasicType(['key'], 'hello');
var WORLD_KEY = new recoil.db.BasicType(['key'], 'world');
var LIST_ITEM_KEY = new recoil.db.BasicType(['id'], 'list');
var LIST_KEY = new recoil.db.BasicType([], 'list-item', new recoil.db.TypePath(LIST_ITEM_KEY, '[]'));

/**
 * @implements recoil.db.DatabaseComms
 * @constructor
 */
var MyDb = function(opt_delay) {
    this.values_ = {};
    this.delay_ = opt_delay ? [] :false ;
};

MyDb.prototype.makeKey = function (args) {
    return args;
};

/**
 *
 * @param data
 * @param oldData
 * @param successFunc
 * @param failFunc
 * @param id
 * @param var_parameters
 */
MyDb.prototype.set = function(data, oldData, successFunc, failFunc, id, key, var_parameters) {
    console.log("db data set", key, data);
    var me = this;
    if (this.delay_) {
        this.delay_.push (function() {
            me.values_[id.getData()][key] = data;
            successFunc(data);
        });
    }
    else {
        this.values_[id.getData()][key] = data;
        successFunc(data);

    }

};

/**
 *
 * @param success
 * @param failure
 * @param id
 * @param var_params
 */
MyDb.prototype.get = function(success, failure, id, key, options) {

    console.log("getting ",id, key);
    if (this.values_[id.getData()] === undefined) {
        this.values_[id.getData()] = {};
    }

    if (this.values_[id.getData()][key] === undefined) {
        if (id.getData() === 'list') {
            this.values_[id.getData()][key] = [1,2,3,4];
        }
        else {
            this.values_[id.getData()][key] = 'xxx' + id.getData() + "-" + key;
        }
    }
    var me = this;
    if (this.delay_) {
        this.delay_.push (function() {

            success(me.values_[id.getData()][key]);
        });
    }
    else {
        success(this.values_[id.getData()][key]);
    }
};

MyDb.prototype.getList = function (successFunction, failFunction, id, query, options) {

};

MyDb.prototype.process = function () {
    this.delay_.pop()();
};

MyDb.prototype.processQueueSize = function () {
    return this.delay_.length;
};
function getVals(vals) {
    var res = [];
    var i = 0;

    if (typeof vals === 'object') {
        for (var key in vals) {
            if (vals.hasOwnProperty(key)) {
                res[i] = vals[key];
                i++;
            }
        }
    }

    return res;
}

/**
 *
 * @param {recoil.db.BasicKey} key
 * @return {*}
 */
MyDb.prototype.getValue = function(key, subKey) {
    return this.values_[key.getData()][subKey];
};

function testGetSame() {
    var frp = new recoil.frp.Frp();
    var coms = new MyDb();
    var readwriteDb = new recoil.db.ReadWriteDatabase(frp, coms);

    var a1 = readwriteDb.get(HELLO_KEY,'a');
    var a2 = readwriteDb.get(HELLO_KEY,'a');
    var c1 = readwriteDb.get(HELLO_KEY,'c');
    var b1 = readwriteDb.get(WORLD_KEY,'a');

    frp.attach(a1);
    frp.attach(a2);
    frp.attach(c1);
    frp.attach(b1);

    assertEquals('xxxhello-a', a1.unsafeMetaGet().get());
    assertEquals('xxxhello-a', a2.unsafeMetaGet().get());
    assertEquals('xxxhello-c', c1.unsafeMetaGet().get());
    assertEquals('xxxworld-a', b1.unsafeMetaGet().get());

    frp.accessTrans(function() {
        a1.set('goodbye');
    }, a1);

    assertEquals('goodbye', a1.unsafeMetaGet().get());
    assertEquals('goodbye', a2.unsafeMetaGet().get());
    assertEquals('xxxhello-c', c1.unsafeMetaGet().get());
    assertEquals('xxxworld-a', b1.unsafeMetaGet().get());

}

function testGetList () {
    var frp = new recoil.frp.Frp();
    var coms = new MyDb(true);
    var db = new recoil.db.ReadWriteDatabase(frp, coms);

    var a = db.get('a',[1]);
    var b = db.get('a',[3]);
    frp.attach(a);
    var list = db.getList('a', recoil.db.Query.True);
    frp.attach(list);

    assertEquals('xxxa', a.unsafeMetaGet().get());
    assertEquals('xxxa', list.unsafeMetaGet().get()[0]);
    assertEquals('xxxa', list.unsafeMetaGet().get()[1]);
    assertEquals('xxxa', list.unsafeMetaGet().get()[2]);

    frp.accessTrans(function () {
        a.set('a1');
    },a);

    assertEquals('a1', a.unsafeMetaGet().get());
    assertEquals('xxxa', list.unsafeMetaGet().get()[0]);
    assertEquals('a1', list.unsafeMetaGet().get()[1]);
    assertEquals('xxxa', list.unsafeMetaGet().get()[2]);

    var newList = goog.array.clone(list.unsafeMetaGet().get());
    newList.push('b');

    frp.accessTrans(function () {
        list.set(newList);
    },list);

    frp.attach(b);

    assertEquals('a1', a.unsafeMetaGet().get());
    assertEquals('b', b.unsafeMetaGet().get());
    assertEquals('xxxa', list.unsafeMetaGet().get()[0]);
    assertEquals('a1', list.unsafeMetaGet().get()[1]);
    assertEquals('xxxa', list.unsafeMetaGet().get()[2]);
    assertEquals('b', list.unsafeMetaGet().get()[3]);

    //check it has been sent to the database
    assertTrue("not implemented yet, insert, delete",false);
}
function testSet() {
    var frp = new recoil.frp.Frp();
    var coms = new MyDb(true);
    var readwriteDb = new recoil.db.ReadWriteDatabase(frp, coms);
    var readDb = new recoil.db.ReadOnlyDatabase(frp, readwriteDb);
    var readwriteB = readwriteDb.get(HELLO_KEY,'a');
    var readB = readDb.get(HELLO_KEY,'a');

    assertFalse(readB.unsafeMetaGet().ready());
    frp.attach(readB);
    assertFalse(readB.unsafeMetaGet().ready());
    coms.process();
    assertTrue(readB.unsafeMetaGet().ready());
    assertEquals('xxxhello-a', readB.unsafeMetaGet().get());

    assertFalse(readwriteB.unsafeMetaGet().ready());
    frp.attach(readwriteB);
    assertTrue(readwriteB.unsafeMetaGet().ready());

    //need to put compare in entity in object_manager

    assertEquals('xxxhello-a', readwriteB.unsafeMetaGet().get());

    frp.accessTrans(function() {
        readwriteB.set('goodbye');
    }, readwriteB);

    assertEquals('goodbye', readwriteB.unsafeMetaGet().get());
    assertEquals('xxxhello-a', readB.unsafeMetaGet().get());
    coms.process();
    assertEquals('goodbye', readwriteB.unsafeMetaGet().get());
    assertEquals('goodbye', readB.unsafeMetaGet().get());
    assertEquals('goodbye', coms.getValue(HELLO_KEY,'a'));

    // Writing to the readwritedb the change should be reflected on the readdb and
    // write to the readdb and the change should not be on the readwritedb
    frp.accessTrans(function() {
        readwriteB.set('boo');
        readB.set('smokey');
    }, readwriteB, readB);

    coms.process();
    assertEquals(0, coms.processQueueSize());
    assertEquals('boo', readB.unsafeMetaGet().get());
    assertEquals('boo', readwriteB.unsafeMetaGet().get());

}

function testDelayed () {
    var frp = new recoil.frp.Frp();
    var tm = frp.tm();
    var coms = new MyDb();

    var readDb = new recoil.db.ReadOnlyDatabase(frp, coms);
    var readwriteDb = new recoil.db.ReadWriteDatabase(frp, coms, readDb);
    var delayedDb = new recoil.db.DelayedDatabase(frp, readwriteDb);

    var val1 =  delayedDb.get(VAL_KEY,"key1");
    var val2 =  delayedDb.get(VAL_KEY,"key1");

    tm.attach(val1);
    tm.attach(val2);

    assertEquals("xxxval-key1", val2.unsafeMetaGet().get());

    frp.accessTrans(function () {
        val1.set(0);
    }, val1);

    assertEquals(0, val2.unsafeMetaGet().get());

    var val3 =  delayedDb.get(VAL_KEY,"key1");
    tm.attach(val3);

    assertEquals(0, val3.unsafeMetaGet().get());

    assertEquals("xxxval-key1",coms.getValue(VAL_KEY,"key1"));

    delayedDb.flush();

    assertEquals(0,coms.getValue(VAL_KEY,"key1"));

    frp.accessTrans(function () {
        val1.set(1);
    }, val1);

    assertEquals(0,coms.getValue(VAL_KEY,"key1"));
    assertEquals(1, val3.unsafeMetaGet().get());

    delayedDb.clear();

    assertEquals(0,coms.getValue(VAL_KEY,"key1"));
    assertEquals(0, val3.unsafeMetaGet().get());

}

function testGetList ()  {
    var frp = new recoil.frp.Frp();
    var coms = new MyDb(false);
    var db = new recoil.db.ReadWriteDatabase(frp, coms);
    var listB = db.get(LIST_KEY,'List');
    var listItemB = db.get(LIST_ITEM_KEY, 1);

    frp.attach(listB);
    frp.attach(listItemB);

    assertEquals([1,2,3,4], listB.unsafeMetaGet().get());
    assertEquals("test", listItemB.unsafeMetaGet().get());

}

<commit_msg>[1] add more test for testGetList<commit_after>goog.provide('recoil.db.DatabaseTest');

goog.require('goog.testing.jsunit');
goog.require('recoil.db.Query');
goog.require('recoil.db.DatabaseComms');
goog.require('recoil.db.ReadOnlyDatabase');
goog.require('recoil.db.ReadWriteDatabase');

goog.require('recoil.frp.Frp');

goog.setTestOnly('recoil.db.DatabaseTest');

var VAL_KEY = new recoil.db.BasicType(['key'], 'val');
var HELLO_KEY = new recoil.db.BasicType(['key'], 'hello');
var WORLD_KEY = new recoil.db.BasicType(['key'], 'world');
var LIST_ITEM_KEY = new recoil.db.BasicType(['id'], 'list-item');
var LIST_KEY = new recoil.db.BasicType([], 'list', new recoil.db.TypePath(LIST_ITEM_KEY, '[]'));

/**
 * @implements recoil.db.DatabaseComms
 * @constructor
 */
var MyDb = function(opt_delay) {
    this.values_ = {};
    this.delay_ = opt_delay ? [] :false ;
};

MyDb.prototype.makeKey = function (args) {
    return args;
};

/**
 *
 * @param data
 * @param oldData
 * @param successFunc
 * @param failFunc
 * @param id
 * @param var_parameters
 */
MyDb.prototype.set = function(data, oldData, successFunc, failFunc, id, key, var_parameters) {
    console.log("db data set", key, data);
    var me = this;
    if (this.delay_) {
        this.delay_.push (function() {
            me.values_[id.getData()][key] = data;
            successFunc(data);
        });
    }
    else {
        this.values_[id.getData()][key] = data;
        successFunc(data);

    }

};

/**
 *
 * @param success
 * @param failure
 * @param id
 * @param var_params
 */
MyDb.prototype.get = function(success, failure, id, key, options) {

    console.log("getting ",id, key);
    if (this.values_[id.getData()] === undefined) {
        this.values_[id.getData()] = {};
    }

    if (this.values_[id.getData()][key] === undefined) {
        if (id.getData() === 'list') {
            this.values_[id.getData()][key] = [1,2,3,4];
        }
        else {
            this.values_[id.getData()][key] = 'xxx' + id.getData() + "-" + key;
        }
    }
    var me = this;
    if (this.delay_) {
        this.delay_.push (function() {

            success(me.values_[id.getData()][key]);
        });
    }
    else {
        success(this.values_[id.getData()][key]);
    }
};

MyDb.prototype.process = function () {
    this.delay_.pop()();
};

MyDb.prototype.processQueueSize = function () {
    return this.delay_.length;
};
function getVals(vals) {
    var res = [];
    var i = 0;

    if (typeof vals === 'object') {
        for (var key in vals) {
            if (vals.hasOwnProperty(key)) {
                res[i] = vals[key];
                i++;
            }
        }
    }

    return res;
}

/**
 *
 * @param {recoil.db.BasicKey} key
 * @return {*}
 */
MyDb.prototype.getValue = function(key, subKey) {
    return this.values_[key.getData()][subKey];
};

function testGetSame() {
    var frp = new recoil.frp.Frp();
    var coms = new MyDb();
    var readwriteDb = new recoil.db.ReadWriteDatabase(frp, coms);

    var a1 = readwriteDb.get(HELLO_KEY,'a');
    var a2 = readwriteDb.get(HELLO_KEY,'a');
    var c1 = readwriteDb.get(HELLO_KEY,'c');
    var b1 = readwriteDb.get(WORLD_KEY,'a');

    frp.attach(a1);
    frp.attach(a2);
    frp.attach(c1);
    frp.attach(b1);

    assertEquals('xxxhello-a', a1.unsafeMetaGet().get());
    assertEquals('xxxhello-a', a2.unsafeMetaGet().get());
    assertEquals('xxxhello-c', c1.unsafeMetaGet().get());
    assertEquals('xxxworld-a', b1.unsafeMetaGet().get());

    frp.accessTrans(function() {
        a1.set('goodbye');
    }, a1);

    assertEquals('goodbye', a1.unsafeMetaGet().get());
    assertEquals('goodbye', a2.unsafeMetaGet().get());
    assertEquals('xxxhello-c', c1.unsafeMetaGet().get());
    assertEquals('xxxworld-a', b1.unsafeMetaGet().get());

}

function testSet() {
    var frp = new recoil.frp.Frp();
    var coms = new MyDb(true);
    var readwriteDb = new recoil.db.ReadWriteDatabase(frp, coms);
    var readDb = new recoil.db.ReadOnlyDatabase(frp, readwriteDb);
    var readwriteB = readwriteDb.get(HELLO_KEY,'a');
    var readB = readDb.get(HELLO_KEY,'a');

    assertFalse(readB.unsafeMetaGet().ready());
    frp.attach(readB);
    assertFalse(readB.unsafeMetaGet().ready());
    coms.process();
    assertTrue(readB.unsafeMetaGet().ready());
    assertEquals('xxxhello-a', readB.unsafeMetaGet().get());

    assertFalse(readwriteB.unsafeMetaGet().ready());
    frp.attach(readwriteB);
    assertTrue(readwriteB.unsafeMetaGet().ready());

    //need to put compare in entity in object_manager

    assertEquals('xxxhello-a', readwriteB.unsafeMetaGet().get());

    frp.accessTrans(function() {
        readwriteB.set('goodbye');
    }, readwriteB);

    assertEquals('goodbye', readwriteB.unsafeMetaGet().get());
    assertEquals('xxxhello-a', readB.unsafeMetaGet().get());
    coms.process();
    assertEquals('goodbye', readwriteB.unsafeMetaGet().get());
    assertEquals('goodbye', readB.unsafeMetaGet().get());
    assertEquals('goodbye', coms.getValue(HELLO_KEY,'a'));

    // Writing to the readwritedb the change should be reflected on the readdb and
    // write to the readdb and the change should not be on the readwritedb
    frp.accessTrans(function() {
        readwriteB.set('boo');
        readB.set('smokey');
    }, readwriteB, readB);

    coms.process();
    assertEquals(0, coms.processQueueSize());
    assertEquals('boo', readB.unsafeMetaGet().get());
    assertEquals('boo', readwriteB.unsafeMetaGet().get());

}

function testDelayed () {
    var frp = new recoil.frp.Frp();
    var tm = frp.tm();
    var coms = new MyDb();

    var readDb = new recoil.db.ReadOnlyDatabase(frp, coms);
    var readwriteDb = new recoil.db.ReadWriteDatabase(frp, coms, readDb);
    var delayedDb = new recoil.db.DelayedDatabase(frp, readwriteDb);

    var val1 =  delayedDb.get(VAL_KEY,"key1");
    var val2 =  delayedDb.get(VAL_KEY,"key1");

    tm.attach(val1);
    tm.attach(val2);

    assertEquals("xxxval-key1", val2.unsafeMetaGet().get());

    frp.accessTrans(function () {
        val1.set(0);
    }, val1);

    assertEquals(0, val2.unsafeMetaGet().get());

    var val3 =  delayedDb.get(VAL_KEY,"key1");
    tm.attach(val3);

    assertEquals(0, val3.unsafeMetaGet().get());

    assertEquals("xxxval-key1",coms.getValue(VAL_KEY,"key1"));

    delayedDb.flush();

    assertEquals(0,coms.getValue(VAL_KEY,"key1"));

    frp.accessTrans(function () {
        val1.set(1);
    }, val1);

    assertEquals(0,coms.getValue(VAL_KEY,"key1"));
    assertEquals(1, val3.unsafeMetaGet().get());

    delayedDb.clear();

    assertEquals(0,coms.getValue(VAL_KEY,"key1"));
    assertEquals(0, val3.unsafeMetaGet().get());

}

function testGetList ()  {
    var frp = new recoil.frp.Frp();
    var coms = new MyDb(false);
    var db = new recoil.db.ReadWriteDatabase(frp, coms);
    var listB = db.get(LIST_KEY,'List');
    var listItem0B = db.get(LIST_ITEM_KEY, 0);
    var listItem1B = db.get(LIST_ITEM_KEY, 1);
    var listItem2B = db.get(LIST_ITEM_KEY, 2);
    var listItem3B = db.get(LIST_ITEM_KEY, 3);

    frp.attach(listB);
    frp.attach(listItem0B);
    frp.attach(listItem1B);
    frp.attach(listItem2B);
    frp.attach(listItem3B);

    assertArrayEquals([1,2,3,4], listB.unsafeMetaGet().get());
    //currently there is no code to register subitems to the main list so
    //this is expected to fail
    assertEquals(1, listItem0B.unsafeMetaGet().get());
    assertEquals(2, listItem1B.unsafeMetaGet().get());
    assertEquals(3, listItem2B.unsafeMetaGet().get());
    assertEquals(4, listItem3B.unsafeMetaGet().get());

    frp.accessTrans(function () {
        listB.set([11,12,13,14]);
    });

    assertArrayEquals([1,2,3,4], listB.unsafeMetaGet().get());
    assertEquals(11, listItem0B.unsafeMetaGet().get());
    assertEquals(12, listItem1B.unsafeMetaGet().get());
    assertEquals(13, listItem2B.unsafeMetaGet().get());
    assertEquals(14, listItem3B.unsafeMetaGet().get());

    frp.accessTrans(function () {
        listB.set([11,12,13]);
    });

    assertEquals(11, listItem0B.unsafeMetaGet().get());
    assertEquals(12, listItem1B.unsafeMetaGet().get());
    assertEquals(13, listItem2B.unsafeMetaGet().get());
    assertEquals(notReady, listItem3B.unsafeMetaGet());

    // TODO also test geting the sub item first then the list

}

<|endoftext|>