<commit_before>SB.Examples.TrackerGame = function()
{
	SB.Game.call(this);
}

goog.inherits(SB.Examples.TrackerGame, SB.Game);

SB.Examples.TrackerGame.prototype.initialize = function(param)
{
	param.tabstop = true;

	SB.Game.prototype.initialize.call(this, param);

	this.turnDir = new THREE.Vector3;
	this.moveDir = new THREE.Vector3;
	this.trackerPos = new THREE.Vector3;
	this.trackerOrientation = new THREE.Quaternion;

	this.lastdx = 0;
	this.dragging = false;
	this.animateDrag = true;
	this.dragAnimation = null;
	this.turnSpeed = 1;

	// Scene root
	var root = new SB.Entity;
	this.root = root;

	// Headlight
    var headlight = new SB.DirectionalLight({ color : 0xFFFFFF, intensity : 1});
    root.addComponent(headlight);

    // A timer
	var timer = new SB.Timer( { loop : true } );
	timer.subscribe("time", this, this.onTimeChanged);
	timer.start();
	root.addComponent(timer);

/*    // Camera
	var mainCamera = new SB.Entity;

	var transform = new SB.Transform;
	mainCamera.addComponent(transform);

	var camera = new SB.Camera({fov: 50, active : true, position:new THREE.Vector3(0, 1, 5)} );
	mainCamera.addComponent(camera);

	root.addChild(mainCamera);

	this.mainCamera = mainCamera;
*/
	// Controller
	var controller = SB.Prefabs.FPSController({ active : true, headlight : true });
	controller.transform.position.set(0, 2.5, 3.67);
	root.addChild(controller);

    // Dragger thing
	var dragger = new SB.Dragger();
	root.addComponent(dragger);

	dragger.subscribe("move", this, this.onDraggerMove);
	this.dragger = dragger;

	// Something to drag
	var carousel = new SB.Entity;

	transform = new SB.Transform();
	carousel.addComponent(transform);

//	transform.rotation.y = Math.PI / 8;

	this.carousel = carousel;

	var grid = new SB.Entity;

	var visual = new SB.Grid({size: 14, color:0});
	grid.addComponent(visual);

	carousel.addChild(grid);

    // Something to draw
	var cylinder = new SB.Entity;

	transform = new SB.Transform();
	transform.position.z = -10;
    visual = new SB.CylinderVisual({radiusTop : 1, radiusBottom : 1, height : 1.667, color : 0x0000ff });

    cylinder.addComponent(transform);
    cylinder.addComponent(visual);

	carousel.addChild(cylinder);

	// Something to show tracker
	var panel = new SB.Entity;

	transform = new SB.Transform();
	transform.position.z = 3;
    visual = new SB.Pane({width:.5, height:.25, material : new THREE.MeshLambertMaterial({color:0x00ff00}) });

    panel.addComponent(transform);
    panel.addComponent(visual);

	cylinder.addChild(panel);

	this.panel = panel;

    this.cylinder = cylinder;

	root.addChild(carousel);

	this.addEntity(root);
	root.realize();

    // This tracks cylinder movement relative to carousel
	var controllerScript = controller.getComponent(SB.FPSControllerScript);
	var camera = controllerScript.viewpoint.getComponent(SB.Camera);

	var tracker = new SB.Tracker({reference : camera, referencePosition:new THREE.Vector3(0, 0, -3)});
	cylinder.addComponent(tracker);
	tracker.subscribe("position", this, this.onTrackerPosition);
	tracker.subscribe("orientation", this, this.onTrackerOrientation);
	tracker.start();

	this.root = root;
}

SB.Examples.TrackerGame.prototype.turn = function(dir)
{
	this.carousel.transform.rotation.addSelf(dir);
}

SB.Examples.TrackerGame.prototype.move = function(dir)
{
	this.carousel.transform.position.addSelf(dir);
}

SB.Examples.TrackerGame.prototype.onMouseDown = function(x, y)
{
	this.dragger.start(x, y);
	this.dragging = true;

	SB.Game.prototype.onMouseDown.call(this, x, y);
}

SB.Examples.TrackerGame.prototype.onMouseUp = function(x, y)
{
	this.dragger.stop(x, y);
	this.dragging = false;
	/*
	if (this.panel.transform.position.z > 3)
	{
		this.panel.transform.position.set(0, 0, 3);
		this.panel.transform.rotation.y = 0;
	}
	else
	{
		this.panel.transform.position.copy(this.trackerPos);
		this.panel.transform.rotation.y = -this.carousel.transform.rotation.y;
	}
	*/
//	this.animating = !this.animating;

	this.lastdx = 0;

	SB.Game.prototype.onMouseUp.call(this, x, y);
}

SB.Examples.TrackerGame.prototype.onMouseMove = function(x, y)
{
	this.dragger.set(x, y);

	SB.Game.prototype.onMouseMove.call(this, x, y);
}

SB.Examples.TrackerGame.prototype.onDraggerMove = function(dx, dy)
{
	if (Math.abs(dx) <= 2)
		dx = 0;

	dx *= .002;

	if (dx)
	{
		this.lastdx = dx;
	}
	else if (this.lastdx && this.dragging)
	{
		dx = this.lastdx;
	}

	if (dx != 0)
	{
		/*
		this.moveDir.set(dx, 0, 0);
		this.move(this.moveDir);
		*/
		this.turnDir.set(0, -dx, 0);
		this.turn(this.turnDir);

	}
}

SB.Examples.TrackerGame.prototype.onTrackerPosition = function(pos)
{
	// console.log("New tracker position: ", pos.x, ", ", pos.y, ", ", pos.z);
	this.trackerPos = pos;
	this.panel.transform.position.copy(this.trackerPos);
//	this.panel.transform.rotation.y = -this.carousel.transform.rotation.y;
}

SB.Examples.TrackerGame.prototype.onTrackerOrientation = function(orient)
{
	// console.log("New tracker orientation: ", orient.x, ", ", orient.y, ", ", orient.z, ", ", orient.w);
	this.trackerOrientation = orient;
	this.panel.transform.orientation.copy(orient);
	this.panel.transform.useQuaternion = true;
}

SB.Examples.TrackerGame.prototype.onTimeChanged = function(t)
{
	if (this.animating)
	{
		this.carousel.transform.rotation.y += 0.01;
	}
}
<commit_msg>Twiddling - trying to figure out headlight situation<commit_after>SB.Examples.TrackerGame = function()
{
	SB.Game.call(this);
}

goog.inherits(SB.Examples.TrackerGame, SB.Game);

SB.Examples.TrackerGame.prototype.initialize = function(param)
{
	param.tabstop = true;

	SB.Game.prototype.initialize.call(this, param);

	this.turnDir = new THREE.Vector3;
	this.moveDir = new THREE.Vector3;
	this.trackerPos = new THREE.Vector3;
	this.trackerOrientation = new THREE.Quaternion;

	this.lastdx = 0;
	this.dragging = false;
	this.animateDrag = true;
	this.dragAnimation = null;
	this.turnSpeed = 1;

	// Scene root
	var root = new SB.Entity;
	this.root = root;

    // A timer
	var timer = new SB.Timer( { loop : true } );
	timer.subscribe("time", this, this.onTimeChanged);
	timer.start();
	root.addComponent(timer);

/*    // Camera
	var mainCamera = new SB.Entity;

	var transform = new SB.Transform;
	mainCamera.addComponent(transform);

	var camera = new SB.Camera({fov: 50, active : true, position:new THREE.Vector3(0, 1, 5)} );
	mainCamera.addComponent(camera);

	root.addChild(mainCamera);

	this.mainCamera = mainCamera;
*/
	// Controller
	var controller = SB.Prefabs.FPSController({ active : true, headlight : true });
	controller.transform.position.set(0, 2.5, 3.67);
	root.addChild(controller);

    // Dragger thing
	var dragger = new SB.Dragger();
	root.addComponent(dragger);

	dragger.subscribe("move", this, this.onDraggerMove);
	this.dragger = dragger;

	// Something to drag
	var carousel = new SB.Entity;

	transform = new SB.Transform();
	carousel.addComponent(transform);

//	transform.rotation.y = Math.PI / 8;

	this.carousel = carousel;

	var grid = new SB.Entity;

	var visual = new SB.Grid({size: 14, color:0});
	grid.addComponent(visual);

	carousel.addChild(grid);

    // Something to draw
	var cylinder = new SB.Entity;

	transform = new SB.Transform();
	transform.position.z = -10;
    visual = new SB.CylinderVisual({radiusTop : 1, radiusBottom : 1, height : 1.667, color : 0x0000ff });

    cylinder.addComponent(transform);
    cylinder.addComponent(visual);

	carousel.addChild(cylinder);

	// Something to show tracker
	var panel = new SB.Entity;

	transform = new SB.Transform();
	transform.position.z = 3;
    visual = new SB.Pane({width:.5, height:.25, material : new THREE.MeshLambertMaterial({color:0x00ff00}) });

    panel.addComponent(transform);
    panel.addComponent(visual);

	cylinder.addChild(panel);

	this.panel = panel;

    this.cylinder = cylinder;

	root.addChild(carousel);

	this.addEntity(root);
	root.realize();

    // This tracks cylinder movement relative to carousel
	var controllerScript = controller.getComponent(SB.FPSControllerScript);
	var camera = controllerScript.viewpoint.getComponent(SB.Camera);

	var tracker = new SB.Tracker({reference : camera, referencePosition:new THREE.Vector3(0, 0, -3)});
	cylinder.addComponent(tracker);
	tracker.subscribe("position", this, this.onTrackerPosition);
	tracker.subscribe("orientation", this, this.onTrackerOrientation);
	tracker.start();

	this.root = root;
}

SB.Examples.TrackerGame.prototype.turn = function(dir)
{
	this.carousel.transform.rotation.addSelf(dir);
}

SB.Examples.TrackerGame.prototype.move = function(dir)
{
	this.carousel.transform.position.addSelf(dir);
}

SB.Examples.TrackerGame.prototype.onMouseDown = function(x, y)
{
	this.dragger.start(x, y);
	this.dragging = true;

	SB.Game.prototype.onMouseDown.call(this, x, y);
}

