<commit_before>//  LauncherOSX
//
//  Created by Boris Schneiderman.
// Modified by Daniel Weck
//  Copyright (c) 2012-2013 The Readium Foundation.
//
//  The Readium SDK is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License

/////////////////////////
//SmilNode

ReadiumSDK.Models.Smil.SmilNode = function() {

    this.hasAncestor = function(node)
    {
        var parent = this.parent;
        while(parent)
        {
            if (parent == node)
            {
                return true;
            }

            parent = parent.parent;
        }

        return false;
    }
};

ReadiumSDK.Models.Smil.TimeContainerNode = function() {
    this.id = "";
    this.epubtype = "";
    this.index = undefined;
    this.parent = undefined;
    this.children = undefined;

    //root node is a smil model
    this.getSmil = function() {

        var node = this;
        while(node.parent) {
            node = node.parent;
        }

        return node;
    }

    this.isEscapable = function(userEscapables)
    {
        if (this.epubtype === "")
        {
            return false;
        }

        var smilModel = this.getSmil();
        if (!smilModel.mo)
        {
            return false;
        }

        var arr = smilModel.mo.escapables;
        if (userEscapables.length > 0)
        {
            arr = userEscapables;
        }

        for (var i = 0; i < arr.length; i++)
        {
            if (this.epubtype.indexOf(arr[i]) >= 0)
            {
                return true;
            }
        }

        return false;
    }

    this.isSkippable = function(userSkippables)
    {
        if (this.epubtype === "")
        {
            return false;
        }

        var smilModel = this.getSmil();
        if (!smilModel.mo)
        {
            return false;
        }

        var arr = smilModel.mo.skippables;
        if (userSkippables.length > 0)
        {
            arr = userSkippables;
        }

        for (var i = 0; i < arr.length; i++)
        {
            if (this.epubtype.indexOf(arr[i]) >= 0)
            {
                return true;
            }
        }

        return false;
    }
};

ReadiumSDK.Models.Smil.TimeContainerNode.prototype = new ReadiumSDK.Models.Smil.SmilNode();

//////////////////////////
//MediaNode

ReadiumSDK.Models.Smil.MediaNode = function() {
    this.src = "";
};

ReadiumSDK.Models.Smil.MediaNode.prototype = new ReadiumSDK.Models.Smil.SmilNode();

////////////////////////////
//SeqNode

ReadiumSDK.Models.Smil.SeqNode = function() {
    this.children = [];
    this.nodeType = "seq";
    this.textref = "";
};

ReadiumSDK.Models.Smil.SeqNode.prototype = new ReadiumSDK.Models.Smil.TimeContainerNode();

//////////////////////////
//ParNode

ReadiumSDK.Models.Smil.ParNode = function() {
    this.children = [];
    this.nodeType = "par";
    this.text = undefined;
    this.audio = undefined;
    this.element = undefined;
};

ReadiumSDK.Models.Smil.ParNode.prototype = new ReadiumSDK.Models.Smil.TimeContainerNode();

//////////////////////////
//TextNode

ReadiumSDK.Models.Smil.TextNode = function() {

    this.nodeType = "text";
    this.srcFile = "";
    this.srcFragmentId = "";
};

ReadiumSDK.Models.Smil.TextNode.prototype = new ReadiumSDK.Models.Smil.MediaNode();

///////////////////////////
//AudioNode

ReadiumSDK.Models.Smil.AudioNode = function() {

    this.nodeType = "audio";

    this.clipBegin = 0;

    this.MAX = 1234567890.1; //Number.MAX_VALUE - 0.1; //Infinity;
    this.clipEnd = this.MAX;
};

ReadiumSDK.Models.Smil.AudioNode.prototype = new ReadiumSDK.Models.Smil.MediaNode();

//////////////////////////////
//SmilModel

ReadiumSDK.Models.SmilModel = function() {

    this.children = []; //collection of seq or par smil nodes
    this.id = undefined; //manifest item id
    this.href = undefined; //href of the .smil source file
    this.duration = undefined;
    this.mo = undefined;
};

ReadiumSDK.Models.SmilModel.fromSmilDTO = function(smilDTO, mo) {

    if (mo.DEBUG)
    {
        console.debug("Media Overlay DTO import...");
    }

    var indent = 0;
    var getIndent = function()
    {
        var str = "";
        for (var i = 0; i < indent; i++)
        {
            str += "   ";
        }
        return str;
    }

    var smilModel = new ReadiumSDK.Models.SmilModel();
    smilModel.id = smilDTO.id;
    smilModel.spineItemId = smilDTO.spineItemId;
    smilModel.href = smilDTO.href;
    smilModel.smilVersion = smilDTO.smilVersion;

    smilModel.duration = smilDTO.duration;
    if (smilModel.duration && smilModel.duration.length && smilModel.duration.length > 0)
    {
        console.error("SMIL duration is string, parsing float... (" + smilModel.duration + ")");
        smilModel.duration = parseFloat(smilModel.duration);
    }

    smilModel.mo = mo; //ReadiumSDK.Models.MediaOverlay

    if (smilModel.mo.DEBUG)
    {
        console.log("JS MO smilVersion=" + smilModel.smilVersion);
        console.log("JS MO id=" + smilModel.id);
        console.log("JS MO spineItemId=" + smilModel.spineItemId);
        console.log("JS MO href=" + smilModel.href);
        console.log("JS MO duration=" + smilModel.duration);
    }

    var safeCopyProperty = function(property, from, to, isRequired) {

        if(property in from) {

            if( !(property in to) ) {
                console.debug("property " + property + " not declared in smil node " + to.nodeType);
            }

            to[property] = from[property];

            if (smilModel.mo.DEBUG)
            {
            console.log(getIndent() + "JS MO: [" + property + "=" + to[property] + "]");
            }
        }
        else if(isRequired) {
            console.error("Required property " + property + " not found in smil node " + from.nodeType);
        }
    };

    var createNodeFromDTO = function(nodeDTO, parent) {

        var node;

        if(nodeDTO.nodeType == "seq") {

            if (smilModel.mo.DEBUG)
            {
            console.log(getIndent() + "JS MO seq");
            }

            node = new ReadiumSDK.Models.Smil.SeqNode();
            node.parent = parent;
            safeCopyProperty("textref", nodeDTO, node, true);
            safeCopyProperty("id", nodeDTO, node);
            safeCopyProperty("epubtype", nodeDTO, node);

            indent++;
            copyChildren(nodeDTO, node);
            indent--;
        }
        else if (nodeDTO.nodeType == "par") {

            if (smilModel.mo.DEBUG)
            {
            console.log(getIndent() + "JS MO par");
            }

            node = new ReadiumSDK.Models.Smil.ParNode();
            node.parent = parent;
            safeCopyProperty("id", nodeDTO, node);
            safeCopyProperty("epubtype", nodeDTO, node);

            indent++;
            copyChildren(nodeDTO, node);
            indent--;

            for(var i = 0, count = node.children.length; i < count; i++) {
                var child = node.children[i];

                if(child.nodeType == "text") {
                    node.text = child;
                }
                else if(child.nodeType == "audio") {
                    node.audio = child;
                }
                else {
                    console.error("Unexpected smil node type: " + child.nodeType);
                }
            }

            if (!node.audio)
            {
                // synthetic speech (playback using TTS engine), or embedded media, or blank page
                var fakeAudio = new ReadiumSDK.Models.Smil.AudioNode();
                fakeAudio.parent = node;
                fakeAudio.clipBegin = 0;
                fakeAudio.clipEnd = fakeAudio.MAX;
                fakeAudio.src = undefined;

                node.audio = fakeAudio;
            }
        }
        else if (nodeDTO.nodeType == "text") {

            if (smilModel.mo.DEBUG)
            {
            console.log(getIndent() + "JS MO text");
            }

            node = new ReadiumSDK.Models.Smil.TextNode();
            node.parent = parent;
            safeCopyProperty("src", nodeDTO, node, true);
            safeCopyProperty("srcFile", nodeDTO, node, true);
            safeCopyProperty("srcFragmentId", nodeDTO, node, false);
            safeCopyProperty("id", nodeDTO, node);
        }
        else if (nodeDTO.nodeType == "audio") {

            if (smilModel.mo.DEBUG)
            {
            console.log(getIndent() + "JS MO audio");
            }

            node = new ReadiumSDK.Models.Smil.AudioNode();
            node.parent = parent;
            safeCopyProperty("src", nodeDTO, node, true);
            safeCopyProperty("id", nodeDTO, node);

            safeCopyProperty("clipBegin", nodeDTO, node);
            if (node.clipBegin && node.clipBegin.length && node.clipBegin.length > 0)
            {
                console.error("SMIL clipBegin is string, parsing float... (" + node.clipBegin + ")");
                node.clipBegin = parseFloat(node.clipBegin);
            }
            if (node.clipBegin < 0)
            {
                if (smilModel.mo.DEBUG)
                {
                    console.log(getIndent() + "JS MO clipBegin adjusted to ZERO");
                }
                node.clipBegin = 0;
            }

            safeCopyProperty("clipEnd", nodeDTO, node);
            if (node.clipEnd && node.clipEnd.length && node.clipEnd.length > 0)
            {
                console.error("SMIL clipEnd is string, parsing float... (" + node.clipEnd + ")");
                node.clipEnd = parseFloat(node.clipEnd);
            }
            if (node.clipEnd <= node.clipBegin)
            {
                if (smilModel.mo.DEBUG)
                {
                    console.log(getIndent() + "JS MO clipEnd adjusted to MAX");
                }
                node.clipEnd = node.MAX;
            }
        }
        else {
            console.error("Unexpected smil node type: " + nodeDTO.nodeType);
            return undefined;
        }

        return node;

    };

    var copyChildren = function(from, to) {

        var count = from.children.length;

        for(var i = 0; i < count; i++) {
            var node = createNodeFromDTO(from.children[i], to);
            node.index = i;
            to.children.push(node);
        }

    };

    copyChildren(smilDTO, smilModel);

    return smilModel;

};
<commit_msg>TTS force (for testing)<commit_after>//  LauncherOSX
//
//  Created by Boris Schneiderman.
// Modified by Daniel Weck
//  Copyright (c) 2012-2013 The Readium Foundation.
//
//  The Readium SDK is free software: you can redistribute it and/or modify
//  it under the terms of the GNU General Public License as published by
//  the Free Software Foundation, either version 3 of the License, or
//  (at your option) any later version.
//
//  This program is distributed in the hope that it will be useful,
//  but WITHOUT ANY WARRANTY; without even the implied warranty of
//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//  GNU General Public License for more details.
//
//  You should have received a copy of the GNU General Public License

