<commit_before>'use strict';

var FoxxApplication = require("org/arangodb/foxx").Application;
var app = new FoxxApplication(applicationContext);

var arangodb = require("org/arangodb");
var actions = require("org/arangodb/actions");
var helloworld = require("a").text;

var texts = app.createRepository("texts");

// .............................................................................
// a simple text output with static text
// .............................................................................

app.get('/hello-world.txt', function(req, res) {
  res.set("Content-Type", "text/plain; charset=utf-8");
  res.body = "Hallo World (static)\n";
  res.statusCode = actions.HTTP_OK;
});

// .............................................................................
// a simple text output from global variable
// .............................................................................

app.get('/hello-world-global.txt', function(req, res) {
  res.set("Content-Type", "text/plain; charset=utf-8");
  res.body = helloworld + " (global)\n";
  res.statusCode = actions.HTTP_OK;
});

// .............................................................................
// a simple text output from local require
// .............................................................................

app.get('/hello-world-local.txt', function(req, res) {
  res.set("Content-Type", "text/plain; charset=utf-8");
  res.body = require("a").text + " (local)\n";
  res.statusCode = actions.HTTP_OK;
});

// .............................................................................
// a simple text output from repository
// .............................................................................

app.get('/hello-world-repo.txt', function(req, res) {
  res.set("Content-Type", "text/plain; charset=utf-8");
  res.body = texts.collection.any().text + " (repo)\n";
  res.statusCode = actions.HTTP_OK;
});

// .............................................................................
// application context
// .............................................................................

app.get('/application-context.txt', function(req, res) {
  res.set("Content-Type", "text/plain; charset=utf-8");
  res.body = arangodb.inspect(applicationContext) + " \n";
  res.statusCode = actions.HTTP_OK;
});

// .............................................................................
// echo the response object
// .............................................................................

app.get('/echo.json', function(req, res, next, options) {
  var result = { request : req, options : options };

  res.responseCode = actions.HTTP_OK;
  res.contentType = "application/json; charset=utf-8";
  res.body = JSON.stringify(result);
});

// .............................................................................
// convert the response object to text
// .............................................................................

app.get('/echo.txt', function(req, res, next, options) {
  var result = { request : req, options : options };

  res.responseCode = actions.HTTP_OK;
  res.contentType = "text/plain; charset=utf-8";
  res.body = arangodb.inspect(result);
});

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

/// Local Variables:
/// mode: outline-minor
/// outline-regexp: "/// @brief\\|/// @addtogroup\\|/// @page\\|// --SECTION--\\|/// @\\}\\|/\\*jslint"
/// End:
<commit_msg>added application-context.json<commit_after>'use strict';

var FoxxApplication = require("org/arangodb/foxx").Application;
var app = new FoxxApplication(applicationContext);

var arangodb = require("org/arangodb");
var actions = require("org/arangodb/actions");
var helloworld = require("a").text;

var texts = app.createRepository("texts");

// .............................................................................
// a simple text output with static text
// .............................................................................

app.get('/hello-world.txt', function(req, res) {
  res.set("Content-Type", "text/plain; charset=utf-8");
  res.body = "Hallo World (static)\n";
  res.statusCode = actions.HTTP_OK;
});

// .............................................................................
// a simple text output from global variable
// .............................................................................

app.get('/hello-world-global.txt', function(req, res) {
  res.set("Content-Type", "text/plain; charset=utf-8");
  res.body = helloworld + " (global)\n";
  res.statusCode = actions.HTTP_OK;
});

// .............................................................................
// a simple text output from local require
// .............................................................................

app.get('/hello-world-local.txt', function(req, res) {
  res.set("Content-Type", "text/plain; charset=utf-8");
  res.body = require("a").text + " (local)\n";
  res.statusCode = actions.HTTP_OK;
});

// .............................................................................
// a simple text output from repository
// .............................................................................

app.get('/hello-world-repo.txt', function(req, res) {
  res.set("Content-Type", "text/plain; charset=utf-8");
  res.body = texts.collection.any().text + " (repo)\n";
  res.statusCode = actions.HTTP_OK;
});

// .............................................................................
// application context as json
// .............................................................................

app.get('/application-context.json', function(req, res) {
  res.contentType = "application/json; charset=utf-8";

  var c = applicationContext._shallowCopy;
  delete c.foxxes;
  delete c.routingInfo;
  delete c.appModule;

  res.body = JSON.stringify(c) + " \n";
  res.statusCode = actions.HTTP_OK;
});

// .............................................................................
// application context as text
// .............................................................................

app.get('/application-context.txt', function(req, res) {
  res.set("Content-Type", "text/plain; charset=utf-8");
  res.body = arangodb.inspect(applicationContext) + " \n";
  res.statusCode = actions.HTTP_OK;
});

// .............................................................................
// echo the response object
// .............................................................................

app.get('/echo.json', function(req, res, next, options) {
  var result = { request : req, options : options };

  res.responseCode = actions.HTTP_OK;
  res.contentType = "application/json; charset=utf-8";
  res.body = JSON.stringify(result);
});

// .............................................................................
// convert the response object to text
// .............................................................................

app.get('/echo.txt', function(req, res, next, options) {
  var result = { request : req, options : options };

  res.responseCode = actions.HTTP_OK;
  res.contentType = "text/plain; charset=utf-8";
  res.body = arangodb.inspect(result);
});

// -----------------------------------------------------------------------------
// --SECTION--                                                       END-OF-FILE
// -----------------------------------------------------------------------------

/// Local Variables:
/// mode: outline-minor
/// outline-regexp: "/// @brief\\|/// @addtogroup\\|/// @page\\|// --SECTION--\\|/// @\\}\\|/\\*jslint"
/// End:
<|endoftext|>


<commit_before>module.exports = function(skill, info, bot, message) {
  bot.self_ref = bot;

util = require("util");

var obj_str = util.inspect(bot);
console.log(obj_str);

 // console.log(JSON.stringify(bot, null, 4));

//bot.storage.users.save({id: message.user, foo:'bar'}, function(err) { console.log('yes'); });

/*bot.memory_store.channels[channel_id]
bot.memory_store.users[user_id]
bot.memory_store.teams[team_id]

botkit.memory_store.channels[channel_id]
botkit.memory_store.users[user_id]
botkit.memory_store.teams[team_id]

  controller.storage.users.save({id: message.user, foo:'bar'}, function(err) { ... });
  controller.storage.users.get(id, function(err, user_data) {...});
  controller.storage.users.all(function(err, all_user_data) {...});

  controller.storage.channels.save({id: message.channel, foo:'bar'}, function(err) { ... });
  controller.storage.channels.get(id, function(err, channel_data) {...});
  controller.storage.channels.all(function(err, all_channel_data) {...});

  controller.storage.teams.save({id: message.team, foo:'bar'}, function(err) { ... });
  controller.storage.teams.get(id, function(err, team_data) {...});
  controller.storage.teams.all(function(err, all_team_data) {...});
  bot.reply(message, 'test successful. maybe code something more useful next time?');*/
};
<commit_msg>Update MemoryTest.js<commit_after>module.exports = function(skill, info, bot, message, db) {
  // save with generated ID
db.save(d, function(err, id){
  // id is a unique ID
});

  bot.self_ref = bot;

util = require("util");

var obj_str = util.inspect(bot);
console.log(obj_str);

 // console.log(JSON.stringify(bot, null, 4));

//bot.storage.users.save({id: message.user, foo:'bar'}, function(err) { console.log('yes'); });

/*bot.memory_store.channels[channel_id]
bot.memory_store.users[user_id]
bot.memory_store.teams[team_id]

botkit.memory_store.channels[channel_id]
botkit.memory_store.users[user_id]
botkit.memory_store.teams[team_id]

  controller.storage.users.save({id: message.user, foo:'bar'}, function(err) { ... });
  controller.storage.users.get(id, function(err, user_data) {...});
  controller.storage.users.all(function(err, all_user_data) {...});

  controller.storage.channels.save({id: message.channel, foo:'bar'}, function(err) { ... });
  controller.storage.channels.get(id, function(err, channel_data) {...});
  controller.storage.channels.all(function(err, all_channel_data) {...});

  controller.storage.teams.save({id: message.team, foo:'bar'}, function(err) { ... });
  controller.storage.teams.get(id, function(err, team_data) {...});
  controller.storage.teams.all(function(err, all_team_data) {...});
  bot.reply(message, 'test successful. maybe code something more useful next time?');*/
};
<|endoftext|>


<commit_before>import { promise } from "lively.lang";
import { addOrChangeCSSDeclaration, addOrChangeLinkedCSS } from "./dom-helper.js";
import { defaultStyle, defaultAttributes, render } from "./morphic-default.js";
import {h} from "virtual-dom";

const defaultCSS = `

.no-html-select {
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.halo-guide {
  -webkit-animation: fadein .5s;
}

.smooth-extent {
  -webkit-transition: width .2s, height .2s, transform .2s;
}

.halo-mesh {
  background-color:transparent;
  background-image: linear-gradient(rgba(0,0,0,.1) 2px, transparent 2px),
  linear-gradient(90deg, rgba(0,0,0,.1) 2px, transparent 2px),
  linear-gradient(rgba(0,0,0,.1) 1px, transparent 1px),
  linear-gradient(90deg, rgba(0,0,0,.1) 1px, transparent 1px);
  background-size:100px 100px, 100px 100px, 10px 10px, 10px 10px;
  background-position:-2px -2px, -2px -2px, -1px -1px, -1px -1px;
   -webkit-animation: fadein .5s;
}

.morph {
  /*for aliasing issue in chrome: http://stackoverflow.com/questions/6492027/css-transform-jagged-edges-in-chrome*/
  -webkit-backface-visibility: hidden;

  /*include border size in extent of element*/
  box-sizing: border-box;

  /*don't use dom selection on morphs*/
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.hand {
  z-index: 1;
}

.halo {
  z-index: 2;
}

.center-text {
	text-align: center;
	vertical-align: middle;
}

.halo-item {
  /*FIXME: we shouldn't need to hardcode the size...*/
	line-height: 24px !important;
	text-align: center;
	vertical-align: middle;
}

@-webkit-keyframes fadein { /* Safari and Chrome */
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}

`;

export class Renderer {

  static default() { return this._default || new this() }

  constructor(world, rootNode, domEnvironment) {
    if (!world || !world.isMorph)
      throw new Error(`Trying to initialize renderer with an invalid world morph: ${world}`)
    if (!rootNode || !("nodeType" in rootNode))
      throw new Error(`Trying to initialize renderer with an invalid root node: ${rootNode}`)
    if (!domEnvironment) {
      var doc = rootNode.ownerDocument;
      domEnvironment = {window: System.global, document: doc};
    }
    this.worldMorph = world;
    world._isWorld = true; // for world() method
    world._renderer = this;
    this.rootNode = rootNode;
    this.domNode = null;
    this.domEnvironment = domEnvironment;
    this.renderMap = new WeakMap();
    this.renderWorldLoopProcess = null;
    FontMetric.initDefault(domEnvironment.document);
  }

  clear() {
    this.stopRenderWorldLoop();
    this.domNode && this.domNode.parentNode.removeChild(this.domNode);
    this.domNode = null;
    this.renderMap = new WeakMap();
    FontMetric.removeDefault();
  }

  ensureDefaultCSS() {
    return promise.waitFor(3000, () => this.domNode.ownerDocument)
      .then(doc => Promise.all([
        addOrChangeCSSDeclaration("lively-morphic-css", defaultCSS, doc),
        addOrChangeLinkedCSS("lively-font-awesome", System.decanonicalize("lively.morphic/assets/font-awesome/css/font-awesome.css"), doc)]));
  }

  startRenderWorldLoop() {
    this.worldMorph.renderAsRoot(this);
    this.renderWorldLoopProcess = this.domEnvironment.window.requestAnimationFrame(() =>
      this.startRenderWorldLoop());
    return this;
  }

  stopRenderWorldLoop() {
    this.domEnvironment.window.cancelAnimationFrame(this.renderWorldLoopProcess);
    this.renderWorldLoopProcess = null;
  }

