<commit_before>import {Text, BlockQuote, OrderedList, BulletList, ListItem,
        HorizontalRule, Paragraph, Heading, CodeBlock, Image, HardBreak,
        EmMark, StrongMark, LinkMark, CodeMark} from "../model"
import {defineTarget} from "../format"

// :: (Node, ?Object) → string
// Serialize the content of the given node to [CommonMark](http://commonmark.org/).
//
// To define serialization behavior for your own [node
// types](#NodeType), give them a `serializeMarkDown` method. It will
// be called with a `MarkdownSerializer` and a `Node`, and should
// update the serializer's state to add the content of the node.
//
// [Mark types](#MarkType) can define `openMarkdown` and
// `closeMarkdown` properties, which provide the markup text that
// marked content should be wrapped in. They may hold either a string
// or a function from a `MarkdownSerializer` and a `Mark` to a string.
export function toMarkdown(doc, options) {
  let state = new MarkdownSerializer(options)
  state.renderContent(doc)
  return state.out
}

defineTarget("markdown", toMarkdown)

// ;; This is an object used to track state and expose
// methods related to markdown serialization. Instances are passed to
// node and mark serialization methods (see `toMarkdown`).
class MarkdownSerializer {
  constructor(options) {
    this.delim = this.out = ""
    this.closed = false
    this.inTightList = false
    // :: Object
    // The options passed to the serializer.
    this.options = options
  }

  flushClose(size) {
    if (this.closed) {
      if (!this.atBlank()) this.out += "\n"
      if (size == null) size = 2
      if (size > 1) {
        let delimMin = this.delim
        let trim = /\s+$/.exec(delimMin)
        if (trim) delimMin = delimMin.slice(0, delimMin.length - trim[0].length)
        for (let i = 1; i < size; i++)
          this.out += delimMin + "\n"
      }
      this.closed = false
    }
  }

  // :: (string, ?string, Node, ())
  // Render a block, prefixing each line with `delim`, and the first
  // line in `firstDelim`. `node` should be the node that is closed at
  // the end of the block, and `f` is a function that renders the
  // content of the block.
  wrapBlock(delim, firstDelim, node, f) {
    let old = this.delim
    this.write(firstDelim || delim)
    this.delim += delim
    f()
    this.delim = old
    this.closeBlock(node)
  }

  atBlank() {
    return /(^|\n)$/.test(this.out)
  }

  // :: ()
  // Ensure the current content ends with a newline.
  ensureNewLine() {
    if (!this.atBlank()) this.out += "\n"
  }

  // :: (?string)
  // Prepare the state for writing output (closing closed paragraphs,
  // adding delimiters, and so on), and then optionally add content
  // (unescaped) to the output.
  write(content) {
    this.flushClose()
    if (this.delim && this.atBlank())
      this.out += this.delim
    if (content) this.out += content
  }

  // :: (Node)
  // Close the block for the given node.
  closeBlock(node) {
    this.closed = node
  }

  // :: (string, ?bool)
  // Add the given text to the document. When escape is not `false`,
  // it will be escaped.
  text(text, escape) {
    let lines = text.split("\n")
    for (let i = 0; i < lines.length; i++) {
      var startOfLine = this.atBlank() || this.closed
      this.write()
      this.out += escape !== false ? this.esc(lines[i], startOfLine) : lines[i]
      if (i != lines.length - 1) this.out += "\n"
    }
  }

  // :: (Node)
  // Render the given node as a block.
  render(node) {
    node.type.serializeMarkdown(this, node)
  }

  // :: (Node)
  // Render the contents of `parent` as block nodes.
  renderContent(parent) {
    parent.forEach(child => this.render(child))
  }

  // :: (Node)
  // Render the contents of `parent` as inline content.
  renderInline(parent) {
    let stack = []
    let progress = node => {
      let marks = node ? node.marks.slice() : []
      if (stack.length && stack[stack.length - 1].type == "code" &&
          (!marks.length || marks[marks.length - 1].type != "code")) {
        this.text("`", false)
        stack.pop()
      }
      // Check the stack for opening marks that have been serialized,
      // and serialize a closing mark if the mark doesn't continue
      // into the next node.
      for (let j = stack.length - 1; j >= 0; j--) {
        let cur = stack[j], found = false
        for (let k = 0; k < marks.length; k++) {
          if (marks[k].eq(stack[j])) {
            marks.splice(k, 1)
            found = true
            break
          }
        }
        if (!found) {
          this.text(this.markString(cur, false), false)
          stack.splice(j, 1)
        }
      }
      for (let j = 0; j < marks.length; j++) {
        let cur = marks[j]
        stack.push(cur)
        this.text(this.markString(cur, true), false)
      }
      if (node) this.render(node)
    }
    parent.forEach(progress)
    progress(null)
  }

  renderList(node, delim, firstDelim) {
    if (this.closed && this.closed.type == node.type)
      this.flushClose(3)
    else if (this.inTightList)
      this.flushClose(1)

    let prevTight = this.inTightList
    this.inTightList = node.attrs.tight
    for (let i = node.iter(), n = 0, item; item = i.next().value; n++) {
      if (n && node.attrs.tight) this.flushClose(1)
      this.wrapBlock(delim, firstDelim(n), node, () => this.render(item))
    }
    this.inTightList = prevTight
  }

  // :: (string, ?bool) → string
  // Escape the given string so that it can safely appear in Markdown
  // content. If `startOfLine` is true, also escape characters that
  // has special meaning only at the start of the line.
  esc(str, startOfLine) {
    str = str.replace(/[`*\\~+\[\]]/g, "\\$&")
    if (startOfLine) str = str.replace(/^[:#-]/, "\\$&")
    return str
  }

  quote(str) {
    var wrap = str.indexOf('"') == -1 ? '""' : str.indexOf("'") == -1 ? "''" : "()"
    return wrap[0] + str + wrap[1]
  }

  // :: (string, number) → string
  // Repeat the given string `n` times.
  repeat(str, n) {
    let out = ""
    for (let i = 0; i < n; i++) out += str
    return out
  }

  // : (Mark, bool) → string
  // Get the markdown string for a given opening or closing mark.
  markString(mark, open) {
    let value = open ? mark.type.openMarkdown : mark.type.closeMarkdown
    return typeof value == "string" ? value : value(this, mark)
  }
}

function def(cls, method) { cls.prototype.serializeMarkdown = method }

def(BlockQuote, (state, node) => {
  state.wrapBlock("> ", null, node, () => state.renderContent(node))
})

def(CodeBlock, (state, node) => {
  if (node.attrs.params == null) {
    state.wrapBlock("    ", null, node, () => state.text(node.textContent, false))
  } else {
    state.write("```" + node.attrs.params + "\n")
    state.text(node.textContent, false)
    state.ensureNewLine()
    state.write("```")
    state.closeBlock(node)
  }
})

def(Heading, (state, node) => {
  state.write(state.repeat("#", node.attrs.level) + " ")
  state.renderInline(node)
  state.closeBlock(node)
})

def(HorizontalRule, (state, node) => {
  state.write(node.attrs.markup || "---")
  state.closeBlock(node)
})

def(BulletList, (state, node) => {
  state.renderList(node, "  ", () => (node.attrs.bullet || "*") + " ")
})

def(OrderedList, (state, node) => {
  let start = Number(node.attrs.order || 1)
  let maxW = String(start + node.size - 1).length
  let space = state.repeat(" ", maxW + 2)
  state.renderList(node, space, i => {
    let nStr = String(start + i)
    return state.repeat(" ", maxW - nStr.length) + nStr + ". "
  })
})

def(ListItem, (state, node) => state.renderContent(node))

def(Paragraph, (state, node) => {
  state.renderInline(node)
  state.closeBlock(node)
})

// Inline nodes

def(Image, (state, node) => {
  state.write("![" + state.esc(node.attrs.alt || "") + "](" + state.esc(node.attrs.src) +
              (node.attrs.title ? " " + state.quote(node.attrs.title) : "") + ")")
})

def(HardBreak, state => state.write("\\\n"))

def(Text, (state, node) => state.text(node.text))

// Marks

function defMark(mark, open, close) {
  mark.prototype.openMarkdown = open
  mark.prototype.closeMarkdown = close
}

defMark(EmMark, "*", "*")

defMark(StrongMark, "**", "**")

defMark(LinkMark, "[",
        (state, mark) => "](" + state.esc(mark.attrs.href) + (mark.attrs.title ? " " + state.quote(mark.attrs.title) : "") + ")")

defMark(CodeMark, "`", "`")
<commit_msg>Fix bogus comparison in to_markdown<commit_after>import {Text, BlockQuote, OrderedList, BulletList, ListItem,
        HorizontalRule, Paragraph, Heading, CodeBlock, Image, HardBreak,
        EmMark, StrongMark, LinkMark, CodeMark} from "../model"
import {defineTarget} from "../format"

// :: (Node, ?Object) → string
// Serialize the content of the given node to [CommonMark](http://commonmark.org/).
//
// To define serialization behavior for your own [node
// types](#NodeType), give them a `serializeMarkDown` method. It will
// be called with a `MarkdownSerializer` and a `Node`, and should
// update the serializer's state to add the content of the node.
//
// [Mark types](#MarkType) can define `openMarkdown` and
// `closeMarkdown` properties, which provide the markup text that
// marked content should be wrapped in. They may hold either a string
// or a function from a `MarkdownSerializer` and a `Mark` to a string.
export function toMarkdown(doc, options) {
  let state = new MarkdownSerializer(options)
  state.renderContent(doc)
  return state.out
}

defineTarget("markdown", toMarkdown)

// ;; This is an object used to track state and expose
// methods related to markdown serialization. Instances are passed to
// node and mark serialization methods (see `toMarkdown`).
class MarkdownSerializer {
  constructor(options) {
    this.delim = this.out = ""
    this.closed = false
    this.inTightList = false
    // :: Object
    // The options passed to the serializer.
    this.options = options
  }

  flushClose(size) {
    if (this.closed) {
      if (!this.atBlank()) this.out += "\n"
      if (size == null) size = 2
      if (size > 1) {
        let delimMin = this.delim
        let trim = /\s+$/.exec(delimMin)
        if (trim) delimMin = delimMin.slice(0, delimMin.length - trim[0].length)
        for (let i = 1; i < size; i++)
          this.out += delimMin + "\n"
      }
      this.closed = false
    }
  }

  // :: (string, ?string, Node, ())
  // Render a block, prefixing each line with `delim`, and the first
  // line in `firstDelim`. `node` should be the node that is closed at
  // the end of the block, and `f` is a function that renders the
  // content of the block.
  wrapBlock(delim, firstDelim, node, f) {
    let old = this.delim
    this.write(firstDelim || delim)
    this.delim += delim
    f()
    this.delim = old
    this.closeBlock(node)
  }

  atBlank() {
    return /(^|\n)$/.test(this.out)
  }

  // :: ()
  // Ensure the current content ends with a newline.
  ensureNewLine() {
    if (!this.atBlank()) this.out += "\n"
  }

  // :: (?string)
  // Prepare the state for writing output (closing closed paragraphs,
  // adding delimiters, and so on), and then optionally add content
  // (unescaped) to the output.
  write(content) {
    this.flushClose()
    if (this.delim && this.atBlank())
      this.out += this.delim
    if (content) this.out += content
  }

  // :: (Node)
  // Close the block for the given node.
  closeBlock(node) {
    this.closed = node
  }

  // :: (string, ?bool)
  // Add the given text to the document. When escape is not `false`,
  // it will be escaped.
  text(text, escape) {
    let lines = text.split("\n")
    for (let i = 0; i < lines.length; i++) {
      var startOfLine = this.atBlank() || this.closed
      this.write()
      this.out += escape !== false ? this.esc(lines[i], startOfLine) : lines[i]
      if (i != lines.length - 1) this.out += "\n"
    }
  }

