<commit_before>import {d3, uuid} from "nbpresent-deps";

import Jupyter from "base/js/namespace";

import {Editor} from "./editor";
import {Toolbar} from "./toolbar";
import {PART} from "./parts";
import {MiniSlide} from "./mini";
import {TemplateLibrary} from "./templates";

let REMOVED = "<removed>";

class Sorter {
  constructor(tree, tour) {
    this.tree = tree;
    this.tour = tour;

    this.templatePicked = this.templatePicked.bind(this);

    this.visible = this.tree.select(["sorting"]);
    this.visible.set(false);

    this.slides = this.tree.select(["slides"]);
    this.selectedSlide = this.tree.select(["selectedSlide"]);
    this.selectedRegion = this.tree.select(["sorter", "selectedRegion"]);

    this.selectedSlide.on("update", () => this.updateSelectedSlide());
    this.selectedRegion.on("update", () => this.updateSelectedRegion());
    this.slides.on("update", () => this.draw());
    this.visible.on("update", () => this.visibleUpdated());

    this.scale = {
      x: d3.scale.linear()
    };

    this.mini = new MiniSlide(this.selectedRegion);

    this.drawn = false;
  }

  visibleUpdated(){
    let visible = this.visible.get();

    if(!this.drawn){
      this.initUI();
      this.drawn = true;
    }

    if(visible) {
      this.draw();
    }else {
      if(this.editor){
        this.editor.destroy();
        this.editor = null;
      }
      if(this.templates){
        this.templates.destroy();
        this.templates = null;
      }
    }

    this.update();
  }

  show(){
    this.visible.set(!this.visible.get());
  }

  update(){
    let visible = this.visible.get();
    this.$view
      .classed({offscreen: !visible})
      .style({
        // necessary for FOUC
        "display": visible ? "block" : "none"
      });

    d3.select("#notebook")
      .style({
        "margin-bottom": visible ? "100px" : null
      });
  }

  initUI(){
    this.$view = d3.select("body")
      .append("div")
      .classed({
        nbpresent_sorter: 1,
        offscreen: 1
      })
      .style({
        display: "none"
      });

    this.$slides = this.$view.append("div")
      .classed({slides_wrap: 1});

    let $brand = this.$view.append("h4")
      .classed({nbpresent_brand: 1})
      .append("a")
      .attr({
        href: "https://continuumio.github.io/nbpresent/",
        target: "_blank"
      })

    $brand.append("i")
      .attr("class", "fa fa-fw fa-gift");

    $brand.append("span")
      .text("nbpresent");

    this.$empty = this.$slides.append("h3")
      .classed({empty: 1})
      .text("No slides yet.");

    let $help = this.$view.append("div")
      .classed({nbpresent_help: 1})
      .append("a")
      .attr({href: "#"})
    .on("click", () => this.tour.restart())
      .append("i")
      .attr("class", "fa fa-question-circle");

    this.initToolbar();
    this.initDrag();
  }

  initDrag(){
    let that = this,
      dragOrigin;

    this.drag = d3.behavior.drag()
      .on("dragstart", function(d){
        let slide = d3.select(this)
          .classed({dragging: 1});

        dragOrigin = parseFloat(slide.style("left"));
      })
      .on("drag", function(d){
        d3.select(this)
          .style({
            left: `${dragOrigin += d3.event.dx}px`,
          });
      })
      .on("dragend", function(d, i){
        let $slide = d3.select(this)
          .classed({dragging: 0});

        let left = parseFloat($slide.style("left")),
          slides = that.tree.get("sortedSlides"),
          slideN = Math.floor(left / that.slideWidth()),
          after;

        if(left < that.slideWidth() || slideN < 0){
          after = null;
        }else if(slideN > slides.length || !slides[slideN]){
          after = slides.slice(-1)[0].key;
        }else{
          after = slides[slideN].key;
        }

        if(d.key !== after){
          that.unlinkSlide(d.key);
          that.selectedSlide.set(that.appendSlide(after, d.key));
        }else{
          that.draw();
        }
      });
  }

  // TODO: make these d3 scales!
  slideHeight() {
    return 100;
  }

  slideWidth(){
    return 200;
  }

  copySlide(slide){
    let newSlide = JSON.parse(JSON.stringify(slide));
    newSlide.id = this.nextId();
    newSlide.regions = d3.entries(newSlide.regions).reduce((memo, d)=>{
      let id = this.nextId();
      // TODO: keep part?
      memo[id] = $.extend(true, {}, d.value, {id, content: null});
      return memo;
    }, {});

    return newSlide;
  }

  slideClicked(d){
    if(this.templates){
      let newSlide = this.copySlide(d.value);
      this.templatePicked({key: newSlide.id, value: newSlide});
      this.templates && this.templates.destroy();
      this.templates = null;
      return;
    }
    this.selectedSlide.set(d.key);
  }

  draw(){
    if(!this.$slides){
      return;
    }
    let that = this;

    let slides = this.tree.get("sortedSlides");

    this.scale.x.range([20, this.slideWidth() + 20]);

    let $slide = this.$slides.selectAll(".slide")
      .data(slides, (d) => d.key);

    $slide.enter().append("div")
      .classed({slide: 1})
      .call(this.drag)
      .on("click", (d) =>{
        this.slideClicked(d)
      })
      .on("dblclick", (d) => this.editSlide(d.key));

    $slide.exit()
      .transition()
      .style({
        top: "200px"
      })
      .remove();

    let selectedSlide = this.selectedSlide.get(),
      selectedRegion = this.selectedRegion.get(),
      selectedSlideLeft;

    $slide
      .style({
        "z-index": (d, i) => i
      })
      .classed({
        active: (d) => d.key === selectedSlide
      })
      .transition()
      .delay((d, i) => i * 10)
      .style({
        left: (d, i) => {
          let left = this.scale.x(i);
          if(d.key === selectedSlide){
            selectedSlideLeft = left;
          }
          return `${left}px`;
        }
      });

    $slide.call(this.mini.update);

    this.$regionToolbar
      .transition()
      .style({
        opacity: selectedRegion ? 1 : 0,
        display: selectedRegion ? "block" : "none",
        left: `${selectedSlideLeft - 30}px`
      });

    this.$empty
      .transition()
      .style({opacity: 1 * !$slide[0].length })
      .transition()
      .style({display: $slide[0].length ? "none": "block"});

    this.$deckToolbar.call(this.deckToolbar.update);
  }

  updateSelectedRegion(){
    let {slide, region} = this.selectedRegion.get() || {};
    if(region){
      this.selectedSlide.set(slide);
      let content = this.slides.get(
        [slide, "regions", region, "content"]);
      if(content){
        this.selectCell(content.cell);
      }
    }else if(this.$regionToolbar){
      this.$regionToolbar.transition()
        .style({opacity: 0})
        .transition()
        .style({display: "none"});
    }
    this.draw();
  }

  // TODO: move this to the cell manager?
  selectCell(id){
    let cell = Jupyter.notebook.get_cells().filter(function(cell, idx){
      if(cell.metadata.nbpresent && cell.metadata.nbpresent.id == id){
        Jupyter.notebook.select(idx);
      };
    });
  }

  updateSelectedSlide(){
    let slide = this.selectedSlide.get(),
      selected = this.selectedRegion.get() || {};

    if(selected.slide != slide){
      this.selectedRegion.set(null);
    }

    this.draw();
    if(this.editor){
      this.editSlide(slide);
    }
  }

  initToolbar(){
    this.deckToolbar = new Toolbar()
      .btnClass("btn-default btn-lg");
    this.$deckToolbar = this.$view.append("div")
      .classed({deck_toolbar: 1})
      .datum([
        [{
          icon: "plus-square-o fa-2x",
          click: () => this.addSlide(),
          tip: "Add Slide"
        }], [{
          icon: "edit fa-2x",
          click: () => this.editSlide(this.selectedSlide.get()),
          tip: "Edit Slide",
          visible: () => this.selectedSlide.get() && !this.editor
        }, {
          icon: "chevron-circle-down fa-2x",
          click: () => this.editSlide(this.selectedSlide.get()),
          tip: "Back to Sorter",
          visible: () => this.editor
        }],
        [{
          icon: "trash fa-2x",
          click: () => {
            this.removeSlide(this.selectedSlide.get());
            this.selectedSlide.set(null);
          },
          tip: "Delete Slide",
          visible: () => this.selectedSlide.get()
        }]
      ])
      .call(this.deckToolbar.update);

    this.regionToolbar = new Toolbar();
    this.$regionToolbar = this.$slides.append("div")
      .classed({region_toolbar: 1})
      .datum([
        [{
          icon: "terminal",
          click: () => this.linkContent(PART.source),
          tip: "Link Region to Cell Input"
        },
        {
          icon: "image",
          click: () => this.linkContent(PART.outputs),
          tip: "Link Region to Cell Output"
        },
        {
          icon: "sliders",
          click: () => this.linkContent(PART.widgets),
          tip: "Link Region to Cell Widgets"
        },
        {
          icon: "unlink",
          click: () => this.linkContent(null),
          tip: "Unlink Region"
        }]
      ])
      .call(this.regionToolbar.update);
  }

  linkContent(part){
    let {slide, region} = this.selectedRegion.get() || {},
      cell = Jupyter.notebook.get_selected_cell(),
      cellId;

    if(!(region && cell)){
      return;
    }

    if(part){
      if(!cell.metadata.nbpresent){
        cell.metadata.nbpresent = {id: this.nextId()};
      }

      cellId = cell.metadata.nbpresent.id;

      this.slides.set([slide, "regions", region, "content"], {
        cell: cellId,
        part
      });
    }else{
      this.slides.unset([slide, "regions", region, "content"]);
    }
  }

  addSlide(){
    if(!this.templates || this.templates.killed){
      this.templates = new TemplateLibrary(this.templatePicked);
    }else{
      this.templates.destroy();
      this.templates = null;
    }
  }

  templatePicked(slide){
    if(slide && this.templates && !this.templates.killed){
      let last = this.tree.get("sortedSlides").slice(-1),
        selected = this.selectedSlide.get();

      this.slides.set([slide.key], slide.value);

      let appended = this.appendSlide(
          selected ? selected : last.length ? last[0].key : null,
          slide.key
        );

      this.selectedSlide.set(appended);
    }
    if(this.templates){
      this.templates.destroy();
      this.templates = null;
    }
  }

  editSlide(id){
    if(this.editor){
      if(this.editor.slide.get("id") === id){
        id = null;
      }
      this.editor.destroy();
      this.editor = null;
    }

    if(id){
      // TODO: do this with an id and big tree ref?
      this.editor = new Editor(this.slides.select(id), this.selectedRegion);
    }
    this.draw();
  }

  nextId(){
    return uuid.v4();
  }