  getNodeForMorph(morph) {
    // Hmm, this also finds dom nodes not associated with this renderer, its
    // domNode... Is this a problem?
    // return this.domNode.ownerDocument.getElementById(morph.id);

    // test, for scoped lookup, fixing the issue mentioned above
    return this.domNode ? this.domNode.querySelector("#" + morph.id) : null;
  }

  getMorphForNode(node) {
    return this.worldMorph ?
      this.worldMorph.withAllSubmorphsDetect(morph => morph.id === node.id) :
      null;
  }

  render(x) {
    if (!x.needsRerender()) {
      var rendered = this.renderMap.get(x);
      if (rendered) return rendered;
    }
    x.aboutToRender();

    var tree = x.render(this);
    this.renderMap.set(x, tree);
    return tree;
  }

  renderMorph(morph) {
    return h("div", {
      ...defaultAttributes(morph),
      style: defaultStyle(morph)
    }, morph.submorphs.map(m => this.render(m)));
  }

  renderText(text) {
    return h("textarea", {
      ...defaultAttributes(text),
      value: text.textString,
      readOnly: text.readOnly,
      placeholder: text.placeholder,
      ...(text._needsSelect && {
        selectionStart: text._selection.start,
        selectionEnd: text._selection.end
      }),
      style: {
        ...defaultStyle(text),
        resize: "none",
        border: 0,
        "white-space": "nowrap",
        padding: "0px",
        "font-family": text.fontFamily,
        "font-size": text.fontSize + "px",
        "color": String(text.fontColor)
      }
    });
  }

  renderImage(image) {
    return h("div", {...defaultAttributes(image),
                     style: defaultStyle(image)},
                    [h("img", {src: image.imageUrl,
                               draggable: false,
                               style: {
                                  "pointer-events": "none",
                                  position: "absolute",
                                  width: "100%", height: "100%"}}),
                    h("div", image.submorphs.map(m => this.render(m)))]);
  }

  renderPath(path) {
    const {transform, transformOrigin, position, WebkitFilter,
           display} = defaultStyle(path),
          {width, height} = path.innerBounds(),
          vertices = renderVertices(path),
          defs = path.gradient && renderGradient(path);
    return h("div", {...defaultAttributes(path),
                     style: {transform, transformOrigin, position,
                             width: width + 'px', height: height + 'px',
                             display, WebkitFilter, "pointer-events": "auto"}},
              h("svg", {namespace: "http://www.w3.org/2000/svg",
                        style: {position: "absolute", "pointer-events": "none"},
                        attributes:
                         {width, height, "viewBox": [-2,-2,width,height].join(" "),
                        ...(path.borderStyle == "dashed" && {"stroke-dasharray": "7 4"})}},
                  [defs].concat(vertices)));
  }
}

function renderVertices(path) {
  var vertices = [];
  for (var i = 0; i < path.vertices.length - 1; i++) {
    var {x: x1, y: y1} = path.vertices[i],
        {x: x2, y: y2} = path.vertices[i+1];
    vertices.push(h("path",
                {namespace: "http://www.w3.org/2000/svg",
                 attributes:
                  {"sroke-width": path.borderWidth,
                   stroke: path.gradient ? "url(#" + path.id + ")" : path.borderColor,
                 d: "M"+x1+","+y1+" "+"L"+x2+","+y2}}));
  }
  return vertices;
}

function renderGradient(path) {
  return h("defs", {namespace: "http://www.w3.org/2000/svg"},
                h("linearGradient", {namespace: "http://www.w3.org/2000/svg",
                                     attributes: {id: path.id}},
                    path.gradient.map(([k, c]) =>
                        h("stop",
                            {namespace: "http://www.w3.org/2000/svg",
                              attributes:
                                {offset: (k * 100) + "%",
                                 "stop-color": c}}))));
}

export class FontMetric {

  static default() {
    if (!this._fontMetric)
      throw new Error("FontMetric has not yet been initialized!")
    return this._fontMetric;
  }

  static initDefault(doc = typeof document !== "undefined" ? document : null) {
    if (!this._fontMetric) {
      this._fontMetric = new FontMetric();
      this._fontMetric.install(doc, doc.body);
    }
  }

  static removeDefault() {
    if (this._fontMetric) {
      this._fontMetric.uninstall();
      this._fontMetric = null;
    }
  }

  constructor() {
    this.charMap = [];
    this.parentElement = null;
    this.element = null;
  }

  install(doc, parentEl) {
    this.parentElement = parentEl;
    this.element = doc.createElement("div");
    this.setMeasureNodeStyles(this.element.style, true);
    this.parentElement.appendChild(this.element);
  }

  uninstall() {
    if (this.element) {
      this.parentElement.removeChild(this.element);
      this.parentElement = null;
      this.element = null;
    }
  }

  setMeasureNodeStyles(style, isRoot) {
    style.width = style.height = "auto";
    style.left = style.top = "0px";
    style.visibility = "hidden";
    style.position = "absolute";
    style.whiteSpace = "pre";
    style.font = "inherit";
    style.overflow = isRoot ? "hidden" : "visible";
  }

  measure(fontFamily, fontSize, char) {
    var rect = null;
    this.element.innerHTML = char;
    this.element.style.fontFamily = fontFamily;
    this.element.style.fontSize = fontSize + "px";
    try {
      rect = this.element.getBoundingClientRect();
    } catch(e) {
      rect = {width: 0, height:0};
    };
    return {
      height: rect.height,
      width: rect.width
    }
  }

  sizeFor(fontFamily, fontSize, char) {
    if (char.length > 1)
      return this.sizeForStr(fontFamily, fontSize, char);

    if (!this.charMap[fontFamily]) {
      this.charMap[fontFamily] = [];
    }
    if (!this.charMap[fontFamily][fontSize]) {
      this.charMap[fontFamily][fontSize] = [];
    }
    if (!this.charMap[fontFamily][fontSize][char])
      this.charMap[fontFamily][fontSize][char] = this.measure(fontFamily, fontSize, char);
    return this.charMap[fontFamily][fontSize][char];
  }

  sizeForStr(fontFamily, fontSize, str) {
    var height = 0, width = 0;
    for (let line of str.split('\n')) {
      let lineHeight = 0, lineWidth = 0;
      for (let char of line.split('')) {
        let { height: charHeight, width: charWidth } = this.sizeFor(fontFamily, fontSize, char);
        if (charHeight > lineHeight) lineHeight = charHeight;
        lineWidth += charWidth;
      }
      if (lineWidth > width) width = lineWidth;
      height += lineHeight || this.sizeFor(fontFamily, fontSize, " ").height;
    }
    return { height: height, width: width };
  }

  asciiSizes(fontFamily, fontSize) {
    var result = {};
    for (var i = 32; i <= 126; i++) {
      var char = String.fromCharCode(i);
      result[char] = this.sizeFor(fontFamily, fontSize, char)
    }
    return result;
  }
}
<commit_msg>fix gradient on orthogonal paths<commit_after>import { promise } from "lively.lang";
import { addOrChangeCSSDeclaration, addOrChangeLinkedCSS } from "./dom-helper.js";
import { defaultStyle, defaultAttributes, render } from "./morphic-default.js";
import {h} from "virtual-dom";

const defaultCSS = `

.no-html-select {
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.halo-guide {
  -webkit-animation: fadein .5s;
}

.smooth-extent {
  -webkit-transition: width .2s, height .2s, transform .2s;
}

.halo-mesh {
  background-color:transparent;
  background-image: linear-gradient(rgba(0,0,0,.1) 2px, transparent 2px),
  linear-gradient(90deg, rgba(0,0,0,.1) 2px, transparent 2px),
  linear-gradient(rgba(0,0,0,.1) 1px, transparent 1px),
  linear-gradient(90deg, rgba(0,0,0,.1) 1px, transparent 1px);
  background-size:100px 100px, 100px 100px, 10px 10px, 10px 10px;
  background-position:-2px -2px, -2px -2px, -1px -1px, -1px -1px;
   -webkit-animation: fadein .5s;
}

.morph {
  /*for aliasing issue in chrome: http://stackoverflow.com/questions/6492027/css-transform-jagged-edges-in-chrome*/
  -webkit-backface-visibility: hidden;

  /*include border size in extent of element*/
  box-sizing: border-box;

  /*don't use dom selection on morphs*/
  -webkit-touch-callout: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

.hand {
  z-index: 1;
}

.halo {
  z-index: 2;
}

.center-text {
	text-align: center;
	vertical-align: middle;
}

.halo-item {
  /*FIXME: we shouldn't need to hardcode the size...*/
	line-height: 24px !important;
	text-align: center;
	vertical-align: middle;
}

@-webkit-keyframes fadein { /* Safari and Chrome */
    from {
        opacity:0;
    }
    to {
        opacity:1;
    }
}

`;

export class Renderer {

  static default() { return this._default || new this() }

  constructor(world, rootNode, domEnvironment) {
    if (!world || !world.isMorph)
      throw new Error(`Trying to initialize renderer with an invalid world morph: ${world}`)
    if (!rootNode || !("nodeType" in rootNode))
      throw new Error(`Trying to initialize renderer with an invalid root node: ${rootNode}`)
    if (!domEnvironment) {
      var doc = rootNode.ownerDocument;
      domEnvironment = {window: System.global, document: doc};
    }
    this.worldMorph = world;
    world._isWorld = true; // for world() method
    world._renderer = this;
    this.rootNode = rootNode;
    this.domNode = null;
    this.domEnvironment = domEnvironment;
    this.renderMap = new WeakMap();
    this.renderWorldLoopProcess = null;
    FontMetric.initDefault(domEnvironment.document);
  }

  clear() {
    this.stopRenderWorldLoop();
    this.domNode && this.domNode.parentNode.removeChild(this.domNode);
    this.domNode = null;
    this.renderMap = new WeakMap();
    FontMetric.removeDefault();
  }

  ensureDefaultCSS() {
    return promise.waitFor(3000, () => this.domNode.ownerDocument)
      .then(doc => Promise.all([
        addOrChangeCSSDeclaration("lively-morphic-css", defaultCSS, doc),
        addOrChangeLinkedCSS("lively-font-awesome", System.decanonicalize("lively.morphic/assets/font-awesome/css/font-awesome.css"), doc)]));
  }

  startRenderWorldLoop() {
    this.worldMorph.renderAsRoot(this);
    this.renderWorldLoopProcess = this.domEnvironment.window.requestAnimationFrame(() =>
      this.startRenderWorldLoop());
    return this;
  }

  stopRenderWorldLoop() {
    this.domEnvironment.window.cancelAnimationFrame(this.renderWorldLoopProcess);
    this.renderWorldLoopProcess = null;
  }

  getNodeForMorph(morph) {
    // Hmm, this also finds dom nodes not associated with this renderer, its
    // domNode... Is this a problem?
    // return this.domNode.ownerDocument.getElementById(morph.id);

    // test, for scoped lookup, fixing the issue mentioned above
    return this.domNode ? this.domNode.querySelector("#" + morph.id) : null;
  }

  getMorphForNode(node) {
    return this.worldMorph ?
      this.worldMorph.withAllSubmorphsDetect(morph => morph.id === node.id) :
      null;
  }

  render(x) {
    if (!x.needsRerender()) {
      var rendered = this.renderMap.get(x);
      if (rendered) return rendered;
    }
    x.aboutToRender();

    var tree = x.render(this);
    this.renderMap.set(x, tree);
    return tree;
  }

  renderMorph(morph) {
    return h("div", {
      ...defaultAttributes(morph),
      style: defaultStyle(morph)
    }, morph.submorphs.map(m => this.render(m)));
  }

  renderText(text) {
    return h("textarea", {
      ...defaultAttributes(text),
      value: text.textString,
      readOnly: text.readOnly,
      placeholder: text.placeholder,
      ...(text._needsSelect && {
        selectionStart: text._selection.start,
        selectionEnd: text._selection.end
      }),
      style: {
        ...defaultStyle(text),
        resize: "none",
        border: 0,
        "white-space": "nowrap",
        padding: "0px",
        "font-family": text.fontFamily,
        "font-size": text.fontSize + "px",
        "color": String(text.fontColor)
      }
    });
  }