  // :: (Node)
  // Render the given node as a block.
  render(node) {
    node.type.serializeMarkdown(this, node)
  }

  // :: (Node)
  // Render the contents of `parent` as block nodes.
  renderContent(parent) {
    parent.forEach(child => this.render(child))
  }

  // :: (Node)
  // Render the contents of `parent` as inline content.
  renderInline(parent) {
    let stack = []
    let progress = node => {
      let marks = node ? node.marks.slice() : []
      if (stack.length && stack[stack.length - 1].type.name == "code" &&
          (!marks.length || marks[marks.length - 1].type.name != "code")) {
        this.text("`", false)
        stack.pop()
      }
      // Check the stack for opening marks that have been serialized,
      // and serialize a closing mark if the mark doesn't continue
      // into the next node.
      for (let j = stack.length - 1; j >= 0; j--) {
        let cur = stack[j], found = false
        for (let k = 0; k < marks.length; k++) {
          if (marks[k].eq(stack[j])) {
            marks.splice(k, 1)
            found = true
            break
          }
        }
        if (!found) {
          this.text(this.markString(cur, false), false)
          stack.splice(j, 1)
        }
      }
      for (let j = 0; j < marks.length; j++) {
        let cur = marks[j]
        stack.push(cur)
        this.text(this.markString(cur, true), false)
      }
      if (node) this.render(node)
    }
    parent.forEach(progress)
    progress(null)
  }

  renderList(node, delim, firstDelim) {
    if (this.closed && this.closed.type == node.type)
      this.flushClose(3)
    else if (this.inTightList)
      this.flushClose(1)

    let prevTight = this.inTightList
    this.inTightList = node.attrs.tight
    for (let i = node.iter(), n = 0, item; item = i.next().value; n++) {
      if (n && node.attrs.tight) this.flushClose(1)
      this.wrapBlock(delim, firstDelim(n), node, () => this.render(item))
    }
    this.inTightList = prevTight
  }

