<commit_before>import React from "react";
import classnames from "classnames";

let cursorX;
let cursorY;
window.document.addEventListener("mousemove", e => {
  cursorX = e.pageX;
  cursorY = e.pageY;
});

// We implement hover ourselves, because we hate ourselves and https://stackoverflow.com/a/13259049/1263117
class Entry extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hover: false };
  }

  componentDidMount() {
    const domRect = this.node.getBoundingClientRect();
    this.setState({
      hover:
        cursorX >= domRect.left &&
        cursorX <= domRect.right &&
        cursorY >= domRect.top &&
        cursorY <= domRect.bottom
    });
  }

  render() {
    return (

 (this.node = node)}
        onMouseEnter={() => this.setState({ hover: true })}
        onMouseLeave={() => this.setState({ hover: false })}
        className={classnames({ hover: this.state.hover })}
      >
        {this.props.children}

    );
  }
}

export default class PlaylistMenu extends React.Component {
  constructor(props) {
    super(props);
    this.state = { selected: false };
    this._handleClick = this._handleClick.bind(this);
  }

  _handleClick(e) {
    const { target } = e;
    const { selected } = this.state;
    if (selected) {
      this.setState({ selected: false });
      return;
    }
    this.setState({ selected: true });

    const handleClickOut = ee => {
      if (!target.contains(ee.target)) {
        this.setState({ selected: false });
        ee.stopPropagation();
      }
      window.document.removeEventListener("click", handleClickOut, {
        capture: true
      });
    };
    window.document.addEventListener("click", handleClickOut, {
      capture: true
    });
  }

  render() {
    return (

        {this.state.selected && (

            {React.Children.map(this.props.children, (child, i) => (
              <Entry key={i}>{child}</Entry>
            ))}

        )}

    );
  }
}
<commit_msg>Fix issue with context menus inside playlist menus<commit_after>import React from "react";
import classnames from "classnames";

let cursorX;
let cursorY;
window.document.addEventListener("mousemove", e => {
  cursorX = e.pageX;
  cursorY = e.pageY;
});

// We implement hover ourselves, because we hate ourselves and https://stackoverflow.com/a/13259049/1263117
class Entry extends React.Component {
  constructor(props) {
    super(props);
    this.state = { hover: false };
  }

  componentDidMount() {
    const domRect = this.node.getBoundingClientRect();
    this.setState({
      hover:
        cursorX >= domRect.left &&
        cursorX <= domRect.right &&
        cursorY >= domRect.top &&
        cursorY <= domRect.bottom
    });
  }

  render() {
    return (

 (this.node = node)}
        onMouseEnter={() => this.setState({ hover: true })}
        onMouseLeave={() => this.setState({ hover: false })}
        className={classnames({ hover: this.state.hover })}
      >
        {this.props.children}

    );
  }
}

export default class PlaylistMenu extends React.Component {
  constructor(props) {
    super(props);
    this.state = { selected: false };
    this._handleClick = this._handleClick.bind(this);
  }

  _handleClick(e) {
    const { target } = e;
    const { selected } = this.state;
    if (selected) {
      this.setState({ selected: false });
      return;
    }

    const handleClickOut = ee => {
      // If the click is _not_ inside the menu.
      if (!target.contains(ee.target)) {
        // If we've clicked on a Context Menu spawed inside this menu, it will
        // register as an external click. However, hiding the menu will remove
        // the Context Menu from the DOM. Therefore, we wait until the next
        // event loop to actually hide ourselves.
        setTimeout(() => {
          // Close the menu
          this.setState({ selected: false });
        }, 0);
        window.document.removeEventListener("click", handleClickOut, {
          capture: true
        });
      }
    };
    window.document.addEventListener("click", handleClickOut, {
      capture: true
    });

    this.setState({ selected: true });
  }

  render() {
    return (

        {this.state.selected && (

            {React.Children.map(this.props.children, (child, i) => (
              <Entry key={i}>{child}</Entry>
            ))}

        )}

    );
  }
}
<|endoftext|>


<commit_before>$(function(){
	function getFiveProducts() {
		$.ajax({
			url: "/getProducts",
			type: "GET",
			dataType:"json",
			success: function(data) {
				$.each(data, function(i, article){
					var divArticle = $("<div/>", {class:"article"});
					divArticle.append($("<p/>", {class:"article_name"}).append(article.name));
					divArticle.append($("<img/>", {class:"article_url"}).attr("src", article.url));
					divArticle.appendTo($(document.body));
					//au clic sur un article changement de style
					divArticle.on("click", function() {
						$(this).addClass("activity");
					});
				});
			}
		});
	}
	getFiveProducts();
});<commit_msg>amélioration changement de style à la séléction d'un produit<commit_after>$(function(){
	function getFiveProducts() {
		$.ajax({
			url: "/getProducts",
			type: "GET",
			dataType:"json",
			success: function(data) {
				$.each(data, function(i, article){
					var divArticle = $("<div/>", {class:"article"});
					divArticle.append($("<p/>", {class:"article_name"}).append(article.name));
					divArticle.append($("<img/>", {class:"article_url"}).attr("src", article.url));
					divArticle.appendTo($(document.body));
					//au clic sur un article changement de style
					divArticle.on("click", function() {
						$(".article.activity").removeClass("activity");
						$(this).addClass("activity");
					});
				});
			}
		});
	}
	getFiveProducts();
});<|endoftext|>


<commit_before>goog.provide('ol.renderer.Map');

goog.require('goog.Disposable');
goog.require('goog.asserts');
goog.require('goog.dispose');
goog.require('goog.object');
goog.require('goog.vec.Mat4');
goog.require('ol.FrameState');
goog.require('ol.layer.Layer');
goog.require('ol.renderer.Layer');
goog.require('ol.vec.Mat4');

/**
 * @constructor
 * @extends {goog.Disposable}
 * @param {Element} container Container.
 * @param {ol.Map} map Map.
 */
ol.renderer.Map = function(container, map) {

  goog.base(this);

  /**
   * @private
   * @type {ol.Map}
   */
  this.map_ = map;

  /**
   * @private
   * @type {Object.<string, ol.renderer.Layer>}
   */
  this.layerRenderers_ = {};

};
goog.inherits(ol.renderer.Map, goog.Disposable);

/**
 * @param {ol.FrameState} frameState FrameState.
 * @protected
 */
ol.renderer.Map.prototype.calculateMatrices2D = function(frameState) {
  var view2DState = frameState.view2DState;
  var coordinateToPixelMatrix = frameState.coordinateToPixelMatrix;
  goog.asserts.assert(!goog.isNull(coordinateToPixelMatrix));
  ol.vec.Mat4.makeTransform2D(coordinateToPixelMatrix,
      frameState.size[0] / 2, frameState.size[1] / 2,
      1 / view2DState.resolution, -1 / view2DState.resolution,
      -view2DState.rotation,
      -view2DState.center[0], -view2DState.center[1]);
  var inverted = goog.vec.Mat4.invert(
      coordinateToPixelMatrix, frameState.pixelToCoordinateMatrix);
  goog.asserts.assert(inverted);
};

/**
 * @param {ol.layer.Layer} layer Layer.
 * @protected
 * @return {ol.renderer.Layer} layerRenderer Layer renderer.
 */
ol.renderer.Map.prototype.createLayerRenderer = function(layer) {
  return new ol.renderer.Layer(this, layer);
};

/**
 * @inheritDoc
 */
ol.renderer.Map.prototype.disposeInternal = function() {
  goog.object.forEach(this.layerRenderers_, function(layerRenderer) {
    goog.dispose(layerRenderer);
  });
  goog.base(this, 'disposeInternal');
};

/**
 * @param {ol.Pixel} pixel Pixel.
 * @param {function(this: S, ol.Feature, ol.layer.Layer): T} callback Feature
 *     callback.
 * @param {S=} opt_obj Scope for feature callback.
 * @param {function(this: U, ol.layer.Layer): boolean=} opt_layerFunction Layer
 *     function.
 * @param {U=} opt_obj2 Scope for layer function.
 * @return {T|undefined} Callback result.
 * @template S,T,U
 */
ol.renderer.Map.prototype.forEachFeatureAtPixel =
    function(pixel, callback, opt_obj, opt_layerFunction, opt_obj2) {
  var layerFunction = goog.isDef(opt_layerFunction) ?
      opt_layerFunction : goog.functions.TRUE;
  var layers = this.map_.getLayers();
  if (goog.isDef(layers)) {
    var layersArray = layers.getArray();
    var i;
    for (i = layersArray.length - 1; i >= 0; --i) {
      var layer = layersArray[i];
      if (layer.getVisible() && layerFunction.call(opt_obj2, layer)) {
        var layerRenderer = this.getLayerRenderer(layer);
        var result =
            layerRenderer.forEachFeatureAtPixel(pixel, callback, opt_obj);
        if (result) {
          return result;
        }
      }
    }
  }
  return undefined;
};

/**
 * @param {ol.layer.Layer} layer Layer.
 * @protected
 * @return {ol.renderer.Layer} Layer renderer.
 */
ol.renderer.Map.prototype.getLayerRenderer = function(layer) {
  var layerKey = goog.getUid(layer).toString();
  if (layerKey in this.layerRenderers_) {
    return this.layerRenderers_[layerKey];
  } else {
    var layerRenderer = this.createLayerRenderer(layer);
    this.layerRenderers_[layerKey] = layerRenderer;
    return layerRenderer;
  }
};

/**
 * @param {string} layerKey Layer key.
 * @protected
 * @return {ol.renderer.Layer} Layer renderer.
 */
ol.renderer.Map.prototype.getLayerRendererByKey = function(layerKey) {
  goog.asserts.assert(layerKey in this.layerRenderers_);
  return this.layerRenderers_[layerKey];
};

/**
 * @protected
 * @return {Object.<number, ol.renderer.Layer>} Layer renderers.
 */
ol.renderer.Map.prototype.getLayerRenderers = function() {
  return this.layerRenderers_;
};

/**
 * @return {ol.Map} Map.
 */
ol.renderer.Map.prototype.getMap = function() {
  return this.map_;
};

/**
 * @param {string} layerKey Layer key.
 * @return {ol.renderer.Layer} Layer renderer.
 * @private
 */
ol.renderer.Map.prototype.removeLayerRendererByKey_ = function(layerKey) {
  goog.asserts.assert(layerKey in this.layerRenderers_);
  var layerRenderer = this.layerRenderers_[layerKey];
  delete this.layerRenderers_[layerKey];
  return layerRenderer;
};

/**
 * Render.
 * @param {?ol.FrameState} frameState Frame state.
 */
ol.renderer.Map.prototype.renderFrame = goog.nullFunction;

/**
 * @param {ol.Map} map Map.
 * @param {ol.FrameState} frameState Frame state.
 * @private
 */
ol.renderer.Map.prototype.removeUnusedLayerRenderers_ =
    function(map, frameState) {
  var layerKey;
  for (layerKey in this.layerRenderers_) {
    if (goog.isNull(frameState) || !(layerKey in frameState.layerStates)) {
      goog.dispose(this.removeLayerRendererByKey_(layerKey));
    }
  }
};

