<commit_before>// =========================================================================
//
// All the client side routes for orgs
//
// =========================================================================
(function() {
	'use strict';

	angular.module('orgs.routes').config([
		'$stateProvider',
		function($stateProvider) {
			$stateProvider
				// -------------------------------------------------------------------------
				//
				// this is the top level, abstract route for all org routes, it only
				// contians the ui-view that all other routes get rendered in
				//
				// -------------------------------------------------------------------------
				.state('orgs', {
					abstract: true,
					url: '/orgs',
					template: '<ui-view autoscroll="true"></ui-view>'
				})
				// -------------------------------------------------------------------------
				//
				// create a new org
				//
				// -------------------------------------------------------------------------
				.state('orgs.create', {
					url: '/create',
					templateUrl: '/modules/orgs/client/views/org-add.html',
					controller: 'OrgCreateController',
					controllerAs: 'vm',
					resolve: {
						org: [
							'OrgsService',
							function(OrgsService) {
								return new OrgsService();
							}
						]
					}
				})
				// -------------------------------------------------------------------------
				//
				// org listing. Resolve to all orgs in the system and place that in
				// the scope. listing itself is done through a directive
				//
				// -------------------------------------------------------------------------
				.state('orgs.list', {
					url: '',
					templateUrl: '/modules/orgs/client/views/list-orgs.client.view.html',
					data: {
						pageTitle: 'Orgs List'
					},
					ncyBreadcrumb: {
						label: 'All orgs'
					},
					resolve: {
						orgs: [
							'OrgsService',
							function(OrgsService) {
								return OrgsService.query().$promise;
							}
						]
					},
					controller: 'OrgsListController',
					controllerAs: 'vm'
				})
				// -------------------------------------------------------------------------
				//
				// view an org, resolve the org data
				//
				// -------------------------------------------------------------------------
				.state('orgs.view', {
					url: '/:orgId',
					templateUrl: '/modules/orgs/client/views/org-view.html',
					controller: 'OrgViewController',
					controllerAs: 'vm',
					resolve: {
						org: [
							'$stateParams',
							'OrgsService',
							function($stateParams, OrgsService) {
								return OrgsService.get({
									orgId: $stateParams.orgId
								}).$promise;
							}
						],
						capabilities: [
							'CapabilitiesService',
							function(CapabilitiesService) {
								return CapabilitiesService.query().$promise;
							}
						]
					}
				})
				// -------------------------------------------------------------------------
				//
				// the base for editing
				//
				// -------------------------------------------------------------------------
				.state('orgadmin', {
					abstract: true,
					url: '/orgadmin/:orgId',
					templateUrl: '/modules/orgs/client/views/org-edit.html',
					controller: 'OrgAdminController',
					controllerAs: 'vm',
					resolve: {
						org: [
							'$stateParams',
							'OrgsService',
							function($stateParams, OrgsService) {
								return OrgsService.get({
									orgId: $stateParams.orgId
								}).$promise;
							}
						],
						capabilities: [
							'CapabilitiesService',
							function(CapabilitiesService) {
								return CapabilitiesService.query().$promise;
							}
						]
					},
					data: {
						roles: ['user', 'admin']
					}
				})
				.state('orgadmin.profile', {
					url: '/main',
					templateUrl: '/modules/orgs/client/views/org-main.html',
					controller: 'OrgProfileController',
					controllerAs: 'vm',
					data: {
						pageTitle: 'Company Settings'
					},
					resolve: {
						// org: [
						// 	'$stateParams',
						// 	'OrgsService',
						// 	function($stateParams, OrgsService) {
						// 		return OrgsService.get({
						// 			orgId: $stateParams.orgId
						// 		}).$promise;
						// 	}
						// ],
						// capabilities: [
						// 	'CapabilitiesService',
						// 	function(CapabilitiesService) {
						// 		return CapabilitiesService.query().$promise;
						// 	}
						// ]
					}
				})
				.state('orgadmin.members', {
					url: '/members',
					templateUrl: '/modules/orgs/client/views/org-members.html',
					controller: 'OrgMembersController',
					controllerAs: 'vm',
					data: {
						pageTitle: 'Company Members'
					},
					resolve: {
						org: [
							'$stateParams',
							'OrgsService',
							function($stateParams, OrgsService) {
								return OrgsService.get({
									orgId: $stateParams.orgId
								}).$promise;
							}
						],
						capabilities: [
							'CapabilitiesService',
							function(CapabilitiesService) {
								return CapabilitiesService.query().$promise;
							}
						]
					}
				})
				.state('orgadmin.terms', {
					url: '/terms',
					templateUrl: '/modules/orgs/client/views/org-terms.html',
					controller: 'OrgTermsController',
					controllerAs: 'vm',
					data: {
						pageTitle: 'Company Terms'
					},
					resolve: {
						org: [
							'$stateParams',
							'OrgsService',
							function($stateParams, OrgsService) {
								return OrgsService.get({
									orgId: $stateParams.orgId
								}).$promise;
							}
						]
					}
				});
		}
	]);
}());
<commit_msg>BA-980 - Clean up client routes for orgs<commit_after>// =========================================================================
//
// All the client side routes for orgs
//
// =========================================================================
(function() {
	'use strict';

	angular.module('orgs.routes').config([
		'$stateProvider',
		function($stateProvider) {
			$stateProvider
				// -------------------------------------------------------------------------
				//
				// this is the top level, abstract route for all org routes, it only
				// contians the ui-view that all other routes get rendered in
				//
				// -------------------------------------------------------------------------
				.state('orgs', {
					abstract: true,
					url: '/orgs',
					template: '<ui-view autoscroll="true"></ui-view>'
				})
				// -------------------------------------------------------------------------
				//
				// create a new org
				//
				// -------------------------------------------------------------------------
				.state('orgs.create', {
					url: '/create',
					templateUrl: '/modules/orgs/client/views/org-add.html',
					controller: 'OrgCreateController',
					controllerAs: 'vm',
					resolve: {
						org: [
							'OrgsService',
							function(OrgsService) {
								return new OrgsService();
							}
						]
					}
				})
				// -------------------------------------------------------------------------
				//
				// org listing. Resolve to all orgs in the system and place that in
				// the scope. listing itself is done through a directive
				//
				// -------------------------------------------------------------------------
				.state('orgs.list', {
					url: '',
					templateUrl: '/modules/orgs/client/views/list-orgs.client.view.html',
					data: {
						pageTitle: 'Orgs List'
					},
					ncyBreadcrumb: {
						label: 'All orgs'
					},
					resolve: {
						orgs: [
							'OrgsService',
							function(OrgsService) {
								return OrgsService.query().$promise;
							}
						]
					},
					controller: 'OrgsListController',
					controllerAs: 'vm'
				})
				// -------------------------------------------------------------------------
				//
				// view an org, resolve the org data
				//
				// -------------------------------------------------------------------------
				.state('orgs.view', {
					url: '/:orgId',
					templateUrl: '/modules/orgs/client/views/org-view.html',
					controller: 'OrgViewController',
					controllerAs: 'vm',
					resolve: {
						org: [
							'$stateParams',
							'OrgsService',
							function($stateParams, OrgsService) {
								return OrgsService.get({
									orgId: $stateParams.orgId
								}).$promise;
							}
						],
						capabilities: [
							'CapabilitiesService',
							function(CapabilitiesService) {
								return CapabilitiesService.query().$promise;
							}
						]
					}
				})
				// -------------------------------------------------------------------------
				//
				// the base for editing
				//
				// -------------------------------------------------------------------------
				.state('orgadmin', {
					abstract: true,
					url: '/orgadmin/:orgId',
					templateUrl: '/modules/orgs/client/views/org-edit.html',
					controller: 'OrgAdminController',
					controllerAs: 'vm',
					resolve: {
						org: [
							'$stateParams',
							'OrgsService',
							function($stateParams, OrgsService) {
								return OrgsService.get({
									orgId: $stateParams.orgId
								}).$promise;
							}
						],
						capabilities: [
							'CapabilitiesService',
							function(CapabilitiesService) {
								return CapabilitiesService.query().$promise;
							}
						]
					},
					data: {
						roles: ['user', 'admin']
					}
				})
				.state('orgadmin.profile', {
					url: '/main',
					templateUrl: '/modules/orgs/client/views/org-main.html',
					controller: 'OrgProfileController',
					controllerAs: 'vm',
					data: {
						pageTitle: 'Company Settings'
					}
				})
				.state('orgadmin.members', {
					url: '/members',
					templateUrl: '/modules/orgs/client/views/org-members.html',
					controller: 'OrgMembersController',
					controllerAs: 'vm',
					data: {
						pageTitle: 'Company Members'
					}
				})
				.state('orgadmin.terms', {
					url: '/terms',
					templateUrl: '/modules/orgs/client/views/org-terms.html',
					controller: 'OrgTermsController',
					controllerAs: 'vm',
					data: {
						pageTitle: 'Company Terms'
					}
				});
		}
	]);
}());
<|endoftext|>


<commit_before>/**
 * Example filters tweets via Streaming API.
 * Raw JSON packets are returned to avoid unwanted parsing overhead
 */

var client = require('../lib/twitter').createClient();

client.setAuth (
    'your consumer key',
    'your consumer secret',
    'some access key',
    'some access secret'
);

var num = 0,
    max = 10;

client.stream( 'statuses/filter', { track: '#sxsw' }, function( json ){
    var tweet = JSON.parse( json );
    if( tweet.text && tweet.user ){
        console.log( tweet.user.screen_name+': "'+tweet.text+'"');
        if( ++num === max ){
            console.log('----');
            client.abort();
        }
    }
} );

<commit_msg>removed complete lie from comment<commit_after>/**
 * Example filters tweets via Streaming API.
 */

var client = require('../lib/twitter').createClient();

client.setAuth (
    'your consumer key',
    'your consumer secret',
    'some access key',
    'some access secret'
);

var num = 0,
    max = 10;

client.stream( 'statuses/filter', { track: '#sxsw' }, function( json ){
    var tweet = JSON.parse( json );
    if( tweet.text && tweet.user ){
        console.log( tweet.user.screen_name+': "'+tweet.text+'"');
        if( ++num === max ){
            console.log('----');
            client.abort();
        }
    }
} );

<|endoftext|>


<commit_before>// cross-browser polyfill
window.URL = window.URL || window.webkitURL;
navigator.getUserMedia = navigator.getUserMedia ||
                         navigator.webkitGetUserMedia ||
                         navigator.mozGetUserMedia;

