<commit_before>/**
 * Competence class
 */
function Competence(viewmodel, id, code, name, weight, subcompetences) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        weight: ko.observable(weight),
        subcompetences: ko.observableArray(subcompetences),

        addSubCompetence: function() {
            this.subcompetences.push(new SubCompetence(this));
        },

        removeThis: function() {
            viewmodel.removeCompetence(this);
        },

        removeSubCompetence: function(subCompetence) {
            this.subcompetences.remove(subCompetence);
        }
    };

}

/**
 * SubCompetence class
 */
function SubCompetence(parent, id, code, name, weight, indicators) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        weight: ko.observable(weight),
        indicators: ko.observableArray(indicators),

        addIndicator: function() {
            this.indicators.push(new Indicator(this));
        },

        removeThis: function() {
            parent.removeSubCompetence(this);
        },

        removeIndicator: function(indicator) {
            this.indicators.remove(indicator);
        }
    };
}

/**
 * Indicator class
 */
function Indicator(parent, id, name, description) {
    return {
        id: ko.observable(id),
        name: ko.observable(name),
        description : ko.observable(description),

        removeThis: function() {
            parent.removeIndicator(this);
        }
    };
}

// View model for the courses page
function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.competences = 0;
    gvm.subcomp = 0;

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

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

    gvm.competences = ko.observableArray([]);

    gvm.addCompetence = function() {
        gvm.competences.push(new Competence(this));

        // Update automated weight calculation
        var size = gvm.competences.length;
        var percent = 100/size;

        ko.utils.arrayForEach(gvm.competences, function(competence){
            competence.weight(percent);
            alert(percent);
        });
    };

    gvm.removeCompetence = function(competence) {
        gvm.competences.remove(competence);
    }

    gvm.updateCompetence = function(id, code, description, max, weight) {
        var comp = new Competence(this, id, code, description, weight);
        gvm.competences.push(comp);
        return comp;
    }

    gvm.clearStructure = function() {
        gvm.competences.destroyAll();
    }
}

/**
 * Push the current project state to the database
 * @returns {undefined}
 */
function saveProjectStructure() {
    $.ajax({
       type: "POST",
       url: "/api/projectstructure/" + projectid,
       data: ko.toJSON(viewModel.competences),
       success: function(){
           // TODO make multilangual and with modals
           alert("Saved projectstructure to server");

           fetchProjectStructure();
       }
    });
}

function fetchProjectStructure() {
    viewModel.clearStructure();

    $.getJSON("/api/projectstructure/" + projectid, function(data){
        $.each(data, function(i, item){
            var competence = viewModel.updateCompetence(item.id, item.code, item.description, item.max, item.weight);

            $.each(item.subcompetences, function(i, subcomp){
               var subcompetence = new SubCompetence(competence, subcomp.id, subcomp.code, subcomp.description, subcomp.weight);
               competence.subcompetences.push(subcompetence);

               $.each(subcomp.indicators, function(i, indic){
                  subcompetence.indicators.push(new Indicator(subcompetence, indic.id, indic.name, indic.description));
               });
            });
        })
    });
}

function initPage() {
    fetchProjectStructure();

    $(".addCompetenceBtn").click(function() {
        viewModel.addCompetence();
    });

    $(".savePageBtn").click(function(){
        saveProjectStructure();
    });

    $(".locked").click(function() {
        setLocked();
    });
}
<commit_msg>weight check<commit_after>/**
 * Competence class
 */
function Competence(viewmodel, id, code, name, weight, subcompetences) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        weight: ko.observable(weight),
        subcompetences: ko.observableArray(subcompetences),

        addSubCompetence: function() {
            this.subcompetences.push(new SubCompetence(this));
        },

        removeThis: function() {
            viewmodel.removeCompetence(this);
        },

        removeSubCompetence: function(subCompetence) {
            this.subcompetences.remove(subCompetence);
        }
    };

}

/**
 * SubCompetence class
 */
function SubCompetence(parent, id, code, name, weight, indicators) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        weight: ko.observable(weight),
        indicators: ko.observableArray(indicators),

        addIndicator: function() {
            this.indicators.push(new Indicator(this));
        },

        removeThis: function() {
            parent.removeSubCompetence(this);
        },

        removeIndicator: function(indicator) {
            this.indicators.remove(indicator);
        }
    };
}

/**
 * Indicator class
 */
function Indicator(parent, id, name, description) {
    return {
        id: ko.observable(id),
        name: ko.observable(name),
        description : ko.observable(description),

        removeThis: function() {
            parent.removeIndicator(this);
        }
    };
}

// View model for the courses page
function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.competences = 0;
    gvm.subcomp = 0;

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

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

    gvm.competences = ko.observableArray([]);

    gvm.addCompetence = function() {
        gvm.competences.push(new Competence(this));

        // Update automated weight calculation
        var size = gvm.competences.length;
        var percent = 100/size;
        console.log(this.weight);

        ko.utils.arrayForEach(gvm.competences, function(competence){
            competence.weight(percent);
            alert(percent);
        });
    };

    gvm.removeCompetence = function(competence) {
        gvm.competences.remove(competence);
    }

    gvm.updateCompetence = function(id, code, description, max, weight) {
        var comp = new Competence(this, id, code, description, weight);
        gvm.competences.push(comp);
        return comp;
    }

    gvm.clearStructure = function() {
        gvm.competences.destroyAll();
    }
}

/**
 * Push the current project state to the database
 * @returns {undefined}
 */
function saveProjectStructure() {
    $.ajax({
       type: "POST",
       url: "/api/projectstructure/" + projectid,
       data: ko.toJSON(viewModel.competences),
       success: function(){
           // TODO make multilangual and with modals
           alert("Saved projectstructure to server");

           fetchProjectStructure();
       }
    });
}

function fetchProjectStructure() {
    viewModel.clearStructure();

    $.getJSON("/api/projectstructure/" + projectid, function(data){
        $.each(data, function(i, item){
            var competence = viewModel.updateCompetence(item.id, item.code, item.description, item.max, item.weight);

            $.each(item.subcompetences, function(i, subcomp){
               var subcompetence = new SubCompetence(competence, subcomp.id, subcomp.code, subcomp.description, subcomp.weight);
               competence.subcompetences.push(subcompetence);

               $.each(subcomp.indicators, function(i, indic){
                  subcompetence.indicators.push(new Indicator(subcompetence, indic.id, indic.name, indic.description));
               });
            });
        })
    });
}

function initPage() {
    fetchProjectStructure();

    $(".addCompetenceBtn").click(function() {
        viewModel.addCompetence();
    });

    $(".savePageBtn").click(function(){
        saveProjectStructure();
    });

    $(".locked").click(function() {
        setLocked();
    });
}
<|endoftext|>


<commit_before>// View model for the courses page
function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.numberOfCompetencesToAdd = 0;

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

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

function addCompetence() {
    ++viewModel.numberOfCompetencesToAdd;

    var competencePanelWrapper = document.createElement('div');
    var competencePanel = document.createElement('div');
    var competencePanelHeading = document.createElement('div');
    var competencePanelBody = document.createElement('div');
    var competencePanelFooter = document.createElement('div');
    var competenceCode = document.createElement('input');
    var competenceName = document.createElement('input');
    var subcompetenceButton = document.createElement('button');

    competenceCode.type = 'text';
    competenceCode.placeholder = "Competence-Code";
    $(competenceCode).addClass("form-control");

    competenceName.type = 'text';
    competenceName.placeholder = "Name of the competence";
    $(competenceName).addClass("form-control");

    $(subcompetenceButton).addClass("btn");
    $(subcompetenceButton).text("Add a subcompetence");
    $(subcompetenceButton).val(viewModel.numberOfCompetencesToAdd);
    $(subcompetenceButton).on('click', function() {
        addSubCompetence("comp-" + $(subcompetenceButton).val())
    });

    $(competencePanelWrapper).addClass("col-md-9");
    $(competencePanel).addClass("panel panel-default");
    $(competencePanelHeading).addClass("panel-heading comp-" + $(subcompetenceButton).val());
    $(competencePanelBody).addClass("panel-body");
    $(competencePanelFooter).addClass("panel-footer");

    $("#top-col").after(competencePanelWrapper);
    $(competencePanelWrapper).append(competencePanel);
    $(competencePanel).append(competencePanelHeading);
    $(competencePanelHeading).append(competenceName);
    $(competenceName).after(competenceCode);
    $(competencePanelHeading).after(competencePanelBody);
    $(competencePanelBody).after(competencePanelFooter);
    $(competencePanelFooter).append(subcompetenceButton);
}

function addSubCompetence(competence) {
    alert(competence);
}

function addIndicator() {

}

function initPage() {
    viewModel.getProjectInfo();
    $("#addCompetenceBtn").click(function() {
        addCompetence();
    })
}<commit_msg>projectpage<commit_after>// View model for the courses page
function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    gvm.numberOfCompetencesToAdd = 0;

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

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

function addCompetence() {

    ++viewModel.numberOfCompetencesToAdd;

    var competencePanelWrapper = document.createElement('div');
    var competencePanel = document.createElement('div');
    var competencePanelHeading = document.createElement('div');
    var competencePanelBody = document.createElement('div');
    var competencePanelFooter = document.createElement('div');
    var competenceCode = document.createElement('input');
    var competenceName = document.createElement('input');
    var subcompetenceButton = document.createElement('button');

    competenceCode.type = 'text';
    competenceCode.placeholder = "Competence-Code";
    $(competenceCode).addClass("form-control");

    competenceName.type = 'text';
    competenceName.placeholder = "Name of the competence";
    $(competenceName).addClass("form-control");

    $(subcompetenceButton).addClass("btn");
    $(subcompetenceButton).text("Add a subcompetence");
    $(subcompetenceButton).val(viewModel.numberOfCompetencesToAdd);
    $(subcompetenceButton).on('click', function() {
        addSubCompetence("comp-" + $(subcompetenceButton).val())
    });

    $(competencePanelWrapper).addClass("col-md-9");
    $(competencePanel).addClass("panel panel-default");
    $(competencePanelHeading).addClass("panel-heading comp-" + $(subcompetenceButton).val());
    $(competencePanelBody).addClass("panel-body");
    $(competencePanelFooter).addClass("panel-footer");

    if(viewModel.numberOfCompetencesToAdd == 0) {
        $("#top-col").after(competencePanelWrapper);
    } else {
        $(".panel:last").after(competencePanelWrapper);
    }

    $(competencePanelWrapper).append(competencePanel);
    $(competencePanel).append(competencePanelHeading);
    $(competencePanelHeading).append(competenceName);
    $(competenceName).after(competenceCode);
    $(competencePanelHeading).after(competencePanelBody);
    $(competencePanelBody).after(competencePanelFooter);
    $(competencePanelFooter).append(subcompetenceButton);
}