/**
 * @param {!ol.FrameState} frameState Frame state.
 * @protected
 */
ol.renderer.Map.prototype.scheduleRemoveUnusedLayerRenderers =
    function(frameState) {
  var layerKey;
  for (layerKey in this.layerRenderers_) {
    if (!(layerKey in frameState.layerStates)) {
      frameState.postRenderFunctions.push(
          goog.bind(this.removeUnusedLayerRenderers_, this));
      return;
    }
  }
};
<commit_msg>Make forEachFeatureAtPixel work with layer groups<commit_after>goog.provide('ol.renderer.Map');

goog.require('goog.Disposable');
goog.require('goog.asserts');
goog.require('goog.dispose');
goog.require('goog.object');
goog.require('goog.vec.Mat4');
goog.require('ol.FrameState');
goog.require('ol.layer.Layer');
goog.require('ol.renderer.Layer');
goog.require('ol.vec.Mat4');

/**
 * @constructor
 * @extends {goog.Disposable}
 * @param {Element} container Container.
 * @param {ol.Map} map Map.
 */
ol.renderer.Map = function(container, map) {

  goog.base(this);

  /**
   * @private
   * @type {ol.Map}
   */
  this.map_ = map;

  /**
   * @private
   * @type {Object.<string, ol.renderer.Layer>}
   */
  this.layerRenderers_ = {};

};
goog.inherits(ol.renderer.Map, goog.Disposable);

/**
 * @param {ol.FrameState} frameState FrameState.
 * @protected
 */
ol.renderer.Map.prototype.calculateMatrices2D = function(frameState) {
  var view2DState = frameState.view2DState;
  var coordinateToPixelMatrix = frameState.coordinateToPixelMatrix;
  goog.asserts.assert(!goog.isNull(coordinateToPixelMatrix));
  ol.vec.Mat4.makeTransform2D(coordinateToPixelMatrix,
      frameState.size[0] / 2, frameState.size[1] / 2,
      1 / view2DState.resolution, -1 / view2DState.resolution,
      -view2DState.rotation,
      -view2DState.center[0], -view2DState.center[1]);
  var inverted = goog.vec.Mat4.invert(
      coordinateToPixelMatrix, frameState.pixelToCoordinateMatrix);
  goog.asserts.assert(inverted);
};

/**
 * @param {ol.layer.Layer} layer Layer.
 * @protected
 * @return {ol.renderer.Layer} layerRenderer Layer renderer.
 */
ol.renderer.Map.prototype.createLayerRenderer = function(layer) {
  return new ol.renderer.Layer(this, layer);
};

/**
 * @inheritDoc
 */
ol.renderer.Map.prototype.disposeInternal = function() {
  goog.object.forEach(this.layerRenderers_, function(layerRenderer) {
    goog.dispose(layerRenderer);
  });
  goog.base(this, 'disposeInternal');
};

/**
 * @param {ol.Pixel} pixel Pixel.
 * @param {function(this: S, ol.Feature, ol.layer.Layer): T} callback Feature
 *     callback.
 * @param {S=} opt_obj Scope for feature callback.
 * @param {function(this: U, ol.layer.Layer): boolean=} opt_layerFunction Layer
 *     function.
 * @param {U=} opt_obj2 Scope for layer function.
 * @return {T|undefined} Callback result.
 * @template S,T,U
 */
ol.renderer.Map.prototype.forEachFeatureAtPixel =
    function(pixel, callback, opt_obj, opt_layerFunction, opt_obj2) {
  var layerFunction = goog.isDef(opt_layerFunction) ?
      opt_layerFunction : goog.functions.TRUE;
  var layersArray = this.map_.getLayerGroup().getLayersArray();
  var i;
  for (i = layersArray.length - 1; i >= 0; --i) {
    var layer = layersArray[i];
    if (layer.getVisible() && layerFunction.call(opt_obj2, layer)) {
      var layerRenderer = this.getLayerRenderer(layer);
      var result =
          layerRenderer.forEachFeatureAtPixel(pixel, callback, opt_obj);
      if (result) {
        return result;
      }
    }
  }
  return undefined;
};

/**
 * @param {ol.layer.Layer} layer Layer.
 * @protected
 * @return {ol.renderer.Layer} Layer renderer.
 */
ol.renderer.Map.prototype.getLayerRenderer = function(layer) {
  var layerKey = goog.getUid(layer).toString();
  if (layerKey in this.layerRenderers_) {
    return this.layerRenderers_[layerKey];
  } else {
    var layerRenderer = this.createLayerRenderer(layer);
    this.layerRenderers_[layerKey] = layerRenderer;
    return layerRenderer;
  }
};

/**
 * @param {string} layerKey Layer key.
 * @protected
 * @return {ol.renderer.Layer} Layer renderer.
 */
ol.renderer.Map.prototype.getLayerRendererByKey = function(layerKey) {
  goog.asserts.assert(layerKey in this.layerRenderers_);
  return this.layerRenderers_[layerKey];
};

/**
 * @protected
 * @return {Object.<number, ol.renderer.Layer>} Layer renderers.
 */
ol.renderer.Map.prototype.getLayerRenderers = function() {
  return this.layerRenderers_;
};

/**
 * @return {ol.Map} Map.
 */
ol.renderer.Map.prototype.getMap = function() {
  return this.map_;
};

/**
 * @param {string} layerKey Layer key.
 * @return {ol.renderer.Layer} Layer renderer.
 * @private
 */
ol.renderer.Map.prototype.removeLayerRendererByKey_ = function(layerKey) {
  goog.asserts.assert(layerKey in this.layerRenderers_);
  var layerRenderer = this.layerRenderers_[layerKey];
  delete this.layerRenderers_[layerKey];
  return layerRenderer;
};

/**
 * Render.
 * @param {?ol.FrameState} frameState Frame state.
 */
ol.renderer.Map.prototype.renderFrame = goog.nullFunction;

/**
 * @param {ol.Map} map Map.
 * @param {ol.FrameState} frameState Frame state.
 * @private
 */
ol.renderer.Map.prototype.removeUnusedLayerRenderers_ =
    function(map, frameState) {
  var layerKey;
  for (layerKey in this.layerRenderers_) {
    if (goog.isNull(frameState) || !(layerKey in frameState.layerStates)) {
      goog.dispose(this.removeLayerRendererByKey_(layerKey));
    }
  }
};

/**
 * @param {!ol.FrameState} frameState Frame state.
 * @protected
 */
ol.renderer.Map.prototype.scheduleRemoveUnusedLayerRenderers =
    function(frameState) {
  var layerKey;
  for (layerKey in this.layerRenderers_) {
    if (!(layerKey in frameState.layerStates)) {
      frameState.postRenderFunctions.push(
          goog.bind(this.removeUnusedLayerRenderers_, this));
      return;
    }
  }
};
<|endoftext|>


<commit_before>document.documentElement.style.height = '100%';
document.body.style.height = '100%';
document.documentElement.style.width = '100%';
document.body.style.width = '100%';

var div = document.createElement('div');
div.style.height = '100%';
div.style.float = 'right';
div.style.width = '30%';
div.style.backgroundColor = 'snow';
div.style.position = 'relative';
div.style.zIndex = '1000';
var ul = document.createElement('ul');
document.body.appendChild(div);
div.appendChild(ul);

function startQuery(quer){
  var searchUrl = 'https://api.wolframalpha.com/v2/query' + '?appid=' + encodeURIComponent(appID) +
  '&input=' + quer + '&format=plaintext&output=JSON';
  var x = new XMLHttpRequest();
  //  x.responseType = 'json';
  x.onload = pareseResponse(x)
  x.onerror = function(err) {
    console.log(err);
  };
  x.open('GET', searchUrl, true);
  x.send();
}

function pareseResponse(x){
  var response = JSON.parse(x.response);
  console.log(response);
  if (!response || !response["queryresult"]["success"] || response["queryresult"]["error"] ){
    console.log('Invalid search to Wolfram');
    return;
  }
  var importantTitle = {"definition":null, "definitions":null, "synonym":null, "synonyms":null, "antonym":null, "antonyms":null,
                        "pronounciation":null, "image":null, "basic movie information":null, "cast":null, "wikipedia summary":null,
                        "basic series information":null, "latest trade":null, "chemical names and formulas":null,
                        "administrative regions": null, "current weather":null, "unit conversions":null, "basic information":null,
                        "notable facts":null, "location and owner":null, "basic properties":null};
  var importantIDs = {"observancedate (country)":null, "notableeventfordate":null};

  var pods = response["queryresult"]["pods"];
  console.log(pods);

  for(i = 0; i < pods.length; i++) {
    lowercase = pods[i].title.toLowerCase();
    if(lowercase === "wikipedia summary"){
      importantTitle[lowercase] = getWikipediaSummary(quer);
    }
    else if(lowercase in importantTitle){
      importantTitle[lowercase] = pods[i].subpods[0].plaintext;
    }
    else if(lowercase in importantIDs){
      importantIDs[lowercase] = pods[i].subpods[0].plaintext;
    }
  };
}

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  console.log("Message recieved");
  if(request.message === "open_sidebar"){
    console.log("Selection event. Looking up: " + request.content);
    startQuery(request.content);
    return true;
  }});
<commit_msg>Added a better format, only printing certain items<commit_after>document.documentElement.style.height = '100%';
document.body.style.height = '100%';
document.documentElement.style.width = '100%';
document.body.style.width = '100%';

var div = document.createElement('div');
div.style.height = '100%';
div.style.float = 'right';
div.style.width = '30%';
div.style.backgroundColor = 'snow';
div.style.position = 'relative';
div.style.zIndex = '1000';
var ul = document.createElement('ul');
document.body.appendChild(div);
div.appendChild(ul);

function startQuery(quer){
  var searchUrl = 'https://api.wolframalpha.com/v2/query' + '?appid=' + encodeURIComponent(appID) +
  '&input=' + quer + '&format=plaintext&output=JSON';
  var x = new XMLHttpRequest();
  //  x.responseType = 'json';
  x.onload = function(){
    parseResponse(x.response);
  }
  x.onerror = function(err) {
    console.log(err);
  };
  x.open('GET', searchUrl, true);
  x.send();
}

function parseResponse(respond){
  var response = JSON.parse(respond);
  console.log(response);
  if (!response || !response["queryresult"]["success"] || response["queryresult"]["error"] ){
    console.log('Invalid search to Wolfram');
    return;
  }
  var importantTitle = {"definition":null, "definitions":null, "synonym":null, "synonyms":null, "antonym":null, "antonyms":null,
                        "pronounciation":null, "image":null, "basic movie information":null, "cast":null, "wikipedia summary":null,
                        "basic series information":null, "latest trade":null, "chemical names and formulas":null,
                        "administrative regions": null, "current weather":null, "unit conversions":null, "basic information":null,
                        "notable facts":null, "location and owner":null, "basic properties":null};
  var importantIDs = {"observancedate (country)":null, "notableeventfordate":null};

  var pods = response["queryresult"]["pods"];
  console.log(pods);

  for(i = 0; i < pods.length; i++) {
    lowercase = pods[i].title.toLowerCase();
    if(lowercase === "wikipedia summary"){
      importantTitle[lowercase] = getWikipediaSummary(quer);
    }
    else if(lowercase in importantTitle){
      importantTitle[lowercase] = pods[i].subpods[0].plaintext;
    }
    else if(lowercase in importantIDs){
      importantIDs[lowercase] = pods[i].subpods[0].plaintext;
    }
  };
  for(var key in importantTitle){
    if(importantTitle.hasOwnProperty(key) && importantTitle[key] !== null){
      var li = document.createElement("li");
      li.innerHTML = "
" + toTitleCase(key) + "

" + importantTitle[key];
      ul.appendChild(li);
    }
  }
  for(var key in importantIDs){
    if(importantIDs.hasOwnProperty(key) && importantIDs[key] !== null){
      var li = document.createElement("li");
      li.innerHTML = "
" + toTitleCase(key) + "

" + importantIDs[key];
      ul.appendChild(li);
    }
  }
}

