<commit_before>import { GET_INITIAL_STATE } from './types';

export default function combineReducers(reducers, { idToProps = {}, alsoAdd } = {}) {
  let combinedReducer = {};
	let alsoResponder;

  function getInitialState() {
    return Object.keys(reducers).reduce((state, reducerID) => {
      const reducer = reducers[reducerID];
      if (reducer[GET_INITIAL_STATE]) {
        state[reducerID] = reducer[GET_INITIAL_STATE](idToProps[reducerID]);
      }
      return state;
    }, {});
  }

  const actionSetHandlers = Object.keys(reducers).reduce((actionSetHandlers, reducerID) => {
  const reducer = reducers[reducerID];
  Object.keys(reducer).reduce((actionSetHandlers, property) => {
    if (property === GET_INITIAL_STATE || !!actionSetHandlers[property]) {
      return actionSetHandlers;
    }

    actionSetHandlers[property] = (initialState, { actionID, forwardTo }) => {
      let newState = Object.keys(reducers).reduce((state, reducerID) => {
        state[reducerID] = forwardTo({
          responder: reducers[reducerID],
          initialState: initialState[reducerID],
          props: idToProps[reducerID]
        });
        return state;
      }, {});

      if (alsoResponder) {
				newState = forwardTo({
					responder: alsoResponder,
					initialState: newState,
					props: {
						idToProps,
						combinedReducer
					}
				});
			}

      return newState;
    }

    return actionSetHandlers;
  }, actionSetHandlers);

  return actionSetHandlers;
  }, {});

  Object.assign(combinedReducer, { [GET_INITIAL_STATE]: getInitialState }, actionSetHandlers);

  if (alsoAdd) {
		alsoResponder = alsoAdd(combinedReducer);
	}

  return combinedReducer;
}
<commit_msg>Fix combineReducers to work with introspection<commit_after>import { GET_INITIAL_STATE } from './types';

export default function combineReducers(reducers, { idToProps = {}, alsoAdd } = {}) {
  let combinedReducer = {};
	let alsoResponder;

  function getInitialState() {
    return Object.keys(reducers).reduce((state, reducerID) => {
      const reducer = reducers[reducerID];
      if (reducer[GET_INITIAL_STATE]) {
        state[reducerID] = reducer[GET_INITIAL_STATE](idToProps[reducerID]);
      }
      return state;
    }, {});
  }

  const actionSetHandlers = Object.keys(reducers).reduce((actionSetHandlers, reducerID) => {
  const reducer = reducers[reducerID];
  Object.keys(reducer).reduce((actionSetHandlers, property) => {
    if (property === GET_INITIAL_STATE || !!actionSetHandlers[property]) {
      return actionSetHandlers;
    }

    actionSetHandlers[property] = (initialState, { isAction, isIntrospection, forwardTo }) => {
      if (isAction) {
        let newState = Object.keys(reducers).reduce((state, reducerID) => {
          state[reducerID] = forwardTo({
            responder: reducers[reducerID],
            initialState: initialState[reducerID],
            props: idToProps[reducerID]
          });
          return state;
        }, {});

        if (alsoResponder) {
  				newState = forwardTo({
  					responder: alsoResponder,
  					initialState: newState,
  					props: {
  						idToProps,
  						combinedReducer
  					}
  				});
  			}

        return newState;
      }
      else if (isIntrospection) {
				if (alsoResponder) {
					// Use customized response, if one was given.
					const response = forwardTo({
						responder: alsoResponder,
						initialState: newState,
						props: {
							idToProps,
							combinedReducer
						}
					});

					if (response) {
						return response;
					}
				}

				// Use first reducer that responds.
				return Object.keys(reducers).find((state, reducerID) =>
					forwardTo({
						responder: reducers[reducerID],
						initialState: initialState[reducerID],
						props: idToProps[reducerID]
					})
				);
			}
    }

    return actionSetHandlers;
  }, actionSetHandlers);

  return actionSetHandlers;
  }, {});

  Object.assign(combinedReducer, { [GET_INITIAL_STATE]: getInitialState }, actionSetHandlers);

  if (alsoAdd) {
		alsoResponder = alsoAdd(combinedReducer);
	}

  return combinedReducer;
}
<|endoftext|>


<commit_before>/**
* resource.GameData Module
*
* Description
*/
angular.module('resource.GameData', [
    'service.localStoragePolyfill',
    'service.GAMESPEED'
])
.factory('GameData', [
    'localStoragePolyfill',
    'GAMESPEED',
function (
    localStoragePolyfill,
    GAMESPEED
){
    function getBestScore() {
        return parseInt(localStoragePolyfill.getItem('game.bestScore'), 10) || 0;
    }

    function getGameSpeed() {
        return parseInt(localStoragePolyfill.getItem('game.speed'), 10) || GAMESPEED['BEGINNER'];
    }

    function setGameSpeed(speed) {
        localStoragePolyfill.setItem('game.speed', speed);
    }

    function setColor(color) {
        data.customColorChosen = color;
    }

    function getColor() {
        return data.customColorChosen;
    }

    var data = {
        gameStart: false,
        gameEnd: false,
        gamePause: false,
        score: 0,
        getGameSpeed: getGameSpeed,
        setGameSpeed: setGameSpeed,
        getBestScore: getBestScore,
        rotationLimit: 4,
        patternLimit: 7,
        cssAnimateTimeout: 300, // milliseconds
        maxCustomPiece: 5,
        customPieceWidth: 4,
        availableColors: 5,
        customColorChosen: '',
        setColor: setColor,
        getColor: getColor,
        gameBoard: {
            borderWidth: 10,
            pieceWidthInPixel: 25, // match the pixel of piece in grid
            boardWidth: 10,
            boardHeight: 20
        }
    };

    return data;
}]);<commit_msg>store the game time history time in game data<commit_after>/**
* resource.GameData Module
*
* Description
*/
angular.module('resource.GameData', [
    'service.localStoragePolyfill',
    'service.GAMESPEED'
])
.factory('GameData', [
    'localStoragePolyfill',
    'GAMESPEED',
function (
    localStoragePolyfill,
    GAMESPEED
){
    function getBestScore() {
        return parseInt(localStoragePolyfill.getItem('game.bestScore'), 10) || 0;
    }

    function getGameSpeed() {
        return parseInt(localStoragePolyfill.getItem('game.speed'), 10) || GAMESPEED['BEGINNER'];
    }

    function setGameSpeed(speed) {
        localStoragePolyfill.setItem('game.speed', speed);
    }

    function setColor(color) {
        data.customColorChosen = color;
    }

    function getColor() {
        return data.customColorChosen;
    }

    var data = {
        gameStart: false,
        gameEnd: false,
        gamePause: false,
        score: 0,
        savedGameTime: null,
        getGameSpeed: getGameSpeed,
        setGameSpeed: setGameSpeed,
        getBestScore: getBestScore,
        rotationLimit: 4,
        patternLimit: 7,
        cssAnimateTimeout: 300, // milliseconds
        maxCustomPiece: 5,
        customPieceWidth: 4,
        availableColors: 5,
        customColorChosen: '',
        setColor: setColor,
        getColor: getColor,
        gameBoard: {
            borderWidth: 10,
            pieceWidthInPixel: 25, // match the pixel of piece in grid
            boardWidth: 10,
            boardHeight: 20
        }
    };

    return data;
}]);<|endoftext|>


<commit_before>/*
 * Copyright (c) 2011-2014 YY Digital Pty Ltd. All Rights Reserved.
 * Please see the LICENSE file included with this distribution for details.
 */

var  os = Ti.Platform.osname;

// Density image setup for android
if (os === "android") {
  var density_orientation = (Ti.Gesture.orientation === Ti.UI.LANDSCAPE_LEFT) ? "land" : "port",
  density_folders = (function () {

    var folders = [],
    ratio = ((Ti.Platform.displayCaps.platformWidth / Ti.Platform.displayCaps.platformHeight) < ((density_orientation === "land") ? (320 / 240) : (240 / 320))) ? "long" : "notlong",
    logicalDensityFactor = Ti.Platform.displayCaps.logicalDensityFactor,
    density;

    if (logicalDensityFactor <= 0.75) {
      density = "ldpi";
    } else if (logicalDensityFactor <= 1.0) {
      density = "mdpi";
    } else if (logicalDensityFactor <= 1.5) {
      density = "hdpi";
    } else if (logicalDensityFactor <= 2.0) {
      density = "xhdpi";
    } else if (logicalDensityFactor <= 3.0) {
      density = "xxhdpi";
    } else {
      density = "xxxhdpi";
    }

    folders.push("res-" + ratio + "-%ORIENTATION%-" + density);
    folders.push("res-%ORIENTATION%-" + density);
    folders.push("res-" + density);

    if (density === "ldpi") {
      folders.push("low");
    } else if (density === "mdpi") {
      folders.push("medium");
    } else if (density === "hdpi") {
      folders.push("high");
    }

    folders.push("res-mdpi");
    folders.push("");

    return folders;
  })();

  Ti.Gesture.addEventListener("orientationchange", function (e) {
    density_orientation = (e.orientation === Ti.UI.LANDSCAPE_LEFT) ? "land" : "port";
  });
}

function injectSuffix(file, suffix) {
  var file_parts = file.split(".");
  var ext = file_parts.pop();
  return file_parts.join(".") + suffix + "." + ext;
}

//density files only for png files
exports.find = function(file) {
  //iOS Retina Check
  if ((os === "ipad" || os === "iphone")) {
    if (Ti.Filesystem.getFile(file).exists()) {
      return file;
    }
    var ret_file_name = injectSuffix(file, "@2x");
    if (Ti.Filesystem.getFile(ret_file_name).exists() && Ti.Platform.displayCaps.density === "high") {
      return ret_file_name;
    }
  } else if (os === "android") {
    var d_file_name = file.replace("android/images/", "android/images/%FOLDER%/"),
    do_file_name,
    i;
    for (i in density_folders) {
      do_file_name = d_file_name.replace("%FOLDER%", density_folders[i].replace('%ORIENTATION%', density_orientation));
      do9_file_name = injectSuffix(do_file_name, '.9');
      if (Ti.Filesystem.getFile(do_file_name).exists() || Ti.Filesystem.getFile(do9_file_name).exists()) {
        return do_file_name;
      }
    }
  }
  return null;
};

<commit_msg>Adding support for @3x iPhone 6 Plus assets<commit_after>/*
 * Copyright (c) 2011-2014 YY Digital Pty Ltd. All Rights Reserved.
 * Please see the LICENSE file included with this distribution for details.
 */

var  os = Ti.Platform.osname;