  renderImage(image) {
    return h("div", {...defaultAttributes(image),
                     style: defaultStyle(image)},
                    [h("img", {src: image.imageUrl,
                               draggable: false,
                               style: {
                                  "pointer-events": "none",
                                  position: "absolute",
                                  width: "100%", height: "100%"}}),
                    h("div", image.submorphs.map(m => this.render(m)))]);
  }

  renderPath(path) {
    const {transform, transformOrigin, position, WebkitFilter,
           display} = defaultStyle(path),
          {width, height} = path.innerBounds(),
          vertices = renderVertices(path),
          defs = path.gradient && renderGradient(path);
    return h("div", {...defaultAttributes(path),
                     style: {transform, transformOrigin, position,
                             width: width + 'px', height: height + 'px',
                             display, WebkitFilter, "pointer-events": "auto"}},
              h("svg", {namespace: "http://www.w3.org/2000/svg",
                        style: {position: "absolute", "pointer-events": "none"},
                        attributes:
                         {width, height, "viewBox": [-2,-2,width,height].join(" "),
                        ...(path.borderStyle == "dashed" && {"stroke-dasharray": "7 4"})}},
                  [defs].concat(vertices)));
  }
}

function renderVertices(path) {
  var vertices = [];
  for (var i = 0; i < path.vertices.length - 1; i++) {
    var {x: x1, y: y1} = path.vertices[i],
        {x: x2, y: y2} = path.vertices[i+1];
    vertices.push(h("path",
                {namespace: "http://www.w3.org/2000/svg",
                 attributes:
                  {"sroke-width": path.borderWidth,
                   stroke: path.gradient ? "url(#" + path.id + ")" : path.borderColor,
                 d: "M"+x1+","+y1+" "+"L"+x2+","+y2}}));
  }
  return vertices;
}

function renderGradient(path) {
  return h("defs", {namespace: "http://www.w3.org/2000/svg"},
                h("linearGradient", {namespace: "http://www.w3.org/2000/svg",
                                     attributes: {id: path.id,
                                                  gradientUnits: "userSpaceOnUse"}
                                     },
                    path.gradient.map(([k, c]) =>
                        h("stop",
                            {namespace: "http://www.w3.org/2000/svg",
                              attributes:
                                {offset: (k * 100) + "%",
                                 "stop-color": c}}))));
}

export class FontMetric {

  static default() {
    if (!this._fontMetric)
      throw new Error("FontMetric has not yet been initialized!")
    return this._fontMetric;
  }

  static initDefault(doc = typeof document !== "undefined" ? document : null) {
    if (!this._fontMetric) {
      this._fontMetric = new FontMetric();
      this._fontMetric.install(doc, doc.body);
    }
  }

  static removeDefault() {
    if (this._fontMetric) {
      this._fontMetric.uninstall();
      this._fontMetric = null;
    }
  }

  constructor() {
    this.charMap = [];
    this.parentElement = null;
    this.element = null;
  }

  install(doc, parentEl) {
    this.parentElement = parentEl;
    this.element = doc.createElement("div");
    this.setMeasureNodeStyles(this.element.style, true);
    this.parentElement.appendChild(this.element);
  }

  uninstall() {
    if (this.element) {
      this.parentElement.removeChild(this.element);
      this.parentElement = null;
      this.element = null;
    }
  }

  setMeasureNodeStyles(style, isRoot) {
    style.width = style.height = "auto";
    style.left = style.top = "0px";
    style.visibility = "hidden";
    style.position = "absolute";
    style.whiteSpace = "pre";
    style.font = "inherit";
    style.overflow = isRoot ? "hidden" : "visible";
  }

  measure(fontFamily, fontSize, char) {
    var rect = null;
    this.element.innerHTML = char;
    this.element.style.fontFamily = fontFamily;
    this.element.style.fontSize = fontSize + "px";
    try {
      rect = this.element.getBoundingClientRect();
    } catch(e) {
      rect = {width: 0, height:0};
    };
    return {
      height: rect.height,
      width: rect.width
    }
  }

  sizeFor(fontFamily, fontSize, char) {
    if (char.length > 1)
      return this.sizeForStr(fontFamily, fontSize, char);

    if (!this.charMap[fontFamily]) {
      this.charMap[fontFamily] = [];
    }
    if (!this.charMap[fontFamily][fontSize]) {
      this.charMap[fontFamily][fontSize] = [];
    }
    if (!this.charMap[fontFamily][fontSize][char])
      this.charMap[fontFamily][fontSize][char] = this.measure(fontFamily, fontSize, char);
    return this.charMap[fontFamily][fontSize][char];
  }

  sizeForStr(fontFamily, fontSize, str) {
    var height = 0, width = 0;
    for (let line of str.split('\n')) {
      let lineHeight = 0, lineWidth = 0;
      for (let char of line.split('')) {
        let { height: charHeight, width: charWidth } = this.sizeFor(fontFamily, fontSize, char);
        if (charHeight > lineHeight) lineHeight = charHeight;
        lineWidth += charWidth;
      }
      if (lineWidth > width) width = lineWidth;
      height += lineHeight || this.sizeFor(fontFamily, fontSize, " ").height;
    }
    return { height: height, width: width };
  }

  asciiSizes(fontFamily, fontSize) {
    var result = {};
    for (var i = 32; i <= 126; i++) {
      var char = String.fromCharCode(i);
      result[char] = this.sizeFor(fontFamily, fontSize, char)
    }
    return result;
  }
}
<|endoftext|>


<commit_before>/*jshint esversion: 6 */
const nThen = require("nthen");
const getFolderSize = require("get-folder-size");
const Util = require("../common-util");
const Ulimit = require("ulimit");

var Fs = require("fs");

var Admin = module.exports;

var getFileDescriptorCount = function (Env, server, cb) {
    Fs.readdir('/proc/self/fd', function(err, list) {
        if (err) { return void cb(err); }
        cb(void 0, list.length);
    });
};

var getFileDescriptorLimit = function (env, server, cb) {
    Ulimit(cb);
};

var getCacheStats = function (env, server, cb) {
    var metaSize = 0;
    var channelSize = 0;
    var metaCount = 0;
    var channelCount = 0;

    try {
        var meta = env.metadata_cache;
        for (var x in meta) {
            if (meta.hasOwnProperty(x)) {
                metaCount++;
                metaSize += JSON.stringify(meta[x]).length;
            }
        }

        var channels = env.channel_cache;
        for (var y in channels) {
            if (channels.hasOwnProperty(y)) {
                channelCount++;
                channelSize += JSON.stringify(channels[y]).length;
            }
        }
    } catch (err) {
        return void cb(err && err.message);
    }

    cb(void 0, {
        metadata: metaCount,
        metaSize: metaSize,
        channel: channelCount,
        channelSize: channelSize,
    });
};

var getActiveSessions = function (Env, Server, cb) {
    var stats = Server.getSessionStats();
    cb(void 0, [
        stats.total,
        stats.unique
    ]);
};

var shutdown = function (Env, Server, cb) {
    if (true) {
        return void cb('E_NOT_IMPLEMENTED');
    }

    // disconnect all users and reject new connections
    Server.shutdown();

    // stop all intervals that may be running
    Object.keys(Env.intervals).forEach(function (name) {
        clearInterval(Env.intervals[name]);
    });

    // set a flag to prevent incoming database writes
    // wait until all pending writes are complete
    // then process.exit(0);
    // and allow system functionality to restart the server
};

var getRegisteredUsers = function (Env, Server, cb) {
    Env.batchRegisteredUsers('', cb, function (done) {
        var dir = Env.paths.pin;
        var folders;
        var users = 0;
        nThen(function (waitFor) {
            Fs.readdir(dir, waitFor(function (err, list) {
                if (err) {
                    waitFor.abort();
                    return void done(err);
                }
                folders = list;
            }));
        }).nThen(function (waitFor) {
            folders.forEach(function (f) {
                var dir = Env.paths.pin + '/' + f;
                Fs.readdir(dir, waitFor(function (err, list) {
                    if (err) { return; }
                    users += list.length;
                }));
            });
        }).nThen(function () {
            done(void 0, users);
        });
    });
};

var getDiskUsage = function (Env, Server, cb) {
    Env.batchDiskUsage('', cb, function (done) {
        var data = {};
        nThen(function (waitFor) {
            getFolderSize('./', waitFor(function(err, info) {
                data.total = info;
            }));
            getFolderSize(Env.paths.pin, waitFor(function(err, info) {
                data.pin = info;
            }));
            getFolderSize(Env.paths.blob, waitFor(function(err, info) {
                data.blob = info;
            }));
            getFolderSize(Env.paths.staging, waitFor(function(err, info) {
                data.blobstage = info;
            }));
            getFolderSize(Env.paths.block, waitFor(function(err, info) {
                data.block = info;
            }));
            getFolderSize(Env.paths.data, waitFor(function(err, info) {
                data.datastore = info;
            }));
        }).nThen(function () {
            done(void 0, data);
        });
    });
};

var getActiveChannelCount = function (Env, Server, cb) {
    cb(void 0, Server.getActiveChannelCount());
};

var flushCache = function (Env, Server,  cb) {
    Env.flushCache();
    cb(void 0, true);
};

// CryptPad_AsyncStore.rpc.send('ADMIN', ['SET_DEFAULT_STORAGE_LIMIT', 1024 * 1024 * 1024 /* 1GB */], console.log)
var setDefaultStorageLimit = function (Env, Server, cb, data) {
    var value = Array.isArray(data) && data[1];
    if (typeof(value) !== 'number' || value <= 0) { return void cb('EINVAL'); }
    var previous = Env.defaultStorageLimit;
    var change = {
        previous: previous,
        current: value,
    };

    Env.defaultStorageLimit = value;
    Env.Log.info('DEFAULT_STORAGE_LIMIT_UPDATE', change);

    cb(void 0, change);
};

var commands = {
    ACTIVE_SESSIONS: getActiveSessions,
    ACTIVE_PADS: getActiveChannelCount,
    REGISTERED_USERS: getRegisteredUsers,
    DISK_USAGE: getDiskUsage,
    FLUSH_CACHE: flushCache,
    SHUTDOWN: shutdown,
    GET_FILE_DESCRIPTOR_COUNT: getFileDescriptorCount,
    GET_FILE_DESCRIPTOR_LIMIT: getFileDescriptorLimit,
    SET_DEFAULT_STORAGE_LIMIT: setDefaultStorageLimit,
    GET_CACHE_STATS: getCacheStats,
};

Admin.command = function (Env, safeKey, data, _cb, Server) {
    var cb = Util.once(Util.mkAsync(_cb));

    var admins = Env.admins;
    //var unsafeKey = Util.unescapeKeyCharacters(safeKey);
    if (admins.indexOf(safeKey) === -1) {
        return void cb("FORBIDDEN");
    }

    var command = commands[data[0]];

    if (typeof(command) === 'function') {
        return void command(Env, Server, cb, data);
    }

    return void cb('UNHANDLED_ADMIN_COMMAND');
};

<commit_msg>return process memory usage in GET CACHE STATS RPC<commit_after>/*jshint esversion: 6 */
const nThen = require("nthen");
const getFolderSize = require("get-folder-size");
const Util = require("../common-util");
const Ulimit = require("ulimit");

var Fs = require("fs");

var Admin = module.exports;

var getFileDescriptorCount = function (Env, server, cb) {
    Fs.readdir('/proc/self/fd', function(err, list) {
        if (err) { return void cb(err); }
        cb(void 0, list.length);
    });
};

var getFileDescriptorLimit = function (env, server, cb) {
    Ulimit(cb);
};

var getCacheStats = function (env, server, cb) {
    var metaSize = 0;
    var channelSize = 0;
    var metaCount = 0;
    var channelCount = 0;

    try {
        var meta = env.metadata_cache;
        for (var x in meta) {
            if (meta.hasOwnProperty(x)) {
                metaCount++;
                metaSize += JSON.stringify(meta[x]).length;
            }
        }

        var channels = env.channel_cache;
        for (var y in channels) {
            if (channels.hasOwnProperty(y)) {
                channelCount++;
                channelSize += JSON.stringify(channels[y]).length;
            }
        }
    } catch (err) {
        return void cb(err && err.message);
    }

    cb(void 0, {
        metadata: metaCount,
        metaSize: metaSize,
        channel: channelCount,
        channelSize: channelSize,
        memoryUsage: process.memoryUsage(),
    });
};