  // :: (string, ?bool) → string
  // Escape the given string so that it can safely appear in Markdown
  // content. If `startOfLine` is true, also escape characters that
  // has special meaning only at the start of the line.
  esc(str, startOfLine) {
    str = str.replace(/[`*\\~+\[\]]/g, "\\$&")
    if (startOfLine) str = str.replace(/^[:#-]/, "\\$&")
    return str
  }

  quote(str) {
    var wrap = str.indexOf('"') == -1 ? '""' : str.indexOf("'") == -1 ? "''" : "()"
    return wrap[0] + str + wrap[1]
  }

  // :: (string, number) → string
  // Repeat the given string `n` times.
  repeat(str, n) {
    let out = ""
    for (let i = 0; i < n; i++) out += str
    return out
  }

  // : (Mark, bool) → string
  // Get the markdown string for a given opening or closing mark.
  markString(mark, open) {
    let value = open ? mark.type.openMarkdown : mark.type.closeMarkdown
    return typeof value == "string" ? value : value(this, mark)
  }
}

function def(cls, method) { cls.prototype.serializeMarkdown = method }

def(BlockQuote, (state, node) => {
  state.wrapBlock("> ", null, node, () => state.renderContent(node))
})

def(CodeBlock, (state, node) => {
  if (node.attrs.params == null) {
    state.wrapBlock("    ", null, node, () => state.text(node.textContent, false))
  } else {
    state.write("```" + node.attrs.params + "\n")
    state.text(node.textContent, false)
    state.ensureNewLine()
    state.write("```")
    state.closeBlock(node)
  }
})

def(Heading, (state, node) => {
  state.write(state.repeat("#", node.attrs.level) + " ")
  state.renderInline(node)
  state.closeBlock(node)
})

def(HorizontalRule, (state, node) => {
  state.write(node.attrs.markup || "---")
  state.closeBlock(node)
})

def(BulletList, (state, node) => {
  state.renderList(node, "  ", () => (node.attrs.bullet || "*") + " ")
})

def(OrderedList, (state, node) => {
  let start = Number(node.attrs.order || 1)
  let maxW = String(start + node.size - 1).length
  let space = state.repeat(" ", maxW + 2)
  state.renderList(node, space, i => {
    let nStr = String(start + i)
    return state.repeat(" ", maxW - nStr.length) + nStr + ". "
  })
})

def(ListItem, (state, node) => state.renderContent(node))

def(Paragraph, (state, node) => {
  state.renderInline(node)
  state.closeBlock(node)
})

// Inline nodes

def(Image, (state, node) => {
  state.write("![" + state.esc(node.attrs.alt || "") + "](" + state.esc(node.attrs.src) +
              (node.attrs.title ? " " + state.quote(node.attrs.title) : "") + ")")
})

def(HardBreak, state => state.write("\\\n"))

def(Text, (state, node) => state.text(node.text))

// Marks

function defMark(mark, open, close) {
  mark.prototype.openMarkdown = open
  mark.prototype.closeMarkdown = close
}

defMark(EmMark, "*", "*")

defMark(StrongMark, "**", "**")

defMark(LinkMark, "[",
        (state, mark) => "](" + state.esc(mark.attrs.href) + (mark.attrs.title ? " " + state.quote(mark.attrs.title) : "") + ")")

defMark(CodeMark, "`", "`")
<|endoftext|>


<commit_before>var newBlock = require('./new-block.js');

/**
 * lost-row: Creates a row that is a fraction of the size of its containing
 * element's height with a gutter.
 *
 * @param {string} [fraction] - This is a simple fraction of the containing
 *   element's height.
 *
 * @param {length} [gutter] - The margin on the bottom of the element used
 *   to create a gutter. Typically this is left alone and settings.gutter
 *   will be used, but you can override it here if you want certain elements
 *   to have a particularly large or small gutter (pass 0 for no gutter at
 *   all).
 *
 * @param {string} [flex|no-flex] - Determines whether this element should
 *   use Flexbox or not.
 *
 * @example
 *   section {
 *     height: 100%;
 *   }
 *   div {
 *     lost-row: 1/3;
 *   }
 */
module.exports = function lostRowDecl(css, settings) {
  css.walkDecls('lost-row', function(decl) {
    var declArr = [],
        lostRow,
        lostRowGutter = settings.gutter,
        lostRowFlexbox = settings.flexbox;

    if (decl.value !== 'none') {
      declArr = decl.value.split(' ');
      lostRow = declArr[0];

      if (declArr[1] !== undefined && declArr[1].search(/^\d/) !== -1) {
        lostRowGutter = declArr[1];
      }

      if (declArr.indexOf('flex') !== -1) {
        lostRowFlexbox = 'flex';
      }

      if (declArr.indexOf('no-flex') !== -1) {
        lostRowFlexbox = 'no-flex';
      }

      decl.parent.nodes.forEach(function (decl) {
        if (decl.prop == 'lost-row-gutter') {
          lostRowGutter = decl.value;

          decl.remove();
        }
      });

      decl.parent.nodes.forEach(function (decl) {
        if (decl.prop == 'lost-row-flexbox') {
          if (decl.prop == 'flex') {
            lostRowFlexbox = 'flex';
          }

          decl.remove();
        }
      });

      decl.cloneBefore({
        prop: 'width',
        value: '100%'
      });

      if (lostRowFlexbox === 'flex') {
        decl.cloneBefore({
          prop: 'flex',
          value: '0 0 auto'
        });
      }

      if (lostRowGutter !== '0') {
        decl.cloneBefore({
          prop: 'height',
          value: 'calc(99.9% * '+ lostRow +' - ('+ lostRowGutter +' - '+ lostRowGutter +' * '+ lostRow +'))'
        });
      } else {
        decl.cloneBefore({
          prop: 'height',
          value: 'calc(99.9% * '+ lostRow +')'
        });
      }

      decl.cloneBefore({
        prop: 'margin-bottom',
        value: lostRowGutter
      });

      newBlock(
        decl,
        ':last-child',
        ['margin-bottom'],
        [0]
      );
    } else {
      decl.cloneBefore({
        prop: 'width',
        value: 'auto'
      });

      decl.cloneBefore({
        prop: 'height',
        value: 'auto'
      });

      decl.cloneBefore({
        prop: 'margin-bottom',
        value: '0'
      });
    }

    decl.remove();
  });
};
<commit_msg>Adds inline docs for lost-row: none<commit_after>var newBlock = require('./new-block.js');

/**
 * lost-row: Creates a row that is a fraction of the size of its containing
 * element's height with a gutter.
 *
 * @param {string} [fraction] - This is a simple fraction of the containing
 *   element's height.
 *
 * @param {length} [gutter] - The margin on the bottom of the element used
 *   to create a gutter. Typically this is left alone and settings.gutter
 *   will be used, but you can override it here if you want certain elements
 *   to have a particularly large or small gutter (pass 0 for no gutter at
 *   all).
 *
 * @param {string} [flex|no-flex] - Determines whether this element should
 *   use Flexbox or not.
 *
 * @param {string} [none] - Resets to a standard browser default.
 *
 * @example
 *   section {
 *     height: 100%;
 *   }
 *   div {
 *     lost-row: 1/3;
 *   }
 */
module.exports = function lostRowDecl(css, settings) {
  css.walkDecls('lost-row', function(decl) {
    var declArr = [],
        lostRow,
        lostRowGutter = settings.gutter,
        lostRowFlexbox = settings.flexbox;

    if (decl.value !== 'none') {
      declArr = decl.value.split(' ');
      lostRow = declArr[0];

      if (declArr[1] !== undefined && declArr[1].search(/^\d/) !== -1) {
        lostRowGutter = declArr[1];
      }

      if (declArr.indexOf('flex') !== -1) {
        lostRowFlexbox = 'flex';
      }

      if (declArr.indexOf('no-flex') !== -1) {
        lostRowFlexbox = 'no-flex';
      }

      decl.parent.nodes.forEach(function (decl) {
        if (decl.prop == 'lost-row-gutter') {
          lostRowGutter = decl.value;

          decl.remove();
        }
      });

      decl.parent.nodes.forEach(function (decl) {
        if (decl.prop == 'lost-row-flexbox') {
          if (decl.prop == 'flex') {
            lostRowFlexbox = 'flex';
          }

          decl.remove();
        }
      });

      decl.cloneBefore({
        prop: 'width',
        value: '100%'
      });

      if (lostRowFlexbox === 'flex') {
        decl.cloneBefore({
          prop: 'flex',
          value: '0 0 auto'
        });
      }

      if (lostRowGutter !== '0') {
        decl.cloneBefore({
          prop: 'height',
          value: 'calc(99.9% * '+ lostRow +' - ('+ lostRowGutter +' - '+ lostRowGutter +' * '+ lostRow +'))'
        });
      } else {
        decl.cloneBefore({
          prop: 'height',
          value: 'calc(99.9% * '+ lostRow +')'
        });
      }

      decl.cloneBefore({
        prop: 'margin-bottom',
        value: lostRowGutter
      });

      newBlock(
        decl,
        ':last-child',
        ['margin-bottom'],
        [0]
      );
    } else {
      decl.cloneBefore({
        prop: 'width',
        value: 'auto'
      });

      decl.cloneBefore({
        prop: 'height',
        value: 'auto'
      });

      decl.cloneBefore({
        prop: 'margin-bottom',
        value: '0'
      });
    }

    decl.remove();
  });
};
<|endoftext|>


<commit_before>var app = require('./app');
var logstore = require('./logstore');
var async = require('async');

var help = require('../help');

exports.create = function create(cb) {
    var self = {};
    async.series([
        app.create().ifNotExists().exec,
        logstore.create
    ], function (err) {
        if (err) return cb(err);
        app.all(function (err, apps) {
            if (err) return cb(err);
            self.app = function (uid, name) {

                if (name.toLowerCase() == 'all') name = '.+';
                var reg = new RegExp('^' + name + '$');

                return apps.filter(function (app) {
                    return app.uid == uid && app.name.match(name);
                });
            };
            self.create = function (uid, name, nacfile, cb) {
                app.construct({
                    uid: uid,
                    name: name,
                    nacfile: nacfile,
                    active: false
                }, function (err, app) {
                    if (err) return cb(err);
                    apps.push(app);
                    return cb(null, app);
                });
            };

            self.cleanup = function () {
                apps = apps.filter(function (app) {
                    return !app.destroyed
                });
            };

            cb(null, self);
        });
    });

};

exports.interface = function daemon_interface(uid, daemon) {
    var self = {};

    function checkError(command, arglen, cb) {
        var cmdError = help.check(command, arglen);
        if (cmdError) {
            cb(new Error(cmdError.join('\n')));
        }
        return cmdError;
    }

    ['start', 'stop', 'restart', 'kill', 'uptime', 'run', 'logs', 'status', 'destroy', 'update'].
        forEach(function (command) {
            self[command] = function (name) {
                // remove name
                var args = [].slice.call(arguments, 1);
                var cb = args[args.length - 1];
                // remove callback
                args = args.slice(0, args.length - 1);
                var cmdError = help.check(command, args.length);
                if (checkError(command, args.length, cb)) return;

                var apps = daemon.app(uid, name);
                if (!apps.length)
                    return cb(new Error(name + ': no app found'));

                async.map(apps, function (app, cb) {
                    var argsCb = args.concat([cb]);
                    app[command].apply(app, argsCb);
                }, function (err, res) {
                    if (command == 'destroy')
                        daemon.cleanup();
                    cb(err, res);
                });

            }
        });
    self.create = function (name, nacfile, cb) {
        if (checkError('create', arguments.length - 2, cb)) return;
        daemon.create(uid, name, nacfile, cb);
    };

    return self;
};

<commit_msg>fix bug in regex match<commit_after>var app = require('./app');
var logstore = require('./logstore');
var async = require('async');

var help = require('../help');

exports.create = function create(cb) {
    var self = {};
    async.series([
        app.create().ifNotExists().exec,
        logstore.create
    ], function (err) {
        if (err) return cb(err);
        app.all(function (err, apps) {
            if (err) return cb(err);
            self.app = function (uid, name) {

                if (name.toLowerCase() == 'all') name = '.+';
                var reg = new RegExp('^' + name + '$');

                return apps.filter(function (app) {
                    return app.uid == uid && app.name.match(reg);
                });
            };
            self.create = function (uid, name, nacfile, cb) {
                app.construct({
                    uid: uid,
                    name: name,
                    nacfile: nacfile,
                    active: false
                }, function (err, app) {
                    if (err) return cb(err);
                    apps.push(app);
                    return cb(null, app);
                });
            };

            self.cleanup = function () {
                apps = apps.filter(function (app) {
                    return !app.destroyed
                });
            };

            cb(null, self);
        });
    });

};

exports.interface = function daemon_interface(uid, daemon) {
    var self = {};

    function checkError(command, arglen, cb) {
        var cmdError = help.check(command, arglen);
        if (cmdError) {
            cb(new Error(cmdError.join('\n')));
        }
        return cmdError;
    }

    ['start', 'stop', 'restart', 'kill', 'uptime', 'run', 'logs', 'status', 'destroy', 'update'].
        forEach(function (command) {
            self[command] = function (name) {
                // remove name
                var args = [].slice.call(arguments, 1);
                var cb = args[args.length - 1];
                // remove callback
                args = args.slice(0, args.length - 1);
                var cmdError = help.check(command, args.length);
                if (checkError(command, args.length, cb)) return;

                var apps = daemon.app(uid, name);
                if (!apps.length)
                    return cb(new Error(name + ': no app found'));

                async.map(apps, function (app, cb) {
                    var argsCb = args.concat([cb]);
                    app[command].apply(app, argsCb);
                }, function (err, res) {
                    if (command == 'destroy')
                        daemon.cleanup();
                    cb(err, res);
                });

            }
        });
    self.create = function (name, nacfile, cb) {
        if (checkError('create', arguments.length - 2, cb)) return;
        daemon.create(uid, name, nacfile, cb);
    };

    return self;
};

<|endoftext|>


<commit_before>import QuotesHelper from './quotesHelper';

describe('JavaScript addition operator', function () {

  var helper = new QuotesHelper();

  // var endpoint = 'http://localhost:3039';
  // this.http.request(endpoint + '/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20IN%20(%22' + this.symbol + '%22)&format=json&env=http://datatables.org/alltables.env')
  beforeAll(function () {
    jasmine.DEFAULT_TIMEOUT_INTERVAL = 30000;
    // bombay.server.configureEndpoints(config);
  });

  it('does some bugs stuff', function (done) {
    expect(true).toBe(true);
    done();
  })

  var endpoint;

  it('does end-to-end ui testing', function (done) {
    const conn = bombay.server.connect();
    console.log('conn = ' + conn);
    conn.then(function() {
      return bombay.client.visit('http://www.cnn.com', 2000);
    }).then(function() {
      return bombay.client.visit('http://localhost:7777', 2000);
    }).then(function () {
      return bombay.client.exists('#quote-details');
    }).then(function (results) {
      // expect(results).toBe(false);
      return bombay.client.setInputVal('GOOG', 'input');
    }).then(function (results) {
      endpoint = bombay.server.configureEndpoint('GET', 'finance/info');
      return bombay.client.click('button#get-stock-quote', 250);
    }).then(function(clickResults) {
      return endpoint.getIncomingRequest();
    }).then(function(req) {
      var symbol = helper.parseStockSymbol(req);
      expect(symbol).toBe('GOOG');
      return endpoint.respondWithString(helper.generateResponse(symbol));
    }).then(function() {
      return bombay.client.exists('#quote-details');
    }).then(function (results) {
      expect(results).toBe(true);
      return bombay.client.getTextVal('#sym', 500);
    }).then(function (results) {
      expect(results).toEqual('GOOG');
      return bombay.client.getTextVal("#pct-change", 500);
    }).then(function (results) {
      expect(results).toEqual('-0.49')
      return bombay.client.setInputVal('TSLA', 'input');
    }).then(function (results) {
      return bombay.client.click('button#get-stock-quote', 250);
    }).then(function(clickResults) {
      return endpoint.getIncomingRequest();
    }).then(function(req) {
      var symbol = helper.parseStockSymbol(req);
      expect(symbol).toBe('TSLA');
      return endpoint.respondWithString(helper.generateResponse(symbol));
    }).then(function (results) {
      return bombay.client.getTextVal('#sym', 1500);
    }).then(function (results) {
      expect(results).toEqual('TSLA');
      return bombay.client.getTextVal("#pct-change", 500);
    }).then(function (results) {
      expect(results).toEqual('1.29');
      done();
    }).catch(function (err) {
      console.log('++++ Unexpected error in spec.  ' + err + '\nExiting...');
      expect(err).toBe(undefined);
      done(-1);
    });
  })

})
<commit_msg>Temporarily removing the 'VISIT' command from the Jasmine spec (for the bombayjs-companion-app sample app) because we've removed the 'VISIT' command capability from bombay.js client.  This is the ability to visit random websites(URLs in browser) which needs a bit more thinking.  This commit does not contain any changes to bombay.js framework itself.<commit_after>import QuotesHelper from './quotesHelper';

describe('JavaScript addition operator', function () {

  var helper = new QuotesHelper();

  // var endpoint = 'http://localhost:3039';
  // this.http.request(endpoint + '/v1/public/yql?q=select%20*%20from%20yahoo.finance.quotes%20where%20symbol%20IN%20(%22' + this.symbol + '%22)&format=json&env=http://datatables.org/alltables.env')
  beforeAll(function () {
    jasmine.DEFAULT_TIMEOUT_INTERVAL = 30000;
    // bombay.server.configureEndpoints(config);
  });

  it('does some bugs stuff', function (done) {
    expect(true).toBe(true);
    done();
  })

  var endpoint;

  it('does end-to-end ui testing', function (done) {
    const conn = bombay.server.connect();
    console.log('conn = ' + conn);
    conn.then(function() {
      return bombay.client.exists('#quote-details');
    }).then(function (results) {
      // expect(results).toBe(false);
      return bombay.client.setInputVal('GOOG', 'input');
    }).then(function (results) {
      endpoint = bombay.server.configureEndpoint('GET', 'finance/info');
      return bombay.client.click('button#get-stock-quote', 250);
    }).then(function(clickResults) {
      return endpoint.getIncomingRequest();
    }).then(function(req) {
      var symbol = helper.parseStockSymbol(req);
      expect(symbol).toBe('GOOG');
      return endpoint.respondWithString(helper.generateResponse(symbol));
    }).then(function() {
      return bombay.client.exists('#quote-details');
    }).then(function (results) {
      expect(results).toBe(true);
      return bombay.client.getTextVal('#sym', 500);
    }).then(function (results) {
      expect(results).toEqual('GOOG');
      return bombay.client.getTextVal("#pct-change", 500);
    }).then(function (results) {
      expect(results).toEqual('-0.49')
      return bombay.client.setInputVal('TSLA', 'input');
    }).then(function (results) {
      return bombay.client.click('button#get-stock-quote', 250);
    }).then(function(clickResults) {
      return endpoint.getIncomingRequest();
    }).then(function(req) {
      var symbol = helper.parseStockSymbol(req);
      expect(symbol).toBe('TSLA');
      return endpoint.respondWithString(helper.generateResponse(symbol));
    }).then(function (results) {
      return bombay.client.getTextVal('#sym', 1500);
    }).then(function (results) {
      expect(results).toEqual('TSLA');
      return bombay.client.getTextVal("#pct-change", 500);
    }).then(function (results) {
      expect(results).toEqual('1.29');
      done();
    }).catch(function (err) {
      console.log('++++ Unexpected error in spec.  ' + err + '\nExiting...');
      expect(err).toBe(undefined);
      done(-1);
    });
  })

})
<|endoftext|>


<commit_before>var fs = require('fs');
var getHomePath = require('home-path');
var logHelper = require('../../util/log-helper');
var path = require('path');
var process = require('process');
var symlinkOrReplaceFilesInFolderSync = require('../../util/symlink-or-replace-files-in-folder-sync');

module.exports.install = function () {
  if (process.platform !== 'win32') {
    logHelper.logStepStarted('git');
    var sourceDir = path.join(__dirname, 'config');
    var destDir = path.join(getHomePath());
    var files = fs.readdirSync(sourceDir);
    logHelper.logSubStepPartialStarted('applying config files');
    symlinkOrReplaceFilesInFolderSync(files, sourceDir, destDir);
    logHelper.logSubStepPartialSuccess();
  }
};
<commit_msg>[git] Install .gitconfig on windows<commit_after>var fs = require('fs');
var getHomePath = require('home-path');
var logHelper = require('../../util/log-helper');
var path = require('path');
var process = require('process');
var symlinkOrReplaceFilesInFolderSync = require('../../util/symlink-or-replace-files-in-folder-sync');

module.exports.install = function () {
  logHelper.logStepStarted('git');
  var sourceDir = path.join(__dirname, 'config');
  var destDir = path.join(getHomePath());
  var files = fs.readdirSync(sourceDir);
  logHelper.logSubStepPartialStarted('applying config files');
  symlinkOrReplaceFilesInFolderSync(files, sourceDir, destDir);
  logHelper.logSubStepPartialSuccess();
};
<|endoftext|>


<commit_before>/**
 * Module Name: Link
 * Description: Stores recent channel links, with commands to retrieve
 * information about links.
 */
var request = require('request');
var link = function(dbot) {
    var urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    var links = {};
    var fetchTitle = function(event, link) {
        request(link, function (error, response, body) {
            if(!error && response.statusCode == 200) {
                body = body.replace(/(\r\n|\n\r|\n)/gm, " ");
                var title = body.valMatch(/<title>(.*)<\/title>/, 2);
                if(title) {
                    event.reply(title[1]);
                } else {
                    event.reply(dbot.t('title_not_found'));
                }
            }
        });
    };

    var commands = {
        '~title': function(event) {
            var link = links[event.channel.name];
            if(event.params[1] !== undefined) {
                var urlMatches = event.params[1].match(urlRegex);
                if(urlMatches !== null) {
                    link = urlMatches[0];
                }
            }
            fetchTitle(event, link);
        }
    };

    return {
        'name': 'link',
        'ignorable': true,
        'commands': commands,

        'listener': function(event) {
            var urlMatches = event.message.match(urlRegex);
            if(urlMatches !== null) {
                links[event.channel.name] = urlMatches[0];

                if(dbot.config.link.autoTitle == true) {
                    fetchTitle(event, urlMatches[0]);
                }
            }
        },
        'on': 'PRIVMSG'
    };
};

exports.fetch = function(dbot) {
    return link(dbot);
};
<commit_msg>Update modules/link/link.js<commit_after>/**
 * Module Name: Link
 * Description: Stores recent channel links, with commands to retrieve
 * information about links.
 */
var request = require('request');
var link = function(dbot) {
    var urlRegex = /(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig;
    var links = {};
    var fetchTitle = function(event, link) {
        request(link, function (error, response, body) {
            if(!error && response.statusCode == 200) {
                body = body.replace(/(\r\n|\n\r|\n)/gm, " ");
                var title = body.valMatch(/<title>(.*)<\/title>/, 2);
                if(title) {
                    event.reply(title[1]);
                }
            }
        });
    };

    var commands = {
        '~title': function(event) {
            var link = links[event.channel.name];
            if(event.params[1] !== undefined) {
                var urlMatches = event.params[1].match(urlRegex);
                if(urlMatches !== null) {
                    link = urlMatches[0];
                }
            }
            fetchTitle(event, link);
        }
    };

    return {
        'name': 'link',
        'ignorable': true,
        'commands': commands,

        'listener': function(event) {
            var urlMatches = event.message.match(urlRegex);
            if(urlMatches !== null) {
                links[event.channel.name] = urlMatches[0];

                if(dbot.config.link.autoTitle == true) {
                    fetchTitle(event, urlMatches[0]);
                }
            }
        },
        'on': 'PRIVMSG'
    };
};

exports.fetch = function(dbot) {
    return link(dbot);
};
<|endoftext|>


<commit_before>var fs = require("fs");
var argv = require("optimist").argv;

var config = {
  testTimeout: 10000,
  serverTimeout: 10000,
  viewportSize: { width: 800, height: 1600 }
};
if (!argv || !argv.port || !argv.eventbriteAPIkey || !argv.url) {
  var configFile = fs.readFileSync(".serenedirc", "utf-8");
  if (!configFile) {
    throw new Error("Missing .serenedirc");
  }
  else {
    configFile = JSON.parse(configFile);
  }
}

config.port = argv.port || configFile.port;
config.eventbriteAPIkey = argv.eventbriteAPIkey || configFile.eventbriteAPIkey;
config.launch = argv.launch === undefined ? true : argv.launch;
config.googleAPIKey = argv.googleAPIKey || configFile.googleAPIKey;
config.url = argv.url || configFile.url;
exports.config = config;<commit_msg>Added serenedi executable's arguments<commit_after>var fs = require("fs");
var optimist = require("optimist");
var path = require("path");
var argv = optimist.argv;

var config = {
  testTimeout: 10000,
  serverTimeout: 10000,
  viewportSize: { width: 800, height: 1600 }
};
if (!argv || !argv.port || !argv.eventbriteAPIkey || !argv.url) {
  var configFile = fs.readFileSync(path.join(__dirname + "/../.serenedirc"), "utf-8");
  if (!configFile) {
    throw new Error("Missing .serenedirc");
  }
  else {
    configFile = JSON.parse(configFile);
  }
}

config.port = argv.port || configFile.port;
config.eventbriteAPIkey = argv.eventbriteAPIkey || configFile.eventbriteAPIkey;
config.launch = argv.launch === undefined ? true : argv.launch;
config.googleAPIKey = argv.googleAPIKey || configFile.googleAPIKey;
config.url = argv.url || configFile.url;
exports.config = config;

if (argv.help) {
  optimist.usage('Launch Serenedi: Location based event search web application.')
    .describe('port', 'Serenedi\'s port number')
    .describe('url', 'URL where Serenedi is hosted on. (includes port number, ex. [--url=127.0.0.1:80])')
    .describe('launch', 'to launch Serenedi on start or not.')
    .describe('googleAPIKey', 'Google API key');

  optimist.showHelp();
  process.exit(0);
}<|endoftext|>


<commit_before>var _                   = require('underscore');
var assert              = require('assert');
var ur                  = require('ur');

function check(pf, xs, ys, tol) {
  for (var i=0; i<xs.length; i++) {
    var x = xs[i];
      var y = ys[i];
    var yFit = ur.getValue(pf, x);
    if (Math.abs(y - yFit) > tol) {
      throw new Error('xs[' + i.toString() + '] = ' + x.toString() + ', ys[' + i.toString() + '] = ' + y.toString() + ' but getValue(pf, ' + x.toString() + ') = ' + yFit.toString());
    }
  }
}

describe('Polyfit3', function() {
  it('should work', function() {
    var pf = new ur.Polyfit3(1, 0.5, 0.3, 0.2);
    assert.equal(ur.getValue(pf, 0.0), 1.0);
    assert.equal(ur.getValue(pf, 1.0), 2.0);
    assert.equal(ur.getValue(pf, 2.0), 4.8);
  });
});

describe('mkPolyfit3', function() {

  it('should accurately model sin(x) in [-1 .. +1]', function() {
    var xs = _.range(-1, 1, 1/64);
    var ys = _.map(xs, function(x) { return Math.sin(x); });

    var xsc = new ur.vec(xs);
    var pf = ur.mkPolyfit3(xsc, new ur.vec(ys));
    check(pf, xs, ys, 0.001);
  });

  it('should work with native Float64Arrays', function() {
    var xs = new Float64Array(128);
    var ys = new Float64Array(128);
    for (var i=0; i<xs.length; i++) {
      xs[i] = (i-64)/64;
      ys[i] = Math.sin(xs[i]);
    }

    var pf = ur.mkPolyfit3(new ur.vec(xs), new ur.vec(ys));
    check(pf, xs, ys, 0.001);
  });

  it('should throw with not enough data', function() {
    try {
      ur.mkPolyfit3(new ur.vec([1,2,3]), new ur.vec([1,2,3]));
    } catch(ex) {
      assert.ok(ex.toString().match(/not enough data/));
      return;
    }
    assert.fail();
  });

});

describe('mkPolyfit5', function() {
  it('should accurately model sin(x) in [-2 .. +2]', function() {
    var xs = _.range(-2, 2, 1/64);
    var ys = _.map(xs, function(x) { return Math.sin(x); });

    var pf = ur.mkPolyfit5(new ur.vec(xs), new ur.vec(ys));
    check(pf, xs, ys, 0.001);
  });
});
<commit_msg>Delete test_polyfit.js<commit_after><|endoftext|>


<commit_before>/*global angular*/
angular.module("picbit")
.controller("UserProfileController", ["$scope", "$rootScope","$backend","$http",
function ($scope, $rootScope, $backend, $http) {
	"use strict";

	// Cambia la seleccion entre las difernetes pestañas
	$scope.selectSection = function(e){
		var $target = $(e.currentTarget);
		var sectionTarget = $target.attr('data-target');

		$('.information').children().removeClass('active');
		$('.tabs').children().removeClass('active');

		$target.parent().addClass('active');
		$(sectionTarget).addClass('active');
	};
	// Permite cambiar la imagen de un usuario, basandose
	// en el input que ha dado
	$scope.changePicture = function(event){
		if (event.files && event.files[0].type.indexOf('image') !== -1){
			var reader = new FileReader();
			reader.onload = function (e) {
				$('#userPicture')
				.attr('src', e.target.result);
			};
			reader.readAsDataURL(event.files[0]);
		}
	};

	// Envia los datos del usuario al servidor
	$scope.submitForm = function(){
		var values = {};
		var $inputs = $('#userInformation input');

		for (var i =0;i<$inputs.length;i++){
			var $target = $($inputs[i]);
			values[$target.attr('data-field')] = $target.val();
		}
		// TODO comprobar que se han cambiado datos respecto a los recibidos
		console.log('TODO send to server: ', values);
	};

	// Comprueba si ya esta registrado un token de una determinada red socialNetwork
	// Valida las clases.
	$scope.existToken = function(socialNetwork){
		return $scope.user && $scope.user.tokens[socialNetwork];
	};

	function loginCallback(e){
		//falta registralo
		$scope.$apply(function(){
			var socialNetwork = e.detail.redSocial;
			var token = e.detail.token;
			var registerTokenError = function(){
				console.error('Algo fue mal al intentar guardar los tokens de ' + socialNetwork);
			};
			$rootScope.user = $rootScope.user || {tokens:{}};
			$rootScope.user.tokens[socialNetwork] = token;

			switch(socialNetwork) {
				case 'googleplus':
				var uri = 'https://www.googleapis.com/plus/v1/people/me?access_token=' + token;
				$http.get(uri).success(function (responseData) {
					$backend.addTokens(socialNetwork, responseData.id, token, $scope.user.user_id).error(registerTokenError);
				});
				break;
				case 'twitter':
				uri = $backend.endpoint + '/api/oauth/twitter/authorization/' + e.detail.oauth_verifier;
				$http.get(uri).success(function (responseData) {
					e.detail.userId = responseData.token_id;
					$backend.addTokens(socialNetwork, responseData.token_id, token,
						$scope.user.user_id, e.detail.oauth_verifier).error(registerTokenError);
					}).error(function() {
						console.log('Problemas al intentar obtener el token_id de un usuario' );
					});
					break;
					default:
					$backend.addTokens(socialNetwork, '', token, $scope.user.user_id).error(registerTokenError);
					break;
				}
			});
		}
		(function(){
			$('#socialNetwork google-login')[0].addEventListener('google-logged', loginCallback);
			$('#socialNetwork github-login')[0].addEventListener('github-logged', loginCallback);
			$('#socialNetwork instagram-login')[0].addEventListener('instagram-logged', loginCallback);
			$('#socialNetwork twitter-login')[0].addEventListener('twitter-logged', loginCallback);
			$('#socialNetwork login-facebook')[0].addEventListener('facebook-logged', loginCallback);
		})();
	}]);
<commit_msg>Fixed typo<commit_after>/*global angular*/
angular.module("picbit")
.controller("UserProfileController", ["$scope", "$rootScope","$backend","$http",
function ($scope, $rootScope, $backend, $http) {
	"use strict";

	// Cambia la seleccion entre las difernetes pestañas
	$scope.selectSection = function(e){
		var $target = $(e.currentTarget);
		var sectionTarget = $target.attr('data-target');

		$('.information').children().removeClass('active');
		$('.tabs').children().removeClass('active');

		$target.parent().addClass('active');
		$(sectionTarget).addClass('active');
	};
	// Permite cambiar la imagen de un usuario, basandose
	// en el input que ha dado
	$scope.changePicture = function(event){
		if (event.files && event.files[0].type.indexOf('image') !== -1){
			var reader = new FileReader();
			reader.onload = function (e) {
				$('#userPicture')
				.attr('src', e.target.result);
			};
			reader.readAsDataURL(event.files[0]);
		}
	};

	// Envia los datos del usuario al servidor
	$scope.submitForm = function(){
		var values = {};
		var $inputs = $('#userInformation input');

		for (var i =0;i<$inputs.length;i++){
			var $target = $($inputs[i]);
			values[$target.attr('data-field')] = $target.val();
		}
		// TODO comprobar que se han cambiado datos respecto a los recibidos
		console.log('TODO send to server: ', values);
	};

	// Comprueba si ya esta registrado un token de una determinada red socialNetwork
	// Valida las clases.
	$scope.existToken = function(socialNetwork){
		return $scope.user && $scope.user.tokens[socialNetwork];
	};
	$scope.showToastr = function(type, message, time){
		toastr.options = {
			"closeButton": false,
			"debug": false,
			"newestOnTop": false,
			"progressBar": false,
			"positionClass": "toast-top-right",
			"preventDuplicates": false,
			"onclick": null,
			"showDuration": "300",
			"hideDuration": "1000",
			"timeOut": "5000",
			"extendedTimeOut": time || "5000",
			"showEasing": "swing",
			"hideEasing": "linear",
			"showMethod": "fadeIn",
			"hideMethod": "fadeOut"
		};
		toastr[type](message);
	};
	function loginCallback(e){
		//falta registralo
		$scope.$apply(function(){
			var socialNetwork = e.detail.redSocial;
			var token = e.detail.token;
			var registerTokenError = function(){
				$scope.showToastr('danger',$scope.language.add_token_error)
			};
			$rootScope.user = $rootScope.user || {tokens:{}};
			$rootScope.user.tokens[socialNetwork] = token;

			switch(socialNetwork) {
				case 'googleplus':
				var uri = 'https://www.googleapis.com/plus/v1/people/me?access_token=' + token;
				$http.get(uri).success(function (responseData) {
					$backend.addTokens(socialNetwork, responseData.id, token, $scope.user.user_id).error(registerTokenError);
				});
				break;
				case 'twitter':
				uri = $backend.endpoint + '/api/oauth/twitter/authorization/' + e.detail.oauth_verifier;
				$http.get(uri).success(function (responseData) {
					e.detail.userId = responseData.token_id;
					$backend.addTokens(socialNetwork, responseData.token_id, token,
						$scope.user.user_id, e.detail.oauth_verifier).error(registerTokenError);
					}).error(function() {
						console.log('Problemas al intentar obtener el token_id de un usuario' );
					});
					break;
					default:
					$backend.addTokens(socialNetwork, '', token, $scope.user.user_id).error(registerTokenError);
					break;
				}
			});
		}
		(function(){
			$('#socialNetwork google-login')[0].addEventListener('google-logged', loginCallback);
			$('#socialNetwork github-login')[0].addEventListener('github-logged', loginCallback);
			$('#socialNetwork instagram-login')[0].addEventListener('instagram-logged', loginCallback);
			$('#socialNetwork twitter-login')[0].addEventListener('twitter-logged', loginCallback);
			$('#socialNetwork login-facebook')[0].addEventListener('facebook-logged', loginCallback);
		})();
	}]);
<|endoftext|>


<commit_before>var _ = require("underscore");
var helper = require("./helper");

var directoryPattern = /(.)?\/(.+):([^\/]+)?\n\n/gi;
var pathPattern = /\/(.+):/gi;
var contentPattern = /:([^[\/]+)?\n\n/gi;

var LsParser = function(root,source,options){
	this.root = root || "";
	this.setup = function(options){
		var _options = options || {};
		var settings = this.settings = {};
		this.result = _options.result || null;
		settings.source = _options.source || null;
		settings.node = {};
		settings.nodeSchema = _options.nodeSchema || null;
		this.append = _options.append || null;
		this.stringlineHandler = _options.stringlineHandler || null;
	}
	this.setup(options);
}
LsParser.prototype.core = function(){
	var self = this, node;
	var settings = this.settings;
	var nodeSchema = settings.nodeSchema;
	var stringlineHandler = this.stringlineHandler;
	var parts = settings.source.match(directoryPattern);
	_.each(parts,function(part){
		node =  _.extend({},settings.nodeSchema);

		var path = helper.getPath(part,self.root,pathPattern);
		node.path = path.split("/") || [];

		var contents = part.match(contentPattern);
		_.each(contents,function(content){
			var contentline = content.split("\n");
			var validFiles = _.reject(contentline,function(line , i){ return (i <= 1 || line.length == 0); });

			_.each(validFiles,function(stringline,i){
				var start = stringline.lastIndexOf(" ")+1;
				var file = stringline.substr(start,stringline.length);
				node.files.push(file);
			});
		});
		self.append(node);
	});
	settings.source = null;
	return this.result;
}

LsParser.prototype.s = function(){
	var self = this,node;
	var settings = this.settings;
	var nodeSchema =settings.nodeSchema;
	var parts = settings.source.match(directoryPattern);
	_.each(parts,function(part){
		node =  _.extend({},settings.nodeSchema);
		var path = helper.getPath(part,self.root,pathPattern);

		node.path = _.rest(path.split("/")) || [];

		var contents = part.match(contentPattern);
		_.each(contents,function(content){
			var contentline = content.split("\n");
			var validFiles = _.reject(contentline,function(line , i){ return (i <= 1 || line.length == 0); });

			_.each(validFiles,function(stringline,i){
				var filestart = stringline.lastIndexOf(" ")+1;
				var file = stringline.substr(filestart,stringline.length);
				var typestart = file.lastIndexOf(".")+1;
				var type = file.substr(typestart,file.length);
				node.Name = file.trim();
				node.type = type.trim();
				self.append(node);
			});
		});
	});
	settings.source = null;
	return this.result;
}
LsParser.prototype.toDictionary = function(str){

	var self = this;
	var settings = this.settings;
	this.setup({
			nodeSchema: { Name:null, type:null, path:[] },
			result: [],
			source: str || settings.source,
			append: function(node){
				var data = _.extend({},node);
				self.result.push(data);
			}
	});
	return this.s();
}

LsParser.prototype.toList = function(str){
	var self = this;
	var settings = this.settings;
	var node = settings.node;
	this.setup({
			nodeSchema: {"path": [],"files": []	},
			result: [],
			source: str || settings.source,
			append: function(node){
				self.result.push(node);
			},
			stringlineHandler: function(stringline){

			}
	});
	return this.core();
};

LsParser.prototype.toJSON = function(str){
	var self = this;
	var settings = this.settings;
	this.setup({
			nodeSchema: {"path": [],"files": []	},
			result: {},
			source: str || settings.source,
			append: function(node){
				var curPtr = helper.getTailNode(self.result,node.path);
				_.extend(curPtr,{"$FILES": node.files});
			}
		});
	return this.core();
};
LsParser.prototype._push = function(target,key,val){
	var self = this;
	var settings = this.settings;
	(target[key] || (function(){target[key] = []; return target[key]})()).push(val)
}
exports.LsParser = LsParser;<commit_msg>delete unused code.<commit_after>var _ = require("underscore");
var helper = require("./helper");

var directoryPattern = /(.)?\/(.+):([^\/]+)?\n\n/gi;
var pathPattern = /\/(.+):/gi;
var contentPattern = /:([^[\/]+)?\n\n/gi;

var LsParser = function(root,source,options){
	this.root = root || "";
	this.setup = function(options){
		var _options = options || {};
		var settings = this.settings = {};
		this.result = _options.result || null;
		settings.source = _options.source || null;
		settings.nodeSchema = _options.nodeSchema || null;
		this.append = _options.append || null;
	}
	this.setup(options);
}
LsParser.prototype.core = function(){
	var self = this, node;
	var settings = this.settings;
	var nodeSchema = settings.nodeSchema;
	var parts = settings.source.match(directoryPattern);
	_.each(parts,function(part){
		node =  _.extend({},settings.nodeSchema);

		var path = helper.getPath(part,self.root,pathPattern);
		node.path = path.split("/") || [];

		var contents = part.match(contentPattern);
		_.each(contents,function(content){
			var contentline = content.split("\n");
			var validFiles = _.reject(contentline,function(line , i){ return (i <= 1 || line.length == 0); });

			_.each(validFiles,function(stringline,i){
				var start = stringline.lastIndexOf(" ")+1;
				var file = stringline.substr(start,stringline.length);
				node.files.push(file);
			});
		});
		self.append(node);
	});
	settings.source = null;
	return this.result;
}

LsParser.prototype.s = function(){
	var self = this,node;
	var settings = this.settings;
	var nodeSchema =settings.nodeSchema;
	var parts = settings.source.match(directoryPattern);
	_.each(parts,function(part){
		node =  _.extend({},settings.nodeSchema);
		var path = helper.getPath(part,self.root,pathPattern);

		node.path = _.rest(path.split("/")) || [];

		var contents = part.match(contentPattern);
		_.each(contents,function(content){
			var contentline = content.split("\n");
			var validFiles = _.reject(contentline,function(line , i){ return (i <= 1 || line.length == 0); });

			_.each(validFiles,function(stringline,i){
				var filestart = stringline.lastIndexOf(" ")+1;
				var file = stringline.substr(filestart,stringline.length);
				var typestart = file.lastIndexOf(".")+1;
				var type = file.substr(typestart,file.length);
				node.Name = file.trim();
				node.type = type.trim();
				self.append(node);
			});
		});
	});
	settings.source = null;
	return this.result;
}
LsParser.prototype.toDictionary = function(str){

	var self = this;
	var settings = this.settings;
	this.setup({
			nodeSchema: { Name:null, type:null, path:[] },
			result: [],
			source: str || settings.source,
			append: function(node){
				var data = _.extend({},node);
				self.result.push(data);
			}
	});
	return this.s();
}

LsParser.prototype.toList = function(str){
	var self = this;
	var settings = this.settings;
	var node = settings.node;
	this.setup({
			nodeSchema: {"path": [],"files": []	},
			result: [],
			source: str || settings.source,
			append: function(node){
				self.result.push(node);
			},
	});
	return this.core();
};

LsParser.prototype.toJSON = function(str){
	var self = this;
	var settings = this.settings;
	this.setup({
			nodeSchema: {"path": [],"files": []	},
			result: {},
			source: str || settings.source,
			append: function(node){
				var curPtr = helper.getTailNode(self.result,node.path);
				_.extend(curPtr,{"$FILES": node.files});
			}
		});
	return this.core();
};
LsParser.prototype._push = function(target,key,val){
	var self = this;
	var settings = this.settings;
	(target[key] || (function(){target[key] = []; return target[key]})()).push(val)
}
exports.LsParser = LsParser;<|endoftext|>


<commit_before>/**
	_onyx.Drawer_ is a control that appears or disappears based on its _open_
	property. It appears or disappears with a sliding animation whose direction
	is determined by the _orient_ property.

	For more information, see the documentation on
	Drawers in the
	Enyo Developer Guide.
*/
enyo.kind({
	name: "onyx.Drawer",
	published: {
		//* The visibility state of the drawer's associated control
		open: true,
		//* "v" for vertical animation; "h" for horizontal animation
		orient: "v",
		//* When true, animate the opening/closing transition
		animated: true
	},
	//* @protected
	style: "overflow: hidden; position: relative;",
	tools: [
		{kind: "Animator", onStep: "animatorStep", onEnd: "animatorEnd"},
		{name: "client", style: "position: relative;", classes: "enyo-border-box"}
	],
	create: function() {
		this.inherited(arguments);
		this.animatedChanged();
		this.openChanged();
	},
	initComponents: function() {
		this.createChrome(this.tools);
		this.inherited(arguments);
	},
	animatedChanged: function() {
		if (!this.animated && this.hasNode() && this.$.animator.isAnimating()) {
			this.$.animator.stop();
			this.animatorEnd();
		}
	},
	openChanged: function() {
		this.$.client.show();
		if (this.hasNode()) {
			if (this.$.animator.isAnimating()) {
				this.$.animator.reverse();
			} else {
				var v = this.orient == "v";
				var d = v ? "height" : "width";
				var p = v ? "top" : "left";
				// unfixing the height/width is needed to properly
				// measure the scrollHeight/Width DOM property, but
				// can cause a momentary flash of content on some browsers
				this.applyStyle(d, null);
				var s = this.hasNode()[v ? "scrollHeight" : "scrollWidth"];
				if (this.animated) {
					this.$.animator.play({
						startValue: this.open ? 0 : s,
						endValue: this.open ? s : 0,
						dimension: d,
						position: p
					});
				} else {
					// directly run last frame if not animating
					this.animatorEnd();
				}
			}
		} else {
			this.$.client.setShowing(this.open);
		}
	},
	animatorStep: function(inSender) {
		// the actual drawer DOM node adjusts its height
		if (this.hasNode()) {
			var d = inSender.dimension;
			this.node.style[d] = this.domStyles[d] = inSender.value + "px";
		}
		// while the client inside the drawer adjusts its position to move out of the visible area
		var cn = this.$.client.hasNode();
		if (cn) {
			var p = inSender.position;
			var o = (this.open ? inSender.endValue : inSender.startValue);
			cn.style[p] = this.$.client.domStyles[p] = (inSender.value - o) + "px";
		}
		if (this.container) {
			this.container.resized();
		}
	},
	animatorEnd: function() {
		if (!this.open) {
			this.$.client.hide();
		}
		else {
			// at end of open animation, clean limit on height/width
			var v = (this.orient == "v");
			var d = v ? "height" : "width";
			var p = v ? "top" : "left";
			var cn = this.$.client.hasNode();
			// clear out changes to container position & node dimension
			if (cn) {
				cn.style[p] = this.$.client.domStyles[p] = null;
			}
			if (this.node) {
				this.node.style[d] = this.domStyles[d] = null;
			}
		}
		if (this.container) {
			this.container.resized();
		}
	}
});<commit_msg>Editing API comments. Enyo-DCO-1.0-Signed-off-by: Jim Tang <jim.tang@palm.com><commit_after>/**
	_onyx.Drawer_ is a control that appears or disappears based on its _open_
	property. By default, the drawer appears or disappears with a sliding
	animation whose direction is determined by the _orient_ property.

	For more information, see the documentation on
	Drawers in the
	Enyo Developer Guide.
*/
enyo.kind({
	name: "onyx.Drawer",
	published: {
		//* The visibility state of the drawer's associated control
		open: true,
		/**
		    Direction of the opening/closing animation--either "v" for vertical
		    or "h" for horizontal
		*/
		orient: "v",
		//* If true, the opening/closing transition will be animated.
		animated: true
	},
	//* @protected
	style: "overflow: hidden; position: relative;",
	tools: [
		{kind: "Animator", onStep: "animatorStep", onEnd: "animatorEnd"},
		{name: "client", style: "position: relative;", classes: "enyo-border-box"}
	],
	create: function() {
		this.inherited(arguments);
		this.animatedChanged();
		this.openChanged();
	},
	initComponents: function() {
		this.createChrome(this.tools);
		this.inherited(arguments);
	},
	animatedChanged: function() {
		if (!this.animated && this.hasNode() && this.$.animator.isAnimating()) {
			this.$.animator.stop();
			this.animatorEnd();
		}
	},
	openChanged: function() {
		this.$.client.show();
		if (this.hasNode()) {
			if (this.$.animator.isAnimating()) {
				this.$.animator.reverse();
			} else {
				var v = this.orient == "v";
				var d = v ? "height" : "width";
				var p = v ? "top" : "left";
				// unfixing the height/width is needed to properly
				// measure the scrollHeight/Width DOM property, but
				// can cause a momentary flash of content on some browsers
				this.applyStyle(d, null);
				var s = this.hasNode()[v ? "scrollHeight" : "scrollWidth"];
				if (this.animated) {
					this.$.animator.play({
						startValue: this.open ? 0 : s,
						endValue: this.open ? s : 0,
						dimension: d,
						position: p
					});
				} else {
					// directly run last frame if not animating
					this.animatorEnd();
				}
			}
		} else {
			this.$.client.setShowing(this.open);
		}
	},
	animatorStep: function(inSender) {
		// the actual drawer DOM node adjusts its height
		if (this.hasNode()) {
			var d = inSender.dimension;
			this.node.style[d] = this.domStyles[d] = inSender.value + "px";
		}
		// while the client inside the drawer adjusts its position to move out of the visible area
		var cn = this.$.client.hasNode();
		if (cn) {
			var p = inSender.position;
			var o = (this.open ? inSender.endValue : inSender.startValue);
			cn.style[p] = this.$.client.domStyles[p] = (inSender.value - o) + "px";
		}
		if (this.container) {
			this.container.resized();
		}
	},
	animatorEnd: function() {
		if (!this.open) {
			this.$.client.hide();
		}
		else {
			// at end of open animation, clean limit on height/width
			var v = (this.orient == "v");
			var d = v ? "height" : "width";
			var p = v ? "top" : "left";
			var cn = this.$.client.hasNode();
			// clear out changes to container position & node dimension
			if (cn) {
				cn.style[p] = this.$.client.domStyles[p] = null;
			}
			if (this.node) {
				this.node.style[d] = this.domStyles[d] = null;
			}
		}
		if (this.container) {
			this.container.resized();
		}
	}
});<|endoftext|>


<commit_before>import { normalize, schema } from 'normalizr';
import data from './sampleData.json';

// Define a usres schema
const author = new schema.Entity('author');

// Define your comments schema
const comment = new schema.Entity(
  'comment',
  {
    commenter: author
  }
);

// Define your article
const article = new schema.Entity(
  'articles',
  {
    author: author,
    comments: [ comment ]
  }
);

const normalizedData = normalize(data, article);
console.log(normalizedData);
<commit_msg>修改输出的JSON的字段名<commit_after>import { normalize, schema } from 'normalizr';
import data from './sampleData.json';

// Define a usres schema
const users = new schema.Entity('users');

// Define your comments schema
const comment = new schema.Entity(
  'comment',
  {
    commenter: users
  }
);

// Define your article
const article = new schema.Entity(
  'articles',
  {
    author: users,
    comments: [ comment ]
  }
);

const normalizedData = normalize(data, article);
console.log(normalizedData);

// {
//   result: "123",
//   entities: {
//     "articles": {
//       "123": {
//         id: "123",
//         author: "1",
//         title: "My awesome blog post",
//         comments: [ "324" ]
//       }
//     },
//     "users": {
//       "1": { "id": "1", "name": "Paul" },
//       "2": { "id": "2", "name": "Nicole" }
//     },
//     "comments": {
//       "324": { id: "324", "commenter": "2" }
//     }
//   }
// }
<|endoftext|>


<commit_before>// lunchbot.js

require('datejs');
var util = require('util');
var Bot = require('slackbots');
var Tokenizer = require('sentence-tokenizer');

var LunchBot = function Constructor(settings) {
    this.settings = settings;
    this.settings.name = this.settings.name || 'LunchBot';
    this.services = [];
    this.tokenizer = new Tokenizer('Chuck');
};

// Inherit stuffs from the original Bot
util.inherits(LunchBot, Bot);

//
//  Helpers
//

String.prototype.containsAny = function(terms) {
    for (term of terms) {
        var idx = this.indexOf(term);
        if (idx != -1) {
            return true;
        }
    }

    return false;
}

LunchBot.prototype._isValidMessage = function(message) {
    if (message.type != 'message' || !Boolean(message.text)) {
        return false;
    }

    // Ignore messages from other bots
    if (message.subtype == 'bot_message') {
        return false;
    }

    // Ignore anything other than messages in groups and channels
    if (typeof message.channel != 'string' || (message.channel[0] != 'C' && message.channel[0] != 'G')) {
        return false;
    }

    // Ignore our own messages
    if (message.user == this.user.id) {
        return false;
    }

    // Ignore messages not mentioning us
    if (message.text.indexOf('<@' + this.user.id + '>') == -1) {
        return false;
    }

    return true;
};

LunchBot.prototype._dateFromMessage = function(message) {
    this.tokenizer.setEntry(message.text);
    var sentences = this.tokenizer.getSentences();

    var date = new Date()
    for (var i = 0; i < sentences.length; i++) {
        var dates = this.tokenizer.getTokens(i).map(function(e) {
            return Date.parse(e);
        }).filter(function(e) {
            return e != undefined && e != null;
        });

        if (dates.length > 0) {
            date = dates[0];
            break;
        }
    }

    return date;
}

//
//  Actions
//

LunchBot.prototype._showMenus = function(message) {
    var that = this;
    var date = this._dateFromMessage(message);

    var fetches = this.services.map(function(e) {
        return e.fetch(date);
    });

    Promise.all(fetches).then(function(values) {
        var attachments = [];

        for (i in values) {
            var messages = values[i];
            var service = that.services[i];

            attachments.push({
                "title": ':' + service.emoji + ': ' + service.name,
                "text": messages.join('\n')
            });
        }

        that.postMessage(message.channel, undefined, {
            icon_emoji: ":fork_and_knife:",
            attachments: JSON.stringify(attachments)
        });
    });
};

//
//  Events
//

LunchBot.prototype._onStart = function() {
    var needle = this.name.toLowerCase();
    this.user = this.users.filter(function(user) {
        return user.name === needle;
    })[0];

    console.log(this.name + " is now active");
};

LunchBot.prototype._onMessage = function(message) {
    if (!this._isValidMessage(message)) {
        return
    }

    const menuTerms = ['menu', 'offers', 'lunch'];
    if (message.text.containsAny(menuTerms)) {
        this._showMenus(message);
    }
};

//
//  Main
//

LunchBot.prototype.run = function() {
    LunchBot.super_.call(this, this.settings);

    this.on('start', this._onStart);
    this.on('message', this._onMessage);
};

module.exports = LunchBot;
<commit_msg>Announce our presence in channels<commit_after>// lunchbot.js

require('datejs');
var util = require('util');
var Bot = require('slackbots');
var Tokenizer = require('sentence-tokenizer');

var LunchBot = function Constructor(settings) {
    this.settings = settings;
    this.settings.name = this.settings.name || 'LunchBot';
    this.services = [];
    this.tokenizer = new Tokenizer('Chuck');
};

// Inherit stuffs from the original Bot
util.inherits(LunchBot, Bot);

//
//  Helpers
//

String.prototype.containsAny = function(terms) {
    for (term of terms) {
        var idx = this.indexOf(term);
        if (idx != -1) {
            return true;
        }
    }

    return false;
};

LunchBot.prototype._isValidJoinMessage = function(message) {
    if (message.type != 'channel_joined') {
        return false;
    }

    // Ignore anything other than messages in groups and channels
    if (typeof message.channel != 'string' || (message.channel[0] != 'C' && message.channel[0] != 'G')) {
        return false;
    }

    return true;
};

LunchBot.prototype._isValidActionMessage = function(message) {
    if (message.type != 'message' || !Boolean(message.text)) {
        return false;
    }

    // Ignore messages from other bots
    if (message.subtype == 'bot_message') {
        return false;
    }

    // Ignore anything other than messages in groups and channels
    if (typeof message.channel != 'string' || (message.channel[0] != 'C' && message.channel[0] != 'G')) {
        return false;
    }

    // Ignore our own messages
    if (message.user == this.user.id) {
        return false;
    }

    // Ignore messages not mentioning us
    if (message.text.indexOf('<@' + this.user.id + '>') == -1) {
        return false;
    }

    return true;
};

LunchBot.prototype._dateFromMessage = function(message) {
    this.tokenizer.setEntry(message.text);
    var sentences = this.tokenizer.getSentences();

    var date = new Date()
    for (var i = 0; i < sentences.length; i++) {
        var dates = this.tokenizer.getTokens(i).map(function(e) {
            return Date.parse(e);
        }).filter(function(e) {
            return e != undefined && e != null;
        });

        if (dates.length > 0) {
            date = dates[0];
            break;
        }
    }

    return date;
};

//
//  Actions
//

LunchBot.prototype._showMenus = function(message) {
    var that = this;
    var date = this._dateFromMessage(message);

    var fetches = this.services.map(function(e) {
        return e.fetch(date);
    });

    Promise.all(fetches).then(function(values) {
        var attachments = [];

        for (i in values) {
            var messages = values[i];
            var service = that.services[i];

            attachments.push({
                "title": ':' + service.emoji + ': ' + service.name,
                "text": messages.join('\n')
            });
        }

        that.postMessage(message.channel, undefined, {
            icon_emoji: ":fork_and_knife:",
            attachments: JSON.stringify(attachments)
        });
    });
};

LunchBot.prototype._announceInChannel = function(channel) {
    var id = typeof channel == 'string' ? channel : channel.id;

    this.postMessage(id, 'Hi! I am now active in this channel', {
        icon_emoji: ":fork_and_knife:"
    });
};

//
//  Events
//

LunchBot.prototype._onStart = function() {
    var needle = this.name.toLowerCase();
    this.user = this.users.filter(function(user) {
        return user.name === needle;
    })[0];

    // Announce we are awake in all of the channels we belong to
    var channels = this.channels.filter(function(c) {
        return c.is_member == true;
    });

    for (channel of channels) {
        this._announceInChannel(channel);
    }

    var groups = this.groups;

    for (group of groups) {
        this._announceInChannel(group);
    }
};

LunchBot.prototype._onMessage = function(message) {
    if (this._isValidActionMessage(message)) {
        const menuTerms = ['menu', 'offers', 'lunch'];
        if (message.text.containsAny(menuTerms)) {
            this._showMenus(message);
        }
    } else if (this._isValidJoinMessage(message)) {
        this._announceInChannel(message.channel);
    }
};

//
//  Main
//

LunchBot.prototype.run = function() {
    LunchBot.super_.call(this, this.settings);

    this.on('start', this._onStart);
    this.on('message', this._onMessage);
};

module.exports = LunchBot;
<|endoftext|>


<commit_before>var pages = function(dbot) {
    var connections = dbot.instance.connections;

    return {
        '/connections': function(req, res) {
            var connections = Object.keys(dbot.instance.connections);
            res.render('connections', { 'name': dbot.config.name, 'connections': connections });
        },

        '/channels/:connection': function(req, res) {
            var connection = req.params.connection;
            if(dbot.instance.connections.hasOwnProperty(connection)) {
                var channels = Object.keys(dbot.instance.connections[connection].channels);
                res.render('channels', { 'name': dbot.config.name, 'connection': connection, 'channels': channels});
            } else {
                res.render_core('error', { 'name': dbot.config.name, 'message': 'No such connection.' });
            }
        },

        '/users/:connection/:channel': function(req, res) {
            var connection = req.params.connection;
            var channel = '#' + req.params.channel;
            var connections = dbot.instance.connections;

            if(connections.hasOwnProperty(connection) &&
                connections[connection].channels.hasOwnProperty(channel)) {

                var channelUsers = dbot.db.knownUsers[connection].channelUsers[channel];
                var usersData = {};
                for(var i=0;i<channelUsers.length;i++) {
                    usersData[channelUsers[i]] = {
                        'name': channelUsers[i],
                        'online': false,
                        'active': false
                    };
                }

                var onlineNicks = connections[connection].channels[channel].nicks;
                onlineNicks.each(function(nick) {
                    var user = dbot.api.users.resolveUser(connection, nick);
                    if(onlineNicks.hasOwnProperty(nick)) {
                        usersData[user].online = true;
                    }
                    /*usersData[nick].active = dbot.api.stats.isActive({
                        'server': connection,
                        'user': nick,
                        'channel': channel
                    });*/
                }.bind(this));

                res.render('users', { 'name': dbot.config.name, 'connection': connection,
                    'channel': channel, 'nicks': usersData });
            } else {
                res.render_core('error', { 'name': dbot.config.name, 'message': 'No such connection or channel.' });
            }
        },

        '/user/:connection/:channel/:user': function(req, res) {
            var connection = req.params.connection;
            var channel = '#' + req.params.channel;
            var user = dbot.cleanNick(req.params.user);

            var quoteCount = 'no';
            if(dbot.db.quoteArrs.hasOwnProperty(user)) {
                var quoteCount = dbot.db.quoteArrs[user].length;
            }

            if(dbot.config.moduleNames.include('kick')) {
                if(!dbot.db.kicks.hasOwnProperty(req.params.user)) {
                    var kicks = '0';
                } else {
                    var kicks = dbot.db.kicks[req.params.user];
                }

                if(!dbot.db.kickers.hasOwnProperty(req.params.user)) {
                    var kicked = '0';
                } else {
                    var kicked = dbot.db.kickers[req.params.user];
                }
            } else {
                var kicks = 'N/A';
                var kicked = 'N/A';
            }

            res.render('user', { 'name': dbot.config.name, 'user': req.params.user,
            'channel': channel, 'connection': connection, 'cleanUser': user,
            'quotecount': quoteCount, 'kicks': kicks, 'kicked': kicked });
        }
    };
};

exports.getPages = function(dbot) {
    return pages(dbot);
};
<commit_msg>active works!<commit_after>var pages = function(dbot) {
    var connections = dbot.instance.connections;

    return {
        '/connections': function(req, res) {
            var connections = Object.keys(dbot.instance.connections);
            res.render('connections', { 'name': dbot.config.name, 'connections': connections });
        },

        '/channels/:connection': function(req, res) {
            var connection = req.params.connection;
            if(dbot.instance.connections.hasOwnProperty(connection)) {
                var channels = Object.keys(dbot.instance.connections[connection].channels);
                res.render('channels', { 'name': dbot.config.name, 'connection': connection, 'channels': channels});
            } else {
                res.render_core('error', { 'name': dbot.config.name, 'message': 'No such connection.' });
            }
        },

        '/users/:connection/:channel': function(req, res) {
            var connection = req.params.connection;
            var channel = '#' + req.params.channel;
            var connections = dbot.instance.connections;

            if(connections.hasOwnProperty(connection) &&
                connections[connection].channels.hasOwnProperty(channel)) {

                var channelUsers = dbot.db.knownUsers[connection].channelUsers[channel];
                var usersData = {};
                for(var i=0;i<channelUsers.length;i++) {
                    usersData[channelUsers[i]] = {
                        'name': channelUsers[i],
                        'online': false,
                        'active': false
                    };
                }

                var onlineNicks = connections[connection].channels[channel].nicks;
                onlineNicks.each(function(nick) {
                    var nick = nick.name;
                    var user = dbot.api.users.resolveUser(connection, nick);
                    if(onlineNicks.hasOwnProperty(nick)) {
                        usersData[user].online = true;
                    }
                    console.log(user);
                    usersData[user].active = dbot.api.stats.isActive({
                        'server': connection,
                        'user': user,
                        'channel': channel
                    });
                }.bind(this));

                res.render('users', { 'name': dbot.config.name, 'connection': connection,
                    'channel': channel, 'nicks': usersData });
            } else {
                res.render_core('error', { 'name': dbot.config.name, 'message': 'No such connection or channel.' });
            }
        },

        '/user/:connection/:channel/:user': function(req, res) {
            var connection = req.params.connection;
            var channel = '#' + req.params.channel;
            var user = dbot.cleanNick(req.params.user);

            var quoteCount = 'no';
            if(dbot.db.quoteArrs.hasOwnProperty(user)) {
                var quoteCount = dbot.db.quoteArrs[user].length;
            }

            if(dbot.config.moduleNames.include('kick')) {
                if(!dbot.db.kicks.hasOwnProperty(req.params.user)) {
                    var kicks = '0';
                } else {
                    var kicks = dbot.db.kicks[req.params.user];
                }

                if(!dbot.db.kickers.hasOwnProperty(req.params.user)) {
                    var kicked = '0';
                } else {
                    var kicked = dbot.db.kickers[req.params.user];
                }
            } else {
                var kicks = 'N/A';
                var kicked = 'N/A';
            }

            res.render('user', { 'name': dbot.config.name, 'user': req.params.user,
            'channel': channel, 'connection': connection, 'cleanUser': user,
            'quotecount': quoteCount, 'kicks': kicks, 'kicked': kicked });
        }
    };
};

exports.getPages = function(dbot) {
    return pages(dbot);
};
<|endoftext|>


<commit_before>//TODO:Javacsript can check if checked Ids hasv the same scale ID
function extractSelectedItems(submitButton) {
	sourceForm = document.getElementById("modifyFormRows");
	destinationForm = submitButton.form;
	var count = 0; //enforce at least 2 check box are checked

	if (sourceForm && destinationForm) {
		var idList = "";

		// look for checkboxes which have IDs of the form "block-12-11" and keep track of the ones that are checked.
		for (var a=0; a < sourceForm.elements.length; a++) {
			if (sourceForm.elements[a].type=="checkbox" &&
sourceForm.elements[a].checked) {
				if (idList.length > 0) { idList += ","; }
				idList += sourceForm.elements[a].id.substr(sourceForm.elements[a].id.lastIndexOf('-')+1);
				count = count + 1;
			}
		}
		destinationForm.templateItemIds.value=idList;

		alert("ids="+destinationForm.templateItemIds.value);
		if(count < 2){
		 alert("you must select at least 2 items to create a block");
		 return false;
		}
		else return true;
	}

	return false;
}
<commit_msg>Remove the lert message of passing id info for Block creation<commit_after>//TODO:Javacsript can check if checked Ids hasv the same scale ID
function extractSelectedItems(submitButton) {
	sourceForm = document.getElementById("modifyFormRows");
	destinationForm = submitButton.form;
	var count = 0; //enforce at least 2 check box are checked

	if (sourceForm && destinationForm) {
		var idList = "";

		// look for checkboxes which have IDs of the form "block-12-11" and keep track of the ones that are checked.
		for (var a=0; a < sourceForm.elements.length; a++) {
			if (sourceForm.elements[a].type=="checkbox" &&
sourceForm.elements[a].checked) {
				if (idList.length > 0) { idList += ","; }
				idList += sourceForm.elements[a].id.substr(sourceForm.elements[a].id.lastIndexOf('-')+1);
				count = count + 1;
			}
		}
		destinationForm.templateItemIds.value=idList;

		//alert("ids="+destinationForm.templateItemIds.value);
		if(count < 2){
		 alert("you must select at least 2 items to create a block");
		 return false;
		}
		else return true;
	}

	return false;
}
<|endoftext|>


<commit_before>/*
Copyright 2013 Martin Schnabel. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
*/
define(["base"], function(base) {

var Tile = Backbone.Model.extend({
	defaults: {
		id: null,
		uri: null,
		name: "unnamed",
		closable: false,
		active: false,
		view: null
	}
});

var Tiles = Backbone.Collection.extend({
	model: Tile
});

var Tabs = base.ListView.extend({
	itemView: base.ListItemView.extend({
		template: _.template([
			'<a href="#<%- get("uri") %>" <% if (get("active")) { %> class="active" <% } %>>',
			'<%= get("name") %>',
			'<% if (get("closable")) { %>',
			'x',
			'<% } %>',
		].join('')),
		events: { "click .close": "removeModel"},
		removeModel: function() {
			this.collection.remove(this.model);
		}
	})
});

var App = Backbone.View.extend({
	el: $("#app").get(0),
	initialize: function() {
		this.active = null;
		this.tabs = new Tabs({collection: this.collection}).render();
		$('').appendTo(this.$el).append(this.tabs.$el);
		this.$cont = $('
').appendTo(this.$el);
		this.listenTo(this.collection, "reset remove", this.render);
	},
	activate: function(id) {
		if (this.active != null) {
			if (this.active.get("id") == id) return;
			this.active.set("active", false);
			this.$cont.children().remove();
		}
		this.active = this.collection.get(id);
		if (this.active != null) {
			this.active.set("active", true);
			this.$cont.append(this.active.get("view").$el);
		}
	},
	render: function() {
		var active = this.collection.find(function(model) {
			return model.active;
		});
		this.activate(active && active.get("id") || null);
		return this;
	}
});

var Router = Backbone.Router.extend({
	routes: {
		"": "index",
		"about": "about"
	},
	initialize: function(opts) {
		this.tiles = opts.tiles || new Tiles([]);
		this.app = new App({collection: this.tiles}).render();
		Backbone.history.start({});
	},
	index: function() {
		this.app.activate("index");
	},
	about: function() {
		this.app.activate("about");
	},
});

return {
	Tile: Tile,
	Tiles: Tiles,
	App: App,
	Router: Router,
};

});
<commit_msg>generates client routes from tiles.<commit_after>/*
Copyright 2013 Martin Schnabel. All rights reserved.
Use of this source code is governed by a BSD-style
license that can be found in the LICENSE file.
*/
define(["base"], function(base) {

var Tile = Backbone.Model.extend({
	defaults: {
		id: null,
		uri: null,
		name: "unnamed",
		closable: false,
		active: false,
		view: null
	}
});

var Tiles = Backbone.Collection.extend({
	model: Tile
});

var Tabs = base.ListView.extend({
	itemView: base.ListItemView.extend({
		template: _.template([
			'<a href="#<%- get("uri") %>" <% if (get("active")) { %> class="active" <% } %>>',
			'<%= get("name") %>',
			'<% if (get("closable")) { %>',
			'x',
			'<% } %>',
		].join('')),
		events: { "click .close": "removeModel"},
		removeModel: function() {
			this.collection.remove(this.model);
		}
	})
});

var App = Backbone.View.extend({
	el: $("#app").get(0),
	initialize: function() {
		this.active = null;
		this.tabs = new Tabs({collection: this.collection}).render();
		$('').appendTo(this.$el).append(this.tabs.$el);
		this.$cont = $('
').appendTo(this.$el);
		this.listenTo(this.collection, "reset remove", this.render);
	},
	activate: function(id) {
		if (this.active != null) {
			if (this.active.get("id") == id) return;
			this.active.set("active", false);
			this.$cont.children().remove();
		}
		this.active = this.collection.get(id);
		if (this.active != null) {
			this.active.set("active", true);
			this.$cont.append(this.active.get("view").$el);
		}
	},
	render: function() {
		var active = this.collection.find(function(model) {
			return model.active;
		});
		this.activate(active && active.get("id") || null);
		return this;
	}
});

var Router = Backbone.Router.extend({
	initialize: function(opts) {
		this.tiles = opts.tiles || new Tiles([]);
		this.app = new App({collection: this.tiles}).render();
		this.tiles.each(this.routetile, this);
		Backbone.history.start({});
	},
	routetile: function(t) {
		var id = t.get("id"), uri = t.get("uri");
		this.route(uri, id, _.bind(this.app.activate, this.app, id));
	}
});

return {
	Tile: Tile,
	Tiles: Tiles,
	App: App,
	Router: Router,
};

});
<|endoftext|>


<commit_before>

'use strict';

var url = require('url'),
    Q = require('q'),
    path = require('path'),
    fs = require('fs');

var utils = require('manifoldjs-lib').utils;

var constants = require('./constants');

//check to make sure there is a working W3C Manifest
function convertFromBase(manifestInfo, callback) {
  if (!manifestInfo || !manifestInfo.content) {
    return Q.reject(new Error('Manifest content is empty or not initialized.')).nodeify(callback);
  }

  //set the content of the W3C Manifest to local var
  var originalManifest = manifestInfo.content;

   //check for any required values for this platform.  In the case of office, we only "require" the start URL, all else is optional
  if (!originalManifest.start_url) {
    return Q.reject(new Error('Start URL is required.')).nodeify(callback);
  }

  //pull out the values that we need, then set them to our locals
  var manifest = originalManifest;
  manifest.scopeArray = [];
  //add the scope in
  var tempArray = [];

   if(originalManifest.mjs_extended_scope){
      manifest.scopeArray = tempArray.concat(originalManifest.mjs_extended_scope)
  }
      if(originalManifest.scope){
        manifest.scopeArray.push(originalManifest.scope)
  }

//set a string of the images you want to include in your final project, if they are in the manifest they will be copied down and into your porject
//you should have a default version of each of the required ones
  var platformIamges = '32x32';
  //set flag to require a default image, require by default
  manifest.requireDefaultImg = true

  // map icons, pull all the icons from manifest that fit our dimentions into an array
  if (originalManifest.icons && originalManifest.icons.length) {
    var icons = {};

    for (var i = 0; i < originalManifest.icons.length; i++) {
      var icon = originalManifest.icons[i];
      var patt = new RegExp(icon.sizes);
        if(patt.test(platformIamges)){
            //update flag to require default
            if(icon.sizes == '23x32') manifest.requireDefaultImg = false;
                var iconDimensions = icon.sizes.split('x');
                if (iconDimensions[0] === iconDimensions[1]) {

                    icons[iconDimensions[0]] = icon.src;
                }
                }
        }
    manifest.icons = icons;

  }

  //convert the manifest object into the XML to return
  //read base manifest from file
  //run replace to update the fields with the ones from the w3c manifest
  //generate the file

  var manifestTemplatePath = path.join(__dirname, 'assets', 'manifest.xml');
    return Q.nfcall(fs.readFile, manifestTemplatePath).then(function (data) {

//console.log(data.toString())
    manifest.rawManifest = data.toString();

    //gen a new GUID
      var guid = utils.newGuid();
    console.log(manifest.icons[0])
      manifest.rawManifest  = manifest.rawManifest.replace(/{GUID}/g, guid)
                                    .replace(/{providerName}/g, "Microsoft")
                                    .replace(/{sourceLocation}/g, manifest.start_url)
                                    .replace(/{defaultLocale}/g, manifest.lang || 'EN-US')
                                    .replace(/{displayName}/g, manifest.short_name ||  manifest.name)
                                    .replace(/{description}/g, manifest.name || 'no description provided')
                                    .replace(/{iconURL}/g,manifest.icons[32]?'<IconUrl DefaultValue="'+manifest.icons[32]+'" />': '<IconUrl DefaultValue="defaultIcon.png" />') //only one image can be used

    //build sorce location URLs
    //<AppDomain>{appDomain}</AppDomain>
    var tempURL = ''
    var srcString = '<AppDomain>'+tempURL+'</AppDomain>  ';
    var scopeString = '';
    if(manifest.scopeArray){
        for(var i=0;manifest.scopeArray.length > i;i++){
        tempURL = manifest.scopeArray[i];
        scopeString+=srcString;
        }
        manifest.rawManifest = manifest.rawManifest.replace(/{appDomain}/g, scopeString)
    }else{
        manifest.rawManifest = manifest.rawManifest.replace(/{appDomain}/g, '')
    }
    //run the repace code to add in new values

  var convertedManifestInfo = {
    'content': manifest,
    'format': constants.OFFICE_MANIFEST_FORMAT
  };

  return Q.resolve(convertedManifestInfo).nodeify(callback);

    })

}

module.exports = {
  convertFromBase: convertFromBase
}
<commit_msg>inverted numbers for images<commit_after>

'use strict';

var url = require('url'),
    Q = require('q'),
    path = require('path'),
    fs = require('fs');

var utils = require('manifoldjs-lib').utils;

var constants = require('./constants');

//check to make sure there is a working W3C Manifest
function convertFromBase(manifestInfo, callback) {
  if (!manifestInfo || !manifestInfo.content) {
    return Q.reject(new Error('Manifest content is empty or not initialized.')).nodeify(callback);
  }

  //set the content of the W3C Manifest to local var
  var originalManifest = manifestInfo.content;

   //check for any required values for this platform.  In the case of office, we only "require" the start URL, all else is optional
  if (!originalManifest.start_url) {
    return Q.reject(new Error('Start URL is required.')).nodeify(callback);
  }

  //pull out the values that we need, then set them to our locals
  var manifest = originalManifest;
  manifest.scopeArray = [];
  //add the scope in
  var tempArray = [];

   if(originalManifest.mjs_extended_scope){
      manifest.scopeArray = tempArray.concat(originalManifest.mjs_extended_scope)
  }
      if(originalManifest.scope){
        manifest.scopeArray.push(originalManifest.scope)
  }

//set a string of the images you want to include in your final project, if they are in the manifest they will be copied down and into your porject
//you should have a default version of each of the required ones
  var platformIamges = '32x32';
  //set flag to require a default image, require by default
  manifest.requireDefaultImg = true

  // map icons, pull all the icons from manifest that fit our dimentions into an array
  if (originalManifest.icons && originalManifest.icons.length) {
    var icons = {};

    for (var i = 0; i < originalManifest.icons.length; i++) {
      var icon = originalManifest.icons[i];
      var patt = new RegExp(icon.sizes);
        if(patt.test(platformIamges)){
            //update flag to require default
            if(icon.sizes == '32x32') manifest.requireDefaultImg = false;
                var iconDimensions = icon.sizes.split('x');
                if (iconDimensions[0] === iconDimensions[1]) {

                    icons[iconDimensions[0]] = icon.src;
                }
                }
        }
    manifest.icons = icons;

  }

  //convert the manifest object into the XML to return
  //read base manifest from file
  //run replace to update the fields with the ones from the w3c manifest
  //generate the file

  var manifestTemplatePath = path.join(__dirname, 'assets', 'manifest.xml');
    return Q.nfcall(fs.readFile, manifestTemplatePath).then(function (data) {

//console.log(data.toString())
    manifest.rawManifest = data.toString();

    //gen a new GUID
      var guid = utils.newGuid();
    console.log(manifest.icons[0])
      manifest.rawManifest  = manifest.rawManifest.replace(/{GUID}/g, guid)
                                    .replace(/{providerName}/g, "Microsoft")
                                    .replace(/{sourceLocation}/g, manifest.start_url)
                                    .replace(/{defaultLocale}/g, manifest.lang || 'EN-US')
                                    .replace(/{displayName}/g, manifest.short_name ||  manifest.name)
                                    .replace(/{description}/g, manifest.name || 'no description provided')
                                    .replace(/{iconURL}/g,manifest.icons[32]?'<IconUrl DefaultValue="'+manifest.icons[32]+'" />': '<IconUrl DefaultValue="defaultIcon.png" />') //only one image can be used

    //build sorce location URLs
    //<AppDomain>{appDomain}</AppDomain>
    var tempURL = ''
    var srcString = '<AppDomain>'+tempURL+'</AppDomain>  ';
    var scopeString = '';
    if(manifest.scopeArray){
        for(var i=0;manifest.scopeArray.length > i;i++){
        tempURL = manifest.scopeArray[i];
        scopeString+=srcString;
        }
        manifest.rawManifest = manifest.rawManifest.replace(/{appDomain}/g, scopeString)
    }else{
        manifest.rawManifest = manifest.rawManifest.replace(/{appDomain}/g, '')
    }
    //run the repace code to add in new values

  var convertedManifestInfo = {
    'content': manifest,
    'format': constants.OFFICE_MANIFEST_FORMAT
  };

  return Q.resolve(convertedManifestInfo).nodeify(callback);

    })

}

module.exports = {
  convertFromBase: convertFromBase
}
<|endoftext|>