<commit_before>var pixel = 9;

var defaultTravelTimes = [900];

var polygonLayer = r360.leafletPolygonLayer().addTo(map);
polygonLayer.setColors([
     // { 'time': 300, 'opacity': 1.0, 'color': '#509373' },
     // { 'time': 600, 'opacity': 1.0, 'color': '#75c380' },
      { 'time': 900, 'opacity': 1.0, 'color': '#C1272D' }
     // { 'time': 1500, 'opacity': 1.0, 'color': '#C1272D' },
     // ["#509373", "#75c380", "#abcf79"]
  ]);
var showPolygons = function() {
    polygonLayer.setStrokeWidth(pixel);

  };

// group.addTo(map)
$('#leaflet-popup').on('click', '.trigger', function(marker, travelOptions) {
// function onClick (marker, travelOptions) {
  var defaultColors = r360.config.defaultTravelTimeControlOptions.travelTimes.filter(function(t){
    return defaultTravelTimes.indexOf(t.time) > -1;
  }).map(function(t){
    return t.color;
  });
  var app1 = document.getElementById('app1');
  angular.element(function() {
     angular.bootstrap(app1, ['app1']);
  });
  angular.module('app1',['ngMaterial', 'ng360'])
  .controller("RainbowExampleController", function() {
    var vm = this;
    vm.rainbowConf = {
        range: { times: [15] },
        travelTime: 15,
        colorRange: {
            "name": "Green to Red",
            "id": "default",
            "colors": [/*"#509373", "#75c380", */"#abcf79"],
            "opacities": [1.0]
        }}
    });
  var polygonLayer = r360.leafletPolygonLayer()
  polygonLayer.addTo(map);
  var travelOptions = r360.travelOptions();
  travelOptions.setServiceKey('N2T7JHHPOTJAWSFQ7YOMJYH')
  travelOptions.setServiceUrl('https://service.route360.net/na_northeast/')
  travelOptions.addSource(marker);
  travelOptions.setTravelTimes([900])
  travelOptions.setTravelType('car');
  r360.PolygonService.getTravelTimePolygons(travelOptions, function(polygons){
    polygonLayer.setStrokeWidth(10);
    polygonLayer.clearAndAddLayers(polygons, false);
  });
});
<commit_msg>Update polkadot.js<commit_after>var pixel = 9;

var defaultTravelTimes = [900];

var polygonLayer = r360.leafletPolygonLayer().addTo(map);
polygonLayer.setColors([
     // { 'time': 300, 'opacity': 1.0, 'color': '#509373' },
     // { 'time': 600, 'opacity': 1.0, 'color': '#75c380' },
      { 'time': 900, 'opacity': 1.0, 'color': '#C1272D' }
     // { 'time': 1500, 'opacity': 1.0, 'color': '#C1272D' },
     // ["#509373", "#75c380", "#abcf79"]
  ]);
var showPolygons = function() {
    polygonLayer.setStrokeWidth(pixel);

  };

// group.addTo(map)
//$('#leaflet-popup').on('click', '.trigger', function(marker, travelOptions) {
function onClick (marker, travelOptions) {
  var defaultColors = r360.config.defaultTravelTimeControlOptions.travelTimes.filter(function(t){
    return defaultTravelTimes.indexOf(t.time) > -1;
  }).map(function(t){
    return t.color;
  });
  var app1 = document.getElementById('app1');
  angular.element(function() {
     angular.bootstrap(app1, ['app1']);
  });
  angular.module('app1',['ngMaterial', 'ng360'])
  .controller("RainbowExampleController", function() {
    var vm = this;
    vm.rainbowConf = {
        range: { times: [15] },
        travelTime: 15,
        colorRange: {
            "name": "Green to Red",
            "id": "default",
            "colors": [/*"#509373", "#75c380", */"#abcf79"],
            "opacities": [1.0]
        }}
    });
  var polygonLayer = r360.leafletPolygonLayer()
  polygonLayer.addTo(map);
  var travelOptions = r360.travelOptions();
  travelOptions.setServiceKey('N2T7JHHPOTJAWSFQ7YOMJYH')
  travelOptions.setServiceUrl('https://service.route360.net/na_northeast/')
  travelOptions.addSource(marker);
  travelOptions.setTravelTimes([900])
  travelOptions.setTravelType('car');
  r360.PolygonService.getTravelTimePolygons(travelOptions, function(polygons){
    polygonLayer.setStrokeWidth(10);
    polygonLayer.clearAndAddLayers(polygons, false);
  });
};
//);
<|endoftext|>


<commit_before>var pixel = 9;

var defaultTravelTimes = [900];

var polygonLayer = r360.leafletPolygonLayer().addTo(map);
polygonLayer.setColors([
     // { 'time': 300, 'opacity': 1.0, 'color': '#509373' },
     // { 'time': 600, 'opacity': 1.0, 'color': '#75c380' },
      { 'time': 900, 'opacity': 1.0, 'color': '#C1272D' }
     // { 'time': 1500, 'opacity': 1.0, 'color': '#C1272D' },
     // ["#509373", "#75c380", "#abcf79"]
  ]);
var showPolygons = function() {
    polygonLayer.setStrokeWidth(pixel);

  };

// group.addTo(map)
// $('#leaflet-popup').on('click', '.trigger', function(marker, travelOptions) {
function onClick (marker, travelOptions) {
  var defaultColors = r360.config.defaultTravelTimeControlOptions.travelTimes.filter(function(t){
    return defaultTravelTimes.indexOf(t.time) > -1;
  }).map(function(t){
    return t.color;
  });
  var app1 = document.getElementById('app1');
  angular.element(function() {
     angular.bootstrap(app1, ['app1']);
  });
  angular.module('app1',['ngMaterial', 'ng360'])
  .controller("RainbowExampleController", function() {
    var vm = this;
    vm.rainbowConf = {
        range: { times: [15] },
        travelTime: 15,
        colorRange: {
            "name": "Green to Red",
            "id": "default",
            "colors": [/*"#509373", "#75c380", */"#abcf79"],
            "opacities": [1.0]
        }}
    });
  var polygonLayer = r360.leafletPolygonLayer()
  polygonLayer.addTo(map);
  var travelOptions = r360.travelOptions();
  travelOptions.setServiceKey('N2T7JHHPOTJAWSFQ7YOMJYH')
  travelOptions.setServiceUrl('https://service.route360.net/na_northeast/')
  travelOptions.addSource(marker);
  travelOptions.setTravelTimes([900])
  travelOptions.setTravelType('car');
  r360.PolygonService.getTravelTimePolygons(travelOptions, function(polygons){
    polygonLayer.setStrokeWidth(10);
    polygonLayer.clearAndAddLayers(polygons, false);
  });
});

<commit_msg>Update polkadot.js<commit_after>var pixel = 9;

var defaultTravelTimes = [900];

var polygonLayer = r360.leafletPolygonLayer().addTo(map);
polygonLayer.setColors([
     // { 'time': 300, 'opacity': 1.0, 'color': '#509373' },
     // { 'time': 600, 'opacity': 1.0, 'color': '#75c380' },
      { 'time': 900, 'opacity': 1.0, 'color': '#C1272D' }
     // { 'time': 1500, 'opacity': 1.0, 'color': '#C1272D' },
     // ["#509373", "#75c380", "#abcf79"]
  ]);
var showPolygons = function() {
    polygonLayer.setStrokeWidth(pixel);

  };

// group.addTo(map)
// $('#leaflet-popup').on('click', '.trigger', function(marker, travelOptions) {
function onClick (marker, travelOptions) {
  var defaultColors = r360.config.defaultTravelTimeControlOptions.travelTimes.filter(function(t){
    return defaultTravelTimes.indexOf(t.time) > -1;
  }).map(function(t){
    return t.color;
  });
  var app1 = document.getElementById('app1');
  angular.element(function() {
     angular.bootstrap(app1, ['app1']);
  });
  angular.module('app1',['ngMaterial', 'ng360'])
  .controller("RainbowExampleController", function() {
    var vm = this;
    vm.rainbowConf = {
        range: { times: [15] },
        travelTime: 15,
        colorRange: {
            "name": "Green to Red",
            "id": "default",
            "colors": [/*"#509373", "#75c380", */"#abcf79"],
            "opacities": [1.0]
        }}
    });
  var polygonLayer = r360.leafletPolygonLayer()
  polygonLayer.addTo(map);
  var travelOptions = r360.travelOptions();
  travelOptions.setServiceKey('N2T7JHHPOTJAWSFQ7YOMJYH')
  travelOptions.setServiceUrl('https://service.route360.net/na_northeast/')
  travelOptions.addSource(marker);
  travelOptions.setTravelTimes([900])
  travelOptions.setTravelType('car');
  r360.PolygonService.getTravelTimePolygons(travelOptions, function(polygons){
    polygonLayer.setStrokeWidth(10);
    polygonLayer.clearAndAddLayers(polygons, false);
  });
};
<|endoftext|>