var getActiveSessions = function (Env, Server, cb) {
    var stats = Server.getSessionStats();
    cb(void 0, [
        stats.total,
        stats.unique
    ]);
};

var shutdown = function (Env, Server, cb) {
    if (true) {
        return void cb('E_NOT_IMPLEMENTED');
    }

    // disconnect all users and reject new connections
    Server.shutdown();

    // stop all intervals that may be running
    Object.keys(Env.intervals).forEach(function (name) {
        clearInterval(Env.intervals[name]);
    });

    // set a flag to prevent incoming database writes
    // wait until all pending writes are complete
    // then process.exit(0);
    // and allow system functionality to restart the server
};

var getRegisteredUsers = function (Env, Server, cb) {
    Env.batchRegisteredUsers('', cb, function (done) {
        var dir = Env.paths.pin;
        var folders;
        var users = 0;
        nThen(function (waitFor) {
            Fs.readdir(dir, waitFor(function (err, list) {
                if (err) {
                    waitFor.abort();
                    return void done(err);
                }
                folders = list;
            }));
        }).nThen(function (waitFor) {
            folders.forEach(function (f) {
                var dir = Env.paths.pin + '/' + f;
                Fs.readdir(dir, waitFor(function (err, list) {
                    if (err) { return; }
                    users += list.length;
                }));
            });
        }).nThen(function () {
            done(void 0, users);
        });
    });
};

var getDiskUsage = function (Env, Server, cb) {
    Env.batchDiskUsage('', cb, function (done) {
        var data = {};
        nThen(function (waitFor) {
            getFolderSize('./', waitFor(function(err, info) {
                data.total = info;
            }));
            getFolderSize(Env.paths.pin, waitFor(function(err, info) {
                data.pin = info;
            }));
            getFolderSize(Env.paths.blob, waitFor(function(err, info) {
                data.blob = info;
            }));
            getFolderSize(Env.paths.staging, waitFor(function(err, info) {
                data.blobstage = info;
            }));
            getFolderSize(Env.paths.block, waitFor(function(err, info) {
                data.block = info;
            }));
            getFolderSize(Env.paths.data, waitFor(function(err, info) {
                data.datastore = info;
            }));
        }).nThen(function () {
            done(void 0, data);
        });
    });
};

var getActiveChannelCount = function (Env, Server, cb) {
    cb(void 0, Server.getActiveChannelCount());
};

var flushCache = function (Env, Server,  cb) {
    Env.flushCache();
    cb(void 0, true);
};

// CryptPad_AsyncStore.rpc.send('ADMIN', ['SET_DEFAULT_STORAGE_LIMIT', 1024 * 1024 * 1024 /* 1GB */], console.log)
var setDefaultStorageLimit = function (Env, Server, cb, data) {
    var value = Array.isArray(data) && data[1];
    if (typeof(value) !== 'number' || value <= 0) { return void cb('EINVAL'); }
    var previous = Env.defaultStorageLimit;
    var change = {
        previous: previous,
        current: value,
    };

    Env.defaultStorageLimit = value;
    Env.Log.info('DEFAULT_STORAGE_LIMIT_UPDATE', change);

    cb(void 0, change);
};

var commands = {
    ACTIVE_SESSIONS: getActiveSessions,
    ACTIVE_PADS: getActiveChannelCount,
    REGISTERED_USERS: getRegisteredUsers,
    DISK_USAGE: getDiskUsage,
    FLUSH_CACHE: flushCache,
    SHUTDOWN: shutdown,
    GET_FILE_DESCRIPTOR_COUNT: getFileDescriptorCount,
    GET_FILE_DESCRIPTOR_LIMIT: getFileDescriptorLimit,
    SET_DEFAULT_STORAGE_LIMIT: setDefaultStorageLimit,
    GET_CACHE_STATS: getCacheStats,
};

Admin.command = function (Env, safeKey, data, _cb, Server) {
    var cb = Util.once(Util.mkAsync(_cb));

    var admins = Env.admins;
    //var unsafeKey = Util.unescapeKeyCharacters(safeKey);
    if (admins.indexOf(safeKey) === -1) {
        return void cb("FORBIDDEN");
    }

    var command = commands[data[0]];

    if (typeof(command) === 'function') {
        return void command(Env, Server, cb, data);
    }

    return void cb('UNHANDLED_ADMIN_COMMAND');
};

<|endoftext|>


<commit_before>let iniciofecha = moment().subtract(0, 'month').startOf('month')
let finfecha = moment().subtract(0, 'month').endOf('month')

