<commit_before>
/**
 * view used to render each row
 */
cdb.admin.RowView = cdb.ui.common.RowView.extend({
  classLabel: 'cdb.admin.RowView',
  events: {
    'click .row_header': 'click_header'
  },

  cellRenderers: {
    'default': '_renderDefault',
    'boolean': '_renderBoolean',
    'number': '_renderNumber'
  },

  initialize: function() {
    var self = this;
    this.elder('initialize');
    this.options.row_header = true;
    this.model.bind('destroy', function() {
      self.trigger('destroyRow');
    })
    this.retrigger('saving', this.model);
    this.retrigger('saved', this.model);
    this.retrigger('savingError', this.model);

  },

  _getRowOptions: function() {
    if(!cdb.admin.RowView.rowOptions) {
       var rowOptions = cdb.admin.RowView.rowOptions= new cdb.admin.RowHeaderDropdown({
        position: 'position',
        template_base: "table/views/table_row_header_options",
        tick: "top",
        horizontal_position: "left",
        tableData: this.getTableView().dataModel
      });
      rowOptions.render();
      this.retrigger('destroyRow', rowOptions);
      this.retrigger('createRow', rowOptions);

    }
    return cdb.admin.RowView.rowOptions;
  },

  click_header: function(e) {
    var rowOptions, tableData, pos, tableOffset, left, top;

    $target = $(e.target);

    tableData = this.getTableView().dataModel;
    if(tableData.isReadOnly()) {
      // if data is read only do not allow
      // to add or remove rows
      return;
    }
    rowOptions = this._getRowOptions();
    e.preventDefault();
    $target.append(rowOptions.el);
    pos = $target.position();

    // xabel: Yep, browser specific code. I'm so sorry for thiw. What's this? 2007?
    if(/Chrome/.test(navigator.appVersion)) {
      left = pos.left + 30;
      top = pos.top + 0;
    } else {
      pos = $target.offset();
      tableOffset = $target.parents('table').offset() || 0;
      left = pos.left - tableOffset.left + 20;
      top = pos.top - tableOffset.top - 15;
    }
    rowOptions.setRow(this.model);
    rowOptions.openAt(left, top);
    this.rowOptions = rowOptions; // to make it testable;
    return false;
  },

  /**
   * return each cell view
   */
  valueView: function(colName, value) {
    if((colName == 'the_geom' || colName == 'the_geom_webmercator' ) &&
      this.getTableView().dataModel.isReadOnly() ) {
      value = 'GeoJSON'
    }
    this.table = this.table || this.getTableView().model;
    var render = '_renderDefault';
    if(colName.length) {
      var colType = this.table.getColumnType(colName);
      render = this.cellRenderers[colType] || render;
    }

    var obj = this[render](value);
    obj.addClass('cell');
    if(cdb.admin.Row.isReservedColumn(colName)) {
      obj.addClass('disabled');
    }
    if(colName === '' && value === '') {
      obj.addClass('row_header');
      //some space
      //TODO: do it with css
      obj.append('    ');
    }
    return obj;
  },

  _renderDefault: function(value) {
    return $('<div>').append(value);
  },

  _renderBoolean: function(value) {
    var v = '';
    if(value === '' || value === null) {
    } else if(value) {
      v = 'true';
    } else {
      v = 'false';
    }
    return $('<div>').append(v);
  },

  _renderNumber: function(value) {
    var d = this._renderDefault(value);
    return d.addClass('number');
  }

});

<commit_msg>row options now get closed when the row lose the focus<commit_after>
/**
 * view used to render each row
 */
cdb.admin.RowView = cdb.ui.common.RowView.extend({
  classLabel: 'cdb.admin.RowView',
  events: {
    'click .row_header': 'click_header',
    // 'mouseout .row_header': 'mouseout_event'
  },

  cellRenderers: {
    'default': '_renderDefault',
    'boolean': '_renderBoolean',
    'number': '_renderNumber'
  },

  initialize: function() {
    var self = this;
    this.elder('initialize');
    _.bindAll(this, 'mouseout_header', 'click_header',
      'mousein_event', 'mouseout_event')
    this.options.row_header = true;
    this.model.bind('destroy', function() {
      self.trigger('destroyRow');
    })
    this.retrigger('saving', this.model);
    this.retrigger('saved', this.model);
    this.retrigger('savingError', this.model);

    this.$el.bind('mouseover', this.mousein_event);
    this.$el.bind('mouseout', this.mouseout_event);

  },
  /**
   * When the mouse steps over the row, mark the attribute 'hasMouse'
   */
  mousein_event: function() {
    this.hasMouse = true;
  },
  /**
   * Here be dragons: this is a hack to be able to detect when
   * the mouse has left a row for real. Mouseout event is not enough,
   * because it gets triggered when you change between tds.
   * It listen for this changes and mark the row as 'unmoused',
   * waiting for another event to step in and mark this row as
   * 'moused' again.
   *
   * @param  {Event} ev
   */
  mouseout_event: function(ev) {
    this.hasMouse = false;
    setTimeout(this.checkDropdownOpen.bind(this),25);
  },
  /**
   * Check if the cursor is not over this row and if the option menu is
   * opened, and if so, clear the menu
   */
  checkDropdownOpen: function() {
    if(!this.hasMouse && this.rowOptions) {
      this.rowOptions.hide();
    }
  },
  _getRowOptions: function() {
    if(!cdb.admin.RowView.rowOptions) {
       var rowOptions = cdb.admin.RowView.rowOptions= new cdb.admin.RowHeaderDropdown({
        position: 'position',
        template_base: "table/views/table_row_header_options",
        tick: "top",
        horizontal_position: "left",
        tableData: this.getTableView().dataModel
      });
      rowOptions.render();
      this.retrigger('destroyRow', rowOptions);
      this.retrigger('createRow', rowOptions);

    }
    return cdb.admin.RowView.rowOptions;
  },
  mouseout_header: function(e) {
    console.log(e);
    console.log(e.currentTarget);
    console.log(e.target);
    if(this.rowOptions) {
      // this.rowOptions.hide();
    }
  },
  click_header: function(e) {
    var rowOptions, tableData, pos, tableOffset, left, top;

    $target = $(e.target);

    tableData = this.getTableView().dataModel;
    if(tableData.isReadOnly()) {
      // if data is read only do not allow
      // to add or remove rows
      return;
    }
    rowOptions = this._getRowOptions();
    e.preventDefault();
    $target.append(rowOptions.el);
    pos = $target.position();

    // xabel: Yep, browser specific code. I'm so sorry for thiw. What's this? 2007?
    if(/Chrome/.test(navigator.appVersion)) {
      left = pos.left + 30;
      top = pos.top + 0;
    } else {
      pos = $target.offset();
      tableOffset = $target.parents('table').offset() || 0;
      left = pos.left - tableOffset.left + 20;
      top = pos.top - tableOffset.top - 15;
    }
    rowOptions.setRow(this.model);
    rowOptions.openAt(left, top);
    this.rowOptions = rowOptions; // to make it testable;
    return false;
  },

  /**
   * return each cell view
   */
  valueView: function(colName, value) {
    if((colName == 'the_geom' || colName == 'the_geom_webmercator' ) &&
      this.getTableView().dataModel.isReadOnly() ) {
      value = 'GeoJSON'
    }
    this.table = this.table || this.getTableView().model;
    var render = '_renderDefault';
    if(colName.length) {
      var colType = this.table.getColumnType(colName);
      render = this.cellRenderers[colType] || render;
    }

    var obj = this[render](value);
    obj.addClass('cell');
    if(cdb.admin.Row.isReservedColumn(colName)) {
      obj.addClass('disabled');
    }
    if(colName === '' && value === '') {
      obj.addClass('row_header');
      //some space
      //TODO: do it with css
      obj.append('    ');
    }
    return obj;
  },

  _renderDefault: function(value) {
    return $('<div>').append(value);
  },

  _renderBoolean: function(value) {
    var v = '';
    if(value === '' || value === null) {
    } else if(value) {
      v = 'true';
    } else {
      v = 'false';
    }
    return $('<div>').append(v);
  },

  _renderNumber: function(value) {
    var d = this._renderDefault(value);
    return d.addClass('number');
  }

});

<|endoftext|>


<commit_before>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

* WARNING: This file is generated by generate_about_tracing_contents.py
*
*        Do not edit directly.
*/

