<commit_before>/**
 * Underhand solution for reading Json on time without worrying about loadings not being on correct time.
 *
 */

function getJsonFromNationsData(){
	//Think if sizeMultiplier should be set instead of the zoom as playerPref
	var x=
{
	"sizeMultiplier": 1.5,
	"nations":
	[
		{
			"name": "Venaja",
			"x": " ,Border:Right",
			"y": 600,
			"width": 187,
			"height": 348,
			"rotation": 0,
			"sprite": "Venaja"

		},
		{
			"name": "Norja",
			"x": "Left:Venaja,Percent:19",
			"y": "Same:Venaja,Percent:-45",
			"width": 258,
			"height": 207,
			"rotation": 0,
			"sprite": "Norja"

		},
		{
			"name": "Suomi",
			"x": "Left:Venaja,Percent:38",
			"y": "Same:Venaja,Percent:-60",
			"width": 120,
			"height": 159,
			"rotation": 0,
			"sprite": "Suomi"
		},
		{
			"name": "Ruotsi",
			"x": "Same:Suomi,Percent:-57.5",
			"y": "Same:Suomi,Percent:19",
			"width": 129,
			"height": 191,
			"rotation": 0,
			"sprite": "Ruotsi"

		},
		{
			"name": "Viro",
			"x": "Left:Venaja,Percent:17",
			"y": "Down:Suomi,Percent:-17",
			"width": 66,
			"height": 34,
			"rotation": 0,
			"sprite": "Viro"
		},
		{
			"name": "Latvia",
			"x": "Same:Viro,Percent:-8",
			"y": "Down:Viro,Percent:-37",
			"width": 69,
			"height": 28,
			"rotation": 0,
			"sprite": "Latvia"
		},
		{
			"name": "Valko-Venaja",
			"x": "Same:Latvia,Percent:36",
			"y": "Down:Latvia,Percent:-13",
			"width": 91,
			"height": 50,
			"rotation": 0,
			"sprite": "Valko-Venaja"
		},
		{
			"name": "Liettua",
			"x": "Same:Latvia,Percent:-11",
			"y": "Down:Latvia,Percent:-34",
			"width": 55,
			"height": 29,
			"rotation": 0,
			"sprite": "Liettua"
		},
		{
			"name": "Ukraina",
			"x": "Same:Valko-Venaja,Percent:15.5",
			"y": "Down:Valko-Venaja,Percent:-13",
			"width": 176,
			"height": 75,
			"rotation": 0,
			"sprite": "Ukraina"
		},
		{
			"name": "Puola",
			"x": "Left:Valko-Venaja,Percent:7",
			"y": "Same:Valko-Venaja,Percent:33",
			"width": 92,
			"height": 58,
			"rotation": 0,
			"sprite": "Puola"
		},
		{
			"name": "Saksa",
			"x": "Left:Puola,Percent:9",
			"y": "Same:Puola,Percent:11",
			"width": 84,
			"height": 72,
			"rotation": 0,
			"sprite": "Saksa"
		},
		{
			"name": "Tanska",
			"x": "Same:Saksa,Percent:15",
			"y": "Up:Saksa,Percent:16",
			"width": 71,
			"height": 39,
			"rotation": 0,
			"sprite": "Tanska"
		},
		{
			"name": "Benelux",
			"x": "Left:Saksa,Percent:43",
			"y": "Same:Saksa,Percent:-2",
			"width": 40,
			"height": 38,
			"rotation": 0,
			"sprite": "Benelux"
		},
		{
			"name": "Ranska",
			"x": "Left:Saksa,Percent:27",
			"y": "Down:Saksa,Percent:-40",
			"width": 120,
			"height": 82,
			"rotation": 0,
			"sprite": "Ranska"
		},
		{
			"name": "Italia",
			"x": "Same:Saksa,Percent:15",
			"y": "Down:Saksa,Percent:0",
			"width": 102,
			"height": 86,
			"rotation": 0,
			"sprite": "Italia"
		},
		{
			"name": "Romania",
			"y": "Down:Ukraina,Percent:-88",
			"x": "Same:Ukraina,Percent:-69",
			"width": 89,
			"height": 40,
			"rotation": 0,
			"sprite": "Romania"
		},
		{
			"name": "Moldova",
			"x": "Same:Ukraina,Percent:-89",
			"y": "Down:Ukraina,Percent:-135",
			"width": 33,
			"height": 29,
			"rotation": 0,
			"sprite": "Moldova"
		},
		{
			"name": "Sveitsi",
			"x": "Same:Italia,Percent:-80.5",
			"y": "Same:Italia,Percent:-215",
			"width": 44,
			"height": 18,
			"rotation": 0,
			"sprite": "Sveitsi"
		},
		{
			"name": "Espanja",
			"x": "Same:Ranska,Percent:-45",
			"y": "Down:Ranska,Percent:-31",
			"width": 102,
			"height": 59,
			"rotation": 0,
			"sprite": "Espanja"
		},
				{
			"name": "Portugal",
			"x": "Left:Espanja,Percent:100",
			"y": "Same:Espanja,Percent:8",
			"width": 27,
			"height": 39,
			"rotation": 0,
			"sprite": "Portugal"
		},
		{
			"name": "Itavalta",
			"x": "Right:Sveitsi,Percent:-18",
			"y": "Same:Sveitsi,Percent:-30",
			"width": 70,
			"height": 24,
			"rotation": 0,
			"sprite": "Itavalta"
		},
				{
			"name": "Tsekki",
			"x": "Right:Saksa,Percent:-40",
			"y": "Same:Saksa,Percent:61",
			"width": 73,
			"height": 23,
			"rotation": 0,
			"sprite": "Tsekki"
		},
			{
			"name": "Slovakia",
			"x": "Right:Tsekki,Percent:-55",
			"y": "Same:Tsekki,Percent:72",
			"width": 52,
			"height": 16,
			"rotation": 0,
			"sprite": "Slovakia"
		},

		{
			"name": "Unkari",
			"x": "Right:Itavalta,Percent:-13",
			"y": "Down:Slovakia,Percent:-32",
			"width": 60,
			"height": 26,
			"rotation": 0,
			"sprite": "Unkari"
		},

		{
			"name": "Entinen-Jugoslavia",
			"x": "Right:Italia,Percent:-45",
			"y": "Same:Italia,Percent:-15",
			"width": 65,
			"height": 39,
			"rotation": 0,
			"sprite": "Entinen-Jugoslavia"
		}

	]
};
return x;
}<commit_msg>lisatty itaista valimerta<commit_after>/**
 * Underhand solution for reading Json on time without worrying about loadings not being on correct time.
 *
 */