function toTitleCase(str)
{
    return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
}

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  console.log("Message recieved");
  if(request.message === "open_sidebar"){
    console.log("Selection event. Looking up: " + request.content);
    startQuery(request.content);
    return true;
  }});
<|endoftext|>


<commit_before>'use strict';

/* https://github.com/angular/protractor/blob/master/docs/toc.md */

describe('my app', function() {

  it('should automatically redirect to / when location hash/fragment is empty', function() {
    browser.get('index.html');
    expect(browser.getLocationAbsUrl()).toMatch("/");
  });

  describe('index', function() {

    beforeEach(function() {
      browser.get('index.html#/');
    });

    it('should render index when user navigates to /', function() {
      expect(element.all(by.css('[ui-view] .main-view .header .changelist')).first().getText()).
        toMatch(/Changelist/);
    });

  });
});
<commit_msg>Fix e2e tests<commit_after>'use strict';

/* https://github.com/angular/protractor/blob/master/docs/toc.md */

describe('my app', function() {

  it('should automatically redirect to / when location hash/fragment is empty', function() {
    browser.get('/');
    expect(browser.getLocationAbsUrl()).toMatch("/");
  });

  describe('index', function() {

    beforeEach(function() {
      browser.get('#/');
    });

    it('should render index when user navigates to /', function() {
      expect(element.all(by.css('[ui-view] .main-view .header .changelist')).first().getText()).
        toMatch(/Changelist/);
    });

  });
});
<|endoftext|>


<commit_before>var EventEmitter = require('events').EventEmitter;
var emitStream = require('emit-stream');

function emitter(stream) {
  // Read events from the client
  var readEmitter = emitStream.fromStream(stream);

  stream.on('error', function(err) {
    readEmitter.emit('error', err);
  });

  // Write events to the client
  var writeEmitter = new EventEmitter;
  var writeStream = emitStream.toStream(writeEmitter);

  writeStream.on('error', function(err) {
    readEmitter.emit('error', err);
  });

  writeStream.pipe(stream);

  var on = readEmitter.on.bind(readEmitter);

  return {
    on: on,
    addListener: on,
    once: readEmitter.once.bind(readEmitter),
    removeListener: readEmitter.removeListener.bind(readEmitter),
    emit: writeEmitter.emit.bind(writeEmitter)
  };
}

module.exports = emitter;<commit_msg>exposing readEmitter and writeEmitter<commit_after>var EventEmitter = require('events').EventEmitter;
var emitStream = require('emit-stream');

function emitter(stream) {
  // Read events from the client
  var readEmitter = emitStream.fromStream(stream);

  stream.on('error', function(err) {
    readEmitter.emit('error', err);
  });

  // Write events to the client
  var writeEmitter = new EventEmitter;
  var writeStream = emitStream.toStream(writeEmitter);

  writeStream.on('error', function(err) {
    readEmitter.emit('error', err);
  });

  writeStream.pipe(stream);

  var on = readEmitter.on.bind(readEmitter);

  return {
    on: on,
    addListener: on,
    once: readEmitter.once.bind(readEmitter),
    removeListener: readEmitter.removeListener.bind(readEmitter),
    emit: writeEmitter.emit.bind(writeEmitter),
    writeEmitter: writeEmitter,
    readEmitter: readEmitter
  };
}

module.exports = emitter;<|endoftext|>


<commit_before>'use strict';

var del = require('del'),
    gulp = require('gulp'),
    config = require('../config'),
    compLibConfig = require('../../component-lib.json'),
    exec = require('child_process').exec;

gulp.task('clean-comp-lib', function(cb) {
  del(compLibConfig.destination, cb);
});

gulp.task('component-library', ['clean-comp-lib', 'sass'], function (cb) {
  var env = global.runmode,
      genCompLib = './node_modules/.bin/kss-node --config component-lib.json';

  exec(genCompLib, function (err, stout, sterr) {
    gulp.src([config.images[env].dest + '/**/*', config.sass[env].dest + '**/*'], {base: config[env].dest})
      .pipe(gulp.dest(compLibConfig.destination + '/public'));
    cb(err);
  });
});
<commit_msg>add images task to comp-lib task<commit_after>'use strict';

var del = require('del'),
    gulp = require('gulp'),
    config = require('../config'),
    compLibConfig = require('../../component-lib.json'),
    exec = require('child_process').exec;

gulp.task('clean-comp-lib', function(cb) {
  del(compLibConfig.destination, cb);
});

gulp.task('component-library', ['clean-comp-lib', 'sass', 'images'], function (cb) {
  var env = global.runmode,
      genCompLib = './node_modules/.bin/kss-node --config component-lib.json';

  exec(genCompLib, function (err, stout, sterr) {
    gulp.src([config.images[env].dest + '/**/*', config.sass[env].dest + '**/*'], {base: config[env].dest})
      .pipe(gulp.dest(compLibConfig.destination + '/public'));
    cb(err);
  });
});
<|endoftext|>


<commit_before>const TRUE_STRING = '#t';
const FALSE_STRING = '#f';

export function evaluate(env, expr) {

  if(expr === undefined) {
    // in case of non-existent else clause in if statement
    return;
  }

  // todo: may need something like:
  if (typeof expr === 'number') {
    return expr;
  }
  if (typeof expr === 'string') {
    if(expr === TRUE_STRING || expr === FALSE_STRING) {
      return expr;
    }
    return env.lookup(expr);
  }
  return funApplication(env, expr);
}

function funApplication(env, listExpr) {

  const fun = evaluate(env, listExpr[0]);

  if(fun === undefined) {
    // todo: use something better than console.log
    console.log(listExpr[0] + " is undefined");
    return;
  }

  // special forms that manipulate the listExpr
  if(isSpecialForm(listExpr)) {
    return fun(env, listExpr);
  }

  // classic functions that don't require named arguments
  if(isClassicFunction(listExpr)) {
    const args = listExpr.slice(1).map(n => evaluate(env, n));
    return fun(args);
  }

  // normal functions that require named arguments
  let args = {};
  if(listExpr.length > 1) {
    const argObj = listExpr[1];
    for(let k in argObj) {
      args[k] = evaluate(env, argObj[k]);
    }
  }
  return fun(args);
}

function isSpecialForm(listExpr) {
  const node = listExpr[0];
  return specialForms[node] !== undefined;
}

function isClassicFunction(listExpr) {
  const node = listExpr[0];
  return classicFunctions[node] !== undefined;
}

function addBindings(env, exprs) {

  const addBinding = function(name, value) {
    const v = evaluate(env, value);
    if(name.constructor === Array) {
      // destructure
      // todo: error check if size of name array !== size of v
      name.forEach((n, i) => env.add(n, v[i]));
    } else {
      env.add(name, v);
    }
  }

  exprs.forEach(([name, value]) => addBinding(name, value));

  return env;
}

export var specialForms = {

  // (if something truthy falsey) || (if something truthy)
  'if': (env, [_, cond, t, f]) =>
    evaluate(env, evaluate(env, cond) === TRUE_STRING ? t : f),

  // (quote (age 99))
  'quote': (env, [_, form]) =>
    form,

  // (define foo 12)
  'define': (env, [_, name, val]) =>
    env.add(name, evaluate(env, val)),

  // (set! foo 42)
  'set!': (env, [_, name, val]) =>
    env.mutate(name, evaluate(env, val)),

  // (begin (f1 1) (f2 3) (f3 5))
  'begin': (env, [_, ...body]) =>
    evalBodyForms(env, body),

  // (let ((a 12) (b 24)) (+ a b foo))
  'let': (env, [_, args, ...body]) => {
    return evalBodyForms(addBindings(env.newScope(), args), body);
  },

  // (fn (x: 0 y: 0) (+ x y))
  'fn': (env, [_, defaultArgForms, ...body]) => {

    let defaultArgValues = {};
    for(let k in defaultArgForms) {
      defaultArgValues[k] = evaluate(env, defaultArgForms[k]);
    }

    return function(args) {
      const newEnv = env.newScope();
      for(let k in defaultArgValues) {
        newEnv.add(k, args[k] === undefined ? defaultArgValues[k] : args[k]);
      }
      return evalBodyForms(newEnv, body);
    }},

  // (log "hello world")
  'log': (env, [_, msg]) =>
    console.log(evaluate(env, msg)),

  // (loop (a from: 1 to: 30 step: 2) (+ a a))
  'loop': (env, [_, [varName, varParameters], ...body]) => {

    let vp = {};
    for(let k in varParameters) {
      vp[k] = evaluate(env, varParameters[k]);
    }

    return loopingFn(env.newScope(), body, varName, vp);
  },

  // (onMatrixStack (f1 1) (f2 3) (f3 5))
  'onMatrixStack': (env, [_, ...body]) => {
    env.lookup('pushMatrix')();
    let res =  evalBodyForms(env, body);
    env.lookup('popMatrix')();
    return res;
  },

}

// whoa bodyform, bodyform for you
function evalBodyForms(env, bodyForms) {
  return bodyForms.reduce((a, b) => evaluate(env, b), null);
}

function loopingFn(env, expr, varName, {from = 0,
                                        to = 10,
                                        until = undefined,
                                        step = 1}) {
  // todo: 'to' should be <=, and 'until' should be '<'

  if(step === 0) {
    console.log("step size of 0 given");
    return;
  }

  var res;
  if(until !== undefined) {
    for(let i=from;i<=until;i+=step) {
      env.add(varName, i);
      res = expr.reduce((a, b) => evaluate(env, b), null);
    }
  } else {
    for(let i=from;i<to;i+=step) {
      env.add(varName, i);
      res = expr.reduce((a, b) => evaluate(env, b), null);
    }
  }

  return res;
}

// todo: classic functions are here because it wouldn't make sense to use named parameters for these functions.
// perhaps there should by a syntax like prefixing with @ to indicate that the function takes a variable number of non-named paramters?
// could get rid of the concept of classic functions and allow the user to create @ functions at the expense of having code like: (@+ 4 3 7 4) rather than (+ 4 3 7 4)

