<commit_before>function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');
    gvm.studentId = $("#saveBtn").data('value');

    // 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.menuLanguage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("MenuLanguage");}, gvm);

    gvm.nameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("NameTableTitle");}, gvm);
    gvm.assessCompletementNumberToSubmit = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AssessCompletementNumberToSubmit");}, gvm);
    gvm.projectWeight = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectWeight");}, gvm);
    gvm.assessCompletementNumberSubmitted = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AssessCompletementNumberSubmitted");}, gvm);
    gvm.saveBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm);
    gvm.cancelBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("CancelBtn");}, gvm);
    gvm.documentScore = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("DocumentScore");}, gvm);

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

    gvm.documents = ko.observableArray([]);
    gvm.userData = ko.observableArray([]);

    gvm.addDocument = function(id,parentId, description, weight, pointType,score) {
        gvm.documents.push(new Document(id,parentId,description,weight,pointType,score));
    };

    gvm.getAllData = function()
    {
        $.getJSON('/api/project/'+ gvm.projectId + '/documents/' + gvm.studentId, function(data) {
            console.log("getAllData");
            console.log(data);
            $.each(data, function(i, item) {
                gvm.enterData(item);
                gvm.userData.push(item);
            });
        });
    };

    gvm.enterData = function(data)
    {
        gvm.documents().forEach(function(item) {
            console.log(data);
            console.log(item);
           if(data.document == item.parentId()) {
               item.id(data.id);
               item.score(data.score);
           }
        });
    };

    gvm.getDocumentsToSubmit = function() {
        $.getJSON('/api/project/'+ gvm.projectId + '/documents', function(data) {
            $.each(data, function(i, item) {
                gvm.addDocument(0, item.id, item.description, item.weight, item.point_type, 0);
            });
            gvm.getAllData();
        });
    };

    gvm.clearStructure = function()
    {
        gvm.userData.destroyAll();
        gvm.documents.destroyAll();
    }
}

function Document(id,parentId,description ,weight,pointType, score)
{
    return {
        id: ko.observable(id),
        parentId: ko.observable(parentId),
        description: ko.observable(description),
        pointType: ko.observable(pointType),
        weight: ko.observable(weight),
        score: ko.observable(score)
    }
}

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

    $("#saveBtn").click(function() {
        $.ajax({
            type: "POST",
            url: "/api/documents/" + projectid + "/user/" + viewModel.studentId + "/save",
            data: ko.toJSON(viewModel.documents),
            success: function(){
                // TODO make multilangual and with modals
                alert("Saved document completeness to server");
                viewModel.clearStructure();
                viewModel.getProjectInfo();
                viewModel.getAllData();
            }
        });
    });

    var url = '/assess/project/' + projectid + '/students';
    $("#cancelBtn").click(function()
    {
        window.location.href = url;
    });
}
<commit_msg>Grade documents<commit_after>function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');
    gvm.studentId = $("#saveBtn").data('value');

    // 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.menuLanguage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("MenuLanguage");}, gvm);

    gvm.nameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("NameTableTitle");}, gvm);
    gvm.assessCompletementNumberToSubmit = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AssessCompletementNumberToSubmit");}, gvm);
    gvm.projectWeight = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectWeight");}, gvm);
    gvm.assessCompletementNumberSubmitted = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AssessCompletementNumberSubmitted");}, gvm);
    gvm.saveBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm);
    gvm.cancelBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("CancelBtn");}, gvm);
    gvm.documentScore = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("DocumentScore");}, gvm);

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

    gvm.documents = ko.observableArray([]);
    gvm.userData = ko.observableArray([]);

    gvm.addDocument = function(id,parentId, description, weight, pointType,score) {
        gvm.documents.push(new Document(id,parentId,description,weight,pointType,score));
    };

    gvm.getAllData = function()
    {
        $.getJSON('/api/project/'+ gvm.projectId + '/documents/' + gvm.studentId, function(data) {
            console.log("getAllData");
            console.log(data);
            $.each(data, function(i, item) {
                gvm.enterData(item);
                gvm.userData.push(item);
            });
        });
    };

    gvm.enterData = function(data)
    {
        gvm.documents().forEach(function(item) {
            console.log(data);
            console.log(item);
           if(data.document == item.parentId()) {
               item.id(data.id);
               item.score(data.score);
           }
        });
    };

    gvm.getDocumentsToSubmit = function() {
        $.getJSON('/api/project/'+ gvm.projectId + '/documents', function(data) {
            $.each(data, function(i, item) {
                gvm.addDocument(0, item.id, item.description, item.weight, item.point_type, 0);
            });
            gvm.getAllData();
        });
    };

    gvm.clearStructure = function()
    {
        gvm.userData.destroyAll();
        gvm.documents.destroyAll();
    }
}

function Document(id,parentId,description ,weight,pointType, score)
{
    return {
        id: ko.observable(id),
        parentId: ko.observable(parentId),
        description: ko.observable(description),
        pointType: ko.observable(pointType),
        weight: ko.observable(weight),
        score: ko.observable(score)
    }
}

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

    $("#saveBtn").click(function() {
        $.ajax({
            type: "POST",
            url: "/api/documents/" + projectid + "/user/" + viewModel.studentId + "/save",
            data: ko.toJSON(viewModel.documents),
            success: function(){
                // TODO make multilangual and with modals
                alert("Saved document completeness to server");
                viewModel.clearStructure();
                viewModel.getProjectInfo();
                viewModel.getDocumentsToSubmit();
            }
        });
    });

    var url = '/assess/project/' + projectid + '/students';
    $("#cancelBtn").click(function()
    {
        window.location.href = url;
    });
}
<|endoftext|>


<commit_before>function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');
    gvm.studentId = $("#saveBtn").data('value');

    // 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.menuLanguage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("MenuLanguage");}, gvm);

    gvm.nameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("NameTableTitle");}, gvm);
    gvm.assessCompletementNumberToSubmit = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AssessCompletementNumberToSubmit");}, gvm);
    gvm.projectWeight = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectWeight");}, gvm);
    gvm.assessCompletementNumberSubmitted = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AssessCompletementNumberSubmitted");}, gvm);
    gvm.saveBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm);
    gvm.cancelBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("CancelBtn");}, gvm);
    gvm.documentScore = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("DocumentScore");}, gvm);
    gvm.documentSubmit = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("DocumentSubmit");}, gvm);

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

    gvm.documents = ko.observableArray([]);
    gvm.userData = ko.observableArray([]);

    gvm.addDocument = function(id,parentId, description, weight, pointType,score, nrDocuments, notSubmitted, nrNotSubmitted) {
        var doc = new Document(id,parentId,description,weight,pointType,score, nrDocuments, notSubmitted, nrNotSubmitted);
        gvm.documents.push(doc);
    };

    gvm.getAllData = function()
    {
        $.getJSON('/api/project/'+ gvm.projectId + '/documents/' + gvm.studentId, function(data) {
            $.each(data, function(i, item) {
                gvm.enterData(item);
                gvm.userData.push(item);
            });
        });
    };

    gvm.enterData = function(data)
    {
        gvm.documents().forEach(function(item) {
           if(data.document == item.parentId()) {
               item.id(data.id);
               item.score(data.score);
               item.notSubmitted(data.not_submitted);
               if (item.pointType() == "Ja/Nee") {
                   if (item.score() > 0) {
                       item.isChecked("yes");
                       item.score(100);
                   }
                   else {
                       item.isChecked("no");
                       item.score(0);
                   }
               }
           }
        });
        console.log(gvm.documents());
    };

    gvm.getDocumentsToSubmit = function() {
        $.getJSON('/api/project/'+ gvm.projectId + '/documents', function(data) {
            $.each(data, function(i, item) {
                var array = [];
                var numberArray = [];
                for(var i = 0; i <= item.nr_documents; i++)
                {
                    array.push(new AssessedDocument(0,0,0, item.point_type));
                    numberArray.push(i);
                }
                gvm.addDocument(0, item.id, item.description, item.weight, item.point_type, 0, array,0,numberArray);
            });
            gvm.getAllData();
        });
    };

    gvm.changeNotSubmitted = function(data,parent) {
        data.notSubmitted(parent);
        var len = data.nrNotSubmitted.length - data.notSubmitted() - 1;
        console.log(len);
        var point = data.pointType();
        data.nrDocuments([]);
        for(var i = 0; i < len; i++)
        {
            data.nrDocuments.push(0,0,0,point);
        }
    };

    gvm.clearStructure = function()
    {
        gvm.userData.destroyAll();
        gvm.documents.destroyAll();
    }
}

function AssessedDocument(id,parentId, score, pointType) {
    return {
        id: ko.observable(id),
        parentId: ko.observable(parentId),
        assessScore: ko.observable(score),
        pointType: ko.observable(pointType)
    }
}

function Document(id,parentId,description ,weight,pointType, score, nrDocuments, notSubmitted,nrNotSubmitted, checked)
{
    var self = this;
    console.log(nrDocuments);
    self.documents = {
        id: ko.observable(id),
        parentId: ko.observable(parentId),
        description: ko.observable(description),
        pointType: ko.observable(pointType),
        weight: ko.observable(weight),
        score: ko.observable(score),
        isChecked: ko.observable(checked),
        nrNotSubmitted: ko.observableArray(nrNotSubmitted),
        nrDocuments: ko.observableArray(nrDocuments),
        notSubmitted: ko.observable(notSubmitted)
    }

    self.documents.checkedValue =  ko.computed({
        //return a formatted price
        read: function() {
            return self.documents.isChecked();
        },
        //if the value changes, make sure that we store a number back to price
        write: function(newValue) {
            self.documents.isChecked(newValue);
            if(self.documents.isChecked() == "yes")
            {
                self.documents.score(100);
            }
            else {
                self.documents.score(0);
            }
        },
        owner: this
    });

    return self.documents;
}

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

    $('.table-responsive').on('show.bs.dropdown', function () {
        $('.table-responsive').css( "overflow", "inherit" );
    });

    $('.table-responsive').on('hide.bs.dropdown', function () {
        $('.table-responsive').css( "overflow", "auto" );
    })

    $("#saveBtn").click(function() {
        $.ajax({
            type: "POST",
            url: "/api/documents/" + projectid + "/user/" + viewModel.studentId + "/save",
            data: ko.toJSON(viewModel.documents),
            success: function(){
                // TODO make multilangual and with modals
                alert("Saved document completeness to server");
                viewModel.clearStructure();
                viewModel.getProjectInfo();
                viewModel.getDocumentsToSubmit();
            }
        });
    });

    var url = '/assess/project/' + projectid + '/students';
    $("#cancelBtn").click(function()
    {
        window.location.href = url;
    });
}
<commit_msg>Grade documents<commit_after>function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.projectId = $("#projectHeader").data('value');
    gvm.studentId = $("#saveBtn").data('value');

    // 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.menuLanguage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("MenuLanguage");}, gvm);

    gvm.nameTableTitle = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("NameTableTitle");}, gvm);
    gvm.assessCompletementNumberToSubmit = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AssessCompletementNumberToSubmit");}, gvm);
    gvm.projectWeight = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectWeight");}, gvm);
    gvm.assessCompletementNumberSubmitted = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AssessCompletementNumberSubmitted");}, gvm);
    gvm.saveBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm);
    gvm.cancelBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("CancelBtn");}, gvm);
    gvm.documentScore = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("DocumentScore");}, gvm);
    gvm.documentSubmit = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("DocumentSubmit");}, gvm);

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

    gvm.documents = ko.observableArray([]);
    gvm.userData = ko.observableArray([]);

    gvm.addDocument = function(id,parentId, description, weight, pointType,score, nrDocuments, notSubmitted, nrNotSubmitted) {
        var doc = new Document(id,parentId,description,weight,pointType,score, nrDocuments, notSubmitted, nrNotSubmitted);
        gvm.documents.push(doc);
    };

    gvm.getAllData = function()
    {
        $.getJSON('/api/project/'+ gvm.projectId + '/documents/' + gvm.studentId, function(data) {
            $.each(data, function(i, item) {
                gvm.enterData(item);
                gvm.userData.push(item);
            });
        });
    };

    gvm.enterData = function(data)
    {
        gvm.documents().forEach(function(item) {
           if(data.document == item.parentId()) {
               item.id(data.id);
               item.score(data.score);
               item.notSubmitted(data.not_submitted);
               if (item.pointType() == "Ja/Nee") {
                   if (item.score() > 0) {
                       item.isChecked("yes");
                       item.score(100);
                   }
                   else {
                       item.isChecked("no");
                       item.score(0);
                   }
               }
           }
        });
        console.log(gvm.documents());
    };

    gvm.getDocumentsToSubmit = function() {
        $.getJSON('/api/project/'+ gvm.projectId + '/documents', function(data) {
            $.each(data, function(i, item) {
                var array = [];
                var numberArray = [];
                for(var i = 0; i <= item.nr_documents; i++)
                {
                    array.push(new AssessedDocument(0,0,0, item.point_type));
                    numberArray.push(i);
                }
                gvm.addDocument(0, item.id, item.description, item.weight, item.point_type, 0, array,0,numberArray);
            });
            gvm.getAllData();
        });
    };

    gvm.changeNotSubmitted = function(data,parent) {
        data.notSubmitted(parent);
        var len = data.nrNotSubmitted().length - data.notSubmitted() - 1;
        console.log(len);
        var point = data.pointType();
        data.nrDocuments([]);
        for(var i = 0; i < len; i++)
        {
            data.nrDocuments.push(0,0,0,point);
        }
    };

    gvm.clearStructure = function()
    {
        gvm.userData.destroyAll();
        gvm.documents.destroyAll();
    }
}