$(document).ready(function () {
    $('#export').click(function () {
        $('#tablaReporteEgresos').tableExport({
        type:'excel',
        fileName: 'Reporte Egresos',
        numbers: {output : false}
        })
      });
    $(".tiponumerico").inputmask({
        alias: "decimal",
        digits: 2,
        groupSeparator: ',',
        autoGroup: true,
        autoUnmask: true
    });

    let start = moment().subtract(1, 'month').startOf('month')
    let end = moment().subtract(1, 'month').endOf('month')

    $(function () {
        moment.locale('es');

        function cb(start, end) {
            $('#fechapersonalizada span').html(start.format('D MMMM, YYYY') + ' - ' + end.format('D MMMM, YYYY'));
            iniciofecha = start
            finfecha = end
        }

        $('#fechapersonalizada').daterangepicker({

            locale: {
                format: 'DD/MM/YYYY',
                applyLabel: 'Aplicar',
                cancelLabel: 'Cancelar',
                customRangeLabel: 'Personalizado',
            },
            startDate: start,
            endDate: end,
            //ranges:jsonrango
            ranges: {
                'Hoy': [moment(), moment()],
                'Ayer': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                'Mes Actual': [moment().subtract(0, 'month').startOf('month'), moment().subtract(0, 'month').endOf('month')],
                "Hace un Mes": [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
                'Hace dos Meses': [moment().subtract(2, 'month').startOf('month'), moment().subtract(2, 'month').endOf('month')],
                'Hace tres Meses': [moment().subtract(3, 'month').startOf('month'), moment().subtract(3, 'month').endOf('month')],
                'Gestion Actual': [moment().subtract(0, 'year').startOf('year'), moment().subtract(0, 'year').endOf('year')],
            }
        }, cb);

        cb(start, end);

    });
    $('#fechapersonalizada').on('apply.daterangepicker', function (ev, picker) {

        retornarReporteEgresos();
    });
    tituloReporte();
    retornarReporteEgresos();
})
$(document).on("change", "#almacen_filtro", function () {

    tituloReporte();
    retornarReporteEgresos();
})
$(document).on("change", "#tipo_filtro", function () {
    tituloReporte();
    retornarReporteEgresos();
})
$(document).on("click", "#refresh", function () {
    retornarReporteEgresos();
})
$(document).on("click", "#pdf", function () {
    let ini = iniciofecha.format('YYYY-MM-DD')
    let fin = finfecha.format('YYYY-MM-DD')
    let alm = $("#almacen_filtro").val() == '' ? '1' : $("#almacen_filtro").val()
    let tin = $("#tipo_filtro").val() == '' ? '1' : $("#tipo_filtro").val()
    let imprimir = base_url("pdf/ReportEgresos/index/") + ini + '/' + fin + '/' + alm + '/' + tin;
    console.log(imprimir);
    window.open(imprimir);
})

function retornarReporteEgresos() {
    tituloReporte();
    let ini = iniciofecha.format('YYYY-MM-DD')
    let fin = finfecha.format('YYYY-MM-DD')
    let alm = $("#almacen_filtro").val()
    let tipoingreso = $("#tipo_filtro").val()
    agregarcargando();
    $.ajax({
        type: "POST",
        url: base_url('index.php/Reportes/mostrarReporteEgresos'),
        dataType: "json",
        data: {
            i: ini,
            f: fin,
            a: alm,
            ti: tipoingreso
        },
    }).done(function (res) {
        for (let index = 0; index < res.length; index++) {
            /*if (res[index].id == null && res[index].tipomov == null && res[index].almacen == null && res[index].cliente == null) {
                res[index].descripcion = `TOTAL GENERAL`
                res[index].punitario = ''
                res[index].almacen = ''
                res[index].cliente = ''
                res[index].fechamov = ''
                res[index].nmov = ''
                res[index].codigo = ''
                res[index].uni = ''
                res[index].mon = ''

            } else if (res[index].id == null && res[index].tipomov == null  && res[index].cliente == null) {
                res[index].descripcion = `TOTAL ALMACEN ${res[index].nombreAlmacen}:`
                res[index].punitario = ''
                res[index].almacen = ''
                res[index].cliente = ''
                res[index].fechamov = ''
                res[index].nmov = ''
                res[index].codigo = ''
                res[index].uni = ''
                res[index].mon = ''

            } else*/
            if (res[index].id == null   && res[index].nmov == null) {
                res[index].descripcion = `TOTAL ${res[index].siglaMov.toUpperCase()}:`
                res[index].punitario = ''
                res[index].almacen = ''
                res[index].cliente = ''
                res[index].fechamov = ''
                res[index].nmov = ''
                res[index].codigo = ''
                res[index].uni = ''
                res[index].mon = ''

            } else if (res[index].id == null) {
                res[index].descripcion = ''
                res[index].punitario = ''
                res[index].almacen = ''
                res[index].cliente = ''
                res[index].fechamov = ''
                res[index].nmov = ''
                res[index].codigo = ''
                res[index].uni = ''
                res[index].mon = ''
            }
        }
        quitarcargando();
        //datosselect = restornardatosSelect(res);
        $("#tablaReporteEgresos").bootstrapTable('destroy');
        $("#tablaReporteEgresos").bootstrapTable({
            data: res,
            striped: true,
            pagination: false,
            pageSize: "100",
            search: true,
            showColumns: true,
            filter: true,
            stickyHeader: true,
            stickyHeaderOffsetY: '50px',
            strictSearch: true,
            //showFooter: true,
            //footerStyle: footerStyle,
            rowStyle:rowStyle,
            columns: [
                {
                    field: 'almacen',
                    title: 'Almacen',
                    sortable: true,
                    searchable: false,
                    visible: (alm == '')? true: false,
                    align: 'center'
                },

                {
                    field: 'cliente',
                    title: tipoingreso == 8 ? 'Destino' : 'Cliente' ,
                    sortable: true,
                    searchable: false,
                    visible: true,
                    /*filter: {
                        type: "select",
                        data: datosselect[0]
                    }*/
                },
                {
                    field: 'fechamov',
                    title: 'Fecha',
                    searchable: false,
                    sortable: true,
                    formatter: formato_fecha_corta_sub
                },

                {
                    field: 'nmov',
                    title: 'N° Mov',
                    sortable: true,
                    align: 'center'
                },
                {
                    field: 'codigo',
                    title: 'Código',
                    sortable: true,
                    searchable: false,
                    /*filter: {
                        type: "select",
                        data: datosselect[1]
                      }*/
                },

                {
                    field: 'descripcion',
                    title: 'Descripción',
                    sortable: true,
                    searchable: false,
                },
                {
                    field: 'uni',
                    title: 'Unidad',
                    sortable: true,
                    searchable: false,
                },
                {
                    field: 'mon',
                    title: 'Moneda',
                    sortable: true,
                    searchable: false,
                },
                {
                    field: 'cantidad',
                    title: 'Cantidad',
                    sortable: true,
                    searchable: false,
                    formatter: operateFormatter3,
                    align: 'right',
                },
                {
                    field: 'punitario',
                    title: 'Precio Unit.',
                    sortable: true,
                    align: 'right',
                    searchable: false,
                    formatter: precioUnitarioFormatter

                },
                {
                    field: 'total',
                    title: 'Total BOB',
                    sortable: true,
                    searchable: false,
                    formatter: operateFormatter3,
                    align: 'right',
                },
                {
                    field: 'totalDolares',
                    title: 'Total $u$',
                    sortable: true,
                    visible: false,
                    searchable: false,
                    formatter: operateFormatter3,
                    align: 'right',
                },

            ]
          });

    }).fail(function (jqxhr, textStatus, error) {
        var err = textStatus + ", " + error;
        console.log("Request Failed: " + err);
    });
}
function rowStyle(row, index) {
    if (row.id==null) {
        return {
            css: {
                //"font-weight": "bold",
                //"border-top": "3px solid white",
                //"border-bottom": "3px solid white",
                "text-align": "right",
                //"padding": "15px",
                "background-color": "#3c8dbc",
                "color": "white",
               // "font-size":"120%",
            }
        };
    }
    return {};
}

function tituloReporte() {
    almText = $('#almacen_filtro').find(":selected").text();
    tipoText = $('#tipo_filtro').find(':selected').text();
    $('#tituloAlmacen').text(almText);
    $('#tituloTipo').text(tipoText);
    $('#ragoFecha').text("DEL " + iniciofecha.format('DD/MM/YYYY') + "  AL  " + finfecha.format('DD/MM/YYYY'));

}

function precioUnitarioFormatter(value, row, index) {
    if (row.punitario == '') {
        ret = ''
    } else {
        num = Math.round(value * 100) / 100
    num = num.toFixed(2);
    ret = (formatNumber.new(num));
    }
    return ret

}
function operateFormatter3(value, row, index) {
    num = Math.round(value * 100) / 100
    num = num.toFixed(2);
    return (formatNumber.new(num));
}

<commit_msg>error fechas reporte egresos<commit_after>let iniciofecha = moment().subtract(1, 'month').startOf('month')
let finfecha = moment().subtract(1, 'month').endOf('month')

$(document).ready(function () {
    $('#export').click(function () {
        $('#tablaReporteEgresos').tableExport({
        type:'excel',
        fileName: 'Reporte Egresos',
        numbers: {output : false}
        })
      });
    $(".tiponumerico").inputmask({
        alias: "decimal",
        digits: 2,
        groupSeparator: ',',
        autoGroup: true,
        autoUnmask: true
    });

    let start = iniciofecha
    let end = finfecha

    $(function () {
        moment.locale('es');

        function cb(start, end) {
            $('#fechapersonalizada span').html(start.format('D MMMM, YYYY') + ' - ' + end.format('D MMMM, YYYY'));
            iniciofecha = start
            finfecha = end
        }

        $('#fechapersonalizada').daterangepicker({

            locale: {
                format: 'DD/MM/YYYY',
                applyLabel: 'Aplicar',
                cancelLabel: 'Cancelar',
                customRangeLabel: 'Personalizado',
            },
            startDate: start,
            endDate: end,
            //ranges:jsonrango
            ranges: {
                'Hoy': [moment(), moment()],
                'Ayer': [moment().subtract(1, 'days'), moment().subtract(1, 'days')],
                'Mes Actual': [moment().subtract(0, 'month').startOf('month'), moment().subtract(0, 'month').endOf('month')],
                "Hace un Mes": [moment().subtract(1, 'month').startOf('month'), moment().subtract(1, 'month').endOf('month')],
                'Hace dos Meses': [moment().subtract(2, 'month').startOf('month'), moment().subtract(2, 'month').endOf('month')],
                'Hace tres Meses': [moment().subtract(3, 'month').startOf('month'), moment().subtract(3, 'month').endOf('month')],
                'Gestion Actual': [moment().subtract(0, 'year').startOf('year'), moment().subtract(0, 'year').endOf('year')],
            }
        }, cb);

        cb(start, end);

    });
    $('#fechapersonalizada').on('apply.daterangepicker', function (ev, picker) {

        retornarReporteEgresos();
    });
    tituloReporte();
    retornarReporteEgresos();
})
$(document).on("change", "#almacen_filtro", function () {

    tituloReporte();
    retornarReporteEgresos();
})
$(document).on("change", "#tipo_filtro", function () {
    tituloReporte();
    retornarReporteEgresos();
})
$(document).on("click", "#refresh", function () {
    retornarReporteEgresos();
})
$(document).on("click", "#pdf", function () {
    let ini = iniciofecha.format('YYYY-MM-DD')
    let fin = finfecha.format('YYYY-MM-DD')
    let alm = $("#almacen_filtro").val() == '' ? '1' : $("#almacen_filtro").val()
    let tin = $("#tipo_filtro").val() == '' ? '1' : $("#tipo_filtro").val()
    let imprimir = base_url("pdf/ReportEgresos/index/") + ini + '/' + fin + '/' + alm + '/' + tin;
    console.log(imprimir);
    window.open(imprimir);
})

function retornarReporteEgresos() {
    tituloReporte();
    let ini = iniciofecha.format('YYYY-MM-DD')
    let fin = finfecha.format('YYYY-MM-DD')
    let alm = $("#almacen_filtro").val()
    let tipoingreso = $("#tipo_filtro").val()
    agregarcargando();
    $.ajax({
        type: "POST",
        url: base_url('index.php/Reportes/mostrarReporteEgresos'),
        dataType: "json",
        data: {
            i: ini,
            f: fin,
            a: alm,
            ti: tipoingreso
        },
    }).done(function (res) {
        for (let index = 0; index < res.length; index++) {
            /*if (res[index].id == null && res[index].tipomov == null && res[index].almacen == null && res[index].cliente == null) {
                res[index].descripcion = `TOTAL GENERAL`
                res[index].punitario = ''
                res[index].almacen = ''
                res[index].cliente = ''
                res[index].fechamov = ''
                res[index].nmov = ''
                res[index].codigo = ''
                res[index].uni = ''
                res[index].mon = ''

            } else if (res[index].id == null && res[index].tipomov == null  && res[index].cliente == null) {
                res[index].descripcion = `TOTAL ALMACEN ${res[index].nombreAlmacen}:`
                res[index].punitario = ''
                res[index].almacen = ''
                res[index].cliente = ''
                res[index].fechamov = ''
                res[index].nmov = ''
                res[index].codigo = ''
                res[index].uni = ''
                res[index].mon = ''

            } else*/
            if (res[index].id == null   && res[index].nmov == null) {
                res[index].descripcion = `TOTAL ${res[index].siglaMov.toUpperCase()}:`
                res[index].punitario = ''
                res[index].almacen = ''
                res[index].cliente = ''
                res[index].fechamov = ''
                res[index].nmov = ''
                res[index].codigo = ''
                res[index].uni = ''
                res[index].mon = ''

            } else if (res[index].id == null) {
                res[index].descripcion = ''
                res[index].punitario = ''
                res[index].almacen = ''
                res[index].cliente = ''
                res[index].fechamov = ''
                res[index].nmov = ''
                res[index].codigo = ''
                res[index].uni = ''
                res[index].mon = ''
            }
        }
        quitarcargando();
        //datosselect = restornardatosSelect(res);
        $("#tablaReporteEgresos").bootstrapTable('destroy');
        $("#tablaReporteEgresos").bootstrapTable({
            data: res,
            striped: true,
            pagination: false,
            pageSize: "100",
            search: true,
            showColumns: true,
            filter: true,
            stickyHeader: true,
            stickyHeaderOffsetY: '50px',
            strictSearch: true,
            //showFooter: true,
            //footerStyle: footerStyle,
            rowStyle:rowStyle,
            columns: [
                {
                    field: 'almacen',
                    title: 'Almacen',
                    sortable: true,
                    searchable: false,
                    visible: (alm == '')? true: false,
                    align: 'center'
                },

                {
                    field: 'cliente',
                    title: tipoingreso == 8 ? 'Destino' : 'Cliente' ,
                    sortable: true,
                    searchable: false,
                    visible: true,
                    /*filter: {
                        type: "select",
                        data: datosselect[0]
                    }*/
                },
                {
                    field: 'fechamov',
                    title: 'Fecha',
                    searchable: false,
                    sortable: true,
                    formatter: formato_fecha_corta_sub
                },

                {
                    field: 'nmov',
                    title: 'N° Mov',
                    sortable: true,
                    align: 'center'
                },
                {
                    field: 'codigo',
                    title: 'Código',
                    sortable: true,
                    searchable: false,
                    /*filter: {
                        type: "select",
                        data: datosselect[1]
                      }*/
                },

                {
                    field: 'descripcion',
                    title: 'Descripción',
                    sortable: true,
                    searchable: false,
                },
                {
                    field: 'uni',
                    title: 'Unidad',
                    sortable: true,
                    searchable: false,
                },
                {
                    field: 'mon',
                    title: 'Moneda',
                    sortable: true,
                    searchable: false,
                },
                {
                    field: 'cantidad',
                    title: 'Cantidad',
                    sortable: true,
                    searchable: false,
                    formatter: operateFormatter3,
                    align: 'right',
                },
                {
                    field: 'punitario',
                    title: 'Precio Unit.',
                    sortable: true,
                    align: 'right',
                    searchable: false,
                    formatter: precioUnitarioFormatter

                },
                {
                    field: 'total',
                    title: 'Total BOB',
                    sortable: true,
                    searchable: false,
                    formatter: operateFormatter3,
                    align: 'right',
                },
                {
                    field: 'totalDolares',
                    title: 'Total $u$',
                    sortable: true,
                    visible: false,
                    searchable: false,
                    formatter: operateFormatter3,
                    align: 'right',
                },

            ]
          });

    }).fail(function (jqxhr, textStatus, error) {
        var err = textStatus + ", " + error;
        console.log("Request Failed: " + err);
    });
}
function rowStyle(row, index) {
    if (row.id==null) {
        return {
            css: {
                //"font-weight": "bold",
                //"border-top": "3px solid white",
                //"border-bottom": "3px solid white",
                "text-align": "right",
                //"padding": "15px",
                "background-color": "#3c8dbc",
                "color": "white",
               // "font-size":"120%",
            }
        };
    }
    return {};
}

function tituloReporte() {
    almText = $('#almacen_filtro').find(":selected").text();
    tipoText = $('#tipo_filtro').find(':selected').text();
    $('#tituloAlmacen').text(almText);
    $('#tituloTipo').text(tipoText);
    $('#ragoFecha').text("DEL " + iniciofecha.format('DD/MM/YYYY') + "  AL  " + finfecha.format('DD/MM/YYYY'));

}

function precioUnitarioFormatter(value, row, index) {
    if (row.punitario == '') {
        ret = ''
    } else {
        num = Math.round(value * 100) / 100
    num = num.toFixed(2);
    ret = (formatNumber.new(num));
    }
    return ret

}
function operateFormatter3(value, row, index) {
    num = Math.round(value * 100) / 100
    num = num.toFixed(2);
    return (formatNumber.new(num));
}

<|endoftext|>


<commit_before>var sprites = {
  stinkies: []
};

var textstyle = {
  fontSize: '16px',
  fill: '#000'
};

var keys = {
  stinky: 'stinky',
  background: 'background',
  buttonGo: 'buttonGo'
};

var stinkiesAvailable = 10;
var mouseBody;
var countShotHitsStinky = 0;
var countShotOnStinky = 0;
var countStinkiesCreated = 0;
var scoreText;
var buttonGo;

var countStinkiesLeft = function() {
  return stinkiesAvailable - countStinkiesCreated;
}

var getRandomInt = function(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min)) + min;
}

var calculateScoreText = function() {
  var result = '📍 ' + countShotOnStinky + '   ';
  result += '💩 ' + countStinkiesLeft() + '   ';
  result += '🚮 ' + countShotHitsStinky;
  return result;
}

var preload = function() {
  game.load.image(keys.background, 'assets/bg.png');
  game.load.spritesheet(keys.buttonGo, 'assets/go.png', 200, 30);
  game.load.spritesheet(keys.stinky, 'assets/stinky.png', 30, 30);
};

var click = function(pointer) {
  var hit = false;
  if (pointer.position.x > 200 || pointer.position.y < game.world.height - 20) {
    countShotOnStinky++;
    var i = sprites.stinkies.length;
    while (i--) {
      var bodies = game.physics.p2.hitTest(pointer.position, [sprites.stinkies[i].body]);
      if (bodies.length) {
        sprites.stinkies[i].shot = true;
        ++countShotHitsStinky;
        hit = true;
      }
    }
  }
  scoreText.text = calculateScoreText();
}

var release = function(pointer) {}

var move = function(pointer, x, y, isDown) {}