  unlinkSlide(id){
    let {prev} = this.slides.get(id),
      next = this.nextSlide(id);

    next && this.slides.set([next, "prev"], prev);
    this.slides.set([id, "prev"], REMOVED);
  }

  removeSlide(id){
    if(!id){
      return;
    }
    this.unlinkSlide(id);
    this.slides.unset(id);
  }

  nextSlide(id){
    let slides = this.tree.get("sortedSlides"),
      next = slides.filter((d) => d.value.prev === id);

    return next.length ? next[0].key : null;
  }

  newSlide(id, prev){
    return {
      id,
      prev,
      regions: {}
    }
  }

  appendSlide(prev, id=null){
    let next = this.nextSlide(prev);

    if(!id){
      id = this.nextId();
      this.slides.set(id, this.newSlide(id, prev));
    }else{
      this.slides.set([id, "prev"], prev);
    }

    next && this.slides.set([next, "prev"], id);

    return id;
  }
}

export {Sorter};
<commit_msg>fixing old links<commit_after>import {d3, uuid} from "nbpresent-deps";

import Jupyter from "base/js/namespace";

import {Editor} from "./editor";
import {Toolbar} from "./toolbar";
import {PART} from "./parts";
import {MiniSlide} from "./mini";
import {TemplateLibrary} from "./templates";

let REMOVED = "<removed>";

class Sorter {
  constructor(tree, tour) {
    this.tree = tree;
    this.tour = tour;

    this.templatePicked = this.templatePicked.bind(this);

    this.visible = this.tree.select(["sorting"]);
    this.visible.set(false);

    this.slides = this.tree.select(["slides"]);
    this.selectedSlide = this.tree.select(["selectedSlide"]);
    this.selectedRegion = this.tree.select(["sorter", "selectedRegion"]);

    this.selectedSlide.on("update", () => this.updateSelectedSlide());
    this.selectedRegion.on("update", () => this.updateSelectedRegion());
    this.slides.on("update", () => this.draw());
    this.visible.on("update", () => this.visibleUpdated());

    this.scale = {
      x: d3.scale.linear()
    };

    this.mini = new MiniSlide(this.selectedRegion);

    this.drawn = false;
  }

  visibleUpdated(){
    let visible = this.visible.get();

    if(!this.drawn){
      this.initUI();
      this.drawn = true;
    }

    if(visible) {
      this.draw();
    }else {
      if(this.editor){
        this.editor.destroy();
        this.editor = null;
      }
      if(this.templates){
        this.templates.destroy();
        this.templates = null;
      }
    }

    this.update();
  }

  show(){
    this.visible.set(!this.visible.get());
  }

  update(){
    let visible = this.visible.get();
    this.$view
      .classed({offscreen: !visible})
      .style({
        // necessary for FOUC
        "display": visible ? "block" : "none"
      });

    d3.select("#notebook")
      .style({
        "margin-bottom": visible ? "100px" : null
      });
  }

  initUI(){
    this.$view = d3.select("body")
      .append("div")
      .classed({
        nbpresent_sorter: 1,
        offscreen: 1
      })
      .style({
        display: "none"
      });

    this.$slides = this.$view.append("div")
      .classed({slides_wrap: 1});

    let $brand = this.$view.append("h4")
      .classed({nbpresent_brand: 1})
      .append("a")
      .attr({
        href: "https://anaconda-server.github.io/nbpresent/",
        target: "_blank"
      })

    $brand.append("i")
      .attr("class", "fa fa-fw fa-gift");

    $brand.append("span")
      .text("nbpresent");

    this.$empty = this.$slides.append("h3")
      .classed({empty: 1})
      .text("No slides yet.");

    let $help = this.$view.append("div")
      .classed({nbpresent_help: 1})
      .append("a")
      .attr({href: "#"})
    .on("click", () => this.tour.restart())
      .append("i")
      .attr("class", "fa fa-question-circle");

    this.initToolbar();
    this.initDrag();
  }

  initDrag(){
    let that = this,
      dragOrigin;

    this.drag = d3.behavior.drag()
      .on("dragstart", function(d){
        let slide = d3.select(this)
          .classed({dragging: 1});

        dragOrigin = parseFloat(slide.style("left"));
      })
      .on("drag", function(d){
        d3.select(this)
          .style({
            left: `${dragOrigin += d3.event.dx}px`,
          });
      })
      .on("dragend", function(d, i){
        let $slide = d3.select(this)
          .classed({dragging: 0});

        let left = parseFloat($slide.style("left")),
          slides = that.tree.get("sortedSlides"),
          slideN = Math.floor(left / that.slideWidth()),
          after;

        if(left < that.slideWidth() || slideN < 0){
          after = null;
        }else if(slideN > slides.length || !slides[slideN]){
          after = slides.slice(-1)[0].key;
        }else{
          after = slides[slideN].key;
        }

        if(d.key !== after){
          that.unlinkSlide(d.key);
          that.selectedSlide.set(that.appendSlide(after, d.key));
        }else{
          that.draw();
        }
      });
  }

  // TODO: make these d3 scales!
  slideHeight() {
    return 100;
  }

  slideWidth(){
    return 200;
  }

  copySlide(slide){
    let newSlide = JSON.parse(JSON.stringify(slide));
    newSlide.id = this.nextId();
    newSlide.regions = d3.entries(newSlide.regions).reduce((memo, d)=>{
      let id = this.nextId();
      // TODO: keep part?
      memo[id] = $.extend(true, {}, d.value, {id, content: null});
      return memo;
    }, {});

    return newSlide;
  }

  slideClicked(d){
    if(this.templates){
      let newSlide = this.copySlide(d.value);
      this.templatePicked({key: newSlide.id, value: newSlide});
      this.templates && this.templates.destroy();
      this.templates = null;
      return;
    }
    this.selectedSlide.set(d.key);
  }

  draw(){
    if(!this.$slides){
      return;
    }
    let that = this;

    let slides = this.tree.get("sortedSlides");

    this.scale.x.range([20, this.slideWidth() + 20]);

    let $slide = this.$slides.selectAll(".slide")
      .data(slides, (d) => d.key);

    $slide.enter().append("div")
      .classed({slide: 1})
      .call(this.drag)
      .on("click", (d) =>{
        this.slideClicked(d)
      })
      .on("dblclick", (d) => this.editSlide(d.key));

    $slide.exit()
      .transition()
      .style({
        top: "200px"
      })
      .remove();

    let selectedSlide = this.selectedSlide.get(),
      selectedRegion = this.selectedRegion.get(),
      selectedSlideLeft;

    $slide
      .style({
        "z-index": (d, i) => i
      })
      .classed({
        active: (d) => d.key === selectedSlide
      })
      .transition()
      .delay((d, i) => i * 10)
      .style({
        left: (d, i) => {
          let left = this.scale.x(i);
          if(d.key === selectedSlide){
            selectedSlideLeft = left;
          }
          return `${left}px`;
        }
      });

    $slide.call(this.mini.update);

    this.$regionToolbar
      .transition()
      .style({
        opacity: selectedRegion ? 1 : 0,
        display: selectedRegion ? "block" : "none",
        left: `${selectedSlideLeft - 30}px`
      });

    this.$empty
      .transition()
      .style({opacity: 1 * !$slide[0].length })
      .transition()
      .style({display: $slide[0].length ? "none": "block"});

    this.$deckToolbar.call(this.deckToolbar.update);
  }

  updateSelectedRegion(){
    let {slide, region} = this.selectedRegion.get() || {};
    if(region){
      this.selectedSlide.set(slide);
      let content = this.slides.get(
        [slide, "regions", region, "content"]);
      if(content){
        this.selectCell(content.cell);
      }
    }else if(this.$regionToolbar){
      this.$regionToolbar.transition()
        .style({opacity: 0})
        .transition()
        .style({display: "none"});
    }
    this.draw();
  }

  // TODO: move this to the cell manager?
  selectCell(id){
    let cell = Jupyter.notebook.get_cells().filter(function(cell, idx){
      if(cell.metadata.nbpresent && cell.metadata.nbpresent.id == id){
        Jupyter.notebook.select(idx);
      };
    });
  }

  updateSelectedSlide(){
    let slide = this.selectedSlide.get(),
      selected = this.selectedRegion.get() || {};

    if(selected.slide != slide){
      this.selectedRegion.set(null);
    }

    this.draw();
    if(this.editor){
      this.editSlide(slide);
    }
  }

  initToolbar(){
    this.deckToolbar = new Toolbar()
      .btnClass("btn-default btn-lg");
    this.$deckToolbar = this.$view.append("div")
      .classed({deck_toolbar: 1})
      .datum([
        [{
          icon: "plus-square-o fa-2x",
          click: () => this.addSlide(),
          tip: "Add Slide"
        }], [{
          icon: "edit fa-2x",
          click: () => this.editSlide(this.selectedSlide.get()),
          tip: "Edit Slide",
          visible: () => this.selectedSlide.get() && !this.editor
        }, {
          icon: "chevron-circle-down fa-2x",
          click: () => this.editSlide(this.selectedSlide.get()),
          tip: "Back to Sorter",
          visible: () => this.editor
        }],
        [{
          icon: "trash fa-2x",
          click: () => {
            this.removeSlide(this.selectedSlide.get());
            this.selectedSlide.set(null);
          },
          tip: "Delete Slide",
          visible: () => this.selectedSlide.get()
        }]
      ])
      .call(this.deckToolbar.update);

    this.regionToolbar = new Toolbar();
    this.$regionToolbar = this.$slides.append("div")
      .classed({region_toolbar: 1})
      .datum([
        [{
          icon: "terminal",
          click: () => this.linkContent(PART.source),
          tip: "Link Region to Cell Input"
        },
        {
          icon: "image",
          click: () => this.linkContent(PART.outputs),
          tip: "Link Region to Cell Output"
        },
        {
          icon: "sliders",
          click: () => this.linkContent(PART.widgets),
          tip: "Link Region to Cell Widgets"
        },
        {
          icon: "unlink",
          click: () => this.linkContent(null),
          tip: "Unlink Region"
        }]
      ])
      .call(this.regionToolbar.update);
  }

  linkContent(part){
    let {slide, region} = this.selectedRegion.get() || {},
      cell = Jupyter.notebook.get_selected_cell(),
      cellId;

    if(!(region && cell)){
      return;
    }

    if(part){
      if(!cell.metadata.nbpresent){
        cell.metadata.nbpresent = {id: this.nextId()};
      }

      cellId = cell.metadata.nbpresent.id;

      this.slides.set([slide, "regions", region, "content"], {
        cell: cellId,
        part
      });
    }else{
      this.slides.unset([slide, "regions", region, "content"]);
    }
  }

  addSlide(){
    if(!this.templates || this.templates.killed){
      this.templates = new TemplateLibrary(this.templatePicked);
    }else{
      this.templates.destroy();
      this.templates = null;
    }
  }