// Density image setup for android
if (os === "android") {
  var density_orientation = (Ti.Gesture.orientation === Ti.UI.LANDSCAPE_LEFT) ? "land" : "port",
  density_folders = (function () {

    var folders = [],
    ratio = ((Ti.Platform.displayCaps.platformWidth / Ti.Platform.displayCaps.platformHeight) < ((density_orientation === "land") ? (320 / 240) : (240 / 320))) ? "long" : "notlong",
    logicalDensityFactor = Ti.Platform.displayCaps.logicalDensityFactor,
    density;

    if (logicalDensityFactor <= 0.75) {
      density = "ldpi";
    } else if (logicalDensityFactor <= 1.0) {
      density = "mdpi";
    } else if (logicalDensityFactor <= 1.5) {
      density = "hdpi";
    } else if (logicalDensityFactor <= 2.0) {
      density = "xhdpi";
    } else if (logicalDensityFactor <= 3.0) {
      density = "xxhdpi";
    } else {
      density = "xxxhdpi";
    }

    folders.push("res-" + ratio + "-%ORIENTATION%-" + density);
    folders.push("res-%ORIENTATION%-" + density);
    folders.push("res-" + density);

    if (density === "ldpi") {
      folders.push("low");
    } else if (density === "mdpi") {
      folders.push("medium");
    } else if (density === "hdpi") {
      folders.push("high");
    }

    folders.push("res-mdpi");
    folders.push("");

    return folders;
  })();

  Ti.Gesture.addEventListener("orientationchange", function (e) {
    density_orientation = (e.orientation === Ti.UI.LANDSCAPE_LEFT) ? "land" : "port";
  });
}

function injectSuffix(file, suffix) {
  var file_parts = file.split(".");
  var ext = file_parts.pop();
  return file_parts.join(".") + suffix + "." + ext;
}

//density files only for png files
exports.find = function(file) {
  //iOS (HD) Retina Check
  if ((os === "ipad" || os === "iphone")) {
    if (Ti.Filesystem.getFile(file).exists()) {
      return file;
    }
    if (Ti.Platform.displayCaps.density > 160) {
      var ret_file_name = injectSuffix(file, (Ti.Platform.displayCaps.density > 320) ? "@3x" : "@2x");
      if (Ti.Filesystem.getFile(ret_file_name).exists() && Ti.Platform.displayCaps.density === "high") {
        return ret_file_name;
      }
    }
  } else if (os === "android") {
    var d_file_name = file.replace("android/images/", "android/images/%FOLDER%/"),
    do_file_name,
    i;
    for (i in density_folders) {
      do_file_name = d_file_name.replace("%FOLDER%", density_folders[i].replace('%ORIENTATION%', density_orientation));
      do9_file_name = injectSuffix(do_file_name, '.9');
      if (Ti.Filesystem.getFile(do_file_name).exists() || Ti.Filesystem.getFile(do9_file_name).exists()) {
        return do_file_name;
      }
    }
  }
  return null;
};

<|endoftext|>


<commit_before>/*
   All emon_widgets code is released under the GNU General Public License v3.
   See COPYRIGHT.txt and LICENSE.txt.

   Part of the OpenEnergyMonitor project:
   http://openenergymonitor.org

   Author: Trystan Lea: trystan.lea@googlemail.com
   If you have any questions please get in touch, try the forums here:
   http://openenergymonitor.org/emon/forum
 */

function vis_widgetlist(){
  var widgets = {
    "realtime":
    {
      "offsetx":0,"offsety":0,"width":400,"height":300,
      "menu":"Visualisations",
      "options":["feedid","colour"],
      "optionstype":["feedid","colour_picker"],
      "optionsname":[_Tr("Feed"),_Tr("Colour")],
      "optionshint":[_Tr("Feed source"),_Tr("Line colour in hex. Blank is use default.")],
      "html":""
    },

    "rawdata":
    {
      "offsetx":0,"offsety":0,"width":400,"height":300,
      "menu":"Visualisations",
      "options":["feedid","colour","units","dp","scale","fill"],
      "optionstype":["feedid","colour_picker","value","value","value","value"],
      "optionsname":[_Tr("Feed"),_Tr("Colour"),_Tr("units"),_Tr("dp"),_Tr("scale"),_Tr("Fill")],
      "optionshint":[_Tr("Feed source"),_Tr("Line colour in hex. Blank is use default."),_Tr("units"),_Tr("Decimal points"),_Tr("Scale by"),_Tr("Fill value")],

      "html":""
    },

    "bargraph":
    {
      "offsetx":0,"offsety":0,"width":400,"height":300,
      "menu":"Visualisations",
      "options":["feedid","colour","interval","units","dp","scale","delta","mode"],
      "optionstype":["feedid","colour_picker","value","value","value","value","boolean","value"],
      "optionsname":[_Tr("Feed"),_Tr("Colour"),_Tr("interval"),_Tr("units"),_Tr("dp"),_Tr("scale"),_Tr("delta"),_Tr("mode")],
      "optionshint":[_Tr("Feed source"),_Tr("Line colour in hex. Blank is use default."),_Tr("Interval (seconds)-you can set \"d\" for day, \"m\" for month, or \"y\" for year"),_Tr("Units"),_Tr("Decimal points"),_Tr("Scale by"),_Tr("Show difference between each bar","Mode set to 'daily' can be used instead of interval for timezone based daily data")],
      "html":""
    },

    "timestoredaily":
    {
      "offsetx":0,"offsety":0,"width":400,"height":300,
      "menu":"Visualisations",
      "options":["feedid","units"],
      "optionstype":["feedid","value"],
      "optionsname":[_Tr("Feed"),_Tr("Units")],
      "optionshint":[_Tr("Feed source"),_Tr("Units to show")],
      "html":""
    },

    "zoom":
    {
      "offsetx":0,"offsety":0,"width":400,"height":300,
      "menu":"Visualisations",
      "options":["power","kwhd","currency","currency_after_val","pricekwh","delta"],
      "optionstype":["feedid","feedid","value","value","value","boolean"],
      "optionsname":[_Tr("Power"),_Tr("kwhd"),_Tr("Currency"),_Tr("Currency position"),_Tr("Kwh price"),_Tr("delta")],
      "optionshint":[_Tr("Power to show"),_Tr("kwhd source"),_Tr("Currency to show"),_Tr("0 = before value, 1 = after value"),_Tr("Set kwh price"),_Tr("Show difference between each bar")],
      "html":""
    },

    "simplezoom":
    {
      "offsetx":0,"offsety":0,"width":400,"height":300,
      "menu":"Visualisations",
      "options":["power","kwhd","delta"],
      "optionstype":["feedid","feedid","boolean"],
      "optionsname":[_Tr("Power"),_Tr("kwhd"),_Tr("delta")],
      "optionshint":[_Tr("Power to show"),_Tr("kwhd source"),_Tr("Show difference between each bar")],
      "html":""
    },

    "histgraph":
    {
      "offsetx":0,"offsety":0,"width":400,"height":300,
      "menu":"Visualisations",
      "options":["feedid"],
      "optionstype":["feedid"],
      "optionsname":[_Tr("Feed")],
      "optionshint":[_Tr("Feed source")],
      "html":""
    },

    "threshold":
    {
      "offsetx":0,"offsety":0,"width":400,"height":300,
      "menu":"Visualisations",
      "options":["feedid","thresholdA","thresholdB"],
      "optionstype":["feedid","value","value"],
      "optionsname":[_Tr("Feed"),_Tr("Threshold A"),_Tr("Threshold B")],
      "optionshint":[_Tr("Feed source"),_Tr("Threshold A used"),_Tr("Threshold B used")],
      "html":""
    },

    "orderthreshold":
    {
      "offsetx":0,"offsety":0,"width":400,"height":300,
      "menu":"Visualisations",
      "options":["feedid","power","thresholdA","thresholdB"],
      "optionstype":["feedid","feedid","value","value"],
      "optionsname":[_Tr("Feed"),_Tr("Power"),_Tr("Threshold A"),_Tr("Threshold B")],
      "optionshint":[_Tr("Feed source"),_Tr("Power"),_Tr("Threshold A used"),_Tr("Threshold B used")],
      "html":""
    },

    "orderbars":
    {
      "offsetx":0,"offsety":0,"width":400,"height":300,
      "menu":"Visualisations",
      "options":["feedid","delta"],
      "optionstype":["feedid","boolean"],
      "optionsname":[_Tr("Feed"),_Tr("delta")],
      "optionshint":[_Tr("Feed source"),_Tr("Show difference between each bar")],
      "html":""
    },

    "stacked":
    {
      "offsetx":0,"offsety":0,"width":400,"height":300,
      "menu":"Visualisations",
      "options":["bottom","top","colourt","colourb","delta"],
      "optionstype":["feedid","feedid","colour_picker","colour_picker","boolean"],
      "optionsname":[_Tr("Bottom"),_Tr("Top"),_Tr("Top colour"),_Tr("Bottom colour"),_Tr("delta")],
      "optionshint":[_Tr("Bottom feed value"),_Tr("Top feed value"),_Tr("Top colour"),_Tr("Bottom colour"),_Tr("Show difference between each bar")],
      "html":""
    },

    "stackedsolar":
    {
      "offsetx":0,"offsety":0,"width":400,"height":300,
      "menu":"Visualisations",
      "options":["solar","consumption","delta"],
      "optionstype":["feedid","feedid","boolean"],
      "optionsname":[_Tr("Solar"),_Tr("Consumption"),_Tr("delta")],
      "optionshint":[_Tr("Solar feed value"),_Tr("Consumption feed value"),_Tr("Show difference between each bar")],
      "html":""
    },

    "smoothie":
    {
      "offsetx":0,"offsety":0,"width":400,"height":300,
      "menu":"Visualisations",
      "options":["feedid","ufac"],
      "optionstype":["feedid","value"],
      "optionsname":[_Tr("Feed"),_Tr("Ufac")],
      "optionshint":[_Tr("Feed source"),_Tr("Ufac value")],
      "html":""
    },

    "multigraph":
    {
      "offsetx":0,"offsety":0,"width":400,"height":300,
      "menu":"Visualisations",
      "options":["mid"],
      "optionstype":["dropbox"],
      "optionsname":[_Tr("Multigraph")],
      "optionshint":[_Tr("Managed on Visualization module")],
      "optionsdata":[multigraphsDropBoxOptions], // Gets multigraphs from vis_widget.php multigraphsDropBoxOptions variable
      "html":""
    },

    "timecompare":
    {
      "offsetx":0,"offsety":0,"width":400,"height":300,
      "menu":"Visualisations",
      "options":["feedid","fill","depth","npoints"],
      "optionstype":["feedid","value","value","value"],
      "optionsname":[_Tr("Feed"),_Tr("Fill"),_Tr("Depth"),_Tr("Data points")],
      "optionshint":[_Tr("Feed source"),_Tr("Fill under line"),_Tr("Number of lines"),_Tr("Default: 800")],
      "html":""
    }
  }

  return widgets;
}

function vis_init(){
  vis_draw();
}

