<commit_before>di.base = function() {
    var vumigo = require('vumigo_v02');
    var App = vumigo.App;
    var AppStates = vumigo.app.AppStates;
    var State = vumigo.states.State;
    var FreeText = vumigo.states.FreeText;
    var EndState = vumigo.states.EndState;
    var PushMessageApi = di.pushmessage.PushMessageApi;

    var DiAppStates  = AppStates.extend(function(self,app,opts) {
        AppStates.call(self, app);
        var create =  self.create;
        self.create = function(name,opts) {

            var push_api =  new PushMessageApi(app.im,app);
            if (!app.is(self.app.im.msg.inbound_push_trigger)) {
                return create(name, opts);
            }
            return !push_api.should_push()
                ? create('states:noop')
                : create('states:push:start');
        };
    });

    var BaseDiApp = App.extend(function(self, start_state_name) {
        App.call(self, start_state_name, {AppStates: DiAppStates});

        // workaround for https://github.com/praekelt/vumi-jssandbox-toolkit/pull/179
        self.states = new DiAppStates(self);
        self.push_api = new PushMessageApi(self.im,self);

        self.init = function() {
            return self.im
                .contacts.for_user()
                .then(function(user_contact) {
                    self.contact = user_contact;
                });
        };

        self.get_date = function() {
            if (_.isUndefined(self.im.config.override_date)) {
                return new Date();
            } else {
                return Date.parse(self.im.config.override_date);
            }
        };

        self.get_date_string = function() {
            return self.get_date().toISOString();
        };

        self.states.add('states:noop', function(name) {
            var state = self.im.user.state.serialize();

            return new State(name, {
                send_reply: false,
                events: {
                    'im im:shutdown': function() {
                        self.im.user.state.reset(state);
                    }
                }
            });
        });

        self.states.add('states:push:start', function(name,opts) {
            //Rerandomize week_day - on client's orders
            self.push_api.rerandomize_week_day();

            //Get the new message
            var msg = self.push_api.get_push_msg();
            var field = self.push_api.get_push_field(msg.type,msg.num);

            //Save contact date
            self.contact.extra['it_'+field] = self.get_date_string();

            return self
                .im.contacts.save(self.contact)
                .then(function() {
                    return new FreeText(name, {
                        question: msg.question,
                        next: function(content) {
                            self.contact.extra[field+'_reply'] = content;
                            self.contact.extra['it_'+field+'_reply'] = self.get_date_string();
                            return self
                                .im.contacts.save(self.contact)
                                .thenResolve('states:push:end');
                        }
                    });
                });
        });

        self.states.add('states:push:end', function(name) {
            console.log("meow");
            return new EndState(name, {
                send_reply: false,
                next: self.start_state_name
            });
        });
    });

    var DiSmsApp = BaseDiApp.extend(function(self) {
        BaseDiApp.call(self, 'states:start');

        self.states.add('states:start', function(name) {
            return new EndState(name, {
                text: 'Nothing for you here'
            });
        });
    });

    return {
        DiAppStates : DiAppStates,
        BaseDiApp : BaseDiApp,
        DiSmsApp : DiSmsApp
    };
}();<commit_msg>Fixed issues + added event<commit_after>di.base = function() {
    var vumigo = require('vumigo_v02');
    var App = vumigo.App;
    var AppStates = vumigo.app.AppStates;
    var State = vumigo.states.State;
    var FreeText = vumigo.states.FreeText;
    var EndState = vumigo.states.EndState;
    var PushMessageApi = di.pushmessage.PushMessageApi;

    var DiAppStates  = AppStates.extend(function(self,app,opts) {
        AppStates.call(self, app);
        var create =  self.create;
        self.create = function(name,opts) {

            var push_api =  new PushMessageApi(app.im,app);
            if (!app.is(self.app.im.msg.inbound_push_trigger)) {
                return create(name, opts);
            }
            return !push_api.should_push()
                ? create('states:noop')
                : create('states:push:start');
        };
    });

    var BaseDiApp = App.extend(function(self, start_state_name) {
        App.call(self, start_state_name, {AppStates: DiAppStates});

        // workaround for https://github.com/praekelt/vumi-jssandbox-toolkit/pull/179
        self.states = new DiAppStates(self);
        self.push_api = new PushMessageApi(self.im,self);

        self.init = function() {
            return self.im
                .contacts.for_user()
                .then(function(user_contact) {
                    self.contact = user_contact;
                });
        };

        self.get_date = function() {
            if (_.isUndefined(self.im.config.override_date)) {
                return new Date();
            } else {
                return Date.parse(self.im.config.override_date);
            }
        };

        self.get_date_string = function() {
            return self.get_date().toISOString();
        };

        self.states.add('states:noop', function(name) {
            var state = self.im.user.state.serialize();

            return new State(name, {
                send_reply: false,
                events: {
                    'im im:shutdown': function() {
                        self.im.user.state.reset(state);
                    }
                }
            });
        });

        self.states.add('states:push:start', function(name,opts) {
            //Rerandomize week_day - on client's orders
            self.push_api.rerandomize_week_day();

            //Get the new message
            var msg = self.push_api.get_push_msg();
            var field = self.push_api.get_push_field(msg.type,msg.num);

            return self
                .im.contacts.save(self.contact)
                .then(function() {
                    return new FreeText(name, {
                        question: msg.question,
                        events: {
                            //Needs to be saved when FreeText is served
                            'state state:enter': function() {
                                self.contact.extra['it_'+field] = self.get_date_string();
                                return self.im.contacts.save(self.contact);
                            }
                        },
                        next: function(content) {
                            //Needs to be saved on reply
                            self.contact.extra[field+'_reply'] = content;
                            self.contact.extra['it_'+field+'_reply'] = self.get_date_string();
                            return self
                                .im.contacts.save(self.contact)
                                .thenResolve('states:push:end');
                        }
                    });
                });
        });

        self.states.add('states:push:end', function(name) {
            return new EndState(name, {
                send_reply: false,
                next: self.start_state_name
            });
        });
    });

    var DiSmsApp = BaseDiApp.extend(function(self) {
        BaseDiApp.call(self, 'states:start');

        self.states.add('states:start', function(name) {
            return new EndState(name, {
                text: 'Nothing for you here'
            });
        });
    });

    return {
        DiAppStates : DiAppStates,
        BaseDiApp : BaseDiApp,
        DiSmsApp : DiSmsApp
    };
}();<|endoftext|>


<commit_before>import { error } from "./core/errors";

import { classes } from "./core/classes";
import { content } from "./core/content";
import { events } from "./core/events";
import { selection } from "./core/selection";

export function select( selector = window, baseElement = document ) {
	let obj = { selector: null };

	if ( typeof selector === "string" ) {
		try {
			obj.elements = baseElement.querySelectorAll( selector );
			obj.selector = selector;
		} catch ( e ) {
			// TODO check if we can just reset the elements perhaps rather than throwing an error?
			error( true, e );
			obj.elements = [];
		}
	} else if ( Array.isArray( selector ) ) {
		obj.elements = [ ...selector ];
	} else {
		obj.elements = [ selector ];
	}

	/**
	 * Apply a callback for each element in this object
	 *
	 * @param  {Function} callback Callback function
	 * @return {Object}
	 */
	obj.apply = function( callback ) {
		for ( let i = 0; i < obj.elements.length; i++ ) {
			callback( obj.elements[i] );
		}

		return obj;
	};

	/**
	 * Extend the functionality
	 *
	 * @param  {Function} callback [description]
	 * @return {[type]}            [description]
	 */
	obj.extend = function( callback ) {
		callback( obj );
	};

	/**
	 * Extend the obj with all the parts
	 */
	obj.extend( classes );
	obj.extend( content );
	obj.extend( events );
	obj.extend( selection );

    return obj;
}
<commit_msg>added each<commit_after>import { error } from "./core/errors";

import { classes } from "./core/classes";
import { content } from "./core/content";
import { events } from "./core/events";
import { selection } from "./core/selection";

export function select( selector = window, baseElement = document ) {
	let obj = { selector: null };

	if ( typeof selector === "string" ) {
		try {
			obj.elements = baseElement.querySelectorAll( selector );
			obj.selector = selector;
		} catch ( e ) {
			// TODO check if we can just reset the elements perhaps rather than throwing an error?
			error( true, e );
			obj.elements = [];
		}
	} else if ( Array.isArray( selector ) ) {
		obj.elements = [ ...selector ];
	} else {
		obj.elements = [ selector ];
	}

	/**
	 * Apply a callback for each element in this object
	 *
	 * @param  {Function} callback Callback function
	 * @return {Object}
	 */
	obj.apply = function( callback ) {
		for ( let i = 0; i < obj.elements.length; i++ ) {
			callback( obj.elements[i] );
		}

		return obj;
	};

	/**
	 * Each is just like apply, but wraps the items in a new select
	 *
	 * @param  {Function} callback Callback function
	 * @return {Object}
	 */
	obj.each = function( callback ) {
		obj.apply( ( item ) => {
			callback( select( item ) );
		} );

		return obj;
	};

	/**
	 * Extend the functionality
	 *
	 * @param  {Function} callback [description]
	 * @return {[type]}            [description]
	 */
	obj.extend = function( callback ) {
		callback( obj );
	};

	/**
	 * Extend the obj with all the parts
	 */
	obj.extend( classes );
	obj.extend( content );
	obj.extend( events );
	obj.extend( selection );

    return obj;
}
<|endoftext|>


<commit_before>/*
 * Global server wide users list handling
 */
Ape.addEvent('adduser', function(user) {
	var name = user.prop('name');

	if(typeof name == "string"){
		name = name.toLowerCase();
		Ape.userlist[name] = user;
	}
});

Ape.addEvent('deluser', function(user) {
	var name = user.prop('name');

	if(typeof name == "string"){
		name = name.toLowerCase();
		delete Ape.userlist[name];
	}
});

/*
 * Global server wide channel's users counter
 */
Ape.addEvent("mkchan", function(channel) {
	//Create users property
	channel.users = {};
	Ape.triggerChannelEvent(channel, "create", [channel]);
});

Ape.addEvent("beforeJoin", function(user, channel) {
	channel.users[user.prop("pubid")] = user;

	user.channels[channel.prop("name")] = channel;

	Ape.triggerChannelEvent(channel, "join", [user, channel]);
});

Ape.addEvent("left", function(user, channel) {
	Ape.triggerChannelEvent(channel, "left", [user, channel]);

	delete channel.users[user.prop("pubid")];
	delete user.channels[channel.prop("name")];
});<commit_msg>added channel destroy event trigger<commit_after>/*
 * Global server wide users list handling
 */