  templatePicked(slide){
    if(slide && this.templates && !this.templates.killed){
      let last = this.tree.get("sortedSlides").slice(-1),
        selected = this.selectedSlide.get();

      this.slides.set([slide.key], slide.value);

      let appended = this.appendSlide(
          selected ? selected : last.length ? last[0].key : null,
          slide.key
        );

      this.selectedSlide.set(appended);
    }
    if(this.templates){
      this.templates.destroy();
      this.templates = null;
    }
  }

  editSlide(id){
    if(this.editor){
      if(this.editor.slide.get("id") === id){
        id = null;
      }
      this.editor.destroy();
      this.editor = null;
    }

    if(id){
      // TODO: do this with an id and big tree ref?
      this.editor = new Editor(this.slides.select(id), this.selectedRegion);
    }
    this.draw();
  }

  nextId(){
    return uuid.v4();
  }

  unlinkSlide(id){
    let {prev} = this.slides.get(id),
      next = this.nextSlide(id);

    next && this.slides.set([next, "prev"], prev);
    this.slides.set([id, "prev"], REMOVED);
  }

  removeSlide(id){
    if(!id){
      return;
    }
    this.unlinkSlide(id);
    this.slides.unset(id);
  }

  nextSlide(id){
    let slides = this.tree.get("sortedSlides"),
      next = slides.filter((d) => d.value.prev === id);

    return next.length ? next[0].key : null;
  }

  newSlide(id, prev){
    return {
      id,
      prev,
      regions: {}
    }
  }

  appendSlide(prev, id=null){
    let next = this.nextSlide(prev);

    if(!id){
      id = this.nextId();
      this.slides.set(id, this.newSlide(id, prev));
    }else{
      this.slides.set([id, "prev"], prev);
    }

    next && this.slides.set([next, "prev"], id);

    return id;
  }
}

export {Sorter};
<|endoftext|>


<commit_before>define(["js/data/RestDataSource", "js/data/Model", "js/data/Collection", "underscore"], function (RestDataSource, Model, Collection, _) {

    var SprdDataSource = RestDataSource.inherit('sprd.data.SprdDataSource', {
        defaults: {
            apiKey: null,
            secret: null,
            session: null
        },

        _getConfigurationForResource: function (resource) {

            var parentContext = resource.$context;
            var configuration = this.$dataSourceConfiguration;

            if (parentContext && parentContext.$contextModel) {
                configuration = configuration.getConfigurationForModelClass(parentContext.$contextModel.factory);
            }

            if (resource instanceof Model) {
                return configuration.getConfigurationForModelClass(resource.factory);
            } else if (resource instanceof Collection) {
                return configuration.getConfigurationForModelClass(resource.$modelFactory);
            }

            return null;
        },

        getQueryParameters: function (method, resource) {
            var obj = {};

            if (this.$.locale) {
                obj.locale = this.$.locale;
            }

            var params = _.defaults(obj, this.callBase());

            var configuration,
                apiKey = this.$.apiKey,
                needsSignature;

            // get the configuration only if needed
            configuration = this._getConfigurationForResource(resource);

            if (!configuration) {
                throw new Error("Configuration for resource not found");
            }

            var signatureRequired = configuration.$.signatureRequired,
                apiKeyRequired = configuration.$.apiKeyRequired,
                sessionRequired = configuration.$.sessionRequired;

            needsSignature = signatureRequired || sessionRequired;

            if (this.$.session && sessionRequired) {
                params = _.defaults({
                    sessionId: this.$.session.$.id
                });
            }

            if (needsSignature) {
                var secret = this.$.secret;
                var time = Date.now();
                var url = this._buildUriForResource(resource, this.$.endPoint);

                var data = method + " " + url + " " + time + " " + secret;

                params = _.defaults({
                    sig: SprdDataSource.SHA1(data),
                    time: time,
                    apiKey: apiKey
                });
            }

            if (apiKeyRequired || signatureRequired || sessionRequired) {
                params = _.defaults(params, {
                    apiKey: apiKey
                });
            }

            return params;
        }
    });

    SprdDataSource.SHA1 = function (msg) {

        function rotateLeft(n, s) {
            return ( n << s ) | (n >>> (32 - s));
        }

        function cvtHex(val) {
            var str = "";
            var i;
            var v;

            for (i = 7; i >= 0; i--) {
                v = (val >>> (i * 4)) & 0x0f;
                str += v.toString(16);
            }
            return str;
        }

        function utf8Encode(string) {
            string = string.replace(/\r\n/g, "\n");
            var utfText = "";

            for (var n = 0; n < string.length; n++) {

                var c = string.charCodeAt(n);

                if (c < 128) {
                    utfText += String.fromCharCode(c);
                }
                else if ((c > 127) && (c < 2048)) {
                    utfText += String.fromCharCode((c >> 6) | 192);
                    utfText += String.fromCharCode((c & 63) | 128);
                }
                else {
                    utfText += String.fromCharCode((c >> 12) | 224);
                    utfText += String.fromCharCode(((c >> 6) & 63) | 128);
                    utfText += String.fromCharCode((c & 63) | 128);
                }

            }

            return utfText;
        }

        var blockStart;
        var i, j;
        var W = new Array(80);
        var H0 = 0x67452301;
        var H1 = 0xEFCDAB89;
        var H2 = 0x98BADCFE;
        var H3 = 0x10325476;
        var H4 = 0xC3D2E1F0;
        var A, B, C, D, E;
        var temp;

        msg = utf8Encode(msg);

        var msg_len = msg.length;

        var word_array = [];
        for (i = 0; i < msg_len - 3; i += 4) {
            j = msg.charCodeAt(i) << 24 | msg.charCodeAt(i + 1) << 16 |
                msg.charCodeAt(i + 2) << 8 | msg.charCodeAt(i + 3);
            word_array.push(j);
        }

        switch (msg_len % 4) {
            case 0:
                i = 0x080000000;
                break;
            case 1:
                i = msg.charCodeAt(msg_len - 1) << 24 | 0x0800000;
                break;

            case 2:
                i = msg.charCodeAt(msg_len - 2) << 24 | msg.charCodeAt(msg_len - 1) << 16 | 0x08000;
                break;

            case 3:
                i = msg.charCodeAt(msg_len - 3) << 24 | msg.charCodeAt(msg_len - 2) << 16 | msg.charCodeAt(msg_len - 1) << 8 | 0x80;
                break;
        }

        word_array.push(i);

        while ((word_array.length % 16) != 14) {
            word_array.push(0);
        }

        word_array.push(msg_len >>> 29);
        word_array.push((msg_len << 3) & 0x0ffffffff);

        for (blockStart = 0; blockStart < word_array.length; blockStart += 16) {

            for (i = 0; i < 16; i++) {
                W[i] = word_array[blockStart + i];
            }

            for (i = 16; i <= 79; i++) {
                W[i] = rotateLeft(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);
            }

            A = H0;
            B = H1;
            C = H2;
            D = H3;
            E = H4;

            for (i = 0; i <= 19; i++) {
                temp = (rotateLeft(A, 5) + ((B & C) | (~B & D)) + E + W[i] + 0x5A827999) & 0x0ffffffff;
                E = D;
                D = C;
                C = rotateLeft(B, 30);
                B = A;
                A = temp;
            }

            for (i = 20; i <= 39; i++) {
                temp = (rotateLeft(A, 5) + (B ^ C ^ D) + E + W[i] + 0x6ED9EBA1) & 0x0ffffffff;
                E = D;
                D = C;
                C = rotateLeft(B, 30);
                B = A;
                A = temp;
            }

            for (i = 40; i <= 59; i++) {
                temp = (rotateLeft(A, 5) + ((B & C) | (B & D) | (C & D)) + E + W[i] + 0x8F1BBCDC) & 0x0ffffffff;
                E = D;
                D = C;
                C = rotateLeft(B, 30);
                B = A;
                A = temp;
            }

            for (i = 60; i <= 79; i++) {
                temp = (rotateLeft(A, 5) + (B ^ C ^ D) + E + W[i] + 0xCA62C1D6) & 0x0ffffffff;
                E = D;
                D = C;
                C = rotateLeft(B, 30);
                B = A;
                A = temp;
            }

            H0 = (H0 + A) & 0x0ffffffff;
            H1 = (H1 + B) & 0x0ffffffff;
            H2 = (H2 + C) & 0x0ffffffff;
            H3 = (H3 + D) & 0x0ffffffff;
            H4 = (H4 + E) & 0x0ffffffff;

        }

        temp = cvtHex(H0) + cvtHex(H1) + cvtHex(H2) + cvtHex(H3) + cvtHex(H4);
        return temp.toLowerCase();
    };

    return SprdDataSource;
});<commit_msg>added some ToDo<commit_after>define(["js/data/RestDataSource", "js/data/Model", "js/data/Collection", "underscore"], function (RestDataSource, Model, Collection, _) {

    var SprdDataSource = RestDataSource.inherit('sprd.data.SprdDataSource', {
        defaults: {
            apiKey: null,
            secret: null,
            session: null
        },

        _getConfigurationForResource: function (resource) {

            var parentContext = resource.$context;
            var configuration = this.$dataSourceConfiguration;

            if (parentContext && parentContext.$contextModel) {
                configuration = configuration.getConfigurationForModelClass(parentContext.$contextModel.factory);
            }

            if (resource instanceof Model) {
                return configuration.getConfigurationForModelClass(resource.factory);
            } else if (resource instanceof Collection) {
                return configuration.getConfigurationForModelClass(resource.$modelFactory);
            }

            return null;
        },

        getQueryParameters: function (method, resource) {
            var obj = {};

            if (this.$.locale) {
                obj.locale = this.$.locale;
            }

            var params = _.defaults(obj, this.callBase());

            var configuration,
                apiKey = this.$.apiKey,
                needsSignature;

            // get the configuration only if needed
            configuration = this._getConfigurationForResource(resource);

            if (!configuration) {
                throw new Error("Configuration for resource not found");
            }

            var signatureRequired = configuration.$.signatureRequired,
                apiKeyRequired = configuration.$.apiKeyRequired,
                sessionRequired = configuration.$.sessionRequired;

            needsSignature = signatureRequired || sessionRequired;

            if (this.$.session && sessionRequired) {
                params = _.defaults({
                    // TODO: change session id to token for translation service
                    sessionId: this.$.session.$.id
                });
            }

            if (needsSignature) {
                var secret = this.$.secret;
                var time = Date.now();
                var url = this._buildUriForResource(resource, this.$.endPoint);

                var data = method + " " + url + " " + time + " " + secret;

                params = _.defaults({
                    sig: SprdDataSource.SHA1(data),
                    time: time,
                    apiKey: apiKey
                });
            }

            if (apiKeyRequired || signatureRequired || sessionRequired) {
                params = _.defaults(params, {
                    apiKey: apiKey
                });
            }

            return params;
        }
    });

    SprdDataSource.SHA1 = function (msg) {

        function rotateLeft(n, s) {
            return ( n << s ) | (n >>> (32 - s));
        }

        function cvtHex(val) {
            var str = "";
            var i;
            var v;

            for (i = 7; i >= 0; i--) {
                v = (val >>> (i * 4)) & 0x0f;
                str += v.toString(16);
            }
            return str;
        }

        function utf8Encode(string) {
            string = string.replace(/\r\n/g, "\n");
            var utfText = "";

            for (var n = 0; n < string.length; n++) {

                var c = string.charCodeAt(n);

                if (c < 128) {
                    utfText += String.fromCharCode(c);
                }
                else if ((c > 127) && (c < 2048)) {
                    utfText += String.fromCharCode((c >> 6) | 192);
                    utfText += String.fromCharCode((c & 63) | 128);
                }
                else {
                    utfText += String.fromCharCode((c >> 12) | 224);
                    utfText += String.fromCharCode(((c >> 6) & 63) | 128);
                    utfText += String.fromCharCode((c & 63) | 128);
                }

            }

            return utfText;
        }

        var blockStart;
        var i, j;
        var W = new Array(80);
        var H0 = 0x67452301;
        var H1 = 0xEFCDAB89;
        var H2 = 0x98BADCFE;
        var H3 = 0x10325476;
        var H4 = 0xC3D2E1F0;
        var A, B, C, D, E;
        var temp;

        msg = utf8Encode(msg);

        var msg_len = msg.length;

        var word_array = [];
        for (i = 0; i < msg_len - 3; i += 4) {
            j = msg.charCodeAt(i) << 24 | msg.charCodeAt(i + 1) << 16 |
                msg.charCodeAt(i + 2) << 8 | msg.charCodeAt(i + 3);
            word_array.push(j);
        }

        switch (msg_len % 4) {
            case 0:
                i = 0x080000000;
                break;
            case 1:
                i = msg.charCodeAt(msg_len - 1) << 24 | 0x0800000;
                break;

            case 2:
                i = msg.charCodeAt(msg_len - 2) << 24 | msg.charCodeAt(msg_len - 1) << 16 | 0x08000;
                break;

            case 3:
                i = msg.charCodeAt(msg_len - 3) << 24 | msg.charCodeAt(msg_len - 2) << 16 | msg.charCodeAt(msg_len - 1) << 8 | 0x80;
                break;
        }

        word_array.push(i);

        while ((word_array.length % 16) != 14) {
            word_array.push(0);
        }

        word_array.push(msg_len >>> 29);
        word_array.push((msg_len << 3) & 0x0ffffffff);

        for (blockStart = 0; blockStart < word_array.length; blockStart += 16) {

            for (i = 0; i < 16; i++) {
                W[i] = word_array[blockStart + i];
            }

            for (i = 16; i <= 79; i++) {
                W[i] = rotateLeft(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);
            }

            A = H0;
            B = H1;
            C = H2;
            D = H3;
            E = H4;

            for (i = 0; i <= 19; i++) {
                temp = (rotateLeft(A, 5) + ((B & C) | (~B & D)) + E + W[i] + 0x5A827999) & 0x0ffffffff;
                E = D;
                D = C;
                C = rotateLeft(B, 30);
                B = A;
                A = temp;
            }

            for (i = 20; i <= 39; i++) {
                temp = (rotateLeft(A, 5) + (B ^ C ^ D) + E + W[i] + 0x6ED9EBA1) & 0x0ffffffff;
                E = D;
                D = C;
                C = rotateLeft(B, 30);
                B = A;
                A = temp;
            }

            for (i = 40; i <= 59; i++) {
                temp = (rotateLeft(A, 5) + ((B & C) | (B & D) | (C & D)) + E + W[i] + 0x8F1BBCDC) & 0x0ffffffff;
                E = D;
                D = C;
                C = rotateLeft(B, 30);
                B = A;
                A = temp;
            }

            for (i = 60; i <= 79; i++) {
                temp = (rotateLeft(A, 5) + (B ^ C ^ D) + E + W[i] + 0xCA62C1D6) & 0x0ffffffff;
                E = D;
                D = C;
                C = rotateLeft(B, 30);
                B = A;
                A = temp;
            }

            H0 = (H0 + A) & 0x0ffffffff;
            H1 = (H1 + B) & 0x0ffffffff;
            H2 = (H2 + C) & 0x0ffffffff;
            H3 = (H3 + D) & 0x0ffffffff;
            H4 = (H4 + E) & 0x0ffffffff;

        }

        temp = cvtHex(H0) + cvtHex(H1) + cvtHex(H2) + cvtHex(H3) + cvtHex(H4);
        return temp.toLowerCase();
    };

    return SprdDataSource;
});<|endoftext|>


