<commit_before>/**
 * @class Oskari.mapframework.bundle.mapfull.MapFullBundleInstance
 *
 * Initializes Oskari core and starts a map window application. Much of the map related properties
 * and initial state are read from bundle configuration/state.
 *
 * See bundle documentation at http://www.oskari.org/trac/wiki/DocumentationBundleMapfull
 */
Oskari.clazz.define("Oskari.mapframework.bundle.mapfull.MapFullBundleInstance",
/**
 * @method create called automatically on construction
 * @static
 */
function() {
	this.map = null;
	this.core = null;
	this.sandbox = null;
	this.mapmodule = null;
	this.state = undefined;
    /**
     * @property {String} mapDivId
     * ID of the DOM element the map will be rendered to
     * Configurable through conf.mapElement
     */
	this.mapDivId = "mapdiv";
}, {

	/**
	 * @method getMapModule
	 * Returns reference to the map module
	 * @return {Oskari.mapframework.ui.module.common.MapModule}
	 */
	getMapModule : function() {
		return this.mapmodule;
	},
    /**
     * @method getSandbox
     * Returns reference to Oskari sandbox
     * @return {Oskari.mapframework.sandbox.Sandbox}
     */
	getSandbox : function() {
		return this.sandbox;
	},

	/**
	 * @method _createUi
	 * Creates the map module and rendes it to DOM element that has the id
	 * specified by #mapDivId. Sets the size of the element if specified in
	 * config or if isn't specified, sets the height of the element to window height
	 * and starts listening to window resizing.
	 * Initializes and registers map module plugins if specified in bundles config.
	 * @private
	 */
	_createUi : function() {
        var me = this;
        // set map size
        // call portlet with ?p_p_id=Portti2Map_WAR_portti2mapportlet&p_p_lifecycle=0&p_p_state=exclusive&p_p_mode=view&published=true
        // -> uses published.jsp
        if(this.conf.size) {
            jQuery('#' + this.mapDivId).width(this.conf.size.width);
            jQuery('#' + this.mapDivId).height(this.conf.size.height);
        }
        else {
            // react to window resize with timer so app stays responsive
            function adjustMapSize() {
                // do not resize map if resizeEnabled is false
                if(me.resizeEnabled == null || me.resizeEnabled) {
                    jQuery('#' + me.mapDivId).height(jQuery(window).height());
                    jQuery('#contentMap').height(jQuery(window).height());
                }
            };

            var resizeTimer;
            jQuery(window).resize(function() {
                clearTimeout(resizeTimer);
                resizeTimer = setTimeout(adjustMapSize, 100);
            });
            adjustMapSize();
        }

		var module = Oskari.clazz.create('Oskari.mapframework.ui.module.common.MapModule', "Main", this.conf.imageLocation, this.conf.mapOptions);

		this.mapmodule = module;
		var map = this.sandbox.register(module);

        module.start(this.sandbox);

		map.render(this.mapDivId);
        // startup plugins
        if(this.conf.plugins) {
            var plugins = this.conf.plugins;
            for(var i = 0; i < plugins.length; i++) {
                plugins[i].instance = Oskari.clazz.create(plugins[i].id, plugins[i].config);
                module.registerPlugin(plugins[i].instance);
                module.startPlugin(plugins[i].instance);
            }
        }

		this.map = map;
	},
    /**
     * @method start
     * Implements BundleInstance protocol start method.
     * Initializes Oskari core and Oskari.mapframework.service.MapLayerService.
     * Creates the map view and moves it to location and zoom
     * level specified by #state.
     *
     * Also defines Proj4js.defs for "EPSG:3067" and "EPSG:4326".
     */
	"start" : function() {

        Proj4js.defs = {
          "EPSG:3067" : "+proj=utm +zone=35 +ellps=GRS80 +units=m +no_defs",
          "EPSG:4326" : "+title=WGS 84 +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"
        };
		var me = this;
		var conf = me.conf;

		var userInterfaceLanguage = Oskari.getLang();

		var core = Oskari.clazz.create('Oskari.mapframework.core.Core');
		this.core = core;
		var sandbox = core.getSandbox();
		this.sandbox = sandbox;

		// take map div ID from config if available
		if(conf && conf.mapElement) {
		    this.mapDivId = conf.mapElement;
		}

        // Init user
        sandbox.setUser(conf.user);
        sandbox.setAjaxUrl(conf.globalMapAjaxUrl);

		// create services
		var services = this._createServices(conf);

		// create enhancements
		var enhancements = [];
		enhancements.push(Oskari.clazz.create('Oskari.mapframework.enhancement.mapfull.StartMapWithLinkEnhancement'));

		core.init(services, enhancements);
		// setup initial maplayers
    	var mapLayerService = sandbox.getService('Oskari.mapframework.service.MapLayerService');
	    var initialLayers = conf.layers;
	    if(initialLayers) {
	        for(var i = 0; i < initialLayers.length; i++) {
				var mapLayer = mapLayerService.createMapLayer(initialLayers[i]);
	            mapLayerService.addLayer(mapLayer, true);
			}
	    }

        this._createUi();

		sandbox.registerAsStateful(this.mediator.bundleId, this);

		var skipLocation = false;
		if(this.mapmodule.isPluginActivated('GeoLocationPlugin')) {
		    // get plugin
		    var plugin = this.mapmodule.getPluginInstance('GeoLocationPlugin');
		    skipLocation = plugin.hasSetLocation();
		}

        this.setState(this.state, skipLocation);

        // create request handlers
        me.mapResizeEnabledRequestHandler = Oskari.clazz.create('Oskari.mapframework.bundle.mapfull.request.MapResizeEnabledRequestHandler', me);

        // register request handlers
        sandbox.addRequestHandler('MapFull.MapResizeEnabledRequest', me.mapResizeEnabledRequestHandler);

	},
    /**
     * @method _teardownState
     * Tears down previous state so we can set a new one.
     * @private
     * @param {Oskari.mapframework.module.Module} module
     *      any registered module so we can just send out requests
     */
    _teardownState : function(module) {
        var selectedLayers = this.sandbox.findAllSelectedMapLayers();
        // remove all current layers
        var rbRemove = this.sandbox.getRequestBuilder('RemoveMapLayerRequest');
        for(var i = 0; i < selectedLayers.length; i++) {
            this.sandbox.request(module.getName(), rbRemove(selectedLayers[i].getId()));
        }
    },

	/**
	 * @method _createServices
	 * Setup services for this application.
	 * Mainly Oskari.mapframework.service.MapLayerService, but also hacks in WMTS support
	 * and if conf.disableDevelopmentMode == 'true' -> disables debug messaging and
	 * initializes Oskari.mapframework.service.UsageSnifferService to provide
	 * feedback to server about map usage.

	 * @param {Object} conf
	 * 		JSON configuration for the application
	 * @private
	 */
	_createServices : function(conf) {
		var me = this;
		/* create services that are available in this application */
		var services = [];

		var mapLayerService = Oskari.clazz.create('Oskari.mapframework.service.MapLayerService',
                conf.globalMapAjaxUrl + 'action_route=GetMapLayers&lang='+Oskari.getLang() , this.core.getSandbox());
        services.push(mapLayerService);

       // TODO: maybe we should set the map state in another bundle so we can setup core/map in mapfull
       // and add wmts/wfs layer support to map with their own bundles -> then set the initial map state (from a new bundle)
       // Setting up WMTS support
       // We'll register a handler for our type
        mapLayerService.registerLayerModel('wmtslayer','Oskari.mapframework.wmts.domain.WmtsLayer');

        var layerModelBuilder =
        	Oskari.clazz.create('Oskari.mapframework.wmts.service.WmtsLayerModelBuilder');

        mapLayerService.registerLayerModelBuilder('wmtslayer',layerModelBuilder);

		// DisableDevelopmentModeEnhancement
		if (conf.disableDevelopmentMode == 'true') {
	        core.disableDebug();
            // create sniffer with 2 second interval and '/log' -url
			services.push(Oskari.clazz.create('Oskari.mapframework.service.UsageSnifferService',2, "/log/"));
			core.enableMapMovementLogging();
	    }
		return services;
	},

    /**
     * @method update
     * implements BundleInstance protocol update method - does nothing atm
     */
	"update" : function() {

	},
    /**
     * @method stop
     * implements BundleInstance protocol stop method
     */
	"stop" : function() {
	    this.sandbox.unregisterStateful(this.mediator.bundleId);
		alert('Stopped!');
	},

    /**
     * @method setState
     * Sets the map state to one specified in the parameter. State is bundle specific, check the
     * bundle documentation for details.
     * @param {Object} state bundle state as JSON
     * @param {Boolean} ignoreLocation true to NOT set map location based on state
     */
    setState : function(state, ignoreLocation) {
        var mapmodule = this.sandbox.findRegisteredModuleInstance('MainMapModule');
        this._teardownState(mapmodule);

        // setting state
        if(state.selectedLayers) {
            var rbAdd = this.sandbox.getRequestBuilder('AddMapLayerRequest');
            var rbOpacity = this.sandbox.getRequestBuilder('ChangeMapLayerOpacityRequest');
            var visibilityRequestBuilder = this.sandbox.getRequestBuilder('MapModulePlugin.MapLayerVisibilityRequest');
            var styleReqBuilder = this.sandbox.getRequestBuilder('ChangeMapLayerStyleRequest');
            var len = state.selectedLayers.length;
            for(var i = 0; i < len; ++i ) {
                var layer = state.selectedLayers[i];
                this.sandbox.request(mapmodule.getName(), rbAdd(layer.id, true));
                this.sandbox.request(mapmodule.getName(), visibilityRequestBuilder(layer.id, layer.hidden !== true));
                if(layer.style) {
                    this.sandbox.request(mapmodule.getName(), styleReqBuilder(layer.id, layer.style));
                }
                if(layer.opacity) {
                    this.sandbox.request(mapmodule.getName(), rbOpacity(layer.id, layer.opacity));
                }
            }
        }

        if(state.east && ignoreLocation !== true) {
            this.sandbox.getMap().moveTo(
                state.east,
                state.north,
                state.zoom);
        }

        this.sandbox.syncMapState(true);
    },
	/**
	 * @method getState
	 * Returns bundle state as JSON. State is bundle specific, check the
     * bundle documentation for details.
	 * @return {Object}
	 */
	getState : function() {
        // get applications current state
        var map = this.sandbox.getMap();
        var selectedLayers = this.sandbox.findAllSelectedMapLayers();
        var zoom = map.getZoom();
        var lat = map.getX();
        var lon = map.getY();

        var state = {
            north : lon,
            east : lat,
            zoom : map.getZoom(),
            selectedLayers : []
        };

        for(var i = 0; i < selectedLayers.length; i++) {
            var layer = selectedLayers[i];
            var layerJson = {
                id : layer.getId(),
                opacity : layer.getOpacity()
            };
            if(!layer.isVisible()) {
                layerJson.hidden = true;
            }
            // check if we have a style selected and doesn't have THE magic string
            if(layer.getCurrentStyle &&
                layer.getCurrentStyle() &&
                layer.getCurrentStyle().getName() &&
                layer.getCurrentStyle().getName() != "!default!") {
                layerJson.style = layer.getCurrentStyle().getName();
            }
            state.selectedLayers.push(layerJson);
        }

		return state;
	}
}, {
    /**
     * @property {String[]} protocol
     * @static
     */
	"protocol" : ["Oskari.bundle.BundleInstance", 'Oskari.userinterface.Stateful']
});
<commit_msg>[AL-867] mapfull now calls openlayers updateSize() when rendered div<commit_after>/**
 * @class Oskari.mapframework.bundle.mapfull.MapFullBundleInstance
 *
 * Initializes Oskari core and starts a map window application. Much of the map related properties
 * and initial state are read from bundle configuration/state.
 *
 * See bundle documentation at http://www.oskari.org/trac/wiki/DocumentationBundleMapfull
 */
