<commit_before>var QuantimodoSearchConstants = {
    sourceURL: apiHost + '/api/',
    vURL: 'public/variables/search/',
    cURL: 'public/correlations/search/',
    voteURL: 'v1/votes',
    predOfURL: apiHost + '/api/v1/variables/_VARIABLE_/public/causes',
    predByURL: apiHost + '/api/v1/variables/_VARIABLE_/public/effects',
    method: 'JSONP',
    predefinedVariable: (typeof qmwpShortCodeDefinedVariable !== 'undefined') ? qmwpShortCodeDefinedVariable : null,
    predefinedVariableAs: (typeof qmwpShortCodeDefinedVariableAs !== 'undefined') ? qmwpShortCodeDefinedVariableAs : null,
};

// Define a new module for our search page app
var quantimodoSearch = angular.module('quantimodoSearch', ['ui.bootstrap']);

// Define config
quantimodoSearch.config(function ($httpProvider) {
    if (typeof mashapeKey !== 'undefined' && mashapeKey) {
        $httpProvider.defaults.headers.common['X-Mashape-Key'] = mashapeKey;
    }

    if (typeof accessToken !== 'undefined' && accessToken) {
        $httpProvider.defaults.headers.common.Authorization = 'Bearer ' + accessToken;
    }
});

// The controller
quantimodoSearch.controller('QuantimodoSearchController', ['$scope', 'QuantimodoSearchService', '$uibModal', 'correlationsVoteHelper',
    function ($scope, QuantimodoSearchService, $uibModal, correlationsVoteHelper) {
        $scope.correlations = [];
        $scope.totalCorrelations = [];
        $scope.maxSize = 10;
        $scope.itemsPerPage = 10;
        $scope.autoLoad = false;
        $scope.homeShown = true;
        $scope.selectOutputAsType = qmwpShortCodeDefinedVariableAs;
        $scope.searchVariable = '';
        $scope.resultTitle = '';
        $scope.countAndTime = '';

        $scope.loadCurrentPageData = function () {
            $scope.correlations =
                $scope.totalCorrelations.slice(($scope.bigCurrentPage - 1) *
                    $scope.itemsPerPage, $scope.itemsPerPage * $scope.bigCurrentPage);
        };

        $scope.loadData = function () {
            $scope.bigTotalItems = $scope.totalCorrelations.length;
            $scope.bigCurrentPage = 1;
            $scope.loadCurrentPageData();
        };

        $scope.setPage = function (pageNo) {
            $scope.currentPage = pageNo;
        };

        $scope.pageChanged = function () {
            $scope.loadCurrentPageData();
        };

        $scope.hasMoreThanTen = function () {
            return $scope.totalCorrelations.length > 10;
        };

        $scope.isNotEmpty = function () {
            return $scope.totalCorrelations.length > 0;
        };

        $scope.showCorrelations = function (variable) {
            var timeToSearch = (new Date()).getTime();
            var correlationURL = '';
            $scope.homeShown = false;
            $scope.autoLoad = true;

            var queryVariable = variable.replace(/ /g, '+');

            correlationURL = QuantimodoSearchConstants.sourceURL + QuantimodoSearchConstants.cURL + variable;

            correlationURL = correlationURL.replace('_VARIABLE_', queryVariable);

            QuantimodoSearchService.getData(correlationURL, {'effectOrCause': $scope.selectOutputAsType},
                function (correlations) {
                    $scope.totalCorrelations = [];
                    if (jQuery.isArray(correlations)) {
                        jQuery.each(correlations, function (_, correlation) {
                            if ($scope.selectOutputAsType === 'effect') {
                                $scope.totalCorrelations.push({
                                    correlation: correlation.correlationCoefficient,
                                    variable: correlation.cause,
                                    category: correlation.causeCategory,
                                    explanation: correlation.correlationExplanation,
                                    originalCorrelation: correlation
                                });
                            } else {
                                $scope.totalCorrelations.push({
                                    correlation: correlation.correlationCoefficient,
                                    variable: correlation.effect,
                                    category: correlation.effectCategory,
                                    explanation: correlation.correlationExplanation,
                                    originalCorrelation: correlation
                                });
                            }
                        });
                    }
                    $scope.resultTitle = 'Strongly predicted by ' + variable;
                    if ($scope.selectOutputAsType === 'effect') {
                        $scope.resultTitle = 'Strongest predictors of ' + variable;
                    }
                    $scope.countAndTime = $scope.totalCorrelations.length +
                        ' results  (' + (((new Date()).getTime() - timeToSearch) / 1000) + ' seconds)';
                    if ($scope.totalCorrelations.length === 0) {
                        $scope.resultTitle = 'Your search for variable ' + variable + ' does not have any results';
                    }
                    $scope.loadData();
                }
            );

        };

        $scope.vote = function (correlationSet, likeValue) {
            console.log('Liked: ' + likeValue);
            console.log(correlationSet);

            var modalInstance = $uibModal.open({
                templateUrl: qmwpPluginUrl + '/templates/search-correlations/vote-confirm-modal.html',
                controller: 'voteModalInstanceController',
                resolve: {
                    confirmationOptions: function () {
                        return {
                            correlation: correlationSet.originalCorrelation,
                            likeValue: likeValue
                        }
                    }
                }
            });

            modalInstance.result.then(function () {
                //confirmed
                var prevVoted = correlationsVoteHelper.getPreviouslyVoted(correlationSet.originalCorrelation);

                if (prevVoted === likeValue) {
                    likeValue = 'null';
                }

                QuantimodoSearchService.vote(correlationSet.originalCorrelation, likeValue, function (resp) {
                    console.log(resp);

                    correlationsVoteHelper.saveVotedCorrelation(correlationSet.originalCorrelation, likeValue);

                    correlationSet.originalCorrelation.userVote = likeValue;

                })

            }, function () {
                console.debug('dismissed');
            });

        };

        $scope.addMeasurement = function (variable) {
            console.log('Going to add measurement for variable: ' + variable);
            QuantimodoSearchService.getVariableByName(variable, function (varDetails) {
                console.log(varDetails);

                var modalInstance = $uibModal.open({
                    templateUrl: qmwpPluginUrl + '/templates/search-correlations/add-measurement-modal.html',
                    controller: 'addMeasurementModalInstanceController',
                    resolve: {
                        variable: function () {
                            return varDetails;
                        }
                    }
                });

                modalInstance.result.then(function (measurement) {
                    //confirmed
                    QuantimodoSearchService.addMeasurement(
                        [{
                            measurements: [{
                                value: measurement.value,
                                timestamp: moment(new Date(measurement.date)).unix()
                            }],
                            name: measurement.variable.name,
                            source: 'QuantiModo',
                            category: measurement.variable.category,
                            combinationOperation: measurement.variable.combinationOperation,
                            unit: measurement.variable.abbreviatedUnitName
                        }],
                        function (result) {
                            console.log(result);
                        });
                }, function () {
                    console.debug('dismissed');
                });

            });
        };

        $scope.openVarSettingsModal = function (variable) {

            console.log('Going change setting for: ' + variable);
            QuantimodoSearchService.getVariableByName(variable, function (varDetails) {
                QuantimodoSearchService.getUnitsForVariableByName(varDetails.name, function (units) {

                    console.log('Variable details:' + varDetails);

                    var modalInstance = $uibModal.open({
                        templateUrl: qmwpPluginUrl + '/templates/search-correlations/variable-settings-modal.html',
                        controller: 'varSettingsModalInstanceController',
                        resolve: {
                            variable: function () {
                                return varDetails;
                            },
                            varUnits: function () {
                                return units.data;
                            }
                        }
                    });

                    modalInstance.result.then(function (variable) {
                        console.log('confirmed');
                    }, function () {
                        console.debug('dismissed');
                    });

                });
            });

        };

        if (QuantimodoSearchConstants.predefinedVariable && QuantimodoSearchConstants.predefinedVariableAs) {
            console.log('Variable: ' + QuantimodoSearchConstants.predefinedVariable);
            console.log('Variable as: ' + QuantimodoSearchConstants.predefinedVariableAs);

            $scope.selectOutputAsType = QuantimodoSearchConstants.predefinedVariableAs;
            $scope.searchVariable = QuantimodoSearchConstants.predefinedVariable;
            $scope.showCorrelations($scope.searchVariable);
        }

    }

]);

quantimodoSearch.controller('voteModalInstanceController', function ($scope, $uibModalInstance, confirmationOptions) {

    console.log(confirmationOptions);

    $scope.opts = confirmationOptions;

    $scope.ok = function () {
        $uibModalInstance.close('confirm');
    };

    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');
    };

});