(function(global, document, navigator) {
  function WebRTC() {}

  // get local stream from user media interface (web-camera, microphone)
  WebRTC.prototype.getUserMedia = function(params, callback) {
    if (!navigator.getUserMedia) throw new Error('getUserMedia() is not supported in your browser');
    var self = this;

    // Additional parameters for Media Constraints
    // http://tools.ietf.org/html/draft-alvestrand-constraints-resolution-00
    /**********************************************
     * googEchoCancellation: true
     * googAutoGainControl: true
     * googNoiseSuppression: true
     * googHighpassFilter: true
     * minWidth: 640
     * minHeight: 480
     * maxWidth: 1280
     * maxHeight: 720
     * minFrameRate: 60
     * maxAspectRatio: 1.333
    **********************************************/
    navigator.getUserMedia(
      params,

      function(stream) {
        self.localStream = stream;
        if (params.elemId)
          self.attachMediaStream(params.elemId, stream, params.options);
        callback(stream, null);
      },

      function(err) {
        callback(null, err);
      }
    );
  };

  // attach media stream to audio/video element
  WebRTC.prototype.attachMediaStream = function(id, stream, options) {
    var elem = document.getElementById(id);
    if (elem) {
      elem.src = global.URL.createObjectURL(stream);
      if (options && options.muted) elem.muted = true;
      if (options && options.mirror) {
        elem.style.webkitTransform = 'scaleX(-1)';
        elem.style.transform = 'scaleX(-1)';
      }
      elem.play();
    }
  };

  // take a screenshot from video stream
  WebRTC.prototype.snapshot = function(id) {
    var video = document.getElementById(id),
        canvas = document.createElement('canvas'),
        context = canvas.getContext('2d');

    if (video) {
      canvas.width = video.clientWidth;
      canvas.height = video.clientHeight;
      if (video.style.transform === 'scaleX(-1)') {
        context.translate(canvas.width, 0);
        context.scale(-1, 1);
      }
      context.drawImage(video, 0, 0, video.clientWidth, video.clientHeight);

      return canvas.toDataURL('image/png');
    }
  };

  // add CSS filters to video stream
  // http://css-tricks.com/almanac/properties/f/filter/
  WebRTC.prototype.filter = function(id, filters) {
    var video = document.getElementById(id);
    if (video) {
      video.style.webkitFilter = filters;
      video.style.filter = filters;
    }
  };

  global.webrtc = new WebRTC;

})(this, document, navigator);
<commit_msg>cross-browser polyfill<commit_after>(function(window, document, navigator) {
  // cross-browser polyfill
  navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia;
  window.RTCPeerConnection = window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection;
  window.RTCSessionDescription = window.RTCSessionDescription || window.mozRTCSessionDescription;
  window.RTCIceCandidate = window.RTCIceCandidate || window.mozRTCIceCandidate;
  window.URL = window.URL || window.webkitURL;

  function WebRTC() {}

  // get local stream from user media interface (web-camera, microphone)
  WebRTC.prototype.getUserMedia = function(params, callback) {
    if (!navigator.getUserMedia) throw new Error('getUserMedia() is not supported in your browser');
    var self = this;

    // Additional parameters for Media Constraints
    // http://tools.ietf.org/html/draft-alvestrand-constraints-resolution-00
    /**********************************************
     * googEchoCancellation: true
     * googAutoGainControl: true
     * googNoiseSuppression: true
     * googHighpassFilter: true
     * minWidth: 640
     * minHeight: 480
     * maxWidth: 1280
     * maxHeight: 720
     * minFrameRate: 60
     * maxAspectRatio: 1.333
    **********************************************/
    navigator.getUserMedia(
      params,

      function(stream) {
        self.localStream = stream;
        if (params.elemId)
          self.attachMediaStream(params.elemId, stream, params.options);
        callback(stream, null);
      },

      function(err) {
        callback(null, err);
      }
    );
  };

  // attach media stream to audio/video element
  WebRTC.prototype.attachMediaStream = function(id, stream, options) {
    var elem = document.getElementById(id);
    if (elem) {
      elem.src = window.URL.createObjectURL(stream);
      if (options && options.muted) elem.muted = true;
      if (options && options.mirror) {
        elem.style.webkitTransform = 'scaleX(-1)';
        elem.style.transform = 'scaleX(-1)';
      }
      elem.play();
    }
  };

  // take a screenshot from video stream
  WebRTC.prototype.snapshot = function(id) {
    var video = document.getElementById(id),
        canvas = document.createElement('canvas'),
        context = canvas.getContext('2d');

    if (video) {
      canvas.width = video.clientWidth;
      canvas.height = video.clientHeight;
      if (video.style.transform === 'scaleX(-1)') {
        context.translate(canvas.width, 0);
        context.scale(-1, 1);
      }
      context.drawImage(video, 0, 0, video.clientWidth, video.clientHeight);

      return canvas.toDataURL('image/png');
    }
  };

  // add CSS filters to video stream
  // http://css-tricks.com/almanac/properties/f/filter/
  WebRTC.prototype.filter = function(id, filters) {
    var video = document.getElementById(id);
    if (video) {
      video.style.webkitFilter = filters;
      video.style.filter = filters;
    }
  };

  window.webrtc = new WebRTC;

})(this, document, navigator);
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the MIT license
 * If a copy of the MIT license was not distributed with this file, you can
 * obtain one at https://raw.github.com/mozilla/butter/master/LICENSE */

define( [ "core/trackevent", "core/track", "core/eventmanager",
          "./track-container", "util/scrollbars", "./timebar",
          "./status", "./trackhandles", "./super-scrollbar",
          "util/lang", "text!layouts/media-instance.html" ],
  function( TrackEvent, Track, EventManager,
            TrackContainer, Scrollbars, TimeBar,
            Status, TrackHandles, SuperScrollbar,
            LangUtils, MEDIA_INSTANCE_LAYOUT ) {

  var DEFAULT_BOUNDS = [ 0, 0.5 ];

  function MediaInstance( butter, media ) {

    var _bounds = DEFAULT_BOUNDS;

    function setContainerBounds( left, right ) {
      if ( _bounds[0] !== left || _bounds[1] !== right ) {
        _bounds = [ left, right ];
        _tracksContainer.setViewportBounds( left, right );
        updateUI();
      }
    }

    var _this = this,
        _media = media,
        _rootElement = LangUtils.domFragment( MEDIA_INSTANCE_LAYOUT, ".media-instance" ),
        _tracksContainer = new TrackContainer( butter, media, _rootElement ),
        _container = _rootElement.querySelector( ".media-container" ),
        _superScrollbar = new SuperScrollbar( _tracksContainer.element, _tracksContainer.container, setContainerBounds, _media ),
        _vScrollBar = new Scrollbars.Vertical( _tracksContainer.element, _tracksContainer.container ),
        _timebar = new TimeBar( butter, _media, butter.ui.tray.statusArea, _tracksContainer ),
        _trackHandles = new TrackHandles( butter, _media, _rootElement, _tracksContainer ),
        _trackEventHighlight = butter.config.value( "ui" ).trackEventHighlight || "click",
        _status;

    _status = new Status( _media, butter.ui.tray.statusArea );

    _tracksContainer.setVerticalScrollbar( _vScrollBar );

    EventManager.extend( _this );

    function onEditorToggled( e ) {
      _tracksContainer.update();
      _timebar.update();
      _superScrollbar.resize();
    }

    window.addEventListener( "resize", function() {
      _vScrollBar.update();
      _timebar.update();
      _superScrollbar.resize();
    }, false );

    function onMediaTimeUpdate() {
      // Move the viewport to be centered around the scrubber
      _tracksContainer.followCurrentTime();
      // Align the timebar again to remove jitter
      // TODO: this is expensive, and only fixes 50% of the problem
      _timebar.update();
    }

    _media.listen( "mediaplay", function(){
      // Make sure the viewport contains the scrubber
      _tracksContainer.snapTo( _media.currentTime );
      // Listen for timeupdate to attempt to center the viewport around the scrubber
      _media.listen( "mediatimeupdate", onMediaTimeUpdate );
    });

    _media.listen( "mediapause", function(){
      // Make sure the viewport contains the scrubber
      _tracksContainer.snapTo( _media.currentTime );
      // Stop listening for timeupdates so that the user can scroll around freely
      _media.unlisten( "mediatimeupdate", onMediaTimeUpdate );
    });

    function blinkTarget( target ){
      if( target !== _media.target ){
        target = butter.getTargetByType( "elementID", target );
        if( target ){
          target.view.blink();
        }
      }
      else {
        _media.view.blink();
      }
    }

    function onTrackEventMouseOver( e ){
      var trackEvent = e.trackEvent,
          corn = trackEvent.popcornOptions;

      if( corn.target ){
        blinkTarget( corn.target );
      }
    }

    function onTrackEventMouseDown( e ) {
      var trackEvent = e.data.trackEvent,
          tracks, i, length,
          wasSelected = trackEvent.selected,
          originalEvent = e.data.originalEvent;

      if ( !originalEvent.shiftKey && !trackEvent.selected ) {
        tracks = _media.tracks;
        for ( i = 0, length = tracks.length; i < length; i++ ) {
          tracks[ i ].deselectEvents( trackEvent );
        }
      }

      trackEvent.selected = true;

      function onTrackEventMouseUp() {
        window.removeEventListener( "mouseup", onTrackEventMouseUp, false );
        window.removeEventListener( "mousemove", onTrackEventDragStarted, false );

        if ( !originalEvent.shiftKey ) {
          tracks = _media.tracks;
          for ( i = 0, length = tracks.length; i < length; i++ ) {
            tracks[ i ].deselectEvents( trackEvent );
          }
        } else if ( trackEvent.selected && wasSelected ) {
          trackEvent.selected = false;
        }
      }

      function onTrackEventDragStarted() {
        window.removeEventListener( "mousemove", onTrackEventDragStarted, false );
        window.removeEventListener( "mouseup", onTrackEventMouseUp, false );
      }

      window.addEventListener( "mouseup", onTrackEventMouseUp, false );
      window.addEventListener( "mousemove", onTrackEventDragStarted, false );
    }

    function onMediaReady(){
      _bounds = DEFAULT_BOUNDS;
      _tracksContainer.setViewportBounds( _bounds[ 0 ], _bounds[ 1 ] );
      updateUI();
      _timebar.enable();
      _media.currentTime = 0;
    }

    function onMediaReadyFirst(){
      _media.unlisten( "mediaready", onMediaReadyFirst );
      _media.listen( "mediaready", onMediaReady );

      _container.appendChild( _tracksContainer.element );
      _rootElement.appendChild( _superScrollbar.element );
      _container.appendChild( _vScrollBar.element );
      _rootElement.appendChild( _trackHandles.element );

      butter.ui.tray.setMediaInstance( _rootElement );

      _media.listen( "trackeventremoved", function( e ){
        var trackEvent = e.data;
        trackEvent.view.unlisten( "trackeventmousedown", onTrackEventMouseDown );
        if( _trackEventHighlight === "hover" ){
          trackEvent.view.unlisten( "trackeventmouseover", onTrackEventMouseOver );
        }
      });

      function onTrackEventAdded( e ){
        var trackEvent = e.data;
        trackEvent.view.listen( "trackeventmousedown", onTrackEventMouseDown );
        trackEvent.view.element.addEventListener( "click", function( e ) {
          butter.editor.editTrackEvent( trackEvent );
        });
        if( _trackEventHighlight === "hover" ){
          trackEvent.view.listen( "trackeventmouseover", onTrackEventMouseOver );
        }
      }

      function onTrackAdded( e ){
        var track = e.data;
        track.view.listen( "plugindropped", onPluginDropped );
        track.view.listen( "trackeventmousedown", onTrackEventMouseDown );
        if( _trackEventHighlight === "hover" ){
          track.view.listen( "trackeventmouseover", onTrackEventMouseOver );
        }

        var existingEvents = track.trackEvents;
        for( var i=0; i<existingEvents.length; ++i ){
          onTrackEventAdded({
            data: existingEvents[ i ]
          });
        }

      }

      var existingTracks = _media.tracks;
      for( var i=0; i<existingTracks.length; ++i ){
        onTrackAdded({
          data: existingTracks[ i ]
        });
      }

      _media.listen( "trackadded", onTrackAdded );
      _media.listen( "trackeventadded", onTrackEventAdded );

      _media.listen( "trackremoved", function( e ){
        var track = e.data;
        track.view.unlisten( "plugindropped", onPluginDropped );
        track.view.unlisten( "trackeventmousedown", onTrackEventMouseDown );
        if( _trackEventHighlight === "hover" ){
          track.view.unlisten( "trackeventmouseover", onTrackEventMouseOver );
        }
      });

      _superScrollbar.initialize();
      onMediaReady();
    }

    _media.listen( "mediaready", onMediaReadyFirst );

    butter.editor.listen( "editortoggled", onEditorToggled );
    butter.listen( "editoropened", onEditorToggled );
    _media.listen( "mediacontentchanged", _timebar.disable );

    function onPluginDropped( e ) {
      var type = e.data.type,
          track = e.data.track,
          start = e.data.start,
          trackEvent;

      if ( _media.ready ) {
        trackEvent = butter.generateSafeTrackEvent( type, start, track );
        butter.editor.editTrackEvent( trackEvent );
      }
    }

    this.destroy = function() {
      if ( _rootElement.parentNode ) {
        _rootElement.parentNode.removeChild( _rootElement );
      }
      butter.editor.unlisten( "editortoggled", onEditorToggled );
      butter.unlisten( "editoropened", onEditorToggled );
    };

    this.hide = function() {
      _rootElement.style.display = "none";
    };

    this.show = function() {
      _rootElement.style.display = "block";
    };

    function updateUI() {
      if( _media.duration ){
        _tracksContainer.update();
        _timebar.update();
        _vScrollBar.update();
        _superScrollbar.update();
        _trackHandles.update();
      }
    }

    butter.listen( "ready", function(){
      updateUI();
    });

    this.trackContainer = _tracksContainer;
    this.element = _rootElement;
    this.media = _media;
  }

  return MediaInstance;

});

