<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);

    // 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 niet mogelijk om meer als 1 maal zelfde velden in te voeren maar geen foutboodschap

         $.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) {

           viewModel.addTableData(item.studid, item.userid , item.name , item.firstname + " " + item.lastname, item.id);

        });

        //TODO pagers doen werken
        //Momenteel wordt enkel alles geselecteerd met LIMIT 0,20
        //Maar de pagers zelf blijven dissabled waardoor het ook niet mogelijk is LIMIT 21,40 op te vragen.
        /* 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, course);
                });
            }
        });
    });
}

/*
 * 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() {
    $('#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;
    });
    loadTablePage(1);
}
<commit_msg>change broke page, undoing<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);

    // 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 niet mogelijk om meer als 1 maal zelfde velden in te voeren maar geen foutboodschap

         $.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) {

           viewModel.addTableData(item.studid, item.userid , item.name , item.firstname + " " + item.lastname, item.id);

        });

        //TODO pagers doen werken
        //Momenteel wordt enkel alles geselecteerd met LIMIT 0,20
        //Maar de pagers zelf blijven dissabled waardoor het ook niet mogelijk is LIMIT 21,40 op te vragen.
        /* 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, course);
                });
            }
        });
    });
}

/*
 * 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() {
    $('#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;
    });
    loadTablePage(1,$('#projectHeader').attr("data-value"));
}
<|endoftext|>


<commit_before>import xpb from 'xpath-builder';

function XPaths () {}
XPaths.prototype = xpb.dsl();

export default class Finder extends XPaths {
  constructor (client) {
    super();
    this.client = client;
  }

  card (cardTitle) {
    let nth = cardTitle.match(/(\d+)(st|nd|rd|th)?/);
    if (nth) {
      nth = parseInt(nth[1], 10) - 1;
      return this.client.$$('.card').then(cards => cards[nth]);
    }

    const xpath = this.descendant('div')
      .where(this.attr('class').equals('card'))
      .where(
        this.descendant('div')
          .where(this.attr('class').equals('card-header'))
          .where(
            this.descendant('span')
              .where(this.text().equals(cardTitle))
          )
      ).toString();

    return this.client.$(xpath);
  }

  cardHeaderInputBox (cardTitle) {
    const xpath = this.descendant('div')
      .where(this.attr('class').equals('card-header'))
      .descendant('input')
      .where(this.attr('type').equals('text'))
      .toString();

    return this.card(cardTitle).$(xpath);
  }

  cardHeaderButton (cardTitle, glyph) {
    const xpath = this.descendant('div')
      .where(this.attr('class').equals('card-header'))
      .descendant('button')
      .descendant('i')
      .where(this.attr('class').contains(`fa-${glyph}`))
      .toString();

    return this.card(cardTitle).$(xpath);
  }

  cardHeaderInputBoxButton (cardTitle, glyph) {
    const xpath = this.nextSibling('span')
      .descendant('button')
      .where(this.attr('type').equals('submit'))
      .descendant('i')
      .where(this.attr('class').contains(`fa-${glyph}`))
      .toString();

    return this.cardHeaderInputBox(cardTitle).$(xpath);
  }

  cardBlockItemList (cardTitle) {
    const xpath = this.descendant('div')
      .where(this.attr('class').equals('card-block'))
      .descendant('ul')
      .toString();

    return this.card(cardTitle).$(xpath);
  }

  cardBlockItem (cardTitle, itemTitle) {
    const xpath = this.descendant('li')
      .where(
        this.descendant('span')
          .where(this.text().equals(itemTitle))
      )
      .toString();

    return this.cardBlockItemList(cardTitle).$(xpath);
  }

  cardBlockInputBox (cardTitle, itemTitle) {
    const xpath = this.descendant('li')
      .descendant('input')
      .where(this.attr('type').equals('text'))
      .where(this.attr('value').equals(itemTitle))
      .toString();

    return this.cardBlockItemList(cardTitle).$(xpath);
  }

  cardBlockInputBoxButton (cardTitle, itemTitle, glyph) {
    const xpath = this.nextSibling('span')
      .descendant('button')
      .where(this.attr('type').equals('submit'))
      .descendant('i')
      .where(this.attr('class').contains(`fa-${glyph}`))
      .toString();

    return this.cardBlockInputBox(cardTitle, itemTitle).$(xpath);
  }

  cardBlockItemCheckBox (cardTitle, itemTitle, glyph) {
    const xpath = this.descendant('input')
      .where(this.attr('type').equals('checkbox'))
      .where(
        this.nextSibling('label')
          .where(this.attr('class').contains(`fa-${glyph}`))
      )
      .toString();

    return this.cardBlockItem(cardTitle, itemTitle).$(xpath);
  }

  cardBlockItemCheckBoxLabel (cardTitle, itemTitle, glyph) {
    const xpath = this.descendant('input')
      .where(this.attr('type').equals('checkbox'))
      .nextSibling('label')
      .where(this.attr('class').contains(`fa-${glyph}`))
      .toString();

    return this.cardBlockItem(cardTitle, itemTitle).$(xpath);
  }

  cardBlockItemButton (cardTitle, itemTitle, glyph) {
    const xpath = this.descendant('button')
      .descendant('i')
      .where(this.attr('class').contains(`fa-${glyph}`))
      .toString();

    return this.cardBlockItem(cardTitle, itemTitle).$(xpath);
  }
}

export const methods = Object.getOwnPropertyNames(Finder.prototype);
<commit_msg>Fixed bad matching for cardName<commit_after>import xpb from 'xpath-builder';

function XPaths () {}
XPaths.prototype = xpb.dsl();

export default class Finder extends XPaths {
  constructor (client) {
    super();
    this.client = client;
  }

  card (cardTitle) {
    let nth = cardTitle.match(/^(\d+)(st|nd|rd|th)?$/);
    if (nth) {
      nth = parseInt(nth[1], 10) - 1;
      return this.client.$$('.card').then(cards => cards[nth]);
    }

    const xpath = this.descendant('div')
      .where(this.attr('class').equals('card'))
      .where(
        this.descendant('div')
          .where(this.attr('class').equals('card-header'))
          .where(
            this.descendant('span')
              .where(this.text().equals(cardTitle))
          )
      ).toString();

    return this.client.$(xpath);
  }

  cardHeaderInputBox (cardTitle) {
    const xpath = this.descendant('div')
      .where(this.attr('class').equals('card-header'))
      .descendant('input')
      .where(this.attr('type').equals('text'))
      .toString();

    return this.card(cardTitle).$(xpath);
  }

  cardHeaderButton (cardTitle, glyph) {
    const xpath = this.descendant('div')
      .where(this.attr('class').equals('card-header'))
      .descendant('button')
      .descendant('i')
      .where(this.attr('class').contains(`fa-${glyph}`))
      .toString();

    return this.card(cardTitle).$(xpath);
  }

  cardHeaderInputBoxButton (cardTitle, glyph) {
    const xpath = this.nextSibling('span')
      .descendant('button')
      .where(this.attr('type').equals('submit'))
      .descendant('i')
      .where(this.attr('class').contains(`fa-${glyph}`))
      .toString();

    return this.cardHeaderInputBox(cardTitle).$(xpath);
  }

  cardBlockItemList (cardTitle) {
    const xpath = this.descendant('div')
      .where(this.attr('class').equals('card-block'))
      .descendant('ul')
      .toString();

    return this.card(cardTitle).$(xpath);
  }

  cardBlockItem (cardTitle, itemTitle) {
    const xpath = this.descendant('li')
      .where(
        this.descendant('span')
          .where(this.text().equals(itemTitle))
      )
      .toString();

    return this.cardBlockItemList(cardTitle).$(xpath);
  }

  cardBlockInputBox (cardTitle, itemTitle) {
    const xpath = this.descendant('li')
      .descendant('input')
      .where(this.attr('type').equals('text'))
      .where(this.attr('value').equals(itemTitle))
      .toString();

    return this.cardBlockItemList(cardTitle).$(xpath);
  }

  cardBlockInputBoxButton (cardTitle, itemTitle, glyph) {
    const xpath = this.nextSibling('span')
      .descendant('button')
      .where(this.attr('type').equals('submit'))
      .descendant('i')
      .where(this.attr('class').contains(`fa-${glyph}`))
      .toString();

    return this.cardBlockInputBox(cardTitle, itemTitle).$(xpath);
  }

  cardBlockItemCheckBox (cardTitle, itemTitle, glyph) {
    const xpath = this.descendant('input')
      .where(this.attr('type').equals('checkbox'))
      .where(
        this.nextSibling('label')
          .where(this.attr('class').contains(`fa-${glyph}`))
      )
      .toString();

    return this.cardBlockItem(cardTitle, itemTitle).$(xpath);
  }

  cardBlockItemCheckBoxLabel (cardTitle, itemTitle, glyph) {
    const xpath = this.descendant('input')
      .where(this.attr('type').equals('checkbox'))
      .nextSibling('label')
      .where(this.attr('class').contains(`fa-${glyph}`))
      .toString();

    return this.cardBlockItem(cardTitle, itemTitle).$(xpath);
  }

  cardBlockItemButton (cardTitle, itemTitle, glyph) {
    const xpath = this.descendant('button')
      .descendant('i')
      .where(this.attr('class').contains(`fa-${glyph}`))
      .toString();

    return this.cardBlockItem(cardTitle, itemTitle).$(xpath);
  }
}

export const methods = Object.getOwnPropertyNames(Finder.prototype);
<|endoftext|>


<commit_before>/**
 * Created by xubt on 5/26/16.
 */
