<commit_before>function constructUsersChartData(json, $scope) {
    var data = [0, 0, 0, 0];

    var usersOnline = 0;
    var adminsOnline = 0;

    for (var user in json) {
        var signedIn = json[user]["signedIn"];
        var admin = json[user]["admin"];

        if(signedIn) usersOnline++;
        if(admin && signedIn) adminsOnline++;

        if(signedIn && !admin) {
            data[0]++; //User online and not admin
        } else if(signedIn && admin) {
            data[2]++; //User online and admin
        } else if(!signedIn && !admin) {
            data[1]++; //User offline and not admin
        } else if(!signedIn && admin) {
            data[3]++; //User offline and admin
        }
    }

    $scope.usersOnline = usersOnline;
    $scope.adminsOnline = adminsOnline;

    return data;
}

function constructClientsChartData(json, $scope) {
    var data = [0, 0, 0, 0, 0];
    var updatesNeeded = [0, 0];
    var operations = [0, 0];

    var clientsOnline = 0;

    for (var client in json) {
        var state = json[client]["state"];

        switch(state) {
            case 0:
                clientsOnline++;
            case 1:
            case 2:
            case 3:
            case 4:
                data[state]++;

                if(json[client]["updates"] !== null && json[client]["updates"] > 0) {
                    updatesNeeded[1]++;
                } else updatesNeeded[0]++;

                if(json[client]["operationStatus"] !== null && json[client]["operationStatus"] === 0) {
                    operations[0]++;
                } else if(json[client]["operationStatus"] !== null && json[client]["operationStatus"] === 1) operations[1]++;
                break;
        }
    }

    $scope.clientsOnline = clientsOnline;

    return {stateData: data, updatesData: updatesNeeded, operationsData: operations};
}

function syncClients(LoginService, SyncService, $scope, $rootScope, $timeout, inital, clientsChart, updatesChart, operationsChart, usersChart, cb) {
    $.get(URL_PREFIX + 'nectar/api/v/' + API_VERSION_MAJOR + "/" + API_VERSION_MINOR + "/query/queryClients?token=" + LoginService.getSessionToken())
    .done(function(data, status, xhr) {
        console.log("Got response for queryClients SUCCESS: " + xhr.status + " " + xhr.statusText);

        var json = KJUR.jws.JWS.readSafeJSONString(xhr.responseText);
        SyncService.setLastClientSyncJSONData(json);

        var data = constructClientsChartData(json, $scope);

        if(inital) {
            var clientsCtx = document.getElementById("clientsChart");
            var updatesCtx = document.getElementById("updatesChart");
            var operationsCtx = document.getElementById("operationsChart");

            clientsChart = new Chart(clientsCtx, {
                type: 'pie',
                data: {
                    labels: [
                        "Online",
                        "Shutdown",
                        "Sleeping",
                        "Restarting",
                        "Unknown"
                    ],
                    datasets: [
                        {
                            data: data.stateData,
                            backgroundColor: [
                                "#20f718",
                                "#35f4ff",
                                "#e1ff77",
                                "#ffd334",
                                "#FF6384"
                            ],
                            hoverBackgroundColor: [
                                "#20f718",
                                "#35f4ff",
                                "#e1ff77",
                                "#ffd334",
                                "#FF6384"
                            ]
                        }
                    ]
                },
                options: {
                    animation:{
                        animateScale: true
                    }
                }
            });

            updatesChart = new Chart(updatesCtx, {
                type: 'pie',
                data: {
                    labels: [
                        "Up to date",
                        "Updates Needed"
                    ],
                    datasets: [
                        {
                            data: data.updatesData,
                            backgroundColor: [
                                "#20f718",
                                "#ffd334",
                            ],
                            hoverBackgroundColor: [
                                "#20f718",
                                "#ffd334",
                            ]
                        }
                    ]
                },
                options: {
                    animation:{
                        animateScale: true
                    }
                }
            });

            operationsChart = new Chart(operationsCtx, {
                type: 'pie',
                data: {
                    labels: [
                        "Idle",
                        "Processing"
                    ],
                    datasets: [
                        {
                            data: data.operationsData,
                            backgroundColor: [
                                "#20f718",
                                "#b784ff",
                            ],
                            hoverBackgroundColor: [
                                "#20f718",
                                "#b784ff",
                            ]
                        }
                    ]
                },
                options: {
                    animation:{
                        animateScale: true
                    }
                }
            });
        } else {
            clientsChart.data.datasets[0].data = data.stateData;
            clientsChart.update();

            updatesChart.data.datasets[0].data = data.updatesData;
            updatesChart.update();

            operationsChart.data.datasets[0].data = data.operationsData;
            operationsChart.update();
        }

        cb();

        $timeout(function() {
            SyncService.syncEverything(LoginService, SyncService, $scope, $rootScope, $timeout, false, clientsChart, updatesChart, operationsChart, usersChart);
        }, 5000); // Sync every 5 seconds
    }).fail(function(xhr, textStatus, errorThrown) {
        // TODO: seperate messages based on status code
        console.error("Got response for queryClients FAILURE: " + xhr.status + " " + xhr.statusText);

        if(xhr.status !== 403) alert("Failed to query server! (" + xhr.status + " " + xhr.statusText + ")");

        cb();

        $timeout(function() {
            SyncService.syncEverything(LoginService, SyncService, $scope, $rootScope, $timeout, false, clientsChart, updatesChart, operationsChart, usersChart);
        }, 5000); // Sync every 5 seconds
    });
}

function syncUsers(LoginService, SyncService, $scope, $rootScope, $timeout, inital, clientsChart, updatesChart, operationsChart, usersChart, cb) {
    $.get(URL_PREFIX + 'nectar/api/v/' + API_VERSION_MAJOR + "/" + API_VERSION_MINOR + "/query/queryUsers?token=" + LoginService.getSessionToken())
    .done(function(data, status, xhr) {
        console.log("Got response for queryUsers SUCCESS: " + xhr.status + " " + xhr.statusText);

        var json = KJUR.jws.JWS.readSafeJSONString(xhr.responseText);
        var data = constructUsersChartData(json, $scope);

        if(inital) {
            var usersCtx = document.getElementById("usersChart");

            usersChart = new Chart(usersCtx, {
                type: 'pie',
                data: {
                    labels: [
                        "Logged In",
                        "Logged Out",
                        "Logged In (Admin)",
                        "Logged Out (Admin)"
                    ],
                    datasets: [
                        {
                            data: data,
                            backgroundColor: [
                                "#20f718",
                                "#4fffbe",
                                "#e1ff77",
                                "#ffd334"
                            ],
                            hoverBackgroundColor: [
                                "#20f718",
                                "#4fffbe",
                                "#e1ff77",
                                "#ffd334"
                            ]
                        }
                    ]
                },
                options: {
                    animation:{
                        animateScale: true
                    }
                }
            });
        } else {
            usersChart.data.datasets[0].data = data;
            usersChart.update();
        }

        syncEventLog(LoginService, SyncService, $scope, $rootScope, $timeout, inital, clientsChart, updatesChart, operationsChart, usersChart, cb);
    }).fail(function(xhr, textStatus, errorThrown) {
        // TODO: seperate messages based on status code
        console.error("Got response for queryClients FAILURE: " + xhr.status + " " + xhr.statusText);

        if(xhr.status !== 403) alert("Failed to query server! (" + xhr.status + " " + xhr.statusText + ")");

        syncEventLog(LoginService, SyncService, $scope, $rootScope, $timeout, inital, clientsChart, updatesChart, operationsChart, usersChart, cb);
    });
}

function syncEventLog(LoginService, SyncService, $scope, $rootScope, $timeout, inital, clientsChart, updatesChart, operationsChart, usersChart, cb) {
    // If inital is true (first time querying the server) then get the whole event log.
    if(inital) {
        $.get(URL_PREFIX + 'nectar/api/v/' + API_VERSION_MAJOR + "/" + API_VERSION_MINOR + "/query/queryEventLog?token=" + LoginService.getSessionToken() + "&entryCount=150")
        .done(function(data, status, xhr) {
            console.log("Got response for queryEventLog SUCCESS: " + xhr.status + " " + xhr.statusText);

            document.getElementById("eventLog").innerHTML = xhr.responseText;

            syncClients(LoginService, SyncService, $scope, $rootScope, $timeout, inital, clientsChart, updatesChart, operationsChart, usersChart, cb);
        }).fail(function(xhr, textStatus, errorThrown) {
            // TODO: seperate messages based on status code
            console.error("Got response for queryEventLog FAILURE: " + xhr.status + " " + xhr.statusText);

            if(xhr.status !== 403) alert("Failed to query server! (" + xhr.status + " " + xhr.statusText + ")");

            syncClients(LoginService, SyncService, $scope, $rootScope, $timeout, inital, clientsChart, updatesChart, operationsChart, usersChart, cb);
        });
    } else {
        $.get(URL_PREFIX + "nectar/api/v/" + API_VERSION_MAJOR + "/" + API_VERSION_MINOR + "/query/queryEventLogSince?token=" + LoginService.getSessionToken() + "&timestamp=" + SyncService.getLastSyncTime())
        .done(function(data, status, xhr) {
            console.log("Got response for queryEventLogSince SUCCESS: " + xhr.status + " " + xhr.statusText);

            document.getElementById("eventLog").innerHTML += xhr.responseText;

            syncClients(LoginService, SyncService, $scope, $rootScope, $timeout, inital, clientsChart, updatesChart, operationsChart, usersChart, cb);
        }).fail(function(xhr, textStatus, errorThrown) {
            // TODO: seperate messages based on status code
            console.error("Got response for queryEventLogSince FAILURE: " + xhr.status + " " + xhr.statusText);

            if(xhr.status !== 403) alert("Failed to query server! (" + xhr.status + " " + xhr.statusText + ")");

            syncClients(LoginService, SyncService, $scope, $rootScope, $timeout, inital, clientsChart, updatesChart, operationsChart, usersChart, cb);
        });
    }
}
<commit_msg>Updated operations chart to include success and failure<commit_after>function constructUsersChartData(json, $scope) {
    var data = [0, 0, 0, 0];

    var usersOnline = 0;
    var adminsOnline = 0;

    for (var user in json) {
        var signedIn = json[user]["signedIn"];
        var admin = json[user]["admin"];

        if(signedIn) usersOnline++;
        if(admin && signedIn) adminsOnline++;

        if(signedIn && !admin) {
            data[0]++; //User online and not admin
        } else if(signedIn && admin) {
            data[2]++; //User online and admin
        } else if(!signedIn && !admin) {
            data[1]++; //User offline and not admin
        } else if(!signedIn && admin) {
            data[3]++; //User offline and admin
        }
    }

    $scope.usersOnline = usersOnline;
    $scope.adminsOnline = adminsOnline;

    return data;
}