SB.Examples.TrackerGame.prototype.onMouseUp = function(x, y)
{
	this.dragger.stop(x, y);
	this.dragging = false;
	/*
	if (this.panel.transform.position.z > 3)
	{
		this.panel.transform.position.set(0, 0, 3);
		this.panel.transform.rotation.y = 0;
	}
	else
	{
		this.panel.transform.position.copy(this.trackerPos);
		this.panel.transform.rotation.y = -this.carousel.transform.rotation.y;
	}
	*/
//	this.animating = !this.animating;

	this.lastdx = 0;

	SB.Game.prototype.onMouseUp.call(this, x, y);
}

SB.Examples.TrackerGame.prototype.onMouseMove = function(x, y)
{
	this.dragger.set(x, y);

	SB.Game.prototype.onMouseMove.call(this, x, y);
}

SB.Examples.TrackerGame.prototype.onDraggerMove = function(dx, dy)
{
	if (Math.abs(dx) <= 2)
		dx = 0;

	dx *= .002;

	if (dx)
	{
		this.lastdx = dx;
	}
	else if (this.lastdx && this.dragging)
	{
		dx = this.lastdx;
	}

	if (dx != 0)
	{
		/*
		this.moveDir.set(dx, 0, 0);
		this.move(this.moveDir);
		*/
		this.turnDir.set(0, -dx, 0);
		this.turn(this.turnDir);

	}
}

SB.Examples.TrackerGame.prototype.onTrackerPosition = function(pos)
{
	// console.log("New tracker position: ", pos.x, ", ", pos.y, ", ", pos.z);
	this.trackerPos = pos;
	this.panel.transform.position.copy(this.trackerPos);
//	this.panel.transform.rotation.y = -this.carousel.transform.rotation.y;
}

SB.Examples.TrackerGame.prototype.onTrackerOrientation = function(orient)
{
	// console.log("New tracker orientation: ", orient.x, ", ", orient.y, ", ", orient.z, ", ", orient.w);
	this.trackerOrientation = orient;
	this.panel.transform.orientation.copy(orient);
	this.panel.transform.useQuaternion = true;
}

SB.Examples.TrackerGame.prototype.onTimeChanged = function(t)
{
	if (this.animating)
	{
		this.carousel.transform.rotation.y += 0.01;
	}
}
<|endoftext|>


<commit_before>import $ from 'jquery';
import Marionette from 'backbone.marionette';
import 'bootstrap-slider';
import 'bootstrap-slider/dist/css/bootstrap-slider.css';

import template from './ExtraParameterRangeView.hbs';
import './ExtraParameterRangeView.css';

const ExtraParameterRangeView = Marionette.ItemView.extend({
  template,
  templateHelpers() {
    const result = this.model.get('name').replace(/([A-Z])/g, ' $1');
    return {
      displayName: result.charAt(0).toUpperCase() + result.slice(1),
    };
  },

  className: 'row extra-parameter',
  events: {
    'slideStop input[data-provide="slider"]': 'onSliderStop',
  },

  onAttach() {
    this.$('[data-provide="slider"]').slider({
      tooltip_position: 'top',
    });
  },

  onSliderStop(event) {
    const $target = $(event.target);
    const type = this.model.get('type');
    const [low, high] = event.value;
    if ($target.data('slider-min') === low && $target.data('slider-max') === high) {
      this.trigger('value:unset', type);
    } else {
      this.trigger('value:change', type, { min: low, max: high });
    }
  },
});

export default ExtraParameterRangeView;
<commit_msg>Using ' - ' instead of ' : ' in Extra parameter range view as slider tooltip.<commit_after>import $ from 'jquery';
import Marionette from 'backbone.marionette';
import 'bootstrap-slider';
import 'bootstrap-slider/dist/css/bootstrap-slider.css';

import template from './ExtraParameterRangeView.hbs';
import './ExtraParameterRangeView.css';

const ExtraParameterRangeView = Marionette.ItemView.extend({
  template,
  templateHelpers() {
    const result = this.model.get('name').replace(/([A-Z])/g, ' $1');
    return {
      displayName: result.charAt(0).toUpperCase() + result.slice(1),
    };
  },

  className: 'row extra-parameter',
  events: {
    'slideStop input[data-provide="slider"]': 'onSliderStop',
  },

  onAttach() {
    this.$('[data-provide="slider"]').slider({
      tooltip_position: 'top',
      formatter(value) {
        if (Array.isArray(value)) {
          return `${value[0]} - ${value[1]}`;
        }
        return value;
      },
    });
  },

  onSliderStop(event) {
    const $target = $(event.target);
    const type = this.model.get('type');
    const [low, high] = event.value;
    if ($target.data('slider-min') === low && $target.data('slider-max') === high) {
      this.trigger('value:unset', type);
    } else {
      this.trigger('value:change', type, { min: low, max: high });
    }
  },
});

export default ExtraParameterRangeView;
<|endoftext|>


<commit_before>// this is similar to microtemplate but adds a lot of functions

Date.prototype.removeTime = function () {
  var d = new Date(this.valueOf());
  d.setHours(0);
  d.setMinutes(0);
  d.setSeconds(0);
  d.setMilliseconds(0);
  return d;
};

Date.prototype.add = function (years, months, days, hours, min, sec) {
  var
  y = this.getFullYear(),
  m = this.getMonth(),
  d = this.getDate(),
  h = this.getHours(),
  i = this.getMinutes(),
  s = this.getSeconds();
  return new Date(
     !years  ? y: y + years
    ,!months ? m: m + months
    ,!days   ? d: d + days
    ,!hours  ? h: h + hours
    ,!min    ? i: i + min
    ,!sec    ? s: s + sec
  );
};

/*
 * Date Format 1.2.3
 * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
 * MIT license
 *
 * Includes enhancements by Scott Trenda <scott.trenda.net>
 * and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */

var dateFormat = function () {
    var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
        timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
        timezoneClip = /[^-+\dA-Z]/g,
        pad = function (val, len) {
            val = String(val);
            len = len || 2;
            while (val.length < len) val = "0" + val;
            return val;
        };

    // Regexes and supporting functions are cached through closure
    return function (date, mask, utc) {
        var dF = dateFormat;

        // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
        if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
            mask = date;
            date = undefined;
        }

        // Passing date through Date applies Date.parse, if necessary
        date = date ? new Date(date) : new Date;
        if (isNaN(date)) throw SyntaxError("invalid date");

        mask = String(dF.masks[mask] || mask || dF.masks["default"]);

        // Allow setting the utc argument via the mask
        if (mask.slice(0, 4) == "UTC:") {
            mask = mask.slice(4);
            utc = true;
        }

        var _ = utc ? "getUTC" : "get",
            d = date[_ + "Date"](),
            D = date[_ + "Day"](),
            m = date[_ + "Month"](),
            y = date[_ + "FullYear"](),
            H = date[_ + "Hours"](),
            M = date[_ + "Minutes"](),
            s = date[_ + "Seconds"](),
            L = date[_ + "Milliseconds"](),
            o = utc ? 0 : date.getTimezoneOffset(),
            flags = {
                d:    d,
                dd:   pad(d),
                ddd:  dF.i18n.dayNames[D],
                dddd: dF.i18n.dayNames[D + 7],
                m:    m + 1,
                mm:   pad(m + 1),
                mmm:  dF.i18n.monthNames[m],
                mmmm: dF.i18n.monthNames[m + 12],
                yy:   String(y).slice(2),
                yyyy: y,
                h:    H % 12 || 12,
                hh:   pad(H % 12 || 12),
                H:    H,
                HH:   pad(H),
                M:    M,
                MM:   pad(M),
                s:    s,
                ss:   pad(s),
                l:    pad(L, 3),
                L:    pad(L > 99 ? Math.round(L / 10) : L),
                t:    H < 12 ? "a"  : "p",
                tt:   H < 12 ? "am" : "pm",
                T:    H < 12 ? "A"  : "P",
                TT:   H < 12 ? "AM" : "PM",
                Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
                o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
                S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
            };

        return mask.replace(token, function ($0) {
            return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
        });
    };
}();

// Some common format strings
dateFormat.masks = {
    "default":      "ddd mmm dd yyyy HH:MM:ss",
    shortDate:      "m/d/yy",
    mediumDate:     "mmm d, yyyy",
    longDate:       "mmmm d, yyyy",
    fullDate:       "dddd, mmmm d, yyyy",
    shortTime:      "h:MM TT",
    mediumTime:     "h:MM:ss TT",
    longTime:       "h:MM:ss TT Z",
    isoDate:        "yyyy-mm-dd",
    isoTime:        "HH:MM:ss",
    isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
    isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
    dayNames: [
        "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
        "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
    ],
    monthNames: [
        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
        "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
    ]
};

Array.prototype.findIndex = function (fn) { for (var i = 0; i < this.length; i++) if (fn(this[i])) return       i; return undefined; }
Array.prototype.find      = function (fn) { for (var i = 0; i < this.length; i++) if (fn(this[i])) return this[i]; return undefined; }

// For convenience...
Date.prototype.format = function (mask, utc) { return dateFormat(this, mask, utc); };