function getJsonFromNationsData(){
	//Think if sizeMultiplier should be set instead of the zoom as playerPref
	var x=
{
	"sizeMultiplier": 1.5,
	"nations":
	[
		{
			"name": "Venaja",
			"x": " ,Border:Right",
			"y": 600,
			"width": 187,
			"height": 348,
			"rotation": 0,
			"sprite": "Venaja"

		},
		{
			"name": "Norja",
			"x": "Left:Venaja,Percent:19",
			"y": "Same:Venaja,Percent:-45",
			"width": 258,
			"height": 207,
			"rotation": 0,
			"sprite": "Norja"

		},
		{
			"name": "Suomi",
			"x": "Left:Venaja,Percent:38",
			"y": "Same:Venaja,Percent:-60",
			"width": 120,
			"height": 159,
			"rotation": 0,
			"sprite": "Suomi"
		},
		{
			"name": "Ruotsi",
			"x": "Same:Suomi,Percent:-57.5",
			"y": "Same:Suomi,Percent:19",
			"width": 129,
			"height": 191,
			"rotation": 0,
			"sprite": "Ruotsi"

		},
		{
			"name": "Viro",
			"x": "Left:Venaja,Percent:17",
			"y": "Down:Suomi,Percent:-17",
			"width": 66,
			"height": 34,
			"rotation": 0,
			"sprite": "Viro"
		},
		{
			"name": "Latvia",
			"x": "Same:Viro,Percent:-8",
			"y": "Down:Viro,Percent:-37",
			"width": 69,
			"height": 28,
			"rotation": 0,
			"sprite": "Latvia"
		},
		{
			"name": "Valko-Venaja",
			"x": "Same:Latvia,Percent:36",
			"y": "Down:Latvia,Percent:-13",
			"width": 91,
			"height": 50,
			"rotation": 0,
			"sprite": "Valko-Venaja"
		},
		{
			"name": "Liettua",
			"x": "Same:Latvia,Percent:-11",
			"y": "Down:Latvia,Percent:-34",
			"width": 55,
			"height": 29,
			"rotation": 0,
			"sprite": "Liettua"
		},
		{
			"name": "Ukraina",
			"x": "Same:Valko-Venaja,Percent:15.5",
			"y": "Down:Valko-Venaja,Percent:-13",
			"width": 176,
			"height": 75,
			"rotation": 0,
			"sprite": "Ukraina"
		},
		{
			"name": "Puola",
			"x": "Left:Valko-Venaja,Percent:7",
			"y": "Same:Valko-Venaja,Percent:33",
			"width": 92,
			"height": 58,
			"rotation": 0,
			"sprite": "Puola"
		},
		{
			"name": "Saksa",
			"x": "Left:Puola,Percent:9",
			"y": "Same:Puola,Percent:11",
			"width": 84,
			"height": 72,
			"rotation": 0,
			"sprite": "Saksa"
		},
		{
			"name": "Tanska",
			"x": "Same:Saksa,Percent:15",
			"y": "Up:Saksa,Percent:16",
			"width": 71,
			"height": 39,
			"rotation": 0,
			"sprite": "Tanska"
		},
		{
			"name": "Benelux",
			"x": "Left:Saksa,Percent:43",
			"y": "Same:Saksa,Percent:-2",
			"width": 40,
			"height": 38,
			"rotation": 0,
			"sprite": "Benelux"
		},
		{
			"name": "Ranska",
			"x": "Left:Saksa,Percent:27",
			"y": "Down:Saksa,Percent:-40",
			"width": 120,
			"height": 82,
			"rotation": 0,
			"sprite": "Ranska"
		},
		{
			"name": "Italia",
			"x": "Same:Saksa,Percent:15",
			"y": "Down:Saksa,Percent:0",
			"width": 102,
			"height": 86,
			"rotation": 0,
			"sprite": "Italia"
		},
		{
			"name": "Romania",
			"y": "Down:Ukraina,Percent:-88",
			"x": "Same:Ukraina,Percent:-69",
			"width": 89,
			"height": 40,
			"rotation": 0,
			"sprite": "Romania"
		},
		{
			"name": "Moldova",
			"x": "Same:Ukraina,Percent:-89",
			"y": "Down:Ukraina,Percent:-135",
			"width": 33,
			"height": 29,
			"rotation": 0,
			"sprite": "Moldova"
		},
		{
			"name": "Sveitsi",
			"x": "Same:Italia,Percent:-80.5",
			"y": "Same:Italia,Percent:-215",
			"width": 44,
			"height": 18,
			"rotation": 0,
			"sprite": "Sveitsi"
		},
		{
			"name": "Espanja",
			"x": "Same:Ranska,Percent:-45",
			"y": "Down:Ranska,Percent:-31",
			"width": 102,
			"height": 59,
			"rotation": 0,
			"sprite": "Espanja"
		},
				{
			"name": "Portugal",
			"x": "Left:Espanja,Percent:100",
			"y": "Same:Espanja,Percent:8",
			"width": 27,
			"height": 39,
			"rotation": 0,
			"sprite": "Portugal"
		},
		{
			"name": "Itavalta",
			"x": "Right:Sveitsi,Percent:-18",
			"y": "Same:Sveitsi,Percent:-30",
			"width": 70,
			"height": 24,
			"rotation": 0,
			"sprite": "Itavalta"
		},
				{
			"name": "Tsekki",
			"x": "Right:Saksa,Percent:-40",
			"y": "Same:Saksa,Percent:61",
			"width": 73,
			"height": 23,
			"rotation": 0,
			"sprite": "Tsekki"
		},
			{
			"name": "Slovakia",
			"x": "Right:Tsekki,Percent:-55",
			"y": "Same:Tsekki,Percent:72",
			"width": 52,
			"height": 16,
			"rotation": 0,
			"sprite": "Slovakia"
		},

		{
			"name": "Unkari",
			"x": "Right:Itavalta,Percent:-13",
			"y": "Down:Slovakia,Percent:-32",
			"width": 60,
			"height": 26,
			"rotation": 0,
			"sprite": "Unkari"
		},

		{
			"name": "Entinen-Jugoslavia",
			"x": "Right:Italia,Percent:-47",
			"y": "Same:Italia,Percent:-25",
			"width": 85,
			"height": 53,
			"rotation": 0,
			"sprite": "Entinen-Jugoslavia"
		},
		{
			"name": "Bulgaria",
			"x": "Right:Italia,Percent:65",
			"y": "Down:Romania,Percent:-22",
			"width": 59,
			"height": 26,
			"rotation": 0,
			"sprite": "Bulgaria"
		},
			{
			"name": "Kreikka",
			"x": "Right:Italia,Percent:33",
			"y": "Down:Romania,Percent:33",
			"width": 78,
			"height": 54,
			"rotation": 0,
			"sprite": "Kreikka"
		}/*,

		{
			"name": "Albania",
			"x": "Right:Italia,Percent:33",
			"y": "Down:Romania,Percent:33",
			"width": 78,
			"height": 54,
			"rotation": 0,
			"sprite": "Albania"
		}
*/

	]
};
return x;
}<|endoftext|>


<commit_before>import { MeetingSeries } from '/imports/meetingseries';
import { $ } from 'meteor/jquery';

function clearForm(template) {
    template.find("#id_meetingproject").value = "";
    template.find("#id_meetingname").value = "";
    template.find("#id_meetingproject").focus();
}

function escapeHandler(event) {
    event.preventDefault();

    let escapeWasPressed = event.key == 'Escape';

    // for browsers that do not support event.key yet
    escapeWasPressed |= event.keyCode === 27;

    if (escapeWasPressed) {
        $('#collapseMeetingSeriesAdd').collapse('hide');
    }
}

async function addMeetingSeries(template, optimisticUICallback, clearForm = true) {

    let aProject = template.find("#id_meetingproject").value;
    let aName = template.find("#id_meetingname").value;

    let ms = new MeetingSeries({
        project: aProject,
        name: aName,
        createdAt: new Date()
    });

    try {
        await ms.save(optimisticUICallback);
        if (clearForm) {
            clearForm(template);
        }
    } catch (error) {
        Session.set('errorTitle', 'Error');
        Session.set('errorReason', error.reason);
    }
}

Template.meetingSeriesAdd.events({
    "submit #id_meetingSeriesAddForm" (event, template) {
        event.preventDefault();

        addMeetingSeries(template);
    },

    "click #btnAddInvite" (event, template) {
        event.preventDefault();

        addMeetingSeries(template, (id) => {
            Router.go('/meetingseries/invite/' + id);
        }, false);
    },

    "hidden.bs.collapse #collapseMeetingSeriesAdd"(evt, tmpl) {
        clearForm(tmpl);
        document.removeEventListener('keyup', escapeHandler);
    },

    "shown.bs.collapse #collapseMeetingSeriesAdd"(evt, tmpl) {
        tmpl.find("#id_meetingproject").focus();
        document.addEventListener('keyup', escapeHandler);
    }
});
<commit_msg>Bugfix: adding a new meeting series displayed always a empty error message.<commit_after>import { MeetingSeries } from '/imports/meetingseries';
import { $ } from 'meteor/jquery';

function clearForm(template) {
    template.find("#id_meetingproject").value = "";
    template.find("#id_meetingname").value = "";
    template.find("#id_meetingproject").focus();
}

function escapeHandler(event) {
    event.preventDefault();

    let escapeWasPressed = event.key == 'Escape';

    // for browsers that do not support event.key yet
    escapeWasPressed |= event.keyCode === 27;

    if (escapeWasPressed) {
        $('#collapseMeetingSeriesAdd').collapse('hide');
    }
}

async function addMeetingSeries(template, optimisticUICallback, doClearForm = true) {

    let aProject = template.find("#id_meetingproject").value;
    let aName = template.find("#id_meetingname").value;

    let ms = new MeetingSeries({
        project: aProject,
        name: aName,
        createdAt: new Date()
    });

    try {
        await ms.save(optimisticUICallback);
        if (doClearForm) {
            clearForm(template);
        }
    } catch (error) {
        Session.set('errorTitle', 'Error');
        Session.set('errorReason', error.reason);
    }
}

Template.meetingSeriesAdd.events({
    "submit #id_meetingSeriesAddForm" (event, template) {
        event.preventDefault();

        addMeetingSeries(template);
    },

    "click #btnAddInvite" (event, template) {
        event.preventDefault();

        addMeetingSeries(template, (id) => {
            Router.go('/meetingseries/invite/' + id);
        }, false);
    },

    "hidden.bs.collapse #collapseMeetingSeriesAdd"(evt, tmpl) {
        clearForm(tmpl);
        document.removeEventListener('keyup', escapeHandler);
    },

    "shown.bs.collapse #collapseMeetingSeriesAdd"(evt, tmpl) {
        tmpl.find("#id_meetingproject").focus();
        document.addEventListener('keyup', escapeHandler);
    }
});
<|endoftext|>


<commit_before>// Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements; and to You under the Apache License, Version 2.0.

var $ = require('jquery');
const Base64 = require('js-base64').Base64;
var d3 = require('d3');
var React = require('react');
var ReactDOM = require('react-dom');
const SpotUtils = require('../utils/SpotUtils');

var DendrogramMixin = {
  buildChart ()
  {
    $(this.svg).width('100%');

    this.cluster = d3.layout.cluster();

    this.diagonal = d3.svg.diagonal()
                                .projection(function (d) {
                                    return [d.y, d.x]
                                });

    this.canvas = d3.select(this.svg).append('g')
                                        .attr('transform', 'translate(100,50)');
  },
  draw() {
      const svgElement = $(this.svg);

      let canvasWidth = svgElement.width();
      let canvasHeight = 100 + this.state.leafNodes * 20; // Make sure last magic number is at least twice the font size

      svgElement.height(canvasHeight);

      this.cluster.size([canvasHeight-100, canvasWidth-300]);

      const nodes = this.cluster.nodes(this.state.data);
      const links = this.cluster.links(nodes);

      this.drawLinks(links);
      this.drawNodes(nodes);
  },
  drawNodes(nodes) {
      const nodeSel = {};

      nodeSel.update = this.canvas.selectAll('.node').data(nodes, n => n.id);

      nodeSel.enter = nodeSel.update.enter();
      nodeSel.exit = nodeSel.update.exit();

      const nodeEl = nodeSel.enter.append('g')
                                .attr('class', n => `node depth_${n.depth}`);

      nodeEl.append('circle')
                        .attr('r', 4.5)
                        .attr('id', n => SpotUtils.encodeId(n.id))
                        .on('mouseover', function (n) {
                          d3.select(this)
                                        .style('cursor', 'pointer')
                                        .style('fill', '#C4D600');
                        })
                        .on('mouseout', function (d)
                        {
                          d3.select(this)
                                        .style('cursor', null)
                                        .style('fill', null);
                        });

        let y1 = 0;
        let y2 = 0;
        for(let x = 0; x < nodes.length; x++) {
          if(y1 === 0 && nodes[x].depth === 1) {
            y1 = nodes[x].y;
          }
          if(y2 === 0 && nodes[x].depth === 2) {
            y2 = nodes[x].y;
          }
          if(y1 !== 0 && y2 !== 0) {
            break;
          }
        }
        const foreignObject_width = (y2 - y1) - 16; // 16 is the 1em given on the "x" (see below) but we need to take it from the last part of the line

        // foreignObject is not supported by IE
        nodeEl.append('foreignObject')
                          .attr('x', n => n.depth === 0 ? '-8em' : '1em') //<--- this is the 1em
                          .attr('y', -6)
                          .append('xhtml:div')
                            .html(n => n.name)
                            .filter(n => n.depth === 1)
                              .style('width','auto')
                              .attr({'class': 'spot-text-wrapper', 'data-toggle': 'tooltip'});

      nodeSel.update.selectAll('foreignObject')
                        .style('width', n => n.depth === 1 ? foreignObject_width : 'auto');

    nodeSel.update.attr('transform', n => `translate(${n.y},${n.x})`);

    nodeSel.exit.remove();
  },
  drawLinks(links) {
      const linkSel = {};

      linkSel.update = this.canvas.selectAll('.link')
                                  .data(links, l => `link-${l.source.id}-${l.target.id}`);
      linkSel.enter = linkSel.update.enter();
      linkSel.exit = linkSel.update.exit();

      linkSel.enter.append('path', '.node')
        .attr('class', 'link')
        .on('mouseover', function (l)
        {
            d3.select(this)
                .style('stroke-width', 2)
                .style('cursor', 'pointer')
                .style('stroke', '#ED1C24');

            d3.selectAll(`#${SpotUtils.encodeId(l.source.id)},#${SpotUtils.encodeId(l.target.id)}`)
                .style('fill', '#C4D600');
      })
      .on('mouseout', function (l)
      {
        d3.select(this)
                      .style('stroke-width', null)
                      .style('cursor', null)
                      .style('stroke', null);

        d3.selectAll(`#${SpotUtils.encodeId(l.source.id)},#${SpotUtils.encodeId(l.target.id)}`)
                        .style('fill', null);
      });

      linkSel.update.attr('d', this.diagonal);

      // Remove old nodes
      linkSel.exit.remove();
  }
};