var create = function() {

  var createSystem = function() {
    game.physics.startSystem(Phaser.Physics.P2JS);
    game.add.sprite(0, 0, keys.background);
    game.input.onDown.add(click, this);
    game.input.onUp.add(release, this);
    game.input.addMoveCallback(move, this);
    scoreText = game.add.text(16, 16, calculateScoreText(), textstyle);
    game.physics.p2.gravity.y = 100;
  };

  var createStinky = function() {
    var posX = 20;
    var posY = getRandomInt(100, 500);
    var stinky = game.add.sprite(posX, posY, keys.stinky);
    game.physics.p2.enable(stinky, false);
    stinky.body.collideWorldBounds = false;
    stinky.body.velocity.x = getRandomInt(100, 400);
    stinky.body.velocity.y = getRandomInt(0, -300);
    stinky.animations.add('infinite', [0, 1, 2, 1], 10, true);
    stinky.animations.add('die', [3, 4, 5, 6, 7, 8, 9], 10, true);
    sprites.stinkies.push(stinky);
  };

  var createGoButton = function(actionOnClick) {
    var posX = 0;
    var posY = game.world.height - 20;
    var actionOnClickWrap = function() {
      ++countStinkiesCreated;
      actionOnClick();
      scoreText.text = calculateScoreText();
    }
    buttonGo = game.add.button(posX, posY, keys.buttonGo, actionOnClickWrap, this, 2, 1, 0);
    game.physics.p2.enable(buttonGo, false);
  };

  createSystem();
  createGoButton(createStinky);
};

var calculateTotalFinalPoints = function() {
  var rateHit = countShotHitsStinky / stinkiesAvailable * 65;
  var rateShotsNeeded = (countShotOnStinky ? countShotHitsStinky / countShotOnStinky : 0) * 35;
  return rateHit + rateShotsNeeded;
};

var createResultText = function() {
  var result = 'No stinky left! \r\n';
  result += 'You shoot ' + countShotOnStinky + ' times on Stinkies!\r\n';
  result += 'You hit ' + countShotHitsStinky + ' of ' + stinkiesAvailable + ' Stinkies!\r\n';
  result += '-----------------------------------------------\r\n';
  result += 'TOTAL: ' + Math.floor(calculateTotalFinalPoints()) + ' %';
  return result;
};

var animationSpeed = 5;

var update = function() {
  var i = sprites.stinkies.length;
  if (countStinkiesLeft() <= -1) {
    game.physics.p2.destroy(buttonGo);
    delete buttonGo;
    game.add.sprite(0, 0, keys.background);
    game.add.text(16, 16, calculateScoreText(), textstyle).text = createResultText();
  } else {
    while (i--) {
      var stinky = sprites.stinkies[i];
      if (stinky.shot) {
        stinky.stinkiesDieSteps = stinky.stinkiesDieSteps || 0;
        if (stinky.stinkiesDieSteps < 6 * animationSpeed) {
          if (stinky.stinkiesDieSteps % animationSpeed == 0) {
            stinky.animations.play('die');
          }
          stinky.stinkiesDieSteps++;
        } else {
          stinky.kill();
          sprites.stinkies.splice(i, 1);
        }
      } else {
        stinky.animations.play('infinite');
      }
    }
  }
};

var game = new Phaser.Game(800, 600, Phaser.AUTO, '', {
  preload: preload,
  create: create,
  update: update
});<commit_msg>remove input onDown when finished<commit_after>var sprites = {
  stinkies: []
};

var textstyle = {
  fontSize: '16px',
  fill: '#000'
};

var keys = {
  stinky: 'stinky',
  background: 'background',
  buttonGo: 'buttonGo'
};

var stinkiesAvailable = 10;
var mouseBody;
var countShotHitsStinky = 0;
var countShotOnStinky = 0;
var countStinkiesCreated = 0;
var scoreText;
var buttonGo;

var countStinkiesLeft = function() {
  return stinkiesAvailable - countStinkiesCreated;
}

var getRandomInt = function(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min)) + min;
}

var calculateScoreText = function() {
  var result = '📍 ' + countShotOnStinky + '   ';
  result += '💩 ' + countStinkiesLeft() + '   ';
  result += '🚮 ' + countShotHitsStinky;
  return result;
}

var preload = function() {
  game.load.image(keys.background, 'assets/bg.png');
  game.load.spritesheet(keys.buttonGo, 'assets/go.png', 200, 30);
  game.load.spritesheet(keys.stinky, 'assets/stinky.png', 30, 30);
};

var click = function(pointer) {
  var hit = false;
  if (pointer.position.x > 200 || pointer.position.y < game.world.height - 20) {
    countShotOnStinky++;
    var i = sprites.stinkies.length;
    while (i--) {
      var bodies = game.physics.p2.hitTest(pointer.position, [sprites.stinkies[i].body]);
      if (bodies.length) {
        sprites.stinkies[i].shot = true;
        ++countShotHitsStinky;
        hit = true;
      }
    }
  }
  scoreText.text = calculateScoreText();
}

var create = function() {

  var createSystem = function() {
    game.physics.startSystem(Phaser.Physics.P2JS);
    game.add.sprite(0, 0, keys.background);
    game.input.onDown.add(click, this);
    scoreText = game.add.text(16, 16, calculateScoreText(), textstyle);
    game.physics.p2.gravity.y = 100;
  };

  var createStinky = function() {
    var posX = 20;
    var posY = getRandomInt(100, 500);
    var stinky = game.add.sprite(posX, posY, keys.stinky);
    game.physics.p2.enable(stinky, false);
    stinky.body.collideWorldBounds = false;
    stinky.body.velocity.x = getRandomInt(100, 400);
    stinky.body.velocity.y = getRandomInt(0, -300);
    stinky.animations.add('infinite', [0, 1, 2, 1], 10, true);
    stinky.animations.add('die', [3, 4, 5, 6, 7, 8, 9], 10, true);
    sprites.stinkies.push(stinky);
  };

  var createGoButton = function(actionOnClick) {
    var posX = 0;
    var posY = game.world.height - 20;
    var actionOnClickWrap = function() {
      ++countStinkiesCreated;
      actionOnClick();
      scoreText.text = calculateScoreText();
    }
    buttonGo = game.add.button(posX, posY, keys.buttonGo, actionOnClickWrap, this, 2, 1, 0);
    game.physics.p2.enable(buttonGo, false);
  };

  createSystem();
  createGoButton(createStinky);
};

var calculateTotalFinalPoints = function() {
  var rateHit = countShotHitsStinky / stinkiesAvailable * 65;
  var rateShotsNeeded = (countShotOnStinky ? countShotHitsStinky / countShotOnStinky : 0) * 35;
  return rateHit + rateShotsNeeded;
};

var createResultText = function() {
  var result = 'No stinky left! \r\n';
  result += 'You shoot ' + countShotOnStinky + ' times on Stinkies!\r\n';
  result += 'You hit ' + countShotHitsStinky + ' of ' + stinkiesAvailable + ' Stinkies!\r\n';
  result += '-----------------------------------------------\r\n';
  result += 'TOTAL: ' + Math.floor(calculateTotalFinalPoints()) + ' %';
  return result;
};

var animationSpeed = 5;

var update = function() {
  var i = sprites.stinkies.length;
  if (countStinkiesLeft() <= -1) {
    game.physics.p2.destroy(buttonGo);
    delete buttonGo;
    game.add.sprite(0, 0, keys.background);
    game.add.text(16, 16, calculateScoreText(), textstyle).text = createResultText();
    game.input.onDown.removeAll();
  } else {
    while (i--) {
      var stinky = sprites.stinkies[i];
      if (stinky.shot) {
        stinky.stinkiesDieSteps = stinky.stinkiesDieSteps || 0;
        if (stinky.stinkiesDieSteps < 6 * animationSpeed) {
          if (stinky.stinkiesDieSteps % animationSpeed == 0) {
            stinky.animations.play('die');
          }
          stinky.stinkiesDieSteps++;
        } else {
          stinky.kill();
          sprites.stinkies.splice(i, 1);
        }
      } else {
        stinky.animations.play('infinite');
      }
    }
  }
};

var game = new Phaser.Game(800, 600, Phaser.AUTO, '', {
  preload: preload,
  create: create,
  update: update
});
<|endoftext|>


<commit_before>var should = require("should");
var sinon = require("sinon");
var WebWorkerMainTemplatePlugin = require("../lib/webworker/WebWorkerMainTemplatePlugin");
var applyPluginWithOptions = require("./helpers/applyPluginWithOptions");