<commit_msg>[#2937] Remove option for trackevent highlighting on hover and deadcode surrounding it<commit_after>/* This Source Code Form is subject to the terms of the MIT license
 * If a copy of the MIT license was not distributed with this file, you can
 * obtain one at https://raw.github.com/mozilla/butter/master/LICENSE */

define( [ "core/trackevent", "core/track", "core/eventmanager",
          "./track-container", "util/scrollbars", "./timebar",
          "./status", "./trackhandles", "./super-scrollbar",
          "util/lang", "text!layouts/media-instance.html" ],
  function( TrackEvent, Track, EventManager,
            TrackContainer, Scrollbars, TimeBar,
            Status, TrackHandles, SuperScrollbar,
            LangUtils, MEDIA_INSTANCE_LAYOUT ) {

  var DEFAULT_BOUNDS = [ 0, 0.5 ];

  function MediaInstance( butter, media ) {

    var _bounds = DEFAULT_BOUNDS;

    function setContainerBounds( left, right ) {
      if ( _bounds[0] !== left || _bounds[1] !== right ) {
        _bounds = [ left, right ];
        _tracksContainer.setViewportBounds( left, right );
        updateUI();
      }
    }

    var _this = this,
        _media = media,
        _rootElement = LangUtils.domFragment( MEDIA_INSTANCE_LAYOUT, ".media-instance" ),
        _tracksContainer = new TrackContainer( butter, media, _rootElement ),
        _container = _rootElement.querySelector( ".media-container" ),
        _superScrollbar = new SuperScrollbar( _tracksContainer.element, _tracksContainer.container, setContainerBounds, _media ),
        _vScrollBar = new Scrollbars.Vertical( _tracksContainer.element, _tracksContainer.container ),
        _timebar = new TimeBar( butter, _media, butter.ui.tray.statusArea, _tracksContainer ),
        _trackHandles = new TrackHandles( butter, _media, _rootElement, _tracksContainer ),
        _status;

    _status = new Status( _media, butter.ui.tray.statusArea );

    _tracksContainer.setVerticalScrollbar( _vScrollBar );

    EventManager.extend( _this );

    function onEditorToggled( e ) {
      _tracksContainer.update();
      _timebar.update();
      _superScrollbar.resize();
    }

    window.addEventListener( "resize", function() {
      _vScrollBar.update();
      _timebar.update();
      _superScrollbar.resize();
    }, false );

    function onMediaTimeUpdate() {
      // Move the viewport to be centered around the scrubber
      _tracksContainer.followCurrentTime();
      // Align the timebar again to remove jitter
      // TODO: this is expensive, and only fixes 50% of the problem
      _timebar.update();
    }

    _media.listen( "mediaplay", function(){
      // Make sure the viewport contains the scrubber
      _tracksContainer.snapTo( _media.currentTime );
      // Listen for timeupdate to attempt to center the viewport around the scrubber
      _media.listen( "mediatimeupdate", onMediaTimeUpdate );
    });

    _media.listen( "mediapause", function(){
      // Make sure the viewport contains the scrubber
      _tracksContainer.snapTo( _media.currentTime );
      // Stop listening for timeupdates so that the user can scroll around freely
      _media.unlisten( "mediatimeupdate", onMediaTimeUpdate );
    });

    function onTrackEventMouseDown( e ){
      var trackEvent = e.data.trackEvent,
          tracks, i, length,
          wasSelected = trackEvent.selected,
          originalEvent = e.data.originalEvent;

      if ( !originalEvent.shiftKey && !trackEvent.selected ) {
        tracks = _media.tracks;
        for ( i = 0, length = tracks.length; i < length; i++ ) {
          tracks[ i ].deselectEvents( trackEvent );
        }
      }

      trackEvent.selected = true;

      function onTrackEventMouseUp() {
        window.removeEventListener( "mouseup", onTrackEventMouseUp, false );
        window.removeEventListener( "mousemove", onTrackEventDragStarted, false );

        if ( !originalEvent.shiftKey ) {
          tracks = _media.tracks;
          for ( i = 0, length = tracks.length; i < length; i++ ) {
            tracks[ i ].deselectEvents( trackEvent );
          }
        } else if ( trackEvent.selected && wasSelected ) {
          trackEvent.selected = false;
        }
      }

      function onTrackEventDragStarted() {
        window.removeEventListener( "mousemove", onTrackEventDragStarted, false );
        window.removeEventListener( "mouseup", onTrackEventMouseUp, false );
      }

      window.addEventListener( "mouseup", onTrackEventMouseUp, false );
      window.addEventListener( "mousemove", onTrackEventDragStarted, false );
    }

    function onMediaReady(){
      _bounds = DEFAULT_BOUNDS;
      _tracksContainer.setViewportBounds( _bounds[ 0 ], _bounds[ 1 ] );
      updateUI();
      _timebar.enable();
      _media.currentTime = 0;
    }

    function onMediaReadyFirst(){
      _media.unlisten( "mediaready", onMediaReadyFirst );
      _media.listen( "mediaready", onMediaReady );

      _container.appendChild( _tracksContainer.element );
      _rootElement.appendChild( _superScrollbar.element );
      _container.appendChild( _vScrollBar.element );
      _rootElement.appendChild( _trackHandles.element );

      butter.ui.tray.setMediaInstance( _rootElement );

      _media.listen( "trackeventremoved", function( e ){
        var trackEvent = e.data;
        trackEvent.view.unlisten( "trackeventmousedown", onTrackEventMouseDown );
      });

      function onTrackEventAdded( e ){
        var trackEvent = e.data;
        trackEvent.view.listen( "trackeventmousedown", onTrackEventMouseDown );
        trackEvent.view.element.addEventListener( "click", function( e ) {
          butter.editor.editTrackEvent( trackEvent );
        });
      }

      function onTrackAdded( e ){
        var track = e.data;
        track.view.listen( "plugindropped", onPluginDropped );
        track.view.listen( "trackeventmousedown", onTrackEventMouseDown );

        var existingEvents = track.trackEvents;
        for( var i=0; i<existingEvents.length; ++i ){
          onTrackEventAdded({
            data: existingEvents[ i ]
          });
        }

      }

      var existingTracks = _media.tracks;
      for( var i=0; i<existingTracks.length; ++i ){
        onTrackAdded({
          data: existingTracks[ i ]
        });
      }

      _media.listen( "trackadded", onTrackAdded );
      _media.listen( "trackeventadded", onTrackEventAdded );

      _media.listen( "trackremoved", function( e ){
        var track = e.data;
        track.view.unlisten( "plugindropped", onPluginDropped );
        track.view.unlisten( "trackeventmousedown", onTrackEventMouseDown );
      });

      _superScrollbar.initialize();
      onMediaReady();
    }

    _media.listen( "mediaready", onMediaReadyFirst );

    butter.editor.listen( "editortoggled", onEditorToggled );
    butter.listen( "editoropened", onEditorToggled );
    _media.listen( "mediacontentchanged", _timebar.disable );

    function onPluginDropped( e ) {
      var type = e.data.type,
          track = e.data.track,
          start = e.data.start,
          trackEvent;

      if ( _media.ready ) {
        trackEvent = butter.generateSafeTrackEvent( type, start, track );
        butter.editor.editTrackEvent( trackEvent );
      }
    }

    this.destroy = function() {
      if ( _rootElement.parentNode ) {
        _rootElement.parentNode.removeChild( _rootElement );
      }
      butter.editor.unlisten( "editortoggled", onEditorToggled );
      butter.unlisten( "editoropened", onEditorToggled );
    };

    this.hide = function() {
      _rootElement.style.display = "none";
    };

    this.show = function() {
      _rootElement.style.display = "block";
    };

    function updateUI() {
      if( _media.duration ){
        _tracksContainer.update();
        _timebar.update();
        _vScrollBar.update();
        _superScrollbar.update();
        _trackHandles.update();
      }
    }

    butter.listen( "ready", function(){
      updateUI();
    });

    this.trackContainer = _tracksContainer;
    this.element = _rootElement;
    this.media = _media;
  }

  return MediaInstance;

});

<|endoftext|>


<commit_before>// Example file. Copy this to your project. Change then names of the referenced files or comment them out.
// Convention is to name sass partials to start with an "_"
module.exports = {
  verbose: true, // Set to true to show diagnostic information

  // IMPORTANT: Set next two configuration so you can customize
  // bootstrapCustomizations: gets loaded before bootstrap so you can configure the variables used by bootstrap
  // mainSass: gets loaded after bootstrap, so you can override a bootstrap style.
  // NOTE, these are optional.

  // Use preBootstrapCustomizations to change $brand-primary. Ensure this preBootstrapCustomizations does not
  // depend on other bootstrap variables.
  preBootstrapCustomizations: "./_pre-bootstrap-customizations.scss",

  // Use bootstrapCustomizations to utilize other sass variables defined in preBootstrapCustomizations or the
  // _variables.scss file. This is useful to set one customization value based on another value.
  bootstrapCustomizations: "./_bootstrap-customizations.scss",

  mainSass: "./_main.scss",

  // Default for the style loading
  styleLoader: "style-loader!css-loader!sass-loader",
  //
  // If you want to use the ExtractTextPlugin
  //   and you want compressed
  //     styleLoader: ExtractTextPlugin.extract("style-loader", "css-loader!sass-loader"),
  //
  // If you want expanded CSS
  //   styleLoader: ExtractTextPlugin.extract("style-loader", "css-loader!sass?outputStyle=expanded"),

  scripts: {
    "transition": true,
    "alert": true,
    "button": true,
    "carousel": true,
    "collapse": true,
    "dropdown": true,
    "modal": true,
    "tooltip": true,
    "popover": true,
    "scrollspy": true,
    "tab": true,
    "affix": true
  },
  styles: {
    "mixins": true,

    "normalize": true,
    "print": true,
    "glyphicons": true,

    "scaffolding": true,
    "type": true,
    "code": true,
    "grid": true,
    "tables": true,
    "forms": true,
    "buttons": true,

    "component-animations": true,
    "dropdowns": true,
    "button-groups": true,
    "input-groups": true,
    "navs": true,
    "navbar": true,
    "breadcrumbs": true,
    "pagination": true,
    "pager": true,
    "labels": true,
    "badges": true,
    "jumbotron": true,
    "thumbnails": true,
    "alerts": true,
    "progress-bars": true,
    "media": true,
    "list-group": true,
    "panels": true,
    "wells": true,
    "responsive-embed": true,
    "close": true,

    "modals": true,
    "tooltip": true,
    "popovers": true,
    "carousel": true,

    "utilities": true,
    "responsive-utilities": true
  }
};

<commit_msg>Reverted to the use of single quotes instead of double ones<commit_after>// Example file. Copy this to your project. Change then names of the referenced files or comment them out.
// Convention is to name sass partials to start with an "_"
module.exports = {
  verbose: true, // Set to true to show diagnostic information

  // IMPORTANT: Set next two configuration so you can customize
  // bootstrapCustomizations: gets loaded before bootstrap so you can configure the variables used by bootstrap
  // mainSass: gets loaded after bootstrap, so you can override a bootstrap style.
  // NOTE, these are optional.

  // Use preBootstrapCustomizations to change $brand-primary. Ensure this preBootstrapCustomizations does not
  // depend on other bootstrap variables.
  preBootstrapCustomizations: "./_pre-bootstrap-customizations.scss",

  // Use bootstrapCustomizations to utilize other sass variables defined in preBootstrapCustomizations or the
  // _variables.scss file. This is useful to set one customization value based on another value.
  bootstrapCustomizations: "./_bootstrap-customizations.scss",

  mainSass: "./_main.scss",

  // Default for the style loading
  styleLoader: "style-loader!css-loader!sass-loader",
  //
  // If you want to use the ExtractTextPlugin
  //   and you want compressed
  //     styleLoader: ExtractTextPlugin.extract("style-loader", "css-loader!sass-loader"),
  //
  // If you want expanded CSS
  //   styleLoader: ExtractTextPlugin.extract("style-loader", "css-loader!sass?outputStyle=expanded"),

  scripts: {
    'transition': true,
    'alert': true,
    'button': true,
    'carousel': true,
    'collapse': true,
    'dropdown': true,
    'modal': true,
    'tooltip': true,
    'popover': true,
    'scrollspy': true,
    'tab': true,
    'affix': true
  },
  styles: {
    "mixins": true,

    "normalize": true,
    "print": true,
    "glyphicons": true,

    "scaffolding": true,
    "type": true,
    "code": true,
    "grid": true,
    "tables": true,
    "forms": true,
    "buttons": true,

    "component-animations": true,
    "dropdowns": true,
    "button-groups": true,
    "input-groups": true,
    "navs": true,
    "navbar": true,
    "breadcrumbs": true,
    "pagination": true,
    "pager": true,
    "labels": true,
    "badges": true,
    "jumbotron": true,
    "thumbnails": true,
    "alerts": true,
    "progress-bars": true,
    "media": true,
    "list-group": true,
    "panels": true,
    "wells": true,
    "responsive-embed": true,
    "close": true,

    "modals": true,
    "tooltip": true,
    "popovers": true,
    "carousel": true,

    "utilities": true,
    "responsive-utilities": true
  }
};

<|endoftext|>


<commit_before>/*******************************************************************************
 * @license
 * Copyright (c) 2013 VMware, Inc. All Rights Reserved.
 * THIS FILE IS PROVIDED UNDER THE TERMS OF THE ECLIPSE PUBLIC LICENSE
 * ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS FILE
 * CONSTITUTES RECIPIENTS ACCEPTANCE OF THE AGREEMENT.
 * You can obtain a current copy of the Eclipse Public License from
 * http://www.opensource.org/licenses/eclipse-1.0.php
 *
 * Contributors:
 *   Kris De Volder
 ******************************************************************************/

//
// On cloudfoundry this module
//  1) replaces the handling of the '/' url.
//  2) adds some 'user tracking' middleware
//

var pathJoin = require('../jsdepend/utils').pathJoin;
var when = require('when');
var mongo = require('../mongo'); //TODO: inject rather than import database instance
var glob = require('../utils/path-glob');

var users = mongo.collection('users');

/**
 * Creates an error function in the context of a given http response object.
 * The error fun may attache error info to the response.
 */
function errorFun(res) {
	function error(err) {
		console.error(err);
		if (err.stack) {
			console.error(err.stack);
		}
		//Only logging errors now, don't reject requests just because
		//there's probably a bug or resource limit problem with user tracking.

//		res.status(500);
//		res.header('Content-Type', 'text/plain');
//		res.write(""+err);
//		if (err.stack) {
//			res.write(""+err.stack);
//		}
//		res.end();
	}
	return error;
}

//TODO: this cooky stuff should really be done as a connect
// middleware on every access not just on access to the 'root' path
// of the webserver.

exports.install = function (app, filesystem) {

	var getUserHome = filesystem.getUserHome;
	var isDirectory = filesystem.isDirectory;
	var mkdir = filesystem.mkdir;
	var copyDir = filesystem.copyDir;
	var exists = filesystem.exists;

	function getUserPath(userID) {
		return pathJoin(getUserHome(), userID);
	}

// Discontinued for now. We will only show a read-only sample now.
//
//	function createUserArea(userID) {
//		var path = getUserPath(userID);
//		return isDirectory(path).then(function (isDir) {
//			if (isDir) {
//				//already got a user-area
//				return;
//			}
//			//must create user area
//			return copyDir('/sample', path);
//		});
//	}

	function randomString(len) {
		var chars = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		var str = "";
		for (var i = 0; i < len; i++) {
			var code = Math.floor(Math.random()*chars.length);
			str = str + chars[code];
		}
		return str;
	}

	function generateUserID(tries) {
		tries = tries || 0;
		var id = randomString(10);
		return createUser(id).then(function () {
			console.log('User created: '+id);
			return id; //Yeah! Found one that's still available.
		}, function (err) {
			console.log('Faile to create User: '+id);
			console.err(err);
			if (++tries < 10) {
				return generateUserID(tries);
			} else {
				//Can't find a free 'private' user id. Use the 'shared' ID.
				return 'shared';
			}
		});
	}

	function recordVisitor(id) {
		console.log('Recording visit: '+id);
		//Ignoring any errors about creating duplicate ids
		return users.then(function (users) {
			return mongo.findAndModify(users,
				//Criteria:
				{_id: id},
				//Sort:
				[['_id','asc']],
				//Update:
				{
					'$inc' : { visits: 1 },
					'$set' : { lastVisit: new Date()}
				},
				//Options:
				{ upsert: true, 'new': true }
			).then(function (user) {
				console.log('Visit recorded: '+JSON.stringify(user, null, '  '));
				return user;
			});
		});
	}

	function createUser(id) {
		return users.then(function (users) {
			//The insert call below will reject when the user id already exists.
			return mongo.insert(users, {
				_id: id,
				created: new Date()
			}).then(function () {return id;});
		});
	}

	/**
	 * When one of these paths gets hit we create user tracking cookies.
	 */
	var trackedPaths = glob.fromJson([
		'/', '/editor/**'
	]);

	function trackUsers(req, res, next) {
		var shouldTrack = trackedPaths.test(req.path);
		console.log('trackUsers ['+shouldTrack+'] '+req.path);
		if (shouldTrack) {
			var userID = req.cookies.userID;
			console.log('cookie userID = '+userID);
			if (!userID) {
				userID = generateUserID();
			}
			//Yes... its deliberate we are doing next sep asyncly
			// (i.e. we aren't waiting for success to proceed).
			when(userID, recordVisitor).otherwise(errorFun(res));
			when(userID, function (userID) {
				res.cookie('userID', userID, {
					maxAge: 365 * 24 * 3600 * 1000 /*expires in one year*/
				});
	//			createUserArea(userID).then(function () {
	//				res.redirect('/editor'+getUserHome()+'/'+userID);
	//			});
			}).otherwise(errorFun(res));
		}
		next();
	}

	app.use(trackUsers);

	// Change the redirect target for the '/' path to point to the
	// sample project.
	app.get('/', function (req, res) {
		res.redirect('/editor/home/sample');
	});

};<commit_msg>Cleanup: logging<commit_after>/*******************************************************************************
 * @license
 * Copyright (c) 2013 VMware, Inc. All Rights Reserved.
 * THIS FILE IS PROVIDED UNDER THE TERMS OF THE ECLIPSE PUBLIC LICENSE
 * ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THIS FILE
 * CONSTITUTES RECIPIENTS ACCEPTANCE OF THE AGREEMENT.
 * You can obtain a current copy of the Eclipse Public License from
 * http://www.opensource.org/licenses/eclipse-1.0.php
 *
 * Contributors:
 *   Kris De Volder
 ******************************************************************************/

//
// On cloudfoundry this module
//  1) replaces the handling of the '/' url.
//  2) adds some 'user tracking' middleware
//

var pathJoin = require('../jsdepend/utils').pathJoin;
var when = require('when');
var mongo = require('../mongo'); //TODO: inject rather than import database instance
var glob = require('../utils/path-glob');

var users = mongo.collection('users');

/**
 * Creates an error function in the context of a given http response object.
 * The error fun may attache error info to the response.
 */
function errorFun(res) {
	function error(err) {
		console.error(err);
		if (err.stack) {
			console.error(err.stack);
		}
		//Only logging errors now, don't reject requests just because
		//there's probably a bug or resource limit problem with user tracking.

//		res.status(500);
//		res.header('Content-Type', 'text/plain');
//		res.write(""+err);
//		if (err.stack) {
//			res.write(""+err.stack);
//		}
//		res.end();
	}
	return error;
}

//TODO: this cooky stuff should really be done as a connect
// middleware on every access not just on access to the 'root' path
// of the webserver.

exports.install = function (app, filesystem) {

	var getUserHome = filesystem.getUserHome;
	var isDirectory = filesystem.isDirectory;
	var mkdir = filesystem.mkdir;
	var copyDir = filesystem.copyDir;
	var exists = filesystem.exists;

	function getUserPath(userID) {
		return pathJoin(getUserHome(), userID);
	}

// Discontinued for now. We will only show a read-only sample now.
//
//	function createUserArea(userID) {
//		var path = getUserPath(userID);
//		return isDirectory(path).then(function (isDir) {
//			if (isDir) {
//				//already got a user-area
//				return;
//			}
//			//must create user area
//			return copyDir('/sample', path);
//		});
//	}

	function randomString(len) {
		var chars = "abcdefghijklmnopqrstuvwxyz01234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		var str = "";
		for (var i = 0; i < len; i++) {
			var code = Math.floor(Math.random()*chars.length);
			str = str + chars[code];
		}
		return str;
	}

	function generateUserID(tries) {
		tries = tries || 0;
		var id = randomString(10);
		return createUser(id).then(function () {
			console.log('User created: '+id);
			return id; //Yeah! Found one that's still available.
		}, function (err) {
			console.log('Faile to create User: '+id);
			console.err(err);
			if (++tries < 10) {
				return generateUserID(tries);
			} else {
				//Can't find a free 'private' user id. Use the 'shared' ID.
				return 'shared';
			}
		});
	}

	function recordVisitor(id) {
		console.log('Recording visit: '+id);
		//Ignoring any errors about creating duplicate ids
		return users.then(function (users) {
			return mongo.findAndModify(users,
				//Criteria:
				{_id: id},
				//Sort:
				[['_id','asc']],
				//Update:
				{
					'$inc' : { visits: 1 },
					'$set' : { lastVisit: new Date()}
				},
				//Options:
				{ upsert: true, 'new': true }
			).then(function (user) {
				console.log('Visit recorded: '+JSON.stringify(user[0]));
				return user;
			});
		});
	}

	function createUser(id) {
		return users.then(function (users) {
			//The insert call below will reject when the user id already exists.
			return mongo.insert(users, {
				_id: id,
				created: new Date()
			}).then(function () {return id;});
		});
	}

	/**
	 * When one of these paths gets hit we create user tracking cookies.
	 */
	var trackedPaths = glob.fromJson([
		'/', '/editor/**'
	]);

	function trackUsers(req, res, next) {
		var shouldTrack = trackedPaths.test(req.path);
//		console.log('trackUsers ['+shouldTrack+'] '+req.path);
		if (shouldTrack) {
			var userID = req.cookies.userID;
			console.log('cookie userID = '+userID);
			if (!userID) {
				userID = generateUserID();
			}
			//Yes... its deliberate we are doing next sep asyncly
			// (i.e. we aren't waiting for success to proceed).
			when(userID, recordVisitor).otherwise(errorFun(res));
			when(userID, function (userID) {
				res.cookie('userID', userID, {
					maxAge: 365 * 24 * 3600 * 1000 /*expires in one year*/
				});
	//			createUserArea(userID).then(function () {
	//				res.redirect('/editor'+getUserHome()+'/'+userID);
	//			});
			}).otherwise(errorFun(res));
		}
		next();
	}

	app.use(trackUsers);

	// Change the redirect target for the '/' path to point to the
	// sample project.
	app.get('/', function (req, res) {
		res.redirect('/editor/home/sample');
	});

};<|endoftext|>


<commit_before>define([
	'dojo/_base/declare',
	'dojo/dom-construct',
	'dgrid/_StoreMixin'
], function (declare, domConstruct, _StoreMixin) {
	return declare(_StoreMixin, {
		// summary:
		//		dgrid mixin which implements the refresh method to
		//		always perform a single query with no start or count
		//		specified, to retrieve all relevant results at once.
		//		Appropriate for grids using memory stores with small
		//		result set sizes.

		refresh: function () {
			var self = this;

			// First defer to List#refresh to clear the grid's
			// previous content
			this.inherited(arguments);

			if (!this._renderedCollection) {
				return;
			}

			return this._trackError(function () {
				var loadingNode = self.loadingNode = domConstruct.create('div', {
					className: 'dgrid-loading',
					innerHTML: self.loadingMessage
				}, self.contentNode);

				var queryResults = self._renderedCollection.fetch();

				queryResults.totalLength.then(function (total) {
					// Record total so it can be retrieved later via get('total')
					self._total = total;

					if (!total) {
						self._insertNoDataNode();
					}
				});

				queryResults.always(function () {
					domConstruct.destroy(loadingNode);
					self.loadingNode = null;
				});

				return self.renderQueryResults(queryResults).then(function (rows) {
					self._emitRefreshComplete();
					return rows;
				});
			});
		},

		renderArray: function () {
			var rows = this.inherited(arguments);

			// Clear _lastCollection which is ordinarily only used for store-less grids
			this._lastCollection = null;

			return rows;
		}
	});
});
<commit_msg>Change an absolute mid to a relative one. Closes #1340<commit_after>define([
	'dojo/_base/declare',
	'dojo/dom-construct',
	'../_StoreMixin'
], function (declare, domConstruct, _StoreMixin) {
	return declare(_StoreMixin, {
		// summary:
		//		dgrid mixin which implements the refresh method to
		//		always perform a single query with no start or count
		//		specified, to retrieve all relevant results at once.
		//		Appropriate for grids using memory stores with small
		//		result set sizes.

		refresh: function () {
			var self = this;

			// First defer to List#refresh to clear the grid's
			// previous content
			this.inherited(arguments);

			if (!this._renderedCollection) {
				return;
			}

			return this._trackError(function () {
				var loadingNode = self.loadingNode = domConstruct.create('div', {
					className: 'dgrid-loading',
					innerHTML: self.loadingMessage
				}, self.contentNode);

				var queryResults = self._renderedCollection.fetch();

				queryResults.totalLength.then(function (total) {
					// Record total so it can be retrieved later via get('total')
					self._total = total;

					if (!total) {
						self._insertNoDataNode();
					}
				});

				queryResults.always(function () {
					domConstruct.destroy(loadingNode);
					self.loadingNode = null;
				});

				return self.renderQueryResults(queryResults).then(function (rows) {
					self._emitRefreshComplete();
					return rows;
				});
			});
		},

		renderArray: function () {
			var rows = this.inherited(arguments);

			// Clear _lastCollection which is ordinarily only used for store-less grids
			this._lastCollection = null;

			return rows;
		}
	});
});
<|endoftext|>