function constructClientsChartData(json, $scope) {
    var data = [0, 0, 0, 0, 0];
    var updatesNeeded = [0, 0];
    var operations = [0, 0, 0, 0];

    var clientsOnline = 0;

    for (var client in json) {
        var state = json[client]["state"];

        switch(state) {
            case 0:
                clientsOnline++;
            case 1:
            case 2:
            case 3:
            case 4:
                data[state]++;

                if(json[client]["updates"] !== null && json[client]["updates"] > 0) {
                    updatesNeeded[1]++;
                } else updatesNeeded[0]++;

                if(json[client]["operationStatus"] !== null) {
                    switch(json[client]["operationStatus"]) {
                        case 0:
                            operations[0]++;
                            break;
                        case 1:
                            operations[3]++;
                            break;
                        case 2:
                            operations[1]++;
                            break;
                        case 3:
                            operations[2]++;
                            break;
                        default:
                            break;
                    }
                }
                break;
        }
    }

    $scope.clientsOnline = clientsOnline;

    return {stateData: data, updatesData: updatesNeeded, operationsData: operations};
}

function syncClients(LoginService, SyncService, $scope, $rootScope, $timeout, inital, clientsChart, updatesChart, operationsChart, usersChart, cb) {
    $.get(URL_PREFIX + 'nectar/api/v/' + API_VERSION_MAJOR + "/" + API_VERSION_MINOR + "/query/queryClients?token=" + LoginService.getSessionToken())
    .done(function(data, status, xhr) {
        console.log("Got response for queryClients SUCCESS: " + xhr.status + " " + xhr.statusText);

        var json = KJUR.jws.JWS.readSafeJSONString(xhr.responseText);
        SyncService.setLastClientSyncJSONData(json);

        var data = constructClientsChartData(json, $scope);

        if(inital) {
            var clientsCtx = document.getElementById("clientsChart");
            var updatesCtx = document.getElementById("updatesChart");
            var operationsCtx = document.getElementById("operationsChart");

            clientsChart = new Chart(clientsCtx, {
                type: 'pie',
                data: {
                    labels: [
                        "Online",
                        "Shutdown",
                        "Sleeping",
                        "Restarting",
                        "Unknown"
                    ],
                    datasets: [
                        {
                            data: data.stateData,
                            backgroundColor: [
                                "#20f718",
                                "#35f4ff",
                                "#e1ff77",
                                "#ffd334",
                                "#FF6384"
                            ],
                            hoverBackgroundColor: [
                                "#20f718",
                                "#35f4ff",
                                "#e1ff77",
                                "#ffd334",
                                "#FF6384"
                            ]
                        }
                    ]
                },
                options: {
                    animation:{
                        animateScale: true
                    }
                }
            });

            updatesChart = new Chart(updatesCtx, {
                type: 'pie',
                data: {
                    labels: [
                        "Up to date",
                        "Updates Needed"
                    ],
                    datasets: [
                        {
                            data: data.updatesData,
                            backgroundColor: [
                                "#20f718",
                                "#ffd334",
                            ],
                            hoverBackgroundColor: [
                                "#20f718",
                                "#ffd334",
                            ]
                        }
                    ]
                },
                options: {
                    animation:{
                        animateScale: true
                    }
                }
            });

            operationsChart = new Chart(operationsCtx, {
                type: 'pie',
                data: {
                    labels: [
                        "Idle",
                        "Idle (Succeeded)",
                        "Idle (Failed)",
                        "Processing"
                    ],
                    datasets: [
                        {
                            data: data.operationsData,
                            backgroundColor: [
                                "#20f718",
                                "#9cff99",
                                "#ff8c00",
                                "#b784ff",
                            ],
                            hoverBackgroundColor: [
                                "#20f718",
                                "#9cff99",
                                "#ff8c00",
                                "#b784ff",
                            ]
                        }
                    ]
                },
                options: {
                    animation:{
                        animateScale: true
                    }
                }
            });
        } else {
            clientsChart.data.datasets[0].data = data.stateData;
            clientsChart.update();

            updatesChart.data.datasets[0].data = data.updatesData;
            updatesChart.update();

            operationsChart.data.datasets[0].data = data.operationsData;
            operationsChart.update();
        }

        cb();

        $timeout(function() {
            SyncService.syncEverything(LoginService, SyncService, $scope, $rootScope, $timeout, false, clientsChart, updatesChart, operationsChart, usersChart);
        }, 5000); // Sync every 5 seconds
    }).fail(function(xhr, textStatus, errorThrown) {
        // TODO: seperate messages based on status code
        console.error("Got response for queryClients FAILURE: " + xhr.status + " " + xhr.statusText);

        if(xhr.status !== 403) alert("Failed to query server! (" + xhr.status + " " + xhr.statusText + ")");

        cb();

        $timeout(function() {
            SyncService.syncEverything(LoginService, SyncService, $scope, $rootScope, $timeout, false, clientsChart, updatesChart, operationsChart, usersChart);
        }, 5000); // Sync every 5 seconds
    });
}

function syncUsers(LoginService, SyncService, $scope, $rootScope, $timeout, inital, clientsChart, updatesChart, operationsChart, usersChart, cb) {
    $.get(URL_PREFIX + 'nectar/api/v/' + API_VERSION_MAJOR + "/" + API_VERSION_MINOR + "/query/queryUsers?token=" + LoginService.getSessionToken())
    .done(function(data, status, xhr) {
        console.log("Got response for queryUsers SUCCESS: " + xhr.status + " " + xhr.statusText);

        var json = KJUR.jws.JWS.readSafeJSONString(xhr.responseText);
        var data = constructUsersChartData(json, $scope);

        if(inital) {
            var usersCtx = document.getElementById("usersChart");

            usersChart = new Chart(usersCtx, {
                type: 'pie',
                data: {
                    labels: [
                        "Logged In",
                        "Logged Out",
                        "Logged In (Admin)",
                        "Logged Out (Admin)"
                    ],
                    datasets: [
                        {
                            data: data,
                            backgroundColor: [
                                "#20f718",
                                "#4fffbe",
                                "#e1ff77",
                                "#ffd334"
                            ],
                            hoverBackgroundColor: [
                                "#20f718",
                                "#4fffbe",
                                "#e1ff77",
                                "#ffd334"
                            ]
                        }
                    ]
                },
                options: {
                    animation:{
                        animateScale: true
                    }
                }
            });
        } else {
            usersChart.data.datasets[0].data = data;
            usersChart.update();
        }

        syncEventLog(LoginService, SyncService, $scope, $rootScope, $timeout, inital, clientsChart, updatesChart, operationsChart, usersChart, cb);
    }).fail(function(xhr, textStatus, errorThrown) {
        // TODO: seperate messages based on status code
        console.error("Got response for queryClients FAILURE: " + xhr.status + " " + xhr.statusText);

        if(xhr.status !== 403) alert("Failed to query server! (" + xhr.status + " " + xhr.statusText + ")");

        syncEventLog(LoginService, SyncService, $scope, $rootScope, $timeout, inital, clientsChart, updatesChart, operationsChart, usersChart, cb);
    });
}

function syncEventLog(LoginService, SyncService, $scope, $rootScope, $timeout, inital, clientsChart, updatesChart, operationsChart, usersChart, cb) {
    // If inital is true (first time querying the server) then get the whole event log.
    if(inital) {
        $.get(URL_PREFIX + 'nectar/api/v/' + API_VERSION_MAJOR + "/" + API_VERSION_MINOR + "/query/queryEventLog?token=" + LoginService.getSessionToken() + "&entryCount=150")
        .done(function(data, status, xhr) {
            console.log("Got response for queryEventLog SUCCESS: " + xhr.status + " " + xhr.statusText);

            document.getElementById("eventLog").innerHTML = xhr.responseText;

            syncClients(LoginService, SyncService, $scope, $rootScope, $timeout, inital, clientsChart, updatesChart, operationsChart, usersChart, cb);
        }).fail(function(xhr, textStatus, errorThrown) {
            // TODO: seperate messages based on status code
            console.error("Got response for queryEventLog FAILURE: " + xhr.status + " " + xhr.statusText);

            if(xhr.status !== 403) alert("Failed to query server! (" + xhr.status + " " + xhr.statusText + ")");

            syncClients(LoginService, SyncService, $scope, $rootScope, $timeout, inital, clientsChart, updatesChart, operationsChart, usersChart, cb);
        });
    } else {
        $.get(URL_PREFIX + "nectar/api/v/" + API_VERSION_MAJOR + "/" + API_VERSION_MINOR + "/query/queryEventLogSince?token=" + LoginService.getSessionToken() + "&timestamp=" + SyncService.getLastSyncTime())
        .done(function(data, status, xhr) {
            console.log("Got response for queryEventLogSince SUCCESS: " + xhr.status + " " + xhr.statusText);

            document.getElementById("eventLog").innerHTML += xhr.responseText;

            syncClients(LoginService, SyncService, $scope, $rootScope, $timeout, inital, clientsChart, updatesChart, operationsChart, usersChart, cb);
        }).fail(function(xhr, textStatus, errorThrown) {
            // TODO: seperate messages based on status code
            console.error("Got response for queryEventLogSince FAILURE: " + xhr.status + " " + xhr.statusText);

            if(xhr.status !== 403) alert("Failed to query server! (" + xhr.status + " " + xhr.statusText + ")");

            syncClients(LoginService, SyncService, $scope, $rootScope, $timeout, inital, clientsChart, updatesChart, operationsChart, usersChart, cb);
        });
    }
}
<|endoftext|>


<commit_before>var logger = require('./logger');
var lodash = require('lodash');
var specSchema= require('./spec-schema');
var contentTypeChecker = require('./content-type');

var isJson = contentTypeChecker.isJson;

var mediaTypeRe = /^\s*([^;]+)/i;

function getMediaType(contentType) {
    return contentType.match( mediaTypeRe )[0].toLowerCase();
}

function getMediaTypeFromSpecReq( specReq ) {
    if( specReq && specReq.headers ) {
        for( var i = 0; i < specReq.headers.length; i++ ) {
            if(/content\-type/i.test( specReq.headers[i].name )) {
                return getMediaType( specReq.headers[i].value );
            }
        }
    }
    return null;
}