quantimodoSearch.controller('addMeasurementModalInstanceController', function ($scope, $uibModalInstance, variable) {

    $scope.variable = variable;

    $scope.mgmtVal = variable.mostCommonValue;

    $scope.mgmtDate = moment().format('lll');

    $scope.ok = function () {
        $uibModalInstance.close({
            variable: variable,
            value: $scope.mgmtVal,
            date: $scope.mgmtDate
        });
    };

    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');
    };

});

quantimodoSearch.controller('varSettingsModalInstanceController',
    function ($scope, $uibModalInstance, QuantimodoSearchService, variable, varUnits) {

        $scope.varUnits = varUnits;
        $scope.variable = angular.copy(variable);
        $scope.assumeMissing = 'true';

        $scope.ok = function () {

            if ($scope.assumeMissing === 'true') {
                $scope.variable.fillingValue = null;
            }

            QuantimodoSearchService.getCurrentUserData(function (userData) {

                var variableSettings = {
                    user: userData.id,
                    variable: variable.name,
                    name: $scope.variable.name,
                    durationOfAction: $scope.variable.durationOfAction,
                    fillingValue: $scope.variable.fillingValue,
                    maximumAllowedValue: $scope.variable.maximumAllowedValue,
                    minimumAllowedValue: $scope.variable.minimumAllowedValue,
                    onsetDelay: $scope.variable.onsetDelay,
                    unit: $scope.variable.abbreviatedUnitName
                };

                QuantimodoSearchService.setVariableSettings(variableSettings, function (response) {
                    console.log(response);
                });

            });

            $uibModalInstance.close({
                variable: $scope.variable,
            });
        };

        $scope.cancel = function () {
            $uibModalInstance.dismiss('cancel');
        };

    });

// The service
quantimodoSearch.service('QuantimodoSearchService', function ($http) {

    this.getData = function (url, p, f) {
        $http.get(url, {params: p}).then(function (response) {
            f(response.data);
        });
    };

    this.vote = function (correlation, vote, callback) {
        $http.post(QuantimodoSearchConstants.sourceURL + QuantimodoSearchConstants.voteURL, {
            cause: correlation.cause,
            correlation: correlation.correlationCoefficient,
            effect: correlation.effect,
            vote: vote
        }).then(function (response) {
            callback(response.data);
        });
    };

    this.getVariableByName = function (varName, callback) {
        $http.get(QuantimodoSearchConstants.sourceURL + 'v1/variables/' + varName).then(function (response) {
            callback(response.data);
        });
    };

    this.addMeasurement = function (measurement, callback) {
        console.log('Going to post this measurement:');
        console.log(measurement);

        $http.post(QuantimodoSearchConstants.sourceURL + 'measurements/v2', measurement, function (result) {
            callback(result);
        });
    }

    this.getUnitsForVariableByName = function (variableName, callback) {
        $http.get(QuantimodoSearchConstants.sourceURL + 'v1/unitsVariable?variable=' + variableName)
            .then(function (response) {
                callback(response);
            });
    };

    this.setVariableSettings = function (variableSettings, callback) {
        $http.post(QuantimodoSearchConstants.sourceURL + 'v1/userVariables', variableSettings, function (response) {
            callback(response.data);
        });
    };

    this.getCurrentUserData = function (callback) {
        $http.get(QuantimodoSearchConstants.sourceURL + 'v1/user/me').then(function (response) {
            callback(response.data);
        })
    };

});

quantimodoSearch.service('correlationsVoteHelper', function () {

    this.getPreviouslyVoted = function (correlation) {
        var votedCorrelations = JSON.parse(localStorage.getItem('votedCorrelations'));
        if (votedCorrelations) {
            for (var i = 0; i < votedCorrelations.length; i++) {
                if (correlation.effect === votedCorrelations[i].effect) {
                    if (correlation.cause === votedCorrelations[i].cause) {
                        return votedCorrelations[i].like;
                    }
                }
            }
        }
    };

    this.saveVotedCorrelation = function (correlation, vote) {

        var votedCorrelations = JSON.parse(localStorage.getItem('votedCorrelations'));

        var correlationToSave = {
            cause: correlation.cause,
            effect: correlation.effect,
            like: vote
        };

        if (votedCorrelations) {
            var found = false;
            for (var i = 0; i < votedCorrelations.length; i++) {
                if (correlation.effect === votedCorrelations[i].effect) {
                    if (correlation.cause === votedCorrelations[i].cause) {
                        votedCorrelations[i] = correlationToSave;
                        found = true;
                        break;
                    }
                }
            }
            if (!found) {
                votedCorrelations.push(correlationToSave);
            }
        } else {
            votedCorrelations = [];
            votedCorrelations.push(correlationToSave);
        }

        localStorage.setItem('votedCorrelations', JSON.stringify(votedCorrelations));

    };

});

// The autocomplete directive
quantimodoSearch.directive('autoComplete', ['QuantimodoSearchService',
    function (QuantimodoSearchService) {
        return {
            link: function (scope, element) {

                // init jqueryUi autocomplete
                element.autocomplete({
                    source: function (request, response) {
                        var searchURL = QuantimodoSearchConstants.sourceURL +
                            QuantimodoSearchConstants.vURL + request.term;
                        QuantimodoSearchService.getData(searchURL, {},
                            function (variables) {
                                response(jQuery.map(variables,
                                    function (item) {
                                        return {
                                            label: item.name,
                                            value: item.name
                                        };
                                    }
                                ));
                            }
                        );
                    },
                    select: function (event, ui) {
                        scope.searchVariable = ui.item.value;
                        if (scope.autoLoad) {
                            scope.showCorrelations(ui.item.value);
                        }
                    },
                    focus: function (event, ui) {
                        scope.searchVariable = ui.item.value;
                        if (scope.autoLoad) {
                            scope.showCorrelations(ui.item.value);
                        }
                    }
                });
            }
        };
    }]);

quantimodoSearch.directive('dateTimePicker', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModelCtrl) {
            jQuery(function () {
                element.datetimepicker({
                    dayOfWeekStart: 1,
                    lang: 'en',
                    startDate: '1986/01/05',
                    format: 'M j, Y h:i A',
                    step: 10,
                    onChangeDateTime: function (date) {
                        ngModelCtrl.$setViewValue(moment(date).format('lll'));
                        scope.$apply();
                    }
                });
            });
        }
    };
});

<commit_msg>variable model is wrapped as array<commit_after>var QuantimodoSearchConstants = {
    sourceURL: apiHost + '/api/',
    vURL: 'public/variables/search/',
    cURL: 'public/correlations/search/',
    voteURL: 'v1/votes',
    predOfURL: apiHost + '/api/v1/variables/_VARIABLE_/public/causes',
    predByURL: apiHost + '/api/v1/variables/_VARIABLE_/public/effects',
    method: 'JSONP',
    predefinedVariable: (typeof qmwpShortCodeDefinedVariable !== 'undefined') ? qmwpShortCodeDefinedVariable : null,
    predefinedVariableAs: (typeof qmwpShortCodeDefinedVariableAs !== 'undefined') ? qmwpShortCodeDefinedVariableAs : null,
};

// Define a new module for our search page app
var quantimodoSearch = angular.module('quantimodoSearch', ['ui.bootstrap']);

// Define config
quantimodoSearch.config(function ($httpProvider) {
    if (typeof mashapeKey !== 'undefined' && mashapeKey) {
        $httpProvider.defaults.headers.common['X-Mashape-Key'] = mashapeKey;
    }

    if (typeof accessToken !== 'undefined' && accessToken) {
        $httpProvider.defaults.headers.common.Authorization = 'Bearer ' + accessToken;
    }
});