/////////////////////////
//SmilNode

ReadiumSDK.Models.Smil.SmilNode = function() {

    this.hasAncestor = function(node)
    {
        var parent = this.parent;
        while(parent)
        {
            if (parent == node)
            {
                return true;
            }

            parent = parent.parent;
        }

        return false;
    }
};

ReadiumSDK.Models.Smil.TimeContainerNode = function() {
    this.id = "";
    this.epubtype = "";
    this.index = undefined;
    this.parent = undefined;
    this.children = undefined;

    //root node is a smil model
    this.getSmil = function() {

        var node = this;
        while(node.parent) {
            node = node.parent;
        }

        return node;
    }

    this.isEscapable = function(userEscapables)
    {
        if (this.epubtype === "")
        {
            return false;
        }

        var smilModel = this.getSmil();
        if (!smilModel.mo)
        {
            return false;
        }

        var arr = smilModel.mo.escapables;
        if (userEscapables.length > 0)
        {
            arr = userEscapables;
        }

        for (var i = 0; i < arr.length; i++)
        {
            if (this.epubtype.indexOf(arr[i]) >= 0)
            {
                return true;
            }
        }

        return false;
    }

    this.isSkippable = function(userSkippables)
    {
        if (this.epubtype === "")
        {
            return false;
        }

        var smilModel = this.getSmil();
        if (!smilModel.mo)
        {
            return false;
        }

        var arr = smilModel.mo.skippables;
        if (userSkippables.length > 0)
        {
            arr = userSkippables;
        }

        for (var i = 0; i < arr.length; i++)
        {
            if (this.epubtype.indexOf(arr[i]) >= 0)
            {
                return true;
            }
        }

        return false;
    }
};

ReadiumSDK.Models.Smil.TimeContainerNode.prototype = new ReadiumSDK.Models.Smil.SmilNode();

//////////////////////////
//MediaNode

ReadiumSDK.Models.Smil.MediaNode = function() {
    this.src = "";
};

ReadiumSDK.Models.Smil.MediaNode.prototype = new ReadiumSDK.Models.Smil.SmilNode();

////////////////////////////
//SeqNode

ReadiumSDK.Models.Smil.SeqNode = function() {
    this.children = [];
    this.nodeType = "seq";
    this.textref = "";
};

ReadiumSDK.Models.Smil.SeqNode.prototype = new ReadiumSDK.Models.Smil.TimeContainerNode();

//////////////////////////
//ParNode

ReadiumSDK.Models.Smil.ParNode = function() {
    this.children = [];
    this.nodeType = "par";
    this.text = undefined;
    this.audio = undefined;
    this.element = undefined;
};

ReadiumSDK.Models.Smil.ParNode.prototype = new ReadiumSDK.Models.Smil.TimeContainerNode();

//////////////////////////
//TextNode

ReadiumSDK.Models.Smil.TextNode = function() {

    this.nodeType = "text";
    this.srcFile = "";
    this.srcFragmentId = "";
};

ReadiumSDK.Models.Smil.TextNode.prototype = new ReadiumSDK.Models.Smil.MediaNode();

///////////////////////////
//AudioNode

ReadiumSDK.Models.Smil.AudioNode = function() {

    this.nodeType = "audio";

    this.clipBegin = 0;

    this.MAX = 1234567890.1; //Number.MAX_VALUE - 0.1; //Infinity;
    this.clipEnd = this.MAX;
};

ReadiumSDK.Models.Smil.AudioNode.prototype = new ReadiumSDK.Models.Smil.MediaNode();

//////////////////////////////
//SmilModel

ReadiumSDK.Models.SmilModel = function() {

    this.children = []; //collection of seq or par smil nodes
    this.id = undefined; //manifest item id
    this.href = undefined; //href of the .smil source file
    this.duration = undefined;
    this.mo = undefined;
};

ReadiumSDK.Models.SmilModel.fromSmilDTO = function(smilDTO, mo) {

    if (mo.DEBUG)
    {
        console.debug("Media Overlay DTO import...");
    }

    var indent = 0;
    var getIndent = function()
    {
        var str = "";
        for (var i = 0; i < indent; i++)
        {
            str += "   ";
        }
        return str;
    }

    var smilModel = new ReadiumSDK.Models.SmilModel();
    smilModel.id = smilDTO.id;
    smilModel.spineItemId = smilDTO.spineItemId;
    smilModel.href = smilDTO.href;
    smilModel.smilVersion = smilDTO.smilVersion;

    smilModel.duration = smilDTO.duration;
    if (smilModel.duration && smilModel.duration.length && smilModel.duration.length > 0)
    {
        console.error("SMIL duration is string, parsing float... (" + smilModel.duration + ")");
        smilModel.duration = parseFloat(smilModel.duration);
    }

    smilModel.mo = mo; //ReadiumSDK.Models.MediaOverlay

    if (smilModel.mo.DEBUG)
    {
        console.log("JS MO smilVersion=" + smilModel.smilVersion);
        console.log("JS MO id=" + smilModel.id);
        console.log("JS MO spineItemId=" + smilModel.spineItemId);
        console.log("JS MO href=" + smilModel.href);
        console.log("JS MO duration=" + smilModel.duration);
    }

    var safeCopyProperty = function(property, from, to, isRequired) {

        if(property in from) {

            if( !(property in to) ) {
                console.debug("property " + property + " not declared in smil node " + to.nodeType);
            }

            to[property] = from[property];

            if (smilModel.mo.DEBUG)
            {
            console.log(getIndent() + "JS MO: [" + property + "=" + to[property] + "]");
            }
        }
        else if(isRequired) {
            console.error("Required property " + property + " not found in smil node " + from.nodeType);
        }
    };

    var createNodeFromDTO = function(nodeDTO, parent) {

        var node;

        if(nodeDTO.nodeType == "seq") {

            if (smilModel.mo.DEBUG)
            {
            console.log(getIndent() + "JS MO seq");
            }

            node = new ReadiumSDK.Models.Smil.SeqNode();
            node.parent = parent;
            safeCopyProperty("textref", nodeDTO, node, true);
            safeCopyProperty("id", nodeDTO, node);
            safeCopyProperty("epubtype", nodeDTO, node);

            indent++;
            copyChildren(nodeDTO, node);
            indent--;
        }
        else if (nodeDTO.nodeType == "par") {

            if (smilModel.mo.DEBUG)
            {
            console.log(getIndent() + "JS MO par");
            }

            node = new ReadiumSDK.Models.Smil.ParNode();
            node.parent = parent;
            safeCopyProperty("id", nodeDTO, node);
            safeCopyProperty("epubtype", nodeDTO, node);

            indent++;
            copyChildren(nodeDTO, node);
            indent--;

            for(var i = 0, count = node.children.length; i < count; i++) {
                var child = node.children[i];

                if(child.nodeType == "text") {
                    node.text = child;
                }
                else if(child.nodeType == "audio") {
                    node.audio = child;
                }
                else {
                    console.error("Unexpected smil node type: " + child.nodeType);
                }
            }

            var forceTTS = false;
            if (forceTTS || !node.audio)
            {
                // synthetic speech (playback using TTS engine), or embedded media, or blank page
                var fakeAudio = new ReadiumSDK.Models.Smil.AudioNode();
                fakeAudio.parent = node;
                fakeAudio.clipBegin = 0;
                fakeAudio.clipEnd = fakeAudio.MAX;
                fakeAudio.src = undefined;

                node.audio = fakeAudio;
            }
        }
        else if (nodeDTO.nodeType == "text") {

            if (smilModel.mo.DEBUG)
            {
            console.log(getIndent() + "JS MO text");
            }

            node = new ReadiumSDK.Models.Smil.TextNode();
            node.parent = parent;
            safeCopyProperty("src", nodeDTO, node, true);
            safeCopyProperty("srcFile", nodeDTO, node, true);
            safeCopyProperty("srcFragmentId", nodeDTO, node, false);
            safeCopyProperty("id", nodeDTO, node);
        }
        else if (nodeDTO.nodeType == "audio") {

            if (smilModel.mo.DEBUG)
            {
            console.log(getIndent() + "JS MO audio");
            }

            node = new ReadiumSDK.Models.Smil.AudioNode();
            node.parent = parent;
            safeCopyProperty("src", nodeDTO, node, true);
            safeCopyProperty("id", nodeDTO, node);

            safeCopyProperty("clipBegin", nodeDTO, node);
            if (node.clipBegin && node.clipBegin.length && node.clipBegin.length > 0)
            {
                console.error("SMIL clipBegin is string, parsing float... (" + node.clipBegin + ")");
                node.clipBegin = parseFloat(node.clipBegin);
            }
            if (node.clipBegin < 0)
            {
                if (smilModel.mo.DEBUG)
                {
                    console.log(getIndent() + "JS MO clipBegin adjusted to ZERO");
                }
                node.clipBegin = 0;
            }

            safeCopyProperty("clipEnd", nodeDTO, node);
            if (node.clipEnd && node.clipEnd.length && node.clipEnd.length > 0)
            {
                console.error("SMIL clipEnd is string, parsing float... (" + node.clipEnd + ")");
                node.clipEnd = parseFloat(node.clipEnd);
            }
            if (node.clipEnd <= node.clipBegin)
            {
                if (smilModel.mo.DEBUG)
                {
                    console.log(getIndent() + "JS MO clipEnd adjusted to MAX");
                }
                node.clipEnd = node.MAX;
            }
        }
        else {
            console.error("Unexpected smil node type: " + nodeDTO.nodeType);
            return undefined;
        }

        return node;

    };

    var copyChildren = function(from, to) {

        var count = from.children.length;

        for(var i = 0; i < count; i++) {
            var node = createNodeFromDTO(from.children[i], to);
            node.index = i;
            to.children.push(node);
        }

    };

    copyChildren(smilDTO, smilModel);

    return smilModel;

};
<|endoftext|>


<commit_before>'use strict';