<commit_before>var render = function (post) {
    var bff = post['package'];
    var objects = bff['objects'];

    var getColorFromArray = function (array, alpha) {
        array = array || [0, 0, 0, 1.0];
        var color = 'rgba(' +   parseInt(array[0] * 255) + ', ' +
                                parseInt(array[1] * 255) + ', ' +
                                parseInt(array[2] * 255) + ', ' +
                                (alpha || (array[3])) + ')';
        return color;
    }

    var getAspectFrame = function (type, parentWidth, parentHeight, childWidth, childHeight) {
        var parentAspect = parentWidth / parentHeight;
        var childAspect = childWidth / childHeight;
        var ratio;

        if (type == 'fill') {
            if (parentAspect > childAspect) {
                ratio = parentWidth / childWidth;
            } else {
                ratio = parentHeight / childHeight;
            }
        } else {
            if (parentAspect > childAspect) {
                ratio = parentHeight / childHeight;
            } else {
                ratio = parentWidth / childWidth;
            }
        }

        var targetW = childWidth * ratio;
        var targetH = childHeight * ratio;

        return [
            parentWidth / 2 - targetW / 2,
            parentHeight / 2 - targetH / 2,
            targetW,
            targetH
        ];
    }

    var getFontNameForStyle = function (style) {
        switch (style) {
            case 'sans':
                return 'Helvetica';
                break;
            case 'serif':
                return 'Georgia';
                break;
            case 'mono':
                return 'Courier';
                break;
            case 'eightbit':
                return 'Courier';
                break;
            case 'poster':
                return 'Impact';
                break;
        }

        return 'Helvetica';
    }

    var bg = bff['background'];
    var $rootNode = $('
');
    $rootNode
        .css('width', 324)
        .css('height', 570)
        .css('overflow', 'hidden')
        .css('display', 'block')
        .css('position', 'relative');

    objects.forEach(function (object, index) {

        var $node;
        var frame = object['frame'];
        var transform = object['transform'];
        var opacity = object['opacity'];

        switch (object['type']) {
            case 'graphic':
                $node = $('
');
                var $image = $('');
                $image.load(function () {
                    var aspectFrame = getAspectFrame(object['scaleMode'] || 'fit', frame[2], frame[3], $image.width(), $image.height());
                    $image
                        .css('left', aspectFrame[0])
                        .css('top', aspectFrame[1])
                        .css('width', aspectFrame[2])
                        .css('height', aspectFrame[3])
                });
                $node.append($image);
                break;

            case 'image':
            case 'gif':
                $node = $('
');
                var $image = $('');
                $image.load(function () {
                    var aspectFrame = getAspectFrame(object['scaleMode'] || 'fill', frame[2], frame[3], $image.width(), $image.height());
                    $image
                        .css('left', aspectFrame[0])
                        .css('top', aspectFrame[1])
                        .css('width', aspectFrame[2])
                        .css('height', aspectFrame[3])
                });
                $node.append($image);

                break;

            case 'text':
                console.log(object);
                $node = $('
');

                var words = object['text'].split(' ');
                var text = '';
                var wordCountForCurrentLine = 0;
                words.forEach(function (word, index) {
                    if (wordCountForCurrentLine >= 5) {
                        wordCountForCurrentLine = 0;
                        text += '\n';
                    } else {
                        if (index > 0) {
                            text += ' ';
                        }
                    }

                    text += word;
                    wordCountForCurrentLine++;
                });

                var lines = text.split('\n');

                var $canvas = $('<canvas>')
                var context = $canvas[0].getContext('2d');
                $canvas[0].width = frame[2];
                $canvas[0].height = frame[3];
                context.font = '100px ' + getFontNameForStyle(object['style']);
                context.textAlign = 'center';
                context.textBaseline = 'top';
                context.fillStyle = getColorFromArray(object['color']);

                var highestLineWidth = 0;
                var yOffset = 0;

                lines.forEach(function (line, index) {
                    var dimensions = context.measureText(line);
                    if (dimensions.width > highestLineWidth) {
                        highestLineWidth = dimensions.width;
                    }

                    yOffset += dimensions.actualBoundingBoxAscent + dimensions.actualBoundingBoxDescent;
                });

                var widthRatio = (frame[2] - 40) / highestLineWidth;
                var heightRatio = (frame[3] - 20) / yOffset;
                var ratio = Math.min(widthRatio, heightRatio);

                var fontSize = (100 * ratio);
                var estimatedHeight = fontSize * lines.length;
                context.font = fontSize + 'px ' + getFontNameForStyle(object['style']);

                lines.forEach(function (line, index) {
                    context.fillText(line, frame[2] / 2, (frame[3] / 2 - estimatedHeight / 2) + index * fontSize);
                });

                $node.append($canvas);
                break;

            case 'paragraph':
                frame = [
                    frame[0] + 20,
                    frame[1] + 10,
                    frame[2] - 40,
                    frame[3] - 20
                ];

                $node = $('
');
                $node.css('font-family', getFontNameForStyle(object['style']));
                $node.css('font-size', object['size'] || 17);
                $node.css('color', getColorFromArray(object['color']));
                $node.css('box-sizing', 'border-box');
                $node.css('text-align', object['alignment'] || 'left');
                $node.html(object['text'].replace(/(?:\r\n|\r|\n)/g, '
'));
                break;

            case 'video':
                $node = $('
');
                var $video = $('<video style="position: absolute" muted loop autoplay>');
                $video[0].onloadeddata = function () {
                    var aspectFrame = getAspectFrame('fill', frame[2], frame[3], $video.width(), $video.height());
                    $video
                        .css('left', aspectFrame[0])
                        .css('top', aspectFrame[1])
                        .css('width', aspectFrame[2])
                        .css('height', aspectFrame[3])
                };
                $video.append('<source src="' + object['src'] + '" type="video/mp4">');
                $node.append($video);
                break;

            case 'link':

                frame = [
                    frame[0] + 5,
                    frame[1] + 5,
                    frame[2] - 10,
                    frame[3] - 10
                ];

                $node = $('' + object['title'] + '');
                $node.css('border', '2px solid ' + getColorFromArray(object['color']));
                $node.css('color', getColorFromArray(object['color']));
                $node.css('box-sizing', 'border-box');
                $node.css('border-radius', 6);
                $node.css('text-align', 'center');
                $node.css('text-decoration', 'none');
                $node.css('line-height', (frame[3] - 3) + 'px');
                $node.css('font-family', 'Helvetica');
                $node.css('font-weight', 600);

                $node.mouseover(function () {
                    $node.css('background', getColorFromArray(object['color'], 0.5));
                });

                $node.mouseout(function () {
                    $node.css('background', 'none');
                });
                break;
        }

        if ($node) {
            $node.addClass('node');
            $node
                .css('overflow', 'hidden')
                .css('position', 'absolute')
                .css('left', frame[0])
                .css('top', frame[1])
                .css('width', frame[2])
                .css('height', frame[3]);

            if (transform) {
                var transformString = [
                    transform[0][0],
                    transform[0][1],
                    transform[1][0],
                    transform[1][1],
                    transform[2][0],
                    transform[2][1]
                ].join(', ');
                $node.css('transform', 'matrix(' + transformString + ')');
            }

            if (opacity) {
                $node.css('opacity', opacity);
            }

            $rootNode.append($node);
        }

    });

    return $rootNode;
}

window.ByteRenderer = {
    render: render
};<commit_msg>render paragraph white space with pre-wrap instead of
<commit_after>var render = function (post) {
    var bff = post['package'];
    var objects = bff['objects'];

    var getColorFromArray = function (array, alpha) {
        array = array || [0, 0, 0, 1.0];
        var color = 'rgba(' +   parseInt(array[0] * 255) + ', ' +
                                parseInt(array[1] * 255) + ', ' +
                                parseInt(array[2] * 255) + ', ' +
                                (alpha || (array[3])) + ')';
        return color;
    }

    var getAspectFrame = function (type, parentWidth, parentHeight, childWidth, childHeight) {
        var parentAspect = parentWidth / parentHeight;
        var childAspect = childWidth / childHeight;
        var ratio;

        if (type == 'fill') {
            if (parentAspect > childAspect) {
                ratio = parentWidth / childWidth;
            } else {
                ratio = parentHeight / childHeight;
            }
        } else {
            if (parentAspect > childAspect) {
                ratio = parentHeight / childHeight;
            } else {
                ratio = parentWidth / childWidth;
            }
        }

        var targetW = childWidth * ratio;
        var targetH = childHeight * ratio;

        return [
            parentWidth / 2 - targetW / 2,
            parentHeight / 2 - targetH / 2,
            targetW,
            targetH
        ];
    }

    var getFontNameForStyle = function (style) {
        switch (style) {
            case 'sans':
                return 'Helvetica';
                break;
            case 'serif':
                return 'Georgia';
                break;
            case 'mono':
                return 'Courier';
                break;
            case 'eightbit':
                return 'Courier';
                break;
            case 'poster':
                return 'Impact';
                break;
        }

        return 'Helvetica';
    }

    var bg = bff['background'];
    var $rootNode = $('
');
    $rootNode
        .css('width', 324)
        .css('height', 570)
        .css('overflow', 'hidden')
        .css('display', 'block')
        .css('position', 'relative');

    objects.forEach(function (object, index) {

        var $node;
        var frame = object['frame'];
        var transform = object['transform'];
        var opacity = object['opacity'];

        switch (object['type']) {
            case 'graphic':
                $node = $('
');
                var $image = $('');
                $image.load(function () {
                    var aspectFrame = getAspectFrame(object['scaleMode'] || 'fit', frame[2], frame[3], $image.width(), $image.height());
                    $image
                        .css('left', aspectFrame[0])
                        .css('top', aspectFrame[1])
                        .css('width', aspectFrame[2])
                        .css('height', aspectFrame[3])
                });
                $node.append($image);
                break;

            case 'image':
            case 'gif':
                $node = $('
');
                var $image = $('');
                $image.load(function () {
                    var aspectFrame = getAspectFrame(object['scaleMode'] || 'fill', frame[2], frame[3], $image.width(), $image.height());
                    $image
                        .css('left', aspectFrame[0])
                        .css('top', aspectFrame[1])
                        .css('width', aspectFrame[2])
                        .css('height', aspectFrame[3])
                });
                $node.append($image);

                break;

            case 'text':
                console.log(object);
                $node = $('
');

                var words = object['text'].split(' ');
                var text = '';
                var wordCountForCurrentLine = 0;
                words.forEach(function (word, index) {
                    if (wordCountForCurrentLine >= 5) {
                        wordCountForCurrentLine = 0;
                        text += '\n';
                    } else {
                        if (index > 0) {
                            text += ' ';
                        }
                    }

                    text += word;
                    wordCountForCurrentLine++;
                });

                var lines = text.split('\n');

                var $canvas = $('<canvas>')
                var context = $canvas[0].getContext('2d');
                $canvas[0].width = frame[2];
                $canvas[0].height = frame[3];
                context.font = '100px ' + getFontNameForStyle(object['style']);
                context.textAlign = 'center';
                context.textBaseline = 'top';
                context.fillStyle = getColorFromArray(object['color']);

                var highestLineWidth = 0;
                var yOffset = 0;

                lines.forEach(function (line, index) {
                    var dimensions = context.measureText(line);
                    if (dimensions.width > highestLineWidth) {
                        highestLineWidth = dimensions.width;
                    }

                    yOffset += dimensions.actualBoundingBoxAscent + dimensions.actualBoundingBoxDescent;
                });

                var widthRatio = (frame[2] - 40) / highestLineWidth;
                var heightRatio = (frame[3] - 20) / yOffset;
                var ratio = Math.min(widthRatio, heightRatio);

                var fontSize = (100 * ratio);
                var estimatedHeight = fontSize * lines.length;
                context.font = fontSize + 'px ' + getFontNameForStyle(object['style']);

                lines.forEach(function (line, index) {
                    context.fillText(line, frame[2] / 2, (frame[3] / 2 - estimatedHeight / 2) + index * fontSize);
                });

                $node.append($canvas);
                break;

            case 'paragraph':
                frame = [
                    frame[0] + 20,
                    frame[1] + 10,
                    frame[2] - 40,
                    frame[3] - 20
                ];

                $node = $('
');
                $node.css('font-family', getFontNameForStyle(object['style']));
                $node.css('font-size', object['size'] || 17);
                $node.css('color', getColorFromArray(object['color']));
                $node.css('box-sizing', 'border-box');
                $node.css('text-align', object['alignment'] || 'left');
                $node.css('white-space', 'pre-wrap');
                break;

            case 'video':
                $node = $('
');
                var $video = $('<video style="position: absolute" muted loop autoplay>');
                $video[0].onloadeddata = function () {
                    var aspectFrame = getAspectFrame('fill', frame[2], frame[3], $video.width(), $video.height());
                    $video
                        .css('left', aspectFrame[0])
                        .css('top', aspectFrame[1])
                        .css('width', aspectFrame[2])
                        .css('height', aspectFrame[3])
                };
                $video.append('<source src="' + object['src'] + '" type="video/mp4">');
                $node.append($video);
                break;

            case 'link':

                frame = [
                    frame[0] + 5,
                    frame[1] + 5,
                    frame[2] - 10,
                    frame[3] - 10
                ];

                $node = $('' + object['title'] + '');
                $node.css('border', '2px solid ' + getColorFromArray(object['color']));
                $node.css('color', getColorFromArray(object['color']));
                $node.css('box-sizing', 'border-box');
                $node.css('border-radius', 6);
                $node.css('text-align', 'center');
                $node.css('text-decoration', 'none');
                $node.css('line-height', (frame[3] - 3) + 'px');
                $node.css('font-family', 'Helvetica');
                $node.css('font-weight', 600);

                $node.mouseover(function () {
                    $node.css('background', getColorFromArray(object['color'], 0.5));
                });

                $node.mouseout(function () {
                    $node.css('background', 'none');
                });
                break;
        }

        if ($node) {
            $node.addClass('node');
            $node
                .css('overflow', 'hidden')
                .css('position', 'absolute')
                .css('left', frame[0])
                .css('top', frame[1])
                .css('width', frame[2])
                .css('height', frame[3]);

            if (transform) {
                var transformString = [
                    transform[0][0],
                    transform[0][1],
                    transform[1][0],
                    transform[1][1],
                    transform[2][0],
                    transform[2][1]
                ].join(', ');
                $node.css('transform', 'matrix(' + transformString + ')');
            }

            if (opacity) {
                $node.css('opacity', opacity);
            }

            $rootNode.append($node);
        }

    });

    return $rootNode;
}

window.ByteRenderer = {
    render: render
};<|endoftext|>


<commit_before>maria.ElementView.subclass(checkit, 'TodoView', {
    uiActions: {
        'mouseover .todo'        : 'onMouseoverRoot'  ,
        'mouseout  .todo'        : 'onMouseoutRoot'   ,
        'click     .check'       : 'onClickCheck'     ,
        'click     .todo-destroy': 'onClickDestroy'   ,
        'dblclick  .todo-content': 'onDblclickDisplay',
        'keyup     .todo-input'  : 'onKeyupInput'     ,
        'keypress  .todo-input'  : 'onKeypressInput'  ,
        'blur      .todo-input'  : 'onBlurInput'
    },
    properties: {
        update: function() {
            var model = this.getModel();
            var content = model.getContent();
            this.find('.todo-content').innerHTML =
                content.replace('&', '&').replace('<', '<');
            this.find('.check').checked = model.isDone();
            aristocrat[model.isDone() ? 'addClass' : 'removeClass'](this.getRootEl(), 'done');
        },
        showEdit: function() {
            var input = this.find('.todo-input');
            input.value = this.getModel().getContent();
            aristocrat.addClass(this.getRootEl(), 'editing');
            input.focus();
        },
        showDisplay: function() {
            aristocrat.removeClass(this.getRootEl(), 'editing');
        },
        getInputValue: function() {
            return this.find('.todo-input').value;
        },
        showHoverState: function() {
            aristocrat.addClass(this.find('.todo'), 'todo-hover');
        },
        hideHoverState: function() {
            aristocrat.removeClass(this.find('.todo'), 'todo-hover');
        },
        showToolTip: function() {
            this.find('.ui-tooltip-top').style.display = 'block';
        },
        hideToolTip: function() {
            this.find('.ui-tooltip-top').style.display = 'none';
        }
    }
});
<commit_msg>change to select to comply with TodoMVC requirement<commit_after>maria.ElementView.subclass(checkit, 'TodoView', {
    uiActions: {
        'mouseover .todo'        : 'onMouseoverRoot'  ,
        'mouseout  .todo'        : 'onMouseoutRoot'   ,
        'click     .check'       : 'onClickCheck'     ,
        'click     .todo-destroy': 'onClickDestroy'   ,
        'dblclick  .todo-content': 'onDblclickDisplay',
        'keyup     .todo-input'  : 'onKeyupInput'     ,
        'keypress  .todo-input'  : 'onKeypressInput'  ,
        'blur      .todo-input'  : 'onBlurInput'
    },
    properties: {
        update: function() {
            var model = this.getModel();
            var content = model.getContent();
            this.find('.todo-content').innerHTML =
                content.replace('&', '&').replace('<', '<');
            this.find('.check').checked = model.isDone();
            aristocrat[model.isDone() ? 'addClass' : 'removeClass'](this.getRootEl(), 'done');
        },
        showEdit: function() {
            var input = this.find('.todo-input');
            input.value = this.getModel().getContent();
            aristocrat.addClass(this.getRootEl(), 'editing');
            input.select();
        },
        showDisplay: function() {
            aristocrat.removeClass(this.getRootEl(), 'editing');
        },
        getInputValue: function() {
            return this.find('.todo-input').value;
        },
        showHoverState: function() {
            aristocrat.addClass(this.find('.todo'), 'todo-hover');
        },
        hideHoverState: function() {
            aristocrat.removeClass(this.find('.todo'), 'todo-hover');
        },
        showToolTip: function() {
            this.find('.ui-tooltip-top').style.display = 'block';
        },
        hideToolTip: function() {
            this.find('.ui-tooltip-top').style.display = 'none';
        }
    }
});
<|endoftext|>


<commit_before>// This is the main ShelfDB javascript framework namespace
var ShelfDB = (function(sdb, $) {

  // This databases base path (the path of the file this script is included from, should be index.php)
  var _basePath = (function() {
    var getUrl = window.location;
    var pathParts = getUrl.pathname.split('/');
    pathParts.splice(-1,1);
    return pathParts.join('/')+'/';
  })();

  var _init = function() {
    coreModule.pageHookClear();
    coreModule.pageHookInit();
  };

  // The core submodule
  var coreModule = (function() {

    return {
      pageHookClear: function() {
        console.log("DEBUG: clearing page hooks");
        $.mobile.pageCreateTasks = [];
        $.mobile.pageContainerBeforeShowTasks = [];
        $.mobile.pageContainerBeforeLoadTasks = [];
        $.mobile.pageContainerBeforeChangeTasks = [];
        $.mobile.pageContainerChangeTasks = [];
      },
      pageHookInit: function() {

        $(document).on('updatelayout',function() {
          console.log("DEBUG: updatelayout");
        });

        $(document).on('menupanelopen',function() {
          console.log("DEBUG: menupanelopen");
          $(window).trigger('resize');
        });

        $(document).on('menupanelclose',function() {
          console.log("DEBUG: menupanelclose");
          $(window).trigger('resize');
        });

        $(document).one('pagecreate', function() {
            console.log("DEBUG: page - create (once)");

            $(':mobile-pagecontainer').on('pagecontainerbeforeshow', function(event,ui) {
              console.log("DEBUG: pagecontainer - beforeshow");

              $.mobile.pageContainerBeforeShowTasks.forEach(function(fun) { fun(event,ui); });
            });

            $(':mobile-pagecontainer').on('pagecontainerbeforeload', function(event,ui) {
              console.log("DEBUG: pagecontainer - beforeload");

              $.mobile.pageContainerBeforeLoadTasks.forEach(function(fun) { fun(event,ui); });

              sdb.Core.pageHookClear();
            });

            $(':mobile-pagecontainer').on('pagecontainerchange', function(event,ui) {
              console.log("DEBUG: pagecontainer - change");

              $.mobile.pageContainerChangeTasks.forEach(function(fun) { fun(event,ui); });

              sdb.Core.pageHookClear();
            });

            $(':mobile-pagecontainer').on('pagecontainerbeforechange', function(event,ui) {
              console.log("DEBUG: pagecontainer - beforechange");

              $.mobile.pageContainerBeforeChangeTasks.forEach(function(fun) { fun(event,ui); });
            });
        });
        $(document).on('popupcreate', function() {
          console.log("DEBUG: popup - create");
        });
        $(document).on('pagecreate', function() {
            console.log("DEBUG: page - create");

            $(document).on( "panelclose", "[data-role=menupanel]", function() {
              console.log('Panel close');
            });

            $.mobile.pageCreateTasks.forEach(function(fun) { fun(); });

            $("[data-role=menupanel]").one("panelbeforeopen", function() {
              var height = $.mobile.pageContainer.pagecontainer("getActivePage").outerHeight();
              $(".ui-panel-wrapper").css("height", height+1);
            });
        });
      },
      basePath: _basePath
    };
  })();

  // Actions
  _init();

  $.extend(sdb, {
    Core: coreModule
  });

  return sdb;
})(typeof ShelfDB !== 'undefined' ? ShelfDB : {}, jQuery);
<commit_msg>Start moving file transfer functions to sdb lib<commit_after>// This is the main ShelfDB javascript framework namespace
var ShelfDB = (function(sdb, $) {

  // This databases base path (the path of the file this script is included from, should be index.php)
  var _basePath = (function() {
    var getUrl = window.location;
    var pathParts = getUrl.pathname.split('/');
    pathParts.splice(-1,1);
    return pathParts.join('/')+'/';
  })();

  var _init = function() {
    coreModule.pageHookClear();
    coreModule.pageHookInit();
  };

  // The core submodule
  var coreModule = (function() {

    return {
      pageHookClear: function() {
        console.log("DEBUG: clearing page hooks");
        $.mobile.pageCreateTasks = [];
        $.mobile.pageContainerBeforeShowTasks = [];
        $.mobile.pageContainerBeforeLoadTasks = [];
        $.mobile.pageContainerBeforeChangeTasks = [];
        $.mobile.pageContainerChangeTasks = [];
      },
      pageHookInit: function() {

        $(document).on('updatelayout',function() {
          console.log("DEBUG: updatelayout");
        });

        $(document).on('menupanelopen',function() {
          console.log("DEBUG: menupanelopen");
          $(window).trigger('resize');
        });

        $(document).on('menupanelclose',function() {
          console.log("DEBUG: menupanelclose");
          $(window).trigger('resize');
        });

        $(document).one('pagecreate', function() {
            console.log("DEBUG: page - create (once)");

            $(':mobile-pagecontainer').on('pagecontainerbeforeshow', function(event,ui) {
              console.log("DEBUG: pagecontainer - beforeshow");

              $.mobile.pageContainerBeforeShowTasks.forEach(function(fun) { fun(event,ui); });
            });

            $(':mobile-pagecontainer').on('pagecontainerbeforeload', function(event,ui) {
              console.log("DEBUG: pagecontainer - beforeload");

              $.mobile.pageContainerBeforeLoadTasks.forEach(function(fun) { fun(event,ui); });

              sdb.Core.pageHookClear();
            });

            $(':mobile-pagecontainer').on('pagecontainerchange', function(event,ui) {
              console.log("DEBUG: pagecontainer - change");

              $.mobile.pageContainerChangeTasks.forEach(function(fun) { fun(event,ui); });

              sdb.Core.pageHookClear();
            });

            $(':mobile-pagecontainer').on('pagecontainerbeforechange', function(event,ui) {
              console.log("DEBUG: pagecontainer - beforechange");

              $.mobile.pageContainerBeforeChangeTasks.forEach(function(fun) { fun(event,ui); });
            });
        });
        $(document).on('popupcreate', function() {
          console.log("DEBUG: popup - create");
        });
        $(document).on('pagecreate', function() {
            console.log("DEBUG: page - create");

            $(document).on( "panelclose", "[data-role=menupanel]", function() {
              console.log('Panel close');
            });

            $.mobile.pageCreateTasks.forEach(function(fun) { fun(); });

            $("[data-role=menupanel]").one("panelbeforeopen", function() {
              var height = $.mobile.pageContainer.pagecontainer("getActivePage").outerHeight();
              $(".ui-panel-wrapper").css("height", height+1);
            });
        });
      },
      basePath: _basePath,
      uploadFile: function(opts, event = null) {
        var defaults = {
          uploadTarget: 'tempFile', //'footprintImage', ,'tempImage', 'tempFile' ...
          files: null,
          success: null,
          error: null
        };

        opts = $.extend(true,{},defaults,opts);

        var abortEvent = function(){
          event.stopPropagation();
          event.preventDefault();
        };

        if( event && !opts.files ) {
          opts.files = event.target.files;
        }

        if( opts.files.length <= 0 ) {
          if( event )
            abortEvent();

          return;
        }

        $.mobile.referencedLoading('show', {
          theme: "a"
        });

        // Add the files
        var data = new FormData();
        $.each(opts.files, function(key, value) {
          data.append(key,value);
        });

        $.each({
          type: 'uploadToTemp',
          target: opts.uploadTarget
        }, function(key, value) {
          data.append(key,value);
        });

        $.ajax({
          url: ShelfDB.Core.basePath+'lib/upload-files.php',
          type: 'POST',
          data: data,
          cache: false,
          dataType: 'json',
          processData: false,
          contentType: false,
          success: function(data, textStatus, jqXHR) {
            if( typeof data.error === 'undefined')
            {
              // Success
              if( typeof opts.success === 'function' )
                opts.success(data);
            } else {
              // Handle error
              if( typeof opts.error === 'function' )
                opts.error(textStatus, data);
            }
            $.mobile.referencedLoading('hide');

          },
          error: function(jqXHR, textStatus, errorThrown) {
            // Handle error
            console.log('ERRORS: ' + textStatus + ' ' + errorThrown.message);
            $.mobile.referencedLoading('hide');

            if( typeof opts.error === 'function' )
              opts.error(errorThrown, data);
          }
        });

      },
      moveUploadedFile: function(opts) {
        var defaults = {
          targetType: null, //'footprintImage', ...
          tempFilename: null,
          success: null,
          error: null,
          data: null
        };

        opts = $.extend(true,{},defaults,opts);

        $.ajax({
        url: ShelfDB.Core.basePath+'lib/upload-files.php',
        type: 'POST',
        data: {
          tempFilename: opts.tempFilename,
          type: 'moveTempToTarget',
          target: opts.targetType,
        },
        cache: false,
        dataType: 'json',
        success: function(data, textStatus, jqXHR) {
          if( typeof data.error === 'undefined') {
            // Success -> create new footprint entry in database
            if( typeof opts.success === 'function' )
              opts.success(data, opts.data);
          } else {
            // Handle error
            $.mobile.referencedLoading('hide');

            if( typeof opts.error === 'function' )
              opts.error(textStatus, data);
          }

        },
        error: function(jqXHR, textStatus, errorThrown) {
          // Handle error
          console.log('ERRORS: ' + textStatus + ' ' + errorThrown.message);
          $.mobile.referencedLoading('hide');

          if( typeof opts.error === 'function' )
            opts.error(errorThrown, opts.data);
        }
      });
      }
    };
  })();

  // Actions
  _init();

  $.extend(sdb, {
    Core: coreModule
  });

  return sdb;
})(typeof ShelfDB !== 'undefined' ? ShelfDB : {}, jQuery);
<|endoftext|>


<commit_before>var Settings = function () {
	this.settings = {};

	// Apply hardcoded defaults
	$.extend(this.settings, Settings.globalDefaultSettings);

	// Apply local installation defaults
	if (Settings.defaultSettings) {
		$.extend(this.settings, Settings.defaultSettings);
	}

	// Apply client-defined settings
	if (localStorage && localStorage['settings']) {
		$.extend(this.settings, localStorage['settings']);
	}
};

// This gets overwritten by config/config.js
Settings.defaultSettings = {};

// These are the hardcoded default settings
Settings.globalDefaultSettings = {
	// Currently, the recommended default fee is 0.1 BTC
	fee: 0.1,

	// By default we'll look for an exit node running on the same
	// host as the web server.
	exitNodeHost: location.host,
	exitNodePost: 3125
};

Settings.prototype.get = function (key, defValue) {
	if ("undefined" !== typeof this.settings[key] &&
		null !== this.settings[key]) {
		return this.settings[key];
	} else {
		return defValue;
	}
};

Settings.prototype.apply = function (newSettings) {
	for (var i in newSettings) {
		if (newSettings.hasOwnProperty(i)) {
			if (newSettings[i] != this.settings[i]) {
				var settingChangeEvent = jQuery.Event('settingsChange');
				settingChangeEvent.key = i;
				settingChangeEvent.oldValue = this.settings[i];
				settingChangeEvent.newValue = newSettings[i];

				this.settings[i] = newSettings[i];

				$(this).trigger(settingChangeEvent);
			}
		}
	}
};
<commit_msg>Fixed typo.<commit_after>var Settings = function () {
	this.settings = {};

	// Apply hardcoded defaults
	$.extend(this.settings, Settings.globalDefaultSettings);

	// Apply local installation defaults
	if (Settings.defaultSettings) {
		$.extend(this.settings, Settings.defaultSettings);
	}

	// Apply client-defined settings
	if (localStorage && localStorage['settings']) {
		$.extend(this.settings, localStorage['settings']);
	}
};

// This gets overwritten by config/config.js
Settings.defaultSettings = {};

// These are the hardcoded default settings
Settings.globalDefaultSettings = {
	// Currently, the recommended default fee is 0.1 BTC
	fee: 0.1,

	// By default we'll look for an exit node running on the same
	// host as the web server.
	exitNodeHost: location.host,
	exitNodePort: 3125
};

Settings.prototype.get = function (key, defValue) {
	if ("undefined" !== typeof this.settings[key] &&
		null !== this.settings[key]) {
		return this.settings[key];
	} else {
		return defValue;
	}
};

Settings.prototype.apply = function (newSettings) {
	for (var i in newSettings) {
		if (newSettings.hasOwnProperty(i)) {
			if (newSettings[i] != this.settings[i]) {
				var settingChangeEvent = jQuery.Event('settingsChange');
				settingChangeEvent.key = i;
				settingChangeEvent.oldValue = this.settings[i];
				settingChangeEvent.newValue = newSettings[i];

				this.settings[i] = newSettings[i];

				$(this).trigger(settingChangeEvent);
			}
		}
	}
};
<|endoftext|>


<commit_before>module.exports = {
  testEnvironment: 'node',
  setupFiles: ['raf/polyfill', '<rootDir>/test/unit/jest-setup.js'],
  coveragePathIgnorePatterns: [
    'node_modules/',
    'dist/',
    'coverage/',
    'resolve.build.config.js',
    'resolve.client.config.js',
    'resolve.server.config.js'
  ],
  unmockedModulePathPatterns: ['node_modules/react/', 'node_modules/enzyme/']
}
<commit_msg>Fix configs<commit_after>module.exports = {
  testEnvironment: 'node',
  setupFiles: ['raf/polyfill', '<rootDir>/test/unit/jest-setup.js'],
  coveragePathIgnorePatterns: [
    'node_modules/',
    'dist/',
    'coverage/',
    'config.app.js',
    'config.dev.js',
    'config.prod.js',
    'config.test_functional.js'
  ],
  unmockedModulePathPatterns: ['node_modules/react/', 'node_modules/enzyme/']
}
<|endoftext|>


<commit_before>'use strict';

const Future = require('..');

function printStatus(fn) {
  switch(%GetOptimizationStatus(fn)) {
    case 1: console.log('Function is optimized'); break;
    case 2: console.log('Function is not optimized'); break;
    case 3: console.log('Function is always optimized'); break;
    case 4: console.log('Function is never optimized'); break;
    case 6: console.log('Function is maybe deoptimized'); break;
    case 7: console.log('Function is optimized by TurboFan'); break;
    default: console.log('Unknown optimization status'); break;
  }
}

const noop = () => {};
const m = Future.of(1);

console.log('--- map chain ap fork ---');

Future.of(1)
.map(x => x + 1)
.chain(x => Future.of(f => f(x + 1)))
.ap(Future.of(x => x + 1))
.fork(noop, noop);

%OptimizeFunctionOnNextCall(Future.of);
%OptimizeFunctionOnNextCall(m.map);
%OptimizeFunctionOnNextCall(m.chain);
%OptimizeFunctionOnNextCall(m.ap);
%OptimizeFunctionOnNextCall(m.fork);

printStatus(Future.of);
printStatus(m.map);
printStatus(m.chain);
printStatus(m.ap);
printStatus(m.fork);

Future.of(1)
.map(x => x + 1)
.chain(x => Future.of(f => f(x + 1)))
.ap(Future.of(x => x + 1))
.fork(noop, noop);

printStatus(Future.of);
printStatus(m.map);
printStatus(m.chain);
printStatus(m.ap);
printStatus(m.fork);

console.log('--- cache fork ---');

Future.of(1).cache().fork(noop, noop);

%OptimizeFunctionOnNextCall(Future.prototype.cache);
%OptimizeFunctionOnNextCall(Future.prototype.fork);

printStatus(Future.prototype.cache);
printStatus(Future.prototype.fork);

Future.of(1).cache().fork(noop, noop);

printStatus(Future.prototype.cache);
printStatus(Future.prototype.fork);

console.log('--- parallel fork ---');

Future.parallel(2, [Future.of(1), Future.of(2)]).fork(noop, noop);

%OptimizeFunctionOnNextCall(Future.parallel);
%OptimizeFunctionOnNextCall(Future.prototype.fork);

printStatus(Future.parallel);
printStatus(Future.prototype.fork);

Future.parallel(2, [Future.of(1), Future.of(2)]).fork(noop, noop);

printStatus(Future.parallel);
printStatus(Future.prototype.fork);
<commit_msg>Fix test-opt script<commit_after>'use strict';

const Future = require('..');

function printStatus(fn) {
  switch(%GetOptimizationStatus(fn)) {
    case 1: console.log('Function is optimized'); break;
    case 2: console.log('Function is not optimized'); break;
    case 3: console.log('Function is always optimized'); break;
    case 4: console.log('Function is never optimized'); break;
    case 6: console.log('Function is maybe deoptimized'); break;
    case 7: console.log('Function is optimized by TurboFan'); break;
    default: console.log('Unknown optimization status'); break;
  }
}

const noop = () => {};
const m = Future.of(1);

console.log('--- map chain ap fork ---');

Future.of(1)
.map(x => x + 1)
.chain(x => Future.of(x + 1))
.ap(Future.of(x => x + 1))
.fork(noop, noop);

%OptimizeFunctionOnNextCall(Future.of);
%OptimizeFunctionOnNextCall(m.map);
%OptimizeFunctionOnNextCall(m.chain);
%OptimizeFunctionOnNextCall(m.ap);
%OptimizeFunctionOnNextCall(m.fork);

printStatus(Future.of);
printStatus(m.map);
printStatus(m.chain);
printStatus(m.ap);
printStatus(m.fork);

Future.of(1)
.map(x => x + 1)
.chain(x => Future.of(x + 1))
.ap(Future.of(x => x + 1))
.fork(noop, noop);

printStatus(Future.of);
printStatus(m.map);
printStatus(m.chain);
printStatus(m.ap);
printStatus(m.fork);

console.log('--- cache fork ---');

Future.of(1).cache().fork(noop, noop);

%OptimizeFunctionOnNextCall(Future.prototype.cache);
%OptimizeFunctionOnNextCall(Future.prototype.fork);

printStatus(Future.prototype.cache);
printStatus(Future.prototype.fork);

Future.of(1).cache().fork(noop, noop);

printStatus(Future.prototype.cache);
printStatus(Future.prototype.fork);

console.log('--- parallel fork ---');

Future.parallel(2, [Future.of(1), Future.of(2)]).fork(noop, noop);

%OptimizeFunctionOnNextCall(Future.parallel);
%OptimizeFunctionOnNextCall(Future.prototype.fork);

printStatus(Future.parallel);
printStatus(Future.prototype.fork);

Future.parallel(2, [Future.of(1), Future.of(2)]).fork(noop, noop);

printStatus(Future.parallel);
printStatus(Future.prototype.fork);
<|endoftext|>


<commit_before>const compose = require('koa-compose')
const Router = require('koa-router')
const Boom = require('boom')

const handleErrors = require('../middlewares/errors')
const widgets = require('./widgets')
const jobs = require('./jobs')

const route = new Router()

route.prefix('/api')

route.use('*', handleErrors())

route.get('/refresh', async (ctx) => {
  ctx.io.emit('refresh')
  ctx.res.body = { refresh: true }
})

const api = () => compose([
  route.routes(),
  route.allowedMethods({
    throw: true,
    notImplemented: () => new Boom.notImplemented(), // eslint-disable-line new-cap
    methodNotAllowed: () => new Boom.methodNotAllowed() // eslint-disable-line new-cap
  }),
  widgets(),
  jobs()
])

module.exports = api
<commit_msg>change /refresh api endpoint to post<commit_after>const compose = require('koa-compose')
const Router = require('koa-router')
const Boom = require('boom')

const handleErrors = require('../middlewares/errors')
const widgets = require('./widgets')
const jobs = require('./jobs')

const route = new Router()

route.prefix('/api')

route.use('*', handleErrors())

route.post('/refresh', async (ctx) => {
  ctx.io.emit('refresh')
  ctx.res.body = { refresh: true }
})

const api = () => compose([
  route.routes(),
  route.allowedMethods({
    throw: true,
    notImplemented: () => new Boom.notImplemented(), // eslint-disable-line new-cap
    methodNotAllowed: () => new Boom.methodNotAllowed() // eslint-disable-line new-cap
  }),
  widgets(),
  jobs()
])

module.exports = api
<|endoftext|>


<commit_before>var _         = require('underscore');
var RaceModel = require('../models/race');

var RaceApi = {

  get: function get(id, res) {

    var params = id !== null ? { _id: id } : {}

    RaceModel.find(params).sort({ createdAt: 1 }).exec(function(err, races) {

      if (err) res.send(err);

      res.json(races);

    });

  },

  update: function update(id, data, res) {

    RaceModel.find({ _id: id }, (err, race) => {

      if (_.contains(race[0].competitors, data.id)) {

        this.pullUserFromRace(id, data.id, res);

      } else {

        this.addUserToRace(id, data.id, res);

      }

    });

  },

  addUserToRace: function addUserToRace(raceId, userId, res) {

    RaceModel.update(
      { _id: raceId },
      { $addToSet: { "competitors": { [userId]: 0.0 } } },
      { safe: true, upsert: true },
      function(err) {

        if (err) res.send(err);

        console.log('user added to race');

        res.json({ message: 'user added to race' });

      }

    );

  },

  pullUserFromRace: function pullUserFromRace(raceId, userId, res) {

    RaceModel.update(
      { _id: raceId },
      { $pull: { "competitors": { [userId]: 0.0 } } },
      function(err) {

        if (err) res.send(err);

        console.log('user pulled from race');

        res.json({ message: 'user pulled from race' });

      }

    );

  },

};

module.exports = RaceApi;
<commit_msg>revert<commit_after>var _         = require('underscore');
var RaceModel = require('../models/race');

var RaceApi = {

  get: function get(id, res) {

    var params = id !== null ? { _id: id } : {}

    RaceModel.find(params).sort({ createdAt: 1 }).exec(function(err, races) {

      if (err) res.send(err);

      res.json(races);

    });

  },

  update: function update(id, data, res) {

    RaceModel.find({ _id: id }, (err, race) => {

      if (_.contains(race[0].competitors, data.id)) {

        this.pullUserFromRace(id, data.id, res);

      } else {

        this.addUserToRace(id, data.id, res);

      }

    });

  },

  addUserToRace: function addUserToRace(raceId, userId, res) {

    RaceModel.update(
      { _id: raceId },
      { $addToSet: { "competitors": userId } },
      { safe: true, upsert: true },
      function(err) {

        if (err) res.send(err);

        console.log('user added to race');

        res.json({ message: 'user added to race' });

      }

    );

  },

  pullUserFromRace: function pullUserFromRace(raceId, userId, res) {

    RaceModel.update(
      { _id: raceId },
      { $pull: { "competitors": userId } },
      function(err) {

        if (err) res.send(err);

        console.log('user pulled from race');

        res.json({ message: 'user pulled from race' });

      }

    );

  },

};

module.exports = RaceApi;
<|endoftext|>


<commit_before>'use strict';

require('dotenv').config();

const Raven = require('raven');
Raven.config(process.env.SENTRY_DSN).install();

const Hapi = require('hapi');
const Joi = require('joi');
const AWS = require('aws-sdk');
const fs = require('fs');
const socketIo = require('socket.io');

module.exports = (PORT) => {
    const REGION = process.env.REGION;
    const MEASUREMENTS_TABLE = process.env.MEASUREMENTS_TABLE;
    const STATION_IDS_TABLE = process.env.STATION_IDS_TABLE;

    // TODO What future will bring us? Nobody knows, but those values may be fetched from db someday (they say so)
    const measurementInterval = 100;
    const distanceHysteresis = 20;
    const splitDistance = 150;

    console.log('Starting server');
    console.log('Port is', PORT);
    console.log('Region is', REGION);
    console.log('Measurements table is', MEASUREMENTS_TABLE);
    console.log('Allowed station IDs table is', STATION_IDS_TABLE);

    const server = new Hapi.Server({ debug: { request: ['error'] } });
    server.connection({
        port: PORT
    });
    const io = socketIo(server.listener);

    AWS.config.region = REGION;
    const ddb = new AWS.DynamoDB();

    let allowedStationIds = [];
    ddb.scan({
        'TableName': STATION_IDS_TABLE,
        'ReturnConsumedCapacity': 'TOTAL'
    }).promise().then((data) => {
        data.Items.forEach(function (element) {
            const stationId = element.StationId.S;
            console.log('Allowing station ID', stationId);

            allowedStationIds.push(stationId);
        });
    }).catch((error) => {
        console.log('Cannot get allowed station IDs from database, error', error);
        Raven.captureException(error);
    });

    server.route({
        method: 'POST',
        path:'/measurement',
        handler: (request, reply) => {
            console.log('POST /measurement');

            const payloadDecoded = request.payload;
            console.log(payloadDecoded);

            const stationId = payloadDecoded.stationId;

            if (!allowedStationIds.includes(stationId)) {
                return reply({
                    message: 'Station ID not allowed.'
                }).code(400);
            }

            const itemTimestamp = Date.now().toString();
            const item = {
                'Timestamp': { 'N': itemTimestamp },
                'StationId': { 'S': stationId },
                'Distance': { 'N': payloadDecoded.distance.toString() }
            };

            const response = reply(new Promise((resolve, reject) => {
                ddb.putItem({
                    'TableName': MEASUREMENTS_TABLE,
                    'Item': item
                }, (error, data) => {
                    if (error) {
                        console.log('Error saving data in database: ' + error);

                        Raven.captureException(error);

                        reject({
                            message: 'Measurement save failed, error: ' + err
                            statusCode: 500,
                            message: 'Measurement save failed, error: ' + error
                        });
                    } else {
                        console.log('Data saved in database');

                        response.created(request.path + '/' + itemTimestamp);
                        resolve({
                            statusCode: 201,
                            message: 'Measurement saved successfully.'
                        });
                    }
                });
            }));

            return response;
        },
        config: {
            validate: {
                payload: {
                    stationId: Joi.string().required(),
                    distance: Joi.number().required()
                }
            }
        }
    });

    server.route({
        method: 'GET',
        path:'/calibration',
        handler: function (request, reply) {
            console.log('GET /calibration');

            return reply({
                message: 'Calibration data sent successfully.',
                data: {
                    measurementInterval: measurementInterval,
                    distanceHysteresis: distanceHysteresis,
                    splitDistance: splitDistance
                }
            });
        }
    });

    server.register(require('inert'), (err) => {
        if (err) {
            console.log(err);
            return;
        }

        server.route({
            method: 'GET',
            path: '/{param*}',
            handler: (request, reply) => {
                console.log('GET /{param*}');

                const requestFile = request.path.split('/').pop();
                const isDirectory = requestFile.length == 0 || !requestFile.includes('.');
                const fullFilesystemPath = 'dist/' + (isDirectory ? 'index.html' : requestFile );

                console.log(`Sending file ${fullFilesystemPath}`);
                return reply.file(fullFilesystemPath);
            }
        });
    });

    io.on('connection', function (socket) {
        const emitStation = () => {
            fetchStation('18fe34d3f4c9').then((station) => {
                socket.emit('station', station);
                setTimeout(emitStation, 500);
            });
        };

        setTimeout(emitStation, 0);
    });

    server.start((err) => {
        if (err) {
            throw err;
        }

        console.log('Server running at: ', server.info.uri);
    });

    function fetchStation(stationId) {
        const params = {
            TableName : MEASUREMENTS_TABLE,
            ScanIndexForward: false,
            Limit: 1,
            KeyConditionExpression: 'StationId = :requestedStationId',
            ExpressionAttributeValues: {
                ':requestedStationId': { 'S': stationId }
            }
        };

        return new Promise((resolve, reject) => {
            ddb.query(params).promise().then((data) => {
                if (data.Count > 0) {
                    const item = data.Items.shift();
                    const recentDistance = parseFloat(item.Distance.N);

                    const stationStatus = recentDistance > splitDistance ? 'unoccupied' : 'occupied';

                    resolve({
                        statusCode: 200,
                        message: 'Station data sent successfully.',
                        data: {
                            lastMeasureTimestamp: item.Timestamp.N,
                            stationStatus: stationStatus
                        }
                    });
                } else {
                    resolve({
                        statusCode: 404,
                        message: `Station with id ${stationId} not found.`
                    });
                }
            }).catch((error) => {
                console.log(error);

                reject(error);
            });
        });
    }
};
<commit_msg>Fix sloppy merge<commit_after>'use strict';

require('dotenv').config();

const Raven = require('raven');
Raven.config(process.env.SENTRY_DSN).install();

const Hapi = require('hapi');
const Joi = require('joi');
const AWS = require('aws-sdk');
const fs = require('fs');
const socketIo = require('socket.io');

module.exports = (PORT) => {
    const REGION = process.env.REGION;
    const MEASUREMENTS_TABLE = process.env.MEASUREMENTS_TABLE;
    const STATION_IDS_TABLE = process.env.STATION_IDS_TABLE;

    // TODO What future will bring us? Nobody knows, but those values may be fetched from db someday (they say so)
    const measurementInterval = 100;
    const distanceHysteresis = 20;
    const splitDistance = 150;

    console.log('Starting server');
    console.log('Port is', PORT);
    console.log('Region is', REGION);
    console.log('Measurements table is', MEASUREMENTS_TABLE);
    console.log('Allowed station IDs table is', STATION_IDS_TABLE);

    const server = new Hapi.Server({ debug: { request: ['error'] } });
    server.connection({
        port: PORT
    });
    const io = socketIo(server.listener);

    AWS.config.region = REGION;
    const ddb = new AWS.DynamoDB();

    let allowedStationIds = [];
    ddb.scan({
        'TableName': STATION_IDS_TABLE,
        'ReturnConsumedCapacity': 'TOTAL'
    }).promise().then((data) => {
        data.Items.forEach(function (element) {
            const stationId = element.StationId.S;
            console.log('Allowing station ID', stationId);

            allowedStationIds.push(stationId);
        });
    }).catch((error) => {
        console.log('Cannot get allowed station IDs from database, error', error);
        Raven.captureException(error);
    });

    server.route({
        method: 'POST',
        path:'/measurement',
        handler: (request, reply) => {
            console.log('POST /measurement');

            const payloadDecoded = request.payload;
            console.log(payloadDecoded);

            const stationId = payloadDecoded.stationId;

            if (!allowedStationIds.includes(stationId)) {
                return reply({
                    message: 'Station ID not allowed.'
                }).code(400);
            }

            const itemTimestamp = Date.now().toString();
            const item = {
                'Timestamp': { 'N': itemTimestamp },
                'StationId': { 'S': stationId },
                'Distance': { 'N': payloadDecoded.distance.toString() }
            };

            const response = reply(new Promise((resolve, reject) => {
                ddb.putItem({
                    'TableName': MEASUREMENTS_TABLE,
                    'Item': item
                }, (error, data) => {
                    if (error) {
                        console.log('Error saving data in database: ' + error);

                        Raven.captureException(error);

                        reject({
                            message: 'Measurement save failed, error: ' + error
                        });
                    } else {
                        console.log('Data saved in database');

                        response.created(request.path + '/' + itemTimestamp);
                        resolve({
                            message: 'Measurement saved successfully.'
                        });
                    }
                });
            }));

            return response;
        },
        config: {
            validate: {
                payload: {
                    stationId: Joi.string().required(),
                    distance: Joi.number().required()
                }
            }
        }
    });

    server.route({
        method: 'GET',
        path:'/calibration',
        handler: function (request, reply) {
            console.log('GET /calibration');

            return reply({
                message: 'Calibration data sent successfully.',
                data: {
                    measurementInterval: measurementInterval,
                    distanceHysteresis: distanceHysteresis,
                    splitDistance: splitDistance
                }
            });
        }
    });

    server.register(require('inert'), (err) => {
        if (err) {
            console.log(err);
            return;
        }

        server.route({
            method: 'GET',
            path: '/{param*}',
            handler: (request, reply) => {
                console.log('GET /{param*}');

                const requestFile = request.path.split('/').pop();
                const isDirectory = requestFile.length == 0 || !requestFile.includes('.');
                const fullFilesystemPath = 'dist/' + (isDirectory ? 'index.html' : requestFile );

                console.log(`Sending file ${fullFilesystemPath}`);
                return reply.file(fullFilesystemPath);
            }
        });
    });

    io.on('connection', function (socket) {
        const emitStation = () => {
            fetchStation('18fe34d3f4c9').then((station) => {
                socket.emit('station', station);
                setTimeout(emitStation, 500);
            });
        };

        setTimeout(emitStation, 0);
    });

    server.start((err) => {
        if (err) {
            throw err;
        }

        console.log('Server running at: ', server.info.uri);
    });

    function fetchStation(stationId) {
        const params = {
            TableName : MEASUREMENTS_TABLE,
            ScanIndexForward: false,
            Limit: 1,
            KeyConditionExpression: 'StationId = :requestedStationId',
            ExpressionAttributeValues: {
                ':requestedStationId': { 'S': stationId }
            }
        };

        return new Promise((resolve, reject) => {
            ddb.query(params).promise().then((data) => {
                if (data.Count > 0) {
                    const item = data.Items.shift();
                    const recentDistance = parseFloat(item.Distance.N);

                    const stationStatus = recentDistance > splitDistance ? 'unoccupied' : 'occupied';

                    resolve({
                        message: 'Station data sent successfully.',
                        data: {
                            lastMeasureTimestamp: item.Timestamp.N,
                            stationStatus: stationStatus
                        }
                    });
                } else {
                    resolve({
                        message: `Station with id ${stationId} not found.`
                    });
                }
            }).catch((error) => {
                console.log(error);

                reject(error);
            });
        });
    }
};
<|endoftext|>


<commit_before>Router.route('/boot', function() {
    this.response.end(Meteor.call('bootstrap'));
}, {
    where: 'server'
});

Meteor.methods({
    bootstrap: function() {
        if (Meteor.users.find().count()) {
            return 'Application already booted';
        }

        if (!Meteor.settings.admin || !Meteor.settings.admin.emailAddress || !Meteor.settings.admin.username) {
            return 'Please complete the settings.json file';
        }

        var adminEmailAddress = Meteor.settings.admin.emailAddress;
        var username = Meteor.settings.admin.username;

        // Create first user
        var userId = Accounts.createUser({ username: username, email: adminEmailAddress });
        // Set newly created user as admin
        Roles.addUsersToRoles(userId, 'admin');

        // Send enrollment email
        Accounts.sendEnrollmentEmail(userId);

        return "First user successfully created !";
    }
});<commit_msg>Changing bootstrap strategy<commit_after>Router.route('/boot', function() {
    this.response.end(Meteor.call('bootstrap'));
}, {
    where: 'server'
});

Meteor.methods({
    bootstrap: function() {
        if (!Meteor.users.find().count()) {
            return 'No user registered';
        }

        if (Roles.getUsersInRole('admin').count()) {
            return 'An admin user already exists';
        }

        var firstUser = Meteor.users.findOne({}, {
            sort: {
                createdAt: 1
            }
        });

        Roles.addUsersToRoles(firstUser._id, 'admin');

        return "First user set as admin !";
    }
});<|endoftext|>


<commit_before>// db.js

var config = require('./config');
var Sequelize = require('sequelize');

var sequelize = new Sequelize(config.database, config.username, config.password, {
  host: config.host,
  dialect: config.dialect
});

var User = sequelize.import('../models/users');

module.exports.Sequelize = Sequelize;
module.exports.sequelize = sequelize;

module.exports.User = User;
<commit_msg>established relationships between users and events<commit_after>// db.js

var config = require('./config');
var Sequelize = require('sequelize');

var sequelize = new Sequelize(config.database, config.username, config.password, {
  host: config.host,
  dialect: config.dialect
});

var User = sequelize.import('../models/users');
var Event = sequelize.import('../models/events');
var UserEvent = sequelize.import('../models/userEvents');

User.hasMany(Event, { through: UserEvent })
Event.hasMany(User, { through: UserEvent })

module.exports.Sequelize = Sequelize;
module.exports.sequelize = sequelize;

module.exports.User = User;
module.exports.Event = Event;
module.exports.UserEvent = UserEvent;
<|endoftext|>


<commit_before>/**
 * Router for "non-dashboard" pages
 */
import express from 'express'
import React from 'react'
import { Switch, Route, StaticRouter } from 'react-router'
import { renderToString } from 'react-dom/server'

const Index = () => (
Hola
)
const router = express.Router()

router.use((req, res, next) => {
  // Check if the user is logged in...
  const logged = !true

  if (logged) {
    next()
  } else {
    next('router')
  }
})

router.get('*', (req, res) => {
  const context = {}

  const html = renderToString(
    <StaticRouter location={req.url} context={context}>
      <Switch>
        <Route exact path="/" component={Index} />
      </Switch>
    </StaticRouter>
  )

  res.render('dashboard', {
    rootComponent: html,
    initialState: {}
  })
})

export default router
<commit_msg>Fix. Typo in module docs<commit_after>/**
 * Router for "dashboard" pages
 */
import express from 'express'
import React from 'react'
import { Switch, Route, StaticRouter } from 'react-router'
import { renderToString } from 'react-dom/server'

const Index = () => (
Hola
)
const router = express.Router()

router.use((req, res, next) => {
  // Check if the user is logged in...
  const logged = !true

  if (logged) {
    next()
  } else {
    next('router')
  }
})

router.get('*', (req, res) => {
  const context = {}

  const html = renderToString(
    <StaticRouter location={req.url} context={context}>
      <Switch>
        <Route exact path="/" component={Index} />
      </Switch>
    </StaticRouter>
  )

  res.render('dashboard', {
    rootComponent: html,
    initialState: {}
  })
})

export default router
<|endoftext|>


<commit_before>const _ = require('underscore');

const cards = require('./cards');
const DrawCard = require('./drawcard.js');
const PlotCard = require('./plotcard.js');
const AgendaCard = require('./agendacard.js');

class Deck {
    constructor(data) {
        this.data = data;
    }

    prepare(player) {
        var result = {
            drawCards: [],
            plotCards: []
        };

        this.eachRepeatedCard(this.data.drawCards, cardData => {
            var drawCard = this.createCard(DrawCard, player, cardData);
            drawCard.location = 'draw deck';
            result.drawCards.push(drawCard);
        });

        this.eachRepeatedCard(this.data.plotCards, cardData => {
            var plotCard = this.createCard(PlotCard, player, cardData);
            plotCard.location = 'plot deck';
            result.plotCards.push(plotCard);
        });

        if(this.data.faction) {
            result.faction = new DrawCard(player, _.extend({
                code: this.data.faction.value,
                type_code: 'faction',
                faction_code: this.data.faction.value
            }, this.data.faction));
        } else {
            result.faction = new DrawCard(player, { type_code: 'faction' });
        }
        result.faction.moveTo('faction');

        result.allCards = [result.faction].concat(result.drawCards).concat(result.plotCards);

        if(this.data.agenda) {
            result.agenda = this.createCard(AgendaCard, player, this.data.agenda);
            result.agenda.moveTo('agenda');
            result.allCards.push(result.agenda);
        } else {
            result.agenda = undefined;
        }

        return result;
    }

    eachRepeatedCard(cards, func) {
        _.each(cards, cardEntry => {
            for(var i = 0; i < cardEntry.count; i++) {
                func(cardEntry.card);
            }
        });
    }

    createCard(baseClass, player, cardData) {
        var cardClass = cards[cardData.code] || baseClass;
        return new cardClass(player, cardData);
    }
}

module.exports = Deck;
<commit_msg>Filter out invalid cards when building deck. (#568)<commit_after>const _ = require('underscore');

const cards = require('./cards');
const DrawCard = require('./drawcard.js');
const PlotCard = require('./plotcard.js');
const AgendaCard = require('./agendacard.js');

class Deck {
    constructor(data) {
        this.data = data;
    }

    prepare(player) {
        var result = {
            drawCards: [],
            plotCards: []
        };

        this.eachRepeatedCard(this.data.drawCards, cardData => {
            if(['attachment', 'character', 'event', 'location'].includes(cardData.type_code)) {
                var drawCard = this.createCard(DrawCard, player, cardData);
                drawCard.location = 'draw deck';
                result.drawCards.push(drawCard);
            }
        });

        this.eachRepeatedCard(this.data.plotCards, cardData => {
            if(cardData.type_code === 'plot') {
                var plotCard = this.createCard(PlotCard, player, cardData);
                plotCard.location = 'plot deck';
                result.plotCards.push(plotCard);
            }
        });

        if(this.data.faction) {
            result.faction = new DrawCard(player, _.extend({
                code: this.data.faction.value,
                type_code: 'faction',
                faction_code: this.data.faction.value
            }, this.data.faction));
        } else {
            result.faction = new DrawCard(player, { type_code: 'faction' });
        }
        result.faction.moveTo('faction');

        result.allCards = [result.faction].concat(result.drawCards).concat(result.plotCards);

        if(this.data.agenda) {
            result.agenda = this.createCard(AgendaCard, player, this.data.agenda);
            result.agenda.moveTo('agenda');
            result.allCards.push(result.agenda);
        } else {
            result.agenda = undefined;
        }

        return result;
    }

    eachRepeatedCard(cards, func) {
        _.each(cards, cardEntry => {
            for(var i = 0; i < cardEntry.count; i++) {
                func(cardEntry.card);
            }
        });
    }

    createCard(baseClass, player, cardData) {
        var cardClass = cards[cardData.code] || baseClass;
        return new cardClass(player, cardData);
    }
}

module.exports = Deck;
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { polyfill } from 'react-lifecycles-compat';
import { isEqual } from 'lodash';

import { styled } from '@storybook/theming';
import json from 'format-json';

import Textarea from 'react-textarea-autosize';

const StyledTextarea = styled(Textarea)(
  {
    flex: '1 0 0',
    boxSizing: 'border-box',
    margin: '0 0 0 5px',
    verticalAlign: 'top',
    outline: 'none',
    border: '1px solid #c7c7c7',
    borderRadius: 2,
    fontSize: 13,
    padding: '8px 5px 7px 8px',
    color: 'rgb(51, 51, 51)',
    fontFamily: 'Arial, sans-serif',
    minHeight: '32px',
    resize: 'vertical',
  },
  ({ shown }) =>
    shown
      ? {}
      : {
          display: 'none',
        },
  ({ failed }) =>
    failed
      ? {
          border: '1px solid #fadddd',
          backgroundColor: '#fff5f5',
        }
      : {}
);

const Button = styled.button({
  display: 'table-cell',
  textTransform: 'uppercase',
  letterSpacing: '3.5px',
  fontSize: 12,
  fontWeight: 'bolder',
  color: 'rgb(130, 130, 130)',
  border: '1px solid rgb(193, 193, 193)',
  textAlign: 'center',
  borderRadius: 2,
  padding: 5,
  cursor: 'pointer',
  paddingLeft: 8,
  margin: '0 0 0 5px',
  backgroundColor: 'inherit',
  verticalAlign: 'top',
  outline: 0,
});

const Label = styled.label({
  display: 'table-cell',
  boxSizing: 'border-box',
  verticalAlign: 'top',
  paddingRight: 5,
  paddingTop: 7,
  textAlign: 'right',
  width: 100,
  fontWeight: '600',
});

const Wrapper = styled.div({
  display: 'flex',
  padding: 5,
  alignItems: 'flex-start',
  boxSizing: 'border-box',
  width: '100%',
});

function getJSONFromString(str) {
  try {
    return JSON.parse(str);
  } catch (e) {
    return str;
  }
}

class Item extends Component {
  static propTypes = {
    name: PropTypes.string.isRequired,
    title: PropTypes.string.isRequired,
    onEmit: PropTypes.func.isRequired,
    // eslint-disable-next-line react/forbid-prop-types, react/no-unused-prop-types
    payload: PropTypes.any,
  };

  static defaultProps = {
    payload: {},
  };

  state = {
    isTextAreaShowed: false,
  };

  onChange = ({ target: { value } }) => {
    const newState = {
      payloadString: value,
    };

    try {
      newState.payload = JSON.parse(value.trim());
      newState.failed = false;
    } catch (err) {
      newState.failed = true;
    }

    this.setState(newState);
  };

  onEmitClick = () => {
    const { onEmit, name } = this.props;
    const { payload } = this.state;

    onEmit({
      name,
      payload,
    });
  };

  onToggleEditClick = () => {
    this.setState(({ isTextAreaShowed }) => ({
      isTextAreaShowed: !isTextAreaShowed,
    }));
  };

  static getDerivedStateFromProps = ({ payload }, { prevPayload }) => {
    if (!isEqual(payload, prevPayload)) {
      const payloadString = json.plain(payload);
      const refinedPayload = getJSONFromString(payloadString);
      return {
        failed: false,
        payload: refinedPayload,
        payloadString,
        prevPayload: refinedPayload,
      };
    }
    return null;
  };

  render() {
    const { title, name } = this.props;
    const { failed, isTextAreaShowed, payloadString } = this.state;

    return (
      <Wrapper>
        <Label htmlFor={`addon-event-${name}`}>{title}
        <Button onClick={this.onEmitClick} disabled={failed} title="Submit event">

            📢

        </Button>


<commit_before><commit_msg>[FIX] survey: show answers on 'print answers'<commit_after><|endoftext|>


<commit_before>
var fs = require('fs');
var parseXml = require('xml2js').parseString;
var moment = require('moment');
const dateFormat = 'YYYY-MM-DDTHH:mm:ss';
const dateFormatOutput = 'YYYY-MM-DD';

	var parseDirectory = function (destinationFolder) {

	//console.log(facturaArray)
	// body...
	var facturaArray = [];
	var index = 0;

	var files = fs.readdir(destinationFolder,function (err,files){

	index = files.length;
	if (!err)
		files.forEach( (fileName)=>{

			readFile(destinationFolder +'/'+ fileName,addFactura);

		});
	else
		throw err;
	});

	function addFactura(factura)
	{
		facturaArray.push(factura);
		if(facturaArray.length === index) next();

	}

	function next()
	{
		console.log('Termine');

		var filter = filterFacturas(facturaArray);

		var sorted = sortFacturas(filter);

		var lineArray =  [];

		for (var i = sorted.length - 1; i >= 0; i--) {
			lineArray.push(createLineFactura(sorted[i]));
		}

		console.log(lineArray);
	}

}

function readFile(fileName, cb)
{

	fs.readFile(fileName,'utf-8', (err, data) => {
  		if (err) throw err;

  		parseXml(data, (err,result)=>{

  		if (err) throw err;

  			var fac =createFactura(result,fileName);
  			cb(fac);
  			return fac;

  		});

	});
}

function createLineFactura(factura)
{
	var dateOutput = moment(factura.date).format(dateFormatOutput);
	var line = `${factura.tipoDeComprobante},${dateOutput},${factura.rfcEmisor},${factura.rfcReceptor},${factura.subtotal},${factura.total}`;
	return line;
}

function filterFacturas(facturaArray)
{
	var filter = facturaArray.filter((elem,index,self   )=> self.findIndex ((t)=>  {return t.uuid === elem.uuid  }) === index)
	return filter;
}

function sortFacturas(facturaArray)
{
	return facturaArray.sort((a,b)=>{

			if(a.date==b.date) return 0;

			if(a.date>b.date) return 1;

			if(a.date<b.date) return -1	;

		});
}

function createFactura( facturaObject, fileName)
{
	var factura = new Factura();
	try
	{
		factura.fileName = fileName;
		var tipoDeComprobante = facturaObject['cfdi:Comprobante']['$'].tipoDeComprobante;
		var subtotal =  parseFloat(facturaObject['cfdi:Comprobante']['$'].subTotal);
		var total = parseFloat(facturaObject['cfdi:Comprobante']['$'].total);
		var fecha = facturaObject['cfdi:Comprobante']['$'].fecha;
		var rfcEmisor = facturaObject['cfdi:Comprobante']['cfdi:Emisor'][0]['$']['rfc'];
		var rfcReceptor = facturaObject['cfdi:Comprobante']['cfdi:Receptor'][0]['$']['rfc'];
		var UUID = facturaObject['cfdi:Comprobante']['cfdi:Complemento'][0]['tfd:TimbreFiscalDigital'][0]['$']['UUID']

		factura.tipoDeComprobante = tipoDeComprobante;
		factura.fecha = fecha;
		factura.total = total;
		factura.subtotal = subtotal;
		factura.rfcEmisor = rfcEmisor;
		factura.rfcReceptor = rfcReceptor;
		factura.uuid = UUID;
		factura.date = moment(factura.fecha , dateFormat);

	} catch (err)
	{
		factura.err = true;
		factura.errMessage= err;
	}
	finally
	{
		return factura;
	}
}

function Factura()
{
	var
	 err,
	 errMessage,
	 rfcEmisor,
	 rfcReceptor,
	 fileName,
	 fecha,
	 date,
	 isIngreso,
	 uuid,
	 iva,
	 isr,
	 subtotal,
	 tipoDeComprobante,
	 total = undefined;

	 function getYear(){

	 };
}

exports.parseDirectory = parseDirectory;
<commit_msg>Saving<commit_after>
var fs = require('fs');
var parseXml = require('xml2js').parseString;
var moment = require('moment');
const dateFormat = 'YYYY-MM-DDTHH:mm:ss';
const dateFormatOutput = 'YYYY-MM-DD';

	var parseDirectory = function (destinationFolder) {

	//console.log(facturaArray)
	// body...
	var facturaArray = [];
	var index = 0;

	var files = fs.readdir(destinationFolder,function (err,files){

	index = files.length;
	if (!err)
		files.forEach( (fileName)=>{

			readFile(destinationFolder +'/'+ fileName,addFactura);

		});
	else
		throw err;
	});

	function addFactura(factura)
	{
		facturaArray.push(factura);
		if(facturaArray.length === index) next();

	}

	function next()
	{
		console.log('Termine');

		var filter = filterFacturas(facturaArray);

		var sorted = sortFacturas(filter);

		var lineArray =  [];

		for (var i = sorted.length - 1; i >= 0; i--) {
			lineArray.push(createLineFactura(sorted[i]));
		}

		var stream = fs.createWriteStream('output.txt');

		stream.once('open',function(fd)
		{

			for (var i = lineArray.length - 1; i >= 0; i--) {
				stream.write(lineArray[i]+'\n');
			}

			stream.end()

		});

	}

}

function readFile(fileName, cb)
{

	fs.readFile(fileName,'utf-8', (err, data) => {
  		if (err) throw err;

  		parseXml(data, (err,result)=>{

  		if (err){
  		console.log(err);
  		return;
  		}

  			var fac =createFactura(result,fileName);
  			cb(fac);
  			return fac;

  		});

	});
}

function createLineFactura(factura)
{
	var dateOutput = moment(factura.date).format(dateFormatOutput);
	var line = `${factura.tipoDeComprobante},${dateOutput},${factura.rfcEmisor},${factura.rfcReceptor},"${factura.nombreEmisor}","${factura.concepto}",${factura.subtotal},${factura.total}`;
	return line;
}

function filterFacturas(facturaArray)
{
	var filter = facturaArray.filter((elem,index,self   )=> self.findIndex ((t)=>  {return t.uuid === elem.uuid  }) === index)
	return filter;
}

function sortFacturas(facturaArray)
{
	return facturaArray.sort((a,b)=>{

			if(a.date==b.date) return 0;

			if(a.date>b.date) return 1;

			if(a.date<b.date) return -1	;

		});
}

function createFactura( facturaObject, fileName)
{
	var factura = new Factura();
	try
	{
		factura.fileName = fileName;
		var tipoDeComprobante = facturaObject['cfdi:Comprobante']['$'].tipoDeComprobante;
		var subtotal =  parseFloat(facturaObject['cfdi:Comprobante']['$'].subTotal);
		var total = parseFloat(facturaObject['cfdi:Comprobante']['$'].total);
		var fecha = facturaObject['cfdi:Comprobante']['$'].fecha;
		var emisor = facturaObject['cfdi:Comprobante']['cfdi:Emisor'][0]['$']['nombre'];
		var rfcEmisor = facturaObject['cfdi:Comprobante']['cfdi:Emisor'][0]['$']['rfc'];
		var rfcReceptor = facturaObject['cfdi:Comprobante']['cfdi:Receptor'][0]['$']['rfc'];
		var UUID = facturaObject['cfdi:Comprobante']['cfdi:Complemento'][0]['tfd:TimbreFiscalDigital'][0]['$']['UUID']
		var concepto = facturaObject['cfdi:Comprobante']['cfdi:Conceptos'][0]['cfdi:Concepto'][0]['$']['descripcion'];

		factura.tipoDeComprobante = tipoDeComprobante;
		factura.fecha = fecha;
		factura.total = total;
		factura.subtotal = subtotal;
		factura.rfcEmisor = rfcEmisor;
		factura.nombreEmisor = emisor;
		factura.rfcReceptor = rfcReceptor;
		factura.uuid = UUID;
		factura.date = moment(factura.fecha , dateFormat);
		factura.concepto = concepto;

	} catch (err)
	{
		factura.err = true;
		factura.errMessage= err;
	}
	finally
	{
		return factura;
	}
}

function Factura()
{
	var
	 err,
	 errMessage,
	 rfcEmisor,
	 nombreEmisor,
	 rfcReceptor,
	 fileName,
	 fecha,
	 date,
	 isIngreso,
	 uuid,
	 iva,
	 isr,
	 subtotal,
	 tipoDeComprobante,
	 concepto,
	 total = undefined;

	 function getYear(){

	 };
}

exports.parseDirectory = parseDirectory;
<|endoftext|>


<commit_before>import Ember from 'ember';
import layout from '../templates/components/md-btn-dropdown';
import MaterializeButton from './md-btn';

const { run: { scheduleOnce }, computed } = Ember;

export default MaterializeButton.extend({
  layout,
  tagName: 'a',
  classNames: ['dropdown-button'],
  icon: 'mdi-navigation-expand-more',
  iconPosition: 'right',
  attributeBindings: [
    'inDuration', 'outDuration', 'constrainWidth', 'hover', 'gutter', 'belowOrigin'
  ],

  didInsertElement() {
    this._super(...arguments);
    scheduleOnce('afterRender', this, this._setupDropdown);
  },

  _setupDropdown() {
    // needed until the Materialize.dropdown plugin is replaced
    this.$().attr('data-activates', this.get('_dropdownContentId'));

    this.$().dropdown({
      hover: !!this.getWithDefault('hover', false),
      constrainWidth: !!this.getWithDefault('constrainWidth', true),
      inDuration: this.getWithDefault('inDuration', this.get('_mdSettings.dropdownInDuration')),
      outDuration: this.getWithDefault('outDuration', this.get('_mdSettings.dropdownOutDuration')),
      gutter: this.getWithDefault('gutter', 0),
      belowOrigin: !!this.getWithDefault('belowOrigin', false)
    });
  },
  _dropdownContentId: computed(function() {
    return `${this.get('elementId')}-dropdown-content`;
  })
});
<commit_msg>Fixed dropdown constrain_width property<commit_after>import Ember from 'ember';
import layout from '../templates/components/md-btn-dropdown';
import MaterializeButton from './md-btn';

const { run: { scheduleOnce }, computed } = Ember;

export default MaterializeButton.extend({
  layout,
  tagName: 'a',
  classNames: ['dropdown-button'],
  icon: 'mdi-navigation-expand-more',
  iconPosition: 'right',
  attributeBindings: [
    'inDuration', 'outDuration', 'constrainWidth', 'hover', 'gutter', 'belowOrigin'
  ],

  didInsertElement() {
    this._super(...arguments);
    scheduleOnce('afterRender', this, this._setupDropdown);
  },

  _setupDropdown() {
    // needed until the Materialize.dropdown plugin is replaced
    this.$().attr('data-activates', this.get('_dropdownContentId'));

    this.$().dropdown({
      hover: !!this.getWithDefault('hover', false),
      constrain_width: !!this.getWithDefault('constrainWidth', true),
      inDuration: this.getWithDefault('inDuration', this.get('_mdSettings.dropdownInDuration')),
      outDuration: this.getWithDefault('outDuration', this.get('_mdSettings.dropdownOutDuration')),
      gutter: this.getWithDefault('gutter', 0),
      belowOrigin: !!this.getWithDefault('belowOrigin', false)
    });
  },
  _dropdownContentId: computed(function() {
    return `${this.get('elementId')}-dropdown-content`;
  })
});
<|endoftext|>


<commit_before>import stringify from 'csv-stringify'
import { groupFilter } from '../graphql/filters'

// Toplevel API entrypoint to check auth & route to desired exporter flow based on parameters
module.exports = {
  groupData: async function (req, res) {
    const p = req.allParams()

    if (!p.groupId) {
      throw new Error("Please specify group ID")
    }
    if (!p.datasets || !p.datasets.length) {
      throw new Error("Please specify datasets to export")
    }

    // auth check
    let ok = false
    try {
      ok = GroupMembership.hasModeratorRole(req.session.userId, p.groupId)
    } catch (err) {
      return res.status(422).send({ error: err.message ? err.message : err })
    }

    if (!ok) {
      return res.status(403).send({ error: "No access" })
    }

    // process specified datasets
    if (p.datasets.includes('members')) {
      return exportMembers(p.groupId, req, res)
    }

    // got to the end and nothing output/exited, throw error
    throw new Error("Unknown datasets specified: " + JSON.stringify(p.datasets))
  }
}

/**
 * Group members export by Group ID
 */
async function exportMembers(groupId, req, res) {
  const users = await new Group({ id: groupId })
                  .members()
                  .fetch()

  const results = []

  // iterate over all group members
  await Promise.all(users.map((u, idx) => {
    // pluck core user data into results
    results.push(u.pick([
      'name', 'contact_email', 'contact_phone', 'avatar_url', 'tagline', 'bio',
      'url', 'twitter_url', 'facebook_url', 'linkedin_url'
    ]))

    // return combined promise to load all dependent user data and
    // assign final child query results back onto matching result objects upon completion
    return Promise.all([

      // location (full details)
      u.locationObject().fetch()
        .then(location => {
          results[idx]['location'] = renderLocation(location)
        }),

      // affiliations
      u.affiliations().fetch()
        .then(affils => {
          results[idx]['affiliations'] = accumulatePivotCell(affils, renderAffiliation)
        }),

      // skills
      u.skills().fetch()
        .then(skills => {
          results[idx]['skills'] = accumulatePivotCell(skills, renderSkill)
        }),

      // skills to learn
      u.skillsToLearn().fetch()
        .then(skills => {
          results[idx]['skills_to_learn'] = accumulatePivotCell(skills, renderSkill)
        }),

      // Join request questions & answers
      u.joinRequests()
        .where({ group_id: groupId, status: JoinRequest.STATUS.Accepted })
        .orderBy('created_at', 'DESC')
        .fetchOne()
        .then(jr => {
          if (!jr) {
            return null
          }
          return jr.questionAnswers().fetch()
            .then(qas => Promise.all(qas.map(qa =>
              Promise.all([
                qa.question().fetch(),
                Promise.resolve(qa)
              ])
            )))
        })
        .then(data => {
          if (!data) return
          results[idx]['join_request_questions'] = accumulatePivotCell(data, renderJoinRequestAnswer)
        }),

      // other groups the requesting member has acccess to
      groupFilter(req.session.userId)(u.groups()).fetch()
        .then(groups => {
          results[idx]['groups'] = accumulatePivotCell(groups, renderGroup)
        }),

    ])
  }))

  // send data as CSV response
  output(res, results, [
    'name', 'contact_email', 'contact_phone', 'location', 'avatar_url', 'tagline', 'bio',
    { key: 'url', header: 'personal_url' },
    'twitter_url', 'facebook_url', 'linkedin_url',
    'skills', 'skills_to_learn',
    'join_request_questions',
    'affiliations',
    'groups'
  ])
}

// toplevel output function for specific endpoints to complete with
function output(res, data, columns) {
  res.setHeader('Content-Type', 'text/csv')
  res.setHeader('Content-Disposition', 'attachment; filename=\"' + 'download-' + Date.now() + '.csv\"')

  stringify(data, {
    header: true,
    columns
  })
    .pipe(res)
}

// reduce helper to format lists of records into single CSV cells
function accumulatePivotCell(records, renderValue) {
  return records.reduce((joined, a) => joined ? (joined + `,${renderValue(a)}`) : renderValue(a), null)
}

// formatting for individual sub-cell record types

function renderLocation(l) {
  if (l === null) {
    return ''
  }
  const geometry = l.get('center')  // :TODO: make this work for polygonal locations, if needed
  const lat = geometry.lat
  const lng = geometry.lng
  return `${l.get('full_text')}${lat && lng ? ` (${lat.toFixed(3)},${lng.toFixed(3)})` : ''}`
}

function renderAffiliation(a) {
  return `${a.get('role')} ${a.get('preposition')} ${a.get('org_name')} ${a.get('url') ? `(${a.get('url')})` : ''}`
}

function renderSkill(s) {
  return s.get('name')
}

function renderJoinRequestAnswer(s) {
  return `${s[0].get('text')} ${s[1].get('answer')}`
}

function renderGroup(g) {
  return `${g.get('name')} (${Frontend.Route.group(g)})`
}
<commit_msg>Separate join questions from answers by a colon<commit_after>import stringify from 'csv-stringify'
import { groupFilter } from '../graphql/filters'

// Toplevel API entrypoint to check auth & route to desired exporter flow based on parameters
module.exports = {
  groupData: async function (req, res) {
    const p = req.allParams()

    if (!p.groupId) {
      throw new Error("Please specify group ID")
    }
    if (!p.datasets || !p.datasets.length) {
      throw new Error("Please specify datasets to export")
    }

    // auth check
    let ok = false
    try {
      ok = GroupMembership.hasModeratorRole(req.session.userId, p.groupId)
    } catch (err) {
      return res.status(422).send({ error: err.message ? err.message : err })
    }

    if (!ok) {
      return res.status(403).send({ error: "No access" })
    }

    // process specified datasets
    if (p.datasets.includes('members')) {
      return exportMembers(p.groupId, req, res)
    }

    // got to the end and nothing output/exited, throw error
    throw new Error("Unknown datasets specified: " + JSON.stringify(p.datasets))
  }
}

/**
 * Group members export by Group ID
 */
async function exportMembers(groupId, req, res) {
  const users = await new Group({ id: groupId })
                  .members()
                  .fetch()

  const results = []

  // iterate over all group members
  await Promise.all(users.map((u, idx) => {
    // pluck core user data into results
    results.push(u.pick([
      'name', 'contact_email', 'contact_phone', 'avatar_url', 'tagline', 'bio',
      'url', 'twitter_url', 'facebook_url', 'linkedin_url'
    ]))

    // return combined promise to load all dependent user data and
    // assign final child query results back onto matching result objects upon completion
    return Promise.all([

      // location (full details)
      u.locationObject().fetch()
        .then(location => {
          results[idx]['location'] = renderLocation(location)
        }),

      // affiliations
      u.affiliations().fetch()
        .then(affils => {
          results[idx]['affiliations'] = accumulatePivotCell(affils, renderAffiliation)
        }),

      // skills
      u.skills().fetch()
        .then(skills => {
          results[idx]['skills'] = accumulatePivotCell(skills, renderSkill)
        }),

      // skills to learn
      u.skillsToLearn().fetch()
        .then(skills => {
          results[idx]['skills_to_learn'] = accumulatePivotCell(skills, renderSkill)
        }),

      // Join request questions & answers
      u.joinRequests()
        .where({ group_id: groupId, status: JoinRequest.STATUS.Accepted })
        .orderBy('created_at', 'DESC')
        .fetchOne()
        .then(jr => {
          if (!jr) {
            return null
          }
          return jr.questionAnswers().fetch()
            .then(qas => Promise.all(qas.map(qa =>
              Promise.all([
                qa.question().fetch(),
                Promise.resolve(qa)
              ])
            )))
        })
        .then(data => {
          if (!data) return
          results[idx]['join_request_questions'] = accumulatePivotCell(data, renderJoinRequestAnswer)
        }),

      // other groups the requesting member has acccess to
      groupFilter(req.session.userId)(u.groups()).fetch()
        .then(groups => {
          results[idx]['groups'] = accumulatePivotCell(groups, renderGroup)
        }),

    ])
  }))

  // send data as CSV response
  output(res, results, [
    'name', 'contact_email', 'contact_phone', 'location', 'avatar_url', 'tagline', 'bio',
    { key: 'url', header: 'personal_url' },
    'twitter_url', 'facebook_url', 'linkedin_url',
    'skills', 'skills_to_learn',
    'join_request_questions',
    'affiliations',
    'groups'
  ])
}

// toplevel output function for specific endpoints to complete with
function output(res, data, columns) {
  res.setHeader('Content-Type', 'text/csv')
  res.setHeader('Content-Disposition', 'attachment; filename=\"' + 'download-' + Date.now() + '.csv\"')

  stringify(data, {
    header: true,
    columns
  })
    .pipe(res)
}

// reduce helper to format lists of records into single CSV cells
function accumulatePivotCell(records, renderValue) {
  return records.reduce((joined, a) => joined ? (joined + `,${renderValue(a)}`) : renderValue(a), null)
}

// formatting for individual sub-cell record types

function renderLocation(l) {
  if (l === null) {
    return ''
  }
  const geometry = l.get('center')  // :TODO: make this work for polygonal locations, if needed
  const lat = geometry.lat
  const lng = geometry.lng
  return `${l.get('full_text')}${lat && lng ? ` (${lat.toFixed(3)},${lng.toFixed(3)})` : ''}`
}

function renderAffiliation(a) {
  return `${a.get('role')} ${a.get('preposition')} ${a.get('org_name')} ${a.get('url') ? `(${a.get('url')})` : ''}`
}

function renderSkill(s) {
  return s.get('name')
}

function renderJoinRequestAnswer(s) {
  return `${s[0].get('text')}: ${s[1].get('answer')}`
}

function renderGroup(g) {
  return `${g.get('name')} (${Frontend.Route.group(g)})`
}
<|endoftext|>