// The controller
quantimodoSearch.controller('QuantimodoSearchController', ['$scope', 'QuantimodoSearchService', '$uibModal', 'correlationsVoteHelper',
    function ($scope, QuantimodoSearchService, $uibModal, correlationsVoteHelper) {
        $scope.correlations = [];
        $scope.totalCorrelations = [];
        $scope.maxSize = 10;
        $scope.itemsPerPage = 10;
        $scope.autoLoad = false;
        $scope.homeShown = true;
        $scope.selectOutputAsType = qmwpShortCodeDefinedVariableAs;
        $scope.searchVariable = '';
        $scope.resultTitle = '';
        $scope.countAndTime = '';

        $scope.loadCurrentPageData = function () {
            $scope.correlations =
                $scope.totalCorrelations.slice(($scope.bigCurrentPage - 1) *
                    $scope.itemsPerPage, $scope.itemsPerPage * $scope.bigCurrentPage);
        };

        $scope.loadData = function () {
            $scope.bigTotalItems = $scope.totalCorrelations.length;
            $scope.bigCurrentPage = 1;
            $scope.loadCurrentPageData();
        };

        $scope.setPage = function (pageNo) {
            $scope.currentPage = pageNo;
        };

        $scope.pageChanged = function () {
            $scope.loadCurrentPageData();
        };

        $scope.hasMoreThanTen = function () {
            return $scope.totalCorrelations.length > 10;
        };

        $scope.isNotEmpty = function () {
            return $scope.totalCorrelations.length > 0;
        };

        $scope.showCorrelations = function (variable) {
            var timeToSearch = (new Date()).getTime();
            var correlationURL = '';
            $scope.homeShown = false;
            $scope.autoLoad = true;

            var queryVariable = variable.replace(/ /g, '+');

            correlationURL = QuantimodoSearchConstants.sourceURL + QuantimodoSearchConstants.cURL + variable;

            correlationURL = correlationURL.replace('_VARIABLE_', queryVariable);

            QuantimodoSearchService.getData(correlationURL, {'effectOrCause': $scope.selectOutputAsType},
                function (correlations) {
                    $scope.totalCorrelations = [];
                    if (jQuery.isArray(correlations)) {
                        jQuery.each(correlations, function (_, correlation) {
                            if ($scope.selectOutputAsType === 'effect') {
                                $scope.totalCorrelations.push({
                                    correlation: correlation.correlationCoefficient,
                                    variable: correlation.cause,
                                    category: correlation.causeCategory,
                                    explanation: correlation.correlationExplanation,
                                    originalCorrelation: correlation
                                });
                            } else {
                                $scope.totalCorrelations.push({
                                    correlation: correlation.correlationCoefficient,
                                    variable: correlation.effect,
                                    category: correlation.effectCategory,
                                    explanation: correlation.correlationExplanation,
                                    originalCorrelation: correlation
                                });
                            }
                        });
                    }
                    $scope.resultTitle = 'Strongly predicted by ' + variable;
                    if ($scope.selectOutputAsType === 'effect') {
                        $scope.resultTitle = 'Strongest predictors of ' + variable;
                    }
                    $scope.countAndTime = $scope.totalCorrelations.length +
                        ' results  (' + (((new Date()).getTime() - timeToSearch) / 1000) + ' seconds)';
                    if ($scope.totalCorrelations.length === 0) {
                        $scope.resultTitle = 'Your search for variable ' + variable + ' does not have any results';
                    }
                    $scope.loadData();
                }
            );

        };

        $scope.vote = function (correlationSet, likeValue) {
            console.log('Liked: ' + likeValue);
            console.log(correlationSet);

            var modalInstance = $uibModal.open({
                templateUrl: qmwpPluginUrl + '/templates/search-correlations/vote-confirm-modal.html',
                controller: 'voteModalInstanceController',
                resolve: {
                    confirmationOptions: function () {
                        return {
                            correlation: correlationSet.originalCorrelation,
                            likeValue: likeValue
                        }
                    }
                }
            });

            modalInstance.result.then(function () {
                //confirmed
                var prevVoted = correlationsVoteHelper.getPreviouslyVoted(correlationSet.originalCorrelation);

                if (prevVoted === likeValue) {
                    likeValue = 'null';
                }

                QuantimodoSearchService.vote(correlationSet.originalCorrelation, likeValue, function (resp) {
                    console.log(resp);

                    correlationsVoteHelper.saveVotedCorrelation(correlationSet.originalCorrelation, likeValue);

                    correlationSet.originalCorrelation.userVote = likeValue;

                })

            }, function () {
                console.debug('dismissed');
            });

        };

        $scope.addMeasurement = function (variable) {
            console.log('Going to add measurement for variable: ' + variable);
            QuantimodoSearchService.getVariableByName(variable, function (varDetails) {
                console.log(varDetails);

                var modalInstance = $uibModal.open({
                    templateUrl: qmwpPluginUrl + '/templates/search-correlations/add-measurement-modal.html',
                    controller: 'addMeasurementModalInstanceController',
                    resolve: {
                        variable: function () {
                            return varDetails;
                        }
                    }
                });

                modalInstance.result.then(function (measurement) {
                    //confirmed
                    QuantimodoSearchService.addMeasurement(
                        [{
                            measurements: [{
                                value: measurement.value,
                                timestamp: moment(new Date(measurement.date)).unix()
                            }],
                            name: measurement.variable.name,
                            source: 'QuantiModo',
                            category: measurement.variable.category,
                            combinationOperation: measurement.variable.combinationOperation,
                            unit: measurement.variable.abbreviatedUnitName
                        }],
                        function (result) {
                            console.log(result);
                        });
                }, function () {
                    console.debug('dismissed');
                });

            });
        };

        $scope.openVarSettingsModal = function (variable) {

            console.log('Going change setting for: ' + variable);
            QuantimodoSearchService.getVariableByName(variable, function (varDetails) {
                QuantimodoSearchService.getUnitsForVariableByName(varDetails.name, function (units) {

                    console.log('Variable details:' + varDetails);

                    var modalInstance = $uibModal.open({
                        templateUrl: qmwpPluginUrl + '/templates/search-correlations/variable-settings-modal.html',
                        controller: 'varSettingsModalInstanceController',
                        resolve: {
                            variable: function () {
                                return varDetails;
                            },
                            varUnits: function () {
                                return units.data;
                            }
                        }
                    });

                    modalInstance.result.then(function (variable) {
                        console.log('confirmed');
                    }, function () {
                        console.debug('dismissed');
                    });

                });
            });

        };

        if (QuantimodoSearchConstants.predefinedVariable && QuantimodoSearchConstants.predefinedVariableAs) {
            console.log('Variable: ' + QuantimodoSearchConstants.predefinedVariable);
            console.log('Variable as: ' + QuantimodoSearchConstants.predefinedVariableAs);

            $scope.selectOutputAsType = QuantimodoSearchConstants.predefinedVariableAs;
            $scope.searchVariable = QuantimodoSearchConstants.predefinedVariable;
            $scope.showCorrelations($scope.searchVariable);
        }

    }

]);

quantimodoSearch.controller('voteModalInstanceController', function ($scope, $uibModalInstance, confirmationOptions) {

    console.log(confirmationOptions);

    $scope.opts = confirmationOptions;

    $scope.ok = function () {
        $uibModalInstance.close('confirm');
    };

    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');
    };

});

quantimodoSearch.controller('addMeasurementModalInstanceController', function ($scope, $uibModalInstance, variable) {

    $scope.variable = variable;

    $scope.mgmtVal = variable.mostCommonValue;

    $scope.mgmtDate = moment().format('lll');

    $scope.ok = function () {
        $uibModalInstance.close({
            variable: variable,
            value: $scope.mgmtVal,
            date: $scope.mgmtDate
        });
    };

    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');
    };

});

quantimodoSearch.controller('varSettingsModalInstanceController',
    function ($scope, $uibModalInstance, QuantimodoSearchService, variable, varUnits) {

        $scope.varUnits = varUnits;
        $scope.variable = angular.copy(variable);
        $scope.assumeMissing = 'true';

        $scope.ok = function () {

            if ($scope.assumeMissing === 'true') {
                $scope.variable.fillingValue = null;
            }

            QuantimodoSearchService.getCurrentUserData(function (userData) {

                var variableSettings = [{
                    user: userData.id,
                    variable: variable.name,
                    name: $scope.variable.name,
                    durationOfAction: $scope.variable.durationOfAction,
                    fillingValue: $scope.variable.fillingValue,
                    maximumAllowedValue: $scope.variable.maximumAllowedValue,
                    minimumAllowedValue: $scope.variable.minimumAllowedValue,
                    onsetDelay: $scope.variable.onsetDelay,
                    unit: $scope.variable.abbreviatedUnitName
                }];

                QuantimodoSearchService.setVariableSettings(variableSettings, function (response) {
                    console.log(response);
                });

            });

            $uibModalInstance.close({
                variable: $scope.variable,
            });
        };

        $scope.cancel = function () {
            $uibModalInstance.dismiss('cancel');
        };

    });

// The service
quantimodoSearch.service('QuantimodoSearchService', function ($http) {

    this.getData = function (url, p, f) {
        $http.get(url, {params: p}).then(function (response) {
            f(response.data);
        });
    };

    this.vote = function (correlation, vote, callback) {
        $http.post(QuantimodoSearchConstants.sourceURL + QuantimodoSearchConstants.voteURL, {
            cause: correlation.cause,
            correlation: correlation.correlationCoefficient,
            effect: correlation.effect,
            vote: vote
        }).then(function (response) {
            callback(response.data);
        });
    };

    this.getVariableByName = function (varName, callback) {
        $http.get(QuantimodoSearchConstants.sourceURL + 'v1/variables/' + varName).then(function (response) {
            callback(response.data);
        });
    };

    this.addMeasurement = function (measurement, callback) {
        console.log('Going to post this measurement:');
        console.log(measurement);

        $http.post(QuantimodoSearchConstants.sourceURL + 'measurements/v2', measurement, function (result) {
            callback(result);
        });
    }

    this.getUnitsForVariableByName = function (variableName, callback) {
        $http.get(QuantimodoSearchConstants.sourceURL + 'v1/unitsVariable?variable=' + variableName)
            .then(function (response) {
                callback(response);
            });
    };

    this.setVariableSettings = function (variableSettings, callback) {
        $http.post(QuantimodoSearchConstants.sourceURL + 'v1/userVariables', variableSettings, function (response) {
            callback(response.data);
        });
    };

    this.getCurrentUserData = function (callback) {
        $http.get(QuantimodoSearchConstants.sourceURL + 'v1/user/me').then(function (response) {
            callback(response.data);
        })
    };

});