Ape.addEvent('adduser', function(user) {
	var name = user.prop('name');

	if(typeof name == "string"){
		name = name.toLowerCase();
		Ape.userlist[name] = user;
	}
});

Ape.addEvent('deluser', function(user) {
	var name = user.prop('name');

	if(typeof name == "string"){
		name = name.toLowerCase();
		delete Ape.userlist[name];
	}
});

/*
 * Global server wide channel's users counter
 */
Ape.addEvent("rmchan", function(channel) {
	Ape.triggerChannelEvent(channel, "destroy", [channel]);
});
Ape.addEvent("mkchan", function(channel) {
	//Create users property
	channel.users = {};
	Ape.triggerChannelEvent(channel, "create", [channel]);
});

Ape.addEvent("beforeJoin", function(user, channel) {
	channel.users[user.prop("pubid")] = user;

	user.channels[channel.prop("name")] = channel;

	Ape.triggerChannelEvent(channel, "join", [user, channel]);
});

Ape.addEvent("left", function(user, channel) {
	Ape.triggerChannelEvent(channel, "left", [user, channel]);

	delete channel.users[user.prop("pubid")];
	delete user.channels[channel.prop("name")];
});<|endoftext|>


<commit_before>/*
 * Copyright (c) 2008-2014 The Open Source Geospatial Foundation
 *
 * Published under the BSD license.
 * See https://github.com/geoext/geoext2/blob/master/license.txt for the full
 * text of the license.
 */

/** api: example[popup]
 *  Feature Popup
 *  -------------
 *  Display a popup with feature information.
 */

Ext.require([
    'Ext.Window', // useless in fact, since we're using ext-all.js in the example
    'GeoExt.panel.Map',
    'GeoExt.window.Popup'
]);

var mapPanel, popup;

Ext.onReady(function() {

    // create a vector layer, add a feature into it
    var vectorLayer = new OpenLayers.Layer.Vector("vector");
    vectorLayer.addFeatures(
        new OpenLayers.Feature.Vector(
            new OpenLayers.Geometry.Point(-45, 5)
        )
    );

    // create select feature control
    var selectCtrl = new OpenLayers.Control.SelectFeature(vectorLayer);

    // define "createPopup" function
    var bogusMarkup = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. " +
            "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. " +
            "Lorem ipsum dolor sit amet, consectetuer adipiscing elit." +
            "Lorem ipsum dolor sit amet, consectetuer adipiscing elit.";

    function createPopup(feature) {
        var checkConstrOpt = Ext.DomQuery.select('input[name="constrainOpt"]:checked')[0].value,
            undef,
            constrainOpts = {
                constrain: (checkConstrOpt === 'constrain-full') ? true : undef,
                constrainHeader: (checkConstrOpt === 'constrain-header') ? true : undef
            },
            popupOpts = Ext.apply({
                title: 'My Popup',
                location: feature,
                width:200,
                html: bogusMarkup,
                maximizable: true,
                collapsible: true,
                anchorPosition: 'auto'
            }, constrainOpts);

        popup = Ext.create('GeoExt.window.Popup', popupOpts);
        // unselect feature when the popup
        // is closed
        popup.on({
            close: function() {
                if(OpenLayers.Util.indexOf(vectorLayer.selectedFeatures,
                                           this.feature) > -1) {
                    selectCtrl.unselect(this.feature);
                }
            }
        });
        popup.show();
    }

    // create popup on "featureselected"
    vectorLayer.events.on({
        featureselected: function(e) {
            createPopup(e.feature);
        }
    });

    // create Ext window including a map panel
    var mapwin = Ext.create('Ext.Window', {
        layout: "fit",
        title: "Map",
        closeAction: "hide",
        width: 600,
        height: 400,
        x: 20,
        y: 250,
        items: {
            xtype: "gx_mappanel",
            border: false,
            region: "center",
            layers: [
                new OpenLayers.Layer.WMS(
                    "OpenStreetMap WMS",
                    "http://ows.terrestris.de/osm/service?",
                    {layers: 'OSM-WMS'},
                    {
                        attribution: '© terrestris GmbH & Co. KG
' +
                            'Data © OpenStreetMap ' +
                            'contributors'
                    }
                ),
                new OpenLayers.Layer.Vector('vector',{
                    isBaseLayer: true
                }),
                vectorLayer
            ]
        }
    });
    mapwin.show();

    mapPanel = mapwin.items.get(0);
    mapPanel.map.addControl(selectCtrl);
    selectCtrl.activate();
});
<commit_msg>Ensure the popup is always on top.<commit_after>/*
 * Copyright (c) 2008-2014 The Open Source Geospatial Foundation
 *
 * Published under the BSD license.
 * See https://github.com/geoext/geoext2/blob/master/license.txt for the full
 * text of the license.
 */

/** api: example[popup]
 *  Feature Popup
 *  -------------
 *  Display a popup with feature information.
 */

Ext.require([
    'Ext.Window', // useless in fact, since we're using ext-all.js in the example
    'GeoExt.panel.Map',
    'GeoExt.window.Popup'
]);

var mapPanel, popup;

Ext.onReady(function() {

    // create a vector layer, add a feature into it
    var vectorLayer = new OpenLayers.Layer.Vector("vector");
    vectorLayer.addFeatures(
        new OpenLayers.Feature.Vector(
            new OpenLayers.Geometry.Point(-45, 5)
        )
    );

    // create select feature control
    var selectCtrl = new OpenLayers.Control.SelectFeature(vectorLayer);

    // define "createPopup" function
    var bogusMarkup = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. " +
            "Lorem ipsum dolor sit amet, consectetuer adipiscing elit. " +
            "Lorem ipsum dolor sit amet, consectetuer adipiscing elit." +
            "Lorem ipsum dolor sit amet, consectetuer adipiscing elit.";

    function createPopup(feature) {
        var checkConstrOpt = Ext.DomQuery.select('input[name="constrainOpt"]:checked')[0].value,
            undef,
            constrainOpts = {
                constrain: (checkConstrOpt === 'constrain-full') ? true : undef,
                constrainHeader: (checkConstrOpt === 'constrain-header') ? true : undef
            },
            popupOpts = Ext.apply({
                title: 'My Popup',
                location: feature,
                width:200,
                html: bogusMarkup,
                maximizable: true,
                collapsible: true,
                anchorPosition: 'auto',
                alwaysOnTop: true
            }, constrainOpts);

        popup = Ext.create('GeoExt.window.Popup', popupOpts);
        // unselect feature when the popup
        // is closed
        popup.on({
            close: function() {
                if(OpenLayers.Util.indexOf(vectorLayer.selectedFeatures,
                                           this.feature) > -1) {
                    selectCtrl.unselect(this.feature);
                }
            }
        });
        popup.show();
    }

    // create popup on "featureselected"
    vectorLayer.events.on({
        featureselected: function(e) {
            createPopup(e.feature);
        }
    });

    // create Ext window including a map panel
    var mapwin = Ext.create('Ext.Window', {
        layout: "fit",
        title: "Map",
        closeAction: "hide",
        width: 600,
        height: 400,
        x: 20,
        y: 250,
        items: {
            xtype: "gx_mappanel",
            border: false,
            region: "center",
            layers: [
                new OpenLayers.Layer.WMS(
                    "OpenStreetMap WMS",
                    "http://ows.terrestris.de/osm/service?",
                    {layers: 'OSM-WMS'},
                    {
                        attribution: '© terrestris GmbH & Co. KG
' +
                            'Data © OpenStreetMap ' +
                            'contributors'
                    }
                ),
                new OpenLayers.Layer.Vector('vector',{
                    isBaseLayer: true
                }),
                vectorLayer
            ]
        }
    });
    mapwin.show();

    mapPanel = mapwin.items.get(0);
    mapPanel.map.addControl(selectCtrl);
    selectCtrl.activate();
});
<|endoftext|>


<commit_before>var mqtt = require('../..')
  , util = require('util');

mqtt.createServer(function(client) {
  var self = this;

  if (!self.clients) self.clients = {};

  client.on('connect', function(packet) {
    self.clients[packet.clientId] = client;
    client.id = packet.clientId;
    console.log("CONNECT: client id: " + client.id);
    client.subscriptions = [];
    client.connack({returnCode: 0});
  });

  client.on('subscribe', function(packet) {
    var granted = [];

    console.log("SUBSCRIBE(%s): %j", client.id, packet);

    for (var i = 0; i < packet.subscriptions.length; i++) {
      var qos = packet.subscriptions[i].qos
        , topic = packet.subscriptions[i].topic
        , reg = new RegExp(topic.replace('+', '[^\/]+').replace('#', '.+') + '$');

      granted.push(qos);
      client.subscriptions.push(reg);
    }

    client.suback({messageId: packet.messageId, granted: granted});
  });

  client.on('publish', function(packet) {
    console.log("PUBLISH(%s): %j", client.id, packet);
    for (var k in self.clients) {
      var c = self.clients[k]
        , publish = false;

      for (var i = 0; i < c.subscriptions.length; i++) {
        var s = c.subscriptions[i];

        if (s.test(packet.topic)) {
          publish = true;
        }
      }

      if (publish) {
        c.publish({topic: packet.topic, payload: packet.payload});
      }
    }
  });

  client.on('pingreq', function(packet) {
    console.log('PINGREQ(%s)', client.id);
    client.pingresp();
  });

  client.on('disconnect', function(packet) {
    client.stream.end();
  });

  client.on('close', function(packet) {
    delete self.clients[client.id];
  });

  client.on('error', function(e) {
    client.stream.end();
    console.log(e);
  });
}).listen(process.argv[2] || 1883);
<commit_msg>[minor] examples/server/orig.js: avoiding unnecessary regexp tests<commit_after>var mqtt = require('../..')
  , util = require('util');