<commit_before>/** @babel */

/**
 * Copyright (c) 2016-present PlatformIO <contact@platformio.org>
 * All rights reserved.
 *
 * This source code is licensed under the license found in the LICENSE file in
 * the root directory of this source tree.
 */

import * as pioNodeHelpers from 'platformio-node-helpers';
import * as utils from './utils';

import fs from 'fs-plus';

export function reinstallPIOCore() {
  const envDir = pioNodeHelpers.core.getEnvDir();
  if (fs.isDirectorySync(envDir)) {
    try {
      fs.removeSync(envDir);
    } catch (err) {
      console.warn(err);
    }
  }
  atom.notifications.addWarning(
    'PlatformIO Core has been uninstalled!',
    {
      detail: 'Please restart Atom to install appropriate version',
      buttons: [
        {
          text: 'Restart',
          onDidClick: () => atom.restartApplication()
        }
      ],
      dismissable: true
    }
  );
}

export function notifyLinterDisabledforArduino() {
  if (localStorage.getItem('platformio-ide:linter-warned') === '2') {
    return;
  }

  atom.confirm({
    message: 'PlatformIO: Smart Code Linter',
    detailedMessage: 'Smart Code Linter (checking the C/C++ code on-the-fly) ' +
      'is disabled by default for Arduino files ("*.ino" and "*.pde").\n' +
      'Please use "*.cpp" instead or enable it manually.',
    buttons: {
      'Enable': () => {
        localStorage.setItem('platformio-ide:linter-warned', '2');
        utils.openUrl('http://docs.platformio.org/page/ide/atom.html#smart-code-linter-is-disabled-for-arduino-files');
      },
      'Remind Later': () => {},
      'Disable': () => localStorage.setItem('platformio-ide:linter-warned', '2')
    }
  });
}

export function notifyDebuggerIsDeprecated() {
  if (localStorage.getItem('platformio-ide:debugger-deprecated') === '1') {
    return;
  }

  atom.confirm({
    message: 'PlatformIO: Debugger for Atom is deprecated',
    detailedMessage: 'Please use PIO Unified Debugger for VSCode with advanced instruments ' +
      '(peripheral and registry views, disassembly, memory view, multithreading & RTOS, etc.)',
    buttons: {
      'Try VSCode': () => {
        utils.openUrl('https://platformio.org/platformio-ide');
      },
      'Remind Later': () => {},
      'Do not show this message': () => localStorage.setItem('platformio-ide:debugger-deprecated', '1')
    }
  });
}

export function notifyExtensionIsDeprecated() {
  if (localStorage.getItem('platformio-ide:extension-deprecated') === '1') {
    return;
  }

  atom.confirm({
    message: 'Try PlatformIO IDE for VSCode',
    detailedMessage: 'According to the user feedback, PlatformIO IDE for Atom has basic integration with PlatformIO ecosystem. ' +
      'This linked with a limited API of Atom text editor for C/C++ development. We highly recommend to try PlatformIO IDE for VSCode: ' +
      'built-in code navigation, completion, formatting, free PIO Unified Debugger with peripheral registers, memory explorer and much more! ' +
      'You existing PlatformIO projects are fully compatible and do not require any changes!',
    buttons: {
      'Try VSCode': () => {
        utils.openUrl('https://platformio.org/platformio-ide');
      },
      'Remind Later': () => {},
      'Do not show this message': () => localStorage.setItem('platformio-ide:extension-deprecated', '1')
    }
  });
}

export function highlightActiveProject(isEnabled = true, retries = 3) {
  const p = utils.getActivePioProject();
  const dirs = [].slice.call(document.querySelectorAll('ol.tree-view-root > li'));
  dirs.forEach((dir) => {
    dir.classList.remove('pio-active-directory');
    if (!dir.dataset.pioProjectPath) {
      const span = dir.querySelector('.project-root-header > span[data-path]');
      dir.dataset.pioProjectPath = fs.realpathSync(span.dataset.path);
    }
  });
  if (dirs.length < 2 || !isEnabled || !p) {
    return;
  }

  let done = false;
  for (const dir of dirs) {
    if (dir.dataset.pioProjectPath === p) {
      dir.classList.add('pio-active-directory');
      done = true;
      break;
    }
  }
  // When running from `atom.project.onDidChangePaths()` or when Atom just starts,
  // an active project directory may not exist in tree-view yet. We should wait
  // for a while and repeat a search, or else user won't be able to recognize
  // a currently active project.
  if (!done && retries > 0) {
    setTimeout(() => highlightActiveProject(isEnabled, retries - 1), 100);
  }
}
<commit_msg>Typo fixes<commit_after>/** @babel */

/**
 * Copyright (c) 2016-present PlatformIO <contact@platformio.org>
 * All rights reserved.
 *
 * This source code is licensed under the license found in the LICENSE file in
 * the root directory of this source tree.
 */

import * as pioNodeHelpers from 'platformio-node-helpers';
import * as utils from './utils';

import fs from 'fs-plus';

export function reinstallPIOCore() {
  const envDir = pioNodeHelpers.core.getEnvDir();
  if (fs.isDirectorySync(envDir)) {
    try {
      fs.removeSync(envDir);
    } catch (err) {
      console.warn(err);
    }
  }
  atom.notifications.addWarning(
    'PlatformIO Core has been uninstalled!',
    {
      detail: 'Please restart Atom to install appropriate version',
      buttons: [
        {
          text: 'Restart',
          onDidClick: () => atom.restartApplication()
        }
      ],
      dismissable: true
    }
  );
}

export function notifyLinterDisabledforArduino() {
  if (localStorage.getItem('platformio-ide:linter-warned') === '2') {
    return;
  }

  atom.confirm({
    message: 'PlatformIO: Smart Code Linter',
    detailedMessage: 'Smart Code Linter (checking the C/C++ code on-the-fly) ' +
      'is disabled by default for Arduino files ("*.ino" and "*.pde").\n' +
      'Please use "*.cpp" instead or enable it manually.',
    buttons: {
      'Enable': () => {
        localStorage.setItem('platformio-ide:linter-warned', '2');
        utils.openUrl('http://docs.platformio.org/page/ide/atom.html#smart-code-linter-is-disabled-for-arduino-files');
      },
      'Remind Later': () => {},
      'Disable': () => localStorage.setItem('platformio-ide:linter-warned', '2')
    }
  });
}