quantimodoSearch.service('correlationsVoteHelper', function () {

    this.getPreviouslyVoted = function (correlation) {
        var votedCorrelations = JSON.parse(localStorage.getItem('votedCorrelations'));
        if (votedCorrelations) {
            for (var i = 0; i < votedCorrelations.length; i++) {
                if (correlation.effect === votedCorrelations[i].effect) {
                    if (correlation.cause === votedCorrelations[i].cause) {
                        return votedCorrelations[i].like;
                    }
                }
            }
        }
    };

    this.saveVotedCorrelation = function (correlation, vote) {

        var votedCorrelations = JSON.parse(localStorage.getItem('votedCorrelations'));

        var correlationToSave = {
            cause: correlation.cause,
            effect: correlation.effect,
            like: vote
        };

        if (votedCorrelations) {
            var found = false;
            for (var i = 0; i < votedCorrelations.length; i++) {
                if (correlation.effect === votedCorrelations[i].effect) {
                    if (correlation.cause === votedCorrelations[i].cause) {
                        votedCorrelations[i] = correlationToSave;
                        found = true;
                        break;
                    }
                }
            }
            if (!found) {
                votedCorrelations.push(correlationToSave);
            }
        } else {
            votedCorrelations = [];
            votedCorrelations.push(correlationToSave);
        }

        localStorage.setItem('votedCorrelations', JSON.stringify(votedCorrelations));

    };

});

// The autocomplete directive
quantimodoSearch.directive('autoComplete', ['QuantimodoSearchService',
    function (QuantimodoSearchService) {
        return {
            link: function (scope, element) {

                // init jqueryUi autocomplete
                element.autocomplete({
                    source: function (request, response) {
                        var searchURL = QuantimodoSearchConstants.sourceURL +
                            QuantimodoSearchConstants.vURL + request.term;
                        QuantimodoSearchService.getData(searchURL, {},
                            function (variables) {
                                response(jQuery.map(variables,
                                    function (item) {
                                        return {
                                            label: item.name,
                                            value: item.name
                                        };
                                    }
                                ));
                            }
                        );
                    },
                    select: function (event, ui) {
                        scope.searchVariable = ui.item.value;
                        if (scope.autoLoad) {
                            scope.showCorrelations(ui.item.value);
                        }
                    },
                    focus: function (event, ui) {
                        scope.searchVariable = ui.item.value;
                        if (scope.autoLoad) {
                            scope.showCorrelations(ui.item.value);
                        }
                    }
                });
            }
        };
    }]);

quantimodoSearch.directive('dateTimePicker', function () {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function (scope, element, attrs, ngModelCtrl) {
            jQuery(function () {
                element.datetimepicker({
                    dayOfWeekStart: 1,
                    lang: 'en',
                    startDate: '1986/01/05',
                    format: 'M j, Y h:i A',
                    step: 10,
                    onChangeDateTime: function (date) {
                        ngModelCtrl.$setViewValue(moment(date).format('lll'));
                        scope.$apply();
                    }
                });
            });
        }
    };
});

<|endoftext|>


<commit_before>'use strict';

// loadingScreen.js: display a loading screen until communication with Siad has been established.
// if an available daemon is not running on the host,
// launch an instance of siad using config.js.

const remote = require('electron').remote;
const IPCRenderer = require('electron').ipcRenderer;
const Siad = require('sia.js');
const config = IPCRenderer.sendSync('config', 'siad');
Siad.configure(config);

const overlay = document.getElementsByClassName('overlay')[0];
const overlayText = overlay.getElementsByClassName('centered')[0].getElementsByTagName('p')[0];
overlayText.textContent = 'Loading Sia...';

const showError = function(error) {
	overlayText.textContent = 'A Sia-UI error has occured: ' + error;
};

// startUI starts a Sia UI instance using the given welcome message.
// calls initUI() after displaying a welcome message.
const startUI = function(welcomemsg, initUI) {
	// Display a welcome message, then initialize the ui
	overlayText.innerHTML = welcomemsg;
	initUI();
	overlay.style.display = 'none';
};

// startSiad configures and starts a Siad instance.
// callback is called on successful start.
const startSiad = function(callback) {
	Siad.configure(config, function(error) {
		if (error) {
			console.error(error);
			overlay.showError(error);
		} else {
			Siad.start(callback);
		}
	});
};

// Check if Siad is already running on this host.
// If it is, start the UI and display a welcome message to the user.
// Otherwise, start a new instance of Siad using config.js.
module.exports = function(initUI) {
	Siad.ifRunning(function() {
		config.detached = true;
		IPCRenderer.sendSync('config', 'siad', config);
		Siad.configure(config);
		startUI('Welcome back', initUI);
	}, function() {
		config.detached = false;
		IPCRenderer.sendSync('config', 'siad', config);
		startSiad(function(error) {
			if (error) {
				console.error(error);
			} else {
				startUI('Welcome to Sia', initUI);
			}
		});
	});
};
<commit_msg>arrow functions<commit_after>'use strict';

// loadingScreen.js: display a loading screen until communication with Siad has been established.
// if an available daemon is not running on the host,
// launch an instance of siad using config.js.

const remote = require('electron').remote;
const IPCRenderer = require('electron').ipcRenderer;
const Siad = require('sia.js');
const config = IPCRenderer.sendSync('config', 'siad');
Siad.configure(config);

const overlay = document.getElementsByClassName('overlay')[0];
const overlayText = overlay.getElementsByClassName('centered')[0].getElementsByTagName('p')[0];
overlayText.textContent = 'Loading Sia...';

const showError = (error) => {
	overlayText.textContent = 'A Sia-UI error has occured: ' + error;
};

// startUI starts a Sia UI instance using the given welcome message.
// calls initUI() after displaying a welcome message.
const startUI = (welcomemsg, initUI) => {
	// Display a welcome message, then initialize the ui
	overlayText.innerHTML = welcomemsg;
	initUI();
	overlay.style.display = 'none';
};

// startSiad configures and starts a Siad instance.
// callback is called on successful start.
const startSiad = (callback) => {
	Siad.configure(config, (error) => {
		if (error) {
			console.error(error);
			overlay.showError(error);
		} else {
			Siad.start(callback);
		}
	});
};

// Check if Siad is already running on this host.
// If it is, start the UI and display a welcome message to the user.
// Otherwise, start a new instance of Siad using config.js.
module.exports = function(initUI) {
	Siad.ifRunning(() => {
		config.detached = true;
		IPCRenderer.sendSync('config', 'siad', config);
		Siad.configure(config);
		startUI('Welcome back', initUI);
	}, () => {
		config.detached = false;
		IPCRenderer.sendSync('config', 'siad', config);
		startSiad((error) => {
			if (error) {
				console.error(error);
			} else {
				startUI('Welcome to Sia', initUI);
			}
		});
	});
};
<|endoftext|>


<commit_before>// Copyright 2002-2013, University of Colorado Boulder

/**
 * String plugin, loads a string using a syntax like:
 * var title = require( 'string!JOHN_TRAVOLTAGE/johnTravoltage.name' );
 *
 * This file conforms to the RequireJS plugin API which is described here: http://requirejs.org/docs/plugins.html#api
 *
 * The reasons we need our own string plugin:
 * So we can only include the (possibly) strings that are needed for a sim
 * So we can enumerate all of the used strings, for purposed of a translation utility
 * For uniformity with image and audio plugin
 *
 * The plugin code itself is excluded from the build by declaring it as a stubModule
 *
 * @author Sam Reid
 */