mqtt.createServer(function(client) {
  var self = this;

  if (!self.clients) self.clients = {};

  client.on('connect', function(packet) {
    self.clients[packet.clientId] = client;
    client.id = packet.clientId;
    console.log("CONNECT: client id: " + client.id);
    client.subscriptions = [];
    client.connack({returnCode: 0});
  });

  client.on('subscribe', function(packet) {
    var granted = [];

    console.log("SUBSCRIBE(%s): %j", client.id, packet);

    for (var i = 0; i < packet.subscriptions.length; i++) {
      var qos = packet.subscriptions[i].qos
        , topic = packet.subscriptions[i].topic
        , reg = new RegExp(topic.replace('+', '[^\/]+').replace('#', '.+') + '$');

      granted.push(qos);
      client.subscriptions.push(reg);
    }

    client.suback({messageId: packet.messageId, granted: granted});
  });

  client.on('publish', function(packet) {
    console.log("PUBLISH(%s): %j", client.id, packet);
    for (var k in self.clients) {
      var c = self.clients[k];

      for (var i = 0; i < c.subscriptions.length; i++) {
        var s = c.subscriptions[i];

        if (s.test(packet.topic)) {
          c.publish({topic: packet.topic, payload: packet.payload});
          break;
        }
      }
    }
  });

  client.on('pingreq', function(packet) {
    console.log('PINGREQ(%s)', client.id);
    client.pingresp();
  });

  client.on('disconnect', function(packet) {
    client.stream.end();
  });

  client.on('close', function(packet) {
    delete self.clients[client.id];
  });

  client.on('error', function(e) {
    client.stream.end();
    console.log(e);
  });
}).listen(process.argv[2] || 1883);
<|endoftext|>


<commit_before>function change_row_state($orderid, $tr, $state, $lqty, $rqty, $tqty)
{
    if($tqty === undefined)
    {
        $lqty = -1;
        $rqty = -1;
        $tqty = -1;
    }
    var $id = $tr.attr("id"); // This will give Id of the item
    var $setstate = -1;
    switch ($state)
    {
        case "fz-success":
            $setstate = 1;
            break;
        case "edit":
            $setstate = 0;
            break;
        case "fz-danger":
            $setstate = 2;
            break;
        default:
            $setstate = -1;
    }

    $data = {};
    // If edit then also send new R,L and Total Qty
    if ($tr.attr("class")==="edit" && $state === "fz-success")
    {
        $data = {
            oiid: $id,
            oiomid: $orderid,
            oileftqty: $lqty,
            oirightqty: $rqty,
            oitotalqty: $tqty,
            status: $setstate
        };
    }
    else
    {
        $data = {
            oiid: $id,
            oiomid: $orderid,
            status: $setstate
        };
    }
    if ($tr.attr("class") != $state && $setstate != -1)
    {
        $.ajax({
                type: "POST",
                url: "../orders/order_item_state",
                dataType: 'json',
                data: $data,
                success: function(res)
                {
                    $tr.attr("class",$state);
                    console.log(res);
                }
            });
    }
}

$(document).ready(function()
{
    $('#print').click(function(event) {
        /* Act on the event */
        window.print();
    });
    // When Item is Ready.
    $('.done').on('click',function()
    {
        // Setting up vars for function
        var tr = $(this).parent();
        var orderid = $('#omid').attr("data-omid");
        var state = "fz-success";
        var lqty = parseInt(tr.children(".LQty").html());
        var rqty = parseInt(tr.children(".RQty").html());
        var tqty = parseInt(tr.children(".TQty").html());
        // Calling function
        change_row_state(orderid, tr, state, lqty, rqty, tqty);
        ////console.log(tqty);
    });
    // When Item is NOT Available
    $('.delete').on('click',function()
    {
        // Setting up vars for function
        var tr = $(this).parent();
        var orderid = $('#omid').attr("data-omid");
        var state = "fz-danger";
        // Calling function
        change_row_state(orderid, tr, state);
    });
    // When Item QTY needs to be changed.
    $('.edit').on('click',function()
    {
        // Setting up vars for function
        var tr = $(this).parent();
        var orderid = $('#omid').attr("data-omid");
        var state = "edit";
        // Calling function
        change_row_state(orderid, tr, state);
        // Make Qty columns editable
        $(this).nextAll('.RQty').attr("contenteditable","true");
        $(this).nextAll('.LQty').attr("contenteditable","true");
        $(this).nextAll('.TQty').attr("contenteditable",true);
    });
	// Store1 or store2 button clicked
	$("#OmStore1,#OmStore2").on('click',function(e)
	{
		var storeName = e.target.id;
		var orderId = $("#omid").attr("data-omid");
		var state = ($("#"+storeName).attr("data-state") == 0)? 1 : 0;
		$.ajax({
                type: "POST",
                url: "../orders/set_store_state",
                dataType: 'json',
                data: {
					orderid: orderId,
					storename: storeName,
					status: state
				},
                success: function(res)
                {
					$("#"+storeName).attr("data-state",state); // Also need to chang class but cant figure how.
                }
            });

	});

});

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
<commit_msg>last commit from 170424<commit_after>function change_row_state($orderid, $tr, $state, $lqty, $rqty, $tqty)
{
    if($tqty === undefined)
    {
        $lqty = -1;
        $rqty = -1;
        $tqty = -1;
    }
    var $id = $tr.attr("id"); // This will give Id of the item
    var $setstate = -1;
    switch ($state)
    {
        case "fz-success":
            $setstate = 1;
            break;
        case "edit":
            $setstate = 0;
            break;
        case "fz-danger":
            $setstate = 2;
            break;
        default:
            $setstate = -1;
    }

    $data = {};
    // If edit then also send new R,L and Total Qty
    if ($tr.attr("class")==="edit" && $state === "fz-success")
    {
        $data = {
            oiid: $id,
            oiomid: $orderid,
            oileftqty: $lqty,
            oirightqty: $rqty,
            oitotalqty: $tqty,
            status: $setstate
        };
    }
    else
    {
        $data = {
            oiid: $id,
            oiomid: $orderid,
            status: $setstate
        };
    }
    if ($tr.attr("class") != $state && $setstate != -1)
    {
        $.ajax({
                type: "POST",
                url: "../orders/order_item_state",
                dataType: 'json',
                data: $data,
                success: function(res)
                {
                    $tr.attr("class",$state);
                    console.log(res);
                }
            });
    }
}

$(document).ready(function()
{
    $('#print').click(function(event) {
        /* Act on the event */
        window.print();
    });
    // When Item is Ready.
    $('.done').on('click',function()
    {
        // Setting up vars for function
        var tr = $(this).parent();
        var orderid = $('#omid').attr("data-omid");
        var state = "fz-success";
        var lqty = parseInt(tr.children(".LQty").html());
        var rqty = parseInt(tr.children(".RQty").html());
        var tqty = parseInt(tr.children(".TQty").html());
        // Calling function
        change_row_state(orderid, tr, state, lqty, rqty, tqty);
        ////console.log(tqty);
    });
    // When Item is NOT Available
    $('.delete').on('click',function()
    {
        // Setting up vars for function
        var tr = $(this).parent();
        var orderid = $('#omid').attr("data-omid");
        var state = "fz-danger";
        // Calling function
        change_row_state(orderid, tr, state);
    });
    // When Item QTY needs to be changed.
    $('.edit').on('click',function()
    {
        // Setting up vars for function
        var tr = $(this).parent();
        var orderid = $('#omid').attr("data-omid");
        var state = "edit";
        // Calling function
        change_row_state(orderid, tr, state);
        // Make Qty columns editable
        $(this).nextAll('.RQty').attr("contenteditable","true");
        $(this).nextAll('.LQty').attr("contenteditable","true");
        $(this).nextAll('.TQty').attr("contenteditable",true);
    });
	// Store1 or store2 button clicked
	$("#OmStore1,#OmStore2").on('click',function(e)
	{
		var storeName = e.target.id;
		var orderId = $("#omid").attr("data-omid");
		var state = ($("#"+storeName).attr("data-state") == 0)? 1 : 0;
		$.ajax({
                type: "POST",
                url: "../orders/set_store_state",
                dataType: 'json',
                data: {
					orderid: orderId,
					storename: storeName,
					status: state
				},
                success: function(res)
                {
					// primary color #337ab7
					//  success color #5cb85c
					$("#"+storeName).attr("data-state",state); // Also need to chang class but cant figure how.
                }
            });

	});

});

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
<|endoftext|>


<commit_before>var port = require('port');

port({
	read: 8005,
	write: 8006,
	encode: 'ascii',
	flags: ['-noprefs', '-send', 'pd dsp 1, dsp 0', './port.pd']
})
.on('connect', function(){
	console.log('on connect');
	this.write('a message to pd;\n');
})
.on('data', function(buffer){
	console.log('on data', buffer.toString());
})
.create();
<commit_msg>fixes typo encode to encoding<commit_after>var port = require('port');

port({
	read: 8005,
	write: 8006,
	encoding: 'ascii',
	flags: ['-noprefs', '-send', 'pd dsp 1, dsp 0', './port.pd']
})
.on('connect', function(){
	console.log('on connect');
	this.write('a message to pd;\n');
})
.on('data', function(buffer){
	console.log('on data', buffer.toString());
})
.create();
<|endoftext|>


<commit_before>/**
 * Boot.js
 *
 * Read out all the configs. register exit handlers. start logging.
 *
 * Then finally start ManiaJS.
 */
'use strict';

import Bunyan             from 'bunyan';
import PrettyStream       from 'bunyan-prettystream';

import App                from './app';

// Logger
var prettyOut = new PrettyStream();
    prettyOut.pipe(process.stdout);

var log = Bunyan.createLogger({
  name: 'maniajs',
  streams: [{
    level: 'debug',
    type: 'raw',
    stream: prettyOut
  }, {
    level: 'info',
    path:   __dirname + '/../log/application.log'
  }]
});
log.info('Starting ManiaJS...');

/** Start ManiaJS */
let app = new App(log);

/** Set Error and exit handlers */
function exitHandler(options) {
  if (options.cleanup) {
    log.info('ManiaJS is going to shutdown...');
    app.exit();
  }
  if (options.error)
    log.error('Uncaught Exception: ', options.error.stack);
  if (options.exit) {
    //process.exit();
  }
}
process.on('exit',              (   ) => exitHandler({cleanup: true}));
process.on('SIGINT',            (   ) => exitHandler({exit   : true}));
process.on('uncaughtException', (err) => exitHandler({error  : err}));

/** Start ManiaJS */
app.prepare()
  .then(()=>app.run())
  .catch((err)=>log.fatal(err));

/** Make sure we will resume executing process */
process.stdin.resume();
<commit_msg>Fixing background continue.<commit_after>/**
 * Boot.js
 *
 * Read out all the configs. register exit handlers. start logging.
 *
 * Then finally start ManiaJS.
 */
'use strict';

import Bunyan             from 'bunyan';
import PrettyStream       from 'bunyan-prettystream';

import App                from './app';

// Logger
var prettyOut = new PrettyStream();
    prettyOut.pipe(process.stdout);