function AssessedDocument(id,parentId, score, pointType) {
    return {
        id: ko.observable(id),
        parentId: ko.observable(parentId),
        assessScore: ko.observable(score),
        pointType: ko.observable(pointType)
    }
}

function Document(id,parentId,description ,weight,pointType, score, nrDocuments, notSubmitted,nrNotSubmitted, checked)
{
    var self = this;
    console.log(nrDocuments);
    self.documents = {
        id: ko.observable(id),
        parentId: ko.observable(parentId),
        description: ko.observable(description),
        pointType: ko.observable(pointType),
        weight: ko.observable(weight),
        score: ko.observable(score),
        isChecked: ko.observable(checked),
        nrNotSubmitted: ko.observableArray(nrNotSubmitted),
        nrDocuments: ko.observableArray(nrDocuments),
        notSubmitted: ko.observable(notSubmitted)
    }

    self.documents.checkedValue =  ko.computed({
        //return a formatted price
        read: function() {
            return self.documents.isChecked();
        },
        //if the value changes, make sure that we store a number back to price
        write: function(newValue) {
            self.documents.isChecked(newValue);
            if(self.documents.isChecked() == "yes")
            {
                self.documents.score(100);
            }
            else {
                self.documents.score(0);
            }
        },
        owner: this
    });

    return self.documents;
}

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

    $('.table-responsive').on('show.bs.dropdown', function () {
        $('.table-responsive').css( "overflow", "inherit" );
    });

    $('.table-responsive').on('hide.bs.dropdown', function () {
        $('.table-responsive').css( "overflow", "auto" );
    })

    $("#saveBtn").click(function() {
        $.ajax({
            type: "POST",
            url: "/api/documents/" + projectid + "/user/" + viewModel.studentId + "/save",
            data: ko.toJSON(viewModel.documents),
            success: function(){
                // TODO make multilangual and with modals
                alert("Saved document completeness to server");
                viewModel.clearStructure();
                viewModel.getProjectInfo();
                viewModel.getDocumentsToSubmit();
            }
        });
    });

    var url = '/assess/project/' + projectid + '/students';
    $("#cancelBtn").click(function()
    {
        window.location.href = url;
    });
}
<|endoftext|>


<commit_before>import Automaton, { State, Transition } from './automaton'
import { UnknownCharError, UnknownStateError,
	     DeterminismError, NoInitialStateError,
		 DuplicateStateError, NoFinalStatesError } from '../errors'
import { pipeTransitions, recursiveTransitionsFirst } from './utils'
import { minimize } from '../core/minimization'
import { epsilon } from '../constants'

export default class DFA extends Automaton {
	removeTransition (from, a) {
		this.states = this.states.map(e => {
			if (e.name === from)
				e.transitions = e.transitions.filter(t => t.a !== a)
			return e
		})
	}
	editTransition (_from, a, { from, to }) {
		this.states = this.states.map(e => {
			if (e.name === _from)
				if (e.name !== from)
					e.transitions = e.transitions.filter(t => t.a !== a)
				else
					e.transitions = e.transitions.map(t => {
						if (t.a === a)
							t.to = to
						return t
					})
			else if (e.name === from)
				this.addTransition(e.name, a, to)
			return e
		})
	}
	transitionIsDeterministic(from, a) {
		return !from.transitions.filter(e => e.a === a)[0]
	}
	extraTransitionValidations (from, a, to) {
		if (!this.transitionIsDeterministic(this.getState(from), a))
			throw new DeterminismError(from, a)
	}
	run (w) {
		if (!this.initialState)
			throw new NoInitialStateError()

		let currState = this.getState(this.initialState)

		for (let a of w) {
			const t = currState.transitions.filter(e => e.a === a)[0]

			if (!t)
				return false

			currState = this.states.filter(e => e.name === t.to)[0]
		}

		return this.stateIsFinal(currState.name)
	}
	toRegex() {
		if (!this.initialState)
			throw new NoInitialStateError()
		if (!this.finalStates.length)
			throw new NoFinalStatesError()

		const clone = new DFA([])
		clone.setFromAutomaton(this)
		clone.charInAlphabet = c => true
		clone.extraTransitionValidations = () => {}

		const uniqueStateId = new Date().getTime()

		const transitionsToInitial = clone.getTransitionsTo(clone.initialState)

		if (transitionsToInitial.length > 0) {
			const newInitStateName = 'q0' + uniqueStateId
			clone.addState(newInitStateName, false)
			clone.addTransition(newInitStateName, epsilon, clone.initialState)
			clone.setInitialState(newInitStateName)
		}

		if (clone.finalStates.length > 1 ||
		    (clone.finalStates.length === 1 &&
			clone.getState(clone.finalStates[0]).transitions.length > 0)) {

			const newFinalStateName = 'fs' + uniqueStateId
			clone.addState(newFinalStateName, false)

			for (const fs of clone.finalStates) {
				clone.addTransition(fs, epsilon, newFinalStateName)
				clone.removeFinal(fs)
			}

			clone.addFinal(newFinalStateName)
		}

		const normalStates = clone.states
			.filter(({name}) =>
				(!clone.stateIsInitial(name) && !clone.stateIsFinal(name)))

		// let i = 1

		for (const ns of normalStates) {
			const transitionsToNs   = clone.getTransitionsTo(ns.name).filter(t => t.from !== ns.name)
			const transitionsFromNs = pipeTransitions(ns.transitions).sort(recursiveTransitionsFirst)

			// console.log(`${i}`)

			for (const transTo of transitionsToNs) {
				const newTrans = new Transition(transTo.from, transTo.a, '')

				if (newTrans.a === epsilon) newTrans.a = ''

				for (const transFrom of transitionsFromNs) {
					const isRecursive = transFrom.from === transFrom.to

					if (transFrom.a === epsilon) transFrom.a = ''

					if (isRecursive)
						newTrans.a += transFrom.a.length > 1 ? `(${transFrom.a})*` : `${transFrom.a}*`
					else {
						let a = transFrom.a.includes('+') ? `(${transFrom.a})` : transFrom.a
						clone.addTransition(newTrans.from, `${newTrans.a}${a}`, transFrom.to)
					}

					// console.log([ ...clone.states ].map(s => s.transitions))
				}

				// console.log(`ABOUT TO REMOVE TRANSITION: From State: ${transTo.from} === Symbol: ${transTo.a}`)
				clone.states = clone.states.map(e => {
					if (e.name === transTo.from)
						e.transitions = e.transitions.filter(t => !(t.a === transTo.a && t.to === transTo.to))
					return e
				})
			}

			// clone.removeState(ns.name)
			// i++
		}

		return pipeTransitions(clone.states[0].transitions)[0].a
	}
	clone() {
		const a = new DFA([])
		a.setFromAutomaton(this)
		return a
	}
	minimize() {
		return minimize(this)
	}

}<commit_msg>Refactor for better polymorphism<commit_after>import Automaton, { State, Transition } from './automaton'
import { UnknownCharError, UnknownStateError,
	     DeterminismError, NoInitialStateError,
		 DuplicateStateError, NoFinalStatesError } from '../errors'
import { pipeTransitions, recursiveTransitionsFirst } from './utils'
import { minimize } from '../core/minimization'
import { epsilon } from '../constants'

export default class DFA extends Automaton {
	removeTransition (from, a) {
		this.states = this.states.map(e => {
			if (e.name === from)
				e.transitions = e.transitions.filter(t => !this.transitionMatches(t.a, a))
			return e
		})
	}
	editTransition (_from, a, { from, to }) {
		this.states = this.states.map(e => {
			if (e.name === _from)
				if (e.name !== from)
					e.transitions = e.transitions.filter(t => !this.transitionMatches(t.a, a))
				else
					e.transitions = e.transitions.map(t => {
						if (this.transitionMatches(t.a, a))
							t.to = to
						return t
					})
			else if (e.name === from)
				this.addTransition(e.name, a, to)
			return e
		})
	}
	transitionIsDeterministic(from, a) {
		return !from.transitions.filter(e => this.transitionMatches(e.a, a))[0]
	}
	extraTransitionValidations (from, a, to) {
		if (!this.transitionIsDeterministic(this.getState(from), a))
			throw new DeterminismError(from, a)
	}
	transitionMatches(symbolA, symbolB) {
		return symbolA === symbolB
	}
	nextStateFromTrans(t) {
		return this.getState(t.to)
	}
	getNextState(currState, a) {
		return currState.transitions
			.filter(e => this.transitionMatches(e.a, a))
				.map(this.nextStateFromTrans.bind(this))[0]
	}
	runInit(w){}
	run (w) {
		if (!this.initialState)
			throw new NoInitialStateError()

		let currState = this.getState(this.initialState)

		this.runInit(w)

		for (let a of w)
			if (!currState)
				return false
			else
				currState = this.getNextState(currState, a)

		return currState && this.stateIsFinal(currState.name)
	}
	toRegex() {
		if (!this.initialState)
			throw new NoInitialStateError()
		if (!this.finalStates.length)
			throw new NoFinalStatesError()

		const clone = new DFA([])
		clone.setFromAutomaton(this)
		clone.charInAlphabet = c => true
		clone.extraTransitionValidations = () => {}

		const uniqueStateId = new Date().getTime()

		const transitionsToInitial = clone.getTransitionsTo(clone.initialState)

		if (transitionsToInitial.length > 0) {
			const newInitStateName = 'q0' + uniqueStateId
			clone.addState(newInitStateName, false)
			clone.addTransition(newInitStateName, epsilon, clone.initialState)
			clone.setInitialState(newInitStateName)
		}

		if (clone.finalStates.length > 1 ||
		    (clone.finalStates.length === 1 &&
			clone.getState(clone.finalStates[0]).transitions.length > 0)) {

			const newFinalStateName = 'fs' + uniqueStateId
			clone.addState(newFinalStateName, false)

			for (const fs of clone.finalStates) {
				clone.addTransition(fs, epsilon, newFinalStateName)
				clone.removeFinal(fs)
			}

			clone.addFinal(newFinalStateName)
		}

		const normalStates = clone.states
			.filter(({name}) =>
				(!clone.stateIsInitial(name) && !clone.stateIsFinal(name)))

		// let i = 1

		for (const ns of normalStates) {
			const transitionsToNs   = clone.getTransitionsTo(ns.name).filter(t => t.from !== ns.name)
			const transitionsFromNs = pipeTransitions(ns.transitions).sort(recursiveTransitionsFirst)

			// console.log(`${i}`)

			for (const transTo of transitionsToNs) {
				const newTrans = new Transition(transTo.from, transTo.a, '')

				if (newTrans.a === epsilon) newTrans.a = ''

				for (const transFrom of transitionsFromNs) {
					const isRecursive = transFrom.from === transFrom.to

					if (transFrom.a === epsilon) transFrom.a = ''

					if (isRecursive)
						newTrans.a += transFrom.a.length > 1 ? `(${transFrom.a})*` : `${transFrom.a}*`
					else {
						let a = transFrom.a.includes('+') ? `(${transFrom.a})` : transFrom.a
						clone.addTransition(newTrans.from, `${newTrans.a}${a}`, transFrom.to)
					}

					// console.log([ ...clone.states ].map(s => s.transitions))
				}

				// console.log(`ABOUT TO REMOVE TRANSITION: From State: ${transTo.from} === Symbol: ${transTo.a}`)
				clone.states = clone.states.map(e => {
					if (e.name === transTo.from)
						e.transitions = e.transitions.filter(t => !(t.a === transTo.a && t.to === transTo.to))
					return e
				})
			}

			// clone.removeState(ns.name)
			// i++
		}

		return pipeTransitions(clone.states[0].transitions)[0].a
	}
	clone() {
		const a = new DFA([])
		a.setFromAutomaton(this)
		return a
	}
	minimize() {
		return minimize(this)
	}

}<|endoftext|>