<commit_before>"use strict";

var timeago = function() {

  var o = {
    second: 1000,
    minute: 60 * 1000,
    hour: 60 * 1000 * 60,
    day: 24 * 60 * 1000 * 60,
    week: 7 * 24 * 60 * 1000 * 60,
    month: 30 * 24 * 60 * 1000 * 60,
    year: 365 * 24 * 60 * 1000 * 60
  };
  var obj = {};

  obj.ago = function(nd, s) {
    var r = Math.round,
      pl = function(v, n) {
        return (s === undefined) ? n + ' ' + v + (n > 1 ? 's' : '') + ' ago' : n + v.substring(0, 1)
      },
      ts = new Date().getTime() - new Date(nd).getTime(),
      ii;
    for (var i in o) {
      if (r(ts) < o[i]) return pl(ii || 'm', r(ts / (o[ii] || 1)))
      ii = i;
    }
    return pl(i, r(ts / o[i]));
  }

  obj.today = function() {
    var now = new Date();
    var Weekday = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
    var Month = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
    return Weekday[now.getDay()] + ", " + Month[now.getMonth()] + " " + now.getDate() + ", " + now.getFullYear();
  }

  obj.timefriendly = function(s) {
    var t = s.match(/(\d).([a-z]*?)s?$/);
    return t[1] * eval(o[t[2]]);
  }

  obj.mintoread = function(text, altcmt, wpm) {
    var m = Math.round(text.split(' ').length / (wpm || 200));
    return (m || '< 1') + (altcmt || ' min to read');
  }

  return obj;
}

