<commit_before>"use strict";

function setUserAgent() {
    document.getElementById("agent").innerHTML = navigator.userAgent;
}

function loginUser() {
    document.location.replace("loop://login?userId=pedro@loopsoftware.fr");
}

function logoutUser() {
    document.location.replace("loop://logout?userId=pedro@loopsoftware.fr");
}

function authoriseUser() {
    document.location.replace("loop://authorisation");
}

function handleAuthorisation(success) {
    alert("fingerprint scan: " + success);
}

function handleNotification(notification) {
    alert(notification.subject + ": " + notification.body);
}

function getCamera() {
    // navigator.mediaDevices.getUserMedia({ video: true })
    //     .then(gotMedia)
    //     .catch(error => console.error('getUserMedia() error:', error));
    document.location.replace("loop://camera");
}

function gotMedia(mediaStream) {
    const mediaStreamTrack = mediaStream.getVideoTracks()[0];
    const imageCapture = new ImageCapture(mediaStreamTrack);
    imageCapture.takePhoto()
        .then(blob => createImageBitmap(blob))
        .then(imageBitmap => {
            const canvas = document.querySelector("#photoCanvas");
            drawCanvas(canvas, imageBitmap);
        })
        .catch(error => console.error("gotMedia() error: ", error));
    console.log(imageCapture);
}

function showPhoto(imgBase64) {
    // const canvas = document.querySelector("#photoCanvas");
    // const context = canvas.getContext("2d");

    // const image = new Image();
    // image.onload = () => {
    //     context.drawImage(image, 0, 0);
    // };

    // image.src = imgBase64;

    const imgElement = document.getElementById("image").src = imgBase64;
}

function drawCanvas(canvas, img) {
    canvas.width = getComputedStyle(canvas).width.split('px')[0];
    canvas.height = getComputedStyle(canvas).height.split('px')[0];
    let ratio = Math.min(canvas.width / img.width, canvas.height / img.height);
    let x = (canvas.width - img.width * ratio) / 2;
    let y = (canvas.height - img.height * ratio) / 2;
    canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height);
    canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height, x, y, img.width * ratio, img.height * ratio);
}

function handleFileSelect(evt) {
    const files = evt.target.files; // FileList object

    // files is a FileList of File objects. List some properties.
    const output = [];
    for (let i = 0, f; f = files[i]; i++) {
        output.push('
', escape(f.name), ' (', f.type || 'n/a', ')
',
            f.size, ' bytes
last modified: ',
            f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a',
            `<br/><img id="${escape(f.name)}" src="" alt="${escape(f.name)}" style="width:200px"/><br/>`,
            '
');
    }
    document.getElementById('list').innerHTML = '
' + output.join('') + '
';

    Array.from(files).forEach(file => {
        const reader = new FileReader();
        reader.onload = event => {
            document.getElementById(escape(file.name)).src = event.target.result;
        };
        reader.readAsDataURL(file);
    });
}

document.getElementById('files').addEventListener('change', handleFileSelect, false);
<commit_msg>show image is not show photo<commit_after>"use strict";

function setUserAgent() {
    document.getElementById("agent").innerHTML = navigator.userAgent;
}

function loginUser() {
    document.location.replace("loop://login?userId=pedro@loopsoftware.fr");
}

function logoutUser() {
    document.location.replace("loop://logout?userId=pedro@loopsoftware.fr");
}

function authoriseUser() {
    document.location.replace("loop://authorisation");
}

function handleAuthorisation(success) {
    alert("fingerprint scan: " + success);
}

function handleNotification(notification) {
    alert(notification.subject + ": " + notification.body);
}

function getCamera() {
    // navigator.mediaDevices.getUserMedia({ video: true })
    //     .then(gotMedia)
    //     .catch(error => console.error('getUserMedia() error:', error));
    document.location.replace("loop://camera");
}

function gotMedia(mediaStream) {
    const mediaStreamTrack = mediaStream.getVideoTracks()[0];
    const imageCapture = new ImageCapture(mediaStreamTrack);
    imageCapture.takePhoto()
        .then(blob => createImageBitmap(blob))
        .then(imageBitmap => {
            const canvas = document.querySelector("#photoCanvas");
            drawCanvas(canvas, imageBitmap);
        })
        .catch(error => console.error("gotMedia() error: ", error));
    console.log(imageCapture);
}

function showPhoto(imgBase64) {
    const canvas = document.querySelector("#photoCanvas");
    const context = canvas.getContext("2d");

    const image = new Image();
    image.onload = () => {
        context.drawImage(image, 0, 0);
    };

    image.src = imgBase64;
}

function showImage(imgBase64) {
    const imgElement = document.getElementById("image").src = imgBase64;
}

function drawCanvas(canvas, img) {
    canvas.width = getComputedStyle(canvas).width.split('px')[0];
    canvas.height = getComputedStyle(canvas).height.split('px')[0];
    let ratio = Math.min(canvas.width / img.width, canvas.height / img.height);
    let x = (canvas.width - img.width * ratio) / 2;
    let y = (canvas.height - img.height * ratio) / 2;
    canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height);
    canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height, x, y, img.width * ratio, img.height * ratio);
}