angular.module('openSenseMapApp')
  .controller('SidebarDownloadCtrl',
	["$scope", "$stateParams", "$http", "OpenSenseBox", "OpenSenseBoxAPI", "leafletData", function($scope, $stateParams, $http, OpenSenseBox, OpenSenseBoxAPI, leafletData){

	$scope.markersFiltered = $scope.$parent.markersFiltered;
	$scope.$watch('$parent.loading', function() {
        $scope.markersFiltered = $scope.$parent.markersFiltered;
    });

	$scope.osemapi = OpenSenseBoxAPI;
	$scope.inputFilter = $scope.inputFilter || {};
	$scope.downloadform = {
		format: 'CSV',
		pleaseWait: false,
		emptyData: false,
		errorOccured: false
	};

	$scope.openDatepicker = function($event) {
		$event.preventDefault();
		$event.stopPropagation();

		// prevent both date pickers from being opened at the same time
		if($event.currentTarget.id === "datepicker1") {
		  $scope.opened1 = true;
		  $scope.opened2 = false;
		} else if($event.currentTarget.id === "datepicker2") {
		  $scope.opened2 = true;
		  $scope.opened1 = false;
		}
	};

	$scope.endingDate = function(numDays){
		$scope.inputFilter.DateTo = new Date();
		$scope.inputFilter.DateFrom = new Date((new Date()).valueOf() - 1000*60*60*24*numDays);
	};

	leafletData.getMap("map_main").then(function(map) {
		$scope.count = $scope.countBbox(map).length;
		map.on('zoomend moveend', function(evt){
			$scope.count = $scope.countBbox(map).length;
		})
	});

	$scope.countBbox = function(map){
		var boxids = [];
		var bbox = map.getBounds();
		angular.forEach($scope.markersFiltered, function(marker, key) {
			if(bbox.contains([marker.lat, marker.lng])) {
				boxids.push(marker.station.id);
			}
		});
		return boxids;
	};

	$scope.dataDownload = function(){
		$scope.downloadform.pleaseWait = true;
		leafletData.getMap("map_main").then(function(map) {
			var boxids = $scope.countBbox(map);
			$http.post($scope.osemapi.url+'/boxes/data',{
				boxid: boxids.join(','),
				'to-date': $scope.inputFilter.DateTo,
				'from-date': $scope.inputFilter.DateFrom,
				phenomenon: $scope.inputFilter.Phenomenon
			})
			.success(function(data) {
				console.log(data.length);
				if(data.length>0){
					var blob = new Blob([data],{type:'text/csv'});
					var link = document.createElement('a');
					link.href = window.URL.createObjectURL(blob);
					link.download = $scope.inputFilter.Phenomenon+'.csv';
					link.click();
		        } else {
		        	$scope.downloadform.emptyData=true;
		        }
		        $scope.downloadform.pleaseWait = false;
			})
			.error(function(data, err) {
				$scope.downloadform.pleaseWait = false;
				if(data.length===0 && err === 404){
					$scope.downloadform.emptyData=true;
				} else {
					$scope.downloadform.errorOccured = true;
					console.log(err);
				}
			});
		});
	};

}]);<commit_msg>fix download in firefox<commit_after>'use strict';

angular.module('openSenseMapApp')
  .controller('SidebarDownloadCtrl',
	["$scope", "$stateParams", "$http", "OpenSenseBox", "OpenSenseBoxAPI", "leafletData", function($scope, $stateParams, $http, OpenSenseBox, OpenSenseBoxAPI, leafletData){

	$scope.markersFiltered = $scope.$parent.markersFiltered;
	$scope.$watch('$parent.loading', function() {
        $scope.markersFiltered = $scope.$parent.markersFiltered;
    });

	$scope.osemapi = OpenSenseBoxAPI;
	$scope.inputFilter = $scope.inputFilter || {};
	$scope.downloadform = {
		format: 'CSV',
		pleaseWait: false,
		emptyData: false,
		errorOccured: false
	};

	$scope.openDatepicker = function($event) {
		$event.preventDefault();
		$event.stopPropagation();

		// prevent both date pickers from being opened at the same time
		if($event.currentTarget.id === "datepicker1") {
		  $scope.opened1 = true;
		  $scope.opened2 = false;
		} else if($event.currentTarget.id === "datepicker2") {
		  $scope.opened2 = true;
		  $scope.opened1 = false;
		}
	};

	$scope.endingDate = function(numDays){
		$scope.inputFilter.DateTo = new Date();
		$scope.inputFilter.DateFrom = new Date((new Date()).valueOf() - 1000*60*60*24*numDays);
	};

	leafletData.getMap("map_main").then(function(map) {
		$scope.count = $scope.countBbox(map).length;
		map.on('zoomend moveend', function(evt){
			$scope.count = $scope.countBbox(map).length;
		})
	});

	$scope.countBbox = function(map){
		var boxids = [];
		var bbox = map.getBounds();
		angular.forEach($scope.markersFiltered, function(marker, key) {
			if(bbox.contains([marker.lat, marker.lng])) {
				boxids.push(marker.station.id);
			}
		});
		return boxids;
	};

	function stampDownload () {
		try {
			return "-" + new Date().toISOString().replace(/-|:|\.\d*Z/g,"").replace("T","_");
		} catch (e) {
			return "";
		}
	}

	$scope.dataDownload = function(){
		$scope.downloadform.pleaseWait = true;
		leafletData.getMap("map_main").then(function(map) {
			var boxids = $scope.countBbox(map);
			$http.post($scope.osemapi.url+'/boxes/data',{
				boxid: boxids.join(','),
				'to-date': $scope.inputFilter.DateTo,
				'from-date': $scope.inputFilter.DateFrom,
				phenomenon: $scope.inputFilter.Phenomenon
			})
			.success(function(data) {
				console.log(data.length);
				if(data.length>0){
					var blob = new Blob([data],{type:'text/csv;charset=utf-8;'});
					var link = document.createElement('a');
					link.href = window.URL.createObjectURL(blob);
					link.download = "opensensemap_org-download-" + encodeURI($scope.inputFilter.Phenomenon) + stampDownload() +'.csv';
					link.style.visibility = 'hidden';
					document.body.appendChild(link);
					link.click();
					document.body.removeChild(link);
				} else {
					$scope.downloadform.emptyData=true;
				}
				$scope.downloadform.pleaseWait = false;
			})
			.error(function(data, err) {
				$scope.downloadform.pleaseWait = false;
				if(data.length===0 && err === 404){
					$scope.downloadform.emptyData=true;
				} else {
					$scope.downloadform.errorOccured = true;
					console.log(err);
				}
			});
		});
	};

}]);
<|endoftext|>