define( function( require ) {
  'use strict';

  // modules
  var _ = require( '../../sherpa/lib/lodash-2.4.1.min' ); // 3rd party dependencies, path relative to config.js
  var localeInfo = require( '../../chipper/js/data/localeInfo' ); // for running in browsers
  var text = require( 'text' );
  var ChipperConstants = require( '../../chipper/js/common/ChipperConstants' );
  var ChipperStringUtils = require( '../../chipper/js/common/ChipperStringUtils' );

  var parse = JSON.parse;

  // Cache the loaded strings so they only have to be read once through file.read (for performance)
  var cache = {};

  // If doubleStrings is specified, concatenate each string with itself as a primitive i18n test
  var stringTest = ( typeof window !== 'undefined' && window.phet.chipper.getQueryParameter( 'stringTest' ) ) ?
                   window.phet.chipper.getQueryParameter( 'stringTest' ) :
                   null;

  /**
   * When running in requirejs mode, check to see if we have already loaded the specified file
   * Also parses it so that only happens once per file (instead of once per string key)
   * @param {string} url path for the string
   * @param {function} callback callback when the check succeeds
   * @param {function} errback callback for when an error occurred
   * @param {???} headers
   */
  function getWithCache( url, callback, errback, headers ) {

    // Check for cache hit
    if ( cache[ url ] ) {
      callback( cache[ url ] );
    }
    else {
      // Cache miss: load the file parse, enter into cache and return it
      text.get( url, function( loadedText ) {
        cache[ url ] = parse( loadedText );
        callback( cache[ url ] );
      }, errback, headers );
    }
  }

  return {

    /**
     * load is a function, and it will be called with the following arguments
     * Documentation taken from http://requirejs.org/docs/plugins.html#apiload
     * @param {string} name - The name of the resource to load. This is the part after the ! separator in the name. So,
     *        if a module asks for 'foo!something/for/foo', the foo module's load function will receive
     *        'something/for/foo' as the name.
     * @param {function} parentRequire - A local "require" function to use to load other modules. This require function
     *        has some utilities on it:
     *          parentRequire.toUrl(moduleResource): where moduleResource is a module name plus an extension. For
     *            instance "view/templates/main.html". It will return a full path to the resource, obeying any RequireJS
     *            configuration.
     *          parentRequire.defined(moduleName): Returns true if the module has already been loaded and defined.
     *            Used to be called require.isDefined before RequireJS 0.25.0.
     *          parentRequire.specified(moduleName): Returns true if the module has already been requested or is in the
     *            process of loading and should be available at some point.
     * @param {function} onload - A function to call with the value for name. This tells the loader that the plugin is
     *        done loading the resource. onload.error() can be called, passing an error object to it, if the plugin
     *        detects an error condition that means the resource will fail to load correctly.
     * @param {Object} config - A configuration object. This is a way for the optimizer and the web app to pass
     *        configuration information to the plugin. The i18n! plugin uses this to get the current current locale, if
     *        the web app wants to force a specific locale. The optimizer will set an isBuild property in the config to
     *        true if this plugin (or pluginBuilder) is being called as part of an optimizer build.
     */
    load: function( name, parentRequire, onload, config ) {

      // Extract the key. Eg for 'JOHN_TRAVOLTAGE/johnTravoltage.name', the key is 'johnTravoltage.name'.
      var key = name.substring( name.lastIndexOf( '/' ) + 1 );

      // Apply the cache buster args (but only during requirejs mode)
      var suffix = config.isBuild ? '' : '?' + config.urlArgs;

      var requirejsNamespace = name.substring( 0, name.indexOf( '/' ) ); // e.g. 'SOME_SIM'
      var requirePath, repositoryPath, repositoryName, locale;

      function getFilenameForLocale( locale ) {
        return repositoryName + '-strings_' + locale + '.json' + suffix;
      }

      // This code block handles the in-browser requirejs version (not the compilation step)
      if ( config.isBuild ) {

        // This code block handles the compilation step (not the in-browser requirejs mode).

        // extract information about the repository name, prefix, and path that will be recorded for later in the build
        requirejsNamespace = name.substring( 0, name.indexOf( '/' ) ); // e.g. 'SOME_SIM'
        requirePath = parentRequire.toUrl( requirejsNamespace ); // e.g. '/Users/something/phet/git/some-sim/js'
        if ( requirePath.substring( requirePath.lastIndexOf( '/' ) ) !== '/js' ) {
          onload.error( new Error( 'requirejs namespace REPO must resolve to repo/js' ) );
        }
        repositoryPath = requirePath.substring( 0, requirePath.lastIndexOf( '/' ) ); // e.g. '/Users/something/phet/git/some-sim'
        repositoryName = repositoryPath.substring( repositoryPath.lastIndexOf( '/' ) + 1 ); // e.g. 'some-sim'

        // lazily construct our strings list
        global.phet.chipper.strings = global.phet.chipper.strings || {};

        // entry saved for later in the build
        global.phet.chipper.strings[ name ] = {
          name: name, // 'SOME_SIM/string.name'
          requirejsNamespace: requirejsNamespace, // 'SOME_SIM'
          requirePath: requirePath, // '/Users/something/phet/git/some-sim/js'
          repositoryPath: repositoryPath, // '/Users/something/phet/git/some-sim'
          repositoryName: repositoryName // 'some-sim'
        };

        // tell require.js we're done processing
        onload( null );
      }
      else {
        requirePath = parentRequire.toUrl( requirejsNamespace );
        if ( requirePath.indexOf( '?' ) >= 0 ) {
          requirePath = requirePath.substring( 0, requirePath.indexOf( '?' ) );
        }
        repositoryPath = requirePath + '/..';
        repositoryName = requirejsNamespace.toLowerCase().split( '_' ).join( '-' );

        // strings may be specified via the 'strings' query parameter, value is expected to be encoded to avoid URI-reserved characters
        var queryParameterStrings = parse( decodeURIComponent( phet.chipper.getQueryParameter( 'strings' ) || '{}' ) );

        // Read the locale from a query parameter, if it is there, or use the fallback locale
        locale = phet.chipper.getQueryParameter( 'locale' ) || ChipperConstants.FALLBACK_LOCALE;
        if ( !localeInfo[ locale ] ) {
          onload.error( new Error( 'unsupported locale: ' + locale ) );
        }
        var isRTL = localeInfo[ locale ].direction === 'rtl';

        var fallbackSpecificPath = repositoryPath + '/' + getFilenameForLocale( ChipperConstants.FALLBACK_LOCALE );
        var localeSpecificPath = ( locale === ChipperConstants.FALLBACK_LOCALE ) ?
                                 fallbackSpecificPath :
                                 repositoryPath + '/../babel/' + repositoryName + '/' + getFilenameForLocale( locale );

        // In the browser, a string specified via the 'strings' query parameter overrides anything,
        // to match the behavior of the chipper version (for dynamically substituting new strings like in the translation utility)
        var queryParameterStringValue = queryParameterStrings[ name ];
        if ( queryParameterStringValue ) {
          onload( queryParameterStringValue );
        }
        else {

          // Load & parse just once per file, getting the fallback strings first.
          getWithCache( fallbackSpecificPath, function( parsedFallbackStrings ) {
              if ( parsedFallbackStrings[ key ] === undefined ) {
                throw new Error( 'Missing string: ' + key + ' in ' + fallbackSpecificPath );
              }
              var fallback = parsedFallbackStrings[ key ].value;

              // Now get the primary strings.
              getWithCache( localeSpecificPath, function( parsed ) {
                  for ( var stringKey in parsed ) {
                    parsed[ stringKey ].value = ChipperStringUtils.addDirectionalFormatting( parsed[ stringKey ].value, isRTL );
                  }

                  // Combine the primary and fallback strings into one object hash.
                  var parsedStrings = _.extend( parsedFallbackStrings, parsed );
                  if ( parsedStrings[ key ] !== undefined ) {
                    onload( window.phet.chipper.mapString( parsedStrings[ key ].value, stringTest ) );
                  }
                  else {
                    throw new Error( 'no entry for string key: ' + key );
                  }
                },
                // Error callback in the text! plugin.  Couldn't load the strings for the specified language, so use a fallback
                function() {

                  if ( !parsedFallbackStrings[ key ] ) {
                    // It would be really strange for there to be no fallback for a certain string, that means it exists in the translation but not the original English
                    throw new Error( 'no fallback for string key:' + key );
                  }
                  // Running in the browser (dynamic requirejs mode) and couldn't find the string file.  Use the fallbacks.
                  console.log( "no string file for " + localeSpecificPath );
                  onload( fallback );
                },
                { accept: 'application/json' }
              );
            },
            onload.error,
            { accept: 'application/json' }
          );
        }
      }
    },

    /**
     * Write code that will look up the string in the compiled sim, used in the compilation step.  write is only used
     * by the optimizer, and it only needs to be implemented if the plugin can output something that would belong in an
     * optimized layer.
     *
     * Documentation taken from http://requirejs.org/docs/plugins.html#apiwrite
     *
     * It is called with the following arguments:
     * @param {string} pluginName - The normalized name for the plugin. Most plugins will not be authored with a name
     *          (they will be anonymous plugins) so it is useful to know the normalized name for the plugin module for use
     *          in the optimized file.
     * @param {string} moduleName - The normalized resource name.
     * @param {function} write - A function to be called with a string of output to write to the optimized file. This
     *          function also contains a property function, write.asModule(moduleName, text). asModule can be used to
     *          write out a module that may have an anonymous define call in there that needs name insertion or/and
     *          contains implicit require("") dependencies that need to be pulled out for the optimized file. asModule
     *          is useful for text transform plugins, like a CoffeeScript plugin.
     */
    write: function( pluginName, moduleName, write ) {
      write( 'define("' + pluginName + '!' + moduleName + '",function(){return window.phet.chipper.strings.get(\"' + moduleName + '\");});\n' );
    }
  };
} );
<commit_msg>fix bogus doc about stringTest query param in string.js<commit_after>// Copyright 2002-2013, University of Colorado Boulder