module.exports = DendrogramMixin;
<commit_msg>there is a default width when the dendrogram has less nodes, now it works on storyboard in case there is only the root and another node<commit_after>// Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements; and to You under the Apache License, Version 2.0.

var $ = require('jquery');
const Base64 = require('js-base64').Base64;
var d3 = require('d3');
var React = require('react');
var ReactDOM = require('react-dom');
const SpotUtils = require('../utils/SpotUtils');

var DendrogramMixin = {
  buildChart ()
  {
    $(this.svg).width('100%');

    this.cluster = d3.layout.cluster();

    this.diagonal = d3.svg.diagonal()
                                .projection(function (d) {
                                    return [d.y, d.x]
                                });

    this.canvas = d3.select(this.svg).append('g')
                                        .attr('transform', 'translate(100,50)');
  },
  draw() {
      const svgElement = $(this.svg);

      let canvasWidth = svgElement.width();
      let canvasHeight = 100 + this.state.leafNodes * 20; // Make sure last magic number is at least twice the font size

      svgElement.height(canvasHeight);

      this.cluster.size([canvasHeight-100, canvasWidth-300]);

      const nodes = this.cluster.nodes(this.state.data);
      const links = this.cluster.links(nodes);

      this.drawLinks(links);
      this.drawNodes(nodes);
  },
  drawNodes(nodes) {
      const nodeSel = {};

      nodeSel.update = this.canvas.selectAll('.node').data(nodes, n => n.id);

      nodeSel.enter = nodeSel.update.enter();
      nodeSel.exit = nodeSel.update.exit();

      const nodeEl = nodeSel.enter.append('g')
                                .attr('class', n => `node depth_${n.depth}`);

      nodeEl.append('circle')
                        .attr('r', 4.5)
                        .attr('id', n => SpotUtils.encodeId(n.id))
                        .on('mouseover', function (n) {
                          d3.select(this)
                                        .style('cursor', 'pointer')
                                        .style('fill', '#C4D600');
                        })
                        .on('mouseout', function (d)
                        {
                          d3.select(this)
                                        .style('cursor', null)
                                        .style('fill', null);
                        });

        let y1 = 0;
        let y2 = 0;
        for(let x = 0; x < nodes.length; x++) {
          if(y1 === 0 && nodes[x].depth === 1) {
            y1 = nodes[x].y;
          }
          if(y2 === 0 && nodes[x].depth === 2) {
            y2 = nodes[x].y;
          }
          if(y1 !== 0 && y2 !== 0) {
            break;
          }
        }
        const foreignObject_width = ((y2 - y1) - 16 ) > 0 ? (y2 - y1) - 16 : '17%'; // 16 is the 1em given on the "x" (see below) but we need to take it from the last part of the line, 17% is the minimum width when there is no third node

        // foreignObject is not supported by IE
        nodeEl.append('foreignObject')
                          .attr('x', n => n.depth === 0 ? '-8em' : '1em') //<--- this is the 1em
                          .attr('y', -6)
                          .append('xhtml:div')
                            .html(n => n.name)
                            .filter(n => n.depth === 1)
                              .style('width','auto')
                              .attr({'class': 'spot-text-wrapper', 'data-toggle': 'tooltip'});

      nodeSel.update.selectAll('foreignObject')
                        .style('width', n => n.depth === 1 ? foreignObject_width : 'auto');

    nodeSel.update.attr('transform', n => `translate(${n.y},${n.x})`);

    nodeSel.exit.remove();
  },
  drawLinks(links) {
      const linkSel = {};

      linkSel.update = this.canvas.selectAll('.link')
                                  .data(links, l => `link-${l.source.id}-${l.target.id}`);
      linkSel.enter = linkSel.update.enter();
      linkSel.exit = linkSel.update.exit();

      linkSel.enter.append('path', '.node')
        .attr('class', 'link')
        .on('mouseover', function (l)
        {
            d3.select(this)
                .style('stroke-width', 2)
                .style('cursor', 'pointer')
                .style('stroke', '#ED1C24');

            d3.selectAll(`#${SpotUtils.encodeId(l.source.id)},#${SpotUtils.encodeId(l.target.id)}`)
                .style('fill', '#C4D600');
      })
      .on('mouseout', function (l)
      {
        d3.select(this)
                      .style('stroke-width', null)
                      .style('cursor', null)
                      .style('stroke', null);

        d3.selectAll(`#${SpotUtils.encodeId(l.source.id)},#${SpotUtils.encodeId(l.target.id)}`)
                        .style('fill', null);
      });

      linkSel.update.attr('d', this.diagonal);

      // Remove old nodes
      linkSel.exit.remove();
  }
};

module.exports = DendrogramMixin;
<|endoftext|>


<commit_before>/* Éditeur OSM dans la Leaflet sidebar */
//les fonctions de manipulation de l'API OSM sont dans OSMAPI.js

//méthode pour pouvoir supprimer facilement un élément d'un tableau
Array.prototype.del = function(val){
    var index = this.indexOf(val)
    if(index > -1){
        this.splice(index,1)
    }
}

function init_form_from_OSM(form,OSM_id) {
        // récupération des valeurs actuelles
        OSM_xml = get_node(OSM_id)
        beer_src = get_tag(OSM_xml,"brewery").toLowerCase()
        name_src = get_tag(OSM_xml,"name") ; if (name_src === "non_fourni") {name_src = ""}  ;
        opening_src = get_tag(OSM_xml,"opening_hours") ; if (opening_src === "non_fourni") {opening_src = ""};
        happy_src = get_tag(OSM_xml,"happy_hours") ; if (happy_src === "non_fourni") {happy_src = ""};
        wifi_src = get_tag(OSM_xml,"internet_access").toLowerCase()

        //écriture des valeurs dans le formulaire
        // id du node, pour pouvoir soumettre le formulaire plus tard
        document.getElementById('OSM_id').value = OSM_id
        // nom du bar
        document.getElementById('bar-name').value = name_src
        // horaires d'ouverture
        document.getElementById('opening_hours').value = opening_src
        // happy hours
        document.getElementById('happy_hours').value = happy_src
        //tout le reste
        var inputForm = form.getElementsByTagName("input"); // récupération ds éléments de type input du formulaire
        var n = inputForm.length;
        for (i=0; i<n; i++)
                {
                if ( (inputForm[i].type.toLowerCase()==="checkbox") && (inputForm[i].name ==="beer"))  // si c'est une case à cocher de type beer
                        {
                        if (inputForm[i].checked) {inputForm[i].checked = false} ; //décocher tout par défaut
                        if (beer_src.indexOf(inputForm[i].value.toLowerCase()) != -1 ) // si j'ai le nom de ma bière dans les données OSM
                                {inputForm[i].checked = true}
                        }

               if ( (inputForm[i].type.toLowerCase()==="radio") && (inputForm[i].name ==="wifi"))
                        {
                        if ((wifi_src === "wlan") || (wifi_src === "yes") ) {if (inputForm[i].value === "wlan") {inputForm[i].checked = true}}
                        if (wifi_src === "non_fourni") {if (inputForm[i].value === "chaispas") {inputForm[i].checked = true}}
                        if (wifi_src === "no") {if (inputForm[i].value === "no") {inputForm[i].checked = true}}
                        }
               }
        };