function vis_draw(){
  var vislist = vis_widgetlist();

  var visclasslist = '';
  for (z in vislist) { visclasslist += '.'+z+','; }
  visclasslist = visclasslist.slice(0, -1);

  $(visclasslist).each(function(){
    var id = $(this).attr("id");
    var feed = $(this).attr("feed") || 0;
    var width = $(this).width();
    var height = $(this).height();

    var apikey_string = "";
    if (apikey) apikey_string = "&apikey="+apikey;

    if (!$(this).html() || reloadiframe==id || reloadiframe==-1 || apikey){
        var attrstring = "";
        var target = $(this).get(0);
        var l = target.attributes.length;
        for (var i=0; i<l; i++){
          var attr = target.attributes[i].name;
          if (attr!="id" && attr!="class" && attr!="style"){
            attrstring += "&"+attr+"="+target.attributes[i].value;
          }
        }
        pathfix=path.substr(path.indexOf('://')+3); // remove protocol
        pathfix=pathfix.substr(pathfix.indexOf('/')); // remove hostname
        $(this).html('');
        console.log('--> new relative url for iframe of '+ $(this).attr("class") + ': '+pathfix+'vis/'+$(this).attr("class")+'?embed=1'+attrstring+apikey_string);
    }

    var iframe = $(this).children('iframe');
    iframe.width(width);
    iframe.height(height);

  });
  reloadiframe = 0;
}

function vis_slowupdate() {}

function vis_fastupdate() {}
<commit_msg>Update vis_render.js<commit_after>/*
   All emon_widgets code is released under the GNU General Public License v3.
   See COPYRIGHT.txt and LICENSE.txt.

   Part of the OpenEnergyMonitor project:
   http://openenergymonitor.org

   Author: Trystan Lea: trystan.lea@googlemail.com
   If you have any questions please get in touch, try the forums here:
   http://openenergymonitor.org/emon/forum
 */

function vis_widgetlist(){
  var widgets = {
    "realtime":
    {
      "offsetx":0,"offsety":0,"width":400,"height":300,
      "menu":"Visualisations",
      "options":["feedid","colour"],
      "optionstype":["feedid","colour_picker"],
      "optionsname":[_Tr("Feed"),_Tr("Colour")],
      "optionshint":[_Tr("Feed source"),_Tr("Line colour in hex. Blank is use default.")],
      "html":""
    },

    "rawdata":
    {
      "offsetx":0,"offsety":0,"width":400,"height":300,
      "menu":"Visualisations",
      "options":["feedid","colour","units","dp","scale","fill"],
      "optionstype":["feedid","colour_picker","value","value","value","value"],
      "optionsname":[_Tr("Feed"),_Tr("Colour"),_Tr("units"),_Tr("dp"),_Tr("scale"),_Tr("Fill")],
      "optionshint":[_Tr("Feed source"),_Tr("Line colour in hex. Blank is use default."),_Tr("units"),_Tr("Decimal points"),_Tr("Scale by"),_Tr("Fill value")],

      "html":""
    },

    "bargraph":
    {
      "offsetx":0,"offsety":0,"width":400,"height":300,
      "menu":"Visualisations",
      "options":["feedid","colour","interval","units","dp","scale","delta","mode"],
      "optionstype":["feedid","colour_picker","value","value","value","value","boolean","value"],
      "optionsname":[_Tr("Feed"),_Tr("Colour"),_Tr("interval"),_Tr("units"),_Tr("dp"),_Tr("scale"),_Tr("delta"),_Tr("mode")],
      "optionshint":[_Tr("Feed source"),_Tr("Line colour in hex. Blank is use default."),_Tr("Interval (seconds)-you can set \"d\" for day, \"m\" for month, or \"y\" for year"),_Tr("Units"),_Tr("Decimal points"),_Tr("Scale by"),_Tr("Show difference between each bar"),_Tr("Mode set to 'daily' can be used instead of interval for timezone based daily data")],
      "html":""
    },

    "timestoredaily":
    {
      "offsetx":0,"offsety":0,"width":400,"height":300,
      "menu":"Visualisations",
      "options":["feedid","units"],
      "optionstype":["feedid","value"],
      "optionsname":[_Tr("Feed"),_Tr("Units")],
      "optionshint":[_Tr("Feed source"),_Tr("Units to show")],
      "html":""
    },

    "zoom":
    {
      "offsetx":0,"offsety":0,"width":400,"height":300,
      "menu":"Visualisations",
      "options":["power","kwhd","currency","currency_after_val","pricekwh","delta"],
      "optionstype":["feedid","feedid","value","value","value","boolean"],
      "optionsname":[_Tr("Power"),_Tr("kwhd"),_Tr("Currency"),_Tr("Currency position"),_Tr("Kwh price"),_Tr("delta")],
      "optionshint":[_Tr("Power to show"),_Tr("kwhd source"),_Tr("Currency to show"),_Tr("0 = before value, 1 = after value"),_Tr("Set kwh price"),_Tr("Show difference between each bar")],
      "html":""
    },

    "simplezoom":
    {
      "offsetx":0,"offsety":0,"width":400,"height":300,
      "menu":"Visualisations",
      "options":["power","kwhd","delta"],
      "optionstype":["feedid","feedid","boolean"],
      "optionsname":[_Tr("Power"),_Tr("kwhd"),_Tr("delta")],
      "optionshint":[_Tr("Power to show"),_Tr("kwhd source"),_Tr("Show difference between each bar")],
      "html":""
    },

    "histgraph":
    {
      "offsetx":0,"offsety":0,"width":400,"height":300,
      "menu":"Visualisations",
      "options":["feedid"],
      "optionstype":["feedid"],
      "optionsname":[_Tr("Feed")],
      "optionshint":[_Tr("Feed source")],
      "html":""
    },

    "threshold":
    {
      "offsetx":0,"offsety":0,"width":400,"height":300,
      "menu":"Visualisations",
      "options":["feedid","thresholdA","thresholdB"],
      "optionstype":["feedid","value","value"],
      "optionsname":[_Tr("Feed"),_Tr("Threshold A"),_Tr("Threshold B")],
      "optionshint":[_Tr("Feed source"),_Tr("Threshold A used"),_Tr("Threshold B used")],
      "html":""
    },

    "orderthreshold":
    {
      "offsetx":0,"offsety":0,"width":400,"height":300,
      "menu":"Visualisations",
      "options":["feedid","power","thresholdA","thresholdB"],
      "optionstype":["feedid","feedid","value","value"],
      "optionsname":[_Tr("Feed"),_Tr("Power"),_Tr("Threshold A"),_Tr("Threshold B")],
      "optionshint":[_Tr("Feed source"),_Tr("Power"),_Tr("Threshold A used"),_Tr("Threshold B used")],
      "html":""
    },

    "orderbars":
    {
      "offsetx":0,"offsety":0,"width":400,"height":300,
      "menu":"Visualisations",
      "options":["feedid","delta"],
      "optionstype":["feedid","boolean"],
      "optionsname":[_Tr("Feed"),_Tr("delta")],
      "optionshint":[_Tr("Feed source"),_Tr("Show difference between each bar")],
      "html":""
    },

    "stacked":
    {
      "offsetx":0,"offsety":0,"width":400,"height":300,
      "menu":"Visualisations",
      "options":["bottom","top","colourt","colourb","delta"],
      "optionstype":["feedid","feedid","colour_picker","colour_picker","boolean"],
      "optionsname":[_Tr("Bottom"),_Tr("Top"),_Tr("Top colour"),_Tr("Bottom colour"),_Tr("delta")],
      "optionshint":[_Tr("Bottom feed value"),_Tr("Top feed value"),_Tr("Top colour"),_Tr("Bottom colour"),_Tr("Show difference between each bar")],
      "html":""
    },

    "stackedsolar":
    {
      "offsetx":0,"offsety":0,"width":400,"height":300,
      "menu":"Visualisations",
      "options":["solar","consumption","delta"],
      "optionstype":["feedid","feedid","boolean"],
      "optionsname":[_Tr("Solar"),_Tr("Consumption"),_Tr("delta")],
      "optionshint":[_Tr("Solar feed value"),_Tr("Consumption feed value"),_Tr("Show difference between each bar")],
      "html":""
    },

    "smoothie":
    {
      "offsetx":0,"offsety":0,"width":400,"height":300,
      "menu":"Visualisations",
      "options":["feedid","ufac"],
      "optionstype":["feedid","value"],
      "optionsname":[_Tr("Feed"),_Tr("Ufac")],
      "optionshint":[_Tr("Feed source"),_Tr("Ufac value")],
      "html":""
    },

    "multigraph":
    {
      "offsetx":0,"offsety":0,"width":400,"height":300,
      "menu":"Visualisations",
      "options":["mid"],
      "optionstype":["dropbox"],
      "optionsname":[_Tr("Multigraph")],
      "optionshint":[_Tr("Managed on Visualization module")],
      "optionsdata":[multigraphsDropBoxOptions], // Gets multigraphs from vis_widget.php multigraphsDropBoxOptions variable
      "html":""
    },

    "timecompare":
    {
      "offsetx":0,"offsety":0,"width":400,"height":300,
      "menu":"Visualisations",
      "options":["feedid","fill","depth","npoints"],
      "optionstype":["feedid","value","value","value"],
      "optionsname":[_Tr("Feed"),_Tr("Fill"),_Tr("Depth"),_Tr("Data points")],
      "optionshint":[_Tr("Feed source"),_Tr("Fill under line"),_Tr("Number of lines"),_Tr("Default: 800")],
      "html":""
    }
  }

  return widgets;
}

function vis_init(){
  vis_draw();
}

function vis_draw(){
  var vislist = vis_widgetlist();

  var visclasslist = '';
  for (z in vislist) { visclasslist += '.'+z+','; }
  visclasslist = visclasslist.slice(0, -1);

  $(visclasslist).each(function(){
    var id = $(this).attr("id");
    var feed = $(this).attr("feed") || 0;
    var width = $(this).width();
    var height = $(this).height();

    var apikey_string = "";
    if (apikey) apikey_string = "&apikey="+apikey;

    if (!$(this).html() || reloadiframe==id || reloadiframe==-1 || apikey){
        var attrstring = "";
        var target = $(this).get(0);
        var l = target.attributes.length;
        for (var i=0; i<l; i++){
          var attr = target.attributes[i].name;
          if (attr!="id" && attr!="class" && attr!="style"){
            attrstring += "&"+attr+"="+target.attributes[i].value;
          }
        }
        pathfix=path.substr(path.indexOf('://')+3); // remove protocol
        pathfix=pathfix.substr(pathfix.indexOf('/')); // remove hostname
        $(this).html('');
        console.log('--> new relative url for iframe of '+ $(this).attr("class") + ': '+pathfix+'vis/'+$(this).attr("class")+'?embed=1'+attrstring+apikey_string);
    }

    var iframe = $(this).children('iframe');
    iframe.width(width);
    iframe.height(height);

  });
  reloadiframe = 0;
}

function vis_slowupdate() {}

function vis_fastupdate() {}
<|endoftext|>


<commit_before>/**
 * Module dependencies.
 */

var _ = require('lodash');
var defaultsDeep = require('merge-defaults');
var async = require('async');