window.FLATTENED = {};
window.FLATTENED_RAW_SCRIPTS = {};
window.FLATTENED['base.event_target'] = true;
window.FLATTENED['ui'] = true;
window.FLATTENED['ui.overlay'] = true;
window.FLATTENED['about_tracing.tracing_controller'] = true;
window.FLATTENED_RAW_SCRIPTS['../third_party/gl-matrix/src/gl-matrix/common.js'] = true;
window.FLATTENED_RAW_SCRIPTS['../third_party/gl-matrix/src/gl-matrix/mat2d.js'] = true;
window.FLATTENED_RAW_SCRIPTS['../third_party/gl-matrix/src/gl-matrix/vec2.js'] = true;
window.FLATTENED['base.gl_matrix'] = true;
window.FLATTENED['base.rect2'] = true;
window.FLATTENED['base.bbox2'] = true;
window.FLATTENED['cc.constants'] = true;
window.FLATTENED['base.range'] = true;
window.FLATTENED['base.sorted_array_utils'] = true;
window.FLATTENED['tracing.model.object_instance'] = true;
window.FLATTENED['cc.layer_impl'] = true;
window.FLATTENED['cc.layer_tree_impl'] = true;
window.FLATTENED['base.quad'] = true;
window.FLATTENED['cc.util'] = true;
window.FLATTENED['cc.layer_tree_host_impl'] = true;
window.FLATTENED['tracing.analysis.util'] = true;
window.FLATTENED['base.guid'] = true;
window.FLATTENED['tracing.selection'] = true;
window.FLATTENED['tracing.analysis.analysis_link'] = true;
window.FLATTENED['tracing.analysis.generic_object_view'] = true;
window.FLATTENED['tracing.analysis.object_snapshot_view'] = true;
window.FLATTENED['ui.drag_handle'] = true;
window.FLATTENED['ui.list_view'] = true;
window.FLATTENED['ui.quad_view_viewport'] = true;
window.FLATTENED['ui.quad_view'] = true;
window.FLATTENED['cc.layer_tree_host_impl_view'] = true;
window.FLATTENED['cc'] = true;
window.FLATTENED['tracing.color_scheme'] = true;
window.FLATTENED['tracing.importer.linux_perf.parser'] = true;
window.FLATTENED['tracing.importer.linux_perf.android_parser'] = true;
window.FLATTENED['tracing.importer.linux_perf.bus_parser'] = true;
window.FLATTENED['tracing.importer.linux_perf.clock_parser'] = true;
window.FLATTENED['tracing.importer.linux_perf.cpufreq_parser'] = true;
window.FLATTENED['tracing.importer.linux_perf.disk_parser'] = true;
window.FLATTENED['tracing.importer.linux_perf.drm_parser'] = true;
window.FLATTENED['tracing.importer.linux_perf.exynos_parser'] = true;
window.FLATTENED['tracing.importer.linux_perf.gesture_parser'] = true;
window.FLATTENED['tracing.importer.linux_perf.i915_parser'] = true;
window.FLATTENED['tracing.importer.linux_perf.kfunc_parser'] = true;
window.FLATTENED['tracing.importer.linux_perf.mali_parser'] = true;
window.FLATTENED['tracing.importer.linux_perf.power_parser'] = true;
window.FLATTENED['tracing.importer.linux_perf.sched_parser'] = true;
window.FLATTENED['tracing.importer.linux_perf.workqueue_parser'] = true;
window.FLATTENED['tracing.filter'] = true;
window.FLATTENED['tracing.model.counter'] = true;
window.FLATTENED['tracing.model.slice'] = true;
window.FLATTENED['tracing.model.cpu'] = true;
window.FLATTENED['tracing.model.time_to_object_instance_map'] = true;
window.FLATTENED['tracing.model.object_collection'] = true;
window.FLATTENED['tracing.model.async_slice_group'] = true;
window.FLATTENED['tracing.model.sample'] = true;
window.FLATTENED['tracing.model.slice_group'] = true;
window.FLATTENED['tracing.model.thread'] = true;
window.FLATTENED['tracing.model.process_base'] = true;
window.FLATTENED['tracing.model.kernel'] = true;
window.FLATTENED['tracing.model.process'] = true;
window.FLATTENED['tracing.model'] = true;
window.FLATTENED['tracing.importer.linux_perf_importer'] = true;
window.FLATTENED['tracing.importer.trace_event_importer'] = true;
window.FLATTENED['tracing.importer.v8.splaytree'] = true;
window.FLATTENED['tracing.importer.v8.codemap'] = true;
window.FLATTENED['tracing.importer.v8.log_reader'] = true;
window.FLATTENED['tracing.importer.v8_log_importer'] = true;
window.FLATTENED['tracing.record_selection_dialog'] = true;
window.FLATTENED['base.settings'] = true;
window.FLATTENED['tracing.analysis.analysis_results'] = true;
window.FLATTENED['tracing.analysis.analyze_counters'] = true;
window.FLATTENED['tracing.analysis.analyze_slices'] = true;
window.FLATTENED['tracing.analysis.analyze_selection'] = true;
window.FLATTENED['tracing.analysis.object_instance_view'] = true;
window.FLATTENED['tracing.analysis.default_object_view'] = true;
window.FLATTENED['tracing.analysis.analysis_view'] = true;
window.FLATTENED['tracing.category_filter_dialog'] = true;
window.FLATTENED['tracing.timeline_viewport'] = true;
window.FLATTENED['base.measuring_stick'] = true;
window.FLATTENED['ui.toggle_button'] = true;
window.FLATTENED['tracing.tracks.track'] = true;
window.FLATTENED['tracing.tracks.container_track'] = true;
window.FLATTENED['tracing.fast_rect_renderer'] = true;
window.FLATTENED['tracing.tracks.canvas_based_track'] = true;
window.FLATTENED['tracing.tracks.slice_track'] = true;
window.FLATTENED['tracing.tracks.cpu_track'] = true;
window.FLATTENED['tracing.tracks.counter_track'] = true;
window.FLATTENED['tracing.tracks.object_instance_track'] = true;
window.FLATTENED['tracing.tracks.slice_group_track'] = true;
window.FLATTENED['tracing.tracks.async_slice_group_track'] = true;
window.FLATTENED['tracing.tracks.thread_track'] = true;
window.FLATTENED['tracing.tracks.process_track'] = true;
window.FLATTENED['tracing.tracks.model_track'] = true;
window.FLATTENED['tracing.tracks.ruler_track'] = true;
window.FLATTENED['tracing.timeline_track_view'] = true;
window.FLATTENED['tracing.find_control'] = true;
window.FLATTENED['tracing.timeline_view'] = true;
window.FLATTENED['about_tracing.profiling_view'] = true;
window.FLATTENED['base'] = true;
<include src="base/event_target.js">
<include src="ui.js">
<include src="ui/overlay.js">
<include src="about_tracing/tracing_controller.js">
<include src="../third_party/gl-matrix/src/gl-matrix/common.js">
<include src="../third_party/gl-matrix/src/gl-matrix/mat2d.js">
<include src="../third_party/gl-matrix/src/gl-matrix/vec2.js">
<include src="base/gl_matrix.js">
<include src="base/rect2.js">
<include src="base/bbox2.js">
<include src="cc/constants.js">
<include src="base/range.js">
<include src="base/sorted_array_utils.js">
<include src="tracing/model/object_instance.js">
<include src="cc/layer_impl.js">
<include src="cc/layer_tree_impl.js">
<include src="base/quad.js">
<include src="cc/util.js">
<include src="cc/layer_tree_host_impl.js">
<include src="tracing/analysis/util.js">
<include src="base/guid.js">
<include src="tracing/selection.js">
<include src="tracing/analysis/analysis_link.js">
<include src="tracing/analysis/generic_object_view.js">
<include src="tracing/analysis/object_snapshot_view.js">
<include src="ui/drag_handle.js">
<include src="ui/list_view.js">
<include src="ui/quad_view_viewport.js">
<include src="ui/quad_view.js">
<include src="cc/layer_tree_host_impl_view.js">
<include src="cc.js">
<include src="tracing/color_scheme.js">
<include src="tracing/importer/linux_perf/parser.js">
<include src="tracing/importer/linux_perf/android_parser.js">
<include src="tracing/importer/linux_perf/bus_parser.js">
<include src="tracing/importer/linux_perf/clock_parser.js">
<include src="tracing/importer/linux_perf/cpufreq_parser.js">
<include src="tracing/importer/linux_perf/disk_parser.js">
<include src="tracing/importer/linux_perf/drm_parser.js">
<include src="tracing/importer/linux_perf/exynos_parser.js">
<include src="tracing/importer/linux_perf/gesture_parser.js">
<include src="tracing/importer/linux_perf/i915_parser.js">
<include src="tracing/importer/linux_perf/kfunc_parser.js">
<include src="tracing/importer/linux_perf/mali_parser.js">
<include src="tracing/importer/linux_perf/power_parser.js">
<include src="tracing/importer/linux_perf/sched_parser.js">
<include src="tracing/importer/linux_perf/workqueue_parser.js">
<include src="tracing/filter.js">
<include src="tracing/model/counter.js">
<include src="tracing/model/slice.js">
<include src="tracing/model/cpu.js">
<include src="tracing/model/time_to_object_instance_map.js">
<include src="tracing/model/object_collection.js">
<include src="tracing/model/async_slice_group.js">
<include src="tracing/model/sample.js">
<include src="tracing/model/slice_group.js">
<include src="tracing/model/thread.js">
<include src="tracing/model/process_base.js">
<include src="tracing/model/kernel.js">
<include src="tracing/model/process.js">
<include src="tracing/model.js">
<include src="tracing/importer/linux_perf_importer.js">
<include src="tracing/importer/trace_event_importer.js">
<include src="tracing/importer/v8/splaytree.js">
<include src="tracing/importer/v8/codemap.js">
<include src="tracing/importer/v8/log_reader.js">
<include src="tracing/importer/v8_log_importer.js">
<include src="tracing/record_selection_dialog.js">
<include src="base/settings.js">
<include src="tracing/analysis/analysis_results.js">
<include src="tracing/analysis/analyze_counters.js">
<include src="tracing/analysis/analyze_slices.js">
<include src="tracing/analysis/analyze_selection.js">
<include src="tracing/analysis/object_instance_view.js">
<include src="tracing/analysis/default_object_view.js">
<include src="tracing/analysis/analysis_view.js">
<include src="tracing/category_filter_dialog.js">
<include src="tracing/timeline_viewport.js">
<include src="base/measuring_stick.js">
<include src="ui/toggle_button.js">
<include src="tracing/tracks/track.js">
<include src="tracing/tracks/container_track.js">
<include src="tracing/fast_rect_renderer.js">
<include src="tracing/tracks/canvas_based_track.js">
<include src="tracing/tracks/slice_track.js">
<include src="tracing/tracks/cpu_track.js">
<include src="tracing/tracks/counter_track.js">
<include src="tracing/tracks/object_instance_track.js">
<include src="tracing/tracks/slice_group_track.js">
<include src="tracing/tracks/async_slice_group_track.js">
<include src="tracing/tracks/thread_track.js">
<include src="tracing/tracks/process_track.js">
<include src="tracing/tracks/model_track.js">
<include src="tracing/tracks/ruler_track.js">
<include src="tracing/timeline_track_view.js">
<include src="tracing/find_control.js">
<include src="tracing/timeline_view.js">
<include src="about_tracing/profiling_view.js">
<include src="base.js">

var tracingController;
var profilingView;  // Made global for debugging purposes only.

document.addEventListener('DOMContentLoaded', function() {
  tracingController = new about_tracing.TracingController(
      chrome.send.bind(chrome));

  profilingView = document.body.querySelector('#profiling-view');
  ui.decorate(profilingView, about_tracing.ProfilingView);
  profilingView.tracingController = tracingController;
});
<commit_msg>Regenerate about_tracing with right base ordering<commit_after>// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

/**
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

* WARNING: This file is generated by generate_about_tracing_contents.py
*
*        Do not edit directly.
*/