<commit_before>(function(){

    angular.module("memoryApp")
    .controller("newGameController", newGameController);

    newGameController.$inject = ["$scope","screenService"];

    function newGameController($scope,screenService){

        $scope.runThis= function() {//this is newGameCanvas

            var canvas =document.getElementById("demoCanvas");
            canvas = screenService.setCanvasDPI(canvas,800,600);

            context =canvas.getContext("2d");
            canvas.style.backgroundColor = 'rgba(0, 255, 127, 0.8)';
            var stage = new createjs.Stage("demoCanvas");
            var text = new createjs.Text("Memory", "bold 120px Lato", "#f8f3f5");
            var text2 = new createjs.Text("start", "bold 30px Lato", "#000000");

            var img = new Image();
            img.src = "images/newGameCard.png"; // image from folder

                 cornercards = new createjs.Bitmap(img);
                 cornercards.x=-2;
                 cornercards.y=20;
                 cornercards.scaleX=0.5;
                 cornercards.scaleY=0.5;
                 cornercards.rotation= -30;

                 cornercards2 = new createjs.Bitmap(img);
                    cornercards2.x=canvas.width-46;
                    cornercards2.y=-10;
                    cornercards2.scaleX=0.5;
                    cornercards2.scaleY=0.5;
                    cornercards2.rotation= 30;

                 cornercards3 = new createjs.Bitmap(img);
                    cornercards3.x=50;
                    cornercards3.y=canvas.height+10;
                    cornercards3.scaleX=0.5;
                    cornercards3.scaleY=0.5;
                    cornercards3.rotation= -150;

                cornercards4 = new createjs.Bitmap(img);
                    cornercards4.x=canvas.width+8;
                    cornercards4.y=canvas.height-20;
                    cornercards4.scaleX=0.5;
                    cornercards4.scaleY=0.5;
                    cornercards4.rotation= 150;

            stage.addChild(cornercards,cornercards2,cornercards3,cornercards4);

            var graphics = new createjs.Graphics().beginFill("#000000").drawRect(canvas.width/2 -50, canvas.height/2+60, 100, 30);
            var shape = new createjs.Shape(graphics);

            graphics = new createjs.Graphics().beginFill("#ffffff").drawRect(canvas.width/2 - 49, canvas.height/2+61, 98, 28);
            var shape2 = new createjs.Shape(graphics);

            text.shadow=new createjs.Shadow("#000000", 5, 5, 10);
            text = screenService.centerThis(canvas,text);
            text2 = screenService.centerThis(canvas,text2);
            text2.y = text2.y+75;
            stage.enableMouseOver(10);

            textContainer = new createjs.Container();
            text.shadow=new createjs.Shadow("#000000", 5, 5, 10);
            textContainer.addChild(text);
            textContainer.shadow=new createjs.Shadow("#000000", 5, 5, 10);
            buttonContainer = new createjs.Container();
            buttonContainer.addChild(shape,shape2,text2);
            buttonContainer.cursor = "pointer";
            shape.shadow=shadow=new createjs.Shadow("#000000", 5, 5, 10);
            butWidth=buttonContainer.getBounds.width;
            butHeight=buttonContainer.getBounds.height;

            buttonContainer.addEventListener("click", function(event) {

                 });

            buttonContainer.on("mouseover", alterTheButton);
             buttonContainer.on("mouseout", changeButtonBack);

            function alterTheButton(event) {
                buttonContainer.alpha=0.8
            }

               function changeButtonBack(event) {
                buttonContainer.alpha=1
            }

            createjs.Ticker.setInterval(25);
            createjs.Ticker.setFPS(30);
            createjs.Ticker.addEventListener("tick", tick);

            function tick(event) {
                //buttonContainer.setBounds(370+x,380)
                //screenService.logPosition(buttonContainer)
                //createjs.Tween.get(buttonContainer).to({alpha:1}, 1000).call(handleComplete);
                stage.update();

            }

            stage.addChild(textContainer);
            stage.addChild(buttonContainer);
            stage.enableMouseOver();
            stage.update();
    }

    }//end Game Contoleer

})();<commit_msg>animate cards<commit_after>(function(){

    angular.module("memoryApp")
    .controller("newGameController", newGameController);

    newGameController.$inject = ["$scope","screenService"];

    function newGameController($scope,screenService){

        $scope.runThis= function() {//this is newGameCanvas

            var canvas =document.getElementById("demoCanvas");
            canvas = screenService.setCanvasDPI(canvas,800,600);

            context =canvas.getContext("2d");
            canvas.style.backgroundColor = 'rgba(0, 255, 127, 0.8)';
            var stage = new createjs.Stage("demoCanvas");
            var text = new createjs.Text("Memory", "bold 120px Lato", "#f8f3f5");
            var text2 = new createjs.Text("start", "bold 30px Lato", "#000000");

            var img = new Image();
            img.src = "images/newGameCard.png"; // image from folder

                 cornercards = new createjs.Bitmap(img);
                 cornercards.x=-2;
                 cornercards.y=20;
                 cornercards.scaleX=0.5;
                 cornercards.scaleY=0.5;
                 cornercards.rotation= -30;

                 cornercards2 = new createjs.Bitmap(img);
                    cornercards2.x=canvas.width-46;
                    cornercards2.y=-10;
                    cornercards2.scaleX=0.5;
                    cornercards2.scaleY=0.5;
                    cornercards2.rotation= 30;

                 cornercards3 = new createjs.Bitmap(img);
                    cornercards3.x=50;
                    cornercards3.y=canvas.height+10;
                    cornercards3.scaleX=0.5;
                    cornercards3.scaleY=0.5;
                    cornercards3.rotation= -150;

                cornercards4 = new createjs.Bitmap(img);
                    cornercards4.x=canvas.width+8;
                    cornercards4.y=canvas.height-20;
                    cornercards4.scaleX=0.5;
                    cornercards4.scaleY=0.5;
                    cornercards4.rotation= 150;

            img.onload =function(){
                stage.addChild(cornercards,cornercards2,cornercards3,cornercards4);
                stage.update();
            }
            stage.addChild(cornercards,cornercards2,cornercards3,cornercards4);

            var graphics = new createjs.Graphics().beginFill("#000000").drawRect(canvas.width/2 -50, canvas.height/2+60, 100, 30);
            var shape = new createjs.Shape(graphics);

            graphics = new createjs.Graphics().beginFill("#ffffff").drawRect(canvas.width/2 - 49, canvas.height/2+61, 98, 28);
            var shape2 = new createjs.Shape(graphics);

            text.shadow=new createjs.Shadow("#000000", 5, 5, 10);
            text = screenService.centerThis(canvas,text);
            text2 = screenService.centerThis(canvas,text2);
            text2.y = text2.y+75;
            stage.enableMouseOver(10);

            textContainer = new createjs.Container();
            text.shadow=new createjs.Shadow("#000000", 5, 5, 10);
            textContainer.addChild(text);
            textContainer.shadow=new createjs.Shadow("#000000", 5, 5, 10);
            buttonContainer = new createjs.Container();
            buttonContainer.addChild(shape,shape2,text2);
            buttonContainer.cursor = "pointer";
            shape.shadow=shadow=new createjs.Shadow("#000000", 5, 5, 10);
            butWidth=buttonContainer.getBounds.width;
            butHeight=buttonContainer.getBounds.height;

            buttonContainer.addEventListener("click", function(event) {
                var speed=1000;
              createjs.Tween.get(cornercards4, { loop: true })
                .to({ x: 50, y:canvas.height+10, rotation:210 }, speed, createjs.Ease.getPowInOut(4))
                .to({ x: -2, y:20, rotation:330 }, speed, createjs.Ease.getPowInOut(4))
                .to({ x: canvas.width-46, y:-10, rotation:390 }, speed, createjs.Ease.getPowInOut(4))
                .to({ x: canvas.width+8, y:canvas.height-20, rotation:510 }, speed, createjs.Ease.getPowInOut(4))

                createjs.Tween.get(cornercards3, { loop: true })
                .to({ x: -2, y:20, rotation:-30 }, speed, createjs.Ease.getPowInOut(4))
                .to({ x: canvas.width-46, y:-10, rotation:30 }, speed, createjs.Ease.getPowInOut(4))
                .to({ x: canvas.width+8, y:canvas.height-20, rotation:150 }, speed, createjs.Ease.getPowInOut(4))
                .to({ x: 50, y:canvas.height+10, rotation:210 }, speed, createjs.Ease.getPowInOut(4))

                createjs.Tween.get(cornercards, { loop: true })

                .to({ x: canvas.width-46, y:-10, rotation:30 }, speed, createjs.Ease.getPowInOut(4))
                .to({ x: canvas.width+8, y:canvas.height-20, rotation:150 }, speed, createjs.Ease.getPowInOut(4))
                .to({ x: 50, y:canvas.height+10, rotation:210 }, speed, createjs.Ease.getPowInOut(4))
                .to({ x: -2, y:20, rotation:330 }, speed, createjs.Ease.getPowInOut(4))

                 createjs.Tween.get(cornercards2, { loop: true })
                .to({ x: canvas.width+8, y:canvas.height-20, rotation:150 }, speed, createjs.Ease.getPowInOut(4))
                .to({ x: 50, y:canvas.height+10, rotation:210 }, speed, createjs.Ease.getPowInOut(4))
                .to({ x: -2, y:20, rotation:330 }, speed, createjs.Ease.getPowInOut(4))
                 .to({ x: canvas.width-46, y:-10, rotation:390 }, speed, createjs.Ease.getPowInOut(4))
            });

            buttonContainer.on("mouseover", alterTheButton);
             buttonContainer.on("mouseout", changeButtonBack);

            function alterTheButton(event) {
                buttonContainer.alpha=0.8
            }

               function changeButtonBack(event) {
                buttonContainer.alpha=1
            }

            createjs.Ticker.setInterval(25);
            createjs.Ticker.setFPS(30);
            createjs.Ticker.addEventListener("tick", tick);

            createjs.Ticker.addEventListener("tick", stage);

            function tick(event) {
                //buttonContainer.setBounds(370+x,380)
                //screenService.logPosition(buttonContainer)
                //createjs.Tween.get(buttonContainer).to({alpha:1}, 1000).call(handleComplete);
                //stage.update();

            }

            stage.addChild(textContainer);
            stage.addChild(buttonContainer);
            stage.enableMouseOver();
            stage.update();
    }

    }//end Game Contoleer

})();<|endoftext|>