function form_from_user(form) {
        OSM_id = document.getElementById('OSM_id').value

        // récupération des valeurs de bière actuelles
        OSM_xml = get_node(OSM_id)
        var beer_tab = get_tag(OSM_xml,"brewery").toLowerCase().split(';');

        // récupération des valeurs saisies dans le formulaire
        var name = document.getElementById('bar-name').value
        var opening = document.getElementById('opening_hours').value
        var happy = document.getElementById('happy_hours').value
        var inputForm = form.getElementsByTagName("input");
        var n = inputForm.length;
        for (i=0; i<n; i++)
                {
                //traitement des cases à cocher des types de bières
                if ( (inputForm[i].type.toLowerCase()==="checkbox") && (inputForm[i].name.toLowerCase()==="beer"))
                        {
                        if (inputForm[i].checked)
                                {
                                if (beer_tab.indexOf(inputForm[i].value) === -1 )
                                        {beer_tab.push(inputForm[i].value) }
                                }
                        else
                                {
                                beer_tab.del(inputForm[i].value)
                                }

                        }

                //traitement des cases à cocher pour le wifi
               if ( (inputForm[i].type.toLowerCase()==="radio") && (inputForm[i].name ==="wifi"))
                        {
                        if (inputForm[i].checked) {var wifi = inputForm[i].value} ;
                        }
                }

        // préparation de l'envoi à OSM
        beer_tab.del("non_fourni")
        var brewery = beer_tab.join(";")

        var envoi = 0

        //ici, faire les changements de tag nécessaires
        if (beer_tab.length > 0) {edit_tag(OSM_xml,"brewery",brewery); envoi = 1}
        // s'il n'y avait qu'une bière, et que l'utilisateur la décoche, beer_tab devient vide, il faut donc supprimer le tag
        else {if(brewery != get_tag(OSM_xml,"brewery")) {del_tag(OSM_xml,"brewery");envoi=1}}
        if (wifi != "chaispas") {edit_tag(OSM_xml,"internet_access", wifi); envoi = 1}
        if ((name != get_tag(OSM_xml,"name")) && (name != "")) {edit_tag(OSM_xml, "name", name); envoi = 1}
        if ((opening != get_tag(OSM_xml,"opening_hours")) && (opening != "")) {edit_tag(OSM_xml, "opening_hours", opening); envoi = 1}
        if ((happy != get_tag(OSM_xml,"happy_hours")) && (happy != "")) {edit_tag(OSM_xml, "happy_hours", happy); envoi = 1}

        if (envoi != 0)
                {
                //ouvrir un changeset
                changeset_id = put_changeset()

                //envoyer le nouveau node
                put_node(OSM_xml, changeset_id, OSM_id)

                //fermer le changeset
                close_changeset(changeset_id);
                }
        //TODO : peut-être replier la sidebar si enregistre sans faire de modif ?
        };

<commit_msg>bugfix : ne jamais envoyer un tag vide ('qqch' = '')<commit_after>/* Éditeur OSM dans la Leaflet sidebar */
//les fonctions de manipulation de l'API OSM sont dans OSMAPI.js

//méthode pour pouvoir supprimer facilement un élément d'un tableau
Array.prototype.del = function(val){
    var index = this.indexOf(val)
    if(index > -1){
        this.splice(index,1)
    }
}

function init_form_from_OSM(form,OSM_id) {
        // récupération des valeurs actuelles
        OSM_xml = get_node(OSM_id)
        beer_src = get_tag(OSM_xml,"brewery").toLowerCase()
        name_src = get_tag(OSM_xml,"name") ; if (name_src === "non_fourni") {name_src = ""}  ;
        opening_src = get_tag(OSM_xml,"opening_hours") ; if (opening_src === "non_fourni") {opening_src = ""};
        happy_src = get_tag(OSM_xml,"happy_hours") ; if (happy_src === "non_fourni") {happy_src = ""};
        wifi_src = get_tag(OSM_xml,"internet_access").toLowerCase()

        //écriture des valeurs dans le formulaire
        // id du node, pour pouvoir soumettre le formulaire plus tard
        document.getElementById('OSM_id').value = OSM_id
        // nom du bar
        document.getElementById('bar-name').value = name_src
        // horaires d'ouverture
        document.getElementById('opening_hours').value = opening_src
        // happy hours
        document.getElementById('happy_hours').value = happy_src
        //tout le reste
        var inputForm = form.getElementsByTagName("input"); // récupération ds éléments de type input du formulaire
        var n = inputForm.length;
        for (i=0; i<n; i++)
                {
                if ( (inputForm[i].type.toLowerCase()==="checkbox") && (inputForm[i].name ==="beer"))  // si c'est une case à cocher de type beer
                        {
                        if (inputForm[i].checked) {inputForm[i].checked = false} ; //décocher tout par défaut
                        if (beer_src.indexOf(inputForm[i].value.toLowerCase()) != -1 ) // si j'ai le nom de ma bière dans les données OSM
                                {inputForm[i].checked = true}
                        }

               if ( (inputForm[i].type.toLowerCase()==="radio") && (inputForm[i].name ==="wifi"))
                        {
                        if ((wifi_src === "wlan") || (wifi_src === "yes") ) {if (inputForm[i].value === "wlan") {inputForm[i].checked = true}}
                        if (wifi_src === "non_fourni") {if (inputForm[i].value === "chaispas") {inputForm[i].checked = true}}
                        if (wifi_src === "no") {if (inputForm[i].value === "no") {inputForm[i].checked = true}}
                        }
               }
        };

function form_from_user(form) {
        OSM_id = document.getElementById('OSM_id').value

        // récupération des valeurs de bière actuelles
        OSM_xml = get_node(OSM_id)
        var beer_tab = get_tag(OSM_xml,"brewery").toLowerCase().split(';');

        // récupération des valeurs saisies dans le formulaire
        var name = document.getElementById('bar-name').value
        var opening = document.getElementById('opening_hours').value
        var happy = document.getElementById('happy_hours').value
        var inputForm = form.getElementsByTagName("input");
        var n = inputForm.length;
        for (i=0; i<n; i++)
                {
                //traitement des cases à cocher des types de bières
                if ( (inputForm[i].type.toLowerCase()==="checkbox") && (inputForm[i].name.toLowerCase()==="beer"))
                        {
                        if (inputForm[i].checked)
                                {
                                if (beer_tab.indexOf(inputForm[i].value) === -1 )
                                        {beer_tab.push(inputForm[i].value) }
                                }
                        else
                                {
                                beer_tab.del(inputForm[i].value)
                                }

                        }

                //traitement des cases à cocher pour le wifi
               if ( (inputForm[i].type.toLowerCase()==="radio") && (inputForm[i].name ==="wifi"))
                        {
                        if (inputForm[i].checked) {var wifi = inputForm[i].value} ;
                        }
                }

        // préparation de l'envoi à OSM
        beer_tab.del("non_fourni")
        var brewery = beer_tab.join(";")

        var envoi = 0

        //ici, faire les changements de tag nécessaires
        if (beer_tab.length > 0) {edit_tag(OSM_xml,"brewery",brewery); envoi = 1}
        // s'il n'y avait qu'une bière, et que l'utilisateur la décoche, beer_tab devient vide, il faut donc supprimer le tag
        else {if(brewery != get_tag(OSM_xml,"brewery")) {del_tag(OSM_xml,"brewery");envoi=1}}
        if (wifi != "chaispas") {edit_tag(OSM_xml,"internet_access", wifi); envoi = 1}
        // si wifi n'était pas vide, mais que maintenant, c'est chaispas, il faut supprimer le tag
        else {if(get_tag(OSM_xml,"internet_access") != "non_fourni") {del_tag(OSM_xml,"internet_access");envoi=1}}
        if ((name != get_tag(OSM_xml,"name")) && (name != "")) {edit_tag(OSM_xml, "name", name); envoi = 1}
        //si nom est vide mais qu'avant il y avait qqch, il faut supprimer le tag
        else {if ((get_tag(OSM_xml,"name") != "non_fourni") && (name == "")) {del_tag(OSM_xml, "name"); envoi = 1}}
        /*
        if ((opening != get_tag(OSM_xml,"opening_hours")) && (opening != "")) {edit_tag(OSM_xml, "opening_hours", opening); envoi = 1}
        if ((happy != get_tag(OSM_xml,"happy_hours")) && (happy != "")) {edit_tag(OSM_xml, "happy_hours", happy); envoi = 1}
        */
        if (envoi != 0)
                {
                //ouvrir un changeset
                changeset_id = put_changeset()

                //envoyer le nouveau node
                put_node(OSM_xml, changeset_id, OSM_id)

                //fermer le changeset
                close_changeset(changeset_id);
                }
        //TODO : peut-être replier la sidebar si enregistre sans faire de modif ?
        };

<|endoftext|>


<commit_before>/* eslint no-underscore-dangle: ["error", { "allow": ["_index", "_type"] }] */

const fs = require('fs');
const path = require('path');
const Promise = require('promise');
const debug = require('debug')('winston:elasticsearch');
const retry = require('retry');

const BulkWriter = function BulkWriter(transport, client, options) {
  this.transport = transport;
  this.client = client;
  this.options = options;
  this.interval = options.interval || 5000;
  this.waitForActiveShards = options.waitForActiveShards;
  this.pipeline = options.pipeline;

  this.bulk = []; // bulk to be flushed
  this.running = false;
  this.timer = false;
  debug('created', this);
};

BulkWriter.prototype.start = function start() {
  this.checkEsConnection();
  debug('started');
};

BulkWriter.prototype.stop = function stop() {
  this.running = false;
  if (!this.timer) { return; }
  clearTimeout(this.timer);
  this.timer = null;
  debug('stopped');
};

BulkWriter.prototype.schedule = function schedule() {
  const thiz = this;
  this.timer = setTimeout(() => {
    thiz.tick();
  }, this.interval);
};

BulkWriter.prototype.tick = function tick() {
  debug('tick');
  const thiz = this;
  if (!this.running) { return; }
  this.flush()
    .then(() => {
      // Emulate finally with last .then()
    })
    .then(() => { // finally()
      thiz.schedule();
    });
};

BulkWriter.prototype.flush = function flush() {
  // write bulk to elasticsearch
  if (this.bulk.length === 0) {
    debug('nothing to flush');
    return new Promise((resolve) => {
      return resolve();
    });
  }
  const bulk = this.bulk.concat();
  this.bulk = [];
  const body = [];
  bulk.forEach(({ index, type, doc }) => {
    body.push({ index: { _index: index, _type: type, pipeline: this.pipeline } }, doc);
  });
  debug('bulk writer is going to write', body);
  return this.write(body);
};