if (typeof module !== 'undefined' && module.exports)
  module.exports = timeago;
<commit_msg>Get current datetime faster<commit_after>"use strict";

var timeago = function() {

  var o = {
    second: 1000,
    minute: 60 * 1000,
    hour: 60 * 1000 * 60,
    day: 24 * 60 * 1000 * 60,
    week: 7 * 24 * 60 * 1000 * 60,
    month: 30 * 24 * 60 * 1000 * 60,
    year: 365 * 24 * 60 * 1000 * 60
  };
  var obj = {};

  obj.ago = function(nd, s) {
    var r = Math.round,
      pl = function(v, n) {
        return (s === undefined) ? n + ' ' + v + (n > 1 ? 's' : '') + ' ago' : n + v.substring(0, 1)
      },
      ts = Date.now() - new Date(nd).getTime(),
      ii;
    for (var i in o) {
      if (r(ts) < o[i]) return pl(ii || 'm', r(ts / (o[ii] || 1)))
      ii = i;
    }
    return pl(i, r(ts / o[i]));
  }

  obj.today = function() {
    var now = new Date();
    var Weekday = new Array("Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday");
    var Month = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
    return Weekday[now.getDay()] + ", " + Month[now.getMonth()] + " " + now.getDate() + ", " + now.getFullYear();
  }

  obj.timefriendly = function(s) {
    var t = s.match(/(\d).([a-z]*?)s?$/);
    return t[1] * eval(o[t[2]]);
  }

  obj.mintoread = function(text, altcmt, wpm) {
    var m = Math.round(text.split(' ').length / (wpm || 200));
    return (m || '< 1') + (altcmt || ' min to read');
  }

  return obj;
}

if (typeof module !== 'undefined' && module.exports)
  module.exports = timeago;
<|endoftext|>


<commit_before>exports.test = function (describe) {
	describe('math', function (test) {
		test('add', 4, '2 + 2');
		test('subtract', 9, '11 - 2');
		test('multiply', 21, '7 * 3');
		test('divide', 3, '12 / 4');
		test('parentheses', 10, '4 + (3 * 2)');
		test('exponent', 16, '4 ** 2');
		test('modulo', 2, '10 % 4');
		test('+=', 6, 'foo = 2\nfoo += 4');
		test('-=', 0, 'foo = 2\nfoo -= 2');
		test('*=', 8, 'foo = 2\nfoo *= 4');
		test('/=', 1, 'foo = 2\nfoo /= 2');
	});

	describe('string manipulation', function (test) {
		test('concatenation', 'foobar', "'foo' + 'bar'");
		test('length', 10, "'abcdefghij'.length");
	});

	describe('explicit', function (test) {
		test('number', 42, '`42`');
	});

	describe('arrays', function (test) {
		test('inline', 'three', "['one', 'two', 'three'][2]");
		test('block', 'baz', "[\n\t'foo'\n\t'bar'\n\t'baz'\n][2]");
	});

	describe('objects', function (test) {
		test('inline', 'second', "obj = {first = 1, second = 'second', third = 3}\nobj.second");
		test('block', 'uther', "obj = {\n\tking = 'arthur'\n\twizard = 'merlin'\n\tfather = 'uther'\n}\nobj.father");
	});
}
<commit_msg>new tests for regex<commit_after>exports.test = function (describe) {
	describe('math', function (test) {
		test('add', 4, '2 + 2');
		test('subtract', 9, '11 - 2');
		test('multiply', 21, '7 * 3');
		test('divide', 3, '12 / 4');
		test('parentheses', 10, '4 + (3 * 2)');
		test('exponent', 16, '4 ** 2');
		test('modulo', 2, '10 % 4');
		test('+=', 6, 'foo = 2\nfoo += 4');
		test('-=', 0, 'foo = 2\nfoo -= 2');
		test('*=', 8, 'foo = 2\nfoo *= 4');
		test('/=', 1, 'foo = 2\nfoo /= 2');
	});

	describe('regex', function (test) {
		test('test', true, "/\\d+/.test('123')");
	})

	describe('string manipulation', function (test) {
		test('concatenation', 'foobar', "'foo' + 'bar'");
		test('length', 10, "'abcdefghij'.length");
	});

	describe('explicit', function (test) {
		test('number', 42, '`42`');
	});

	describe('arrays', function (test) {
		test('inline', 'three', "['one', 'two', 'three'][2]");
		test('block', 'baz', "[\n\t'foo'\n\t'bar'\n\t'baz'\n][2]");
	});

	describe('objects', function (test) {
		test('inline', 'second', "obj = {first = 1, second = 'second', third = 3}\nobj.second");
		test('block', 'uther', "obj = {\n\tking = 'arthur'\n\twizard = 'merlin'\n\tfather = 'uther'\n}\nobj.father");
	});
}
<|endoftext|>


<commit_before>'use strict';

const fs = require('fs');
const path = require('path');

const ROOMFAQ_FILE = path.resolve(__dirname, '../config/chat-plugins/faqs.json');
const ALLOWED_HTML = ['a', 'font', 'i', 'u', 'b', 'strong', 'em', 'small', 'sub', 'sup', 'ins', 'del', 'code'];

let roomFaqs = {};
try {
	roomFaqs = require(ROOMFAQ_FILE);
} catch (e) {
	if (e.code !== 'MODULE_NOT_FOUND') throw e;
}
if (!roomFaqs || typeof roomFaqs !== 'object') roomFaqs = {};

function saveRoomFaqs() {
	fs.writeFileSync(ROOMFAQ_FILE, JSON.stringify(roomFaqs));
}

// Aliases are implemented as a "regular" FAQ entry starting with a >. EX: {a: "text", b: ">a"}
// This is done to allow easy checking whether a key is associated with a value or alias as well as preserve backwards compatibility.
function getAlias(roomid, key) {
	if (!roomFaqs[roomid]) return false;
	let value = roomFaqs[roomid][key];
	if (value && value[0] === '>') return value.substr(1);
	return false;
}