<commit_before>/*
* Unobtrusive autocomplete
*
* To use it, you just have to include the HTML attribute autocomplete
* with the autocomplete URL as the value
*
*   Example:
*       <input type="text" data-autocomplete="/url/to/autocomplete">
*
* Optionally, you can use a jQuery selector to specify a field that can
* be updated with the element id whenever you find a matching value
*
*   Example:
*       <input type="text" data-autocomplete="/url/to/autocomplete" id_element="#id_field">
*/

$(document).ready(function(){
  $('input[data-autocomplete]').live('focus', function(i){
    $(this).autocomplete({
      source: $(this).attr('data-autocomplete'),
      select: function(event, ui) {
        $(this).val(ui.item.value);
        if ($(this).attr('id_element')) {
          $($(this).attr('id_element')).val(ui.item.id);
        }
        return false;
      }
    });
  });
});
<commit_msg>Modified from jqueryUI multiple example. If data-delimiter attr is present, will only send / replace last elem, splitting on delimiter<commit_after>/*
* Unobtrusive autocomplete
*
* To use it, you just have to include the HTML attribute autocomplete
* with the autocomplete URL as the value
*
*   Example:
*       <input type="text" data-autocomplete="/url/to/autocomplete">
*
* Optionally, you can use a jQuery selector to specify a field that can
* be updated with the element id whenever you find a matching value
*
*   Example:
*       <input type="text" data-autocomplete="/url/to/autocomplete" id_element="#id_field">
*/

$(document).ready(function(){
  $('input[data-autocomplete]').live('focus', function(i){
		this.delimiter = $(this).attr('data-delimiter') || null;
		_selfinput = this;
		function split( val ) {
			return val.split( _selfinput.delimiter );
		}
		function extractLast( term ) {
			return split( term ).pop();
		}

    $(this).autocomplete({
      source: $(this).attr('data-autocomplete'),
			search: function() {
				// custom minLength
				var term = extractLast( this.value );
				if ( term.length < 2 ) {
					return false;
				}
			},
			select: function( event, ui ) {
				var terms = split( this.value );
				// remove the current input
				terms.pop();
				// add the selected item
				terms.push( ui.item.value );
				// add placeholder to get the comma-and-space at the end
				console.log(_selfinput.delimiter);
				if (_selfinput.delimiter != null) {
					terms.push( "" );
					this.value = terms.join( _selfinput.delimiter );
				} else {
					this.value = terms.join("");
				};

				return false;
			}

    });
  });
});
<|endoftext|>


<commit_before>'use strict';

var app = require('app');
var BrowserWindow = require('browser-window');
var angular = require('./js/libs/ext/ng-electron/ng-bridge');
var ncp = require('ncp').ncp;
ncp.limit = 16;

var kill = require('tree-kill');
var cp = require('child_process');

var commandLineArgs = require('command-line-args')

var optionDefinitions = [
  { name: 'dev', type: Boolean, defaultOption: false },
  { name: 'version', type: String }
];

var options = commandLineArgs(optionDefinitions)

var server;

var visualizationWindows = [];

var mainWindow = null;
var welcomeMenu = null;

var Menu = require('menu');
var MenuItem = require('menu-item');
var Dialog = require('dialog');

// Quit when all windows are closed and no other one is listening to this.
app.on('window-all-closed', function() {
  if (app.listeners('window-all-closed').length == 1) {
    if (server) kill(server.pid, 'SIGKILL', function(err) {
      app.quit();
    });
  }
});

var openDialog = function(type, win) {
  angular.send({
    type: 'openDialog',
    data: type
  }, win);
};

var setOsxMenu = function(menu) {
  Menu.setApplicationMenu(menu);
};

var buildHelpMenu = function(mainMenu) {

  // Help menu
  var helpMenu = new Menu();
  helpMenu.append(new MenuItem({
    label: 'About',
    click: function() {
      angular.send({
        type: 'openHelp',
        data: app.getVersion()
      });
    }
  }));
  mainMenu.append(new MenuItem({
    label: 'Help',
    role: 'help',
    submenu: helpMenu
  }));

};

var buildViewMenu = function(mainMenu) {

  // Debug menu
  var viewMenu = new Menu();
  viewMenu.append(new MenuItem({
    label: 'Reload',
    accelerator: 'CmdOrCtrl+R',
    click: function(item, focusedWindow) {
      if (focusedWindow)
        focusedWindow.reload();
    }
  }));
  viewMenu.append(new MenuItem({
    label: 'Open Groovy Console',
    click: function(item, focusedWindow) {
      openDialog('GroovyConsoleSession', focusedWindow);
    }
  }));
  viewMenu.append(new MenuItem({
    label: 'Toggle Full Screen',
    accelerator: (function() {
      if (process.platform == 'darwin')
        return 'Ctrl+Command+F';
      else
        return 'F11';
    })(),
    click: function(item, focusedWindow) {
      if (focusedWindow)
        focusedWindow.setFullScreen(!focusedWindow.isFullScreen());
    }
  }));
  viewMenu.append(new MenuItem({
    label: 'Toggle Developer Tools',
    accelerator: (function() {
      if (process.platform == 'darwin')
        return 'Alt+Command+I';
      else
        return 'Ctrl+Shift+I';
    })(),
    click: function(item, focusedWindow) {
      if (focusedWindow)
        focusedWindow.toggleDevTools();
    }
  }));
  viewMenu.append(new MenuItem({
    label: 'User Interactions Log',
    click: function(item, focusedWindow) {
      openDialog('UserInteractions', focusedWindow);
    }
  }));
  mainMenu.append(new MenuItem({
    label: 'View',
    submenu: viewMenu
  }));

};

var buildFileMenu = function(mainMenu) {

  // File menu
  var fileMenu = new Menu();
  fileMenu.append(new MenuItem({
    label: 'Open Visualization',
    accelerator: (function() {
      if (process.platform == 'darwin')
        return 'Alt+Command+O';
      else
        return 'Ctrl+Shift+O';
    })(),
    click: function() {
      Dialog.showOpenDialog({
          title: 'Open BMotionWeb Visualization',
          filters: [{
            name: 'BMotionWeb Manifest (bmotion.json)',
            extensions: ['json']
          }, {
            name: 'Formal Model (*.mch, *.csp, *.bcm, *.bcc)',
            extensions: ['mch', 'csp', 'bcm', 'bcc']
          }],
          properties: ['openFile']
        },
        function(files) {
          if (files) {
            var filename = files[0].replace(/^.*[\\\/]/, '');
            var fileExtension = filename.split('.').pop();
            angular.send({
              type: fileExtension === 'json' ? 'startVisualisationViaFileMenu' : 'startFormalModelOnlyViaFileMenu',
              data: files[0]
            }, mainWindow);
          }
        });
    }
  }));
  fileMenu.append(new MenuItem({
    label: 'New Visualization',
    accelerator: (function() {
      if (process.platform == 'darwin')
        return 'Alt+Command+N';
      else
        return 'Ctrl+Shift+N';
    })(),
    click: function() {

      angular.send({
        type: 'createNewVisualization'
      }, mainWindow);

    }
  }));
  /*fileMenu.append(new MenuItem({
    type: 'separator'
  }));
  fileMenu.append(new MenuItem({
    label: 'Open Formal Model',
    click: function() {
      Dialog.showOpenDialog({
          title: 'Please select a formal model.',
          filters: [{
            name: 'Formal Model (*.mch, *.csp, *.bcm, *.bcc)',
            extensions: ['mch', 'csp', 'bcm', 'bcc']
          }],
          properties: ['openFile']
        },
        function(files) {
          if (files) {
            angular.send({
              type: 'startFormalModelOnlyViaFileMenu',
              data: files[0]
            }, mainWindow);
          }
        });
    }
  }));*/
  mainMenu.append(new MenuItem({
    label: 'File',
    submenu: fileMenu,
    visible: false
  }));

};

var buildDiagramMenu = function(mainMenu, tool) {

  // Diagram menu
  var diagramMenu = new Menu();
  diagramMenu.append(new MenuItem({
    label: 'Trace Diagram',
    accelerator: (function() {
      if (process.platform == 'darwin')
        return 'Alt+Command+T';
      else
        return 'Ctrl+Shift+T';
    })(),
    click: function() {
      angular.send({
        type: 'openTraceDiagramModal'
      });
    }
  }));
  diagramMenu.append(new MenuItem({
    label: 'Projection Diagram',
    accelerator: (function() {
      if (process.platform == 'darwin')
        return 'Alt+Command+P';
      else
        return 'Ctrl+Shift+P';
    })(),
    click: function() {
      angular.send({
        type: 'openElementProjectionModal'
      });
    },
    enabled: tool === 'EventBVisualization' || tool === 'ClassicalBVisualization'
  }));

  mainMenu.append(new MenuItem({
    label: 'Diagram',
    submenu: diagramMenu
  }));

};

var buildVisualizationMenu = function(mainMenu, tool, addFileHelpMenu) {
  if (process.platform == 'darwin') buildOsxMenu(mainMenu);
  if (addFileHelpMenu) buildFileMenu(mainMenu);
  buildEditMenu(mainMenu);
  buildProBMenu(mainMenu);
  buildDiagramMenu(mainMenu, tool);
  buildViewMenu(mainMenu);
  if (addFileHelpMenu) buildHelpMenu(mainMenu);
  buildWindowMenu(mainMenu);
};