module.exports = function(sails) {

  /**
   * Expose hook constructor
   *
   * @api private
   */

  return Hook;

  function Hook(definition) {

    /**
     * Load the hook asynchronously
     *
     * @api private
     */

    this.load = function(cb) {

      var self = this;

      // Determine if this hook should load based on Sails environment & hook config
      if (this.config.envs &&
        this.config.envs.length > 0 &&
        this.config.envs.indexOf(sails.config.environment) === -1) {
        return cb();
      }

      // Convenience config to bind routes before any of the static app routes
      sails.on('router:before', function() {
        _.each(self.routes.before, function(middleware, route) {
          middleware._middlewareType = self.identity.toUpperCase() + ' HOOK' + (middleware.name ? (': ' + middleware.name) : '');
          sails.router.bind(route, middleware);
        });
      });

      // Convenience config to bind routes after the static app routes
      sails.on('router:after', function() {
        _.each(self.routes.after, function(middleware, route) {
          middleware._middlewareType = self.identity.toUpperCase() + ' HOOK' + (middleware.name ? (': ' + middleware.name) : '');
          sails.router.bind(route, middleware);
        });
      });

      /**
       * Apply hook default configuration to sails.config
       *
       * @api private
       */
      function applyDefaults() {
        defaultsDeep(sails.config,
          _.isFunction(self.defaults) ?
          self.defaults(sails.config) :
          self.defaults);
      }

      // Run configure and loadModules methods
      async.auto({

        // If the `userconfig` hook is enabled, always wait for it
        // (unless of course, THIS IS `userconfig`)
        configuration: function(cb) {

          if (sails.config.hooks.userconfig) {

            // Can't wait for `userconfig` if this IS `userconfig`!!
            // Also, `moduleloader` cannot wait for userconfig.
            if (self.identity === 'userconfig' || self.identity === 'moduleloader') {

              applyDefaults();
              self.configure();
              return cb();
            }

            sails.after('hook:userconfig:loaded', function() {
              applyDefaults();
              self.configure();
              return cb();
            });
            return;
          }

          applyDefaults();
          self.configure();
          return cb();
        },

        // If the `moduleloader` hook is enabled, always wait for it
        // (unless of course, THIS IS `moduleloader`)
        modules: ['configuration',
          function(cb) {

            // Can't wait for moduleloader if this IS moduleloader!!
            if (self.identity === 'moduleloader') {
              return cb();
            }

            if (sails.config.hooks.moduleloader) {

              // Load modules
              sails.after('hook:moduleloader:loaded', function moduleloaderReady() {
                return self.loadModules(cb);
              });
              return;
            }

            return cb();
          }
        ]
      }, function(err) {
        if (err) return cb(err);

        // Call initialize() method if one provided
        if (self.initialize) {
          self.initialize(cb);
        } else cb();
      });

    };

    /**
     * Default configuration for this hook
     * (should be overiden by hook definition)
     *
     * @returns {}
     */
    this.defaults = function(config) {
      return {};
    };

    /**
     * `configure`
     *
     * Normalize and validate configuration for this hook.
     * Then fold modifications back into `sails.config`
     *
     * Hooks may override this function.
     */
    this.configure = function() {
      return;
    };

    /**
     * Hooks should override this function
     */
    this.loadModules = function(cb) {
      return cb();
    };

    /////// TODO: most of the following could be replaced by taking advantage of lodash "merge"

    // Ensure that the hook definition has valid properties
    _normalize(this);
    definition = _normalize(definition);

    // Merge default definition with overrides in the definition passed in
    _.extend(definition.config, this.config, definition.config);
    _.extend(definition.middleware, this.middleware, definition.middleware);
    _.extend(definition.routes.before, this.routes.before, definition.routes.before);
    _.extend(definition.routes.after, this.routes.after, definition.routes.after);
    _.extend(this, definition);

    // Bind context of new methods from definition
    _.bindAll(this);

    /**
     * Ensure that a hook definition has the required properties
     * @api private
     */

    function _normalize(def) {

      def = def || {};

      // Default hook config
      def.config = def.config || {};

      // list of environments to run in, if empty defaults to all
      def.config.envs = def.config.envs || [];

      def.middleware = def.middleware || {};

      // Default hook routes
      def.routes = def.routes || {};
      def.routes.before = def.routes.before || {};
      def.routes.after = def.routes.after || {};

      // Always set ready to true-- doesn't need to do anything asynchronous
      def.ready = true;

      return def;
    }
  }

};
<commit_msg>Easier installable hook default configuration using special __configKey__ key.<commit_after>/**
 * Module dependencies.
 */

var _ = require('lodash');
var defaultsDeep = require('merge-defaults');
var async = require('async');

module.exports = function(sails) {

  /**
   * Expose hook constructor
   *
   * @api private
   */

  return Hook;

  function Hook(definition) {

    /**
     * Load the hook asynchronously
     *
     * @api private
     */

    this.load = function(cb) {

      var self = this;

      // Determine if this hook should load based on Sails environment & hook config
      if (this.config.envs &&
        this.config.envs.length > 0 &&
        this.config.envs.indexOf(sails.config.environment) === -1) {
        return cb();
      }

      // Convenience config to bind routes before any of the static app routes
      sails.on('router:before', function() {
        _.each(self.routes.before, function(middleware, route) {
          middleware._middlewareType = self.identity.toUpperCase() + ' HOOK' + (middleware.name ? (': ' + middleware.name) : '');
          sails.router.bind(route, middleware);
        });
      });

      // Convenience config to bind routes after the static app routes
      sails.on('router:after', function() {
        _.each(self.routes.after, function(middleware, route) {
          middleware._middlewareType = self.identity.toUpperCase() + ' HOOK' + (middleware.name ? (': ' + middleware.name) : '');
          sails.router.bind(route, middleware);
        });
      });

      /**
       * Apply hook default configuration to sails.config
       *
       * @api private
       */
      function applyDefaults() {
        // Get the hook defaults
        var defaults = (_.isFunction(self.defaults) ?
                  self.defaults(sails.config) :
                  self.defaults) || {};
        // Replace the special __configKey__ key with the actual config key
        if (self.defaults.__configKey__ && self.configKey) {
          self.defaults[self.configKey] = self.defaults.__configKey__;
          delete self.defaults.__configKey__;
        }

        defaultsDeep(sails.config, defaults);
      }

      // Run configure and loadModules methods
      async.auto({

        // If the `userconfig` hook is enabled, always wait for it
        // (unless of course, THIS IS `userconfig`)
        configuration: function(cb) {

          if (sails.config.hooks.userconfig) {

            // Can't wait for `userconfig` if this IS `userconfig`!!
            // Also, `moduleloader` cannot wait for userconfig.
            if (self.identity === 'userconfig' || self.identity === 'moduleloader') {

              applyDefaults();
              self.configure();
              return cb();
            }

            sails.after('hook:userconfig:loaded', function() {
              applyDefaults();
              self.configure();
              return cb();
            });
            return;
          }

          applyDefaults();
          self.configure();
          return cb();
        },

        // If the `moduleloader` hook is enabled, always wait for it
        // (unless of course, THIS IS `moduleloader`)
        modules: ['configuration',
          function(cb) {

            // Can't wait for moduleloader if this IS moduleloader!!
            if (self.identity === 'moduleloader') {
              return cb();
            }

            if (sails.config.hooks.moduleloader) {

              // Load modules
              sails.after('hook:moduleloader:loaded', function moduleloaderReady() {
                return self.loadModules(cb);
              });
              return;
            }

            return cb();
          }
        ]
      }, function(err) {
        if (err) return cb(err);

        // Call initialize() method if one provided
        if (self.initialize) {
          self.initialize(cb);
        } else cb();
      });

    };

    /**
     * Default configuration for this hook
     * (should be overiden by hook definition)
     *
     * @returns {}
     */
    this.defaults = function(config) {
      return {};
    };

    /**
     * `configure`
     *
     * Normalize and validate configuration for this hook.
     * Then fold modifications back into `sails.config`
     *
     * Hooks may override this function.
     */
    this.configure = function() {
      return;
    };

    /**
     * Hooks should override this function
     */
    this.loadModules = function(cb) {
      return cb();
    };

    /////// TODO: most of the following could be replaced by taking advantage of lodash "merge"

    // Ensure that the hook definition has valid properties
    _normalize(this);
    definition = _normalize(definition);

    // Merge default definition with overrides in the definition passed in
    _.extend(definition.config, this.config, definition.config);
    _.extend(definition.middleware, this.middleware, definition.middleware);
    _.extend(definition.routes.before, this.routes.before, definition.routes.before);
    _.extend(definition.routes.after, this.routes.after, definition.routes.after);
    _.extend(this, definition);

    // Bind context of new methods from definition
    _.bindAll(this);

    /**
     * Ensure that a hook definition has the required properties
     * @api private
     */

    function _normalize(def) {

      def = def || {};

      // Default hook config
      def.config = def.config || {};

      // list of environments to run in, if empty defaults to all
      def.config.envs = def.config.envs || [];

      def.middleware = def.middleware || {};

      // Default hook routes
      def.routes = def.routes || {};
      def.routes.before = def.routes.before || {};
      def.routes.after = def.routes.after || {};

      // Always set ready to true-- doesn't need to do anything asynchronous
      def.ready = true;

      return def;
    }
  }

};
<|endoftext|>


<commit_before>goog.provide('og.proj');
goog.provide('og.proj.Projection');
goog.provide('og.Units');
goog.provide('og.proj.METERS_PER_UNIT');

/**
 * Projection units: 'degrees', 'ft', 'm' or 'km'.
 * @enum {string}
 * @api
 */
og.proj.Units = {
    DEGREES: 'degrees',
    FEET: 'ft',
    METERS: 'm',
    KILOMETERS: 'km',
};

/**
 * Meters per unit lookup table.
 * @const
 * @type {Object.<og.proj.Units, number>}
 * @api
 */
og.proj.METERS_PER_UNIT = {};
og.proj.METERS_PER_UNIT[og.proj.Units.FEET] = 0.3048;
og.proj.METERS_PER_UNIT[og.proj.Units.METERS] = 1;
og.proj.METERS_PER_UNIT[og.proj.Units.KILOMETERS] = 1000;

og.proj.Projection = function (options) {

    /**
     * @public
     * @type {string}
     */
    this.code = options.code;

    /**
     * @public
     * @type {og.proj.Units}
     */
    this.units = /** @type {ol.proj.Units} */ (options.units);

    /**
     * Projection identifier, especially usefull for comparison.
     * @const
     * @type {integer}
     */
    this.id = og.proj.Projection._counter++;
};

og.proj.Projection._counter = 0;<commit_msg>Units object commas bug fixed.<commit_after>goog.provide('og.proj');
goog.provide('og.proj.Projection');
goog.provide('og.Units');
goog.provide('og.proj.METERS_PER_UNIT');

/**
 * Projection units: 'degrees', 'ft', 'm' or 'km'.
 * @enum {string}
 * @api
 */
og.proj.Units = {
    "DEGREES": "degrees",
    "FEET": "ft",
    "METERS": "m",
    "KILOMETERS": "km"
};

/**
 * Meters per unit lookup table.
 * @const
 * @type {Object.<og.proj.Units, number>}
 * @api
 */
og.proj.METERS_PER_UNIT = {};
og.proj.METERS_PER_UNIT[og.proj.Units.FEET] = 0.3048;
og.proj.METERS_PER_UNIT[og.proj.Units.METERS] = 1;
og.proj.METERS_PER_UNIT[og.proj.Units.KILOMETERS] = 1000;