kanbanApp.factory('boardsService', ['$http', '$q', 'httpServices',
    function ($http, $q, httpServices) {
        return {
            boardsLink: '',
            load: function (_boardsLink) {
                return httpServices.send({
                    method: 'GET',
                    url: _boardsLink
                });
            },
            loadBoardByLink: function (_boardLink) {
                var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
                $http({
                    method: 'GET',
                    url: _boardLink
                }).success(function (data, status, headers, config) {
                    deferred.resolve(data);  // 声明执行成功，即http请求数据成功，可以返回数据了
                }).error(function (data, status, headers, config) {
                    deferred.reject(data);   // 声明执行失败，即服务器返回错误
                });
                return deferred.promise;   // 返回承诺，这里并不是最终数据，而是访问最终数据的API
            },
            create: function (_board) {
                return httpServices.send({
                    method: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(_board),
                    url: this.boardsLink
                });
            }
        };
    }]);
<commit_msg>Adding deleteBoard method.<commit_after>/**
 * Created by xubt on 5/26/16.
 */
kanbanApp.factory('boardsService', ['$http', '$q', 'httpServices',
    function ($http, $q, httpServices) {
        return {
            boardsLink: '',
            load: function (_boardsLink) {
                return httpServices.send({
                    method: 'GET',
                    url: _boardsLink
                });
            },
            loadBoardByLink: function (_boardLink) {
                var deferred = $q.defer(); // 声明延后执行，表示要去监控后面的执行
                $http({
                    method: 'GET',
                    url: _boardLink
                }).success(function (data, status, headers, config) {
                    deferred.resolve(data);  // 声明执行成功，即http请求数据成功，可以返回数据了
                }).error(function (data, status, headers, config) {
                    deferred.reject(data);   // 声明执行失败，即服务器返回错误
                });
                return deferred.promise;   // 返回承诺，这里并不是最终数据，而是访问最终数据的API
            },
            create: function (_board) {
                return httpServices.send({
                    method: 'POST',
                    contentType: 'application/json',
                    data: JSON.stringify(_board),
                    url: this.boardsLink
                });
            },
            update: function (_board) {
                return httpServices.send({
                    method: 'PUT',
                    contentType: 'application/json',
                    data: JSON.stringify(_board),
                    url: _board._links.self.href
                });
            },
            deleteBoard: function (_board) {
                return httpServices.send({
                    method: 'DELETE',
                    url: _board._links.self.href
                });
            }
        };
    }]);
<|endoftext|>


<commit_before>/*******************************************************************************
 * Copyright 2012 University of Southern California
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * This code was developed by the Information Integration Group as part
 * of the Karma project at the Information Sciences Institute of the
 * University of Southern California.  For more information, publications,
 * and related projects, please see: http://www.isi.edu/integration
 ******************************************************************************/

var D3ModelManager = (function() {
	var instance = null;

	function PrivateConstructor() {
		var models;

		function init() {
			models = [];

			window.onscroll = function(event){
				for (var worksheetId in models) {
					models[worksheetId].onscroll(event);
				}
			};

			window.onresize = function(event) {
				for (var worksheetId in models) {
					models[worksheetId].onresize(event);
				}
			};
		}

		function getModelManager(worksheetId, layoutElement, layoutClass, width, force) {
			if(models[worksheetId]) {
				//This is temporary. Comment this out when the D3ModelLayout can handle updates.
				if(force)
					models[worksheetId] = new D3ModelLayout(layoutElement, layoutClass, width, worksheetId);
			} else {
				models[worksheetId] = new D3ModelLayout(layoutElement, layoutClass, width, worksheetId);
			}
			return models[worksheetId];
		};

		function displayModel(json) {
			var worksheetId = json["worksheetId"];
			var mainWorksheetDiv = $("div#" + worksheetId);
			var wsVisible = mainWorksheetDiv.data("worksheetVisible");
			if (!wsVisible) {
				return;
			}

			var w = 0;
			var mainWorksheetDiv = $("div#" + worksheetId);
			var layoutElement = "div#svgDiv_" + worksheetId;

			if ($(mainWorksheetDiv).data("svgVis") != null) {
				//$(layoutElement).remove();
			} else {
				$("<div>").attr("id", "svgDiv_" + worksheetId).addClass("svg-model").insertBefore('div#' + worksheetId + " > div.table-container");
			}

			if (w == 0)
				w = $("div#" + worksheetId).width();

			var tableLeftOffset = mainWorksheetDiv.offset().left;

			var alignJson;
			var nodesMap;
			if(json.alignObject) {
				var maxX = 0;
				alignJson = json.alignObject;
				nodesMap = [];
				$.each(alignJson.anchors, function(index, node) {
					var hNodeId = node["hNodeId"];
					var columnNode = $("td#" + hNodeId);
					var leftX = $(columnNode).offset().left - tableLeftOffset;
					node.xPos = leftX + ($(columnNode).width()/2);
					var nodeMax = leftX + $(columnNode).width();
					if(nodeMax > maxX)
						maxX = nodeMax;
					nodesMap[node["id"]] = node;
				});
				alignJson.width = maxX + 100;

				$.each(alignJson.nodes, function(index, node) {
					nodesMap[node["id"]] = node;
				});

				$.each(alignJson.links, function(index, link) {
					if(link.label == "classLink")
						link.label = "uri";
				});
			} else {
				alignJson = json;
			}
			var layout;
			try {
				layout = getModelManager(worksheetId, layoutElement, "col-sm-10", w);
				console.log(JSON.stringify(alignJson));
				layout.generateLayoutForJson(alignJson);
			} catch(err) {
				console.log("Got exception in D3ModelLayout:" + err.message);
				console.log(err.stack);
				//Try again generating a new D3Layout
				$(layoutElement).empty();
				layout = getModelManager(worksheetId, layoutElement, "col-sm-10", w, true);
				console.log(JSON.stringify(alignJson));
				layout.generateLayoutForJson(alignJson);
			}
			var alignmentId = json["alignmentId"];
			$(mainWorksheetDiv).data("alignmentId", alignmentId);
			$(mainWorksheetDiv).data("svgVis", {"svgVis":true});

			layout.setNodeClickListener(function(d, event) {
				console.log("This function is called when the node is clicked");
				if (d["nodeType"] == "InternalNode" || d["nodeType"] == "LiteralNode") {
					var nodeCategory = "";
					if (d.isForcedByUser)
						nodeCategory = "forcedAdded";
					var id;
					if(d.nodeId)
						id = d.nodeId;
					else
						id = d.id;
					ClassDropdownMenu.getInstance().show(worksheetId, id, d.label, d.nodeDomain, d.nodeDomain, nodeCategory,
							alignmentId, d.nodeType, d.isUri, event);

				}

			});

			layout.setLinkClickListener(function(d, event) {
				console.log("This function is called when the link is clicked");
				var sourceObj, targetObj;
				if(nodesMap) {
					sourceObj = nodesMap[d.source];
					targetObj = nodesMap[d.target];
				} else {
					sourceObj = d.source;
					targetObj = d.target;
				}
				PropertyDropdownMenu.getInstance().show(
						worksheetId,
						alignmentId,
						d.id,
						d.linkUri,
						d.sourceNodeId,
						sourceObj.nodeType,
						sourceObj.label,
						sourceObj.nodeDomain,
						d.sourceNodeId,
						d.source.isUri,
						d.targetNodeId,
						targetObj.nodeType,
						targetObj.label,
						targetObj.nodeDomain,
						d.targetNodeId,
						d.target.isUri,
						event);
			});
		};

		function refreshModel(worksheetId) {
			var mainWorksheetDiv = $("div#" + worksheetId);
			var svg = $(mainWorksheetDiv).data("svgVis");
			if (svg) {
				var alignmentId = $(mainWorksheetDiv).data("alignmentId");
				console.log("RefreshSVGAlignmentCommand: " + worksheetId, alignmentId);
				var info = generateInfoObject(worksheetId, "", "RefreshSVGAlignmentCommand");
				info["alignmentId"] = alignmentId;
				showLoading(worksheetId);
				sendRequest(info, worksheetId);
			}
		};

		function printModel(worksheetId) {
			var layout = getModelManager(worksheetId);
			if(layout.printExtented) {
				showLoading(worksheetId);
				layout.printExtented(3, function() {
					hideLoading(worksheetId);
				});
			} else {
				alert("The Model Manager does not support printing");
			}
		}

		return { //Return back the public methods
			init: init,
			getModelManager: getModelManager,
			displayModel: displayModel,
			refreshModel: refreshModel,
			printModel: printModel
		};
	};

	function getInstance() {
		if (!instance) {
			instance = new PrivateConstructor();
			instance.init();
		}
		return instance;
	}

	return {
		getInstance: getInstance
	};

})();

<commit_msg>bug fix<commit_after>/*******************************************************************************
 * Copyright 2012 University of Southern California
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * This code was developed by the Information Integration Group as part
 * of the Karma project at the Information Sciences Institute of the
 * University of Southern California.  For more information, publications,
 * and related projects, please see: http://www.isi.edu/integration
 ******************************************************************************/