var buildModelMenu = function(mainMenu) {
  if (process.platform == 'darwin') buildOsxMenu(mainMenu);
  buildFileMenu(mainMenu);
  if (process.platform == 'darwin') buildEditMenu(mainMenu);
  buildProBMenu(mainMenu);
  buildViewMenu(mainMenu);
  buildHelpMenu(mainMenu);
  buildWindowMenu(mainMenu);
};

var buildProBMenu = function(mainMenu) {

  // ProB Menu
  var probMenu = new Menu();
  probMenu.append(new MenuItem({
    label: 'Events',
    click: function(item, focusedWindow) {
      openDialog('Events', focusedWindow);
    }
  }));
  probMenu.append(new MenuItem({
    label: 'History',
    click: function(item, focusedWindow) {
      openDialog('CurrentTrace', focusedWindow);
    }
  }));
  probMenu.append(new MenuItem({
    label: 'State',
    click: function(item, focusedWindow) {
      openDialog('StateInspector', focusedWindow);
    }
  }));
  probMenu.append(new MenuItem({
    label: 'Animations',
    click: function(item, focusedWindow) {
      openDialog('CurrentAnimations', focusedWindow);
    }
  }));
  probMenu.append(new MenuItem({
    label: 'Model Checking',
    click: function(item, focusedWindow) {
      openDialog('ModelCheckingUI', focusedWindow);
    }
  }));
  probMenu.append(new MenuItem({
    label: 'Console',
    click: function(item, focusedWindow) {
      openDialog('BConsole', focusedWindow);
    }
  }));

  mainMenu.append(new MenuItem({
    label: 'ProB',
    submenu: probMenu,
    visible: false
  }));

};

var buildWelcomeMenu = function(mainMenu) {
  if (process.platform == 'darwin') buildOsxMenu(mainMenu);
  buildFileMenu(mainMenu);
  if (process.platform == 'darwin') buildEditMenu(mainMenu);
  buildViewMenu(mainMenu);
  buildHelpMenu(mainMenu);
  buildWindowMenu(mainMenu);
};

var buildOsxMenu = function(mainMenu) {

  var name = require('app').getName();

  // OSX Menu
  var osxMenu = new Menu();
  osxMenu.append(new MenuItem({
    label: 'About ' + name,
    role: 'about'
  }));
  osxMenu.append(new MenuItem({
    type: 'separator'
  }));
  osxMenu.append(new MenuItem({
    label: 'Services',
    role: 'services'
  }));
  osxMenu.append(new MenuItem({
    type: 'separator'
  }));
  osxMenu.append(new MenuItem({
    label: 'Hide ' + name,
    accelerator: 'Command+H',
    role: 'hide'
  }));
  osxMenu.append(new MenuItem({
    label: 'Hide Others',
    accelerator: 'Command+Shift+H',
    role: 'hideothers'
  }));
  osxMenu.append(new MenuItem({
    label: 'Show All',
    role: 'unhide'
  }));
  osxMenu.append(new MenuItem({
    type: 'separator'
  }));
  osxMenu.append(new MenuItem({
    label: 'Quit',
    accelerator: 'Command+Q',
    click: function(item, focusedWindow) {
      if (focusedWindow)
        focusedWindow.close();
    }
  }));

  mainMenu.append(new MenuItem({
    label: name,
    submenu: osxMenu
  }));

};

var buildWindowMenu = function(mainMenu) {

  var windowMenu = new Menu();
  windowMenu.append(new MenuItem({
    label: 'Minimize',
    accelerator: 'CmdOrCtrl+M',
    role: 'minimize',
    click: function(item, focusedWindow) {
      if (focusedWindow)
        focusedWindow.minimize();
    }
  }));
  windowMenu.append(new MenuItem({
    label: 'Close',
    accelerator: 'CmdOrCtrl+W',
    role: 'close',
    click: function(item, focusedWindow) {
      if (focusedWindow)
        focusedWindow.close();
    }
  }));

  if (process.platform == 'darwin') {
    windowMenu.append(new MenuItem({
      type: 'separator'
    }));
    windowMenu.append(new MenuItem({
      label: 'Bring All to Front',
      role: 'front'
    }));
  }

  mainMenu.append(new MenuItem({
    label: 'Window',
    role: 'window',
    submenu: windowMenu
  }));

};

var buildEditMenu = function(mainMenu) {

  var editMenu = new Menu();
  editMenu.append(new MenuItem({
    label: 'Undo',
    accelerator: 'CmdOrCtrl+Z',
    role: 'undo'
  }));
  editMenu.append(new MenuItem({
    label: 'Redo',
    accelerator: 'Shift+CmdOrCtrl+Z',
    role: 'redo'
  }));
  editMenu.append(new MenuItem({
    type: 'separator'
  }));
  editMenu.append(new MenuItem({
    label: 'Cut',
    accelerator: 'CmdOrCtrl+X',
    role: 'cut'
  }));
  editMenu.append(new MenuItem({
    label: 'Copy',
    accelerator: 'CmdOrCtrl+C',
    role: 'copy'
  }));
  editMenu.append(new MenuItem({
    label: 'Paste',
    accelerator: 'CmdOrCtrl+V',
    role: 'paste'
  }));
  editMenu.append(new MenuItem({
    label: 'Select All',
    accelerator: 'CmdOrCtrl+A',
    role: 'selectall'
  }));

  mainMenu.append(new MenuItem({
    label: 'Edit',
    submenu: editMenu
  }));

};

var shouldQuit = app.makeSingleInstance(function(commandLine, workingDirectory) {
  // Someone tried to run a second instance, we should focus our window
  if (mainWindow) {
    if (!mainWindow.isDestroyed()) {
      if (mainWindow.isMinimized()) mainWindow.restore();
      mainWindow.focus();
    } else {
      visualizationWindows.forEach(function(win) {
        if (!win.isDestroyed()) {
          if (win.isMinimized()) win.restore();
          win.focus();
        }
      });
    }
  }
  return true;
});

if (shouldQuit) {
  if (server) kill(server.pid, 'SIGKILL', function(err) {
    app.quit();
  });
  app.quit();
  return;
}

app.on('before-quit', function() {
  if (server) kill(server.pid, 'SIGKILL', function(err) {
    app.quit();
  });
});

app.on('ready', function() {

  mainWindow = new BrowserWindow({
    height: 600,
    width: 800,
    title: 'BMotionWeb v' + app.getVersion() + ' ' + options.dev,
    icon: __dirname + '/resources/icons/bmsicon16x16.png'
  });
  mainWindow.loadURL('file://' + __dirname + '/' + (options.dev === true ? 'dev' : 'index') + ".html");

  /*mainWindow.on('close', function() {
    visualizationWindows.forEach(function(win) {
      win.close();
    });
  });*/

  welcomeMenu = new Menu();
  buildWelcomeMenu(welcomeMenu);
  if (process.platform == 'darwin') {
    setOsxMenu(welcomeMenu);
  } else {
    mainWindow.setMenu(welcomeMenu);
  }

  mainWindow.on('focus', function() {
    if (process.platform == 'darwin') {
      setOsxMenu(welcomeMenu);
    }
  });

  if(!options.dev) {
    // Start BMotionWeb server
    var path = require('path');
    var appPath = path.dirname(__dirname);
    var isWin = /^win/.test(process.platform);
    var separator = isWin ? ';' : ':';
    server = cp.spawn('java', ['-Xmx1024m', '-cp', appPath + '/libs/*' + separator + appPath + '/libs/bmotion-prob-' + app.getVersion() + '.jar', 'de.bmotion.prob.Standalone', '-local'], {
      detached: true
    });

    server.stdout.on('data', function(data) {
      console.log('BMotionWeb Server: ' + data.toString('utf8'));
    });
    server.stderr.on('data', function(data) {
      console.log('BMotionWeb Server: ' + data.toString('utf8'));
    });
    server.on('close', function(code) {
      console.log('BMotionWeb Server process exited with code ' + code);
    });
    // ------------------------
  }

  angular.listen(function(data) {
    if (data.type === 'openVisualizationWindow') {
      var newVisualizationWindow = new BrowserWindow({
        parent: mainWindow,
        height: 600,
        width: 800,
        icon: __dirname + '/resources/icons/bmsicon16x16.png'
      });
      newVisualizationWindow.loadURL('file://' + __dirname + '/index.html#/vis/' + data.sessionId);
      newVisualizationWindow.webContents.on('did-finish-load', () => {
        newVisualizationWindow.setTitle(data.name ? data.name : 'Visualization');
      });
      var visualizationMenu = new Menu();
      buildVisualizationMenu(visualizationMenu, data.tool, data.addMenu);
      if (process.platform == 'darwin') {
        setOsxMenu(visualizationMenu);
      } else {
        newVisualizationWindow.setMenu(visualizationMenu);
      }
      visualizationWindows.push(newVisualizationWindow);

      newVisualizationWindow.on('close', function() {
        visualizationWindows.splice(visualizationWindows.indexOf(newVisualizationWindow), 1);
        angular.send({
          type: 'destroySession',
          sessionId: data.sessionId
        },newVisualizationWindow);
      });

      newVisualizationWindow.on('focus', function() {
        if (process.platform == 'darwin') {
          setOsxMenu(visualizationMenu);
        }
      });

    }
  });

});
<commit_msg>Fixed focus window issues<commit_after>'use strict';

var app = require('app');
var BrowserWindow = require('browser-window');
var angular = require('./js/libs/ext/ng-electron/ng-bridge');
var ncp = require('ncp').ncp;
ncp.limit = 16;

var kill = require('tree-kill');
var cp = require('child_process');

var commandLineArgs = require('command-line-args')

var optionDefinitions = [
  { name: 'dev', type: Boolean, defaultOption: false },
  { name: 'version', type: String }
];

var options = commandLineArgs(optionDefinitions)

var server;

var visualizationWindows = [];

var mainWindow = null;
var welcomeMenu = null;

var Menu = require('menu');
var MenuItem = require('menu-item');
var Dialog = require('dialog');

// Quit when all windows are closed and no other one is listening to this.
app.on('window-all-closed', function() {
  if (app.listeners('window-all-closed').length == 1) {
    if (server) kill(server.pid, 'SIGKILL', function(err) {
      app.quit();
    });
  }
});

var openDialog = function(type, win) {
  angular.send({
    type: 'openDialog',
    data: type
  }, win);
};

var setOsxMenu = function(menu) {
  Menu.setApplicationMenu(menu);
};

var buildHelpMenu = function(mainMenu) {

  // Help menu
  var helpMenu = new Menu();
  helpMenu.append(new MenuItem({
    label: 'About',
    click: function(item, focusedWindow) {
      angular.send({
        type: 'openHelp',
        data: app.getVersion()
      }, focusedWindow);
    }
  }));
  mainMenu.append(new MenuItem({
    label: 'Help',
    role: 'help',
    submenu: helpMenu
  }));

};