function addSubCompetence(competence) {
    alert(competence);
}

function addIndicator() {

}

function initPage() {
    viewModel.getProjectInfo();
    $("#addCompetenceBtn").click(function() {
        addCompetence();
    })
}<|endoftext|>


<commit_before>(function ($, root, undefined) {

	var isMobile = function() {
	  return ('ontouchstart' in window)
	}();

	var bannerEle = '#banner';
	var bannerOverlap = 30;

	var absolute = false;

	$(function () {
		$('.nav a[href^=#], .banner-button, #checkout-steps a').on('click', function(e){

			var location = $(this).attr('href');
			scrollTo(location, e);
		});

		$('.home-scroll').on('click', function(e){
			e.preventDefault();

			$.scrollTo( 0, 500, { 'axis':'y', offset: {top: -1 * parseInt($('.scrolled.reference').css('height')) } } );

			ga('send', 'pageview', '/');

		});

		$('.flash a').on('click', function(e){
			e.preventDefault();
			$(this).parent().css('display', 'none').fadeOut(1000);
		});

		$('form.select-package, form.reserve-date').on('submit', function(e){
			e.preventDefault();
			var $form = $(this);

			//do not allow payment while options are changing
			//$('#checkout-steps > a.done + a.done + a').unbind();
			$('#charge').addClass('hidden');

			$.ajax({
	            type: "POST",
	            url: $(this).attr('action'),
	            data: $(this).serialize(),
	            dataType: "json",
	            success: function(data) {
	                console.log(data);

					if (data.status == 'ok') {

		                if ($form.hasClass('select-package')) {
			                $('form.select-package input[type=submit]').each(function(ele, i){
			                	$(this)
			                		.removeClass('cupid-green')
			                		.addClass('clean-gray')
			                		.attr('value', $(this).attr('data-title'))
			                	;
			                });
		                }

		                $('#checkout-steps')
		                	.removeClass('hidden')
		                	.slideDown(700)
		                		.find('a.' + $form.find('input[name=action]')
		                			.val())
		                			.addClass('done')
		                ;

		                selectPackage($form.find('input[type=submit]'));

		                bindPayment();

	               	} else {
	               		addFlash(data.flash.errorMessage, data.flash.errorClass);
	               	}
	            },
	            error: function(){
	                 addFlash('There was a problem connecting to the server.

Please try again', 'warning');
	            }
	        });
		})

		setContentMargin();
		selectPackage($('.select-package.cupid-green'));
		selectPackage($('form.reserve-date .cupid-green'));
		bindPayment();

		var scrollPoint = getScrollPoint();
		shrinkHeader(scrollPoint);

		$( window )
			.on('scroll', function(e) {
				shrinkHeader(scrollPoint);
			})
			.on('resize', function() {
				setContentMargin();
				scrollPoint = getScrollPoint(parseInt($(bannerEle).css('height')));

			})
		;

		controlFlash();

	});

	function bindPayment()
	{
		var $pay = $('#checkout-steps > a.done + a.done + a');

		if ($pay.length > 0){

			$pay.on('click', function(e){
				scrollTo($(this).attr('href'), e);
			});

			setupPaymentButtons();

			/*

			$pay.on('click', function(e){
		    	var $selectedPackage = $('input.select-package.cupid-green');
				stripeHandler.open({
					name: 'Avow',
					description: $selectedPackage.attr('data-package-name'),
					amount: $selectedPackage.parent().find('input[name=package_price]').val() * 100
				});
				e.preventDefault();
		    });
		*/

		    $('#charge').removeClass('hidden');
		} else {
			$('#checkout-steps > a:last-child').off().on('click', function(e){
				e.preventDefault();
			});
		}
	}

	function setupPaymentButtons()
	{
		var $selectedPackage = $('input.select-package.cupid-green');

		$('#charge button.pay').each(function(i, ele){
			var payPercent = $(this).attr('data-pay-percent');
			var amount = $selectedPackage.parent().find('input[name=package_price]').val();
			var amountStripe = amount * payPercent;
			var amountPretty = '$' + (amount * payPercent / 100);

			$(this)
				.html($(this).attr('data-button-text') + ' (' + amountPretty + ')')
				.on('click', function(e){
			    	$('button.pay').removeClass('chosen-payment-method');
			    	$(this)
			    		.addClass('chosen-payment-method')
			    		.attr('data-stripe-amount', amountStripe);
			    	;

					stripeHandler.open({
						name: 'Avow',
						description: $selectedPackage.attr('data-package-name'),
						amount: amountStripe
					});
					e.preventDefault();
			    });
		})
	}

	function scrollTo(location, e)
	{
		e.preventDefault();

		var offset = -1 * ( parseInt($('.scrolled.reference').css('height')) /* + parseInt($('#checkout-steps').css('height')) */ );
		$.scrollTo(location, 500, { axis: 'y', offset: {top:  offset} });

		ga('send', 'pageview', location.replace('#', '/'));
	}

	function shrinkHeader(scrollPoint)
	{
		if (!absolute && $(this).scrollTop() >= scrollPoint - bannerOverlap) {
			$('.top-header').addClass('scrolled');
			absolute = !absolute;

		} else if (absolute && $(this).scrollTop() < scrollPoint - bannerOverlap) {
			$('.top-header').removeClass('scrolled');
			absolute = !absolute;
		}
	}

	function selectPackage($ele)
	{
		$ele.removeClass('clean-gray')
	    	.addClass('cupid-green')
	    	.attr('value', $ele.attr('data-selected-title'))
	    ;
	}

	function setContentMargin()
	{
		$('main.homepage > section:nth-child(2)').css('marginTop', (parseInt($(bannerEle).css('height')) + parseInt($(bannerEle).css('top'))) + 'px');
	}

	function getScrollPoint()
	{

		var offset = parseInt($('.scrolled.reference').css('height'));
		offset = 0;

		var position = parseInt($(bannerEle).css('height')) - offset;

		return position;
	}

})(jQuery, this);

function postForm(action, method, input) {
    "use strict";
    var form;
    form = jQuery('<form />', {
        action: action,
        method: method,
        style: 'display: none;'
    });
    if (typeof input !== 'undefined') {
        jQuery.each(input, function (name, value) {
            jQuery('<input />', {
                type: 'hidden',
                name: name,
                value: value
            }).appendTo(form);
        });
    }
    form.appendTo('body').submit();
}

function addFlash(errorMessage, errorClass)
{
	jQuery('.flash').addClass(errorClass).find('div').html(errorMessage);
	controlFlash();
}

function controlFlash() {
	$('.flash').hide();
	if ($('.flash > div').html().length > 0) {
		$('.flash').show().delay(10000).fadeOut(1000);
	}

}
<commit_msg>console fix<commit_after>(function() {  if (!window.console) {    window.console = {};  }  var m = [    "log", "info", "warn", "error", "debug", "trace", "dir", "group",    "groupCollapsed", "groupEnd", "time", "timeEnd", "profile", "profileEnd",    "dirxml", "assert", "count", "markTimeline", "timeStamp", "clear"  ];  for (var i = 0; i < m.length; i++) {    if (!window.console[m[i]]) {      window.console[m[i]] = function() {};    }      } })();
(function ($, root, undefined) {

	var isMobile = function() {
	  return ('ontouchstart' in window)
	}();

	var bannerEle = '#banner';
	var bannerOverlap = 30;

	var absolute = false;

	$(function () {
		$('.nav a[href^=#], .banner-button, #checkout-steps a').on('click', function(e){

			var location = $(this).attr('href');
			scrollTo(location, e);
		});

		$('.home-scroll').on('click', function(e){
			e.preventDefault();

			$.scrollTo( 0, 500, { 'axis':'y', offset: {top: -1 * parseInt($('.scrolled.reference').css('height')) } } );

			ga('send', 'pageview', '/');

		});

		$('.flash a').on('click', function(e){
			e.preventDefault();
			$(this).parent().css('display', 'none').fadeOut(1000);
		});

		$('form.select-package, form.reserve-date').on('submit', function(e){
			e.preventDefault();
			var $form = $(this);

			//do not allow payment while options are changing
			//$('#checkout-steps > a.done + a.done + a').unbind();
			$('#charge').addClass('hidden');

			$.ajax({
	            type: "POST",
	            url: $(this).attr('action'),
	            data: $(this).serialize(),
	            dataType: "json",
	            success: function(data) {
	                console.log(data);

					if (data.status == 'ok') {

		                if ($form.hasClass('select-package')) {
			                $('form.select-package input[type=submit]').each(function(ele, i){
			                	$(this)
			                		.removeClass('cupid-green')
			                		.addClass('clean-gray')
			                		.attr('value', $(this).attr('data-title'))
			                	;
			                });
		                }

		                $('#checkout-steps')
		                	.removeClass('hidden')
		                	.slideDown(700)
		                		.find('a.' + $form.find('input[name=action]')
		                			.val())
		                			.addClass('done')
		                ;

		                selectPackage($form.find('input[type=submit]'));

		                bindPayment();

	               	} else {
	               		addFlash(data.flash.errorMessage, data.flash.errorClass);
	               	}
	            },
	            error: function(){
	                 addFlash('There was a problem connecting to the server.

Please try again', 'warning');
	            }
	        });
		})

		setContentMargin();
		selectPackage($('.select-package.cupid-green'));
		selectPackage($('form.reserve-date .cupid-green'));
		bindPayment();

		var scrollPoint = getScrollPoint();
		shrinkHeader(scrollPoint);

		$( window )
			.on('scroll', function(e) {
				shrinkHeader(scrollPoint);
			})
			.on('resize', function() {
				setContentMargin();
				scrollPoint = getScrollPoint(parseInt($(bannerEle).css('height')));

			})
		;

		controlFlash();

	});

	function bindPayment()
	{
		var $pay = $('#checkout-steps > a.done + a.done + a');

		if ($pay.length > 0){

			$pay.on('click', function(e){
				scrollTo($(this).attr('href'), e);
			});

			setupPaymentButtons();

			/*

			$pay.on('click', function(e){
		    	var $selectedPackage = $('input.select-package.cupid-green');
				stripeHandler.open({
					name: 'Avow',
					description: $selectedPackage.attr('data-package-name'),
					amount: $selectedPackage.parent().find('input[name=package_price]').val() * 100
				});
				e.preventDefault();
		    });
		*/

		    $('#charge').removeClass('hidden');
		} else {
			$('#checkout-steps > a:last-child').off().on('click', function(e){
				e.preventDefault();
			});
		}
	}

	function setupPaymentButtons()
	{
		var $selectedPackage = $('input.select-package.cupid-green');

		$('#charge button.pay').each(function(i, ele){
			var payPercent = $(this).attr('data-pay-percent');
			var amount = $selectedPackage.parent().find('input[name=package_price]').val();
			var amountStripe = amount * payPercent;
			var amountPretty = '$' + (amount * payPercent / 100);

			$(this)
				.html($(this).attr('data-button-text') + ' (' + amountPretty + ')')
				.on('click', function(e){
			    	$('button.pay').removeClass('chosen-payment-method');
			    	$(this)
			    		.addClass('chosen-payment-method')
			    		.attr('data-stripe-amount', amountStripe);
			    	;

					stripeHandler.open({
						name: 'Avow',
						description: $selectedPackage.attr('data-package-name'),
						amount: amountStripe
					});
					e.preventDefault();
			    });
		})
	}

	function scrollTo(location, e)
	{
		e.preventDefault();

		var offset = -1 * ( parseInt($('.scrolled.reference').css('height')) /* + parseInt($('#checkout-steps').css('height')) */ );
		$.scrollTo(location, 500, { axis: 'y', offset: {top:  offset} });

		ga('send', 'pageview', location.replace('#', '/'));
	}

	function shrinkHeader(scrollPoint)
	{
		if (!absolute && $(this).scrollTop() >= scrollPoint - bannerOverlap) {
			$('.top-header').addClass('scrolled');
			absolute = !absolute;

		} else if (absolute && $(this).scrollTop() < scrollPoint - bannerOverlap) {
			$('.top-header').removeClass('scrolled');
			absolute = !absolute;
		}
	}

	function selectPackage($ele)
	{
		$ele.removeClass('clean-gray')
	    	.addClass('cupid-green')
	    	.attr('value', $ele.attr('data-selected-title'))
	    ;
	}

	function setContentMargin()
	{
		$('main.homepage > section:nth-child(2)').css('marginTop', (parseInt($(bannerEle).css('height')) + parseInt($(bannerEle).css('top'))) + 'px');
	}

	function getScrollPoint()
	{

		var offset = parseInt($('.scrolled.reference').css('height'));
		offset = 0;

		var position = parseInt($(bannerEle).css('height')) - offset;

		return position;
	}

})(jQuery, this);

function postForm(action, method, input) {
    "use strict";
    var form;
    form = jQuery('<form />', {
        action: action,
        method: method,
        style: 'display: none;'
    });
    if (typeof input !== 'undefined') {
        jQuery.each(input, function (name, value) {
            jQuery('<input />', {
                type: 'hidden',
                name: name,
                value: value
            }).appendTo(form);
        });
    }
    form.appendTo('body').submit();
}

function addFlash(errorMessage, errorClass)
{
	jQuery('.flash').addClass(errorClass).find('div').html(errorMessage);
	controlFlash();
}

function controlFlash() {
	$('.flash').hide();
	if ($('.flash > div').html().length > 0) {
		$('.flash').show().delay(10000).fadeOut(1000);
	}

}
<|endoftext|>


<commit_before>/**
 * Competence class
 */
function Competence(viewmodel, id, code, name, weight, locked, subcompetences) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        weight: ko.observable(weight),
        locked: false,
        subcompetences: ko.observableArray(subcompetences),

        addSubCompetence: function() {
            this.subcompetences.push(new SubCompetence(this));
            automatedWeightCalculation(this.subcompetences());
            /*var total = 100;
            alert(total);
            console.log(this.subcompetences);
            for(var sub in this.subcompetences){
                alert(sub);
                sub.calculateWeight(100);
                total -= sub.weight;
                alert(total);
            }*/
        },

        removeThis: function() {
            viewmodel.removeCompetence(this);
        },

        toggleLock: function(data, event){
            if(this.locked == true)
            {
                $(event.target).addClass("icon-unlock").removeClass("icon-lock");
                this.locked = false;
            }
            else
            {
                $(event.target).addClass("icon-lock").removeClass("icon-unlock");
                this.locked = true;
            }
        },

        removeSubCompetence: function(subCompetence) {
            this.subcompetences.remove(subCompetence);
        }
    };

}