BulkWriter.prototype.append = function append(index, type, doc) {
  if (this.options.buffering === true) {
    if (typeof this.options.bufferLimit === 'number' && this.bulk.length >= this.options.bufferLimit) {
      debug('message discarded because buffer limit exceeded');
      // @todo: i guess we can use callback to notify caller
      return;
    }
    this.bulk.push({
      index, type, doc
    });
  } else {
    this.write([{ index: { _index: index, _type: type, pipeline: this.pipeline } }, doc]);
  }
};

BulkWriter.prototype.write = function write(body) {
  const thiz = this;
  return this.client.bulk({
    body,
    waitForActiveShards: this.waitForActiveShards,
    timeout: this.interval + 'ms',
  }).then((response) => {
    const res = response.body;
    if (res.errors && res.items) {
      res.items.forEach((item) => {
        if (item.index && item.index.error) {
          thiz.transport.emit('error', item.index.error);
          // eslint-disable-next-line no-console
          console.error('Elasticsearch index error', item.index);
        }
      });
    }
  }).catch((e) => { // prevent [DEP0018] DeprecationWarning
    // rollback this.bulk array
    const newBody = [];
    for (let i = 0; i < body.length; i += 2) {
      newBody.push({ index: body[i].index._index, type: body[i].index._type, doc: body[i + 1] });
    }
    const lenSum = thiz.bulk.length + newBody.length;
    if (thiz.options.bufferLimit && (lenSum >= thiz.options.bufferLimit)) {
      thiz.bulk = newBody.concat(thiz.bulk.slice(0, thiz.options.bufferLimit - newBody.length));
    } else {
      thiz.bulk = newBody.concat(thiz.bulk);
    }
    thiz.transport.emit('error', e);
    // eslint-disable-next-line no-console
    console.error(e);

    debug('error occurred', e);
    this.stop();
    this.checkEsConnection();
  });
};

BulkWriter.prototype.checkEsConnection = function checkEsConnection() {
  const thiz = this;
  thiz.esConnection = false;

  const operation = retry.operation({
    forever: true,
    retries: 1,
    factor: 1,
    minTimeout: 1 * 1000,
    maxTimeout: 60 * 1000,
    randomize: false
  });
  return new Promise((fulfill, reject) => {
    operation.attempt((currentAttempt) => {
      debug('checking for connection');
      thiz.client.ping().then(
        (res) => {
          thiz.esConnection = true;
          // Ensure mapping template is existing if desired
          if (thiz.options.ensureMappingTemplate) {
            thiz.ensureMappingTemplate(fulfill, reject);
          } else {
            fulfill(true);
          }
          if (thiz.options.buffering === true) {
            debug('starting bulk writer');
            thiz.running = true;
            thiz.tick();
          }
        },
        (err) => {
          debug('checking for connection');
          if (operation.retry(err)) {
            return;
          }
          // thiz.esConnection = false;
          reject(new Error('Cannot connect to ES'));
        }
      );
    });
  });
};

BulkWriter.prototype.ensureMappingTemplate = function ensureMappingTemplate(fulfill, reject) {
  const thiz = this;

  const indexPrefix = (typeof thiz.options.indexPrefix === 'function' ? thiz.options.indexPrefix() : thiz.options.indexPrefix);
  // eslint-disable-next-line prefer-destructuring
  let mappingTemplate = thiz.options.mappingTemplate;
  if (mappingTemplate === null || typeof mappingTemplate === 'undefined') {
    const rawdata = fs.readFileSync(path.join(__dirname, 'index-template-mapping.json'));
    mappingTemplate = JSON.parse(rawdata);
    mappingTemplate.index_patterns = indexPrefix + '-*';
  }

  const tmplCheckMessage = {
    name: 'template_' + indexPrefix
  };
  thiz.client.indices.existsTemplate(tmplCheckMessage).then(
    (res) => {
      if (res.statusCode && res.statusCode === 404) {
        const tmplMessage = {
          name: 'template_' + indexPrefix,
          create: true,
          body: mappingTemplate
        };
        thiz.client.indices.putTemplate(tmplMessage).then(
          (res1) => {
            fulfill(res1.body);
          },
          (err1) => {
            thiz.transport.emit('error', err1);
            reject(err1);
          }
        );
      } else {
        fulfill(res.body);
      }
    },
    (res) => {
      thiz.transport.emit('error', res);
      reject(res);
    }
  );
};

module.exports = BulkWriter;
<commit_msg>By changing push to unshift elements with the same timestamp are in the right order<commit_after>/* eslint no-underscore-dangle: ["error", { "allow": ["_index", "_type"] }] */

const fs = require('fs');
const path = require('path');
const Promise = require('promise');
const debug = require('debug')('winston:elasticsearch');
const retry = require('retry');

const BulkWriter = function BulkWriter(transport, client, options) {
  this.transport = transport;
  this.client = client;
  this.options = options;
  this.interval = options.interval || 5000;
  this.waitForActiveShards = options.waitForActiveShards;
  this.pipeline = options.pipeline;

  this.bulk = []; // bulk to be flushed
  this.running = false;
  this.timer = false;
  debug('created', this);
};

BulkWriter.prototype.start = function start() {
  this.checkEsConnection();
  debug('started');
};

BulkWriter.prototype.stop = function stop() {
  this.running = false;
  if (!this.timer) { return; }
  clearTimeout(this.timer);
  this.timer = null;
  debug('stopped');
};

BulkWriter.prototype.schedule = function schedule() {
  const thiz = this;
  this.timer = setTimeout(() => {
    thiz.tick();
  }, this.interval);
};

BulkWriter.prototype.tick = function tick() {
  debug('tick');
  const thiz = this;
  if (!this.running) { return; }
  this.flush()
    .then(() => {
      // Emulate finally with last .then()
    })
    .then(() => { // finally()
      thiz.schedule();
    });
};

BulkWriter.prototype.flush = function flush() {
  // write bulk to elasticsearch
  if (this.bulk.length === 0) {
    debug('nothing to flush');
    return new Promise((resolve) => {
      return resolve();
    });
  }
  const bulk = this.bulk.concat();
  this.bulk = [];
  const body = [];
  bulk.forEach(({ index, type, doc }) => {
    body.push({ index: { _index: index, _type: type, pipeline: this.pipeline } }, doc);
  });
  debug('bulk writer is going to write', body);
  return this.write(body);
};

BulkWriter.prototype.append = function append(index, type, doc) {
  if (this.options.buffering === true) {
    if (typeof this.options.bufferLimit === 'number' && this.bulk.length >= this.options.bufferLimit) {
      debug('message discarded because buffer limit exceeded');
      // @todo: i guess we can use callback to notify caller
      return;
    }
    this.bulk.unshift({
      index, type, doc
    });
  } else {
    this.write([{ index: { _index: index, _type: type, pipeline: this.pipeline } }, doc]);
  }
};

BulkWriter.prototype.write = function write(body) {
  const thiz = this;
  return this.client.bulk({
    body,
    waitForActiveShards: this.waitForActiveShards,
    timeout: this.interval + 'ms',
  }).then((response) => {
    const res = response.body;
    if (res.errors && res.items) {
      res.items.forEach((item) => {
        if (item.index && item.index.error) {
          thiz.transport.emit('error', item.index.error);
          // eslint-disable-next-line no-console
          console.error('Elasticsearch index error', item.index);
        }
      });
    }
  }).catch((e) => { // prevent [DEP0018] DeprecationWarning
    // rollback this.bulk array
    const newBody = [];
    for (let i = 0; i < body.length; i += 2) {
      newBody.push({ index: body[i].index._index, type: body[i].index._type, doc: body[i + 1] });
    }
    const lenSum = thiz.bulk.length + newBody.length;
    if (thiz.options.bufferLimit && (lenSum >= thiz.options.bufferLimit)) {
      thiz.bulk = newBody.concat(thiz.bulk.slice(0, thiz.options.bufferLimit - newBody.length));
    } else {
      thiz.bulk = newBody.concat(thiz.bulk);
    }
    thiz.transport.emit('error', e);
    // eslint-disable-next-line no-console
    console.error(e);

    debug('error occurred', e);
    this.stop();
    this.checkEsConnection();
  });
};

BulkWriter.prototype.checkEsConnection = function checkEsConnection() {
  const thiz = this;
  thiz.esConnection = false;

  const operation = retry.operation({
    forever: true,
    retries: 1,
    factor: 1,
    minTimeout: 1 * 1000,
    maxTimeout: 60 * 1000,
    randomize: false
  });
  return new Promise((fulfill, reject) => {
    operation.attempt((currentAttempt) => {
      debug('checking for connection');
      thiz.client.ping().then(
        (res) => {
          thiz.esConnection = true;
          // Ensure mapping template is existing if desired
          if (thiz.options.ensureMappingTemplate) {
            thiz.ensureMappingTemplate(fulfill, reject);
          } else {
            fulfill(true);
          }
          if (thiz.options.buffering === true) {
            debug('starting bulk writer');
            thiz.running = true;
            thiz.tick();
          }
        },
        (err) => {
          debug('checking for connection');
          if (operation.retry(err)) {
            return;
          }
          // thiz.esConnection = false;
          reject(new Error('Cannot connect to ES'));
        }
      );
    });
  });
};

BulkWriter.prototype.ensureMappingTemplate = function ensureMappingTemplate(fulfill, reject) {
  const thiz = this;

  const indexPrefix = (typeof thiz.options.indexPrefix === 'function' ? thiz.options.indexPrefix() : thiz.options.indexPrefix);
  // eslint-disable-next-line prefer-destructuring
  let mappingTemplate = thiz.options.mappingTemplate;
  if (mappingTemplate === null || typeof mappingTemplate === 'undefined') {
    const rawdata = fs.readFileSync(path.join(__dirname, 'index-template-mapping.json'));
    mappingTemplate = JSON.parse(rawdata);
    mappingTemplate.index_patterns = indexPrefix + '-*';
  }

  const tmplCheckMessage = {
    name: 'template_' + indexPrefix
  };
  thiz.client.indices.existsTemplate(tmplCheckMessage).then(
    (res) => {
      if (res.statusCode && res.statusCode === 404) {
        const tmplMessage = {
          name: 'template_' + indexPrefix,
          create: true,
          body: mappingTemplate
        };
        thiz.client.indices.putTemplate(tmplMessage).then(
          (res1) => {
            fulfill(res1.body);
          },
          (err1) => {
            thiz.transport.emit('error', err1);
            reject(err1);
          }
        );
      } else {
        fulfill(res.body);
      }
    },
    (res) => {
      thiz.transport.emit('error', res);
      reject(res);
    }
  );
};