og.proj.Projection = function (options) {

    /**
     * @public
     * @type {string}
     */
    this.code = options.code;

    /**
     * @public
     * @type {og.proj.Units}
     */
    this.units = /** @type {ol.proj.Units} */ (options.units);

    /**
     * Projection identifier, especially usefull for comparison.
     * @const
     * @type {integer}
     */
    this.id = og.proj.Projection._counter++;
};

og.proj.Projection._counter = 0;<|endoftext|>


<commit_before>/*
HTTP Strict Transport Security (HSTS)

http://tools.ietf.org/html/draft-ietf-websec-strict-transport-sec-04

*/

module.exports = function (maxAge, includeSubdomains) {
    if (!maxAge) maxAge = '15768000'; // Approximately 6 months
    var header = "maxAge=" + maxAge;

    if (includeSubdomains) header += '; includeSubdomains';

    return function (req, res, next)  {
        if (req.connection.encrypted) {
            res.header('Strict-Transport-Security', header);
        }
        next();
    };
};

<commit_msg>Use req.secure if it is set<commit_after>/*
HTTP Strict Transport Security (HSTS)

http://tools.ietf.org/html/draft-ietf-websec-strict-transport-sec-04

*/

module.exports = function (maxAge, includeSubdomains) {
    if (!maxAge) maxAge = '15768000'; // Approximately 6 months
    var header = "maxAge=" + maxAge;

    if (includeSubdomains) header += '; includeSubdomains';

    return function (req, res, next)  {
        if (typeof req.secure !== "undefined" ? req.secure : req.connection.encrypted) {
            res.header('Strict-Transport-Security', header);
        }
        next();
    };
};

<|endoftext|>


<commit_before><commit_msg>app.js<commit_after><|endoftext|>


<commit_before>/* Ember Mocha Adapter | (C) 2014 Teddy Zeenny | https://github.com/teddyzeenny/ember-mocha-adapter */

(function() {
  var done, doneTimeout, isAsync, emberBdd, isPromise;

  done = null;
  doneTimeout = null;
  isAsync = 0;

  Ember.Test.MochaAdapter = Ember.Test.Adapter.extend({
    init: function() {
      this._super();
      window.Mocha.interfaces['ember-bdd'] = emberBdd;
      window.mocha.ui('ember-bdd');
    },
    asyncStart: function() {
      isAsync++;
      clearTimeout(doneTimeout);
    },
    asyncEnd: function() {
      if (--isAsync === 0 && done && !isPromise) {
        doneTimeout = setTimeout(function() {
          complete();
        });
      }
    },
    exception: function(reason) {
      if (!(reason instanceof Error)) {
        reason = new Error(reason);
      }
      if (done) {
        complete(reason);
      } else {
        setTimeout(function() {
          throw reason;
        });
      }
    }
  });

  function fixAsync(suites, methodName) {
    return function(name, fn) {
      if (!fn) {
        fn = name;
        name = fn.name;
      }

      var suite = suites[0];
      var hook = suite[methodName];
      var asyncFn = fn;

      if (fn.length === 0) {
        asyncFn = function(d) {
          invoke(this, fn, d);
        };
      }

      if (hook.length === 2) {
        hook.call(suite, name, asyncFn);
      } else {
        hook.call(suite, asyncFn);
      }
    };
  }

  function invoke(context, fn, d) {
    done = d;
    isPromise = false;
    var result = fn.call(context);
    // If a promise is returned,
    // complete test when promise fulfills / rejects
    if (result && typeof result.then === 'function') {
      isPromise = true;
      result.then(function() { complete(); }, complete);
    } else {
      Ember.deprecate('Relying on the implicit async behavior of acceptance tests is deprecated. ' +
        'Please make sure to `return` your last async helper (e.g. `return andThen(...);`) from ' +
        'the test function or add `return wait();` to the end of your acceptance tests.\n\nThis will ' +
        'allow you to upgrade to Mocha 3.x soon.\n\n', isAsync === 0, {
        id: 'ember-mocha.implicit-async',
        until: '1.0.0',
        url: 'https://github.com/emberjs/ember-mocha#acceptance-tests'
      });

      if (isAsync === 0) { complete(); }
    }
  }

  // Called whenever an async test passes or fails.
  // if `e` is passed, that means the test
  // failed with exception `e`
  function complete(e) {
    clearTimeout(doneTimeout);
    if (!done) { return; }
    var d = done;
    done = null;
    if (e) {
      // test failure
      if (!(e instanceof Error)) {
        e = new Error(e);
      }
      d(e);
    } else {
      // test passed
      d();
    }
  }

  /**
   ember-bdd mocha interface.
   This interface allows
   the Ember.js tester
   to forget about sync / async
   and treat all tests the same.

   This interface, along with the adapter
   will take care of handling sync vs async
   */

  emberBdd = function(suite) {
    var suites = [suite];

    suite.on('pre-require', function(context, file, mocha) {

      context.before = fixAsync(suites, 'beforeAll');

      context.after = fixAsync(suites, 'afterAll');

      context.beforeEach = fixAsync(suites, 'beforeEach');

      context.afterEach = fixAsync(suites, 'afterEach');

      context.it = context.specify = function(title, fn){
        var suite = suites[0], test;
        if (suite.pending) {
          fn = null;
        }
        if (!fn || fn.length === 1) {
          test = new Mocha.Test(title, fn);
        } else {
          var method = function(d) {
            invoke(this, fn, d);
          };
          method.toString = function() {
            return fn.toString();
          }
          test = new Mocha.Test(title, method);
        }
        suite.addTest(test);
        return test;
      };

      context.describe = context.context = function(title, fn){
        var suite = Mocha.Suite.create(suites[0], title);
        suites.unshift(suite);
        fn.call(suite);
        suites.shift();
        return suite;
      };

      context.xdescribe =
        context.xcontext =
          context.describe.skip = function(title, fn){
            var suite = Mocha.Suite.create(suites[0], title);
            suite.pending = true;
            suites.unshift(suite);
            fn.call(suite);
            suites.shift();
          };

      context.describe.only = function(title, fn){
        var suite = context.describe(title, fn);
        mocha.grep(suite.fullTitle());
      };

      context.it.only = function(title, fn){
        var test = context.it(title, fn);
        mocha.grep(test.fullTitle());
      };

      context.xit =
        context.xspecify =
          context.it.skip = function(title){
            context.it(title);
          };

    });

  };

}());

Ember.Test.adapter = Ember.Test.MochaAdapter.create();
<commit_msg>ember-mocha-adapter: Add test name to deprecation message<commit_after>/* Ember Mocha Adapter | (C) 2014 Teddy Zeenny | https://github.com/teddyzeenny/ember-mocha-adapter */

(function() {
  var done, doneTimeout, isAsync, emberBdd, isPromise;

  done = null;
  doneTimeout = null;
  isAsync = 0;

  Ember.Test.MochaAdapter = Ember.Test.Adapter.extend({
    init: function() {
      this._super();
      window.Mocha.interfaces['ember-bdd'] = emberBdd;
      window.mocha.ui('ember-bdd');
    },
    asyncStart: function() {
      isAsync++;
      clearTimeout(doneTimeout);
    },
    asyncEnd: function() {
      if (--isAsync === 0 && done && !isPromise) {
        doneTimeout = setTimeout(function() {
          complete();
        });
      }
    },
    exception: function(reason) {
      if (!(reason instanceof Error)) {
        reason = new Error(reason);
      }
      if (done) {
        complete(reason);
      } else {
        setTimeout(function() {
          throw reason;
        });
      }
    }
  });

  function fixAsync(suites, methodName) {
    return function(name, fn) {
      if (!fn) {
        fn = name;
        name = fn.name;
      }

      var suite = suites[0];
      var hook = suite[methodName];
      var asyncFn = fn;

      if (fn.length === 0) {
        asyncFn = function(d) {
          invoke(this, fn, d);
        };
      }

      if (hook.length === 2) {
        hook.call(suite, name, asyncFn);
      } else {
        hook.call(suite, asyncFn);
      }
    };
  }

  function invoke(context, fn, d) {
    done = d;
    isPromise = false;
    var result = fn.call(context);
    // If a promise is returned,
    // complete test when promise fulfills / rejects
    if (result && typeof result.then === 'function') {
      isPromise = true;
      result.then(function() { complete(); }, complete);
    } else {
      var testName = getTestName(context);
      var messageSuffix = testName ? ('Test: ' + testName + '\n\n') : '';

      Ember.deprecate('Relying on the implicit async behavior of acceptance tests is deprecated. ' +
        'Please make sure to `return` your last async helper (e.g. `return andThen(...);`) from ' +
        'the test function or add `return wait();` to the end of your acceptance tests.\n\nThis will ' +
        'allow you to upgrade to Mocha 3.x soon.\n\n'+ messageSuffix, isAsync === 0, {
        id: 'ember-mocha.implicit-async',
        until: '1.0.0',
        url: 'https://github.com/emberjs/ember-mocha#acceptance-tests'
      });

      if (isAsync === 0) { complete(); }
    }
  }

  function getTestName(context) {
    var titles = [];

    var node = context.test;
    while (node) {
      if (node.title) {
        titles.push(node.title);
      }

      node = node.parent;
    }

    return titles.reverse().join(' ');
  }

  // Called whenever an async test passes or fails.
  // if `e` is passed, that means the test
  // failed with exception `e`
  function complete(e) {
    clearTimeout(doneTimeout);
    if (!done) { return; }
    var d = done;
    done = null;
    if (e) {
      // test failure
      if (!(e instanceof Error)) {
        e = new Error(e);
      }
      d(e);
    } else {
      // test passed
      d();
    }
  }

  /**
   ember-bdd mocha interface.
   This interface allows
   the Ember.js tester
   to forget about sync / async
   and treat all tests the same.

   This interface, along with the adapter
   will take care of handling sync vs async
   */

  emberBdd = function(suite) {
    var suites = [suite];

    suite.on('pre-require', function(context, file, mocha) {

      context.before = fixAsync(suites, 'beforeAll');

      context.after = fixAsync(suites, 'afterAll');

      context.beforeEach = fixAsync(suites, 'beforeEach');

      context.afterEach = fixAsync(suites, 'afterEach');

      context.it = context.specify = function(title, fn){
        var suite = suites[0], test;
        if (suite.pending) {
          fn = null;
        }
        if (!fn || fn.length === 1) {
          test = new Mocha.Test(title, fn);
        } else {
          var method = function(d) {
            invoke(this, fn, d);
          };
          method.toString = function() {
            return fn.toString();
          }
          test = new Mocha.Test(title, method);
        }
        suite.addTest(test);
        return test;
      };

      context.describe = context.context = function(title, fn){
        var suite = Mocha.Suite.create(suites[0], title);
        suites.unshift(suite);
        fn.call(suite);
        suites.shift();
        return suite;
      };

      context.xdescribe =
        context.xcontext =
          context.describe.skip = function(title, fn){
            var suite = Mocha.Suite.create(suites[0], title);
            suite.pending = true;
            suites.unshift(suite);
            fn.call(suite);
            suites.shift();
          };

      context.describe.only = function(title, fn){
        var suite = context.describe(title, fn);
        mocha.grep(suite.fullTitle());
      };

      context.it.only = function(title, fn){
        var test = context.it(title, fn);
        mocha.grep(test.fullTitle());
      };

      context.xit =
        context.xspecify =
          context.it.skip = function(title){
            context.it(title);
          };

    });

  };

}());