var buildViewMenu = function(mainMenu) {

  // Debug menu
  var viewMenu = new Menu();
  viewMenu.append(new MenuItem({
    label: 'Reload',
    accelerator: 'CmdOrCtrl+R',
    click: function(item, focusedWindow) {
      if (focusedWindow)
        focusedWindow.reload();
    }
  }));
  viewMenu.append(new MenuItem({
    label: 'Open Groovy Console',
    click: function(item, focusedWindow) {
      openDialog('GroovyConsoleSession', focusedWindow);
    }
  }));
  viewMenu.append(new MenuItem({
    label: 'Toggle Full Screen',
    accelerator: (function() {
      if (process.platform == 'darwin')
        return 'Ctrl+Command+F';
      else
        return 'F11';
    })(),
    click: function(item, focusedWindow) {
      if (focusedWindow)
        focusedWindow.setFullScreen(!focusedWindow.isFullScreen());
    }
  }));
  viewMenu.append(new MenuItem({
    label: 'Toggle Developer Tools',
    accelerator: (function() {
      if (process.platform == 'darwin')
        return 'Alt+Command+I';
      else
        return 'Ctrl+Shift+I';
    })(),
    click: function(item, focusedWindow) {
      if (focusedWindow)
        focusedWindow.toggleDevTools();
    }
  }));
  viewMenu.append(new MenuItem({
    label: 'User Interactions Log',
    click: function(item, focusedWindow) {
      openDialog('UserInteractions', focusedWindow);
    }
  }));
  mainMenu.append(new MenuItem({
    label: 'View',
    submenu: viewMenu
  }));

};

var buildFileMenu = function(mainMenu) {

  // File menu
  var fileMenu = new Menu();
  fileMenu.append(new MenuItem({
    label: 'Open Visualization',
    accelerator: (function() {
      if (process.platform == 'darwin')
        return 'Alt+Command+O';
      else
        return 'Ctrl+Shift+O';
    })(),
    click: function() {
      Dialog.showOpenDialog({
          title: 'Open BMotionWeb Visualization',
          filters: [{
            name: 'BMotionWeb Manifest (bmotion.json)',
            extensions: ['json']
          }, {
            name: 'Formal Model (*.mch, *.csp, *.bcm, *.bcc)',
            extensions: ['mch', 'csp', 'bcm', 'bcc']
          }],
          properties: ['openFile']
        },
        function(files) {
          if (files) {
            var filename = files[0].replace(/^.*[\\\/]/, '');
            var fileExtension = filename.split('.').pop();
            angular.send({
              type: fileExtension === 'json' ? 'startVisualisationViaFileMenu' : 'startFormalModelOnlyViaFileMenu',
              data: files[0]
            }, mainWindow);
          }
        });
    }
  }));
  fileMenu.append(new MenuItem({
    label: 'New Visualization',
    accelerator: (function() {
      if (process.platform == 'darwin')
        return 'Alt+Command+N';
      else
        return 'Ctrl+Shift+N';
    })(),
    click: function() {

      angular.send({
        type: 'createNewVisualization'
      }, mainWindow);

    }
  }));
  /*fileMenu.append(new MenuItem({
    type: 'separator'
  }));
  fileMenu.append(new MenuItem({
    label: 'Open Formal Model',
    click: function() {
      Dialog.showOpenDialog({
          title: 'Please select a formal model.',
          filters: [{
            name: 'Formal Model (*.mch, *.csp, *.bcm, *.bcc)',
            extensions: ['mch', 'csp', 'bcm', 'bcc']
          }],
          properties: ['openFile']
        },
        function(files) {
          if (files) {
            angular.send({
              type: 'startFormalModelOnlyViaFileMenu',
              data: files[0]
            }, mainWindow);
          }
        });
    }
  }));*/
  mainMenu.append(new MenuItem({
    label: 'File',
    submenu: fileMenu,
    visible: false
  }));

};

var buildDiagramMenu = function(mainMenu, tool) {

  // Diagram menu
  var diagramMenu = new Menu();
  diagramMenu.append(new MenuItem({
    label: 'Trace Diagram',
    accelerator: (function() {
      if (process.platform == 'darwin')
        return 'Alt+Command+T';
      else
        return 'Ctrl+Shift+T';
    })(),
    click: function(item, focusedWindow) {
      angular.send({
        type: 'openTraceDiagramModal'
      }, focusedWindow);
    }
  }));
  diagramMenu.append(new MenuItem({
    label: 'Projection Diagram',
    accelerator: (function() {
      if (process.platform == 'darwin')
        return 'Alt+Command+P';
      else
        return 'Ctrl+Shift+P';
    })(),
    click: function(item, focusedWindow) {
      angular.send({
        type: 'openElementProjectionModal'
      }, focusedWindow);
    },
    enabled: tool === 'EventBVisualization' || tool === 'ClassicalBVisualization'
  }));

  mainMenu.append(new MenuItem({
    label: 'Diagram',
    submenu: diagramMenu
  }));

};

var buildVisualizationMenu = function(mainMenu, tool, addFileHelpMenu) {
  if (process.platform == 'darwin') buildOsxMenu(mainMenu);
  if (addFileHelpMenu) buildFileMenu(mainMenu);
  buildEditMenu(mainMenu);
  buildProBMenu(mainMenu);
  buildDiagramMenu(mainMenu, tool);
  buildViewMenu(mainMenu);
  if (addFileHelpMenu) buildHelpMenu(mainMenu);
  buildWindowMenu(mainMenu);
};

var buildModelMenu = function(mainMenu) {
  if (process.platform == 'darwin') buildOsxMenu(mainMenu);
  buildFileMenu(mainMenu);
  if (process.platform == 'darwin') buildEditMenu(mainMenu);
  buildProBMenu(mainMenu);
  buildViewMenu(mainMenu);
  buildHelpMenu(mainMenu);
  buildWindowMenu(mainMenu);
};

var buildProBMenu = function(mainMenu) {

  // ProB Menu
  var probMenu = new Menu();
  probMenu.append(new MenuItem({
    label: 'Events',
    click: function(item, focusedWindow) {
      openDialog('Events', focusedWindow);
    }
  }));
  probMenu.append(new MenuItem({
    label: 'History',
    click: function(item, focusedWindow) {
      openDialog('CurrentTrace', focusedWindow);
    }
  }));
  probMenu.append(new MenuItem({
    label: 'State',
    click: function(item, focusedWindow) {
      openDialog('StateInspector', focusedWindow);
    }
  }));
  probMenu.append(new MenuItem({
    label: 'Animations',
    click: function(item, focusedWindow) {
      openDialog('CurrentAnimations', focusedWindow);
    }
  }));
  probMenu.append(new MenuItem({
    label: 'Model Checking',
    click: function(item, focusedWindow) {
      openDialog('ModelCheckingUI', focusedWindow);
    }
  }));
  probMenu.append(new MenuItem({
    label: 'Console',
    click: function(item, focusedWindow) {
      openDialog('BConsole', focusedWindow);
    }
  }));

  mainMenu.append(new MenuItem({
    label: 'ProB',
    submenu: probMenu,
    visible: false
  }));

};

var buildWelcomeMenu = function(mainMenu) {
  if (process.platform == 'darwin') buildOsxMenu(mainMenu);
  buildFileMenu(mainMenu);
  if (process.platform == 'darwin') buildEditMenu(mainMenu);
  buildViewMenu(mainMenu);
  buildHelpMenu(mainMenu);
  buildWindowMenu(mainMenu);
};

var buildOsxMenu = function(mainMenu) {

  var name = require('app').getName();

  // OSX Menu
  var osxMenu = new Menu();
  osxMenu.append(new MenuItem({
    label: 'About ' + name,
    role: 'about'
  }));
  osxMenu.append(new MenuItem({
    type: 'separator'
  }));
  osxMenu.append(new MenuItem({
    label: 'Services',
    role: 'services'
  }));
  osxMenu.append(new MenuItem({
    type: 'separator'
  }));
  osxMenu.append(new MenuItem({
    label: 'Hide ' + name,
    accelerator: 'Command+H',
    role: 'hide'
  }));
  osxMenu.append(new MenuItem({
    label: 'Hide Others',
    accelerator: 'Command+Shift+H',
    role: 'hideothers'
  }));
  osxMenu.append(new MenuItem({
    label: 'Show All',
    role: 'unhide'
  }));
  osxMenu.append(new MenuItem({
    type: 'separator'
  }));
  osxMenu.append(new MenuItem({
    label: 'Quit',
    accelerator: 'Command+Q',
    click: function(item, focusedWindow) {
      if (focusedWindow)
        focusedWindow.close();
    }
  }));

  mainMenu.append(new MenuItem({
    label: name,
    submenu: osxMenu
  }));

};

var buildWindowMenu = function(mainMenu) {

  var windowMenu = new Menu();
  windowMenu.append(new MenuItem({
    label: 'Minimize',
    accelerator: 'CmdOrCtrl+M',
    role: 'minimize',
    click: function(item, focusedWindow) {
      if (focusedWindow)
        focusedWindow.minimize();
    }
  }));
  windowMenu.append(new MenuItem({
    label: 'Close',
    accelerator: 'CmdOrCtrl+W',
    role: 'close',
    click: function(item, focusedWindow) {
      if (focusedWindow)
        focusedWindow.close();
    }
  }));

  if (process.platform == 'darwin') {
    windowMenu.append(new MenuItem({
      type: 'separator'
    }));
    windowMenu.append(new MenuItem({
      label: 'Bring All to Front',
      role: 'front'
    }));
  }

  mainMenu.append(new MenuItem({
    label: 'Window',
    role: 'window',
    submenu: windowMenu
  }));

};

var buildEditMenu = function(mainMenu) {

  var editMenu = new Menu();
  editMenu.append(new MenuItem({
    label: 'Undo',
    accelerator: 'CmdOrCtrl+Z',
    role: 'undo'
  }));
  editMenu.append(new MenuItem({
    label: 'Redo',
    accelerator: 'Shift+CmdOrCtrl+Z',
    role: 'redo'
  }));
  editMenu.append(new MenuItem({
    type: 'separator'
  }));
  editMenu.append(new MenuItem({
    label: 'Cut',
    accelerator: 'CmdOrCtrl+X',
    role: 'cut'
  }));
  editMenu.append(new MenuItem({
    label: 'Copy',
    accelerator: 'CmdOrCtrl+C',
    role: 'copy'
  }));
  editMenu.append(new MenuItem({
    label: 'Paste',
    accelerator: 'CmdOrCtrl+V',
    role: 'paste'
  }));
  editMenu.append(new MenuItem({
    label: 'Select All',
    accelerator: 'CmdOrCtrl+A',
    role: 'selectall'
  }));

  mainMenu.append(new MenuItem({
    label: 'Edit',
    submenu: editMenu
  }));

};

var shouldQuit = app.makeSingleInstance(function(commandLine, workingDirectory) {
  // Someone tried to run a second instance, we should focus our window
  if (mainWindow) {
    if (!mainWindow.isDestroyed()) {
      if (mainWindow.isMinimized()) mainWindow.restore();
      mainWindow.focus();
    } else {
      visualizationWindows.forEach(function(win) {
        if (!win.isDestroyed()) {
          if (win.isMinimized()) win.restore();
          win.focus();
        }
      });
    }
  }
  return true;
});

if (shouldQuit) {
  if (server) kill(server.pid, 'SIGKILL', function(err) {
    app.quit();
  });
  app.quit();
  return;
}

app.on('before-quit', function() {
  if (server) kill(server.pid, 'SIGKILL', function(err) {
    app.quit();
  });
});