export var classicFunctions = {
  '+': (args) =>
    args.reduce((a, b) => a + b, 0),

  '*': (args) =>
    args.reduce((a, b) => a * b, 1),

  '-': (args) =>
    args.length === 1 ? -args[0] : args.reduce((a, b) => a - b),

  '/': (args) =>
    args.reduce((a, b) => a / b),

  '=': ([first, ...rest]) =>
    rest.every(a => a === first) ? TRUE_STRING : FALSE_STRING,

  '<': (args) => {
    let prev = args[0];
    for(let i = 1; i < args.length; i++) {
      const current = args[i];
      if(!(current < prev)) {
        return FALSE_STRING
      }
      prev = current;
    }
    return TRUE_STRING;
  },

  '>': (args) => {
    let prev = args[0];
    for(let i = 1; i < args.length; i++) {
      const current = args[i];
      if(!(current > prev)) {
        return FALSE_STRING;
      }
      prev = current;
    }
    return TRUE_STRING;
  },

  'list' : (args) =>
    args,

  'pair' : (args) => {
    let res = [];
    for(let i=0;i<args.length;i+=2) {
      res.push([args[i], args[i+1]]);
    }
    return res;
  }
}

<commit_msg>log and print special forms<commit_after>const TRUE_STRING = '#t';
const FALSE_STRING = '#f';

export function evaluate(env, expr) {

  if(expr === undefined) {
    // in case of non-existent else clause in if statement
    return;
  }

  // todo: may need something like:
  if (typeof expr === 'number') {
    return expr;
  }
  if (typeof expr === 'string') {
    if(expr === TRUE_STRING || expr === FALSE_STRING) {
      return expr;
    }
    return env.lookup(expr);
  }
  return funApplication(env, expr);
}

function funApplication(env, listExpr) {

  const fun = evaluate(env, listExpr[0]);

  if(fun === undefined) {
    // todo: use something better than console.log
    console.log(listExpr[0] + " is undefined");
    return;
  }

  // special forms that manipulate the listExpr
  if(isSpecialForm(listExpr)) {
    return fun(env, listExpr);
  }

  // classic functions that don't require named arguments
  if(isClassicFunction(listExpr)) {
    const args = listExpr.slice(1).map(n => evaluate(env, n));
    return fun(args);
  }

  // normal functions that require named arguments
  let args = {};
  if(listExpr.length > 1) {
    const argObj = listExpr[1];
    for(let k in argObj) {
      args[k] = evaluate(env, argObj[k]);
    }
  }
  return fun(args);
}

function isSpecialForm(listExpr) {
  const node = listExpr[0];
  return specialForms[node] !== undefined;
}

function isClassicFunction(listExpr) {
  const node = listExpr[0];
  return classicFunctions[node] !== undefined;
}

function addBindings(env, exprs) {

  const addBinding = function(name, value) {
    const v = evaluate(env, value);
    if(name.constructor === Array) {
      // destructure
      // todo: error check if size of name array !== size of v
      name.forEach((n, i) => env.add(n, v[i]));
    } else {
      env.add(name, v);
    }
  }

  exprs.forEach(([name, value]) => addBinding(name, value));

  return env;
}

export var specialForms = {

  // (if something truthy falsey) || (if something truthy)
  'if': (env, [_, cond, t, f]) =>
    evaluate(env, evaluate(env, cond) === TRUE_STRING ? t : f),

  // (quote (age 99))
  'quote': (env, [_, form]) =>
    form,

  // (define foo 12)
  'define': (env, [_, name, val]) =>
    env.add(name, evaluate(env, val)),

  // (set! foo 42)
  'set!': (env, [_, name, val]) =>
    env.mutate(name, evaluate(env, val)),

  // (begin (f1 1) (f2 3) (f3 5))
  'begin': (env, [_, ...body]) =>
    evalBodyForms(env, body),

  // (let ((a 12) (b 24)) (+ a b foo))
  'let': (env, [_, args, ...body]) => {
    return evalBodyForms(addBindings(env.newScope(), args), body);
  },

  // (fn (x: 0 y: 0) (+ x y))
  'fn': (env, [_, defaultArgForms, ...body]) => {

    let defaultArgValues = {};
    for(let k in defaultArgForms) {
      defaultArgValues[k] = evaluate(env, defaultArgForms[k]);
    }

    return function(args) {
      const newEnv = env.newScope();
      for(let k in defaultArgValues) {
        newEnv.add(k, args[k] === undefined ? defaultArgValues[k] : args[k]);
      }
      return evalBodyForms(newEnv, body);
    }},

  // (print "hi" foo) => hi 42
  'print': (env, [_, ...msgs]) => {
    console.log(msgs.reduce((a, b) => a + " " + evaluate(env, b), ""));
  },

  // (log "hi" foo) => hi <foo:42>
  'log': (env, [_, ...msgs]) => {
    let message = msgs.reduce((a, b) => {
      if(typeof b === 'string' && b !== TRUE_STRING && b !== FALSE_STRING) {
        return a + " <" + b + ":" + evaluate(env, b) + ">";
      }
      return a + " " + evaluate(env, b);
    }, "");
    console.log(message);
  },

  // (loop (a from: 1 to: 30 step: 2) (+ a a))
  'loop': (env, [_, [varName, varParameters], ...body]) => {

    let vp = {};
    for(let k in varParameters) {
      vp[k] = evaluate(env, varParameters[k]);
    }

    return loopingFn(env.newScope(), body, varName, vp);
  },

  // (onMatrixStack (f1 1) (f2 3) (f3 5))
  'onMatrixStack': (env, [_, ...body]) => {
    env.lookup('pushMatrix')();
    let res =  evalBodyForms(env, body);
    env.lookup('popMatrix')();
    return res;
  },

}

// whoa bodyform, bodyform for you
function evalBodyForms(env, bodyForms) {
  return bodyForms.reduce((a, b) => evaluate(env, b), null);
}

function loopingFn(env, expr, varName, {from = 0,
                                        to = 10,
                                        until = undefined,
                                        step = 1}) {
  // todo: 'to' should be <=, and 'until' should be '<'

  if(step === 0) {
    console.log("step size of 0 given");
    return;
  }

  var res;
  if(until !== undefined) {
    for(let i=from;i<=until;i+=step) {
      env.add(varName, i);
      res = expr.reduce((a, b) => evaluate(env, b), null);
    }
  } else {
    for(let i=from;i<to;i+=step) {
      env.add(varName, i);
      res = expr.reduce((a, b) => evaluate(env, b), null);
    }
  }

  return res;
}

// todo: classic functions are here because it wouldn't make sense to use named parameters for these functions.
// perhaps there should by a syntax like prefixing with @ to indicate that the function takes a variable number of non-named paramters?
// could get rid of the concept of classic functions and allow the user to create @ functions at the expense of having code like: (@+ 4 3 7 4) rather than (+ 4 3 7 4)

export var classicFunctions = {
  '+': (args) =>
    args.reduce((a, b) => a + b, 0),

  '*': (args) =>
    args.reduce((a, b) => a * b, 1),

  '-': (args) =>
    args.length === 1 ? -args[0] : args.reduce((a, b) => a - b),

  '/': (args) =>
    args.reduce((a, b) => a / b),

  '=': ([first, ...rest]) =>
    rest.every(a => a === first) ? TRUE_STRING : FALSE_STRING,

  '<': (args) => {
    let prev = args[0];
    for(let i = 1; i < args.length; i++) {
      const current = args[i];
      if(!(current < prev)) {
        return FALSE_STRING
      }
      prev = current;
    }
    return TRUE_STRING;
  },

  '>': (args) => {
    let prev = args[0];
    for(let i = 1; i < args.length; i++) {
      const current = args[i];
      if(!(current > prev)) {
        return FALSE_STRING;
      }
      prev = current;
    }
    return TRUE_STRING;
  },

  'list' : (args) =>
    args,

  'pair' : (args) => {
    let res = [];
    for(let i=0;i<args.length;i+=2) {
      res.push([args[i], args[i+1]]);
    }
    return res;
  }
}

<|endoftext|>