/**
 * SubCompetence class
 */
function SubCompetence(parent, id, code, name, weight, locked, indicators) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        weight: ko.observable(weight),
        locked: false,
        indicators: ko.observableArray(indicators),

        addIndicator: function() {
            this.indicators.push(new Indicator(this));
            automatedWeightCalculation(this.indicators());
        },

        /*calculateWeight: function(total){
            this.weight = total;
        },*/

        removeThis: function() {
            parent.removeSubCompetence(this);
        },

        toggleLock: function(data, event){
            if(this.locked == true)
            {
                $(event.target).addClass("icon-unlock").removeClass("icon-lock");
                this.locked = false;
            }
            else
            {
                $(event.target).addClass("icon-lock").removeClass("icon-unlock");
                this.locked = true;
            }
        },

        removeIndicator: function(indicator) {
            this.indicators.remove(indicator);
        }

    };
}

/**
 * Indicator class
 */
function Indicator(parent, id, name, weight, locked, description) {
    return {
        id: ko.observable(id),
        name: ko.observable(name),
        weight: ko.observable(weight),
        locked: false,
        description : ko.observable(description),

        removeThis: function() {
            parent.removeIndicator(this);
        },

        toggleLock: function(data, event){
            if(this.locked == true)
            {
                $(event.target).addClass("icon-unlock").removeClass("icon-lock");
                this.locked = false;
            }
            else
            {
                $(event.target).addClass("icon-lock").removeClass("icon-unlock");
                this.locked = true;
            }
        }
    };
}

// View model for the courses page
function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    //gvm.competences = 0;
    gvm.subcomp = 0;

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

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

    gvm.competences = ko.observableArray([]);

    gvm.addCompetence = function() {
        gvm.competences.push(new Competence(this));

        // Update automated weight calculation
        ko.utils.arrayForEach(gvm.competences, function(competence){
            console.log(competence.weight);
            competence.weight(percent);
        });
    };

    gvm.removeCompetence = function(competence) {
        gvm.competences.remove(competence);
    }

    gvm.updateCompetence = function(id, code, description, max, weight) {
        var comp = new Competence(this, id, code, description, weight);
        gvm.competences.push(comp);
        return comp;
    }

    gvm.clearStructure = function() {
        gvm.competences.destroyAll();
    }
}

/**
 * Push the current project state to the database
 * @returns {undefined}
 */
function saveProjectStructure() {
    $.ajax({
       type: "POST",
       url: "/api/projectstructure/" + projectid,
       data: ko.toJSON(viewModel.competences),
       success: function(){
           // TODO make multilangual and with modals
           alert("Saved projectstructure to server");

           fetchProjectStructure();
       }
    });
}

function fetchProjectStructure() {
    viewModel.clearStructure();

    $.getJSON("/api/projectstructure/" + projectid, function(data){
        $.each(data, function(i, item){
            var competence = viewModel.updateCompetence(item.id, item.code, item.description, item.max, item.weight);

            $.each(item.subcompetences, function(i, subcomp){
               var subcompetence = new SubCompetence(competence, subcomp.id, subcomp.code, subcomp.description, subcomp.weight);
               competence.subcompetences.push(subcompetence);

               $.each(subcomp.indicators, function(i, indic){
                  subcompetence.indicators.push(new Indicator(subcompetence, indic.id, indic.name, indic.description));
               });
            });
        })
    });
}

function initPage() {
    fetchProjectStructure();

    $(".addCompetenceBtn").click(function() {
        viewModel.addCompetence();
    });

    $(".savePageBtn").click(function(){
        saveProjectStructure();
    });
}

function automatedWeightCalculation(data)
{
    var lockedPercent = 0;
    var nrOfUnlocked = 0;

    for(var index = 0; index < data.length; index++)
    {
        if(data[index].locked == true)
        {
            lockedPercent = lockedPercent + parseInt(data[index].weight());
        }
        else
        {
            nrOfUnlocked++;
        }
    }

    var remainingPercent = 100 - lockedPercent;

    var percentPerCompetence = remainingPercent / nrOfUnlocked;

    percentPerCompetence = Math.round(percentPerCompetence).toFixed(2);

    for(var index = 0; index < data.length; index++)
    {
        if(data[index].locked == false)
        {
            data[index].weight(percentPerCompetence);
        }
    }
}
<commit_msg>weight check<commit_after>/**
 * Competence class
 */
function Competence(viewmodel, id, code, name, weight, locked, subcompetences) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        weight: ko.observable(weight),
        locked: false,
        subcompetences: ko.observableArray(subcompetences),

        addSubCompetence: function() {
            this.subcompetences.push(new SubCompetence(this));
            automatedWeightCalculation(this.subcompetences());
            /*var total = 100;
            alert(total);
            console.log(this.subcompetences);
            for(var sub in this.subcompetences){
                alert(sub);
                sub.calculateWeight(100);
                total -= sub.weight;
                alert(total);
            }*/
        },

        removeThis: function() {
            viewmodel.removeCompetence(this);
        },

        toggleLock: function(data, event){
            if(this.locked == true)
            {
                $(event.target).addClass("icon-unlock").removeClass("icon-lock");
                this.locked = false;
            }
            else
            {
                $(event.target).addClass("icon-lock").removeClass("icon-unlock");
                this.locked = true;
            }
        },

        removeSubCompetence: function(subCompetence) {
            this.subcompetences.remove(subCompetence);
        }
    };

}

/**
 * SubCompetence class
 */