module.exports = BulkWriter;
<|endoftext|>


<commit_before>/**
 * Module dependencies
 */

var path = require('path');
var async = require('async');
var Asset = require('./asset');
var Service = require('./service');
var isArray = require('lodash.isarray');
var discovery = require('./discovery');
var Farcaster = require('./farcaster');
var spawnSync = require('child_process').spawnSync;
var singletonify = require('./helper').singletonify;
var partialRender = require('./render');

/**
 * Parse commmand line arguments
 */
var argv = require('minimist')(process.argv);
var SERVICE = argv.service;
var SERVICE_DIR = argv['service-dir'];
var ALLOW_PENDING = argv['allow-pending'];

/**
 * Object for holding pending services
 */
var pendingServices = {};

/**
 * Constructor for MicroMono class
 *
 * @return {MicroMono} Instance of MicroMono class
 */
var MicroMono = module.exports = function MicroMono(options) {
  this.options = this.getDefaultOptions(options);
  this.services = {};
  if (SERVICE) {
    var services = SERVICE.split(',');
    // load services required from command line
    services.forEach(function(name) {
      this.require(name);
    }, this);
  }

  if (ALLOW_PENDING) {
    setInterval(function() {
      var services = Object.keys(pendingServices);
      if (services.length > 0) {
        console.log('Pending service(s): %s', services.join(', '));
      }
    }, 2000);
  }
};

/**
 * MicroMono public API.
 *
 * @type {Object}
 */
MicroMono.prototype = {

  getDefaultOptions: function(options) {
    options = options || {};

    if (!options.packagePath) {
      var parentFile = module.parent.parent.filename;
      options.packagePath = path.dirname(parentFile);
    }

    return options;
  },

  getPackageInfo: function(packagePath) {
    this.asset = new Asset(packagePath);

    try {
      this.asset.parseJSPM();
    } catch (e) {}
  },

  require: function(package) {
    var ServiceClass;

    try {
      // @todo handle path start with './'?
      if (SERVICE_DIR) {
        package = path.resolve(SERVICE_DIR, package);
      }
      ServiceClass = require(package);
    } catch (e) {
      var expectedMessage = 'Cannot find module \'' + package + '\'';
      if (e.code !== 'MODULE_NOT_FOUND' || e.message !== expectedMessage) {
        // throw error if we found the module which contains error.
        throw e;
      }
      var probedResult = spawnSync('node', [require.resolve('./prober'), package]);
      if (probedResult.status !== 0) {
        if (ALLOW_PENDING && probedResult.status === 100) {
          // probe timeout, save the name to pending services and continue
          ServiceClass = pendingServices[package] = Service;
        } else {
          throw new Error(probedResult.stderr.toString());
        }
      } else {
        var serviceInfo = JSON.parse(probedResult.stdout);
        console.log('New service `%s` probed from network.', serviceInfo.name);
        console.log(serviceInfo);
        ServiceClass = Farcaster.build(serviceInfo);
      }
    }

    var ServiceFactory;

    if (ServiceClass === Service) {
      ServiceFactory = Service;
    } else {
      ServiceFactory = singletonify(ServiceClass);
      this.registerService(package, ServiceFactory);
    }

    return ServiceFactory;
  },

  /**
   * @param  {Function} [app] Instance of express application
   * @return {Promise}
   */
  boot: function(app) {
    if (typeof app === 'function') {
      if (app.prototype.isRemote) {
        var Service = app;
        var service = new Service();
        this.registerService(service.announcement.name, service);
        app = null;
      } else if (app.get('views')) {
        app.use(partialRender(app));
      }
    } else if (typeof app === 'string') {
      this.require(app);
      app = null;
    } else if (isArray(app)) {
      app.forEach(function(package) {
        this.require(package);
      }, this);
      app = null;
    }

    var self = this;
    var services = this.services;
    this.getPackageInfo(this.options.packagePath);
    var asset = this.asset;

    var promise = asset.configJSPM()
      .then(function() {
        return new Promise(function(resolve, reject) {
          async.each(Object.keys(services), function runService(name, callback) {
            var serviceInstance = services[name];
            if (typeof serviceInstance === 'function') {
              var ServiceFactory = serviceInstance;
              serviceInstance = new ServiceFactory();
              self.registerService(name, serviceInstance);
            }
            asset.mergeJSPMDeps(serviceInstance.announcement.client);
            var p = serviceInstance.run(app);
            if (!app) {
              p = p.then(function() {
                discovery.announce(serviceInstance.announcement);
              });
            }
            p.then(callback).catch(callback);
          }, function bootServicesFinished(err) {
            err ? reject(err) : resolve();
          });
        });
      });

    if (app) {
      // assume we are in the server mode
      promise = promise.then(function() {
        discovery.listen(function(err, data, rinfo) {
          if (data && data.name) {
            var serviceName = data.name;
            var serviceInstance = services[serviceName];
            if (pendingServices[serviceName]) {
              // Found pending service
              var ServiceClass = self.require(serviceName);
              var ServiceFactory = singletonify(ServiceClass);
              serviceInstance = new ServiceFactory();
              self.registerService(serviceName, serviceInstance);
              delete pendingServices[serviceName];
            } else if (serviceInstance && serviceInstance.isRemote()) {
              // Only remote probed service has the ability to add provider.
              serviceInstance.addProvider(data);
            }
          }
        });
      });

      if (asset.publicURL && asset.publicPath) {
        // serve local asset files
        promise = promise.then(function() {
          app.use(asset.publicURL, require('express').static(asset.publicPath));
        });
      }
    }

    return promise;
  },

  registerService: function(name, serviceInstance) {
    this.services[name] = serviceInstance;
  }
};
<commit_msg>Use cached service class if possible.<commit_after>/**
 * Module dependencies
 */

var path = require('path');
var async = require('async');
var Asset = require('./asset');
var Service = require('./service');
var isArray = require('lodash.isarray');
var discovery = require('./discovery');
var Farcaster = require('./farcaster');
var spawnSync = require('child_process').spawnSync;
var singletonify = require('./helper').singletonify;
var partialRender = require('./render');

/**
 * Parse commmand line arguments
 */
var argv = require('minimist')(process.argv);
var SERVICE = argv.service;
var SERVICE_DIR = argv['service-dir'];
var ALLOW_PENDING = argv['allow-pending'];

/**
 * Object for holding pending services
 */
var pendingServices = {};

/**
 * Constructor for MicroMono class
 *
 * @return {MicroMono} Instance of MicroMono class
 */
var MicroMono = module.exports = function MicroMono(options) {
  this.options = this.getDefaultOptions(options);
  this.services = {};
  if (SERVICE) {
    var services = SERVICE.split(',');
    // load services required from command line
    services.forEach(function(name) {
      this.require(name);
    }, this);
  }

  if (ALLOW_PENDING) {
    setInterval(function() {
      var services = Object.keys(pendingServices);
      if (services.length > 0) {
        console.log('Pending service(s): %s', services.join(', '));
      }
    }, 2000);
  }
};

/**
 * MicroMono public API.
 *
 * @type {Object}
 */
MicroMono.prototype = {

  getDefaultOptions: function(options) {
    options = options || {};

    if (!options.packagePath) {
      var parentFile = module.parent.parent.filename;
      options.packagePath = path.dirname(parentFile);
    }

    return options;
  },

  getPackageInfo: function(packagePath) {
    this.asset = new Asset(packagePath);

    try {
      this.asset.parseJSPM();
    } catch (e) {}
  },

  require: function(package) {
    var ServiceClass;

    try {
      // @todo handle path start with './'?
      if (SERVICE_DIR) {
        package = path.resolve(SERVICE_DIR, package);
      }
      if (this.services[package]) {
        ServiceClass = this.services[package];
      } else {
        ServiceClass = require(package);
      }
    } catch (e) {
      var expectedMessage = 'Cannot find module \'' + package + '\'';
      if (e.code !== 'MODULE_NOT_FOUND' || e.message !== expectedMessage) {
        // throw error if we found the module which contains error.
        throw e;
      }
      var probedResult = spawnSync('node', [require.resolve('./prober'), package]);
      if (probedResult.status !== 0) {
        if (ALLOW_PENDING && probedResult.status === 100) {
          // probe timeout, save the name to pending services and continue
          ServiceClass = pendingServices[package] = Service;
        } else {
          throw new Error(probedResult.stderr.toString());
        }
      } else {
        var serviceInfo = JSON.parse(probedResult.stdout);
        console.log('New service `%s` probed from network.', serviceInfo.name);
        console.log(serviceInfo);
        ServiceClass = Farcaster.build(serviceInfo);
      }
    }

    var ServiceFactory;

    if (ServiceClass === Service) {
      ServiceFactory = Service;
    } else {
      ServiceFactory = singletonify(ServiceClass);
      this.registerService(package, ServiceFactory);
    }

    return ServiceFactory;
  },

  /**
   * @param  {Function} [app] Instance of express application
   * @return {Promise}
   */
  boot: function(app) {
    if (typeof app === 'function') {
      if (app.prototype.isRemote) {
        var Service = app;
        var service = new Service();
        this.registerService(service.announcement.name, service);
        app = null;
      } else if (app.get('views')) {
        app.use(partialRender(app));
      }
    } else if (typeof app === 'string') {
      this.require(app);
      app = null;
    } else if (isArray(app)) {
      app.forEach(function(package) {
        this.require(package);
      }, this);
      app = null;
    }

    var self = this;
    var services = this.services;
    this.getPackageInfo(this.options.packagePath);
    var asset = this.asset;

    var promise = asset.configJSPM()
      .then(function() {
        return new Promise(function(resolve, reject) {
          async.each(Object.keys(services), function runService(name, callback) {
            var serviceInstance = services[name];
            if (typeof serviceInstance === 'function') {
              var ServiceFactory = serviceInstance;
              serviceInstance = new ServiceFactory();
              self.registerService(name, serviceInstance);
            }
            asset.mergeJSPMDeps(serviceInstance.announcement.client);
            var p = serviceInstance.run(app);
            if (!app) {
              p = p.then(function() {
                discovery.announce(serviceInstance.announcement);
              });
            }
            p.then(callback).catch(callback);
          }, function bootServicesFinished(err) {
            err ? reject(err) : resolve();
          });
        });
      });

    if (app) {
      // assume we are in the server mode
      promise = promise.then(function() {
        discovery.listen(function(err, data, rinfo) {
          if (data && data.name) {
            var serviceName = data.name;
            var serviceInstance = services[serviceName];
            if (pendingServices[serviceName]) {
              // Found pending service
              var ServiceClass = self.require(serviceName);
              var ServiceFactory = singletonify(ServiceClass);
              serviceInstance = new ServiceFactory();
              self.registerService(serviceName, serviceInstance);
              delete pendingServices[serviceName];
            } else if (serviceInstance && serviceInstance.isRemote()) {
              // Only remote probed service has the ability to add provider.
              serviceInstance.addProvider(data);
            }
          }
        });
      });

      if (asset.publicURL && asset.publicPath) {
        // serve local asset files
        promise = promise.then(function() {
          app.use(asset.publicURL, require('express').static(asset.publicPath));
        });
      }
    }

    return promise;
  },

  registerService: function(name, serviceInstance) {
    this.services[name] = serviceInstance;
  }
};
<|endoftext|>