describe("WebWorkerMainTemplatePlugin", function() {
	var env;

	beforeEach(function() {
		env = {};
	});

	it("has apply function", function() {
		(new WebWorkerMainTemplatePlugin()).apply.should.be.a.Function();
	});

	describe("when applied", function() {
		beforeEach(function() {
			env.eventBindings = applyPluginWithOptions(WebWorkerMainTemplatePlugin);
			env.handlerContext = {
				requireFn: 'requireFn',
				indent: (value) => typeof value === 'string' ? value : value.join("\n"),
				asString: (values) => values.join("\n"),
				renderCurrentHashCode: (value) => value,
				outputOptions: {
					chunkFilename: 'chunkFilename'
				},
				applyPluginsWaterfall: (moduleName, fileName, data) => {
					return '"' + moduleName + data.hash + data.hashWithLength() + (data.chunk && data.chunk.id || '') + '"';
				},
				renderAddModule: () => 'renderAddModuleSource();',
			};
		});

		it("binds five event handlers", function() {
			env.eventBindings.length.should.be.exactly(5);
		});

		describe("local-vars handler", function() {
			beforeEach(function() {
				env.eventBinding = env.eventBindings[0];
			});

			it("binds to local-vars event", function() {
				env.eventBinding.name.should.be.exactly("local-vars");
			});

			describe("when no chunks are provided", function() {
				beforeEach(function() {
					var chunk = {
						ids: [],
						chunks: []
					};
					env.source = env.eventBinding.handler.call(env.handlerContext, "moduleSource()", chunk);
				});

				it("returns the original source", function() {
					env.source.should.be.exactly("moduleSource()")
				});
			});

			describe("when chunks are provided", function() {
				beforeEach(function() {
					var chunk = {
						ids: [1, 2, 3],
						chunks: [
							'foo',
							'bar',
							'baz'
						]
					};
					env.source = env.eventBinding.handler.call(env.handlerContext, "moduleSource()", chunk, 'abc123');
				});

				it("returns the original source with installed mapping", function() {
					env.source.should.be.exactly(`
moduleSource()

// object to store loaded chunks
// "1" means "already loaded"
var installedChunks = {
1: 1,
2: 1,
3: 1
};
`.trim())
				});
			});
		});

		describe("require-ensure handler", function() {
			beforeEach(function() {
				env.eventBinding = env.eventBindings[1];
			});

			it("binds to require-ensure event", function() {
				env.eventBinding.name.should.be.exactly("require-ensure");
			});

			describe("when called", function() {
				beforeEach(function() {
					var chunk = {};
					env.source = env.eventBinding.handler.call(env.handlerContext, "moduleSource()", chunk, 'abc123');
				});

				it("creates import scripts call and promise resolve", function() {
					env.source.should.be.exactly(`
// "1" is the signal for "already loaded"
if(!installedChunks[chunkId]) {
importScripts("asset-path" + abc123 + "" + abc123 + "" + chunkId + "");
}
return Promise.resolve();
`.trim())
				});
			});
		});

		describe("bootstrap handler", function() {
			beforeEach(function() {
				env.eventBinding = env.eventBindings[2];
			});

			it("binds to bootstrap event", function() {
				env.eventBinding.name.should.be.exactly("bootstrap");
			});

			describe("when no chunks are provided", function() {
				beforeEach(function() {
					var chunk = {
						ids: [],
						chunks: []
					};
					env.source = env.eventBinding.handler.call(env.handlerContext, "moduleSource()", chunk);
				});

				it("returns the original source", function() {
					env.source.should.be.exactly("moduleSource()")
				});
			});

			describe("when chunks are provided", function() {
				beforeEach(function() {
					var chunk = {
						ids: [1, 2, 3],
						chunks: [
							'foo',
							'bar',
							'baz'
						]
					};
					env.source = env.eventBinding.handler.call(env.handlerContext, "moduleSource()", chunk);
				});

				it("returns the original source with chunk callback", function() {
					env.source.should.be.exactly(`
moduleSource()
this["webpackChunk"] = function webpackChunkCallback(chunkIds, moreModules) {
for(var moduleId in moreModules) {
renderAddModuleSource();
}
while(chunkIds.length)
installedChunks[chunkIds.pop()] = 1;
};
`.trim())
				});
			});
		});

		describe("hot-bootstrap handler", function() {
			beforeEach(function() {
				env.eventBinding = env.eventBindings[3];
			});

			it("binds to hot-bootstrap event", function() {
				env.eventBinding.name.should.be.exactly("hot-bootstrap");
			});

			describe("when called", function() {
				beforeEach(function() {
					var chunk = {};
					env.source = env.eventBinding.handler.call(env.handlerContext, "moduleSource()", chunk, 'abc123');
				});

				it("returns the original source with hot update callback", function() {
					env.source.should.be.exactly(`
moduleSource()
var parentHotUpdateCallback = this["webpackHotUpdate"];
this["webpackHotUpdate"] = function webpackHotUpdateCallback(chunkId, moreModules) { // eslint-disable-line no-unused-vars
	hotAddUpdateChunk(chunkId, moreModules);
	if(parentHotUpdateCallback) parentHotUpdateCallback(chunkId, moreModules);
} ;

function hotDownloadUpdateChunk(chunkId) { // eslint-disable-line no-unused-vars
	importScripts(requireFn.p + "asset-path" + abc123 + "" + abc123 + "" + chunkId + "");
}

function hotDownloadManifest(callback) { // eslint-disable-line no-unused-vars
	return new Promise(function(resolve, reject) {
		if(typeof XMLHttpRequest === "undefined")
			return reject(new Error("No browser support"));
		try {
			var request = new XMLHttpRequest();
			var requestPath = requireFn.p + "asset-path" + abc123 + "" + abc123 + "";
			request.open("GET", requestPath, true);
			request.timeout = 10000;
			request.send(null);
		} catch(err) {
			return reject(err);
		}
		request.onreadystatechange = function() {
			if(request.readyState !== 4) return;
			if(request.status === 0) {
				// timeout
				reject(new Error("Manifest request to " + requestPath + " timed out."));
			} else if(request.status === 404) {
				// no update available
				resolve();
			} else if(request.status !== 200 && request.status !== 304) {
				// other failure
				reject(new Error("Manifest request to " + requestPath + " failed."));
			} else {
				// success
				try {
					var update = JSON.parse(request.responseText);
				} catch(e) {
					reject(e);
					return;
				}
				resolve(update);
			}
		};
	});
}

function hotDisposeChunk(chunkId) { //eslint-disable-line no-unused-vars
	delete installedChunks[chunkId];
}
`.trim())
				});
			});
		});

		describe("hash handler", function() {
			beforeEach(function() {
				env.eventBinding = env.eventBindings[4];
				env.handlerContext = {
					outputOptions: {
						publicPath: "Alpha",
						filename: "Bravo",
						chunkFilename: "Charlie",
						chunkCallbackName: "Delta",
						library: "Echo"
					}
				};
				env.hashMock = {
					update: sinon.spy()
				};
				env.eventBinding.handler.call(env.handlerContext, env.hashMock);
			});

			it("binds to hash event", function() {
				env.eventBinding.name.should.be.exactly("hash");
			});

			it("updates hash object", function() {
				env.hashMock.update.callCount.should.be.exactly(7);
				sinon.assert.calledWith(env.hashMock.update, "webworker");
				sinon.assert.calledWith(env.hashMock.update, "3");
				sinon.assert.calledWith(env.hashMock.update, "Alpha");
				sinon.assert.calledWith(env.hashMock.update, "Bravo");
				sinon.assert.calledWith(env.hashMock.update, "Charlie");
				sinon.assert.calledWith(env.hashMock.update, "Delta");
				sinon.assert.calledWith(env.hashMock.update, "Echo");
			});
		});
	});
});
<commit_msg>refactoring to ES6<commit_after>"use strict";

const should = require("should");
const sinon = require("sinon");
const WebWorkerMainTemplatePlugin = require("../lib/webworker/WebWorkerMainTemplatePlugin");
const applyPluginWithOptions = require("./helpers/applyPluginWithOptions");

describe("WebWorkerMainTemplatePlugin", function() {
	let env;

	beforeEach(() => {
		env = {}
	});

	it("has apply function", function() {
		(new WebWorkerMainTemplatePlugin()).apply.should.be.a.Function();
	});

	describe("when applied", function() {
		beforeEach(function() {
			env.eventBindings = applyPluginWithOptions(WebWorkerMainTemplatePlugin);
			env.handlerContext = {
				requireFn: 'requireFn',
				indent: (value) => typeof value === 'string' ? value : value.join("\n"),
				asString: (values) => values.join("\n"),
				renderCurrentHashCode: (value) => value,
				outputOptions: {
					chunkFilename: 'chunkFilename'
				},
				applyPluginsWaterfall: (moduleName, fileName, data) => {
					return `"${moduleName}${data.hash}${data.hashWithLength()}${data.chunk && data.chunk.id || ''}"`;
				},
				renderAddModule: () => 'renderAddModuleSource();',
			};
		});

		it("binds five event handlers", function() {
			env.eventBindings.length.should.be.exactly(5);
		});

		describe("local-vars handler", function() {
			beforeEach(() => {
				env.eventBinding = env.eventBindings[0];
			});

			it("binds to local-vars event", () => {
				env.eventBinding.name.should.be.exactly("local-vars");
			});

			describe("when no chunks are provided", () => {
				beforeEach(() => {
					const chunk = {
						ids: [],
						chunks: []
					};
					env.source = env.eventBinding.handler.call(env.handlerContext, "moduleSource()", chunk);
				});

				it("returns the original source", () => {
					env.source.should.be.exactly("moduleSource()")
				});
			});

			describe("when chunks are provided", () => {
				beforeEach(() => {
					const chunk = {
						ids: [1, 2, 3],
						chunks: [
							'foo',
							'bar',
							'baz'
						]
					};
					env.source = env.eventBinding.handler.call(env.handlerContext, "moduleSource()", chunk, 'abc123');
				});

				it("returns the original source with installed mapping", () => {
					env.source.should.be.exactly(`
moduleSource()

// object to store loaded chunks
// "1" means "already loaded"
var installedChunks = {
1: 1,
2: 1,
3: 1
};
`.trim())
				});
			});
		});

		describe("require-ensure handler", () => {
			beforeEach(() => {
				env.eventBinding = env.eventBindings[1];
			});

			it("binds to require-ensure event", () => {
				env.eventBinding.name.should.be.exactly("require-ensure");
			});

			describe("when called", () => {
				beforeEach(() => {
					const chunk = {};
					env.source = env.eventBinding.handler.call(env.handlerContext, "moduleSource()", chunk, 'abc123');
				});

				it("creates import scripts call and promise resolve", () => {
					env.source.should.be.exactly(`
// "1" is the signal for "already loaded"
if(!installedChunks[chunkId]) {
importScripts("asset-path" + abc123 + "" + abc123 + "" + chunkId + "");
}
return Promise.resolve();
`.trim())
				});
			});
		});

		describe("bootstrap handler", () => {
			beforeEach(() => {
				env.eventBinding = env.eventBindings[2];
			});

			it("binds to bootstrap event", () => {
				env.eventBinding.name.should.be.exactly("bootstrap");
			});

			describe("when no chunks are provided", () => {
				beforeEach(() => {
					const chunk = {
						ids: [],
						chunks: []
					};
					env.source = env.eventBinding.handler.call(env.handlerContext, "moduleSource()", chunk);
				});

				it("returns the original source", () => {
					env.source.should.be.exactly("moduleSource()")
				});
			});

			describe("when chunks are provided", () => {
				beforeEach(() => {
					const chunk = {
						ids: [1, 2, 3],
						chunks: [
							'foo',
							'bar',
							'baz'
						]
					};
					env.source = env.eventBinding.handler.call(env.handlerContext, "moduleSource()", chunk);
				});

				it("returns the original source with chunk callback", () => {
					env.source.should.be.exactly(`
moduleSource()
this["webpackChunk"] = function webpackChunkCallback(chunkIds, moreModules) {
for(var moduleId in moreModules) {
renderAddModuleSource();
}
while(chunkIds.length)
installedChunks[chunkIds.pop()] = 1;
};
`.trim())
				});
			});
		});

		describe("hot-bootstrap handler", () => {
			beforeEach(() => {
				env.eventBinding = env.eventBindings[3];
			});

			it("binds to hot-bootstrap event", () => {
				env.eventBinding.name.should.be.exactly("hot-bootstrap");
			});

			describe("when called", () => {
				beforeEach(() => {
					const chunk = {};
					env.source = env.eventBinding.handler.call(env.handlerContext, "moduleSource()", chunk, 'abc123');
				});

				it("returns the original source with hot update callback", () => {
					env.source.should.be.exactly(`
moduleSource()
var parentHotUpdateCallback = this["webpackHotUpdate"];
this["webpackHotUpdate"] = function webpackHotUpdateCallback(chunkId, moreModules) { // eslint-disable-line no-unused-vars
	hotAddUpdateChunk(chunkId, moreModules);
	if(parentHotUpdateCallback) parentHotUpdateCallback(chunkId, moreModules);
} ;

function hotDownloadUpdateChunk(chunkId) { // eslint-disable-line no-unused-vars
	importScripts(requireFn.p + "asset-path" + abc123 + "" + abc123 + "" + chunkId + "");
}

function hotDownloadManifest(callback) { // eslint-disable-line no-unused-vars
	return new Promise(function(resolve, reject) {
		if(typeof XMLHttpRequest === "undefined")
			return reject(new Error("No browser support"));
		try {
			var request = new XMLHttpRequest();
			var requestPath = requireFn.p + "asset-path" + abc123 + "" + abc123 + "";
			request.open("GET", requestPath, true);
			request.timeout = 10000;
			request.send(null);
		} catch(err) {
			return reject(err);
		}
		request.onreadystatechange = function() {
			if(request.readyState !== 4) return;
			if(request.status === 0) {
				// timeout
				reject(new Error("Manifest request to " + requestPath + " timed out."));
			} else if(request.status === 404) {
				// no update available
				resolve();
			} else if(request.status !== 200 && request.status !== 304) {
				// other failure
				reject(new Error("Manifest request to " + requestPath + " failed."));
			} else {
				// success
				try {
					var update = JSON.parse(request.responseText);
				} catch(e) {
					reject(e);
					return;
				}
				resolve(update);
			}
		};
	});
}

function hotDisposeChunk(chunkId) { //eslint-disable-line no-unused-vars
	delete installedChunks[chunkId];
}
`.trim())
				});
			});
		});

		describe("hash handler", () => {
			beforeEach(() => {
				env.eventBinding = env.eventBindings[4];
				env.handlerContext = {
					outputOptions: {
						publicPath: "Alpha",
						filename: "Bravo",
						chunkFilename: "Charlie",
						chunkCallbackName: "Delta",
						library: "Echo"
					}
				};
				env.hashMock = {
					update: sinon.spy()
				};
				env.eventBinding.handler.call(env.handlerContext, env.hashMock);
			});

			it("binds to hash event", () => {
				env.eventBinding.name.should.be.exactly("hash");
			});

			it("updates hash object", () => {
				env.hashMock.update.callCount.should.be.exactly(7);
				sinon.assert.calledWith(env.hashMock.update, "webworker");
				sinon.assert.calledWith(env.hashMock.update, "3");
				sinon.assert.calledWith(env.hashMock.update, "Alpha");
				sinon.assert.calledWith(env.hashMock.update, "Bravo");
				sinon.assert.calledWith(env.hashMock.update, "Charlie");
				sinon.assert.calledWith(env.hashMock.update, "Delta");
				sinon.assert.calledWith(env.hashMock.update, "Echo");
			});
		});
	});
});
<|endoftext|>