Oskari.clazz.define("Oskari.mapframework.bundle.mapfull.MapFullBundleInstance",
/**
 * @method create called automatically on construction
 * @static
 */
function() {
	this.map = null;
	this.core = null;
	this.sandbox = null;
	this.mapmodule = null;
	this.state = undefined;
    /**
     * @property {String} mapDivId
     * ID of the DOM element the map will be rendered to
     * Configurable through conf.mapElement
     */
	this.mapDivId = "mapdiv";
}, {

	/**
	 * @method getMapModule
	 * Returns reference to the map module
	 * @return {Oskari.mapframework.ui.module.common.MapModule}
	 */
	getMapModule : function() {
		return this.mapmodule;
	},
    /**
     * @method getSandbox
     * Returns reference to Oskari sandbox
     * @return {Oskari.mapframework.sandbox.Sandbox}
     */
	getSandbox : function() {
		return this.sandbox;
	},

	/**
	 * @method _createUi
	 * Creates the map module and rendes it to DOM element that has the id
	 * specified by #mapDivId. Sets the size of the element if specified in
	 * config or if isn't specified, sets the height of the element to window height
	 * and starts listening to window resizing.
	 * Initializes and registers map module plugins if specified in bundles config.
	 * @private
	 */
	_createUi : function() {
        var me = this;

        var module = Oskari.clazz.create('Oskari.mapframework.ui.module.common.MapModule', "Main", this.conf.imageLocation, this.conf.mapOptions);

        this.mapmodule = module;
        var map = this.sandbox.register(module);
        // set map size
        // call portlet with ?p_p_id=Portti2Map_WAR_portti2mapportlet&p_p_lifecycle=0&p_p_state=exclusive&p_p_mode=view&published=true
        // -> uses published.jsp
        if(this.conf.size) {
            jQuery('#' + this.mapDivId).width(this.conf.size.width);
            jQuery('#' + this.mapDivId).height(this.conf.size.height);
        }
        else {
            // react to window resize with timer so app stays responsive
            function adjustMapSize() {
                // do not resize map if resizeEnabled is false
                if(me.resizeEnabled == null || me.resizeEnabled) {
                    jQuery('#' + me.mapDivId).height(jQuery(window).height());
                    jQuery('#contentMap').height(jQuery(window).height());
                    map.updateSize();
                }
            };

            var resizeTimer;
            jQuery(window).resize(function() {
                clearTimeout(resizeTimer);
                resizeTimer = setTimeout(adjustMapSize, 100);
            });
            adjustMapSize();
        }

        module.start(this.sandbox);

		map.render(this.mapDivId);
        // startup plugins
        if(this.conf.plugins) {
            var plugins = this.conf.plugins;
            for(var i = 0; i < plugins.length; i++) {
                plugins[i].instance = Oskari.clazz.create(plugins[i].id, plugins[i].config);
                module.registerPlugin(plugins[i].instance);
                module.startPlugin(plugins[i].instance);
            }
        }

		this.map = map;
	},
    /**
     * @method start
     * Implements BundleInstance protocol start method.
     * Initializes Oskari core and Oskari.mapframework.service.MapLayerService.
     * Creates the map view and moves it to location and zoom
     * level specified by #state.
     *
     * Also defines Proj4js.defs for "EPSG:3067" and "EPSG:4326".
     */
	"start" : function() {

        Proj4js.defs = {
          "EPSG:3067" : "+proj=utm +zone=35 +ellps=GRS80 +units=m +no_defs",
          "EPSG:4326" : "+title=WGS 84 +proj=longlat +ellps=WGS84 +datum=WGS84 +no_defs"
        };
		var me = this;
		var conf = me.conf;

		var userInterfaceLanguage = Oskari.getLang();

		var core = Oskari.clazz.create('Oskari.mapframework.core.Core');
		this.core = core;
		var sandbox = core.getSandbox();
		this.sandbox = sandbox;

		// take map div ID from config if available
		if(conf && conf.mapElement) {
		    this.mapDivId = conf.mapElement;
		}

        // Init user
        sandbox.setUser(conf.user);
        sandbox.setAjaxUrl(conf.globalMapAjaxUrl);

		// create services
		var services = this._createServices(conf);

		// create enhancements
		var enhancements = [];
		enhancements.push(Oskari.clazz.create('Oskari.mapframework.enhancement.mapfull.StartMapWithLinkEnhancement'));

		core.init(services, enhancements);
		// setup initial maplayers
    	var mapLayerService = sandbox.getService('Oskari.mapframework.service.MapLayerService');
	    var initialLayers = conf.layers;
	    if(initialLayers) {
	        for(var i = 0; i < initialLayers.length; i++) {
				var mapLayer = mapLayerService.createMapLayer(initialLayers[i]);
	            mapLayerService.addLayer(mapLayer, true);
			}
	    }

        this._createUi();

		sandbox.registerAsStateful(this.mediator.bundleId, this);

		var skipLocation = false;
		if(this.mapmodule.isPluginActivated('GeoLocationPlugin')) {
		    // get plugin
		    var plugin = this.mapmodule.getPluginInstance('GeoLocationPlugin');
		    skipLocation = plugin.hasSetLocation();
		}

        this.setState(this.state, skipLocation);

        // create request handlers
        me.mapResizeEnabledRequestHandler = Oskari.clazz.create('Oskari.mapframework.bundle.mapfull.request.MapResizeEnabledRequestHandler', me);

        // register request handlers
        sandbox.addRequestHandler('MapFull.MapResizeEnabledRequest', me.mapResizeEnabledRequestHandler);

	},
    /**
     * @method _teardownState
     * Tears down previous state so we can set a new one.
     * @private
     * @param {Oskari.mapframework.module.Module} module
     *      any registered module so we can just send out requests
     */
    _teardownState : function(module) {
        var selectedLayers = this.sandbox.findAllSelectedMapLayers();
        // remove all current layers
        var rbRemove = this.sandbox.getRequestBuilder('RemoveMapLayerRequest');
        for(var i = 0; i < selectedLayers.length; i++) {
            this.sandbox.request(module.getName(), rbRemove(selectedLayers[i].getId()));
        }
    },

	/**
	 * @method _createServices
	 * Setup services for this application.
	 * Mainly Oskari.mapframework.service.MapLayerService, but also hacks in WMTS support
	 * and if conf.disableDevelopmentMode == 'true' -> disables debug messaging and
	 * initializes Oskari.mapframework.service.UsageSnifferService to provide
	 * feedback to server about map usage.

	 * @param {Object} conf
	 * 		JSON configuration for the application
	 * @private
	 */
	_createServices : function(conf) {
		var me = this;
		/* create services that are available in this application */
		var services = [];

		var mapLayerService = Oskari.clazz.create('Oskari.mapframework.service.MapLayerService',
                conf.globalMapAjaxUrl + 'action_route=GetMapLayers&lang='+Oskari.getLang() , this.core.getSandbox());
        services.push(mapLayerService);

       // TODO: maybe we should set the map state in another bundle so we can setup core/map in mapfull
       // and add wmts/wfs layer support to map with their own bundles -> then set the initial map state (from a new bundle)
       // Setting up WMTS support
       // We'll register a handler for our type
        mapLayerService.registerLayerModel('wmtslayer','Oskari.mapframework.wmts.domain.WmtsLayer');

        var layerModelBuilder =
        	Oskari.clazz.create('Oskari.mapframework.wmts.service.WmtsLayerModelBuilder');

        mapLayerService.registerLayerModelBuilder('wmtslayer',layerModelBuilder);

		// DisableDevelopmentModeEnhancement
		if (conf.disableDevelopmentMode == 'true') {
	        core.disableDebug();
            // create sniffer with 2 second interval and '/log' -url
			services.push(Oskari.clazz.create('Oskari.mapframework.service.UsageSnifferService',2, "/log/"));
			core.enableMapMovementLogging();
	    }
		return services;
	},

    /**
     * @method update
     * implements BundleInstance protocol update method - does nothing atm
     */
	"update" : function() {

	},
    /**
     * @method stop
     * implements BundleInstance protocol stop method
     */
	"stop" : function() {
	    this.sandbox.unregisterStateful(this.mediator.bundleId);
		alert('Stopped!');
	},

    /**
     * @method setState
     * Sets the map state to one specified in the parameter. State is bundle specific, check the
     * bundle documentation for details.
     * @param {Object} state bundle state as JSON
     * @param {Boolean} ignoreLocation true to NOT set map location based on state
     */
    setState : function(state, ignoreLocation) {
        var mapmodule = this.sandbox.findRegisteredModuleInstance('MainMapModule');
        this._teardownState(mapmodule);

        // setting state
        if(state.selectedLayers) {
            var rbAdd = this.sandbox.getRequestBuilder('AddMapLayerRequest');
            var rbOpacity = this.sandbox.getRequestBuilder('ChangeMapLayerOpacityRequest');
            var visibilityRequestBuilder = this.sandbox.getRequestBuilder('MapModulePlugin.MapLayerVisibilityRequest');
            var styleReqBuilder = this.sandbox.getRequestBuilder('ChangeMapLayerStyleRequest');
            var len = state.selectedLayers.length;
            for(var i = 0; i < len; ++i ) {
                var layer = state.selectedLayers[i];
                this.sandbox.request(mapmodule.getName(), rbAdd(layer.id, true));
                this.sandbox.request(mapmodule.getName(), visibilityRequestBuilder(layer.id, layer.hidden !== true));
                if(layer.style) {
                    this.sandbox.request(mapmodule.getName(), styleReqBuilder(layer.id, layer.style));
                }
                if(layer.opacity) {
                    this.sandbox.request(mapmodule.getName(), rbOpacity(layer.id, layer.opacity));
                }
            }
        }

        if(state.east && ignoreLocation !== true) {
            this.sandbox.getMap().moveTo(
                state.east,
                state.north,
                state.zoom);
        }

        this.sandbox.syncMapState(true);
    },
	/**
	 * @method getState
	 * Returns bundle state as JSON. State is bundle specific, check the
     * bundle documentation for details.
	 * @return {Object}
	 */
	getState : function() {
        // get applications current state
        var map = this.sandbox.getMap();
        var selectedLayers = this.sandbox.findAllSelectedMapLayers();
        var zoom = map.getZoom();
        var lat = map.getX();
        var lon = map.getY();

        var state = {
            north : lon,
            east : lat,
            zoom : map.getZoom(),
            selectedLayers : []
        };

        for(var i = 0; i < selectedLayers.length; i++) {
            var layer = selectedLayers[i];
            var layerJson = {
                id : layer.getId(),
                opacity : layer.getOpacity()
            };
            if(!layer.isVisible()) {
                layerJson.hidden = true;
            }
            // check if we have a style selected and doesn't have THE magic string
            if(layer.getCurrentStyle &&
                layer.getCurrentStyle() &&
                layer.getCurrentStyle().getName() &&
                layer.getCurrentStyle().getName() != "!default!") {
                layerJson.style = layer.getCurrentStyle().getName();
            }
            state.selectedLayers.push(layerJson);
        }

		return state;
	}
}, {
    /**
     * @property {String[]} protocol
     * @static
     */
	"protocol" : ["Oskari.bundle.BundleInstance", 'Oskari.userinterface.Stateful']
});
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import PropTypes from 'prop-types';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import Typography from '@material-ui/core/Typography';