function getMediaTypeFromHttpReq( httpReq ) {
    var contentTypeHeader = getHeaderFromHttpReq( httpReq, 'content-type' );
    if( contentTypeHeader ) {
        return getMediaType( contentTypeHeader );
    }
    return null;
}

function getHeaderFromHttpReq( httpReq, header ) {
    if ( header in httpReq.headers ) {
        return httpReq.headers[header];
    }
    return null;
}

function getBodyContent(req, parseToJson){
    var body = null;
    if (req && req.body) {
        body = req.body.trim();
    }

    if (parseToJson){
        try {
            body = JSON.parse(body);
        } catch (e) {
            logger.log('[WARNING]'.red, 'JSON body could not be parsed. Using body as is.');
        }
    }

    return body;
}

exports.areContentTypesSame = function(httpReq, specReq) {
    return getMediaTypeFromHttpReq(httpReq) === getMediaTypeFromSpecReq(specReq);
};

exports.matchesBody = function(httpReq, specReq) {
    if (!specReq) {
        return true;
    }

    var contentType = getMediaTypeFromHttpReq(httpReq);

    var reqBody = getBodyContent(httpReq, isJson(contentType));
    var specBody = getBodyContent(specReq, isJson(contentType));

    return lodash.isEqual(reqBody, specBody);
};

exports.matchesSchema = function(httpReq, specReq) {
    if (!specReq){
        return true;
    }

    var contentType = getMediaTypeFromHttpReq(httpReq);
    var reqBody = getBodyContent(httpReq, isJson(contentType));

    return specSchema.matchWithSchema(reqBody, specReq.schema);
};

exports.matchesHeader = function(httpReq, specReq) {
    if (!specReq || !specReq.headers){
        return true;
    }

    function removeContentTypeHeader(header){
        return header.name.toLowerCase() !== 'content-type';
    }

    function containsHeader( header ){
        var httpReqHeader = header.name.toLowerCase();
        return httpReq.headers.hasOwnProperty(httpReqHeader) &&
            httpReq.headers[httpReqHeader] === header.value;
    }

    return specReq.headers.filter(removeContentTypeHeader).every(containsHeader);
};
<commit_msg>Always match bodies when the request content type is multipart/form-data<commit_after>var logger = require('./logger');
var lodash = require('lodash');
var specSchema= require('./spec-schema');
var contentTypeChecker = require('./content-type');

var isJson = contentTypeChecker.isJson;

var mediaTypeRe = /^\s*([^;]+)/i;

function getMediaType(contentType) {
    return contentType.match( mediaTypeRe )[0].toLowerCase();
}

function getMediaTypeFromSpecReq( specReq ) {
    if( specReq && specReq.headers ) {
        for( var i = 0; i < specReq.headers.length; i++ ) {
            if(/content\-type/i.test( specReq.headers[i].name )) {
                return getMediaType( specReq.headers[i].value );
            }
        }
    }
    return null;
}

function getMediaTypeFromHttpReq( httpReq ) {
    var contentTypeHeader = getHeaderFromHttpReq( httpReq, 'content-type' );
    if( contentTypeHeader ) {
        return getMediaType( contentTypeHeader );
    }
    return null;
}

function getHeaderFromHttpReq( httpReq, header ) {
    if ( header in httpReq.headers ) {
        return httpReq.headers[header];
    }
    return null;
}

function getBodyContent(req, parseToJson){
    var body = null;
    if (req && req.body) {
        body = req.body.trim();
    }

    if (parseToJson){
        try {
            body = JSON.parse(body);
        } catch (e) {
            logger.log('[WARNING]'.red, 'JSON body could not be parsed. Using body as is.');
        }
    }

    return body;
}

exports.areContentTypesSame = function(httpReq, specReq) {
    return getMediaTypeFromHttpReq(httpReq) === getMediaTypeFromSpecReq(specReq);
};

exports.matchesBody = function(httpReq, specReq) {
    if (!specReq) {
        return true;
    }

    var contentType = getMediaTypeFromHttpReq(httpReq);

    if (contentTypeChecker.isMultipart(contentType)) {
        return true;
    }

    var reqBody = getBodyContent(httpReq, isJson(contentType));
    var specBody = getBodyContent(specReq, isJson(contentType));

    return lodash.isEqual(reqBody, specBody);
};

exports.matchesSchema = function(httpReq, specReq) {
    if (!specReq){
        return true;
    }

    var contentType = getMediaTypeFromHttpReq(httpReq);
    var reqBody = getBodyContent(httpReq, isJson(contentType));

    return specSchema.matchWithSchema(reqBody, specReq.schema);
};

exports.matchesHeader = function(httpReq, specReq) {
    if (!specReq || !specReq.headers){
        return true;
    }

    function removeContentTypeHeader(header){
        return header.name.toLowerCase() !== 'content-type';
    }

    function containsHeader( header ){
        var httpReqHeader = header.name.toLowerCase();
        return httpReq.headers.hasOwnProperty(httpReqHeader) &&
            httpReq.headers[httpReqHeader] === header.value;
    }

    return specReq.headers.filter(removeContentTypeHeader).every(containsHeader);
};
<|endoftext|>


<commit_before>/**
 * Created by nitaip on 27/07/2015.
 */