function SubCompetence(parent, id, code, name, weight, locked, indicators) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        weight: ko.observable(weight),
        locked: false,
        indicators: ko.observableArray(indicators),

        addIndicator: function() {
            this.indicators.push(new Indicator(this));
            automatedWeightCalculation(this.indicators());
        },

        /*calculateWeight: function(total){
            this.weight = total;
        },*/

        removeThis: function() {
            parent.removeSubCompetence(this);
        },

        toggleLock: function(data, event){
            if(this.locked == true)
            {
                $(event.target).addClass("icon-unlock").removeClass("icon-lock");
                this.locked = false;
            }
            else
            {
                $(event.target).addClass("icon-lock").removeClass("icon-unlock");
                this.locked = true;
            }
        },

        removeIndicator: function(indicator) {
            this.indicators.remove(indicator);
        }

    };
}

/**
 * Indicator class
 */
function Indicator(parent, id, name, weight, locked, description) {
    return {
        id: ko.observable(id),
        name: ko.observable(name),
        weight: ko.observable(weight),
        locked: false,
        description : ko.observable(description),

        removeThis: function() {
            parent.removeIndicator(this);
        },

        toggleLock: function(data, event){
            if(this.locked == true)
            {
                $(event.target).addClass("icon-unlock").removeClass("icon-lock");
                this.locked = false;
            }
            else
            {
                $(event.target).addClass("icon-lock").removeClass("icon-unlock");
                this.locked = true;
            }
        }
    };
}

// View model for the courses page
function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    //gvm.competences = 0;
    gvm.subcomp = 0;

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

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

    gvm.competences = ko.observableArray([]);

    gvm.addCompetence = function() {
        gvm.competences.push(new Competence(this));

        // Update automated weight calculation
        ko.utils.arrayForEach(gvm.competences, function(competence){
            console.log(competence.weight);
            competence.weight(percent);
        });
    };

    gvm.removeCompetence = function(competence) {
        gvm.competences.remove(competence);
    }

    gvm.updateCompetence = function(id, code, description, max, weight) {
        var comp = new Competence(this, id, code, description, weight);
        gvm.competences.push(comp);
        return comp;
    }

    gvm.clearStructure = function() {
        gvm.competences.destroyAll();
    }
}

/**
 * Push the current project state to the database
 * @returns {undefined}
 */
function saveProjectStructure() {
    $.ajax({
       type: "POST",
       url: "/api/projectstructure/" + projectid,
       data: ko.toJSON(viewModel.competences),
       success: function(){
           // TODO make multilangual and with modals
           alert("Saved projectstructure to server");

           fetchProjectStructure();
       }
    });
}

function fetchProjectStructure() {
    viewModel.clearStructure();

    $.getJSON("/api/projectstructure/" + projectid, function(data){
        $.each(data, function(i, item){
            var competence = viewModel.updateCompetence(item.id, item.code, item.description, item.max, item.weight);

            $.each(item.subcompetences, function(i, subcomp){
               var subcompetence = new SubCompetence(competence, subcomp.id, subcomp.code, subcomp.description, subcomp.weight);
               competence.subcompetences.push(subcompetence);

               $.each(subcomp.indicators, function(i, indic){
                  subcompetence.indicators.push(new Indicator(subcompetence, indic.id, indic.name, indic.description));
               });
            });
        })
    });
}

function initPage() {
    fetchProjectStructure();

    $(".addCompetenceBtn").click(function() {
        viewModel.addCompetence();
    });

    $(".savePageBtn").click(function(){
        saveProjectStructure();
    });
}

function automatedWeightCalculation(data)
{
    var lockedPercent = 0;
    var nrOfUnlocked = 0;

    for(var index = 0; index < data.length; index++)
    {
        if(data[index].locked == true)
        {
            lockedPercent = lockedPercent + parseInt(data[index].weight());
        }
        else
        {
            nrOfUnlocked++;
        }
    }

    var remainingPercent = 100 - lockedPercent;

    var percentPerCompetence = remainingPercent / nrOfUnlocked;

    percentPerCompetence = percentPerCompetence.toFixed(2);

    for(var index = 0; index < data.length; index++)
    {
        if(data[index].locked == false)
        {
            data[index].weight(percentPerCompetence);
        }
    }
}
<|endoftext|>


<commit_before>// list of objects

// put bag array in here until JSON works
var initialBag = ["A", "A", "A", "A", "A", "A", "A", "A", "A", "B", "B","C","C","D","D","D","D","E","E","E","E","E","E","E","E","E","E","E","E"];
// player

// bag
// bag will start as array
// that we splice from
// each turn when player gets new tiles

function Bag() {
  this.bagTiles = [];
};

function Player(name, score, rack) {
  this.name = name;
  this.score = score;
  this.rack = rack;
};

function Cell(x, y, pointMultiplier) {
  this.x = x;
  this.y = y;
  this.pointMultiplier = pointMultiplier;
};

function Rack() {
  this.rackTiles = [];
  this.needNumber = 7;
};

Rack.prototype.generateRack = function (needNumber,initialBag) {
  for (var i = 0; i < needNumber; i++) {
    var currentRandomInt = getRandomInt(0, 20);
    this.rackTiles.push(initialBag[currentRandomInt]);
    initialBag.splice(currentRandomInt, 1);
  };
  // random number between 1 and length of array
  // splice that number, place in Player's rack
  // repeat until player rack full
}

function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
};

// cell on board
// board ?

// rack

//
$(function () {
  // var word = JSON.parse(bag);
  // // console.log(JSON.parse(words));
  // console.log(JSON.parse(word));
  // console.log(word[1]);
  var rack = new Rack();
  rack.generateRack(7, initialBag);
  console.log(rack);
  console.log(initialBag);
});
<commit_msg>add vertical and horizontal checks<commit_after>// list of objects

// put bag array in here until JSON works
var initialBag = ["A", "A", "B", "C", "F", "P", "O", "O", "T", "R", "S","C","V","D","I","I","N","N","M","M","E","R","R","T","L","L","Q","Z","H","J","G","_"];
// player

// bag
// bag will start as array
// that we splice from
// each turn when player gets new tiles

function Bag() {
  this.bagTiles = [];
};

function Board() {

};

function Player(name, rack) {
  this.name = name;
  this.score = 0;
  this.rack = rack;
  this.currentWord = [];
};

function Cell(x, y, pointMultiplier) {
  this.x = x;
  this.y = y;
  this.pointMultiplier = pointMultiplier;
};

function Rack() {
  this.rackTiles = [];
  this.needNumber = 7;
};

Player.prototype.buildWord = function (tile) {
  debugger;
  return this.currentWord.push(tile);
};

Board.prototype.checkHorizontalPosition = function (currentWord) {
  var checkHorizontal;
  for (var i = 0; i < currentWord.length; i++) {
    if (currentWord[i].x === currentWord[i+1].x) {
      checkHorizontal = true;
    } else {
      checkHorizontal = false;
    }
  }
  return checkHorizontal;
};
Board.prototype.checkVerticalPosition = function (currentWord) {
  var checkVertical;
  for (var i = 0; i < currentWord.length; i++) {
    if (currentWord[i].y === currentWord[i+1].y) {
      checkVertical = true;
    } else {
      checkVertical = false;
    }
  }
  return checkVertical;
};

Rack.prototype.generateRack = function (needNumber,initialBag) {
  for (var i = 0; i < needNumber; i++) {
    var currentRandomInt = getRandomInt(0, 20);
    this.rackTiles.push(initialBag[currentRandomInt]);
    initialBag.splice(currentRandomInt, 1);
  };
  // random number between 1 and length of array
  // splice that number, place in Player's rack
  // repeat until player rack full
}

function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
};

// cell on board
// board ?

// rack

//
$(function () {
  // var word = JSON.parse(bag);
  // // console.log(JSON.parse(words));
  // console.log(JSON.parse(word));
  // console.log(word[1]);
  var rack = new Rack();
  rack.generateRack(7, initialBag);
  console.log(rack);
  console.log(initialBag);

  debugger;
  var player = new Player ("Tom", rack);
  var word=" ";
  for (var i = 0, j = 0; i < 5; i++) {
    var cell = new Cell(i, j, 2);
    word += player.buildWord(rack.rackTiles[i]);
    console.log(rack.rackTiles[i]);
  }
  console.log(word[2]);

});
<|endoftext|>


<commit_before>/**
 * Competence class
 */
function Competence(viewmodel, id, code, name, weight, locked, subcompetences) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        weight: ko.observable(weight),
        locked: false,
        subcompetences: ko.observableArray(subcompetences),

        addSubCompetence: function() {
            this.subcompetences.push(new SubCompetence(this));
            automatedWeightCalculation(this.subcompetences());
            /*var total = 100;
            alert(total);
            console.log(this.subcompetences);
            for(var sub in this.subcompetences){
                alert(sub);
                sub.calculateWeight(100);
                total -= sub.weight;
                alert(total);
            }*/
        },

        removeThis: function() {
            viewmodel.removeCompetence(this);
        },

        toggleLock: function(data, event){
            if(this.locked == true)
            {
                $(event.target).addClass("icon-unlock").removeClass("icon-lock");
                this.locked = false;
            }
            else
            {
                $(event.target).addClass("icon-lock").removeClass("icon-unlock");
                this.locked = true;
            }
        },

        removeSubCompetence: function(subCompetence) {
            this.subcompetences.remove(subCompetence);
            automatedWeightCalculation(this.subcompetences());
        }
    };

}

/**
 * SubCompetence class
 */
function SubCompetence(parent, id, code, name, weight, locked, indicators) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        weight: ko.observable(weight),
        locked: false,
        indicators: ko.observableArray(indicators),

        addIndicator: function() {
            this.indicators.push(new Indicator(this));
            automatedWeightCalculation(this.indicators());
        },

        /*calculateWeight: function(total){
            this.weight = total;
        },*/

        removeThis: function() {
            parent.removeSubCompetence(this);

        },

        toggleLock: function(data, event){
            if(this.locked == true)
            {
                $(event.target).addClass("icon-unlock").removeClass("icon-lock");
                this.locked = false;
            }
            else
            {
                $(event.target).addClass("icon-lock").removeClass("icon-unlock");
                this.locked = true;
            }
        },

        removeIndicator: function(indicator) {
            this.indicators.remove(indicator);
            automatedWeightCalculation(this.indicators());
        }

    };
}

/**
 * Indicator class
 */