var log = Bunyan.createLogger({
  name: 'maniajs',
  streams: [{
    level: 'debug',
    type: 'raw',
    stream: prettyOut
  }, {
    level: 'info',
    path:   __dirname + '/../log/application.log'
  }]
});
log.info('Starting ManiaJS...');

/** Start ManiaJS */
let app = new App(log);

/** Set Error and exit handlers */
function exitHandler(options) {
  if (options.cleanup) {
    log.info('ManiaJS is going to shutdown...');
    app.exit();
  }
  if (options.error)
    log.error('Uncaught Exception: ', options.error.stack);
  if (options.exit) {
    process.exit();
  }
}
process.on('exit',              (   ) => exitHandler({cleanup: true}));
process.on('SIGINT',            (   ) => exitHandler({exit   : true}));
process.on('uncaughtException', (err) => exitHandler({error  : err}));

/** Start ManiaJS */
app.prepare()
  .then(()=>app.run())
  .catch((err)=>log.fatal(err));

/** Make sure we will resume executing process */
process.stdin.resume();
<|endoftext|>


<commit_before>(function ($, root, undefined) {

  $(function () {

    'use strict';

    var isLoaded = false;

    //Function to the css rule
    function checkSize(){
      switch( $(window).width() > 992 )
      {
        case true:
          if(!isLoaded)
          {
            $('.js-flickity').flickity({
              // options
              freeScroll: false,
              pageDots: false
            });
          };

          //Get template from localized data in function.php::223
          $('#posts-hero').html(template.tile);

          //Do magic based on screen size
          if( $(window).width() >= 1200 )
          {

            // DOM ready, take it away
            $('.isotope').isotope({
              layoutMode: 'masonryHorizontal',
              itemSelector: '.item',
              resizable: false,
              //sortBy: 'random',
              masonryHorizontal: {
                rowHeight: 144,
                gutter: 30
              }
            });
            if(isLoaded)
            {
              $('.js-flickity').flickity({
                // options
                freeScroll: false,
                pageDots: false
              }).flickity('reloadCells');
            }

          } else {
            $('.isotope').isotope({
              layoutMode: 'masonryHorizontal',
              itemSelector: '.item',
              resizable: false,
              //sortBy: 'random',
              masonryHorizontal: {
                rowHeight: 111,
                gutter: 30
              }
            });
            if(isLoaded)
            {
              $('.js-flickity').flickity({
                // options
                freeScroll: false,
                pageDots: false
              }).flickity('reloadCells');
            }
          }
          break;
        default:
          //If below 970 loat carousel from localized data in function.php::223
          console.log('made it');
          $('#posts-hero').html(template.carousel);
      }
      (function(){
        isLoaded = true;
      })();
    }

    // run test on initial page load
    checkSize();

    // run test on resize of the window
    $(window).resize(checkSize);

  });

})(jQuery, this);<commit_msg>add promise to fix onload bug.<commit_after>(function ($, root, undefined) {

  $(function () {

    'use strict';

    function initiateFlickity()
    {
      $('.gallery').flickity({
        freeScroll: false,
        pageDots: false
      });
    }

    //Function to the css rule
    function checkSize(){
      switch( $(window).width() > 992 )
      {
        case true:

          //Get template from localized data in function.php::223
          $('#posts-hero').html(template.tile).promise().done(function()
          {

              initiateFlickity();

          });

          //Do magic based on screen size
          if( $(window).width() >= 1200 )
          {

            // DOM ready, take it away
            $('.isotope').isotope({
              layoutMode: 'masonryHorizontal',
              itemSelector: '.item',
              resizable: false,
              //sortBy: 'random',
              masonryHorizontal: {
                rowHeight: 144,
                gutter: 30
              }
            });
          } else {
            $('.isotope').isotope({
              layoutMode: 'masonryHorizontal',
              itemSelector: '.item',
              resizable: false,
              //sortBy: 'random',
              masonryHorizontal: {
                rowHeight: 111,
                gutter: 30
              }
            });
          }
          break;
        default:
          //If below 970 loat carousel from localized data in function.php::223
          $('#posts-hero').html(template.carousel);
      }
    }

    // run test on initial page load
    checkSize();

    // run test on resize of the window
    $(window).resize(checkSize);

  });

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


<commit_before>/* jshint unused: false */
import ajax from 'ghost/utils/ajax';
import ValidationEngine from 'ghost/mixins/validation-engine';

var ForgottenController = Ember.Controller.extend(ValidationEngine, {
    email: '',
    submitting: false,

    // ValidationEngine settings
    validationType: 'forgotten',

    actions: {
        submit: function () {
            var self = this,
                data = self.getProperties('email');

            this.toggleProperty('submitting');
            this.validate({ format: false }).then(function () {
                ajax({
                    url: self.get('ghostPaths.url').api('authentication', 'passwordreset'),
                    type: 'POST',
                    data: {
                        passwordreset: [{
                            email: data.email
                        }]
                    }
                }).then(function (resp) {
                    self.toggleProperty('submitting');
                    self.notifications.showSuccess('Please check your email for instructions.');
                    self.transitionToRoute('signin');
                }).catch(function (resp) {
                    self.toggleProperty('submitting');
                    self.notifications.showAPIError(resp, 'There was a problem logging in, please try again.');
                });
            }).catch(function (errors) {
                self.toggleProperty('submitting');
                self.notifications.showErrors(errors);
            });
        }
    }
});

export default ForgottenController;
<commit_msg>Stop validation error notification stack<commit_after>/* jshint unused: false */
import ajax from 'ghost/utils/ajax';
import ValidationEngine from 'ghost/mixins/validation-engine';

var ForgottenController = Ember.Controller.extend(ValidationEngine, {
    email: '',
    submitting: false,

    // ValidationEngine settings
    validationType: 'forgotten',

    actions: {
        submit: function () {
            var self = this,
                data = self.getProperties('email');

            this.toggleProperty('submitting');
            this.validate({ format: false }).then(function () {
                ajax({
                    url: self.get('ghostPaths.url').api('authentication', 'passwordreset'),
                    type: 'POST',
                    data: {
                        passwordreset: [{
                            email: data.email
                        }]
                    }
                }).then(function (resp) {
                    self.toggleProperty('submitting');
                    self.notifications.showSuccess('Please check your email for instructions.');
                    self.transitionToRoute('signin');
                }).catch(function (resp) {
                    self.toggleProperty('submitting');
                    self.notifications.closePassive();
                    self.notifications.showAPIError(resp, 'There was a problem logging in, please try again.');
                });
            }).catch(function (errors) {
                self.toggleProperty('submitting');
                self.notifications.closePassive();
                self.notifications.showErrors(errors);
            });
        }
    }
});

export default ForgottenController;
<|endoftext|>


<commit_before>define([
       "jquery", "underscore", "backbone"
      , "views/temp-snippet"
      , "helper/pubsub"
      , "text!templates/app/renderform.html"
], function(
  $, _, Backbone
  , TempSnippetView
  , PubSub
  , _renderForm
){
  return Backbone.View.extend({
    tagName: "fieldset"
    , initialize: function(){
      this.collection.on("add", this.render, this);
      this.collection.on("remove", this.render, this);
      this.collection.on("change", this.render, this);
      PubSub.on("mySnippetDrag", this.handleSnippetDrag, this);
      PubSub.on("tempMove", this.handleTempMove, this);
      PubSub.on("tempDrop", this.handleTempDrop, this);
      this.$build = $("#build");
      this.renderForm = _.template(_renderForm);
      this.render();
    }

    , render: function(){
      //Render Snippet Views
      this.$el.empty();
      var that = this;
      _.each(this.collection.renderAll(), function(snippet){
        that.$el.append(snippet);
      });
      $("#render").val(that.renderForm({
        text: _.map(this.collection.renderAllClean(), function(e){return e.html()}).join("\n")
      }));
      this.$el.appendTo("#build form");
      this.delegateEvents();
    }

    , getBottomAbove: function(eventY){
      var myFormBits = $(this.$el.find(".component"));
      var topelement = _.find(myFormBits, function(renderedSnippet) {
        if (($(renderedSnippet).position().top + $(renderedSnippet).height()) > eventY  - 90) {
          return true;
        }
        else {
          return false;
        }
      });
      if (topelement){
        return topelement;
      } else {
        return myFormBits[0];
      }
    }

    , handleSnippetDrag: function(mouseEvent, snippetModel) {
      $("body").append(new TempSnippetView({model: snippetModel}).render());
      this.collection.remove(snippetModel);
      PubSub.trigger("newTempPostRender", mouseEvent);
    }

    , handleTempMove: function(mouseEvent){
      $(".target").removeClass("target");
      if(mouseEvent.pageX >= this.$build.position().left &&
          mouseEvent.pageX < (this.$build.width() + this.$build.position().left) &&
          mouseEvent.pageY >= this.$build.position().top &&
          mouseEvent.pageY < (this.$build.height() + this.$build.position().top)){
        $(this.getBottomAbove(mouseEvent.pageY)).addClass("target");
      } else {
        $(".target").removeClass("target");
      }
    }

    , handleTempDrop: function(mouseEvent, model, index){
      if(mouseEvent.pageX >= this.$build.position().left &&
         mouseEvent.pageX < (this.$build.width() + this.$build.position().left) &&
         mouseEvent.pageY >= this.$build.position().top &&
         mouseEvent.pageY < (this.$build.height() + this.$build.position().top)) {
        var index = $(".target").index();
        $(".target").removeClass("target");
        this.collection.add(model,{at: index+1});
      } else {
        $(".target").removeClass("target");
      }
    }
  })
});
<commit_msg>fix element position bug using getBoundingClientRect() instead of jquery position()<commit_after>define([
       "jquery", "underscore", "backbone"
      , "views/temp-snippet"
      , "helper/pubsub"
      , "text!templates/app/renderform.html"
], function(
  $, _, Backbone
  , TempSnippetView
  , PubSub
  , _renderForm
){
  return Backbone.View.extend({
    tagName: "fieldset"
    , initialize: function(){
      this.collection.on("add", this.render, this);
      this.collection.on("remove", this.render, this);
      this.collection.on("change", this.render, this);
      PubSub.on("mySnippetDrag", this.handleSnippetDrag, this);
      PubSub.on("tempMove", this.handleTempMove, this);
      PubSub.on("tempDrop", this.handleTempDrop, this);
      this.$build = $("#build");
      this.build = document.getElementById("build");
      this.buildBCR = this.build.getBoundingClientRect();
      this.renderForm = _.template(_renderForm);
      this.render();
    }

    , render: function(){
      //Render Snippet Views
      this.$el.empty();
      var that = this;
      _.each(this.collection.renderAll(), function(snippet){
        that.$el.append(snippet);
      });
      $("#render").val(that.renderForm({
        text: _.map(this.collection.renderAllClean(), function(e){return e.html()}).join("\n")
      }));
      this.$el.appendTo("#build form");
      this.delegateEvents();
    }

    , getBottomAbove: function(eventY){
      var myFormBits = $(this.$el.find(".component"));
      var topelement = _.find(myFormBits, function(renderedSnippet) {
        if (($(renderedSnippet).position().top + $(renderedSnippet).height()) > eventY  - 160) {
          return true;
        }
        else {
          return false;
        }
      });
      if (topelement){
        return topelement;
      } else {
        return myFormBits[0];
      }
    }

    , handleSnippetDrag: function(mouseEvent, snippetModel) {
      $("body").append(new TempSnippetView({model: snippetModel}).render());
      this.collection.remove(snippetModel);
      PubSub.trigger("newTempPostRender", mouseEvent);
    }

    , handleTempMove: function(mouseEvent){
      $(".target").removeClass("target");
      if(mouseEvent.pageX >= this.buildBCR.left &&
          mouseEvent.pageX < (this.$build.width() + this.buildBCR.left) &&
          mouseEvent.pageY >= this.buildBCR.top &&
          mouseEvent.pageY < (this.$build.height() + this.buildBCR.top)){
        $(this.getBottomAbove(mouseEvent.pageY)).addClass("target");
      } else {
        $(".target").removeClass("target");
      }
    }

    , handleTempDrop: function(mouseEvent, model, index){
      if(mouseEvent.pageX >= this.buildBCR.left &&
         mouseEvent.pageX < (this.$build.width() + this.buildBCR.left) &&
         mouseEvent.pageY >= this.buildBCR.top &&
         mouseEvent.pageY < (this.$build.height() + this.buildBCR.top)) {
        var index = $(".target").index();
        $(".target").removeClass("target");
        this.collection.add(model,{at: index+1});
      } else {
        $(".target").removeClass("target");
      }
    }
  })
});
<|endoftext|>


<commit_before>'use strict'

// const Speedtest = require('../models/speedtest');
const execSync = require("child_process").execSync;

module.exports.test = (req, res) => {
  const speedy = execSync("speedtest-cli --simple").toString();
  res.send(speedy);
};
<commit_msg>Expanded new speedtest adding route<commit_after>'use strict'

// const Speedtest = require('../models/speedtest');
const execSync = require('child_process').execSync;
const q = require('q')

const speedtest = () => {
  return execSync('speedtest-cli --simple').toString();
}

module.exports.test = (req, res) => {
  q.fcall(speedtest).then(results => {
    const resArr = results.split('\n');
    resArr.pop();
    // via http://txt2re.com/index-javascript.php3?s=Download:%2082.15%20Mbit/s&3
    const regex = new RegExp('.*?([+-]?\\d*\\.\\d+)(?![-+0-9\\.])'); // eslint-disable-line no-new
    const modArr = resArr.map((item) => {
      return regex.exec(item)[1];
    });
    console.log('Value Array:\n', modArr); // eslint-disable-line no-console
  });

  res.send('Testing...');
};
<|endoftext|>


<commit_before>/* ========================================================================
 * Bootstrap: affix.js v3.1.0
 * http://getbootstrap.com/javascript/#affix
 * ========================================================================
 * Copyright 2011-2014 Twitter, Inc.
 * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
 * ======================================================================== */

+function ($) {
  'use strict';

  // AFFIX CLASS DEFINITION
  // ======================

  var Affix = function (element, options) {
    this.options = $.extend({}, Affix.DEFAULTS, options)
    this.$window = $(window)
      .on('scroll.bs.affix.data-api', $.proxy(this.checkPosition, this))
      .on('click.bs.affix.data-api',  $.proxy(this.checkPositionWithEventLoop, this))

    this.$element     = $(element)
    this.affixed      =
    this.unpin        =
    this.pinnedOffset = null

    this.checkPosition()
  }

  Affix.RESET = 'affix affix-top affix-bottom'

  Affix.DEFAULTS = {
    offset: 0
  }

  Affix.prototype.getPinnedOffset = function () {
    if (this.pinnedOffset) return this.pinnedOffset
    this.$element.removeClass(Affix.RESET).addClass('affix')
    var scrollTop = this.$window.scrollTop()
    var position  = this.$element.offset()
    return (this.pinnedOffset = position.top - scrollTop)
  }

  Affix.prototype.checkPositionWithEventLoop = function () {
    setTimeout($.proxy(this.checkPosition, this), 1)
  }

  Affix.prototype.checkPosition = function () {
    if (!this.$element.is(':visible')) return

    var scrollHeight = $(document).height()
    var scrollTop    = this.$window.scrollTop()
    var position     = this.$element.offset()
    var offset       = this.options.offset
    var offsetTop    = offset.top
    var offsetBottom = offset.bottom

    if (this.affixed == 'top') position.top += scrollTop

    if (typeof offset != 'object')         offsetBottom = offsetTop = offset
    if (typeof offsetTop == 'function')    offsetTop    = offset.top(this.$element)
    if (typeof offsetBottom == 'function') offsetBottom = offset.bottom(this.$element)

    var affix = this.unpin   != null && (scrollTop + this.unpin <= position.top) ? false :
                offsetBottom != null && (position.top + this.$element.height() >= scrollHeight - offsetBottom) ? 'bottom' :
                offsetTop    != null && (scrollTop <= offsetTop) ? 'top' : false

    if (this.affixed === affix) return
    if (this.unpin) this.$element.css('top', '')

    var affixType = 'affix' + (affix ? '-' + affix : '')
    var e         = $.Event(affixType + '.bs.affix')

    this.$element.trigger(e)

    if (e.isDefaultPrevented()) return

    this.affixed = affix
    this.unpin = affix == 'bottom' ? this.getPinnedOffset() : null

    this.$element
      .removeClass(Affix.RESET)
      .addClass(affixType)
      .trigger($.Event(affixType.replace('affix', 'affixed')))

    if (affix == 'bottom') {
      this.$element.offset({ top: scrollHeight - offsetBottom - this.$element.height() })
    }
  }

  // AFFIX PLUGIN DEFINITION
  // =======================

  var old = $.fn.affix

  $.fn.affix = function (option) {
    return this.each(function () {
      var $this   = $(this)
      var data    = $this.data('bs.affix')
      var options = typeof option == 'object' && option

      if (!data) $this.data('bs.affix', (data = new Affix(this, options)))
      if (typeof option == 'string') data[option]()
    })
  }

  $.fn.affix.Constructor = Affix

  // AFFIX NO CONFLICT
  // =================

  $.fn.affix.noConflict = function () {
    $.fn.affix = old
    return this
  }

  // AFFIX DATA-API
  // ==============

  $(window).on('load', function () {
    $('[data-spy="affix"]').each(function () {
      var $spy = $(this)
      var data = $spy.data()

      data.offset = data.offset || {}

      if (data.offsetBottom) data.offset.bottom = data.offsetBottom
      if (data.offsetTop)    data.offset.top    = data.offsetTop

      $spy.affix(data)
    })
  })

}(jQuery);
<commit_msg>removing bs affix<commit_after><|endoftext|>


<commit_before>define(['app/module'], function (module) {

  module.controller('qnaDocCtlr', [

    '$scope',
    'marked',
    'appRouting',
    'ssQnaDoc',
    'ssAnswer',
    'ssComment',
    'ssVote',
    'ssAcceptedAnswer',
    function (
      $scope,
      marked,
      appRouting,
      ssQnaDoc,
      ssAnswer,
      ssComment,
      ssVote,
      ssAcceptedAnswer
    ) {

      $scope.setLoading(true);

      var init = function () {
        var doc = ssQnaDoc.getOne(
          { id: appRouting.params.id },
          // by passing a contributorId we instigate the getting
          // and availability of hasVoted properties on the content
          // objects
          $scope.store.session ? $scope.store.session.id : null
        );
        doc.$ml.waiting.then(
          function () {
            $scope.doc = doc;
            $scope.setLoading(false);

           /**
            * @ngdoc method
            * @name $scope.canVoteQuestion
            * @description Returns whether current user can vote on
            * the question associated with the QnaDoc.
            * @returns {boolean} true or false
            */
            $scope.canVoteQuestion = function () {
              if (!$scope.store.session) {
                return false;
              }
              return !$scope.doc.hasVotedOn;
            };

           /**
            * @ngdoc method
            * @name $scope.canVoteAnswer
            * @description Returns whether current user can vote on
            * an answer associated with the QnaDoc.
            * @param {ssAnswer} answer The ssAnswer object.
            * @returns {boolean} true or false
            */
            $scope.canVoteAnswer = function (answer) {
              if (!$scope.store.session) {
                return false;
              }
              return !answer.hasVotedOn;
            };

            $scope.canAcceptAnswer = function (answer) {
              if (!$scope.store.session) {
                return false;
              }
              return $scope.store.session.id === $scope.doc.owner.id;
            };

            $scope.showQuestionComment = false;
            $scope.showAnswerComment = [];
            angular.forEach($scope.doc.answers, function (answer, index) {
              $scope.showAnswerComment[index] = false;
            });

          },
          function (error) {
            if (error.status === 401) {
              $scope.setLocalError('Document Not Found');
            }
            else {
              throw new Error('loading qnaDoc with id ' + appRouting.params.id +
                  ': ' + JSON.stringify(error)
              );
            }
          }
        );

      };

      $scope.answersCountLabel = function () {
        var count = 0;
        if ($scope.doc  && $scope.doc.answers) {
          for (var i = 0; i < $scope.doc.answers.length; i++) {
            // don't count empty answer object used for new answer
            count += ($scope.doc.answers[i].id) ? 1 : 0;
          }
        }
        var plural = count !== 1;
        return count + (plural ? ' Answers' : ' Answer');
      };

      $scope.marked = function (text) {
        return marked(text);
      };

      $scope.setQueryText = function (text) {
        appRouting.go('^.explore', { q: $scope.searchbarText });
      };

      $scope.saveAnswer = function (answer) {
        if (answer.$ml.valid) {
          answer.post().$ml.waiting.then(function () {
            // Create new empty answer object for answer form
            $scope.doc.addAnswer({}, $scope.doc);
          },
          function (error) {
            if (error.status === 401) {
              $scope.setLocalError(
                'User does not have permission to answer questions'
              );
            }
            else {
              throw new Error('Error occurred: ' + JSON.stringify(error));
            }
          });
        }
      };

      $scope.saveQuestionComment = function (comment) {
        if (comment.$ml.valid) {
          comment.post().$ml.waiting.then(function () {
            $scope.doc.addComment({}, $scope.doc);
            // Show link and hide form
            $scope.showQuestionComment = false;
          },
          function (error) {
            if (error.status === 401) {
              $scope.setLocalError(
                'User does not have permission to post comments'
              );
            }
            else {
              throw new Error('Error occurred: ' + JSON.stringify(error));
            }
          });
        }
      };

      $scope.saveAnswerComment = function (comment) {
        if (comment.$ml.valid) {
          var formIndex = this.$parent.$index;
          comment.post().$ml.waiting.then(function () {
            comment.$ml.parent.addComment({}, comment.parent);
            // Show link and hide form
            $scope.showAnswerComment[formIndex] = false;
          },
          function (error) {
            if (error.status === 401) {
              $scope.setLocalError(
                'User does not have permission to post comments'
              );
            }
            else {
              throw new Error('Error occurred: ' + JSON.stringify(error));
            }
          });
        }
      };

      $scope.vote = function (val, item) {
        var vote = ssVote.create({upDown: val}, item);
        if (vote.$ml.valid) {
          vote.post().$ml.waiting.then(function () {
            // Do nothing more on success
          },
          function (error) {
            if (error.status === 400) {
              $scope.setLocalError(
                error.data.message
              );
            }
            else {
              throw new Error('Error occurred: ' + JSON.stringify(error));
            }
          });
        }
      };

      $scope.accept = function (answer) {
        window.console.log('Accept: ' + answer.id);
        var acceptedAnswer = ssAcceptedAnswer.create({}, answer);
        if (acceptedAnswer.$ml.valid) {
          acceptedAnswer.post().$ml.waiting.then(function () {
            // Do nothing more on success
          },
          function (error) {
            if (error.status === 400) {
              $scope.setLocalError(
                error.data.message
              );
            }
            else {
              throw new Error('Error occurred: ' + JSON.stringify(error));
            }
          });
        }
      };

      $scope.setPageTitle('doc');
      $scope.searchbarText = appRouting.params.q ? appRouting.params.q : null;
      init();

    }

  ]);

});
<commit_msg>browser: remove console.log statement<commit_after>define(['app/module'], function (module) {

  module.controller('qnaDocCtlr', [

    '$scope',
    'marked',
    'appRouting',
    'ssQnaDoc',
    'ssAnswer',
    'ssComment',
    'ssVote',
    'ssAcceptedAnswer',
    function (
      $scope,
      marked,
      appRouting,
      ssQnaDoc,
      ssAnswer,
      ssComment,
      ssVote,
      ssAcceptedAnswer
    ) {

      $scope.setLoading(true);

      var init = function () {
        var doc = ssQnaDoc.getOne(
          { id: appRouting.params.id },
          // by passing a contributorId we instigate the getting
          // and availability of hasVoted properties on the content
          // objects
          $scope.store.session ? $scope.store.session.id : null
        );
        doc.$ml.waiting.then(
          function () {
            $scope.doc = doc;
            $scope.setLoading(false);

           /**
            * @ngdoc method
            * @name $scope.canVoteQuestion
            * @description Returns whether current user can vote on
            * the question associated with the QnaDoc.
            * @returns {boolean} true or false
            */
            $scope.canVoteQuestion = function () {
              if (!$scope.store.session) {
                return false;
              }
              return !$scope.doc.hasVotedOn;
            };

           /**
            * @ngdoc method
            * @name $scope.canVoteAnswer
            * @description Returns whether current user can vote on
            * an answer associated with the QnaDoc.
            * @param {ssAnswer} answer The ssAnswer object.
            * @returns {boolean} true or false
            */
            $scope.canVoteAnswer = function (answer) {
              if (!$scope.store.session) {
                return false;
              }
              return !answer.hasVotedOn;
            };

            $scope.canAcceptAnswer = function (answer) {
              if (!$scope.store.session) {
                return false;
              }
              return $scope.store.session.id === $scope.doc.owner.id;
            };

            $scope.showQuestionComment = false;
            $scope.showAnswerComment = [];
            angular.forEach($scope.doc.answers, function (answer, index) {
              $scope.showAnswerComment[index] = false;
            });

          },
          function (error) {
            if (error.status === 401) {
              $scope.setLocalError('Document Not Found');
            }
            else {
              throw new Error('loading qnaDoc with id ' + appRouting.params.id +
                  ': ' + JSON.stringify(error)
              );
            }
          }
        );

      };

      $scope.answersCountLabel = function () {
        var count = 0;
        if ($scope.doc  && $scope.doc.answers) {
          for (var i = 0; i < $scope.doc.answers.length; i++) {
            // don't count empty answer object used for new answer
            count += ($scope.doc.answers[i].id) ? 1 : 0;
          }
        }
        var plural = count !== 1;
        return count + (plural ? ' Answers' : ' Answer');
      };

      $scope.marked = function (text) {
        return marked(text);
      };

      $scope.setQueryText = function (text) {
        appRouting.go('^.explore', { q: $scope.searchbarText });
      };

      $scope.saveAnswer = function (answer) {
        if (answer.$ml.valid) {
          answer.post().$ml.waiting.then(function () {
            // Create new empty answer object for answer form
            $scope.doc.addAnswer({}, $scope.doc);
          },
          function (error) {
            if (error.status === 401) {
              $scope.setLocalError(
                'User does not have permission to answer questions'
              );
            }
            else {
              throw new Error('Error occurred: ' + JSON.stringify(error));
            }
          });
        }
      };

      $scope.saveQuestionComment = function (comment) {
        if (comment.$ml.valid) {
          comment.post().$ml.waiting.then(function () {
            $scope.doc.addComment({}, $scope.doc);
            // Show link and hide form
            $scope.showQuestionComment = false;
          },
          function (error) {
            if (error.status === 401) {
              $scope.setLocalError(
                'User does not have permission to post comments'
              );
            }
            else {
              throw new Error('Error occurred: ' + JSON.stringify(error));
            }
          });
        }
      };

      $scope.saveAnswerComment = function (comment) {
        if (comment.$ml.valid) {
          var formIndex = this.$parent.$index;
          comment.post().$ml.waiting.then(function () {
            comment.$ml.parent.addComment({}, comment.parent);
            // Show link and hide form
            $scope.showAnswerComment[formIndex] = false;
          },
          function (error) {
            if (error.status === 401) {
              $scope.setLocalError(
                'User does not have permission to post comments'
              );
            }
            else {
              throw new Error('Error occurred: ' + JSON.stringify(error));
            }
          });
        }
      };

      $scope.vote = function (val, item) {
        var vote = ssVote.create({upDown: val}, item);
        if (vote.$ml.valid) {
          vote.post().$ml.waiting.then(function () {
            // Do nothing more on success
          },
          function (error) {
            if (error.status === 400) {
              $scope.setLocalError(
                error.data.message
              );
            }
            else {
              throw new Error('Error occurred: ' + JSON.stringify(error));
            }
          });
        }
      };

      $scope.accept = function (answer) {
        // window.console.log('Accept: ' + answer.id);
        var acceptedAnswer = ssAcceptedAnswer.create({}, answer);
        if (acceptedAnswer.$ml.valid) {
          acceptedAnswer.post().$ml.waiting.then(function () {
            // Do nothing more on success
          },
          function (error) {
            if (error.status === 400) {
              $scope.setLocalError(
                error.data.message
              );
            }
            else {
              throw new Error('Error occurred: ' + JSON.stringify(error));
            }
          });
        }
      };

      $scope.setPageTitle('doc');
      $scope.searchbarText = appRouting.params.q ? appRouting.params.q : null;
      init();

    }

  ]);

});
<|endoftext|>


<commit_before>if (typeof user === 'undefined') user = "highfidelity/";
if (typeof repository === 'undefined') repository = "hifi_tests/";
if (typeof branch === 'undefined') branch = "master/";

var autoTester = Script.require("https://github.com/" + user + repository + "blob/" + branch + "tests/utils/autoTester.js?raw=true" );

autoTester.perform("Zone - Ambient Light Inheritance", Script.resolvePath("."), "secondary", function(testType) {
    var avatarOriginPosition = MyAvatar.position;

    var zoneRedPosition   = { x: avatarOriginPosition.x, y: avatarOriginPosition.y - 4.0, z: avatarOriginPosition.z - 17.5 };
    var zoneBluePosition  = { x: avatarOriginPosition.x, y: avatarOriginPosition.y - 4.0, z: avatarOriginPosition.z - 17.5 };
    var zoneGreenPosition = { x: avatarOriginPosition.x, y: avatarOriginPosition.y - 4.0, z: avatarOriginPosition.z - 17.5 };

    var ZONE_HEIGHT = 10.0;
    var zoneRedDimensions   = { x: 40.0, y: ZONE_HEIGHT, z: 40.0};
    var zoneGreenDimensions = { x: 30.0, y: ZONE_HEIGHT, z: 30.0};
    var zoneBlueDimensions  = { x: 20.0, y: ZONE_HEIGHT, z: 20.0};

    var TESTS_URL = "https://github.com/" + user + repository + "blob/" + branch;
    var SUFFIX = "?raw=true";
    var RAW_TESTS_URL = "https://raw.githubusercontent.com/" + user + repository + branch;

    var zoneRed;
    var zoneGreen;
    var zoneBlue;
    var sphere;

    var SPHERE_OFFSET = { x: 0.0, y: 0.6, z: -2.0 };

    var LIFETIME = 60.0;

    // Add test steps, These may be called via the timing mechanism for auto-testing,
    // or stepped through with the space bar

    autoTester.addStep("Setup zones and sphere", function () {
        // Create zones
        var BRIGHT_SKY_URL = Script.resolvePath(RAW_TESTS_URL + 'assets/skymaps/Sky_Day-Sun-Mid-photo.texmeta.json');
        var zoneRedProperties = {
            lifetime: LIFETIME,
            type: "Zone",
            name: "zone red",
            position: zoneRedPosition,
            dimensions: zoneRedDimensions,

            keyLightMode: "disabled",

            ambientLightMode: "enabled",
            ambientLight: {
                ambientURL: BRIGHT_SKY_URL
            }
        };
        zoneRed = Entities.addEntity(zoneRedProperties);

        var CLOUDY_SKY_URL = Script.resolvePath(TESTS_URL + 'assets/skymaps/ThickCloudsWater2.jpg' + SUFFIX);
        var zoneGreenProperties = {
            lifetime: LIFETIME,
            type: "Zone",
            name: "zone green",
            position: zoneGreenPosition,
            dimensions: zoneGreenDimensions,

            keyLightMode: "disabled",

            ambientLightMode: "enabled",
            ambientLight: {
                ambientURL: CLOUDY_SKY_URL
            }
        };
        zoneGreen = Entities.addEntity(zoneGreenProperties);

        var NIGHT_SKY_URL = Script.resolvePath(TESTS_URL + 'assets/skymaps/FullMoon1024Compressed.jpg' + SUFFIX);
        var zoneBlueProperties = {
            lifetime: LIFETIME,
            type: "Zone",
            name: "zone blue",
            position: zoneBluePosition,
            dimensions: zoneBlueDimensions,

            keyLightMode: "disabled",

            ambientLightMode: "enabled",
            ambientLight: {
                ambientURL: NIGHT_SKY_URL
            }
        };
        zoneBlue = Entities.addEntity(zoneBlueProperties);

        // Add a white sphere
        var sphereProperties = {
            lifetime: LIFETIME,
            type: "Sphere",
            name: "sphere",
            position: Vec3.sum(MyAvatar.position, SPHERE_OFFSET),
            dimensions: { x: 0.4, y: 0.4, z: 0.4 },
            "color": {"red":255,"green":255,"blue":255},
            visible: true,
            userData: JSON.stringify({ grabbableKey: { grabbable: false } })
        };
        sphere = Entities.addEntity(sphereProperties);
    });
    autoTester.addStepSnapshot("Red zone, bright ambient light");

    autoTester.addStep("Move to green zone", function () {
        var offset = { x: 0.0, y: 0.0, z: -5.0 };
        MyAvatar.position  = Vec3.sum(avatarOriginPosition, offset);
        validationCamera_setTranslation(offset);

        Entities.editEntity(sphere, { position: Vec3.sum(MyAvatar.position, SPHERE_OFFSET) });
    });
    autoTester.addStepSnapshot("Green zone, medium ambient light");

    autoTester.addStep("Move to blue zone", function () {
        var offset = { x: 0.0, y: 0.0, z: -10.0 };
        MyAvatar.position  = Vec3.sum(avatarOriginPosition, offset);
        validationCamera_setTranslation(offset);

        Entities.editEntity(sphere, { position: Vec3.sum(MyAvatar.position, SPHERE_OFFSET) });
    });
    autoTester.addStepSnapshot("Blue zone, dark ambient light");

    autoTester.addStep("Diable ambient light in blue zone", function () {
        Entities.editEntity(zoneBlue, { ambientLightMode: "disabled" });
    });
    autoTester.addStepSnapshot("Blue off,  no ambient light");

    autoTester.addStep("Inherit ambient light", function () {
        Entities.editEntity(zoneBlue, { ambientLightMode: "inherit" });
    });
    autoTester.addStepSnapshot("Blue zone, medium ambient light (from green)");

    autoTester.addStep("Disable green ambient light", function () {
        Entities.editEntity(zoneGreen, { ambientLightMode: "disabled" });
    });
    autoTester.addStepSnapshot("Green off,  no ambient light");

    autoTester.addStep("Set green ambient light to inherit", function () {
        Entities.editEntity(zoneGreen, { ambientLightMode: "inherit" });
    });
    autoTester.addStepSnapshot("Green inherit, bright ambient light (from red)");

    autoTester.addStep("Set red ambient light to off", function () {
        Entities.editEntity(zoneRed, { ambientLightMode: "disabled" });
    });
    autoTester.addStepSnapshot("Red off,  no ambient light");

    autoTester.addStep("Move to green zone", function () {
        var offset = { x: 0.0, y: 0.0, z: -5.0 };
        MyAvatar.position  = Vec3.sum(avatarOriginPosition, offset);
        validationCamera_setTranslation(offset);

        Entities.editEntity(sphere, { position: Vec3.sum(MyAvatar.position, SPHERE_OFFSET) });
    });
    autoTester.addStepSnapshot("Green zone, still no ambient light");

    autoTester.addStep("Set red ambient light to on", function () {
        Entities.editEntity(zoneRed, { ambientLightMode: "enabled" });
    });
    autoTester.addStepSnapshot("Red on, bright ambient light");

    autoTester.addStep("Delete entities", function () {
        Entities.deleteEntity(zoneRed);
        Entities.deleteEntity(zoneGreen);
        Entities.deleteEntity(zoneBlue);
        Entities.deleteEntity(sphere);
    });

    var result = autoTester.runTest(testType);
});
<commit_msg>Renamed variable.<commit_after>if (typeof user === 'undefined') user = "highfidelity/";
if (typeof repository === 'undefined') repository = "hifi_tests/";
if (typeof branch === 'undefined') branch = "master/";

var autoTester = Script.require("https://github.com/" + user + repository + "blob/" + branch + "tests/utils/autoTester.js?raw=true" );

autoTester.perform("Zone - Ambient Light Inheritance", Script.resolvePath("."), "secondary", function(testType) {
    var avatarOriginPosition = MyAvatar.position;

    var zoneRedPosition   = { x: avatarOriginPosition.x, y: avatarOriginPosition.y - 4.0, z: avatarOriginPosition.z - 17.5 };
    var zoneBluePosition  = { x: avatarOriginPosition.x, y: avatarOriginPosition.y - 4.0, z: avatarOriginPosition.z - 17.5 };
    var zoneGreenPosition = { x: avatarOriginPosition.x, y: avatarOriginPosition.y - 4.0, z: avatarOriginPosition.z - 17.5 };

    var ZONE_HEIGHT = 10.0;
    var zoneRedDimensions   = { x: 40.0, y: ZONE_HEIGHT, z: 40.0};
    var zoneGreenDimensions = { x: 30.0, y: ZONE_HEIGHT, z: 30.0};
    var zoneBlueDimensions  = { x: 20.0, y: ZONE_HEIGHT, z: 20.0};

    var TESTS_URL = "https://github.com/" + user + repository + "blob/" + branch;
    var SUFFIX = "?raw=true";
    var RAW_TESTS_URL = "https://raw.githubusercontent.com/" + user + repository + branch;

    var zoneRed;
    var zoneGreen;
    var zoneBlue;
    var sphere;

    var SPHERE_OFFSET = { x: 0.0, y: 0.6, z: -2.0 };

    var LIFETIME = 60.0;

    // Add test steps, These may be called via the timing mechanism for auto-testing,
    // or stepped through with the space bar

    autoTester.addStep("Setup zones and sphere", function () {
        // Create zones
        var BRIGHT_SKY_URL = Script.resolvePath(RAW_TESTS_URL + 'assets/skymaps/Sky_Day-Sun-Mid-photo.texmeta.json');
        var zoneRedProperties = {
            lifetime: LIFETIME,
            type: "Zone",
            name: "zone red",
            position: zoneRedPosition,
            dimensions: zoneRedDimensions,

            keyLightMode: "disabled",

            ambientLightMode: "enabled",
            ambientLight: {
                ambientURL: BRIGHT_SKY_URL
            }
        };
        zoneRed = Entities.addEntity(zoneRedProperties);

        var CLOUDY_SKY_URL = Script.resolvePath(TESTS_URL + 'assets/skymaps/ThickCloudsWater2.jpg' + SUFFIX);
        var zoneGreenProperties = {
            lifetime: LIFETIME,
            type: "Zone",
            name: "zone green",
            position: zoneGreenPosition,
            dimensions: zoneGreenDimensions,

            keyLightMode: "disabled",

            ambientLightMode: "enabled",
            ambientLight: {
                ambientURL: CLOUDY_SKY_URL
            }
        };
        zoneGreen = Entities.addEntity(zoneGreenProperties);

        var NIGHT_SKY_URL = Script.resolvePath(TESTS_URL + 'assets/skymaps/FullMoon1024Compressed.jpg' + SUFFIX);
        var zoneBlueProperties = {
            lifetime: LIFETIME,
            type: "Zone",
            name: "zone blue",
            position: zoneBluePosition,
            dimensions: zoneBlueDimensions,

            keyLightMode: "disabled",

            ambientLightMode: "enabled",
            ambientLight: {
                ambientURL: NIGHT_SKY_URL
            }
        };
        zoneBlue = Entities.addEntity(zoneBlueProperties);

        // Add a white sphere
        var sphereProperties = {
            lifetime: LIFETIME,
            type: "Sphere",
            name: "sphere",
            position: Vec3.sum(MyAvatar.position, SPHERE_OFFSET),
            dimensions: { x: 0.4, y: 0.4, z: 0.4 },
            "color": {"red":255,"green":255,"blue":255},
            visible: true,
            userData: JSON.stringify({ grabbableKey: { grabbable: false } })
        };
        sphere = Entities.addEntity(sphereProperties);
    });
    autoTester.addStepSnapshot("Red zone, bright ambient light");

    autoTester.addStep("Move to green zone", function () {
        var position = { x: 0.0, y: 0.0, z: -5.0 };
        MyAvatar.position  = Vec3.sum(avatarOriginPosition, position);
        validationCamera_setTranslation(position);

        Entities.editEntity(sphere, { position: Vec3.sum(MyAvatar.position, SPHERE_OFFSET) });
    });
    autoTester.addStepSnapshot("Green zone, medium ambient light");

    autoTester.addStep("Move to blue zone", function () {
        var position = { x: 0.0, y: 0.0, z: -10.0 };
        MyAvatar.position  = Vec3.sum(avatarOriginPosition, position);
        validationCamera_setTranslation(position);

        Entities.editEntity(sphere, { position: Vec3.sum(MyAvatar.position, SPHERE_OFFSET) });
    });
    autoTester.addStepSnapshot("Blue zone, dark ambient light");

    autoTester.addStep("Diable ambient light in blue zone", function () {
        Entities.editEntity(zoneBlue, { ambientLightMode: "disabled" });
    });
    autoTester.addStepSnapshot("Blue off,  no ambient light");

    autoTester.addStep("Inherit ambient light", function () {
        Entities.editEntity(zoneBlue, { ambientLightMode: "inherit" });
    });
    autoTester.addStepSnapshot("Blue zone, medium ambient light (from green)");

    autoTester.addStep("Disable green ambient light", function () {
        Entities.editEntity(zoneGreen, { ambientLightMode: "disabled" });
    });
    autoTester.addStepSnapshot("Green off,  no ambient light");

    autoTester.addStep("Set green ambient light to inherit", function () {
        Entities.editEntity(zoneGreen, { ambientLightMode: "inherit" });
    });
    autoTester.addStepSnapshot("Green inherit, bright ambient light (from red)");

    autoTester.addStep("Set red ambient light to off", function () {
        Entities.editEntity(zoneRed, { ambientLightMode: "disabled" });
    });
    autoTester.addStepSnapshot("Red off,  no ambient light");

    autoTester.addStep("Move to green zone", function () {
        var position = { x: 0.0, y: 0.0, z: -5.0 };
        MyAvatar.position  = Vec3.sum(avatarOriginPosition, position);
        validationCamera_setTranslation(position);

        Entities.editEntity(sphere, { position: Vec3.sum(MyAvatar.position, SPHERE_OFFSET) });
    });
    autoTester.addStepSnapshot("Green zone, still no ambient light");

    autoTester.addStep("Set red ambient light to on", function () {
        Entities.editEntity(zoneRed, { ambientLightMode: "enabled" });
    });
    autoTester.addStepSnapshot("Red on, bright ambient light");

    autoTester.addStep("Delete entities", function () {
        Entities.deleteEntity(zoneRed);
        Entities.deleteEntity(zoneGreen);
        Entities.deleteEntity(zoneBlue);
        Entities.deleteEntity(sphere);
    });

    var result = autoTester.runTest(testType);
});
<|endoftext|>


<commit_before>let React = require('react');
let TestUtils = React.addons.TestUtils;
let chai = require('chai');
let sinonChai = require('sinon-chai');
let expect = chai.expect;
chai.use(sinonChai);
let renderTarget, renderedComponent;
let actionCreator, store;

describe('Displaying the shopping cart overview', () => {
  let categories = [
    {id: 1, name: 'first category'},
    {id: 2, name: 'second category'}
  ];
  let articles = [
    {id: 3, name: 'first article', intensity: 3, price: 42, isMatchingFilter: true, category: 1},
    {id: 4, name: 'second article', intensity: 8, price: 38, isMatchingFilter: true, category: 2}
  ];
  beforeEach(function() {
    let ComponentClass = require('../../app/components/shopping-cart-controller-view.react.js');
    renderTarget = document.getElementsByTagName('body')[0];

    let dataAccess = {
      getCategoriesAndArticles: () => {
        return {
          categories: categories,
          articles: articles
        };
      }
    };

    let ActionCreator = require('../../app/action-creator.js');
    actionCreator = new ActionCreator(dataAccess);
    let ArticleStore = require('../../app/article-store.js');
    store = new ArticleStore();
    renderedComponent = React.render(<ComponentClass actionCreator={actionCreator} store={store} />, renderTarget);
    // initialize action creator, to fetch article data from server etc.
    actionCreator.initialize();
  });

  afterEach(() => {
    React.unmountComponentAtNode(renderTarget);
    renderedComponent = null;
  });

  describe('when no articles added to shopping cart', () => {
    it('should display no items', () => {
      let shoppingCartItems = TestUtils.scryRenderedDOMComponentsWithClass(renderedComponent, 'shopping-cart-item');
      expect(shoppingCartItems).to.deep.equal([]);
    });

    it('should display empty footer', () => {
      let shoppingCartFooter = TestUtils.scryRenderedDOMComponentsWithClass(renderedComponent, 'shopping-cart-footer')[0].getDOMNode();
      expect(shoppingCartFooter.children[2].textContent).to.equal('0');
      expect(shoppingCartFooter.children[3].textContent).to.equal('0');
    });
  });

  describe('when two different articles added to shopping cart', () => {
    beforeEach(() => {
      actionCreator.addArticleToShoppingCart(3, 5);
      actionCreator.addArticleToShoppingCart(4, 3);
    });

    it('should display name, amount and price of first article', () => {
      let shoppingCartItem = TestUtils.scryRenderedDOMComponentsWithClass(renderedComponent, 'shopping-cart-item')[0].getDOMNode();
      expect(shoppingCartItem.children[0].textContent).to.equal('first article');
      expect(shoppingCartItem.children[1].textContent).to.equal('0.42');
      expect(shoppingCartItem.children[2].children[0].textContent).to.equal('5');
      expect(shoppingCartItem.children[3].textContent).to.equal('2.1');
    });

    it('should display name, amount and price of second article', () => {
      let shoppingCartItem = TestUtils.scryRenderedDOMComponentsWithClass(renderedComponent, 'shopping-cart-item')[1].getDOMNode();
      expect(shoppingCartItem.children[0].textContent).to.equal('second article');
      expect(shoppingCartItem.children[1].textContent).to.equal('0.38');
      expect(shoppingCartItem.children[2].children[0].textContent).to.equal('3');
      expect(shoppingCartItem.children[3].textContent).to.equal('1.14');
    });

    it('should display footer with total amount', () => {
      let shoppingCartFooter = TestUtils.scryRenderedDOMComponentsWithClass(renderedComponent, 'shopping-cart-footer')[0].getDOMNode();
      expect(shoppingCartFooter.children[2].textContent).to.equal('8');
    });

    it('should display footer with total price', () => {
      let shoppingCartFooter = TestUtils.scryRenderedDOMComponentsWithClass(renderedComponent, 'shopping-cart-footer')[0].getDOMNode();
      expect(shoppingCartFooter.children[3].textContent).to.equal('3.24');
    });

    describe('Clicking the + button of an article', () => {
      it('should increase article amount by 10', () => {
        let shoppingCartItem = TestUtils.scryRenderedDOMComponentsWithClass(renderedComponent, 'shopping-cart-item')[0].getDOMNode();
        let addButton = shoppingCartItem.children[2].children[1];
        React.addons.TestUtils.Simulate.click(addButton);
        expect(shoppingCartItem.children[2].children[0].textContent).to.equal('15');
      });
    });
  });
});
<commit_msg>Make article amounts in specs a little bit more realistic.<commit_after>let React = require('react');
let TestUtils = React.addons.TestUtils;
let chai = require('chai');
let sinonChai = require('sinon-chai');
let expect = chai.expect;
chai.use(sinonChai);
let renderTarget, renderedComponent;
let actionCreator, store;

describe('Displaying the shopping cart overview', () => {
  let categories = [
    {id: 1, name: 'first category'},
    {id: 2, name: 'second category'}
  ];
  let articles = [
    {id: 3, name: 'first article', intensity: 3, price: 42, isMatchingFilter: true, category: 1},
    {id: 4, name: 'second article', intensity: 8, price: 38, isMatchingFilter: true, category: 2}
  ];
  beforeEach(function() {
    let ComponentClass = require('../../app/components/shopping-cart-controller-view.react.js');
    renderTarget = document.getElementsByTagName('body')[0];

    let dataAccess = {
      getCategoriesAndArticles: () => {
        return {
          categories: categories,
          articles: articles
        };
      }
    };

    let ActionCreator = require('../../app/action-creator.js');
    actionCreator = new ActionCreator(dataAccess);
    let ArticleStore = require('../../app/article-store.js');
    store = new ArticleStore();
    renderedComponent = React.render(<ComponentClass actionCreator={actionCreator} store={store} />, renderTarget);
    // initialize action creator, to fetch article data from server etc.
    actionCreator.initialize();
  });

  afterEach(() => {
    React.unmountComponentAtNode(renderTarget);
    renderedComponent = null;
  });

  describe('when no articles added to shopping cart', () => {
    it('should display no items', () => {
      let shoppingCartItems = TestUtils.scryRenderedDOMComponentsWithClass(renderedComponent, 'shopping-cart-item');
      expect(shoppingCartItems).to.deep.equal([]);
    });

    it('should display empty footer', () => {
      let shoppingCartFooter = TestUtils.scryRenderedDOMComponentsWithClass(renderedComponent, 'shopping-cart-footer')[0].getDOMNode();
      expect(shoppingCartFooter.children[2].textContent).to.equal('0');
      expect(shoppingCartFooter.children[3].textContent).to.equal('0');
    });
  });

  describe('when two different articles added to shopping cart', () => {
    beforeEach(() => {
      actionCreator.addArticleToShoppingCart(3, 20);
      actionCreator.addArticleToShoppingCart(4, 30);
    });

    it('should display name, amount and price of first article', () => {
      let shoppingCartItem = TestUtils.scryRenderedDOMComponentsWithClass(renderedComponent, 'shopping-cart-item')[0].getDOMNode();
      expect(shoppingCartItem.children[0].textContent).to.equal('first article');
      expect(shoppingCartItem.children[1].textContent).to.equal('0.42');
      expect(shoppingCartItem.children[2].children[0].textContent).to.equal('20');
      expect(shoppingCartItem.children[3].textContent).to.equal('8.4');
    });

    it('should display name, amount and price of second article', () => {
      let shoppingCartItem = TestUtils.scryRenderedDOMComponentsWithClass(renderedComponent, 'shopping-cart-item')[1].getDOMNode();
      expect(shoppingCartItem.children[0].textContent).to.equal('second article');
      expect(shoppingCartItem.children[1].textContent).to.equal('0.38');
      expect(shoppingCartItem.children[2].children[0].textContent).to.equal('30');
      expect(shoppingCartItem.children[3].textContent).to.equal('11.4');
    });

    it('should display footer with total amount', () => {
      let shoppingCartFooter = TestUtils.scryRenderedDOMComponentsWithClass(renderedComponent, 'shopping-cart-footer')[0].getDOMNode();
      expect(shoppingCartFooter.children[2].textContent).to.equal('50');
    });

    it('should display footer with total price', () => {
      let shoppingCartFooter = TestUtils.scryRenderedDOMComponentsWithClass(renderedComponent, 'shopping-cart-footer')[0].getDOMNode();
      expect(shoppingCartFooter.children[3].textContent).to.equal('19.8');
    });

    describe('Clicking the add button of an article', () => {
      it('should increase article amount by 10', () => {
        let shoppingCartItem = TestUtils.scryRenderedDOMComponentsWithClass(renderedComponent, 'shopping-cart-item')[0].getDOMNode();
        let addButton = shoppingCartItem.children[2].children[1];
        React.addons.TestUtils.Simulate.click(addButton);
        expect(shoppingCartItem.children[2].children[0].textContent).to.equal('30');
      });
    });
  });
});
<|endoftext|>