/**
 * String plugin, loads a string using a syntax like:
 * var title = require( 'string!JOHN_TRAVOLTAGE/johnTravoltage.name' );
 *
 * This file conforms to the RequireJS plugin API which is described here: http://requirejs.org/docs/plugins.html#api
 *
 * The reasons we need our own string plugin:
 * So we can only include the (possibly) strings that are needed for a sim
 * So we can enumerate all of the used strings, for purposed of a translation utility
 * For uniformity with image and audio plugin
 *
 * The plugin code itself is excluded from the build by declaring it as a stubModule
 *
 * @author Sam Reid
 */
define( function( require ) {
  'use strict';

  // modules
  var _ = require( '../../sherpa/lib/lodash-2.4.1.min' ); // 3rd party dependencies, path relative to config.js
  var localeInfo = require( '../../chipper/js/data/localeInfo' ); // for running in browsers
  var text = require( 'text' );
  var ChipperConstants = require( '../../chipper/js/common/ChipperConstants' );
  var ChipperStringUtils = require( '../../chipper/js/common/ChipperStringUtils' );

  var parse = JSON.parse;

  // Cache the loaded strings so they only have to be read once through file.read (for performance)
  var cache = {};

  // See documentation of stringTest query parameter in initialize-globals.js
  var stringTest = ( typeof window !== 'undefined' && window.phet.chipper.getQueryParameter( 'stringTest' ) ) ?
                   window.phet.chipper.getQueryParameter( 'stringTest' ) :
                   null;

  /**
   * When running in requirejs mode, check to see if we have already loaded the specified file
   * Also parses it so that only happens once per file (instead of once per string key)
   * @param {string} url path for the string
   * @param {function} callback callback when the check succeeds
   * @param {function} errback callback for when an error occurred
   * @param {???} headers
   */
  function getWithCache( url, callback, errback, headers ) {

    // Check for cache hit
    if ( cache[ url ] ) {
      callback( cache[ url ] );
    }
    else {
      // Cache miss: load the file parse, enter into cache and return it
      text.get( url, function( loadedText ) {
        cache[ url ] = parse( loadedText );
        callback( cache[ url ] );
      }, errback, headers );
    }
  }

  return {

    /**
     * load is a function, and it will be called with the following arguments
     * Documentation taken from http://requirejs.org/docs/plugins.html#apiload
     * @param {string} name - The name of the resource to load. This is the part after the ! separator in the name. So,
     *        if a module asks for 'foo!something/for/foo', the foo module's load function will receive
     *        'something/for/foo' as the name.
     * @param {function} parentRequire - A local "require" function to use to load other modules. This require function
     *        has some utilities on it:
     *          parentRequire.toUrl(moduleResource): where moduleResource is a module name plus an extension. For
     *            instance "view/templates/main.html". It will return a full path to the resource, obeying any RequireJS
     *            configuration.
     *          parentRequire.defined(moduleName): Returns true if the module has already been loaded and defined.
     *            Used to be called require.isDefined before RequireJS 0.25.0.
     *          parentRequire.specified(moduleName): Returns true if the module has already been requested or is in the
     *            process of loading and should be available at some point.
     * @param {function} onload - A function to call with the value for name. This tells the loader that the plugin is
     *        done loading the resource. onload.error() can be called, passing an error object to it, if the plugin
     *        detects an error condition that means the resource will fail to load correctly.
     * @param {Object} config - A configuration object. This is a way for the optimizer and the web app to pass
     *        configuration information to the plugin. The i18n! plugin uses this to get the current current locale, if
     *        the web app wants to force a specific locale. The optimizer will set an isBuild property in the config to
     *        true if this plugin (or pluginBuilder) is being called as part of an optimizer build.
     */
    load: function( name, parentRequire, onload, config ) {

      // Extract the key. Eg for 'JOHN_TRAVOLTAGE/johnTravoltage.name', the key is 'johnTravoltage.name'.
      var key = name.substring( name.lastIndexOf( '/' ) + 1 );

      // Apply the cache buster args (but only during requirejs mode)
      var suffix = config.isBuild ? '' : '?' + config.urlArgs;

      var requirejsNamespace = name.substring( 0, name.indexOf( '/' ) ); // e.g. 'SOME_SIM'
      var requirePath, repositoryPath, repositoryName, locale;

      function getFilenameForLocale( locale ) {
        return repositoryName + '-strings_' + locale + '.json' + suffix;
      }

      // This code block handles the in-browser requirejs version (not the compilation step)
      if ( config.isBuild ) {

        // This code block handles the compilation step (not the in-browser requirejs mode).

        // extract information about the repository name, prefix, and path that will be recorded for later in the build
        requirejsNamespace = name.substring( 0, name.indexOf( '/' ) ); // e.g. 'SOME_SIM'
        requirePath = parentRequire.toUrl( requirejsNamespace ); // e.g. '/Users/something/phet/git/some-sim/js'
        if ( requirePath.substring( requirePath.lastIndexOf( '/' ) ) !== '/js' ) {
          onload.error( new Error( 'requirejs namespace REPO must resolve to repo/js' ) );
        }
        repositoryPath = requirePath.substring( 0, requirePath.lastIndexOf( '/' ) ); // e.g. '/Users/something/phet/git/some-sim'
        repositoryName = repositoryPath.substring( repositoryPath.lastIndexOf( '/' ) + 1 ); // e.g. 'some-sim'

        // lazily construct our strings list
        global.phet.chipper.strings = global.phet.chipper.strings || {};

        // entry saved for later in the build
        global.phet.chipper.strings[ name ] = {
          name: name, // 'SOME_SIM/string.name'
          requirejsNamespace: requirejsNamespace, // 'SOME_SIM'
          requirePath: requirePath, // '/Users/something/phet/git/some-sim/js'
          repositoryPath: repositoryPath, // '/Users/something/phet/git/some-sim'
          repositoryName: repositoryName // 'some-sim'
        };

        // tell require.js we're done processing
        onload( null );
      }
      else {
        requirePath = parentRequire.toUrl( requirejsNamespace );
        if ( requirePath.indexOf( '?' ) >= 0 ) {
          requirePath = requirePath.substring( 0, requirePath.indexOf( '?' ) );
        }
        repositoryPath = requirePath + '/..';
        repositoryName = requirejsNamespace.toLowerCase().split( '_' ).join( '-' );

        // strings may be specified via the 'strings' query parameter, value is expected to be encoded to avoid URI-reserved characters
        var queryParameterStrings = parse( decodeURIComponent( phet.chipper.getQueryParameter( 'strings' ) || '{}' ) );

        // Read the locale from a query parameter, if it is there, or use the fallback locale
        locale = phet.chipper.getQueryParameter( 'locale' ) || ChipperConstants.FALLBACK_LOCALE;
        if ( !localeInfo[ locale ] ) {
          onload.error( new Error( 'unsupported locale: ' + locale ) );
        }
        var isRTL = localeInfo[ locale ].direction === 'rtl';

        var fallbackSpecificPath = repositoryPath + '/' + getFilenameForLocale( ChipperConstants.FALLBACK_LOCALE );
        var localeSpecificPath = ( locale === ChipperConstants.FALLBACK_LOCALE ) ?
                                 fallbackSpecificPath :
                                 repositoryPath + '/../babel/' + repositoryName + '/' + getFilenameForLocale( locale );

        // In the browser, a string specified via the 'strings' query parameter overrides anything,
        // to match the behavior of the chipper version (for dynamically substituting new strings like in the translation utility)
        var queryParameterStringValue = queryParameterStrings[ name ];
        if ( queryParameterStringValue ) {
          onload( queryParameterStringValue );
        }
        else {

          // Load & parse just once per file, getting the fallback strings first.
          getWithCache( fallbackSpecificPath, function( parsedFallbackStrings ) {
              if ( parsedFallbackStrings[ key ] === undefined ) {
                throw new Error( 'Missing string: ' + key + ' in ' + fallbackSpecificPath );
              }
              var fallback = parsedFallbackStrings[ key ].value;

              // Now get the primary strings.
              getWithCache( localeSpecificPath, function( parsed ) {
                  for ( var stringKey in parsed ) {
                    parsed[ stringKey ].value = ChipperStringUtils.addDirectionalFormatting( parsed[ stringKey ].value, isRTL );
                  }

                  // Combine the primary and fallback strings into one object hash.
                  var parsedStrings = _.extend( parsedFallbackStrings, parsed );
                  if ( parsedStrings[ key ] !== undefined ) {
                    onload( window.phet.chipper.mapString( parsedStrings[ key ].value, stringTest ) );
                  }
                  else {
                    throw new Error( 'no entry for string key: ' + key );
                  }
                },
                // Error callback in the text! plugin.  Couldn't load the strings for the specified language, so use a fallback
                function() {

                  if ( !parsedFallbackStrings[ key ] ) {
                    // It would be really strange for there to be no fallback for a certain string, that means it exists in the translation but not the original English
                    throw new Error( 'no fallback for string key:' + key );
                  }
                  // Running in the browser (dynamic requirejs mode) and couldn't find the string file.  Use the fallbacks.
                  console.log( "no string file for " + localeSpecificPath );
                  onload( fallback );
                },
                { accept: 'application/json' }
              );
            },
            onload.error,
            { accept: 'application/json' }
          );
        }
      }
    },

    /**
     * Write code that will look up the string in the compiled sim, used in the compilation step.  write is only used
     * by the optimizer, and it only needs to be implemented if the plugin can output something that would belong in an
     * optimized layer.
     *
     * Documentation taken from http://requirejs.org/docs/plugins.html#apiwrite
     *
     * It is called with the following arguments:
     * @param {string} pluginName - The normalized name for the plugin. Most plugins will not be authored with a name
     *          (they will be anonymous plugins) so it is useful to know the normalized name for the plugin module for use
     *          in the optimized file.
     * @param {string} moduleName - The normalized resource name.
     * @param {function} write - A function to be called with a string of output to write to the optimized file. This
     *          function also contains a property function, write.asModule(moduleName, text). asModule can be used to
     *          write out a module that may have an anonymous define call in there that needs name insertion or/and
     *          contains implicit require("") dependencies that need to be pulled out for the optimized file. asModule
     *          is useful for text transform plugins, like a CoffeeScript plugin.
     */
    write: function( pluginName, moduleName, write ) {
      write( 'define("' + pluginName + '!' + moduleName + '",function(){return window.phet.chipper.strings.get(\"' + moduleName + '\");});\n' );
    }
  };
} );
<|endoftext|>