var D3ModelManager = (function() {
	var instance = null;

	function PrivateConstructor() {
		var models;

		function init() {
			models = [];

			window.onscroll = function(event){
				for (var worksheetId in models) {
					models[worksheetId].onscroll(event);
				}
			};

			window.onresize = function(event) {
				for (var worksheetId in models) {
					models[worksheetId].onresize(event);
				}
			};
		}

		function getModelManager(worksheetId, layoutElement, layoutClass, width, force) {
			if(models[worksheetId]) {
				//This is temporary. Comment this out when the D3ModelLayout can handle updates.
				if(force)
					models[worksheetId] = new D3ModelLayout(layoutElement, layoutClass, width, worksheetId);
			} else {
				models[worksheetId] = new D3ModelLayout(layoutElement, layoutClass, width, worksheetId);
			}
			return models[worksheetId];
		};

		function displayModel(json) {
			var worksheetId = json["worksheetId"];
			var mainWorksheetDiv = $("div#" + worksheetId);
			var wsVisible = mainWorksheetDiv.data("worksheetVisible");
			if (!wsVisible) {
				return;
			}

			var w = 0;
			var mainWorksheetDiv = $("div#" + worksheetId);
			var layoutElement = "div#svgDiv_" + worksheetId;

			if ($(mainWorksheetDiv).data("svgVis") != null) {
				//$(layoutElement).remove();
			} else {
				$("<div>").attr("id", "svgDiv_" + worksheetId).addClass("svg-model").insertBefore('div#' + worksheetId + " > div.table-container");
			}

			if (w == 0)
				w = $("div#" + worksheetId).width();

			var tableLeftOffset = mainWorksheetDiv.offset().left;

			var alignJson;
			var nodesMap;
			if(json.alignObject) {
				var maxX = 0;
				alignJson = json.alignObject;
				nodesMap = [];
				$.each(alignJson.anchors, function(index, node) {
					var hNodeId = node["hNodeId"];
					var columnNode = $("td#" + hNodeId);
					var leftX = $(columnNode).offset().left - tableLeftOffset;
					node.xPos = leftX + ($(columnNode).width()/2);
					var nodeMax = leftX + $(columnNode).width();
					if(nodeMax > maxX)
						maxX = nodeMax;
					nodesMap[node["id"]] = node;
				});
				alignJson.width = maxX + 100;

				$.each(alignJson.nodes, function(index, node) {
					nodesMap[node["id"]] = node;
				});

				$.each(alignJson.links, function(index, link) {
					if(link.label == "classLink")
						link.label = "uri";
				});
			} else {
				alignJson = json;
			}
			var layout;
			try {
				layout = getModelManager(worksheetId, layoutElement, "col-sm-10", w);
				console.log(JSON.stringify(alignJson));
				layout.generateLayoutForJson(alignJson);
			} catch(err) {
				console.log("Got exception in D3ModelLayout:" + err.message);
				console.log(err.stack);
				//Try again generating a new D3Layout
				$(layoutElement).empty();
				layout = getModelManager(worksheetId, layoutElement, "col-sm-10", w, true);
				console.log(JSON.stringify(alignJson));
				layout.generateLayoutForJson(alignJson);
			}
			var alignmentId = json["alignmentId"];
			$(mainWorksheetDiv).data("alignmentId", alignmentId);
			$(mainWorksheetDiv).data("svgVis", {"svgVis":true});

			layout.setNodeClickListener(function(d, event) {
				console.log("This function is called when the node is clicked");
				if (d["nodeType"] == "InternalNode" || d["nodeType"] == "LiteralNode") {
					var nodeCategory = "";
					if (d.isForcedByUser)
						nodeCategory = "forcedAdded";
					var id;
					if(d.nodeId)
						id = d.nodeId;
					else
						id = d.id;
					ClassDropdownMenu.getInstance().show(worksheetId, id, d.label, id, d.nodeDomain, nodeCategory,
					//ClassDropdownMenu.getInstance().show(worksheetId, id, d.label, d.nodeDomain, d.nodeDomain, nodeCategory,
							alignmentId, d.nodeType, d.isUri, event);

				}

			});

			layout.setLinkClickListener(function(d, event) {
				console.log("This function is called when the link is clicked");
				var sourceObj, targetObj;
				if(nodesMap) {
					sourceObj = nodesMap[d.source];
					targetObj = nodesMap[d.target];
				} else {
					sourceObj = d.source;
					targetObj = d.target;
				}
				PropertyDropdownMenu.getInstance().show(
						worksheetId,
						alignmentId,
						d.id,
						d.linkUri,
						d.sourceNodeId,
						sourceObj.nodeType,
						sourceObj.label,
						sourceObj.nodeDomain,
						d.sourceNodeId,
						d.source.isUri,
						d.targetNodeId,
						targetObj.nodeType,
						targetObj.label,
						targetObj.nodeDomain,
						d.targetNodeId,
						d.target.isUri,
						event);
			});
		};

		function refreshModel(worksheetId) {
			var mainWorksheetDiv = $("div#" + worksheetId);
			var svg = $(mainWorksheetDiv).data("svgVis");
			if (svg) {
				var alignmentId = $(mainWorksheetDiv).data("alignmentId");
				console.log("RefreshSVGAlignmentCommand: " + worksheetId, alignmentId);
				var info = generateInfoObject(worksheetId, "", "RefreshSVGAlignmentCommand");
				info["alignmentId"] = alignmentId;
				showLoading(worksheetId);
				sendRequest(info, worksheetId);
			}
		};

		function printModel(worksheetId) {
			var layout = getModelManager(worksheetId);
			if(layout.printExtented) {
				showLoading(worksheetId);
				layout.printExtented(3, function() {
					hideLoading(worksheetId);
				});
			} else {
				alert("The Model Manager does not support printing");
			}
		}

		return { //Return back the public methods
			init: init,
			getModelManager: getModelManager,
			displayModel: displayModel,
			refreshModel: refreshModel,
			printModel: printModel
		};
	};

	function getInstance() {
		if (!instance) {
			instance = new PrivateConstructor();
			instance.init();
		}
		return instance;
	}

	return {
		getInstance: getInstance
	};

})();

<|endoftext|>


<commit_before>'use strict';

var cities = ['redmond', 'kirkland', 'bellevue', 'glendale', 'north hollywood'];
var guess = prompt('Which cities have I lived in across two states? You have 6 tries. Good luck!');
var rounds = 6;

while(rounds >= 0) {
  for(var i = 0; i < cities.length; i++){
    if (rounds === 0) {
      alert('Sorry, you ran out of turns');
      break;
    } else if(guess.toLowerCase() === cities[i]){
      console.log([i]);
      alert('Correct! I did live there!');
      break;
    } else {
      rounds--;
      alert('Negative. Try again. Only a few more options.');
      continue;
    }
  }
}
<commit_msg>removed curly bracket from sub7.js<commit_after>'use strict';

var cities = ['redmond', 'kirkland', 'bellevue', 'glendale', 'north hollywood'];
var guess = prompt('Which cities have I lived in across two states? You have 6 tries. Good luck!');
var rounds = 6;

while(rounds >= 0) {
  for(var i = 0; i < cities.length; i++){
    if (rounds === 0) {
      alert('Sorry, you ran out of turns');
      break;
    } else if(guess.toLowerCase() === cities[i]){
      rounds--;
      console.log([i]);
      alert('Correct! I did live there!');
    } else {
      rounds--;
      alert('Negative. Try again. Only a few more options.');
      continue;
    }
  }
}
<|endoftext|>


<commit_before>/* Sway (c) 2016 Benson Pan. MIT @license: en.wikipedia.org/wiki/MIT_License */

/* Note: Sway relies on Velocity.js, a copy can be found on VelocityJS.org */
var callCount = 0;