Ember.Test.adapter = Ember.Test.MochaAdapter.create();
<|endoftext|>


<commit_before>$(function() {

    // Magic underscore settings to allow underscore templates to play
    // nicely with Rails ERB templates!
    _.templateSettings = {
        interpolate: /\{\{\=(.+?)\}\}/g,
        evaluate: /\{\{(.+?)\}\}/g
    };

    // Models
    var Session = Backbone.Model.extend({
        defaults: {
            'owner': '',
            'repo': ''
        },
        initialize: function() {
            var self = this;
            _.bindAll(this, 'getURL');
            $.getJSON('/sessions/get', function(response) {
                var data = response.data;
                var token = null;
                if (response.status == "ok" && data.token) {
                    console.log('session created!');
                    token = data.token;
                }
                self.set('token', token);
            });
        },
        getURL: function() {
            var self = this;
            return self.get('owner') + '/' + self.get('repo');
        }
    });
    var session = new Session();

    var GithubUser = Backbone.Model.extend({
        initialize: function(user) {
            var name = user.login ? user.login : '';
            var gravatar = user.gravatar_id ? user.gravatar_id : '';
            var url = user.html_url ? user.html_url : '';

            this.set('name', name);
            this.set('gravatar', gravatar);
            this.set('url', url);
        },
        getLink: function() {
            var rval = ['',
                        this.getIcon(),
                        this.get('name'),
                        ''].join('');

            return rval;
        },
        getIcon: function() {
            var rval = [''].join('');

            return rval;
        }
    });

    var Issue = Backbone.Model.extend({
        getClosedTime: function() {
            var closed = this.get('closed_at') || 0;
            var date = new Date(closed);
            return date.getTime() / 1000;
        },
        getCreatedTime: function() {
            var created = this.get('created_at') || 0;
            var date = new Date(created);
            return date.getTime() / 1000;
        },
        createLink: function() {
            var rval = '';

            var assignee = this.get('assignee') || null;
            var creator = this.get('user');
            var title = this.get('title');
            var url = this.get('html_url');

            var created_at = new Date(this.get('created_at'));
            var issue_created = created_at.getMonth() + '/' + created_at.getDate() + '/' + created_at.getFullYear();

            if (creator && title && url) {
                var creator_user = new GithubUser(creator);
                var assigned_user = assignee ? new GithubUser(assignee) : null;
                rval = ['',
                        '',
                        creator_user.getIcon(),
                        '⇒',
                        assigned_user ? assigned_user.getIcon() : '?',
                        '',
                        title,
                        '' +
                        'created by ' + creator_user.get('name') + ' on ' + issue_created,
                        '',
                        ''].join('');
            }

            return rval;
        }
    });
    var IssuesBase = Backbone.Collection.extend({
        model: Issue,
        comparator: function(issue) {
            return issue.get('closed_at');
        },
        url: function() {
            var token = session.get('token');
            var owner = session.get('owner');
            var repo = session.get('repo');

            var url = ['https://api.github.com',
                       '/repos/'+owner+'/'+repo+'/issues',
                       '?access_token='+token,
                       '&state='+this.state,
                       '&milestone='+this.milestoneId,
                       ''].join('');
            return url;
        },
        parse: function(response) {
            return response;
        },
        state: 'open',
        milestoneId: 0
    });
    var OpenIssues = IssuesBase.extend({
        state: 'open'
    });
    var ClosedIssues = IssuesBase.extend({
        state: 'closed'
    });

    var Milestone = Backbone.Model.extend({
        getNumIssues: function() {
            return this.get('open_issues') + this.get('closed_issues');
        },
        getCreator: function() {
            var rval = '';
            var creator = this.get('creator');

            if (creator) {
                var user = new GithubUser(creator);
                rval = user.getLink();
            }

            return rval;
        },
        getDueDateFormatted: function() {
            var date = new Date(this.get('due_on'));
            var dateArray = date.toString().split(' ');
            return dateArray.slice(0, 4).join(' ');
        }
    });
    var Milestones = Backbone.Collection.extend({
        model: Milestone,
        url: function() {
            var token = session.get('token');
            var owner = session.get('owner');
            var repo = session.get('repo');

            var url = ['https://api.github.com',
                       '/repos/'+owner+'/'+repo+'/milestones',
                       '?access_token=',
                       token].join('');
            return url;
        },
        parse: function(response) {
            console.log('parsing...');
            return response;
        },
        getByNumber: function(id) {
            var number = parseInt(id, 10);
            return this.findWhere({number: number});
        }
    });
    var milestones = new Milestones();

    var Message = Backbone.Model.extend({
        initialize: function() {
            _.bindAll(this, 'setProblem', 'setError');
        },
        setProblem: function(text) {
            var self = this;
            self.set('title', 'Problem');
            self.set('text', text);
        },
        setError: function(text) {
            var self = this;
            self.set('title', 'Error');
            self.set('text', text);
        }
    });

    // Views
    var RepoView = Backbone.View.extend({
        el: '.content',
        events: {
            'click button#fetch': 'getInputText',
            'keypress input[type=text]': 'filterKeypress'
        },
        initialize: function() {
            _.bindAll(this, 'render', 'filterKeypress', 'loadRepoMilestones',
                            'getInputText', 'errorHandler');
            var self = this;

            self.message = new Message();

            milestones.on('sync', function() {
                if (milestones.length === 0) {
                    self.message.setProblem('This repository has no milestones!');
                }
                self.render();
            });
            milestones.on('error', self.errorHandler, this);
        },
        render: function() {
            var self = this;
            var template = _.template($("#tmpl_repo").html(),
                                      {milestones: milestones.models,
                                       session: session,
                                       message: self.message});
            this.$el.html( template );
            return this;
        },
        filterKeypress: function(e) {
            var self = this;

            // If 'enter' key pressed, process the input field.
            if (e.keyCode == 13) self.getInputText();
        },
        loadRepoMilestones: function(owner, repo) {
            var self = this;

            self.message.clear();
            milestones.reset();

            // Update session model.
            session.set('owner', owner);
            session.set('repo', repo);

            // Fetch the milestones.
            milestones.fetch();
        },
        getInputText: function() {
            var self = this;

            // Parse the input textbox for the owner and respository.
            var input = $('input', this.el).val();
            var parts = input.split('/');
            var owner = parts[0] || null;
            var repo = parts[1] || null;

            // Persist the owner/repo to the url.
            router.navigate(owner + '/' + repo);

            self.loadRepoMilestones(owner, repo);
        },
        errorHandler: function(model, error) {
            var self = this;
            console.log('KA-BOOM!');
            if (!session.get('token') || error.status == 403) {
                self.message.setError('Sign into Github before you wreck yourself!');
                self.render();
            } else if (error.status == 404) {
                self.message.setProblem('Repository not found! Do you have access to it?');
                self.render();
            } else {
                console.log('error: ', error);
            }
        }
    });

    var MilestoneView = Backbone.View.extend({
        el: '.content',
        initialize: function() {
            _.bindAll(this, 'render', 'loadMilestone', 'renderChart');
            var self = this;

            self.message = new Message();
            self.milestone = new Milestone();
            self.openIssues = new OpenIssues();
            self.closedIssues = new ClosedIssues();

            // dependencies
            self.openIssues.on('sync', self.renderChart);
            self.closedIssues.on('sync', self.renderChart);
        },
        render: function(tmpl, data) {
            var template = _.template($(tmpl).html(), data);
            this.$el.html( template );
            return this;
        },
        renderChart: function() {
            var self = this;

            if (self.openIssues.length > 0 && self.closedIssues.length > 0) {
                // Clear the chart of any previous elements.
                $('#chart').empty();
                $('#y_axis').empty();
                $('#legend').empty();

                var totalIssueCount = self.openIssues.length + self.closedIssues.length;

                // Add ideal velocity line.
                var start = self.milestone.get('created_at');
                var end = self.milestone.get('due_on') || new Date().toISOString();
                var startDate = new Date(start).getTime() / 1000;
                var endDate = new Date(end).getTime() / 1000;

                var ideal = [
                    {x: startDate, y: totalIssueCount},
                    {x: endDate,   y: 0}
                ];

                // Add actual velocity line.
                var closedCount = totalIssueCount;

                var actual = _.map(self.closedIssues.models, function(issue) {
                    return {
                        x: issue.getClosedTime(),
                        y: --closedCount
                    };
                });

                // Add creation line.
                var allIssues = self.openIssues.models.concat(self.closedIssues.models);
                allIssues = _.sortBy(allIssues, function(issue) { return issue.getCreatedTime(); });

                var openCount = 0;

                var created = _.map(allIssues, function(issue) {
                    var createdTime = issue.getCreatedTime();
                    return {
                        x: createdTime >= startDate ? createdTime : startDate,
                        y: ++openCount
                    };
                });

                console.log('issue: ', allIssues[0]);

                // Build graph!
                var graph = new Rickshaw.Graph({
                    element: document.querySelector("#chart"),
                    width: 900,
                    height: 500,
                    renderer: 'line',
                    interpolation: 'basis',
                    series: [{
                        data:  ideal,
                        color: '#75ABC5',
                        name:  'Ideal'
                    }, {
                        data:  actual,
                        color: '#F89406',
                        name:  'Actual'
                    }, {
                        data:  created,
                        color: '#30c020',
                        name:  'Created'
                    }]
                });
                graph.render();

                var legend = new Rickshaw.Graph.Legend( {
                    graph: graph,
                    element: document.getElementById('legend')

                } );

                var highlighter = new Rickshaw.Graph.Behavior.Series.Highlight( {
                    graph: graph,
                    legend: legend
                } );

                var time = new Rickshaw.Fixtures.Time();
                var days = time.unit('day');

                var xAxis = new Rickshaw.Graph.Axis.Time({
                    graph: graph
                    //timeUnit: days
                });

                xAxis.render();

                var yAxis = new Rickshaw.Graph.Axis.Y({
                    graph:          graph,
                    tickFormat:     Rickshaw.Fixtures.Number.formatKMBT,
                    ticksTreatment: 'glow',
                    orientation:    'left',
                    element:        document.getElementById('y_axis')
                });

                yAxis.render();
            }
        },
        loadMilestone: function(id) {
            var self = this;

            // Render the loading template.
            self.render("#tmpl_loading", {});

            self.milestone = milestones.getByNumber(id);
            console.log('milestone: ', self.milestone);

            self.openIssues.milestoneId = self.milestone.get('number');
            self.closedIssues.milestoneId = self.milestone.get('number');

            // Clear any previous messages.
            self.message.clear();

            // Set a message if the milestone has no due date.
            if (self.milestone.get('due_on') === null) {
                self.message.setProblem('Milestone has no due date!');
            }

            // Render the milestone template.
            self.render('#tmpl_milestone', {milestone: self.milestone,
                                            session: session,
                                            message: self.message});

            self.openIssues.fetch({
                success: function(issues) {
                    data = {
                        issues: issues.models
                    };
                    var template = _.template($('#tmpl_issues').html(), data);
                    $('.open', self.el).html(template);
                }
            });
            self.closedIssues.fetch({
                success: function(issues) {
                    data = {
                        issues: issues.models
                    };
                    var template = _.template($('#tmpl_issues').html(), data);
                    $('.closed', self.el).html(template);
                }
            });
        }
    });

    // Router
    var Router = Backbone.Router.extend({
        routes: {
            '': 'home',
            ':owner/:repo': 'repository',
            ':owner/:repo/:id': 'milestone'
        }
    });

    // Instantiations.
    var repoView = new RepoView();
    var milestoneView = new MilestoneView();
    var router = new Router();

    router.on('route:home', function() {
        console.log('Load the home page!');
        repoView.render();
    });

    router.on('route:milestone', function(owner, repo, id) {
        console.log('Load the milestone page!');
        // load token
        // load owner/repo
        // load milestones
        // renders repoView
        // safe: load milestoneView!
        repoView.loadRepoMilestones(owner, repo);
        milestones.once('sync', function() {
            milestoneView.loadMilestone(id);
        });
    });

    router.on('route:repository', function(owner, repo) {
        console.log('Load the repository page!');
        repoView.loadRepoMilestones(owner, repo);
    });

    // Once the session token finishes loading, start the application!
    session.once('change:token', function(model, value) {
        console.log('token: ', value);

        // Let's get this party started!
        Backbone.history.start();
    });
});
<commit_msg>Add respository summary view and route. #27<commit_after>$(function() {

    // Magic underscore settings to allow underscore templates to play
    // nicely with Rails ERB templates!
    _.templateSettings = {
        interpolate: /\{\{\=(.+?)\}\}/g,
        evaluate: /\{\{(.+?)\}\}/g
    };

    // Models
    var Session = Backbone.Model.extend({
        defaults: {
            'owner': '',
            'repo': ''
        },
        initialize: function() {
            var self = this;
            _.bindAll(this, 'getURL');
            $.getJSON('/sessions/get', function(response) {
                var data = response.data;
                var token = null;
                if (response.status == "ok" && data.token) {
                    console.log('session created!');
                    token = data.token;
                }
                self.set('token', token);
            });
        },
        getURL: function() {
            var self = this;
            return self.get('owner') + '/' + self.get('repo');
        }
    });
    var session = new Session();

    var GithubUser = Backbone.Model.extend({
        initialize: function(user) {
            var name = user.login ? user.login : '';
            var gravatar = user.gravatar_id ? user.gravatar_id : '';
            var url = user.html_url ? user.html_url : '';

            this.set('name', name);
            this.set('gravatar', gravatar);
            this.set('url', url);
        },
        getLink: function() {
            var rval = ['',
                        this.getIcon(),
                        this.get('name'),
                        ''].join('');

            return rval;
        },
        getIcon: function() {
            var rval = [''].join('');

            return rval;
        }
    });

    var Issue = Backbone.Model.extend({
        getClosedTime: function() {
            var closed = this.get('closed_at') || 0;
            var date = new Date(closed);
            return date.getTime() / 1000;
        },
        getCreatedTime: function() {
            var created = this.get('created_at') || 0;
            var date = new Date(created);
            return date.getTime() / 1000;
        },
        createLink: function() {
            var rval = '';

            var assignee = this.get('assignee') || null;
            var creator = this.get('user');
            var title = this.get('title');
            var url = this.get('html_url');

            var created_at = new Date(this.get('created_at'));
            var issue_created = created_at.getMonth() + '/' + created_at.getDate() + '/' + created_at.getFullYear();

            if (creator && title && url) {
                var creator_user = new GithubUser(creator);
                var assigned_user = assignee ? new GithubUser(assignee) : null;
                rval = ['',
                        '',
                        creator_user.getIcon(),
                        '⇒',
                        assigned_user ? assigned_user.getIcon() : '?',
                        '',
                        title,
                        '' +
                        'created by ' + creator_user.get('name') + ' on ' + issue_created,
                        '',
                        ''].join('');
            }

            return rval;
        }
    });
    var IssuesBase = Backbone.Collection.extend({
        model: Issue,
        comparator: function(issue) {
            return issue.get('closed_at');
        },
        url: function() {
            var token = session.get('token');
            var owner = session.get('owner');
            var repo = session.get('repo');

            var url = ['https://api.github.com',
                       '/repos/'+owner+'/'+repo+'/issues',
                       '?access_token='+token,
                       '&state='+this.state,
                       '&milestone='+this.milestoneId,
                       ''].join('');
            return url;
        },
        parse: function(response) {
            return response;
        },
        state: 'open',
        milestoneId: 0
    });
    var OpenIssues = IssuesBase.extend({
        state: 'open'
    });
    var ClosedIssues = IssuesBase.extend({
        state: 'closed'
    });

    var Milestone = Backbone.Model.extend({
        getNumIssues: function() {
            return this.get('open_issues') + this.get('closed_issues');
        },
        getCreator: function() {
            var rval = '';
            var creator = this.get('creator');

            if (creator) {
                var user = new GithubUser(creator);
                rval = user.getLink();
            }

            return rval;
        },
        getDueDateFormatted: function() {
            var date = new Date(this.get('due_on'));
            var dateArray = date.toString().split(' ');
            return dateArray.slice(0, 4).join(' ');
        }
    });
    var Milestones = Backbone.Collection.extend({
        model: Milestone,
        url: function() {
            var token = session.get('token');
            var owner = session.get('owner');
            var repo = session.get('repo');

            var url = ['https://api.github.com',
                       '/repos/'+owner+'/'+repo+'/milestones',
                       '?access_token=',
                       token].join('');
            return url;
        },
        parse: function(response) {
            console.log('parsing...');
            return response;
        },
        getByNumber: function(id) {
            var number = parseInt(id, 10);
            return this.findWhere({number: number});
        }
    });
    var milestones = new Milestones();

    var Message = Backbone.Model.extend({
        initialize: function() {
            _.bindAll(this, 'setProblem', 'setError');
        },
        setProblem: function(text) {
            var self = this;
            self.set('title', 'Problem');
            self.set('text', text);
        },
        setError: function(text) {
            var self = this;
            self.set('title', 'Error');
            self.set('text', text);
        }
    });

    // Views
    var RepoView = Backbone.View.extend({
        el: '.content',
        events: {
            'click button#fetch': 'getInputText',
            'keypress input[type=text]': 'filterKeypress'
        },
        initialize: function() {
            _.bindAll(this, 'render', 'filterKeypress', 'loadRepoMilestones',
                            'getInputText', 'errorHandler');
            var self = this;

            self.message = new Message();

            milestones.on('sync', function() {
                if (milestones.length === 0) {
                    self.message.setProblem('This repository has no milestones!');
                }
                self.render();
            });
            milestones.on('error', self.errorHandler, this);
        },
        render: function() {
            var self = this;
            var template = _.template($("#tmpl_repo").html(),
                                      {milestones: milestones.models,
                                       session: session,
                                       message: self.message});
            this.$el.html( template );
            return this;
        },
        filterKeypress: function(e) {
            var self = this;

            // If 'enter' key pressed, process the input field.
            if (e.keyCode == 13) self.getInputText();
        },
        loadRepoMilestones: function(owner, repo) {
            var self = this;

            self.message.clear();
            milestones.reset();

            // Update session model.
            session.set('owner', owner);
            session.set('repo', repo);

            // Fetch the milestones.
            milestones.fetch();
        },
        getInputText: function() {
            var self = this;

            // Parse the input textbox for the owner and respository.
            var input = $('input', this.el).val();
            var parts = input.split('/');
            var owner = parts[0] || null;
            var repo = parts[1] || null;

            // Persist the owner/repo to the url.
            router.navigate(owner + '/' + repo);

            self.loadRepoMilestones(owner, repo);
        },
        errorHandler: function(model, error) {
            var self = this;
            console.log('KA-BOOM!');
            if (!session.get('token') || error.status == 403) {
                self.message.setError('Sign into Github before you wreck yourself!');
                self.render();
            } else if (error.status == 404) {
                self.message.setProblem('Repository not found! Do you have access to it?');
                self.render();
            } else {
                console.log('error: ', error);
            }
        }
    });

    var MilestoneView = Backbone.View.extend({
        el: '.content',
        initialize: function() {
            _.bindAll(this, 'render', 'loadMilestone', 'renderChart');
            var self = this;

            self.message = new Message();
            self.milestone = new Milestone();
            self.openIssues = new OpenIssues();
            self.closedIssues = new ClosedIssues();

            // dependencies
            self.openIssues.on('sync', self.renderChart);
            self.closedIssues.on('sync', self.renderChart);
        },
        render: function(tmpl, data) {
            var template = _.template($(tmpl).html(), data);
            this.$el.html( template );
            return this;
        },
        renderChart: function() {
            var self = this;

            if (self.openIssues.length > 0 && self.closedIssues.length > 0) {
                // Clear the chart of any previous elements.
                $('#chart').empty();
                $('#y_axis').empty();
                $('#legend').empty();

                var totalIssueCount = self.openIssues.length + self.closedIssues.length;

                // Add ideal velocity line.
                var start = self.milestone.get('created_at');
                var end = self.milestone.get('due_on') || new Date().toISOString();
                var startDate = new Date(start).getTime() / 1000;
                var endDate = new Date(end).getTime() / 1000;

                var ideal = [
                    {x: startDate, y: totalIssueCount},
                    {x: endDate,   y: 0}
                ];

                // Add actual velocity line.
                var closedCount = totalIssueCount;

                var actual = _.map(self.closedIssues.models, function(issue) {
                    return {
                        x: issue.getClosedTime(),
                        y: --closedCount
                    };
                });

                // Add creation line.
                var allIssues = self.openIssues.models.concat(self.closedIssues.models);
                allIssues = _.sortBy(allIssues, function(issue) { return issue.getCreatedTime(); });

                var openCount = 0;

                var created = _.map(allIssues, function(issue) {
                    var createdTime = issue.getCreatedTime();
                    return {
                        x: createdTime >= startDate ? createdTime : startDate,
                        y: ++openCount
                    };
                });

                console.log('issue: ', allIssues[0]);

                // Build graph!
                var graph = new Rickshaw.Graph({
                    element: document.querySelector("#chart"),
                    width: 900,
                    height: 500,
                    renderer: 'line',
                    interpolation: 'basis',
                    series: [{
                        data:  ideal,
                        color: '#75ABC5',
                        name:  'Ideal'
                    }, {
                        data:  actual,
                        color: '#F89406',
                        name:  'Actual'
                    }, {
                        data:  created,
                        color: '#30c020',
                        name:  'Created'
                    }]
                });
                graph.render();

                var legend = new Rickshaw.Graph.Legend( {
                    graph: graph,
                    element: document.getElementById('legend')

                } );

                var highlighter = new Rickshaw.Graph.Behavior.Series.Highlight( {
                    graph: graph,
                    legend: legend
                } );

                var time = new Rickshaw.Fixtures.Time();
                var days = time.unit('day');

                var xAxis = new Rickshaw.Graph.Axis.Time({
                    graph: graph
                    //timeUnit: days
                });

                xAxis.render();

                var yAxis = new Rickshaw.Graph.Axis.Y({
                    graph:          graph,
                    tickFormat:     Rickshaw.Fixtures.Number.formatKMBT,
                    ticksTreatment: 'glow',
                    orientation:    'left',
                    element:        document.getElementById('y_axis')
                });

                yAxis.render();
            }
        },
        loadMilestone: function(id) {
            var self = this;

            // Render the loading template.
            self.render("#tmpl_loading", {});

            self.milestone = milestones.getByNumber(id);
            console.log('milestone: ', self.milestone);

            self.openIssues.milestoneId = self.milestone.get('number');
            self.closedIssues.milestoneId = self.milestone.get('number');

            // Clear any previous messages.
            self.message.clear();

            // Set a message if the milestone has no due date.
            if (self.milestone.get('due_on') === null) {
                self.message.setProblem('Milestone has no due date!');
            }

            // Render the milestone template.
            self.render('#tmpl_milestone', {milestone: self.milestone,
                                            session: session,
                                            message: self.message});

            self.openIssues.fetch({
                success: function(issues) {
                    data = {
                        issues: issues.models
                    };
                    var template = _.template($('#tmpl_issues').html(), data);
                    $('.open', self.el).html(template);
                }
            });
            self.closedIssues.fetch({
                success: function(issues) {
                    data = {
                        issues: issues.models
                    };
                    var template = _.template($('#tmpl_issues').html(), data);
                    $('.closed', self.el).html(template);
                }
            });
        }
    });

    var SummaryView = Backbone.View.extend({
        el: '.content',
        initialize: function() {
            _.bindAll(this, 'render');
            var self = this;
        },
        render: function() {
            var template = _.template($('#tmpl_summary').html(),
                                      {session: session});
            this.$el.html( template );
            return this;
        }
    });

    // Router
    var Router = Backbone.Router.extend({
        routes: {
            '': 'home',
            ':owner/:repo': 'repository',
            ':owner/:repo/summary': 'summary',
            ':owner/:repo/:id': 'milestone'
        }
    });

    // Instantiations.
    var repoView = new RepoView();
    var milestoneView = new MilestoneView();
    var summaryView = new SummaryView();
    var router = new Router();

    router.on('route:home', function() {
        console.log('Load the home page!');
        repoView.render();
    });

    router.on('route:milestone', function(owner, repo, id) {
        console.log('Load the milestone page!');
        // load token
        // load owner/repo
        // load milestones
        // renders repoView
        // safe: load milestoneView!
        repoView.loadRepoMilestones(owner, repo);
        milestones.once('sync', function() {
            milestoneView.loadMilestone(id);
        });
    });

    router.on('route:repository', function(owner, repo) {
        console.log('Load the repository page!');
        repoView.loadRepoMilestones(owner, repo);
    });

    router.on('route:summary', function(owner, repo) {
        console.log('Load the repository summary page!');
        summaryView.render();
    });

    // Once the session token finishes loading, start the application!
    session.once('change:token', function(model, value) {
        console.log('token: ', value);

        // Let's get this party started!
        Backbone.history.start();
    });
});
<|endoftext|>