window.FLATTENED = {};
window.FLATTENED_RAW_SCRIPTS = {};
window.FLATTENED['base'] = true;
window.FLATTENED['base.event_target'] = true;
window.FLATTENED['ui'] = true;
window.FLATTENED['ui.overlay'] = true;
window.FLATTENED['about_tracing.tracing_controller'] = true;
window.FLATTENED_RAW_SCRIPTS['../third_party/gl-matrix/src/gl-matrix/common.js'] = true;
window.FLATTENED_RAW_SCRIPTS['../third_party/gl-matrix/src/gl-matrix/mat2d.js'] = true;
window.FLATTENED_RAW_SCRIPTS['../third_party/gl-matrix/src/gl-matrix/vec2.js'] = true;
window.FLATTENED['base.gl_matrix'] = true;
window.FLATTENED['base.rect2'] = true;
window.FLATTENED['base.bbox2'] = true;
window.FLATTENED['cc.constants'] = true;
window.FLATTENED['base.range'] = true;
window.FLATTENED['base.sorted_array_utils'] = true;
window.FLATTENED['tracing.model.object_instance'] = true;
window.FLATTENED['cc.layer_impl'] = true;
window.FLATTENED['cc.layer_tree_impl'] = true;
window.FLATTENED['base.quad'] = true;
window.FLATTENED['cc.util'] = true;
window.FLATTENED['cc.layer_tree_host_impl'] = true;
window.FLATTENED['tracing.analysis.util'] = true;
window.FLATTENED['base.guid'] = true;
window.FLATTENED['tracing.selection'] = true;
window.FLATTENED['tracing.analysis.analysis_link'] = true;
window.FLATTENED['tracing.analysis.generic_object_view'] = true;
window.FLATTENED['tracing.analysis.object_snapshot_view'] = true;
window.FLATTENED['ui.drag_handle'] = true;
window.FLATTENED['ui.list_view'] = true;
window.FLATTENED['ui.quad_view_viewport'] = true;
window.FLATTENED['ui.quad_view'] = true;
window.FLATTENED['cc.layer_tree_host_impl_view'] = true;
window.FLATTENED['cc'] = true;
window.FLATTENED['tracing.color_scheme'] = true;
window.FLATTENED['tracing.importer.linux_perf.parser'] = true;
window.FLATTENED['tracing.importer.linux_perf.android_parser'] = true;
window.FLATTENED['tracing.importer.linux_perf.bus_parser'] = true;
window.FLATTENED['tracing.importer.linux_perf.clock_parser'] = true;
window.FLATTENED['tracing.importer.linux_perf.cpufreq_parser'] = true;
window.FLATTENED['tracing.importer.linux_perf.disk_parser'] = true;
window.FLATTENED['tracing.importer.linux_perf.drm_parser'] = true;
window.FLATTENED['tracing.importer.linux_perf.exynos_parser'] = true;
window.FLATTENED['tracing.importer.linux_perf.gesture_parser'] = true;
window.FLATTENED['tracing.importer.linux_perf.i915_parser'] = true;
window.FLATTENED['tracing.importer.linux_perf.kfunc_parser'] = true;
window.FLATTENED['tracing.importer.linux_perf.mali_parser'] = true;
window.FLATTENED['tracing.importer.linux_perf.power_parser'] = true;
window.FLATTENED['tracing.importer.linux_perf.sched_parser'] = true;
window.FLATTENED['tracing.importer.linux_perf.workqueue_parser'] = true;
window.FLATTENED['tracing.filter'] = true;
window.FLATTENED['tracing.model.counter'] = true;
window.FLATTENED['tracing.model.slice'] = true;
window.FLATTENED['tracing.model.cpu'] = true;
window.FLATTENED['tracing.model.time_to_object_instance_map'] = true;
window.FLATTENED['tracing.model.object_collection'] = true;
window.FLATTENED['tracing.model.async_slice_group'] = true;
window.FLATTENED['tracing.model.sample'] = true;
window.FLATTENED['tracing.model.slice_group'] = true;
window.FLATTENED['tracing.model.thread'] = true;
window.FLATTENED['tracing.model.process_base'] = true;
window.FLATTENED['tracing.model.kernel'] = true;
window.FLATTENED['tracing.model.process'] = true;
window.FLATTENED['tracing.model'] = true;
window.FLATTENED['tracing.importer.linux_perf_importer'] = true;
window.FLATTENED['tracing.importer.trace_event_importer'] = true;
window.FLATTENED['tracing.importer.v8.splaytree'] = true;
window.FLATTENED['tracing.importer.v8.codemap'] = true;
window.FLATTENED['tracing.importer.v8.log_reader'] = true;
window.FLATTENED['tracing.importer.v8_log_importer'] = true;
window.FLATTENED['tracing.record_selection_dialog'] = true;
window.FLATTENED['base.settings'] = true;
window.FLATTENED['tracing.analysis.analysis_results'] = true;
window.FLATTENED['tracing.analysis.analyze_counters'] = true;
window.FLATTENED['tracing.analysis.analyze_slices'] = true;
window.FLATTENED['tracing.analysis.analyze_selection'] = true;
window.FLATTENED['tracing.analysis.object_instance_view'] = true;
window.FLATTENED['tracing.analysis.default_object_view'] = true;
window.FLATTENED['tracing.analysis.analysis_view'] = true;
window.FLATTENED['tracing.category_filter_dialog'] = true;
window.FLATTENED['tracing.timeline_viewport'] = true;
window.FLATTENED['base.measuring_stick'] = true;
window.FLATTENED['ui.toggle_button'] = true;
window.FLATTENED['tracing.tracks.track'] = true;
window.FLATTENED['tracing.tracks.container_track'] = true;
window.FLATTENED['tracing.fast_rect_renderer'] = true;
window.FLATTENED['tracing.tracks.canvas_based_track'] = true;
window.FLATTENED['tracing.tracks.slice_track'] = true;
window.FLATTENED['tracing.tracks.cpu_track'] = true;
window.FLATTENED['tracing.tracks.counter_track'] = true;
window.FLATTENED['tracing.tracks.object_instance_track'] = true;
window.FLATTENED['tracing.tracks.slice_group_track'] = true;
window.FLATTENED['tracing.tracks.async_slice_group_track'] = true;
window.FLATTENED['tracing.tracks.thread_track'] = true;
window.FLATTENED['tracing.tracks.process_track'] = true;
window.FLATTENED['tracing.tracks.model_track'] = true;
window.FLATTENED['tracing.tracks.ruler_track'] = true;
window.FLATTENED['tracing.timeline_track_view'] = true;
window.FLATTENED['tracing.find_control'] = true;
window.FLATTENED['tracing.timeline_view'] = true;
window.FLATTENED['about_tracing.profiling_view'] = true;
<include src="base.js">
<include src="base/event_target.js">
<include src="ui.js">
<include src="ui/overlay.js">
<include src="about_tracing/tracing_controller.js">
<include src="../third_party/gl-matrix/src/gl-matrix/common.js">
<include src="../third_party/gl-matrix/src/gl-matrix/mat2d.js">
<include src="../third_party/gl-matrix/src/gl-matrix/vec2.js">
<include src="base/gl_matrix.js">
<include src="base/rect2.js">
<include src="base/bbox2.js">
<include src="cc/constants.js">
<include src="base/range.js">
<include src="base/sorted_array_utils.js">
<include src="tracing/model/object_instance.js">
<include src="cc/layer_impl.js">
<include src="cc/layer_tree_impl.js">
<include src="base/quad.js">
<include src="cc/util.js">
<include src="cc/layer_tree_host_impl.js">
<include src="tracing/analysis/util.js">
<include src="base/guid.js">
<include src="tracing/selection.js">
<include src="tracing/analysis/analysis_link.js">
<include src="tracing/analysis/generic_object_view.js">
<include src="tracing/analysis/object_snapshot_view.js">
<include src="ui/drag_handle.js">
<include src="ui/list_view.js">
<include src="ui/quad_view_viewport.js">
<include src="ui/quad_view.js">
<include src="cc/layer_tree_host_impl_view.js">
<include src="cc.js">
<include src="tracing/color_scheme.js">
<include src="tracing/importer/linux_perf/parser.js">
<include src="tracing/importer/linux_perf/android_parser.js">
<include src="tracing/importer/linux_perf/bus_parser.js">
<include src="tracing/importer/linux_perf/clock_parser.js">
<include src="tracing/importer/linux_perf/cpufreq_parser.js">
<include src="tracing/importer/linux_perf/disk_parser.js">
<include src="tracing/importer/linux_perf/drm_parser.js">
<include src="tracing/importer/linux_perf/exynos_parser.js">
<include src="tracing/importer/linux_perf/gesture_parser.js">
<include src="tracing/importer/linux_perf/i915_parser.js">
<include src="tracing/importer/linux_perf/kfunc_parser.js">
<include src="tracing/importer/linux_perf/mali_parser.js">
<include src="tracing/importer/linux_perf/power_parser.js">
<include src="tracing/importer/linux_perf/sched_parser.js">
<include src="tracing/importer/linux_perf/workqueue_parser.js">
<include src="tracing/filter.js">
<include src="tracing/model/counter.js">
<include src="tracing/model/slice.js">
<include src="tracing/model/cpu.js">
<include src="tracing/model/time_to_object_instance_map.js">
<include src="tracing/model/object_collection.js">
<include src="tracing/model/async_slice_group.js">
<include src="tracing/model/sample.js">
<include src="tracing/model/slice_group.js">
<include src="tracing/model/thread.js">
<include src="tracing/model/process_base.js">
<include src="tracing/model/kernel.js">
<include src="tracing/model/process.js">
<include src="tracing/model.js">
<include src="tracing/importer/linux_perf_importer.js">
<include src="tracing/importer/trace_event_importer.js">
<include src="tracing/importer/v8/splaytree.js">
<include src="tracing/importer/v8/codemap.js">
<include src="tracing/importer/v8/log_reader.js">
<include src="tracing/importer/v8_log_importer.js">
<include src="tracing/record_selection_dialog.js">
<include src="base/settings.js">
<include src="tracing/analysis/analysis_results.js">
<include src="tracing/analysis/analyze_counters.js">
<include src="tracing/analysis/analyze_slices.js">
<include src="tracing/analysis/analyze_selection.js">
<include src="tracing/analysis/object_instance_view.js">
<include src="tracing/analysis/default_object_view.js">
<include src="tracing/analysis/analysis_view.js">
<include src="tracing/category_filter_dialog.js">
<include src="tracing/timeline_viewport.js">
<include src="base/measuring_stick.js">
<include src="ui/toggle_button.js">
<include src="tracing/tracks/track.js">
<include src="tracing/tracks/container_track.js">
<include src="tracing/fast_rect_renderer.js">
<include src="tracing/tracks/canvas_based_track.js">
<include src="tracing/tracks/slice_track.js">
<include src="tracing/tracks/cpu_track.js">
<include src="tracing/tracks/counter_track.js">
<include src="tracing/tracks/object_instance_track.js">
<include src="tracing/tracks/slice_group_track.js">
<include src="tracing/tracks/async_slice_group_track.js">
<include src="tracing/tracks/thread_track.js">
<include src="tracing/tracks/process_track.js">
<include src="tracing/tracks/model_track.js">
<include src="tracing/tracks/ruler_track.js">
<include src="tracing/timeline_track_view.js">
<include src="tracing/find_control.js">
<include src="tracing/timeline_view.js">
<include src="about_tracing/profiling_view.js">

var tracingController;
var profilingView;  // Made global for debugging purposes only.

document.addEventListener('DOMContentLoaded', function() {
  tracingController = new about_tracing.TracingController(
      chrome.send.bind(chrome));

  profilingView = document.body.querySelector('#profiling-view');
  ui.decorate(profilingView, about_tracing.ProfilingView);
  profilingView.tracingController = tracingController;
});
<|endoftext|>


<commit_before>angular.module(
    "diceApp",
    [
        "ngWebSocket"
    ]
    )
    .factory("IncomingThrows", function ($websocket) {
        var dataStream = $websocket('ws://' + window.location.hostname + ':3001/throws');
        var throws = [];

        dataStream.onMessage(function (message) {
            throws.push(JSON.parse(message.data));
        });
        return {
            throws: throws
        }
    })
    .service('nameService', function () {
        return {
            playerName: "John Doe"
        }
    })
    .controller("NameController", function ($scope, nameService) {
        $scope.$watch(
            function () {
                return $scope.playerName
            },
            function (newValue) {
                nameService.playerName = newValue
            }
        )
    })
    .controller("DiceSelectionController", function ($scope, nameService, IncomingThrows) {
        var diceSelection = this;
        diceSelection.types = [
            "ability",
            "boost",
            "challenge",
            "difficulty",
            "force",
            "proficiency",
            "setback"
        ];
        diceSelection.selected = {
            ability: 0,
            boost: 0,
            challenge: 0,
            difficulty: 0,
            force: 0,
            proficiency: 0,
            setback: 0
        };
        diceSelection.selectDice = function (typeName, index) {
            diceSelection.selected[typeName] = index + 1;
        };
        diceSelection.selectedDice = function (dieType) {
            return _.range(0, diceSelection.selected[dieType])
        };
        diceSelection.unselectedDice = function (dieType) {
            return _.range(diceSelection.selected[dieType], 5)
        };
        diceSelection.resetAll = function () {
            diceSelection.selected.ability = 0;
            diceSelection.selected.boost = 0;
            diceSelection.selected.challenge = 0;
            diceSelection.selected.difficulty = 0;
            diceSelection.selected.force = 0;
            diceSelection.selected.proficiency = 0;
            diceSelection.selected.setback = 0;
        };
        diceSelection.roll = function () {
            console.log(nameService.playerName + " rolls")
        };
    });