<commit_before>define(
[
    'models',
    'views/common',
    'views/dialogs',
    'text!templates/cluster/network_tab.html',
    'text!templates/cluster/verify_network_control.html'
],
function(models, commonViews, dialogViews, networkTabTemplate, networkTabVerificationControlTemplate) {
    'use strict';
    var NetworkTab, NetworkTabVerificationControl;

    NetworkTab = commonViews.Tab.extend({
        template: _.template(networkTabTemplate),
        updateInterval: 3000,
        hasChanges: false,
        events: {
            'keyup input[type=text]': 'changeNetworks',
            'change select': 'changeNetworks',
            'click .net-manager input:not([checked])': 'changeManager',
            'click .verify-networks-btn:not([disabled])': 'verifyNetworks',
            'click .btn-revert-changes:not([disabled])': 'revertChanges',
            'click .apply-btn:not([disabled])': 'applyChanges'
        },
        defaultButtonsState: function(buttonState) {
            this.$('.btn:not(.verify-networks-btn)').attr('disabled', buttonState);
        },
        disableControls: function() {
            this.$('.btn, input, select').attr('disabled', true);
        },
        changeNetworks: function(e) {
            var row = e ? this.$(e.currentTarget).parents('.control-group') : this.$('.control-group.fixed-network');
            row.removeClass('error').find('.help-inline').text('');
            row.find('.error').removeClass('error');
            if (e) {
                // display vlan ids range
                if (this.$(e.currentTarget).hasClass('range')) {
                    if (parseInt(this.$('input[name=fixed-amount]').val(), 10) > 1 && parseInt(this.$('input[name=fixed-vlan_start]').val(), 10)) {
                        this.$('.fixed-header .vlan').text('VLAN ID range');
                        this.$('input[name=fixed-vlan_start]').addClass('range');
                        var vlanEnd =  parseInt(this.$('input[name=fixed-vlan_start]').val(), 10) + parseInt(this.$('input[name=fixed-amount]').val(), 10) - 1;
                        vlanEnd = vlanEnd > 4094 ? 4094 : vlanEnd;
                        this.$('input[name=fixed-vlan-end]').val(vlanEnd);
                        this.$('.vlan-end').removeClass('hide').show();
                    } else {
                        this.$('.fixed-header .vlan').text('VLAN ID');
                        this.$('.vlan-end').hide();
                    }
                }
                // set fixedAmount
                if (this.$(e.currentTarget).attr('name') == 'fixed-amount' && parseInt(this.$(e.currentTarget).val(), 10)) {
                    this.fixedAmount = parseInt(this.$(e.currentTarget).val(), 10);
                }
            }
            // validate data per each change
            this.networks.get(row.data('network-id')).set({
                cidr: $('.cidr input', row).val(),
                vlan_start: parseInt($('.vlan_start input:first', row).val(), 10),
                amount: this.manager == 'FlatDHCPManager' || this.networks.get(row.data('network-id')).get('name') != 'fixed' ? 1: parseInt(this.$('input[name=fixed-amount]').val(), 10),
                network_size: parseInt($('.network_size select', row).val(), 10)
            }, {validate: true});
            // check for changes
            var noChanges = _.isEqual(this.model.get('networks').toJSON(), this.networks.toJSON()) && this.model.get('net_manager') == this.manager;
            this.defaultButtonsState(noChanges);
            this.hasChanges = !noChanges;
            app.page.removeVerificationTask();
        },
        changeManager: function(e) {
            this.manager = this.$(e.currentTarget).val();
            this.changeNetworks();
            this.render();
            this.$('input[name=fixed-amount]').val(this.fixedAmount);
        },
        startVerification: function() {
            var task = new models.Task();
            var options = {
                method: 'PUT',
                url: _.result(this.model, 'url') + '/verify/networks',
                data: JSON.stringify(this.networks)
            };
            task.save({}, options)
                .fail(_.bind(function() {
                        var dialog = new dialogViews.SimpleMessage({error: true, title: 'Network verification'});
                        app.page.registerSubView(dialog);
                        dialog.render();
                    }, this))
                .always(_.bind(function() {
                    this.model.get('tasks').fetch({data: {cluster_id: this.model.id}, reset: true}).done(_.bind(this.scheduleUpdate, this));
                }, this));
        },
        verifyNetworks: function() {
            if (!this.$('.control-group.error').length) {
                app.page.removeVerificationTask().done(_.bind(this.startVerification, this));
            }
        },
        applyChanges: function() {
            var deferred;
            if (!_.some(this.networks.models, 'validationError')) {
                this.disableControls();
                this.model.save({net_manager: this.manager}, {patch: true, wait: true});
                deferred = Backbone.sync('update', this.networks, {url: _.result(this.model, 'url') + '/save/networks'})
                    .always(_.bind(function() {
                        this.model.fetch().done(_.bind(this.render, this));
                    }, this))
                    .done(_.bind(function(task) {
                        if (task && task.status == 'error') {
                            this.defaultButtonsState(false);
                        } else {
                            this.model.set({networks: this.networks.clone()});
                            this.setInitialData();
                        }
                    }, this))
                    .fail(_.bind(function() {
                        this.defaultButtonsState(false);
                        var dialog = new dialogViews.SimpleMessage({error: true, title: 'Networks'});
                        app.page.registerSubView(dialog);
                        dialog.render();
                    }, this));

            } else {
                deferred = new $.Deferred();
                deferred.reject();
            }
            return deferred;
        },
        scheduleUpdate: function() {
            if (this.model.task('verify_networks', 'running')) {
                this.registerDeferred($.timeout(this.updateInterval).done(_.bind(this.update, this)));
            }
        },
        update: function() {
            var task = this.model.task('verify_networks', 'running');
            if (task) {
                this.registerDeferred(task.fetch().always(_.bind(this.scheduleUpdate, this)));
            }
        },
        bindTaskEvents: function() {
            var task = this.model.task('verify_networks') || this.model.task('check_networks', 'error') || this.model.task('deploy', 'running');
            if (task) {
                task.bind('change:status', this.render, this);
                if (this.networks) {
                    this.render();
                }
            }
        },
        bindEvents: function() {
            this.model.get('tasks').bind('remove', this.renderVerificationControl, this);
            this.model.get('tasks').bind('reset', this.bindTaskEvents, this);
            this.bindTaskEvents();
        },
        setInitialData: function() {
            this.hasChanges = false;
            this.networks = new models.Networks(this.model.get('networks').toJSON());
            this.networks.on('invalid', function(model, errors) {
                this.$('.control-group[data-network-id=' + model.id + ']').addClass('error').find('.help-inline').text(errors.cidr || errors.vlan_start || errors.amount);
            }, this);
            this.manager = this.model.get('net_manager');
            var fixedNetwork = _.find(this.model.get('networks').models, function(network) {return network.get('name') == 'fixed';});
            this.fixedAmount = fixedNetwork.get('amount') || 1;
        },
        revertChanges: function() {
            this.setInitialData();
            app.page.removeVerificationTask().done(_.bind(this.render, this));
        },
        initialize: function(options) {
            _.defaults(this, options);
            this.model.bind('change:tasks', this.bindEvents, this);
            this.bindEvents();
            if (!this.model.get('networks')) {
                this.model.set({networks: new models.Networks()});
                this.model.get('networks').fetch({data: {cluster_id: this.model.id}})
                    .done(_.bind(function() {
                        this.setInitialData();
                        this.render();
                    }, this));
            } else {
                this.setInitialData();
            }
        },
        showVerificationErrors: function() {
            var task = this.model.task('verify_networks', 'error') || this.model.task('check_networks', 'error');
            if (task && task.get('result').length) {
                _.each(task.get('result'), function(failedNetwork) {
                    _.each(failedNetwork.errors, function(field) {
                        this.$('.control-group[data-network-id=' + failedNetwork.id + ']').find('.' + field).children().addClass('error');
                    }, this);
                }, this);
            }
        },
        renderVerificationControl: function() {
            var verificationView = new NetworkTabVerificationControl({model: this.model, networks: this.networks});
            this.registerSubView(verificationView);
            this.$('.verification-control').html(verificationView.render().el);
            this.showVerificationErrors();
        },
        render: function() {
            this.$el.html(this.template({cluster: this.model, networks: this.networks, net_manager: this.manager, hasChanges: this.hasChanges}));
            this.renderVerificationControl();
            return this;
        }
    });

    NetworkTabVerificationControl = Backbone.View.extend({
        template: _.template(networkTabVerificationControlTemplate),
        initialize: function(options) {
            _.defaults(this, options);
        },
        render: function() {
            this.$el.html(this.template({cluster: this.model, networks: this.networks}));
            return this;
        }
    });

    return NetworkTab;
});
<commit_msg>Disable Save Settings button if there are validation errors (networks tab)<commit_after>define(
[
    'models',
    'views/common',
    'views/dialogs',
    'text!templates/cluster/network_tab.html',
    'text!templates/cluster/verify_network_control.html'
],
function(models, commonViews, dialogViews, networkTabTemplate, networkTabVerificationControlTemplate) {
    'use strict';
    var NetworkTab, NetworkTabVerificationControl;

    NetworkTab = commonViews.Tab.extend({
        template: _.template(networkTabTemplate),
        updateInterval: 3000,
        hasChanges: false,
        events: {
            'keyup input[type=text]': 'changeNetworks',
            'change select': 'changeNetworks',
            'click .net-manager input:not([checked])': 'changeManager',
            'click .verify-networks-btn:not([disabled])': 'verifyNetworks',
            'click .btn-revert-changes:not([disabled])': 'revertChanges',
            'click .apply-btn:not([disabled])': 'applyChanges'
        },
        defaultButtonsState: function(buttonState) {
            this.$('.btn:not(.verify-networks-btn)').attr('disabled', buttonState);
        },
        disableControls: function() {
            this.$('.btn, input, select').attr('disabled', true);
        },
        changeNetworks: function(e) {
            var row = e ? this.$(e.currentTarget).parents('.control-group') : this.$('.control-group.fixed-network');
            row.removeClass('error').find('.help-inline').text('');
            row.find('.error').removeClass('error');
            if (e) {
                // display vlan ids range
                if (this.$(e.currentTarget).hasClass('range')) {
                    if (parseInt(this.$('input[name=fixed-amount]').val(), 10) > 1 && parseInt(this.$('input[name=fixed-vlan_start]').val(), 10)) {
                        this.$('.fixed-header .vlan').text('VLAN ID range');
                        this.$('input[name=fixed-vlan_start]').addClass('range');
                        var vlanEnd =  parseInt(this.$('input[name=fixed-vlan_start]').val(), 10) + parseInt(this.$('input[name=fixed-amount]').val(), 10) - 1;
                        vlanEnd = vlanEnd > 4094 ? 4094 : vlanEnd;
                        this.$('input[name=fixed-vlan-end]').val(vlanEnd);
                        this.$('.vlan-end').removeClass('hide').show();
                    } else {
                        this.$('.fixed-header .vlan').text('VLAN ID');
                        this.$('.vlan-end').hide();
                    }
                }
                // set fixedAmount
                if (this.$(e.currentTarget).attr('name') == 'fixed-amount' && parseInt(this.$(e.currentTarget).val(), 10)) {
                    this.fixedAmount = parseInt(this.$(e.currentTarget).val(), 10);
                }
            }
            // validate data per each change
            this.networks.get(row.data('network-id')).set({
                cidr: $('.cidr input', row).val(),
                vlan_start: parseInt($('.vlan_start input:first', row).val(), 10),
                amount: this.manager == 'FlatDHCPManager' || this.networks.get(row.data('network-id')).get('name') != 'fixed' ? 1: parseInt(this.$('input[name=fixed-amount]').val(), 10),
                network_size: parseInt($('.network_size select', row).val(), 10)
            }, {validate: true});
            // check for changes
            var noChanges = _.isEqual(this.model.get('networks').toJSON(), this.networks.toJSON()) && this.model.get('net_manager') == this.manager || _.some(this.networks.models, 'validationError');
            this.defaultButtonsState(noChanges);
            this.hasChanges = !noChanges;
            app.page.removeVerificationTask();
        },
        changeManager: function(e) {
            this.manager = this.$(e.currentTarget).val();
            this.changeNetworks();
            this.render();
            this.$('input[name=fixed-amount]').val(this.fixedAmount);
        },
        startVerification: function() {
            var task = new models.Task();
            var options = {
                method: 'PUT',
                url: _.result(this.model, 'url') + '/verify/networks',
                data: JSON.stringify(this.networks)
            };
            task.save({}, options)
                .fail(_.bind(function() {
                        var dialog = new dialogViews.SimpleMessage({error: true, title: 'Network verification'});
                        app.page.registerSubView(dialog);
                        dialog.render();
                    }, this))
                .always(_.bind(function() {
                    this.model.get('tasks').fetch({data: {cluster_id: this.model.id}, reset: true}).done(_.bind(this.scheduleUpdate, this));
                }, this));
        },
        verifyNetworks: function() {
            if (!this.$('.control-group.error').length) {
                app.page.removeVerificationTask().done(_.bind(this.startVerification, this));
            }
        },
        applyChanges: function() {
            var deferred;
            if (!_.some(this.networks.models, 'validationError')) {
                this.disableControls();
                this.model.save({net_manager: this.manager}, {patch: true, wait: true});
                deferred = Backbone.sync('update', this.networks, {url: _.result(this.model, 'url') + '/save/networks'})
                    .always(_.bind(function() {
                        this.model.fetch().done(_.bind(this.render, this));
                    }, this))
                    .done(_.bind(function(task) {
                        if (task && task.status == 'error') {
                            this.defaultButtonsState(false);
                        } else {
                            this.model.set({networks: this.networks.clone()});
                            this.setInitialData();
                        }
                    }, this))
                    .fail(_.bind(function() {
                        this.defaultButtonsState(false);
                        var dialog = new dialogViews.SimpleMessage({error: true, title: 'Networks'});
                        app.page.registerSubView(dialog);
                        dialog.render();
                    }, this));

            } else {
                deferred = new $.Deferred();
                deferred.reject();
            }
            return deferred;
        },
        scheduleUpdate: function() {
            if (this.model.task('verify_networks', 'running')) {
                this.registerDeferred($.timeout(this.updateInterval).done(_.bind(this.update, this)));
            }
        },
        update: function() {
            var task = this.model.task('verify_networks', 'running');
            if (task) {
                this.registerDeferred(task.fetch().always(_.bind(this.scheduleUpdate, this)));
            }
        },
        bindTaskEvents: function() {
            var task = this.model.task('verify_networks') || this.model.task('check_networks', 'error') || this.model.task('deploy', 'running');
            if (task) {
                task.bind('change:status', this.render, this);
                if (this.networks) {
                    this.render();
                }
            }
        },
        bindEvents: function() {
            this.model.get('tasks').bind('remove', this.renderVerificationControl, this);
            this.model.get('tasks').bind('reset', this.bindTaskEvents, this);
            this.bindTaskEvents();
        },
        setInitialData: function() {
            this.hasChanges = false;
            this.networks = new models.Networks(this.model.get('networks').toJSON());
            this.networks.on('invalid', function(model, errors) {
                this.$('.control-group[data-network-id=' + model.id + ']').addClass('error').find('.help-inline').text(errors.cidr || errors.vlan_start || errors.amount);
            }, this);
            this.manager = this.model.get('net_manager');
            var fixedNetwork = _.find(this.model.get('networks').models, function(network) {return network.get('name') == 'fixed';});
            this.fixedAmount = fixedNetwork.get('amount') || 1;
        },
        revertChanges: function() {
            this.setInitialData();
            app.page.removeVerificationTask().done(_.bind(this.render, this));
        },
        initialize: function(options) {
            _.defaults(this, options);
            this.model.bind('change:tasks', this.bindEvents, this);
            this.bindEvents();
            if (!this.model.get('networks')) {
                this.model.set({networks: new models.Networks()});
                this.model.get('networks').fetch({data: {cluster_id: this.model.id}})
                    .done(_.bind(function() {
                        this.setInitialData();
                        this.render();
                    }, this));
            } else {
                this.setInitialData();
            }
        },
        showVerificationErrors: function() {
            var task = this.model.task('verify_networks', 'error') || this.model.task('check_networks', 'error');
            if (task && task.get('result').length) {
                _.each(task.get('result'), function(failedNetwork) {
                    _.each(failedNetwork.errors, function(field) {
                        this.$('.control-group[data-network-id=' + failedNetwork.id + ']').find('.' + field).children().addClass('error');
                    }, this);
                }, this);
            }
        },
        renderVerificationControl: function() {
            var verificationView = new NetworkTabVerificationControl({model: this.model, networks: this.networks});
            this.registerSubView(verificationView);
            this.$('.verification-control').html(verificationView.render().el);
            this.showVerificationErrors();
        },
        render: function() {
            this.$el.html(this.template({cluster: this.model, networks: this.networks, net_manager: this.manager, hasChanges: this.hasChanges}));
            this.renderVerificationControl();
            return this;
        }
    });

    NetworkTabVerificationControl = Backbone.View.extend({
        template: _.template(networkTabVerificationControlTemplate),
        initialize: function(options) {
            _.defaults(this, options);
        },
        render: function() {
            this.$el.html(this.template({cluster: this.model, networks: this.networks}));
            return this;
        }
    });

    return NetworkTab;
});
<|endoftext|>