app.on('ready', function() {

  mainWindow = new BrowserWindow({
    height: 600,
    width: 800,
    title: 'BMotionWeb v' + app.getVersion() + ' ' + options.dev,
    icon: __dirname + '/resources/icons/bmsicon16x16.png'
  });
  mainWindow.loadURL('file://' + __dirname + '/' + (options.dev === true ? 'dev' : 'index') + ".html");

  /*mainWindow.on('close', function() {
    visualizationWindows.forEach(function(win) {
      win.close();
    });
  });*/

  welcomeMenu = new Menu();
  buildWelcomeMenu(welcomeMenu);
  if (process.platform == 'darwin') {
    setOsxMenu(welcomeMenu);
  } else {
    mainWindow.setMenu(welcomeMenu);
  }

  mainWindow.on('focus', function() {
    if (process.platform == 'darwin') {
      setOsxMenu(welcomeMenu);
    }
  });

  if(!options.dev) {
    // Start BMotionWeb server
    var path = require('path');
    var appPath = path.dirname(__dirname);
    var isWin = /^win/.test(process.platform);
    var separator = isWin ? ';' : ':';
    server = cp.spawn('java', ['-Xmx1024m', '-cp', appPath + '/libs/*' + separator + appPath + '/libs/bmotion-prob-' + app.getVersion() + '.jar', 'de.bmotion.prob.Standalone', '-local'], {
      detached: true
    });

    server.stdout.on('data', function(data) {
      console.log('BMotionWeb Server: ' + data.toString('utf8'));
    });
    server.stderr.on('data', function(data) {
      console.log('BMotionWeb Server: ' + data.toString('utf8'));
    });
    server.on('close', function(code) {
      console.log('BMotionWeb Server process exited with code ' + code);
    });
    // ------------------------
  }

  angular.listen(function(data) {
    if (data.type === 'openVisualizationWindow') {
      var newVisualizationWindow = new BrowserWindow({
        parent: mainWindow,
        height: 600,
        width: 800,
        icon: __dirname + '/resources/icons/bmsicon16x16.png'
      });
      newVisualizationWindow.loadURL('file://' + __dirname + '/index.html#/vis/' + data.sessionId);
      newVisualizationWindow.webContents.on('did-finish-load', () => {
        newVisualizationWindow.setTitle(data.name ? data.name : 'Visualization');
      });
      var visualizationMenu = new Menu();
      buildVisualizationMenu(visualizationMenu, data.tool, data.addMenu);
      if (process.platform == 'darwin') {
        setOsxMenu(visualizationMenu);
      } else {
        newVisualizationWindow.setMenu(visualizationMenu);
      }
      visualizationWindows.push(newVisualizationWindow);

      newVisualizationWindow.on('close', function() {
        visualizationWindows.splice(visualizationWindows.indexOf(newVisualizationWindow), 1);
        angular.send({
          type: 'destroySession',
          sessionId: data.sessionId
        }, newVisualizationWindow);
      });

      newVisualizationWindow.on('focus', function() {
        if (process.platform == 'darwin') {
          setOsxMenu(visualizationMenu);
        }
      });

    }
  });

});
<|endoftext|>


<commit_before>import React from "react";
import { connect } from "react-redux";
import classnames from "classnames";

import { WINDOWS } from "../../constants";

import MiniTime from "../MiniTime";

import ActionButtons from "./ActionButtons";
import MainBalance from "./MainBalance";
import Close from "./Close";
import ClutterBar from "./ClutterBar";
import MainContextMenu from "./MainContextMenu";
import Eject from "./Eject";
import EqToggleButton from "./EqToggleButton";
import PlaylistToggleButton from "./PlaylistToggleButton";
import Kbps from "./Kbps";
import Khz from "./Khz";
import Marquee from "./Marquee";
import MonoStereo from "./MonoStereo";
import Position from "./Position";
import Repeat from "./Repeat";
import Shade from "./Shade";
import Shuffle from "./Shuffle";
import Time from "./Time";
import Visualizer from "./Visualizer";
import MainVolume from "./MainVolume";

import { SET_FOCUSED_WINDOW } from "../../actionTypes";

import { loadFileFromReference } from "../../actionCreators";

import "../../../css/main-window.css";

export class MainWindow extends React.Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
    this.handleDrop = this.handleDrop.bind(this);
  }

  handleClick() {
    this.props.setFocus();
  }

  supress(e) {
    e.stopPropagation();
    e.preventDefault();
  }

  handleDrop(e) {
    this.supress(e);
    const { files } = e.dataTransfer;
    // TODO: Move this to an actionCreator
    this.props.dispatch(loadFileFromReference(files[0]));
  }

  render() {
    const {
      focused,
      loading,
      doubled,
      shade,
      llama,
      status,
      working
    } = this.props;

    const className = classnames({
      window: true,
      // TODO: Handle these status changes in the individual components
      play: status === "PLAYING",
      stop: status === "STOPPED",
      pause: status === "PAUSED",
      selected: focused === WINDOWS.MAIN,
      draggable: true,
      loading,
      doubled,
      llama,
      shade
    });

    return (

          <MainContextMenu fileInput={this.props.fileInput} />
          {shade && <MiniTime />}

          <Shade />
          <Close />

          <ClutterBar />

          <Time />
          <Visualizer analyser={this.props.mediaPlayer._analyser} />

          <Marquee />
          <Kbps />
          <Khz />
          <MonoStereo />

        <MainVolume />
        <MainBalance />

          <EqToggleButton />
          <PlaylistToggleButton />

        <Position />
        <ActionButtons />
        <Eject fileInput={this.props.fileInput} />

          <Shuffle />
          <Repeat />

    );
  }
}

const mapStateToProps = state => {
  const {
    media: { status },
    display: { loading, doubled, shade, llama, working },
    windows: { focused }
  } = state;
  return { status, loading, doubled, shade, llama, working, focused };
};

const mapDispatchToProps = dispatch => ({
  setFocus: () => {
    dispatch({ type: SET_FOCUSED_WINDOW, window: WINDOWS.MAIN });
  }
});
export default connect(mapStateToProps, mapDispatchToProps)(MainWindow);
<commit_msg>Fix dragging in files.<commit_after>import React from "react";
import { connect } from "react-redux";
import classnames from "classnames";

import { WINDOWS } from "../../constants";

import MiniTime from "../MiniTime";

import ActionButtons from "./ActionButtons";
import MainBalance from "./MainBalance";
import Close from "./Close";
import ClutterBar from "./ClutterBar";
import MainContextMenu from "./MainContextMenu";
import Eject from "./Eject";
import EqToggleButton from "./EqToggleButton";
import PlaylistToggleButton from "./PlaylistToggleButton";
import Kbps from "./Kbps";
import Khz from "./Khz";
import Marquee from "./Marquee";
import MonoStereo from "./MonoStereo";
import Position from "./Position";
import Repeat from "./Repeat";
import Shade from "./Shade";
import Shuffle from "./Shuffle";
import Time from "./Time";
import Visualizer from "./Visualizer";
import MainVolume from "./MainVolume";

import { SET_FOCUSED_WINDOW } from "../../actionTypes";

import { loadFileFromReference } from "../../actionCreators";

import "../../../css/main-window.css";

export class MainWindow extends React.Component {
  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);
    this.handleDrop = this.handleDrop.bind(this);
  }

  handleClick() {
    this.props.setFocus();
  }

  supress(e) {
    e.stopPropagation();
    e.preventDefault();
  }

  handleDrop(e) {
    this.supress(e);
    const { files } = e.dataTransfer;
    // TODO: Move this to an actionCreator
    this.props.loadFileFromReference(files[0]);
  }

  render() {
    const {
      focused,
      loading,
      doubled,
      shade,
      llama,
      status,
      working
    } = this.props;

    const className = classnames({
      window: true,
      // TODO: Handle these status changes in the individual components
      play: status === "PLAYING",
      stop: status === "STOPPED",
      pause: status === "PAUSED",
      selected: focused === WINDOWS.MAIN,
      draggable: true,
      loading,
      doubled,
      llama,
      shade
    });

    return (

          <MainContextMenu fileInput={this.props.fileInput} />
          {shade && <MiniTime />}

          <Shade />
          <Close />

          <ClutterBar />

          <Time />
          <Visualizer analyser={this.props.mediaPlayer._analyser} />

          <Marquee />
          <Kbps />
          <Khz />
          <MonoStereo />

        <MainVolume />
        <MainBalance />

          <EqToggleButton />
          <PlaylistToggleButton />

        <Position />
        <ActionButtons />
        <Eject fileInput={this.props.fileInput} />

          <Shuffle />
          <Repeat />

    );
  }
}

const mapStateToProps = state => {
  const {
    media: { status },
    display: { loading, doubled, shade, llama, working },
    windows: { focused }
  } = state;
  return { status, loading, doubled, shade, llama, working, focused };
};

const mapDispatchToProps = {
  setFocus: () => ({ type: SET_FOCUSED_WINDOW, window: WINDOWS.MAIN }),
  loadFileFromReference
};
export default connect(mapStateToProps, mapDispatchToProps)(MainWindow);
<|endoftext|>


<commit_before>'use strict';

angular
    .module('ShowpadDemo')
    .controller('DemoController', [
        '$scope', '$three',
        function ($scope, $three) {

            // list of available colors
            $scope.backgroundColors = ['#c0ebcf', '#7ebccc', '#d3e495', '#ecf0f1'];
            $scope.cupboardColors = ['#9b59b6', '#3498db', '#00ba00', '#48c9b0', '#f1c40f', '#e67e22', '#e74c3c', '#ecf0f1'];

            // select default colors
            $scope.backgroundColor = $scope.backgroundColors[0];
            $scope.cupboardColor = $scope.cupboardColors[0];

            // set default rows and size
            $scope.verticalRows = 5;
            $scope.horizontalRows = 5;
            $scope.squareSize = 40;

            //
            $scope.canvasWrapper = document.getElementById('canvas-wrapper');

            /**
             * @param {String} color
             */
            $scope.setBackgroundColor = function (color) {
                $scope.backgroundColor = color;
            }

            /**
             * @param {String} color
             */
            $scope.setCupboardColor = function (color) {
                $scope.cupboardColor = color;
            }

            // watch for changes in configuration, render $three if needed
            $scope.$watch('[cupboardColor, verticalRows, horizontalRows, squareSize]', function() {
                $three.generate(
                    parseInt($scope.horizontalRows, 10),
                    parseInt($scope.verticalRows, 10),
                    parseInt($scope.squareSize, 10),
                    $scope.cupboardColor, 10
                );
                $three.render();
            }, true);

            // watch background color to change DOM element style
            $scope.$watch('backgroundColor', function (backgroundColor) {
                $scope.canvasWrapper.style.backgroundColor = backgroundColor;
            })

            // initialise $three with the canvas wrapper element
            $three.init($scope.canvasWrapper);
        }
    ]);<commit_msg>sanitizing numbers<commit_after>'use strict';

angular
    .module('ShowpadDemo')
    .controller('DemoController', [
        '$scope', '$three',
        function ($scope, $three) {

            // list of available colors
            $scope.backgroundColors = ['#c0ebcf', '#7ebccc', '#d3e495', '#ecf0f1'];
            $scope.cupboardColors = ['#9b59b6', '#3498db', '#00ba00', '#48c9b0', '#f1c40f', '#e67e22', '#e74c3c', '#ecf0f1'];

            // select default colors
            $scope.backgroundColor = $scope.backgroundColors[0];
            $scope.cupboardColor = $scope.cupboardColors[0];

            // set default rows and size
            $scope.verticalRows = 5;
            $scope.horizontalRows = 5;
            $scope.squareSize = 40;

            //
            $scope.canvasWrapper = document.getElementById('canvas-wrapper');

            /**
             * @param {String} color
             */
            $scope.setBackgroundColor = function (color) {
                $scope.backgroundColor = color;
            }

            /**
             * @param {String} color
             */
            $scope.setCupboardColor = function (color) {
                $scope.cupboardColor = color;
            }

            // watch for changes in configuration, render $three if needed
            $scope.$watch('[cupboardColor, verticalRows, horizontalRows, squareSize]', function() {
                // sanitize
                $scope.squareSize = Math.min(Math.max(10, parseInt($scope.squareSize, 10)), 100);
                $scope.verticalRows = Math.min(Math.max(1, parseInt($scope.verticalRows, 10)), 50);
                $scope.horizontalRows = Math.min(Math.max(1, parseInt($scope.horizontalRows, 10)), 50);

                $three.generate(
                    $scope.horizontalRows,
                    $scope.verticalRows,
                    $scope.squareSize,
                    $scope.cupboardColor, 10
                );
                $three.render();
            }, true);

            // watch background color to change DOM element style
            $scope.$watch('backgroundColor', function (backgroundColor) {
                $scope.canvasWrapper.style.backgroundColor = backgroundColor;
            })

            // initialise $three with the canvas wrapper element
            $three.init($scope.canvasWrapper);
        }
    ]);<|endoftext|>