<commit_msg>Implement sending throws from client to server<commit_after>/**
 * @param route Part of the URI after the host name and port, including "/"
 * @returns {WebSocket}
 */
var createWebSocket = function (route) {
    return new WebSocket('ws://' + window.location.hostname + ':3001' + route)
};
angular.module(
    "diceApp",
    [
        "ngWebSocket"
    ]
    )
    .factory("IncomingThrows", function ($websocket) {
        var dataStream = createWebSocket("/newThrows");
        var throws = [];

        dataStream.onmessage = function (message) {
            var items = JSON.parse(message.data);
            throws.push(items);
            console.log("incoming message:");
            console.log(items)
        };

        return {
            throws: throws
        }
    })
    .service('history', function () {
        return {
            throwResults: []
        }
    })
    .service('nameService', function () {
        return {
            playerName: "John Doe"
        }
    })
    .controller("NameController", function ($scope, nameService) {
        $scope.$watch(
            function () {
                return $scope.playerName
            },
            function (newValue) {
                nameService.playerName = newValue
            }
        )
    })
    .controller("DiceSelectionController", function ($scope, nameService, IncomingThrows, history) {
        var diceSelection = this;
        diceSelection.types = [
            "ability",
            "boost",
            "challenge",
            "difficulty",
            "force",
            "proficiency",
            "setback"
        ];
        diceSelection.selected = {
            ability: 0,
            boost: 0,
            challenge: 0,
            difficulty: 0,
            force: 0,
            proficiency: 0,
            setback: 0
        };
        diceSelection.selectDice = function (typeName, index) {
            diceSelection.selected[typeName] = index + 1;
        };
        diceSelection.selectedDice = function (dieType) {
            return _.range(0, diceSelection.selected[dieType])
        };
        diceSelection.unselectedDice = function (dieType) {
            return _.range(diceSelection.selected[dieType], 5)
        };
        diceSelection.resetAll = function () {
            diceSelection.selected.ability = 0;
            diceSelection.selected.boost = 0;
            diceSelection.selected.challenge = 0;
            diceSelection.selected.difficulty = 0;
            diceSelection.selected.force = 0;
            diceSelection.selected.proficiency = 0;
            diceSelection.selected.setback = 0;
        };

        diceSelection.roll = function () {
            var webSocket = createWebSocket("/roll");
            webSocket.onopen = function () {
                webSocket.send(JSON.stringify(diceSelection.selected));
            };
            webSocket.onmessage = function (event) {
                var thorResultsFromServer = JSON.parse(event.data);
                history.throwResults = history.throwResults.concat(thorResultsFromServer);
                webSocket.close()
            };
            console.log(nameService.playerName + " rolls");
        };
    });
<|endoftext|>


<commit_before>/** Connexion **/

function verifyToken(){
    $.get(App.baseUri+'/token/verify?token='+getUserToken())
        .done(function (response) {
            if (response.data === true){
                $('#menu_login').text('Espace membre');
                $('#menu_logout').css("display", "block");
                getUserInfos();
                verrifAdressPerso();
                addFavorite();

            }
            $("#menu_login").click(function () {
                showMyAccount();
            });
        });
}

function verrifAdressPerso(){
    var inputDesc = $('#account-addFavorite-desc');
    var inputAdress = $('#account-addFavorite-address');

     inputDesc.keyup(function() {
         if( inputDesc.val() !== '' && inputAdress.val() !== ''){
             $('.save-button').removeClass('disabled');

         }else {
             $('.save-button').addClass('disabled');

         }
     });

    inputAdress.keyup(function() {
        if( inputDesc.val() !== '' && inputAdress.val() !== ''){
            $('.save-button').removeClass('disabled');
        }else {
            $('.save-button').addClass('disabled');
        }
    });
}

function addFavorite(){
    var address = $('#account-addFavorite-address').val();
    var description = $('#account-addFavorite-desc').val();

    if (address !== '' && description !== ''){
        $.ajax({
            url : App.baseUri+'/user/favorite',
            type : 'POST',
            data : 'address='+address + '&description='+ description + '&token='+getUserToken(),
            dataType : 'JSON',
            success : function(data){
                console.log(data + 'succes');
            },
            error : function(data){
                console.log(data + 'erreur');
                $('.error-container').fadeIn();
            },
        });
    }
}

function showMyAccount() {
    $(".connexion-container").fadeOut();
    $("#main-title").fadeOut();
    $(".myAccount-container").fadeIn("slow");
    $("#login").fadeIn();
}

var xhrFavorites = null;
function fetchUserFavorites(callback) {
    if (typeof xhrFavorites === XMLHttpRequest) {
        xhrFavorites.abort();
    }

    xhrFavorites = new XMLHttpRequest();
    xhrFavorites.open('GET', App.baseUri+'/user/favorites?token='+getUserToken());
    xhrFavorites.onload = function() {
        var json = JSON.parse(xhrFavorites.responseText);

        callback(json);
    };
    xhrFavorites.send();
}
var entityMap = {
    '&': '&',
    '<': '<',
    '>': '>',
    '"': '"',
    "'": ''',
    '/': '/',
    '`': '`',
    '=': '='
};

function escapeHtml (string) {
    return String(string).replace(/[&<>"'`=\/]/g, function (s) {
        return entityMap[s];
    });
}

function createFavoriteElement(address, description) {
    address = escapeHtml(address);
    description = escapeHtml(description);

     return "
" +
         "<button type='button' title='" + address + "' class='col-lg-3 col-md-3 col-sm-3 btn btn-primary address-btn' data-address='" + address + "'> " +
         "" +
         "</button>" +
         "
" + description +"
"+
         "
";
}

function createFavoriteElements(data) {
    var elements = '';
    for (var i in data) {
        elements += createFavoriteElement(data[i].address, data[i].description);
    }

    return elements;
}

var google = null;
function onSignIn(googleUser) {
    google = googleUser;
    var id_token = googleUser.getAuthResponse().id_token;
    var xhr = new XMLHttpRequest();

    xhr.open('POST', App.baseUri+'/login');
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onload = function() {
        var json = JSON.parse(xhr.responseText);

        var a = getUserToken();
        createCookieAuthToken(json.data.token);
        if (a.length === 0 && getUserToken().length > 0) {
            document.location.reload();
        }
    };
    xhr.send('token=' + id_token+'&email='+googleUser.getBasicProfile().getEmail());
}

const AUTH_COOKIE_NAME = 'anatroc.auth.token';
const USER_INFO_KEY = 'user.info';

function createCookieAuthToken(token) {
    var d = new Date();

    d.setTime(d.getTime() + (14*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = AUTH_COOKIE_NAME + "=" + token + ";" + expires + ";path=/";
}

function getUserToken() {
    var name = AUTH_COOKIE_NAME + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');

    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

function getUserInfos() {
    $.get(App.baseUri+'/user/info?token='+getUserToken())
        .done(function (response) {
            var email = response.data.email;
            var n = email.indexOf('@');
            var name = email.substring(0, n != -1 ? n : email.length);

            $('.login-container').fadeIn();

            $('#nameAccount').text(name);
        });
}

function responseApiHasError(response) {
    return typeof response.hasOwnProperty('errors') && response.errors.length > 0;
}

function logout(){
    google.disconnect();

    $.ajax({
        url : App.baseUri+'/logout',
        type : 'POST',
        data : 'token='+getUserToken(),
        dataType : 'JSON',
        success : function(data){
            delete_cookie('anatroc.auth.token');
            document.location.reload();
        },
        error : function(data){
            console.log(data + 'erreur');
            $('.error-container').fadeIn();
        },
    });
}

var delete_cookie = function(name) {
    document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
};

$(function () {

    verifyToken();
    fetchUserFavorites(function (response) {
        if (!responseApiHasError(response)) {
            $("#favorites").append(createFavoriteElements(response.data));
        }
    });
    //
    $("#favorites").on('click', 'button', function () {
        var favorite = $(this).data('address');
        var fromInput = $("#search-input-from");

        if (($.trim(fromInput.val())).length === 0) {
            fromInput.val(favorite);
            return;
        }

        var toInput = $("#search-input-to");

        if (($.trim(toInput.val())).length === 0) {
            toInput.val(favorite);
            return;
        }
    });

    $('#button-connect').on("click", function () {
        showMyAccount();
    });

    $('#menu_logout').on("click", function () {
        logout();
        delete_cookie('anatroc.auth.token');
    });

});<commit_msg>Retablissement de la classe pour la génération bouton favori<commit_after>/** Connexion **/

function verifyToken(){
    $.get(App.baseUri+'/token/verify?token='+getUserToken())
        .done(function (response) {
            if (response.data === true){
                $('#menu_login').text('Espace membre');
                $('#menu_logout').css("display", "block");
                getUserInfos();
                verrifAdressPerso();
                addFavorite();

            }
            $("#menu_login").click(function () {
                showMyAccount();
            });
        });
}

function verrifAdressPerso(){
    var inputDesc = $('#account-addFavorite-desc');
    var inputAdress = $('#account-addFavorite-address');

     inputDesc.keyup(function() {
         if( inputDesc.val() !== '' && inputAdress.val() !== ''){
             $('.save-button').removeClass('disabled');

         }else {
             $('.save-button').addClass('disabled');

         }
     });

    inputAdress.keyup(function() {
        if( inputDesc.val() !== '' && inputAdress.val() !== ''){
            $('.save-button').removeClass('disabled');
        }else {
            $('.save-button').addClass('disabled');
        }
    });
}

function addFavorite(){
    var address = $('#account-addFavorite-address').val();
    var description = $('#account-addFavorite-desc').val();

    if (address !== '' && description !== ''){
        $.ajax({
            url : App.baseUri+'/user/favorite',
            type : 'POST',
            data : 'address='+address + '&description='+ description + '&token='+getUserToken(),
            dataType : 'JSON',
            success : function(data){
                console.log(data + 'succes');
            },
            error : function(data){
                console.log(data + 'erreur');
                $('.error-container').fadeIn();
            },
        });
    }
}

function showMyAccount() {
    $(".connexion-container").fadeOut();
    $("#main-title").fadeOut();
    $(".myAccount-container").fadeIn("slow");
    $("#login").fadeIn();
}

var xhrFavorites = null;
function fetchUserFavorites(callback) {
    if (typeof xhrFavorites === XMLHttpRequest) {
        xhrFavorites.abort();
    }

    xhrFavorites = new XMLHttpRequest();
    xhrFavorites.open('GET', App.baseUri+'/user/favorites?token='+getUserToken());
    xhrFavorites.onload = function() {
        var json = JSON.parse(xhrFavorites.responseText);

        callback(json);
    };
    xhrFavorites.send();
}
var entityMap = {
    '&': '&',
    '<': '<',
    '>': '>',
    '"': '"',
    "'": ''',
    '/': '/',
    '`': '`',
    '=': '='
};

function escapeHtml (string) {
    return String(string).replace(/[&<>"'`=\/]/g, function (s) {
        return entityMap[s];
    });
}

function createFavoriteElement(address, description) {
    address = escapeHtml(address);
    description = escapeHtml(description);

     return "
" +
         "<button type='button' title='" + address + "' class='col-lg-3 col-md-3 col-sm-3 btn btn-favorite address-btn' data-address='" + address + "'> " +
         "" +
         "</button>" +
         "
" + description +"
"+
         "
";
}