function Indicator(parent, id, name, weight, locked, description) {
    return {
        id: ko.observable(id),
        name: ko.observable(name),
        weight: ko.observable(weight),
        locked: false,
        description : ko.observable(description),

        removeThis: function() {
            parent.removeIndicator(this);
        },

        toggleLock: function(data, event){
            if(this.locked == true)
            {
                $(event.target).addClass("icon-unlock").removeClass("icon-lock");
                this.locked = false;
            }
            else
            {
                $(event.target).addClass("icon-lock").removeClass("icon-unlock");
                this.locked = true;
            }
        }
    };
}

// View model for the courses page
function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    //gvm.competences = 0;
    gvm.subcomp = 0;

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

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

    gvm.competences = ko.observableArray([]);

    gvm.addCompetence = function() {
        gvm.competences.push(new Competence(this));
        automatedWeightCalculation(this.competences());

        // Update automated weight calculation
        ko.utils.arrayForEach(gvm.competences, function(competence){
            console.log(competence.weight);
            competence.weight(percent);
        });
    };

    gvm.removeCompetence = function(competence) {
        gvm.competences.remove(competence);
        automatedWeightCalculation(this.competences());
    }

    gvm.updateCompetence = function(id, code, description, max, weight) {
        var comp = new Competence(this, id, code, description, weight);
        gvm.competences.push(comp);
        return comp;
    }

    gvm.clearStructure = function() {
        gvm.competences.destroyAll();
    }
}

/**
 * Push the current project state to the database
 * @returns {undefined}
 */
function saveProjectStructure() {
    $.ajax({
       type: "POST",
       url: "/api/projectstructure/" + projectid,
       data: ko.toJSON(viewModel.competences),
       success: function(){
           // TODO make multilangual and with modals
           alert("Saved projectstructure to server");

           fetchProjectStructure();
       }
    });
}

function fetchProjectStructure() {
    viewModel.clearStructure();

    $.getJSON("/api/projectstructure/" + projectid, function(data){
        $.each(data, function(i, item){
            var competence = viewModel.updateCompetence(item.id, item.code, item.description, item.max, item.weight);

            $.each(item.subcompetences, function(i, subcomp){
               var subcompetence = new SubCompetence(competence, subcomp.id, subcomp.code, subcomp.description, subcomp.weight);
               competence.subcompetences.push(subcompetence);

               $.each(subcomp.indicators, function(i, indic){
                  subcompetence.indicators.push(new Indicator(subcompetence, indic.id, indic.name, indic.description));
               });
            });
        })
    });
}

function initPage() {
    fetchProjectStructure();

    $(".addCompetenceBtn").click(function() {
        viewModel.addCompetence();
    });

    $(".savePageBtn").click(function(){
        totalPercentCheck();
        saveProjectStructure();
    });
}

function totalPercentCheck()
{
    console.log(viewModel.competences().weight);
}

function automatedWeightCalculation(data)
{
    var lockedPercent = 0;
    var nrOfUnlocked = 0;

    for(var index = 0; index < data.length; index++)
    {
        if(data[index].locked == true)
        {
            lockedPercent = lockedPercent + parseInt(data[index].weight());
        }
        else
        {
            nrOfUnlocked++;
        }
    }

    var remainingPercent = 100 - lockedPercent;

    var percentPerCompetence = remainingPercent / nrOfUnlocked;

    percentPerCompetence = percentPerCompetence.toFixed(2);

    for(var index = 0; index < data.length; index++)
    {
        if(data[index].locked == false)
        {
            data[index].weight(percentPerCompetence);
        }
    }
}
<commit_msg>total percent check<commit_after>/**
 * Competence class
 */
function Competence(viewmodel, id, code, name, weight, locked, subcompetences) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        weight: ko.observable(weight),
        locked: false,
        subcompetences: ko.observableArray(subcompetences),

        addSubCompetence: function() {
            this.subcompetences.push(new SubCompetence(this));
            automatedWeightCalculation(this.subcompetences());
            /*var total = 100;
            alert(total);
            console.log(this.subcompetences);
            for(var sub in this.subcompetences){
                alert(sub);
                sub.calculateWeight(100);
                total -= sub.weight;
                alert(total);
            }*/
        },

        removeThis: function() {
            viewmodel.removeCompetence(this);
        },

        toggleLock: function(data, event){
            if(this.locked == true)
            {
                $(event.target).addClass("icon-unlock").removeClass("icon-lock");
                this.locked = false;
            }
            else
            {
                $(event.target).addClass("icon-lock").removeClass("icon-unlock");
                this.locked = true;
            }
        },

        removeSubCompetence: function(subCompetence) {
            this.subcompetences.remove(subCompetence);
            automatedWeightCalculation(this.subcompetences());
        }
    };

}

/**
 * SubCompetence class
 */
function SubCompetence(parent, id, code, name, weight, locked, indicators) {
    return {
        id: ko.observable(id),
        code: ko.observable(code),
        name: ko.observable(name),
        weight: ko.observable(weight),
        locked: false,
        indicators: ko.observableArray(indicators),

        addIndicator: function() {
            this.indicators.push(new Indicator(this));
            automatedWeightCalculation(this.indicators());
        },

        /*calculateWeight: function(total){
            this.weight = total;
        },*/

        removeThis: function() {
            parent.removeSubCompetence(this);

        },

        toggleLock: function(data, event){
            if(this.locked == true)
            {
                $(event.target).addClass("icon-unlock").removeClass("icon-lock");
                this.locked = false;
            }
            else
            {
                $(event.target).addClass("icon-lock").removeClass("icon-unlock");
                this.locked = true;
            }
        },

        removeIndicator: function(indicator) {
            this.indicators.remove(indicator);
            automatedWeightCalculation(this.indicators());
        }

    };
}

/**
 * Indicator class
 */
function Indicator(parent, id, name, weight, locked, description) {
    return {
        id: ko.observable(id),
        name: ko.observable(name),
        weight: ko.observable(weight),
        locked: false,
        description : ko.observable(description),

        removeThis: function() {
            parent.removeIndicator(this);
        },

        toggleLock: function(data, event){
            if(this.locked == true)
            {
                $(event.target).addClass("icon-unlock").removeClass("icon-lock");
                this.locked = false;
            }
            else
            {
                $(event.target).addClass("icon-lock").removeClass("icon-unlock");
                this.locked = true;
            }
        }
    };
}

// View model for the courses page
function pageViewModel(gvm) {
    // projecttitle
    gvm.projecttitle = ko.observable("");
    //gvm.competences = 0;
    gvm.subcomp = 0;

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

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

    gvm.competences = ko.observableArray([]);

    gvm.addCompetence = function() {
        gvm.competences.push(new Competence(this));
        automatedWeightCalculation(this.competences());

        // Update automated weight calculation
        ko.utils.arrayForEach(gvm.competences, function(competence){
            console.log(competence.weight);
            competence.weight(percent);
        });
    };

    gvm.removeCompetence = function(competence) {
        gvm.competences.remove(competence);
        automatedWeightCalculation(this.competences());
    }

    gvm.updateCompetence = function(id, code, description, max, weight) {
        var comp = new Competence(this, id, code, description, weight);
        gvm.competences.push(comp);
        return comp;
    }

    gvm.clearStructure = function() {
        gvm.competences.destroyAll();
    }
}

/**
 * Push the current project state to the database
 * @returns {undefined}
 */
function saveProjectStructure() {
    $.ajax({
       type: "POST",
       url: "/api/projectstructure/" + projectid,
       data: ko.toJSON(viewModel.competences),
       success: function(){
           // TODO make multilangual and with modals
           alert("Saved projectstructure to server");

           fetchProjectStructure();
       }
    });
}

function fetchProjectStructure() {
    viewModel.clearStructure();

    $.getJSON("/api/projectstructure/" + projectid, function(data){
        $.each(data, function(i, item){
            var competence = viewModel.updateCompetence(item.id, item.code, item.description, item.max, item.weight);

            $.each(item.subcompetences, function(i, subcomp){
               var subcompetence = new SubCompetence(competence, subcomp.id, subcomp.code, subcomp.description, subcomp.weight);
               competence.subcompetences.push(subcompetence);

               $.each(subcomp.indicators, function(i, indic){
                  subcompetence.indicators.push(new Indicator(subcompetence, indic.id, indic.name, indic.description));
               });
            });
        })
    });
}

function initPage() {
    fetchProjectStructure();

    $(".addCompetenceBtn").click(function() {
        viewModel.addCompetence();
    });

    $(".savePageBtn").click(function(){
        totalPercentCheck();
        saveProjectStructure();
    });
}

function totalPercentCheck()
{
    console.log(viewModel.competences()[0].weight);
}

function automatedWeightCalculation(data)
{
    var lockedPercent = 0;
    var nrOfUnlocked = 0;

    for(var index = 0; index < data.length; index++)
    {
        if(data[index].locked == true)
        {
            lockedPercent = lockedPercent + parseInt(data[index].weight());
        }
        else
        {
            nrOfUnlocked++;
        }
    }

    var remainingPercent = 100 - lockedPercent;

    var percentPerCompetence = remainingPercent / nrOfUnlocked;

    percentPerCompetence = percentPerCompetence.toFixed(2);

    for(var index = 0; index < data.length; index++)
    {
        if(data[index].locked == false)
        {
            data[index].weight(percentPerCompetence);
        }
    }
}
<|endoftext|>


<commit_before>

function reset() {
    console.log('Resetting');
}
<commit_msg>fixed controller issue<commit_after>

function reset() {
    console.log('Resetting');
}