<commit_before>zr.controller('TeamManagementController', ['$scope', 'teamResources', function($scope, teamResources) {
	$scope.teams = teamResources.data.rows;
	$scope.currentTeam = null;
	$scope.isLead = false;
	$scope.countries = ['United States', 'Austria', 'Belgium', 'Czech Republic', 'Denmark', 'Finland', 'France', 'Germany', 'Greece', 'Ireland', 'Italy', 'Luxembourg', 'Netherlands', 'Norway', 'Poland', 'Portugal', 'Romania', 'Spain', 'Sweden', 'Switzerland', 'United Kingdom'];
	$scope.states = ["", "AK", "AL", "AR", "AS", "AZ", "CA", "CO", "CT", "DC", "DE", "FL", "FM", "GA", "GU", "HI", "IA", "ID", "IL", "IN", "KS", "KY", "LA", "MA", "MD", "ME", "MH", "MI", "MN", "MO", "MP", "MS", "MT", "NC", "ND", "NE", "NH", "NJ", "NM", "NV", "NY", "OH", "OK", "OR", "PA", "PR", "PW", "RI", "SC", "SD", "TN", "TX", "UT", "VA", "VI", "VT", "WA", "WI", "WV", "WY"];

	$scope.setTeam = function(team) {
		$scope.currentTeam = team;
	};
	if($scope.teams && $scope.teams.length !== 0) {
		$scope.setTeam($scope.teams[0]);
	}

	//For editing the basic team info
	$scope.setData = function() {
		gapi.client.request({
			'path': '/admin/directory/v1/groups/' + $scope.currentTeam.id,
			'method': 'PUT',
			'params': {
				'fields': ''
			},
			'body': {
				'description': JSON.stringify($scope.currentTeam.description)
			}
		})
		.execute(function() {});
	};
}]);
<commit_msg>Team management<commit_after>zr.controller('TeamManagementController', ['$scope', 'teamResources', function($scope, teamResources) {
	$scope.teams = teamResources.data.rows;
	$scope.currentTeam = null;
	$scope.isLead = true;
	$scope.countries = ['United States', 'Austria', 'Belgium', 'Czech Republic', 'Denmark', 'Finland', 'France', 'Germany', 'Greece', 'Ireland', 'Italy', 'Luxembourg', 'Netherlands', 'Norway', 'Poland', 'Portugal', 'Romania', 'Spain', 'Sweden', 'Switzerland', 'United Kingdom'];
	$scope.states = ["", "AK", "AL", "AR", "AS", "AZ", "CA", "CO", "CT", "DC", "DE", "FL", "FM", "GA", "GU", "HI", "IA", "ID", "IL", "IN", "KS", "KY", "LA", "MA", "MD", "ME", "MH", "MI", "MN", "MO", "MP", "MS", "MT", "NC", "ND", "NE", "NH", "NJ", "NM", "NV", "NY", "OH", "OK", "OR", "PA", "PR", "PW", "RI", "SC", "SD", "TN", "TX", "UT", "VA", "VI", "VT", "WA", "WI", "WV", "WY"];

	$scope.setTeam = function(team) {
		$scope.currentTeam = team;
	};
	if($scope.teams && $scope.teams.length !== 0) {
		$scope.setTeam($scope.teams[0]);
	}

	//For editing the basic team info
	$scope.setData = function() {
		gapi.client.request({
			'path': '/admin/directory/v1/groups/' + $scope.currentTeam.id,
			'method': 'PUT',
			'params': {
				'fields': ''
			},
			'body': {
				'description': JSON.stringify($scope.currentTeam.description)
			}
		})
		.execute(function() {});
	};
}]);
<|endoftext|>


<commit_before>var gtlds ={ 'com':  true,
             'net':  true,
             'org':  true,
             'info': true,
             'biz':  true,
             'name': true,
             'coop': true,
             'edu':  true,
             'gov':  true,
             'aero': true,
             'asia': true,
             'cat':  true,
             'int':  true,
             'jobs': true,
             'mil':  true,
             'mobi': true,
             'xxx':  true,
             'tel':  true,
             'museum': true,
             'travel': true };

var jp_second_domains = { 'ac': true,
                          'ad': true,
                          'co': true,
                          'ed': true,
                          'go': true,
                          'gr': true,
                          'lg': true,
                          'ne': true,
                          'or': true };

var ae_second_domains = { 'net':  true,
                          'gov':  true,
                          'ac':   true,
                          'sch':  true,
                          'org':  true,
                          'mil':  true,
                          'pro':  true,
                          'name': true };

var au_second_domains = { 'com':      true,
                          'net':      true,
                          'org':      true,
                          'edu':      true,
                          'gov':      true,
                          'csiro':    true,
                          'asn':      true,
                          'id':       true,
                          'act':      true,
                          'nsw':      true,
                          'nt':       true,
                          'qld':      true,
                          'sa':       true,
                          'tas':      true,
                          'vic':      true,
                          'wa':       true,
                          'archie':   true,
                          'conf':     true,
                          'gw':       true,
                          'info':     true,
                          'otc':      true,
                          'oz':       true,
                          'telememo': true };

var co_second_domains = { 'com': true,
                          'org': true,
                          'edu': true,
                          'gov': true,
                          'net': true,
                          'mil': true,
                          'nom': true };

var es_second_domains = { 'com': true,
                          'nom': true,
                          'org': true,
                          'gob': true,
                          'edu': true };

var fr_second_domains = { 'tm':     true,
                          'asso':   true,
                          'nom':    true,
                          'prd':    true,
                          'presse': true,
                          'com':    true,
                          'gouv':   true };

var it_second_domains = { 'gov': true,
                          'edu': true };

var ly_second_domains = { 'com': true,
                          'net': true,
                          'gov': true,
                          'plc': true,
                          'edu': true,
                          'sch': true,
                          'med': true,
                          'org': true,
                          'id':  true };

var uk_second_domains = { 'ac':     true,
                          'co':     true,
                          'gov':    true,
                          'ltd':    true,
                          'me':     true,
                          'mod':    true,
                          'net':    true,
                          'nic':    true,
                          'nhs':    true,
                          'org':    true,
                          'plc':    true,
                          'police': true,
                          'sch':    true };

var st_second_domains = { 'nic':       true,
                          'gov':       true,
                          'saotome':   true,
                          'principle': true,
                          'consulado': true,
                          'embaixada': true,
                          'org':       true,
                          'edu':       true,
                          'net':       true,
                          'com':       true,
                          'sotre':     true,
                          'mil':       true,
                          'co':        true };

var trunc_domain = function(domain) {
    var sp  = domain.split('.').reverse();
    var tld;
    var sld;
    var result;

    if (sp.length < 2)
        return false;

    tld = sp[0];

    if (tld in gtlds) {
        return sp.slice(0, 2).reverse().join('.');
    } else if (tld == 'jp') {
        sld = sp[1];

        if (sld in jp_second_domains) {
            return sp.slice(0, 3).reverse().join('.');
        } else {
            return sp.slice(0, 2).reverse().join('.');
        }
    } else if (tld == 'ae') {
        sld = sp[1];

        if (sld in ae_second_domains) {
            return sp.slice(0, 3).reverse().join('.');
        } else {
            return sp.slice(0, 2).reverse().join('.');
        }
    } else if (tld == 'au') {
        sld = sp[1];

        if (sld in au_second_domains) {
            return sp.slice(0, 3).reverse().join('.');
        } else {
            return sp.slice(0, 2).reverse().join('.');
        }
    } else if (tld == 'co') {
        sld = sp[1];

        if (sld in co_second_domains) {
            return sp.slice(0, 3).reverse().join('.');
        } else {
            return sp.slice(0, 2).reverse().join('.');
        }
    } else if (tld == 'es') {
        sld = sp[1];

        if (sld in es_second_domains) {
            return sp.slice(0, 3).reverse().join('.');
        } else {
            return sp.slice(0, 2).reverse().join('.');
        }
    } else if (tld == 'fr') {
        sld = sp[1];

        if (sld in fr_second_domains) {
            return sp.slice(0, 3).reverse().join('.');
        } else {
            return sp.slice(0, 2).reverse().join('.');
        }
    } else if (tld == 'it') {
        sld = sp[1];

        if (sld in it_second_domains) {
            return sp.slice(0, 3).reverse().join('.');
        } else {
            return sp.slice(0, 2).reverse().join('.');
        }
    } else if (tld == 'ly') {
        sld = sp[1];

        if (sld in ly_second_domains) {
            return sp.slice(0, 3).reverse().join('.');
        } else {
            return sp.slice(0, 2).reverse().join('.');
        }
    } else if (tld == 'uk') {
        sld = sp[1];

        if (sld in uk_second_domains) {
            return sp.slice(0, 3).reverse().join('.');
        } else {
            return sp.slice(0, 2).reverse().join('.');
        }
    } else if (tld == 'st') {
        sld = sp[1];

        if (sld in st_second_domains) {
            return sp.slice(0, 3).reverse().join('.');
        } else {
            return sp.slice(0, 2).reverse().join('.');
        }
    } else if (parseInt(tld, 10) != NaN) {
        return domain;
    }

    if (sp.length > 3) {
        return sp.slice(0, 3).reverse().join('.');
    }

    return domain;
}

db.system.js.save({"_id": "trunc_domain", "value": trunc_domain});
db.system.js.save({"_id": "gtlds", "value": gtlds});
db.system.js.save({"_id": "jp_second_domains", "value": jp_second_domains});
db.system.js.save({"_id": "ae_second_domains", "value": ae_second_domains});
db.system.js.save({"_id": "fr_second_domains", "value": fr_second_domains});
db.system.js.save({"_id": "co_second_domains", "value": co_second_domains});
db.system.js.save({"_id": "ly_second_domains", "value": ly_second_domains});
db.system.js.save({"_id": "uk_second_domains", "value": uk_second_domains});

function trunc_hosts() {
    db.trunc_hosts.remove();
    db.trunc_hosts.ensureIndex({value: 1});

    for (var c = db.hosts.find(); c.hasNext(); ) {
        var domain = c.next()['_id'];
        var tr_domain = trunc_domain(domain);

        db.trunc_hosts.insert({_id: domain, value: tr_domain});
    }
}

trunc_hosts();

function map() {
    if ('referer' in this) {
        var referers = {};
        var uri;
        var referer;
        var tr_uri;
        var tr_referer;

        try {
            uri     = this.uri.split('/')[2].split(':')[0];
            referer = this.referer.split('/')[2].split(':')[0];
        } catch (e) {
            return;
        }

        tr_uri     = trunc_domain(uri);
        tr_referer = trunc_domain(referer);

        if (uri == referer)
            return;

        referers[referer] = 1;
        emit(uri, referers);
    }
}

function reduce(key, values) {
    var referers = {};

    values.forEach(function(value) {
        for (var i in value) {
            if (i in referers)
                referers[i] += value[i];
            else
                referers[i] = value[i];
        }
    });

    return referers;
}