class Navi extends Component {
  render() {
    return (
      <AppBar position="absolute" style={this.props.style}>
        <Toolbar>
          <Typography variant="title" color="inherit">
            {this.props.title}
          </Typography>
        </Toolbar>
      </AppBar>
    );
  }
}

Navi.propTypes = {
  title: PropTypes.string.isRequired,
}

export default Navi;
<commit_msg>Add menu to navi to create hamburger menu<commit_after>import React, { useState } from "react";

import AppBar from "@material-ui/core/AppBar";
import Toolbar from "@material-ui/core/Toolbar";
import Typography from "@material-ui/core/Typography";

import ListSubheader from "@material-ui/core/ListSubheader";
import List from "@material-ui/core/List";
import ListItem from "@material-ui/core/ListItem";
import Drawer from "@material-ui/core/Drawer";

import IconButton from "@material-ui/core/IconButton";
import MenuIcon from "@material-ui/icons/Menu";

import { Link } from "react-router-dom";

const Navi = ({ title }) => {
  const [isOpen, setOpen] = useState(false);
  return (
    <>
      <AppBar position="sticky" style={{ backgroundColor: "white" }}>
        <Toolbar>
          <IconButton onClick={() => setOpen(!isOpen)}>
            <MenuIcon />
          </IconButton>
          <div
            style={{
              fontWeight: 900,
              fontSize: 20,
              marginLeft: 24,
              color: "black"
            }}
          >
            {title}
          </div>
        </Toolbar>
      </AppBar>
      <Drawer open={isOpen} onClose={() => setOpen(false)}>
        <List
          style={{
            width: 200,
            height: "100%",
            backgroundColor: "rgb(44,44,44)",
            color: "white"
          }}
        >
          <ListSubheader style={{ color: "white" }}>Menu</ListSubheader>
          <ListItem component={Link} to="/" button>
            Top
          </ListItem>
          <ListItem component={Link} to="/sample" button>
            Sample
          </ListItem>
        </List>
      </Drawer>
    </>
  );
};

export default Navi;
<|endoftext|>


<commit_before>var color = require('cli-color')
var execSync = require('execSync').exec
var fs = require('fs')
var path = require('path')
var sleep = require('sleep').sleep

/**
 * So most of this stuff will be sync, because we are moving
 * files around building docker images, etc. These all have
 * to be done in a specific order or chaos ensues
 */
var cwd = path.join(process.cwd(),"tests")
process.stdout.write("Fetching Distributions... ")
var distros = fs.readdirSync(cwd)
var failed = []
process.stdout.write("["+color.green("OK!")+"]\n")
distros.forEach(function(v1) {
  if(!fs.statSync(path.join(cwd,v1)).isDirectory()) return;
  process.stdout.write("Fetcing versions of "+capitalize(v1)+"... ")
  var versions = fs.readdirSync(path.join(cwd,v1))
  process.stdout.write("["+color.green("OK!")+"]\n")
  versions.forEach(function(v2) {
    if(!fs.statSync(path.join(cwd,v1,v2)).isDirectory()) return;
    //If Dockerfile already exists, delete it.
    if(fs.existsSync(path.join(process.cwd(),"Dockerfile")))
      fs.unlinkSync(path.join(process.cwd(),"Dockerfile"))
    //Move the dockerfile to the base of our repo
    fs.linkSync(path.join(cwd,v1,v2,"Dockerfile"),path.join(process.cwd(),"Dockerfile"))
    //Build the docker image using the dockerfile
    process.stdout.write("Building version "+v2+" of "+capitalize(v1)+"... ")
    var cmd = "docker build -t \"getos:"+v1+v2+"\" ."
    var dockerResult = execSync("docker build -t \"getos:"+v1+v2+"\" .")
    if(dockerResult.code!==0) {
      failed.push(dockerResult)
      process.stdout.write("["+color.red("FAILED!")+"]\n")
    } else {
      process.stdout.write("["+color.green("OK!")+"]\n")
      process.stdout.write("Running container... ")
      //Show output from distribution
      var nodeResult = execSync("docker run -d getos:"+v1+v2)
      if(nodeResult.code!==0) {
        failed.push(nodeResult)
        process.stdout.write("["+color.red("FAILED!")+"]\n")
      } else {
        sleep(2)
        var dockerLog = execSync("docker logs "+nodeResult.stdout)
        if(dockerLog.code!==0) {
          failed.push(dockerLog)
          process.stdout.write("["+color.red("FAILED!")+"]\n")
        } else {
          process.stdout.write("["+color.green("OK!")+"]\n")
          process.stdout.write("Output from version "+v2+" of "+capitalize(v1)+": \n")
          process.stdout.write(dockerLog.stdout)
        }
      }
    }
    //Delete the dockerfile
    fs.unlinkSync(path.join(process.cwd(),"Dockerfile"))
  })
})

if(failed.length>0) {
  fs.writeFileSync("tests.log",JSON.stringify(failed,null," "))
}

function capitalize(str) {
  return str.charAt(0).toUpperCase()+str.slice(1)
}
<commit_msg>Only use execSync if Node doesn't support execSync natively<commit_after>var color = require('cli-color')
var execSync = require('child_process').execSync || require('execSync').exec
var fs = require('fs')
var path = require('path')
var sleep = require('sleep').sleep

/**
 * So most of this stuff will be sync, because we are moving
 * files around building docker images, etc. These all have
 * to be done in a specific order or chaos ensues
 */
var cwd = path.join(process.cwd(),"tests")
process.stdout.write("Fetching Distributions... ")
var distros = fs.readdirSync(cwd)
var failed = []
process.stdout.write("["+color.green("OK!")+"]\n")
distros.forEach(function(v1) {
  if(!fs.statSync(path.join(cwd,v1)).isDirectory()) return;
  process.stdout.write("Fetcing versions of "+capitalize(v1)+"... ")
  var versions = fs.readdirSync(path.join(cwd,v1))
  process.stdout.write("["+color.green("OK!")+"]\n")
  versions.forEach(function(v2) {
    if(!fs.statSync(path.join(cwd,v1,v2)).isDirectory()) return;
    //If Dockerfile already exists, delete it.
    if(fs.existsSync(path.join(process.cwd(),"Dockerfile")))
      fs.unlinkSync(path.join(process.cwd(),"Dockerfile"))
    //Move the dockerfile to the base of our repo
    fs.linkSync(path.join(cwd,v1,v2,"Dockerfile"),path.join(process.cwd(),"Dockerfile"))
    //Build the docker image using the dockerfile
    process.stdout.write("Building version "+v2+" of "+capitalize(v1)+"... ")
    var cmd = "docker build -t \"getos:"+v1+v2+"\" ."
    var dockerResult = execSync("docker build -t \"getos:"+v1+v2+"\" .")
    if(dockerResult.code!==0) {
      failed.push(dockerResult)
      process.stdout.write("["+color.red("FAILED!")+"]\n")
    } else {
      process.stdout.write("["+color.green("OK!")+"]\n")
      process.stdout.write("Running container... ")
      //Show output from distribution
      var nodeResult = execSync("docker run -d getos:"+v1+v2)
      if(nodeResult.code!==0) {
        failed.push(nodeResult)
        process.stdout.write("["+color.red("FAILED!")+"]\n")
      } else {
        sleep(2)
        var dockerLog = execSync("docker logs "+nodeResult.stdout)
        if(dockerLog.code!==0) {
          failed.push(dockerLog)
          process.stdout.write("["+color.red("FAILED!")+"]\n")
        } else {
          process.stdout.write("["+color.green("OK!")+"]\n")
          process.stdout.write("Output from version "+v2+" of "+capitalize(v1)+": \n")
          process.stdout.write(dockerLog.stdout)
        }
      }
    }
    //Delete the dockerfile
    fs.unlinkSync(path.join(process.cwd(),"Dockerfile"))
  })
})

if(failed.length>0) {
  fs.writeFileSync("tests.log",JSON.stringify(failed,null," "))
}

function capitalize(str) {
  return str.charAt(0).toUpperCase()+str.slice(1)
}
<|endoftext|>


<commit_before>module.exports = {
	output: 'dist/*',
	sass: [
		'app/sass/**/*'
	],
	html: [
		'app/html/**/*'
	],
	assets: [
		'app/assets/**/*'
	],
	scripts: [
		'app/js/app.js',
		'app/js/services/*.js',
		'app/js/filters/*.js',
		'app/js/directives/*.js',
		'app/js/controllers/*.js'
	],
	scriptsSkip: [
		'!app/js/**/*.test.js',
		'!app/js/**/*.mock.js'
	],
	libs: [
		'app/vendor/angular/angular.js',
		'app/vendor/angular-sanitize/angular-sanitize.js',
		'app/vendor/angular-ui-router/release/angular-ui-router.js'
	]
};
<commit_msg>specify endings for faster build and more precise build<commit_after>module.exports = {
	output: 'dist/*',
	sass: [
		'app/sass/**/*.scss'
	],
	html: [
		'app/html/**/*.html'
	],
	assets: [
		'app/assets/**/*'
	],
	scripts: [
		'app/js/app.js',
		'app/js/services/*.js',
		'app/js/filters/*.js',
		'app/js/directives/*.js',
		'app/js/controllers/*.js'
	],
	scriptsSkip: [
		'!app/js/**/*.test.js',
		'!app/js/**/*.mock.js'
	],
	libs: [
		'app/vendor/angular/angular.js',
		'app/vendor/angular-sanitize/angular-sanitize.js',
		'app/vendor/angular-ui-router/release/angular-ui-router.js'
	]
};
<|endoftext|>


<commit_before>const Iterator = require('../Iterator.js')

var rectify  = x=>x>0?x:0
var softplus = x=>Math.log(1+Math.exp(x))

var a = [5,-1,-45,2,34]

console.log(Iterator(a).map(rectify).toArray())
console.log(Iterator(a).map(softplus).toArray())
console.log(Iterator.random().take(1000).groupBy(i=>i>0.5, 'count'))

var factorials = ()=>Iter.range().skip(1).cumulate((a,b)=>a*b)
<commit_msg>More function examples<commit_after>const Iterator = require('../Iterator.js')

var rectify  = x=>x>0?x:0
var softplus = x=>Math.log(1+Math.exp(x))

var a = [5,-1,-45,2,34]

console.log(Iterator(a).map(rectify).toArray())
console.log(Iterator(a).map(softplus).toArray())
console.log(Iterator.random().take(1000).groupBy(i=>i>0.5, 'count'))

//Some functions that can be easily expressed with Iterators:
const factorials = ()=>Iter.range().skip(1).cumulate((a,b)=>a*b)

const factorial = n=>Iter.range(2,n+1).product()

const binomial = (n,k)=>Iter.range(1,k+1).map(i=>(n+1-i)/i).product()