function createFavoriteElements(data) {
    var elements = '';
    for (var i in data) {
        elements += createFavoriteElement(data[i].address, data[i].description);
    }

    return elements;
}

var google = null;
function onSignIn(googleUser) {
    google = googleUser;
    var id_token = googleUser.getAuthResponse().id_token;
    var xhr = new XMLHttpRequest();

    xhr.open('POST', App.baseUri+'/login');
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.onload = function() {
        var json = JSON.parse(xhr.responseText);

        var a = getUserToken();
        createCookieAuthToken(json.data.token);
        if (a.length === 0 && getUserToken().length > 0) {
            document.location.reload();
        }
    };
    xhr.send('token=' + id_token+'&email='+googleUser.getBasicProfile().getEmail());
}

const AUTH_COOKIE_NAME = 'anatroc.auth.token';
const USER_INFO_KEY = 'user.info';

function createCookieAuthToken(token) {
    var d = new Date();

    d.setTime(d.getTime() + (14*24*60*60*1000));
    var expires = "expires="+ d.toUTCString();
    document.cookie = AUTH_COOKIE_NAME + "=" + token + ";" + expires + ";path=/";
}

function getUserToken() {
    var name = AUTH_COOKIE_NAME + "=";
    var decodedCookie = decodeURIComponent(document.cookie);
    var ca = decodedCookie.split(';');

    for(var i = 0; i <ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

function getUserInfos() {
    $.get(App.baseUri+'/user/info?token='+getUserToken())
        .done(function (response) {
            var email = response.data.email;
            var n = email.indexOf('@');
            var name = email.substring(0, n != -1 ? n : email.length);

            $('.login-container').fadeIn();

            $('#nameAccount').text(name);
        });
}

function responseApiHasError(response) {
    return typeof response.hasOwnProperty('errors') && response.errors.length > 0;
}

function logout(){
    google.disconnect();

    $.ajax({
        url : App.baseUri+'/logout',
        type : 'POST',
        data : 'token='+getUserToken(),
        dataType : 'JSON',
        success : function(data){
            delete_cookie('anatroc.auth.token');
            document.location.reload();
        },
        error : function(data){
            console.log(data + 'erreur');
            $('.error-container').fadeIn();
        },
    });
}

var delete_cookie = function(name) {
    document.cookie = name + '=;expires=Thu, 01 Jan 1970 00:00:01 GMT;';
};

$(function () {

    verifyToken();
    fetchUserFavorites(function (response) {
        if (!responseApiHasError(response)) {
            $("#favorites").append(createFavoriteElements(response.data));
        }
    });
    //
    $("#favorites").on('click', 'button', function () {
        var favorite = $(this).data('address');
        var fromInput = $("#search-input-from");

        if (($.trim(fromInput.val())).length === 0) {
            fromInput.val(favorite);
            return;
        }

        var toInput = $("#search-input-to");

        if (($.trim(toInput.val())).length === 0) {
            toInput.val(favorite);
            return;
        }
    });

    $('#button-connect').on("click", function () {
        showMyAccount();
    });

    $('#menu_logout').on("click", function () {
        logout();
        delete_cookie('anatroc.auth.token');
    });

});<|endoftext|>


<commit_before>import request from 'request';
import fs from 'fs';
import Promise from 'bluebird';
import mkdirp from 'mkdirp';
import rimraf from 'rimraf';
import crypto from 'crypto';
import { PassThrough } from 'stream';
import PBError from './PBError';
import Step from './Step';

const rm = Promise.promisify(rimraf);
const mkdir = Promise.promisify(mkdirp);
const OUT_DIR = '.package-bundle';

export default class Downloader extends Step {
  static cleanUp() {
    return rm(OUT_DIR);
  }

  constructor(args) {
    super(args, 2, 'Downloading packages');
    this.args = args;
    this.totalSize = 0;
  }

  init(downloads) {
    super.init(downloads.size);
    this.downloads = downloads;

    return Promise.map(
      this.downloads.entries(),
      ([/* key */, { name, version, dist }]) => this.getPackage(name, version, dist),
      { concurrency: this.args.concurrency || 50 }
    )
      .then(() => this.complete('Downloaded packages'));
  }

  getPackage(pkg, version, { shasum, tarball }) {
    const tarballUri = tarball ? tarball.replace(/https:\/\/registry.npmjs.org/i, 'http://registry.npmjs.org') : tarball;
    const outDir = this.args.archive ? OUT_DIR : OUT_DIR.substring(1);
    const folder = this.args.flat ? outDir : `${outDir}/${pkg}/-`;
    const proxy = this.args.proxy || null;
    const stripped = pkg.includes('/') && (this.args.flat ? pkg.replace('/', '-') : pkg.split('/')[1]);
    const strippedName = stripped || pkg;
    const hash = crypto.createHash('sha1');
    hash.setEncoding('hex');
    return mkdir(folder)
      .then(() => new Promise((resolve, reject) => {
        const hashPass = new PassThrough; // eslint-disable-line

        hashPass
          .pipe(hash)
          .on('finish', () => {
            const hashResult = hash.read();
            if (hashResult !== shasum) {
              reject(new PBError(`sha1 hashes do not match for ${pkg}@${version}\nDownloaded (${hashResult})} does not equal provided (${shasum})`));
            } else {
              this.tick(1);
              resolve();
            }
          });
        request.get(tarballUri, { proxy })
          .on('error', () => reject())
          .on('response', (res) => {
            const size = parseInt(res.headers['content-length'], 10);
            this.totalSize += size;
          })
          .pipe(hashPass)
          .pipe(fs.createWriteStream(`${folder}/${strippedName}-${version}.tgz`));
      }));
  }
}
<commit_msg>Revert "Downloader uses http registry instead of https"<commit_after>import request from 'request';
import fs from 'fs';
import Promise from 'bluebird';
import mkdirp from 'mkdirp';
import rimraf from 'rimraf';
import crypto from 'crypto';
import { PassThrough } from 'stream';
import PBError from './PBError';
import Step from './Step';

const rm = Promise.promisify(rimraf);
const mkdir = Promise.promisify(mkdirp);
const OUT_DIR = '.package-bundle';

export default class Downloader extends Step {
  static cleanUp() {
    return rm(OUT_DIR);
  }

  constructor(args) {
    super(args, 2, 'Downloading packages');
    this.args = args;
    this.totalSize = 0;
  }

  init(downloads) {
    super.init(downloads.size);
    this.downloads = downloads;

    return Promise.map(
      this.downloads.entries(),
      ([/* key */, { name, version, dist }]) => this.getPackage(name, version, dist),
      { concurrency: this.args.concurrency || 50 }
    )
      .then(() => this.complete('Downloaded packages'));
  }

  getPackage(pkg, version, { shasum, tarball }) {
    const outDir = this.args.archive ? OUT_DIR : OUT_DIR.substring(1);
    const folder = this.args.flat ? outDir : `${outDir}/${pkg}/-`;
    const proxy = this.args.proxy || null;
    const stripped = pkg.includes('/') && (this.args.flat ? pkg.replace('/', '-') : pkg.split('/')[1]);
    const strippedName = stripped || pkg;
    const hash = crypto.createHash('sha1');
    hash.setEncoding('hex');
    return mkdir(folder)
      .then(() => new Promise((resolve, reject) => {
        const hashPass = new PassThrough; // eslint-disable-line

        hashPass
          .pipe(hash)
          .on('finish', () => {
            const hashResult = hash.read();
            if (hashResult !== shasum) {
              reject(new PBError(`sha1 hashes do not match for ${pkg}@${version}\nDownloaded (${hashResult})} does not equal provided (${shasum})`));
            } else {
              this.tick(1);
              resolve();
            }
          });
        request.get(tarball, { proxy })
          .on('error', () => reject())
          .on('response', (res) => {
            const size = parseInt(res.headers['content-length'], 10);
            this.totalSize += size;
          })
          .pipe(hashPass)
          .pipe(fs.createWriteStream(`${folder}/${strippedName}-${version}.tgz`));
      }));
  }
}
<|endoftext|>


<commit_before>// Dep: [KadOH]/globals
// Dep: [KadOH]/util/crypto
// Dep: [KadOH]/kbucket
// Dep: [KadOH]/peerarray
// Dep: [KadOH]/peer
// Dep: [KadOH]/core/eventemitter

(function(exports) {

  var KadOH        = exports,
      Crypto       = KadOH.util.Crypto,
      KBucket      = KadOH.KBucket,
      Peer         = KadOH.Peer,
      PeerArray    = KadOH.PeerArray,
      globals      = KadOH.globals,
      EventEmitter = KadOH.core.EventEmitter;

  /**
   * Represents the routing table of a {@link Node}.
   * @name RoutingTable
   * @augments EventEmitter
   * @class
   */
  KadOH.RoutingTable = EventEmitter.extend(
    /** @lends RoutingTable# */
    {
    /**
     * Construct an instance of a {@link RoutingTable} associated to the instance of {@link Node} passed as parameter.
     * @xclass Represents the routing table of a {@link Node}.
     * @xaugments EventEmitter
     * @constructs
     * @param {Node} node - Associated node.
     */
    initialize: function(node) {
      this.supr();
      this._node = node;
      this._parentID = ('string' === typeof node) ? node : node.getID();
      this._kbuckets = [new KBucket(this)];
    },

    // Public

    /**
     * Stop the routing table engine :
     *   - stop all refreshTimout for  KBuckets
     * @public
     * @return {this}
     */
    stop: function() {
      for (var i = 0, l = this._kbuckets.length; i < l; i++) {
        this._kbuckets[i].stopRefreshTimeout();
      }
      return this;
    },

    /**
     * Calculates the distance from 0 to B-1 between the parent `id` and the given `key`.
     * These keys are SHA1 hashes as hexadecimal `String`
     * @see {@link Crypto#distance}
     *
     * @param {String} key
     * @return {String} distance between the two keys
     * @public
     */
    distance: function(peer) {
      var dist;
      if (peer instanceof Peer) {
        dist = peer.getDistance();
        if (!dist) {
          peer.cacheDistance(this._parentID);
          dist = peer.getDistance();
        }
      } else {
        dist = Crypto.distance(this._parentID, peer);
      }
      return dist;
    },

    /**
     * Add multiple peers to the routing table
     *
     * @param {Peer[]} peers List of peers to add to the table
     */
    add: function(peers) {
      peers.forEach(function(peer) {
        this.addPeer(peer);
      }, this);
      return this;
    },

    /**
     * Add a peer to the routing table or update it if its already in.
     *
     * @param {Peer} peer object to add
     * @return {Void}
     * @public
     */
    addPeer: function(peer) {
      if (peer.getID() === this._parentID) {
        return;
      }

      peer.cacheDistance(this._parentID);

      var index   = this._kbucketIndexFor(peer),
          kbucket = this._kbuckets[index];

      // find the kbucket for the peer
      try {
        kbucket.addPeer(peer);
        KadOH.log.info('RoutingTable','add peer', peer.getAddress(), peer.getID());
        this.emit('added', peer);
      } catch(e) {
        // if the kbucket is full and splittable
        if (e === 'split') {
          var range = kbucket.getRange();
          this._kbuckets.push(kbucket.split());
          this.emit('splitted');
          KadOH.log.info('RoutingTable','split kbucket', range, kbucket.getRange());
          this.addPeer(peer);
        } else {
          throw e;
        }
      }
      return this;
    },

    /**
     * Get the `number` closest peers from a given `id`
     * but ignore the specified ones in an Array
     *
     * @param {String} id
     * @param {Number} [number = {@link globals.ALPHA}] The number of peers you want
     * @param {String[] | Peer[]} exclude Array of ids or peers to exclude
     */
    getClosePeers: function(id, number, exclude) {
      if (typeof number !== 'number') {
        number = globals.ALPHA;
      }

      // get the default kbucket for this id
      var index         = this._kbucketIndexFor(id),
          kbuckets_left = this.howManyKBuckets() - 1,
          peers         = new PeerArray();

      peers.add(this._kbuckets[index].getPeers(number, exclude));

      // if we don't have enough peers in the default kbucket
      // try to find other ones in the closest kbuckets
      if (peers.length() < number && kbuckets_left > 0) {
        var indexes_path = [],
            i;

        // build an array which values are the kbuckets index
        // sorted by their distance with the default kbucket
        for (i = 0; i < this.howManyKBuckets(); i++) {
          indexes_path[i] = i;
        }
        indexes_path.splice(index, 1);

        if (index > 1) {
          indexes_path.sort(function(a, b) {
            var diff = Math.abs(a - index) - Math.abs(b - index);
            if (diff < 0)
              return -1;
            else if (diff > 0)
              return 1;
            return 0;
          });
        }

        // read through the sorted kbuckets and retrieve the closest peers
        // until we get the good amount
        i = 0;
        while (peers.length() < number && (index = indexes_path[i++])) {
          peers.add(this._kbuckets[index].getPeers(number - peers.length(), exclude));
        }
      }

      return peers;
    },

    getPeer: function(peer) {
      peer = this._kbucketFor(peer).getPeer(peer);
      if (peer) {
        return peer;
      }
      return false;
    },

    removePeer: function(peer) {
      return this._kbucketFor(peer).removePeer(peer);
    },

    getKBuckets: function() {
      return this._kbuckets;
    },

    howManyKBuckets: function() {
      return this._kbuckets.length;
    },

    howManyPeers: function() {
      return this._kbuckets.reduce(function(sum, kbucket) {
        return sum + kbucket.length();
      }, 0);
    },

    getParentID: function() {
      return this._parentID;
    },

    // Private

    /**
     * Find the appropriate KBucket index for a given key
     *
     * @param {String} key SHA1 hash
     * @return {Integer} index for the `_kbuckets`
     * @private
     */
    _kbucketIndexFor: function(peer) {
      var dist = this.distance(peer);
      // if the id is our id, return the splittable kbucket
      if (dist === 0) {
        return this._kbuckets.length - 1;
      }
      // find the kbucket with the distance in range
      for (var i = 0; i < this._kbuckets.length; i++) {
        if (this._kbuckets[i].distanceInRange(dist)) {
          return i;
        }
      }
      return -1;
    },

    _kbucketFor: function(peer) {
      var index = this._kbucketIndexFor(peer);
      if (index !== -1)
        return this._kbuckets[index];
      return false;
    },

    /**
     * Exports the routing table to a serializable object
     *
     * @param {Object}  [options] options hash
     * @param {Boolean} [options.include_lastseen] If true the last_seen
     * paramter will be included in peer triple array
     *
     * @param {Boolean} [options.include_distance] If true the distance
     * paramter will be included in peer triple array
     *
     * @return {Object}
     */
    exports: function(options) {
      var refresh  = Infinity;
      var kbuckets = this._kbuckets.map(function(kbucket) {
        var object = kbucket.exports(options);
        refresh = Math.min(refresh, object.refresh);
        return object;
      });
      return {
        id       : this._parentID,
        kbuckets : kbuckets,
        refresh  : refresh
      };
    },

    /**
     * Imports a previously exported routing table
     * and returns true if the process succeeded
     *
     * @param  {Object} routing_table
     * @return {Boolean}
     */
    imports: function(routing_table) {
      if (routing_table.id !== this._parentID) {
        return false;
      }
      var now = new Date().getTime();
      if (routing_table.refresh < now) {
        return false;
      }

      try {
        var kbuckets = routing_table.kbuckets;
        for (var i = 0, l = kbuckets.length; i < l; i++) {
          var kbucket = new KBucket();
          if (!kbucket.imports(kbuckets[i])) {
            throw new Error();
          }
          this._kbuckets[i] = kbucket;
        }
        return true;
      } catch(e) {
        KadOH.log.fatal('RoutingTable', 'failed to import', routing_table);
        return false;
      }
    }

  });

})('object' === typeof module ? module.exports : (this.KadOH = this.KadOH || {}));
<commit_msg>#start routingTable<commit_after>// Dep: [KadOH]/globals
// Dep: [KadOH]/util/crypto
// Dep: [KadOH]/kbucket
// Dep: [KadOH]/peerarray
// Dep: [KadOH]/peer
// Dep: [KadOH]/core/eventemitter

(function(exports) {

  var KadOH        = exports,
      Crypto       = KadOH.util.Crypto,
      KBucket      = KadOH.KBucket,
      Peer         = KadOH.Peer,
      PeerArray    = KadOH.PeerArray,
      globals      = KadOH.globals,
      EventEmitter = KadOH.core.EventEmitter;

  /**
   * Represents the routing table of a {@link Node}.
   * @name RoutingTable
   * @augments EventEmitter
   * @class
   */
  KadOH.RoutingTable = EventEmitter.extend(
    /** @lends RoutingTable# */
    {
    /**
     * Construct an instance of a {@link RoutingTable} associated to the instance of {@link Node} passed as parameter.
     * @xclass Represents the routing table of a {@link Node}.
     * @xaugments EventEmitter
     * @constructs
     * @param {Node} node - Associated node.
     */
    initialize: function(node) {
      this.supr();
      this._node = node;
      this._parentID = ('string' === typeof node) ? node : node.getID();
      this._kbuckets = [new KBucket(this)];
    },

    // Public

    /**
     * Start the routing table engine :
     *   - start all refreshTimeouts for KBuckets
     * @return {this}
     */
    start: function() {
      this.stop();
      for (var i = 0, l = this._kbuckets.length; i < l; i++) {
        this._kbuckets[i].setRefreshTimeout();
      }
    },

    /**
     * Stop the routing table engine :
     *   - stop all refreshTimout for KBuckets
     * @return {this}
     */
    stop: function() {
      for (var i = 0, l = this._kbuckets.length; i < l; i++) {
        this._kbuckets[i].stopRefreshTimeout();
      }
      return this;
    },

    /**
     * Calculates the distance from 0 to B-1 between the parent `id` and the given `key`.
     * These keys are SHA1 hashes as hexadecimal `String`
     * @see {@link Crypto#distance}
     *
     * @param {String} key
     * @return {String} distance between the two keys
     * @public
     */
    distance: function(peer) {
      var dist;
      if (peer instanceof Peer) {
        dist = peer.getDistance();
        if (!dist) {
          peer.cacheDistance(this._parentID);
          dist = peer.getDistance();
        }
      } else {
        dist = Crypto.distance(this._parentID, peer);
      }
      return dist;
    },

    /**
     * Add multiple peers to the routing table
     *
     * @param {Peer[]} peers List of peers to add to the table
     */
    add: function(peers) {
      peers.forEach(function(peer) {
        this.addPeer(peer);
      }, this);
      return this;
    },

    /**
     * Add a peer to the routing table or update it if its already in.
     *
     * @param {Peer} peer object to add
     * @return {Void}
     * @public
     */
    addPeer: function(peer) {
      if (peer.getID() === this._parentID) {
        return;
      }

      peer.cacheDistance(this._parentID);

      var index   = this._kbucketIndexFor(peer),
          kbucket = this._kbuckets[index];

      // find the kbucket for the peer
      try {
        kbucket.addPeer(peer);
        KadOH.log.info('RoutingTable','add peer', peer.getAddress(), peer.getID());
        this.emit('added', peer);
      } catch(e) {
        // if the kbucket is full and splittable
        if (e === 'split') {
          var range = kbucket.getRange();
          this._kbuckets.push(kbucket.split());
          this.emit('splitted');
          KadOH.log.info('RoutingTable','split kbucket', range, kbucket.getRange());
          this.addPeer(peer);
        } else {
          throw e;
        }
      }
      return this;
    },

    /**
     * Get the `number` closest peers from a given `id`
     * but ignore the specified ones in an Array
     *
     * @param {String} id
     * @param {Number} [number = {@link globals.ALPHA}] The number of peers you want
     * @param {String[] | Peer[]} exclude Array of ids or peers to exclude
     */
    getClosePeers: function(id, number, exclude) {
      if (typeof number !== 'number') {
        number = globals.ALPHA;
      }

      // get the default kbucket for this id
      var index         = this._kbucketIndexFor(id),
          kbuckets_left = this.howManyKBuckets() - 1,
          peers         = new PeerArray();

      peers.add(this._kbuckets[index].getPeers(number, exclude));

      // if we don't have enough peers in the default kbucket
      // try to find other ones in the closest kbuckets
      if (peers.length() < number && kbuckets_left > 0) {
        var indexes_path = [],
            i;

        // build an array which values are the kbuckets index
        // sorted by their distance with the default kbucket
        for (i = 0; i < this.howManyKBuckets(); i++) {
          indexes_path[i] = i;
        }
        indexes_path.splice(index, 1);

        if (index > 1) {
          indexes_path.sort(function(a, b) {
            var diff = Math.abs(a - index) - Math.abs(b - index);
            if (diff < 0)
              return -1;
            else if (diff > 0)
              return 1;
            return 0;
          });
        }

        // read through the sorted kbuckets and retrieve the closest peers
        // until we get the good amount
        i = 0;
        while (peers.length() < number && (index = indexes_path[i++])) {
          peers.add(this._kbuckets[index].getPeers(number - peers.length(), exclude));
        }
      }

      return peers;
    },

    getPeer: function(peer) {
      peer = this._kbucketFor(peer).getPeer(peer);
      if (peer) {
        return peer;
      }
      return false;
    },

    removePeer: function(peer) {
      return this._kbucketFor(peer).removePeer(peer);
    },

    getKBuckets: function() {
      return this._kbuckets;
    },

    howManyKBuckets: function() {
      return this._kbuckets.length;
    },

    howManyPeers: function() {
      return this._kbuckets.reduce(function(sum, kbucket) {
        return sum + kbucket.length();
      }, 0);
    },

    getParentID: function() {
      return this._parentID;
    },

    // Private

    /**
     * Find the appropriate KBucket index for a given key
     *
     * @param {String} key SHA1 hash
     * @return {Integer} index for the `_kbuckets`
     * @private
     */
    _kbucketIndexFor: function(peer) {
      var dist = this.distance(peer);
      // if the id is our id, return the splittable kbucket
      if (dist === 0) {
        return this._kbuckets.length - 1;
      }
      // find the kbucket with the distance in range
      for (var i = 0; i < this._kbuckets.length; i++) {
        if (this._kbuckets[i].distanceInRange(dist)) {
          return i;
        }
      }
      return -1;
    },

    _kbucketFor: function(peer) {
      var index = this._kbucketIndexFor(peer);
      if (index !== -1)
        return this._kbuckets[index];
      return false;
    },

    /**
     * Exports the routing table to a serializable object
     *
     * @param {Object}  [options] options hash
     * @param {Boolean} [options.include_lastseen] If true the last_seen
     * paramter will be included in peer triple array
     *
     * @param {Boolean} [options.include_distance] If true the distance
     * paramter will be included in peer triple array
     *
     * @return {Object}
     */
    exports: function(options) {
      var refresh  = Infinity;
      var kbuckets = this._kbuckets.map(function(kbucket) {
        var object = kbucket.exports(options);
        refresh = Math.min(refresh, object.refresh);
        return object;
      });
      return {
        id       : this._parentID,
        kbuckets : kbuckets,
        refresh  : refresh
      };
    },

    /**
     * Imports a previously exported routing table
     * and returns true if the process succeeded
     *
     * @param  {Object} routing_table
     * @return {Boolean}
     */
    imports: function(routing_table) {
      if (routing_table.id !== this._parentID) {
        return false;
      }
      var now = new Date().getTime();
      if (routing_table.refresh < now) {
        return false;
      }

      try {
        var kbuckets = routing_table.kbuckets;
        for (var i = 0, l = kbuckets.length; i < l; i++) {
          var kbucket = new KBucket();
          if (!kbucket.imports(kbuckets[i])) {
            throw new Error();
          }
          this._kbuckets[i] = kbucket;
        }
        return true;
      } catch(e) {
        KadOH.log.fatal('RoutingTable', 'failed to import', routing_table);
        return false;
      }
    }

  });

})('object' === typeof module ? module.exports : (this.KadOH = this.KadOH || {}));
<|endoftext|>


<commit_before>
(function($){
    var PHPHub = {

        init: function(){
            var self = this;
            $(document).pjax('a:not(a[target="_blank"])', 'body');
            $(document).on('pjax:start', function() {
                NProgress.start();
            });
            $(document).on('pjax:end', function() {
                NProgress.done();
            });
            $(document).on('pjax:complete', function() {
                NProgress.done();
                self.siteBootUp();
            });

            self.siteBootUp();
            self.initLightBox();
            self.initNotificationsCount();
        },

        /*
        * Things to be execute when normal page load
        * and pjax page load.
        */
        siteBootUp: function(){
            var self = this;
            self.initExternalLink();
            self.initTimeAgo();
            self.initEmoji();
            self.initAutocompleteAtUser();
            self.initScrollToTop();
            self.initTextareaAutoResize();
            self.initHeightLight();
            self.initLocalStorage();
            self.initEditorPreview();
            self.initReplyOnPressKey();
            self.initDeleteForm();
            self.initInlineAttach();
            self.snowing();
        },

        /**
         * Open External Links In New Window
         */
        initExternalLink: function(){
            $('a[href^="http://"], a[href^="https://"]').each(function() {
               var a = new RegExp('/' + window.location.host + '/');
               if(!a.test(this.href) ) {
                   $(this).click(function(event) {
                       event.preventDefault();
                       event.stopPropagation();
                       window.open(this.href, '_blank');
                   });
               }
            });
        },

        /**
         * Automatically transform any Date format to human
         * friendly format, all you need to do is add a
         * `.timeago` class.
         */
        initTimeAgo: function(){
            moment.lang('zh-cn');
            $('.timeago').each(function(){
                var time_str = $(this).text();
                if(moment(time_str, "YYYY-MM-DD HH:mm:ss", true).isValid()) {
                    $(this).text(moment(time_str).fromNow());
                }
            });
        },

        /**
         * Enable emoji everywhere.
         */
        initEmoji: function(){
            emojify.setConfig({
                img_dir : Config.cdnDomain + 'assets/images/emoji',
                ignored_tags : {
                    'SCRIPT'  : 1,
                    'TEXTAREA': 1,
                    'A'       : 1,
                    'PRE'     : 1,
                    'CODE'    : 1
                }
            });
            emojify.run();

            $('#reply_content').textcomplete([
                { // emoji strategy
                    match: /\B:([\-+\w]*)$/,
                    search: function (term, callback) {
                        callback($.map(emojies, function (emoji) {
                            return emoji.indexOf(term) === 0 ? emoji : null;
                        }));
                    },
                    template: function (value) {
                        return '' + value;
                    },
                    replace: function (value) {
                        return ':' + value + ': ';
                    },
                    index: 1,
                    maxCount: 5
                }
            ]);
        },

        /**
         * Autocomplete @user
         */
        initAutocompleteAtUser: function() {
            var at_users = [],
                  user;
            $users = $('.media-heading').find('a.author');
            for (var i = 0; i < $users.length; i++) {
                user = $users.eq(i).text().trim();
                if ($.inArray(user, at_users) == -1) {
                    at_users.push(user);
                };
            };

            $('textarea').textcomplete([{
                mentions: at_users,
                match: /\B@(\w*)$/,
                search: function(term, callback) {
                    callback($.map(this.mentions, function(mention) {
                        return mention.indexOf(term) === 0 ? mention : null;
                    }));
                },
                index: 1,
                replace: function(mention) {
                    return '@' + mention + ' ';
                }
            }], {
                appendTo: 'body'
            });

        },

        /**
         * Autoresizing the textarea when you typing.
         */
        initTextareaAutoResize: function(){
            $('textarea').autosize();
        },

        /**
         * Scroll to top in one click.
         */
        initScrollToTop: function(){
            $.scrollUp.init();
        },

        /**
         * Code heightlight.
         */
        initHeightLight: function(){
            Prism.highlightAll();
        },

        /**
         * lightbox
         */
        initLightBox: function(){
            $(document).delegate('.content-body img:not(.emoji)', 'click', function(event) {
                event.preventDefault();
                return $(this).ekkoLightbox({
                    onShown: function() {
                        if (window.console) {
                            // return console.log('Checking our the events huh?');
                        }
                    }
                });
            });
        },

        /**
         * do content preview
         */
        runPreview: function() {
            var replyContent = $("#reply_content");
            var oldContent = replyContent.val();

            if (oldContent) {
                marked(oldContent, function (err, content) {
                  $('#preview-box').html(content);
                  emojify.run(document.getElementById('preview-box'));
                });
            }
        },

        /**
         * Init post content preview
         */
        initEditorPreview: function() {
            var self = this;
            $("#reply_content").focus(function(event) {
                $("#reply_notice").fadeIn(1500);
                $("#preview-box").fadeIn(1500);
                $("#preview-lable").fadeIn(1500);

                if (!$("#reply_content").val()) {
                    $("html, body").animate({ scrollTop: $(document).height()}, 1800);
                }
            });
            $('#reply_content').keyup(function(){
                self.runPreview();
            });
        },

        /**
         * Notify user unread notifications when they stay on the
         * page for too long.
         */
        initNotificationsCount: function(argumen) {
            var original_title = document.title;
            if (Config.user_id > 0) {
                function scheduleGetNotification(){
                    $.get( Config.routes.notificationsCount, function( data ) {
                        var nCount = parseInt(data)
                        if (nCount > 0) {
                            $('#notification-count').text(nCount);
                            $('#notification-count').hasClass('badge-important') || $('#notification-count').addClass('badge-important');
                            document.title = '(' + nCount + ') '+ original_title;
                        } else {
                            document.title =  original_title;
                            $('#notification-count').text(0);
                            $('#notification-count').addClass('badge-fade');
                            $('#notification-count').removeClass('badge-important');

                        }
                        setTimeout(scheduleGetNotification, 15000);
                    });
                };
                setTimeout(scheduleGetNotification, 15000);
            }
        },

        /*
         * Use Ctrl + Enter for reply
         */
        initReplyOnPressKey: function() {
            $(document).on("keydown", "#reply_content", function(e)
            {
                if ((e.keyCode == 10 || e.keyCode == 13) && e.ctrlKey) {
                    $(this).parents("form").submit();
                    return false;
                }
            });
        },

        /*
         * Construct a form when using the following code, makes more clean code.
         *   {{ link_to_route('tasks.destroy', 'D', $task->id, ['data-method'=>'delete']) }}
         * See this answer: http://stackoverflow.com/a/23082278/689832
         */
        initDeleteForm: function() {
            $('[data-method]').append(function(){
                return "\n"+
                "<form action='"+$(this).attr('data-url')+"' method='POST' style='display:none'>\n"+
                "   <input type='hidden' name='_method' value='"+$(this).attr('data-method')+"'>\n"+
                "   <input type='hidden' name='_token' value='"+Config.token+"'>\n"+
                "</form>\n"
                })
                .attr('style','cursor:pointer;')
                .click(function() {
                    if ($(this).attr('data-method') == 'post') {
                        $(this).find("form").submit();
                    }
                    if ($(this).attr('data-method') == 'delete' && confirm("Are you sure want to proceed?")) {
                        $(this).find("form").submit();
                    }
                });
           // attr('onclick',' if (confirm("Are you sure want to proceed?")) { $(this).find("form").submit(); };');
        },

        /**
         * Local Storage
         */
        initLocalStorage: function() {
            var self = this;
            $("#reply_content").focus(function(event) {

                // Topic Title ON Topic Creation View
                localforage.getItem('topic-title', function(err, value) {
                    if ($('.topic_create #topic-title').val() == '' && !err) {
                        $('.topic_create #topic-title').val(value);
                    };
                });
                $('.topic_create #topic-title').keyup(function(){
                    localforage.setItem('topic-title', $(this).val());
                });

                // Topic Content ON Topic Creation View
                localforage.getItem('topic_create_content', function(err, value) {
                    if ($('.topic_create #reply_content').val() == '' && !err) {
                        $('.topic_create #reply_content').val(value);
                        self.runPreview();
                    }
                });
                $('.topic_create #reply_content').keyup(function(){
                    localforage.setItem('topic_create_content', $(this).val());
                });

                // Reply Content ON Topic Detail View
                localforage.getItem('reply_content', function(err, value) {
                    if ($('.topics-show #reply_content').val() == '' && !err) {
                        $('.topics-show #reply_content').val(value);
                        self.runPreview();
                    }
                });
                $('.topics-show #reply_content').keyup(function(){
                    localforage.setItem('reply_content', $(this).val());
                });
            })

            // Clear Local Storage on submit
            $("#topic-create-form").submit(function(event){
                localforage.removeItem('topic_create_content');
                localforage.removeItem('topic-title');
            });
            $("#reply-form").submit(function(event){
                localforage.removeItem('reply_content');
            });
        },

        /**
         * Upload image
         */
        initInlineAttach: function() {
            var self = this;
            $('#reply_content').inlineattach({
                uploadUrl: Config.routes.upload_image,
                extraParams: {
                  '_token': Config.token,
                },
                onUploadedFile: function(response) {
                    setTimeout(self.runPreview, 200);
                },
            });
        },

        /**
         * Snowing around the world
         */
        snowing: function() {

            // only show snow in Christmas
            var today = new Date()
            var christmas = new Date(today.getFullYear(), 11, 25) // Month is 0-11 in JavaScript
            if (today.getMonth() == 11 && (today.getDate() > 22 && today.getDate() < 30))
            {
                $('#body').snowfall({
                    flakeCount: 100,
                    minSize: 2,
                    maxSize:5,
                    round: true
                });
            }
        },

    }
    window.PHPHub = PHPHub;
})(jQuery);

$(document).ready(function()
{
    PHPHub.init();
});

// reply a reply
function replyOne(username){
    replyContent = $("#reply_content");
	oldContent = replyContent.val();
	prefix = "@" + username + " ";
	newContent = ''
	if(oldContent.length > 0){
	    if (oldContent != prefix) {
	        newContent = oldContent + "\n" + prefix;
	    }
	} else {
	    newContent = prefix
	}
	replyContent.focus();
	replyContent.val(newContent);
	moveEnd($("#reply_content"));
}

var moveEnd = function(obj){
	obj.focus();

	var len = obj.value === undefined ? 0 : obj.value.length;

	if (document.selection) {
		var sel = obj.createTextRange();
		sel.moveStart('character',len);
		sel.collapse();
		sel.select();
	} else if (typeof obj.selectionStart == 'number' && typeof obj.selectionEnd == 'number') {
		obj.selectionStart = obj.selectionEnd = len;
	}
}
<commit_msg>fixing init script on pjax back not calling<commit_after>
(function($){
    var PHPHub = {

        init: function(){
            var self = this;
            $(document).pjax('a:not(a[target="_blank"])', 'body');
            $(document).on('pjax:start', function() {
                NProgress.start();
            });
            $(document).on('pjax:end', function() {
                NProgress.done();
                self.siteBootUp();
            });
            $(document).on('pjax:complete', function() {
                NProgress.done();
            });

            self.siteBootUp();
            self.initLightBox();
            self.initNotificationsCount();
        },

        /*
        * Things to be execute when normal page load
        * and pjax page load.
        */
        siteBootUp: function(){
            var self = this;
            self.initExternalLink();
            self.initTimeAgo();
            self.initEmoji();
            self.initAutocompleteAtUser();
            self.initScrollToTop();
            self.initTextareaAutoResize();
            self.initHeightLight();
            self.initLocalStorage();
            self.initEditorPreview();
            self.initReplyOnPressKey();
            self.initDeleteForm();
            self.initInlineAttach();
            self.snowing();
        },

        /**
         * Open External Links In New Window
         */
        initExternalLink: function(){
            $('a[href^="http://"], a[href^="https://"]').each(function() {
               var a = new RegExp('/' + window.location.host + '/');
               if(!a.test(this.href) ) {
                   $(this).click(function(event) {
                       event.preventDefault();
                       event.stopPropagation();
                       window.open(this.href, '_blank');
                   });
               }
            });
        },

        /**
         * Automatically transform any Date format to human
         * friendly format, all you need to do is add a
         * `.timeago` class.
         */
        initTimeAgo: function(){
            moment.lang('zh-cn');
            $('.timeago').each(function(){
                var time_str = $(this).text();
                if(moment(time_str, "YYYY-MM-DD HH:mm:ss", true).isValid()) {
                    $(this).text(moment(time_str).fromNow());
                }
            });
        },

        /**
         * Enable emoji everywhere.
         */
        initEmoji: function(){
            emojify.setConfig({
                img_dir : Config.cdnDomain + 'assets/images/emoji',
                ignored_tags : {
                    'SCRIPT'  : 1,
                    'TEXTAREA': 1,
                    'A'       : 1,
                    'PRE'     : 1,
                    'CODE'    : 1
                }
            });
            emojify.run();

            $('#reply_content').textcomplete([
                { // emoji strategy
                    match: /\B:([\-+\w]*)$/,
                    search: function (term, callback) {
                        callback($.map(emojies, function (emoji) {
                            return emoji.indexOf(term) === 0 ? emoji : null;
                        }));
                    },
                    template: function (value) {
                        return '' + value;
                    },
                    replace: function (value) {
                        return ':' + value + ': ';
                    },
                    index: 1,
                    maxCount: 5
                }
            ]);
        },

        /**
         * Autocomplete @user
         */
        initAutocompleteAtUser: function() {
            var at_users = [],
                  user;
            $users = $('.media-heading').find('a.author');
            for (var i = 0; i < $users.length; i++) {
                user = $users.eq(i).text().trim();
                if ($.inArray(user, at_users) == -1) {
                    at_users.push(user);
                };
            };

            $('textarea').textcomplete([{
                mentions: at_users,
                match: /\B@(\w*)$/,
                search: function(term, callback) {
                    callback($.map(this.mentions, function(mention) {
                        return mention.indexOf(term) === 0 ? mention : null;
                    }));
                },
                index: 1,
                replace: function(mention) {
                    return '@' + mention + ' ';
                }
            }], {
                appendTo: 'body'
            });

        },

        /**
         * Autoresizing the textarea when you typing.
         */
        initTextareaAutoResize: function(){
            $('textarea').autosize();
        },

        /**
         * Scroll to top in one click.
         */
        initScrollToTop: function(){
            $.scrollUp.init();
        },

        /**
         * Code heightlight.
         */
        initHeightLight: function(){
            Prism.highlightAll();
        },

        /**
         * lightbox
         */
        initLightBox: function(){
            $(document).delegate('.content-body img:not(.emoji)', 'click', function(event) {
                event.preventDefault();
                return $(this).ekkoLightbox({
                    onShown: function() {
                        if (window.console) {
                            // return console.log('Checking our the events huh?');
                        }
                    }
                });
            });
        },

        /**
         * do content preview
         */
        runPreview: function() {
            var replyContent = $("#reply_content");
            var oldContent = replyContent.val();

            if (oldContent) {
                marked(oldContent, function (err, content) {
                  $('#preview-box').html(content);
                  emojify.run(document.getElementById('preview-box'));
                });
            }
        },

        /**
         * Init post content preview
         */
        initEditorPreview: function() {
            var self = this;
            $("#reply_content").focus(function(event) {
                $("#reply_notice").fadeIn(1500);
                $("#preview-box").fadeIn(1500);
                $("#preview-lable").fadeIn(1500);

                if (!$("#reply_content").val()) {
                    $("html, body").animate({ scrollTop: $(document).height()}, 1800);
                }
            });
            $('#reply_content').keyup(function(){
                self.runPreview();
            });
        },

        /**
         * Notify user unread notifications when they stay on the
         * page for too long.
         */
        initNotificationsCount: function(argumen) {
            var original_title = document.title;
            if (Config.user_id > 0) {
                function scheduleGetNotification(){
                    $.get( Config.routes.notificationsCount, function( data ) {
                        var nCount = parseInt(data)
                        if (nCount > 0) {
                            $('#notification-count').text(nCount);
                            $('#notification-count').hasClass('badge-important') || $('#notification-count').addClass('badge-important');
                            document.title = '(' + nCount + ') '+ original_title;
                        } else {
                            document.title =  original_title;
                            $('#notification-count').text(0);
                            $('#notification-count').addClass('badge-fade');
                            $('#notification-count').removeClass('badge-important');

                        }
                        setTimeout(scheduleGetNotification, 15000);
                    });
                };
                setTimeout(scheduleGetNotification, 15000);
            }
        },

        /*
         * Use Ctrl + Enter for reply
         */
        initReplyOnPressKey: function() {
            $(document).on("keydown", "#reply_content", function(e)
            {
                if ((e.keyCode == 10 || e.keyCode == 13) && e.ctrlKey) {
                    $(this).parents("form").submit();
                    return false;
                }
            });
        },

        /*
         * Construct a form when using the following code, makes more clean code.
         *   {{ link_to_route('tasks.destroy', 'D', $task->id, ['data-method'=>'delete']) }}
         * See this answer: http://stackoverflow.com/a/23082278/689832
         */
        initDeleteForm: function() {
            $('[data-method]').append(function(){
                return "\n"+
                "<form action='"+$(this).attr('data-url')+"' method='POST' style='display:none'>\n"+
                "   <input type='hidden' name='_method' value='"+$(this).attr('data-method')+"'>\n"+
                "   <input type='hidden' name='_token' value='"+Config.token+"'>\n"+
                "</form>\n"
                })
                .attr('style','cursor:pointer;')
                .click(function() {
                    if ($(this).attr('data-method') == 'post') {
                        $(this).find("form").submit();
                    }
                    if ($(this).attr('data-method') == 'delete' && confirm("Are you sure want to proceed?")) {
                        $(this).find("form").submit();
                    }
                });
           // attr('onclick',' if (confirm("Are you sure want to proceed?")) { $(this).find("form").submit(); };');
        },

        /**
         * Local Storage
         */
        initLocalStorage: function() {
            var self = this;
            $("#reply_content").focus(function(event) {

                // Topic Title ON Topic Creation View
                localforage.getItem('topic-title', function(err, value) {
                    if ($('.topic_create #topic-title').val() == '' && !err) {
                        $('.topic_create #topic-title').val(value);
                    };
                });
                $('.topic_create #topic-title').keyup(function(){
                    localforage.setItem('topic-title', $(this).val());
                });

                // Topic Content ON Topic Creation View
                localforage.getItem('topic_create_content', function(err, value) {
                    if ($('.topic_create #reply_content').val() == '' && !err) {
                        $('.topic_create #reply_content').val(value);
                        self.runPreview();
                    }
                });
                $('.topic_create #reply_content').keyup(function(){
                    localforage.setItem('topic_create_content', $(this).val());
                });

                // Reply Content ON Topic Detail View
                localforage.getItem('reply_content', function(err, value) {
                    if ($('.topics-show #reply_content').val() == '' && !err) {
                        $('.topics-show #reply_content').val(value);
                        self.runPreview();
                    }
                });
                $('.topics-show #reply_content').keyup(function(){
                    localforage.setItem('reply_content', $(this).val());
                });
            })

            // Clear Local Storage on submit
            $("#topic-create-form").submit(function(event){
                localforage.removeItem('topic_create_content');
                localforage.removeItem('topic-title');
            });
            $("#reply-form").submit(function(event){
                localforage.removeItem('reply_content');
            });
        },

        /**
         * Upload image
         */
        initInlineAttach: function() {
            var self = this;
            $('#reply_content').inlineattach({
                uploadUrl: Config.routes.upload_image,
                extraParams: {
                  '_token': Config.token,
                },
                onUploadedFile: function(response) {
                    setTimeout(self.runPreview, 200);
                },
            });
        },

        /**
         * Snowing around the world
         */
        snowing: function() {

            // only show snow in Christmas
            var today = new Date()
            var christmas = new Date(today.getFullYear(), 11, 25) // Month is 0-11 in JavaScript
            if (today.getMonth() == 11 && (today.getDate() > 22 && today.getDate() < 30))
            {
                $('#body').snowfall({
                    flakeCount: 100,
                    minSize: 2,
                    maxSize:5,
                    round: true
                });
            }
        },

    }
    window.PHPHub = PHPHub;
})(jQuery);

$(document).ready(function()
{
    PHPHub.init();
});

// reply a reply
function replyOne(username){
    replyContent = $("#reply_content");
	oldContent = replyContent.val();
	prefix = "@" + username + " ";
	newContent = ''
	if(oldContent.length > 0){
	    if (oldContent != prefix) {
	        newContent = oldContent + "\n" + prefix;
	    }
	} else {
	    newContent = prefix
	}
	replyContent.focus();
	replyContent.val(newContent);
	moveEnd($("#reply_content"));
}

var moveEnd = function(obj){
	obj.focus();

	var len = obj.value === undefined ? 0 : obj.value.length;

	if (document.selection) {
		var sel = obj.createTextRange();
		sel.moveStart('character',len);
		sel.collapse();
		sel.select();
	} else if (typeof obj.selectionStart == 'number' && typeof obj.selectionEnd == 'number') {
		obj.selectionStart = obj.selectionEnd = len;
	}
}
<|endoftext|>