<commit_before>var ApplicationRouter = Backbone.Router.extend({

	initialize: function(el, pRoutes) {
		this.el = el;
	},

	currentView: null,
	pastView: null,

	routes: {
		"": "changeView",
        ":id" : "changeView",
        "work/:id" : "noHandle",
		"*else": "notFound",
	},

	switchView: function(view) {
        var previous = this.currentView;
		if (previous) {
			// Detach the old view
            previous.transitionOut(function(){
                previous.remove();
            })

		  	//add past view
		  	this.pastView = previous;
            // Move the view element into the DOM (replacing the old content)
		    this.el.prepend(view.el);
        }
        else{
            //if no previous view existed, totally replace contents in dom
            this.el.html(view.el);
        }

		// Render view after it is in the DOM (styles are applied)
		view.render();
		this.currentView = view;
        this.currentView.transitionIn();
	},

	/*
	 * Change the active element in the topbar
	 */
	changeView: function(id){
        if(!id) {
            id = 'home';
        }
        if(id.indexOf("work/") == -1 ){
            //$('.loading-screen').fadeIn(400);
            NProgress.start();
            // Make a reference to router itself
            // Fuck this. no like seriously, fuck this
            var router = this;
            console.log(id);

            $.ajax({
                url:'../template/' + id + '.html',
                dataType: 'text',
                cache: true,
                success: function(data){
                    router.addedView = new TemplatedView({template:data, data:{}, routeId:id});
                    router.switchView(router.addedView);
                    //router.setActiveEntry(id);
                    $('.loading-screen').fadeOut(400);
                    NProgress.done();
                },
                error: function(){ // [TODO] eeewwww this code is not DRY
                    router.addedView = new ContentView({template:"#404"});
                    router.switchView(router.addedView);
                    $('.loading-screen').fadeOut(400);
                    NProgress.done();
                },
                progress: function(){
                    NProgress.inc();
                },
            });

        }
	},

    noHandle: function(id){
        return id;
    },

	setActiveEntry: function(url) {
		// Unmark all entries
		$('li').removeClass('active');

		// Mark active entry
		$("li a[href='#" + url + "']").parents('li').addClass('active');
	},

/*
	at: function() {
		this.switchView(this.atView);
		this.setActiveEntry('#at');
	},

	duis: function() {
		this.switchView(this.duisView);
		this.setActiveEntry('#duis');
	},*/

	notFound: function() {
        NProgress.done();
		this.addedView = new ContentView({template:"#404"});
		this.switchView(this.addedView);
	}

});
<commit_msg>changed ajax url<commit_after>var ApplicationRouter = Backbone.Router.extend({

	initialize: function(el, pRoutes) {
		this.el = el;
	},

	currentView: null,
	pastView: null,

	routes: {
		"": "changeView",
        ":id" : "changeView",
        "work/:id" : "noHandle",
		"*else": "notFound",
	},

	switchView: function(view) {
        var previous = this.currentView;
		if (previous) {
			// Detach the old view
            previous.transitionOut(function(){
                previous.remove();
            })

		  	//add past view
		  	this.pastView = previous;
            // Move the view element into the DOM (replacing the old content)
		    this.el.prepend(view.el);
        }
        else{
            //if no previous view existed, totally replace contents in dom
            this.el.html(view.el);
        }

		// Render view after it is in the DOM (styles are applied)
		view.render();
		this.currentView = view;
        this.currentView.transitionIn();
	},

	/*
	 * Change the active element in the topbar
	 */
	changeView: function(id){
        if(!id) {
            id = 'home';
        }
        if(id.indexOf("work/") == -1 ){
            //$('.loading-screen').fadeIn(400);
            NProgress.start();
            // Make a reference to router itself
            // Fuck this. no like seriously, fuck this
            var router = this;
            console.log(id);

            $.ajax({
                url:'template/' + id + '.html',
                dataType: 'text',
                cache: true,
                success: function(data){
                    router.addedView = new TemplatedView({template:data, data:{}, routeId:id});
                    router.switchView(router.addedView);
                    //router.setActiveEntry(id);
                    $('.loading-screen').fadeOut(400);
                    NProgress.done();
                },
                error: function(){ // [TODO] eeewwww this code is not DRY
                    router.addedView = new ContentView({template:"#404"});
                    router.switchView(router.addedView);
                    $('.loading-screen').fadeOut(400);
                    NProgress.done();
                },
                progress: function(){
                    NProgress.inc();
                },
            });

        }
	},

    noHandle: function(id){
        return id;
    },

	setActiveEntry: function(url) {
		// Unmark all entries
		$('li').removeClass('active');

		// Mark active entry
		$("li a[href='#" + url + "']").parents('li').addClass('active');
	},

/*
	at: function() {
		this.switchView(this.atView);
		this.setActiveEntry('#at');
	},

	duis: function() {
		this.switchView(this.duisView);
		this.setActiveEntry('#duis');
	},*/

	notFound: function() {
        NProgress.done();
		this.addedView = new ContentView({template:"#404"});
		this.switchView(this.addedView);
	}

});
<|endoftext|>


<commit_before>/* This software is licensed under a BSD license; see the LICENSE file for details. */

function boolToInt(x) { if (x) return 1; else return 0; }

DashedSentence.name = "DashedSentence";
DashedSentence.obligatory = ["s"];