<commit_before>var util = require('util')
  , net = require('net')
  , http = require('http');

var protocol = 'http:';

function HttpMiddleware(proxy, options) {
  this.options = options;
  this.proxy = proxy;
  this.defaults = {
   port: 80
  };
}

function createHttp(proxy, options) {
  proxy.registerProtocol(protocol, new HttpMiddleware(proxy, options));
}

module.exports.HttpMiddleware = HttpMiddleware;
module.exports.createHttp = createHttp;

HttpMiddleware.prototype.getUrl = function (request) {
  return protocol + request.headers.host;
};

HttpMiddleware.prototype.createServer = function (serverOptions) {
  var self = this;
  var server = http.createServer()
    .on('connect', function (request, socket, bodyHead) {
      self.doConnect(request, socket, bodyHead);
    })
    .on('request', function (request, response) {
      request.protocol = protocol;
      self.proxy.proxyRequest(request, response);
    })
    .listen(serverOptions.port);
  server.serverOptions = serverOptions;
  server.getUrl = this.getUrl;

  return server;
};

HttpMiddleware.prototype.doConnect = function (request, socket, bodyHead) {
  if (this.options['mode'] === 'forward') {
    this.connectForward(request, socket, bodyHead);
  } else {
    this.connectReverse(request, socket, bodyHead);
  }
};