<commit_before>'use strict';

var mongoose = require('mongoose'),
    config = require('../config/config');

// console.log('connecting to mongoDb:', config.database);

mongoose.connect(config.database, function(err) {
    if (err) {
        throw err;
    }
//  else {
//      console.log('connected');
//  }
});
<commit_msg>removed development code<commit_after>'use strict';

var mongoose = require('mongoose'),
    config = require('../config/config');

mongoose.connect(config.database, function(err) {
    if (err) {
        throw err;
    }
});
<|endoftext|>


<commit_before>
module.exports = {
	'API_URI': process.env.API_URI ? process.env.API_URI : 'http://0.0.0.0:3000/'
}<commit_msg>fix export constants<commit_after>
export default const constants = {
	'API_URI': process.env.API_URI ? process.env.API_URI : 'http://0.0.0.0:3000/'
}<|endoftext|>


<commit_before>var store = {
    "initModel": function($scope, $http) {
        pull($http, "/products/enabled", {}, $scope, "products", function() {
            $scope.productsByCategory = [];
            mainloop: for ( var i = 0; i < $scope.products.length; ++i ) {
                for ( var j = 0; j < $scope.productsByCategory.length; ++j ) {
                    if ( $scope.products[i].category == $scope.productsByCategory[j].name ) {
                        $scope.productsByCategory[j].products.push($scope.products[i]);
                        continue mainloop;
                    }
                }
                $scope.productsByCategory.push({
                    "name": $scope.products[i].category,
                    "products": [
                        $scope.products[i]
                    ]
                });
            }
        });
        $scope.shared = {
            "local": {
                "store": true,
                "total": 0,
                "customer": {},
                "pinDigit": false
            }
        };
        var fakescope = {};
        pull($http, "/option", {
            "name": "StoreName"
        }, fakescope, "result", function() {
            $scope.shared.local.storeName = fakescope.result.value;
        });
        $("#barcode").val("");
    },
    "onBarcodeScan": function() {
        pull(store.$http, "/customer", {
            "barcode": $("#barcode").val()
        }, $scope.shared.local, "customer", function() {
            if ( $scope.shared.local.customer ) {
                $scope.shared.local.purchases = [];
                $scope.shared.local.total = 0;
                location.href = "#step-2";
                window.onhashchange();
            } else {
                $("#barcode").val("");
            }
        });
        return false;
    },
    "verifyAccount": function() {
        location.href = "#step-3";
        window.onhashchange();
        $scope.shared.local.purchases = [];
        $scope.shared.local.total = 0;
        return false;
    },
    "sendPurchase": function() {
        var purchases = [];
        for ( var i = 0; i < store.$scope.shared.local.purchases.length; ++i ) {
            purchases[i] = store.$scope.shared.local.purchases[i].product.id;
        }
        var fakeScope = {};
        pull(store.$http, "/purchase", {
            "barcode": $("#barcode").val(),
            "pin": store.$scope.shared.remote.pin,
            "purchases": purchases
        }, fakeScope, "status", function() {
            if ( fakeScope.status.success ) {
                location.href = "#step-1";
                window.onhashchange();
                store.initModel(store.$scope, store.$http);
            } else {
                Materialize.toast("Invalid pin", 4000);
                store.$scope.shared.local.alert = "Invalid pin";
                store.$scope.shared.local.alertHash = Math.random();
                store.$scope.shared.local.pinDigit = null;
                var unbind = $scope.$watch("shared.remote.pin", function(newValue) {
                    if (newValue && newValue.length != $scope.shared.local.customer.pinLength) {
                        unbind();
                        unbind = $scope.$watch("shared.remote.pin", function(newValue) {
                            if (newValue && newValue.length == $scope.shared.local.customer.pinLength) {
                                unbind();
                                store.sendPurchase();
                                store.$scope.shared.local.resetPass = Math.random();
                                store.$scope.shared.local.pinDigit = false;
                            }
                        });
                    }
                });
            }
        });
    },
    "purchase": function() {
        location.href = "#step-4";
        window.onhashchange();
        if ( store.$scope.shared.local.customer.pinLength > 0 ) {
            store.$scope.$apply(function() {
                store.$scope.shared.local.resetPass = Math.random();
                store.$scope.shared.local.promptPass = true;
                store.$scope.shared.local.pinDigit = null;
            });
            var unbind = $scope.$watch("shared.remote.pin", function(newValue) {
                if ( newValue && newValue.length == $scope.shared.local.customer.pinLength ) {
                    unbind();
                    store.sendPurchase();
                    store.$scope.shared.local.resetPass = Math.random();
                    store.$scope.shared.local.pinDigit = false;
                }
            });
        } else {
            store.sendPurchase();
        }
        return false;
    },
    "initDisplay": function($scope, $http) {
        $scope.displayToken = randomToken(6);
        var tokens = {
            "toDisplay": randomToken(64),
            "toControl": randomToken(64)
        };
        session.initSend($http, $scope.displayToken);
        session.send(tokens);
        session.initSend($http, tokens.toDisplay);
        session.initRecv($http, tokens.toControl);
        session.onRead = function(data) {
            if ( data.connected ) {
                $scope.displayToken = false;
                session.onRead = function(data) {
                    $scope.shared.remote = data;
                };
                $scope.$watch("shared.local", function(newValue) {
                    session.send($scope.shared.local);
                }, true);
            }
        };
    }
};

function angularCallback($scope, $http) {
    store.initModel($scope, $http);
    store.initDisplay($scope, $http);
    $scope.buy = function(category$index, $index) {
        $scope.shared.local.purchases.push({
            "product": $scope.productsByCategory[category$index].products[$index]
        });
        $scope.shared.local.total += $scope.productsByCategory[category$index].products[$index].price;
    };
    $scope.cancelPurchase = function($index) {
        var purchase = $scope.shared.local.purchases.splice($index, 1)[0];
        $scope.shared.local.total -= purchase.product.price;
    };
    store.$scope = $scope;
    store.$http = $http;
}

function onPageChange(page) {
    if (page == 1) {
        store.$scope.$apply(function() {
            store.$scope.shared.local.customer = null;
            store.$scope.shared.local.promptPass = false;
        });
        $("#barcode").val("");
    } else if (page == 3) {
        store.$scope.$apply(function() {
            store.$scope.shared.local.promptPass = false;
        });
    }
}

function sufficientPermissions(permissions) {
    return permissions && permissions.store;
}