function DashedSentence(div, options, finishedCallback, utils) {
    this.options = options;
    this.words = options.s.split(/\s+/);
    this.mode = dget(options, "mode", "self-paced reading");
    this.wordTime = dget(options, "wordTime", 300); // Only for speeded accpetability.
    this.wordPauseTime = dget(options, "wordPauseTime", 100); // Ditto.
    this.currentWord = 0;

    // Defaults.
    this.unshownBorderColor = dget(options, "unshownBorderColor", "#9ea4b1");
    this.shownBorderColor = dget(options, "shownBorderColor", "black");
    this.unshownWordColor = dget(options, "unshownWordColor", "white");
    this.shownWordColor = dget(options, "shownWordColor", "black");

    // Precalculate MD5 of sentence.
    var canonicalSentence = this.words.join(' ');
    this.sentenceMD5 = hex_md5(canonicalSentence);

    this.div = div;
    this.div.className = "sentence";

    this.resultsLines = [];
    this.previousTime = null;

    this.wordDivs = new Array(this.words.length);
    for (var j = 0; j < this.words.length; ++j) {
        var div = document.createElement("div");
        div.appendChild(document.createTextNode(this.words[j]));
        this.div.appendChild(div);
        this.wordDivs[j] = div;
    }

    this.blankWord = function(w) {
        if (this.currentWord <= this.words.length) {
            this.wordDivs[w].style.borderColor = this.unshownBorderColor;
            this.wordDivs[w].style.color = this.unshownWordColor;
        }
    };
    this.showWord = function(w) {
        if (this.currentWord < this.words.length) {
            this.wordDivs[w].style.borderColor = this.shownBorderColor;
            this.wordDivs[w].style.color = this.shownWordColor;
        }
    }

    if (this.mode == "speeded acceptability") {
        this.showWord(0);
        var t = this;
        function wordTimeout() {
            t.blankWord(t.currentWord);
            ++(t.currentWord);
            if (t.currentWord >= t.words.length)
                finishedCallback([[["Sentence MD5", t.sentenceMD5]]]);
            else
                utils.setTimeout(wordPauseTimeout, t.wordPauseTime);
        }
        function wordPauseTimeout() {
            t.showWord(t.currentWord);
            utils.clearTimeout(wordPauseTimeout);
            utils.setTimeout(wordTimeout, t.wordTime);
        }
        utils.setTimeout(wordTimeout, this.wordTime);
    }

    if (this.mode == "self-paced reading") {
        this.handleKey = function(code, time) {
            if (code == 32) {
                this.recordSprResult(time, this.currentWord);

                if (this.currentWord - 1 >= 0)
                    this.blankWord(this.currentWord - 1);
                if (this.currentWord < this.words.length)
                    this.showWord(this.currentWord);
                ++(this.currentWord);
                if (this.currentWord > this.words.length)
                    finishedCallback(this.resultsLines);

                return false;
            }
            else {
                return true;
            }
        };
    }

    this.recordSprResult = function(time, word) {
        if (word > 0 && word < this.wordDivs.length) {
            assert(this.previousTime, "Internal error in dashed_sentence.js");
            this.resultsLines.push([
                ["Word number", word],
                ["Reading time", time - this.previousTime],
                ["Newline?", boolToInt((word > 0) && (this.wordDivs[word - 1].offsetTop !=
                                                      this.wordDivs[word].offsetTop))],
                ["Sentence MD5", this.sentenceMD5]
            ]);
        }
        this.previousTime = time;
    };
}

DashedSentence.htmlDescription = function (opts) {
    return document.createTextNode(opts.s);
}

<commit_msg>DashedSentence now supports stopping points and multi-word chunks.<commit_after>/* This software is licensed under a BSD license; see the LICENSE file for details. */

function boolToInt(x) { if (x) return 1; else return 0; }

DashedSentence.name = "DashedSentence";
DashedSentence.obligatory = ["s"];

function DashedSentence(div, options, finishedCallback, utils) {
    this.options = options;
    if (typeof(options.s) == "string")
        this.words = options.s.split(/\s+/);
    else {
        assert_is_arraylike(options.s, "Bad value for 's' option of DashedSentence.");
        this.words = options.s;
    }
    this.mode = dget(options, "mode", "self-paced reading");
    this.wordTime = dget(options, "wordTime", 300); // Only for speeded accpetability.
    this.wordPauseTime = dget(options, "wordPauseTime", 100); // Ditto.
    this.currentWord = 0;

    // Is there a "stopping point" specified?
    this.stoppingPoint = this.words.length;
    for (var i = 0; i < this.words.length; ++i) {
        if (stringStartsWith("@", this.words[i])) {
            this.words[i] = this.words[i].substring(1);
            this.stoppingPoint = i + 1;
            break;
        }
    }

    // Defaults.
    this.unshownBorderColor = dget(options, "unshownBorderColor", "#9ea4b1");
    this.shownBorderColor = dget(options, "shownBorderColor", "black");
    this.unshownWordColor = dget(options, "unshownWordColor", "white");
    this.shownWordColor = dget(options, "shownWordColor", "black");

    // Precalculate MD5 of sentence.
    var canonicalSentence = this.words.join(' ');
    this.sentenceMD5 = hex_md5(canonicalSentence);

    this.div = div;
    this.div.className = "sentence";

    this.resultsLines = [];
    this.previousTime = null;

    this.wordDivs = new Array(this.words.length);
    for (var j = 0; j < this.words.length; ++j) {
        var div = document.createElement("div");
        div.appendChild(document.createTextNode(this.words[j]));
        this.div.appendChild(div);
        this.wordDivs[j] = div;
    }

    this.blankWord = function(w) {
        if (this.currentWord <= this.stoppingPoint) {
            this.wordDivs[w].style.borderColor = this.unshownBorderColor;
            this.wordDivs[w].style.color = this.unshownWordColor;
        }
    };
    this.showWord = function(w) {
        if (this.currentWord < this.stoppingPoint) {
            this.wordDivs[w].style.borderColor = this.shownBorderColor;
            this.wordDivs[w].style.color = this.shownWordColor;
        }
    }

    if (this.mode == "speeded acceptability") {
        this.showWord(0);
        var t = this;
        function wordTimeout() {
            t.blankWord(t.currentWord);
            ++(t.currentWord);
            if (t.currentWord >= t.stoppingPoint)
                finishedCallback([[["Sentence MD5", t.sentenceMD5]]]);
            else
                utils.setTimeout(wordPauseTimeout, t.wordPauseTime);
        }
        function wordPauseTimeout() {
            t.showWord(t.currentWord);
            utils.clearTimeout(wordPauseTimeout);
            utils.setTimeout(wordTimeout, t.wordTime);
        }
        utils.setTimeout(wordTimeout, this.wordTime);
    }

    if (this.mode == "self-paced reading") {
        this.handleKey = function(code, time) {
            if (code == 32) {
                this.recordSprResult(time, this.currentWord);

                if (this.currentWord - 1 >= 0)
                    this.blankWord(this.currentWord - 1);
                if (this.currentWord < this.stoppingPoint)
                    this.showWord(this.currentWord);
                ++(this.currentWord);
                if (this.currentWord > this.stoppingPoint)
                    finishedCallback(this.resultsLines);

                return false;
            }
            else {
                return true;
            }
        };
    }

    this.recordSprResult = function(time, word) {
        if (word > 0 && word < this.stoppingPoint) {
            assert(this.previousTime, "Internal error in dashed_sentence.js");
            this.resultsLines.push([
                ["Word number", word],
                ["Reading time", time - this.previousTime],
                ["Newline?", boolToInt((word > 0) && (this.wordDivs[word - 1].offsetTop !=
                                                      this.wordDivs[word].offsetTop))],
                ["Sentence MD5", this.sentenceMD5]
            ]);
        }
        this.previousTime = time;
    };
}

DashedSentence.htmlDescription = function (opts) {
    return document.createTextNode(opts.s);
}

<|endoftext|>


<commit_before> function toggler(item, item2) {

$(".prices").addClass('hidden');
$(".menu").removeClass('active');
//alert("dfd");
 $("."+item).removeClass('hidden');
  $("#menu"+item).addClass('active');
 //$(item).toggle();
 $("#title").text(  item2);
}

  jQuery(document).ready(function($) {

String.prototype.cleanup = function() {
   return this.toLowerCase().replace(/[^a-zA-Z0-9]+/g, "");
}

     $.getJSON( "prices.json", function( data ) {

  var items = [];
  $.each( data, function( key, val ) {
    var link = ""+key+"";
    $( link).appendTo( "#list1" );

 $.each(val, function (index, value) {

  var price = `
     <tr class="prices hidden `+key.cleanup()+` id="`+key.cleanup()+`">
        `+this.vetement+`
        `+this.catgorie+`
        `+this.action+`
        `+this.prix+` €

  `;
    $(price).appendTo("#priceslisttable");
    });

  });

});

});<commit_msg>quotes<commit_after> function toggler(item, item2) {

$(".prices").addClass('hidden');
$(".menu").removeClass('active');
//alert("dfd");
 $("."+item).removeClass('hidden');
  $("#menu"+item).addClass('active');
 //$(item).toggle();
 $("#title").text(  item2);
}

  jQuery(document).ready(function($) {

String.prototype.cleanup = function() {
   return this.toLowerCase().replace(/[^a-zA-Z0-9]+/g, "");
}

     $.getJSON( "prices.json", function( data ) {

  var items = [];
  $.each( data, function( key, val ) {
    var link = ""+key+"";
    $( link).appendTo( "#list1" );

 $.each(val, function (index, value) {

  var price = "
"+
      +""+this.vetement+"	"+
      +""+this.catgorie+"	"+
      +""+this.action+"	"+
      +""+this.prix+"€	"+
      +"
";

    $(price).appendTo("#priceslisttable");
    });

  });

});

});<|endoftext|>