const binomials = n=>Iter.range(0,n+1).map(i=>binomial(n,i)).toArray()

const binomialsPyramid = n=>Iter.range(0,n).map(binomials).toArray()<|endoftext|>


<commit_before>/*
	Copyright (c) 2010-2012 Filip Moberg, (filip@mcsquare.se)

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.

	Author:		Filip Moberg
	Name:		inception.js
	Version:	1.2
	Codename:	Di Caprio
	Released:	2012-01-03
	Comments:	This version was so awesome, it deserved TWO new version numbers. Totally rebuilt from scratch - inception revisited.
*/

// Sandbox the environment
/** @param {...undefined} undefined */
(function(window, undefined) {

	// Declare environment variables
	var document = window.document, navigator = window.navigator, location = window.location;

	// Create function in window object
	/** @constructor */
	window.inception = (function inception(oo) {

		var env = this;
		var self = this;
		var core = env.__core__;

		// Make sure core function is instantiated
		if (this === window) {
			return new inception(arguments[0]);
		}

		// Declare core object (with core functions)
		this.__core__ = {

			settings: {
				jQuery: {
					ready: "document"
				},
				error: {
					show: true
				}
			},

			onload: [],

			instance: arguments[0],

			// Extend a primary object with a secondary
			extend: function(o) {

				// If set to true, the returned object will be a copy instead of reference
				if (o.clone === true) {
					o.from = this.clone(o.from);
				}

				for (var n in o.from) {
					if (o.construct === true && typeof o.from[n] === "function" && n !== "wrapper") {

						// Make a clone so the use of multiple selectors won't construct the same function twice
						o.from = this.clone(o.from);
						var core = env.__core__, node = [core.instance].concat(o.node.replace(/@/g, "").split(".")), wrapper = node[0], cache;
						o.wrapper = [];

						cache = core.wrapper.cache[core.instance];

						if (typeof cache === "function") {
							o.wrapper.push(cache);
						}

						for (var i=1; i < node.length; ++i) {
							wrapper = wrapper + "__" + node[i];
							cache = core.wrapper.cache[wrapper];
							if (typeof cache === "function") {
								o.wrapper.push(cache);
							}
						}

						for (var i=o.wrapper.length; i >= 0; --i) {

							// Construct the function
							o.from[n] = this.functionConstructor({method: o.from[n], func: n, node: o.node, loop: o.loop, wrapper: o.wrapper[i]});
						}
					}

					if (typeof o.from[n] === "object" && n !== "selector" && n !== "$") {

						if (typeof o.to[n] === "undefined") {
							if (o.from[n] === null) {
								o.to[n] = null;
							} else if (o.from[n].constructor.toString().indexOf("Array") !== -1) {
								o.to[n] = [];
							} else {
								o.to[n] = {};
							}
						}

						this.extend({to: o.to[n], from: o.from[n], construct: o.construct, node: o.node, loop: o.loop});
					} else {
						o.to[n] = o.from[n];
					}
				}

				return o.to;
			},

			// Create deep copy of target object
			clone: function() {
				return this.extend({to: {}, from: arguments[0]});
			},

			// Count child objects
			count : function(o) {

				var c = 0, i;

				for (i in o) {
					if (o.hasOwnProperty(o)) {
						++c;
					}
				}

				return c;
			},

			// Create object from node string
			stringToObject: function() {

				var selector = arguments[0].replace(/ /g, "").split("@").slice(1), a = [], s, o, i, node, shell;

				for (s in selector) {
					node = selector[s].split(".");

					if (node[0] !== "") {
						o = {};
						shell = o;

						for (i = 0; i < node.length-1; ++i) {
							o = o[node[i]] = {};
						}

						if (arguments[1]) {
							o = o[node[i]] = arguments[1];
						} else {
							o = o[node[i]] = {};
						}

						a.push(shell);
					}
				}

				return a;
			},

			// Create selector from node string
			stringToSelector: function() {
				var a = [], n = this.stringToArray(arguments[0]), i, x;

				for (i in n) {
					var s = n[i].split(".");
					var node = env;

					for (x in s) {
						if (typeof node[s[x]] !== "undefined") {
							node = node[s[x]];
						}
					}

					if (node !== env) {
						a.push(node);
					}
				}

				return a;
			},

			// Create array from node string
			stringToArray: function() {
				return arguments[0].replace(/ /g, "").split("@").slice(1);
			},

			// Wrapper engine. Used for fetching stored wrappers in runtime.
			wrapper: {
				cache: {
				},

				get: function(o) {
					var wrapper, core = env.__core__, node = [core.instance].concat(o.node.replace(/@/g, "").split(".")), n, i;

					for (i in node) {
						if (!n) {
							n = node[i];
						} else {
							n = n + "__" + node[i];
						}
						if (typeof core.wrapper.cache[n] === "function") {
							wrapper = core.wrapper.cache[n];
						}
					}
					return wrapper;
				}
			},

			// Construct user function(s)
			functionConstructor: function(o) {

				var self = this;
				var core = env.__core__;

				switch(o.func) {

					// If function is an onReady function and it's the first node selector, load it into jQuery ready - else, load it straight after the window object.
					case "onReady":
						if (o.loop === "0" && typeof o.method !== "undefined") {

							if (typeof window.jQuery === "function") {

								window.jQuery(window[core.settings.jQuery.ready]).ready(function() {

									// Call method with its parent object as reference
									o.method.call(window[self.instance][o.node]);
								});

							} else {

								this.onload.push(o.method);

								window.onload = function() {
									for (o in self.onload) {

										// Call method with its parent object as reference
										self.onload[o].call(window[self.instance][o.node]);
									}
								}
							}
						}
						break;

					// Construct function as ordinary
					default:
						return function() {

							if (typeof this[o.func] === "function") {

								// Set up selector
								this[o.func].selector = this[o.func].$ = core.selector;

								// Set up selector (for new methods, if the current method is used as a constructor)
								this[o.func].prototype.selector = this[o.func].prototype.$ = core.selector;

								// Set up node
								this[o.func].node = core.clone(core.node);

								// This line is for legacy purposes only (where the selector is called from the global object)
								window[core.instance].$ = window[core.instance].selector = core.selector;
							}

							// Execute user function in correct environment
							if (typeof o.wrapper === "function") {
								var self = this;
								var args = arguments;

								// Execute user function inside wrappers (if available)
								return o.wrapper.call({
									call: function() {

										// Apply method with its parent object as reference
										return o.method.apply(self, args);
									}
								});
							} else {
								// Execute user function as ordinary (if there are no wrappers defined for this object)
								return o.method.apply(this, arguments);
							}
						};

						break;
				}

			},

			// Error handling
			error: function() {
				var core = env.__core__;

				if (core.settings.error.show === true) {
					throw new Error(arguments[0]);
				}
				return
			}
		};

		// Make the global object a reference to the instance function and return it
		/** @constructor */
		return new (window[arguments[0]] = function() {

			var extended, core = env.__core__;

			// Extend core object with instance object internally
			// Declare user functions and variables
			extended = core.extend({to: env, from: {

				// Default node and selector values
				__core__: {
					node: {
						getString: "",
						getArray: []
					},
					selector: []
				},

				// Extend selected node(s) with given object/function
				extend: function() {
					var shell, s = [], node;

					// Error on invalid node selector
					if (typeof core.node.getArray[0] === "undefined") {
						return core.error("inception.js: Trying to extend with invalid node selector.");
					}

					// Error on false input object
					if (typeof arguments[0] === "undefined") {
						return core.error("inception.js: Trying to extend with invalid input object.");
					}

					// Create shell object of selector node(s)
					shell = core.stringToObject(core.node.getString, arguments[0]);

					// Match shell with node array
					node = core.node.getArray;

					// Iterate over shell and extend each node
					for (var i in shell) {
						core.extend({to: this, from: shell[i], construct: true, node: node[i], loop: i});
						s.push(shell[i]);
					}

					// Extend up to the global object
					window[core.instance] = core.extend({to: window[core.instance], from: this});

					// Return inception object
					return env;
				},

				// Create a new instance and extend with a copy of selected objects
				clone: function() {

					var name = [], arg = arguments[0], i;

					if (arg) {
						name.push(arg);
					} else {
						name = core.node.getArray;
					}

					for (i in name) {
						// Create a new instance
						new inception(name[i]);

						// Extend with core object
						core.extend({to: window[name[i]], from: core.clone(env)});

						// Extend with inner object
						core.extend({to: window[name[i]](), from: core.clone(env)});
					}

					return env;
				},

				// Crate a wrapper that sticks to a specified node, and then wraps the calling function with itself.
				wrap: function() {

					var a, i;

					if (typeof arguments[0] === "function") {

						a = core.node.getString.replace(/\./g, "__").replace(/ /g, "").split("@").slice(1);

						if (a.length === 0) {

							// Set wrapper cache
							core.wrapper.cache[core.instance] = arguments[0];
						}

						for (i in a) {

							// Set wrapper cache
							core.wrapper.cache[core.instance + "__" + a[i]] = arguments[0];

							// Extend to core object
							core.extend({to: window[core.instance].__core__.wrapper, from: core.wrapper});
						}
					}

					return env;
				},

				// Used to read and set new environment settings
				settings: function() {
					var core = env.__core__, settings = arguments[0];

					return core.extend({to: core.settings, from: settings});
				},

				// a DOM helper, to easily create new elements through jQuery. This actually is more of a jQuery plugin, but it's often useful - so I included it.
				append: function() {
					var core = env.__core__, o = arguments[0], jQuery = window.jQuery;

					// Faster than jQueries append, but lets you pass through css, bind and attribute objects to jQuery.
					if (typeof window.jQuery === "function") {
						return core.$.each(function() {

							if (o.element) {
								var obj = document.createElement(o.element);
								this.appendChild(obj);
							}

							if (o.css) {
								jQuery(obj).css(o.css);
							}

							if (o.attr) {
								jQuery(obj).attr(o.attr);
							}

							if (o.bind) {
								for (var k in o.bind) {
									jQuery(obj).bind(k, o.bind[k]);
								}
							}
						});
					}

					return env;
				}
			}});

			// Extend up to the global object
			window[core.instance] = core.extend({to: window[core.instance], from: extended});

			// Append correct selector
			if (typeof arguments[0] === "string" && arguments[0].indexOf("@") !== -1) {

				// Set selector to an inception selector
				core.$ = core.selector = core.stringToSelector(arguments[0]);

				// Save original selector string
				core.node.getString = arguments[0];
				core.node.getArray = core.stringToArray(arguments[0]);

			} else if (typeof window.jQuery === "function") {

				// Set selector to a jQuery selector (if it's not an inception selector and if jQuery is present)
				core.$ = core.selector = window.jQuery(arguments[0]);
			} else if (arguments[0]) {

				// Use native javascript CSS selector
				core.$ = core.selector = document.querySelectorAll(arguments[0]);
			} else {

				// Clear all old selectors
				core.node.getString = "";
				core.node.getArray = "";
				core.$ = core.selector = [];
			}

			// Return extended core object
			return extended;
		});
	});

})(window);
<commit_msg>Version 1.2.1 - Bug fix for onReady functions - they now execute with correct references to 'this'.<commit_after>/*
	Copyright (c) 2010-2012 Filip Moberg, (filip@mcsquare.se)

	Permission is hereby granted, free of charge, to any person obtaining a copy
	of this software and associated documentation files (the "Software"), to deal
	in the Software without restriction, including without limitation the rights
	to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
	copies of the Software, and to permit persons to whom the Software is
	furnished to do so, subject to the following conditions:

	The above copyright notice and this permission notice shall be included in
	all copies or substantial portions of the Software.

	THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
	IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
	FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
	AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
	LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
	OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
	THE SOFTWARE.

	Author:		Filip Moberg
	Name:		inception.js
	Version:	1.2
	Codename:	Di Caprio
	Released:	2012-01-03
	Comments:	This version was so awesome, it deserved TWO new version numbers. Totally rebuilt from scratch - inception revisited.
*/