window.onkeypress = function(e) {
    if ( store.$scope.shared.local.pinDigit === false ) {
        if ( e.keyCode == 13 ) {
            store.onBarcodeScan();
        } else if ( e.key.length == 1 ) {
            $("#barcode").val($("#barcode").val() + e.key);
        }
    } else if ( e.key.length == 1 ) {
        store.$scope.$apply(function() {
            store.$scope.shared.local.pinDigit = e.key;
        });
    }
};
<commit_msg>Fixed text entry<commit_after>var store = {
    "initModel": function($scope, $http) {
        pull($http, "/products/enabled", {}, $scope, "products", function() {
            $scope.productsByCategory = [];
            mainloop: for ( var i = 0; i < $scope.products.length; ++i ) {
                for ( var j = 0; j < $scope.productsByCategory.length; ++j ) {
                    if ( $scope.products[i].category == $scope.productsByCategory[j].name ) {
                        $scope.productsByCategory[j].products.push($scope.products[i]);
                        continue mainloop;
                    }
                }
                $scope.productsByCategory.push({
                    "name": $scope.products[i].category,
                    "products": [
                        $scope.products[i]
                    ]
                });
            }
        });
        $scope.shared = {
            "local": {
                "store": true,
                "total": 0,
                "customer": {},
                "pinDigit": false
            }
        };
        var fakescope = {};
        pull($http, "/option", {
            "name": "StoreName"
        }, fakescope, "result", function() {
            $scope.shared.local.storeName = fakescope.result.value;
        });
        $("#barcode").val("");
    },
    "onBarcodeScan": function() {
        pull(store.$http, "/customer", {
            "barcode": $("#barcode").val()
        }, $scope.shared.local, "customer", function() {
            if ( $scope.shared.local.customer ) {
                $scope.shared.local.purchases = [];
                $scope.shared.local.total = 0;
                location.href = "#step-2";
                window.onhashchange();
            } else {
                $("#barcode").val("");
            }
        });
        return false;
    },
    "verifyAccount": function() {
        location.href = "#step-3";
        window.onhashchange();
        $scope.shared.local.purchases = [];
        $scope.shared.local.total = 0;
        return false;
    },
    "sendPurchase": function() {
        var purchases = [];
        for ( var i = 0; i < store.$scope.shared.local.purchases.length; ++i ) {
            purchases[i] = store.$scope.shared.local.purchases[i].product.id;
        }
        var fakeScope = {};
        pull(store.$http, "/purchase", {
            "barcode": $("#barcode").val(),
            "pin": store.$scope.shared.remote.pin,
            "purchases": purchases
        }, fakeScope, "status", function() {
            if ( fakeScope.status.success ) {
                location.href = "#step-1";
                window.onhashchange();
                store.initModel(store.$scope, store.$http);
            } else {
                Materialize.toast("Invalid pin", 4000);
                store.$scope.shared.local.alert = "Invalid pin";
                store.$scope.shared.local.alertHash = Math.random();
                store.$scope.shared.local.pinDigit = null;
                var unbind = $scope.$watch("shared.remote.pin", function(newValue) {
                    if (newValue && newValue.length != $scope.shared.local.customer.pinLength) {
                        unbind();
                        unbind = $scope.$watch("shared.remote.pin", function(newValue) {
                            if (newValue && newValue.length == $scope.shared.local.customer.pinLength) {
                                unbind();
                                store.sendPurchase();
                                store.$scope.shared.local.resetPass = Math.random();
                                store.$scope.shared.local.pinDigit = false;
                            }
                        });
                    }
                });
            }
        });
    },
    "purchase": function() {
        location.href = "#step-4";
        window.onhashchange();
        if ( store.$scope.shared.local.customer.pinLength > 0 ) {
            store.$scope.$apply(function() {
                store.$scope.shared.local.resetPass = Math.random();
                store.$scope.shared.local.promptPass = true;
                store.$scope.shared.local.pinDigit = null;
            });
            var unbind = $scope.$watch("shared.remote.pin", function(newValue) {
                if ( newValue && newValue.length == $scope.shared.local.customer.pinLength ) {
                    unbind();
                    store.sendPurchase();
                    store.$scope.shared.local.resetPass = Math.random();
                    store.$scope.shared.local.pinDigit = false;
                }
            });
        } else {
            store.sendPurchase();
        }
        return false;
    },
    "initDisplay": function($scope, $http) {
        $scope.displayToken = randomToken(6);
        var tokens = {
            "toDisplay": randomToken(64),
            "toControl": randomToken(64)
        };
        session.initSend($http, $scope.displayToken);
        session.send(tokens);
        session.initSend($http, tokens.toDisplay);
        session.initRecv($http, tokens.toControl);
        session.onRead = function(data) {
            if ( data.connected ) {
                $scope.displayToken = false;
                session.onRead = function(data) {
                    $scope.shared.remote = data;
                };
                $scope.$watch("shared.local", function(newValue) {
                    session.send($scope.shared.local);
                }, true);
            }
        };
    }
};

function angularCallback($scope, $http) {
    store.initModel($scope, $http);
    store.initDisplay($scope, $http);
    $scope.buy = function(category$index, $index) {
        $scope.shared.local.purchases.push({
            "product": $scope.productsByCategory[category$index].products[$index]
        });
        $scope.shared.local.total += $scope.productsByCategory[category$index].products[$index].price;
    };
    $scope.cancelPurchase = function($index) {
        var purchase = $scope.shared.local.purchases.splice($index, 1)[0];
        $scope.shared.local.total -= purchase.product.price;
    };
    store.$scope = $scope;
    store.$http = $http;
}

function onPageChange(page) {
    if (page == 1) {
        store.$scope.$apply(function() {
            store.$scope.shared.local.customer = null;
            store.$scope.shared.local.promptPass = false;
        });
        $("#barcode").val("");
    } else if (page == 3) {
        store.$scope.$apply(function() {
            store.$scope.shared.local.promptPass = false;
        });
    }
}

function sufficientPermissions(permissions) {
    return permissions && permissions.store;
}

window.onkeypress = function(e) {
    if ( location.hash == "" || location.hash == "#step-1" ) {
        if ( e.keyCode == 13 ) {
            store.onBarcodeScan();
        } else if ( e.key.length == 1 ) {
            $("#barcode").val($("#barcode").val() + e.key);
        }
    } else if ( e.key.length == 1 && location.hash == "#step-4" ) {
        store.$scope.$apply(function() {
            store.$scope.shared.local.pinDigit = e.key;
        });
    }
};
<|endoftext|>


<commit_before>describe("Test", function(){

it("should open the user page", function(){

	browser.get("http://localhost:8000/");
	var button = element(by.id("createSession"));
	button.click();
	browser.sleep(2000);
	expect(browser.getCurrentUrl()).toEqual("http://localhost:8000/user");

});

it("should create a session and add a user", function(){

	browser.get("http://localhost:8000/");
	var button = element(by.id("createSession"));
	button.click();
	browser.sleep(2000);
	var input = element(by.id("username"));
	input.sendKeys("Simona");
	var joinButton = element(by.id("joinSession"));
	joinButton.click();
	browser.sleep(2000);
	expect(element(by.id("addStart")).isPresent()).toBe(true);

});

it("should join an existing session", function(){

	browser.get("http://localhost:8000/");
	var inputSession = element(by.id("sessionId"));
	inputSession.sendKeys("testing123");
	var joinSessionBtn = element(by.id("enterSession"));
	joinSessionBtn.click();
	browser.sleep(2000);
	var input = element(by.id("username"));
	input.sendKeys("Simona1");
	var joinButton = element(by.id("joinSession"));
	joinButton.click();
	browser.sleep(3000);
	expect(element(by.id("addStart")).isPresent()).toBe(true);

});

it("should add user to active users", function(){

	browser.get("http://localhost:8000/");
	var inputSession = element(by.id("sessionId"));
	inputSession.sendKeys("testing123");
	var joinSessionBtn = element(by.id("enterSession"));
	joinSessionBtn.click();
	browser.sleep(2000);
	var input = element(by.id("username"));
	input.sendKeys("Simona");
	var joinButton = element(by.id("joinSession"));
	joinButton.click();
	browser.sleep(4000);
	var user = element(by.id("Simona"));
	expect(user.isPresent()).toBe(true);

});

it("should not join a non-existing session", function(){

	browser.get("http://localhost:8000/");
	var inputSession = element(by.id("sessionId"));
	inputSession.sendKeys("simonovaSesija");
	var joinSessionBtn = element(by.id("enterSession"));
	joinSessionBtn.click();
	browser.sleep(2000);
	var warning = element(by.id("warningSession")).isDisplayed();
	expect(warning).toBe(true);

});

it("should add an anonymous user on empty username input", function(){

	browser.get("http://localhost:8000/");
	var inputSession = element(by.id("sessionId"));
	inputSession.sendKeys("testing123");
	var joinSessionBtn = element(by.id("enterSession"));
	joinSessionBtn.click();
	browser.sleep(2000);
	var input = element(by.id("username"));
	input.sendKeys("");
	var joinButton = element(by.id("joinSession"));
	joinButton.click();
	browser.sleep(4000);
	var user = element(by.id("Anonymous"));
	expect(user.isPresent()).toBe(true);

});

});<commit_msg>e2e tests fix<commit_after>describe("Test", function(){

it("should open the user page", function(){

	browser.get("http://localhost:8000/");
	var button = element(by.id("createSession"));
	button.click();
	browser.sleep(6000);
	expect(browser.getCurrentUrl()).toEqual("http://localhost:8000/user");

});

it("should create a session and add a user", function(){

	browser.get("http://localhost:8000/");
	var button = element(by.id("createSession"));
	button.click();
	browser.sleep(6000);
	var input = element(by.id("username"));
	input.sendKeys("Simona");
	var joinButton = element(by.id("joinSession"));
	joinButton.click();
	browser.sleep(2000);
	expect(element(by.id("addStart")).isPresent()).toBe(true);

});

it("should join an existing session", function(){

	browser.get("http://localhost:8000/");
	var inputSession = element(by.id("sessionId"));
	inputSession.sendKeys("testing123");
	var joinSessionBtn = element(by.id("enterSession"));
	joinSessionBtn.click();
	browser.sleep(6000);
	var input = element(by.id("username"));
	input.sendKeys("Simona1");
	var joinButton = element(by.id("joinSession"));
	joinButton.click();
	browser.sleep(3000);
	expect(element(by.id("addStart")).isPresent()).toBe(true);

});

it("should add user to active users", function(){

	browser.get("http://localhost:8000/");
	var inputSession = element(by.id("sessionId"));
	inputSession.sendKeys("testing123");
	var joinSessionBtn = element(by.id("enterSession"));
	joinSessionBtn.click();
	browser.sleep(6000);
	var input = element(by.id("username"));
	input.sendKeys("Simona");
	var joinButton = element(by.id("joinSession"));
	joinButton.click();
	browser.sleep(4000);
	var user = element(by.id("Simona"));
	expect(user.isPresent()).toBe(true);

});

it("should not join a non-existing session", function(){

	browser.get("http://localhost:8000/");
	var inputSession = element(by.id("sessionId"));
	inputSession.sendKeys("simonovaSesija");
	var joinSessionBtn = element(by.id("enterSession"));
	joinSessionBtn.click();
	browser.sleep(2000);
	var warning = element(by.id("warningSession")).isDisplayed();
	expect(warning).toBe(true);

});

it("should add an anonymous user on empty username input", function(){

	browser.get("http://localhost:8000/");
	var inputSession = element(by.id("sessionId"));
	inputSession.sendKeys("testing123");
	var joinSessionBtn = element(by.id("enterSession"));
	joinSessionBtn.click();
	browser.sleep(6000);
	var input = element(by.id("username"));
	input.sendKeys("");
	var joinButton = element(by.id("joinSession"));
	joinButton.click();
	browser.sleep(4000);
	var user = element(by.id("Anonymous"));
	expect(user.isPresent()).toBe(true);

});

});<|endoftext|>


<commit_before>/**
 * Application services module
 */
var app_services = angular.module('drupalionic.services', ['drupalionic.configuration']);

/**
 * Account factory that holds logic for login, logout and account create
 * It uses $q to handle promises and $http for requess
 * It inyects the URLs from the config.js file
 */