exports.commands = {
	addfaq: function (target, room, user) {
		if (!this.canTalk()) return this.errorReply("You cannot do this while unable to talk.");
		if (!this.can('declare', null, room)) return false;
		if (!room.chatRoomData) return this.errorReply("This command is unavailable in temporary rooms.");
		let [topic, ...text] = target.split(',');

		topic = toId(topic);
		if (!(topic && text.length)) return this.parse('/help roomfaq');
		text = text.join(',').trim();
		if (topic.length > 25) return this.errorReply("FAQ topics should not exceed 25 characters.");
		if (text.length > 500) return this.errorReply("FAQ entries should not exceed 500 characters.");

		text = text.replace(/^>/, '>');

		let htmltags = text.toLowerCase().match(/<\/?(\w+)\b/g);
		if (htmltags && htmltags.some(val => !ALLOWED_HTML.includes(toId(val)))) {
			let tagList = ALLOWED_HTML.map(tag => `<${tag}>`).join(', ');
			return this.errorReply(`Disallowed HTML tags found. Allowed html tags: ${tagList}`);
		}

		text = this.canHTML(text);
		if (!text) return;

		if (!roomFaqs[room.id]) roomFaqs[room.id] = {};
		roomFaqs[room.id][topic] = text;
		saveRoomFaqs();
		this.sendReplyBox(text);
		this.privateModCommand(`(${user.name} added a FAQ for '${topic}')`);
	},
	removefaq: function (target, room, user) {
		if (!this.canTalk()) return this.errorReply("You cannot do this while unable to talk.");
		if (!this.can('declare', null, room)) return false;
		if (!room.chatRoomData) return this.errorReply("This command is unavailable in temporary rooms.");
		let topic = toId(target);
		if (!topic) return this.parse('/help roomfaq');

		if (!(roomFaqs[room.id] && roomFaqs[room.id][topic])) return this.errorReply("Invalid topic.");
		delete roomFaqs[room.id][topic];
		Object.keys(roomFaqs[room.id]).filter(val => getAlias(room.id, val) === topic).map(val => delete roomFaqs[room.id][val]);
		if (!Object.keys(roomFaqs[room.id]).length) delete roomFaqs[room.id];
		saveRoomFaqs();
		this.privateModCommand(`(${user.name} removed the FAQ for '${topic}')`);
	},
	addalias: function (target, room, user) {
		if (!this.canTalk()) return this.errorReply("You cannot do this while unable to talk.");
		if (!this.can('declare', null, room)) return false;
		if (!room.chatRoomData) return this.errorReply("This command is unavailable in temporary rooms.");
		let [alias, topic] = target.split(',').map(val => toId(val));

		if (!(alias && topic)) return this.parse('/help roomfaq');
		if (alias.length > 25) return this.errorReply("FAQ topics should not exceed 25 characters.");

		if (!(roomFaqs[room.id] && topic in roomFaqs[room.id])) return this.errorReply(`The topic ${topic} was not found in this room's faq list.`);
		if (getAlias(room.id, topic)) return this.errorReply(`You cannot make an alias of an alias. Use /addalias ${alias}, ${getAlias(room.id, topic)} instead.`);
		roomFaqs[room.id][alias] = `>${topic}`;
		saveRoomFaqs();
		this.privateModCommand(`(${user.name} added an alias for '${topic}': ${alias})`);
	},
	roomfaq: function (target, room, user) {
		if (!roomFaqs[room.id]) return this.errorReply("This room has no FAQ topics.");
		let topic = toId(target);
		if (topic === 'constructor') return false;
		if (!topic) return this.sendReplyBox(`List of topics in this room: ${Object.keys(roomFaqs[room.id]).filter(val => !getAlias(room.id, val)).join(', ')}`);
		if (!roomFaqs[room.id][topic]) return this.errorReply("Invalid topic.");
		topic = getAlias(room.id, topic) || topic;

		if (!this.runBroadcast()) return;
		this.sendReplyBox(roomFaqs[room.id][topic]);
		if (!this.broadcasting && user.can('declare', null, room)) this.sendReplyBox('/addfaq ' + topic + ', ' + Chat.escapeHTML(roomFaqs[room.id][topic]) + '');
	},
	roomfaqhelp: [
		"/roomfaq - Shows the list of all available FAQ topics",
		"/roomfaq <topic> - Shows the FAQ for <topic>.",
		"/addfaq <topic>, <text> - Adds an entry for <topic> in this room or updates it. Requires: # & ~",
		"/addalias <alias>, <topic> - Adds <alias> as an alias for <topic>, displaying it when users use /roomfaq <alias>. Requires: # & ~",
		"/removefaq <topic> - Removes the entry for <topic> in this room. If used on an alias, removes the alias. Requires: # & ~",
	],
};
<commit_msg>Add 'rfaq' as an alias for 'roomfaq'<commit_after>'use strict';

const fs = require('fs');
const path = require('path');

const ROOMFAQ_FILE = path.resolve(__dirname, '../config/chat-plugins/faqs.json');
const ALLOWED_HTML = ['a', 'font', 'i', 'u', 'b', 'strong', 'em', 'small', 'sub', 'sup', 'ins', 'del', 'code'];

let roomFaqs = {};
try {
	roomFaqs = require(ROOMFAQ_FILE);
} catch (e) {
	if (e.code !== 'MODULE_NOT_FOUND') throw e;
}
if (!roomFaqs || typeof roomFaqs !== 'object') roomFaqs = {};

function saveRoomFaqs() {
	fs.writeFileSync(ROOMFAQ_FILE, JSON.stringify(roomFaqs));
}

// Aliases are implemented as a "regular" FAQ entry starting with a >. EX: {a: "text", b: ">a"}
// This is done to allow easy checking whether a key is associated with a value or alias as well as preserve backwards compatibility.
function getAlias(roomid, key) {
	if (!roomFaqs[roomid]) return false;
	let value = roomFaqs[roomid][key];
	if (value && value[0] === '>') return value.substr(1);
	return false;
}

exports.commands = {
	addfaq: function (target, room, user) {
		if (!this.canTalk()) return this.errorReply("You cannot do this while unable to talk.");
		if (!this.can('declare', null, room)) return false;
		if (!room.chatRoomData) return this.errorReply("This command is unavailable in temporary rooms.");
		let [topic, ...text] = target.split(',');

		topic = toId(topic);
		if (!(topic && text.length)) return this.parse('/help roomfaq');
		text = text.join(',').trim();
		if (topic.length > 25) return this.errorReply("FAQ topics should not exceed 25 characters.");
		if (text.length > 500) return this.errorReply("FAQ entries should not exceed 500 characters.");

		text = text.replace(/^>/, '>');

		let htmltags = text.toLowerCase().match(/<\/?(\w+)\b/g);
		if (htmltags && htmltags.some(val => !ALLOWED_HTML.includes(toId(val)))) {
			let tagList = ALLOWED_HTML.map(tag => `<${tag}>`).join(', ');
			return this.errorReply(`Disallowed HTML tags found. Allowed html tags: ${tagList}`);
		}

		text = this.canHTML(text);
		if (!text) return;

		if (!roomFaqs[room.id]) roomFaqs[room.id] = {};
		roomFaqs[room.id][topic] = text;
		saveRoomFaqs();
		this.sendReplyBox(text);
		this.privateModCommand(`(${user.name} added a FAQ for '${topic}')`);
	},
	removefaq: function (target, room, user) {
		if (!this.canTalk()) return this.errorReply("You cannot do this while unable to talk.");
		if (!this.can('declare', null, room)) return false;
		if (!room.chatRoomData) return this.errorReply("This command is unavailable in temporary rooms.");
		let topic = toId(target);
		if (!topic) return this.parse('/help roomfaq');

		if (!(roomFaqs[room.id] && roomFaqs[room.id][topic])) return this.errorReply("Invalid topic.");
		delete roomFaqs[room.id][topic];
		Object.keys(roomFaqs[room.id]).filter(val => getAlias(room.id, val) === topic).map(val => delete roomFaqs[room.id][val]);
		if (!Object.keys(roomFaqs[room.id]).length) delete roomFaqs[room.id];
		saveRoomFaqs();
		this.privateModCommand(`(${user.name} removed the FAQ for '${topic}')`);
	},
	addalias: function (target, room, user) {
		if (!this.canTalk()) return this.errorReply("You cannot do this while unable to talk.");
		if (!this.can('declare', null, room)) return false;
		if (!room.chatRoomData) return this.errorReply("This command is unavailable in temporary rooms.");
		let [alias, topic] = target.split(',').map(val => toId(val));

		if (!(alias && topic)) return this.parse('/help roomfaq');
		if (alias.length > 25) return this.errorReply("FAQ topics should not exceed 25 characters.");

		if (!(roomFaqs[room.id] && topic in roomFaqs[room.id])) return this.errorReply(`The topic ${topic} was not found in this room's faq list.`);
		if (getAlias(room.id, topic)) return this.errorReply(`You cannot make an alias of an alias. Use /addalias ${alias}, ${getAlias(room.id, topic)} instead.`);
		roomFaqs[room.id][alias] = `>${topic}`;
		saveRoomFaqs();
		this.privateModCommand(`(${user.name} added an alias for '${topic}': ${alias})`);
	},
	rfaq: 'roomfaq',
	roomfaq: function (target, room, user) {
		if (!roomFaqs[room.id]) return this.errorReply("This room has no FAQ topics.");
		let topic = toId(target);
		if (topic === 'constructor') return false;
		if (!topic) return this.sendReplyBox(`List of topics in this room: ${Object.keys(roomFaqs[room.id]).filter(val => !getAlias(room.id, val)).join(', ')}`);
		if (!roomFaqs[room.id][topic]) return this.errorReply("Invalid topic.");
		topic = getAlias(room.id, topic) || topic;

		if (!this.runBroadcast()) return;
		this.sendReplyBox(roomFaqs[room.id][topic]);
		if (!this.broadcasting && user.can('declare', null, room)) this.sendReplyBox('/addfaq ' + topic + ', ' + Chat.escapeHTML(roomFaqs[room.id][topic]) + '');
	},
	roomfaqhelp: [
		"/roomfaq - Shows the list of all available FAQ topics",
		"/roomfaq <topic> - Shows the FAQ for <topic>.",
		"/addfaq <topic>, <text> - Adds an entry for <topic> in this room or updates it. Requires: # & ~",
		"/addalias <alias>, <topic> - Adds <alias> as an alias for <topic>, displaying it when users use /roomfaq <alias>. Requires: # & ~",
		"/removefaq <topic> - Removes the entry for <topic> in this room. If used on an alias, removes the alias. Requires: # & ~",
	],
};
<|endoftext|>


<commit_before>var pkg = require('../../package.js'),
    extend = require('xtend');
var gulp = require('gulp'),
    gulp_eslint = require('gulp-eslint');

gulp.task('lint:js', function () {
    var eslint = true;

    if (pkg.dizmo && pkg.dizmo.build) {
        var cfg_lint = pkg.dizmo.build.lint;
        if (cfg_lint || cfg_lint === undefined) {
            eslint = extend({}, cfg_lint);
        }
    }

    var argv = require('yargs')
        .default('lint', eslint).argv;
    if (typeof argv.lint === 'string') {
        argv.lint = JSON.parse(argv.lint);
    }

    var bundle = gulp.src([
        './src/**/*.js', '!src/lib/**', '!build/**', '!node_modules/**']);
    if (argv.lint || argv.lint === undefined) {
        bundle = bundle.pipe(gulp_eslint.apply(
            this, [extend({}, argv.lint)]
        )).pipe(gulp_eslint.format());
    }
    return bundle;
});

gulp.task('lint', ['lint:js']);
<commit_msg>DIG-79: fixed lint:false case<commit_after>var pkg = require('../../package.js'),
    extend = require('xtend');
var gulp = require('gulp'),
    gulp_eslint = require('gulp-eslint');

gulp.task('lint:js', function () {
    var lint = true;
    if (pkg.dizmo && pkg.dizmo.build) {
        var cfg_lint = pkg.dizmo.build.lint;
        if (cfg_lint || cfg_lint === undefined) {
            lint = extend({}, cfg_lint);
        } else {
            lint = false;
        }
    }

    var argv = require('yargs')
        .default('lint', lint).argv;
    if (typeof argv.lint === 'string') {
        argv.lint = JSON.parse(argv.lint);
    }

    var bundle = gulp.src([
        './src/**/*.js', '!src/lib/**', '!build/**', '!node_modules/**']);
    if (argv.lint || argv.lint === undefined) {
        bundle = bundle
            .pipe(gulp_eslint.apply(this, [extend({}, argv.lint)]))
            .pipe(gulp_eslint.format());
    }
    return bundle;
});

