<commit_before>;(function ($, document, window) {
    'use strict';

    /**
     * Chart initializer.
     */
    function Chartjs(chart)
    {
        this.id = chart.id;
        this.type = chart.chart;
        this.options = chart.options;
        this.ajax = chart.ajax;

        this.init();

        return this;
    }

    Chartjs.prototype = {

        /**
         * Initialize method.
         *
         * @return {undefined}
         */
        init: function () {
            if (!$.isEmptyObject(this.options.dataChart)) {
                this.options.dataChart = this.escapeData(this.options.dataChart);
                this.draw();
            } else {
                this.getData();
            }
        },

        escapeData: function (data) {
            var that = this;

            let label = '';
            switch (this.type) {
                case 'bar':
                case 'pie':
                    data.data.labels.forEach(function (label, key) {
                        data.data.labels[key] = this.escapeValue(label)
                    });
                    break;
                case 'funnelChart':
                    data.data.forEach(function (item, key) {
                        data.data[key].label = this.escapeValue(item.label)
                    });
                    break;
            }

            return data;
        },

        escapeValue: function (value) {
            new DOMParser().parseFromString(value, 'text/html');

            // strip html tags
            let result = doc.body.textContent || '';

            // strip   html entities
            result = result.replace(/\u00a0/g, '');

            return result ? result : 'N/A';
        },

        /**
         * Draw method.
         *
         * @return {undefined}
         */
        draw: function () {
            switch (this.type) {
                case 'bar':
                case 'doughnut':
                case 'line':
                case 'polarArea':
                case 'pie':
                case 'horizontalBar':
                    var ctx = document.getElementById("canvas_" + this.id).getContext('2d');
                    var myChart = new Chart(ctx, this.options.dataChart);
                    break;
                case 'knobChart':
                    $('.knob-graph').knob({
                        'width': 85,
                        'height': 85,
                        'linecap': 'round',
                        'thickness': '.2',
                        'readOnly': true,
                        'cursor': false,
                        'draw': function () {
                            var colorGradients = [
                                '#05497d', '#043b64', '#032c4c', //blue
                                '#1e3302', '#2c4c03', '#3b6404', '#497d05', '#579606', '#66ae07', '#74c708', //green
                                '#a7a60e', '#bfbd0f', '#d6d411', //yellow
                                '#a70e0f', '#bf0f11', '#d61113', '#ec1517', //red
                            ];
                            var randomColor = Math.floor(Math.random() * colorGradients.length);
                            this.o.fgColor = colorGradients[randomColor];
                        }
                    });
                    break;
                case 'funnelChart':
                    this.options.dataChart.data.sort(function (a, b) {
                        return (a.value < b.value) ? 1 : ((b.value < a.value) ? -1 : 0);
                    });

                    var d3chart = new D3Funnel('#' + this.id);
                    d3chart.draw(this.options.dataChart.data, {
                        block: {
                            dynamicHeight: true
                        }
                    });
                    break;
            }
        },

        getData: function () {
            var that = this;

            if (!this.ajax) {
                console.log('No ajax information, cannot fetch chart data.');

                return;
            }

            var placeholder = this.getPlaceholder();
            // add loading placeholder
            $('#' + this.id).append(placeholder.element);

            $.ajax({
                url: this.ajax.url,
                method: 'GET',
                headers: {
                    Accept: 'application/json',
                    'Content-Type': 'application/json',
                    Authorization: 'Bearer ' + this.ajax.token
                },
                success: function (data, textStatus, jqXHR) {
                    // remove placeholder
                    $('#' + placeholder.id).remove();
                    that.options.dataChart = that.normalizeData(data.data);
                    that.draw();
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    console.log(jqXHR);
                    console.log(textStatus);
                    console.log(errorThrown);
                }
            });
        },

        normalizeData: function (data) {
            var that = this;
            let parseData = [];
            let parseLabel = [];
            let label;
            let num;

            switch (this.type) {
                case 'funnelChart':
                    data.forEach(function (v, k) {
                        var label = data[k][that.options.xkey[0]];
                        var value = data[k][that.options.ykeys[0]];
                        data[k].label = $('
').html(label).text();
                        data[k].value = parseInt(value);
                    });
                    break;
                case 'doughnut':
                    label = that.options.xkey[0];
                    num = that.options.ykeys[0];
                    data.forEach(function (v, k) {
                        parseLabel.push($('
').html(data[k][label]).text());
                        parseData.push($('
').html(data[k][num]).text());
                    });
                    data = {
                        type: "pie",
                        data: {
                            datasets: [{
                                data: parseData,
                                backgroundColor: this.getColor(parseData.length)
                            }],
                            labels: parseLabel
                        }
                    };

                    break;
                case 'bar':
                    label = that.options.xkey[0];
                    num = that.options.ykeys[0];
                    data.forEach(function (v, k) {
                        parseLabel.push($('
').html(data[k][label]).text());
                        parseData.push($('
').html(data[k][num]).text());
                    });
                    data = {
                        type: "bar",
                        data: {
                            datasets: [{
                                data: parseData,
                                backgroundColor: this.getColor(parseData.length)
                            }],
                            labels: parseLabel
                        },
                        options: {
                            legend: {
                                display: false
                            },
                            scales: {
                                yAxes: [{
                                    ticks: {
                                        beginAtZero: true
                                    }
                                }]
                            }
                        }
                    };

                    break;
            }

            return data;
        },

        getColor : function (count) {
            var result = [];
            var colorGradients = ["#ff9a00","#ff165d","#f6f7d7","#3ec1d3","#521262","#6639a6","#3490de","#6fe7dd","#a4f6a5","#f1eb9a","#f8a978","#f68787","#e88a1a","#35477d","#a06ee1","#fcd307","#007880","#c7004c","#e3c4a8","#77628c","#5893d4","#30e3ca","#f8f3d4","#ffcfdf","#3f72af","#f73859","#61c0bf","#6639a6","#00e0ff","#d4a5a5","#dde7f2","#55e9bc","#d72323","#ff9a00"];
            // Quick hash function to get a unique number from a string
            let unique = Math.abs(this.id.split("").reduce(function (a, b) {
                a = ((a << 5) - a) + b.charCodeAt(0);

                return a & a
            }, 0)) % colorGradients.length;

            for (let i = 0; i < count; i++) {
                result.push(colorGradients[(unique + i) % colorGradients.length ])
            }

            return result;
        },

        getPlaceholder: function () {
            var result = {};

            // random id
            result.id = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
            result.element = $('
', {id: result.id, style: 'height:350px;padding-top:160px;'});
            result.element.html(
                '
 Processing...
'
            );

            return result;
        }
    };

    if (!window.chartsData) {
        console.log('No charts to initialize');

        return;
    }

    var charts = [];
    window.chartsData.forEach(function (data) {
        var id = data.id;
        var isVisible = (!$('a[href="#' + id + '"]').data('toggle') || $('#' + id).hasClass('active'));
        if (isVisible) {
            new Chartjs(data);
            charts.push('#' + data.options.id);
        }
    });

    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
        var chartId = $(e.target).attr('href');

        // chart already initialized
        if (-1 !== charts.indexOf(chartId)) {
            return;
        }

        // get chart data
        var data = $.grep(window.chartsData, function (v) {
            return '#' + v.id === chartId;
        });

        if (!data.length) {
            return;
        }

        data = data[0];
        // init chart
        new Chartjs(data);
        charts.push('#' + data.id);
    });

})(jQuery, document, window);
<commit_msg>Cleaner var naming (task #8668)<commit_after>;(function ($, document, window) {
    'use strict';

    /**
     * Chart initializer.
     */
    function Chartjs(chart)
    {
        this.id = chart.id;
        this.type = chart.chart;
        this.options = chart.options;
        this.ajax = chart.ajax;

        this.init();

        return this;
    }

    Chartjs.prototype = {

        /**
         * Initialize method.
         *
         * @return {undefined}
         */
        init: function () {
            if (!$.isEmptyObject(this.options.dataChart)) {
                this.options.dataChart = this.escapeData(this.options.dataChart);
                this.draw();
            } else {
                this.getData();
            }
        },

        escapeData: function (dataChart) {
            var that = this;

            let label = '';
            switch (this.type) {
                case 'bar':
                case 'pie':
                    dataChart.data.labels.forEach(function (label, key) {
                        dataChart.data.labels[key] = that.escapeValue(label)
                    });
                    break;
                case 'funnelChart':
                    dataChart.data.forEach(function (item, key) {
                        dataChart.data[key].label = that.escapeValue(item.label)
                    });
                    break;
            }

            return dataChart;
        },

        escapeValue: function (value) {
            const doc = new DOMParser().parseFromString(value, 'text/html');

            // strip html tags
            let result = doc.body.textContent || '';

            // strip   html entities
            result = result.replace(/\u00a0/g, '');

            return result ? result : 'N/A';
        },

        /**
         * Draw method.
         *
         * @return {undefined}
         */
        draw: function () {
            switch (this.type) {
                case 'bar':
                case 'doughnut':
                case 'line':
                case 'polarArea':
                case 'pie':
                case 'horizontalBar':
                    var ctx = document.getElementById("canvas_" + this.id).getContext('2d');
                    var myChart = new Chart(ctx, this.options.dataChart);
                    break;
                case 'knobChart':
                    $('.knob-graph').knob({
                        'width': 85,
                        'height': 85,
                        'linecap': 'round',
                        'thickness': '.2',
                        'readOnly': true,
                        'cursor': false,
                        'draw': function () {
                            var colorGradients = [
                                '#05497d', '#043b64', '#032c4c', //blue
                                '#1e3302', '#2c4c03', '#3b6404', '#497d05', '#579606', '#66ae07', '#74c708', //green
                                '#a7a60e', '#bfbd0f', '#d6d411', //yellow
                                '#a70e0f', '#bf0f11', '#d61113', '#ec1517', //red
                            ];
                            var randomColor = Math.floor(Math.random() * colorGradients.length);
                            this.o.fgColor = colorGradients[randomColor];
                        }
                    });
                    break;
                case 'funnelChart':
                    this.options.dataChart.data.sort(function (a, b) {
                        return (a.value < b.value) ? 1 : ((b.value < a.value) ? -1 : 0);
                    });

                    var d3chart = new D3Funnel('#' + this.id);
                    d3chart.draw(this.options.dataChart.data, {
                        block: {
                            dynamicHeight: true
                        }
                    });
                    break;
            }
        },

        getData: function () {
            var that = this;

            if (!this.ajax) {
                console.log('No ajax information, cannot fetch chart data.');

                return;
            }

            var placeholder = this.getPlaceholder();
            // add loading placeholder
            $('#' + this.id).append(placeholder.element);

            $.ajax({
                url: this.ajax.url,
                method: 'GET',
                headers: {
                    Accept: 'application/json',
                    'Content-Type': 'application/json',
                    Authorization: 'Bearer ' + this.ajax.token
                },
                success: function (data, textStatus, jqXHR) {
                    // remove placeholder
                    $('#' + placeholder.id).remove();
                    that.options.dataChart = that.normalizeData(data.data);
                    that.draw();
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    console.log(jqXHR);
                    console.log(textStatus);
                    console.log(errorThrown);
                }
            });
        },

        normalizeData: function (data) {
            var that = this;
            let parseData = [];
            let parseLabel = [];
            let label;
            let num;

            switch (this.type) {
                case 'funnelChart':
                    data.forEach(function (v, k) {
                        var label = data[k][that.options.xkey[0]];
                        var value = data[k][that.options.ykeys[0]];
                        data[k].label = $('
').html(label).text();
                        data[k].value = parseInt(value);
                    });
                    break;
                case 'doughnut':
                    label = that.options.xkey[0];
                    num = that.options.ykeys[0];
                    data.forEach(function (v, k) {
                        parseLabel.push($('
').html(data[k][label]).text());
                        parseData.push($('
').html(data[k][num]).text());
                    });
                    data = {
                        type: "pie",
                        data: {
                            datasets: [{
                                data: parseData,
                                backgroundColor: this.getColor(parseData.length)
                            }],
                            labels: parseLabel
                        }
                    };

                    break;
                case 'bar':
                    label = that.options.xkey[0];
                    num = that.options.ykeys[0];
                    data.forEach(function (v, k) {
                        parseLabel.push($('
').html(data[k][label]).text());
                        parseData.push($('
').html(data[k][num]).text());
                    });
                    data = {
                        type: "bar",
                        data: {
                            datasets: [{
                                data: parseData,
                                backgroundColor: this.getColor(parseData.length)
                            }],
                            labels: parseLabel
                        },
                        options: {
                            legend: {
                                display: false
                            },
                            scales: {
                                yAxes: [{
                                    ticks: {
                                        beginAtZero: true
                                    }
                                }]
                            }
                        }
                    };

                    break;
            }

            return data;
        },

        getColor : function (count) {
            var result = [];
            var colorGradients = ["#ff9a00","#ff165d","#f6f7d7","#3ec1d3","#521262","#6639a6","#3490de","#6fe7dd","#a4f6a5","#f1eb9a","#f8a978","#f68787","#e88a1a","#35477d","#a06ee1","#fcd307","#007880","#c7004c","#e3c4a8","#77628c","#5893d4","#30e3ca","#f8f3d4","#ffcfdf","#3f72af","#f73859","#61c0bf","#6639a6","#00e0ff","#d4a5a5","#dde7f2","#55e9bc","#d72323","#ff9a00"];
            // Quick hash function to get a unique number from a string
            let unique = Math.abs(this.id.split("").reduce(function (a, b) {
                a = ((a << 5) - a) + b.charCodeAt(0);

                return a & a
            }, 0)) % colorGradients.length;

            for (let i = 0; i < count; i++) {
                result.push(colorGradients[(unique + i) % colorGradients.length ])
            }

            return result;
        },

        getPlaceholder: function () {
            var result = {};

            // random id
            result.id = Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
            result.element = $('
', {id: result.id, style: 'height:350px;padding-top:160px;'});
            result.element.html(
                '
 Processing...
'
            );

            return result;
        }
    };

    if (!window.chartsData) {
        console.log('No charts to initialize');

        return;
    }

    var charts = [];
    window.chartsData.forEach(function (data) {
        var id = data.id;
        var isVisible = (!$('a[href="#' + id + '"]').data('toggle') || $('#' + id).hasClass('active'));
        if (isVisible) {
            new Chartjs(data);
            charts.push('#' + data.options.id);
        }
    });

    $('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
        var chartId = $(e.target).attr('href');

        // chart already initialized
        if (-1 !== charts.indexOf(chartId)) {
            return;
        }

        // get chart data
        var data = $.grep(window.chartsData, function (v) {
            return '#' + v.id === chartId;
        });

        if (!data.length) {
            return;
        }

        data = data[0];
        // init chart
        new Chartjs(data);
        charts.push('#' + data.id);
    });

})(jQuery, document, window);
<|endoftext|>


<commit_before>function PropertyIssuanceController($scope, $http,$modal, userService, walletTradeService){
  $scope.showErrors=false;
  $scope.propertyTypes = [
    { value: 1, description: "New Indivisible tokens"},
    { value: 2, description: "New Divisible currency"},
    { value: 65,  description: "Indivisible tokens replacing a previous property"},
    { value: 66,  description: "Divisible currency replacing a previous property"},
    { value: 129,  description: "Indivisible tokens appending a previous property"},
    { value: 130, description:  "Divisible currency appending a previous property"}
  ];
  $scope.isNewProperty = true;

  $scope.checkPropertyType = function(){
    if ($scope.propertyType != 1 && $scope.propertyType != 2)
      $scope.isNewProperty = false;
    else
      $scope.isNewProperty = true;
  };

  function getUnsignedPropertyIssuanceTransaction(propertyType, previousPropertyId, propertyCategory, propertySubcategory, propertyName, propertyUrl, propertyData, numberProperties) {
    var data = {
      propertyType : propertyType,
      previousPropertyId:previousPropertyId,
      propertyCategory:propertyCategory,
      propertySubcategory:propertySubcategory,
      propertyName:propertyName,
      propertyUrl:propertyUrl,
      propertyData:propertyData,
      numberProperties:numberProperties
    };
    var promise = walletTradeService.getUnsignedTransaction(50,data);

    return promise;
  }

  function preparePropertyIssuanceTransaction(propertyType, previousPropertyId, propertyCategory, propertySubcategory, propertyName, propertyUrl, propertyData, numberProperties, from, $modalScope) {
    var addressData = userService.getAddress(from);
    var privKey = new Bitcoin.ECKey.decodeEncryptedFormat(addressData.privkey, addressData.address); // Using address as temporary password
    var pubKey = privKey.getPubKeyHex();

    $scope.propertyIssuanceTxPromise = getUnsignedPropertyIssuanceTransaction(propertyType, previousPropertyId, propertyCategory, propertySubcategory, propertyName, propertyUrl, propertyData, numberProperties, from, $modalScope);
    $scope.propertyIssuanceTxPromise.then(function(successData) {

      if (successData.status != 200) {
        $modalScope.waiting = false;
        $modalScope.issueError = true;
        $modalScope.error = 'Error preparing Property Issuance transaction: ' + successData.data;
      } else {
        var unsignedTransaction = successData.unsignedhex;

        try {
          var bytes = Bitcoin.Util.hexToBytes(unsignedTransaction);
          var transaction = Bitcoin.Transaction.deserialize(bytes);
          /*var script = parseScript(successData.sourceScript);

          transaction.ins.forEach(function(input) {
            input.script = script;
          });*/

          //DEBUG console.log('before',transaction, Bitcoin.Util.bytesToHex(transaction.serialize()));
          var signedSuccess = transaction.signWithKey(privKey);

          var finalTransaction = Bitcoin.Util.bytesToHex(transaction.serialize());

          //Showing the user the transaction hash doesn't work right now
          //var transactionHash = Bitcoin.Util.bytesToHex(transaction.getHash().reverse());

          walletTradeService.pushSignedTransaction(finalTransaction).then(function(successData) {
            var successData = successData.data;
            if (successData.pushed.match(/submitted|success/gi) != null) {
              $modalScope.waiting = false;
              $modalScope.issueSuccess = true;
              $modalScope.url = 'http://blockchain.info/address/' + from + '?sort=0';
            } else {
              $modalScope.waiting = false;
              $modalScope.issueError = true;
              $modalScope.error = successData.pushed; //Unspecified error, show user
            }
          }, function(errorData) {
            $modalScope.waiting = false;
            $modalScope.issueError = true;
            if (errorData.message)
              $modalScope.error = 'Server error: ' + errorData.message;
            else
              if (errorData.data)
                $modalScope.error = 'Server error: ' + errorData.data;
              else
                $modalScope.error = 'Unknown Server Error';
            console.error(errorData);
          });

          //DEBUG console.log(addressData, privKey, bytes, transaction, script, signedSuccess, finalTransaction );
          function parseScript(script) {
            var newScript = new Bitcoin.Script();
            var s = script.split(" ");
            for (var i = 0; i < s.length; i++) {
              if (Bitcoin.Opcode.map.hasOwnProperty(s[i])) {
                newScript.writeOp(Bitcoin.Opcode.map[s[i]]);
              } else {
                newScript.writeBytes(Bitcoin.Util.hexToBytes(s[i]));
              }
            }
            return newScript;
          }
        } catch (e) {
          $modalScope.sendError = true;
          if (e.message)
            $modalScope.error = 'Error sending transaction: ' + e.message;
          else
            if (e.data)
              $modalScope.error = 'Error sending transaction: ' + e.data;
            else
              $modalScope.error = 'Unknown error sending transaction';
          console.error(e);
        }
      }
    }, function(errorData) {
      $modalScope.sendError = true;
      if (errorData.message)
        $modalScope.error = 'Server error: ' + errorData.message;
      else
        if (errorData.data)
          $modalScope.error = 'Server error: ' + errorData.data;
        else
          $modalScope.error = 'Unknown Server Error';
      console.error(errorData);
    });
  }

  $scope.validatePropertyIssuanceForm = function() {
    var dustValue = 5430;
    var minerMinimum = 10000;
    var nonZeroValue = 1;

    var convertToSatoshi = [
      $scope.minerFees,
      $scope.balanceData[1]
    ];

    var convertedValues =$scope.convertDisplayedValue(convertToSatoshi);
    var minerFees = +convertedValues[0];
    var btcbalance = convertedValues[1];
    var numberProperties=$scope.numberProperties,
    propertyType = $scope.propertyType,
    previousPropertyId=$scope.previousPropertyId,
    propertyName=$scope.propertyName,
    propertyCategory=$scope.propertyCategory,
    propertySubcategory=$scope.propertySubcategory,
    propertyUrl=$scope.propertyUrl;

    var error = 'Please ';
    if ($scope.issuanceForm.$valid == false) {
      error += 'make sure all fields are completely filled, ';
    }
    if (minerFees < minerMinimum)
      error += 'make sure your fee entry is at least 0.0001 BTC to cover miner costs, ';
    if ((minerFees <= btcbalance) == false)
        error += 'make sure you have enough Bitcoin to cover your fees, ';
    if (!propertyName || propertyName == '\0')
      error += 'make sure you enter a Property Name, ';

    if (error.length < 8) {
      $scope.$parent.showErrors = false;
      // open modal
      var modalInstance = $modal.open({
        templateUrl: '/partials/explorer_asset_issuance_modal.html',
        controller: function($scope, $rootScope, userService, data, preparePropertyIssuanceTransaction, getUnsignedPropertyIssuanceTransaction, convertSatoshiToDisplayedValue, getDisplayedAbbreviation) {
          $scope.issueSuccess = false, $scope.issueError = false, $scope.waiting = false, $scope.privKeyPass = {};
          $scope.convertSatoshiToDisplayedValue=  convertSatoshiToDisplayedValue,
          $scope.getDisplayedAbbreviation=  getDisplayedAbbreviation,
          $scope.numberProperties=  data.numberProperties,
          $scope.propertyTypeName=  data.propertyTypeName,
          $scope.propertyName= data.propertyName,
          $scope.propertyCategory= data.propertyCategory,
          $scope.propertySubcategory= data.propertySubcategory,
          $scope.propertyUrl= data.propertyUrl;

          $scope.ok = function() {
            $scope.clicked = true;
            $scope.waiting = true;
            preparePropertyIssuanceTransaction(data.propertyType, data.previousPropertyId, data.propertyCategory, data.propertySubcategory, data.propertyName, data.propertyUrl, data.propertyData, data.numberProperties, from, $scope);
          };
        },
        resolve: {
          data: function() {
            return {
              numberProperties:numberProperties,
              propertyType:propertyType,
              propertyTypeName:propertyType == 1 || propertyType == 65 || propertyType == 129? 'Indivisible' : 'Divisible', // Only values 1 or 2 are supported right now, but leave room for expansion.
              previousPropertyId:previousPropertyId,
              propertyName:propertyName,
              propertyCategory:propertyCategory,
              propertySubcategory:propertySubcategory,
              propertyUrl:propertyUrl,
              propertyData:'\0' // this is fixed to 1 byte by the spec
            };
          },
          preparePropertyIssuanceTransaction: function() {
            return preparePropertyIssuanceTransaction;
          },
          getUnsignedPropertyIssuanceTransaction: function() {
            return getUnsignedPropertyIssuanceTransaction;
          },
          pushSignedTransaction: function() {
            return walletTradeService.pushSignedTransaction;
          },
          convertSatoshiToDisplayedValue: function() {
            return $scope.convertSatoshiToDisplayedValue;
          },
          getDisplayedAbbreviation: function() {
            return $scope.getDisplayedAbbreviation;
          }
        }
      });
    } else {
      error += 'and try again.';
      $scope.error = error;
      $scope.$parent.showErrors = true;
    }
  };
}
<commit_msg>Minor fixes for proper display<commit_after>function PropertyIssuanceController($scope, $http,$modal, userService, walletTradeService){

  $scope.propertyTypes = [
    { value: 1, description: "New Indivisible tokens"},
    { value: 2, description: "New Divisible currency"},
    { value: 65,  description: "Indivisible tokens replacing a previous property"},
    { value: 66,  description: "Divisible currency replacing a previous property"},
    { value: 129,  description: "Indivisible tokens appending a previous property"},
    { value: 130, description:  "Divisible currency appending a previous property"}
  ];
  $scope.isNewProperty = true;

  $scope.checkPropertyType = function(){
    if ($scope.propertyType != 1 && $scope.propertyType != 2)
      $scope.isNewProperty = false;
    else
      $scope.isNewProperty = true;
  };

  function getUnsignedPropertyIssuanceTransaction(propertyType, previousPropertyId, propertyCategory, propertySubcategory, propertyName, propertyUrl, propertyData, numberProperties) {
    var data = {
      propertyType : propertyType,
      previousPropertyId:previousPropertyId,
      propertyCategory:propertyCategory,
      propertySubcategory:propertySubcategory,
      propertyName:propertyName,
      propertyUrl:propertyUrl,
      propertyData:propertyData,
      numberProperties:numberProperties
    };
    var promise = walletTradeService.getUnsignedTransaction(50,data);

    return promise;
  }

  function preparePropertyIssuanceTransaction(propertyType, previousPropertyId, propertyCategory, propertySubcategory, propertyName, propertyUrl, propertyData, numberProperties, from, $modalScope) {
    var addressData = userService.getAddress(from);
    var privKey = new Bitcoin.ECKey.decodeEncryptedFormat(addressData.privkey, addressData.address); // Using address as temporary password
    var pubKey = privKey.getPubKeyHex();

    $scope.propertyIssuanceTxPromise = getUnsignedPropertyIssuanceTransaction(propertyType, previousPropertyId, propertyCategory, propertySubcategory, propertyName, propertyUrl, propertyData, numberProperties, from, $modalScope);
    $scope.propertyIssuanceTxPromise.then(function(successData) {

      if (successData.status != 200) {
        $modalScope.waiting = false;
        $modalScope.issueError = true;
        $modalScope.error = 'Error preparing Property Issuance transaction: ' + successData.data;
      } else {
        var unsignedTransaction = successData.unsignedhex;

        try {
          var bytes = Bitcoin.Util.hexToBytes(unsignedTransaction);
          var transaction = Bitcoin.Transaction.deserialize(bytes);
          /*var script = parseScript(successData.sourceScript);

          transaction.ins.forEach(function(input) {
            input.script = script;
          });*/

          //DEBUG console.log('before',transaction, Bitcoin.Util.bytesToHex(transaction.serialize()));
          var signedSuccess = transaction.signWithKey(privKey);

          var finalTransaction = Bitcoin.Util.bytesToHex(transaction.serialize());

          //Showing the user the transaction hash doesn't work right now
          //var transactionHash = Bitcoin.Util.bytesToHex(transaction.getHash().reverse());

          walletTradeService.pushSignedTransaction(finalTransaction).then(function(successData) {
            var successData = successData.data;
            if (successData.pushed.match(/submitted|success/gi) != null) {
              $modalScope.waiting = false;
              $modalScope.issueSuccess = true;
              $modalScope.url = 'http://blockchain.info/address/' + from + '?sort=0';
            } else {
              $modalScope.waiting = false;
              $modalScope.issueError = true;
              $modalScope.error = successData.pushed; //Unspecified error, show user
            }
          }, function(errorData) {
            $modalScope.waiting = false;
            $modalScope.issueError = true;
            if (errorData.message)
              $modalScope.error = 'Server error: ' + errorData.message;
            else
              if (errorData.data)
                $modalScope.error = 'Server error: ' + errorData.data;
              else
                $modalScope.error = 'Unknown Server Error';
            console.error(errorData);
          });

          //DEBUG console.log(addressData, privKey, bytes, transaction, script, signedSuccess, finalTransaction );
          function parseScript(script) {
            var newScript = new Bitcoin.Script();
            var s = script.split(" ");
            for (var i = 0; i < s.length; i++) {
              if (Bitcoin.Opcode.map.hasOwnProperty(s[i])) {
                newScript.writeOp(Bitcoin.Opcode.map[s[i]]);
              } else {
                newScript.writeBytes(Bitcoin.Util.hexToBytes(s[i]));
              }
            }
            return newScript;
          }
        } catch (e) {
          $modalScope.sendError = true;
          if (e.message)
            $modalScope.error = 'Error sending transaction: ' + e.message;
          else
            if (e.data)
              $modalScope.error = 'Error sending transaction: ' + e.data;
            else
              $modalScope.error = 'Unknown error sending transaction';
          console.error(e);
        }
      }
    }, function(errorData) {
      $modalScope.sendError = true;
      if (errorData.message)
        $modalScope.error = 'Server error: ' + errorData.message;
      else
        if (errorData.data)
          $modalScope.error = 'Server error: ' + errorData.data;
        else
          $modalScope.error = 'Unknown Server Error';
      console.error(errorData);
    });
  }

  $scope.validatePropertyIssuanceForm = function() {
    var dustValue = 5430;
    var minerMinimum = 10000;
    var nonZeroValue = 1;

    var convertToSatoshi = [
      $scope.minerFees,
      $scope.balanceData[1]
    ];

    var convertedValues =$scope.convertDisplayedValue(convertToSatoshi);
    var minerFees = +convertedValues[0];
    var btcbalance = convertedValues[1];
    var numberProperties=$scope.numberProperties,
    propertyType = $scope.propertyType,
    previousPropertyId=$scope.previousPropertyId,
    propertyName=$scope.propertyName,
    propertyCategory=$scope.propertyCategory,
    propertySubcategory=$scope.propertySubcategory,
    propertyUrl=$scope.propertyUrl;

    var error = 'Please ';
    if ($scope.issuanceForm.$valid == false) {
      error += 'make sure all fields are completely filled, ';
    }
    if (minerFees < minerMinimum)
      error += 'make sure your fee entry is at least 0.0001 BTC to cover miner costs, ';
    if ((minerFees <= btcbalance) == false)
        error += 'make sure you have enough Bitcoin to cover your fees, ';
    if (!propertyName || propertyName == '\0')
      error += 'make sure you enter a Property Name, ';

    if (error.length < 8) {
      $scope.$parent.showErrors = false;
      // open modal
      var modalInstance = $modal.open({
        templateUrl: '/partials/explorer_assets_issuance_modal.html',
        controller: function($scope, $rootScope, userService, data, preparePropertyIssuanceTransaction, getUnsignedPropertyIssuanceTransaction, convertSatoshiToDisplayedValue, getDisplayedAbbreviation) {
          $scope.issueSuccess = false, $scope.issueError = false, $scope.waiting = false, $scope.privKeyPass = {};
          $scope.convertSatoshiToDisplayedValue=  convertSatoshiToDisplayedValue,
          $scope.getDisplayedAbbreviation=  getDisplayedAbbreviation,
          $scope.numberProperties=  data.numberProperties,
          $scope.propertyTypeName=  data.propertyTypeName,
          $scope.propertyName= data.propertyName,
          $scope.propertyCategory= data.propertyCategory,
          $scope.propertySubcategory= data.propertySubcategory,
          $scope.propertyUrl= data.propertyUrl;

          $scope.ok = function() {
            $scope.clicked = true;
            $scope.waiting = true;
            preparePropertyIssuanceTransaction(data.propertyType, data.previousPropertyId, data.propertyCategory, data.propertySubcategory, data.propertyName, data.propertyUrl, data.propertyData, data.numberProperties, from, $scope);
          };
        },
        resolve: {
          data: function() {
            return {
              numberProperties:numberProperties,
              propertyType:propertyType,
              propertyTypeName:propertyType == 1 || propertyType == 65 || propertyType == 129? 'Indivisible' : 'Divisible', // Only values 1 or 2 are supported right now, but leave room for expansion.
              previousPropertyId:previousPropertyId,
              propertyName:propertyName,
              propertyCategory:propertyCategory,
              propertySubcategory:propertySubcategory,
              propertyUrl:propertyUrl,
              propertyData:'\0' // this is fixed to 1 byte by the spec
            };
          },
          preparePropertyIssuanceTransaction: function() {
            return preparePropertyIssuanceTransaction;
          },
          getUnsignedPropertyIssuanceTransaction: function() {
            return getUnsignedPropertyIssuanceTransaction;
          },
          pushSignedTransaction: function() {
            return walletTradeService.pushSignedTransaction;
          },
          convertSatoshiToDisplayedValue: function() {
            return $scope.convertSatoshiToDisplayedValue;
          },
          getDisplayedAbbreviation: function() {
            return $scope.getDisplayedAbbreviation;
          }
        }
      });
    } else {
      error += 'and try again.';
      $scope.error = error;
      $scope.$parent.showErrors = true;
    }
  };
}
<|endoftext|>


<commit_before>'use strict';

const express = require('express');
const parser = require('body-parser');
const technoDoc = require('techno-gendoc');
const path = require('path');
var zip = new require('node-zip')();

const users = new Map();
const sessions = new Map();

technoDoc.generate(require('./api'), 'dist');

zip.file('./dist/assets/js/bundle.js');
var data = zip.generate({base64:false,compression:'DEFLATE'});

const app = express();
app.use('/', express.static('dist', {maxAge: 1}));
app.use('/app', express.static('dist', {maxAge: 1}));
app.use('/sign', express.static('dist', {maxAge: 1}));
app.use('/reg', express.static('dist', {maxAge: 1}));
app.use('/score', express.static('dist', {maxAge: 1}));
app.use('/score/:page', express.static('dist', {maxAge: 1}));
app.use('/singleplayer', express.static('dist', {maxAge: 1}));

app.listen(process.env.PORT || 3000, () => {
	console.log(`App started on port ${process.env.PORT || 3000}`);
});
<commit_msg>add gzip<commit_after>'use strict';

const express = require('express');
const parser = require('body-parser');
const technoDoc = require('techno-gendoc');
const path = require('path');
const compression = require('compression')

const users = new Map();
const sessions = new Map();

const app = express();
app.use(compression());
app.use('/', express.static('dist', {maxAge: 1}));
app.use('/app', express.static('dist', {maxAge: 1}));
app.use('/sign', express.static('dist', {maxAge: 1}));
app.use('/reg', express.static('dist', {maxAge: 1}));
app.use('/score', express.static('dist', {maxAge: 1}));
app.use('/score/:page', express.static('dist', {maxAge: 1}));
app.use('/singleplayer', express.static('dist', {maxAge: 1}));

app.listen(process.env.PORT || 3000, () => {
	console.log(`App started on port ${process.env.PORT || 3000}`);
});
<|endoftext|>


<commit_before>#!/usr/bin/env node
const { resolve } = require('path')
const { start: options } = require(resolve('./package.json'))

// eslint-disable-next-line no-global-assign
require = require('esm')(module, {
  mainFields: ['module', 'main']
})

if (Array.isArray(options.require)) {
  options.require.forEach((pkg) => {
    if (typeof pkg === 'string') {
      require(pkg)
    } else if (Array.isArray(pkg)) {
      require(pkg[0])(pkg[1])
    }
  })
}

const { default: cliLib } = require('./lib')

cliLib(process.argv, options).catch((error) => {
  if (error !== null) {
    console.log(error)
  }

  // eslint-disable-next-line no-process-exit
  process.exit(1)
})
<commit_msg>✔ cli: disable ESM loader cache for a while<commit_after>#!/usr/bin/env node

// eslint-disable-next-line no-global-assign
require = require('esm')(module, {
  mainFields: ['module', 'main'],
  cache: false
})

const { resolve } = require('path')
const { start: options } = require(resolve('./package.json'))

if (Array.isArray(options.require)) {
  options.require.forEach((pkg) => {
    if (typeof pkg === 'string') {
      require(pkg)
    } else if (Array.isArray(pkg)) {
      require(pkg[0])(pkg[1])
    }
  })
}

const { default: cliLib } = require('./lib')

cliLib(process.argv, options).catch((error) => {
  if (error !== null) {
    console.log(error)
  }

  // eslint-disable-next-line no-process-exit
  process.exit(1)
})
<|endoftext|>


<commit_before>
express = require("express");
cim = require("../index");

var console = cim("APP");

app = express();

app.listen(8080, function(){
  console.log("now listening on port %d", 8080);
});

app.get("/", function(req, res) {
  var logger = cim("root", console);
  logger.log("Request");
  res.send('sub');
});

app.get("/sub", function(req, res) {
  var logger = cim("sub", console);
  logger.log("Request");
  res.send('root');
});
<commit_msg>cim -> clim<commit_after>express = require("express");
clim = require("../index");

var console = clim("APP");

app = express();

app.listen(8080, function(){
  console.log("now listening on port %d", 8080);
});

app.get("/", function(req, res) {
  var logger = clim("root", console);
  logger.log("Request");
  res.send('sub');
});

app.get("/sub", function(req, res) {
  var logger = clim("sub", console);
  logger.log("Request");
  res.send('root');
});
<|endoftext|>


<commit_before>
import OffsetKey from '../utils/offset-key'
import React from 'react'
import ReactDOM from 'react-dom'
import Text from './text'
import keycode from 'keycode'
import { Raw } from '..'
import { isCommand, isWindowsCommand } from '../utils/event'

/**
 * Content.
 */

class Content extends React.Component {

  /**
   * Props.
   */

  static propTypes = {
    onBeforeInput: React.PropTypes.func,
    onChange: React.PropTypes.func,
    onKeyDown: React.PropTypes.func,
    onPaste: React.PropTypes.func,
    onSelect: React.PropTypes.func,
    renderMark: React.PropTypes.func.isRequired,
    renderNode: React.PropTypes.func.isRequired,
    state: React.PropTypes.object.isRequired,
  };

  /**
   * Constructor.
   *
   * @param {Object} props
   */

  constructor(props) {
    super(props)
    this.tmp = {}
  }

  /**
   * Should the component update?
   *
   * @param {Object} props
   * @param {Object} state
   * @return {Boolean} shouldUpdate
   */

  shouldComponentUpdate(props, state) {
    if (props.state == this.props.state) return false
    if (props.state.document == this.props.state.document) return false
    if (props.state.isNative) return false
    return true
  }

  /**
   * On before input, bubble up.
   *
   * @param {Event} e
   */

  onBeforeInput(e) {
    this.props.onBeforeInput(e)
  }

  /**
   * On change, bubble up.
   *
   * @param {State} state
   */

  onChange(state) {
    this.props.onChange(state)
  }

  /**
   * On copy, defer to `onCutCopy`, then bubble up.
   *
   * @param {Event} e
   */

  onCopy(e) {
    this.onCutCopy(e)
  }

  /**
   * On cut, defer to `onCutCopy`, then bubble up.
   *
   * @param {Event} e
   */

  onCut(e) {
    this.onCutCopy(e)

    // Once the cut has successfully executed, delete the current selection.
    window.requestAnimationFrame(() => {
      const state = this.props.state.transform().delete().apply()
      this.onChange(state)
    })
  }

  /**
   * On cut and copy, add the currently selected fragment to the currently
   * selected DOM, so that it will show up when pasted.
   *
   * @param {Event} e
   */

  onCutCopy(e) {
    const native = window.getSelection()
    if (!native.rangeCount) return

    const { state } = this.props
    const { fragment } = state
    const raw = Raw.serializeNode(fragment)
    const string = JSON.stringify(raw)
    const encoded = window.btoa(string)

    // Wrap the first character of the selection in a span that has the encoded
    // fragment attached as an attribute, so it will show up in the copied HTML.
    const range = native.getRangeAt(0)
    const contents = range.cloneContents()
    const wrapper = window.document.createElement('span')
    const text = contents.childNodes[0]
    const char = text.textContent.slice(0, 1)
    const first = window.document.createTextNode(char)
    const rest = text.textContent.slice(1)
    text.textContent = rest
    wrapper.appendChild(first)
    wrapper.setAttribute('data-fragment', encoded)
    contents.insertBefore(wrapper, text)

    // Add the phony content to the DOM, and select it, so it will be copied.
    const body = window.document.querySelector('body')
    const div = window.document.createElement('div')
    div.setAttribute('contenteditable', true)
    div.style.position = 'absolute'
    div.style.left = '-9999px'
    div.appendChild(contents)
    body.appendChild(div)

    // Set the `isCopying` flag, so our `onSelect` logic doesn't fire.
    this.tmp.isCopying = true
    native.selectAllChildren(div)

    // Revert to the previous selection right after copying.
    window.requestAnimationFrame(() => {
      body.removeChild(div)
      native.removeAllRanges()
      native.addRange(range)
      this.tmp.isCopying = false
    })
  }

  /**
   * On key down, prevent the default behavior of certain commands that will
   * leave the editor in an out-of-sync state, then bubble up.
   *
   * @param {Event} e
   */

  onKeyDown(e) {
    const key = keycode(e.which)

    if (
      (key == 'enter') ||
      (key == 'backspace') ||
      (key == 'delete') ||
      (key == 'b' && isCommand(e)) ||
      (key == 'i' && isCommand(e)) ||
      (key == 'y' && isWindowsCommand(e)) ||
      (key == 'z' && isCommand(e))
    ) {
      e.preventDefault()
    }

    this.props.onKeyDown(e)
  }

  /**
   * On paste, determine the type and bubble up.
   *
   * @param {Event} e
   */

  onPaste(e) {
    e.preventDefault()
    const data = e.clipboardData
    const { types } = data
    const paste = {}

    // Handle files.
    if (data.files.length != 0) {
      paste.type = 'files'
      paste.files = data.files
    }

    // Treat it as rich text if there is HTML content.
    else if (types.includes('text/html')) {
      paste.type = 'html'
      paste.text = data.getData('text/plain')
      paste.html = data.getData('text/html')
    }

    // Treat everything else as plain text.
    else {
      paste.type = 'text'
      paste.text = data.getData('text/plain')
    }

    // If html, and the html includes a `data-fragment` attribute, it's actually
    // a raw-serialized JSON fragment from a previous cut/copy, so deserialize
    // it and insert it normally.
    if (paste.type == 'html' && ~paste.html.indexOf('<span data-fragment="')) {
      const regexp = /data-fragment="([^\s]+)"/
      const matches = regexp.exec(paste.html)
      const [ full, encoded ] = matches
      const string = window.atob(encoded)
      const json = JSON.parse(string)
      const fragment = Raw.deserialize(json)
      let { state } = this.props

      state = state
        .transform()
        .insertFragment(fragment.document)
        .apply()

      this.onChange(state)
      return
    }

    paste.data = data
    this.props.onPaste(e, paste)
  }

  /**
   * On select, update the current state's selection.
   *
   * @param {Event} e
   */

  onSelect(e) {
    if (this.tmp.isCopying) return

    let { state } = this.props
    let { document, selection } = state
    const native = window.getSelection()

    if (!native.rangeCount) {
      selection = selection.merge({ isFocused: false })
      state = state.merge({ selection })
      this.onChange(state)
      return
    }

    const el = ReactDOM.findDOMNode(this)
    const { anchorNode, anchorOffset, focusNode, focusOffset } = native
    const anchor = OffsetKey.findPoint(anchorNode, anchorOffset)
    const focus = OffsetKey.findPoint(focusNode, focusOffset)

    selection = selection.merge({
      anchorKey: anchor.key,
      anchorOffset: anchor.offset,
      focusKey: focus.key,
      focusOffset: focus.offset,
      isFocused: true
    })

    selection = selection.normalize(document)
    state = state.merge({ selection })
    this.onChange(state)
  }

  /**
   * Render the editor content.
   *
   * @return {Component} component
   */

  render() {
    const { state } = this.props
    const { document } = state
    const children = document.nodes
      .map(node => this.renderNode(node))
      .toArray()

    const style = {
      outline: 'none', // prevent the default outline styles
      whiteSpace: 'pre-wrap', // preserve adjacent whitespace and new lines
      wordWrap: 'break-word' // allow words to break if they are too long
    }

    return (

 this.onBeforeInput(e)}
        onCopy={e => this.onCopy(e)}
        onCut={e => this.onCut(e)}
        onKeyDown={e => this.onKeyDown(e)}
        onPaste={e => this.onPaste(e)}
        onSelect={e => this.onSelect(e)}
      >
        {children}

    )
  }

  /**
   * Render a `node`.
   *
   * @param {Node} node
   * @return {Component} component
   */

  renderNode(node) {
    switch (node.kind) {
      case 'block':
      case 'inline':
        return this.renderElement(node)
      case 'text':
        return this.renderText(node)
    }
  }

  /**
   * Render an element `node`.
   *
   * @param {Node} node
   * @return {Component} component
   */

  renderElement(node) {
    const { renderNode, state } = this.props
    const Component = renderNode(node)
    const children = node.nodes
      .map(child => this.renderNode(child))
      .toArray()

    return (
      <Component
        key={node.key}
        node={node}
        state={state}
      >
        {children}
      </Component>
    )
  }

  /**
   * Render a text `node`.
   *
   * @param {Node} node
   * @return {Component} component
   */

  renderText(node) {
    const { renderMark, renderNode, state } = this.props
    return (
      <Text
        key={node.key}
        node={node}
        renderMark={renderMark}
        state={state}
      />
    )
  }

}

/**
 * Export.
 */

export default Content

<commit_msg>add on blur logic to content component<commit_after>
import OffsetKey from '../utils/offset-key'
import React from 'react'
import ReactDOM from 'react-dom'
import Text from './text'
import keycode from 'keycode'
import { Raw } from '..'
import { isCommand, isWindowsCommand } from '../utils/event'

/**
 * Content.
 */

class Content extends React.Component {

  /**
   * Props.
   */

  static propTypes = {
    onBeforeInput: React.PropTypes.func,
    onChange: React.PropTypes.func,
    onKeyDown: React.PropTypes.func,
    onPaste: React.PropTypes.func,
    onSelect: React.PropTypes.func,
    renderMark: React.PropTypes.func.isRequired,
    renderNode: React.PropTypes.func.isRequired,
    state: React.PropTypes.object.isRequired,
  };

  /**
   * Constructor.
   *
   * @param {Object} props
   */

  constructor(props) {
    super(props)
    this.tmp = {}
  }

  /**
   * Should the component update?
   *
   * @param {Object} props
   * @param {Object} state
   * @return {Boolean} shouldUpdate
   */

  shouldComponentUpdate(props, state) {
    if (props.state == this.props.state) return false
    if (props.state.document == this.props.state.document) return false
    if (props.state.isNative) return false
    return true
  }

  /**
   * On before input, bubble up.
   *
   * @param {Event} e
   */

  onBeforeInput(e) {
    this.props.onBeforeInput(e)
  }

  /**
   * On blur, update the selection to be not focused.
   *
   * @param {Event} e
   */

  onBlur(e) {
    if (this.tmp.isCopying) return

    let { state } = this.props
    let { document, selection } = state
    selection = selection.merge({ isFocused: false })
    state = state.merge({ selection })
    this.onChange(state)
  }

  /**
   * On change, bubble up.
   *
   * @param {State} state
   */

  onChange(state) {
    this.props.onChange(state)
  }

  /**
   * On copy, defer to `onCutCopy`, then bubble up.
   *
   * @param {Event} e
   */

  onCopy(e) {
    this.onCutCopy(e)
  }

  /**
   * On cut, defer to `onCutCopy`, then bubble up.
   *
   * @param {Event} e
   */

  onCut(e) {
    this.onCutCopy(e)

    // Once the cut has successfully executed, delete the current selection.
    window.requestAnimationFrame(() => {
      const state = this.props.state.transform().delete().apply()
      this.onChange(state)
    })
  }

  /**
   * On cut and copy, add the currently selected fragment to the currently
   * selected DOM, so that it will show up when pasted.
   *
   * @param {Event} e
   */

  onCutCopy(e) {
    const native = window.getSelection()
    if (!native.rangeCount) return

    const { state } = this.props
    const { fragment } = state
    const raw = Raw.serializeNode(fragment)
    const string = JSON.stringify(raw)
    const encoded = window.btoa(string)

    // Wrap the first character of the selection in a span that has the encoded
    // fragment attached as an attribute, so it will show up in the copied HTML.
    const range = native.getRangeAt(0)
    const contents = range.cloneContents()
    const wrapper = window.document.createElement('span')
    const text = contents.childNodes[0]
    const char = text.textContent.slice(0, 1)
    const first = window.document.createTextNode(char)
    const rest = text.textContent.slice(1)
    text.textContent = rest
    wrapper.appendChild(first)
    wrapper.setAttribute('data-fragment', encoded)
    contents.insertBefore(wrapper, text)

    // Add the phony content to the DOM, and select it, so it will be copied.
    const body = window.document.querySelector('body')
    const div = window.document.createElement('div')
    div.setAttribute('contenteditable', true)
    div.style.position = 'absolute'
    div.style.left = '-9999px'
    div.appendChild(contents)
    body.appendChild(div)

    // Set the `isCopying` flag, so our `onSelect` logic doesn't fire.
    this.tmp.isCopying = true
    native.selectAllChildren(div)

    // Revert to the previous selection right after copying.
    window.requestAnimationFrame(() => {
      body.removeChild(div)
      native.removeAllRanges()
      native.addRange(range)
      this.tmp.isCopying = false
    })
  }

  /**
   * On key down, prevent the default behavior of certain commands that will
   * leave the editor in an out-of-sync state, then bubble up.
   *
   * @param {Event} e
   */

  onKeyDown(e) {
    const key = keycode(e.which)

    if (
      (key == 'enter') ||
      (key == 'backspace') ||
      (key == 'delete') ||
      (key == 'b' && isCommand(e)) ||
      (key == 'i' && isCommand(e)) ||
      (key == 'y' && isWindowsCommand(e)) ||
      (key == 'z' && isCommand(e))
    ) {
      e.preventDefault()
    }

    this.props.onKeyDown(e)
  }

  /**
   * On paste, determine the type and bubble up.
   *
   * @param {Event} e
   */

  onPaste(e) {
    e.preventDefault()
    const data = e.clipboardData
    const { types } = data
    const paste = {}

    // Handle files.
    if (data.files.length != 0) {
      paste.type = 'files'
      paste.files = data.files
    }

    // Treat it as rich text if there is HTML content.
    else if (types.includes('text/html')) {
      paste.type = 'html'
      paste.text = data.getData('text/plain')
      paste.html = data.getData('text/html')
    }

    // Treat everything else as plain text.
    else {
      paste.type = 'text'
      paste.text = data.getData('text/plain')
    }

    // If html, and the html includes a `data-fragment` attribute, it's actually
    // a raw-serialized JSON fragment from a previous cut/copy, so deserialize
    // it and insert it normally.
    if (paste.type == 'html' && ~paste.html.indexOf('<span data-fragment="')) {
      const regexp = /data-fragment="([^\s]+)"/
      const matches = regexp.exec(paste.html)
      const [ full, encoded ] = matches
      const string = window.atob(encoded)
      const json = JSON.parse(string)
      const fragment = Raw.deserialize(json)
      let { state } = this.props

      state = state
        .transform()
        .insertFragment(fragment.document)
        .apply()

      this.onChange(state)
      return
    }

    paste.data = data
    this.props.onPaste(e, paste)
  }

  /**
   * On select, update the current state's selection.
   *
   * @param {Event} e
   */

  onSelect(e) {
    if (this.tmp.isCopying) return

    let { state } = this.props
    let { document, selection } = state
    const native = window.getSelection()

    if (!native.rangeCount) {
      selection = selection.merge({ isFocused: false })
      state = state.merge({ selection })
      this.onChange(state)
      return
    }

    const el = ReactDOM.findDOMNode(this)
    const { anchorNode, anchorOffset, focusNode, focusOffset } = native
    const anchor = OffsetKey.findPoint(anchorNode, anchorOffset)
    const focus = OffsetKey.findPoint(focusNode, focusOffset)

    selection = selection.merge({
      anchorKey: anchor.key,
      anchorOffset: anchor.offset,
      focusKey: focus.key,
      focusOffset: focus.offset,
      isFocused: true
    })

    selection = selection.normalize(document)
    state = state.merge({ selection })
    this.onChange(state)
  }

  /**
   * Render the editor content.
   *
   * @return {Component} component
   */

  render() {
    const { state } = this.props
    const { document } = state
    const children = document.nodes
      .map(node => this.renderNode(node))
      .toArray()

    const style = {
      outline: 'none', // prevent the default outline styles
      whiteSpace: 'pre-wrap', // preserve adjacent whitespace and new lines
      wordWrap: 'break-word' // allow words to break if they are too long
    }

    return (

 this.onBeforeInput(e)}
        onBlur={e => this.onBlur(e)}
        onCopy={e => this.onCopy(e)}
        onCut={e => this.onCut(e)}
        onKeyDown={e => this.onKeyDown(e)}
        onPaste={e => this.onPaste(e)}
        onSelect={e => this.onSelect(e)}
      >
        {children}

    )
  }

  /**
   * Render a `node`.
   *
   * @param {Node} node
   * @return {Component} component
   */

  renderNode(node) {
    switch (node.kind) {
      case 'block':
      case 'inline':
        return this.renderElement(node)
      case 'text':
        return this.renderText(node)
    }
  }

  /**
   * Render an element `node`.
   *
   * @param {Node} node
   * @return {Component} component
   */

  renderElement(node) {
    const { renderNode, state } = this.props
    const Component = renderNode(node)
    const children = node.nodes
      .map(child => this.renderNode(child))
      .toArray()

    return (
      <Component
        key={node.key}
        node={node}
        state={state}
      >
        {children}
      </Component>
    )
  }

  /**
   * Render a text `node`.
   *
   * @param {Node} node
   * @return {Component} component
   */

  renderText(node) {
    const { renderMark, renderNode, state } = this.props
    return (
      <Text
        key={node.key}
        node={node}
        renderMark={renderMark}
        state={state}
      />
    )
  }

}

/**
 * Export.
 */

export default Content

<|endoftext|>


<commit_before>'use strict';

/**
 * Module dependencies.
 */

var papi = require('./lib');
var util = require('util');

/**
 * GitHub API client
 */

function GitHub(opts) {
  opts = opts || {};

  if (!opts.baseUrl) {
    opts.baseUrl = 'https://api.github.com';
  }
  if (!opts.headers) {
    opts.headers = {};
  }
  if (!opts.headers.accept) {
    opts.headers.accept = 'application/vnd.github.v3+json';
  }
  if (!opts.headers['user-agent']) {
    opts.headers['user-agent'] = 'RapiGitHub/0.1.0';
  }
  if (opts.tags) {
    opts.tags = ['github'].concat(opts.tags);
  } else {
    opts.tags = ['github'];
  }
  if (!opts.timeout) {
    opts.timeout = 60 * 1000;
  }

  papi.Client.call(this, opts);

  if (opts.debug) {
    this.on('log', console.log);
  }
}

util.inherits(GitHub, papi.Client);

/**
 * Get user gists
 */

GitHub.prototype.gists = function(username, callback) {
  var opts = {
    path: '/users/{username}/gists',
    params: { username: username },
  };

  return this._get(opts, callback);
};

/**
 * Print gists for user `silas`
 */

function main() {
  var github = new GitHub({ debug: true });

  github.gists('silas', function(err, res) {
    if (err) throw err;

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

    res.body.forEach(function(gist) {
      if (gist.description) console.log(gist.description);
    });
  });
}

/**
 * Initialize
 */

if (require.main === module) {
  main();
} else {
  module.exports = GitHub;
}
<commit_msg>Fix example user-agent<commit_after>'use strict';

/**
 * Module dependencies.
 */

var papi = require('./lib');
var util = require('util');

/**
 * GitHub API client
 */

function GitHub(opts) {
  opts = opts || {};

  if (!opts.baseUrl) {
    opts.baseUrl = 'https://api.github.com';
  }
  if (!opts.headers) {
    opts.headers = {};
  }
  if (!opts.headers.accept) {
    opts.headers.accept = 'application/vnd.github.v3+json';
  }
  if (!opts.headers['user-agent']) {
    opts.headers['user-agent'] = 'PapiGitHub/0.1.0';
  }
  if (opts.tags) {
    opts.tags = ['github'].concat(opts.tags);
  } else {
    opts.tags = ['github'];
  }
  if (!opts.timeout) {
    opts.timeout = 60 * 1000;
  }

  papi.Client.call(this, opts);

  if (opts.debug) {
    this.on('log', console.log);
  }
}

util.inherits(GitHub, papi.Client);

/**
 * Get user gists
 */

GitHub.prototype.gists = function(username, callback) {
  var opts = {
    path: '/users/{username}/gists',
    params: { username: username },
  };

  return this._get(opts, callback);
};

/**
 * Print gists for user `silas`
 */

function main() {
  var github = new GitHub({ debug: true });

  github.gists('silas', function(err, res) {
    if (err) throw err;

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

    res.body.forEach(function(gist) {
      if (gist.description) console.log(gist.description);
    });
  });
}

/**
 * Initialize
 */

if (require.main === module) {
  main();
} else {
  module.exports = GitHub;
}
<|endoftext|>


<commit_before>/**
 * @author Gilles Coomans <gilles.coomans@gmail.com>
 */
if (typeof define !== 'function') {
	var define = require('amdefine')(module);
}
define(["require", "./utils"], function(require, utils) {
	"use strict";
	var compiler = {

	};
	compiler.Shared = function(datas) {
		//console.log("CREATE DEEPSHARED")
		datas._deep_shared_ = true;
		return datas;
	};
	compiler.compile = function() {
		var base = utils.copy(arguments[0]);
		var len = arguments.length;
		for (var i = 1; i < len; ++i)
			compiler.aup(arguments[i], base);
		return base;
	};
	utils.decorateUpFrom = function(src, target, properties) {
		properties.forEach(function(prop) {
			if (typeof src[prop] !== 'undefined')
				target[prop] = compiler.aup(src[prop], target[prop]);
		});
	};
	utils.decorateBottomFrom = function(src, target, properties) {
		properties.forEach(function(prop) {
			if (typeof src[prop] !== 'undefined')
				target[prop] = compiler.abottom(src[prop], target[prop]);
		});
	};
	utils.upFromArgs = compiler.upFromArgs = function(base, args, opt) {
		var len = args.length - 1;
		for (; len > -1; --len)
			base = compiler.aup(args[len], base, opt);
		return base;
	};
	utils.bottomFromArgs = compiler.bottomFromArgs = function(base, args, opt) {
		var len = args.length - 1;
		for (; len > -1; --len)
			base = compiler.abottom(args[len], base, opt);
		return base;
	};
	/*
		utils.set = function(root, query, value)
		{
			var splitted = query;
			if(!query.forEach)
				splitted = query.replace("]", "[").split("[");
			split = splitted.shift();
			var tmp = root;
			while(split)
			{
				if(split[0] == '/')
				{
					var key = split.substring(1);
					if(key[key.length-1] == '/')
						key = key.substring(0,key.length-1);
					if(tmp[key])
						tmp = tmp[key];
					split = splitted.shift();
					continue;
				}
				var list = split.split(",");
				for(var i =0; i < list.length; ++i)
					if(tmp[list[i]])
						utils.set(tmp[list[i]]);

			}
		}
*/

	compiler.aup = function(src, target, opt){
		// console.log("aup : ", src, target, opt)
		if (typeof src === 'undefined')
			return target;
		if (src === null)
			return null;
		opt = opt || {};
		if (typeof target === 'undefined' || target === null)
			return utils.copy(src, false, opt.excludeGrounds);
		/*if (src._deep_sheet_) {
			throw new Error("using sheets through up");
			if (!target._deep_sheet_) {
				deep.sheet(src, target);
				return target;
			}
		} else if (target._deep_sheet_) {
			throw new Error("using sheets through up");
			src = utils.copy(src);
			return src;
		}*/
		if (target._deep_compiler_) {
			target = target._up(src);
			return target;
		}
		if (src._deep_compiler_) {
			if (src._clone)
				src = src._clone()
			return src._bottom(target);
		}
		if (src._deep_shared_) {
			//console.log("up from shared");
			src._deep_shared_ = false;
			target = compiler.abottom(target, src);
			src._deep_shared_ = true;
			return target;
		}
		if (target._deep_shared_) {
			//console.log("up to shared : ", parent, key)
			target._deep_shared_ = false;
			target = compiler.abottom(target, src);
			target._deep_shared_ = true;
			return target;
		}
		var srcType = utils.getJSPrimitiveType(src);
		var targetType = utils.getJSPrimitiveType(target);
		if (srcType !== targetType) {
			//console.log("aup will copy : srctype != targetType : ", srcType, targetType)
			target = utils.copy(src, false, opt.excludeGrounds);
			return target;
		}
		switch (srcType) {
			case 'array':
				var result = compiler.upArray(src, target);
				return result;
			case 'object':
				// console.log("aup : merging object", src, target)
				if (src instanceof RegExp)
					return src;
				if (src instanceof Date) {
					target = new Date(src.valueOf());
					return target;
				}
				for (var i in src) {
					if(i == '_backgrounds' || i == '_foregrounds' || i == "_transformations")
						if(opt.excludeGrounds)
							continue;
						else
						{
							target[i] = target[i] ? target[i].concat(src[i]) : src[i].slice();
							continue;
						}
					if (typeof target[i] === 'undefined') {
						// console.log("aup merging object : target[i] is undefined : copy src[i]")
						target[i] = utils.copy(src[i]);
						continue;
					}
					if (src[i] === null) {
						target[i] = null;
						continue;
					}

					if (typeof src[i] === 'object' || typeof src[i] === 'function')
					{
						// console.log("aup object merge : src[i] is function")
						target[i] = compiler.aup(src[i], target[i]); //, target, i);
					}
					else
						target[i] = src[i];
					if(target[i] && target[i]._deep_remover_)
						delete target[i];
				}
				return target;
			default:
				return src;
		}
	}
	compiler.abottom = function(src, target, opt){
		opt = opt || {};
		if (src === null || typeof src === "undefined")
			return target;
		if (target === null)
			return target;
		if (typeof target === 'undefined') {
			target = utils.copy(src, false, opt.excludeGrounds);
			return target;
		}
		/*if (target._deep_sheet_) {
			throw new Error("using sheets through bottom");
			if (!src._deep_sheet_) {
				deep.sheet(target, src);
				return src;
			}
		} else if (src._deep_sheet_)
		{
			throw new Error("using sheets through bottom");
			return target;
		}*/
		if (target._deep_compiler_) {
			target = target._bottom(src);
			return target;
		}
		if (src._deep_compiler_) {
			if(src._clone)
				src = src._clone();
			src._up(target);
			return src;
		}
		if (src._deep_shared_) {
			//console.log("bottom from shared");
			src._deep_shared_ = false;
			src = compiler.aup(target, src);
			src._deep_shared_ = true;
			return src;
		}
		if (target._deep_shared_) {
			//console.log("bottom to shared : ", parent, key)
			target._deep_shared_ = false;
			src = compiler.aup(target, src); //, parent, key);
			target._deep_shared_ = true;
			return src;
		}
		var srcType = utils.getJSPrimitiveType(src);
		var targetType = utils.getJSPrimitiveType(target);
		if (srcType !== targetType)
			return target;
		switch (srcType) {
			case 'array':
				var result = compiler.bottomArray(src, target);
				return result;
			case 'object':

				for (var i in src)
				{
					if(i == '_backgrounds' || i == '_foregrounds' || i == "_transformations")
						if(opt.excludeGrounds)
							continue;
						else
						{
							target[i] = target[i] ? src[i].concat(target[i]) : src[i].slice();
							continue;
						}
					if (src[i] !== null) {
						if (typeof target[i] === 'undefined')
							target[i] = utils.copy(src[i]);
						else if (typeof src[i] === 'object' || typeof src[i] === 'function')
							target[i] = compiler.abottom(src[i], target[i]); //, target, i);
						if(target[i] && target[i]._deep_remover_)
							delete target[i];
					}
				}
				var copied = utils.shallowCopy(target);
				var i = null;
				for (i in target)
					delete target[i];
				for (i in src) {
					if((i == '_backgrounds' || i == '_foregrounds' || i == '_transformations') && opt.excludeGrounds)
						continue;
					target[i] = copied[i];
					delete copied[i];
				}
				for (i in copied)
					target[i] = copied[i];
				return target;
			default:
				return target;
		}
	}

	/**
	 * up : merge object from up
	 * @param  {[type]} src     [description]
	 * @param  {[type]} target  [description]
	 * @return {[type]}         [description]
	 */
	utils.up = compiler.up = function() {
		var target = arguments[0];
		for (var i = 1, len = arguments.length; i < len; i++)
			target = compiler.aup(arguments[i], target);
		return target;
	};

	utils.bottom = compiler.bottom = function() {
		var target = arguments[arguments.length - 1],
			src = arguments[0];
		for (var i = arguments.length - 2; i > 0; i--)
			target = compiler.abottom(arguments[i], target);
		return compiler.abottom(src, target);
	};

	utils.bottomArray = compiler.bottomArray = function(src, target, mergeOn, excludeGrounds) {
		if (src.length === 0)
			return target;
		var map = {};
		var len = src.length,
			val = null,
			i = 0;
		for (; i < len; ++i) {
			var a = src[i];
			if (a && mergeOn)
				val = utils.fromPath(a, mergeOn);
			else if (a && a.id)
				val = a.id;
			else
				val = String(a);
			map[val] = {
				ref: a,
				index: i
			};
		}
		Array.prototype.unshift.apply(target, src); // prepend src to target
		var elem = target[i]; // check target from target[src.length]
		while (i < target.length) // seek after collision in target, apply it, and remove given element from target
		{
			// catch current value
			if (elem && mergeOn)
				val = utils.fromPath(elem, mergeOn);
			else if (elem && elem.id)
				val = elem.id;
			else
				val = String(elem);
			if (map[val]) {
				target[map[val.index]] = compiler.aup(elem, map[val].ref, { excludeGrounds:excludeGrounds });
				target.splice(i, 1); // remove collided element from t
			}
			elem = target[++i];
		}
		return target;
	};

	utils.upArray = compiler.upArray = function(src, target, mergeOn, excludeGrounds) {
		if (src.length === 0)
			return target;
		var map = {};
		var len = target.length,
			val = null,
			i = 0;
		for (; i < len; ++i) {
			var a = target[i];
			if (a && mergeOn)
				val = utils.fromPath(a, mergeOn);
			else if (a && a.id)
				val = a.id;
			else
				val = String(a);
			map[val] = {
				ref: a,
				index: i
			};
		}
		i = 0;
		var elem = src[i],
			length = src.length; // check target from target[src.length]
		while (i < length) // seek after collision in target, apply it, and remove given element from target
		{
			// catch current value
			if (elem && mergeOn)
				val = utils.fromPath(elem, mergeOn);
			else if (elem && elem.id)
				val = elem.id;
			else
				val = String(elem);
			if (map[val])
				target[map[val.index]] = compiler.aup(elem, map[val].ref, { excludeGrounds:excludeGrounds });
			else
				target.push(elem);
			elem = src[++i];
		}
		return target;
	};
	return compiler;
});<commit_msg>add getPrimitiveType to compiler<commit_after>/**
 * @author Gilles Coomans <gilles.coomans@gmail.com>
 */
if (typeof define !== 'function') {
	var define = require('amdefine')(module);
}
define(["require", "./utils"], function(require, utils) {
	"use strict";

	function getJSPrimitiveType(obj) {
		if (obj && obj.forEach)
			return "array";
		return typeof obj;
	};

	var compiler = {};
	compiler.Shared = function(datas) {
		//console.log("CREATE DEEPSHARED")
		datas._deep_shared_ = true;
		return datas;
	};
	compiler.compile = function() {
		var base = utils.copy(arguments[0]);
		var len = arguments.length;
		for (var i = 1; i < len; ++i)
			compiler.aup(arguments[i], base);
		return base;
	};
	utils.decorateUpFrom = function(src, target, properties) {
		properties.forEach(function(prop) {
			if (typeof src[prop] !== 'undefined')
				target[prop] = compiler.aup(src[prop], target[prop]);
		});
	};
	utils.decorateBottomFrom = function(src, target, properties) {
		properties.forEach(function(prop) {
			if (typeof src[prop] !== 'undefined')
				target[prop] = compiler.abottom(src[prop], target[prop]);
		});
	};
	utils.upFromArgs = compiler.upFromArgs = function(base, args, opt) {
		var len = args.length - 1;
		for (; len > -1; --len)
			base = compiler.aup(args[len], base, opt);
		return base;
	};
	utils.bottomFromArgs = compiler.bottomFromArgs = function(base, args, opt) {
		var len = args.length - 1;
		for (; len > -1; --len)
			base = compiler.abottom(args[len], base, opt);
		return base;
	};
	/*
		utils.set = function(root, query, value)
		{
			var splitted = query;
			if(!query.forEach)
				splitted = query.replace("]", "[").split("[");
			split = splitted.shift();
			var tmp = root;
			while(split)
			{
				if(split[0] == '/')
				{
					var key = split.substring(1);
					if(key[key.length-1] == '/')
						key = key.substring(0,key.length-1);
					if(tmp[key])
						tmp = tmp[key];
					split = splitted.shift();
					continue;
				}
				var list = split.split(",");
				for(var i =0; i < list.length; ++i)
					if(tmp[list[i]])
						utils.set(tmp[list[i]]);

			}
		}
*/

	compiler.aup = function(src, target, opt){
		// console.log("aup : ", src, target, opt)
		if (typeof src === 'undefined')
			return target;
		if (src === null)
			return null;
		opt = opt || {};
		if (typeof target === 'undefined' || target === null)
			return utils.copy(src, false, opt.excludeGrounds);
		/*if (src._deep_sheet_) {
			throw new Error("using sheets through up");
			if (!target._deep_sheet_) {
				deep.sheet(src, target);
				return target;
			}
		} else if (target._deep_sheet_) {
			throw new Error("using sheets through up");
			src = utils.copy(src);
			return src;
		}*/
		if (target._deep_compiler_) {
			target = target._up(src);
			return target;
		}
		if (src._deep_compiler_) {
			if (src._clone)
				src = src._clone()
			return src._bottom(target);
		}
		if (src._deep_shared_) {
			//console.log("up from shared");
			src._deep_shared_ = false;
			target = compiler.abottom(target, src);
			src._deep_shared_ = true;
			return target;
		}
		if (target._deep_shared_) {
			//console.log("up to shared : ", parent, key)
			target._deep_shared_ = false;
			target = compiler.abottom(target, src);
			target._deep_shared_ = true;
			return target;
		}
		var srcType = utils.getJSPrimitiveType(src);
		var targetType = utils.getJSPrimitiveType(target);
		if (srcType !== targetType) {
			//console.log("aup will copy : srctype != targetType : ", srcType, targetType)
			target = utils.copy(src, false, opt.excludeGrounds);
			return target;
		}
		switch (srcType) {
			case 'array':
				var result = compiler.upArray(src, target);
				return result;
			case 'object':
				// console.log("aup : merging object", src, target)
				if (src instanceof RegExp)
					return src;
				if (src instanceof Date) {
					target = new Date(src.valueOf());
					return target;
				}
				for (var i in src) {
					if(i == '_backgrounds' || i == '_foregrounds' || i == "_transformations")
						if(opt.excludeGrounds)
							continue;
						else
						{
							target[i] = target[i] ? target[i].concat(src[i]) : src[i].slice();
							continue;
						}
					if (typeof target[i] === 'undefined') {
						// console.log("aup merging object : target[i] is undefined : copy src[i]")
						target[i] = utils.copy(src[i]);
						continue;
					}
					if (src[i] === null) {
						target[i] = null;
						continue;
					}

					if (typeof src[i] === 'object' || typeof src[i] === 'function')
					{
						// console.log("aup object merge : src[i] is function")
						target[i] = compiler.aup(src[i], target[i]); //, target, i);
					}
					else
						target[i] = src[i];
					if(target[i] && target[i]._deep_remover_)
						delete target[i];
				}
				return target;
			default:
				return src;
		}
	}
	compiler.abottom = function(src, target, opt){
		opt = opt || {};
		if (src === null || typeof src === "undefined")
			return target;
		if (target === null)
			return target;
		if (typeof target === 'undefined') {
			target = utils.copy(src, false, opt.excludeGrounds);
			return target;
		}
		/*if (target._deep_sheet_) {
			throw new Error("using sheets through bottom");
			if (!src._deep_sheet_) {
				deep.sheet(target, src);
				return src;
			}
		} else if (src._deep_sheet_)
		{
			throw new Error("using sheets through bottom");
			return target;
		}*/
		if (target._deep_compiler_) {
			target = target._bottom(src);
			return target;
		}
		if (src._deep_compiler_) {
			if(src._clone)
				src = src._clone();
			src._up(target);
			return src;
		}
		if (src._deep_shared_) {
			//console.log("bottom from shared");
			src._deep_shared_ = false;
			src = compiler.aup(target, src);
			src._deep_shared_ = true;
			return src;
		}
		if (target._deep_shared_) {
			//console.log("bottom to shared : ", parent, key)
			target._deep_shared_ = false;
			src = compiler.aup(target, src); //, parent, key);
			target._deep_shared_ = true;
			return src;
		}
		var srcType = utils.getJSPrimitiveType(src);
		var targetType = utils.getJSPrimitiveType(target);
		if (srcType !== targetType)
			return target;
		switch (srcType) {
			case 'array':
				var result = compiler.bottomArray(src, target);
				return result;
			case 'object':

				for (var i in src)
				{
					if(i == '_backgrounds' || i == '_foregrounds' || i == "_transformations")
						if(opt.excludeGrounds)
							continue;
						else
						{
							target[i] = target[i] ? src[i].concat(target[i]) : src[i].slice();
							continue;
						}
					if (src[i] !== null) {
						if (typeof target[i] === 'undefined')
							target[i] = utils.copy(src[i]);
						else if (typeof src[i] === 'object' || typeof src[i] === 'function')
							target[i] = compiler.abottom(src[i], target[i]); //, target, i);
						if(target[i] && target[i]._deep_remover_)
							delete target[i];
					}
				}
				var copied = utils.shallowCopy(target);
				var i = null;
				for (i in target)
					delete target[i];
				for (i in src) {
					if((i == '_backgrounds' || i == '_foregrounds' || i == '_transformations') && opt.excludeGrounds)
						continue;
					target[i] = copied[i];
					delete copied[i];
				}
				for (i in copied)
					target[i] = copied[i];
				return target;
			default:
				return target;
		}
	}

	/**
	 * up : merge object from up
	 * @param  {[type]} src     [description]
	 * @param  {[type]} target  [description]
	 * @return {[type]}         [description]
	 */
	utils.up = compiler.up = function() {
		var target = arguments[0];
		for (var i = 1, len = arguments.length; i < len; i++)
			target = compiler.aup(arguments[i], target);
		return target;
	};

	utils.bottom = compiler.bottom = function() {
		var target = arguments[arguments.length - 1],
			src = arguments[0];
		for (var i = arguments.length - 2; i > 0; i--)
			target = compiler.abottom(arguments[i], target);
		return compiler.abottom(src, target);
	};

	utils.bottomArray = compiler.bottomArray = function(src, target, mergeOn, excludeGrounds) {
		if (src.length === 0)
			return target;
		var map = {};
		var len = src.length,
			val = null,
			i = 0;
		for (; i < len; ++i) {
			var a = src[i];
			if (a && mergeOn)
				val = utils.fromPath(a, mergeOn);
			else if (a && a.id)
				val = a.id;
			else
				val = String(a);
			map[val] = {
				ref: a,
				index: i
			};
		}
		Array.prototype.unshift.apply(target, src); // prepend src to target
		var elem = target[i]; // check target from target[src.length]
		while (i < target.length) // seek after collision in target, apply it, and remove given element from target
		{
			// catch current value
			if (elem && mergeOn)
				val = utils.fromPath(elem, mergeOn);
			else if (elem && elem.id)
				val = elem.id;
			else
				val = String(elem);
			if (map[val]) {
				target[map[val.index]] = compiler.aup(elem, map[val].ref, { excludeGrounds:excludeGrounds });
				target.splice(i, 1); // remove collided element from t
			}
			elem = target[++i];
		}
		return target;
	};

	utils.upArray = compiler.upArray = function(src, target, mergeOn, excludeGrounds) {
		if (src.length === 0)
			return target;
		var map = {};
		var len = target.length,
			val = null,
			i = 0;
		for (; i < len; ++i) {
			var a = target[i];
			if (a && mergeOn)
				val = utils.fromPath(a, mergeOn);
			else if (a && a.id)
				val = a.id;
			else
				val = String(a);
			map[val] = {
				ref: a,
				index: i
			};
		}
		i = 0;
		var elem = src[i],
			length = src.length; // check target from target[src.length]
		while (i < length) // seek after collision in target, apply it, and remove given element from target
		{
			// catch current value
			if (elem && mergeOn)
				val = utils.fromPath(elem, mergeOn);
			else if (elem && elem.id)
				val = elem.id;
			else
				val = String(elem);
			if (map[val])
				target[map[val.index]] = compiler.aup(elem, map[val].ref, { excludeGrounds:excludeGrounds });
			else
				target.push(elem);
			elem = src[++i];
		}
		return target;
	};
	return compiler;
});<|endoftext|>


<commit_before>/*jshint evil: false, strict: false, undef: true, white: false, plusplus:false, node:true */

var path = require('path');
var _ = require('underscore');
var style = require('../colors');
var debug = process.env.DEBUG || false;

function log() {
    var args = Array.prototype.slice.call(arguments);
    args.unshift('  ');
    console.log.apply(console, args);
}

function debugLog() {
    if(debug) {
        console.log(style.orange('DEBUG'));
        var args = Array.prototype.slice.call(arguments);
        args.unshift('  ');
        console.log.apply(console, args);
    }
}

function printObject(prefix, obj) {
    var names = Object.keys(obj);
    names.forEach(function(name) {
        var value = obj[name];
        if(typeof value === 'undefined') {
            return;
        }
        log(prefix,style.bold(name),':',value);
        //replace prefix by same amount of spaces
        prefix = Array(prefix.length + 1).join(" ");
    });
}

module.exports = function(settings) {
    var trimBody_optional = (settings && settings.trimBody_optional) ? settings.trimBody_optional : null;
    //true by default
    var trimBody = (_.isNull(trimBody_optional) || _.isUndefined(trimBody_optional)) ? true : trimBody_optional.toLowerCase() === 'true';

    function getTrimmedBody(body) {
        var maxlen = 500;
        var shouldTrim = trimBody && !!body && body.length > maxlen;
        if(typeof body === 'string') {
            if(shouldTrim) {
                body = body.substr(0,maxlen) + '...';
            } else {
                return body;
            }
        }
        else if(Buffer.isBuffer(body)) {
            if(shouldTrim) {
                return 'binary buffer: ' + body.slice(0, maxlen).toString('hex') + '...';
            } else {
                return 'binary buffer: ' + body.toString('hex');
            }
        }
        return body;
    }

    function printRequest(req) {
        var requestDescription = _.extend({}, req.headers, {body: getTrimmedBody(req.body)});
        printObject('==>', requestDescription);
    }

    function printResponse(res) {
        var responseDescription = _.extend({status: res.statusCode}, res.headers, {body: getTrimmedBody(res.body)});
        printObject('<==', responseDescription);
    }

    function startStep(description) {
        process.stdout.write(description + ' ... ');
    }

    function endStep(success) {
        if(!success) {
            console.log(style.red(style.bold('FAILED')));
        } else {
            console.log(style.green(style.bold('OK!')));
        }
    }

    return {
        runStarted: function(testCaseCount) {

        },
        testCaseStarted: function(testCase, file) {
            console.log(style.cyan("-=>"),'Running', path.basename(file));
        },
        testStarted: function(testCase, test, description, index) {
            startStep(style.yellow('    * ') + description);
        },
        testFailed: function(testCase, test, err, index) {
            endStep(false);
            process.stdout.write('   ' + err.message);
            if(typeof err.actual !== 'undefined' && typeof err.actual !== 'object' && err.expected) {
                process.stdout.write(', expected ' + err.expected + ' but got ' + err.actual);
            }
            process.stdout.write('\n');
            if(test.line) {
                var stackArray = err.stack.split("\n");
                log('have a look at', test.line);
                var outPut = "";
                for (var i =0; i <= 2; i++) {
                    outPut += stackArray[i] + "\n";
                }
                log(style.red("where: ") +  outPut);
                debugLog(err.stack);
            }
            if(err.request) {
                printRequest(err.request);
            }
            if(err.response) {
                printResponse(err.response);
            }
        },
        testSucceeded: function(testCase, test, description, index) {
            endStep(true);
        },
        testCaseEnded: function(testCase, file, hasFailures) {},
        runEnded: function(testCaseCount, failureCount, totalTestCount) {
            if(failureCount === 0) {
                console.log(style.bold('ran ' + totalTestCount + ' tests in ' +
                        testCaseCount + ' test cases, all ran with ' +
                        style.green('SUCCESS')));
            } else {
                console.log(style.bold('ran ' + testCaseCount + ' test cases, ' +
                        failureCount + ' of them ' + style.red('FAILED')));
            }
        },
        write: function(message) {
            console.log(message);
        }
    };
};<commit_msg>print request & response in debug environments<commit_after>/*jshint evil: false, strict: false, undef: true, white: false, plusplus:false, node:true */

var path = require('path');
var _ = require('underscore');
var style = require('../colors');
var debug = process.env.DEBUG || false;

function log() {
    var args = Array.prototype.slice.call(arguments);
    args.unshift('  ');
    console.log.apply(console, args);
}

function debugLog() {
    if(debug) {
        console.log(style.orange('DEBUG'));
        var args = Array.prototype.slice.call(arguments);
        args.unshift('  ');
        console.log.apply(console, args);
    }
}

function printObject(prefix, obj) {
    var names = Object.keys(obj);
    names.forEach(function(name) {
        var value = obj[name];
        if(typeof value === 'undefined') {
            return;
        }
        log(prefix,style.bold(name),':',value);
        //replace prefix by same amount of spaces
        prefix = Array(prefix.length + 1).join(" ");
    });
}

module.exports = function(settings) {
    var trimBody_optional = (settings && settings.trimBody_optional) ? settings.trimBody_optional : null;
    //true by default
    var trimBody = (_.isNull(trimBody_optional) || _.isUndefined(trimBody_optional)) ? true : trimBody_optional.toLowerCase() === 'true';

    function getTrimmedBody(body) {
        var maxlen = 500;
        var shouldTrim = trimBody && !!body && body.length > maxlen;
        if(typeof body === 'string') {
            if(shouldTrim) {
                body = body.substr(0,maxlen) + '...';
            } else {
                return body;
            }
        }
        else if(Buffer.isBuffer(body)) {
            if(shouldTrim) {
                return 'binary buffer: ' + body.slice(0, maxlen).toString('hex') + '...';
            } else {
                return 'binary buffer: ' + body.toString('hex');
            }
        }
        return body;
    }

    function printRequest(req) {
        var requestDescription = _.extend({}, req.headers, {body: getTrimmedBody(req.body)});
        printObject('==>', requestDescription);
    }

    function printResponse(res) {
        var responseDescription = _.extend({status: res.statusCode}, res.headers, {body: getTrimmedBody(res.body)});
        printObject('<==', responseDescription);
    }

    function startStep(description) {
        process.stdout.write(description + ' ... ');
    }

    function endStep(success) {
        if(!success) {
            console.log(style.red(style.bold('FAILED')));
        } else {
            console.log(style.green(style.bold('OK!')));
        }
    }

    return {
        runStarted: function(testCaseCount) {

        },
        testCaseStarted: function(testCase, file) {
            console.log(style.cyan("-=>"),'Running', path.basename(file));
        },
        testStarted: function(testCase, test, description, index) {
            startStep(style.yellow('    * ') + description);
        },
        testFailed: function(testCase, test, err, index) {
            endStep(false);
            process.stdout.write('   ' + err.message);
            if(typeof err.actual !== 'undefined' && typeof err.actual !== 'object' && err.expected) {
                process.stdout.write(', expected ' + err.expected + ' but got ' + err.actual);
            }
            process.stdout.write('\n');
            if(test.line) {
                var stackArray = err.stack.split("\n");
                log('have a look at', test.line);
                var outPut = "";
                for (var i =0; i <= 2; i++) {
                    outPut += stackArray[i] + "\n";
                }
                log(style.red("where: ") +  outPut);
                debugLog(err.stack);
            }
            if(debug) {
                if(err.request) {
                    printRequest(err.request);
                }
                if(err.response) {
                    printResponse(err.response);
                }
            }
        },
        testSucceeded: function(testCase, test, description, index) {
            endStep(true);
        },
        testCaseEnded: function(testCase, file, hasFailures) {},
        runEnded: function(testCaseCount, failureCount, totalTestCount) {
            if(failureCount === 0) {
                console.log(style.bold('ran ' + totalTestCount + ' tests in ' +
                        testCaseCount + ' test cases, all ran with ' +
                        style.green('SUCCESS')));
            } else {
                console.log(style.bold('ran ' + testCaseCount + ' test cases, ' +
                        failureCount + ' of them ' + style.red('FAILED')));
            }
        },
        write: function(message) {
            console.log(message);
        }
    };
};<|endoftext|>