// @formatter:off
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
        (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
// @formatter:on

ga('create', 'UA-59789536-3', 'auto');
ga('set', 'checkProtocolTask', function () {
});

function hashCode(str) {
    var hash = 0, i, chr, len;
    if (str.length == 0) return hash;
    for (i = 0, len = str.length; i < len; i++) {
        chr = str.charCodeAt(i);
        hash = ((hash << 5) - hash) + chr;
        hash |= 0; // Convert to 32bit integer
    }
    return hash;
}

function uuid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

function getUUID() {
    if (!localStorage['_uid'] || !localStorage['_uid'].length) {
        localStorage['_uid'] = uuid();
    }
    return localStorage['_uid'];
}

ga('set', 'uid', getUUID());
ga('set', 'version', chrome.runtime.getManifest().version);

if (host()) {
    ga('set', 'organization', md5(host()));
}<commit_msg>Updated Tracking ID<commit_after>/**
 * Created by nitaip on 27/07/2015.
 */
// @formatter:off
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
        (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
    m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
// @formatter:on

ga('create', 'UA-65738374-2', 'auto');
ga('set', 'checkProtocolTask', function () {
});

function hashCode(str) {
    var hash = 0, i, chr, len;
    if (str.length == 0) return hash;
    for (i = 0, len = str.length; i < len; i++) {
        chr = str.charCodeAt(i);
        hash = ((hash << 5) - hash) + chr;
        hash |= 0; // Convert to 32bit integer
    }
    return hash;
}

function uuid() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

function getUUID() {
    if (!localStorage['_uid'] || !localStorage['_uid'].length) {
        localStorage['_uid'] = uuid();
    }
    return localStorage['_uid'];
}

ga('set', 'uid', getUUID());
ga('set', 'version', chrome.runtime.getManifest().version);

if (host()) {
    ga('set', 'organization', md5(host()));
}<|endoftext|>


<commit_before>var path = require('path')
var ipc = require("electron").ipcRenderer
var request = require('request')
var d3 = require('d3')
var simplify = require('./simplify')

console.log("loaded")
ipc.on("server-ready", ready)

var URL = 'http://localhost:5000/';

var width = 600;
var height = 600;

var META = {};

// global state controling if we are drawing or not
var drawing;
var tx = 0;
var ty = 0;
var scale = 1;
// path related variables
var pathX = [];
var pathY = [];
var tanX = []
var tanY = [];
var flowX = []
var flowY = []
// we cache our frames and average globally
var frameCache = {};
var average;
var currentFrame;
var currentIndex = "Average";
var flux = []
var hotspots = [];

var canvas, ctx;
var curvectx;

// Global variable for slicing. Will be accessible to user and all functions should
// use them
var start = 0;
var stop = -1;

function ready() {
  // all of our UI code will begin executing here.
  // it's fine to define functions outside of this ready function,
  // but we don't want anything to happen until the server is good to go

  // wire up the file handling
  var inputElement = document.getElementById("new-file");
  inputElement.addEventListener("change", handleFile, false);
  // enable drag-and-drop of files onto the window
  var dropZone = document.body;
  dropZone.addEventListener('dragover', handleFileDrag, false);
  dropZone.addEventListener('drop', handleFile, false);

  canvas = d3.select("#frame").node();
  ctx = canvas.getContext('2d');
  canvas.width = width;
  canvas.height = height;

  var curvecanvas = d3.select("#curve").node();
  curvecanvas.width = width;
  curvecanvas.height = height;
  curvectx = curvecanvas.getContext('2d');

  d3.select("#draw-button").on("click", function() {
    drawing = !drawing;
    var button = d3.select(this)
      .classed("active", drawing)
      .text(function() {
        if(drawing) return "Drawing";
        return "Draw";
      })
    d3.select("#frame").classed("Drawing", drawing)
  })

  var zoom = d3.behavior.zoom()
    //.center([width/2, height/2])
    .scaleExtent([0.5, 20])
    .on("zoomstart", function() {
      if(drawing) {
        pathX = []
        pathY = []
      }
    })
    .on("zoom", function() {
      if(drawing) {
        var x = d3.event.sourceEvent.layerX - tx;
        var y = d3.event.sourceEvent.layerY - ty;
        pathX.push(x/scale)
        pathY.push(y/scale)
        renderCurve();
      } else {
        tx = d3.event.translate[0];
        ty = d3.event.translate[1];
        scale = d3.event.scale;
        renderFrame()
      }
    })
    .on("zoomend", function() {
      if(drawing) {
        //console.log("path", pathX, pathY)
        console.log("done drawing")
        drawing = false;

        d3.select("#draw-button")
          .classed("active", drawing)
          .text(function() {
            if(drawing) return "Drawing";
            return "Draw";
          })
        d3.select("#frame").classed("Drawing", drawing)

        var points = []
        pathX.forEach(function(x,i) {
          var y = pathY[i]
          points.push({x:x, y:y})
        })
        // the 2nd argument is a threshold, a value of 1 won't simplify
        // bigger number means more aggressive simplifying
        var simplified = simplify(points, 0.3)
        pathX = []
        pathY = []
        simplified.forEach(function(p) {
          pathX.push(p.x)
          pathY.push(p.y)
        })
        renderCurve();
        console.log("simplified", simplified)
        getFlux();
        getHotspots();
      }
    })

  d3.select("#frame").call(zoom)
    .on("mousemove", function () {
      coordinates = d3.mouse(this);
      var x = ((coordinates[0] - tx) / scale)/width * META.xdim;
      var y = ((coordinates[1] - ty) / scale)/width * META.ydim;
      var loc = "("+x.toFixed(1)+", "+y.toFixed(1)+")";
      d3.select("#mouse-location").text(loc);})
    .on("mouseenter", function () {
      d3.select("#mouse-location").classed("hidden", false);})
    .on("mouseleave", function () {
      d3.select("#mouse-location").classed("hidden", true);
    });

  d3.select("#slice-begin").on("input", handleSliceBegin).on("blur", function() {
    d3.select("#slice-begin").property("value", start);
  });
  d3.select("#slice-end").on("input", handleSliceEnd).on("blur", function() {
    d3.select("#slice-end").property("value", stop);
  });

  d3.select("#calcFlux-button").on("click", getFlux);
  d3.select("#findHotspots-button").on("click", getHotspots);
}

function handleSliceBegin() {
  console.log("this.value = ", this.value);
  console.log("typeof this.value = ", typeof this.value);
  console.log("Number(this.value) = ", Number(this.value));
  console.log("typeof Number(this.value) = ", typeof Number(this.value));
  begin = Number(this.value);
  if (isNaN(begin)) console.log("IS NAN!");
  if (begin < 0 || isNaN(begin)) {
    start = 0;
  } else if (begin >= stop) {
    start = stop-1;
  } else {
    start = begin;
  }
  console.log("start = ", start);
  console.log("stop = ", stop);
  d3.select("#slice-end").attr("min", start+1);
}

function handleSliceEnd(newVal) {
  console.log("this.value = ", this.value);
  end = Number(this.value);
  if (end >= META.frames || isNaN(end)) {
    stop = META.frames-1;
  } else if (end <= start) {
    stop = start+1;
  } else {
    stop = end;
  }
  console.log("start = ", start);
  console.log("stop = ", stop);
  d3.select("#slice-begin").attr("max", stop-1);
}

function renderFrame() {
  var data = currentFrame;
  d3.select("#title").text(currentIndex)

  var min = d3.min(data, function(row) {
    return d3.min(row)
  })
  var max = d3.max(data, function(row) {
    return d3.max(row)
  })
  console.log("min, max", min,max);

  canvas.width = width;
  canvas.height = height;
  var rw = width/ META.xdim
  var rh = height / META.ydim

  ctx.clearRect(0, 0, width, height)

  var colorScale = d3.scale.linear()
    .domain([min, max])
    .range(["#253494", "#ffffcc"])

  for(var j = 0; j < data.length; j++) {
    var row = data[j];
    for(var i = 0; i < row.length; i++) {
      var d = row[i];
      ctx.fillStyle = colorScale(d);
      ctx.fillRect(tx + i * rw * scale, ty + j * rh * scale, Math.ceil(rw * scale), Math.ceil(rh * scale))
    }
  }
  renderCurve();
}

function renderCurve() {
  curvectx.clearRect(0, 0, width, height)
  curvectx.strokeStyle = "rgba(240, 20, 20, 0.6)";
  curvectx.fillStyle = "rgba(240, 20, 20, 0.2)";

  curvectx.beginPath();
  //curvectx.moveTo(tx + pathX[0] * scale, ty + pathY[1] * scale);
  pathX.forEach(function(x, i) {
    var y = pathY[i];
    curvectx.lineTo(tx + x * scale, ty + y * scale)
    curvectx.stroke();
  });

  pathX.forEach(function(x, i) {
    var y = pathY[i];
    curvectx.beginPath();
    curvectx.arc(tx + x * scale, ty + y * scale, 3, 0, Math.PI*2)
    curvectx.fill();
  })
}

// when a file is selected (or dropped on the app) we process it
function handleFile(evt) {
  d3.select("#loading").classed("hidden", false)
  d3.select("#instructions").classed("hidden", true)
  evt.stopPropagation();
  evt.preventDefault();

  var files = this.files
  if(!files && evt.dataTransfer) files = evt.dataTransfer.files

  console.log("handled", files)
  if(!files[0]) return; // TODO: error

  var file = files[0];
  // we tell the server about the file
  // (but we don't actually process it in the client)
  ipc.send("load-file", {name: file.name, path: file.path})
  d3.select("title").text("Astroflow: " + file.name)
}

// this function gets called when the user drags a file over
function handleFileDrag(evt) {
  evt.stopPropagation();
  evt.preventDefault();
  evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
}

function getMetadata(callback) {
  d3.json(URL + "getMetadata", function(err, meta) {
    console.log("meta", meta)
    META.frames = meta.frames
    META.xdim = meta.xdim
    META.ydim = meta.ydim
    callback();
    renderFramesUI();
  })
}

function getFrame(i) {
  console.log("get frame", i)
  if(frameCache[i]) {
    currentFrame = frameCache[i].frame;
    currentIndex = i;
    renderFrame()
  } else {
    d3.json(URL + "getFrame?i=" + i, function(err, frame) {
      console.log("frame", frame)
      frameCache[i] = frame
      currentFrame = frame.frame;
      currentIndex = i;
      renderFrame()
    })
  }
}

function getAverage(callback) {
  d3.json(URL + "getAverage", function(err, frame) {
    console.log("frame", frame)
    average = frame.average
    currentFrame = average;
    currentIndex = "Average";
    renderFrame()
    callback(frame)
  })
}

function getFlux() {
  if(pathX.length >= 4 && pathY.length >= 4) { // Ensure a path has been collected
    var dataX = []
    var dataY = []
    pathX.forEach(function(x) { dataX.push(x/width * META.xdim)})
    pathY.forEach(function(y) { dataY.push(y/width * META.ydim)})
    var options = {
      uri: URL + "calcFlux",
      method: 'POST',
      json: { "beg": start, "end": stop, "path": [dataX, dataY]}
    };

    d3.select("#flux-button").text("LOADING Flux")
    request(options, function (error, response, body) {
      if (!error && response.statusCode == 200) {
      } else {
        console.log("error", error);
      }
      d3.select("#flux-button").text("Calculate Flux")
      // node convention is to allways put error as first argument, and pass null if no error
      // the body is the JSON payload we want
      //console.log("body = ", body);
      flux = body.flux;
      //console.log("flux = ", flux);
      renderFlux(start, stop);
    });
  }
}

function getHotspots() {
  if(pathX.length >= 4 && pathY.length >= 4) { // Ensure a path has been collected
    var dataX = []
    var dataY = []
    pathX.forEach(function(x) { dataX.push(x/width * META.xdim)})
    pathY.forEach(function(y) { dataY.push(y/width * META.ydim)})
    var options = {
      uri: URL + "findHotspots",
      method: 'POST',
      json: { "beg": start, "end": stop, "path": [dataX, dataY]}
    };

    d3.select("#hotspots-button").text("LOADING Hotspots")

    request(options, function (error, response, body) {
      if (!error && response.statusCode == 200) {
      } else {
        console.log("error", error);
      }
      // node convention is to allways put error as first argument, and pass null if no error
      // the body is the JSON payload we want
      d3.select("#hotspots-button").text("Find Hotspots")
      console.log("hotspots", body);
      hotspots = processHotspots(body);
      renderHotspots(start, stop);
    });
  }
}

function processHotspots(results) {
  var arrays = results.hotspots
  var n = arrays[0].length;
  var spots = [];
  for(var i = 0; i < n; i++) {
    var frame = arrays[0][i]
    var pointIndex = arrays[1][i];
    var spot = {
      frame: frame,
      point: {
        x: results.pathPts[0][pointIndex],
        y: results.pathPts[0][pointIndex],
      },
      slope: arrays[2][i],
      nzero: arrays[3][i],
      strength: arrays[4][i],
      confidence: arrays[5][i]
    }
    spots.push(spot)
  }
  return spots;
}

ipc.on("server-started", function() {
  console.log("server started!")
  getMetadata(function() {
    start = 0;
    stop = META.frames-1;
    d3.select("#slice-begin")
      .attr("value", start)
      .attr("max", META.frames-2);
    d3.select("#slice-end")
      .attr("value", stop)
      .attr("max", stop);
  });
  getAverage(function() {
    d3.select("#analysis").classed("hidden", false)
    d3.select("#frames").classed("hidden", false)
    d3.select("#loading").classed("hidden", true)
  });
  //getFrame(0)
});

ipc.on("test-event-response", function() {
  console.log("response:")
  console.log(arguments)
})
<commit_msg>bug with y value<commit_after>var path = require('path')
var ipc = require("electron").ipcRenderer
var request = require('request')
var d3 = require('d3')
var simplify = require('./simplify')

console.log("loaded")
ipc.on("server-ready", ready)

var URL = 'http://localhost:5000/';

var width = 600;
var height = 600;

var META = {};

// global state controling if we are drawing or not
var drawing;
var tx = 0;
var ty = 0;
var scale = 1;
// path related variables
var pathX = [];
var pathY = [];
var tanX = []
var tanY = [];
var flowX = []
var flowY = []
// we cache our frames and average globally
var frameCache = {};
var average;
var currentFrame;
var currentIndex = "Average";
var flux = []
var hotspots = [];

var canvas, ctx;
var curvectx;

// Global variable for slicing. Will be accessible to user and all functions should
// use them
var start = 0;
var stop = -1;

function ready() {
  // all of our UI code will begin executing here.
  // it's fine to define functions outside of this ready function,
  // but we don't want anything to happen until the server is good to go

  // wire up the file handling
  var inputElement = document.getElementById("new-file");
  inputElement.addEventListener("change", handleFile, false);
  // enable drag-and-drop of files onto the window
  var dropZone = document.body;
  dropZone.addEventListener('dragover', handleFileDrag, false);
  dropZone.addEventListener('drop', handleFile, false);

  canvas = d3.select("#frame").node();
  ctx = canvas.getContext('2d');
  canvas.width = width;
  canvas.height = height;

  var curvecanvas = d3.select("#curve").node();
  curvecanvas.width = width;
  curvecanvas.height = height;
  curvectx = curvecanvas.getContext('2d');

  d3.select("#draw-button").on("click", function() {
    drawing = !drawing;
    var button = d3.select(this)
      .classed("active", drawing)
      .text(function() {
        if(drawing) return "Drawing";
        return "Draw";
      })
    d3.select("#frame").classed("Drawing", drawing)
  })

  var zoom = d3.behavior.zoom()
    //.center([width/2, height/2])
    .scaleExtent([0.5, 20])
    .on("zoomstart", function() {
      if(drawing) {
        pathX = []
        pathY = []
      }
    })
    .on("zoom", function() {
      if(drawing) {
        var x = d3.event.sourceEvent.layerX - tx;
        var y = d3.event.sourceEvent.layerY - ty;
        pathX.push(x/scale)
        pathY.push(y/scale)
        renderCurve();
      } else {
        tx = d3.event.translate[0];
        ty = d3.event.translate[1];
        scale = d3.event.scale;
        renderFrame()
      }
    })
    .on("zoomend", function() {
      if(drawing) {
        //console.log("path", pathX, pathY)
        console.log("done drawing")
        drawing = false;

        d3.select("#draw-button")
          .classed("active", drawing)
          .text(function() {
            if(drawing) return "Drawing";
            return "Draw";
          })
        d3.select("#frame").classed("Drawing", drawing)

        var points = []
        pathX.forEach(function(x,i) {
          var y = pathY[i]
          points.push({x:x, y:y})
        })
        // the 2nd argument is a threshold, a value of 1 won't simplify
        // bigger number means more aggressive simplifying
        var simplified = simplify(points, 0.3)
        pathX = []
        pathY = []
        simplified.forEach(function(p) {
          pathX.push(p.x)
          pathY.push(p.y)
        })
        renderCurve();
        console.log("simplified", simplified)
        getFlux();
        getHotspots();
      }
    })

  d3.select("#frame").call(zoom)
    .on("mousemove", function () {
      coordinates = d3.mouse(this);
      var x = ((coordinates[0] - tx) / scale)/width * META.xdim;
      var y = ((coordinates[1] - ty) / scale)/width * META.ydim;
      var loc = "("+x.toFixed(1)+", "+y.toFixed(1)+")";
      d3.select("#mouse-location").text(loc);})
    .on("mouseenter", function () {
      d3.select("#mouse-location").classed("hidden", false);})
    .on("mouseleave", function () {
      d3.select("#mouse-location").classed("hidden", true);
    });

  d3.select("#slice-begin").on("input", handleSliceBegin).on("blur", function() {
    d3.select("#slice-begin").property("value", start);
  });
  d3.select("#slice-end").on("input", handleSliceEnd).on("blur", function() {
    d3.select("#slice-end").property("value", stop);
  });

  d3.select("#calcFlux-button").on("click", getFlux);
  d3.select("#findHotspots-button").on("click", getHotspots);
}

function handleSliceBegin() {
  console.log("this.value = ", this.value);
  console.log("typeof this.value = ", typeof this.value);
  console.log("Number(this.value) = ", Number(this.value));
  console.log("typeof Number(this.value) = ", typeof Number(this.value));
  begin = Number(this.value);
  if (isNaN(begin)) console.log("IS NAN!");
  if (begin < 0 || isNaN(begin)) {
    start = 0;
  } else if (begin >= stop) {
    start = stop-1;
  } else {
    start = begin;
  }
  console.log("start = ", start);
  console.log("stop = ", stop);
  d3.select("#slice-end").attr("min", start+1);
}

function handleSliceEnd(newVal) {
  console.log("this.value = ", this.value);
  end = Number(this.value);
  if (end >= META.frames || isNaN(end)) {
    stop = META.frames-1;
  } else if (end <= start) {
    stop = start+1;
  } else {
    stop = end;
  }
  console.log("start = ", start);
  console.log("stop = ", stop);
  d3.select("#slice-begin").attr("max", stop-1);
}

function renderFrame() {
  var data = currentFrame;
  d3.select("#title").text(currentIndex)

  var min = d3.min(data, function(row) {
    return d3.min(row)
  })
  var max = d3.max(data, function(row) {
    return d3.max(row)
  })
  console.log("min, max", min,max);

  canvas.width = width;
  canvas.height = height;
  var rw = width/ META.xdim
  var rh = height / META.ydim

  ctx.clearRect(0, 0, width, height)

  var colorScale = d3.scale.linear()
    .domain([min, max])
    .range(["#253494", "#ffffcc"])

  for(var j = 0; j < data.length; j++) {
    var row = data[j];
    for(var i = 0; i < row.length; i++) {
      var d = row[i];
      ctx.fillStyle = colorScale(d);
      ctx.fillRect(tx + i * rw * scale, ty + j * rh * scale, Math.ceil(rw * scale), Math.ceil(rh * scale))
    }
  }
  renderCurve();
}

function renderCurve() {
  curvectx.clearRect(0, 0, width, height)
  curvectx.strokeStyle = "rgba(240, 20, 20, 0.6)";
  curvectx.fillStyle = "rgba(240, 20, 20, 0.2)";

  curvectx.beginPath();
  //curvectx.moveTo(tx + pathX[0] * scale, ty + pathY[1] * scale);
  pathX.forEach(function(x, i) {
    var y = pathY[i];
    curvectx.lineTo(tx + x * scale, ty + y * scale)
    curvectx.stroke();
  });

  pathX.forEach(function(x, i) {
    var y = pathY[i];
    curvectx.beginPath();
    curvectx.arc(tx + x * scale, ty + y * scale, 3, 0, Math.PI*2)
    curvectx.fill();
  })
}

// when a file is selected (or dropped on the app) we process it
function handleFile(evt) {
  d3.select("#loading").classed("hidden", false)
  d3.select("#instructions").classed("hidden", true)
  evt.stopPropagation();
  evt.preventDefault();

  var files = this.files
  if(!files && evt.dataTransfer) files = evt.dataTransfer.files

  console.log("handled", files)
  if(!files[0]) return; // TODO: error

  var file = files[0];
  // we tell the server about the file
  // (but we don't actually process it in the client)
  ipc.send("load-file", {name: file.name, path: file.path})
  d3.select("title").text("Astroflow: " + file.name)
}

// this function gets called when the user drags a file over
function handleFileDrag(evt) {
  evt.stopPropagation();
  evt.preventDefault();
  evt.dataTransfer.dropEffect = 'copy'; // Explicitly show this is a copy.
}

function getMetadata(callback) {
  d3.json(URL + "getMetadata", function(err, meta) {
    console.log("meta", meta)
    META.frames = meta.frames
    META.xdim = meta.xdim
    META.ydim = meta.ydim
    callback();
    renderFramesUI();
  })
}

function getFrame(i) {
  console.log("get frame", i)
  if(frameCache[i]) {
    currentFrame = frameCache[i].frame;
    currentIndex = i;
    renderFrame()
  } else {
    d3.json(URL + "getFrame?i=" + i, function(err, frame) {
      console.log("frame", frame)
      frameCache[i] = frame
      currentFrame = frame.frame;
      currentIndex = i;
      renderFrame()
    })
  }
}

function getAverage(callback) {
  d3.json(URL + "getAverage", function(err, frame) {
    console.log("frame", frame)
    average = frame.average
    currentFrame = average;
    currentIndex = "Average";
    renderFrame()
    callback(frame)
  })
}

function getFlux() {
  if(pathX.length >= 4 && pathY.length >= 4) { // Ensure a path has been collected
    var dataX = []
    var dataY = []
    pathX.forEach(function(x) { dataX.push(x/width * META.xdim)})
    pathY.forEach(function(y) { dataY.push(y/width * META.ydim)})
    var options = {
      uri: URL + "calcFlux",
      method: 'POST',
      json: { "beg": start, "end": stop, "path": [dataX, dataY]}
    };

    d3.select("#flux-button").text("LOADING Flux")
    request(options, function (error, response, body) {
      if (!error && response.statusCode == 200) {
      } else {
        console.log("error", error);
      }
      d3.select("#flux-button").text("Calculate Flux")
      // node convention is to allways put error as first argument, and pass null if no error
      // the body is the JSON payload we want
      //console.log("body = ", body);
      flux = body.flux;
      //console.log("flux = ", flux);
      renderFlux(start, stop);
    });
  }
}

function getHotspots() {
  if(pathX.length >= 4 && pathY.length >= 4) { // Ensure a path has been collected
    var dataX = []
    var dataY = []
    pathX.forEach(function(x) { dataX.push(x/width * META.xdim)})
    pathY.forEach(function(y) { dataY.push(y/width * META.ydim)})
    var options = {
      uri: URL + "findHotspots",
      method: 'POST',
      json: { "beg": start, "end": stop, "path": [dataX, dataY]}
    };

    d3.select("#hotspots-button").text("LOADING Hotspots")

    request(options, function (error, response, body) {
      if (!error && response.statusCode == 200) {
      } else {
        console.log("error", error);
      }
      // node convention is to allways put error as first argument, and pass null if no error
      // the body is the JSON payload we want
      d3.select("#hotspots-button").text("Find Hotspots")
      console.log("hotspots", body);
      hotspots = processHotspots(body);
      renderHotspots(start, stop);
    });
  }
}

function processHotspots(results) {
  var arrays = results.hotspots
  var n = arrays[0].length;
  var spots = [];
  for(var i = 0; i < n; i++) {
    var frame = arrays[0][i]
    var pointIndex = arrays[1][i];
    var spot = {
      frame: frame,
      point: {
        x: results.pathPts[0][pointIndex],
        y: results.pathPts[1][pointIndex],
      },
      slope: arrays[2][i],
      nzero: arrays[3][i],
      strength: arrays[4][i],
      confidence: arrays[5][i]
    }
    spots.push(spot)
  }
  return spots;
}

ipc.on("server-started", function() {
  console.log("server started!")
  getMetadata(function() {
    start = 0;
    stop = META.frames-1;
    d3.select("#slice-begin")
      .attr("value", start)
      .attr("max", META.frames-2);
    d3.select("#slice-end")
      .attr("value", stop)
      .attr("max", stop);
  });
  getAverage(function() {
    d3.select("#analysis").classed("hidden", false)
    d3.select("#frames").classed("hidden", false)
    d3.select("#loading").classed("hidden", true)
  });
  //getFrame(0)
});

ipc.on("test-event-response", function() {
  console.log("response:")
  console.log(arguments)
})
<|endoftext|>


<commit_before>'use strict';

require('dotenv').load();

var assert = require('assert');
var PushQueue = require('../main.js');

describe('PushQueue', function(){
  describe('#post()', function(){
    it('should throw if JSON serializable things are not supplied', function(){
      [ 1234
      , 'some string'
      , null
      , function(){}
      ].forEach(function(badvalue){
        assert.throws(function(){
          PushQueue.post(badvalue);
        });
      });
    });

    it('should not throw if JSON serializable things are supplied', function(){
      ['{ "good": "strings" }'
      , {good: "object"}
      , ["strings", "in array"]
      , '["string", "array"]'
      ].forEach(function(goodvalue){
        assert.doesNotThrow(function(){
          PushQueue.post(goodvalue);
        });
      });
    });

    it('should publish the values to the SQS queue', function(done){
     assert.doesNotThrow(function(){
        PushQueue.post({test: "things"})
            .then(function(data){
              console.log(data);
              done();
            });
        });
     });

  });
});
<commit_msg>pending test marked<commit_after>'use strict';

require('dotenv').load();

var assert = require('assert');
var expect = require('expect');
var PushQueue = require('../main.js');

describe('PushQueue', function(){
  describe('#post()', function(){
    it('should throw if JSON serializable things are not supplied', function(){
      [ 1234
      , 'some string'
      , null
      , function(){}
      ].forEach(function(badvalue){
        assert.throws(function(){
          PushQueue.post(badvalue);
        });
      });
    });

    it('should not throw if JSON serializable things are supplied', function(){
      ['{ "good": "strings" }'
      , {good: "object"}
      , ["strings", "in array"]
      , '["string", "array"]'
      ].forEach(function(goodvalue){
        assert.doesNotThrow(function(){
          PushQueue.post(goodvalue);
        });
      });
    });

    // Pending test

    //it('should publish the values to the SQS queue', function(done){
    // assert.doesNotThrow(function(){
    //    PushQueue.post({test: "things"})
    //        .then(function(data){
    //          expect(data)
    //          done();
    //        });
    //    });
    // });

  });
});
<|endoftext|>


<commit_before>const fs = require('fs');
const path = require('path');
var config = require('config');
var request = require('request');
var progress = require('request-progress');
var rimraf = require('rimraf');
var logger = require('winston');

var emby = require('./emby');

const rootFolder = '/movies/';
const imageFolder = 'Images'
const expectedImages = ['fanart.jpg', 'landscape.jpg', 'logo.png', 'poster.jpg'];
const expectedMovieExtension = ['.mkv', '.mp4'];
const expectedSubtitleExtension = '.srt';

exports.folderExists = function folderExists(folder) {
    logger.debug("Looking for folder '%s'", folder);
    return fs.existsSync(path.join(rootFolder, folder));
}

exports.fileExists = function fileExists(filePath) {
    return fs.existsSync(filePath);
}

exports.missingFiles = function missingFiles(folder) {
    logger.debug("Looking for missing files in folder '%s'", folder);
    var missing = [];

    if (!fs.existsSync(path.join(rootFolder, folder, folder + expectedSubtitleExtension))) {
        missing.push('subtitle');
    }

    var movieExists = false;

    for (var extension of expectedMovieExtension) {
        if (fs.existsSync(path.join(rootFolder, folder, folder + extension))) {
            movieExists = true;
        }
    }

    if (!movieExists) {
        missing.push('movie');
    }

    for (var image of expectedImages) {
        if (!fs.existsSync(path.join(rootFolder, folder, imageFolder, image))) {
            missing.push(image);
        }
    }

    logger.debug("Missing files found: %j", missing);

    return missing;
}

exports.getBaseName = function getBaseName(movie) {
    let name = `${movie.Name} (${movie.ProductionYear})`;
    name = name.replace(':', ' -');
    return name;
}

exports.getExpectedFolders = function getExpectedFolders(playlist) {
    logger.debug("Getting expected folders for plalist");
    let expected = [];
    for (let movie of playlist) {
        expected.push(this.getBaseName(movie));
    }

    logger.debug("Expected folders: %j", expected);
    return expected;
}

exports.getActualFolders = function getActualFolders() {
    return getFolders(config.get('cinema.movie-folder'));
}

exports.getExtraFolders = function getExtraFolders(playlist) {
    logger.debug("Getting folders not in playlist");
    let expectedFolders = exports.getExpectedFolders(playlist);
    let actualFolders = exports.getActualFolders();
    let extraFolders = [];

    for (let actualFolder of actualFolders) {
        if (expectedFolders.indexOf(actualFolder) === -1) {
            extraFolders.push(actualFolder);
        }
    }

    logger.debug("Extra folders found: %j");
    return extraFolders;
}

exports.deleteExtraFolders = function deleteExtraFolders(playlist) {
    logger.debug("Deleting extra folders");
    let foldersToDelete = exports.getExtraFolders(playlist);
    logger.debug("Extra folders to delete: %j", foldersToDelete);

    for (let folder of foldersToDelete) {
        let folderToDelete = path.join(config.get('cinema.movie-folder'), folder);
        rimraf.sync(folderToDelete);
    }
}

exports.getMovieFilePath = function getMovieFilePath(movie) {
    let baseName = exports.getBaseName(movie);
    let extension = movie.Container;
    let fileName = baseName + '.' + extension;
    let basePath = path.join(config.get('cinema.movie-folder'), baseName);
    let filePath = path.join(basePath, fileName);

    return filePath;
}

exports.getMovieImagePath = function getMovieImagePath(movie) {
    let baseName = exports.getBaseName(movie);
    return path.join(config.get('cinema.movie-folder'), baseName, imageFolder);
}

exports.downloadMissingFiles = function downloadMissingFiles(playlist) {
    for (let movie of playlist) {
        createFolderStructure(movie);
    }
}

exports.downloadMovieFiles = function downloadMovieFiles(movie) {
    createFolderStructure(movie);
    downloadImages(movie);
    downloadMovie(movie);
}

exports.downloadImages = function downloadImages(movie) {
    let baseName = exports.getBaseName(movie);
    let basePath = path.join(config.get('cinema.movie-folder'), baseName, imageFolder);
    let images = emby.getImages(movie);
    for (let image of images) {
        let filePath = path.join(basePath, image.filename);
        let url = emby.getImageUrl(movie, image.type);
        if (exports.fileExists(filePath)) {
            let urlSize = exports.getUrlFileSize(url);
            // TODO: Check actual filesize and download again if different
            logger.info("Image '%s' already exists", image.filename);
        } else {
            exports.downloadFile(url, path.join(basePath, image.filename));
        }
    }
}

exports.downloadMovie = function downloadMovie(movie) {
    let baseName = exports.getBaseName(movie);
    let extension = movie.Container;
    let fileName = baseName + '.' + extension;
    let basePath = path.join(config.get('cinema.movie-folder'), baseName);
    let filePath = path.join(basePath, fileName);
    let url = emby.getMovieUrl(movie);

    if (exports.fileExists(filePath)) {
        let urlSize = exports.getUrlFileSize(url);
        // TODO: Check actual filesize and download again if different
        logger.info("Movie '%s' alredy exists", fileName);
    } else {
        exports.downloadFile(url, path.join(basePath, baseName + '.' + extension));
    }
}

function createFolder(dir) {
    if (!fs.existsSync(dir)){
        fs.mkdirSync(dir);
    }
}

exports.createFolderStructure = function createFolderStructure(movie) {
    logger.debug("Creating folder structure");
    var baseName = exports.getBaseName(movie);
    var basePath = path.join(config.get('cinema.movie-folder'), baseName);
    createFolder(basePath);
    createFolder(path.join(basePath, 'Images'));
}

function getFolders(dir) {
    let files = fs.readdirSync(dir);
    let folders = [];
    for (let file of files) {
        if (fs.statSync(path.join(dir, file)).isDirectory()) {
            folders.push(file);
        }
    }

    return folders;
}

function byteToString(bytes) {
    if (bytes >= 1048576) {
        return Math.round(bytes / 1048576 * 10) / 10 + ' MiB';
    } else if (bytes >= 1024) {
        return Math.round(bytes / 1024) + ' KiB';
    } else {
        return bytes + ' B';
    }
}

function secondsToString(seconds) {
    if (seconds >= 60) {
        return Math.round(seconds / 60) + ' minutes';
    } else {
        return Math.round(seconds) + ' seconds';
    }
}

exports.getUrlFileSize = function getUrlFileSize(url) {
    var r = request.get(url)
    .on('response', function handleResponse(response) {
        r.abort();
        return Number(response.headers['content-length']) || null;
    });
}

exports.downloadFile = function downloadFile(url, fileName) {
    logger.info("'%s' download started", path.basename(fileName));
    progress(request(url), {
        throttle: 2000,                    // Throttle the progress event to 2000ms, defaults to 1000ms
        delay: 1000,                       // Only start to emit after 1000ms delay, defaults to 0ms
        // lengthHeader: 'x-transfer-length'  // Length header to use, defaults to content-length
    })
    .on('progress', function (state) {
        // The state is an object that looks like this:
        // {
        //     percent: 0.5,               // Overall percent (between 0 to 1)
        //     speed: 554732,              // The download speed in bytes/sec
        //     size: {
        //         total: 90044871,        // The total payload size in bytes
        //         transferred: 27610959   // The transferred payload size in bytes
        //     },
        //     time: {
        //         elapsed: 36.235,        // The total elapsed seconds since the start (3 decimals)
        //         remaining: 81.403       // The remaining seconds to finish (3 decimals)
        //     }
        // }
        let percent = Math.round(state.percent * 100);

        logger.info('%s: %d%% %s/%s (%s/s) ETA: %s',
            path.basename(fileName), percent, byteToString(state.size.transferred), byteToString(state.size.total), byteToString(state.speed), secondsToString(state.time.remaining));
    })
    .on('error', function (err) {
        logger.error("Failed to download file '%s': %s", fileName, err);
        fs.unlinkSync(fileName);
    })
    .on('end', function () {
        logger.info("'%s' finished downloading", path.basename(fileName));
    })
    .pipe(fs.createWriteStream(fileName));
}
<commit_msg>Correct function calls<commit_after>const fs = require('fs');
const path = require('path');
var config = require('config');
var request = require('request');
var progress = require('request-progress');
var rimraf = require('rimraf');
var logger = require('winston');

var emby = require('./emby');

const rootFolder = '/movies/';
const imageFolder = 'Images'
const expectedImages = ['fanart.jpg', 'landscape.jpg', 'logo.png', 'poster.jpg'];
const expectedMovieExtension = ['.mkv', '.mp4'];
const expectedSubtitleExtension = '.srt';

exports.folderExists = function folderExists(folder) {
    logger.debug("Looking for folder '%s'", folder);
    return fs.existsSync(path.join(rootFolder, folder));
}

exports.fileExists = function fileExists(filePath) {
    return fs.existsSync(filePath);
}

exports.missingFiles = function missingFiles(folder) {
    logger.debug("Looking for missing files in folder '%s'", folder);
    var missing = [];

    if (!fs.existsSync(path.join(rootFolder, folder, folder + expectedSubtitleExtension))) {
        missing.push('subtitle');
    }

    var movieExists = false;

    for (var extension of expectedMovieExtension) {
        if (fs.existsSync(path.join(rootFolder, folder, folder + extension))) {
            movieExists = true;
        }
    }

    if (!movieExists) {
        missing.push('movie');
    }

    for (var image of expectedImages) {
        if (!fs.existsSync(path.join(rootFolder, folder, imageFolder, image))) {
            missing.push(image);
        }
    }

    logger.debug("Missing files found: %j", missing);

    return missing;
}

exports.getBaseName = function getBaseName(movie) {
    let name = `${movie.Name} (${movie.ProductionYear})`;
    name = name.replace(':', ' -');
    return name;
}

exports.getExpectedFolders = function getExpectedFolders(playlist) {
    logger.debug("Getting expected folders for plalist");
    let expected = [];
    for (let movie of playlist) {
        expected.push(this.getBaseName(movie));
    }

    logger.debug("Expected folders: %j", expected);
    return expected;
}

exports.getActualFolders = function getActualFolders() {
    return getFolders(config.get('cinema.movie-folder'));
}

exports.getExtraFolders = function getExtraFolders(playlist) {
    logger.debug("Getting folders not in playlist");
    let expectedFolders = exports.getExpectedFolders(playlist);
    let actualFolders = exports.getActualFolders();
    let extraFolders = [];

    for (let actualFolder of actualFolders) {
        if (expectedFolders.indexOf(actualFolder) === -1) {
            extraFolders.push(actualFolder);
        }
    }

    logger.debug("Extra folders found: %j");
    return extraFolders;
}

exports.deleteExtraFolders = function deleteExtraFolders(playlist) {
    logger.debug("Deleting extra folders");
    let foldersToDelete = exports.getExtraFolders(playlist);
    logger.debug("Extra folders to delete: %j", foldersToDelete);

    for (let folder of foldersToDelete) {
        let folderToDelete = path.join(config.get('cinema.movie-folder'), folder);
        rimraf.sync(folderToDelete);
    }
}

exports.getMovieFilePath = function getMovieFilePath(movie) {
    let baseName = exports.getBaseName(movie);
    let extension = movie.Container;
    let fileName = baseName + '.' + extension;
    let basePath = path.join(config.get('cinema.movie-folder'), baseName);
    let filePath = path.join(basePath, fileName);

    return filePath;
}

exports.getMovieImagePath = function getMovieImagePath(movie) {
    let baseName = exports.getBaseName(movie);
    return path.join(config.get('cinema.movie-folder'), baseName, imageFolder);
}

exports.downloadMissingFiles = function downloadMissingFiles(playlist) {
    for (let movie of playlist) {
        createFolderStructure(movie);
    }
}

exports.downloadMovieFiles = function downloadMovieFiles(movie) {
    exports.createFolderStructure(movie);
    exports.downloadImages(movie);
    exports.downloadMovie(movie);
}

exports.downloadImages = function downloadImages(movie) {
    let baseName = exports.getBaseName(movie);
    let basePath = path.join(config.get('cinema.movie-folder'), baseName, imageFolder);
    let images = emby.getImages(movie);
    for (let image of images) {
        let filePath = path.join(basePath, image.filename);
        let url = emby.getImageUrl(movie, image.type);
        if (exports.fileExists(filePath)) {
            let urlSize = exports.getUrlFileSize(url);
            // TODO: Check actual filesize and download again if different
            logger.info("Image '%s' already exists", image.filename);
        } else {
            exports.downloadFile(url, path.join(basePath, image.filename));
        }
    }
}

exports.downloadMovie = function downloadMovie(movie) {
    let baseName = exports.getBaseName(movie);
    let extension = movie.Container;
    let fileName = baseName + '.' + extension;
    let basePath = path.join(config.get('cinema.movie-folder'), baseName);
    let filePath = path.join(basePath, fileName);
    let url = emby.getMovieUrl(movie);

    if (exports.fileExists(filePath)) {
        let urlSize = exports.getUrlFileSize(url);
        // TODO: Check actual filesize and download again if different
        logger.info("Movie '%s' alredy exists", fileName);
    } else {
        exports.downloadFile(url, path.join(basePath, baseName + '.' + extension));
    }
}

function createFolder(dir) {
    if (!fs.existsSync(dir)){
        fs.mkdirSync(dir);
    }
}

exports.createFolderStructure = function createFolderStructure(movie) {
    logger.debug("Creating folder structure");
    var baseName = exports.getBaseName(movie);
    var basePath = path.join(config.get('cinema.movie-folder'), baseName);
    createFolder(basePath);
    createFolder(path.join(basePath, 'Images'));
}

function getFolders(dir) {
    let files = fs.readdirSync(dir);
    let folders = [];
    for (let file of files) {
        if (fs.statSync(path.join(dir, file)).isDirectory()) {
            folders.push(file);
        }
    }

    return folders;
}

function byteToString(bytes) {
    if (bytes >= 1048576) {
        return Math.round(bytes / 1048576 * 10) / 10 + ' MiB';
    } else if (bytes >= 1024) {
        return Math.round(bytes / 1024) + ' KiB';
    } else {
        return bytes + ' B';
    }
}

function secondsToString(seconds) {
    if (seconds >= 60) {
        return Math.round(seconds / 60) + ' minutes';
    } else {
        return Math.round(seconds) + ' seconds';
    }
}

exports.getUrlFileSize = function getUrlFileSize(url) {
    var r = request.get(url)
    .on('response', function handleResponse(response) {
        r.abort();
        return Number(response.headers['content-length']) || null;
    });
}

exports.downloadFile = function downloadFile(url, fileName) {
    logger.info("'%s' download started", path.basename(fileName));
    progress(request(url), {
        throttle: 2000,                    // Throttle the progress event to 2000ms, defaults to 1000ms
        delay: 1000,                       // Only start to emit after 1000ms delay, defaults to 0ms
        // lengthHeader: 'x-transfer-length'  // Length header to use, defaults to content-length
    })
    .on('progress', function (state) {
        // The state is an object that looks like this:
        // {
        //     percent: 0.5,               // Overall percent (between 0 to 1)
        //     speed: 554732,              // The download speed in bytes/sec
        //     size: {
        //         total: 90044871,        // The total payload size in bytes
        //         transferred: 27610959   // The transferred payload size in bytes
        //     },
        //     time: {
        //         elapsed: 36.235,        // The total elapsed seconds since the start (3 decimals)
        //         remaining: 81.403       // The remaining seconds to finish (3 decimals)
        //     }
        // }
        let percent = Math.round(state.percent * 100);

        logger.info('%s: %d%% %s/%s (%s/s) ETA: %s',
            path.basename(fileName), percent, byteToString(state.size.transferred), byteToString(state.size.total), byteToString(state.speed), secondsToString(state.time.remaining));
    })
    .on('error', function (err) {
        logger.error("Failed to download file '%s': %s", fileName, err);
        fs.unlinkSync(fileName);
    })
    .on('end', function () {
        logger.info("'%s' finished downloading", path.basename(fileName));
    })
    .pipe(fs.createWriteStream(fileName));
}
<|endoftext|>


<commit_before>#!/usr/bin/env node

const path = require('path')
const {execSync} = require('child_process')

const args = process.argv.slice(3)
const file = path.join(__dirname, `ozy-${process.argv[2]}`)
let command = `${file} ${args.join(' ')}`

if (process.env.NODE_ENV !== 'production') {
  command = `env $(cat .env | xargs) ${command}`
}

try {
  execSync(command, {stdio: 'inherit'})
} catch (error) {
  process.exit(1)
}
<commit_msg>No .env in test.<commit_after>#!/usr/bin/env node

const path = require('path')
const {execSync} = require('child_process')

const args = process.argv.slice(3)
const file = path.join(__dirname, `ozy-${process.argv[2]}`)
let command = `${file} ${args.join(' ')}`

switch (process.env.NODE_ENV) {
  case 'production':
    break

  case 'test':
    break

  default:
    command = `env $(cat .env | xargs) ${command}`
    break
}

try {
  execSync(command, {stdio: 'inherit'})
} catch (error) {
  process.exit(1)
}
<|endoftext|>


<commit_before>//DOM Elements with sound
var all_sounds = document.querySelectorAll('audio');

for (var i = 0; i < all_sounds.length; i++) {
	all_sounds[i].addEventListener("canplaythrough", loadedSounds, false);
}

var loaded=0;
var percent=0;
function loadedSounds(e) {
	loaded++; // Increment loaded counter to check if all sounds can be played
	percent = Math.floor(100 * loaded / all_sounds.length); // Calculate percentage
	document.querySelector('.load_status').innerText = percent+"%"; // Set textual percentage to load status
	document.querySelector('.load_fill').style.width= percent+"%";

	//console.log(percent);
	if (loaded == all_sounds.length) {
		//alert('Loaded!');
		setTimeout(fadeOutLoader, 1000);
	}

	function fadeOutLoader() {
		var fadeTarget = document.getElementById("load_screen");
		fadeTarget.style.opacity = 0;
		setTimeout(function(){	// Remove node
			document.querySelector('body').removeChild(fadeTarget);
		},2000);
	}
}

// DOM Elements for clock control
var hours = document.querySelector('.hours');
var minutes = document.querySelector('.minutes');
var seconds = document.querySelector('.seconds');
var separator = document.querySelector('.separator');

// DOM Elements that control play/stop sounds
var play_btn = document.querySelectorAll('.play');

// Adding listeners to every play/stop button
for (var i = 0; i < play_btn.length; i++) {
	play_btn[i].addEventListener("click", playSound, false);
}

// DOM elements that controll sound volume
var volume_control=document.querySelectorAll('.volume_bar');

// Adding listeners to every volume control slider
for (var i = 0; i < volume_control.length; i++) {
	volume_control[i].addEventListener("input", volumeSound, false);
	volume_control[i].style.opacity=0;
}

// DOM element that mutes and unmutes the page
var mute_btn = document.querySelector(".mute_btn a");
var is_muted = false;
mute_btn.addEventListener('click', muteDocument, false);

// DOM element that resets the sounds
var reset_btn = document.querySelector(".reset_btn a");
reset_btn.addEventListener('click', resetSounds, false);

// Controlling stoping and playing the sound
function playSound(e){
	if (is_muted) {
		muteDocument();
	}
	var targetElement = e.target || e.srcElement;
	var selectedSound = targetElement.parentElement.parentElement.querySelector('audio');
	var volumeControler = targetElement.parentElement.parentElement.querySelector('.volume_bar');
	var soundImage = targetElement.parentElement.parentElement.querySelector('img');

	if(selectedSound.paused){
		volumeControler.style.opacity=1;
		selectedSound.loop=true;
		if (volumeControler.value==0) {
			volumeControler.value=0.1;
		}
		selectedSound.volume = volumeControler.value;
		selectedSound.play();
		soundImage.classList.add("playing");
	}
	else{
		volumeControler.style.opacity=0;
		selectedSound.pause();
		selectedSound.currentTime = 0;
		volumeControler.value=0;
		soundImage.classList.remove("playing");
	}
	console.log(event.target.type);
	console.log(selectedSound);
}

// Controlling volume of the sounds
function volumeSound(e){
	if (is_muted) {
		muteDocument();
	}
	var targetElement = e.target || e.srcElement;
	var vol = targetElement.value;
	var selectedSound = targetElement.parentElement.querySelector('audio');
	selectedSound.volume = vol;
}

function clock() {
	var days = ["SUN","MON","TUE","WED","THU","FRI","SAT"];
	var months = ["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"];
	const now = new Date();
	// if (now.getSeconds()==0 || now.getMinutes==0) {
	// 	separator.classList.add("blink");
	// }
	hours.innerText = now.getHours()<10?"0"+now.getHours():now.getHours();
	minutes.innerText = now.getMinutes()<10?"0"+now.getMinutes():now.getMinutes();
	// seconds.innerText = now.getSeconds()<10?"0"+now.getSeconds():now.getSeconds();
}
clock();
var interval = setInterval(clock,1000);

var playing_sounds = [];
function muteDocument() {
	if (!is_muted) {
		playing_sounds.length=0;
		is_muted = true;
		document.querySelector('.unmuted').style.display="none";
		document.querySelector('.muted').style.display="inline";
		var all_audio = document.querySelectorAll('audio');
		for (var i = 0; i < all_audio.length; i++) {
			if(!all_audio[i].paused){
				playing_sounds.push([all_audio[i],all_audio[i].volume]);
			}
		}
		playing_sounds.forEach(function (sound) {
			sound[0].volume=0;
		});
	}
	else{
		is_muted = false;
		document.querySelector('.unmuted').style.display="inline";
		document.querySelector('.muted').style.display="none";
		playing_sounds.forEach(function (sound) {
			sound[0].volume=sound[1];
		});
	}
}

function resetSounds() {
	var all_audio = document.querySelectorAll('audio');
	for (var i = 0; i < all_audio.length; i++) {
		all_audio[i].pause();
		all_audio[i].currentTime = 0;
		all_audio[i].value=0;
	}
	var all_play_btns = document.querySelectorAll('.start_btn img');
	for (var i = 0; i < all_play_btns.length; i++) {
		all_play_btns[i].classList.remove("playing");
	}
	var all_volume_control = document.querySelectorAll('.volume_bar');
	for (var i = 0; i < all_volume_control.length; i++) {
		all_volume_control[i].value=0;
		all_volume_control[i].style.opacity=0;
	}
}
<commit_msg>Remove listeners after loading is done<commit_after>//DOM Elements with sound
var all_sounds = document.querySelectorAll('audio');

for (var i = 0; i < all_sounds.length; i++) {
	all_sounds[i].addEventListener("canplaythrough", loadedSounds, false);
}

var loaded=0;
var percent=0;
function loadedSounds(e) {
	loaded++; // Increment loaded counter to check if all sounds can be played
	percent = Math.floor(100 * loaded / all_sounds.length); // Calculate percentage
	document.querySelector('.load_status').innerText = percent+"%"; // Set textual percentage to load status
	document.querySelector('.load_fill').style.width= percent+"%";

	//console.log(percent);
	if (loaded == all_sounds.length) {
		//alert('Loaded!');
		for (var i = 0; i < all_sounds.length; i++) {
			all_sounds[i].removeEventListener("canplaythrough", loadedSounds);
		}
		setTimeout(fadeOutLoader, 1000);
	}

	function fadeOutLoader() {
		var fadeTarget = document.getElementById("load_screen");
		fadeTarget.style.opacity = 0;
		setTimeout(function(){	// Remove node
			document.querySelector('body').removeChild(fadeTarget);
		},2000);
	}
}

// DOM Elements for clock control
var hours = document.querySelector('.hours');
var minutes = document.querySelector('.minutes');
var seconds = document.querySelector('.seconds');
var separator = document.querySelector('.separator');

// DOM Elements that control play/stop sounds
var play_btn = document.querySelectorAll('.play');

// Adding listeners to every play/stop button
for (var i = 0; i < play_btn.length; i++) {
	play_btn[i].addEventListener("click", playSound, false);
}

// DOM elements that controll sound volume
var volume_control=document.querySelectorAll('.volume_bar');

// Adding listeners to every volume control slider
for (var i = 0; i < volume_control.length; i++) {
	volume_control[i].addEventListener("input", volumeSound, false);
	volume_control[i].style.opacity=0;
}

// DOM element that mutes and unmutes the page
var mute_btn = document.querySelector(".mute_btn a");
var is_muted = false;
mute_btn.addEventListener('click', muteDocument, false);

// DOM element that resets the sounds
var reset_btn = document.querySelector(".reset_btn a");
reset_btn.addEventListener('click', resetSounds, false);

// Controlling stoping and playing the sound
function playSound(e){
	if (is_muted) {
		muteDocument();
	}
	var targetElement = e.target || e.srcElement;
	var selectedSound = targetElement.parentElement.parentElement.querySelector('audio');
	var volumeControler = targetElement.parentElement.parentElement.querySelector('.volume_bar');
	var soundImage = targetElement.parentElement.parentElement.querySelector('img');

	if(selectedSound.paused){
		volumeControler.style.opacity=1;
		selectedSound.loop=true;
		if (volumeControler.value==0) {
			volumeControler.value=0.1;
		}
		selectedSound.volume = volumeControler.value;
		selectedSound.play();
		soundImage.classList.add("playing");
	}
	else{
		volumeControler.style.opacity=0;
		selectedSound.pause();
		selectedSound.currentTime = 0;
		volumeControler.value=0;
		soundImage.classList.remove("playing");
	}
	console.log(event.target.type);
	console.log(selectedSound);
}

// Controlling volume of the sounds
function volumeSound(e){
	if (is_muted) {
		muteDocument();
	}
	var targetElement = e.target || e.srcElement;
	var vol = targetElement.value;
	var selectedSound = targetElement.parentElement.querySelector('audio');
	selectedSound.volume = vol;
}

function clock() {
	var days = ["SUN","MON","TUE","WED","THU","FRI","SAT"];
	var months = ["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"];
	const now = new Date();
	// if (now.getSeconds()==0 || now.getMinutes==0) {
	// 	separator.classList.add("blink");
	// }
	hours.innerText = now.getHours()<10?"0"+now.getHours():now.getHours();
	minutes.innerText = now.getMinutes()<10?"0"+now.getMinutes():now.getMinutes();
	// seconds.innerText = now.getSeconds()<10?"0"+now.getSeconds():now.getSeconds();
}
clock();
var interval = setInterval(clock,1000);

var playing_sounds = [];
function muteDocument() {
	if (!is_muted) {
		playing_sounds.length=0;
		is_muted = true;
		document.querySelector('.unmuted').style.display="none";
		document.querySelector('.muted').style.display="inline";
		var all_audio = document.querySelectorAll('audio');
		for (var i = 0; i < all_audio.length; i++) {
			if(!all_audio[i].paused){
				playing_sounds.push([all_audio[i],all_audio[i].volume]);
			}
		}
		playing_sounds.forEach(function (sound) {
			sound[0].volume=0;
		});
	}
	else{
		is_muted = false;
		document.querySelector('.unmuted').style.display="inline";
		document.querySelector('.muted').style.display="none";
		playing_sounds.forEach(function (sound) {
			sound[0].volume=sound[1];
		});
	}
}

function resetSounds() {
	var all_audio = document.querySelectorAll('audio');
	for (var i = 0; i < all_audio.length; i++) {
		all_audio[i].pause();
		all_audio[i].currentTime = 0;
		all_audio[i].value=0;
	}
	var all_play_btns = document.querySelectorAll('.start_btn img');
	for (var i = 0; i < all_play_btns.length; i++) {
		all_play_btns[i].classList.remove("playing");
	}
	var all_volume_control = document.querySelectorAll('.volume_bar');
	for (var i = 0; i < all_volume_control.length; i++) {
		all_volume_control[i].value=0;
		all_volume_control[i].style.opacity=0;
	}
}
<|endoftext|>


<commit_before>(function(){
  'use strict';

  var should = require("chai").should();
  var codes = require("../dist-node/index.js");

  describe('switzerland-postal-code', function(){
    it("should return a location", function(){
      var cologny = codes['1223'];
      cologny.should.equal('Cologny');
    });

    it("should return a composed location", function(){
      var cologny = codes['1295'];
      cologny.should.equal('Mies - Tannay');
    });

    it("should contains at least 2500 items", function(){
      var enoughLocation = Object.keys(codes).length > 2500;
      enoughLocation.should.equal(true);
    });
  });
})();
<commit_msg>update unit tests<commit_after>(function(){
  'use strict';

  var should = require("chai").should();
  var codes = require("../dist-node/index.js");

  describe('switzerland-postal-code', function(){
    it("should return a location", function(){
      var cologny = codes['1223'];
      cologny.should.equal('Cologny');
    });

    it("should return a composed location", function(){
      var miesTannay = codes['1295'];
      miesTannay.should.equal('Mies - Tannay');
    });

    it("should contains at least 3000 items", function(){
      var enoughLocation = Object.keys(codes).length > 3000;
      enoughLocation.should.equal(true);
    });
  });
})();
<|endoftext|>