function RatingCalculatorController($scope) {

    $scope.games = [];
    for (var i = 0; i < 5; i++) {
        var g = {
            id: "game" + i,
            result: 1
        };
        $scope.games[i] = g;
    }

    $scope.addNewGame = function() {
        console.log("Adding new game");
        var newItemNo = $scope.games.length + 1;
        $scope.games.push({
            'id': 'game' + newItemNo

        });
    };

    $scope.removeChoice = function(index) {

        $scope.games.splice(index, 1);
    };

    // fields description of entity
    $scope.fields = [{
            name: 'grade',
            title: 'Grade',
            required: true,
            cssClassing: 'testing',
            type: {
                view: 'input'
            }
        },
        {
            name: 'result',
            title: 'Result`',
            required: true,
            cssClassing: 'testing',
            type: {
                view: 'radio'
            }
        },

    ];

    $scope.calculate = function() {
        console.log('Calculating Grade...')

        var currentgrade = parseInt($('#currentgrade').val());

        console.log('Current Grade:' + currentgrade);

        console.log('Grades:');
        for (var i = 0; i < $scope.games.length; i++) {
            console.log($scope.games[i].grade);
        }

        console.log('Results:');;
        for (var i = 0; i < $scope.games.length; i++) {
            console.log($scope.games[i].result);
        }

        var result = 0;
        var divisor = 0;

        if (currentgrade != 'undefined' && currentgrade > 0 && !isNaN(currentgrade)) {
            result = result + currentgrade;
            divisor++;
        }

        for (var i = 0; i < $scope.games.length; i++) {
            var opponentsgrade = $scope.games[i].grade;

            if ($scope.games[i].grade != 'undefined' && $scope.games[i].result != 'undefined' && !isNaN($scope.games[i].grade)) {
                // the grades differ by no more than 40 rule
                if (currentgrade != 'undefined' && currentgrade > 0)
                    if (opponentsgrade > currentgrade + 40) {
                        console.log('Apply the grade difference rule to opponent ' + i);
                        opponentsgrade = currentgrade + 40;
                    }

                if (opponentsgrade < currentgrade - 40) {
                    console.log('Apply the grade difference rule to opponent ' + i);
                    opponentsgrade = currentgrade - 40;
                }

                var offset;
                if ($scope.games[i].result == 0) {
                    offset = 0;
                } else if ($scope.games[i].result == 1) {
                    offset = 50;
                } else {
                    offset = -50;
                }

                result = parseInt(result) + parseInt(opponentsgrade) + offset;
                divisor++;
            }
        }

        result = result / divisor;
        result = Math.round(result);

        $('#messages').empty();
        if (isNaN(result)) {
            $('#messages').append('
There are some invalid entries for either your grade or your opponents grades.  Correct and try again.
');
        } else {
            $('#messages').append('Your grade is now ' + result);
        }
    }
}
<|endoftext|>


<commit_before>// Copyright 2021, University of Colorado Boulder

const execute = require( '../common/execute' );
const _ = require( 'lodash' ); // eslint-disable-line
const fs = require( 'fs' );

// constants
// Don't use getActiveRepos() since it cannot be run from the root
const contents = fs.readFileSync( 'perennial/data/active-repos', 'utf8' ).trim();
const repos = contents.split( '\n' ).map( sim => sim.trim() );

/**
 * Pulls all repos (with rebase)
 *
 * USAGE:
 * cd ${root containing all repos}
 * node perennial/js/scripts/pull-all.js
 *
 * @author Sam Reid (PhET Interactive Simulations)
 */
( async () => {

  const a = repos.map( repo => execute( 'git', [ 'pull', '--rebase' ], `${repo}`, {

    // resolve errors so Promise.all doesn't fail on first repo that cannot pull/rebase
    errors: 'resolve'
  } ) );
  const out = await Promise.all( a );

  // Report results
  for ( let i = 0; i < a.length; i++ ) {
    const repo = repos[ i ];
    const o = out[ i ];

    if ( o.code === 0 && o.stderr === '' && ( o.stdout.includes( 'up to date' ) ) ) {

      // nothing to do
    }
    else {
      console.log( '##', repo );
      o.stdout.trim().length > 0 && console.log( o.stdout );
      o.stderr.trim().length > 0 && console.log( o.stderr );
      o.error && console.log( o.error );
    }
  }
} )();<commit_msg>Revert "less strict logging for all that are 'up to date', https://github.com/phetsims/perennial/issues/261"<commit_after>// Copyright 2021, University of Colorado Boulder

const execute = require( '../common/execute' );
const _ = require( 'lodash' ); // eslint-disable-line
const fs = require( 'fs' );

// constants
// Don't use getActiveRepos() since it cannot be run from the root
const contents = fs.readFileSync( 'perennial/data/active-repos', 'utf8' ).trim();
const repos = contents.split( '\n' ).map( sim => sim.trim() );

/**
 * Pulls all repos (with rebase)
 *
 * USAGE:
 * cd ${root containing all repos}
 * node perennial/js/scripts/pull-all.js
 *
 * @author Sam Reid (PhET Interactive Simulations)
 */
( async () => {

  const a = repos.map( repo => execute( 'git', [ 'pull', '--rebase' ], `${repo}`, {

    // resolve errors so Promise.all doesn't fail on first repo that cannot pull/rebase
    errors: 'resolve'
  } ) );
  const out = await Promise.all( a );

  // Report results
  for ( let i = 0; i < a.length; i++ ) {
    const repo = repos[ i ];
    const o = out[ i ];

    if ( o.code === 0 && o.stderr === '' && ( o.stdout === 'Already up to date.\nCurrent branch master is up to date.\n' ||
                                              o.stdout === 'Already up to date.\n' ||
                                              o.stdout === 'Current branch master is up to date.\n' ) ) {

      // nothing to do
    }
    else {
      console.log( '##', repo );
      o.stdout.trim().length > 0 && console.log( o.stdout );
      o.stderr.trim().length > 0 && console.log( o.stderr );
      o.error && console.log( o.error );
    }
  }
} )();<|endoftext|>


<commit_before>(function($) {
	$(document).ready(function() {

		/**
		 * Проверяем наличие флеша
		 */

		if (navigator.plugins['Shockwave Flash']) {
			$('html').removeClass('no-shockwave-flash').addClass('shockwave-flash');
		}

		/**
		 * Определяем браузер
		 */

		var browser;
		if ($.browser.webkit || $.browser.safari) {
			browser = 'webkit';
		} else if ($.browser.opera) {
			browser = 'opera';
		} else if ($.browser.msie) {
			browser = 'ie';
		} else if ($.browser.mozilla) {
			browser = 'mozilla';
		}

		/**
		 * Функция вывода уведомления
		 */

		// флаг факта открытия хотя бы одного уведомления
		var has_noty = false;

		$.fn.alert = function(pwd) {
			pwd = $(this).text();
			if (typeof pwd == 'undefined') {
				text = 'Пароль скопирован';
			} else {
				text = 'Скопирован пароль ' + pwd;
			}
			if (!$.browser.mozilla) {
				noty({
					layout: 'topCenter',
					type: 'success',
					text: text,
					timeout: 1500,
					maxVisible: 3,
					animation: {
						open: {height: 'toggle'},
						close: {height: 'toggle'},
						easing: 'swing',
						speed: 100
					}
				});
				has_noty = true;
			}
			return this;
		};

		/**
		 * Функция получения нового пароля
		 */

		$.fn.getPwd = function() {
			var item = $(this);
			$.ajax({
				url: 'generate.php',
				data: {
					length: item.data('length'),
					number: item.data('number'),
					mark: item.data('mark'),
					extra: item.data('extra')
				},
				success: function(data) {
					setTimeout(function() {
						item.removeClass('copied');
						item.siblings('.zclip').remove();
						item.text(data);
						item.unbind('zClip_copy zClip_beforeCopy zClip_afterCopy');
						item.zClipRun();
					}, 1700);
				}
			});
			return this;
		};

		/**
		 * zClip run
		 */

		$.fn.zClipRun = function() {
			var item = $(this);
			item.zclip({
				path: 'js/vendor/jquery.zclip.1.1.1/ZeroClipboard.swf',
				copy: function() {
					return item.text();
				},
				afterCopy: function() {
					item
						.addClass('copied')
						.alert()
						.getPwd();
				}
			});
		};

		/**
		 * Если это не старые IE и включен флеш, то вешаем обработку копирования в буфер
		 * и уведомление об этом
		 */
		if (
			!$('html').hasClass('lt-ie9') &&
			navigator.plugins['Shockwave Flash']
		) {
			var pwds = $('.pwd');
			pwds.each(function(index, item) {
				$(item).zClipRun();
			});
		}

	});
})(jQuery);
<commit_msg>Рефакторинг<commit_after>(function($) {
	$(document).ready(function() {

		var html = $('html');

		/**
		 * Проверяем наличие флеша
		 */

		if (navigator.plugins['Shockwave Flash']) {
			html.removeClass('no-shockwave-flash').addClass('shockwave-flash');
		}

		/**
		 * Определяем браузер
		 */

		var browser;
		if ($.browser.webkit || $.browser.safari) {
			browser = 'webkit';
		} else if ($.browser.opera) {
			browser = 'opera';
		} else if ($.browser.msie) {
			browser = 'ie';
		} else if ($.browser.mozilla) {
			browser = 'mozilla';
		}

		/**
		 * Функция вывода уведомления
		 */

		// флаг факта открытия хотя бы одного уведомления
		var has_noty = false;

		$.fn.alert = function(pwd) {
			pwd = $(this).text();
			if (typeof pwd == 'undefined') {
				text = 'Пароль скопирован';
			} else {
				text = 'Скопирован пароль ' + pwd;
			}
			if (!$.browser.mozilla) {
				noty({
					layout: 'topCenter',
					type: 'success',
					text: text,
					timeout: 1500,
					maxVisible: 3,
					animation: {
						open: {height: 'toggle'},
						close: {height: 'toggle'},
						easing: 'swing',
						speed: 100
					}
				});
				has_noty = true;
			}
			return this;
		};

		/**
		 * Функция получения нового пароля
		 */

		$.fn.getPwd = function() {
			var item = $(this);
			$.ajax({
				url: 'generate.php',
				data: {
					length: item.data('length'),
					number: item.data('number'),
					mark: item.data('mark'),
					extra: item.data('extra')
				},
				success: function(data) {
					setTimeout(function() {
						item.removeClass('copied');
						item.siblings('.zclip').remove();
						item.text(data);
						item.unbind('zClip_copy zClip_beforeCopy zClip_afterCopy');
						item.zClipRun();
					}, 1700);
				}
			});
			return this;
		};

		/**
		 * zClip run
		 */

		$.fn.zClipRun = function() {
			var item = $(this);
			item.zclip({
				path: 'js/vendor/jquery.zclip.1.1.1/ZeroClipboard.swf',
				copy: function() {
					return item.text();
				},
				afterCopy: function() {
					item
						.addClass('copied')
						.alert()
						.getPwd();
				}
			});
		};

		/**
		 * Если это не старые IE и включен флеш, то вешаем обработку копирования в буфер
		 * и уведомление об этом
		 */
		if (
			!html.hasClass('lt-ie9') &&
			navigator.plugins['Shockwave Flash']
		) {
			var pwds = $('.pwd');
			pwds.each(function(index, item) {
				$(item).zClipRun();
			});
		}

	});
})(jQuery);
<|endoftext|>


<commit_before>import compat from '../common/compat';

import PostControls from './utils/PostControls';
import KeyboardNavigatable from './utils/KeyboardNavigatable';
import slidable from './utils/slidable';
import affixSidebar from './utils/affixSidebar';
import History from './utils/History';
import DiscussionControls from './utils/DiscussionControls';
import alertEmailConfirmation from './utils/alertEmailConfirmation';
import UserControls from './utils/UserControls';
import Pane from './utils/Pane';
import DiscussionPage from './components/DiscussionPage';
import LogInModal from './components/LogInModal';
import ComposerBody from './components/ComposerBody';
import ForgotPasswordModal from './components/ForgotPasswordModal';
import Notification from './components/Notification';
import LogInButton from './components/LogInButton';
import DiscussionsUserPage from './components/DiscussionsUserPage';
import Composer from './components/Composer';
import SessionDropdown from './components/SessionDropdown';
import HeaderPrimary from './components/HeaderPrimary';
import PostEdited from './components/PostEdited';
import PostStream from './components/PostStream';
import ChangePasswordModal from './components/ChangePasswordModal';
import IndexPage from './components/IndexPage';
import DiscussionRenamedNotification from './components/DiscussionRenamedNotification';
import DiscussionsSearchSource from './components/DiscussionsSearchSource';
import HeaderSecondary from './components/HeaderSecondary';
import ComposerButton from './components/ComposerButton';
import DiscussionList from './components/DiscussionList';
import ReplyPlaceholder from './components/ReplyPlaceholder';
import TextEditor from './components/TextEditor';
import TextEditorButton from './components/TextEditorButton';
import AvatarEditor from './components/AvatarEditor';
import Post from './components/Post';
import SettingsPage from './components/SettingsPage';
import TerminalPost from './components/TerminalPost';
import ChangeEmailModal from './components/ChangeEmailModal';
import NotificationsDropdown from './components/NotificationsDropdown';
import UserPage from './components/UserPage';
import PostUser from './components/PostUser';
import UserCard from './components/UserCard';
import UsersSearchSource from './components/UsersSearchSource';
import NotificationGrid from './components/NotificationGrid';
import PostPreview from './components/PostPreview';
import EventPost from './components/EventPost';
import DiscussionHero from './components/DiscussionHero';
import PostMeta from './components/PostMeta';
import EditUserModal from './components/EditUserModal';
import SearchSource from './components/SearchSource';
import DiscussionRenamedPost from './components/DiscussionRenamedPost';
import DiscussionComposer from './components/DiscussionComposer';
import LogInButtons from './components/LogInButtons';
import NotificationList from './components/NotificationList';
import WelcomeHero from './components/WelcomeHero';
import SignUpModal from './components/SignUpModal';
import CommentPost from './components/CommentPost';
import ReplyComposer from './components/ReplyComposer';
import NotificationsPage from './components/NotificationsPage';
import PostStreamScrubber from './components/PostStreamScrubber';
import EditPostComposer from './components/EditPostComposer';
import RenameDiscussionModal from './components/RenameDiscussionModal';
import Search from './components/Search';
import DiscussionListItem from './components/DiscussionListItem';
import LoadingPost from './components/LoadingPost';
import PostsUserPage from './components/PostsUserPage';
import routes from './routes';
import ForumApplication from './ForumApplication';

export default Object.assign(compat, {
  'utils/PostControls': PostControls,
  'utils/KeyboardNavigatable': KeyboardNavigatable,
  'utils/slidable': slidable,
  'utils/affixSidebar': affixSidebar,
  'utils/History': History,
  'utils/DiscussionControls': DiscussionControls,
  'utils/alertEmailConfirmation': alertEmailConfirmation,
  'utils/UserControls': UserControls,
  'utils/Pane': Pane,
  'components/DiscussionPage': DiscussionPage,
  'components/LogInModal': LogInModal,
  'components/ComposerBody': ComposerBody,
  'components/ForgotPasswordModal': ForgotPasswordModal,
  'components/Notification': Notification,
  'components/LogInButton': LogInButton,
  'components/DiscussionsUserPage': DiscussionsUserPage,
  'components/Composer': Composer,
  'components/SessionDropdown': SessionDropdown,
  'components/HeaderPrimary': HeaderPrimary,
  'components/PostEdited': PostEdited,
  'components/PostStream': PostStream,
  'components/ChangePasswordModal': ChangePasswordModal,
  'components/IndexPage': IndexPage,
  'components/DiscussionRenamedNotification': DiscussionRenamedNotification,
  'components/DiscussionsSearchSource': DiscussionsSearchSource,
  'components/HeaderSecondary': HeaderSecondary,
  'components/ComposerButton': ComposerButton,
  'components/DiscussionList': DiscussionList,
  'components/ReplyPlaceholder': ReplyPlaceholder,
  'components/TextEditor': TextEditor,
  'components/TextEditorButton': TextEditorButton,
  'components/AvatarEditor': AvatarEditor,
  'components/Post': Post,
  'components/SettingsPage': SettingsPage,
  'components/TerminalPost': TerminalPost,
  'components/ChangeEmailModal': ChangeEmailModal,
  'components/NotificationsDropdown': NotificationsDropdown,
  'components/UserPage': UserPage,
  'components/PostUser': PostUser,
  'components/UserCard': UserCard,
  'components/UsersSearchSource': UsersSearchSource,
  'components/NotificationGrid': NotificationGrid,
  'components/PostPreview': PostPreview,
  'components/EventPost': EventPost,
  'components/DiscussionHero': DiscussionHero,
  'components/PostMeta': PostMeta,
  'components/EditUserModal': EditUserModal,
  'components/SearchSource': SearchSource,
  'components/DiscussionRenamedPost': DiscussionRenamedPost,
  'components/DiscussionComposer': DiscussionComposer,
  'components/LogInButtons': LogInButtons,
  'components/NotificationList': NotificationList,
  'components/WelcomeHero': WelcomeHero,
  'components/SignUpModal': SignUpModal,
  'components/CommentPost': CommentPost,
  'components/ReplyComposer': ReplyComposer,
  'components/NotificationsPage': NotificationsPage,
  'components/PostStreamScrubber': PostStreamScrubber,
  'components/EditPostComposer': EditPostComposer,
  'components/RenameDiscussionModal': RenameDiscussionModal,
  'components/Search': Search,
  'components/DiscussionListItem': DiscussionListItem,
  'components/LoadingPost': LoadingPost,
  'components/PostsUserPage': PostsUserPage,
  routes: routes,
  ForumApplication: ForumApplication,
});
<commit_msg>Expose state classes via compat<commit_after>import compat from '../common/compat';

import PostControls from './utils/PostControls';
import KeyboardNavigatable from './utils/KeyboardNavigatable';
import slidable from './utils/slidable';
import affixSidebar from './utils/affixSidebar';
import History from './utils/History';
import DiscussionControls from './utils/DiscussionControls';
import alertEmailConfirmation from './utils/alertEmailConfirmation';
import UserControls from './utils/UserControls';
import Pane from './utils/Pane';
import DiscussionListState from './state/DiscussionListState';
import GlobalSearchState from './states/GlobalSearchState';
import NotificationListState from './states/NotificationListState';
import SearchState from './states/SearchState';
import DiscussionPage from './components/DiscussionPage';
import LogInModal from './components/LogInModal';
import ComposerBody from './components/ComposerBody';
import ForgotPasswordModal from './components/ForgotPasswordModal';
import Notification from './components/Notification';
import LogInButton from './components/LogInButton';
import DiscussionsUserPage from './components/DiscussionsUserPage';
import Composer from './components/Composer';
import SessionDropdown from './components/SessionDropdown';
import HeaderPrimary from './components/HeaderPrimary';
import PostEdited from './components/PostEdited';
import PostStream from './components/PostStream';
import ChangePasswordModal from './components/ChangePasswordModal';
import IndexPage from './components/IndexPage';
import DiscussionRenamedNotification from './components/DiscussionRenamedNotification';
import DiscussionsSearchSource from './components/DiscussionsSearchSource';
import HeaderSecondary from './components/HeaderSecondary';
import ComposerButton from './components/ComposerButton';
import DiscussionList from './components/DiscussionList';
import ReplyPlaceholder from './components/ReplyPlaceholder';
import TextEditor from './components/TextEditor';
import TextEditorButton from './components/TextEditorButton';
import AvatarEditor from './components/AvatarEditor';
import Post from './components/Post';
import SettingsPage from './components/SettingsPage';
import TerminalPost from './components/TerminalPost';
import ChangeEmailModal from './components/ChangeEmailModal';
import NotificationsDropdown from './components/NotificationsDropdown';
import UserPage from './components/UserPage';
import PostUser from './components/PostUser';
import UserCard from './components/UserCard';
import UsersSearchSource from './components/UsersSearchSource';
import NotificationGrid from './components/NotificationGrid';
import PostPreview from './components/PostPreview';
import EventPost from './components/EventPost';
import DiscussionHero from './components/DiscussionHero';
import PostMeta from './components/PostMeta';
import EditUserModal from './components/EditUserModal';
import SearchSource from './components/SearchSource';
import DiscussionRenamedPost from './components/DiscussionRenamedPost';
import DiscussionComposer from './components/DiscussionComposer';
import LogInButtons from './components/LogInButtons';
import NotificationList from './components/NotificationList';
import WelcomeHero from './components/WelcomeHero';
import SignUpModal from './components/SignUpModal';
import CommentPost from './components/CommentPost';
import ReplyComposer from './components/ReplyComposer';
import NotificationsPage from './components/NotificationsPage';
import PostStreamScrubber from './components/PostStreamScrubber';
import EditPostComposer from './components/EditPostComposer';
import RenameDiscussionModal from './components/RenameDiscussionModal';
import Search from './components/Search';
import DiscussionListItem from './components/DiscussionListItem';
import LoadingPost from './components/LoadingPost';
import PostsUserPage from './components/PostsUserPage';
import routes from './routes';
import ForumApplication from './ForumApplication';

export default Object.assign(compat, {
  'utils/PostControls': PostControls,
  'utils/KeyboardNavigatable': KeyboardNavigatable,
  'utils/slidable': slidable,
  'utils/affixSidebar': affixSidebar,
  'utils/History': History,
  'utils/DiscussionControls': DiscussionControls,
  'utils/alertEmailConfirmation': alertEmailConfirmation,
  'utils/UserControls': UserControls,
  'utils/Pane': Pane,
  'states/DiscussionListState': DiscussionListState,
  'states/GlobalSearchState': GlobalSearchState,
  'states/NotificationListState': NotificationListState,
  'states/SearchState': SearchState,
  'components/DiscussionPage': DiscussionPage,
  'components/LogInModal': LogInModal,
  'components/ComposerBody': ComposerBody,
  'components/ForgotPasswordModal': ForgotPasswordModal,
  'components/Notification': Notification,
  'components/LogInButton': LogInButton,
  'components/DiscussionsUserPage': DiscussionsUserPage,
  'components/Composer': Composer,
  'components/SessionDropdown': SessionDropdown,
  'components/HeaderPrimary': HeaderPrimary,
  'components/PostEdited': PostEdited,
  'components/PostStream': PostStream,
  'components/ChangePasswordModal': ChangePasswordModal,
  'components/IndexPage': IndexPage,
  'components/DiscussionRenamedNotification': DiscussionRenamedNotification,
  'components/DiscussionsSearchSource': DiscussionsSearchSource,
  'components/HeaderSecondary': HeaderSecondary,
  'components/ComposerButton': ComposerButton,
  'components/DiscussionList': DiscussionList,
  'components/ReplyPlaceholder': ReplyPlaceholder,
  'components/TextEditor': TextEditor,
  'components/TextEditorButton': TextEditorButton,
  'components/AvatarEditor': AvatarEditor,
  'components/Post': Post,
  'components/SettingsPage': SettingsPage,
  'components/TerminalPost': TerminalPost,
  'components/ChangeEmailModal': ChangeEmailModal,
  'components/NotificationsDropdown': NotificationsDropdown,
  'components/UserPage': UserPage,
  'components/PostUser': PostUser,
  'components/UserCard': UserCard,
  'components/UsersSearchSource': UsersSearchSource,
  'components/NotificationGrid': NotificationGrid,
  'components/PostPreview': PostPreview,
  'components/EventPost': EventPost,
  'components/DiscussionHero': DiscussionHero,
  'components/PostMeta': PostMeta,
  'components/EditUserModal': EditUserModal,
  'components/SearchSource': SearchSource,
  'components/DiscussionRenamedPost': DiscussionRenamedPost,
  'components/DiscussionComposer': DiscussionComposer,
  'components/LogInButtons': LogInButtons,
  'components/NotificationList': NotificationList,
  'components/WelcomeHero': WelcomeHero,
  'components/SignUpModal': SignUpModal,
  'components/CommentPost': CommentPost,
  'components/ReplyComposer': ReplyComposer,
  'components/NotificationsPage': NotificationsPage,
  'components/PostStreamScrubber': PostStreamScrubber,
  'components/EditPostComposer': EditPostComposer,
  'components/RenameDiscussionModal': RenameDiscussionModal,
  'components/Search': Search,
  'components/DiscussionListItem': DiscussionListItem,
  'components/LoadingPost': LoadingPost,
  'components/PostsUserPage': PostsUserPage,
  routes: routes,
  ForumApplication: ForumApplication,
});
<|endoftext|>


<commit_before>/*global describe:false, it:false, expect:false*/
import * as full from './full';
import _ from 'lodash';

function probability(entry) {
  return entry.re * entry.re + entry.im * entry.im;
}

describe('thinSplitter', () => {
  it('should consist of 4 tensors', () => {
    expect(full.thinSplitter.length).toBe(4);
  });

  it('should consist of unitary tensors', () => {
    _.each(full.thinSplitter, (tensor) => {
      for (let entry of tensor.map.values()) {
        const probabilities = _.sum(_.map([...entry.values()], probability));
        expect(probabilities).toBeCloseTo(1, 5);
      }
    });
  });

  it('should pass a beam parallel to the element', () => {
    // 0th element represents splitter's "-" rotation,
    // so it's parallel to ">" beam direction.
    const transition = full.thinSplitter[0].map.get('>-');

    expect(transition.size).toBe(1);
    expect(transition.get('>-')).toBeDefined();
  });

  it('should pass half of the beam perpendicular to the element', () => {
    // 2nd element represents splitter's "|" rotation,
    // so it's perpendicular to ">" beam direction.
    const transition = full.thinSplitter[2].map.get('>-');

    expect(transition.size).toBe(2);
    expect(transition.get('>-')).toBeDefined();
    expect(transition.get('<-')).toBeDefined();
  });
});
<commit_msg>fix(test) thisSplitter unitary for (a)diag orientation<commit_after>/*global describe:false, it:false, expect:false*/
import * as full from './full';
import _ from 'lodash';

function probability(entry) {
  return entry.re * entry.re + entry.im * entry.im;
}

describe('thinSplitter', () => {
  it('should consist of 4 tensors', () => {
    expect(full.thinSplitter.length).toBe(4);
  });

  it('diagonal orientations should consist of unitary tensors', () => {
    _.each(_.at(full.thinSplitter, [1, 3]), (tensor) => {
      for (let entry of tensor.map.values()) {
        const probabilities = _.sum(_.map([...entry.values()], probability));
        expect(probabilities).toBeCloseTo(1, 5);
      }
    });
  });

  it('should pass half of the beam perpendicular to the element', () => {
    // 2nd element represents splitter's "|" rotation,
    // so it's perpendicular to ">" beam direction.
    const transition = full.thinSplitter[2].map.get('>-');

    expect(transition.size).toBe(2);
    expect(transition.get('>-')).toBeDefined();
    expect(transition.get('<-')).toBeDefined();
  });
});
<|endoftext|>


<commit_before>/**
 * Created by cferrier on 10/1/2016.
 */
<commit_msg>working on creating sound objects when users updated<commit_after>/**
 * Created by cferrier on 10/1/2016.
 */

// members
for (var username in members){
	if oldMembers.hasOwnProperty(username){
		// username:instrument
		if (oldMembers[username] != newMembers[username]){

		}
	}
}

// set instrument
// set frequency
// set volume

//play <|endoftext|>


<commit_before><commit_msg>Added publication of recommended anime<commit_after>Meteor.publishComposite('homePageActiveEntries', function() {
	return {
		find: function() {
			return Meteor.users.find({_id: this.userId});
		},
		children: [
			{
				find: function(user) {
					var animeIds = _.pluck(user.recommendedAnime, 'animeId');
					// Limit to 12 recommendations for now
					return Anime.find({_id: {$in: animeIds}}, {fields: requireCollectionFields.anime.requiredLibraryEntry, limit: 12});
				}
			}
		]
	};
});<|endoftext|>


<commit_before>'use strict';
var React = require('react');
var _ = require('../underscore_ext');
import Input from 'react-toolbox/lib/input';
var {rxEvents} = require('../react-utils');

var isValid = _.curry((min, max, value) => {
	var v = value.trim(),
		i = parseInt(v);
	return v === '' || !(isNaN(i) || i < min || i > max);
});

function parseValue(value, dflt) {
	var v = value.trim();
	return v === '' ? dflt : parseInt(v);
}

// initialValue is int or null.
// dflt, min, max are int.
class NumberForm extends React.Component {
	constructor(props) {
	    super(props);
	    var {initialValue} = props;
	    this.state = {value: initialValue == null ? '' : '' + initialValue, focused: false};
	}

	componentWillMount() {
		var {dflt, min, max} = this.props;
		var events = rxEvents(this, 'change');
		this.change = events.change
			.do(value => this.setState({value}))
			.debounceTime(200)
			.filter(isValid(min, max))
			.subscribe(value => this.props.onChange(parseValue(value, dflt)));
	}

	componentWillUnmount() {
		this.change.unsubscribe();
	}

	onBlur = () => {
		this.setState({focused: false});
	};

	onFocus = () => {
		this.setState({focused: true});
	};

	render() {
		var {min, max, dflt, initialValue, ...other} = this.props,
			{value, focused} = this.state;
		return (
			<form className="form-horizontal">
				<Input
					{...other}
					onBlur={this.onBlur}
					onFocus={this.onFocus}
					type='text'
					value={'' + value}
					label={`Survival time cutoff (in range [${min}, ${max}])`}
					placeholder={focused ? 'Enter a number.' : undefined}
					onChange={this.on.change}/>
			</form>
		);
	}
}

module.exports = NumberForm;
<commit_msg>survival time cutoff wording change<commit_after>'use strict';
var React = require('react');
var _ = require('../underscore_ext');
import Input from 'react-toolbox/lib/input';
var {rxEvents} = require('../react-utils');

var isValid = _.curry((min, max, value) => {
	var v = value.trim(),
		i = parseInt(v);
	return v === '' || !(isNaN(i) || i < min || i > max);
});

function parseValue(value, dflt) {
	var v = value.trim();
	return v === '' ? dflt : parseInt(v);
}

// initialValue is int or null.
// dflt, min, max are int.
class NumberForm extends React.Component {
	constructor(props) {
	    super(props);
	    var {initialValue} = props;
	    this.state = {value: initialValue == null ? '' : '' + initialValue, focused: false};
	}

	componentWillMount() {
		var {dflt, min, max} = this.props;
		var events = rxEvents(this, 'change');
		this.change = events.change
			.do(value => this.setState({value}))
			.debounceTime(200)
			.filter(isValid(min, max))
			.subscribe(value => this.props.onChange(parseValue(value, dflt)));
	}

	componentWillUnmount() {
		this.change.unsubscribe();
	}

	onBlur = () => {
		this.setState({focused: false});
	};

	onFocus = () => {
		this.setState({focused: true});
	};

	render() {
		var {min, max, dflt, initialValue, ...other} = this.props,
			{value, focused} = this.state;
		return (
			<form className="form-horizontal">
				<Input
					{...other}
					onBlur={this.onBlur}
					onFocus={this.onFocus}
					type='text'
					value={'' + value}
					label={`Custom survival time cutoff`}
					placeholder={focused ? `Enter a number between ${min} and ${max}` : undefined}
					onChange={this.on.change}/>
			</form>
		);
	}
}

module.exports = NumberForm;
<|endoftext|>