<commit_before>import { LightningElement, track, wire } from 'lwc';

import stgHealthCheckErrorLastRunDate from '@salesforce/label/c.stgHealthCheckErrorLastRunDate';

import getHealthCheckViewModel from '@salesforce/apex/HealthCheckController.getHealthCheckViewModel';
import updateHealthCheckLastRunDate from '@salesforce/apex/HealthCheckController.updateHealthCheckLastRunDate';

export default class HealthCheck extends LightningElement {
    @track expanded = true;
    @track totalChecks = 0;
    @track passedChecks = 0;
    @track lastRunDate = '';
    @track displayHealthCheckGroup = false;

    @track healthCheckDefinitionsToDisplayList = [];

    LabelReference = {
        stgHealthCheckErrorLastRunDate
    }

    handleHealthCheckRun(){
        updateHealthCheckLastRunDate()
            .then(result => {
                this.lastRunDate = result;

                if(!this.displayHealthCheckGroup) {
                    this.displayHealthCheckGroup = true;
                    return;
                }

                let healthCheckDisplay = this.template.querySelector('c-health-check-display');
                healthCheckDisplay.refreshHealthCheck();
            })
            .catch(error => {
                this.lastRunDate = this.LabelReference.stgHealthCheckErrorLastRunDate;
            });
    }

    @wire(getHealthCheckViewModel)
    healthCheckViewModel({error, data}){
        if (data){
            this.lastRunDate = data.lastRunDate;
            this.healthCheckDefinitionsToDisplayList = data.healthCheckDefinitionList;
        } else if (error){
            //console.log('error retrieving health check view model: ', error);
        }
    }

    get displayHealthCheck(){
        return !(!this.displayHealthCheckGroup || !this.healthCheckDefinitionsToDisplayList);
    }

}<commit_msg>Revert "test precommit"<commit_after>import { LightningElement, track, wire } from 'lwc';

import stgHealthCheckErrorLastRunDate from '@salesforce/label/c.stgHealthCheckErrorLastRunDate';

import getHealthCheckViewModel from '@salesforce/apex/HealthCheckController.getHealthCheckViewModel';
import updateHealthCheckLastRunDate from '@salesforce/apex/HealthCheckController.updateHealthCheckLastRunDate';

export default class HealthCheck extends LightningElement {
    @track expanded = true;
    @track totalChecks = 0;
    @track passedChecks = 0;
    @track lastRunDate = '';
    @track displayHealthCheckGroup = false;

    @track healthCheckDefinitionsToDisplayList = [];

    LabelReference = {
        stgHealthCheckErrorLastRunDate
    }

    handleHealthCheckRun(){
        updateHealthCheckLastRunDate()
            .then(result => {
                this.lastRunDate = result;

                if(!this.displayHealthCheckGroup) {
                    this.displayHealthCheckGroup = true;
                    return;
                }

                let healthCheckDisplay = this.template.querySelector('c-health-check-display');
                healthCheckDisplay.refreshHealthCheck();
            })
            .catch(error => {
                this.lastRunDate = this.LabelReference.stgHealthCheckErrorLastRunDate;
            });
    }

    @wire(getHealthCheckViewModel)
    healthCheckViewModel({error, data}){
        if (data){
            this.lastRunDate = data.lastRunDate;
            this.healthCheckDefinitionsToDisplayList = data.healthCheckDefinitionList;
        } else if (error){
            //console.log('error retrieving health check view model: ', error);
        }
    }

    get displayHealthCheck(){
        return !(!this.displayHealthCheckGroup || !this.healthCheckDefinitionsToDisplayList);
    }

}<|endoftext|>


<commit_before>const fs = require('fs');
const path = require('path');
const Promise = require('promise');
const debug = require('debug')('winston:elasticsearch');
const retry = require('retry');

const BulkWriter = function BulkWriter(transport, client, options) {
  this.transport = transport;
  this.client = client;
  this.options = options;
  this.interval = options.interval || 5000;
  this.waitForActiveShards = options.waitForActiveShards;
  this.pipeline = options.pipeline;

  this.bulk = []; // bulk to be flushed
  this.running = false;
  this.timer = false;
  debug('created', this);
};

BulkWriter.prototype.start = function start() {
  this.checkEsConnection();
  debug('started');
};

BulkWriter.prototype.stop = function stop() {
  this.running = false;
  if (!this.timer) { return; }
  clearTimeout(this.timer);
  this.timer = null;
  debug('stopped');
};

BulkWriter.prototype.schedule = function schedule() {
  const thiz = this;
  this.timer = setTimeout(() => {
    thiz.tick();
  }, this.interval);
};

BulkWriter.prototype.tick = function tick() {
  debug('tick');
  const thiz = this;
  if (!this.running) { return; }
  this.flush()
    .then(() => {
      // Emulate finally with last .then()
    })
    .then(() => { // finally()
      thiz.schedule();
    });
};

BulkWriter.prototype.flush = function flush() {
  // write bulk to elasticsearch
  if (this.bulk.length === 0) {
    debug('nothing to flush');
    return new Promise((resolve) => {
      return resolve();
    });
  }
  const bulk = this.bulk.concat();
  this.bulk = [];
  const body = [];
  bulk.forEach(({ index, type, doc }) => {
    body.push({ index: { _index: index, _type: type, pipeline: this.pipeline } }, doc);
  });
  debug('bulk writer is going to write', body);
  return this.write(body);
};

BulkWriter.prototype.append = function append(index, type, doc) {
  if (this.options.buffering === true) {
    if (typeof this.options.bufferLimit === 'number' && this.bulk.length >= this.options.bufferLimit) {
      debug('message discarded because buffer limit exceeded');
      // @todo: i guess we can use callback to notify caller
      return;
    }
    this.bulk.push({
      index, type, doc
    });
  } else {
    this.write([{ index: { _index: index, _type: type, pipeline: this.pipeline } }, doc]);
  }
};

BulkWriter.prototype.write = function write(body) {
  const thiz = this;
  return this.client.bulk({
    body,
    waitForActiveShards: this.waitForActiveShards,
    timeout: this.interval + 'ms',
    type: this.type
  }).then((res) => {
    if (res.errors && res.items) {
      res.items.forEach((item) => {
        if (item.index && item.index.error) {
          // eslint-disable-next-line no-console
          thiz.transport.emit('error', item.index.error);
          console.error('Elasticsearch index error', item.index);
        }
      });
    }
  }).catch((e) => { // prevent [DEP0018] DeprecationWarning
    // rollback this.bulk array
    const _body = [];
    for (let i = 0; i < body.length; i += 2) {
      _body.push({index: body[i].index._index, type: body[i].index._type, doc: body[i+1]});
    }
    const lenSum = thiz.bulk.length + _body.length;
    if (thiz.options.bufferLimit && (lenSum >= thiz.options.bufferLimit)) {
      thiz.bulk = _body.concat(thiz.bulk.slice(0, thiz.options.bufferLimit - _body.length));
    } else {
      thiz.bulk = _body.concat(thiz.bulk);
    }
    // eslint-disable-next-line no-console
    thiz.transport.emit('error', e);
    console.error(e);

    debug('error occurred', e);
    this.stop();
    this.checkEsConnection();
  });
};

BulkWriter.prototype.checkEsConnection = function checkEsConnection() {
  const thiz = this;
  thiz.esConnection = false;

  const operation = retry.operation({
    forever: true,
    retries: 1,
    factor: 1,
    minTimeout: 1 * 1000,
    maxTimeout: 60 * 1000,
    randomize: false
  });
  return new Promise((fulfill, reject) => {
    operation.attempt((currentAttempt) => {
      debug('checking for connection');
      thiz.client.ping().then(
        (res) => {
          thiz.esConnection = true;
          // Ensure mapping template is existing if desired
          if (thiz.options.ensureMappingTemplate) {
            thiz.ensureMappingTemplate(fulfill, reject);
          } else {
            fulfill(true);
          }
          if (thiz.options.buffering === true) {
            debug('starting bulk writer');
            thiz.running = true;
            thiz.tick();
          }
        },
        (err) => {
          debug('checking for connection');
          if (operation.retry(err)) {
            return;
          }
          // thiz.esConnection = false;
          reject(new Error('Cannot connect to ES'));
        }
      );
    });
  });
};