var sway = function(message, animation)
{
	var velocity_param;
	var notCalled = 1;
	callCount++;

	// var fns = ['opacity', 'width', 'height', 'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft', 'top', 'right', 'bottom', 'left', 'marginTop', 'marginRight', 'marginBottom', 'marginLeft', 'borderTopWidth', 'borderRightWidth', 'borderBottomWidth', 'borderLeftWidth', 'borderRadius', 'outerWidth', 'fontSize', 'lineHeight', 'letterSpacing', 'wordSpacing', 'color', 'colorRed', 'colorGreen', 'colorBlue', 'colorAlpha', 'backgroundColor', 'backgroundColorRed', 'backgroundColorBlue', 'backgroundColorGreen', 'backgroundColorAlpha', 'borderColor', 'borderColorRed', 'borderColorGreen', 'borderColorBlue', 'borderColorAlpha', 'outlineColor', 'outlineColorRed', 'outlineColorGreen', 'outlineColorBlue', 'outlineColorAlpha', 'textShadowX', 'textShadowY', 'textShadowBlur', 'boxShadowX', 'boxShadowY', 'boxShadowBlur', 'boxShadowSpread', 'translateX', 'translateY', 'translateZ', 'scale', 'scaleX', 'scaleY', 'rotateX', 'rotateY', 'rotateZ', 'skewX', 'skewY'];

	for (var key in animation)
	{
		velocity_param = key;
	}

	$('.sway').each(function(i, obj)
	{
		if ($(this).is(':empty') && notCalled)
		{
			notCalled = 0;

			while (message != '')
			{
				// retrieve content using .text() instead, in case no js support
				var indexSpace1 = message.indexOf(' ');
				if (indexSpace1 != -1)
				{
					if (message.indexOf('
') == 0)
					{
						$(this).append('
');
						message = message.substring(indexSpace1 + 1);
					}

					else
					{
						$(this).append('
' + message.substring(0, indexSpace1) + '
 ');
						message = message.substring(indexSpace1 + 1);
					}

				}
				else
				{
					$(this).append('
' + message + '
');
					message = '';
				}
			}
			$('.inner-sway' + callCount).each(function(i, obj)
			{
				var temp = {};
				var ending = {};
				temp[velocity_param] = parseInt(animation[velocity_param]) * -1;
				ending[velocity_param] = $(this).css(velocity_param);

				if (velocity_param.indexOf("scale") != -1)
				{
					ending[velocity_param] = 1;
				}
				if (velocity_param.indexOf("fontSize") != -1)
				{
					console.log($(this).css("font-size"));
					temp[velocity_param] = 10;
				}

				$(this).hover(function()
				{
					$(this).velocity(animation, {duration:100, easing: 'easeOutBounce'});
					$(this).velocity(temp, {duration:200, easing: 'easeOutBounce'});
					$(this).velocity(ending, {duration:250, easing: 'easeOutBounce'});
				},
				function()
				{

				});
			});
			$('.inner-sway' + callCount).css({'display':'inline-block'});
		}
		if (notCalled && i == $('.sway').length - 1)
			console.log("Sway: Function was called more than number of available .sway divs")
	});
}
<commit_msg>Update sway.js<commit_after>/* Sway (c) 2016 Benson Pan. MIT @license: en.wikipedia.org/wiki/MIT_License */

/* Note: Sway relies on Velocity.js, a copy can be found on VelocityJS.org */
var callCount = 0;

var sway = function(animation)
{
	var velocity_param;

	// var fns = ['opacity', 'width', 'height', 'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft', 'top', 'right', 'bottom', 'left', 'marginTop', 'marginRight', 'marginBottom', 'marginLeft', 'borderTopWidth', 'borderRightWidth', 'borderBottomWidth', 'borderLeftWidth', 'borderRadius', 'outerWidth', 'fontSize', 'lineHeight', 'letterSpacing', 'wordSpacing', 'color', 'colorRed', 'colorGreen', 'colorBlue', 'colorAlpha', 'backgroundColor', 'backgroundColorRed', 'backgroundColorBlue', 'backgroundColorGreen', 'backgroundColorAlpha', 'borderColor', 'borderColorRed', 'borderColorGreen', 'borderColorBlue', 'borderColorAlpha', 'outlineColor', 'outlineColorRed', 'outlineColorGreen', 'outlineColorBlue', 'outlineColorAlpha', 'textShadowX', 'textShadowY', 'textShadowBlur', 'boxShadowX', 'boxShadowY', 'boxShadowBlur', 'boxShadowSpread', 'translateX', 'translateY', 'translateZ', 'scale', 'scaleX', 'scaleY', 'rotateX', 'rotateY', 'rotateZ', 'skewX', 'skewY'];

	for (var key in animation)
	{
		velocity_param = key;
	}

	$('.sway').each(function(i, obj)
	{
		if (callCount <= i)
		{
			var message = $(this).text();
			notCalled = 0;
			$(this).html(''); // clear the html

			while (message != '')
			{
				// retrieve content using .text() instead, in case no js support
				var indexSpace1 = message.indexOf(' ');
				if (indexSpace1 != -1)
				{
					if (message.indexOf('
') == 0)
					{
						$(this).append('
');
						message = message.substring(indexSpace1 + 1);
					}

					else
					{
						$(this).append('
' + message.substring(0, indexSpace1) + '
 ');
						message = message.substring(indexSpace1 + 1);
					}

				}
				else
				{
					$(this).append('
' + message + '
');
					message = '';
				}
			}
			$('.inner-sway' + callCount).each(function(i, obj)
			{
				var temp = {};
				var ending = {};
				temp[velocity_param] = parseInt(animation[velocity_param]) * -1;
				ending[velocity_param] = $(this).css(velocity_param);

				if (velocity_param.indexOf("scale") != -1)
				{
					ending[velocity_param] = 1;
				}
				if (velocity_param.indexOf("fontSize") != -1)
				{
					console.log($(this).css("font-size"));
					temp[velocity_param] = 10;
				}

				$(this).hover(function()
				{
					$(this).velocity(animation, {duration:100, easing: 'easeOutBounce'});
					$(this).velocity(temp, {duration:200, easing: 'easeOutBounce'});
					$(this).velocity(ending, {duration:250, easing: 'easeOutBounce'});
				},
				function()
				{
				});
			});
			$('.inner-sway' + callCount).css({'display':'inline-block'});
		}

		if (notCalled && i == $('.sway').length - 1)
			console.log("Sway: Function was called more than number of available .sway divs")
	});
	callCount++;
}
<|endoftext|>


<commit_before>"use strict";
require("requirish")._(module);

var assert = require("better-assert");
var _ = require("underscore");

var opcua = require("index");
var UAObjectType = require("./ua_object_type").UAObjectType;

exports.install = function (AddressSpace) {

    AddressSpace.prototype.addState = function (component, stateName, stateNumber, isInitialState) {

        var addressSpace = this;

        isInitialState = !!isInitialState;

        assert(component instanceof UAObjectType);
        assert(_.isString(stateName));
        assert(_.isBoolean(isInitialState));

        var initialStateType = addressSpace.findObjectType("InitialStateType");
        var stateType = addressSpace.findObjectType("StateType");

        var state;
        if (isInitialState) {
            state = initialStateType.instantiate({
                browseName: stateName,
                componentOf: component
            });
        } else {
            state = stateType.instantiate({
                browseName: stateName,
                componentOf: component
            });
        }
        // ensure state number is unique
        state.stateNumber.setValueFromSource({
            dataType: opcua.DataType.UInt32,
            value: stateNumber
        });
        return state;
    };

    AddressSpace.prototype.addTransition = function (component, fromState, toState, transitionNumber) {

        var addressSpace = this;

        assert(component instanceof UAObjectType);
        assert(_.isString(fromState));
        assert(_.isString(toState));
        assert(_.isFinite(transitionNumber));

        var fromStateNode = component.getComponentByName(fromState);
        if (!fromStateNode) {
            throw new Error("Cannot find state with name " + fromState);
        }
        assert(fromStateNode.browseName.name.toString() === fromState);

        var toStateNode = component.getComponentByName(toState);
        if (!toStateNode) {
            throw new Error("Cannot find state with name " + toState);
        }
        assert(toStateNode && toStateNode.browseName.name.toString() === toState);

        var transitionType = addressSpace.findObjectType("TransitionType");

        var transition = transitionType.instantiate({
            browseName: fromState + "To" + toState + "Transition",
            componentOf: component
        });

        transition.addReference({
            referenceType: "ToState",
            isForward: true,
            nodeId: toStateNode.nodeId
        });
        transition.addReference({
            referenceType: "FromState",
            isForward: true,
            nodeId: fromStateNode.nodeId
        });

        transition.transitionNumber.setValueFromSource({
            dataType: opcua.DataType.UInt32, value: transitionNumber
        })

    };

};

<commit_msg>fix  code generation issue<commit_after>"use strict";
require("requirish")._(module);

var assert = require("better-assert");
var _ = require("underscore");

exports.install = function (AddressSpace) {

    var DataType = require("lib/datamodel/variant").DataType;
    var UAObjectType = require("./ua_object_type").UAObjectType;

    AddressSpace.prototype.addState = function (component, stateName, stateNumber, isInitialState) {

        var addressSpace = this;

        isInitialState = !!isInitialState;

        assert(component instanceof UAObjectType);
        assert(_.isString(stateName));
        assert(_.isBoolean(isInitialState));

        var initialStateType = addressSpace.findObjectType("InitialStateType");
        var stateType = addressSpace.findObjectType("StateType");

        var state;
        if (isInitialState) {
            state = initialStateType.instantiate({
                browseName: stateName,
                componentOf: component
            });
        } else {
            state = stateType.instantiate({
                browseName: stateName,
                componentOf: component
            });
        }
        // ensure state number is unique
        state.stateNumber.setValueFromSource({
            dataType: DataType.UInt32,
            value: stateNumber
        });
        return state;
    };

    AddressSpace.prototype.addTransition = function (component, fromState, toState, transitionNumber) {

        var addressSpace = this;

        assert(component instanceof UAObjectType);
        assert(_.isString(fromState));
        assert(_.isString(toState));
        assert(_.isFinite(transitionNumber));

        var fromStateNode = component.getComponentByName(fromState);
        if (!fromStateNode) {
            throw new Error("Cannot find state with name " + fromState);
        }
        assert(fromStateNode.browseName.name.toString() === fromState);

        var toStateNode = component.getComponentByName(toState);
        if (!toStateNode) {
            throw new Error("Cannot find state with name " + toState);
        }
        assert(toStateNode && toStateNode.browseName.name.toString() === toState);

        var transitionType = addressSpace.findObjectType("TransitionType");

        var transition = transitionType.instantiate({
            browseName: fromState + "To" + toState + "Transition",
            componentOf: component
        });

        transition.addReference({
            referenceType: "ToState",
            isForward: true,
            nodeId: toStateNode.nodeId
        });
        transition.addReference({
            referenceType: "FromState",
            isForward: true,
            nodeId: fromStateNode.nodeId
        });

        transition.transitionNumber.setValueFromSource({
            dataType: DataType.UInt32, value: transitionNumber
        })

    };

};

<|endoftext|>


<commit_before>
/**
 * view used to render each row
 */
cdb.admin.RowView = cdb.ui.common.RowView.extend({
  classLabel: 'cdb.admin.RowView',
  events: {
    'click .row_header': 'click_header',
    // 'mouseout .row_header': 'mouseout_event'
  },

  cellRenderers: {
    'default': '_renderDefault',
    'boolean': '_renderBoolean',
    'number': '_renderNumber'
  },

  initialize: function() {
    var self = this;
    this.elder('initialize');
    _.bindAll(this, 'mouseout_header', 'click_header',
      'mousein_event', 'mouseout_event')
    this.options.row_header = true;
    this.model.bind('destroy', function() {
      self.trigger('destroyRow');
    })
    this.retrigger('saving', this.model);
    this.retrigger('saved', this.model);
    this.retrigger('savingError', this.model);

    this.$el.bind('mouseover', this.mousein_event);
    this.$el.bind('mouseout', this.mouseout_event);

  },
  /**
   * When the mouse steps over the row, mark the attribute 'hasMouse'
   */
  mousein_event: function() {
    this.hasMouse = true;
  },
  /**
   * Here be dragons: this is a hack to be able to detect when
   * the mouse has left a row for real. Mouseout event is not enough,
   * because it gets triggered when you change between tds.
   * It listen for this changes and mark the row as 'unmoused',
   * waiting for another event to step in and mark this row as
   * 'moused' again.
   *
   * @param  {Event} ev
   */
  mouseout_event: function(ev) {
    this.hasMouse = false;
    setTimeout(this.checkDropdownOpen.bind(this),25);
  },
  /**
   * Check if the cursor is not over this row and if the option menu is
   * opened, and if so, clear the menu
   */
  checkDropdownOpen: function() {
    if(!this.hasMouse && this.rowOptions) {
      this.rowOptions.hide();
    }
  },
  _getRowOptions: function() {
    if(!cdb.admin.RowView.rowOptions) {
       var rowOptions = cdb.admin.RowView.rowOptions= new cdb.admin.RowHeaderDropdown({
        position: 'position',
        template_base: "table/views/table_row_header_options",
        tick: "top",
        horizontal_position: "left",
        tableData: this.getTableView().dataModel
      });
      rowOptions.render();
      this.retrigger('destroyRow', rowOptions);
      this.retrigger('createRow', rowOptions);

    }
    return cdb.admin.RowView.rowOptions;
  },
  mouseout_header: function(e) {
    console.log(e);
    console.log(e.currentTarget);
    console.log(e.target);
    if(this.rowOptions) {
      // this.rowOptions.hide();
    }
  },
  click_header: function(e) {
    var rowOptions, tableData, pos, tableOffset, left, top;

    $target = $(e.target);

    tableData = this.getTableView().dataModel;
    if(tableData.isReadOnly()) {
      // if data is read only do not allow
      // to add or remove rows
      return;
    }
    rowOptions = this._getRowOptions();
    e.preventDefault();
    $target.append(rowOptions.el);
    pos = $target.position();

    // xabel: Yep, browser specific code. I'm so sorry for thiw. What's this? 2007?
    if(/Chrome/.test(navigator.appVersion)) {
      left = pos.left + 30;
      top = pos.top + 0;
    } else {
      pos = $target.offset();
      tableOffset = $target.parents('table').offset() || 0;
      left = pos.left - tableOffset.left + 20;
      top = pos.top - tableOffset.top - 15;
    }
    rowOptions.setRow(this.model);
    rowOptions.openAt(left, top);
    this.rowOptions = rowOptions; // to make it testable;
    return false;
  },

  /**
   * return each cell view
   */
  valueView: function(colName, value) {
    if((colName == 'the_geom' || colName == 'the_geom_webmercator' ) &&
      this.getTableView().dataModel.isReadOnly() ) {
      value = 'GeoJSON'
    }
    this.table = this.table || this.getTableView().model;
    var render = '_renderDefault';
    if(colName.length) {
      var colType = this.table.getColumnType(colName);
      render = this.cellRenderers[colType] || render;
    }

    var obj = this[render](value);
    obj.addClass('cell');
    if(cdb.admin.Row.isReservedColumn(colName)) {
      obj.addClass('disabled');
    }
    if(colName === '' && value === '') {
      obj.addClass('row_header');
      //some space
      //TODO: do it with css
      obj.append('    ');
    }
    return obj;
  },

  _renderDefault: function(value) {
    return $('<div>').append(value);
  },

  _renderBoolean: function(value) {
    var v = '';
    if(value === '' || value === null) {
    } else if(value) {
      v = 'true';
    } else {
      v = 'false';
    }
    return $('<div>').append(v);
  },

  _renderNumber: function(value) {
    var d = this._renderDefault(value);
    return d.addClass('number');
  }

});

<commit_msg>fixed #979<commit_after>
/**
 * view used to render each row
 */
cdb.admin.RowView = cdb.ui.common.RowView.extend({
  classLabel: 'cdb.admin.RowView',
  events: {
    'click .row_header': 'click_header',
    // 'mouseout .row_header': 'mouseout_event'
  },

  cellRenderers: {
    'default': '_renderDefault',
    'boolean': '_renderBoolean',
    'number': '_renderNumber'
  },

  initialize: function() {
    var self = this;
    this.elder('initialize');
    _.bindAll(this, 'mouseout_header', 'click_header',
      'mousein_event', 'mouseout_event')
    this.options.row_header = true;
    this.model.bind('destroy', function() {
      self.trigger('destroyRow');
    })
    this.retrigger('saving', this.model);
    this.retrigger('saved', this.model);
    this.retrigger('savingError', this.model);

    this.$el.bind('mouseover', this.mousein_event);
    this.$el.bind('mouseout', this.mouseout_event);

  },
  /**
   * When the mouse steps over the row, mark the attribute 'hasMouse'
   */
  mousein_event: function() {
    this.hasMouse = true;
  },
  /**
   * Here be dragons: this is a hack to be able to detect when
   * the mouse has left a row for real. Mouseout event is not enough,
   * because it gets triggered when you change between tds.
   * It listen for this changes and mark the row as 'unmoused',
   * waiting for another event to step in and mark this row as
   * 'moused' again.
   *
   * @param  {Event} ev
   */
  mouseout_event: function(ev) {
    this.hasMouse = false;
    setTimeout(this.checkDropdownOpen.bind(this),25);
  },
  /**
   * Check if the cursor is not over this row and if the option menu is
   * opened, and if so, clear the menu
   */
  checkDropdownOpen: function() {
    if(!this.hasMouse && this.rowOptions) {
      this.rowOptions.hide();
    }
  },
  _getRowOptions: function() {
    if(!cdb.admin.RowView.rowOptions) {
       var rowOptions = cdb.admin.RowView.rowOptions= new cdb.admin.RowHeaderDropdown({
        position: 'position',
        template_base: "table/views/table_row_header_options",
        tick: "top",
        horizontal_position: "left",
        tableData: this.getTableView().dataModel
      });
      rowOptions.render();
      this.retrigger('destroyRow', rowOptions);
      this.retrigger('createRow', rowOptions);

    }
    return cdb.admin.RowView.rowOptions;
  },
  mouseout_header: function(e) {
    console.log(e);
    console.log(e.currentTarget);
    console.log(e.target);
    if(this.rowOptions) {
      // this.rowOptions.hide();
    }
  },
  click_header: function(e) {
    var rowOptions, tableData, pos, tableOffset, left, top;

    $target = $(e.target);

    tableData = this.getTableView().dataModel;
    if(tableData.isReadOnly()) {
      // if data is read only do not allow
      // to add or remove rows
      return;
    }
    rowOptions = this._getRowOptions();
    e.preventDefault();
    $target.append(rowOptions.el);
    pos = $target.position();

    // xabel: Yep, browser specific code. I'm so sorry for thiw. What's this? 2007?
    if(/Chrome/.test(navigator.appVersion)) {
      left = pos.left + 30;
      top = pos.top + 0;
    } else {
      pos = $target.offset();
      tableOffset = $target.parents('table').offset() || 0;
      left = pos.left - tableOffset.left + 20;
      top = pos.top - tableOffset.top - 15;
    }
    rowOptions.setRow(this.model);
    rowOptions.openAt(left, top);
    this.rowOptions = rowOptions; // to make it testable;
    return false;
  },

  /**
   * return each cell view
   */
  valueView: function(colName, value) {
    if((colName == 'the_geom' || colName == 'the_geom_webmercator' ) &&
      this.getTableView().dataModel.isReadOnly() ) {
      value = 'GeoJSON'
    }
    this.table = this.table || this.getTableView().model;
    var render = '_renderDefault';
    if(colName.length) {
      var colType = this.table.getColumnType(colName);
      render = this.cellRenderers[colType] || render;
    }

    var obj = this[render](value);
    obj.addClass('cell');
    if(cdb.admin.Row.isReservedColumn(colName)) {
      obj.addClass('disabled');
    }
    if(colName === '' && value === '') {
      obj.addClass('row_header');
      //some space
      //TODO: do it with css
      obj.append('    ');
    }
    return obj;
  },

  _renderDefault: function(value) {
    return $('<div>').append(_.escape(value));
  },

  _renderBoolean: function(value) {
    var v = '';
    if(value === '' || value === null) {
    } else if(value) {
      v = 'true';
    } else {
      v = 'false';
    }
    return $('<div>').append(v);
  },

  _renderNumber: function(value) {
    var d = this._renderDefault(value);
    return d.addClass('number');
  }

});

<|endoftext|>


<commit_before>var cdb = require('cartodb-deep-insights.js');

cdb.deepInsights.createDashboard('#dashboard', window.vizJSON, {
  no_cdn: false,
  cartodb_logo: false,
  renderMenu: true
});
<commit_msg>Touching public editor js<commit_after>var cdb = require('cartodb-deep-insights.js');
cdb.deepInsights.createDashboard('#dashboard', window.vizJSON, {
  no_cdn: false,
  cartodb_logo: false,
  renderMenu: true
});
<|endoftext|>


<commit_before>const Polyglot = require('node-polyglot');
const Locale = require('locale/index');

const ACTIVE_LOCALE = window.ACTIVE_LOCALE || 'en';
const polyglot = new Polyglot({
  locale: ACTIVE_LOCALE, // Needed for pluralize behaviour
  phrases: Locale[ACTIVE_LOCALE]
});
window._t = polyglot.t.bind(polyglot);

const $ = require('jquery');
const _ = require('underscore');
const Backbone = require('backbone');
const UserModel = require('dashboard/data/user-model');
const OrganizationModel = require('dashboard/data/organization-model');
const ConfigModel = require('dashboard/data/config-model');
const DashboardHeaderView = require('dashboard/components/dashboard-header-view');
const SupportView = require('dashboard/components/support-view');
const HeaderViewModel = require('./views/organization/header-view-model');
const LocalStorage = require('dashboard/helpers/local-storage');
const FlashMessageModel = require('dashboard/data/flash-message-model');
const FlashMessageView = require('dashboard/components/flash-message/flash-message-view');
const TipsyTooltipView = require('builder/components/tipsy-tooltip-view');
const OrganizationUsersView = require('dashboard/views/organization/organization-users/organization-users-view');
const OrganizationNotificationView = require('dashboard/views/organization/organization-notification/organization-notification-view');
const OrganizationUserQuota = require('dashboard/views/organization/organization-user-quota');
const AvatarSelector = require('dashboard/components/avatar-selector/avatar-selector-view');
const OrganizationUserForm = require('dashboard/views/organization/organization-user-form');
const RegenerateKeysDialog = require('dashboard/views/organization/regenerate-keys-dialog-view');
const ModalsServiceModel = require('builder/components/modals/modals-service-model');
const DeleteOrganization = require('dashboard/views/organization/delete-organization-view');
const IconPickerView = require('dashboard/views/organization/icon-picker/organization-icon-picker-view');
const DeleteOrganizationUser = require('dashboard/views/organization/delete-organization-user-view');
const GroupsRouter = require('dashboard/common/router-organization-groups');
const GroupsMainView = require('dashboard/views/organization/groups-admin/groups-main-view');
const OrganizationGroupsCollection = require('dashboard/data/organization-groups-collection');
const getObjectValue = require('deep-insights/util/get-object-value');
require('dashboard/data/backbone/sync-options');

const DOMAIN_REGEXP = /^[a-zA-Z0-9*][a-zA-Z0-9-_]{0,61}[a-zA-Z0-9]{0,1}\.([a-zA-Z]{1,6}|[a-zA-Z0-9-]{1,30}\.[a-zA-Z]{2,3})$/;
const configModel = new ConfigModel(
  _.defaults(
    { base_url: window.user_data.base_url },
    window.config
  )
);

if (window.trackJs) {
  window.trackJs.configure({
    userId: window.user_data.username
  });
}

/**
 *  Entry point for the new organization, bootstraps all
 *  dependency models and application.
 */

$(function () {
  let organizationUser;
  let organization;
  let organizationUsers;

  const modalsService = new ModalsServiceModel();

  const userModel = new UserModel(window.user_data, { configModel });

  if (window.user_data.organization) {
    organization = new OrganizationModel({
      ...window.user_data.organization,
      ...window.organization_data
    }, {
      userModel,
      configModel
    });
    organizationUsers = organization.users;
    organization.owner = new UserModel(getObjectValue(window.user_data, 'organization.owner'));
    userModel.setOrganization(organization);
  }

  if (window.organization_user_data) {
    organizationUser = new UserModel(window.organization_user_data, { configModel });

    if (organization) {
      organizationUser.setOrganization(organization);
    }
  }

  const headerView = new DashboardHeaderView({
    el: $('#header'), // pre-rendered in DOM by Rails app
    model: userModel,
    userModelUrl: userModel.viewUrl(),
    viewModel: new HeaderViewModel(),
    localStorage: new LocalStorage(),
    configModel
  });
  headerView.render();

  const flashMessageModel = new FlashMessageModel();
  const flashMessageView = new FlashMessageView({
    model: flashMessageModel
  });
  flashMessageView.render();
  flashMessageView.$el.insertAfter(headerView.$el);

  const supportView = new SupportView({
    el: $('#support-banner'),
    userModel
  });
  supportView.render();

  // Avatar
  if ($('.js-avatarSelector').length > 0) {
    const avatarSelector = new AvatarSelector({
      el: $('.js-avatarSelector'),
      renderModel: new Backbone.Model({
        inputName: $('.js-fileAvatar').attr('name'),
        name: userModel.organization.get('name'),
        avatar_url: userModel.organization.get('avatar_url'),
        id: userModel.get('id')
      }),
      avatarAcceptedExtensions: window.avatar_valid_extensions,
      configModel
    });

    avatarSelector.render();
  }

  // Tooltips
  $('[data-title]').each(function (i, el) {
    new TipsyTooltipView({ // eslint-disable-line
      el: el,
      title: function () {
        return $(this).attr('data-title');
      }
    });
  });

  // Icon picker
  if ($('.js-iconPicker').length > 0) {
    this.icon_picker_view = new IconPickerView({
      el: $('.js-iconPicker'),
      orgId: userModel.organization.get('id'),
      configModel
    });
  }

  // Domain whitelisting
  if ($('.js-domains').length > 0) {
    require('jquery-ui');
    require('tagit');

    $('.js-domainsList').tagit({
      allowSpaces: false,
      singleField: true,
      singleFieldNode: $('.js-whitelist'),
      fieldName: $('.js-whitelist').attr('name'),
      tagLimit: 10,
      readOnly: false,
      onBlur: function () {
        $('.js-domains').removeClass('is-focus');

        if ($('.tagit-choice').length > 0) {
          $('.js-placeholder').hide();
        } else {
          $('.js-placeholder').show();
        }

        if ($('.tagit-new').length > 0) {
          $('.tagit-new input').val('');
        }
      },
      onFocus: function () {
        $('.js-domains').addClass('is-focus');

        $('.js-placeholder').hide();
      },
      beforeTagAdded: function (ev, ui) {
        if (!DOMAIN_REGEXP.test(ui.tagLabel)) {
          return false;
        }

        if ($('.tagit-choice').length > 0) {
          $('.js-placeholder').hide();
        } else { $('.js-placeholder').show(); }
      },
      afterTagAdded: function (ev, ui) {
        if ($('.tagit-choice').length > 0) {
          $('.js-placeholder').hide();
        } else { $('.js-placeholder').show(); }
      }
    });
  }

  // Organization user form
  if (organizationUser) {
    this.organization_user_form = new OrganizationUserForm({
      el: $('.js-organizationUserForm'),
      model: organizationUser
    });
  }

  // User quota main view
  if (organizationUser) {
    this.organization_user_quota = new OrganizationUserQuota({
      el: $('.js-userQuota'),
      model: organizationUser
    });
  }

  // Organization users list
  if ($('.js-orgUsersList').length === 1) {
    this.organizationUsersView = new OrganizationUsersView({
      el: '.js-orgUsersList',
      organization,
      organizationUsers,
      userModel,
      configModel
    });

    this.organizationUsersView.render();
  }

  // User deletion
  const deleteAccountButton = $('.js-deleteAccount');
  if (deleteAccountButton.length > 0 && window.authenticity_token) {
    deleteAccountButton.click(function (ev) {
      if (ev) {
        ev.preventDefault();
      }

      modalsService.create(modalModel =>
        new DeleteOrganizationUser({
          modalModel,
          configModel,
          organizationUser,
          authenticityToken: window.authenticity_token
        })
      );
    });
  }

  // Organization deletion
  if ($('.js-deleteOrganization').length > 0 && window.authenticity_token) {
    $('.js-deleteOrganization').click(function (event) {
      if (event) event.preventDefault();

      modalsService.create(modalModel => (
        new DeleteOrganization({
          authenticityToken: window.authenticity_token,
          userModel,
          modalModel
        })
      ));
    });
  }

  // Notifications
  if ($('.js-OrganizationNotification').length > 0) {
    const authenticityToken = $('[name=authenticity_token][value]').get(0).value;

    this.organization_notification_view = new OrganizationNotificationView({
      el: '.js-OrganizationNotification',
      authenticityToken,
      userModel
    });

    this.organization_notification_view.render();
  }

  // User quotas
  const toggleUserQuotas = function () {
    const viewer = $('.js-userViewerOption:checked').val();
    if (viewer === 'true') {
      $('.user-quotas').hide();
      $('.js-org-admin-row').hide();
      $('#org_admin').prop('checked', false);
    } else {
      $('.user-quotas').show();
      $('.js-org-admin-row').show();
    }
  };

  toggleUserQuotas();

  $('.js-userViewerOption').bind('change', function (ev) {
    toggleUserQuotas();
  });

  // API keys
  const regenerateApiKeyHandler = function (event, scope, form_action) {
    if (event) event.preventDefault();

    const authenticity_token = $('[name=authenticity_token][value]').get(0).value;

    modalsService.create(modalModel => (
      new RegenerateKeysDialog({ type: 'api', scope, form_action, authenticity_token, modalModel })
    ));
  };

  $('.js-regenerateOrgUsersApiKey').bind('click', function (event) {
    const current_username = $(this).attr('data-current_username');

    regenerateApiKeyHandler(event, 'organization', `/u/${current_username}/organization/regenerate_api_keys`);
  });

  $('.js-regenerateOrgUserApiKey').bind('click', function (ev) {
    const username = $(this).attr('data-username');
    const current_username = $(this).attr('data-current_username');

    regenerateApiKeyHandler(ev, 'organization_user', `/u/${current_username}/organization/users/${username}/regenerate_api_key`);
  });

  const $groups = $('.js-groups-content');
  if ($groups) {
    if (!userModel.isOrgAdmin()) {
      window.location = userModel.viewUrl().accountProfile();
      return false;
    }

    const groups = new OrganizationGroupsCollection([], {
      organization: userModel.organization,
      configModel
    });

    const router = new GroupsRouter({
      rootUrl: userModel.viewUrl().organization().groups(),
      flashMessageModel,
      groups,
      userModel
    });

    const groupsMainView = new GroupsMainView({
      el: $groups,
      groups,
      routerModel: router,
      user: userModel
    });
    groupsMainView.render();

    router.enableAfterMainView();
  }
});
<commit_msg>missing url_prefix was preventing users from being deleted<commit_after>const Polyglot = require('node-polyglot');
const Locale = require('locale/index');

const ACTIVE_LOCALE = window.ACTIVE_LOCALE || 'en';
const polyglot = new Polyglot({
  locale: ACTIVE_LOCALE, // Needed for pluralize behaviour
  phrases: Locale[ACTIVE_LOCALE]
});
window._t = polyglot.t.bind(polyglot);

const $ = require('jquery');
const _ = require('underscore');
const Backbone = require('backbone');
const UserModel = require('dashboard/data/user-model');
const OrganizationModel = require('dashboard/data/organization-model');
const ConfigModel = require('dashboard/data/config-model');
const DashboardHeaderView = require('dashboard/components/dashboard-header-view');
const SupportView = require('dashboard/components/support-view');
const HeaderViewModel = require('./views/organization/header-view-model');
const LocalStorage = require('dashboard/helpers/local-storage');
const FlashMessageModel = require('dashboard/data/flash-message-model');
const FlashMessageView = require('dashboard/components/flash-message/flash-message-view');
const TipsyTooltipView = require('builder/components/tipsy-tooltip-view');
const OrganizationUsersView = require('dashboard/views/organization/organization-users/organization-users-view');
const OrganizationNotificationView = require('dashboard/views/organization/organization-notification/organization-notification-view');
const OrganizationUserQuota = require('dashboard/views/organization/organization-user-quota');
const AvatarSelector = require('dashboard/components/avatar-selector/avatar-selector-view');
const OrganizationUserForm = require('dashboard/views/organization/organization-user-form');
const RegenerateKeysDialog = require('dashboard/views/organization/regenerate-keys-dialog-view');
const ModalsServiceModel = require('builder/components/modals/modals-service-model');
const DeleteOrganization = require('dashboard/views/organization/delete-organization-view');
const IconPickerView = require('dashboard/views/organization/icon-picker/organization-icon-picker-view');
const DeleteOrganizationUser = require('dashboard/views/organization/delete-organization-user-view');
const GroupsRouter = require('dashboard/common/router-organization-groups');
const GroupsMainView = require('dashboard/views/organization/groups-admin/groups-main-view');
const OrganizationGroupsCollection = require('dashboard/data/organization-groups-collection');
const getObjectValue = require('deep-insights/util/get-object-value');
require('dashboard/data/backbone/sync-options');

const DOMAIN_REGEXP = /^[a-zA-Z0-9*][a-zA-Z0-9-_]{0,61}[a-zA-Z0-9]{0,1}\.([a-zA-Z]{1,6}|[a-zA-Z0-9-]{1,30}\.[a-zA-Z]{2,3})$/;
const configModel = new ConfigModel(
  _.defaults(
    {
      base_url: window.user_data.base_url,
      url_prefix: window.user_data.base_url
    },
    window.config
  )
);

if (window.trackJs) {
  window.trackJs.configure({
    userId: window.user_data.username
  });
}

/**
 *  Entry point for the new organization, bootstraps all
 *  dependency models and application.
 */

$(function () {
  let organizationUser;
  let organization;
  let organizationUsers;

  const modalsService = new ModalsServiceModel();

  const userModel = new UserModel(window.user_data, { configModel });

  if (window.user_data.organization) {
    organization = new OrganizationModel({
      ...window.user_data.organization,
      ...window.organization_data
    }, {
      userModel,
      configModel
    });
    organizationUsers = organization.users;
    organization.owner = new UserModel(getObjectValue(window.user_data, 'organization.owner'));
    userModel.setOrganization(organization);
  }

  if (window.organization_user_data) {
    organizationUser = new UserModel(window.organization_user_data, { configModel });

    if (organization) {
      organizationUser.setOrganization(organization);
    }
  }

  const headerView = new DashboardHeaderView({
    el: $('#header'), // pre-rendered in DOM by Rails app
    model: userModel,
    userModelUrl: userModel.viewUrl(),
    viewModel: new HeaderViewModel(),
    localStorage: new LocalStorage(),
    configModel
  });
  headerView.render();

  const flashMessageModel = new FlashMessageModel();
  const flashMessageView = new FlashMessageView({
    model: flashMessageModel
  });
  flashMessageView.render();
  flashMessageView.$el.insertAfter(headerView.$el);

  const supportView = new SupportView({
    el: $('#support-banner'),
    userModel
  });
  supportView.render();

  // Avatar
  if ($('.js-avatarSelector').length > 0) {
    const avatarSelector = new AvatarSelector({
      el: $('.js-avatarSelector'),
      renderModel: new Backbone.Model({
        inputName: $('.js-fileAvatar').attr('name'),
        name: userModel.organization.get('name'),
        avatar_url: userModel.organization.get('avatar_url'),
        id: userModel.get('id')
      }),
      avatarAcceptedExtensions: window.avatar_valid_extensions,
      configModel
    });

    avatarSelector.render();
  }

  // Tooltips
  $('[data-title]').each(function (i, el) {
    new TipsyTooltipView({ // eslint-disable-line
      el: el,
      title: function () {
        return $(this).attr('data-title');
      }
    });
  });

  // Icon picker
  if ($('.js-iconPicker').length > 0) {
    this.icon_picker_view = new IconPickerView({
      el: $('.js-iconPicker'),
      orgId: userModel.organization.get('id'),
      configModel
    });
  }

  // Domain whitelisting
  if ($('.js-domains').length > 0) {
    require('jquery-ui');
    require('tagit');

    $('.js-domainsList').tagit({
      allowSpaces: false,
      singleField: true,
      singleFieldNode: $('.js-whitelist'),
      fieldName: $('.js-whitelist').attr('name'),
      tagLimit: 10,
      readOnly: false,
      onBlur: function () {
        $('.js-domains').removeClass('is-focus');

        if ($('.tagit-choice').length > 0) {
          $('.js-placeholder').hide();
        } else {
          $('.js-placeholder').show();
        }

        if ($('.tagit-new').length > 0) {
          $('.tagit-new input').val('');
        }
      },
      onFocus: function () {
        $('.js-domains').addClass('is-focus');

        $('.js-placeholder').hide();
      },
      beforeTagAdded: function (ev, ui) {
        if (!DOMAIN_REGEXP.test(ui.tagLabel)) {
          return false;
        }

        if ($('.tagit-choice').length > 0) {
          $('.js-placeholder').hide();
        } else { $('.js-placeholder').show(); }
      },
      afterTagAdded: function (ev, ui) {
        if ($('.tagit-choice').length > 0) {
          $('.js-placeholder').hide();
        } else { $('.js-placeholder').show(); }
      }
    });
  }

  // Organization user form
  if (organizationUser) {
    this.organization_user_form = new OrganizationUserForm({
      el: $('.js-organizationUserForm'),
      model: organizationUser
    });
  }

  // User quota main view
  if (organizationUser) {
    this.organization_user_quota = new OrganizationUserQuota({
      el: $('.js-userQuota'),
      model: organizationUser
    });
  }

  // Organization users list
  if ($('.js-orgUsersList').length === 1) {
    this.organizationUsersView = new OrganizationUsersView({
      el: '.js-orgUsersList',
      organization,
      organizationUsers,
      userModel,
      configModel
    });

    this.organizationUsersView.render();
  }

  // User deletion
  const deleteAccountButton = $('.js-deleteAccount');
  if (deleteAccountButton.length > 0 && window.authenticity_token) {
    deleteAccountButton.click(function (ev) {
      if (ev) {
        ev.preventDefault();
      }

      modalsService.create(modalModel =>
        new DeleteOrganizationUser({
          modalModel,
          configModel,
          organizationUser,
          authenticityToken: window.authenticity_token
        })
      );
    });
  }

  // Organization deletion
  if ($('.js-deleteOrganization').length > 0 && window.authenticity_token) {
    $('.js-deleteOrganization').click(function (event) {
      if (event) event.preventDefault();

      modalsService.create(modalModel => (
        new DeleteOrganization({
          authenticityToken: window.authenticity_token,
          userModel,
          modalModel
        })
      ));
    });
  }

  // Notifications
  if ($('.js-OrganizationNotification').length > 0) {
    const authenticityToken = $('[name=authenticity_token][value]').get(0).value;

    this.organization_notification_view = new OrganizationNotificationView({
      el: '.js-OrganizationNotification',
      authenticityToken,
      userModel
    });

    this.organization_notification_view.render();
  }

  // User quotas
  const toggleUserQuotas = function () {
    const viewer = $('.js-userViewerOption:checked').val();
    if (viewer === 'true') {
      $('.user-quotas').hide();
      $('.js-org-admin-row').hide();
      $('#org_admin').prop('checked', false);
    } else {
      $('.user-quotas').show();
      $('.js-org-admin-row').show();
    }
  };

  toggleUserQuotas();

  $('.js-userViewerOption').bind('change', function (ev) {
    toggleUserQuotas();
  });

  // API keys
  const regenerateApiKeyHandler = function (event, scope, form_action) {
    if (event) event.preventDefault();

    const authenticity_token = $('[name=authenticity_token][value]').get(0).value;

    modalsService.create(modalModel => (
      new RegenerateKeysDialog({ type: 'api', scope, form_action, authenticity_token, modalModel })
    ));
  };

  $('.js-regenerateOrgUsersApiKey').bind('click', function (event) {
    const current_username = $(this).attr('data-current_username');

    regenerateApiKeyHandler(event, 'organization', `/u/${current_username}/organization/regenerate_api_keys`);
  });

  $('.js-regenerateOrgUserApiKey').bind('click', function (ev) {
    const username = $(this).attr('data-username');
    const current_username = $(this).attr('data-current_username');

    regenerateApiKeyHandler(ev, 'organization_user', `/u/${current_username}/organization/users/${username}/regenerate_api_key`);
  });

  const $groups = $('.js-groups-content');
  if ($groups) {
    if (!userModel.isOrgAdmin()) {
      window.location = userModel.viewUrl().accountProfile();
      return false;
    }

    const groups = new OrganizationGroupsCollection([], {
      organization: userModel.organization,
      configModel
    });

    const router = new GroupsRouter({
      rootUrl: userModel.viewUrl().organization().groups(),
      flashMessageModel,
      groups,
      userModel
    });

    const groupsMainView = new GroupsMainView({
      el: $groups,
      groups,
      routerModel: router,
      user: userModel
    });
    groupsMainView.render();

    router.enableAfterMainView();
  }
});
<|endoftext|>


<commit_before>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
*/

var cordova = require('cordova');

module.exports = {
    id: "blackberry10",
    initialize: function () {
        document.addEventListener("deviceready", function () {
            /*
             TODO
            blackberry.event.addEventListener("pause", function () {
                cordova.fireDocumentEvent("pause");
            });
            blackberry.event.addEventListener("resume", function () {
                cordova.fireDocumentEvent("resume");
            });
            */
            window.addEventListener("online", function () {
                cordova.fireDocumentEvent("online");
            });

            window.addEventListener("offline", function () {
                cordova.fireDocumentEvent("offline");
            });
        });
    },
    clobbers: {
        open: {
            path: "cordova/plugin/InAppBrowser"
        },
        requestFileSystem: {
            path: "cordova/plugin/blackberry10/requestFileSystem"
        }
    },
    merges: {
        navigator: {
            children: {
                compass: {
                    path: 'cordova/plugin/blackberry10/compass'
                }
            }
        }
    }
};
<commit_msg>[BlackBerry10] Remove window.open clobber so child window functions correctly<commit_after>/*
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 *
*/

var cordova = require('cordova');

module.exports = {
    id: "blackberry10",
    initialize: function () {
        document.addEventListener("deviceready", function () {
            /*
             TODO
            blackberry.event.addEventListener("pause", function () {
                cordova.fireDocumentEvent("pause");
            });
            blackberry.event.addEventListener("resume", function () {
                cordova.fireDocumentEvent("resume");
            });
            */
            window.addEventListener("online", function () {
                cordova.fireDocumentEvent("online");
            });

            window.addEventListener("offline", function () {
                cordova.fireDocumentEvent("offline");
            });
        });
    },
    clobbers: {
        requestFileSystem: {
            path: "cordova/plugin/blackberry10/requestFileSystem"
        }
    },
    merges: {
        navigator: {
            children: {
                compass: {
                    path: 'cordova/plugin/blackberry10/compass'
                }
            }
        }
    }
};
<|endoftext|>


<commit_before>
module.exports = {
  entries: [
    '~app/assets/my_app/index.js',
  ],
};
<commit_msg>chore(templates): use a hash as entries<commit_after>
module.exports = {
  entries: {
    application: '~app/assets/my_app/index.js',
  },
};
<|endoftext|>


<commit_before>'use strict';

/*
* When adding names to the namespace, ensure that they are added in alphabetical order according to alias (namespace key).
*/

var ns = [];

ns.push({
	'alias': 'hasClassSupport',
	'path': '@stdlib/utils/detect-class-support',
	'value': require( '@stdlib/utils/detect-class-support' ),
	'type': 'Function',
	'related': []
});

ns.push({
	'alias': 'hasFunctionNameSupport',
	'path': '@stdlib/utils/detect-function-name-support',
	'value': require( '@stdlib/utils/detect-function-name-support' ),
	'type': 'Function',
	'related': []
});

ns.push({
	'alias': 'hasGeneratorSupport',
	'path': '@stdlib/utils/detect-generator-support',
	'value': require( '@stdlib/utils/detect-generator-support' ),
	'type': 'Function',
	'related': []
});

ns.push({
	'alias': 'hasMapSupport',
	'path': '@stdlib/utils/detect-map-support',
	'value': require( '@stdlib/utils/detect-map-support' ),
	'type': 'Function',
	'related': []
});

ns.push({
	'alias': 'hasOwnProp',
	'path': '@stdlib/utils/has-own-property',
	'value': require( '@stdlib/utils/has-own-property' ),
	'type': 'Function',
	'related': []
});

ns.push({
	'alias': 'hasPrototype',
	'path': '@stdlib/utils/has-prototype',
	'value': require( '@stdlib/utils/has-prototype' ),
	'type': 'Function',
	'related': [
		'@stdlib/utils/get-prototype-of'
	]
});

ns.push({
	'alias': 'hasSetSupport',
	'path': '@stdlib/utils/detect-set-support',
	'value': require( '@stdlib/utils/detect-set-support' ),
	'type': 'Function',
	'related': []
});

ns.push({
	'alias': 'hasSymbolSupport',
	'path': '@stdlib/utils/detect-symbol-support',
	'value': require( '@stdlib/utils/detect-symbol-support' ),
	'type': 'Function',
	'related': []
});

ns.push({
	'alias': 'hasToStringTagSupport',
	'path': '@stdlib/utils/detect-tostringtag-support',
	'value': require( '@stdlib/utils/detect-tostringtag-support' ),
	'type': 'Function',
	'related': []
});

ns.push({
	'alias': 'hasWeakMapSupport',
	'path': '@stdlib/utils/detect-weakmap-support',
	'value': require( '@stdlib/utils/detect-weakmap-support' ),
	'type': 'Function',
	'related': []
});

ns.push({
	'alias': 'hasWeakSetSupport',
	'path': '@stdlib/utils/detect-weakset-support',
	'value': require( '@stdlib/utils/detect-weakset-support' ),
	'type': 'Function',
	'related': []
});

ns.push({
	'alias': 'homedir',
	'path': '@stdlib/utils/homedir',
	'value': require( '@stdlib/utils/homedir' ),
	'type': 'Function',
	'related': [
		'@stdlib/utils/configdir',
		'@stdlib/utils/tmpdir'
	]
});

ns.push({
	'alias': 'HOURS_IN_DAY',
	'path': '@stdlib/time/constants/hours-in-day',
	'value': require( '@stdlib/time/constants/hours-in-day' ),
	'type': 'number',
	'related': [
		'@stdlib/time/constants/hours-in-week'
	]
});

ns.push({
	'alias': 'HOURS_IN_WEEK',
	'path': '@stdlib/time/constants/hours-in-week',
	'value': require( '@stdlib/time/constants/hours-in-week' ),
	'type': 'number',
	'related': [
		'@stdlib/time/constants/hours-in-day'
	]
});

ns.push({
	'alias': 'httpServer',
	'path': '@stdlib/net/http-server',
	'value': require( '@stdlib/net/http-server' ),
	'type': 'Function',
	'related': []
});

// EXPORTS //

module.exports = ns;
<commit_msg>Update namespace<commit_after>'use strict';

/*
* When adding names to the namespace, ensure that they are added in alphabetical order according to alias (namespace key).
*/

var ns = [];

ns.push({
	'alias': 'hasClassSupport',
	'path': '@stdlib/utils/detect-class-support',
	'value': require( '@stdlib/utils/detect-class-support' ),
	'type': 'Function',
	'related': []
});

ns.push({
	'alias': 'hasFunctionNameSupport',
	'path': '@stdlib/utils/detect-function-name-support',
	'value': require( '@stdlib/utils/detect-function-name-support' ),
	'type': 'Function',
	'related': []
});

ns.push({
	'alias': 'hasGeneratorSupport',
	'path': '@stdlib/utils/detect-generator-support',
	'value': require( '@stdlib/utils/detect-generator-support' ),
	'type': 'Function',
	'related': []
});

ns.push({
	'alias': 'hasMapSupport',
	'path': '@stdlib/utils/detect-map-support',
	'value': require( '@stdlib/utils/detect-map-support' ),
	'type': 'Function',
	'related': []
});

ns.push({
	'alias': 'hasOwnProp',
	'path': '@stdlib/utils/has-own-property',
	'value': require( '@stdlib/utils/has-own-property' ),
	'type': 'Function',
	'related': []
});

ns.push({
	'alias': 'hasPrototype',
	'path': '@stdlib/utils/has-prototype',
	'value': require( '@stdlib/utils/has-prototype' ),
	'type': 'Function',
	'related': [
		'@stdlib/utils/get-prototype-of'
	]
});

ns.push({
	'alias': 'hasSetSupport',
	'path': '@stdlib/utils/detect-set-support',
	'value': require( '@stdlib/utils/detect-set-support' ),
	'type': 'Function',
	'related': []
});

ns.push({
	'alias': 'hasSymbolSupport',
	'path': '@stdlib/utils/detect-symbol-support',
	'value': require( '@stdlib/utils/detect-symbol-support' ),
	'type': 'Function',
	'related': []
});

ns.push({
	'alias': 'hasToStringTagSupport',
	'path': '@stdlib/utils/detect-tostringtag-support',
	'value': require( '@stdlib/utils/detect-tostringtag-support' ),
	'type': 'Function',
	'related': []
});

ns.push({
	'alias': 'hasWeakMapSupport',
	'path': '@stdlib/utils/detect-weakmap-support',
	'value': require( '@stdlib/utils/detect-weakmap-support' ),
	'type': 'Function',
	'related': []
});

ns.push({
	'alias': 'hasWeakSetSupport',
	'path': '@stdlib/utils/detect-weakset-support',
	'value': require( '@stdlib/utils/detect-weakset-support' ),
	'type': 'Function',
	'related': []
});

ns.push({
	'alias': 'homedir',
	'path': '@stdlib/utils/homedir',
	'value': require( '@stdlib/utils/homedir' ),
	'type': 'Function',
	'related': [
		'@stdlib/utils/configdir',
		'@stdlib/utils/tmpdir'
	]
});

ns.push({
	'alias': 'HOURS_IN_DAY',
	'path': '@stdlib/time/constants/hours-in-day',
	'value': require( '@stdlib/time/constants/hours-in-day' ),
	'type': 'number',
	'related': [
		'@stdlib/time/constants/hours-in-week'
	]
});

ns.push({
	'alias': 'HOURS_IN_WEEK',
	'path': '@stdlib/time/constants/hours-in-week',
	'value': require( '@stdlib/time/constants/hours-in-week' ),
	'type': 'number',
	'related': [
		'@stdlib/time/constants/hours-in-day'
	]
});

ns.push({
	'alias': 'hoursInMonth',
	'path': '@stdlib/time/hours-in-month',
	'value': require( '@stdlib/time/hours-in-month' ),
	'type': 'Function',
	'related': [
		'@stdlib/time/hours-in-year'
	]
});

ns.push({
	'alias': 'hoursInYear',
	'path': '@stdlib/time/hours-in-year',
	'value': require( '@stdlib/time/hours-in-year' ),
	'type': 'Function',
	'related': [
		'@stdlib/time/hours-in-month'
	]
});

ns.push({
	'alias': 'httpServer',
	'path': '@stdlib/net/http-server',
	'value': require( '@stdlib/net/http-server' ),
	'type': 'Function',
	'related': []
});

// EXPORTS //

module.exports = ns;
<|endoftext|>