export function notifyDebuggerIsDeprecated() {
  if (localStorage.getItem('platformio-ide:debugger-deprecated') === '1') {
    return;
  }

  atom.confirm({
    message: 'PlatformIO: Debugger for Atom is deprecated',
    detailedMessage: 'Please use PIO Unified Debugger for VSCode with advanced instruments ' +
      '(peripheral and registry views, disassembly, memory view, multithreading & RTOS, etc.)',
    buttons: {
      'Try VSCode': () => {
        utils.openUrl('https://platformio.org/platformio-ide');
      },
      'Remind Later': () => {},
      'Do not show this message': () => localStorage.setItem('platformio-ide:debugger-deprecated', '1')
    }
  });
}

export function notifyExtensionIsDeprecated() {
  if (localStorage.getItem('platformio-ide:extension-deprecated') === '1') {
    return;
  }

  atom.confirm({
    message: 'Try PlatformIO IDE for VSCode',
    detailedMessage: 'According to the users feedback, PlatformIO IDE for Atom has basic integration with PlatformIO ecosystem. ' +
      'This linked with a limited API of Atom text editor for C/C++ development. We highly recommend to try PlatformIO IDE for VSCode: ' +
      'built-in code navigation, completion, formatting, free PIO Unified Debugger with peripheral registers, memory explorer and much more! ' +
      'Your existing PlatformIO projects are fully compatible and do not require any changes!',
    buttons: {
      'Try VSCode': () => {
        utils.openUrl('https://platformio.org/platformio-ide');
      },
      'Remind Later': () => {},
      'Do not show this message': () => localStorage.setItem('platformio-ide:extension-deprecated', '1')
    }
  });
}

export function highlightActiveProject(isEnabled = true, retries = 3) {
  const p = utils.getActivePioProject();
  const dirs = [].slice.call(document.querySelectorAll('ol.tree-view-root > li'));
  dirs.forEach((dir) => {
    dir.classList.remove('pio-active-directory');
    if (!dir.dataset.pioProjectPath) {
      const span = dir.querySelector('.project-root-header > span[data-path]');
      dir.dataset.pioProjectPath = fs.realpathSync(span.dataset.path);
    }
  });
  if (dirs.length < 2 || !isEnabled || !p) {
    return;
  }

  let done = false;
  for (const dir of dirs) {
    if (dir.dataset.pioProjectPath === p) {
      dir.classList.add('pio-active-directory');
      done = true;
      break;
    }
  }
  // When running from `atom.project.onDidChangePaths()` or when Atom just starts,
  // an active project directory may not exist in tree-view yet. We should wait
  // for a while and repeat a search, or else user won't be able to recognize
  // a currently active project.
  if (!done && retries > 0) {
    setTimeout(() => highlightActiveProject(isEnabled, retries - 1), 100);
  }
}
<|endoftext|>


<commit_before>//Get the required shit together
const config = require("./config.json");
const API = require("./api.json");
const Discord = require("discord.js");
const client = new Discord.Client();
const MSS = require("./functions/");
const fs = require("fs");
var command = [];
var reaction = [];

//Login to Discord
client.login(API.discord);