var res = db.requests.mapReduce(map, reduce, {out: {replace: 'graph_trunc_host'}});

shellPrint(res);
<commit_msg>fixed bugs on js/mongo_http_graph_trunc_host.js<commit_after>var gtlds ={ 'com':  true,
             'net':  true,
             'org':  true,
             'info': true,
             'biz':  true,
             'name': true,
             'coop': true,
             'edu':  true,
             'gov':  true,
             'aero': true,
             'asia': true,
             'cat':  true,
             'int':  true,
             'jobs': true,
             'mil':  true,
             'mobi': true,
             'xxx':  true,
             'tel':  true,
             'museum': true,
             'travel': true };

var jp_second_domains = { 'ac': true,
                          'ad': true,
                          'co': true,
                          'ed': true,
                          'go': true,
                          'gr': true,
                          'lg': true,
                          'ne': true,
                          'or': true };

var ae_second_domains = { 'net':  true,
                          'gov':  true,
                          'ac':   true,
                          'sch':  true,
                          'org':  true,
                          'mil':  true,
                          'pro':  true,
                          'name': true };

var au_second_domains = { 'com':      true,
                          'net':      true,
                          'org':      true,
                          'edu':      true,
                          'gov':      true,
                          'csiro':    true,
                          'asn':      true,
                          'id':       true,
                          'act':      true,
                          'nsw':      true,
                          'nt':       true,
                          'qld':      true,
                          'sa':       true,
                          'tas':      true,
                          'vic':      true,
                          'wa':       true,
                          'archie':   true,
                          'conf':     true,
                          'gw':       true,
                          'info':     true,
                          'otc':      true,
                          'oz':       true,
                          'telememo': true };

var co_second_domains = { 'com': true,
                          'org': true,
                          'edu': true,
                          'gov': true,
                          'net': true,
                          'mil': true,
                          'nom': true };

var es_second_domains = { 'com': true,
                          'nom': true,
                          'org': true,
                          'gob': true,
                          'edu': true };

var fr_second_domains = { 'tm':     true,
                          'asso':   true,
                          'nom':    true,
                          'prd':    true,
                          'presse': true,
                          'com':    true,
                          'gouv':   true };

var it_second_domains = { 'gov': true,
                          'edu': true };

var ly_second_domains = { 'com': true,
                          'net': true,
                          'gov': true,
                          'plc': true,
                          'edu': true,
                          'sch': true,
                          'med': true,
                          'org': true,
                          'id':  true };

var uk_second_domains = { 'ac':     true,
                          'co':     true,
                          'gov':    true,
                          'ltd':    true,
                          'me':     true,
                          'mod':    true,
                          'net':    true,
                          'nic':    true,
                          'nhs':    true,
                          'org':    true,
                          'plc':    true,
                          'police': true,
                          'sch':    true };

var st_second_domains = { 'nic':       true,
                          'gov':       true,
                          'saotome':   true,
                          'principle': true,
                          'consulado': true,
                          'embaixada': true,
                          'org':       true,
                          'edu':       true,
                          'net':       true,
                          'com':       true,
                          'sotre':     true,
                          'mil':       true,
                          'co':        true };

var trunc_domain = function(domain) {
    var sp  = domain.split('.').reverse();
    var tld;
    var sld;
    var result;

    if (sp.length < 2)
        return false;

    tld = sp[0];

    if (tld in gtlds) {
        return sp.slice(0, 2).reverse().join('.');
    } else if (tld == 'jp') {
        sld = sp[1];

        if (sld in jp_second_domains) {
            return sp.slice(0, 3).reverse().join('.');
        } else {
            return sp.slice(0, 2).reverse().join('.');
        }
    } else if (tld == 'ae') {
        sld = sp[1];

        if (sld in ae_second_domains) {
            return sp.slice(0, 3).reverse().join('.');
        } else {
            return sp.slice(0, 2).reverse().join('.');
        }
    } else if (tld == 'au') {
        sld = sp[1];

        if (sld in au_second_domains) {
            return sp.slice(0, 3).reverse().join('.');
        } else {
            return sp.slice(0, 2).reverse().join('.');
        }
    } else if (tld == 'co') {
        sld = sp[1];

        if (sld in co_second_domains) {
            return sp.slice(0, 3).reverse().join('.');
        } else {
            return sp.slice(0, 2).reverse().join('.');
        }
    } else if (tld == 'es') {
        sld = sp[1];

        if (sld in es_second_domains) {
            return sp.slice(0, 3).reverse().join('.');
        } else {
            return sp.slice(0, 2).reverse().join('.');
        }
    } else if (tld == 'fr') {
        sld = sp[1];

        if (sld in fr_second_domains) {
            return sp.slice(0, 3).reverse().join('.');
        } else {
            return sp.slice(0, 2).reverse().join('.');
        }
    } else if (tld == 'it') {
        sld = sp[1];

        if (sld in it_second_domains) {
            return sp.slice(0, 3).reverse().join('.');
        } else {
            return sp.slice(0, 2).reverse().join('.');
        }
    } else if (tld == 'ly') {
        sld = sp[1];

        if (sld in ly_second_domains) {
            return sp.slice(0, 3).reverse().join('.');
        } else {
            return sp.slice(0, 2).reverse().join('.');
        }
    } else if (tld == 'uk') {
        sld = sp[1];

        if (sld in uk_second_domains) {
            return sp.slice(0, 3).reverse().join('.');
        } else {
            return sp.slice(0, 2).reverse().join('.');
        }
    } else if (tld == 'st') {
        sld = sp[1];

        if (sld in st_second_domains) {
            return sp.slice(0, 3).reverse().join('.');
        } else {
            return sp.slice(0, 2).reverse().join('.');
        }
    } else if (parseInt(tld, 10) != NaN) {
        return domain;
    }

    if (sp.length > 3) {
        return sp.slice(0, 3).reverse().join('.');
    }

    return domain;
}

db.system.js.save({"_id": "trunc_domain", "value": trunc_domain});
db.system.js.save({"_id": "gtlds", "value": gtlds});
db.system.js.save({"_id": "jp_second_domains", "value": jp_second_domains});
db.system.js.save({"_id": "ae_second_domains", "value": ae_second_domains});
db.system.js.save({"_id": "fr_second_domains", "value": fr_second_domains});
db.system.js.save({"_id": "co_second_domains", "value": co_second_domains});
db.system.js.save({"_id": "ly_second_domains", "value": ly_second_domains});
db.system.js.save({"_id": "uk_second_domains", "value": uk_second_domains});

function trunc_hosts() {
    db.trunc_hosts.remove();
    db.trunc_hosts.ensureIndex({value: 1});

    for (var c = db.hosts.find(); c.hasNext(); ) {
        var domain = c.next()['_id'];
        var tr_domain = trunc_domain(domain);

        db.trunc_hosts.insert({_id: domain, value: tr_domain});
    }
}

trunc_hosts();

function map() {
    if ('referer' in this) {
        var referers = {};
        var uri;
        var referer;
        var tr_uri;
        var tr_referer;

        try {
            uri     = this.uri.split('/')[2].split(':')[0];
            referer = this.referer.split('/')[2].split(':')[0];
        } catch (e) {
            return;
        }

        uri     = trunc_domain(uri);
        referer = trunc_domain(referer);

        if (uri == referer)
            return;

        referers[referer] = 1;
        emit(uri, referers);
    }
}

function reduce(key, values) {
    var referers = {};

    values.forEach(function(value) {
        for (var i in value) {
            if (i in referers)
                referers[i] += value[i];
            else
                referers[i] = value[i];
        }
    });

    return referers;
}

var res = db.requests.mapReduce(map, reduce, {out: {replace: 'graph_trunc_host'}});

shellPrint(res);
<|endoftext|>


<commit_before>import React, { Component, PropTypes } from 'react';
import { RefreshControl } from 'react-native';
import { connect } from 'react-redux';

import DigiError from '../../common/DigiError';

import Event from './Event';

export const findEvent = (eventId, events) => {
  for (let edition in events) {
    if (events.hasOwnProperty(edition) && events[edition].items) {
      for (let i = 0; i < events[edition].items.length; i++) {
        if (parseInt(events[edition].items[i].Event.id, 10) === eventId) {
          return events[edition].items[i];
        }
      }
    }
  }
  return null;
}

const EventContainer = class EventContainer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      event: null,
    };
  }

  componentWillMount() {
    const { events, eventId } = this.props;
    const event = findEvent(eventId, events);
    if (!event) {
      // TODO: fetch event
    }
  }

  componentWillReceiveProps(nextProps) {
    const { events, eventId } = nextProps;
    if (!this.state.event) {
      const event = findEvent(eventId, events);
      if (event) {
        this.setState({
          event,
        });
      }
    }
  }

  render() {
    const { navigator } = this.props;
    const { event } = this.state;

    const refreshControl = (
      <RefreshControl
        refreshing={true}
        onRefresh={() => null}
      />
    );

    if (!event) {
      return (
        <DigiError
          refreshControl={refreshControl}
          image={require('../../common/img/tumbeast-network.png')}
          text="Oups, impossible de récupérer l'évènement"
        />
      );
    }

    return (
      <Event
        navigator={navigator}
        event={event}
      />
    );
  }
}

EventContainer.propTypes = {
  navigator: PropTypes.object.isRequired,
  events: PropTypes.object.isRequired,
  eventId: PropTypes.number.isRequired,
};

const mapStateToProps = (state) => {
  return {
    events: state.events,
  }
}

export default connect(mapStateToProps)(EventContainer);
<commit_msg>refactor EventContainer.findEvent<commit_after>import React, { Component, PropTypes } from 'react';
import { RefreshControl } from 'react-native';
import { connect } from 'react-redux';

import DigiError from '../../common/DigiError';

import Event from './Event';

export const findEvent = (eventId, events) => {
  return Object.values(events).map(edition => (
    edition.items.filter(item => (
      parseInt(item.Event.id, 10) === eventId)
    )
  )).reduce((previousValue, currentValue) => ({
    ...previousValue,
    ...currentValue[0],
  }), {});
}

const EventContainer = class EventContainer extends Component {
  constructor(props) {
    super(props);
    this.state = {
      event: null,
    };
  }

  componentWillMount() {
    const { events, eventId } = this.props;
    const event = findEvent(eventId, events);
    if (!event) {
      // TODO: fetch event
    }
  }

  componentWillReceiveProps(nextProps) {
    const { events, eventId } = nextProps;
    if (!this.state.event) {
      const event = findEvent(eventId, events);
      if (event) {
        this.setState({
          event,
        });
      }
    }
  }

  render() {
    const { navigator } = this.props;
    const { event } = this.state;

    const refreshControl = (
      <RefreshControl
        refreshing={true}
        onRefresh={() => null}
      />
    );

    if (!event) {
      return (
        <DigiError
          refreshControl={refreshControl}
          image={require('../../common/img/tumbeast-network.png')}
          text="Oups, impossible de récupérer l'évènement"
        />
      );
    }

    return (
      <Event
        navigator={navigator}
        event={event}
      />
    );
  }
}

EventContainer.propTypes = {
  navigator: PropTypes.object.isRequired,
  events: PropTypes.object.isRequired,
  eventId: PropTypes.number.isRequired,
};

const mapStateToProps = (state) => {
  return {
    events: state.events,
  }
}

export default connect(mapStateToProps)(EventContainer);
<|endoftext|>


<commit_before><commit_msg>create a dataset type training pop<commit_after><|endoftext|>


<commit_before><commit_msg>add aanalysis call<commit_after><|endoftext|>