gulp.task('lint', ['lint:js']);
<|endoftext|>


<commit_before>function loadFont(a,b,c){function d(){if(!window.FontFace)return!1;var a=new FontFace("t",'url("data:application/font-woff2,") format("woff2")',{});return a.load(),"loading"===a.status}var e=navigator.userAgent,f=!window.addEventListener||e.match(/(Android (2|3|4.0|4.1|4.2|4.3))|(Opera (Mini|Mobi))/)&&!e.match(/Chrome/);if(!f){var g={};try{g=localStorage||{}}catch(h){}var i="x-font-"+a,j=i+"url",k=i+"css",l=g[j],m=g[k],n=document.createElement("style");if(n.rel="stylesheet",document.head.appendChild(n),!m||l!==b&&l!==c){var o=c&&d()?c:b,p=new XMLHttpRequest;p.open("GET",o),p.onload=function(){p.status>=200&&p.status<400&&(g[j]=o,g[k]=n.textContent=p.responseText)},p.send()}else n.textContent=m}}<commit_msg>Update fontloader.js<commit_after>function loadFont(a,b,c){function d(){if(!window.FontFace)return!1;var a=new FontFace("t",'url("data:application/font-woff2,") format("woff2")',{});return a.load(),"loading"===a.status}var e=navigator.userAgent,f=!window.addEventListener||e.match(/(Android (2|3|4.0|4.1|4.2|4.3))|(Opera (Mini|Mobi))/)&&!e.match(/Chrome/);if(!f){var g={};try{g=localStorage||{}}catch(h){}var i="font-"+a,j=i+"url",k=i+"css",l=g[j],m=g[k],n=document.createElement("style");if(n.rel="stylesheet",document.head.appendChild(n),!m||l!==b&&l!==c){var o=c&&d()?c:b,p=new XMLHttpRequest;p.open("GET",o),p.onload=function(){p.status>=200&&p.status<400&&(g[j]=o,g[k]=n.textContent=p.responseText)},p.send()}else n.textContent=m}}
<|endoftext|>


<commit_before>/* eslint-env es6 */
/* global THREE, VertexIndices, FaceIndices */
window.applyBoxVertexColors = (function() {
  'use strict';

  function setFaceVertexColor( face, index, color ) {
    if ( face.a === index ) {
      face.vertexColors[ 0 ] = color;
    }

    if ( face.b === index ) {
      face.vertexColors[ 1 ] = color;
    }

    if ( face.c === index ) {
      face.vertexColors[ 2 ] = color;
    }
  }

  function baseVertexColors( geometry, key, color ) {
    const indices = VertexIndices[ key.toUpperCase() ];

    geometry.faces.forEach( face => {
      if ( Array.isArray( indices ) ) {
        indices.forEach( index =>
          setFaceVertexColor( face, index, color )
        );
      } else {
        setFaceVertexColor( face, indices, color );
      }
    });

    return geometry;
  }

  return function vertexColors( geometry, colors, ...args ) {
    if ( typeof colors === 'string' ) {
      return baseVertexColors( geometry, colors, ...args );
    } else if ( typeof colors === 'object' ) {
      Object.keys( colors ).forEach( key => {
        const color = new THREE.Color( colors[ key ] );
        baseVertexColors( geometry, key, color );
      });
    }

    return geometry;
  };
}());

// Like _.defaults, but with THREE.Face vertexColors.
window.defaultVertexColors = (function() {
  'use strict';

  return function defaults( geometry, defaultColor ) {
    defaultColor = new THREE.Color( defaultColor );

    geometry.faces.forEach( face => {
      for ( let i = 0; i < 3; i++ ) {
        if ( face.vertexColors[ i ] === undefined ) {
          face.vertexColors[ i ] = defaultColor;
        }
      }
    });

    return geometry;
  };
}());

window.applyBoxFaceColors = (function() {
  'use strict';

  function baseFaceColors( geometry, key, color ) {
    const indices = FaceIndices[ key.toUpperCase() ];
    indices.forEach( index => geometry.faces[ index ].color.set( color ) );
    return geometry;
  }

  return function faceColors( geometry, colors, ...args ) {
    if ( typeof colors === 'string' ) {
      return baseFaceColors( geometry, colors, ...args );
    } else {
      Object.keys( colors ).forEach( key => {
        const color = colors[ key ];
        baseFaceColors( geometry, key, color );
      });
    }

    return geometry;
  };
}());

window.applyBoxFaceVertexColors = (function() {
  'use strict';

  function baseFaceVertexColors( geometry, key, color ) {
    const indices = FaceIndices[ key.toUpperCase() ];

    indices.forEach( index => {
      const face = geometry.faces[ index ];
      for ( let i = 0; i < 3; i++ ) {
        face.vertexColors[ i ] = color;
      }
    });

    return geometry;
  }

  return function faceVertexColors( geometry, colors, ...args ) {
    if ( typeof colors === 'string' ) {
      return baseFaceVertexColors( geometry, colors, ...args );
    } else {
      Object.keys( colors ).forEach( key => {
        const color = new THREE.Color( colors[ key ] );
        baseFaceVertexColors( geometry, key, color );
      });
    }

    return geometry;
  };
}());
<commit_msg>lathe[cuboid]: Fix BoxGeometry color helpers for string args.<commit_after>/* eslint-env es6 */
/* global THREE, VertexIndices, FaceIndices */
window.applyBoxVertexColors = (function() {
  'use strict';

  function setFaceVertexColor( face, index, color ) {
    if ( face.a === index ) {
      face.vertexColors[ 0 ] = color;
    }

    if ( face.b === index ) {
      face.vertexColors[ 1 ] = color;
    }

    if ( face.c === index ) {
      face.vertexColors[ 2 ] = color;
    }
  }

  function baseVertexColors( geometry, key, color ) {
    const indices = VertexIndices[ key.toUpperCase() ];

    geometry.faces.forEach( face => {
      if ( Array.isArray( indices ) ) {
        indices.forEach( index =>
          setFaceVertexColor( face, index, color )
        );
      } else {
        setFaceVertexColor( face, indices, color );
      }
    });

    return geometry;
  }

  return function vertexColors( geometry, colors, ...args ) {
    if ( typeof colors === 'string' ) {
      const key = colors;
      const color = new THREE.Color( ...args );
      baseVertexColors( geometry, key, color );
    } else if ( typeof colors === 'object' ) {
      Object.keys( colors ).forEach( key => {
        const color = new THREE.Color( colors[ key ] );
        baseVertexColors( geometry, key, color );
      });
    }

    return geometry;
  };
}());

// Like _.defaults, but with THREE.Face vertexColors.
window.defaultVertexColors = (function() {
  'use strict';

  return function defaults( geometry, defaultColor ) {
    defaultColor = new THREE.Color( defaultColor );

    geometry.faces.forEach( face => {
      for ( let i = 0; i < 3; i++ ) {
        if ( face.vertexColors[ i ] === undefined ) {
          face.vertexColors[ i ] = defaultColor;
        }
      }
    });

    return geometry;
  };
}());

window.applyBoxFaceColors = (function() {
  'use strict';

  function baseFaceColors( geometry, key, color ) {
    const indices = FaceIndices[ key.toUpperCase() ];
    indices.forEach( index => geometry.faces[ index ].color.set( color ) );
    return geometry;
  }

  return function faceColors( geometry, colors, ...args ) {
    if ( typeof colors === 'string' ) {
      const key = colors;
      const color = args[ 0 ];
      baseFaceColors( geometry, key, color );
    } else {
      Object.keys( colors ).forEach( key => {
        const color = colors[ key ];
        baseFaceColors( geometry, key, color );
      });
    }

    return geometry;
  };
}());

window.applyBoxFaceVertexColors = (function() {
  'use strict';

  function baseFaceVertexColors( geometry, key, color ) {
    const indices = FaceIndices[ key.toUpperCase() ];

    indices.forEach( index => {
      const face = geometry.faces[ index ];
      for ( let i = 0; i < 3; i++ ) {
        face.vertexColors[ i ] = color;
      }
    });

    return geometry;
  }

  return function faceVertexColors( geometry, colors, ...args ) {
    if ( typeof colors === 'string' ) {
      const key = colors;
      const color = new THREE.Color( ...args );
      baseFaceVertexColors( geometry, key, color );
    } else {
      Object.keys( colors ).forEach( key => {
        const color = new THREE.Color( colors[ key ] );
        baseFaceVertexColors( geometry, key, color );
      });
    }

    return geometry;
  };
}());
<|endoftext|>


<commit_before>#!/usr/bin/env node
var assert = require('assert');

var async = require('async');
var mongoose = require('mongoose');
var funkit = require('funkit');
var equals = funkit.ops.equals;
var is = require('is-js');

var sugar = require('../lib/mongoose-sugar');
var models = require('./models');

var log = console.log.bind(console);

main();

function main() {
    var address = 'mongodb://localhost/mongoose-sugar-test';

    mongoose.connect(address, function(err) {
        if(err) log('Make sure mongod is running!');
    });

    log('Executing tests!');

    async.series(setup([
        createAuthor(),
        updateAuthor,
        removeAuthor,
        getAuthor,
        getAuthorName,
        getAllAuthors,
        getAllAuthorsLimit,
        getAllAuthorNames,
        getMeta
    ], function(t) {
        return function(cb) {
            async.series([
                removeAuthors,
                removeLibraries
            ], t.bind(undefined, cb));
        };
    }), function() {
        log('Tests executed!');

        process.exit();
    });
}

function setup(tests, fn) {
    return tests.map(function(t) {
        return fn(t);
    });
}

// TODO: figure out why bind doesn't work for these!
function removeAuthors(cb) {
    removeAll(models.Author, cb);
}

function removeLibraries(cb) {
    removeAll(models.Library, cb);
}

function getAuthorName(cb) {
    createAuthor()(function(err, author) {
        sugar.get(models.Author, author._id, ['name'], function(err, d) {
            assert.equal(d.name, author.name);
            assert.equal(d._id, author._id.toString()); // XXX. toString needed

            cb(err, d);
        });
    });
}

function getAuthor(cb) {
    createAuthor()(function(err, author) {
        sugar.get(models.Author, author._id, function(err, d) {
            // XXX: figure out why d._id.toString() is needed (different encoding?)
            //assert.ok(equals(author, d));
            assert.equal(author._id, d._id.toString());

            cb(err, d);
        });
    });
}

function getAllAuthors(cb) {
    // TODO: move into an array and generate createAuthors based on these
    var firstData = {name: 'Jack'};
    var secondData = {name: 'Joe'};

    async.series([
        createAuthor(firstData),
        createAuthor(secondData),
        getAll
    ], cb);

    function getAll(cb) {
        sugar.getAll(models.Author, function(err, d) {
            assert.equal(d.length, 2);

            // TODO: check just if the returned data contains (no need for order)
            assert.equal(d[0].name, firstData.name);
            assert.equal(d[1].name, secondData.name);

            cb(err, d);
        });
    }
}

// TODO: join with above somehow
function getAllAuthorNames(cb) {
    var firstData = {name: 'Jack', extra: ['foo', 'bar']};
    var secondData = {name: 'Joe', extra: ['boo', 'moo']};

    async.series([
        createAuthor(firstData),
        createAuthor(secondData),
        getAll
    ], cb);

    function getAll(cb) {
        sugar.getAll(models.Author, {fields: ['name']}, function(err, d) {
            assert.equal(d.length, 2);

            // TODO: no need for these to be in order
            assert.equal(d[0].name, firstData.name);
            assert.equal(d[0].extra, undefined);
            assert.equal(d[1].name, secondData.name);
            assert.equal(d[1].extra, undefined);

            cb(err, d);
        });
    }
}