// Sandbox the environment
/** @param {...undefined} undefined */
(function(window, undefined) {

	// Declare environment variables
	var document = window.document, navigator = window.navigator, location = window.location;

	// Create function in window object
	/** @constructor */
	window.inception = (function inception(oo) {

		var env = this;
		var self = this;
		var core = env.__core__;

		// Make sure core function is instantiated
		if (this === window) {
			return new inception(arguments[0]);
		}

		// Declare core object (with core functions)
		this.__core__ = {

			settings: {
				jQuery: {
					ready: "document"
				},
				error: {
					show: true
				}
			},

			onload: [],

			instance: arguments[0],

			// Extend a primary object with a secondary
			extend: function(o) {

				// If set to true, the returned object will be a copy instead of reference
				if (o.clone === true) {
					o.from = this.clone(o.from);
				}

				for (var n in o.from) {
					if (o.construct === true && typeof o.from[n] === "function" && n !== "wrapper") {

						// Make a clone so the use of multiple selectors won't construct the same function twice
						o.from = this.clone(o.from);
						var core = env.__core__, node = [core.instance].concat(o.node.replace(/@/g, "").split(".")), wrapper = node[0], cache;
						o.wrapper = [];

						cache = core.wrapper.cache[core.instance];

						if (typeof cache === "function") {
							o.wrapper.push(cache);
						}

						for (var i=1; i < node.length; ++i) {
							wrapper = wrapper + "__" + node[i];
							cache = core.wrapper.cache[wrapper];
							if (typeof cache === "function") {
								o.wrapper.push(cache);
							}
						}

						for (var i=o.wrapper.length; i >= 0; --i) {

							// Construct the function
							o.from[n] = this.functionConstructor({method: o.from[n], func: n, node: o.node, loop: o.loop, wrapper: o.wrapper[i]});
						}
					}

					if (typeof o.from[n] === "object" && n !== "selector" && n !== "$") {

						if (typeof o.to[n] === "undefined") {
							if (o.from[n] === null) {
								o.to[n] = null;
							} else if (o.from[n].constructor.toString().indexOf("Array") !== -1) {
								o.to[n] = [];
							} else {
								o.to[n] = {};
							}
						}

						this.extend({to: o.to[n], from: o.from[n], construct: o.construct, node: o.node, loop: o.loop});
					} else {
						o.to[n] = o.from[n];
					}
				}

				return o.to;
			},

			// Create deep copy of target object
			clone: function() {
				return this.extend({to: {}, from: arguments[0]});
			},

			// Count child objects
			count : function(o) {

				var c = 0, i;

				for (i in o) {
					if (o.hasOwnProperty(o)) {
						++c;
					}
				}

				return c;
			},

			// Create object from node string
			stringToObject: function() {

				var selector = arguments[0].replace(/ /g, "").split("@").slice(1), a = [], s, o, i, node, shell;

				for (s in selector) {
					node = selector[s].split(".");

					if (node[0] !== "") {
						o = {};
						shell = o;

						for (i = 0; i < node.length-1; ++i) {
							o = o[node[i]] = {};
						}

						if (arguments[1]) {
							o = o[node[i]] = arguments[1];
						} else {
							o = o[node[i]] = {};
						}

						a.push(shell);
					}
				}

				return a;
			},

			// Create selector from node string
			stringToSelector: function() {
				var a = [], n = this.stringToArray(arguments[0]), i, x;

				for (i in n) {
					var s = n[i].split(".");
					var node = env;

					for (x in s) {
						if (typeof node[s[x]] !== "undefined") {
							node = node[s[x]];
						}
					}

					if (node !== env) {
						a.push(node);
					}
				}

				return a;
			},

			// Create array from node string
			stringToArray: function() {
				return arguments[0].replace(/ /g, "").split("@").slice(1);
			},

			// Wrapper engine. Used for fetching stored wrappers in runtime.
			wrapper: {
				cache: {
				},

				get: function(o) {
					var wrapper, core = env.__core__, node = [core.instance].concat(o.node.replace(/@/g, "").split(".")), n, i;

					for (i in node) {
						if (!n) {
							n = node[i];
						} else {
							n = n + "__" + node[i];
						}
						if (typeof core.wrapper.cache[n] === "function") {
							wrapper = core.wrapper.cache[n];
						}
					}
					return wrapper;
				}
			},

			// Construct user function(s)
			functionConstructor: function(o) {

				var self = this;
				var core = env.__core__;

				switch(o.func) {

					// If function is an onReady function and it's the first node selector, load it into jQuery ready - else, load it straight after the window object.
					case "onReady":
						if (o.loop === "0" && typeof o.method !== "undefined") {

							if (typeof window.jQuery === "function") {

								window.jQuery(window[core.settings.jQuery.ready]).ready(function() {

									o.nodeKeys = o.node.split(".");
									o.parentNode = window[self.instance];
									for (var i in o.nodeKeys) {
										o.parentNode = o.parentNode[o.nodeKeys[i]];
									}

									// Call method with its parent object as reference
									o.method.call(window[self.instance][o.node]);
								});

							} else {

								this.onload.push(o.method);

								window.onload = function() {
									for (o in self.onload) {

										o.nodeKeys = o.node.split(".");
										o.parentNode = window[self.instance];
										for (var i in o.nodeKeys) {
											o.parentNode = o.parentNode[o.nodeKeys[i]];
										}

										// Call method with its parent object as reference
										self.onload[o].call(window[self.instance][o.node]);
									}
								}
							}
						}
						break;

					// Construct function as ordinary
					default:
						return function() {

							if (typeof this[o.func] === "function") {

								// Set up selector
								this[o.func].selector = this[o.func].$ = core.selector;

								// Set up selector (for new methods, if the current method is used as a constructor)
								this[o.func].prototype.selector = this[o.func].prototype.$ = core.selector;

								// Set up node
								this[o.func].node = core.clone(core.node);

								// This line is for legacy purposes only (where the selector is called from the global object)
								window[core.instance].$ = window[core.instance].selector = core.selector;
							}

							// Execute user function in correct environment
							if (typeof o.wrapper === "function") {
								var self = this;
								var args = arguments;

								// Execute user function inside wrappers (if available)
								return o.wrapper.call({
									call: function() {

										// Apply method with its parent object as reference
										return o.method.apply(self, args);
									}
								});
							} else {
								// Execute user function as ordinary (if there are no wrappers defined for this object)
								return o.method.apply(this, arguments);
							}
						};

						break;
				}

			},

			// Error handling
			error: function() {
				var core = env.__core__;

				if (core.settings.error.show === true) {
					throw new Error(arguments[0]);
				}
				return
			}
		};

		// Make the global object a reference to the instance function and return it
		/** @constructor */
		return new (window[arguments[0]] = function() {

			var extended, core = env.__core__;

			// Extend core object with instance object internally
			// Declare user functions and variables
			extended = core.extend({to: env, from: {

				// Default node and selector values
				__core__: {
					node: {
						getString: "",
						getArray: []
					},
					selector: []
				},

				// Extend selected node(s) with given object/function
				extend: function() {
					var shell, s = [], node;

					// Error on invalid node selector
					if (typeof core.node.getArray[0] === "undefined") {
						return core.error("inception.js: Trying to extend with invalid node selector.");
					}

					// Error on false input object
					if (typeof arguments[0] === "undefined") {
						return core.error("inception.js: Trying to extend with invalid input object.");
					}

					// Create shell object of selector node(s)
					shell = core.stringToObject(core.node.getString, arguments[0]);

					// Match shell with node array
					node = core.node.getArray;

					// Iterate over shell and extend each node
					for (var i in shell) {
						core.extend({to: this, from: shell[i], construct: true, node: node[i], loop: i});
						s.push(shell[i]);
					}

					// Extend up to the global object
					window[core.instance] = core.extend({to: window[core.instance], from: this});

					// Return inception object
					return env;
				},

				// Create a new instance and extend with a copy of selected objects
				clone: function() {

					var name = [], arg = arguments[0], i;

					if (arg) {
						name.push(arg);
					} else {
						name = core.node.getArray;
					}

					for (i in name) {
						// Create a new instance
						new inception(name[i]);

						// Extend with core object
						core.extend({to: window[name[i]], from: core.clone(env)});

						// Extend with inner object
						core.extend({to: window[name[i]](), from: core.clone(env)});
					}

					return env;
				},

				// Crate a wrapper that sticks to a specified node, and then wraps the calling function with itself.
				wrap: function() {

					var a, i;

					if (typeof arguments[0] === "function") {

						a = core.node.getString.replace(/\./g, "__").replace(/ /g, "").split("@").slice(1);

						if (a.length === 0) {

							// Set wrapper cache
							core.wrapper.cache[core.instance] = arguments[0];
						}

						for (i in a) {

							// Set wrapper cache
							core.wrapper.cache[core.instance + "__" + a[i]] = arguments[0];

							// Extend to core object
							core.extend({to: window[core.instance].__core__.wrapper, from: core.wrapper});
						}
					}

					return env;
				},

				// Used to read and set new environment settings
				settings: function() {
					var core = env.__core__, settings = arguments[0];

					return core.extend({to: core.settings, from: settings});
				},

				// a DOM helper, to easily create new elements through jQuery. This actually is more of a jQuery plugin, but it's often useful - so I included it.
				append: function() {
					var core = env.__core__, o = arguments[0], jQuery = window.jQuery;

					// Faster than jQueries append, but lets you pass through css, bind and attribute objects to jQuery.
					if (typeof window.jQuery === "function") {
						return core.$.each(function() {

							if (o.element) {
								var obj = document.createElement(o.element);
								this.appendChild(obj);
							}

							if (o.css) {
								jQuery(obj).css(o.css);
							}

							if (o.attr) {
								jQuery(obj).attr(o.attr);
							}

							if (o.bind) {
								for (var k in o.bind) {
									jQuery(obj).bind(k, o.bind[k]);
								}
							}
						});
					}

					return env;
				}
			}});

			// Extend up to the global object
			window[core.instance] = core.extend({to: window[core.instance], from: extended});

			// Append correct selector
			if (typeof arguments[0] === "string" && arguments[0].indexOf("@") !== -1) {

				// Set selector to an inception selector
				core.$ = core.selector = core.stringToSelector(arguments[0]);

				// Save original selector string
				core.node.getString = arguments[0];
				core.node.getArray = core.stringToArray(arguments[0]);

			} else if (typeof window.jQuery === "function") {

				// Set selector to a jQuery selector (if it's not an inception selector and if jQuery is present)
				core.$ = core.selector = window.jQuery(arguments[0]);
			} else if (arguments[0]) {

				// Use native javascript CSS selector
				core.$ = core.selector = document.querySelectorAll(arguments[0]);
			} else {

				// Clear all old selectors
				core.node.getString = "";
				core.node.getArray = "";
				core.$ = core.selector = [];
			}

			// Return extended core object
			return extended;
		});
	});

})(window);
<|endoftext|>