//Include all files in the commands directory for commands
fs.readdir("./commands/", function(err, items) {
	items.forEach(function(item) {
		var file = item.replace(/['"]+/g, "");
		console.log(file);
		command[file] = require("./commands/" + file + "/");
	});
});

//Include all files in the commands directory for reactions
fs.readdir("./reactions/", function(err, items) {
	items.forEach(function(item) {
		var file = item.replace(/['"]+/g, "");
		if (file.endsWith(".js")) {
			file = file.replace(".js", "").toLowerCase();
			console.log(file);
			reaction[file] = require("./reactions/" + file);
		}
	});
	//List all avalible reactions
	//console.dir(reaction);
});

client.on("ready", function() {
	console.log("Successfully connected to Discord!");
	client.user.setGame(config.MSS.prefix + "man | " + config.MSS.version);
});

client.on("message", function(message) {
	console.log(message.content);

	//Split message into keywords
	let input = message.content.replace(/\n/g, "").split(" ");

	//Disallow if the author is a bot
	if (message.author.bot) return;

	//Remove the first term if it contains the bot ID, as well as the required brackets. Also make sure there's a second term to replace the first one.
	if (input[0].indexOf(client.user.id) != -1 && input[1]) {
		input.shift();
		//Add the !! back!!
		input[0] = "!!" + input[0];
	}

	//Check if the first term has the prefix
	if (!input[0].startsWith(config.MSS.prefix)) return false;

	//If it does, make the command lowercase and remove the prefix
	input[0] = input[0].substring(config.MSS.prefix.length).toLowerCase();

	//If the command exists, run the command
	if (command[input[0]]) {
		command[input[0]](message);
	}
});

client.on("messageReactionAdd", function(messageReaction, user) {
	//Not on other's messages
	if(!(messageReaction.message.author.id === client.user.id)) return;
	//Not if the author is a bot
	if (user.bot) return;

	//Get decimal codepoint of emoji
	var input = messageReaction.emoji.name.codePointAt().toString();

	console.log(input);

	if (reaction[input]) {
		reaction[input](messageReaction, user);
	}
});

process.on("unhandledRejection", function(err) {
  console.error("Uncaught Promise Error: \n" + err.stack);
});
<commit_msg>Add a message.content rebuilder<commit_after>//Get the required shit together
const config = require("./config.json");
const API = require("./api.json");
const Discord = require("discord.js");
const client = new Discord.Client();
const MSS = require("./functions/");
const fs = require("fs");
var command = [];
var reaction = [];

//Login to Discord
client.login(API.discord);

//Include all files in the commands directory for commands
fs.readdir("./commands/", function(err, items) {
	items.forEach(function(item) {
		var file = item.replace(/['"]+/g, "");
		console.log(file);
		command[file] = require("./commands/" + file + "/");
	});
});

//Include all files in the commands directory for reactions
fs.readdir("./reactions/", function(err, items) {
	items.forEach(function(item) {
		var file = item.replace(/['"]+/g, "");
		if (file.endsWith(".js")) {
			file = file.replace(".js", "").toLowerCase();
			console.log(file);
			reaction[file] = require("./reactions/" + file);
		}
	});
	//List all avalible reactions
	//console.dir(reaction);
});

client.on("ready", function() {
	console.log("Successfully connected to Discord!");
	client.user.setGame(config.MSS.prefix + "man | " + config.MSS.version);
});

client.on("message", function(message) {

	//Split message into keywords
	let input = message.content.replace(/\n/g, "").split(" ");

	//Disallow if the author is a bot
	if (message.author.bot) return;

	//Remove the first term if it contains the bot ID
	if (input[0].indexOf(client.user.id) != -1 && input[1]) {
		input.shift();
		//Rebuild the new message to fit the legacy format.
		message.content = input.join(" ");
	}

	//If there's a prefix, remove it. Otherwise, stop the execution of commands.
	if (input[0].startsWith(config.MSS.prefix)) {
		input[0] = input[0].substring(config.MSS.prefix.length).toLowerCase();
	} else {
		return false;
	}

	//If the command exists, run the command
	if (command[input[0]]) {
		command[input[0]](message);
	}
});

client.on("messageReactionAdd", function(messageReaction, user) {
	//Not on other's messages
	if(!(messageReaction.message.author.id === client.user.id)) return;
	//Not if the author is a bot
	if (user.bot) return;

	//Get decimal codepoint of emoji
	var input = messageReaction.emoji.name.codePointAt().toString();

	console.log(input);

	if (reaction[input]) {
		reaction[input](messageReaction, user);
	}
});

process.on("unhandledRejection", function(err) {
  console.error("Uncaught Promise Error: \n" + err.stack);
});
<|endoftext|>


<commit_before>(function() {
  var Logger = require('logger-facade-nodejs'),
      _ = require('lodash'),
      SMI = require('./smi'),
      Backend = require('./backend'),
      Frontend = require('./frontend');

  var Broker = function(configuration, smiService, frontend, backend){
    var defaults = {
      version: '0.0',
      frontend: 'tcp://127.0.0.1:5560',
      backend: 'tcp://127.0.0.1:5559',
      smi: {
        // heartbeat interval in ms
        heartbeat: 1000,
        // max ttl for a service in ms
        maxTTL: 1500,
        // refresh service ttl update interval in ms
        updateInterval: 100
      }
    };

    var config = _.defaults(configuration, defaults);
    var log = Logger.getLogger('Broker');

    // public methods

    this.run = function(){
      log.info("Async Broker v%s", config.version);

      smiService = smiService || new SMI(config.smi);
      smiService.run(config.smi);

      backend =  backend || new Backend({ backend: config.backend }, smiService);
      frontend = frontend || new Frontend({ frontend: config.frontend }, smiService);

      backend.frontendSendCallback = frontend.send;
      frontend.backendSendCallback = backend.send;

      backend.run();
      frontend.run();

      log.info("Async Broker is waiting for messages...\n");
    };

    this.stop = function(){
      log.info("\nAsync Broker disconnecting...");

      smiService.stop();
      frontend.stop();
      backend.stop();
    };

  };

  module.exports = Broker;
})();
<commit_msg>fix #9 - use module version as broker version<commit_after>(function() {
  var Logger = require('logger-facade-nodejs'),
      _ = require('lodash'),
      SMI = require('./smi'),
      Backend = require('./backend'),
      Frontend = require('./frontend'),
      packageJson = require('../package.json');

  var Broker = function(configuration, smiService, frontend, backend){
    var defaults = {
      frontend: 'tcp://127.0.0.1:5560',
      backend: 'tcp://127.0.0.1:5559',
      smi: {
        // heartbeat interval in ms
        heartbeat: 1000,
        // max ttl for a service in ms
        maxTTL: 1500,
        // refresh service ttl update interval in ms
        updateInterval: 100
      }
    };

    var config = _.defaults(configuration, defaults);

    // alway override version
    config.version = packageJson.version;

    var log = Logger.getLogger('Broker');

    // public methods

    this.run = function(){
      log.info("Async Broker v%s", config.version);

      smiService = smiService || new SMI(config.smi);
      smiService.run(config.smi);

      backend =  backend || new Backend({ backend: config.backend }, smiService);
      frontend = frontend || new Frontend({ frontend: config.frontend }, smiService);

      backend.frontendSendCallback = frontend.send;
      frontend.backendSendCallback = backend.send;

      backend.run();
      frontend.run();

      log.info("Async Broker is waiting for messages...\n");
    };

    this.stop = function(){
      log.info("\nAsync Broker disconnecting...");

      smiService.stop();
      frontend.stop();
      backend.stop();
    };

  };

  module.exports = Broker;
})();
<|endoftext|>


<commit_before>/**
 * An asynchronous local file system API, based on a subset
 * of the `narwhal/fs` API and the `narwhal/promise` API,
 * such that the method names are the same but some return
 * values are promises instead of fully resolved values.
 * @module
 */

/*whatsupdoc*/

var FS = require("fs"); // node
var Q = require("q");
var Reader = require("./reader");
var Writer = require("./writer");
var Common = require("./fs-common");
var Mock = require("./fs-mock");
var Root = require("./fs-root");

Common.update(exports, process.cwd);
exports.Mock = Mock;
exports.Root = Root;

// facilitates AIMD (additive increase, multiplicative decrease) for backing off
var backOffDelay = 0;
var backOffFactor = 1.0001;
function dampen(wrapped, thisp) {
    var retry = function () {
        var args = arguments;
        var ready = backOffDelay ? Q.delay(backOffDelay) : Q.resolve();
        return ready.then(function () {
            return Q.when(wrapped.apply(thisp, args), function (stream) {
                backOffDelay = Math.max(0, backOffDelay - 1);
                return stream;
            }, function (error) {
                if (error.code === "EMFILE") {
                    backOffDelay = (backOffDelay + 1) * backOffFactor;
                    return retry.apply(null, args);
                } else {
                    throw error;
                }
            });
        });
    };
    return retry;
}

/**
 * @param {String} path
 * @param {Object} options (flags, mode, bufferSize, charset, begin, end)
 * @returns {Promise * Stream} a stream from the `q-io` module.
 */
exports.open = dampen(function (path, flags, charset, options) {
    var self = this;
    if (typeof flags == "object") {
        options = flags;
        flags = options.flags;
        charset = options.charset;
    }
    options = options || {};
    flags = flags || "r";
    var nodeOptions = {
        "flags": flags.replace(/b/g, "")
    };
    if ("bufferSize" in options) {
        nodeOptions.bufferSize = options.bufferSize;
    }
    if ("mode" in options) {
        nodeOptions.mode = options.mode;
    }
    if ("begin" in options) {
        nodeOptions.start = options.begin;
        nodeOptions.end = options.end - 1;
    }
    if (flags.indexOf("b") >= 0) {
        if (charset) {
            throw new Error("Can't open a binary file with a charset: " + charset);
        }
    } else {
        charset = charset || 'utf-8';
    }
    if (flags.indexOf("w") >= 0) {
        var stream = FS.createWriteStream(String(path), nodeOptions);
        return Writer(stream, charset);
    } else {
        var stream = FS.createReadStream(String(path), nodeOptions);
        return Reader(stream, charset);
    }
});

exports.remove = function (path) {
    path = String(path);
    var done = Q.defer();
    FS.unlink(path, function (error) {
        if (error) {
            error.message = "Can't remove " + JSON.stringify(path) + ": " + error.message;
            done.reject(error);
        } else {
            done.resolve();
        }
    });
    return done.promise;
};

exports.move = function (source, target) {
    source = String(source);
    target = String(target);
    return exports.exists(target)
    .then(function (exists) {
        if (exists) {
            var error = new Error("Can't move over existing entry " + target);
            error.code = "EEXISTS";
            throw error;
        }
        return Q.ninvoke(FS, "rename", source, target)
        .fail(function (error) {
            error.message = (
                "Can't move " + JSON.stringify(source) + " to " +
                JSON.stringify(target) + " because " + error.message
            );
            throw error;
        });
    });
};

exports.makeDirectory = function (path, mode) {
    path = String(path);
    var done = Q.defer();
    if (typeof mode === "string") {
        mode = parseInt(mode, 8);
    } else if (mode === void 0) {
        mode = parseInt('755', 8);
    }
    FS.mkdir(path, mode, function (error) {
        if (error) {
            error.message = "Can't makeDirectory " + JSON.stringify(path) + " with mode " + mode + ": " + error.message;
            if (error.code === "EISDIR") {
                error.exists = true;
                error.isDirectory = true;
            }
            if (error.code === "EEXIST") {
                error.exists = true;
            }
            done.reject(error);
        } else {
            done.resolve();
        }
    });
    return done.promise;
};

exports.removeDirectory = function (path) {
    path = String(path);
    var done = Q.defer();
    FS.rmdir(path, function (error) {
        if (error) {
            error.message = "Can't removeDirectory " + JSON.stringify(path) + ": " + error.message;
            done.reject(error);
        } else {
            done.resolve();
        }
    });
    return done.promise;
};

/**
 */
exports.list = dampen(function (path) {
    path = String(path);
    var result = Q.defer();
    FS.readdir(path, function (error, list) {
        if (error) {
            error.message = "Can't list " + JSON.stringify(path) + ": " + error.message;
            return result.reject(error);
        } else {
            result.resolve(list);
        }
    });
    return result.promise;
});

/**
 * @param {String} path
 * @returns {Promise * Stat}
 */
exports.stat = function (path) {
    var self = this;
    path = String(path);
    var done = Q.defer();
    try {
        FS.stat(path, function (error, stat) {
            if (error) {
                error.message = "Can't stat " + JSON.stringify(path) + ": " + error;
                done.reject(error);
            } else {
                done.resolve(new Stats(stat));
            }
        });
    } catch (error) {
        done.reject(error);
    }
    return done.promise;
};

var Stats = function (nodeStat) {
    this.node = nodeStat;
    this.size = nodeStat.size;
};

var stats = [
    "isDirectory",
    "isFile",
    "isBlockDevice",
    "isCharacterDevice",
    "isSymbolicLink",
    "isFIFO",
    "isSocket"
];

stats.forEach(function (name) {
    Stats.prototype[name] = function () {
        return this.node[name]();
    };
});

Stats.prototype.lastModified = function () {
    return new Date(this.node.mtime);
};

Stats.prototype.lastAccessed = function () {
    return new Date(this.node.atime);
};

exports.statLink = function (path) {
    path = String(path);
    var done = Q.defer();
    try {
        FS.lstat(path, function (error, stat) {
            if (error) {
                error.message = "Can't statLink " + JSON.stringify(path) + ": " + error.message;
                done.reject(error);
            } else {
                done.resolve(stat);
            }
        });
    } catch (error) {
        done.reject(error);
    }
    return done.promise;
};

exports.statFd = function (fd) {
    fd = Number(fd);
    var done = Q.defer();
    try {
        FS.fstat(fd, function (error, stat) {
            if (error) {
                error.message = "Can't statFd file descriptor " + JSON.stringify(fd) + ": " + error.message;
                done.reject(error);
            } else {
                done.resolve(stat);
            }
        });
    } catch (error) {
        done.reject(error);
    }
    return done.promise;
};

exports.link = function (source, target) {
    source = String(source);
    target = String(target);
    var done = Q.defer();
    try {
        FS.link(source, target, function (error) {
            if (error) {
                error.message = "Can't link " + JSON.stringify(source) + " to " + JSON.stringify(target) + ": " + error.message;
                done.reject(error);
            } else {
                done.resolve();
            }
        });
    } catch (error) {
        done.reject(error);
    }
    return done.promise;
};

// this lookup table translates the link types that Q-IO accepts (which have
// been normalized to full words to be consistent with the naming convention)
var linkTypes = {
    "file": "file",
    "directory": "dir",
    "junction": "junction"
};

exports.symbolicLink = function (target, relative, type) {
    if (!linkTypes.hasOwnProperty(type)) {
        console.warn(new Error("For Windows compatibility, symbolicLink must be called with a type argument \"file\", \"directory\", or \"junction\""));
    }
    type = linkTypes[type];
    target = String(target);
    relative = String(relative);
    var done = Q.defer();
    try {
        FS.symlink(relative, target, type || 'file', function (error) {
            if (error) {
                error.message = "Can't create symbolicLink " + JSON.stringify(target) + " to relative location " + JSON.stringify(relative) + ": " + error.message;
                done.reject(error);
            } else {
                done.resolve();
            }
        });
    } catch (error) {
        done.reject(error);
    }
    return done.promise;
};

exports.chown = function (path, uid, gid) {
    path = String(path);
    var done = Q.defer();
    try {
        FS.chown(path, uid, gid, function (error) {
            if (error) {
                error.message = "Can't chown (change owner) of " + JSON.stringify(path) + " to user " + JSON.stringify(uid) + " and group " + JSON.stringify(gid) + ": " + error.message;
                done.reject(error);
            } else {
                done.resolve();
            }
        });
    } catch (error) {
        done.reject(error);
    }
    return done.promise;
};

exports.chmod = function (path, mode) {
    path = String(path);
    mode = String(mode);
    var done = Q.defer();
    try {
        FS.chmod(path, mode, function (error) {
            if (error) {
                error.message = "Can't chmod (change permissions mode) of " + JSON.stringify(path) + " to (octal number) " + mode.toString(8) + ": " + error.message;
                done.reject(error);
            } else {
                done.resolve();
            }
        });
    } catch (error) {
        done.reject(error);
    }
    return done.promise;
};

exports.canonical = function (path) {
    var result = Q.defer();
    FS.realpath(path, function (error, canonicalPath) {
        if (error) {
            error.message = "Can't get canonical path of " + JSON.stringify(path) + " by way of C realpath: " + error.message;
            result.reject(error);
        } else {
            result.resolve(canonicalPath);
        }
    });
    return result.promise;
};

exports.readLink = function (path) {
    var result = Q.defer();
    FS.readlink(path, function (error, path) {
        if (error) {
            error.message = "Can't get link from " + JSON.stringify(path) + " by way of C readlink: " + error.message;
            result.reject(error);
        } else {
            result.resolve(path);
        }
    });
    return result.promise;
};

exports.mock = function (path) {
    return Mock.mock(this, path);
};

<commit_msg>Allow overwrite in move<commit_after>/**
 * An asynchronous local file system API, based on a subset
 * of the `narwhal/fs` API and the `narwhal/promise` API,
 * such that the method names are the same but some return
 * values are promises instead of fully resolved values.
 * @module
 */

/*whatsupdoc*/

var FS = require("fs"); // node
var Q = require("q");
var Reader = require("./reader");
var Writer = require("./writer");
var Common = require("./fs-common");
var Mock = require("./fs-mock");
var Root = require("./fs-root");

Common.update(exports, process.cwd);
exports.Mock = Mock;
exports.Root = Root;

// facilitates AIMD (additive increase, multiplicative decrease) for backing off
var backOffDelay = 0;
var backOffFactor = 1.0001;
function dampen(wrapped, thisp) {
    var retry = function () {
        var args = arguments;
        var ready = backOffDelay ? Q.delay(backOffDelay) : Q.resolve();
        return ready.then(function () {
            return Q.when(wrapped.apply(thisp, args), function (stream) {
                backOffDelay = Math.max(0, backOffDelay - 1);
                return stream;
            }, function (error) {
                if (error.code === "EMFILE") {
                    backOffDelay = (backOffDelay + 1) * backOffFactor;
                    return retry.apply(null, args);
                } else {
                    throw error;
                }
            });
        });
    };
    return retry;
}

/**
 * @param {String} path
 * @param {Object} options (flags, mode, bufferSize, charset, begin, end)
 * @returns {Promise * Stream} a stream from the `q-io` module.
 */
exports.open = dampen(function (path, flags, charset, options) {
    var self = this;
    if (typeof flags == "object") {
        options = flags;
        flags = options.flags;
        charset = options.charset;
    }
    options = options || {};
    flags = flags || "r";
    var nodeOptions = {
        "flags": flags.replace(/b/g, "")
    };
    if ("bufferSize" in options) {
        nodeOptions.bufferSize = options.bufferSize;
    }
    if ("mode" in options) {
        nodeOptions.mode = options.mode;
    }
    if ("begin" in options) {
        nodeOptions.start = options.begin;
        nodeOptions.end = options.end - 1;
    }
    if (flags.indexOf("b") >= 0) {
        if (charset) {
            throw new Error("Can't open a binary file with a charset: " + charset);
        }
    } else {
        charset = charset || 'utf-8';
    }
    if (flags.indexOf("w") >= 0) {
        var stream = FS.createWriteStream(String(path), nodeOptions);
        return Writer(stream, charset);
    } else {
        var stream = FS.createReadStream(String(path), nodeOptions);
        return Reader(stream, charset);
    }
});

exports.remove = function (path) {
    path = String(path);
    var done = Q.defer();
    FS.unlink(path, function (error) {
        if (error) {
            error.message = "Can't remove " + JSON.stringify(path) + ": " + error.message;
            done.reject(error);
        } else {
            done.resolve();
        }
    });
    return done.promise;
};

exports.move = function (source, target, overwrite) {
    var checkExists;
    source = String(source);
    target = String(target);
    if (!overwrite) {
        checkExists = exports.exists(target)
        .then(function (exists) {
            if (exists) {
                var error = new Error("Can't move over existing entry " + target);
                error.code = "EEXISTS";
                throw error;
            }
        });
    } else {
        checkExists = Q();
    }
    return checkExists.then(function () {
        return Q.ninvoke(FS, "rename", source, target)
        .fail(function (error) {
            error.message = (
                "Can't move " + JSON.stringify(source) + " to " +
                JSON.stringify(target) + " because " + error.message
            );
            throw error;
        });
    });
};

exports.makeDirectory = function (path, mode) {
    path = String(path);
    var done = Q.defer();
    if (typeof mode === "string") {
        mode = parseInt(mode, 8);
    } else if (mode === void 0) {
        mode = parseInt('755', 8);
    }
    FS.mkdir(path, mode, function (error) {
        if (error) {
            error.message = "Can't makeDirectory " + JSON.stringify(path) + " with mode " + mode + ": " + error.message;
            if (error.code === "EISDIR") {
                error.exists = true;
                error.isDirectory = true;
            }
            if (error.code === "EEXIST") {
                error.exists = true;
            }
            done.reject(error);
        } else {
            done.resolve();
        }
    });
    return done.promise;
};

exports.removeDirectory = function (path) {
    path = String(path);
    var done = Q.defer();
    FS.rmdir(path, function (error) {
        if (error) {
            error.message = "Can't removeDirectory " + JSON.stringify(path) + ": " + error.message;
            done.reject(error);
        } else {
            done.resolve();
        }
    });
    return done.promise;
};

/**
 */
exports.list = dampen(function (path) {
    path = String(path);
    var result = Q.defer();
    FS.readdir(path, function (error, list) {
        if (error) {
            error.message = "Can't list " + JSON.stringify(path) + ": " + error.message;
            return result.reject(error);
        } else {
            result.resolve(list);
        }
    });
    return result.promise;
});

/**
 * @param {String} path
 * @returns {Promise * Stat}
 */
exports.stat = function (path) {
    var self = this;
    path = String(path);
    var done = Q.defer();
    try {
        FS.stat(path, function (error, stat) {
            if (error) {
                error.message = "Can't stat " + JSON.stringify(path) + ": " + error;
                done.reject(error);
            } else {
                done.resolve(new Stats(stat));
            }
        });
    } catch (error) {
        done.reject(error);
    }
    return done.promise;
};

var Stats = function (nodeStat) {
    this.node = nodeStat;
    this.size = nodeStat.size;
};

var stats = [
    "isDirectory",
    "isFile",
    "isBlockDevice",
    "isCharacterDevice",
    "isSymbolicLink",
    "isFIFO",
    "isSocket"
];

stats.forEach(function (name) {
    Stats.prototype[name] = function () {
        return this.node[name]();
    };
});

Stats.prototype.lastModified = function () {
    return new Date(this.node.mtime);
};

Stats.prototype.lastAccessed = function () {
    return new Date(this.node.atime);
};

exports.statLink = function (path) {
    path = String(path);
    var done = Q.defer();
    try {
        FS.lstat(path, function (error, stat) {
            if (error) {
                error.message = "Can't statLink " + JSON.stringify(path) + ": " + error.message;
                done.reject(error);
            } else {
                done.resolve(stat);
            }
        });
    } catch (error) {
        done.reject(error);
    }
    return done.promise;
};

exports.statFd = function (fd) {
    fd = Number(fd);
    var done = Q.defer();
    try {
        FS.fstat(fd, function (error, stat) {
            if (error) {
                error.message = "Can't statFd file descriptor " + JSON.stringify(fd) + ": " + error.message;
                done.reject(error);
            } else {
                done.resolve(stat);
            }
        });
    } catch (error) {
        done.reject(error);
    }
    return done.promise;
};

exports.link = function (source, target) {
    source = String(source);
    target = String(target);
    var done = Q.defer();
    try {
        FS.link(source, target, function (error) {
            if (error) {
                error.message = "Can't link " + JSON.stringify(source) + " to " + JSON.stringify(target) + ": " + error.message;
                done.reject(error);
            } else {
                done.resolve();
            }
        });
    } catch (error) {
        done.reject(error);
    }
    return done.promise;
};

// this lookup table translates the link types that Q-IO accepts (which have
// been normalized to full words to be consistent with the naming convention)
var linkTypes = {
    "file": "file",
    "directory": "dir",
    "junction": "junction"
};

exports.symbolicLink = function (target, relative, type) {
    if (!linkTypes.hasOwnProperty(type)) {
        console.warn(new Error("For Windows compatibility, symbolicLink must be called with a type argument \"file\", \"directory\", or \"junction\""));
    }
    type = linkTypes[type];
    target = String(target);
    relative = String(relative);
    var done = Q.defer();
    try {
        FS.symlink(relative, target, type || 'file', function (error) {
            if (error) {
                error.message = "Can't create symbolicLink " + JSON.stringify(target) + " to relative location " + JSON.stringify(relative) + ": " + error.message;
                done.reject(error);
            } else {
                done.resolve();
            }
        });
    } catch (error) {
        done.reject(error);
    }
    return done.promise;
};

exports.chown = function (path, uid, gid) {
    path = String(path);
    var done = Q.defer();
    try {
        FS.chown(path, uid, gid, function (error) {
            if (error) {
                error.message = "Can't chown (change owner) of " + JSON.stringify(path) + " to user " + JSON.stringify(uid) + " and group " + JSON.stringify(gid) + ": " + error.message;
                done.reject(error);
            } else {
                done.resolve();
            }
        });
    } catch (error) {
        done.reject(error);
    }
    return done.promise;
};

exports.chmod = function (path, mode) {
    path = String(path);
    mode = String(mode);
    var done = Q.defer();
    try {
        FS.chmod(path, mode, function (error) {
            if (error) {
                error.message = "Can't chmod (change permissions mode) of " + JSON.stringify(path) + " to (octal number) " + mode.toString(8) + ": " + error.message;
                done.reject(error);
            } else {
                done.resolve();
            }
        });
    } catch (error) {
        done.reject(error);
    }
    return done.promise;
};

exports.canonical = function (path) {
    var result = Q.defer();
    FS.realpath(path, function (error, canonicalPath) {
        if (error) {
            error.message = "Can't get canonical path of " + JSON.stringify(path) + " by way of C realpath: " + error.message;
            result.reject(error);
        } else {
            result.resolve(canonicalPath);
        }
    });
    return result.promise;
};

exports.readLink = function (path) {
    var result = Q.defer();
    FS.readlink(path, function (error, path) {
        if (error) {
            error.message = "Can't get link from " + JSON.stringify(path) + " by way of C readlink: " + error.message;
            result.reject(error);
        } else {
            result.resolve(path);
        }
    });
    return result.promise;
};

exports.mock = function (path) {
    return Mock.mock(this, path);
};

<|endoftext|>


<commit_before>/**
 * A view for managing the administration UI's database model change pages.
 *
 * This sets up the page to manage the configuration form and any inline
 * groups used for adding, modifying, or deleting related objects.
 */
RB.Admin.ChangeFormPageView = RB.Admin.PageView.extend({
    /**
     * Initialize the view.
     *
     * Args:
     *     options (object):
     *         The options passed to the page.
     *
     * Option Args:
     *     formID (string):
     *         The element ID for the form.
     */
    initialize(options) {
        RB.Admin.PageView.prototype.initialize.call(this, options);

        this.formID = options.formID;
        this.formView = null;
        this.inlineGroupViews = [];
    },

    /**
     * Render the page.
     *
     * This will set up the form and inline group management.
     */
    renderPage() {
        RB.Admin.PageView.prototype.renderPage.call(this);

        console.assert(this.inlineGroupViews.length === 0);

        this.formView = new RB.FormView({
            el: $(`#${this.formID}`),
        });
        this.formView.render();

        this.$('.rb-c-admin-form-inline-group').each((i, el) => {
            const inlineGroup = new RB.Admin.InlineFormGroup({
                prefix: $(el).data('prefix'),
            });
            const inlineGroupView = new RB.Admin.InlineFormGroupView({
                el: el,
                model: inlineGroup,
            });
            inlineGroupView.renderPage();

            this.inlineGroupViews.push(inlineGroupView);

            this.listenTo(
                inlineGroupView,
                'inlineFormAdded',
                () => this.formView.setupFormWidgets(inlineGroupView.$el));
        });
    },
});
<commit_msg>Fix a bad render call when rendering change form pages.<commit_after>/**
 * A view for managing the administration UI's database model change pages.
 *
 * This sets up the page to manage the configuration form and any inline
 * groups used for adding, modifying, or deleting related objects.
 */
RB.Admin.ChangeFormPageView = RB.Admin.PageView.extend({
    /**
     * Initialize the view.
     *
     * Args:
     *     options (object):
     *         The options passed to the page.
     *
     * Option Args:
     *     formID (string):
     *         The element ID for the form.
     */
    initialize(options) {
        RB.Admin.PageView.prototype.initialize.call(this, options);

        this.formID = options.formID;
        this.formView = null;
        this.inlineGroupViews = [];
    },

    /**
     * Render the page.
     *
     * This will set up the form and inline group management.
     */
    renderPage() {
        RB.Admin.PageView.prototype.renderPage.call(this);

        console.assert(this.inlineGroupViews.length === 0);

        this.formView = new RB.FormView({
            el: $(`#${this.formID}`),
        });
        this.formView.render();

        this.$('.rb-c-admin-form-inline-group').each((i, el) => {
            const inlineGroup = new RB.Admin.InlineFormGroup({
                prefix: $(el).data('prefix'),
            });
            const inlineGroupView = new RB.Admin.InlineFormGroupView({
                el: el,
                model: inlineGroup,
            });
            inlineGroupView.render();

            this.inlineGroupViews.push(inlineGroupView);

            this.listenTo(
                inlineGroupView,
                'inlineFormAdded',
                () => this.formView.setupFormWidgets(inlineGroupView.$el));
        });
    },
});
<|endoftext|>


<commit_before>#!/usr/bin/env node

'strict mode';

const venezuela = require('./index');
const pkg = require('./package.json');
const updateNotifier = require('update-notifier');
const program = require('commander');
const colors = require('colors');

updateNotifier({pkg: pkg}).notify();

program
  .version(pkg.version)
  .usage('<estado|municipio|parroquia> [opciones]')
  .description(colors.yellow('Muestra información sobre el territorio Venezolano.'.bold))
  .option('-a, --ayuda', 'muestra cómo utilizar venezuela-js')
  .option('-c, --capital nombre', 'muestra la capital de la entidad')
  .option('-m, --municipio nombre', 'muestra la información de un municipio')
  .option('-p, --parroquia nombre', 'muestra la información de una parroquia')
  .option('-M, --municipios nombre', 'muestra todos los municipios de un estado')
  .parse(process.argv);

program.on('--help', () => {
  const mensaje = `
  Ejemplos:

    $ venezuela "Nueva Esparta"
    $ venezuela Zulia
    $ venezuela --capital
    $ venezuela --municipio Libertador
    $ venezuela --parroquia "San Juan"
    $ venezuela Bolívar -M
    $ venezuela Falcón -c
  `;

  console.log(mensaje);
});

const crear = (function () {
  return {
    bandera,
    entidad,
    entidades,
    listaDeMunicipios
  };

  function bandera() {
    const amarillo = colors.yellow.bold('▓▒');
    const azul = colors.blue.bold('▓▒');
    const rojo = colors.red.bold('▓▒');
    const bandera = `${amarillo}${azul}${rojo}`;

    return bandera;
  }

  function entidad(datos) {
    return Object.keys(datos).map(nombre => {
      const titulo = nombre.replace('_', ' ').toUpperCase();
      const contenido = typeof datos[nombre] === 'number' ? datos[nombre] : datos[nombre].toUpperCase();
      const tituloConEstilo = colors.white.bold(titulo);
      const contenidoConEstilo = colors.yellow.bold(contenido);

      return `${tituloConEstilo}${' '.repeat(4)}${contenidoConEstilo}`;
    }).join('\n');
  };

  function entidades(datos) {
    return datos.map(dato => entidad(dato)).join('\n\n');
  }

  function listaDeMunicipios(datos) {
    const titulo = `MUNICIPIOS DEL ESTADO ${datos.estado.toUpperCase()}`;
    const tituloConEstilo = colors.white.bold(titulo);
    const municipios = parrafo(datos.municipios);
    const informacion = `${tituloConEstilo}\n\n${municipios}`;

    return informacion;
  }

  function parrafo(palabras) {
    const numeroDeGrupos = palabras.length / 3;
    let grupos = [];
    let parrafo;

    for (let n = 0; n < numeroDeGrupos; n++) {
      const grupo = palabras.slice(n*3, n*3+3)
        .map((palabra, indice) => indice === 0 ? palabra : ` • ${palabra}`);

      grupos = [...grupos, grupo];
    }

    parrafo = grupos.map(grupo => grupo.join(''))
      .reduce((parrafo, oracion) => `${parrafo}\n${oracion}`);

    return colors.yellow.bold(parrafo);
  }
})();

const mostrar = (function () {
  return {
    resultado: procesar
  };

  function procesar(datos) {
    let contenido;

    if (!datos) {
      contenido = colors.white.bold('Nombre inválido.');
    } else if (typeof datos === 'string') {
      contenido = colors.white.bold(datos);
    } else if (Array.isArray(datos)) {
      contenido = crear.entidades(datos);
    } else if (Array.isArray(datos.municipios)) {
      contenido = crear.listaDeMunicipios(datos);
    } else {
      contenido = crear.entidad(datos);
    }

    console.log(`\n${' '.repeat(4)}${crear.bandera()}\n\n${contenido}`);
  }
})();

(function consultar() {
  const nombre = program.args ? program.args[0] : undefined;
  let necesitaAyuda = false;
  let datos;

  if (!nombre && program.capital) {
    datos = venezuela.capital;
  } else if (program.capital) {
    const data = (venezuela.estado(nombre) ||
      venezuela.municipio(nombre) ||
        venezuela.parroquia(nombre));

    datos = data ? data.capital : undefined;
  } else if (program.municipios) {
    datos = venezuela.estado(nombre, {municipios: true});
  } else if (program.municipio) {
    datos = venezuela.municipio(nombre);
  } else if (program.parroquia) {
    datos = venezuela.parroquia(nombre);
  } else if (program.ayuda || process.argv.length === 2) {
    necesitaAyuda = true;
  } else if (process.argv.length === 3) {
    datos = (venezuela.estado(nombre) ||
      venezuela.municipio(nombre) ||
        venezuela.parroquia(nombre));
  }

  necesitaAyuda ? program.help() : mostrar.resultado(datos);
})();
<commit_msg>chore(cli): mejora consistencia & legibilidad<commit_after>#!/usr/bin/env node

'strict mode';

const venezuela = require('./index');
const pkg = require('./package.json');
const updateNotifier = require('update-notifier');
const program = require('commander');
const colors = require('colors');

updateNotifier({pkg: pkg}).notify();

program
  .version(pkg.version)
  .usage('<estado|municipio|parroquia> [opciones]')
  .description(colors.yellow('Muestra información sobre el territorio Venezolano.'.bold))
  .option('-a, --ayuda', 'muestra cómo utilizar venezuela-js')
  .option('-c, --capital nombre', 'muestra la capital de la entidad')
  .option('-m, --municipio nombre', 'muestra la información de un municipio')
  .option('-p, --parroquia nombre', 'muestra la información de una parroquia')
  .option('-M, --municipios nombre', 'muestra todos los municipios de un estado')
  .parse(process.argv);

program.on('--help', () => {
  const mensaje = `
  Ejemplos:

    $ venezuela "Nueva Esparta"
    $ venezuela Zulia
    $ venezuela --capital
    $ venezuela --municipio Libertador
    $ venezuela --parroquia "San Juan"
    $ venezuela Bolívar -M
    $ venezuela Falcón -c
  `;

  console.log(mensaje);
});

const crear = (function () {
  return {
    bandera,
    entidad,
    entidades,
    listaDeMunicipios
  };

  function bandera() {
    const amarillo = colors.yellow.bold('▓▒');
    const azul = colors.blue.bold('▓▒');
    const rojo = colors.red.bold('▓▒');
    const bandera = `${amarillo}${azul}${rojo}`;

    return bandera;
  }

  function entidad(datos) {
    return Object.keys(datos).map(nombre => {
      const titulo = nombre.replace('_', ' ').toUpperCase();
      const contenido = String(datos[nombre]).toUpperCase();
      const tituloConEstilo = colors.white.bold(titulo);
      const contenidoConEstilo = colors.yellow.bold(contenido);

      return `${tituloConEstilo} ${contenidoConEstilo}`;
    }).join('\n');
  };

  function entidades(datos) {
    return datos.map(dato => entidad(dato)).join('\n\n');
  }

  function listaDeMunicipios(datos) {
    const titulo = `MUNICIPIOS DEL ESTADO ${datos.estado.toUpperCase()}`;
    const tituloConEstilo = colors.white.bold(titulo);
    const contenido = parrafo(datos.municipios);

    return `${tituloConEstilo}\n\n${contenido}`;
  }

  function parrafo(palabras) {
    const numeroDeGrupos = palabras.length / 3;
    let grupos = [];
    let parrafo;

    for (let n = 0; n < numeroDeGrupos; n++) {
      const grupo = palabras.slice(n*3, n*3+3)
        .map((palabra, indice) => indice === 0 ? palabra : ` • ${palabra}`);

      grupos = [...grupos, grupo];
    }

    parrafo = grupos.map(grupo => grupo.join(''))
      .reduce((parrafo, oracion) => `${parrafo}\n${oracion}`);

    return colors.yellow.bold(parrafo);
  }
})();

const mostrar = (function () {
  return {
    resultado: procesar
  };

  function procesar(datos) {
    let contenido;

    if (!datos) {
      contenido = colors.white.bold('Nombre inválido.');
    } else if (typeof datos === 'string') {
      contenido = colors.white.bold(datos);
    } else if (Array.isArray(datos)) {
      contenido = crear.entidades(datos);
    } else if (Array.isArray(datos.municipios)) {
      contenido = crear.listaDeMunicipios(datos);
    } else {
      contenido = crear.entidad(datos);
    }

    console.log(`\n${' '.repeat(4)}${crear.bandera()}\n\n${contenido}`);
  }
})();

(function consultar() {
  const nombre = program.args ? program.args[0] : undefined;
  let necesitaAyuda = false;
  let datos;

  if (!nombre && program.capital) {
    datos = venezuela.capital;
  } else if (program.capital) {
    const data = (venezuela.estado(nombre) ||
      venezuela.municipio(nombre) ||
        venezuela.parroquia(nombre));

    datos = data ? data.capital : undefined;
  } else if (program.municipios) {
    datos = venezuela.estado(nombre, {municipios: true});
  } else if (program.municipio) {
    datos = venezuela.municipio(nombre);
  } else if (program.parroquia) {
    datos = venezuela.parroquia(nombre);
  } else if (program.ayuda || process.argv.length === 2) {
    necesitaAyuda = true;
  } else if (process.argv.length === 3) {
    datos = (venezuela.estado(nombre) ||
      venezuela.municipio(nombre) ||
        venezuela.parroquia(nombre));
  }

  necesitaAyuda ? program.help() : mostrar.resultado(datos);
})();
<|endoftext|>