BulkWriter.prototype.ensureMappingTemplate = function ensureMappingTemplate(fulfill, reject) {
  const thiz = this;
  // eslint-disable-next-line prefer-destructuring
  let mappingTemplate = thiz.options.mappingTemplate;
  if (mappingTemplate === null || typeof mappingTemplate === 'undefined') {
    const rawdata = fs.readFileSync(path.join(__dirname, 'index-template-mapping.json'));
    mappingTemplate = JSON.parse(rawdata);
  }
  const tmplCheckMessage = {
    name: 'template_' + (typeof thiz.options.indexPrefix === 'function' ? thiz.options.indexPrefix() : thiz.options.indexPrefix)
  };
  thiz.client.indices.getTemplate(tmplCheckMessage).then(
    (res) => {
      console.log(res);
      fulfill(res);
    },
    (res) => {
      console.log('rrrrrrrrrrrrrrrrR', res);
      if (res.status && res.status === 404) {
        const tmplMessage = {
          name: 'template_' + (typeof thiz.options.indexPrefix === 'function' ? thiz.options.indexPrefix() : thiz.options.indexPrefix),
          create: true,
          body: mappingTemplate
        };
        thiz.client.indices.putTemplate(tmplMessage).then(
          (res1) => {
            fulfill(res1);
          },
          (err1) => {
            reject(err1);
          }
        );
      }
    }
  );
};

module.exports = BulkWriter;
<commit_msg>Don't pass redundant "type" field<commit_after>const fs = require('fs');
const path = require('path');
const Promise = require('promise');
const debug = require('debug')('winston:elasticsearch');
const retry = require('retry');

const BulkWriter = function BulkWriter(transport, client, options) {
  this.transport = transport;
  this.client = client;
  this.options = options;
  this.interval = options.interval || 5000;
  this.waitForActiveShards = options.waitForActiveShards;
  this.pipeline = options.pipeline;

  this.bulk = []; // bulk to be flushed
  this.running = false;
  this.timer = false;
  debug('created', this);
};

BulkWriter.prototype.start = function start() {
  this.checkEsConnection();
  debug('started');
};

BulkWriter.prototype.stop = function stop() {
  this.running = false;
  if (!this.timer) { return; }
  clearTimeout(this.timer);
  this.timer = null;
  debug('stopped');
};

BulkWriter.prototype.schedule = function schedule() {
  const thiz = this;
  this.timer = setTimeout(() => {
    thiz.tick();
  }, this.interval);
};

BulkWriter.prototype.tick = function tick() {
  debug('tick');
  const thiz = this;
  if (!this.running) { return; }
  this.flush()
    .then(() => {
      // Emulate finally with last .then()
    })
    .then(() => { // finally()
      thiz.schedule();
    });
};

BulkWriter.prototype.flush = function flush() {
  // write bulk to elasticsearch
  if (this.bulk.length === 0) {
    debug('nothing to flush');
    return new Promise((resolve) => {
      return resolve();
    });
  }
  const bulk = this.bulk.concat();
  this.bulk = [];
  const body = [];
  bulk.forEach(({ index, type, doc }) => {
    body.push({ index: { _index: index, _type: type, pipeline: this.pipeline } }, doc);
  });
  debug('bulk writer is going to write', body);
  return this.write(body);
};

BulkWriter.prototype.append = function append(index, type, doc) {
  if (this.options.buffering === true) {
    if (typeof this.options.bufferLimit === 'number' && this.bulk.length >= this.options.bufferLimit) {
      debug('message discarded because buffer limit exceeded');
      // @todo: i guess we can use callback to notify caller
      return;
    }
    this.bulk.push({
      index, type, doc
    });
  } else {
    this.write([{ index: { _index: index, _type: type, pipeline: this.pipeline } }, doc]);
  }
};

BulkWriter.prototype.write = function write(body) {
  const thiz = this;
  return this.client.bulk({
    body,
    waitForActiveShards: this.waitForActiveShards,
    timeout: this.interval + 'ms',
  }).then((res) => {
    if (res.errors && res.items) {
      res.items.forEach((item) => {
        if (item.index && item.index.error) {
          // eslint-disable-next-line no-console
          thiz.transport.emit('error', item.index.error);
          console.error('Elasticsearch index error', item.index);
        }
      });
    }
  }).catch((e) => { // prevent [DEP0018] DeprecationWarning
    // rollback this.bulk array
    const _body = [];
    for (let i = 0; i < body.length; i += 2) {
      _body.push({index: body[i].index._index, type: body[i].index._type, doc: body[i+1]});
    }
    const lenSum = thiz.bulk.length + _body.length;
    if (thiz.options.bufferLimit && (lenSum >= thiz.options.bufferLimit)) {
      thiz.bulk = _body.concat(thiz.bulk.slice(0, thiz.options.bufferLimit - _body.length));
    } else {
      thiz.bulk = _body.concat(thiz.bulk);
    }
    // eslint-disable-next-line no-console
    thiz.transport.emit('error', e);
    console.error(e);

    debug('error occurred', e);
    this.stop();
    this.checkEsConnection();
  });
};

BulkWriter.prototype.checkEsConnection = function checkEsConnection() {
  const thiz = this;
  thiz.esConnection = false;

  const operation = retry.operation({
    forever: true,
    retries: 1,
    factor: 1,
    minTimeout: 1 * 1000,
    maxTimeout: 60 * 1000,
    randomize: false
  });
  return new Promise((fulfill, reject) => {
    operation.attempt((currentAttempt) => {
      debug('checking for connection');
      thiz.client.ping().then(
        (res) => {
          thiz.esConnection = true;
          // Ensure mapping template is existing if desired
          if (thiz.options.ensureMappingTemplate) {
            thiz.ensureMappingTemplate(fulfill, reject);
          } else {
            fulfill(true);
          }
          if (thiz.options.buffering === true) {
            debug('starting bulk writer');
            thiz.running = true;
            thiz.tick();
          }
        },
        (err) => {
          debug('checking for connection');
          if (operation.retry(err)) {
            return;
          }
          // thiz.esConnection = false;
          reject(new Error('Cannot connect to ES'));
        }
      );
    });
  });
};

BulkWriter.prototype.ensureMappingTemplate = function ensureMappingTemplate(fulfill, reject) {
  const thiz = this;
  // eslint-disable-next-line prefer-destructuring
  let mappingTemplate = thiz.options.mappingTemplate;
  if (mappingTemplate === null || typeof mappingTemplate === 'undefined') {
    const rawdata = fs.readFileSync(path.join(__dirname, 'index-template-mapping.json'));
    mappingTemplate = JSON.parse(rawdata);
  }
  const tmplCheckMessage = {
    name: 'template_' + (typeof thiz.options.indexPrefix === 'function' ? thiz.options.indexPrefix() : thiz.options.indexPrefix)
  };
  thiz.client.indices.getTemplate(tmplCheckMessage).then(
    (res) => {
      console.log(res);
      fulfill(res);
    },
    (res) => {
      console.log('rrrrrrrrrrrrrrrrR', res);
      if (res.status && res.status === 404) {
        const tmplMessage = {
          name: 'template_' + (typeof thiz.options.indexPrefix === 'function' ? thiz.options.indexPrefix() : thiz.options.indexPrefix),
          create: true,
          body: mappingTemplate
        };
        thiz.client.indices.putTemplate(tmplMessage).then(
          (res1) => {
            fulfill(res1);
          },
          (err1) => {
            reject(err1);
          }
        );
      }
    }
  );
};

module.exports = BulkWriter;
<|endoftext|>


<commit_before>function reduceAdd(p, v) {
    v.groups.forEach (function(val, idx) {
        p[val] = (p[val] || 0) + 1; //increment counts
    });
    return p;
}

function reduceRemove(p, v) {
    v.groups.forEach (function(val, idx) {
        p[val] = (p[val] || 0) - 1; //decrement counts
    });
    return p;

}

function reduceInitial() {
    return {};
}

ExampleApp.directive('category', ['MetadataService', function(MetadataService) {

    return {
        restrict: 'AE',
        templateUrl: 'category_widget/category.html',
        scope: {},
        link: function(scope, element, attrs) {
            scope.categories = [];

            scope.$on('init', function() {
                var data = MetadataService.getData();
                scope.dimCategory = data.dimension(function(d){return d.groups;});
                scope.groupCategory = scope.dimCategory.groupAll().reduce(reduceAdd, reduceRemove, reduceInitial);

            });

            scope.$on('filterChanged', function() {
            });

        }
    };
}]);
<commit_msg>improved category widget<commit_after>ExampleApp.directive('category', ['MetadataService', function(MetadataService) {

    return {
        restrict: 'AE',
        templateUrl: 'category_widget/category.html',
        scope: {},
        link: function(scope, element, attrs) {
            scope.categories = [];

            scope.$on('init', function() {
                var data = MetadataService.getData();
                scope.dimCategory = data.dimension(function(d){return d.groups;});
                scope.groupCategory = scope.dimCategory.groupAll().reduce(scope.reduceAdd, scope.reduceRemove, scope.reduceInitial);

            });

            scope.$on('filterChanged', function() {
            });

            scope.reduceAdd = function (p, v) {
                v.groups.forEach (function(val, idx) {
                    p[val] = (p[val] || 0) + 1; //increment counts
                });
                return p;
            };

            scope.reduceRemove = function(p, v) {
                v.groups.forEach (function(val, idx) {
                    p[val] = (p[val] || 0) - 1; //decrement counts
                });
                return p;
            };

            scope.reduceInitial = function() {
                return {};
            }

        }
    };
}]);
<|endoftext|>