HttpMiddleware.prototype.createAgent = function (backendOptions, socket) {
  socket.agent = new http.Agent;
  return socket.agent;
};

HttpMiddleware.prototype.request = function (options, callback) {
  options = util._extend(options, this.defaults);
  return http.request(options, callback);
};

HttpMiddleware.prototype.synReply = function (request, socket, statusCode, headers, cb) {
  var response = new http.ServerResponse(request);
  response.useChunkedEncodingByDefault = false;

  response.on('finish', function () {
    this.detachSocket(socket);
    if (cb) { cb.call(); }
  });

  response.assignSocket(socket);
  response.writeHead(statusCode, headers);
  response.end();
};

HttpMiddleware.prototype.connectForward = function (request, socket, bodyHead) {
  var self = this;
  var requestOptions = {
    host: request.url.split(':')[0],
    port: request.url.split(':')[1] || 443
  };

  var tunnel = net.createConnection(requestOptions, function() {
    tunnel.pipe(socket);
    socket.pipe(tunnel);
    self.synReply(request, socket, 200, {
        'Connection': 'keep-alive'
    });
  });

  tunnel.setNoDelay(true);

  tunnel.on('error', function(e) {
    console.log("Tunnel error: " + e);
    self.synReply(request, socket, 502, {}, function() {
      socket.end();
    });
  });
};

HttpMiddleware.prototype.connectReverse = function (request, socket, bodyHead) {
  // TODO: Implement connect reverse forwarding
  socket.destroy();
};<commit_msg>Add logging for HTTP connect's<commit_after>var util = require('util')
  , net = require('net')
  , http = require('http');

var protocol = 'http:';

function HttpMiddleware(proxy, options) {
  this.options = options;
  this.proxy = proxy;
  this.defaults = {
   port: 80
  };
}

function createHttp(proxy, options) {
  proxy.registerProtocol(protocol, new HttpMiddleware(proxy, options));
}

module.exports.HttpMiddleware = HttpMiddleware;
module.exports.createHttp = createHttp;

HttpMiddleware.prototype.getUrl = function (request) {
  return protocol + request.headers.host;
};

HttpMiddleware.prototype.createServer = function (serverOptions) {
  var self = this;
  var server = http.createServer()
    .on('connect', function (request, socket, bodyHead) {
      self.doConnect(request, socket, bodyHead);
    })
    .on('request', function (request, response) {
      request.protocol = protocol;
      self.proxy.proxyRequest(request, response);
    })
    .listen(serverOptions.port);
  server.serverOptions = serverOptions;
  server.getUrl = this.getUrl;

  return server;
};

HttpMiddleware.prototype.doConnect = function (request, socket, bodyHead) {
  if (this.options['mode'] === 'forward') {
    this.connectForward(request, socket, bodyHead);
  } else {
    this.connectReverse(request, socket, bodyHead);
  }
};

HttpMiddleware.prototype.createAgent = function (backendOptions, socket) {
  socket.agent = new http.Agent;
  return socket.agent;
};

HttpMiddleware.prototype.request = function (options, callback) {
  options = util._extend(options, this.defaults);
  return http.request(options, callback);
};

HttpMiddleware.prototype.synReply = function (request, socket, statusCode, headers, cb) {
  var response = new http.ServerResponse(request);
  response.useChunkedEncodingByDefault = false;

  response.on('finish', function () {
    this.detachSocket(socket);
    if (cb) { cb.call(); }
  });

  response.assignSocket(socket);
  response.writeHead(statusCode, headers);
  response.end();
};

HttpMiddleware.prototype.connectForward = function (request, socket, bodyHead) {
  var self = this;
  var requestOptions = {
    host: request.url.split(':')[0],
    port: request.url.split(':')[1] || 443
  };

  if (this.options.verbose) {
      console.log('connect: %s:%s', requestOptions.host, requestOptions.port);
  }

  var tunnel = net.createConnection(requestOptions, function() {
    tunnel.pipe(socket);
    socket.pipe(tunnel);
    self.synReply(request, socket, 200, {
        'Connection': 'keep-alive'
    });
  });

  tunnel.setNoDelay(true);

  tunnel.on('error', function(e) {
    console.log("Tunnel error: " + e);
    self.synReply(request, socket, 502, {}, function() {
      socket.end();
    });
  });
};

HttpMiddleware.prototype.connectReverse = function (request, socket, bodyHead) {
  // TODO: Implement connect reverse forwarding
  socket.destroy();
};<|endoftext|>


<commit_before><commit_msg>modified facilites data<commit_after><|endoftext|>


<commit_before>$(document).ready(function() {

  function carouselMagic(id, frames) {
  var owl = $(id);
  var items = frames
  owl.owlCarousel({
      items : items, //10 items above 1000px browser width
      itemsDesktop : [1000,3], //5 items between 1000px and 901px
      itemsDesktopSmall : [900,2], // betweem 900px and 601px
      itemsTablet: [600,1], //2 items between 600 and 0
      itemsMobile : false // itemsMobile disabled - inherit from itemsTablet option
  });

  owl.trigger('owl.play',2500)
  // Custom Navigation Events
  $(".next").click(function(){
    owl.trigger('owl.next');
  })
  $(".prev").click(function(){
    owl.trigger('owl.prev');
  })
  $(".play").click(function(){
    owl.trigger('owl.play',2200); //owl.play event accept autoPlay speed as second parameter
  })
  $(".stop").click(function(){
    owl.trigger('owl.stop');
  })

}

carouselMagic("#trending_carousel", 3)

});
<commit_msg>added js for next two carousel features<commit_after>$(document).ready(function() {

  function carouselMagic(id, frames) {
  var owl = $(id);
  var items = frames
  owl.owlCarousel({
      items : items, //10 items above 1000px browser width
      itemsDesktop : [1000,3], //5 items between 1000px and 901px
      itemsDesktopSmall : [900,2], // betweem 900px and 601px
      itemsTablet: [600,1], //2 items between 600 and 0
      itemsMobile : false // itemsMobile disabled - inherit from itemsTablet option
  });

  owl.trigger('owl.play',2500)
  // Custom Navigation Events
  $(".next").click(function(){
    owl.trigger('owl.next');
  })
  $(".prev").click(function(){
    owl.trigger('owl.prev');
  })
  $(".play").click(function(){
    owl.trigger('owl.play',2200); //owl.play event accept autoPlay speed as second parameter
  })
  $(".stop").click(function(){
    owl.trigger('owl.stop');
  })

}

carouselMagic("#trending_carousel", 3)
carouselMagic("#my_rooms_carousel", 3)
carouselMagic("#joined_rooms_carousel", 3)

});
<|endoftext|>