<commit_before>( function ( $, OO ) {

	var ifundef = function ( val, then ) {
		if ( val !== undefined && val !== null ) {
			return val;
		} else {
			return then;
		}
	};

	OO.ui.instantiateFromParameters = function ( config, fieldMap ) {
		var className = config[ 'class' ],
			error, widget;
		fieldMap = fieldMap || {};

		if ( typeof OO.ui[className] === 'undefined' ) {
			throw 'Unable to load OO.ui.' + className;
		}

		error = OO.ui.preprocessConfig( config, fieldMap );

		// Pass out errors
		if ( error ) {
			return error;
		}

		if ( className === 'FieldLayout' ) {
			widget = config.fieldWidget;

			delete config.fieldWidget;
			widget = new OO.ui.FieldLayout( widget, config );
		} else {
			widget = new OO.ui[className]( config );
			if ( config.name !== undefined ) {
				fieldMap[config.name] = widget;
			}
		}
		return widget;
	};

	OO.ui.preprocessConfig = function ( config, fieldMap ) {
		var newItems,
			error = false;
		fieldMap = fieldMap || {};

		if ( config.items ) {
			newItems = [];
			$.each( config.items, function ( index, item ) {
				var newItem = OO.ui.instantiateFromParameters( item, fieldMap );

				if ( newItem.$element ) {
					// A proper OOUI
					newItems.push( newItem );
				} else {
					error = newItem;
				}
			} );

			config.items = newItems;
		}

		if ( config.fieldWidget ) {
			config.fieldWidget = OO.ui.instantiateFromParameters( config.fieldWidget,
			fieldMap );
		}

		$.each( config, function ( name, value ) {
			if ( String( name ).substr( 0, 1 ) === '$' ) {
				config[name] = $( value );
			} else if ( typeof value === 'object' && $.isPlainObject( value ) ) {
				OO.ui.preprocessConfig( value, fieldMap );
			}
		} );

		if ( error ) {
			return error;
		}
	};

	OO.ui.getWidgetValue = function ( widget ) {
		switch ( widget.constructor ){
			case OO.ui.ActionWidget:
			case OO.ui.ButtonGroupWidget:
			case OO.ui.ButtonWidget:
			case OO.ui.DecoratedOptionWidget:
			case OO.ui.DropdownWidget:
			case OO.ui.IconWidget:
			case OO.ui.IndicatorWidget:
			case OO.ui.LabelWidget:
			case OO.ui.MenuOptionWidget:
			case OO.ui.MenuSelectOptionWidget:
			case OO.ui.OutlineControlsWidget:
			case OO.ui.OutlineOptionWidget:
			case OO.ui.OutlineSelectWidget:
			case OO.ui.PopupButtonWidget:
			case OO.ui.PopupWidget:
			case OO.ui.ProgressBarWidget:
			case OO.ui.RadioOptionWidget:
				return widget.getData();
			case OO.ui.ButtonOptionWidget:
			case OO.ui.CheckboxInputWidget:
				return widget.isSelected();
			case OO.ui.RadioSelectWidget:
				if ( widget.getSelectedItem() ) {
					return widget.getSelectedItem().getData();
				} else {
					return null;
				}
				break;
			case OO.ui.ButtonInputWidget:
			case OO.ui.DropdownInputWidget:
			case OO.ui.RadioInputWidget:
				return ifundef( widget.getData(), widget.getValue() );
			case OO.ui.MenuSelectWidget:
			case OO.ui.ButtonSelectWidget:
				if ( widget.getSelectedItem() ) {
					return widget.getSelectedItem().getData();
				} else {
					return null;
				}
				break;
			case OO.ui.ComboboxInputWidget:
				if ( widget.getMenu().getSelectedItem() ) {
					return widget.getMenu().getSelectedItem().getData();
				} else {
					return null;
				}
				break;
			case OO.ui.SearchWidget:
				return widget.getQuery().getValue();
			case OO.ui.TextInputWidget:
			case OO.ui.ToggleButtonWidget:
			case OO.ui.ToggleSwitchWidget:
				return widget.getValue();
			default:
				if(widget.getData){
					return widget.getValue();
				}else{
					return null;
				}
		}
	};

	OO.ui.setWidgetValue = function ( widget, value ) {
		switch ( widget.constructor ){
			case OO.ui.ActionWidget:
			case OO.ui.ButtonGroupWidget:
			case OO.ui.ButtonWidget:
			case OO.ui.DecoratedOptionWidget:
			case OO.ui.DropdownWidget:
			case OO.ui.IconWidget:
			case OO.ui.IndicatorWidget:
			case OO.ui.LabelWidget:
			case OO.ui.MenuOptionWidget:
			case OO.ui.MenuSelectOptionWidget:
			case OO.ui.OutlineControlsWidget:
			case OO.ui.OutlineOptionWidget:
			case OO.ui.OutlineSelectWidget:
			case OO.ui.PopupButtonWidget:
			case OO.ui.PopupWidget:
			case OO.ui.ProgressBarWidget:
			case OO.ui.RadioOptionWidget:
				widget.setData(value);
				break;
			case OO.ui.ButtonOptionWidget:
			case OO.ui.CheckboxInputWidget:
				widget.setSelected(value);
				break;
			case OO.ui.RadioSelectWidget:
				widget.selectItem( widget.getItemFromData(value) );
				break;
			case OO.ui.ButtonInputWidget:
			case OO.ui.DropdownInputWidget:
			case OO.ui.RadioInputWidget:
				widget.setData(value);
				break;
			case OO.ui.MenuSelectWidget:
			case OO.ui.ButtonSelectWidget:
				widget.selectItem( widget.getItemFromData(value) );
				break;
			case OO.ui.ComboboxInputWidget:
				widget.getMenu().selectItem( widget.getMenu().getItemFromData(value) );
				break;
			case OO.ui.SearchWidget:
				widget.getQuery().setValue(value);
				break;
			case OO.ui.TextInputWidget:
			case OO.ui.ToggleButtonWidget:
			case OO.ui.ToggleSwitchWidget:
				widget.setValue(ifundef(value, ""));
				break;
			default:
				if(widget.setValue){
					return widget.getValue(value);
				}else{
					return null;
				}
			}
	};

} )( jQuery, OO );
<commit_msg>Minor fix to setValue() for general oo.ui elements<commit_after>( function ( $, OO ) {

	var ifundef = function ( val, then ) {
		if ( val !== undefined && val !== null ) {
			return val;
		} else {
			return then;
		}
	};

	OO.ui.instantiateFromParameters = function ( config, fieldMap ) {
		var className = config[ 'class' ],
			error, widget;
		fieldMap = fieldMap || {};

		if ( typeof OO.ui[className] === 'undefined' ) {
			throw 'Unable to load OO.ui.' + className;
		}

		error = OO.ui.preprocessConfig( config, fieldMap );

		// Pass out errors
		if ( error ) {
			return error;
		}

		if ( className === 'FieldLayout' ) {
			widget = config.fieldWidget;

			delete config.fieldWidget;
			widget = new OO.ui.FieldLayout( widget, config );
		} else {
			widget = new OO.ui[className]( config );
			if ( config.name !== undefined ) {
				fieldMap[config.name] = widget;
			}
		}
		return widget;
	};

	OO.ui.preprocessConfig = function ( config, fieldMap ) {
		var newItems,
			error = false;
		fieldMap = fieldMap || {};

		if ( config.items ) {
			newItems = [];
			$.each( config.items, function ( index, item ) {
				var newItem = OO.ui.instantiateFromParameters( item, fieldMap );

				if ( newItem.$element ) {
					// A proper OOUI
					newItems.push( newItem );
				} else {
					error = newItem;
				}
			} );

			config.items = newItems;
		}

		if ( config.fieldWidget ) {
			config.fieldWidget = OO.ui.instantiateFromParameters( config.fieldWidget,
			fieldMap );
		}

		$.each( config, function ( name, value ) {
			if ( String( name ).substr( 0, 1 ) === '$' ) {
				config[name] = $( value );
			} else if ( typeof value === 'object' && $.isPlainObject( value ) ) {
				OO.ui.preprocessConfig( value, fieldMap );
			}
		} );

		if ( error ) {
			return error;
		}
	};

	OO.ui.getWidgetValue = function ( widget ) {
		switch ( widget.constructor ){
			case OO.ui.ActionWidget:
			case OO.ui.ButtonGroupWidget:
			case OO.ui.ButtonWidget:
			case OO.ui.DecoratedOptionWidget:
			case OO.ui.DropdownWidget:
			case OO.ui.IconWidget:
			case OO.ui.IndicatorWidget:
			case OO.ui.LabelWidget:
			case OO.ui.MenuOptionWidget:
			case OO.ui.MenuSelectOptionWidget:
			case OO.ui.OutlineControlsWidget:
			case OO.ui.OutlineOptionWidget:
			case OO.ui.OutlineSelectWidget:
			case OO.ui.PopupButtonWidget:
			case OO.ui.PopupWidget:
			case OO.ui.ProgressBarWidget:
			case OO.ui.RadioOptionWidget:
				return widget.getData();
			case OO.ui.ButtonOptionWidget:
			case OO.ui.CheckboxInputWidget:
				return widget.isSelected();
			case OO.ui.RadioSelectWidget:
				if ( widget.getSelectedItem() ) {
					return widget.getSelectedItem().getData();
				} else {
					return null;
				}
				break;
			case OO.ui.ButtonInputWidget:
			case OO.ui.DropdownInputWidget:
			case OO.ui.RadioInputWidget:
				return ifundef( widget.getData(), widget.getValue() );
			case OO.ui.MenuSelectWidget:
			case OO.ui.ButtonSelectWidget:
				if ( widget.getSelectedItem() ) {
					return widget.getSelectedItem().getData();
				} else {
					return null;
				}
				break;
			case OO.ui.ComboboxInputWidget:
				if ( widget.getMenu().getSelectedItem() ) {
					return widget.getMenu().getSelectedItem().getData();
				} else {
					return null;
				}
				break;
			case OO.ui.SearchWidget:
				return widget.getQuery().getValue();
			case OO.ui.TextInputWidget:
			case OO.ui.ToggleButtonWidget:
			case OO.ui.ToggleSwitchWidget:
				return widget.getValue();
			default:
				if(widget.getData){
					return widget.getValue();
				}else{
					return null;
				}
		}
	};

	OO.ui.setWidgetValue = function ( widget, value ) {
		switch ( widget.constructor ){
			case OO.ui.ActionWidget:
			case OO.ui.ButtonGroupWidget:
			case OO.ui.ButtonWidget:
			case OO.ui.DecoratedOptionWidget:
			case OO.ui.DropdownWidget:
			case OO.ui.IconWidget:
			case OO.ui.IndicatorWidget:
			case OO.ui.LabelWidget:
			case OO.ui.MenuOptionWidget:
			case OO.ui.MenuSelectOptionWidget:
			case OO.ui.OutlineControlsWidget:
			case OO.ui.OutlineOptionWidget:
			case OO.ui.OutlineSelectWidget:
			case OO.ui.PopupButtonWidget:
			case OO.ui.PopupWidget:
			case OO.ui.ProgressBarWidget:
			case OO.ui.RadioOptionWidget:
				widget.setData(value);
				break;
			case OO.ui.ButtonOptionWidget:
			case OO.ui.CheckboxInputWidget:
				widget.setSelected(value);
				break;
			case OO.ui.RadioSelectWidget:
				widget.selectItem( widget.getItemFromData(value) );
				break;
			case OO.ui.ButtonInputWidget:
			case OO.ui.DropdownInputWidget:
			case OO.ui.RadioInputWidget:
				widget.setData(value);
				break;
			case OO.ui.MenuSelectWidget:
			case OO.ui.ButtonSelectWidget:
				widget.selectItem( widget.getItemFromData(value) );
				break;
			case OO.ui.ComboboxInputWidget:
				widget.getMenu().selectItem( widget.getMenu().getItemFromData(value) );
				break;
			case OO.ui.SearchWidget:
				widget.getQuery().setValue(value);
				break;
			case OO.ui.TextInputWidget:
			case OO.ui.ToggleButtonWidget:
			case OO.ui.ToggleSwitchWidget:
				widget.setValue(ifundef(value, ""));
				break;
			default:
				if(widget.setValue){
					return widget.setValue(value);
				}else{
					return null;
				}
			}
	};

} )( jQuery, OO );
<|endoftext|>