<commit_before>'use strict';

/*
* The following copyright, license, and long comment were part of the original implementation available as part of [FreeBSD]{@link https://svnweb.freebsd.org/base/release/9.3.0/lib/msun/src/e_acosh.c?view=markup}.
*
* The implementation follows the original, but has been modified for JavaScript.
*/

/*
* ====================================================
* Copyright (C) 2004 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/

// MODULES //

var isnan = require( '@stdlib/math/base/assert/is-nan' );
var log1p = require( '@stdlib/math/base/special/log1p' );
var sqrt = require( '@stdlib/math/base/special/sqrt' );
var LN2 = require( '@stdlib/constants/math/float64-ln-two' );
var ln = require( '@stdlib/math/base/special/ln' );

// VARIABLES //

var HUGE = 1 << 28; // 2**28

// MAIN //

/**
* Computes the hyperbolic arccosine of a number.
*
* #### Method
*
* Based on
*
* ```tex
* \operatorname{acosh}(x) = \log \left[ x + \sqrt{ x^2 - 1 } \right]
* ```
*
* we have
*
* ```tex
* \operatorname{acosh}(x) = \begin{cases}
* \log(x) + \tfrac{\ln}{2} & \text{ if x is large } \\
* \log \left( 2x-\tfrac{1}{\sqrt{x^2-1}+x} \right) & \text{ if } x > 2 \\
* \operatorname{log1p}\left( x - 1 + \sqrt{ 2 \cdot (x-1) + (x-1)^2 } \right) & \text{ otherwise }
* \end{cases}
* ```
*
* #### Special Cases
*
* ```tex
* \begin{align*}
* \operatorname{acosh}(x) &= \mathrm{NaN}\ \text{ if } x < 1 \\
* \end{align*}
* ```
*
* @param {number} x - input value
* @returns {number} hyperbolic arccosine (in radians)
*
* @example
* var v = acosh( 1.0 );
* // returns 0.0
*
* @example
* var v = acosh( 2.0 );
* // returns ~1.317
*
* @example
* var v = acosh( NaN );
* // returns NaN
*/
function acosh( x ) {
	var t;
	if ( isnan( x ) ) {
		return NaN;
	}
	if ( x < 1.0 ) {
		return NaN;
	}
	if ( x === 1.0 ) {
		return 0.0;
	}
	if ( x >= HUGE ) {
		return ln( x ) + LN2;
	}
	if ( x > 2.0 ) {
		return ln( (2.0*x) - ( 1.0 / ( x + sqrt( (x*x) - 1.0 ) ) ) );
	}
	// Case: 2 >= x > 1
	t = x - 1.0;
	return log1p( t + sqrt( (2.0*t) + (t*t) ) );
} // end FUNCTION acosh()

// EXPORTS //

module.exports = acosh;
<commit_msg>Adjust heading level<commit_after>'use strict';

/*
* The following copyright, license, and long comment were part of the original implementation available as part of [FreeBSD]{@link https://svnweb.freebsd.org/base/release/9.3.0/lib/msun/src/e_acosh.c?view=markup}.
*
* The implementation follows the original, but has been modified for JavaScript.
*/

/*
* ====================================================
* Copyright (C) 2004 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/

// MODULES //

var isnan = require( '@stdlib/math/base/assert/is-nan' );
var log1p = require( '@stdlib/math/base/special/log1p' );
var sqrt = require( '@stdlib/math/base/special/sqrt' );
var LN2 = require( '@stdlib/constants/math/float64-ln-two' );
var ln = require( '@stdlib/math/base/special/ln' );

// VARIABLES //

var HUGE = 1 << 28; // 2**28

// MAIN //

/**
* Computes the hyperbolic arccosine of a number.
*
* ## Method
*
* Based on
*
* ```tex
* \operatorname{acosh}(x) = \log \left[ x + \sqrt{ x^2 - 1 } \right]
* ```
*
* we have
*
* ```tex
* \operatorname{acosh}(x) = \begin{cases}
* \log(x) + \tfrac{\ln}{2} & \text{ if x is large } \\
* \log \left( 2x-\tfrac{1}{\sqrt{x^2-1}+x} \right) & \text{ if } x > 2 \\
* \operatorname{log1p}\left( x - 1 + \sqrt{ 2 \cdot (x-1) + (x-1)^2 } \right) & \text{ otherwise }
* \end{cases}
* ```
*
* ## Special Cases
*
* ```tex
* \begin{align*}
* \operatorname{acosh}(x) &= \mathrm{NaN}\ \text{ if } x < 1 \\
* \end{align*}
* ```
*
* @param {number} x - input value
* @returns {number} hyperbolic arccosine (in radians)
*
* @example
* var v = acosh( 1.0 );
* // returns 0.0
*
* @example
* var v = acosh( 2.0 );
* // returns ~1.317
*
* @example
* var v = acosh( NaN );
* // returns NaN
*/
function acosh( x ) {
	var t;
	if ( isnan( x ) ) {
		return NaN;
	}
	if ( x < 1.0 ) {
		return NaN;
	}
	if ( x === 1.0 ) {
		return 0.0;
	}
	if ( x >= HUGE ) {
		return ln( x ) + LN2;
	}
	if ( x > 2.0 ) {
		return ln( (2.0*x) - ( 1.0 / ( x + sqrt( (x*x) - 1.0 ) ) ) );
	}
	// Case: 2 >= x > 1
	t = x - 1.0;
	return log1p( t + sqrt( (2.0*t) + (t*t) ) );
} // end FUNCTION acosh()

// EXPORTS //

module.exports = acosh;
<|endoftext|>


<commit_before>'use strict';

var mongoose = require('mongoose'),
  GitDev = mongoose.model('GitDev'),
  /*request = require('request'),*/
  /*async = require('async'),*/
  GitApiConfig = require('../config/git_api'),
  GitHubApi = require('github');

exports.ajax_test = function(req, res) {

  var json_response = {'status': 'success', 'msg': 'A json object just for you!'};

  res.json(json_response);

};

exports.git_developer_lookup = function(req, res) {

  var gitdev = new GitDev(req.body),
    developer = gitdev.username,
    user = {};

  var github = new GitHubApi({
    version: '3.0.0',
    headers: {
      'user-agent': GitApiConfig.user_agent
    }
  });

  github.authenticate({
    type: 'oauth',
    key: GitApiConfig.client_id,
    secret: GitApiConfig.client_secret
  });

  github.user.getFrom({user:developer},
    function(err, api_res) {
      if (err) {
        console.log(err);
      } else {
        user = api_res;
        // remove the headers from the github response obj - no reasons to save them
        delete user.meta;
        gitdev.user = user;

        gitdev.save(function(err) {
          if (err) {
            console.log(err);
          } else {
            console.log('success');
            console.log(gitdev);
          }
        });
      }
    }
  );
  // This won't work since the network call is async
  console.log(user);

  /*
  // Should probably upsert here instead...
  gitdev.save(function(err) {
    if (err) {
      return res.status(500).json({
        error: 'Cannot create Git Developer'
      });
    }
    res.json(gitdev);
  }); */
};<commit_msg>use async library to process github api calls in series and parallel where appropriate<commit_after>'use strict';

var /*mongoose = require('mongoose'),*/
  /*GitDev = mongoose.model('GitDev'),*/
  /*request = require('request'),*/
  async = require('async'),
  GitApiConfig = require('../config/git_api'),
  GitHubApi = require('github');

exports.ajax_test = function(req, res) {

  var json_response = {'status': 'success', 'msg': 'A json object just for you!'};

  res.json(json_response);

};

exports.git_developer_lookup = function(req, res) {

  var developer = req.body.username;

  var github = new GitHubApi({
    version: '3.0.0',
    headers: {
      'user-agent': GitApiConfig.user_agent
    }
  });

  // Just authenticate against my app for now -
  // later we can add the ability for user to authenticate themselves
  // for private element access
  var authenticate_github = function () {
    github.authenticate({
      type: 'oauth',
      key: GitApiConfig.client_id,
      secret: GitApiConfig.client_secret
    });
  };

  async.series([
    function(callback) {

      authenticate_github();

      github.user.getFrom({user:developer},
        function(err, api_res) {
          var user;
          if (!err) {
            user = api_res;
            // remove the headers from the github response obj - no reasons to save them
            delete user.meta;
          }
          callback(err, user);
        }
      );
    }
  ],
  function(err, results) {
    console.log(results);
    console.log('Result Reached');
  });

  // gitdev = new GitDev(req.body)

  // This won't work since the network call is async
  //console.log(user);

  /*
  // Should probably upsert here instead...
  gitdev.save(function(err) {
    if (err) {
      return res.status(500).json({
        error: 'Cannot create Git Developer'
      });
    }
    res.json(gitdev);
  }); */
};<|endoftext|>


<commit_before>/*jshint debug:true, noarg:true, noempty:true, eqeqeq:true, bitwise:true, undef:true, curly:true, browser: true, devel: true, jquery:true, strict:false */
/*global Backbone, _, jQuery, Sail */