app_services.factory('Account', function($http, $q, drupal_instance, api_endpoint) {

 return {

     /*
      * Login against the Drupal Service API
      * @param  {String} username
      * @param  {String} password
      * @return {Promise}
      */
      login : function( username, password ){

          var defer = $q.defer();

          $http({
            method        :'POST',
            url           : drupal_instance + api_endpoint + 'user/login',
            dataType      : 'json',
            crossDomain   : true,
            data          : 'username=' + username + '&password=' + password,
            headers       : {
              "Content-Type": "application/x-www-form-urlencoded"
            }
          })

          .success(function(data, status, headers, config){
              defer.resolve(data);
          })

          .error(function(data, status, headers, config){
              defer.reject(data);
          });

          return defer.promise;
      },

      /*
      * Create an account against the Drupal Service API
      * @param  {String} username
      * @param  {String} email
      * @param  {String} password
      * @return {Promise}
      */
      createAccount : function(username, email, password){

          var defer = $q.defer();

          $http({
            method        :'POST',
            url           : drupal_instance + api_endpoint + 'user/register',
            dataType      : 'json',
            crossDomain   : true,
            data          : {
              name : username,
              pass : password,
              mail : email
            },
            headers       : {
              "Content-Type": "application/x-www-form-urlencoded"
            }
          })

          .success(function(data, status, headers, config){
              defer.resolve(data);
          })

          .error(function(data, status, headers, config){
              defer.reject(data);
          });

          return defer.promise;
      }

 }

});

/**
 * Auth factory that holds logic and data regarding the user across the app
 */
app_services.factory( 'Auth', function($window) {

  var currentUser;

  return {

    //Set the user data to use accross the app, this is saved when loggedIn
    setUserData: function(key,value) {
      $window.localStorage[data] = value;
    },

    //Get the currentUser data
    getUserData: function(key) {
      return $window.localStorage[key] || '{}';
    },

    //Helper function to know if the user is loggedIn or not
    isLoggedIn: function() {

      currentUser = $window.localStorage['user'];

      if( (typeof currentUser === "object") && (currentUser !== null) ){
          return true;
      }else{
        return false;
      }

    }
  };
});
<commit_msg>Edit wrong words<commit_after>/**
 * Application services module
 */
var app_services = angular.module('drupalionic.services', ['drupalionic.configuration']);

/**
 * Account factory that holds logic for login, logout and account create
 * It uses $q to handle promises and $http for requess
 * It inyects the URLs from the config.js file
 */
app_services.factory('Account', function($http, $q, drupal_instance, api_endpoint) {

 return {

     /*
      * Login against the Drupal Service API
      * @param  {String} username
      * @param  {String} password
      * @return {Promise}
      */
      login : function( username, password ){

          var defer = $q.defer();

          $http({
            method        :'POST',
            url           : drupal_instance + api_endpoint + 'user/login',
            dataType      : 'json',
            crossDomain   : true,
            data          : 'username=' + username + '&password=' + password,
            headers       : {
              "Content-Type": "application/x-www-form-urlencoded"
            }
          })

          .success(function(data, status, headers, config){
              defer.resolve(data);
          })

          .error(function(data, status, headers, config){
              defer.reject(data);
          });

          return defer.promise;
      },

      /*
      * Create an account against the Drupal Service API
      * @param  {String} username
      * @param  {String} email
      * @param  {String} password
      * @return {Promise}
      */
      createAccount : function(username, email, password){

          var defer = $q.defer();

          $http({
            method        :'POST',
            url           : drupal_instance + api_endpoint + 'user/register',
            dataType      : 'json',
            crossDomain   : true,
            data          : {
              name : username,
              pass : password,
              mail : email
            },
            headers       : {
              "Content-Type": "application/x-www-form-urlencoded"
            }
          })

          .success(function(data, status, headers, config){
              defer.resolve(data);
          })

          .error(function(data, status, headers, config){
              defer.reject(data);
          });

          return defer.promise;
      }

 }

});

/**
 * Auth factory that holds logic and data regarding the user across the app
 */
app_services.factory( 'Auth', function($window) {

  var currentUser;

  return {

    //Set the user data to use accross the app, this is saved when loggedIn
    setUserData: function(key,value) {
      $window.localStorage[key] = value;
    },

    //Get the currentUser data
    getUserData: function(key) {
      return $window.localStorage[key] || '{}';
    },

    //Helper function to know if the user is loggedIn or not
    isLoggedIn: function() {

      currentUser = $window.localStorage['user'];

      if( (typeof currentUser === "object") && (currentUser !== null) ){
          return true;
      }else{
        return false;
      }

    }
  };
});
<|endoftext|>


<commit_before>/* jshint -W097 */// jshint strict:false
/*jslint node: true */
var expect = require('chai').expect;
var setup  = require('./lib/setup');

var objects = null;
var states  = null;
var onStateChanged = null;
var onObjectChanged = null;
var sendToID = 1;

var adapterShortName = setup.adapterName.substring(setup.adapterName.indexOf('.')+1);

function checkConnectionOfAdapter(cb, counter) {
    counter = counter || 0;
    console.log('Try check #' + counter);
    if (counter > 30) {
        if (cb) cb('Cannot check connection');
        return;
    }

    states.getState('system.adapter.' + adapterShortName + '.0.alive', function (err, state) {
        if (err) console.error(err);
        if (state && state.val) {
            if (cb) cb();
        } else {
            setTimeout(function () {
                checkConnectionOfAdapter(cb, counter + 1);
            }, 1000);
        }
    });
}

function checkValueOfState(id, value, cb, counter) {
    counter = counter || 0;
    if (counter > 20) {
        if (cb) cb('Cannot check value Of State ' + id);
        return;
    }

    states.getState(id, function (err, state) {
        if (err) console.error(err);
        if (value === null && !state) {
            if (cb) cb();
        } else
        if (state && (value === undefined || state.val === value)) {
            if (cb) cb();
        } else {
            setTimeout(function () {
                checkValueOfState(id, value, cb, counter + 1);
            }, 500);
        }
    });
}

function sendTo(target, command, message, callback) {
    onStateChanged = function (id, state) {
        if (id === 'messagebox.system.adapter.test.0') {
            callback(state.message);
        }
    };

    states.pushMessage('system.adapter.' + target, {
        command:    command,
        message:    message,
        from:       'system.adapter.test.0',
        callback: {
            message: message,
            id:      sendToID++,
            ack:     false,
            time:    (new Date()).getTime()
        }
    });
}

describe('Test ' + adapterShortName + ' adapter', function() {
    before('Test ' + adapterShortName + ' adapter: Start js-controller', function (_done) {
        this.timeout(600000); // because of first install from npm

        setup.setupController(async function () {
            var config = setup.getAdapterConfig();
            // enable adapter
            config.common.enabled  = true;
            config.common.loglevel = 'debug';

            //config.native.dbtype   = 'sqlite';

            await setup.setAdapterConfig(config.common, config.native);

            setup.startController(true, function(id, obj) {}, function (id, state) {
                    if (onStateChanged) onStateChanged(id, state);
                },
                function (_objects, _states) {
                    objects = _objects;
                    states  = _states;
                    _done();
                });
        });
    });

/*
    ENABLE THIS WHEN ADAPTER RUNS IN DEAMON MODE TO CHECK THAT IT HAS STARTED SUCCESSFULLY
*/
    it('Test ' + adapterShortName + ' adapter: Check if adapter started', function (done) {
        this.timeout(60000);
        checkConnectionOfAdapter(function (res) {
            if (res) console.log(res);
            expect(res).not.to.be.equal('Cannot check connection');
            objects.setObject('system.adapter.test.0', {
                    common: {

                    },
                    type: 'instance'
                },
                function () {
                    states.subscribeMessage('system.adapter.test.0');
                    done();
                });
        });
    });
/**/

/*
    PUT YOUR OWN TESTS HERE USING
    it('Testname', function ( done) {
        ...
    });

    You can also use "sendTo" method to send messages to the started adapter
*/

    after('Test ' + adapterShortName + ' adapter: Stop js-controller', function (done) {
        this.timeout(10000);

        setup.stopController(function (normalTerminated) {
            console.log('Adapter normal terminated: ' + normalTerminated);
            done();
        });
    });
});
<commit_msg>update testAdapter.js<commit_after>/* jshint -W097 */// jshint strict:false
/*jslint node: true */
var expect = require('chai').expect;
var setup  = require('./lib/setup');

var objects = null;
var states  = null;
var onStateChanged = null;
var onObjectChanged = null;
var sendToID = 1;

var adapterShortName = setup.adapterName.substring(setup.adapterName.indexOf('.')+1);

function checkConnectionOfAdapter(cb, counter) {
    counter = counter || 0;
    console.log('Try check #' + counter);
    if (counter > 30) {
        if (cb) cb('Cannot check connection');
        return;
    }

    states.getState('system.adapter.' + adapterShortName + '.0.alive', function (err, state) {
        if (err) console.error(err);
        if (state && state.val) {
            if (cb) cb();
        } else {
            setTimeout(function () {
                checkConnectionOfAdapter(cb, counter + 1);
            }, 1000);
        }
    });
}

function checkValueOfState(id, value, cb, counter) {
    counter = counter || 0;
    if (counter > 20) {
        if (cb) cb('Cannot check value Of State ' + id);
        return;
    }

    states.getState(id, function (err, state) {
        if (err) console.error(err);
        if (value === null && !state) {
            if (cb) cb();
        } else
        if (state && (value === undefined || state.val === value)) {
            if (cb) cb();
        } else {
            setTimeout(function () {
                checkValueOfState(id, value, cb, counter + 1);
            }, 500);
        }
    });
}

function sendTo(target, command, message, callback) {
    onStateChanged = function (id, state) {
        if (id === 'messagebox.system.adapter.test.0') {
            callback(state.message);
        }
    };

    states.pushMessage('system.adapter.' + target, {
        command:    command,
        message:    message,
        from:       'system.adapter.test.0',
        callback: {
            message: message,
            id:      sendToID++,
            ack:     false,
            time:    (new Date()).getTime()
        }
    });
}

describe('Test ' + adapterShortName + ' adapter', function() {
    before('Test ' + adapterShortName + ' adapter: Start js-controller', function (_done) {
        this.timeout(600000); // because of first install from npm

        setup.setupController(async function () {
            var config = await setup.getAdapterConfig();
            // enable adapter
            config.common.enabled  = true;
            config.common.loglevel = 'debug';

            //config.native.dbtype   = 'sqlite';

            await setup.setAdapterConfig(config.common, config.native);

            setup.startController(true, function(id, obj) {}, function (id, state) {
                    if (onStateChanged) onStateChanged(id, state);
                },
                function (_objects, _states) {
                    objects = _objects;
                    states  = _states;
                    _done();
                });
        });
    });

/*
    ENABLE THIS WHEN ADAPTER RUNS IN DEAMON MODE TO CHECK THAT IT HAS STARTED SUCCESSFULLY
*/
    it('Test ' + adapterShortName + ' adapter: Check if adapter started', function (done) {
        this.timeout(60000);
        checkConnectionOfAdapter(function (res) {
            if (res) console.log(res);
            expect(res).not.to.be.equal('Cannot check connection');
            objects.setObject('system.adapter.test.0', {
                    common: {

                    },
                    type: 'instance'
                },
                function () {
                    states.subscribeMessage('system.adapter.test.0');
                    done();
                });
        });
    });
/**/

/*
    PUT YOUR OWN TESTS HERE USING
    it('Testname', function ( done) {
        ...
    });

    You can also use "sendTo" method to send messages to the started adapter
*/

    after('Test ' + adapterShortName + ' adapter: Stop js-controller', function (done) {
        this.timeout(10000);

        setup.stopController(function (normalTerminated) {
            console.log('Adapter normal terminated: ' + normalTerminated);
            done();
        });
    });
});
<|endoftext|>