String.prototype.toDate = function () {
  var m = this.match(/^(\d\d\d\d)-(\d\d)-(\d\d)( (\d\d):(\d\d):(\d\d))?$/);
  if (m) return new Date(
    parseInt(m[1]), parseInt(m[2], 10) - 1, parseInt(m[3], 10),
    parseInt(m[5]||0, 10), parseInt(m[6]||0, 10), parseInt(m[7]||0, 10)
 );
  m = this.match(/^(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)\.000Z$/);
  if (m) return new Date(
    parseInt(m[1]), parseInt(m[2], 10) - 1, parseInt(m[3], 10),
    parseInt(m[4]||0, 10), parseInt(m[5]||0, 10), parseInt(m[6]||0, 10)
  );
  return null;
};
function escHtml(str) { return !str ? '' : String(str) .replace(/&/g, "&") .replace(/"/g, """) .replace(/'/g, "'") .replace(/</g, "<") .replace(/>/g, ">"); };
encUrl = encodeURIComponent;

var tr = query('tr').data;
var translations = {};

for (var t in tr) {
    if (!translations[tr[t].lang]) {
        translations[tr[t].lang] = {};
    }

    translations[tr[t].lang][tr[t].label] = tr[t].content;
}

var activeTranslation = vars.lang;
var toDb = [];
var debug = null;
var transl;

function _translate ( body ) {
  transl = body.match(/(?=<!(?!DOCTYPE|--))([\s\S]*?<!>)/igm);
      if (transl && transl.length > 0) {
          for ( t = 0; t < transl.length; t++) {

              //finding all block to be translated is working
              block = transl[t];
              var blockAttributes;
              var res = block.match(/<!([^: ]+:[^<>]+)>/);

              if ( res && res[1] ) {
                  blockAttributes = res[1].split(" ");
              }

              attributeName = block.match(/<!(.*?)>/)[1];

              if (blockAttributes) {
                  re = new RegExp("<!" + attributeName + "(.*?)>(.*?)<!>","");
                  blockToBeTranslated = block.match(re)[2];

                  for (i = 0; i < blockAttributes.length; i++) {
                      attrName = blockAttributes[i].split(':')[0];
                      attrValue = blockAttributes[i].split(':')[1];

                          rep = new RegExp(attrName + '="([^"]*)"',"");
                          val = blockToBeTranslated.match(rep);

                          debug=reg = new RegExp(attrName + '="(.+?)"', "g");
                          blockToBeTranslated = (translations[activeTranslation] && translations[activeTranslation][attrValue] ?
                              blockToBeTranslated.replace(reg, attrName + '="' + translations[activeTranslation][attrValue] + '"') :
                              blockToBeTranslated);

                          toDb.push({
                              label: attrName,
                              content: '',
                              default_text: (val ? val[1] : '')
                          });
                      //block = block.replace(block, blockToBeTranslated);
                  }
                  body = body.replace(block, blockToBeTranslated);

              } else {

                  //replacing single translations is working
                  var re = new RegExp("<!" + attributeName + "(.*?)>(?:\\s*?)(.*?)(\\s*?)<!>","");
                      attributeText = block.match(re)[2];
                  var replace = ( translations[activeTranslation] && translations[activeTranslation][attributeName] ? translations[activeTranslation][attributeName]  : attributeText );

                  toDb.push({
                      label: attributeName,
                      content: '',
                      default_text: attributeText
                  });

                  body = body.replace(block, replace);
              }
          }
      }
  return body;
}

if (!vars.debugjs) { template = _translate(template); }
if (vars.writeDb) { post("tr", {}, toDb); }

fnBody =
    template.split("%>").map(function (p) {
        return p.split("<%").map(function (pp, i) {
          if (!pp) return ""; else
          if (i && pp.charAt(0) == "=") return "print( (" + pp.substr(1) + ").toString() );"; else // TODO: zazler should take any value
          if (i && pp.charAt(0) == "~") return "print( escHtml(" + pp.substr(1) + ") );"; else
          if (!i) return "print( " + JSON.stringify(pp) + " );"; else
          return pp;
        }).join("\n");
      }).join("\n");

if (vars.debugjs)
     { contentType('text/plain', 'utf-8'); print(fnBody); }
else { contentType("text/html",  "utf-8"); eval(fnBody);  }

<commit_msg>microtemplate<commit_after>// this is similar to microtemplate but adds a lot of functions

Date.prototype.removeTime = function () {
  var d = new Date(this.valueOf());
  d.setHours(0);
  d.setMinutes(0);
  d.setSeconds(0);
  d.setMilliseconds(0);
  return d;
};

Date.prototype.add = function (years, months, days, hours, min, sec) {
  var
  y = this.getFullYear(),
  m = this.getMonth(),
  d = this.getDate(),
  h = this.getHours(),
  i = this.getMinutes(),
  s = this.getSeconds();
  return new Date(
     !years  ? y: y + years
    ,!months ? m: m + months
    ,!days   ? d: d + days
    ,!hours  ? h: h + hours
    ,!min    ? i: i + min
    ,!sec    ? s: s + sec
  );
};

/*
 * Date Format 1.2.3
 * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
 * MIT license
 *
 * Includes enhancements by Scott Trenda <scott.trenda.net>
 * and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */

var dateFormat = function () {
    var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
        timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
        timezoneClip = /[^-+\dA-Z]/g,
        pad = function (val, len) {
            val = String(val);
            len = len || 2;
            while (val.length < len) val = "0" + val;
            return val;
        };

    // Regexes and supporting functions are cached through closure
    return function (date, mask, utc) {
        var dF = dateFormat;

        // You can't provide utc if you skip other args (use the "UTC:" mask prefix)
        if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
            mask = date;
            date = undefined;
        }

        // Passing date through Date applies Date.parse, if necessary
        date = date ? new Date(date) : new Date;
        if (isNaN(date)) throw SyntaxError("invalid date");

        mask = String(dF.masks[mask] || mask || dF.masks["default"]);

        // Allow setting the utc argument via the mask
        if (mask.slice(0, 4) == "UTC:") {
            mask = mask.slice(4);
            utc = true;
        }

        var _ = utc ? "getUTC" : "get",
            d = date[_ + "Date"](),
            D = date[_ + "Day"](),
            m = date[_ + "Month"](),
            y = date[_ + "FullYear"](),
            H = date[_ + "Hours"](),
            M = date[_ + "Minutes"](),
            s = date[_ + "Seconds"](),
            L = date[_ + "Milliseconds"](),
            o = utc ? 0 : date.getTimezoneOffset(),
            flags = {
                d:    d,
                dd:   pad(d),
                ddd:  dF.i18n.dayNames[D],
                dddd: dF.i18n.dayNames[D + 7],
                m:    m + 1,
                mm:   pad(m + 1),
                mmm:  dF.i18n.monthNames[m],
                mmmm: dF.i18n.monthNames[m + 12],
                yy:   String(y).slice(2),
                yyyy: y,
                h:    H % 12 || 12,
                hh:   pad(H % 12 || 12),
                H:    H,
                HH:   pad(H),
                M:    M,
                MM:   pad(M),
                s:    s,
                ss:   pad(s),
                l:    pad(L, 3),
                L:    pad(L > 99 ? Math.round(L / 10) : L),
                t:    H < 12 ? "a"  : "p",
                tt:   H < 12 ? "am" : "pm",
                T:    H < 12 ? "A"  : "P",
                TT:   H < 12 ? "AM" : "PM",
                Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
                o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
                S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
            };

        return mask.replace(token, function ($0) {
            return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
        });
    };
}();

// Some common format strings
dateFormat.masks = {
    "default":      "ddd mmm dd yyyy HH:MM:ss",
    shortDate:      "m/d/yy",
    mediumDate:     "mmm d, yyyy",
    longDate:       "mmmm d, yyyy",
    fullDate:       "dddd, mmmm d, yyyy",
    shortTime:      "h:MM TT",
    mediumTime:     "h:MM:ss TT",
    longTime:       "h:MM:ss TT Z",
    isoDate:        "yyyy-mm-dd",
    isoTime:        "HH:MM:ss",
    isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
    isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
    dayNames: [
        "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
        "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
    ],
    monthNames: [
        "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
        "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
    ]
};

Array.prototype.findIndex = function (fn) { for (var i = 0; i < this.length; i++) if (fn(this[i])) return       i; return undefined; }
Array.prototype.find      = function (fn) { for (var i = 0; i < this.length; i++) if (fn(this[i])) return this[i]; return undefined; }

// For convenience...
Date.prototype.format = function (mask, utc) { return dateFormat(this, mask, utc); };

String.prototype.toDate = function () {
  var m = this.match(/^(\d\d\d\d)-(\d\d)-(\d\d)( (\d\d):(\d\d):(\d\d))?$/);
  if (m) return new Date(
    parseInt(m[1]), parseInt(m[2], 10) - 1, parseInt(m[3], 10),
    parseInt(m[5]||0, 10), parseInt(m[6]||0, 10), parseInt(m[7]||0, 10)
 );
  m = this.match(/^(\d\d\d\d)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)\.000Z$/);
  if (m) return new Date(
    parseInt(m[1]), parseInt(m[2], 10) - 1, parseInt(m[3], 10),
    parseInt(m[4]||0, 10), parseInt(m[5]||0, 10), parseInt(m[6]||0, 10)
  );
  return null;
};
function escHtml(str) { return !str ? '' : String(str) .replace(/&/g, "&") .replace(/"/g, """) .replace(/'/g, "'") .replace(/</g, "<") .replace(/>/g, ">"); };
encUrl = encodeURIComponent;

var tr = query('tr').data;
var translations = {};

for (var t in tr) {
    if (!translations[tr[t].lang]) {
        translations[tr[t].lang] = {};
    }

    translations[tr[t].lang][tr[t].label] = tr[t].content;
}

var activeTranslation = vars.lang;
var toDb = [];
var debug = null;
var transl;

function _translate ( body ) {
  transl = body.match(/(?=<!(?!DOCTYPE|--))([\s\S]*?<!>)/igm);
      if (transl && transl.length > 0) {
          for ( t = 0; t < transl.length; t++) {

              //finding all block to be translated is working
              block = transl[t];
              var blockAttributes;
              var res = block.match(/<!([^: ]+:[^<>]+)>/);

              if ( res && res[1] ) {
                  blockAttributes = res[1].split(" ");
              }

              attributeName = block.match(/<!(.*?)>/)[1];

              if (blockAttributes) {
                  re = new RegExp("<!" + attributeName + "(.*?)>(.*?)<!>","");
                  blockToBeTranslated = block.match(re)[2];

                  for (i = 0; i < blockAttributes.length; i++) {
                      attrName = blockAttributes[i].split(':')[0];
                      attrValue = blockAttributes[i].split(':')[1];

                          rep = new RegExp(attrName + '="([^"]*)"',"");
                          val = blockToBeTranslated.match(rep);

                          debug=reg = new RegExp(attrName + '="(.+?)"', "g");
                          blockToBeTranslated = (translations[activeTranslation] && translations[activeTranslation][attrValue] ?
                              blockToBeTranslated.replace(reg, attrName + '="' + translations[activeTranslation][attrValue] + '"') :
                              blockToBeTranslated);

                          toDb.push({
                              label: attrName,
                              content: (val ? val[1] : '')
                          });
                      //block = block.replace(block, blockToBeTranslated);
                  }
                  body = body.replace(block, blockToBeTranslated);

              } else {

                  //replacing single translations is working
                  var re = new RegExp("<!" + attributeName + "(.*?)>(?:\\s*?)(.*?)(\\s*?)<!>","");
                      attributeText = block.match(re)[2];
                  var replace = ( translations[activeTranslation] && translations[activeTranslation][attributeName] ? translations[activeTranslation][attributeName]  : attributeText );

                  toDb.push({
                      label: attributeName,
                      content: attributeText
                  });

                  body = body.replace(block, replace);
              }
          }
      }
  return body;
}

if (!vars.debugjs) { template = _translate(template); }
if (vars.writeDb) { post("tr", {}, toDb); }

fnBody =
    template.split("%>").map(function (p) {
        return p.split("<%").map(function (pp, i) {
          if (!pp) return ""; else
          if (i && pp.charAt(0) == "=") return "print( (" + pp.substr(1) + ").toString() );"; else // TODO: zazler should take any value
          if (i && pp.charAt(0) == "~") return "print( escHtml(" + pp.substr(1) + ") );"; else
          if (!i) return "print( " + JSON.stringify(pp) + " );"; else
          return pp;
        }).join("\n");
      }).join("\n");

if (vars.debugjs)
     { contentType('text/plain', 'utf-8'); print(fnBody); }
else { contentType("text/html",  "utf-8"); eval(fnBody);  }

<|endoftext|>


<commit_before>'use strict';

var pendingpointsListUrl = 'http://162.242.174.14:8000/get/pendingpoints';
var assertionUrl = 'http://162.242.174.14:8000/persona';
var postCommentUrl = 'http://162.242.174.14:8000/post/comment';

$(document).ready(function(){
    var loggedInUser = null;

    function logout(){
        loggedInUser = null;
        var response = $.post(assertionUrl + '/logout');
        response.always(showPersona);
    }

    function verify(assertion){
        var response = $.ajax(assertionUrl + '/verify', {data: {assertion: assertion}, type: 'POST', xhrFields: {withCredentials: true}});
        response.done(login);
        response.fail(function(){
            navigator.id.logout();
        });
    }

    function login(data){
        showCommentForms(data.email);
    }

    if(navigator.id){
        navigator.id.watch({
            loggedInUser: loggedInUser,
            onlogin: verify,
            onlogout: logout
        });
    }

    function showPersona(){
		$('.leaveComment').html('
To comment, please sign in — you can use an existing email address.

');
		$('.signinButton').click(function(){ navigator.id.request(); }).css('cursor', 'pointer');
	}

	function showCommentForms(email){
        $('#pendingpoints .comments').each(function(){
            var pointId = $(this).attr('id').substr(9);
            $(this).find('.leaveComment').html('
Commenting as ' + email + ' (Not your email address?)
<form class="commentForm"><fieldset>
<textarea name="comment" required class="input-xxlarge"></textarea>

<button class="btn btn-primary" id="postComment">Send</button>
</fieldset></form>')
            .find('.commentForm').submit(function(e){
                var response = $.ajax(postCommentUrl, {data: {comment: $('#comments-' + pointId + ' .leaveComment textarea').val(), pointId: pointId}, type: 'POST', xhrFields: {withCredentials: true}});
                response.done(showConfirmation);
                response.fail(showError);
                e.preventDefault();
            });
        });

		$('.signoutButton').click(function(){ navigator.id.logout(); });
	}

	function showConfirmation(){
		$('#pendingpoints').before('
<button type="button" class="close" data-dismiss="alert">×</button>Your comment has been submitted. Thank you!
');
        showOverview();
	}

	function showError(){
		$('#pendingpoints').before('
<button type="button" class="close" data-dismiss="alert">×</button>Something went wrong saving your comment, did you fill in all the fields?
');
	}

    function showOverview(){
        var response = $.get(pendingpointsListUrl, 'json');
        response.done(function(points){
            $('#pendingpoints').text('');
            points.forEach(function(point){
                point.tosdr.point = point.tosdr.point.replace(/[^A-Za-z]/g, '');
                point.id = point.id.replace(/[^A-Za-z0-9_-]/g, '');
                point.title = $('
').text(point.title).html();
                var badge = '',
                    icon = 'question-sign',
                    sign = '?';
                if (point.tosdr.point == 'good') {
                    badge = 'badge-success';
                    icon = 'thumbs-up';
                    sign = '+';
                } else if (point.tosdr.point == 'bad') {
                    badge = 'badge-warning';
                    icon = 'thumbs-down';
                    sign = '-';
                } else if (point.tosdr.point == 'blocker') {
                    badge = 'badge-important';
                    icon = 'remove';
                    sign = '×';
                } else if (point.tosdr.point == 'neutral') {
                    badge = 'badge-neutral';
                    icon = 'asterisk';
                    sign = '⋅';
                }
                $('#pendingpoints').append('

' + sign + ' ' + point.title + '

');
                $.each(point.services, function(index, service){
                    $('#pendingpoints .' + point.id + ' .services').append('
' + service.replace(/[^A-Za-z0-9_-]/g, '') + '
 ');
                });

                $.each(point.comments, function(index, comment){
                    $('#pendingpoints .comments-' + point.id + ' .leaveComment').before('

');
                    $('#currentAddition').text(comment.content).prepend('').removeAttr('id');
                });
            });
            showPersona();
        });
    }

    showOverview();
});
<commit_msg>Show an error message when the list of pending points cannot be fetched.<commit_after>'use strict';

var pendingpointsListUrl = 'http://162.242.174.14:8000/get/pendingpoints';
var assertionUrl = 'http://162.242.174.14:8000/persona';
var postCommentUrl = 'http://162.242.174.14:8000/post/comment';

$(document).ready(function(){
    var loggedInUser = null;

    function logout(){
        loggedInUser = null;
        var response = $.post(assertionUrl + '/logout');
        response.always(showPersona);
    }

    function verify(assertion){
        var response = $.ajax(assertionUrl + '/verify', {data: {assertion: assertion}, type: 'POST', xhrFields: {withCredentials: true}});
        response.done(login);
        response.fail(function(){
            navigator.id.logout();
        });
    }

    function login(data){
        showCommentForms(data.email);
    }

    if(navigator.id){
        navigator.id.watch({
            loggedInUser: loggedInUser,
            onlogin: verify,
            onlogout: logout
        });
    }

    function showPersona(){
		$('.leaveComment').html('
To comment, please sign in — you can use an existing email address.

');
		$('.signinButton').click(function(){ navigator.id.request(); }).css('cursor', 'pointer');
	}

	function showCommentForms(email){
        $('#pendingpoints .comments').each(function(){
            var pointId = $(this).attr('id').substr(9);
            $(this).find('.leaveComment').html('
Commenting as ' + email + ' (Not your email address?)
<form class="commentForm"><fieldset>
<textarea name="comment" required class="input-xxlarge"></textarea>

<button class="btn btn-primary" id="postComment">Send</button>
</fieldset></form>')
            .find('.commentForm').submit(function(e){
                var response = $.ajax(postCommentUrl, {data: {comment: $('#comments-' + pointId + ' .leaveComment textarea').val(), pointId: pointId}, type: 'POST', xhrFields: {withCredentials: true}});
                response.done(showConfirmation);
                response.fail(showError);
                e.preventDefault();
            });
        });

		$('.signoutButton').click(function(){ navigator.id.logout(); });
	}

	function showConfirmation(){
		$('#pendingpoints').before('
<button type="button" class="close" data-dismiss="alert">×</button>Your comment has been submitted. Thank you!
');
        showOverview();
	}

	function showError(){
		$('#pendingpoints').before('
<button type="button" class="close" data-dismiss="alert">×</button>Something went wrong saving your comment, did you fill in all the fields?
');
	}

    function showOverview(){
        var response = $.get(pendingpointsListUrl, 'json');
        response.done(function(points){
            $('#pendingpoints').text('');
            points.forEach(function(point){
                point.tosdr.point = point.tosdr.point.replace(/[^A-Za-z]/g, '');
                point.id = point.id.replace(/[^A-Za-z0-9_-]/g, '');
                point.title = $('
').text(point.title).html();
                var badge = '',
                    icon = 'question-sign',
                    sign = '?';
                if (point.tosdr.point == 'good') {
                    badge = 'badge-success';
                    icon = 'thumbs-up';
                    sign = '+';
                } else if (point.tosdr.point == 'bad') {
                    badge = 'badge-warning';
                    icon = 'thumbs-down';
                    sign = '-';
                } else if (point.tosdr.point == 'blocker') {
                    badge = 'badge-important';
                    icon = 'remove';
                    sign = '×';
                } else if (point.tosdr.point == 'neutral') {
                    badge = 'badge-neutral';
                    icon = 'asterisk';
                    sign = '⋅';
                }
                $('#pendingpoints').append('

' + sign + ' ' + point.title + '

');
                $.each(point.services, function(index, service){
                    $('#pendingpoints .' + point.id + ' .services').append('
' + service.replace(/[^A-Za-z0-9_-]/g, '') + '
 ');
                });

                $.each(point.comments, function(index, comment){
                    $('#pendingpoints .comments-' + point.id + ' .leaveComment').before('

');
                    $('#currentAddition').text(comment.content).prepend('').removeAttr('id');
                });
            });
            showPersona();
        });

        response.fail(function(response, textStatus, errorThrown){
            console.log(textStatus, errorThrown);
            $('#pendingpoints').text('Unfortunately, something went wrong fetching the pending discussion points.');
        });
    }

    showOverview();
});
<|endoftext|>


<commit_before>var net = require('net');
var events = require('events');
var action = require('./message/action.js');
var util = require('util');
var namiEvents = require('./message/event.js');
var timer = require('timers');

// Constructor
function Nami(amiData) {
    Nami.super_.call(this);
    this.connected = false;
    this.loggedIn = false;
    this.amiData = amiData;
    this.EOL = "\r\n";
    this.EOM = this.EOL + this.EOL;
    this.welcomeMessage = "Asterisk Call Manager/1.1" + this.EOL;
    this.received = false;
}
// Nami inherits from the EventEmitter so Nami itself can throw events.
util.inherits(Nami, events.EventEmitter);

Nami.prototype.onRawEvent = function (buffer) {
    var event = new namiEvents.Event(buffer);
    this.emit('namiEvent', event);
}

// in net.Socket scope
Nami.prototype.onData = function (data) {
    while ((theEOM = data.indexOf(this.me.EOM)) != -1) {
        this.me.received = this.me.received.concat(data.substr(0, theEOM));
        this.me.emit('namiRawEvent', this.me.received);
        this.me.received = "";
        data = data.substr(theEOM + this.me.EOM.length);
    }
    this.me.received = data;
}
Nami.prototype.onConnect = function () {
    this.connected = true;
}
Nami.prototype.login = function () {
    this.socket.on('data', this.onData);
    this.send(new action.LoginAction(
        this.amiData.username, this.amiData.secret
    ));
}

Nami.prototype.onWelcomeMessage = function (data) {
    var welcome = data.indexOf(this.me.welcomeMessage);
    if (welcome == -1) {
        this.me.emit('namiInvalidPeer', data);
    } else {
        this.me.login();
    }
}
Nami.prototype.open = function () {
    this.socket = new net.Socket();
    this.socket.on('connect', this.onConnect);
    this.on('namiRawEvent', this.onRawEvent);
    this.socket.once('data', this.onWelcomeMessage);
    this.socket.setEncoding('ascii');
    this.received = "";
    this.socket.me = this;
    this.socket.connect(this.amiData.port, this.amiData.host);
}

Nami.prototype.send = function (action) {
    this.socket.write(action.marshall());
}

exports.Nami = Nami;
<commit_msg>used self for nami data event handlers<commit_after>var net = require('net');
var events = require('events');
var action = require('./message/action.js');
var util = require('util');
var namiEvents = require('./message/event.js');
var timer = require('timers');

// Constructor
function Nami(amiData) {
    Nami.super_.call(this);
    this.connected = false;
    this.loggedIn = false;
    this.amiData = amiData;
    this.EOL = "\r\n";
    this.EOM = this.EOL + this.EOL;
    this.welcomeMessage = "Asterisk Call Manager/1.1" + this.EOL;
    this.received = false;
}
// Nami inherits from the EventEmitter so Nami itself can throw events.
util.inherits(Nami, events.EventEmitter);

Nami.prototype.onRawEvent = function (buffer) {
    var event = new namiEvents.Event(buffer);
    this.emit('namiEvent', event);
}

Nami.prototype.onData = function (data) {
    while ((theEOM = data.indexOf(this.EOM)) != -1) {
        this.received = this.received.concat(data.substr(0, theEOM));
        this.emit('namiRawEvent', this.received);
        this.received = "";
        data = data.substr(theEOM + this.EOM.length);
    }
    this.received = data;
}
Nami.prototype.onConnect = function () {
    this.connected = true;
}
Nami.prototype.login = function () {
	var self = this;
    this.socket.on('data', function (data) {
    	self.onData(data);
    });
    this.send(new action.LoginAction(
        this.amiData.username, this.amiData.secret
    ));
}

Nami.prototype.onWelcomeMessage = function (data) {
    var welcome = data.indexOf(this.welcomeMessage);
    if (welcome == -1) {
        this.emit('namiInvalidPeer', data);
    } else {
        this.login();
    }
}
Nami.prototype.open = function () {
    this.socket = new net.Socket();
    var self = this;
    this.socket.on('connect', this.onConnect);
    this.on('namiRawEvent', this.onRawEvent);
    this.socket.once('data', function (data) {
    	self.onWelcomeMessage(data);
    });
    this.socket.setEncoding('ascii');
    this.received = "";
    this.socket.connect(this.amiData.port, this.amiData.host);
}

Nami.prototype.send = function (action) {
    this.socket.write(action.marshall());
}

exports.Nami = Nami;
<|endoftext|>


<commit_before>
var IMAGES = new Array(0);

/******************************************************************************/

function printImageSize(url, imageOverlay) {
    var image = new Image();
    image.name = url;
    image.src = url;
    image.onload = function() {
            var size = this.width + 'x' + this.height;
            imageOverlay.append('
Size: ' + size);
        };
}

function backgroundHasURL(string) {
    var re = /(url\()(.*)(\))/;
    var array = re.exec(string);
    if(array) {
        var url = array[2];
        return url;
    }

    return false;
}

function storeImage(url) {
    if(! url)
        return;

    var imgWrap = $('
').attr('class', 'imageWrap');

    var img = $('').attr('class', 'theImage')
                         .attr('src', url)
                         .appendTo(imgWrap);

    var imageOverlay = $('
').attr('class', 'imageOverlay')
                                  .appendTo(imgWrap);

    var openLink = $('').attr('href', url)
                              .attr('target', '_blank')
                              .html('open')
                              .appendTo(imageOverlay);

    printImageSize(url, imageOverlay);

    IMAGES.push(imgWrap);
}

function findBackgroundImage(element) {
    if($(element).attr('class') == 'spaceball') /* Flickr mask. */
        return;

    var background = $(element).css('background');
    var url = backgroundHasURL(background);
    storeImage(url);
}

function getImagesPanel() {
    var title = $('').attr('id', 'title')
                         .attr('href', "http://github.com/givanse/cr24Sauce")
                         .attr('target', '_blank')
                         .html('cr24Sauce');
    var imagesPanel = $('
').attr('id', 'imagesPanel')
                                 .attr('class', 'ui-widget-content')
                                 .append(title)
                                 .append(IMAGES);
    imagesPanel.draggable();
    return imagesPanel;
}

$(document).ready(function() {
    /* google.com */
    $('div').each(function(index, element) {
        findBackgroundImage(element);
    });

    /* flickr.com */
    $('div#allsizes-photo img').each(function(index, img) {
        var url = $(img).attr('src');
        storeImage(url);
    });

    /* google.com */
    $('meta').each(function(index, element) {
        var property = $(element).attr('property');
        if(property != 'og:image')
            return;

        var url = $(element).attr('content');
        storeImage(url);
    });

    var imagesPanel = getImagesPanel();

    var wrapper = $('
').attr('id', 'cr24SauceWrapper')
                             .append(imagesPanel);

    $(document.body).append(wrapper);
});

/* EOF */
<commit_msg>discard small images, less than 128 width or height<commit_after>
var IMAGES = new Array(0);

/******************************************************************************/

function onloadAddToOverlayImageSize(imageWrapper, imageOverlay, url) {
    var image = new Image();
    image.name = url;
    image.src = url;

    image.onload = function() {
            var minimumSize = 128;
            if(this.width <= minimumSize || this.height <= minimumSize) {
                imageWrapper.parentNode.removeChild(imageWrapper);
                return;
            }

            var size = this.width + 'x' + this.height;
            imageOverlay.append('
Size: ' + size);
        };
}

function backgroundHasURL(string) {
    var re = /(url\()(.*)(\))/;
    var array = re.exec(string);
    if(array) {
        var url = array[2];
        return url;
    }

    return false;
}

function storeImage(url) {
    if(! url)
        return;

    var imgWrap = $('
').attr('class', 'imageWrap');

    var theImage = $('').attr('class', 'theImage')
                         .attr('src', url)
                         .appendTo(imgWrap);

    var imageOverlay = $('
').attr('class', 'imageOverlay')
                                  .appendTo(imgWrap);

    var openImageLink = $('').attr('href', url)
                              .attr('target', '_blank')
                              .html('open')
                              .appendTo(imageOverlay);

    onloadAddToOverlayImageSize(imgWrap[0], imageOverlay, url);

    IMAGES.push(imgWrap);
}

function getImagesPanel() {
    var title = $('').attr('id', 'title')
                         .attr('href', "http://github.com/givanse/cr24Sauce")
                         .attr('target', '_blank')
                         .html('cr24Sauce');
    var imagesPanel = $('
').attr('id', 'imagesPanel')
                                 .attr('class', 'ui-widget-content')
                                 .append(title)
                                 .append(IMAGES);
    imagesPanel.draggable();
    return imagesPanel;
}

$(document).ready(function() {
    /* DIVs with background images */
    $('div').each(function(index, element) {
        if($(element).attr('class') == 'spaceball') /* Flickr mask, skip. */
            return;

        var background = $(element).css('background');
        var url = backgroundHasURL(background);
        storeImage(url);
    });

    $('div#allsizes-photo img').each(function(index, img) {
        var url = $(img).attr('src');
        storeImage(url);
    });

    /* youtube.com */
    $('meta').each(function(index, element) {
        var property = $(element).attr('property');
        if(property != 'og:image')
            return;

        var url = $(element).attr('content');
        storeImage(url);
    });

    var imagesPanel = getImagesPanel();

    var wrapper = $('
').attr('id', 'cr24SauceWrapper')
                             .append(imagesPanel);

    $(document.body).append(wrapper);
});

/* EOF */
<|endoftext|>


<commit_before>const { addBudgetItemsError, clearBudgetItemsErrors } = require('./ducks/budgetItems/errors')

const {
  startLoadingBudgetItemFilter,
  finishLoadingBudgetItemFilter,
  setSelectedBudgetItemIds,
  setBudgetItemFilterOptions
} = require('./ducks/filters/budgetItems')

const { beginLoadingBudgetItems, finishLoadingBudgetItems } = require('./ducks/budgetItems/loading')
const { setBudgetItems } = require('./ducks/budgetItems/data')

const georgianBudgetAPI = require('js/services/georgianBudgetAPI')

const updateBudgetItems = () => (dispatch, getState) => {
  const state = getState()
  const locale = state.locale
  const budgetItemType = state.filters.budgetItemType.value
  const financeType = state.filters.financeType.value
  const budgetItemIds = state.filters.budgetItems.selectedIds

  if (budgetItemIds.length === 0) {
    dispatch(setBudgetItems([]))
    return
  }

  const requiredState = [locale, budgetItemType, financeType, budgetItemIds]

  for (let i = 0; i < requiredState.length; i++) {
    if (requiredState[i].length === 0) return
  }

  dispatch(beginLoadingBudgetItems())

  georgianBudgetAPI.get(locale, 'v1', {
    params: {
      filters: {
        budgetItemType: budgetItemType,
        financeType: financeType
      },
      budgetItemIds: budgetItemIds
    }
  }).catch((error) => {
    dispatch(addBudgetItemsError(`Error communicating with API: ${error}`))
  }).then((response) => {
    dispatch(clearBudgetItemsErrors())

    if (typeof response.data !== 'object') {
      dispatch(addBudgetItemsError('Error communicating with API'))
      return
    }

    const errors = response.data.errors
    const budgetItems = response.data.budgetItems

    if (errors.length > 0) {
      errors.forEach((error) => {
        dispatch(addBudgetItemsError(error.text))
      })
    }

    if (budgetItems) {
      dispatch(setBudgetItems(budgetItems))
    }

    dispatch(finishLoadingBudgetItems())
  })
}

const updateBudgetItemFilterOptions = () => (dispatch, getState) => {
  const state = getState()

  const locale = state.locale
  const budgetItemType = state.filters.budgetItemType.value

  const requiredState = [locale, budgetItemType]

  for (let i = 0; i < requiredState.length; i++) {
    if (requiredState[i].length === 0) return
  }

  dispatch(startLoadingBudgetItemFilter())

  georgianBudgetAPI.get(locale, 'v1', {
    params: {
      budgetItemFields: 'id,name',

      filters: {
        budgetItemType: budgetItemType
      }
    }
  }).catch((error) => {
    dispatch(addBudgetItemsError(`Error communicating with API: ${error}`))
  }).then((response) => {
    if (!response || !response.data || typeof response.data !== 'object') {
      dispatch(addBudgetItemsError('Error communicating with API'))
      return
    }

    const errors = response.data.errors
    const budgetItems = response.data.budgetItems

    if (errors && errors.length > 0) {
      errors.forEach((error) => {
        if (error.text) {
          dispatch(addBudgetItemsError(error.text))
        } else {
          dispatch(addBudgetItemsError('Error communicating with API'))
        }
      })
    }

    if (budgetItems) {
      const budgetItemFilterOptions = budgetItems.map((budgetItem) => {
        const option = {
          id: budgetItem.id,
          name: budgetItem.name
        }

        let errored = false

        if (typeof option.id !== 'number') {
          dispatch(addBudgetItemsError('Budget item does not have valid id to use as option value'))
          errored = true
        }

        if (typeof option.name !== 'string') {
          dispatch(addBudgetItemsError(`Budget item (id: ${option.name}) does not have valid name to use as option label`))
          errored = true
        }

        if (errored) return null

        return option
      }).filter((option) => option !== null && option !== undefined)

      dispatch(setBudgetItemFilterOptions(budgetItemFilterOptions))

      if (budgetItemType === 'total' && budgetItemFilterOptions.length > 0) {
        dispatch(setSelectedBudgetItemIds([budgetItemFilterOptions[0].id]))
        dispatch(updateBudgetItems())
      }

      dispatch(finishLoadingBudgetItemFilter())
    }
  })
}

module.exports = {
  updateBudgetItems,
  updateBudgetItemFilterOptions
}
<commit_msg>Further refactor.<commit_after>const { addBudgetItemsError, clearBudgetItemsErrors } = require('./ducks/budgetItems/errors')

const {
  startLoadingBudgetItemFilter,
  finishLoadingBudgetItemFilter,
  setSelectedBudgetItemIds,
  setBudgetItemFilterOptions
} = require('./ducks/filters/budgetItems')

const { beginLoadingBudgetItems, finishLoadingBudgetItems } = require('./ducks/budgetItems/loading')
const { setBudgetItems } = require('./ducks/budgetItems/data')

const georgianBudgetAPI = require('js/services/georgianBudgetAPI')

const updateBudgetItems = () => (dispatch, getState) => {
  const state = getState()
  const locale = state.locale
  const budgetItemType = state.filters.budgetItemType.value
  const financeType = state.filters.financeType.value
  const budgetItemIds = state.filters.budgetItems.selectedIds

  if (budgetItemIds.length === 0) {
    dispatch(setBudgetItems([]))
    return
  }

  const requiredState = [locale, budgetItemType, financeType, budgetItemIds]

  for (let i = 0; i < requiredState.length; i++) {
    if (requiredState[i].length === 0) return
  }

  dispatch(beginLoadingBudgetItems())

  georgianBudgetAPI.get(locale, 'v1', {
    params: {
      filters: {
        budgetItemType: budgetItemType,
        financeType: financeType
      },
      budgetItemIds: budgetItemIds
    }
  }).catch((error) => {
    dispatch(addBudgetItemsError(`Error communicating with API: ${error}`))
  }).then((response) => {
    dispatch(clearBudgetItemsErrors())

    if (!response || !response.data || typeof response.data !== 'object') {
      dispatch(addBudgetItemsError('Error communicating with API'))
      return
    }

    const { errors, budgetItems } = response.data

    errors.forEach((error) => {
      dispatch(addBudgetItemsError(error.text))
    })

    dispatch(setBudgetItems(budgetItems))
    dispatch(finishLoadingBudgetItems())
  })
}

const updateBudgetItemFilterOptions = () => (dispatch, getState) => {
  const state = getState()

  const locale = state.locale
  const budgetItemType = state.filters.budgetItemType.value

  const requiredState = [locale, budgetItemType]

  for (let i = 0; i < requiredState.length; i++) {
    if (requiredState[i].length === 0) return
  }

  dispatch(startLoadingBudgetItemFilter())

  georgianBudgetAPI.get(locale, 'v1', {
    params: {
      budgetItemFields: 'id,name',

      filters: {
        budgetItemType: budgetItemType
      }
    }
  }).catch((error) => {
    dispatch(addBudgetItemsError(`Error communicating with API: ${error}`))
  }).then((response) => {
    if (!response || !response.data || typeof response.data !== 'object') {
      dispatch(addBudgetItemsError('Error communicating with API'))
      return
    }

    const errors = response.data.errors
    const budgetItems = response.data.budgetItems

    if (errors && errors.length > 0) {
      errors.forEach((error) => {
        if (error.text) {
          dispatch(addBudgetItemsError(error.text))
        } else {
          dispatch(addBudgetItemsError('Error communicating with API'))
        }
      })
    }

    if (budgetItems) {
      const budgetItemFilterOptions = budgetItems.map((budgetItem) => {
        const option = {
          id: budgetItem.id,
          name: budgetItem.name
        }

        let errored = false

        if (typeof option.id !== 'number') {
          dispatch(addBudgetItemsError('Budget item does not have valid id to use as option value'))
          errored = true
        }

        if (typeof option.name !== 'string') {
          dispatch(addBudgetItemsError(`Budget item (id: ${option.name}) does not have valid name to use as option label`))
          errored = true
        }

        if (errored) return null

        return option
      }).filter((option) => option !== null && option !== undefined)

      dispatch(setBudgetItemFilterOptions(budgetItemFilterOptions))

      if (budgetItemType === 'total' && budgetItemFilterOptions.length > 0) {
        dispatch(setSelectedBudgetItemIds([budgetItemFilterOptions[0].id]))
        dispatch(updateBudgetItems())
      }

      dispatch(finishLoadingBudgetItemFilter())
    }
  })
}

module.exports = {
  updateBudgetItems,
  updateBudgetItemFilterOptions
}
<|endoftext|>


<commit_before>game.TitleScreen = me.ScreenObject.extend({
	/**
	 *  action to perform on state change
	 */
	onResetEvent: function() {
		me.game.world.addChild(new me.Sprite(0, 0, me.loader.getImage('title-screen')), -10);
		// this is showing the title screen

		me.game.world.addChild(new (me.Renderable.extend({
			init: function() {
				this._super(me.Renderable, 'init', [270, 240, 300, 50]);
				// making a call to the super function
				this.font = new me.Font("Arial", 46, "white");
				// setting a font on the screen
				me.input.registerPointerEvent("pointerdown",this, this.newGame.bind(this), true);
				// this is waiting for the mouse to be clicked to start the game
			},

            draw: function(renderer) {
				this.font.draw(renderer.getContext(), "START A NEW GAME", this.pos.x, this.pos.y);
				// when we are drawing something we are passing in the context of where we are
			},

			update: function(dt) {
				return true;
				// making sure we are listening to stuff
			},
			newGame: function() {
				console.log('new');
				me.input.releasePointerEvent('pointerdown', this);
				me.save.remove('exp');
				me.save.remove('exp1');
				me.save.remove('exp2');
				me.save.remove('exp3');
				me.save.remove('exp4');
				me.state.change(me.state.PLAY);

		}

		})));

		me.game.world.addChild(new (me.Renderable.extend({
			init: function() {
				this._super(me.Renderable, 'init', [380, 340, 250, 50]);
				// making a call to the super function
				this.font = new me.Font("Arial", 46, "white");
				// setting a font on the screen
				me.input.registerPointerEvent("pointerdown",this, this.newGame.bind(this), true);
				// this is waiting for the mouse to be clicked to start the game
			},

            draw: function(renderer) {
				this.font.draw(renderer.getContext(), "CONTINUE", this.pos.x, this.pos.y);
				// when we are drawing something we are passing in the context of where we are
			},

			update: function(dt) {
				return true;
				// making sure we are listening to stuff
			},
			newGame: function() {
				console.log("continue");
				game.data.exp = me.save.exp;
				game.data.exp1 = me.save.exp1;
				game.data.exp2 = me.save.exp2;
				game.data.exp3 = me.save.exp3;
				game.data.exp4 = me.save.exp4;
				me.input.releasePointerEvent('pointerdown', this);
				me.state.change(me.state.SPENDEXP);

		}
		// this is like adding the start a new game pointer function it just changed a few things

		})));
	  },

	/**
	 *  action to perform when leaving this screen (state change)
	 */
	onDestroyEvent: function() {
	}
});
<commit_msg>coded and commented video 43<commit_after>game.TitleScreen = me.ScreenObject.extend({
	/**
	 *  action to perform on state change
	 */
	onResetEvent: function() {
		me.game.world.addChild(new me.Sprite(0, 0, me.loader.getImage('title-screen')), -10);
		// this is showing the title screen

		me.game.world.addChild(new (me.Renderable.extend({
			init: function() {
				this._super(me.Renderable, 'init', [270, 240, 300, 50]);
				// making a call to the super function
				this.font = new me.Font("Arial", 46, "white");
				// setting a font on the screen
				me.input.registerPointerEvent("pointerdown",this, this.newGame.bind(this), true);
				// this is waiting for the mouse to be clicked to start the game
			},

            draw: function(renderer) {
				this.font.draw(renderer.getContext(), "START A NEW GAME", this.pos.x, this.pos.y);
				// when we are drawing something we are passing in the context of where we are
			},

			update: function(dt) {
				return true;
				// making sure we are listening to stuff
			},
			newGame: function() {
				console.log('new');
				me.input.releasePointerEvent('pointerdown', this);
				me.save.remove('exp');
				me.save.remove('exp1');
				me.save.remove('exp2');
				me.save.remove('exp3');
				me.save.remove('exp4');
				me.save.add({exp: 0, exp1: 0,exp: 2, exp3: 0, exp4: 0});
				me.state.change(me.state.PLAY);

		}

		})));

		me.game.world.addChild(new (me.Renderable.extend({
			init: function() {
				this._super(me.Renderable, 'init', [380, 340, 250, 50]);
				// making a call to the super function
				this.font = new me.Font("Arial", 46, "white");
				// setting a font on the screen
				me.input.registerPointerEvent("pointerdown",this, this.newGame.bind(this), true);
				// this is waiting for the mouse to be clicked to start the game
			},

            draw: function(renderer) {
				this.font.draw(renderer.getContext(), "CONTINUE", this.pos.x, this.pos.y);
				// when we are drawing something we are passing in the context of where we are
			},

			update: function(dt) {
				return true;
				// making sure we are listening to stuff
			},
			newGame: function() {
				console.log("continue");
				game.data.exp = me.save.exp;
				game.data.exp1 = me.save.exp1;
				game.data.exp2 = me.save.exp2;
				game.data.exp3 = me.save.exp3;
				game.data.exp4 = me.save.exp4;
				me.input.releasePointerEvent('pointerdown', this);
				me.state.change(me.state.SPENDEXP);

		}
		// this is like adding the start a new game pointer function it just changed a few things

		})));
	  },

	/**
	 *  action to perform when leaving this screen (state change)
	 */
	onDestroyEvent: function() {
	}
});
<|endoftext|>


<commit_before>var _ = require('underscore')
var utils = require('./utils.js')

function ascii_decode(buf) {
        return String.fromCharCode.apply(null, new Uint8Array(buf));
}

function read_uint16_LE(buffer) {
        var view = new DataView(buffer);
        var val = view.getUint8(0);
        val |= view.getUint8(1) << 8;
        return val;
}

function numpy_buffer_to_ndarray(buf) {
    var magic = ascii_decode(buf.slice(0,6));
    if (magic.slice(1,6) != 'NUMPY') {
        throw new Error('unknown file type');
    }

    var version = new Uint8Array(buf.slice(6,8));
    var headerLength = read_uint16_LE(buf.slice(8,10));
    var headerStr = ascii_decode(buf.slice(10, 10+headerLength));
    var offsetBytes = 10 + headerLength;
      //rest = buf.slice(10+headerLength);  XXX -- This makes a copy!!! https://www.khronos.org/registry/typedarray/specs/latest/#5

    var info =  JSON.parse(headerStr.toLowerCase().replace('(','[').replace(',),',']').replace('),',']').replace(/'/g,"\""));

    // Intepret the bytes according to the specified dtype
    var data;
    if (info.descr === "|u1") {
      data = new Uint8Array(buf, offsetBytes);
    } else if (info.descr === "|i1") {
      data = new Int8Array(buf, offsetBytes);
    } else if (info.descr === "<u2") {
      data = new Uint16Array(buf, offsetBytes);
    } else if (info.descr === "<i2") {
      data = new Int16Array(buf, offsetBytes);
    } else if (info.descr === "<u4") {
      data = new Uint32Array(buf, offsetBytes);
    } else if (info.descr === "<i4") {
      data = new Int32Array(buf, offsetBytes);
    } else if (info.descr === "<f4") {
      data = new Float32Array(buf, offsetBytes);
    } else if (info.descr === "<f8") {
      data = new Float64Array(buf, offsetBytes);
    } else {
      throw new Error('unknown numeric dtype')
    }

    return ndarray(data, info.shape);

}

function deserialize_array_or_json(data, manager) {
    if(data == null)
        return null;
    var arrays = null;
    if(_.isNumber(data)) {
        return data;
    } else
    if(_.isArray(data) && !data.buffer) { // plain json, or list of buffers
        if(data.length == 0) {
            arrays = []
        } else
        if(!data[0].buffer) {
            // plain json
            if(_.isArray(data[0])) {
                arrays = _.map(data, function(array1d) { return new Float32Array(array1d)})
            } else {
                arrays = [new Float32Array(data)]
            }
        } else {
            arrays = _.map(data, function(data) { return new Float32Array(data.buffer)});
        }
    } else {
        nd = numpy_buffer_to_ndarray(data.buffer)
        if (nd.shape.length == 2) {
            arrays = []
            for(var i = 0; i < nd.shape[0]; i++) {
                var ar = nd.data.slice(i*nd.stride[0], (i+1)*nd.stride[0])
                arrays.push(ar)
            }
        } else { // assume 1d... ?
            arrays = [nd.data];
        }
    }
    arrays.original_data = data;
    return arrays;
}

function deserialize_color_or_json(data, manager) {
    if(data == null)
        return null;
    var arrays = null;

    // It can deals with these 6 cases: which are threated in the same order
    // shape is 0 dim, and it's a string, interpret as color
    // shape is 1 dim, items are strings, seperate color for each item
    // shape is 2 dim, items are strings, sequence of the above
    // shape is 1 dim, items are floats, it should be of length 3 -> rgb values
    // shape is 2 dim, items are float, it should be of shape (len(x), 3) -> rgb values
    // shape is 3 dim, items are float, it should be (sequence_length, len(x), 3) -> rgb values
    function string_array_to_rgb(string_array) {
        var rgbs = new Float32Array(string_array.length * 3);
        for(var i = 0; i < string_array.length; i++) {
            var color = new THREE.Color(string_array[i]);
            rgbs[i*3+0] = color.r;
            rgbs[i*3+1] = color.g;
            rgbs[i*3+2] = color.b;
        }
        return rgbs;
    }
    function rgb_array_to_rgb(rgb_array) {
        var rgbs = new Float32Array(rgb_array.length * 3);
        for(var i = 0; i < rgb_array.length; i++) {
            rgbs[i*3+0] = rgb_array[i][0];
            rgbs[i*3+1] = rgb_array[i][1];
            rgbs[i*3+2] = rgb_array[i][2];
        }
        return rgbs;
    }

    if (typeof data == "string") { // single color
        var color = new THREE.Color(data)
        arrays = new Float32Array([color.r, color.g, color.b]) // no sequence, scalar
    } else
    if(utils.is_typedarray(data)) {
        return data
    } else
    if(_.isArray(data) && !data.buffer) { // plain json, or list of buffers
        var dimension = utils.get_array_dimension(data)
        if(dimension == 1 && typeof data[0] == "string") {
            arrays = string_array_to_rgb(data)
        } else
        if(dimension == 2 && utils.is_typedarray(data[0])) { // similar to dimension is 3 and _isNumber(data[0][0][0])
            arrays = data
        } else
        if(dimension == 2 && typeof data[0][0] == "string") {
            arrays = _.map(data, string_array_to_rgb)
        } else {
        if(dimension == 1 && _.isNumber(data[0])) {
            if(data.length != 3)
                console.error("color expected to be of length 3", data)
            arrays = new Float32Array([data[0], data[1], data[2]]) // no sequence, scalar
        } else
        if(dimension == 2 && _.isNumber(data[0][0])) {
            arrays = rgb_array_to_rgb(data)
        } else
        if(dimension == 3 && _.isNumber(data[0][0][0])) {
            arrays = _.map(data, rgb_array_to_rgb)
        } else {
            console.log("unhandled case for color")}
        }
    } else {
        var nd = numpy_buffer_to_ndarray(data.buffer)
        if(nd.shape.length == 3) { // convert to flattend list of arrays
            arrays = []
            for(var i = 0; i < nd.shape[0]; i++) {
                var ar = nd.data.slice(i*nd.stride[0], (i+1)*nd.stride[0])
                arrays.push(ar)
            }
        } else { // assume 2d... ?
            arrays = [nd.data];
        }
    }
    arrays.original_data = data;
    return arrays;
}

function serialize_array_or_json(obj, manager) {
    if(_.isNumber(obj)) return obj; // return numbers directly
    if(obj != null) {
        if(typeof obj.original_data == "undefined") // if someone modified the data from javascript land, we don't have this
            return obj
        else
            return obj.original_data; // ftm we just feed back the original data, we don't modify currently
    } else {
       return null;
    }
}

module.exports = {
      serialize_array_or_json:   serialize_array_or_json,
    deserialize_array_or_json: deserialize_array_or_json,
    deserialize_color_or_json: deserialize_color_or_json,
    array_or_json: { deserialize: deserialize_array_or_json, serialize: serialize_array_or_json },
    color_or_json: { deserialize: deserialize_color_or_json, serialize: serialize_array_or_json }
}<commit_msg>fix: we need THREE in the namespace for color parsing<commit_after>var _ = require('underscore')
var utils = require('./utils.js')
var THREE = require('three')

function ascii_decode(buf) {
        return String.fromCharCode.apply(null, new Uint8Array(buf));
}

function read_uint16_LE(buffer) {
        var view = new DataView(buffer);
        var val = view.getUint8(0);
        val |= view.getUint8(1) << 8;
        return val;
}

function numpy_buffer_to_ndarray(buf) {
    var magic = ascii_decode(buf.slice(0,6));
    if (magic.slice(1,6) != 'NUMPY') {
        throw new Error('unknown file type');
    }

    var version = new Uint8Array(buf.slice(6,8));
    var headerLength = read_uint16_LE(buf.slice(8,10));
    var headerStr = ascii_decode(buf.slice(10, 10+headerLength));
    var offsetBytes = 10 + headerLength;
      //rest = buf.slice(10+headerLength);  XXX -- This makes a copy!!! https://www.khronos.org/registry/typedarray/specs/latest/#5

    var info =  JSON.parse(headerStr.toLowerCase().replace('(','[').replace(',),',']').replace('),',']').replace(/'/g,"\""));

    // Intepret the bytes according to the specified dtype
    var data;
    if (info.descr === "|u1") {
      data = new Uint8Array(buf, offsetBytes);
    } else if (info.descr === "|i1") {
      data = new Int8Array(buf, offsetBytes);
    } else if (info.descr === "<u2") {
      data = new Uint16Array(buf, offsetBytes);
    } else if (info.descr === "<i2") {
      data = new Int16Array(buf, offsetBytes);
    } else if (info.descr === "<u4") {
      data = new Uint32Array(buf, offsetBytes);
    } else if (info.descr === "<i4") {
      data = new Int32Array(buf, offsetBytes);
    } else if (info.descr === "<f4") {
      data = new Float32Array(buf, offsetBytes);
    } else if (info.descr === "<f8") {
      data = new Float64Array(buf, offsetBytes);
    } else {
      throw new Error('unknown numeric dtype')
    }

    return ndarray(data, info.shape);

}

function deserialize_array_or_json(data, manager) {
    if(data == null)
        return null;
    var arrays = null;
    if(_.isNumber(data)) {
        return data;
    } else
    if(_.isArray(data) && !data.buffer) { // plain json, or list of buffers
        if(data.length == 0) {
            arrays = []
        } else
        if(!data[0].buffer) {
            // plain json
            if(_.isArray(data[0])) {
                arrays = _.map(data, function(array1d) { return new Float32Array(array1d)})
            } else {
                arrays = [new Float32Array(data)]
            }
        } else {
            arrays = _.map(data, function(data) { return new Float32Array(data.buffer)});
        }
    } else {
        nd = numpy_buffer_to_ndarray(data.buffer)
        if (nd.shape.length == 2) {
            arrays = []
            for(var i = 0; i < nd.shape[0]; i++) {
                var ar = nd.data.slice(i*nd.stride[0], (i+1)*nd.stride[0])
                arrays.push(ar)
            }
        } else { // assume 1d... ?
            arrays = [nd.data];
        }
    }
    arrays.original_data = data;
    return arrays;
}

function deserialize_color_or_json(data, manager) {
    if(data == null)
        return null;
    var arrays = null;

    // It can deals with these 6 cases: which are threated in the same order
    // shape is 0 dim, and it's a string, interpret as color
    // shape is 1 dim, items are strings, seperate color for each item
    // shape is 2 dim, items are strings, sequence of the above
    // shape is 1 dim, items are floats, it should be of length 3 -> rgb values
    // shape is 2 dim, items are float, it should be of shape (len(x), 3) -> rgb values
    // shape is 3 dim, items are float, it should be (sequence_length, len(x), 3) -> rgb values
    function string_array_to_rgb(string_array) {
        var rgbs = new Float32Array(string_array.length * 3);
        for(var i = 0; i < string_array.length; i++) {
            var color = new THREE.Color(string_array[i]);
            rgbs[i*3+0] = color.r;
            rgbs[i*3+1] = color.g;
            rgbs[i*3+2] = color.b;
        }
        return rgbs;
    }
    function rgb_array_to_rgb(rgb_array) {
        var rgbs = new Float32Array(rgb_array.length * 3);
        for(var i = 0; i < rgb_array.length; i++) {
            rgbs[i*3+0] = rgb_array[i][0];
            rgbs[i*3+1] = rgb_array[i][1];
            rgbs[i*3+2] = rgb_array[i][2];
        }
        return rgbs;
    }

    if (typeof data == "string") { // single color
        var color = new THREE.Color(data)
        arrays = new Float32Array([color.r, color.g, color.b]) // no sequence, scalar
    } else
    if(utils.is_typedarray(data)) {
        return data
    } else
    if(_.isArray(data) && !data.buffer) { // plain json, or list of buffers
        var dimension = utils.get_array_dimension(data)
        if(dimension == 1 && typeof data[0] == "string") {
            arrays = string_array_to_rgb(data)
        } else
        if(dimension == 2 && utils.is_typedarray(data[0])) { // similar to dimension is 3 and _isNumber(data[0][0][0])
            arrays = data
        } else
        if(dimension == 2 && typeof data[0][0] == "string") {
            arrays = _.map(data, string_array_to_rgb)
        } else {
        if(dimension == 1 && _.isNumber(data[0])) {
            if(data.length != 3)
                console.error("color expected to be of length 3", data)
            arrays = new Float32Array([data[0], data[1], data[2]]) // no sequence, scalar
        } else
        if(dimension == 2 && _.isNumber(data[0][0])) {
            arrays = rgb_array_to_rgb(data)
        } else
        if(dimension == 3 && _.isNumber(data[0][0][0])) {
            arrays = _.map(data, rgb_array_to_rgb)
        } else {
            console.log("unhandled case for color")}
        }
    } else {
        var nd = numpy_buffer_to_ndarray(data.buffer)
        if(nd.shape.length == 3) { // convert to flattend list of arrays
            arrays = []
            for(var i = 0; i < nd.shape[0]; i++) {
                var ar = nd.data.slice(i*nd.stride[0], (i+1)*nd.stride[0])
                arrays.push(ar)
            }
        } else { // assume 2d... ?
            arrays = [nd.data];
        }
    }
    arrays.original_data = data;
    return arrays;
}

function serialize_array_or_json(obj, manager) {
    if(_.isNumber(obj)) return obj; // return numbers directly
    if(obj != null) {
        if(typeof obj.original_data == "undefined") // if someone modified the data from javascript land, we don't have this
            return obj
        else
            return obj.original_data; // ftm we just feed back the original data, we don't modify currently
    } else {
       return null;
    }
}

module.exports = {
      serialize_array_or_json:   serialize_array_or_json,
    deserialize_array_or_json: deserialize_array_or_json,
    deserialize_color_or_json: deserialize_color_or_json,
    array_or_json: { deserialize: deserialize_array_or_json, serialize: serialize_array_or_json },
    color_or_json: { deserialize: deserialize_color_or_json, serialize: serialize_array_or_json }
}<|endoftext|>


<commit_before>$.get("https://api.stackexchange.com/2.2/users/1163298/associated", function(data) {
	rep = 0;

	for( i = 0; i < data.items.length; i++ ) {
		if( data.items[i].reputation > 200 ) {
			rep += data.items[i].reputation;
		}
	}

	rep = (rep + '').replace(/(\d)(?=(\d{3})+$)/g, '$1,');
	$("#reputation").text(rep);
});<commit_msg>Added 'Reputation' label to the stackexchange card.<commit_after>$.get("https://api.stackexchange.com/2.2/users/1163298/associated", function(data) {
	rep = 0;

	for( i = 0; i < data.items.length; i++ ) {
		if( data.items[i].reputation > 200 ) {
			rep += data.items[i].reputation;
		}
	}

	rep = (rep + '').replace(/(\d)(?=(\d{3})+$)/g, '$1,');
	$("#reputation").text('Reputation: ' + rep);
});<|endoftext|>


<commit_before>// Copyright 2016, University of Colorado Boulder

/**
 *
 * @author Sam Reid (PhET Interactive Simulations)
 * @author Andrew Adare
 */
define( function( require ) {
  'use strict';

  // modules
  var assertTypeOf = require( 'PHET_IO/assertions/assertTypeOf' );
  var phetioNamespace = require( 'PHET_IO/phetioNamespace' );
  var phetioInherit = require( 'PHET_IO/phetioInherit' );
  var TObject = require( 'PHET_IO/types/TObject' );

  var validUnits = [
    'amperes',
    'becquerels',
    'centimeters',
    'coulombs',
    'degrees Celsius',
    'farads',
    'grams',
    'gray',
    'henrys',
    'henries',
    'hertz',
    'joules',
    'katals',
    'kelvins',
    'liters',
    'liters/second',
    'lumens',
    'lux',
    'meters',
    'moles',
    'moles/liter',
    'nanometers',
    'newtons',
    'ohms',
    'pascals',
    'percent',
    'radians',
    'seconds',
    'siemens',
    'sieverts',
    'steradians',
    'tesla',
    'unitless',
    'volts',
    'watts',
    'webers'
  ];

  var TNumber = function( units, options ) {
    assert && assert( units, 'All TNumbers should specify units' );
    assert && assert( validUnits.indexOf( units ) >= 0, units + ' is not recognized as a valid unit of measurement' );

    options = _.extend( {
        type: 'FloatingPoint', // either 'FloatingPoint' | 'Integer'
        min: -Infinity, // TODO: remove min and max in favor of keeping range only
        max: Infinity,
        range: new Range( -Infinity, Infinity ), // No defaultValue
        stepSize: null, // This will be used for slider increments
        values: null // null | {Number[]} if it can only take certain possible values, specify them here, like [0,2,8]
                     // TODO: enforce that values is of Array type
      },
      options
    );

    return phetioInherit( TObject, 'TNumber(' + units + ')', function( instance, phetioID ) {
      TObject.call( this, instance, phetioID );
      assertTypeOf( instance, 'number' );
    }, {}, {
      units: units,
      type: options.type,
      min: options.range.min,
      max: options.range.max,
      values: options.values,
      stepSize: options.stepSize,
      defaultValue: options.range.defaultValue,
      documentation: 'Wrapper for the built-in JS number type (floating point, but also represents integers)',

      fromStateObject: function( stateObject ) {
        return stateObject;
      },

      toStateObject: function( value ) {
        return value;
      }
    } );
  };

  phetioNamespace.register( 'TNumber', TNumber );

  return TNumber;
} );
<commit_msg>Reverted to 9a49a6f7e6dbdad6d07ab6850847a9d254eeccb6<commit_after>// Copyright 2016, University of Colorado Boulder

/**
 *
 * @author Sam Reid (PhET Interactive Simulations)
 * @author Andrew Adare
 */
define( function( require ) {
  'use strict';

  // modules
  var assertTypeOf = require( 'PHET_IO/assertions/assertTypeOf' );
  var phetioNamespace = require( 'PHET_IO/phetioNamespace' );
  var phetioInherit = require( 'PHET_IO/phetioInherit' );
  var TObject = require( 'PHET_IO/types/TObject' );

  var validUnits = [
    'amperes',
    'becquerels',
    'centimeters',
    'coulombs',
    'degrees Celsius',
    'farads',
    'grams',
    'gray',
    'henrys',
    'henries',
    'hertz',
    'joules',
    'katals',
    'kelvins',
    'liters',
    'liters/second',
    'lumens',
    'lux',
    'meters',
    'moles',
    'moles/liter',
    'nanometers',
    'newtons',
    'ohms',
    'pascals',
    'percent',
    'radians',
    'seconds',
    'siemens',
    'sieverts',
    'steradians',
    'tesla',
    'unitless',
    'volts',
    'watts',
    'webers'
  ];

  var TNumber = function( units, options ) {
    assert && assert( units, 'All TNumbers should specify units' );
    assert && assert( validUnits.indexOf( units ) >= 0, units + ' is not recognized as a valid unit of measurement' );

    options = _.extend( {
        type: 'FloatingPoint', // either 'FloatingPoint' | 'Integer'
        min: -Infinity,
        max: Infinity,
        values: null // null | {Number[]} if it can only take certain possible values, specify them here, like [0,2,8]
      },
      options
    );
    return phetioInherit( TObject, 'TNumber(' + units + ')', function( instance, phetioID ) {
      TObject.call( this, instance, phetioID );
      assertTypeOf( instance, 'number' );
    }, {}, {
      units: units,
      type: options.type,
      min: options.min,
      max: options.max,
      values: options.values,
      documentation: 'Wrapper for the built-in JS number type (floating point, but also represents integers)',

      fromStateObject: function( stateObject ) {
        return stateObject;
      },

      toStateObject: function( value ) {
        return value;
      }
    } );
  };

  phetioNamespace.register( 'TNumber', TNumber );

  return TNumber;
} );
<|endoftext|>