function handleFileSelect(evt) {
    const files = evt.target.files; // FileList object

    // files is a FileList of File objects. List some properties.
    const output = [];
    for (let i = 0, f; f = files[i]; i++) {
        output.push('
', escape(f.name), ' (', f.type || 'n/a', ')
',
            f.size, ' bytes
last modified: ',
            f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a',
            `<br/><img id="${escape(f.name)}" src="" alt="${escape(f.name)}" style="width:200px"/><br/>`,
            '
');
    }
    document.getElementById('list').innerHTML = '
' + output.join('') + '
';

    Array.from(files).forEach(file => {
        const reader = new FileReader();
        reader.onload = event => {
            document.getElementById(escape(file.name)).src = event.target.result;
        };
        reader.readAsDataURL(file);
    });
}

document.getElementById('files').addEventListener('change', handleFileSelect, false);
<|endoftext|>


<commit_before>/**
 * service-worker.js
 *
 * Set up the service worker.
 */

export default (function () {

	if ('serviceWorker' in navigator) {

		if (navigator.serviceWorker.controller) {
			return navigator.serviceWorker.ready;
		} else {

			// Return the instantiation promise
			return navigator.serviceWorker.register('./sw.js')
			.then(() => navigator.serviceWorker.ready);
		}
	}
}());
<commit_msg>Fix sw url<commit_after>/**
 * service-worker.js
 *
 * Set up the service worker.
 */

export default (function () {

	if ('serviceWorker' in navigator) {

		if (navigator.serviceWorker.controller) {
			return navigator.serviceWorker.ready;
		} else {

			// Return the instantiation promise
			return navigator.serviceWorker.register('/sw.min.js')
			.then(() => navigator.serviceWorker.ready);
		}
	}
}());
<|endoftext|>


<commit_before>/* global nw, angular, console, require, Peer, StellarSdk */

angular.module('app', [
	'pascalprecht.translate',
	'ngRoute',
	'ionic'
], function ($compileProvider) {
	'use strict';
	$compileProvider.aHrefSanitizationWhitelist(/^\s*((https?|ftp|mailto|file|chrome-extension|tel):)|#/);
})
.run(function ($rootScope, $window) {
	'use strict';
	$rootScope.goBack = function() {
		$window.history.back();
	};
})
.run(function (platformInfo) {
	'use strict';

	if (platformInfo.isNW) {

//		nw.Window.get().showDevTools();

		// Load native UI library
		var gui = require('nw.gui');

		// Create menu
		var menu = new gui.Menu({
			type: 'menubar'
		});

		// Append Menu to Window
		gui.Window.get().menu = menu;

		// create MacBuiltin
		try {
			menu.createMacBuiltin('Stargazer', {
				hideEdit: false,
				hideWindow: true
			});
		} catch (e) {}
	}
})

.config(['$translateProvider', function ($translateProvider) {
	'use strict';

	$translateProvider
	.useSanitizeValueStrategy('escape')
	.addInterpolation('$translateMessageFormatInterpolation')
	.fallbackLanguage('en');

	$translateProvider.translations('en', /* @include ../i18n/en.json */);
	$translateProvider.translations('sv', /* @include ../i18n/sv.json */);
}]);
<commit_msg>Add support for hardware back button<commit_after>/* global angular, navigator, nw, require, StellarSdk */

angular.module('app', [
	'pascalprecht.translate',
	'ngRoute',
	'ionic'
], function ($compileProvider) {
	'use strict';
	$compileProvider.aHrefSanitizationWhitelist(/^\s*((https?|ftp|mailto|file|chrome-extension|tel):)|#/);
})

.run(function ($ionicPlatform, $rootScope, $route, $window) {
	'use strict';

	$rootScope.goBack = function() {
		$window.history.back();
	};

	$ionicPlatform.registerBackButtonAction(function () {
		if ($route.current.controller !== 'HomeCtrl') {
			$rootScope.goBack();
		} else {
			navigator.app.exitApp();
		}
	}, 100);
})

.run(function (platformInfo) {
	'use strict';

	if (platformInfo.isNW) {

//		nw.Window.get().showDevTools();

		// Load native UI library
		var gui = require('nw.gui');

		// Create menu
		var menu = new gui.Menu({
			type: 'menubar'
		});

		// Append Menu to Window
		gui.Window.get().menu = menu;

		// create MacBuiltin
		try {
			menu.createMacBuiltin('Stargazer', {
				hideEdit: false,
				hideWindow: true
			});
		} catch (e) {}
	}
})

.config(['$translateProvider', function ($translateProvider) {
	'use strict';

	$translateProvider
	.useSanitizeValueStrategy('escape')
	.addInterpolation('$translateMessageFormatInterpolation')
	.fallbackLanguage('en');

	$translateProvider.translations('en', /* @include ../i18n/en.json */);
	$translateProvider.translations('sv', /* @include ../i18n/sv.json */);
}]);
<|endoftext|>


<commit_before>var cy;
var default_node_width = 175;
var default_node_height = 35;
var default_font_size = 11;
var default_color = '#323232';

jQuery.noConflict();
var $j = jQuery;

function drawGraph(elements, current_element_id){
    $j('#cy').cytoscape({
        layout: {
            name: 'breadthfirst'
        },

        showOverlay: false,

        style: cytoscape.stylesheet()
            .selector('node')
            .css({
                'shape': 'roundrectangle',
                'border-color': 'data(borderColor)',
                'border-width': 2,
                'das': 'mapData(weight, 40, 80, 20, 60)',
                'content': 'data(name)',
                'text-valign': 'center',
                'text-outline-width': 1,
                'text-outline-color': 'data(faveColor)',
                'background-color': 'data(faveColor)',
                'color':default_color,
                'width':default_node_width,
                'height':default_node_height,
                'font-size':default_font_size
            })

            .selector('edge')
            .css({
                'width': 1.5,
                'target-arrow-shape': 'none',
                'line-color': 'data(faveColor)',
                'source-arrow-color': 'data(faveColor)',
                'target-arrow-color': 'data(faveColor)',
                'content': 'data(name)',
                'color': '#323232',
                'font-size': (default_font_size-2)
            }),

        elements: elements,

        ready: function(){
            cy = this;
            var nodes = cy.$('node');

            //process only when having nodes
            if (nodes.length > 0){
                processPanzoom();

                nodes.on('click', function(e){
                    var node = e.cyTarget;
                    if(node.selected() === true){
                        clickLabelLink(node, e.originalEvent);
                    }else{
                        animateNode(node);
                        displayNodeInfo(node);
                    }
                });

                //animate the current node
                var current_node = cy.nodes('[id=\''+ current_element_id +'\']')[0];
                animateNode(current_node);
                displayNodeInfo(current_node);

                disableMouseWheel();
                resizeGraph();
            }else{
                $j('.isa_graph')[0].hide();
            }
        }
    });
}

function animateNode(node){
    var nodes = cy.$('node');
    var edges = cy.$('edge');

    //first normalizing all nodes and fading all nodes and edges
    normalizingNodes(nodes);
    fadingNodes(nodes);
    fadingEdges(edges);

    //then appearing the chosen node and the connected nodes and edges
    appearingNodes(node);
    edges.each(function(i, edge){
        var source = edge.source();
        var target =edge.target();
        if (source.id() === node.id()){
            appearingEdges(edge);
            appearingNodes(target);
        }
        if (target.id() === node.id()){
            appearingEdges(edge);
            appearingNodes(source);
        }
    });

    //then animate the chosen node
    node.animate({
        css: { 'width':250, 'height':50 }
    }, {
        duration: 300
    });
    // set font style here for better animation (instead of in animate function).
    node.css('font-size', 14);
    node.css('font-weight', 'bolder');
    if (node.data().name !== 'Hidden item')
        node.css('color', '#0000e5');
    node.select();
}

function displayNodeInfo(node){
    var html = "
Chosen item
";
    html += "
";
    var item_data = node.data();
    html += itemInfo(item_data);
    html += '
';

    html += '
';

    html += "
Connected items
";
    html += "
";
    var connected_nodes = connectedNodes(node);
    for(var i=0;i<connected_nodes.length;i++){
        var node_data = connected_nodes[i].data();
        html += itemInfo(node_data);
    }

    html += '
';

    var node_info = $('node_info');
    $('node_info').innerHTML = html;

    //can not use Effect.Appear here, it does not activate clientHeight
    node_info.style['display'] = 'block';
    alignCenterVertical(node_info, node_info.clientHeight);
}

function itemInfo(item_data){
    var html = '
';
    html += item_data.item_info;
    html += '
';
    return html;
}

function connectedNodes(node){
    var edges = cy.$('edge');
    var connected_nodes = [];
    edges.each(function(i, edge){
        var source = edge.source();
        var target =edge.target();
        if (source.id() === node.id()){
            connected_nodes.push(target);
        }
        if (target.id() === node.id()){
            connected_nodes.push(source);
        }
    });
    return connected_nodes;
}

function targetNodeCollection(node){
    var edges = cy.$('edge');
    var target_node_collection = cy.collection();
    edges.each(function(i, edge){
        var source = edge.source();
        var target =edge.target();
        if (source.id() === node.id()){
            target_node_collection = target_node_collection.add(target);
        }
    });
    return target_node_collection;
}

function sourceNodeCollection(node){
    var edges = cy.$('edge');
    var source_node_collection = cy.collection();
    edges.each(function(i, edge){
        var source = edge.source();
        var target =edge.target();
        if (target.id() === node.id()){
            source_node_collection = source_node_collection.add(source);
        }
    });
    return source_node_collection;
}

function edgeToTargetCollection(node){
    var edges = cy.$('edge');
    var edge_to_target_collection = cy.collection();
    edges.each(function(i, edge){
        var source = edge.source();
        var target =edge.target();
        if (source.id() === node.id()){
            edge_to_target_collection = edge_to_target_collection.add(edge);
        }
    });
    return edge_to_target_collection;
}

function edgeToSourceCollection(node){
    var edges = cy.$('edge');
    var edge_to_source_collection = cy.collection();
    edges.each(function(i, edge){
        var source = edge.source();
        var target =edge.target();
        if (target.id() === node.id()){
            edge_to_source_collection = edge_to_source_collection.add(edge);
        }
    });
    return edge_to_source_collection;
}

function processPanzoom() {
    //display panzoom
    $j('#cy').cytoscapePanzoom({
        panSpeed: 1
    });

    //set again the graph height if panzoom height is bigger
    var panzoom_height = 220;
    var graph_height = cy.container().style.height.split('px')[0];
    cy.container().style.height = Math.max(graph_height, panzoom_height) +'px';

    alignCenterVertical($j('.ui-cytoscape-panzoom')[0], panzoom_height);

    //reset on panzoom also reset all nodes and edges css
    $j('.ui-cytoscape-panzoom-reset').click(function () {
        var nodes = cy.$('node')
        normalizingNodes(nodes);
        appearingNodes(nodes);
        appearingEdges(cy.$('edge'));
        Effect.Fade('node_info', { duration: 0.25 });
    });
}

function alignCenterVertical(element, element_height){
    var graph_height = cy.container().style.height.split('px')[0];
    var distance_from_top = (graph_height - element_height)/2;
    if (distance_from_top > 0){
        element.style['top']=distance_from_top+'px';
    }else{
        element.style['top']='0px';
    }
}

function appearingNodes(nodes){
    nodes.css('opacity', 1);
}

function appearingEdges(edges){
    edges.css('opacity', 1);
}

function fadingNodes(nodes){
    nodes.css('opacity', 0.3);
}

function fadingEdges(edges){
    edges.css('opacity', 0.2);
}

function normalizingNodes(nodes){
    nodes.css('width',default_node_width);
    nodes.css('height',default_node_height);
    nodes.css('font-size',default_font_size);
    nodes.css('font-weight', 'normal');
    nodes.css('color',default_color);
    nodes.unselect();
}

function resizeGraph(){
    cy.fit(50);
    if (cy.zoom() > 1){
        cy.reset();
        cy.center();
    }
}

function labelPosition(node){
    var label_pos = new Object();
    var graph_pos = $j('#cy')[0].getBoundingClientRect();
    var node_posX = node.renderedPosition().x + graph_pos.left;
    var node_posY = node.renderedPosition().y + graph_pos.top;
    var font_size = node.renderedCss()['font-size'];
    var label = node.data().name;
    var ruler = $j('#ruler')[0];
    ruler.style.fontSize = font_size;
    ruler.style.fontWeight = 'bolder';
    ruler.innerHTML = label;
    var zoom_level = cy.zoom();
    var label_width = ruler.offsetWidth + 2*zoom_level;
    var label_height = ruler.offsetHeight;
    label_pos.minX = node_posX - label_width/2;
    label_pos.maxX = node_posX + label_width/2;
    label_pos.minY = node_posY - label_height/2;
    label_pos.maxY = node_posY + label_height/2;
    return label_pos;
}

function mouseOnLabel(node, mouse_event){
    var label_pos = labelPosition(node);
    var mouse_posX = mouse_event.clientX;
    var mouse_posY = mouse_event.clientY;
    var mouse_on_label = mouse_posX > label_pos.minX && mouse_posX < label_pos.maxX && mouse_posY > label_pos.minY && mouse_posY < label_pos.maxY;
    return mouse_on_label;
}

function clickLabelLink(node, mouse_event){
    if (node.data().name !== "Hidden item"){
        if (mouseOnLabel(node, mouse_event)){
            var link = document.createElement('a');
            link.href = node.data().item_info.split('"')[1];
            clickLink(link);
        }
    }
}

function disableMouseWheel(){
    var canvas_render = cy.renderer();
    var bindings = canvas_render.bindings;
    for( var i=0; i<bindings.length; i++){
        binding = bindings[i];
        var event = binding.event;
        if (event.match(/wheel/i) != null || event.match(/scroll/i) !=null){
            binding.target.removeEventListener(event, binding.handler, binding.useCapture);
        }
    }
}
<commit_msg>use dot notation<commit_after>var cy;
var default_node_width = 175;
var default_node_height = 35;
var default_font_size = 11;
var default_color = '#323232';

jQuery.noConflict();
var $j = jQuery;

function drawGraph(elements, current_element_id){
    $j('#cy').cytoscape({
        layout: {
            name: 'breadthfirst'
        },

        showOverlay: false,

        style: cytoscape.stylesheet()
            .selector('node')
            .css({
                'shape': 'roundrectangle',
                'border-color': 'data(borderColor)',
                'border-width': 2,
                'das': 'mapData(weight, 40, 80, 20, 60)',
                'content': 'data(name)',
                'text-valign': 'center',
                'text-outline-width': 1,
                'text-outline-color': 'data(faveColor)',
                'background-color': 'data(faveColor)',
                'color':default_color,
                'width':default_node_width,
                'height':default_node_height,
                'font-size':default_font_size
            })

            .selector('edge')
            .css({
                'width': 1.5,
                'target-arrow-shape': 'none',
                'line-color': 'data(faveColor)',
                'source-arrow-color': 'data(faveColor)',
                'target-arrow-color': 'data(faveColor)',
                'content': 'data(name)',
                'color': '#323232',
                'font-size': (default_font_size-2)
            }),

        elements: elements,

        ready: function(){
            cy = this;
            var nodes = cy.$('node');

            //process only when having nodes
            if (nodes.length > 0){
                processPanzoom();

                nodes.on('click', function(e){
                    var node = e.cyTarget;
                    if(node.selected() === true){
                        clickLabelLink(node, e.originalEvent);
                    }else{
                        animateNode(node);
                        displayNodeInfo(node);
                    }
                });

                //animate the current node
                var current_node = cy.nodes('[id=\''+ current_element_id +'\']')[0];
                animateNode(current_node);
                displayNodeInfo(current_node);

                disableMouseWheel();
                resizeGraph();
            }else{
                $j('.isa_graph')[0].hide();
            }
        }
    });
}

function animateNode(node){
    var nodes = cy.$('node');
    var edges = cy.$('edge');

    //first normalizing all nodes and fading all nodes and edges
    normalizingNodes(nodes);
    fadingNodes(nodes);
    fadingEdges(edges);

    //then appearing the chosen node and the connected nodes and edges
    appearingNodes(node);
    edges.each(function(i, edge){
        var source = edge.source();
        var target =edge.target();
        if (source.id() === node.id()){
            appearingEdges(edge);
            appearingNodes(target);
        }
        if (target.id() === node.id()){
            appearingEdges(edge);
            appearingNodes(source);
        }
    });

    //then animate the chosen node
    node.animate({
        css: { 'width':250, 'height':50 }
    }, {
        duration: 300
    });
    // set font style here for better animation (instead of in animate function).
    node.css('font-size', 14);
    node.css('font-weight', 'bolder');
    if (node.data().name !== 'Hidden item')
        node.css('color', '#0000e5');
    node.select();
}

function displayNodeInfo(node){
    var html = "
Chosen item
";
    html += "
";
    var item_data = node.data();
    html += itemInfo(item_data);
    html += '
';

    html += '
';

    html += "
Connected items
";
    html += "
";
    var connected_nodes = connectedNodes(node);
    for(var i=0;i<connected_nodes.length;i++){
        var node_data = connected_nodes[i].data();
        html += itemInfo(node_data);
    }

    html += '
';

    var node_info = $('node_info');
    $('node_info').innerHTML = html;

    //can not use Effect.Appear here, it does not activate clientHeight
    node_info.style.display = 'block';
    alignCenterVertical(node_info, node_info.clientHeight);
}

function itemInfo(item_data){
    var html = '
';
    html += item_data.item_info;
    html += '
';
    return html;
}

function connectedNodes(node){
    var edges = cy.$('edge');
    var connected_nodes = [];
    edges.each(function(i, edge){
        var source = edge.source();
        var target =edge.target();
        if (source.id() === node.id()){
            connected_nodes.push(target);
        }
        if (target.id() === node.id()){
            connected_nodes.push(source);
        }
    });
    return connected_nodes;
}

function targetNodeCollection(node){
    var edges = cy.$('edge');
    var target_node_collection = cy.collection();
    edges.each(function(i, edge){
        var source = edge.source();
        var target =edge.target();
        if (source.id() === node.id()){
            target_node_collection = target_node_collection.add(target);
        }
    });
    return target_node_collection;
}

function sourceNodeCollection(node){
    var edges = cy.$('edge');
    var source_node_collection = cy.collection();
    edges.each(function(i, edge){
        var source = edge.source();
        var target =edge.target();
        if (target.id() === node.id()){
            source_node_collection = source_node_collection.add(source);
        }
    });
    return source_node_collection;
}

function edgeToTargetCollection(node){
    var edges = cy.$('edge');
    var edge_to_target_collection = cy.collection();
    edges.each(function(i, edge){
        var source = edge.source();
        var target =edge.target();
        if (source.id() === node.id()){
            edge_to_target_collection = edge_to_target_collection.add(edge);
        }
    });
    return edge_to_target_collection;
}

function edgeToSourceCollection(node){
    var edges = cy.$('edge');
    var edge_to_source_collection = cy.collection();
    edges.each(function(i, edge){
        var source = edge.source();
        var target =edge.target();
        if (target.id() === node.id()){
            edge_to_source_collection = edge_to_source_collection.add(edge);
        }
    });
    return edge_to_source_collection;
}

function processPanzoom() {
    //display panzoom
    $j('#cy').cytoscapePanzoom({
        panSpeed: 1
    });

    //set again the graph height if panzoom height is bigger
    var panzoom_height = 220;
    var graph_height = cy.container().style.height.split('px')[0];
    cy.container().style.height = Math.max(graph_height, panzoom_height) +'px';

    alignCenterVertical($j('.ui-cytoscape-panzoom')[0], panzoom_height);

    //reset on panzoom also reset all nodes and edges css
    $j('.ui-cytoscape-panzoom-reset').click(function () {
        var nodes = cy.$('node')
        normalizingNodes(nodes);
        appearingNodes(nodes);
        appearingEdges(cy.$('edge'));
        Effect.Fade('node_info', { duration: 0.25 });
    });
}

function alignCenterVertical(element, element_height){
    var graph_height = cy.container().style.height.split('px')[0];
    var distance_from_top = (graph_height - element_height)/2;
    if (distance_from_top > 0){
        element.style.top=distance_from_top+'px';
    }else{
        element.style.top='0px';
    }
}

function appearingNodes(nodes){
    nodes.css('opacity', 1);
}

function appearingEdges(edges){
    edges.css('opacity', 1);
}

function fadingNodes(nodes){
    nodes.css('opacity', 0.3);
}

function fadingEdges(edges){
    edges.css('opacity', 0.2);
}

function normalizingNodes(nodes){
    nodes.css('width',default_node_width);
    nodes.css('height',default_node_height);
    nodes.css('font-size',default_font_size);
    nodes.css('font-weight', 'normal');
    nodes.css('color',default_color);
    nodes.unselect();
}

function resizeGraph(){
    cy.fit(50);
    if (cy.zoom() > 1){
        cy.reset();
        cy.center();
    }
}

function labelPosition(node){
    var label_pos = new Object();
    var graph_pos = $j('#cy')[0].getBoundingClientRect();
    var node_posX = node.renderedPosition().x + graph_pos.left;
    var node_posY = node.renderedPosition().y + graph_pos.top;
    var font_size = node.renderedCss()['font-size'];
    var label = node.data().name;
    var ruler = $j('#ruler')[0];
    ruler.style.fontSize = font_size;
    ruler.style.fontWeight = 'bolder';
    ruler.innerHTML = label;
    var zoom_level = cy.zoom();
    var label_width = ruler.offsetWidth + 2*zoom_level;
    var label_height = ruler.offsetHeight;
    label_pos.minX = node_posX - label_width/2;
    label_pos.maxX = node_posX + label_width/2;
    label_pos.minY = node_posY - label_height/2;
    label_pos.maxY = node_posY + label_height/2;
    return label_pos;
}

function mouseOnLabel(node, mouse_event){
    var label_pos = labelPosition(node);
    var mouse_posX = mouse_event.clientX;
    var mouse_posY = mouse_event.clientY;
    var mouse_on_label = mouse_posX > label_pos.minX && mouse_posX < label_pos.maxX && mouse_posY > label_pos.minY && mouse_posY < label_pos.maxY;
    return mouse_on_label;
}

function clickLabelLink(node, mouse_event){
    if (node.data().name !== "Hidden item"){
        if (mouseOnLabel(node, mouse_event)){
            var link = document.createElement('a');
            link.href = node.data().item_info.split('"')[1];
            clickLink(link);
        }
    }
}

function disableMouseWheel(){
    var canvas_render = cy.renderer();
    var bindings = canvas_render.bindings;
    for( var i=0; i<bindings.length; i++){
        binding = bindings[i];
        var event = binding.event;
        if (event.match(/wheel/i) != null || event.match(/scroll/i) !=null){
            binding.target.removeEventListener(event, binding.handler, binding.useCapture);
        }
    }
}
<|endoftext|>


<commit_before>var width = 420;
var height = 630;
var gapWidth = width/6;
var gapHeight = height/9;
var turnCount = 0;
var gameSpeed = 300;
var gameTimer;
var countMatrix = new Array(9);
var colorMatrix = new Array(9);
var undoCount = new Array(9)
var undoColor = new Array(9);
var isGameOver = false;
var counterAnimate = 0;
var flag = false;

var canvas = document.getElementById("arena");
var button = document.getElementById("undo");
var sound = document.getElementById("sound");
var gameArena = canvas.getContext("2d");
canvas.addEventListener("click", gameLoop);
button.addEventListener("click", undoGame);

initialiseMatrix();
initialise();

function initialise()
{
	isGameOver = false;
	matrixDefault();
	drawArena();
	turnCount = 0;
	counterAnimate = 0;
	gameTimer = setInterval(updateMatrix, gameSpeed);
}

function initialiseMatrix()
{
	for(var counter = 0; counter < 9; counter++)
	{
		countMatrix[counter] = new Array(6);
		colorMatrix[counter] = new Array(6);
		undoCount[counter] = new Array(6);
		undoColor[counter] = new Array(6);
	}
}

function matrixDefault()
{
	for(var i = 0; i < 9; i++)
	{
		for(var j = 0; j < 6; j++)
		{
			colorMatrix[i][j] = "";		//No color
			countMatrix[i][j] = 0;		//No value
			undoCount[i][j] = 0;		//No value
			undoColor[i][j] = "";		//No color
		}
	}
}

function drawArena()
{
	gameArena.clearRect(0, 0, width, height);
	gameArena.strokeStyle = "black";

	for(var counter = 1; counter < 6; counter++)
	{
		gameArena.beginPath();
		gameArena.moveTo(counter*gapWidth, 0);
		gameArena.lineTo(counter*gapWidth, height);
		gameArena.closePath();
		gameArena.stroke();
	}

	for(var counter = 1; counter < 9; counter++)
	{
		gameArena.beginPath();
		gameArena.moveTo(0 , counter*gapHeight);
		gameArena.lineTo(width , counter*gapHeight);
		gameArena.closePath();
		gameArena.stroke();
	}

	for(var i = 0; i < 9; i++)
	{
		for(var j = 0; j < 6; j++)
		{
			if(countMatrix[i][j] == 0)
				continue;
			if(countMatrix[i][j] == 1)
				oneCircle(i, j, colorMatrix[i][j]);
			else if(countMatrix[i][j] == 2)
				twoCircle(i, j, colorMatrix[i][j]);
			else
				threeCircle(i, j, colorMatrix[i][j]);
		}
	}
}

function undoGame()
{
	if(turnCount > 0 && flag == false)
	{
		flag = true;
		turnCount--;
		for(var i = 0; i < 9; i++)
		{
			for(var j = 0; j < 6; j++)
			{
				countMatrix[i][j] = undoCount[i][j];
				colorMatrix[i][j] = undoColor[i][j];
			}
		}
	}

}

function takeBackUp()
{
	for(var i = 0; i < 9; i++)
	{
		for(var j = 0; j < 6; j++)
		{
			undoCount[i][j] = countMatrix[i][j];
			undoColor[i][j] = colorMatrix[i][j];
		}
	}
}

function gameLoop(event)
{
	var rect = canvas.getBoundingClientRect();
	var x = event.clientX - rect.left;
	var y = event.clientY - rect.top;

	var row = Math.floor(x/gapWidth);
	var column = Math.floor(y/gapHeight);

	if(!isGameOver)
	{
		takeBackUp();
		if(turnCount%2 == 0 && (colorMatrix[column][row] == "" || colorMatrix[column][row] == "red"))
		{
			countMatrix[column][row]++;		//Weird graphic coordinate-system
			colorMatrix[column][row] = "red";
			turnCount++;
			flag = false;
		}
		if(turnCount%2 == 1 && (colorMatrix[column][row] == "" || colorMatrix[column][row] == "green"))
		{
			countMatrix[column][row]++;		//Weird graphic coordinate-system
			colorMatrix[column][row] = "green";
			turnCount++;
			flag = false;
		}
	}
}

function populateCornerCells(i, j){
	countMatrix[i][j] -= 2;
	countMatrix[ i == 8 ? i-1 : i+1 ][j]++;
	countMatrix[i][ j==5 ? j-1 : j+1 ]++;
	colorMatrix[ i == 8 ? i-1 : i+1 ][j] = colorMatrix[i][j];
	colorMatrix[i][ j==5 ? j-1 : j+1 ] = colorMatrix[i][j];
	if(countMatrix[i][j] == 0)
		colorMatrix[i][j] = "";
	sound.play();
}

function populateSideHCells(i, j){  // H = Height
	countMatrix[i][j] -= 3;
	countMatrix[i-1][j]++;
	countMatrix[i+1][j]++;
	countMatrix[i][ j==0 ? j+1 : j-1 ]++;
	colorMatrix[i][ j==0 ? j+1 : j-1 ] = colorMatrix[i][j];
	colorMatrix[i-1][j] = colorMatrix[i][j];
	colorMatrix[i+1][j] = colorMatrix[i][j];
	if(countMatrix[i][j] == 0)
		colorMatrix[i][j] = "";
	sound.play();
}

function populateSideWCells(i, j) {  // W = Width
	countMatrix[i][j] -= 3;
	countMatrix[ i==0 ? i+1 : i-1 ][j]++;
	countMatrix[i][j-1]++;
	countMatrix[i][j+1]++;
	colorMatrix[ i==0 ? i+1 : i-1 ][j] = colorMatrix[i][j];
	colorMatrix[i][j-1] = colorMatrix[i][j];
	colorMatrix[i][j+1] = colorMatrix[i][j];
	if(countMatrix[i][j] == 0)
		colorMatrix[i][j] = "";
	sound.play();
}

function updateMatrix()
{
	counterAnimate++;
	drawArena();
	var cornerCord = [[0,0], [8,0], [8,5], [0,5]];

	while(notStable()){
		for(var i = 0; i < 4;i++)
			if(countMatrix[cornerCord[i][0]][cornerCord[i][1]] >= 2){ populateCornerCells(cornerCord[i][0], cornerCord[i][1]); break; }

		for(var i = 1; i < 8; i++){
			if(countMatrix[i][0] >= 3){ populateSideHCells(i, 0); break; }
			if(countMatrix[i][5] >= 3){ populateSideHCells(i, 5); break; }
		}

		for(var i = 1; i < 5; i++){
			if(countMatrix[0][i] >= 3){ populateSideWCells(0, i); break; }
			if(countMatrix[8][i] >= 3){ populateSideWCells(8, i); break; }
		}

		for(var i = 1; i < 8; i++){
			for(var j = 1; j < 5; j++){
				if(countMatrix[i][j] >= 4){
					countMatrix[i][j] -= 4;
					countMatrix[i-1][j]++;
					countMatrix[i+1][j]++;
					countMatrix[i][j-1]++;
					countMatrix[i][j+1]++;
					colorMatrix[i-1][j] = colorMatrix[i][j];
					colorMatrix[i+1][j] = colorMatrix[i][j];
					colorMatrix[i][j-1] = colorMatrix[i][j];
					colorMatrix[i][j+1] = colorMatrix[i][j];
					if(countMatrix[i][j] == 0)
						colorMatrix[i][j] = "";
					sound.play();
					break;
				}
			}
		}
		break;
	}
	checkGameOver();
}

function checkGameOver()
{
	if(gameOver() == 1 || gameOver() == 2)
	{
		isGameOver = true;
		gameOverScreen(gameOver());
		clearInterval(gameTimer);
		setTimeout(initialise, 4000);
	}
}

function notStable()
{
	var ans = false;
	if(countMatrix[0][0] >= 2 || countMatrix[8][0] >= 2 || countMatrix[8][5] >= 2 || countMatrix[0][5] >= 2)
		ans = true;

	for(var i = 1; i < 8; i++)
		if(countMatrix[i][0] >= 3 || countMatrix[i][5] >= 3)
			ans = true;

	for(var i = 1; i < 5; i++)
		if(countMatrix[0][i] >= 3 || countMatrix[8][i] >= 3)
			ans = true;

	for(var i = 1; i < 8; i++)
		for(var j = 1; j < 8; j++)
			if(countMatrix[i][j] >= 4)
				ans = true;

	return ans;
}

function gameOver()
{
	var countRed = 0;
	var countGreen = 0;
	for(var i = 0; i < 9; i++)
	{
		for(var j = 0;j < 6; j++)
		{
			if(colorMatrix[i][j] == "red") countRed++;
			if(colorMatrix[i][j] == "green") countGreen++;
		}
	}
	if(turnCount > 1)
	{
		if(countRed == 0)
		{
			return 2;
		}
		if(countGreen == 0)
		{
			return 1;
		}
	}
}

function gameOverScreen(player)
{
	if(player == 2)
	{
		gameArena.clearRect(0, 0, width, height);
		gameArena.fillStyle = "black";
		gameArena.fillRect(0, 0, width, height);
		gameArena.fillStyle = "white";
		gameArena.font = "40px Times New Roman";
		gameArena.fillText("Player 2 wins!", width/2 - 150, height/2 - 50);
	}
	else
	{
		gameArena.clearRect(0, 0, width, height);
		gameArena.fillStyle = "black";
		gameArena.fillRect(0, 0, width, height);
		gameArena.fillStyle = "white";
		gameArena.font = "40px Times New Roman";
		gameArena.fillText("Player 1 wins!", width/2 - 150, height/2 - 50);
	}
}

function oneCircle(row, column, color)
{
	gameArena.beginPath();
	gameArena.arc(column*gapWidth + 35, row*gapHeight + 35, 15, 0, Math.PI*2);
	gameArena.fillStyle = color;
	gameArena.fill();
	if((row == 0 && column == 0) || (row == 8 && column == 0) || (row == 0 && column == 5) || (row == 8 && column == 5))
	{
		if(counterAnimate%2 == 0)
			gameArena.strokeStyle = "black";
		else
			gameArena.strokeStyle = color;
	}
	else
	{
		gameArena.strokeStyle = "black";
	}
	gameArena.lineWidth = 3;
	gameArena.stroke();
	gameArena.closePath();
	gameArena.lineWidth = 1;
}

function twoCircle(row, column, color)
{
	gameArena.beginPath();
	gameArena.arc(column*gapWidth + 20, row*gapHeight + 35, 15, 0, Math.PI*2);
	gameArena.fillStyle = color;
	gameArena.fill();
	if(((row >= 1 && row < 8) && (column == 0 || column == 5)) || ((row == 0 || row == 8) && (column >= 1 && column < 5)))
	{
		if(counterAnimate%2 == 0)
			gameArena.strokeStyle = "black";
		else
			gameArena.strokeStyle = color;
	}
	else
	{
		gameArena.strokeStyle = "black";
	}
	gameArena.lineWidth = 3;
	gameArena.stroke();
	gameArena.closePath();
	gameArena.lineWidth = 1;

	gameArena.beginPath();
	gameArena.arc(column*gapWidth + 50, row*gapHeight + 35, 15, 0, Math.PI*2);
	gameArena.fillStyle = color;
	gameArena.fill();
	if(((row >= 1 && row < 8) && (column == 0 || column == 5)) || ((row == 0 || row == 8) && (column >= 1 && column < 5)))
	{
		if(counterAnimate%2 == 0)
			gameArena.strokeStyle = "black";
		else
			gameArena.strokeStyle = color;
	}
	else
	{
		gameArena.strokeStyle = "black";
	}
	gameArena.lineWidth = 3;
	gameArena.stroke();
	gameArena.closePath();
	gameArena.lineWidth = 1;
}

function threeCircle(row, column, color)
{
	gameArena.beginPath();
	gameArena.arc(column*gapWidth + 20, row*gapHeight + 17, 15, 0, Math.PI*2);
	gameArena.fillStyle = color;
	gameArena.fill();
	if(counterAnimate%2 == 0)
		gameArena.strokeStyle = "black";
	else
		gameArena.strokeStyle = color;
	gameArena.lineWidth = 3;
	gameArena.stroke();
	gameArena.closePath();
	gameArena.lineWidth = 1;

	gameArena.beginPath();
	gameArena.arc(column*gapWidth + 20, row*gapHeight + 53, 15, 0, Math.PI*2);
	gameArena.fillStyle = color;
	gameArena.fill();
	if(counterAnimate%2 == 0)
		gameArena.strokeStyle = "black";
	else
		gameArena.strokeStyle = color;
	gameArena.lineWidth = 3;
	gameArena.stroke();
	gameArena.closePath();
	gameArena.lineWidth = 1;

	gameArena.beginPath();
	gameArena.arc(column*gapWidth + 50, row*gapHeight + 35, 15, 0, Math.PI*2);
	gameArena.fillStyle = color;
	gameArena.fill();
	if(counterAnimate%2 == 0)
		gameArena.strokeStyle = "black";
	else
		gameArena.strokeStyle = color;
	gameArena.lineWidth = 3;
	gameArena.stroke();
	gameArena.closePath();
	gameArena.lineWidth = 1;
}<commit_msg>added check gameOver()<commit_after>var width = 420;
var height = 630;
var gapWidth = width/6;
var gapHeight = height/9;
var turnCount = 0;
var gameSpeed = 300;
var gameTimer;
var countMatrix = new Array(9);
var colorMatrix = new Array(9);
var undoCount = new Array(9)
var undoColor = new Array(9);
var isGameOver = false;
var counterAnimate = 0;
var flag = false;

var canvas = document.getElementById("arena");
var button = document.getElementById("undo");
var sound = document.getElementById("sound");
var gameArena = canvas.getContext("2d");
canvas.addEventListener("click", gameLoop);
button.addEventListener("click", undoGame);

initialiseMatrix();
initialise();

function initialise()
{
	isGameOver = false;
	matrixDefault();
	drawArena();
	turnCount = 0;
	counterAnimate = 0;
	gameTimer = setInterval(updateMatrix, gameSpeed);
}

function initialiseMatrix()
{
	for(var counter = 0; counter < 9; counter++)
	{
		countMatrix[counter] = new Array(6);
		colorMatrix[counter] = new Array(6);
		undoCount[counter] = new Array(6);
		undoColor[counter] = new Array(6);
	}
}

function matrixDefault()
{
	for(var i = 0; i < 9; i++)
	{
		for(var j = 0; j < 6; j++)
		{
			colorMatrix[i][j] = "";		//No color
			countMatrix[i][j] = 0;		//No value
			undoCount[i][j] = 0;		//No value
			undoColor[i][j] = "";		//No color
		}
	}
}

function drawArena()
{
	gameArena.clearRect(0, 0, width, height);
	gameArena.strokeStyle = "black";

	for(var counter = 1; counter < 6; counter++)
	{
		gameArena.beginPath();
		gameArena.moveTo(counter*gapWidth, 0);
		gameArena.lineTo(counter*gapWidth, height);
		gameArena.closePath();
		gameArena.stroke();
	}

	for(var counter = 1; counter < 9; counter++)
	{
		gameArena.beginPath();
		gameArena.moveTo(0 , counter*gapHeight);
		gameArena.lineTo(width , counter*gapHeight);
		gameArena.closePath();
		gameArena.stroke();
	}

	for(var i = 0; i < 9; i++)
	{
		for(var j = 0; j < 6; j++)
		{
			if(countMatrix[i][j] == 0)
				continue;
			if(countMatrix[i][j] == 1)
				oneCircle(i, j, colorMatrix[i][j]);
			else if(countMatrix[i][j] == 2)
				twoCircle(i, j, colorMatrix[i][j]);
			else
				threeCircle(i, j, colorMatrix[i][j]);
		}
	}
}

function undoGame()
{
	if(turnCount > 0 && flag == false)
	{
		flag = true;
		turnCount--;
		for(var i = 0; i < 9; i++)
		{
			for(var j = 0; j < 6; j++)
			{
				countMatrix[i][j] = undoCount[i][j];
				colorMatrix[i][j] = undoColor[i][j];
			}
		}
	}

}

function takeBackUp()
{
	for(var i = 0; i < 9; i++)
	{
		for(var j = 0; j < 6; j++)
		{
			undoCount[i][j] = countMatrix[i][j];
			undoColor[i][j] = colorMatrix[i][j];
		}
	}
}

function gameLoop(event)
{
	var rect = canvas.getBoundingClientRect();
	var x = event.clientX - rect.left;
	var y = event.clientY - rect.top;

	var row = Math.floor(x/gapWidth);
	var column = Math.floor(y/gapHeight);

	if(!isGameOver)
	{
		takeBackUp();
		if(turnCount%2 == 0 && (colorMatrix[column][row] == "" || colorMatrix[column][row] == "red"))
		{
			countMatrix[column][row]++;		//Weird graphic coordinate-system
			colorMatrix[column][row] = "red";
			turnCount++;
			flag = false;
		}
		if(turnCount%2 == 1 && (colorMatrix[column][row] == "" || colorMatrix[column][row] == "green"))
		{
			countMatrix[column][row]++;		//Weird graphic coordinate-system
			colorMatrix[column][row] = "green";
			turnCount++;
			flag = false;
		}
	}
}

function checkGameOver()
{
	if(gameOver() == 1 || gameOver() == 2)
	{
		isGameOver = true;
		gameOverScreen(gameOver());
		clearInterval(gameTimer);
		setTimeout(initialise, 4000);
	}
}

function populateCornerCells(i, j){
	countMatrix[i][j] -= 2;
	countMatrix[ i == 8 ? i-1 : i+1 ][j]++;
	countMatrix[i][ j==5 ? j-1 : j+1 ]++;
	colorMatrix[ i == 8 ? i-1 : i+1 ][j] = colorMatrix[i][j];
	colorMatrix[i][ j==5 ? j-1 : j+1 ] = colorMatrix[i][j];
	if(countMatrix[i][j] == 0)
		colorMatrix[i][j] = "";
	sound.play();
}

function populateSideHCells(i, j){  // H = Height
	countMatrix[i][j] -= 3;
	countMatrix[i-1][j]++;
	countMatrix[i+1][j]++;
	countMatrix[i][ j==0 ? j+1 : j-1 ]++;
	colorMatrix[i][ j==0 ? j+1 : j-1 ] = colorMatrix[i][j];
	colorMatrix[i-1][j] = colorMatrix[i][j];
	colorMatrix[i+1][j] = colorMatrix[i][j];
	if(countMatrix[i][j] == 0)
		colorMatrix[i][j] = "";
	sound.play();
}

function populateSideWCells(i, j) {  // W = Width
	countMatrix[i][j] -= 3;
	countMatrix[ i==0 ? i+1 : i-1 ][j]++;
	countMatrix[i][j-1]++;
	countMatrix[i][j+1]++;
	colorMatrix[ i==0 ? i+1 : i-1 ][j] = colorMatrix[i][j];
	colorMatrix[i][j-1] = colorMatrix[i][j];
	colorMatrix[i][j+1] = colorMatrix[i][j];
	if(countMatrix[i][j] == 0)
		colorMatrix[i][j] = "";
	sound.play();
}

function updateMatrix()
{
	counterAnimate++;
	drawArena();
	var cornerCord = [[0,0], [8,0], [8,5], [0,5]];

	while(notStable()){
		for(var i = 0; i < 4;i++)
			if(countMatrix[cornerCord[i][0]][cornerCord[i][1]] >= 2){ populateCornerCells(cornerCord[i][0], cornerCord[i][1]); break; }

		for(var i = 1; i < 8; i++){
			if(countMatrix[i][0] >= 3){ populateSideHCells(i, 0); break; }
			if(countMatrix[i][5] >= 3){ populateSideHCells(i, 5); break; }
		}

		for(var i = 1; i < 5; i++){
			if(countMatrix[0][i] >= 3){ populateSideWCells(0, i); break; }
			if(countMatrix[8][i] >= 3){ populateSideWCells(8, i); break; }
		}

		for(var i = 1; i < 8; i++){
			for(var j = 1; j < 5; j++){
				if(countMatrix[i][j] >= 4){
					countMatrix[i][j] -= 4;
					countMatrix[i-1][j]++;
					countMatrix[i+1][j]++;
					countMatrix[i][j-1]++;
					countMatrix[i][j+1]++;
					colorMatrix[i-1][j] = colorMatrix[i][j];
					colorMatrix[i+1][j] = colorMatrix[i][j];
					colorMatrix[i][j-1] = colorMatrix[i][j];
					colorMatrix[i][j+1] = colorMatrix[i][j];
					if(countMatrix[i][j] == 0)
						colorMatrix[i][j] = "";
					sound.play();
					break;
				}
			}
		}
		break;
	}
	checkGameOver();
}

function checkGameOver()
{
	if(gameOver() == 1 || gameOver() == 2)
	{
		isGameOver = true;
		gameOverScreen(gameOver());
		clearInterval(gameTimer);
		setTimeout(initialise, 4000);
	}
}

function notStable()
{
	var ans = false;
	if(countMatrix[0][0] >= 2 || countMatrix[8][0] >= 2 || countMatrix[8][5] >= 2 || countMatrix[0][5] >= 2)
		ans = true;

	for(var i = 1; i < 8; i++)
		if(countMatrix[i][0] >= 3 || countMatrix[i][5] >= 3)
			ans = true;

	for(var i = 1; i < 5; i++)
		if(countMatrix[0][i] >= 3 || countMatrix[8][i] >= 3)
			ans = true;

	for(var i = 1; i < 8; i++)
		for(var j = 1; j < 8; j++)
			if(countMatrix[i][j] >= 4)
				ans = true;

	return ans;
}

function gameOver()
{
	var countRed = 0;
	var countGreen = 0;
	for(var i = 0; i < 9; i++)
	{
		for(var j = 0;j < 6; j++)
		{
			if(colorMatrix[i][j] == "red") countRed++;
			if(colorMatrix[i][j] == "green") countGreen++;
		}
	}
	if(turnCount > 1)
	{
		if(countRed == 0)
		{
			return 2;
		}
		if(countGreen == 0)
		{
			return 1;
		}
	}
}

function gameOverScreen(player)
{
	if(player == 2)
	{
		gameArena.clearRect(0, 0, width, height);
		gameArena.fillStyle = "black";
		gameArena.fillRect(0, 0, width, height);
		gameArena.fillStyle = "white";
		gameArena.font = "40px Times New Roman";
		gameArena.fillText("Player 2 wins!", width/2 - 150, height/2 - 50);
	}
	else
	{
		gameArena.clearRect(0, 0, width, height);
		gameArena.fillStyle = "black";
		gameArena.fillRect(0, 0, width, height);
		gameArena.fillStyle = "white";
		gameArena.font = "40px Times New Roman";
		gameArena.fillText("Player 1 wins!", width/2 - 150, height/2 - 50);
	}
}

function oneCircle(row, column, color)
{
	gameArena.beginPath();
	gameArena.arc(column*gapWidth + 35, row*gapHeight + 35, 15, 0, Math.PI*2);
	gameArena.fillStyle = color;
	gameArena.fill();
	if((row == 0 && column == 0) || (row == 8 && column == 0) || (row == 0 && column == 5) || (row == 8 && column == 5))
	{
		if(counterAnimate%2 == 0)
			gameArena.strokeStyle = "black";
		else
			gameArena.strokeStyle = color;
	}
	else
	{
		gameArena.strokeStyle = "black";
	}
	gameArena.lineWidth = 3;
	gameArena.stroke();
	gameArena.closePath();
	gameArena.lineWidth = 1;
}

function twoCircle(row, column, color)
{
	gameArena.beginPath();
	gameArena.arc(column*gapWidth + 20, row*gapHeight + 35, 15, 0, Math.PI*2);
	gameArena.fillStyle = color;
	gameArena.fill();
	if(((row >= 1 && row < 8) && (column == 0 || column == 5)) || ((row == 0 || row == 8) && (column >= 1 && column < 5)))
	{
		if(counterAnimate%2 == 0)
			gameArena.strokeStyle = "black";
		else
			gameArena.strokeStyle = color;
	}
	else
	{
		gameArena.strokeStyle = "black";
	}
	gameArena.lineWidth = 3;
	gameArena.stroke();
	gameArena.closePath();
	gameArena.lineWidth = 1;

	gameArena.beginPath();
	gameArena.arc(column*gapWidth + 50, row*gapHeight + 35, 15, 0, Math.PI*2);
	gameArena.fillStyle = color;
	gameArena.fill();
	if(((row >= 1 && row < 8) && (column == 0 || column == 5)) || ((row == 0 || row == 8) && (column >= 1 && column < 5)))
	{
		if(counterAnimate%2 == 0)
			gameArena.strokeStyle = "black";
		else
			gameArena.strokeStyle = color;
	}
	else
	{
		gameArena.strokeStyle = "black";
	}
	gameArena.lineWidth = 3;
	gameArena.stroke();
	gameArena.closePath();
	gameArena.lineWidth = 1;
}

function threeCircle(row, column, color)
{
	gameArena.beginPath();
	gameArena.arc(column*gapWidth + 20, row*gapHeight + 17, 15, 0, Math.PI*2);
	gameArena.fillStyle = color;
	gameArena.fill();
	if(counterAnimate%2 == 0)
		gameArena.strokeStyle = "black";
	else
		gameArena.strokeStyle = color;
	gameArena.lineWidth = 3;
	gameArena.stroke();
	gameArena.closePath();
	gameArena.lineWidth = 1;

	gameArena.beginPath();
	gameArena.arc(column*gapWidth + 20, row*gapHeight + 53, 15, 0, Math.PI*2);
	gameArena.fillStyle = color;
	gameArena.fill();
	if(counterAnimate%2 == 0)
		gameArena.strokeStyle = "black";
	else
		gameArena.strokeStyle = color;
	gameArena.lineWidth = 3;
	gameArena.stroke();
	gameArena.closePath();
	gameArena.lineWidth = 1;

	gameArena.beginPath();
	gameArena.arc(column*gapWidth + 50, row*gapHeight + 35, 15, 0, Math.PI*2);
	gameArena.fillStyle = color;
	gameArena.fill();
	if(counterAnimate%2 == 0)
		gameArena.strokeStyle = "black";
	else
		gameArena.strokeStyle = color;
	gameArena.lineWidth = 3;
	gameArena.stroke();
	gameArena.closePath();
	gameArena.lineWidth = 1;
}<|endoftext|>


<commit_before>import React, { Component } from 'react'
import Link from '../components/Link'
import { Col, Row } from 'react-bootstrap'
import './blogs.scss'
import FloatedSection from '../components/floated-section'

export default class WorkPage extends Component {
  static title = 'Blogs'

  render() {
    return (

        <FloatedSection delay={300}>
          <Row>
            <Col sm={6}>

週休7日で働きたい

                  フリーランスしつつ自作サービス開発しながら食っていきたいブログ

My main blog in Japanese

            </Col>
            <Col sm={6}>

Work as Life

                  I’d like to quit my freelance career with my solo dev product.
                  Here to share my experiences of this journey with you.

英語のメインブログ

            </Col>
          </Row>
        </FloatedSection>
        <FloatedSection delay={400}>
          <Row>
            <Col sm={6}>

丁寧に手を抜く

ライフログ的な

My life logs in Japanese

            </Col>
          </Row>
        </FloatedSection>

    )
  }
}
<commit_msg>fix(blogs): update blog name<commit_after>import React, { Component } from 'react'
import Link from '../components/Link'
import { Col, Row } from 'react-bootstrap'
import './blogs.scss'
import FloatedSection from '../components/floated-section'

export default class WorkPage extends Component {
  static title = 'Blogs'

  render() {
    return (

        <FloatedSection delay={300}>
          <Row>
            <Col sm={6}>

週休7日で働きたい

                  フリーランスしつつ自作サービス開発しながら食っていきたいブログ

My main blog in Japanese

            </Col>
            <Col sm={6}>

Dev as Life

                  I’d like to quit my freelance career with my solo dev product.
                  Here to share my experiences of this journey with you.

英語のメインブログ

            </Col>
          </Row>
        </FloatedSection>
        <FloatedSection delay={400}>
          <Row>
            <Col sm={6}>

丁寧に手を抜く

ライフログ的な

My life logs in Japanese

            </Col>
          </Row>
        </FloatedSection>

    )
  }
}
<|endoftext|>


<commit_before>/*jshint esversion: 6 */
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import * as actions from './actions/index.js';
import store from './store';

const mapStateToProps = (state) => (state, store);

const mapDispatchToProps = (dispatch) =>
  bindActionCreators(actions, dispatch);

const Connection = (view)=>
  connect(mapStateToProps, mapDispatchToProps)(view);

export {mapStateToProps};
export default Connection;
<commit_msg>(fix) mapStateToProps<commit_after>/*jshint esversion: 6 */
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import * as actions from './actions/index.js';
import store from './store';

const mapStateToProps = () => (store);

const mapDispatchToProps = (dispatch) =>
  bindActionCreators(actions, dispatch);

const Connection = (view)=>
  connect(mapStateToProps, mapDispatchToProps)(view);

export {mapStateToProps};
export default Connection;
<|endoftext|>


<commit_before>var myApp = angular.module('appBus', [], function($interpolateProvider) {
   $interpolateProvider.startSymbol('[[');
   $interpolateProvider.endSymbol(']]');
});

myApp.controller("MyCtrl", function($scope, $http)
{
   $scope.bus = [];
   $scope.horarios = [];

   $http.get('http://localhost/Projetos/timebus/onibus')
   .success(function(response) {
      if (response.status == 200)
      {
         $scope.bus = angular.fromJson(response.dados);
      }
   }).error(function() {
      console.error('Arquivo .JSON não encontrado!')
   });

   $scope.getBus = function( ) {
      var linha = $scope.onibus.split(" - ");

      $http.get('http://localhost/Projetos/timebus/onibus/'+ linha[0])
      .success(function(response) {
         if (response.status == 200)
         {
            $scope.horarios = angular.fromJson(response.dados.horarios);
         }
      }).error(function() {
         console.error('Arquivo .JSON não encontrado!');
      });
   }

   $scope.download = function( ) {
      alert('ok');
   }

});

<commit_msg>Alterado url de requisição<commit_after>var myApp = angular.module('appBus', [], function($interpolateProvider) {
   $interpolateProvider.startSymbol('[[');
   $interpolateProvider.endSymbol(']]');
});

myApp.controller("MyCtrl", function($scope, $http)
{
   $scope.bus = [];
   $scope.horarios = [];

   $http.get('http://timebus.encontreumdoador.com.br/onibus')
   .success(function(response) {
      if (response.status == 200)
      {
         $scope.bus = angular.fromJson(response.dados);
      }
   }).error(function() {
      console.error('Arquivo .JSON não encontrado!')
   });

   $scope.getBus = function( ) {
      var linha = $scope.onibus.split(" - ");

      $http.get('http://timebus.encontreumdoador.com.br/onibus/'+ linha[0])
      .success(function(response) {
         if (response.status == 200)
         {
            $scope.horarios = angular.fromJson(response.dados.horarios);
         }
      }).error(function() {
         console.error('Arquivo .JSON não encontrado!');
      });
   }

   $scope.download = function( ) {
      alert('ok');
   }

});

<|endoftext|>


<commit_before>var LeavePage = function() {

  $('#submit_new_content').on('click', function() {
    window.btn_clicked = true;
  })

  window.onbeforeunload = function(event){
      if(!window.btn_clicked){
        // Need to add alert to prevent user from leaving page.
        if($('.edit_snippet')){
            var $url = $('.edit_snippet')[0].action;
            $.ajax({
              type: "DELETE",
              url: $url,
              dataType: "text"
            }).done(function(response){
              console.log("Success");
            });
        }
      }
  };
}
<commit_msg>Namespace DeleteSnippetWidget<commit_after>var DeleteSnippetWidget = {}

DeleteSnippetWidget.autoDeleteIncompleteSnippet = function() {
  var submitNewContentExists = document.getElementById("submit_new_content")
  if(submitNewContentExists) {
    this.LeavePage();
  }
}

DeleteSnippetWidget.LeavePage = function() {

  $('#submit_new_content').on('click', function() {
    window.btn_clicked = true;
  })

  window.onbeforeunload = function(event){
      if(!window.btn_clicked){
        // Need to add alert to prevent user from leaving page.
        if($('.edit_snippet')){
            var $url = $('.edit_snippet')[0].action;
            $.ajax({
              type: "DELETE",
              url: $url,
              dataType: "text"
            }).done(function(response){
              console.log("Success");
            });
        }
      }
  };
}
<|endoftext|>


<commit_before>const express = require('express')
const app = express()
const path = require('path')
const nunjucks = require('nunjucks')

// Set up App
const appViews = [
  path.join(__dirname, '/app/views/'),
  path.join(__dirname, '/app/templates/')
]

nunjucks.configure(appViews, {
  autoescape: true,
  express: app,
  noCache: true,
  watch: true
})

// Set views engine
app.set('view engine', 'html')

// Serve static content for the app from the "public" directory
app.use('/public', express.static(path.join(__dirname, '/public')))

// Send assetPath to all views
app.use(function (req, res, next) {
  res.locals.asset_path = '/public/'
  next()
})

// Render views/index
app.get('/', function (req, res) {
  res.render('index')
})

// Log when app is running
app.listen(3000, function () {
  console.log('App is running...')
})
<commit_msg>Update the output when the app is running<commit_after>const express = require('express')
const app = express()
const path = require('path')
const nunjucks = require('nunjucks')

// Set up App
const appViews = [
  path.join(__dirname, '/app/views/'),
  path.join(__dirname, '/app/templates/')
]

nunjucks.configure(appViews, {
  autoescape: true,
  express: app,
  noCache: true,
  watch: true
})

// Set views engine
app.set('view engine', 'html')

// Serve static content for the app from the "public" directory
app.use('/public', express.static(path.join(__dirname, '/public')))

// Send assetPath to all views
app.use(function (req, res, next) {
  res.locals.asset_path = '/public/'
  next()
})

// Render views/index
app.get('/', function (req, res) {
  res.render('index')
})

// Log when app is running
app.listen(3000, function () {
  console.log('GOV.UK Frontend Alpha\n')
  console.log('Listening on port 3000   url: http://localhost:3000')
})
<|endoftext|>


<commit_before>"use strict";

function setUserAgent() {
    document.getElementById("agent").innerHTML = navigator.userAgent;
}

function loginUser() {
    const userId = "pedro@loopsoftware.fr";
    document.location.replace(`loop://register?userId=${userId}`);
}

function handleDeviceCapabilities(capabilities) {
    if (capabilities.html5Camera === false) {
        // use the getCameraCapture() function to request the device to take use camera...
        alert("cannot use html5 camera...");
    } else {
        // use html5 camera capture to get photos...
        alert("can use html5 camera!");
    }

    // if (capabilities.html5Camera === true) {
    //     // use html5 camera capture to get photos...
    //     alert("can use html5 camera!");
    // } else {
    //     // use the getCameraCapture() function to request the device to take use camera...
    //     alert("cannot use html5 camera...");
    // }
}

function logoutUser() {
    const userId = "pedro@loopsoftware.fr";
    document.location.replace(`loop://unregister?userId=${userId}`);
}

function authoriseUser() {
    document.location.replace("loop://fingerprint");
}

function handleFingerprintResult(success) {
    alert("fingerprint scan: " + success);
}

function handleNotification(notification) {
    alert(notification.subject + ": " + notification.body);
}

function getCamera() {
    // navigator.mediaDevices.getUserMedia({ video: true })
    //     .then(gotMedia)
    //     .catch(error => console.error('getUserMedia() error:', error));
    document.location.replace("loop://camera");
}

function gotMedia(mediaStream) {
    const mediaStreamTrack = mediaStream.getVideoTracks()[0];
    const imageCapture = new ImageCapture(mediaStreamTrack);
    imageCapture.takePhoto()
        .then(blob => createImageBitmap(blob))
        .then(imageBitmap => {
            const canvas = document.querySelector("#photoCanvas");
            drawCanvas(canvas, imageBitmap);
        })
        .catch(error => console.error("gotMedia() error: ", error));
    console.log(imageCapture);
}

window.URL = window.URL || window.webkitURL;

var fileSelect = document.getElementById("fileSelect"),
    fileElem = document.getElementById("fileElem"),
    fileList = document.getElementById("fileList");

fileSelect.addEventListener("click", function (e) {
    if (fileElem) {
        fileElem.click();
    }
    e.preventDefault(); // prevent navigation to "#"
}, false);

function handleFiles(files) {
    if (!files.length) {
        fileList.innerHTML = "
No files selected!
";
    } else {
        fileList.innerHTML = "";
        var list = document.createElement("ul");
        fileList.appendChild(list);
        for (var i = 0; i < files.length; i++) {
            var li = document.createElement("li");
            list.appendChild(li);

            var img = document.createElement("img");
            img.src = window.URL.createObjectURL(files[i]);
            img.height = 60;
            img.onload = function () {
                window.URL.revokeObjectURL(this.src);
            }
            li.appendChild(img);
            var info = document.createElement("span");
            info.innerHTML = files[i].name + ": " + files[i].size + " bytes";
            li.appendChild(info);
        }
    }
}

function handleCameraResult(imgBase64) {
    alert("received image...");

    const image = new Image();
    image.onload = () => {
        const canvas = document.querySelector("#photoCanvas");
        const context = canvas.getContext("2d");

        context.drawImage(image, 0, 0, 800, 600);
    };

    image.src = imgBase64;
}

function showImage(imgBase64) {
    const imgElement = document.getElementById("image").src = imgBase64;
}

function drawCanvas(canvas, img) {
    canvas.width = getComputedStyle(canvas).width.split('px')[0];
    canvas.height = getComputedStyle(canvas).height.split('px')[0];
    let ratio = Math.min(canvas.width / img.width, canvas.height / img.height);
    let x = (canvas.width - img.width * ratio) / 2;
    let y = (canvas.height - img.height * ratio) / 2;
    canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height);
    canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height, x, y, img.width * ratio, img.height * ratio);
}

function handleFileSelect(evt) {
    const files = evt.target.files; // FileList object

    // files is a FileList of File objects. List some properties.
    const output = [];
    for (let i = 0, f; f = files[i]; i++) {
        output.push('
', escape(f.name), ' (', f.type || 'n/a', ')
',
            f.size, ' bytes
last modified: ',
            f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a',
            `<br/><img id="${escape(f.name)}" src="" alt="${escape(f.name)}" style="width:200px"/><br/>`,
            '
');
    }
    document.getElementById('list').innerHTML = '
' + output.join('') + '
';

    Array.from(files).forEach(file => {
        const reader = new FileReader();
        reader.onload = event => {
            document.getElementById(escape(file.name)).src = event.target.result;
        };
        reader.readAsDataURL(file);
    });
}

document.getElementById('files').addEventListener('change', handleFileSelect, false);
<commit_msg>x.x.x<commit_after>"use strict";

function setUserAgent() {
    document.getElementById("agent").innerHTML = navigator.userAgent;
}

function loginUser() {
    const userId = "pedro@loopsoftware.fr";
    document.location.replace(`loop://register?userId=${userId}`);
}

function handleDeviceCapabilities(capabilities) {
    if (capabilities.html5Camera === false) {
        // use the getCameraCapture() function to request the device to take use camera...
        alert("cannot use html5 camera...");
    } else {
        // use html5 camera capture to get photos...
        alert("can use html5 camera!");
    }

    // if (capabilities.html5Camera === true) {
    //     // use html5 camera capture to get photos...
    //     alert("can use html5 camera!");
    // } else {
    //     // use the getCameraCapture() function to request the device to take use camera...
    //     alert("cannot use html5 camera...");
    // }
}

function logoutUser() {
    const userId = "pedro@loopsoftware.fr";
    document.location.replace(`loop://unregister?userId=${userId}`);
}

function authoriseUser() {
    document.location.replace("loop://fingerprint");
}

function handleFingerprintResult(success) {
    alert("fingerprint scan: " + success);
}

function handleNotification(notification) {
    alert(notification.subject + ": " + notification.body);
}

function getCamera() {
    // navigator.mediaDevices.getUserMedia({ video: true })
    //     .then(gotMedia)
    //     .catch(error => console.error('getUserMedia() error:', error));
    document.location.replace("loop://camera");
}

function gotMedia(mediaStream) {
    const mediaStreamTrack = mediaStream.getVideoTracks()[0];
    const imageCapture = new ImageCapture(mediaStreamTrack);
    imageCapture.takePhoto()
        .then(blob => createImageBitmap(blob))
        .then(imageBitmap => {
            const canvas = document.querySelector("#photoCanvas");
            drawCanvas(canvas, imageBitmap);
        })
        .catch(error => console.error("gotMedia() error: ", error));
    console.log(imageCapture);
}

window.URL = window.URL || window.webkitURL;

var fileSelect = document.getElementById("fileSelect"),
    fileElem = document.getElementById("fileElem"),
    fileList = document.getElementById("fileList");

fileSelect.addEventListener("click", function (e) {
    if (fileElem) {
        fileElem.click();
    }
    e.preventDefault(); // prevent navigation to "#"
}, false);

function handleFiles(files) {
    if (!files.length) {
        fileList.innerHTML = "
No files selected!
";
    } else {
        fileList.innerHTML = "";
        var list = document.createElement("ul");
        fileList.appendChild(list);
        for (var i = 0; i < files.length; i++) {
            var li = document.createElement("li");
            list.appendChild(li);

            var img = document.createElement("img");
            img.src = window.URL.createObjectURL(files[i]);
            img.height = 60;
            img.onload = function () {
                window.URL.revokeObjectURL(this.src);
            }
            li.appendChild(img);
            var info = document.createElement("span");
            info.innerHTML = files[i].name + ": " + files[i].size + " bytes";
            li.appendChild(info);
        }
    }
}

function handleCameraResult(imgBase64) {
    switch (result) {
        case "no-camera":
            alert("no camera!");
            break;

        case "user-cancel":
            alert("user cancelled...");
            break;

        default:
            {
                alert("received image...");

                const image = new Image();
                image.onload = () => {
                    const canvas = document.querySelector("#photoCanvas");
                    const context = canvas.getContext("2d");

                    context.drawImage(image, 0, 0, 800, 600);
                };

                image.src = imgBase64;
            }
            break;
    }
}

function showImage(imgBase64) {
    const imgElement = document.getElementById("image").src = imgBase64;
}

function drawCanvas(canvas, img) {
    canvas.width = getComputedStyle(canvas).width.split('px')[0];
    canvas.height = getComputedStyle(canvas).height.split('px')[0];
    let ratio = Math.min(canvas.width / img.width, canvas.height / img.height);
    let x = (canvas.width - img.width * ratio) / 2;
    let y = (canvas.height - img.height * ratio) / 2;
    canvas.getContext('2d').clearRect(0, 0, canvas.width, canvas.height);
    canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height, x, y, img.width * ratio, img.height * ratio);
}

function handleFileSelect(evt) {
    const files = evt.target.files; // FileList object

    // files is a FileList of File objects. List some properties.
    const output = [];
    for (let i = 0, f; f = files[i]; i++) {
        output.push('
', escape(f.name), ' (', f.type || 'n/a', ')
',
            f.size, ' bytes
last modified: ',
            f.lastModifiedDate ? f.lastModifiedDate.toLocaleDateString() : 'n/a',
            `<br/><img id="${escape(f.name)}" src="" alt="${escape(f.name)}" style="width:200px"/><br/>`,
            '
');
    }
    document.getElementById('list').innerHTML = '
' + output.join('') + '
';

    Array.from(files).forEach(file => {
        const reader = new FileReader();
        reader.onload = event => {
            document.getElementById(escape(file.name)).src = event.target.result;
        };
        reader.readAsDataURL(file);
    });
}

document.getElementById('files').addEventListener('change', handleFileSelect, false);
<|endoftext|>


<commit_before>'use strict';

/**
 * Maintains an object tree from the runner events.
 *
 * @param {Object} runner The scenario Runner instance to connect to.
 *
 * TODO(esprehn): Every output type creates one of these, but we probably
 *  want one global shared instance. Need to handle events better too
 *  so the HTML output doesn't need to do spec model.getSpec(spec.id)
 *  silliness.
 *
 * TODO(vojta) refactor on, emit methods (from all objects) - use inheritance
 */
angular.scenario.ObjectModel = function(runner) {
  var self = this;

  this.specMap = {};
  this.listeners = [];
  this.value = {
    name: '',
    children: {}
  };

  runner.on('SpecBegin', function(spec) {
    var block = self.value,
        definitions = [];

    angular.forEach(self.getDefinitionPath(spec), function(def) {
      if (!block.children[def.name]) {
        block.children[def.name] = {
          id: def.id,
          name: def.name,
          children: {},
          specs: {}
        };
      }
      block = block.children[def.name];
      definitions.push(def.name);
    });

    var it = self.specMap[spec.id] =
             block.specs[spec.name] =
             new angular.scenario.ObjectModel.Spec(spec.id, spec.name, definitions);

    // forward the event
    self.emit('SpecBegin', it);
  });

  runner.on('SpecError', function(spec, error) {
    var it = self.getSpec(spec.id);
    it.status = 'error';
    it.error = error;

    // forward the event
    self.emit('SpecError', it, error);
  });

  runner.on('SpecEnd', function(spec) {
    var it = self.getSpec(spec.id);
    complete(it);

    // forward the event
    self.emit('SpecEnd', it);
  });

  runner.on('StepBegin', function(spec, step) {
    var it = self.getSpec(spec.id);
    step = new angular.scenario.ObjectModel.Step(step.name);
    it.steps.push(step);

    // forward the event
    self.emit('StepBegin', it, step);
  });

  runner.on('StepEnd', function(spec) {
    var it = self.getSpec(spec.id);
    var step = it.getLastStep();
    if (step.name !== step.name) {
      throw 'Events fired in the wrong order. Step names don\'t match.';
    }
    complete(step);

    // forward the event
    self.emit('StepEnd', it, step);
  });

  runner.on('StepFailure', function(spec, step, error) {
    var it = self.getSpec(spec.id),
        modelStep = it.getLastStep();

    modelStep.setErrorStatus('failure', error, step.line());
    it.setStatusFromStep(modelStep);

    // forward the event
    self.emit('StepFailure', it, modelStep, error);
  });

  runner.on('StepError', function(spec, step, error) {
    var it = self.getSpec(spec.id),
        modelStep = it.getLastStep();

    modelStep.setErrorStatus('error', error, step.line());
    it.setStatusFromStep(modelStep);

    // forward the event
    self.emit('StepError', it, modelStep, error);
  });

  runner.on('RunnerBegin', function() {
    self.emit('RunnerBegin');
  });
  runner.on('RunnerEnd', function() {
    self.emit('RunnerEnd');
  });

  function complete(item) {
    item.endTime = Date.now();
    item.duration = item.endTime - item.startTime;
    item.status = item.status || 'success';
  }
};

/**
 * Adds a listener for an event.
 *
 * @param {string} eventName Name of the event to add a handler for
 * @param {function()} listener Function that will be called when event is fired
 */
angular.scenario.ObjectModel.prototype.on = function(eventName, listener) {
  eventName = eventName.toLowerCase();
  this.listeners[eventName] = this.listeners[eventName] || [];
  this.listeners[eventName].push(listener);
};

/**
 * Emits an event which notifies listeners and passes extra
 * arguments.
 *
 * @param {string} eventName Name of the event to fire.
 */
angular.scenario.ObjectModel.prototype.emit = function(eventName) {
  var self = this,
      args = Array.prototype.slice.call(arguments, 1);

  eventName = eventName.toLowerCase();

  if (this.listeners[eventName]) {
    angular.forEach(this.listeners[eventName], function(listener) {
      listener.apply(self, args);
    });
  }
};

/**
 * Computes the path of definition describe blocks that wrap around
 * this spec.
 *
 * @param spec Spec to compute the path for.
 * @return {Array<Describe>} The describe block path
 */
angular.scenario.ObjectModel.prototype.getDefinitionPath = function(spec) {
  var path = [];
  var currentDefinition = spec.definition;
  while (currentDefinition && currentDefinition.name) {
    path.unshift(currentDefinition);
    currentDefinition = currentDefinition.parent;
  }
  return path;
};

/**
 * Gets a spec by id.
 *
 * @param {string} id The id of the spec to get the object for.
 * @return {Object} the Spec instance
 */
angular.scenario.ObjectModel.prototype.getSpec = function(id) {
  return this.specMap[id];
};

/**
 * A single it block.
 *
 * @param {string} id Id of the spec
 * @param {string} name Name of the spec
 * @param {Array<string>=} definitionNames List of all describe block names that wrap this spec
 */
angular.scenario.ObjectModel.Spec = function(id, name, definitionNames) {
  this.id = id;
  this.name = name;
  this.startTime = Date.now();
  this.steps = [];
  this.fullDefinitionName = (definitionNames || []).join(' ');
};

/**
 * Adds a new step to the Spec.
 *
 * @param {string} name Name of the step (really name of the future)
 * @return {Object} the added step
 */
angular.scenario.ObjectModel.Spec.prototype.addStep = function(name) {
  var step = new angular.scenario.ObjectModel.Step(name);
  this.steps.push(step);
  return step;
};

/**
 * Gets the most recent step.
 *
 * @return {Object} the step
 */
angular.scenario.ObjectModel.Spec.prototype.getLastStep = function() {
  return this.steps[this.steps.length - 1];
};

/**
 * Set status of the Spec from given Step
 *
 * @param {angular.scenario.ObjectModel.Step} step
 */
angular.scenario.ObjectModel.Spec.prototype.setStatusFromStep = function(step) {
  if (!this.status || step.status == 'error') {
    this.status = step.status;
    this.error = step.error;
    this.line = step.line;
  }
};

/**
 * A single step inside a Spec.
 *
 * @param {string} name Name of the step
 */
angular.scenario.ObjectModel.Step = function(name) {
  this.name = name;
  this.startTime = Date.now();
};

/**
 * Helper method for setting all error status related properties
 *
 * @param {string} status
 * @param {string} error
 * @param {string} line
 */
angular.scenario.ObjectModel.Step.prototype.setErrorStatus = function(status, error, line) {
  this.status = status;
  this.error = error;
  this.line = line;
};
<commit_msg>Updating src/ngScenario/ObjectModel.js, throw new Error<commit_after>'use strict';

/**
 * Maintains an object tree from the runner events.
 *
 * @param {Object} runner The scenario Runner instance to connect to.
 *
 * TODO(esprehn): Every output type creates one of these, but we probably
 *  want one global shared instance. Need to handle events better too
 *  so the HTML output doesn't need to do spec model.getSpec(spec.id)
 *  silliness.
 *
 * TODO(vojta) refactor on, emit methods (from all objects) - use inheritance
 */
angular.scenario.ObjectModel = function(runner) {
  var self = this;

  this.specMap = {};
  this.listeners = [];
  this.value = {
    name: '',
    children: {}
  };

  runner.on('SpecBegin', function(spec) {
    var block = self.value,
        definitions = [];

    angular.forEach(self.getDefinitionPath(spec), function(def) {
      if (!block.children[def.name]) {
        block.children[def.name] = {
          id: def.id,
          name: def.name,
          children: {},
          specs: {}
        };
      }
      block = block.children[def.name];
      definitions.push(def.name);
    });

    var it = self.specMap[spec.id] =
             block.specs[spec.name] =
             new angular.scenario.ObjectModel.Spec(spec.id, spec.name, definitions);

    // forward the event
    self.emit('SpecBegin', it);
  });

  runner.on('SpecError', function(spec, error) {
    var it = self.getSpec(spec.id);
    it.status = 'error';
    it.error = error;

    // forward the event
    self.emit('SpecError', it, error);
  });

  runner.on('SpecEnd', function(spec) {
    var it = self.getSpec(spec.id);
    complete(it);

    // forward the event
    self.emit('SpecEnd', it);
  });

  runner.on('StepBegin', function(spec, step) {
    var it = self.getSpec(spec.id);
    step = new angular.scenario.ObjectModel.Step(step.name);
    it.steps.push(step);

    // forward the event
    self.emit('StepBegin', it, step);
  });

  runner.on('StepEnd', function(spec) {
    var it = self.getSpec(spec.id);
    var step = it.getLastStep();
    if (step.name !== step.name) {
      throw new Error('Events fired in the wrong order. Step names don\'t match.');
    }
    complete(step);

    // forward the event
    self.emit('StepEnd', it, step);
  });

  runner.on('StepFailure', function(spec, step, error) {
    var it = self.getSpec(spec.id),
        modelStep = it.getLastStep();

    modelStep.setErrorStatus('failure', error, step.line());
    it.setStatusFromStep(modelStep);

    // forward the event
    self.emit('StepFailure', it, modelStep, error);
  });

  runner.on('StepError', function(spec, step, error) {
    var it = self.getSpec(spec.id),
        modelStep = it.getLastStep();

    modelStep.setErrorStatus('error', error, step.line());
    it.setStatusFromStep(modelStep);

    // forward the event
    self.emit('StepError', it, modelStep, error);
  });

  runner.on('RunnerBegin', function() {
    self.emit('RunnerBegin');
  });
  runner.on('RunnerEnd', function() {
    self.emit('RunnerEnd');
  });

  function complete(item) {
    item.endTime = Date.now();
    item.duration = item.endTime - item.startTime;
    item.status = item.status || 'success';
  }
};

/**
 * Adds a listener for an event.
 *
 * @param {string} eventName Name of the event to add a handler for
 * @param {function()} listener Function that will be called when event is fired
 */
angular.scenario.ObjectModel.prototype.on = function(eventName, listener) {
  eventName = eventName.toLowerCase();
  this.listeners[eventName] = this.listeners[eventName] || [];
  this.listeners[eventName].push(listener);
};

/**
 * Emits an event which notifies listeners and passes extra
 * arguments.
 *
 * @param {string} eventName Name of the event to fire.
 */
angular.scenario.ObjectModel.prototype.emit = function(eventName) {
  var self = this,
      args = Array.prototype.slice.call(arguments, 1);

  eventName = eventName.toLowerCase();

  if (this.listeners[eventName]) {
    angular.forEach(this.listeners[eventName], function(listener) {
      listener.apply(self, args);
    });
  }
};

/**
 * Computes the path of definition describe blocks that wrap around
 * this spec.
 *
 * @param spec Spec to compute the path for.
 * @return {Array<Describe>} The describe block path
 */
angular.scenario.ObjectModel.prototype.getDefinitionPath = function(spec) {
  var path = [];
  var currentDefinition = spec.definition;
  while (currentDefinition && currentDefinition.name) {
    path.unshift(currentDefinition);
    currentDefinition = currentDefinition.parent;
  }
  return path;
};

/**
 * Gets a spec by id.
 *
 * @param {string} id The id of the spec to get the object for.
 * @return {Object} the Spec instance
 */
angular.scenario.ObjectModel.prototype.getSpec = function(id) {
  return this.specMap[id];
};

/**
 * A single it block.
 *
 * @param {string} id Id of the spec
 * @param {string} name Name of the spec
 * @param {Array<string>=} definitionNames List of all describe block names that wrap this spec
 */
angular.scenario.ObjectModel.Spec = function(id, name, definitionNames) {
  this.id = id;
  this.name = name;
  this.startTime = Date.now();
  this.steps = [];
  this.fullDefinitionName = (definitionNames || []).join(' ');
};

/**
 * Adds a new step to the Spec.
 *
 * @param {string} name Name of the step (really name of the future)
 * @return {Object} the added step
 */
angular.scenario.ObjectModel.Spec.prototype.addStep = function(name) {
  var step = new angular.scenario.ObjectModel.Step(name);
  this.steps.push(step);
  return step;
};

/**
 * Gets the most recent step.
 *
 * @return {Object} the step
 */
angular.scenario.ObjectModel.Spec.prototype.getLastStep = function() {
  return this.steps[this.steps.length - 1];
};

/**
 * Set status of the Spec from given Step
 *
 * @param {angular.scenario.ObjectModel.Step} step
 */
angular.scenario.ObjectModel.Spec.prototype.setStatusFromStep = function(step) {
  if (!this.status || step.status == 'error') {
    this.status = step.status;
    this.error = step.error;
    this.line = step.line;
  }
};

/**
 * A single step inside a Spec.
 *
 * @param {string} name Name of the step
 */
angular.scenario.ObjectModel.Step = function(name) {
  this.name = name;
  this.startTime = Date.now();
};

/**
 * Helper method for setting all error status related properties
 *
 * @param {string} status
 * @param {string} error
 * @param {string} line
 */
angular.scenario.ObjectModel.Step.prototype.setErrorStatus = function(status, error, line) {
  this.status = status;
  this.error = error;
  this.line = line;
};
<|endoftext|>


<commit_before>/*globals CustomEvent*/
import Resolver from 'ember/resolver';

var App = Ember.Application.extend({
  LOG_ACTIVE_GENERATION   : true,
  LOG_MODULE_RESOLVER     : true,
  LOG_TRANSITIONS         : true,
  LOG_TRANSITIONS_INTERNAL: true,
  LOG_VIEW_LOOKUPS        : true,
  modulePrefix            : 'appkit', // TODO: loaded via config
  Resolver                : Resolver['default'],
  init: function () {
    window.ENV.firebaseRoot = new Firebase("https://" + window.ENV.dbName + ".firebaseio.com/");
    this._super.apply(this, arguments);
  }
});

Ember.Application.initializer({
  name: "BuildEnvironmentDetector",
  initialize: function (container, application) {
    application.deferReadiness();

    var self = this,
        buildEnv = Ember.Object.create();

    application.register('build-environment:environment:current', buildEnv, { instantiate: false, singleton: true });
    Ember.A(['model', 'controller', 'view', 'route']).forEach(function(component) {
      application.inject(component, 'buildEnvironment', 'build-environment:environment:current');
    });

    var isLocal = false;
    var localSocket = null;
    var keepReload = Ember.$('meta[name="keepReload"]').attr('content');
    if(document.location.hostname === "localhost" || document.location.hostname === "127.0.0.1")
    {
      isLocal = true;
      localSocket = {
        socket: new window.WebSocket('ws://localhost:6557'),
        doneCallback: null,
        connected: false
      };

      localSocket.socket.onmessage = function(event) {
        if(event.data === 'done') {
          if(localSocket.doneCallback) localSocket.doneCallback();
          localSocket.doneCallback = null; //Reset so done doesn't get called twice
        } else if (event.data.indexOf('done:') === 0) {
          var data = JSON.parse(event.data.replace('done:', ''));
          if(localSocket.doneCallback) localSocket.doneCallback(data);
          localSocket.doneCallback = null; //Reset so done doesn't get called twice
        }
      };

      localSocket.socket.onopen = function() {
        localSocket.connected = true;
      };

      if(!$('meta[name=suppressAlert]').attr('content')) {
        localSocket.socket.onclose = function() {
          alert('Local Socket unable to connect');
        };
      }

      // Shut down LiveReload
      if(window.LiveReload && !keepReload) {
        var shutDown = new CustomEvent('LiveReloadShutDown');
        document.addEventListener("LiveReloadConnect", function() {
          document.dispatchEvent(shutDown);
        }, false);
      }
    }

    buildEnv.set('local', isLocal);
    buildEnv.set('localSocket', localSocket);

    application.set('buildEnvironment', buildEnv);

    application.advanceReadiness();
  }
});

Ember.Application.initializer({
  name: "FirebaseSimpleLogin",
  initialize: function (container, application) {

    application.deferReadiness();

    var self = this,
        siteName = Ember.$('meta[name="siteName"]').attr('content'),
        session = Ember.Object.create();

    // Add `session` to all the things
    application.register('firebase-simple-login:session:current', session, { instantiate: false, singleton: true });
    Ember.A(['model', 'controller', 'view', 'route']).forEach(function(component) {
      application.inject(component, 'session', 'firebase-simple-login:session:current');
    });
    application.set('session', session);

    session.set('auth', new FirebaseSimpleLogin(window.ENV.firebaseRoot, function(error, user) {

      if (error) {
        // an error occurred while attempting login
        session.set('error', error);
        application.advanceReadiness();
      } else if (user) {

        window.ENV.firebaseRoot.child('management/sites/' + siteName + '/key').once('value', function (snapshot) {

          var bucket = snapshot.val();

          window.ENV.firebase = window.ENV.firebaseRoot.child('buckets/' + siteName + '/' + bucket + '/dev');

          // user authenticated with Firebase
          session.set('user', user);
          session.set('error', null);
          session.set('site', {
            name: siteName,
            token: bucket
          });
          application.advanceReadiness();
        }, function (error) {
          session.get('auth').logout();
          session.set('error', error);
          application.advanceReadiness();
        });
      } else {
        // user is logged out
        session.set('user', null);
        session.set('site', null);
        application.advanceReadiness();
      }
    }));

    window.ENV.sendBuildSignal = function() {
      var user = session.get('user.email');

      if(application.get('buildEnvironment').local === false)
      {
        var data = {
          'userid': user,
          'sitename': siteName
        };

        window.ENV.firebase.root().child('management/commands/build/' + siteName).set(data, function() {});
      } else {
        window.ENV.sendGruntCommand('build');
      }
    };

    window.ENV.sendGruntCommand = function(command, callback) {
      var localSocket = application.get('buildEnvironment').localSocket;
      if(localSocket && localSocket.connected) {
        localSocket.socket.send(command);
        if(callback) localSocket.doneCallback = callback;
      }
    }.bind(this);
  }
});

// Before any route, kick user to login if they aren't logged in
Ember.Route.reopen({
  beforeModel: function (transition) {
    var openRoutes = ['login', 'password-reset', 'create-user', 'confirm-email', 'resend-email'];
    if (Ember.$.inArray(transition.targetName, openRoutes) === -1 && !this.get('session.user')) {
      this.get('session').set('transition', transition);
      transition.abort();
      this.transitionTo('login');
    }
  }
});

// Ian doesn't like pluralizing, singularizing
Ember.Inflector.inflector.pluralize = function (string ) { return string; };
Ember.Inflector.inflector.singularize = function (string ) { return string; };

export default App;
<commit_msg>add window namespace so we pass the linter<commit_after>/*globals CustomEvent*/
import Resolver from 'ember/resolver';

var App = Ember.Application.extend({
  LOG_ACTIVE_GENERATION   : true,
  LOG_MODULE_RESOLVER     : true,
  LOG_TRANSITIONS         : true,
  LOG_TRANSITIONS_INTERNAL: true,
  LOG_VIEW_LOOKUPS        : true,
  modulePrefix            : 'appkit', // TODO: loaded via config
  Resolver                : Resolver['default'],
  init: function () {
    window.ENV.firebaseRoot = new Firebase("https://" + window.ENV.dbName + ".firebaseio.com/");
    this._super.apply(this, arguments);
  }
});

Ember.Application.initializer({
  name: "BuildEnvironmentDetector",
  initialize: function (container, application) {
    application.deferReadiness();

    var self = this,
        buildEnv = Ember.Object.create();

    application.register('build-environment:environment:current', buildEnv, { instantiate: false, singleton: true });
    Ember.A(['model', 'controller', 'view', 'route']).forEach(function(component) {
      application.inject(component, 'buildEnvironment', 'build-environment:environment:current');
    });

    var isLocal = false;
    var localSocket = null;
    var keepReload = Ember.$('meta[name="keepReload"]').attr('content');
    if(document.location.hostname === "localhost" || document.location.hostname === "127.0.0.1")
    {
      isLocal = true;
      localSocket = {
        socket: new window.WebSocket('ws://localhost:6557'),
        doneCallback: null,
        connected: false
      };

      localSocket.socket.onmessage = function(event) {
        if(event.data === 'done') {
          if(localSocket.doneCallback) localSocket.doneCallback();
          localSocket.doneCallback = null; //Reset so done doesn't get called twice
        } else if (event.data.indexOf('done:') === 0) {
          var data = JSON.parse(event.data.replace('done:', ''));
          if(localSocket.doneCallback) localSocket.doneCallback(data);
          localSocket.doneCallback = null; //Reset so done doesn't get called twice
        }
      };

      localSocket.socket.onopen = function() {
        localSocket.connected = true;
      };

      if(!$('meta[name=suppressAlert]').attr('content')) {
        localSocket.socket.onclose = function() {
          window.alert('Local Socket unable to connect');
        };
      }

      // Shut down LiveReload
      if(window.LiveReload && !keepReload) {
        var shutDown = new CustomEvent('LiveReloadShutDown');
        document.addEventListener("LiveReloadConnect", function() {
          document.dispatchEvent(shutDown);
        }, false);
      }
    }

    buildEnv.set('local', isLocal);
    buildEnv.set('localSocket', localSocket);

    application.set('buildEnvironment', buildEnv);

    application.advanceReadiness();
  }
});

Ember.Application.initializer({
  name: "FirebaseSimpleLogin",
  initialize: function (container, application) {

    application.deferReadiness();

    var self = this,
        siteName = Ember.$('meta[name="siteName"]').attr('content'),
        session = Ember.Object.create();

    // Add `session` to all the things
    application.register('firebase-simple-login:session:current', session, { instantiate: false, singleton: true });
    Ember.A(['model', 'controller', 'view', 'route']).forEach(function(component) {
      application.inject(component, 'session', 'firebase-simple-login:session:current');
    });
    application.set('session', session);

    session.set('auth', new FirebaseSimpleLogin(window.ENV.firebaseRoot, function(error, user) {

      if (error) {
        // an error occurred while attempting login
        session.set('error', error);
        application.advanceReadiness();
      } else if (user) {

        window.ENV.firebaseRoot.child('management/sites/' + siteName + '/key').once('value', function (snapshot) {

          var bucket = snapshot.val();

          window.ENV.firebase = window.ENV.firebaseRoot.child('buckets/' + siteName + '/' + bucket + '/dev');

          // user authenticated with Firebase
          session.set('user', user);
          session.set('error', null);
          session.set('site', {
            name: siteName,
            token: bucket
          });
          application.advanceReadiness();
        }, function (error) {
          session.get('auth').logout();
          session.set('error', error);
          application.advanceReadiness();
        });
      } else {
        // user is logged out
        session.set('user', null);
        session.set('site', null);
        application.advanceReadiness();
      }
    }));

    window.ENV.sendBuildSignal = function() {
      var user = session.get('user.email');

      if(application.get('buildEnvironment').local === false)
      {
        var data = {
          'userid': user,
          'sitename': siteName
        };

        window.ENV.firebase.root().child('management/commands/build/' + siteName).set(data, function() {});
      } else {
        window.ENV.sendGruntCommand('build');
      }
    };

    window.ENV.sendGruntCommand = function(command, callback) {
      var localSocket = application.get('buildEnvironment').localSocket;
      if(localSocket && localSocket.connected) {
        localSocket.socket.send(command);
        if(callback) localSocket.doneCallback = callback;
      }
    }.bind(this);
  }
});

// Before any route, kick user to login if they aren't logged in
Ember.Route.reopen({
  beforeModel: function (transition) {
    var openRoutes = ['login', 'password-reset', 'create-user', 'confirm-email', 'resend-email'];
    if (Ember.$.inArray(transition.targetName, openRoutes) === -1 && !this.get('session.user')) {
      this.get('session').set('transition', transition);
      transition.abort();
      this.transitionTo('login');
    }
  }
});

// Ian doesn't like pluralizing, singularizing
Ember.Inflector.inflector.pluralize = function (string ) { return string; };
Ember.Inflector.inflector.singularize = function (string ) { return string; };

export default App;
<|endoftext|>


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

    getTimeDifference();

});

  function Post(id, content, user_id, created_at, updated_at) {
    this.id = id;
    this.content = content;
    this.user_id = user_id;
    this.created_at = created_at;
    this.updated_at = updated_at;
  }

  function User(id, username) {
    this.id = id;
    this.username = username;
  }

  function getTimeDifference() {
    var activeUserIds = [];
    $.ajax({
      method: "get",
      url: "/posts.json",
      dataType: "json"
    }).success(function(data) {
      var post;

      // loop through objects to check to see if the difference is less than 7 days. If it is, put the user_id from that object into an array
      // once the array is full, get a list of users, compare their id to the user_id array to see if there is any matches and get a list of users
      // append the list of users to the dom.

      for(var key in data) {
        post = new Post(data[key]["id"], data[key]["content"], data[key]["user_id"], data[key]["created_at"], data[key]["updated_at"]);
        var splitData = post["created_at"].split("T");
        var splitDate = splitData[0].split("-");
        splitDate = splitDate.join(",");
        var prevTime = new Date(splitDate);  // Feb 1, 2011
        var thisTime = new Date();              // now
        var diff = thisTime.getTime() - prevTime.getTime();   // now - Feb 1
        var daysPast = (diff / (1000*60*60*24));
          if(daysPast < 8) {
            activeUserIds.push(post["user_id"]);
          }
        }

        addActiveUsers(activeUserIds);

    });
  }

  function addActiveUsers(userIdsArray) {
    // console.log(userIdsArray)
    var usernames = [];
    if(userIdsArray.length > 0) {
      $.get("/users", function(data) {
        // console.log("this is the data: " + data);
        for(var i=0; i < userIdsArray.length; i++) {

           for(var j=0; j< data.length; j++) {
             if(userIdsArray[i] === data[j]["id"]) {
              usernames.push(data[j]["username"]);
            }
          }
        }
        // console.log(usernames);
        $("#active-users").append("

");
        $.each(usernames, function(iterator, username) {
          $("#active-users ul").append("
" + username + "</li");
        })
       });
     } else {
      $("#active-users").append("
There have not been active users in the past 7 days
");
    }
  }
<commit_msg>refactored second function to use javascript model object<commit_after>$(document).ready(function() {

    getTimeDifference();

});

  function Post(id, content, user_id, created_at, updated_at) {
    this.id = id;
    this.content = content;
    this.user_id = user_id;
    this.created_at = created_at;
    this.updated_at = updated_at;
  }

  function User(id, username) {
    this.id = id;
    this.username = username;
  }

  function getTimeDifference() {
    var activeUserIds = [];
    $.ajax({
      method: "get",
      url: "/posts.json",
      dataType: "json"
    }).success(function(data) {
      var post;

      // loop through objects to check to see if the difference is less than 7 days. If it is, put the user_id from that object into an array
      // once the array is full, get a list of users, compare their id to the user_id array to see if there is any matches and get a list of users
      // append the list of users to the dom.

      for(var key in data) {
        post = new Post(data[key]["id"], data[key]["content"], data[key]["user_id"], data[key]["created_at"], data[key]["updated_at"]);
        var splitData = post["created_at"].split("T");
        var splitDate = splitData[0].split("-");
        splitDate = splitDate.join(",");
        var prevTime = new Date(splitDate);  // Feb 1, 2011
        var thisTime = new Date();              // now
        var diff = thisTime.getTime() - prevTime.getTime();   // now - Feb 1
        var daysPast = (diff / (1000*60*60*24));
          if(daysPast < 8) {
            activeUserIds.push(post["user_id"]);
          }
        }

        addActiveUsers(activeUserIds);

    });
  }

  function addActiveUsers(userIdsArray) {
    // console.log(userIdsArray)
    var usernames = [];
    if(userIdsArray.length > 0) {
      $.get("/users", function(data) {
      var user;
        // console.log("this is the data: " + data);
        //create new user object
        for(var key in data) {
          user = new User(data[key]["id"], data[key]["username"]);
        }
        for(var i=0; i < userIdsArray.length; i++) {

          //  for(var j=0; j< data.length; j++) {
             if(userIdsArray[i] === user["id"]) {
              usernames.push(user["username"]);
            }
          // }
        }
        // console.log(usernames);
        $("#active-users").append("

");
        $.each(usernames, function(iterator, username) {
          $("#active-users ul").append("
" + username + "</li");
        })
       });
     } else {
      $("#active-users").append("
There have not been active users in the past 7 days
");
    }
  }
<|endoftext|>