(function() {
  "use strict";
  var HG = this.HG || {};
  this.Skeletor.Mobile = this.Skeletor.Mobile || {};
  var app = this.Skeletor.Mobile;
  app.View = {};

  /**
    InputView
  **/
  app.View.InputView = Backbone.View.extend({
    view: this,
    template: "#resume-unpublished-notes",

    initialize: function() {
      var view = this;
      console.log('Initializing InputView...', view.el);
    },

    events: {
      'click .resume-note-btn'   : "resumeNote",
      'click .new-note-btn'      : 'showNewNote',
      'click .modal-select-note' : 'selectNoteToResume',
      'click .cancel-note-btn'   : 'cancelNote',
      'click .share-note-btn'    : 'shareNote',
      //'click .note-body'         : 'createOrRestoreNote',
      'keyup :input': function(ev) {
        var view = this,
          field = ev.target.name,
          input = ev.target.value;
        // clear timer on keyup so that a save doesn't happen while typing
        window.clearTimeout(app.autoSaveTimer);

        // save after 10 keystrokes
        app.autoSave(app.currentNote, field, input, false);

        // setting up a timer so that if we stop typing we save stuff after 5 seconds
        app.autoSaveTimer = setTimeout(function(){
          app.autoSave(app.currentNote, field, input, true);
        }, 5000);
      }
    },

    resumeNote: function(){
      var view = this;

      // retrieve unpublished notes of user
      var notesToRestore = view.collection.where({author: app.username, published: false});

      // fill the modal
      jQuery('#select-note-modal').html('');
      _.each(notesToRestore, function(note){
        var option = _.template(jQuery(view.template).text(), {'option_text': note.get('body'), id: note.id});
        jQuery('#select-note-modal').append(option);
      });

      //show modal
      console.log('Show modal to pick previous note.');
      jQuery('.unpublished-note-picker').modal('show');
    },

    showNewNote: function() {
      console.log('Starting new note.');

      // create an note object
      var note = {};
      note.author = app.username;
      note.created_at = new Date();
      note.body = '';
      note.published = false;

      // make note wakeful and add it to notes collection
      app.addNote(note);

      // Clear text input field
      this.$el.find('.note-body').val('');

      jQuery('.note-taking-toggle').slideDown();
      jQuery('.resume-note-btn, .new-note-btn').attr('disabled', 'disabled');
    },

    cancelNote: function() {
      console.log("Cancelling note and hiding textarea.");
      // Hide textarea
      jQuery('.note-taking-toggle').slideUp();
      jQuery('.resume-note-btn, .new-note-btn').removeAttr('disabled', 'disabled');
    },

    selectNoteToResume: function(ev){
      var view = this;
      console.log('Select a note.');

      var selectedOption = jQuery('#select-note-modal').children()[jQuery('#select-note-modal').index()];
      // retrieve id of selectd note
      var selectedNoteId = jQuery(selectedOption).data('id');
      app.currentNote = view.collection.findWhere({_id: selectedNoteId});

      // Clear text input field
      this.$el.find('.note-body').val('');

      this.$el.find('.note-body').val(app.currentNote.get('body'));

      jQuery('.unpublished-note-picker').modal('hide');
      jQuery('.note-taking-toggle').slideDown();
      jQuery('.resume-note-btn, .new-note-btn').attr('disabled', 'disabled');
    },

    // createOrRestoreNote: function(ev) {
    //   // alert('createNewNote: want me to do stuff, teach me');
    //   var view = this;

    //   var noteToRestore = view.collection.findWhere({author: app.username, published: false});
    //   if (noteToRestore) {
    //     app.currentNote = noteToRestore;
    //     this.$el.find('.note-body').val(app.currentNote.get('body'));
    //   } else {
    //     // no unpublished note, so we create a new note
    //     var note = {};
    //     note.author = app.username;
    //     note.created_at = new Date();
    //     note.body = '';
    //     note.published = false;

    //     app.addNote(note);
    //   }
    // },

    shareNote: function() {
      console.log('want me to do stuff, teach me');

      app.currentNote.set('body', this.$el.find('.note-body').val());
      app.currentNote.set('published', true);

      app.currentNote.save();

      // clearing up
      this.$el.find('.note-body').val('');
      // turn off auto save
      window.clearTimeout(app.autoSaveTimer);
      app.currentNote = null;
      jQuery('.note-taking-toggle').slideUp();
    },

    // autosaveNote: function(ev) {
    //   var field = ev.target.name,
    //       input = jQuery('#'+ev.target.id).val();
    //   // clear timer on keyup so that a save doesn't happen while typing
    //   window.clearTimeout(app.autoSaveTimer);

    //   // save after 10 keystrokes
    //   app.autoSave(view.model, field, input, false);

    //   // setting up a timer so that if we stop typing we save stuff after 5 seconds
    //   app.autoSaveTimer = setTimeout(function(){
    //     app.autoSave(view.model, field, input, true);
    //   }, 5000);
    // },

    render: function () {
      console.log('Rendering InputView...');
    }
  });

  /**
    ListView
  **/
  app.View.ListView = Backbone.View.extend({
    template: "#notes-list-template",

    initialize: function () {
      var view = this;
      console.log('Initializing ListView...', view.el);

      view.collection.on('change', function(n) {
        view.render();
      });

      view.collection.on('add', function(n) {
        view.render();
      });

      view.render();

      return view;
    },

    events: {
      // nothing here yet, but could be click events on list items to have actions (delete, response and so forth)
    },

    render: function () {
      var view = this;
      console.log("Rendering ListView");

      // find the list where items are rendered into
      var list = this.$el.find('ul');

      // Only want to show published notes at some point
      var publishedNotes = view.collection.where({published: true});

      _.each(publishedNotes, function(note){
        var me_or_others = 'others';
        // add class 'me' or 'other' to note
        if (note.get('author') === app.username) {
          me_or_others = 'me';
        }

        //
        var listItem = _.template(jQuery(view.template).text(), {'id': note.id, 'text': note.get('body'), 'me_or_others': me_or_others, 'author': note.get('author'), 'created_at': note.get('created_at')});

        var existingNote = list.find("[data-id='" + note.id + "']");

        if (existingNote.length === 0) {
          list.append(listItem);
        } else {
          existingNote.replaceWith(listItem);
        }
      });

    }

  });

  this.HG = HG;
}).call(this);
<commit_msg>quick fix to shareNote function<commit_after>/*jshint debug:true, noarg:true, noempty:true, eqeqeq:true, bitwise:true, undef:true, curly:true, browser: true, devel: true, jquery:true, strict:false */
/*global Backbone, _, jQuery, Sail */

(function() {
  "use strict";
  var HG = this.HG || {};
  this.Skeletor.Mobile = this.Skeletor.Mobile || {};
  var app = this.Skeletor.Mobile;
  app.View = {};

  /**
    InputView
  **/
  app.View.InputView = Backbone.View.extend({
    view: this,
    template: "#resume-unpublished-notes",

    initialize: function() {
      var view = this;
      console.log('Initializing InputView...', view.el);
    },

    events: {
      'click .resume-note-btn'   : "resumeNote",
      'click .new-note-btn'      : 'showNewNote',
      'click .modal-select-note' : 'selectNoteToResume',
      'click .cancel-note-btn'   : 'cancelNote',
      'click .share-note-btn'    : 'shareNote',
      //'click .note-body'         : 'createOrRestoreNote',
      'keyup :input': function(ev) {
        var view = this,
          field = ev.target.name,
          input = ev.target.value;
        // clear timer on keyup so that a save doesn't happen while typing
        window.clearTimeout(app.autoSaveTimer);

        // save after 10 keystrokes
        app.autoSave(app.currentNote, field, input, false);

        // setting up a timer so that if we stop typing we save stuff after 5 seconds
        app.autoSaveTimer = setTimeout(function(){
          app.autoSave(app.currentNote, field, input, true);
        }, 5000);
      }
    },

    resumeNote: function(){
      var view = this;

      // retrieve unpublished notes of user
      var notesToRestore = view.collection.where({author: app.username, published: false});

      // fill the modal
      jQuery('#select-note-modal').html('');
      _.each(notesToRestore, function(note){
        var option = _.template(jQuery(view.template).text(), {'option_text': note.get('body'), id: note.id});
        jQuery('#select-note-modal').append(option);
      });

      //show modal
      console.log('Show modal to pick previous note.');
      jQuery('.unpublished-note-picker').modal('show');
    },

    showNewNote: function() {
      console.log('Starting new note.');

      // create an note object
      var note = {};
      note.author = app.username;
      note.created_at = new Date();
      note.body = '';
      note.published = false;

      // make note wakeful and add it to notes collection
      app.addNote(note);

      // Clear text input field
      this.$el.find('.note-body').val('');

      jQuery('.note-taking-toggle').slideDown();
      jQuery('.resume-note-btn, .new-note-btn').attr('disabled', 'disabled');
    },

    cancelNote: function() {
      console.log("Cancelling note and hiding textarea.");
      // Hide textarea
      jQuery('.note-taking-toggle').slideUp();
      jQuery('.resume-note-btn, .new-note-btn').removeAttr('disabled', 'disabled');
    },

    selectNoteToResume: function(ev){
      var view = this;
      console.log('Select a note.');

      var selectedOption = jQuery('#select-note-modal').children()[jQuery('#select-note-modal').index()];
      // retrieve id of selectd note
      var selectedNoteId = jQuery(selectedOption).data('id');
      app.currentNote = view.collection.findWhere({_id: selectedNoteId});

      // Clear text input field
      this.$el.find('.note-body').val('');

      this.$el.find('.note-body').val(app.currentNote.get('body'));

      jQuery('.unpublished-note-picker').modal('hide');
      jQuery('.note-taking-toggle').slideDown();
      jQuery('.resume-note-btn, .new-note-btn').attr('disabled', 'disabled');
    },

    // createOrRestoreNote: function(ev) {
    //   // alert('createNewNote: want me to do stuff, teach me');
    //   var view = this;

    //   var noteToRestore = view.collection.findWhere({author: app.username, published: false});
    //   if (noteToRestore) {
    //     app.currentNote = noteToRestore;
    //     this.$el.find('.note-body').val(app.currentNote.get('body'));
    //   } else {
    //     // no unpublished note, so we create a new note
    //     var note = {};
    //     note.author = app.username;
    //     note.created_at = new Date();
    //     note.body = '';
    //     note.published = false;

    //     app.addNote(note);
    //   }
    // },

    shareNote: function() {
      console.log('want me to do stuff, teach me');

      app.currentNote.set('body', this.$el.find('.note-body').val());
      app.currentNote.set('published', true);

      app.currentNote.save();

      // clearing up
      this.$el.find('.note-body').val('');
      // turn off auto save
      window.clearTimeout(app.autoSaveTimer);
      app.currentNote = null;
      jQuery('.note-taking-toggle').slideUp();
      jQuery('.resume-note-btn, .new-note-btn').removeAttr('disabled', 'disabled');
    },

    // autosaveNote: function(ev) {
    //   var field = ev.target.name,
    //       input = jQuery('#'+ev.target.id).val();
    //   // clear timer on keyup so that a save doesn't happen while typing
    //   window.clearTimeout(app.autoSaveTimer);

    //   // save after 10 keystrokes
    //   app.autoSave(view.model, field, input, false);

    //   // setting up a timer so that if we stop typing we save stuff after 5 seconds
    //   app.autoSaveTimer = setTimeout(function(){
    //     app.autoSave(view.model, field, input, true);
    //   }, 5000);
    // },

    render: function () {
      console.log('Rendering InputView...');
    }
  });

  /**
    ListView
  **/
  app.View.ListView = Backbone.View.extend({
    template: "#notes-list-template",

    initialize: function () {
      var view = this;
      console.log('Initializing ListView...', view.el);

      view.collection.on('change', function(n) {
        view.render();
      });

      view.collection.on('add', function(n) {
        view.render();
      });

      view.render();

      return view;
    },

    events: {
      // nothing here yet, but could be click events on list items to have actions (delete, response and so forth)
    },

    render: function () {
      var view = this;
      console.log("Rendering ListView");

      // find the list where items are rendered into
      var list = this.$el.find('ul');

      // Only want to show published notes at some point
      var publishedNotes = view.collection.where({published: true});

      _.each(publishedNotes, function(note){
        var me_or_others = 'others';
        // add class 'me' or 'other' to note
        if (note.get('author') === app.username) {
          me_or_others = 'me';
        }

        //
        var listItem = _.template(jQuery(view.template).text(), {'id': note.id, 'text': note.get('body'), 'me_or_others': me_or_others, 'author': note.get('author'), 'created_at': note.get('created_at')});

        var existingNote = list.find("[data-id='" + note.id + "']");

        if (existingNote.length === 0) {
          list.append(listItem);
        } else {
          existingNote.replaceWith(listItem);
        }
      });

    }

  });

  this.HG = HG;
}).call(this);
<|endoftext|>


<commit_before>/*global TodoMVC */
'use strict';