// TODO: join with above somehow
function getAllAuthorsLimit(cb) {
    var firstData = {name: 'Jack', extra: ['foo', 'bar']};
    var secondData = {name: 'Joe', extra: ['boo', 'moo']};

    async.series([
        createAuthor(firstData),
        createAuthor(secondData),
        getAll
    ], cb);

    function getAll(cb) {
        sugar.getAll(models.Author, {fields: ['name'], limit: 1}, function(err, d) {
            assert.equal(d.length, 1);

            // TODO: no need for these to be in order
            assert.equal(d[0].name, firstData.name);
            assert.equal(d[0].extra, undefined);

            cb(err, d);
        });
    }
}

function updateAuthor(cb) {
    createAuthor()(function(err, d) {
        var name = d.name + d.name;

        d.name = name;

        sugar.update(models.Author, d._id, d, function(err, d) {
            assert.equal(d.name, name);

            cb(err, d);
        });
    });
}

function removeAuthor(cb) {
    createAuthor()(function(err, d) {
        sugar.remove(models.Author, d._id, function(err, d) {
            assert.ok(d.deleted);

            sugar.count(models.Author, function(err, d) {
                assert.equal(d, 0);

                cb(err, d);
            });
        });
    });
}

// XXX: using factory here since bind does not seem to work with async
function createAuthor(data) {
    var name, extra; // TODO: tidy up
    if(data) {
        name = data.name;
        extra = data.extra;
    }
    else {
        name = 'Joe';
        extra = ['foobar', 'barbar'];
        data = {
            name: name,
            extra: extra
        };
    }

    return function(cb) {
        sugar.create(models.Author, data, function(err, d) {
            assert.equal(d.name, name);
            assert.ok(equals(d.extra, extra));

            cb(err, d);
        });
    };
}

function removeAll(model, cb) {
    sugar.removeAll(model, function(err, d) {
        cb(err, d);
    });
}

function getMeta(cb) {
    sugar.getMeta(models.Author, function(err, d) {
        assert.ok(is.object(d));

        cb(err, d);
    });
}
<commit_msg>Test getAll offset<commit_after>#!/usr/bin/env node
var assert = require('assert');

var async = require('async');
var mongoose = require('mongoose');
var funkit = require('funkit');
var equals = funkit.ops.equals;
var is = require('is-js');

var sugar = require('../lib/mongoose-sugar');
var models = require('./models');

var log = console.log.bind(console);

main();

function main() {
    var address = 'mongodb://localhost/mongoose-sugar-test';

    mongoose.connect(address, function(err) {
        if(err) log('Make sure mongod is running!');
    });

    log('Executing tests!');

    async.series(setup([
        createAuthor(),
        updateAuthor,
        removeAuthor,
        getAuthor,
        getAuthorName,
        getAllAuthors,
        getAllAuthorsLimit,
        getAllAuthorsOffset,
        getAllAuthorNames,
        getMeta
    ], function(t) {
        return function(cb) {
            async.series([
                removeAuthors,
                removeLibraries
            ], t.bind(undefined, cb));
        };
    }), function() {
        log('Tests executed!');

        process.exit();
    });
}

function setup(tests, fn) {
    return tests.map(function(t) {
        return fn(t);
    });
}

// TODO: figure out why bind doesn't work for these!
function removeAuthors(cb) {
    removeAll(models.Author, cb);
}

function removeLibraries(cb) {
    removeAll(models.Library, cb);
}

function getAuthorName(cb) {
    createAuthor()(function(err, author) {
        sugar.get(models.Author, author._id, ['name'], function(err, d) {
            assert.equal(d.name, author.name);
            assert.equal(d._id, author._id.toString()); // XXX. toString needed

            cb(err, d);
        });
    });
}

function getAuthor(cb) {
    createAuthor()(function(err, author) {
        sugar.get(models.Author, author._id, function(err, d) {
            // XXX: figure out why d._id.toString() is needed (different encoding?)
            //assert.ok(equals(author, d));
            assert.equal(author._id, d._id.toString());

            cb(err, d);
        });
    });
}

function getAllAuthors(cb) {
    // TODO: move into an array and generate createAuthors based on these
    var firstData = {name: 'Jack'};
    var secondData = {name: 'Joe'};

    async.series([
        createAuthor(firstData),
        createAuthor(secondData),
        getAll
    ], cb);

    function getAll(cb) {
        sugar.getAll(models.Author, function(err, d) {
            assert.equal(d.length, 2);

            // TODO: check just if the returned data contains (no need for order)
            assert.equal(d[0].name, firstData.name);
            assert.equal(d[1].name, secondData.name);

            cb(err, d);
        });
    }
}

// TODO: join with above somehow
function getAllAuthorNames(cb) {
    var firstData = {name: 'Jack', extra: ['foo', 'bar']};
    var secondData = {name: 'Joe', extra: ['boo', 'moo']};

    async.series([
        createAuthor(firstData),
        createAuthor(secondData),
        getAll
    ], cb);

    function getAll(cb) {
        sugar.getAll(models.Author, {fields: ['name']}, function(err, d) {
            assert.equal(d.length, 2);

            // TODO: no need for these to be in order
            assert.equal(d[0].name, firstData.name);
            assert.equal(d[0].extra, undefined);
            assert.equal(d[1].name, secondData.name);
            assert.equal(d[1].extra, undefined);

            cb(err, d);
        });
    }
}

// TODO: join with above somehow
function getAllAuthorsLimit(cb) {
    var firstData = {name: 'Jack', extra: ['foo', 'bar']};
    var secondData = {name: 'Joe', extra: ['boo', 'moo']};

    async.series([
        createAuthor(firstData),
        createAuthor(secondData),
        getAll
    ], cb);

    function getAll(cb) {
        sugar.getAll(models.Author, {limit: 1}, function(err, d) {
            assert.equal(d.length, 1);

            // TODO: no need for these to be in order
            assert.equal(d[0].name, firstData.name);
            assert.ok(equals(d[0].extra, firstData.extra));

            cb(err, d);
        });
    }
}

// TODO: join with above somehow
function getAllAuthorsOffset(cb) {
    var firstData = {name: 'Jack', extra: ['foo', 'bar']};
    var secondData = {name: 'Joe', extra: ['boo', 'moo']};

    async.series([
        createAuthor(firstData),
        createAuthor(secondData),
        getAll
    ], cb);

    function getAll(cb) {
        sugar.getAll(models.Author, {limit: 1, offset: 1}, function(err, d) {
            assert.equal(d.length, 1);

            // TODO: no need for these to be in order
            assert.equal(d[0].name, secondData.name);
            assert.ok(equals(d[0].extra, secondData.extra));

            cb(err, d);
        });
    }
}

function updateAuthor(cb) {
    createAuthor()(function(err, d) {
        var name = d.name + d.name;

        d.name = name;

        sugar.update(models.Author, d._id, d, function(err, d) {
            assert.equal(d.name, name);

            cb(err, d);
        });
    });
}

function removeAuthor(cb) {
    createAuthor()(function(err, d) {
        sugar.remove(models.Author, d._id, function(err, d) {
            assert.ok(d.deleted);

            sugar.count(models.Author, function(err, d) {
                assert.equal(d, 0);

                cb(err, d);
            });
        });
    });
}

// XXX: using factory here since bind does not seem to work with async
function createAuthor(data) {
    var name, extra; // TODO: tidy up
    if(data) {
        name = data.name;
        extra = data.extra;
    }
    else {
        name = 'Joe';
        extra = ['foobar', 'barbar'];
        data = {
            name: name,
            extra: extra
        };
    }

    return function(cb) {
        sugar.create(models.Author, data, function(err, d) {
            assert.equal(d.name, name);
            assert.ok(equals(d.extra, extra));

            cb(err, d);
        });
    };
}

function removeAll(model, cb) {
    sugar.removeAll(model, function(err, d) {
        cb(err, d);
    });
}

function getMeta(cb) {
    sugar.getMeta(models.Author, function(err, d) {
        assert.ok(is.object(d));

        cb(err, d);
    });
}
<|endoftext|>


<commit_before>import Ember from 'ember';

/* ============================================== */

/*
 * Representa el lenguaje que podra utilizarse
 * en una actividad
 */
var Lenguaje = Ember.Object.extend({

  init() {
    this.set('categorias', []);
    this.set('bloques', {});
  },

  agregar(c, bs) {
    if(bs !== undefined) {
      this.categoria(c);
      bs.forEach(function (b) {
        this.bloque(c, b);
      }.bind(this));
    }
  },

  categoria(c) {
    this.get('categorias').pushObject(c);
    var bs = this.get('bloques');
    bs[c] = [];
    this.set('bloques', bs);
  },

  bloque(c, b) {
    var block = this.definir_bloque(b);
    this.get('bloques')[c].pushObject(block);
  },

  definir_bloque(b) {
    var block = b.create();
    block.registrar_en_blockly();
    return block;
  },

  build() {
    var str_toolbox = '';

    str_toolbox += '<xml>';

    this.get('categorias').forEach(function(item) {
      if (item === 'Variables') {
        str_toolbox += this._build_variables();
      } else if (item === 'Procedimientos') {
        str_toolbox += this._build_procedures();
      } else {
        str_toolbox += this._build_categoria(item);
      }
    }.bind(this));

    str_toolbox += '</xml>';

    return str_toolbox;
  },

  _build_categoria(categoria) {
    var str_category = '';

    str_category += '<category name="x">\n'.replace('x', categoria);

    this.get('bloques')[categoria].forEach(function(b) {
       str_category += b.build();
    });

    str_category += '</category>\n';

    return str_category;
  },

  _build_procedures() {
    return '<category name="Procedimientos" custom="PROCEDURE"></category>';
  },

  _build_variables() {
    return '<category name="Variables" custom="VARIABLE"></category>';
  }

});

export default Lenguaje;
<commit_msg>refactor: remuevo lista innecesaria de categorias en lenguaje<commit_after>import Ember from 'ember';

/* ============================================== */

/*
 * Representa el lenguaje que podra utilizarse
 * en una actividad
 */
var Lenguaje = Ember.Object.extend({

  init() {
    this.set('bloques', {});
  },

  agregar(c, bs) {
    if(bs !== undefined) {
      this.categoria(c);
      bs.forEach(function (b) {
        this.bloque(c, b);
      }.bind(this));
    }
  },

  categoria(c) {
    if(this.get('bloques')[c] === undefined){
      this.get('bloques')[c] = [];
    }
  },

  bloque(c, b) {
    var block = this.definir_bloque(b);
    this.get('bloques')[c].pushObject(block);
  },

  definir_bloque(b) {
    var block = b.create();
    block.registrar_en_blockly();
    return block;
  },

  build() {
    var str_toolbox = '';

    str_toolbox += '<xml>';

    for (var categoria in this.get('bloques')) {
      if (categoria === 'Variables') {
        str_toolbox += this._build_variables();
      } else if (categoria === 'Mis procedimientos') {
        str_toolbox += this._build_procedures();
      } else {
        str_toolbox += this._build_categoria(categoria);
      }
    }

    str_toolbox += '</xml>';

    return str_toolbox;
  },

  _build_categoria(categoria) {
    var str_category = '';

    str_category += '<category name="x">\n'.replace('x', categoria);

    this.get('bloques')[categoria].forEach(function(b) {
       str_category += b.build();
    });

    str_category += '</category>\n';

    return str_category;
  },

  _build_procedures() {
    return '<category name="Mis procedimientos" custom="PROCEDURE"></category>';
  },

  _build_variables() {
    return '<category name="Variables" custom="VARIABLE"></category>';
  }

});

export default Lenguaje;
<|endoftext|>