<commit_before>module.exports = function(opts) {
  var through = require('through2'),
    gutil = require('gulp-util'),
    glob = require('glob'),
    CleanCSS = require('clean-css'),
    autoprefixer = require('autoprefixer-core'),
    uglifyJs = require('uglify-js'),
    uglify = uglifyJs.uglify,
    parser = uglifyJs.parser,
    path = require('path'),
    fs = require('fs');

  var START_REG = /<!--\s*build:(\w+)\s*([^\s]+)\s*-->/gim,
    END_REG = /<!--\s*endbuild\s*-->/gim,
    JSFILE_REG = /<script\s+.*src=(?:"|')([^"']+?)(?:"|').*><\/script>/gi,
    CSSFILE_REG = /<link\s+.*href\s*=\s*(?:"|')([^"']+)(?:"|').*>/gi,
    IMPORT_REG = /@import\s*url\((?:'|")?([^\s]+)(?:'|")?\)[\s\;]?/gi;

  opts = mergeObj({
    root: process.cwd().replace(/\\/g, '/'),
    assetsDir: ''
  }, opts);

  function mergeObj(source1, source2) {
    var target = {};
    for (var key1 in source1) {
      target[key1] = source1[key1];
    }
    for (var key2 in source2) {
      target[key2] = source2[key2];
    }
    return target;
  }

  function resolveSrc(p, relativeDir) {
    switch (true) {
      case !path.isAbsolute(p):
        p = path.join(relativeDir, p);
        break;
      case p[0] === '/':
        p = path.join(opts.root, opts.assetsDir, p);
        break;
    }
    return path.resolve(p).replace(/\\/g, '/');
  }

  function resolveDest(p, base) {
    p = p.replace(base, '');
    return path.resolve(p).replace(/^\//i, '');
  }

  function getNewImports(filepath, content, included) {
    var newPaths = [];
    content.replace(IMPORT_REG, function(g, p) {
      p = resolveSrc(p, path.dirname(filepath));
      if (included.indexOf(p) === -1) {
        newPaths.push(p);
      }
    });
    return newPaths;
  }

  function concatSource(paths) {
    var source = '';
    for (var i = 0; i < paths.length; i) {
      var p = paths[i];

      if (glob.sync(p)[0] === undefined) {
        throw new gutil.PluginError('gulp-htmlbuild', 'file ' + p + ' not found\n');
      }

      var _source = fs.readFileSync(p).toString();

      // 支持 @import url(import.css)
      if (path.extname(p) === '.css') {
        var newPaths = getNewImports(p, _source, paths);

        // 推入paths数组，位置紧邻 i 前面
        if (newPaths.length) {
          Array.prototype.splice.apply(paths, [i, 0].concat(newPaths));
          continue;
        }
        _source = _source.replace(IMPORT_REG, '');
      }
      source += _source;
      i += 1;
    }
    return source;
  }

  /*
   * do autoprefixer, clean-css
   */
  function optimizeCss(source) {
    var ret = '';
    // autoprefixer
    ret = autoprefixer.process(source, {
      safe: true,
      browsers: ['> 2%', 'last 4 versions', 'Firefox ESR', 'iOS >= 6', 'Android >= 2.3', 'ExplorerMobile >= 10']
    }).css;
    // minify
    ret = new CleanCSS({
      advanced: false,
      keepSpecialComments: 0,
      processImport: false,
      rebase: false
    }).minify(ret).styles;

    return ret;
  }

  /*
   * do uglify
   */
  function optimizeJs(source) {
    var ret = '';
    ret = parser.parse(source);
    ret = uglify.ast_mangle(ret, {
      except: ['require', 'exports', 'module']
    });
    ret = uglify.ast_lift_variables(ret);
    ret = uglify.ast_squeeze(ret);
    ret = uglify.gen_code(ret, {
      'quote_keys': true
    });
    return ret;
  }

  function inlineOptimze() {

  }

  function Builder(file, push) {
    this.push = push;

    this.filebase = file.base.replace(/\\/g, '/');
    this.filepath = file.path.replace(/\\/g, '/');
    this.filedir = path.dirname(this.filepath).replace(/\\/g, '/');

    var result = this.analysis(file);
    this.pushHtmlFile(result.blocks).pushStaticFile(result.files);
  }

  Builder.prototype = {
    /*
     * 分析 html 代码
     * return {blocks: ['html代码块'], files: [{type: 'css', paths: ['static file path']}]}
     */
    analysis: function(file) {
      var sections = file.contents.toString().split(END_REG);

      var blocks = [],
        files = [];

      var self = this;

      sections.forEach(function(s) {
        if (s.match(START_REG)) {
          // s[0] html code
          // s[1] string 'css' or 'js'
          // s[2] string dest url
          // s[3] tags of link or script
          s = s.split(START_REG);
          blocks.push(s[0]);
          switch (s[1]) {
            case 'css':
              blocks.push('<link rel="stylesheet" href="' + s[2] + '">');
              break;
            case 'js':
              blocks.push('<script src="' + s[2] + '"></script>');
              break;
            default:
              throw new gutil.PluginError('gulp-htmlbuild', 'only build:css build:js accept\n');
          }
          var paths = self.matchContentPaths(s[1] === 'css' ? CSSFILE_REG : JSFILE_REG, s[3]);
          var source = concatSource(paths);
          files.push({
            type: s[1],
            dest: resolveSrc(s[2], self.filedir),
            source: source
          });
        } else {
          blocks.push(s);
        }
      });

      return {
        blocks: blocks,
        files: files
      }
    },
    matchContentPaths: function(reg, content) {
      var self = this;
      var paths = [];
      content.replace(reg, function(g, p) {
        p = resolveSrc(p, self.filedir);
        paths.push(p);
      });
      return paths;
    },
    pushHtmlFile: function(blocks) {
      var dest = resolveDest(this.filepath, this.filebase);

      var htmlFile = new gutil.File({
        path: dest,
        contents: new Buffer(blocks.join(''))
      });
      this.push(htmlFile);
      return this;
    },
    pushStaticFile: function(groups) {
      var self = this;
      groups.forEach(function(group) {
        var dest = resolveDest(group.dest, self.filebase);

        var optimizeFun = group.type === 'css' ? optimizeCss : optimizeJs;
        var optimized = optimizeFun(group.source);

        self.push(new gutil.File({
          path: dest,
          contents: new Buffer(optimized)
        }));
      });
      return this;
    }
  };

  return through.obj(function(file, enc, cb) {
    if (file.isStream()) {
      this.emit('error', new gutil.PluginError('gulp-htmlbuild', 'Streams are not supported!\n'));
      cb();
    } else if (file.isNull()) {
      cb(null, file);
    } else {
      try {
        new Builder(file, this.push.bind(this));
      } catch (e) {
        this.emit('error', e);
      } finally {
        cb();
      }
    }
  });
};<commit_msg>fix dest bug<commit_after>module.exports = function(opts) {
  var through = require('through2'),
    gutil = require('gulp-util'),
    glob = require('glob'),
    CleanCSS = require('clean-css'),
    autoprefixer = require('autoprefixer-core'),
    uglifyJs = require('uglify-js'),
    uglify = uglifyJs.uglify,
    parser = uglifyJs.parser,
    path = require('path'),
    fs = require('fs');

  var START_REG = /<!--\s*build:(\w+)\s*([^\s]+)\s*-->/gim,
    END_REG = /<!--\s*endbuild\s*-->/gim,
    JSFILE_REG = /<script\s+.*src=(?:"|')([^"']+?)(?:"|').*><\/script>/gi,
    CSSFILE_REG = /<link\s+.*href\s*=\s*(?:"|')([^"']+)(?:"|').*>/gi,
    IMPORT_REG = /@import\s*url\((?:'|")?([^\s]+)(?:'|")?\)[\s\;]?/gi;

  opts = mergeObj({
    root: process.cwd().replace(/\\/g, '/'),
    assetsDir: ''
  }, opts);

  function mergeObj(source1, source2) {
    var target = {};
    for (var key1 in source1) {
      target[key1] = source1[key1];
    }
    for (var key2 in source2) {
      target[key2] = source2[key2];
    }
    return target;
  }

  function resolveSrc(p, relativeDir) {
    switch (true) {
      case !path.isAbsolute(p):
        p = path.join(relativeDir, p);
        break;
      case p[0] === '/':
        p = path.join(opts.root, opts.assetsDir, p);
        break;
    }
    return path.resolve(p).replace(/\\/g, '/');
  }

  function relativeDest(p, base) {
    return p.replace(base, '').replace(opts.root, '').replace(/^\//i, '');
  }

  function getNewImports(filepath, content, included) {
    var newPaths = [];
    content.replace(IMPORT_REG, function(g, p) {
      p = resolveSrc(p, path.dirname(filepath));
      if (included.indexOf(p) === -1) {
        newPaths.push(p);
      }
    });
    return newPaths;
  }

  function concatSource(paths) {
    var source = '';
    for (var i = 0; i < paths.length; i) {
      var p = paths[i];

      if (glob.sync(p)[0] === undefined) {
        throw new gutil.PluginError('gulp-htmlbuild', 'file ' + p + ' not found\n');
      }

      var _source = fs.readFileSync(p).toString();

      // 支持 @import url(import.css)
      if (path.extname(p) === '.css') {
        var newPaths = getNewImports(p, _source, paths);

        // 推入paths数组，位置紧邻 i 前面
        if (newPaths.length) {
          Array.prototype.splice.apply(paths, [i, 0].concat(newPaths));
          continue;
        }
        _source = _source.replace(IMPORT_REG, '');
      }
      source += _source;
      i += 1;
    }
    return source;
  }

  /*
   * do autoprefixer, clean-css
   */
  function optimizeCss(source) {
    var ret = '';
    // autoprefixer
    ret = autoprefixer.process(source, {
      safe: true,
      browsers: ['> 2%', 'last 4 versions', 'Firefox ESR', 'iOS >= 6', 'Android >= 2.3', 'ExplorerMobile >= 10']
    }).css;
    // minify
    ret = new CleanCSS({
      advanced: false,
      keepSpecialComments: 0,
      processImport: false,
      rebase: false
    }).minify(ret).styles;

    return ret;
  }

  /*
   * do uglify
   */
  function optimizeJs(source) {
    var ret = '';
    ret = parser.parse(source);
    ret = uglify.ast_mangle(ret, {
      except: ['require', 'exports', 'module']
    });
    ret = uglify.ast_lift_variables(ret);
    ret = uglify.ast_squeeze(ret);
    ret = uglify.gen_code(ret, {
      'quote_keys': true
    });
    return ret;
  }

  function inlineOptimze() {

  }

  function Builder(file, push) {
    this.push = push;

    this.filebase = file.base.replace(/\\/g, '/');
    this.filepath = file.path.replace(/\\/g, '/');
    this.filedir = path.dirname(this.filepath).replace(/\\/g, '/');

    var result = this.analysis(file);
    this.pushHtmlFile(result.blocks).pushStaticFile(result.files);
  }

  Builder.prototype = {
    /*
     * 分析 html 代码
     * return {blocks: ['html代码块'], files: [{type: 'css', paths: ['static file path']}]}
     */
    analysis: function(file) {
      var sections = file.contents.toString().split(END_REG);

      var blocks = [],
        files = [];

      var self = this;

      sections.forEach(function(s) {
        if (s.match(START_REG)) {
          // s[0] html code
          // s[1] string 'css' or 'js'
          // s[2] string dest url
          // s[3] tags of link or script
          s = s.split(START_REG);
          blocks.push(s[0]);
          switch (s[1]) {
            case 'css':
              blocks.push('<link rel="stylesheet" href="' + s[2] + '">');
              break;
            case 'js':
              blocks.push('<script src="' + s[2] + '"></script>');
              break;
            default:
              throw new gutil.PluginError('gulp-htmlbuild', 'only build:css build:js accept\n');
          }
          var paths = self.matchContentPaths(s[1] === 'css' ? CSSFILE_REG : JSFILE_REG, s[3]);
          var source = concatSource(paths);
          files.push({
            type: s[1],
            dest: resolveSrc(s[2], self.filedir),
            source: source
          });
        } else {
          blocks.push(s);
        }
      });

      return {
        blocks: blocks,
        files: files
      }
    },
    matchContentPaths: function(reg, content) {
      var self = this;
      var paths = [];
      content.replace(reg, function(g, p) {
        p = resolveSrc(p, self.filedir);
        paths.push(p);
      });
      return paths;
    },
    pushHtmlFile: function(blocks) {
      var dest = relativeDest(this.filepath, this.filebase);
      console.log(dest);
      var htmlFile = new gutil.File({
        path: dest,
        contents: new Buffer(blocks.join(''))
      });
      this.push(htmlFile);
      return this;
    },
    pushStaticFile: function(groups) {
      var self = this;
      groups.forEach(function(group) {
        console.log('group dest', group.dest);
        var dest = relativeDest(group.dest, self.filebase);
        console.log(dest);
        var optimizeFun = group.type === 'css' ? optimizeCss : optimizeJs;
        var optimized = optimizeFun(group.source);

        self.push(new gutil.File({
          path: dest,
          contents: new Buffer(optimized)
        }));
      });
      return this;
    }
  };

  return through.obj(function(file, enc, cb) {
    if (file.isStream()) {
      this.emit('error', new gutil.PluginError('gulp-htmlbuild', 'Streams are not supported!\n'));
      cb();
    } else if (file.isNull()) {
      cb(null, file);
    } else {
      try {
        new Builder(file, this.push.bind(this));
      } catch (e) {
        this.emit('error', e);
      } finally {
        cb();
      }
    }
  });
};<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import {autobind} from 'core-decorators';
import yubikiri from 'yubikiri';

import {RemotePropType} from '../prop-types';
import ObserveModelDecorator from '../decorators/observe-model';
import GithubLoginView from '../views/github-login-view';
import {UNAUTHENTICATED} from '../shared/keytar-strategy';
import {nullRemote} from '../models/remote';
import PrInfoController from './pr-info-controller';

@ObserveModelDecorator({
  getModel: props => props.loginModel,
  fetchData: (loginModel, {host}) => {
    return yubikiri({
      token: loginModel.getToken(host),
    });
  },
})
export default class RemotePrController extends React.Component {
  static propTypes = {
    loginModel: PropTypes.object.isRequired,
    host: PropTypes.string, // fully qualified URI to the API endpoint, e.g. 'https://api.github.com'
    remote: RemotePropType.isRequired,
    token: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.symbol,
    ]),
    currentBranchName: PropTypes.string.isRequired,
    selectedPrUrl: PropTypes.string,
    aheadCount: PropTypes.number,
    isUnpublished: PropTypes.bool.isRequired,
    onSelectPr: PropTypes.func.isRequired,
    onUnpinPr: PropTypes.func.isRequired,
    onPushBranch: PropTypes.func.isRequired,
  }

  static defaultProps = {
    host: 'https://api.github.com',
    remote: nullRemote,
    token: null,
  }

  render() {
    const {
      host, remote, currentBranchName, token, loginModel, selectedPrUrl, aheadCount, isUnpublished,
      onSelectPr, onUnpinPr, onPushBranch,
    } = this.props;
    return (

        {token && token !== UNAUTHENTICATED && <PrInfoController
          {...{
            host, remote, currentBranchName, token, loginModel, selectedPrUrl, aheadCount, isUnpublished,
            onSelectPr, onUnpinPr, onPushBranch,
          }}
          onLogin={this.handleLogin}
          onLogout={this.handleLogout}
                                               />
          }
        {(!token || token === UNAUTHENTICATED) && <GithubLoginView onLogin={this.handleLogin} />}

    );
  }

  @autobind
  handleLogin(token) {
    this.props.loginModel.setToken(this.props.host, token);
  }

  @autobind
  handleLogout() {
    this.props.loginModel.removeToken(this.props.host);
  }
}
<commit_msg>Implement create PR handler in RemotePrController<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import {autobind} from 'core-decorators';
import yubikiri from 'yubikiri';
import {shell} from 'electron';

import {RemotePropType} from '../prop-types';
import ObserveModelDecorator from '../decorators/observe-model';
import GithubLoginView from '../views/github-login-view';
import {UNAUTHENTICATED} from '../shared/keytar-strategy';
import {nullRemote} from '../models/remote';
import PrInfoController from './pr-info-controller';

@ObserveModelDecorator({
  getModel: props => props.loginModel,
  fetchData: (loginModel, {host}) => {
    return yubikiri({
      token: loginModel.getToken(host),
    });
  },
})
export default class RemotePrController extends React.Component {
  static propTypes = {
    loginModel: PropTypes.object.isRequired,
    host: PropTypes.string, // fully qualified URI to the API endpoint, e.g. 'https://api.github.com'
    remote: RemotePropType.isRequired,
    token: PropTypes.oneOfType([
      PropTypes.string,
      PropTypes.symbol,
    ]),
    currentBranchName: PropTypes.string.isRequired,
    selectedPrUrl: PropTypes.string,
    aheadCount: PropTypes.number,
    isUnpublished: PropTypes.bool.isRequired,
    onSelectPr: PropTypes.func.isRequired,
    onUnpinPr: PropTypes.func.isRequired,
    onPushBranch: PropTypes.func.isRequired,
  }

  static defaultProps = {
    host: 'https://api.github.com',
    remote: nullRemote,
    token: null,
  }

  render() {
    const {
      host, remote, currentBranchName, token, loginModel, selectedPrUrl, aheadCount, isUnpublished,
      onSelectPr, onUnpinPr, onPushBranch,
    } = this.props;
    return (

        {token && token !== UNAUTHENTICATED && <PrInfoController
          {...{
            host, remote, currentBranchName, token, loginModel, selectedPrUrl, aheadCount, isUnpublished,
            onSelectPr, onUnpinPr, onPushBranch,
          }}
          onLogin={this.handleLogin}
          onLogout={this.handleLogout}
          onCreatePr={this.handleCreatePr}
                                               />
          }
        {(!token || token === UNAUTHENTICATED) && <GithubLoginView onLogin={this.handleLogin} />}

    );
  }

  @autobind
  handleLogin(token) {
    this.props.loginModel.setToken(this.props.host, token);
  }

  @autobind
  handleLogout() {
    this.props.loginModel.removeToken(this.props.host);
  }

  @autobind
  handleCreatePr() {
    let createPrUrl = 'https://github.com/';
    createPrUrl += this.props.remote.getOwner() + '/' + this.props.remote.getRepo();
    createPrUrl += '/compare/' + encodeURIComponent(this.props.currentBranchName);
    createPrUrl += '?expand=1';

    return new Promise((resolve, reject) => {
      shell.openExternal(createPrUrl, {}, err => {
        if (err) { reject(err); } else { resolve(); }
      });
    });
  }
}
<|endoftext|>


<commit_before>'use strict';

var q = require('q'),
    _ = require('lodash'),

    config,

    elasticsearch = require('elasticsearch'),
    client,

    adaptResult = function (result) {
        var _result = result._source;
        _result.id = result._id;

        return _result;
    },

    adaptResults = function (results) {
        results = _.map(results, function (result) {
            return adaptResult(result);
        });

        return results;
    },

    /**
     * The most basic GET functionality.
     *
     * @param  {string} id The id of the record you wish to retrieve.
     * @return {object}    The chainable functionality used to build the sentence.
     */
    get = function (id) {
        var typeName;

        return {
            /**
             * @param  {string} _typeName
             * @return {string}
             */
            'ofType': function (_typeName) {
                typeName = _typeName;
                return this;
            },

            'from': function (indexName) {
                var defer = q.defer();

                client.get({
                    'index': indexName,
                    'type': typeName,
                    'id': id
                }, function (error, response) {
                    var result;

                    if (error) {
                        defer.reject(error);
                        return;
                    }

                    result = adaptResult(response);
                    defer.resolve(response);
                });

                return defer.promise;
            }
        };
    };

exports.post = function (data) {
    var typeName;

    if (!Array.isArray(data)) {
        data = [data];
    }

    return {
        ofType: function (_typeName) {
            typeName = _typeName;
            return this;
        },

        into: function (indexName) {
            var promises = [],
                errorDefer;

            if (!typeName) {
                errorDefer = q.defer();
                errorDefer.reject(new Error('You must specify a type'));
                return errorDefer.promise;
            }

            data.forEach(function (item) {
                var params,
                    defer = q.defer();

                promises.push(defer.promise);

                if (!item.createdAt) {
                    item.createdAt = (new Date()).toISOString();
                }

                params = {
                    index: indexName,
                    type: typeName,
                    timestamp: (new Date()).toISOString(),
                    body: item
                };

                if (item.id) {
                    params.id = item.id;
                }

                client.create(
                    params,
                    function (error, response) {
                        if (error) {
                            defer.reject(error);
                            return;
                        }
                        client.get({
                            index: indexName,
                            type: typeName,
                            id: response._id
                        }, function (error, result) {
                            if (error) {
                                defer.reject(error);
                                return;
                            }
                            result = adaptResult(result);
                            defer.resolve(result);
                        });
                    }
                );
            });

            if (data.length === 1) {
                return promises[0];
            }

            return q.all(promises);
        }
    };
};

exports.query = function (queryString) {
    var typeName,
        offset = 0,
        sort = '',
        // results to return
        size = 1000000;

    return {
        ofType: function (_typeName) {
            typeName = _typeName;
            return this;
        },

        withOffset: function (_offset) {
            offset = _offset;
            return this;
        },

        sortBy: function (_sort) {
            sort = _sort;
            return this;
        },

        withSize: function (_size) {
            size = _size;
            return this;
        },

        from: function (indexName) {
            var defer = q.defer();

            if (!typeName) {
                defer.reject(new Error('Type name must be supplied'));
            }

            client.search({
                index: indexName,
                q: queryString,
                from: offset,
                size: size,
                sort: sort
            }, function (error, results) {
                var response;
                if (error) {
                    defer.reject(error);
                    return;
                }
                response = adaptResults(results.hits.hits);
                response.total = results.hits.total;
                defer.resolve(response);
            });

            return defer.promise;
        }
    };
};

/**
 * Use to retrieve all results of [type] from [index].
 *
 * @param  {string} type
 * @return {promise}
 */
exports.getAll = function (type) {
    var offset = 0,
        sort = '',
        size = 1000;

    return {
        withOffset: function (_offset) {
            offset = _offset;
            return this;
        },

        size: function (_size) {
            size = _size;
            return this;
        },

        /**
         * @param String _sort A comma-separated list of <field>:<direction>
         *                      pairs
         * @TODO: validate _sort
         */
        sortBy: function (_sort) {
            sort = _sort;
            return this;
        },
        from: function (indexName) {
            var defer = q.defer();

            if (!type) {
                // @TODO: if we ever actually need 'types' as a array, check
                // back in git history.
                defer.reject(new Error('Type must be supplied'));
            }

            client.search({
                index: indexName,
                q: '_type:' + type,
                from: offset,
                sort: sort,
                size: size
            }, function (error, results) {
                var response;
                if (error) {
                    defer.reject(error);
                    return;
                }
                response = adaptResults(results.hits.hits);
                response.total = results.hits.total;
                defer.resolve(response);
            });

            return defer.promise;
        }
    };
};

exports.put = function (data) {
    var typeName;

    return {
        ofType: function (_typeName) {
            typeName = _typeName;
            return this;
        },
        withId: function (_id) {
            data.id = _id;
            return this;
        },
        into: function (indexName) {
            var promises = [],
                defer = q.defer();

            promises.push(defer.promise);

            if (!typeName) {
                defer.reject(new Error('You must specify a type'));
                return;
            }

            client.get({
                index: indexName,
                type: typeName,
                id: data.id
            }, function (error, response) {
                if (error) {
                    // if it didn't find it, do a est.post?
                    defer.reject(error);
                    return;
                }

                data.updatedAt = (new Date()).toISOString();

                _.forEach(response._source, function (value, name) {
                    if (!data[name]) {
                        data[name] = value;
                    }
                });

                client.update({
                    index: indexName,
                    type: typeName,
                    id: data.id,
                    body: {
                        doc: data
                    }
                }, function (error, response) {
                    if (error) {
                        defer.reject(error);
                        return;
                    }
                    client.get({
                        index: indexName,
                        type: typeName,
                        id: response._id
                    }, function (error, response) {
                        var result;

                        if (error) {
                            defer.reject(error);
                            return;
                        }

                        result = adaptResult(response);
                        defer.resolve(result);
                    });
                });
            });

            if (data.length === 1) {
                return promises[0];
            }
            return q.all(promises);
        }
    };
};

/**
 * Delete type from index.
 * @example
 * db.delete('myType').withId(5).from('myIndex');
 * // 'withId' param is the id to delete.
 * // 'from' param is the string name of the index to delete from.
 *
 * @param  {string} typeName The name of the type to delete.
 * @return {object}
 */
exports.delete = function (typeName) {
    var id;
    return {
        withId: function (_id) {
            id = _id;
            return this;
        },
        from: function (indexName) {
            var defer = q.defer();
            client.delete({
                index: indexName,
                type: typeName,
                id: id
            }, function (error, response) {
                if (error) {
                    defer.reject(error);
                    return;
                }
                defer.resolve(response);
            });
            return defer.promise;
        }
    };
};

exports.checkIndexExists = function (indexName) {
    var defer = q.defer();

    client.indices.exists({
        index: indexName
    }, function (error, response) {
        if (error) {
            defer.reject(error);
            return;
        }

        defer.resolve(response);
    });

    return defer.promise;
};

exports.destroyIndex = function (indexName) {
    var defer = q.defer();

    client.indices.delete({
        index: indexName
    }, function (error, response) {
        if (error) {
            defer.reject(error);
            return;
        }

        defer.resolve(response);
    });

    return defer.promise;
};

exports.createIndex = function (indexName) {
    var defer = q.defer();

    client.indices.create({
        index: indexName
    }, function (error, response) {
        if (error) {
            defer.reject(error);
            return;
        }

        defer.resolve(response);
    });

    return defer.promise;
};

/**
 * Sets the configuration for the location of the database. Acts as a getter and a setter.
 *
 * @see config.js.example
 * @param  {object} _config The configuration object.
 * @return {object|undefined}         The configuration object.
 */
exports.config = function (_config) {
    if (!_config) {
        return config;
    }

    config = _config;

    client = new elasticsearch.Client({
        host: config.db.url,
        maxKeepAliveRequests: 1
    });

    return config;
};

/**
 * Given a name and a template, it will save it to the es templates.
 * For more info on how and why to use templates refer to the docs.
 *
 * @param {string} name name of the template.
 * @param {string} template the json template as a string.
 * @return {object} promise
 */
exports.createTemplate = function (name, template) {
    var defer = q.defer();

    client.indices.putTemplate({
        name: name,
        body: template
    }, function (error, response) {
        if (error) {
            defer.reject(error);
            return;
        }

        defer.resolve(response);
    });

    return defer.promise;
};

// API
exports.get = get;
<commit_msg>Added ability to pass query objects into query function<commit_after>'use strict';

var q = require('q'),
    _ = require('lodash'),

    config,

    elasticsearch = require('elasticsearch'),
    client,

    adaptResult = function (result) {
        var _result = result._source;
        _result.id = result._id;

        return _result;
    },

    adaptResults = function (results) {
        results = _.map(results, function (result) {
            return adaptResult(result);
        });

        return results;
    },

    /**
     * The most basic GET functionality.
     *
     * @param  {string} id The id of the record you wish to retrieve.
     * @return {object}    The chainable functionality used to build the sentence.
     */
    get = function (id) {
        var typeName;

        return {
            /**
             * @param  {string} _typeName
             * @return {string}
             */
            'ofType': function (_typeName) {
                typeName = _typeName;
                return this;
            },

            'from': function (indexName) {
                var defer = q.defer();

                client.get({
                    'index': indexName,
                    'type': typeName,
                    'id': id
                }, function (error, response) {
                    var result;

                    if (error) {
                        defer.reject(error);
                        return;
                    }

                    result = adaptResult(response);
                    defer.resolve(response);
                });

                return defer.promise;
            }
        };
    };

exports.post = function (data) {
    var typeName;

    if (!Array.isArray(data)) {
        data = [data];
    }

    return {
        ofType: function (_typeName) {
            typeName = _typeName;
            return this;
        },

        into: function (indexName) {
            var promises = [],
                errorDefer;

            if (!typeName) {
                errorDefer = q.defer();
                errorDefer.reject(new Error('You must specify a type'));
                return errorDefer.promise;
            }

            data.forEach(function (item) {
                var params,
                    defer = q.defer();

                promises.push(defer.promise);

                if (!item.createdAt) {
                    item.createdAt = (new Date()).toISOString();
                }

                params = {
                    index: indexName,
                    type: typeName,
                    timestamp: (new Date()).toISOString(),
                    body: item
                };

                if (item.id) {
                    params.id = item.id;
                }

                client.create(
                    params,
                    function (error, response) {
                        if (error) {
                            defer.reject(error);
                            return;
                        }
                        client.get({
                            index: indexName,
                            type: typeName,
                            id: response._id
                        }, function (error, result) {
                            if (error) {
                                defer.reject(error);
                                return;
                            }
                            result = adaptResult(result);
                            defer.resolve(result);
                        });
                    }
                );
            });

            if (data.length === 1) {
                return promises[0];
            }

            return q.all(promises);
        }
    };
};

exports.query = function (queryString) {
    var typeName,
        offset = 0,
        sort = '',
        // results to return
        size = 1000000;

    return {
        ofType: function (_typeName) {
            typeName = _typeName;
            return this;
        },

        withOffset: function (_offset) {
            offset = _offset;
            return this;
        },

        sortBy: function (_sort) {
            sort = _sort;
            return this;
        },

        withSize: function (_size) {
            size = _size;
            return this;
        },

        from: function (indexName) {
            var defer = q.defer(),
                params = {
                    index: indexName,
                    type: typeName,
                    from: offset,
                    size: size,
                    sort: sort
                };

            if (typeof queryString === 'string') {
                params.q = queryString;

            } else {
                params.body = {
                    'query': queryString
                };
            }

            client.search(params, function (error, results) {
                var response;

                if (error) {
                    defer.reject(error);
                    return;
                }

                response = adaptResults(results.hits.hits);
                response.total = results.hits.total;
                defer.resolve(response);
            });

            return defer.promise;
        }
    };
};

/**
 * Use to retrieve all results of [type] from [index].
 *
 * @param  {string} type
 * @return {promise}
 */
exports.getAll = function (type) {
    var offset = 0,
        sort = '',
        size = 1000;

    return {
        withOffset: function (_offset) {
            offset = _offset;
            return this;
        },

        size: function (_size) {
            size = _size;
            return this;
        },

        /**
         * @param String _sort A comma-separated list of <field>:<direction>
         *                      pairs
         * @TODO: validate _sort
         */
        sortBy: function (_sort) {
            sort = _sort;
            return this;
        },
        from: function (indexName) {
            var defer = q.defer();

            if (!type) {
                // @TODO: if we ever actually need 'types' as a array, check
                // back in git history.
                defer.reject(new Error('Type must be supplied'));
            }

            client.search({
                index: indexName,
                q: '_type:' + type,
                from: offset,
                sort: sort,
                size: size
            }, function (error, results) {
                var response;
                if (error) {
                    defer.reject(error);
                    return;
                }
                response = adaptResults(results.hits.hits);
                response.total = results.hits.total;
                defer.resolve(response);
            });

            return defer.promise;
        }
    };
};

exports.put = function (data) {
    var typeName;

    return {
        ofType: function (_typeName) {
            typeName = _typeName;
            return this;
        },
        withId: function (_id) {
            data.id = _id;
            return this;
        },
        into: function (indexName) {
            var promises = [],
                defer = q.defer();

            promises.push(defer.promise);

            if (!typeName) {
                defer.reject(new Error('You must specify a type'));
                return;
            }

            client.get({
                index: indexName,
                type: typeName,
                id: data.id
            }, function (error, response) {
                if (error) {
                    // if it didn't find it, do a est.post?
                    defer.reject(error);
                    return;
                }

                data.updatedAt = (new Date()).toISOString();

                _.forEach(response._source, function (value, name) {
                    if (!data[name]) {
                        data[name] = value;
                    }
                });

                client.update({
                    index: indexName,
                    type: typeName,
                    id: data.id,
                    body: {
                        doc: data
                    }
                }, function (error, response) {
                    if (error) {
                        defer.reject(error);
                        return;
                    }
                    client.get({
                        index: indexName,
                        type: typeName,
                        id: response._id
                    }, function (error, response) {
                        var result;

                        if (error) {
                            defer.reject(error);
                            return;
                        }

                        result = adaptResult(response);
                        defer.resolve(result);
                    });
                });
            });

            if (data.length === 1) {
                return promises[0];
            }
            return q.all(promises);
        }
    };
};

/**
 * Delete type from index.
 * @example
 * db.delete('myType').withId(5).from('myIndex');
 * // 'withId' param is the id to delete.
 * // 'from' param is the string name of the index to delete from.
 *
 * @param  {string} typeName The name of the type to delete.
 * @return {object}
 */
exports.delete = function (typeName) {
    var id;
    return {
        withId: function (_id) {
            id = _id;
            return this;
        },
        from: function (indexName) {
            var defer = q.defer();
            client.delete({
                index: indexName,
                type: typeName,
                id: id
            }, function (error, response) {
                if (error) {
                    defer.reject(error);
                    return;
                }
                defer.resolve(response);
            });
            return defer.promise;
        }
    };
};

exports.checkIndexExists = function (indexName) {
    var defer = q.defer();

    client.indices.exists({
        index: indexName
    }, function (error, response) {
        if (error) {
            defer.reject(error);
            return;
        }

        defer.resolve(response);
    });

    return defer.promise;
};

exports.destroyIndex = function (indexName) {
    var defer = q.defer();

    client.indices.delete({
        index: indexName
    }, function (error, response) {
        if (error) {
            defer.reject(error);
            return;
        }

        defer.resolve(response);
    });

    return defer.promise;
};

exports.createIndex = function (indexName) {
    var defer = q.defer();

    client.indices.create({
        index: indexName
    }, function (error, response) {
        if (error) {
            defer.reject(error);
            return;
        }

        defer.resolve(response);
    });

    return defer.promise;
};

/**
 * Sets the configuration for the location of the database. Acts as a getter and a setter.
 *
 * @see config.js.example
 * @param  {object} _config The configuration object.
 * @return {object|undefined}         The configuration object.
 */
exports.config = function (_config) {
    if (!_config) {
        return config;
    }

    config = _config;

    client = new elasticsearch.Client({
        host: config.db.url,
        maxKeepAliveRequests: 1
    });

    return config;
};

/**
 * Given a name and a template, it will save it to the es templates.
 * For more info on how and why to use templates refer to the docs.
 *
 * @param {string} name name of the template.
 * @param {string} template the json template as a string.
 * @return {object} promise
 */
exports.createTemplate = function (name, template) {
    var defer = q.defer();

    client.indices.putTemplate({
        name: name,
        body: template
    }, function (error, response) {
        if (error) {
            defer.reject(error);
            return;
        }

        defer.resolve(response);
    });

    return defer.promise;
};

// API
exports.get = get;
<|endoftext|>


<commit_before>import React from 'react';
import {connectToStores} from 'fluxible-addons-react';
import invertReplyBoxFlag from '../../../../actions/contentdiscussion/invertReplyBoxFlag';
import ActivityFeedUtil from '../util/ActivityFeedUtil';
import AddReply from './AddReply';
import {navigateAction} from 'fluxible-router';
import {connectToStores} from 'fluxible-addons-react';
import cheerio from 'cheerio';
import DeckTreeStore from '../../../../stores/DeckTreeStore';
import TreeUtil from '../../TreePanel/util/TreeUtil';

class Comment extends React.Component {
    handleReply() {
        this.context.executeAction(invertReplyBoxFlag, {comment: this.props.comment});
    }

    //return the position of the node in the deck
    getPath(node){
        const flatTree = this.props.DeckTreeStore.flatTree;
        let path = '';
        for (let i=0; i < flatTree.size; i++) {
            if (flatTree.get(i).get('type') === node.content_kind && flatTree.get(i).get('id') === node.content_id) {
                path = flatTree.get(i).get('path');
                let nodeSelector = {id: this.props.selector.id, stype: node.content_kind, sid: node.content_id, spath: path};
                let nodeURL = TreeUtil.makeNodeURL(nodeSelector, 'deck', 'view');

                return nodeURL;
            }
        }
        return path;
    }

    handleRefClick(e) {
        e.preventDefault();

        this.context.executeAction(navigateAction, {
            url: this.getPath(this.props.activity)
        });
        // return false;
    }

    render() {
        const comment = this.props.comment;
        const replyLink = (

                Reply

        );

        const cheerioContentName = (node.content_name !== undefined) ? cheerio.load(node.content_name).text() : '';
        const nodeRef = (node.content_kind !== this.props.selector.stype || node.content_id.split('-')[0] !== this.props.selector.sid.split('-')[0]) ? ({' (from ' + node.content_kind + ' '}{cheerioContentName})) : '';

        return (

                    {(comment.author.avatar && comment.author.avatar !== '') ?  : }

                    {comment.author.username}

                        {ActivityFeedUtil.formatDate(comment.timestamp)}
                        {nodeRef}

                        {comment.title}

                        {ActivityFeedUtil.breakLines(comment.text)}

                    { (String(this.props.userid) !== '') ? replyLink : ''}
                    { comment.replyBoxOpened ? (<AddReply comment={comment} userid={this.props.userid}/>) : '' }

                {comment.replies ?
{comment.replies.map((reply, index) => { return (<Comment key={index} comment={reply} userid={this.props.userid}/>); })}
 : ''}

        );
    }
}

Comment.contextTypes = {
    executeAction: React.PropTypes.func.isRequired
};
Comment = connectToStores(Comment, [DeckTreeStore], (context, props) => {
    return {
        DeckTreeStore: context.getStore(DeckTreeStore).getState()
    };
});
export default Comment;
<commit_msg>SWIK-1177 Removed duplicate declaration<commit_after>import React from 'react';
import {connectToStores} from 'fluxible-addons-react';
import invertReplyBoxFlag from '../../../../actions/contentdiscussion/invertReplyBoxFlag';
import ActivityFeedUtil from '../util/ActivityFeedUtil';
import AddReply from './AddReply';
import {navigateAction} from 'fluxible-router';
import cheerio from 'cheerio';
import DeckTreeStore from '../../../../stores/DeckTreeStore';
import TreeUtil from '../../TreePanel/util/TreeUtil';

class Comment extends React.Component {
    handleReply() {
        this.context.executeAction(invertReplyBoxFlag, {comment: this.props.comment});
    }

    //return the position of the node in the deck
    getPath(node){
        const flatTree = this.props.DeckTreeStore.flatTree;
        let path = '';
        for (let i=0; i < flatTree.size; i++) {
            if (flatTree.get(i).get('type') === node.content_kind && flatTree.get(i).get('id') === node.content_id) {
                path = flatTree.get(i).get('path');
                let nodeSelector = {id: this.props.selector.id, stype: node.content_kind, sid: node.content_id, spath: path};
                let nodeURL = TreeUtil.makeNodeURL(nodeSelector, 'deck', 'view');

                return nodeURL;
            }
        }
        return path;
    }

    handleRefClick(e) {
        e.preventDefault();

        this.context.executeAction(navigateAction, {
            url: this.getPath(this.props.activity)
        });
        // return false;
    }

    render() {
        const comment = this.props.comment;
        const replyLink = (

                Reply

        );

        const cheerioContentName = (node.content_name !== undefined) ? cheerio.load(node.content_name).text() : '';
        const nodeRef = (node.content_kind !== this.props.selector.stype || node.content_id.split('-')[0] !== this.props.selector.sid.split('-')[0]) ? ({' (from ' + node.content_kind + ' '}{cheerioContentName})) : '';

        return (

                    {(comment.author.avatar && comment.author.avatar !== '') ?  : }

                    {comment.author.username}

                        {ActivityFeedUtil.formatDate(comment.timestamp)}
                        {nodeRef}

                        {comment.title}

                        {ActivityFeedUtil.breakLines(comment.text)}

                    { (String(this.props.userid) !== '') ? replyLink : ''}
                    { comment.replyBoxOpened ? (<AddReply comment={comment} userid={this.props.userid}/>) : '' }

                {comment.replies ?
{comment.replies.map((reply, index) => { return (<Comment key={index} comment={reply} userid={this.props.userid}/>); })}
 : ''}

        );
    }
}

Comment.contextTypes = {
    executeAction: React.PropTypes.func.isRequired
};
Comment = connectToStores(Comment, [DeckTreeStore], (context, props) => {
    return {
        DeckTreeStore: context.getStore(DeckTreeStore).getState()
    };
});
export default Comment;
<|endoftext|>


<commit_before>var express         = require('express'),
	bodyParser      = require('body-parser');

var sql             = require('mssql'),
	util            = require('../util');

module.exports      = function (configuration) {
	var router      = express.Router(),
	authenticate    = require('azure-mobile-apps/src/express/middleware/authenticate')(configuration),
	authorize       = require('azure-mobile-apps/src/express/middleware/authorize');

	var completeError = function(err, res) {
		if (err) {
			console.error(err);
			if (res) res.sendStatus(500);
		}
	};

	router.post('/', authenticate, (req, res, next) => {
		console.log('in POST /acceptinvitation');
		// var userSid = req.azureMobile.user.id;
		var userSid = req.body.userSid;
		console.log(userSid);
		var voucher = req.body.voucher;
		console.log(voucher);
		res.json( {
			"links": [
				{ "rel": "userSid", "method": "voucher", "href": "/ok" }
			]}
		);
		sql.connect(util.sqlConfiguration)
		.then(function() {
			new sql.Request()
			.input('userSid', sql.NVarChar(40), userSid)
			.input('token', sql.NVarChar(36), voucher)
			.execute('sp_acceptInvitationToTertulia')
			.then((recordsets) => {
				console.log('recordsets[1]: ', recordsets[1]);
				console.log('recordsets['returnValue']: ', recordsets['returnValue']);
				if (recordsets['returnValue'] == 0) {
					res.status(201)	// 201: Created
						.type('application/json')
						.json( { result: 'Ok' } );
					return next();
				} else {
					res.status(409)	// 409: Conflict, 422: Unprocessable Entity (WebDAV; RFC 4918)
						.type('application/json')
						.json( { result: 'Unavailable' } );
					return next('409');
				}
				next();
			})
			.catch(function(err) {
				next(err);
			});
		});
		next();
	});

	return router;
};
<commit_msg>wip save<commit_after>var express         = require('express'),
	bodyParser      = require('body-parser');

var sql             = require('mssql'),
	util            = require('../util');

module.exports      = function (configuration) {
	var router      = express.Router(),
	authenticate    = require('azure-mobile-apps/src/express/middleware/authenticate')(configuration),
	authorize       = require('azure-mobile-apps/src/express/middleware/authorize');

	var completeError = function(err, res) {
		if (err) {
			console.error(err);
			if (res) res.sendStatus(500);
		}
	};

	router.post('/', authenticate, (req, res, next) => {
		console.log('in POST /acceptinvitation');
		// var userSid = req.azureMobile.user.id;
		var userSid = req.body.userSid;
		console.log(userSid);
		var voucher = req.body.voucher;
		console.log(voucher);
		res.json( {
			"links": [
				{ "rel": "userSid", "method": "voucher", "href": "/ok" }
			]}
		);
		sql.connect(util.sqlConfiguration)
		.then(function() {
			new sql.Request()
			.input('userSid', sql.NVarChar(40), userSid)
			.input('token', sql.NVarChar(36), voucher)
			.execute('sp_acceptInvitationToTertulia')
			.then((recordsets) => {
				console.log('recordsets[1]: ', recordsets[1]);
				console.log('recordsets["returnValue"]: ', recordsets['returnValue']);
				if (recordsets['returnValue'] == 0) {
					res.status(201)	// 201: Created
						.type('application/json')
						.json( { result: 'Ok' } );
					return next();
				} else {
					res.status(409)	// 409: Conflict, 422: Unprocessable Entity (WebDAV; RFC 4918)
						.type('application/json')
						.json( { result: 'Unavailable' } );
					return next('409');
				}
				next();
			})
			.catch(function(err) {
				next(err);
			});
		});
		next();
	});

	return router;
};
<|endoftext|>