TodoMVC.module('Todos', function (Todos, App, Backbone) {
	// Todo Model
	// ----------
	Todos.Todo = Backbone.Model.extend({
		defaults: {
			title: '',
			completed: false,
			created: 0
		},

		initialize: function () {
			if (this.isNew()) {
				this.set('created', Date.now());
			}
		},

		toggle: function () {
			return this.set('completed', !this.isCompleted());
		},

		isCompleted: function () {
			return this.get('completed');
		},

		matchesFilter: function (filter) {
			if (filter == 'all') {
				return true;
			}

			if (filter == 'active') {
				return !this.isCompleted();
			}

			return this.isCompleted();
		}
	});

	// Todo Collection
	// ---------------
	Todos.TodoList = Backbone.Collection.extend({
		model: Todos.Todo,

		localStorage: new Backbone.LocalStorage('todos-backbone-marionette'),

		getCompleted: function () {
			return this.filter(this._isCompleted);
		},

		getActive: function () {
			return this.reject(this._isCompleted);
		},

		comparator: 'created',

		_isCompleted: function (todo) {
			return todo.isCompleted();
		}
	});
});
<commit_msg>Use === insteadOf == even for strings<commit_after>/*global TodoMVC */
'use strict';

TodoMVC.module('Todos', function (Todos, App, Backbone) {
	// Todo Model
	// ----------
	Todos.Todo = Backbone.Model.extend({
		defaults: {
			title: '',
			completed: false,
			created: 0
		},

		initialize: function () {
			if (this.isNew()) {
				this.set('created', Date.now());
			}
		},

		toggle: function () {
			return this.set('completed', !this.isCompleted());
		},

		isCompleted: function () {
			return this.get('completed');
		},

		matchesFilter: function (filter) {
			if (filter === 'all') {
				return true;
			}

			if (filter === 'active') {
				return !this.isCompleted();
			}

			return this.isCompleted();
		}
	});

	// Todo Collection
	// ---------------
	Todos.TodoList = Backbone.Collection.extend({
		model: Todos.Todo,

		localStorage: new Backbone.LocalStorage('todos-backbone-marionette'),

		getCompleted: function () {
			return this.filter(this._isCompleted);
		},

		getActive: function () {
			return this.reject(this._isCompleted);
		},

		comparator: 'created',

		_isCompleted: function (todo) {
			return todo.isCompleted();
		}
	});
});
<|endoftext|>


<commit_before>// possible constraints:
// - your direction should be normalized
// - your speed is limited to maxSpeed (cannot adjust speed?)
// - your velocity is direction.mulFloat(dt*speed)
GameObject.subclass("Tank", {
	initialize: function($super, world, pos, vel, dir, config) {
	    $super(world, "tank", pos, new Vector2(2, 2), 1, vel, config.speed);

        this.turretDirection = dir;
        this.turretAnimation = new Animation(new AnimationSheet("assets/turret.png", 18, 18), 0.4, [0,1,2,3]);

        this.bullets = config.bullets;
        this.bulletRicochets = config.bulletRicochets;
        this.bulletSpeed = config.bulletSpeed;

		this.initConstraints();
    },
    initConstraints: function() {
        var that = this,
            map = this.world.map;

        // constraint:
        // - do not be on a wall tile
        bbb.assert({
            // collision solving is already provided by the babelsberg.assert
            // method and its ability the revert to a valid state
            onError: function(error) {
                if(!error instanceof ContinuousAssertError) {
                    throw error;
                }
            },
            ctx: {
                that: that,
                map: map
            }
        }, function() {
            // collision detection against the current tile
            var pos = that.position.divVector(map.tileSize).floor();
            return map.tiles[pos.y][pos.x].canWalkThrough();
        });

        // assumption: tanks are inserted first into the world
        this.world.getGameObjects().each(function(tank) {
            // constraint:
            // - solve collisions
            that.onCollisionWith(tank, function(that, tank) {
                var desiredDistance = that.radius + tank.radius,
                    distVector = tank.position.sub(that.position),
                    realDistance = distVector.length(),
                    moveVector = distVector.mulFloat((desiredDistance - realDistance) / 1.9);
                tank.position.addSelf(moveVector);
                that.position.subSelf(moveVector);
                //console.log(realDistance, "post", that.position.distance(tank.position, that.radius + tank.radius));
            });
        });
	},

	update: function($super, dt) {
	    this.controls && this.controls.update(dt);

	    $super(dt);
        this.turretAnimation.update(dt);
	},

	draw: function($super, renderer) {
	    $super(renderer);
		this.turretAnimation.draw(
		    renderer, this.getWorldAABB(true), this.turretDirection.getDirectedAngle(new Vector2(1,0))
		);
	},

    fireBullet: function(world, dt) {
        if(this.bullets == 0) { return; }
        this.bullets--;

        var direction = this.turretDirection.normalizedCopy();
        var bullet = new Bullet(world,
            this.position.add(direction.mulFloat(this.radius + 0.25 + this.speed * dt)),
            direction,
            this,
            this.bulletRicochets,
            this.bulletSpeed
        );
        world.getGameObjects().each(function(other) {
            bullet.onCollisionWith(other, function(bullet, other) {
                // 3 possibilities to avoid this to happen more than one time:
                // 1. in collision callback:
                //     if(bullet.alive && other.alive)
                //     but get not rid of the actual constraint -> slow with more and more bullets
                // 2. layer each game object
                //     layer.activeOn(bullet in world)
                //     but collision callback is linked to 2 game objects
                // 3. in collision callback
                //     bullet.unconstrainAND_DISABLE_ALL() to disable all linked constraints
                //     very general; we instead keep track of these manually and disable all constraints on destroy
                bullet.destroy();
                other.destroy();
            });
        });
        world.spawn(bullet);
    }
});

Tank.subclass("PlayerTank", {
	initialize: function($super, world, pos, vel, dir, config) {
	    $super(world, pos, vel, dir, config);

		this.animation = new Animation(new AnimationSheet("assets/tank.png", 18, 18), 0.4, [0,1,2,3]);
    }
});

Tank.subclass("CPUTank", {
    initialize: function($super, world, pos, vel, dir, config) {
        $super(world, pos, vel, dir, config);

		this.animation = new Animation(new AnimationSheet("assets/tank.png", 18, 18), 0.4, [4,5,6,7]);

        // constraint:
        // - keep velocity direction and turret direction in sync
        /*
        var that = this;
        var turretConstraint = bbb.always({
            solver: new DBPlanner(),
            ctx: {
                that: that
            },
            methods: function() {
                that.turretDirection.formula([that.velocity, that.velocity.x, that.velocity.y], function(velocity, velocityX, velocityY) {
                    return velocity;
                });
            }
        }, function() {
            return that.turretDirection.equals(that.velocity);
        });

        this.constraints.push(turretConstraint);
        */
	}
});

Tank.SPEED_IMMOBILE = 0;
Tank.SPEED_NORMAL = 16 / 6;
Tank.SPEED_SLOW = 0.5 * Tank.SPEED_NORMAL;
Tank.SPEED_FAST = 1.5 * Tank.SPEED_NORMAL;
<commit_msg>ease "do not stand in a wall" constraint<commit_after>// possible constraints:
// - your direction should be normalized
// - your speed is limited to maxSpeed (cannot adjust speed?)
// - your velocity is direction.mulFloat(dt*speed)
GameObject.subclass("Tank", {
	initialize: function($super, world, pos, vel, dir, config) {
	    $super(world, "tank", pos, new Vector2(2, 2), 1, vel, config.speed);

        this.turretDirection = dir;
        this.turretAnimation = new Animation(new AnimationSheet("assets/turret.png", 18, 18), 0.4, [0,1,2,3]);

        this.bullets = config.bullets;
        this.bulletRicochets = config.bulletRicochets;
        this.bulletSpeed = config.bulletSpeed;

		this.initConstraints();
    },
    initConstraints: function() {
        var that = this,
            map = this.world.map;

        // constraint:
        // - do not be on a wall tile
        bbb.assert({
            // collision solving is already provided by the babelsberg.assert
            // method and its ability the revert to a valid state
            onError: function(error) {
                if(!error instanceof ContinuousAssertError) {
                    throw error;
                }
            },
            ctx: {
                that: that,
                map: map
            }
        }, function() {
            // collision detection against the current tile
            return that.getTile(that.position).canWalkThrough();
        });

        // assumption: tanks are inserted first into the world
        this.world.getGameObjects().each(function(tank) {
            // constraint:
            // - solve collisions
            that.onCollisionWith(tank, function(that, tank) {
                var desiredDistance = that.radius + tank.radius,
                    distVector = tank.position.sub(that.position),
                    realDistance = distVector.length(),
                    moveVector = distVector.mulFloat((desiredDistance - realDistance) / 1.9);
                tank.position.addSelf(moveVector);
                that.position.subSelf(moveVector);
                //console.log(realDistance, "post", that.position.distance(tank.position, that.radius + tank.radius));
            });
        });
	},

	update: function($super, dt) {
	    this.controls && this.controls.update(dt);

	    $super(dt);
        this.turretAnimation.update(dt);
	},

	draw: function($super, renderer) {
	    $super(renderer);
		this.turretAnimation.draw(
		    renderer, this.getWorldAABB(true), this.turretDirection.getDirectedAngle(new Vector2(1,0))
		);
	},

    fireBullet: function(world, dt) {
        if(this.bullets == 0) { return; }
        this.bullets--;

        var direction = this.turretDirection.normalizedCopy();
        var bullet = new Bullet(world,
            this.position.add(direction.mulFloat(this.radius + 0.25 + this.speed * dt)),
            direction,
            this,
            this.bulletRicochets,
            this.bulletSpeed
        );
        world.getGameObjects().each(function(other) {
            bullet.onCollisionWith(other, function(bullet, other) {
                // 3 possibilities to avoid this to happen more than one time:
                // 1. in collision callback:
                //     if(bullet.alive && other.alive)
                //     but get not rid of the actual constraint -> slow with more and more bullets
                // 2. layer each game object
                //     layer.activeOn(bullet in world)
                //     but collision callback is linked to 2 game objects
                // 3. in collision callback
                //     bullet.unconstrainAND_DISABLE_ALL() to disable all linked constraints
                //     very general; we instead keep track of these manually and disable all constraints on destroy
                bullet.destroy();
                other.destroy();
            });
        });
        world.spawn(bullet);
    }
});

Tank.subclass("PlayerTank", {
	initialize: function($super, world, pos, vel, dir, config) {
	    $super(world, pos, vel, dir, config);

		this.animation = new Animation(new AnimationSheet("assets/tank.png", 18, 18), 0.4, [0,1,2,3]);
    }
});

Tank.subclass("CPUTank", {
    initialize: function($super, world, pos, vel, dir, config) {
        $super(world, pos, vel, dir, config);

		this.animation = new Animation(new AnimationSheet("assets/tank.png", 18, 18), 0.4, [4,5,6,7]);

        // constraint:
        // - keep velocity direction and turret direction in sync
        /*
        var that = this;
        var turretConstraint = bbb.always({
            solver: new DBPlanner(),
            ctx: {
                that: that
            },
            methods: function() {
                that.turretDirection.formula([that.velocity, that.velocity.x, that.velocity.y], function(velocity, velocityX, velocityY) {
                    return velocity;
                });
            }
        }, function() {
            return that.turretDirection.equals(that.velocity);
        });

        this.constraints.push(turretConstraint);
        */
	}
});

Tank.SPEED_IMMOBILE = 0;
Tank.SPEED_NORMAL = 16 / 6;
Tank.SPEED_SLOW = 0.5 * Tank.SPEED_NORMAL;
Tank.SPEED_FAST = 1.5 * Tank.SPEED_NORMAL;
<|endoftext|>