<commit_before>/**
 * states.js
 * Created by anonymous on 09/12/15 13:12.
 */

(function() {
    'use strict';

    angular
        .module('client')
        .config(clientRouter);

    clientRouter.$inject = ['$stateProvider', '$urlRouterProvider', 'layoutProvider'];

    /* @ngInject */
    function clientRouter($stateProvider, $urlRouterProvider, layoutProvider) {
        $urlRouterProvider.otherwise('/');

        $stateProvider
            .state('client', {
                abstract: true,
                views   : {
                    'layout@'       : {
                        templateUrl : layoutProvider.layout('minimalist.theme'),
                        controller  : 'ClientController',
                        controllerAs: 'client'
                    },
                    'header@client' : {
                        templateUrl : layoutProvider.layout('minimalist.header'),
                        controller  : 'HeaderController',
                        controllerAs: 'header'
                    },
                    'sidenav@client': {
                        templateUrl : layoutProvider.layout('minimalist.sidenav'),
                        controller  : 'SidenavController',
                        controllerAs: 'sidenav'
                    },
                    'aside@client'  : {
                        templateUrl : layoutProvider.layout('minimalist.aside'),
                        controller  : 'AsideController',
                        controllerAs: 'aside'
                    },
                    'footer@client' : {
                        templateUrl : layoutProvider.layout('minimalist.footer'),
                        controller  : 'FooterController',
                        controllerAs: 'footer'
                    },
                    'main@client'   : {}
                }
            })
            .state('client.landing', {
                url  : '/',
                data : {pageName: 'Welcome'},
                views: {
                    'main@client': {
                        templateUrl : layoutProvider.view('client.landing'),
                        controller  : 'ClientLandingController',
                        controllerAs: 'landing'
                    }
                }
            })
            .state('client.home', {
                url  : '/home',
                data : {pageName: 'Home'},
                views: {
                    'main@client': {
                        templateUrl : layoutProvider.view('client.home'),
                        controller  : 'ClientHomeController',
                        controllerAs: 'home'
                    }
                }
            })
            .state('staticpage', {
                abstract: true,
                url     : '/page',
                views   : {
                    'layout@'           : {
                        templateUrl : layoutProvider.layout('minimalist.theme'),
                        controller  : 'StaticpageController',
                        controllerAs: 'staticpage'
                    },
                    'header@staticpage' : {
                        templateUrl : layoutProvider.layout('minimalist.header'),
                        controller  : 'HeaderController',
                        controllerAs: 'header'
                    },
                    'sidenav@staticpage': {
                        templateUrl : layoutProvider.layout('minimalist.sidenav'),
                        controller  : 'SidenavController',
                        controllerAs: 'sidenav'
                    },
                    'aside@staticpage'  : {
                        templateUrl : layoutProvider.layout('minimalist.aside'),
                        controller  : 'AsideController',
                        controllerAs: 'aside'
                    },
                    'footer@staticpage' : {
                        templateUrl : layoutProvider.layout('minimalist.footer'),
                        controller  : 'FooterController',
                        controllerAs: 'footer'
                    },
                    'main@staticpage'   : {}
                }
            })
            .state('staticpage.landing', {
                url  : '/',
                data : {pageName: 'Landing page'},
                views: {
                    'main@staticpage': {
                        templateUrl : layoutProvider.view('staticpage.landing'),
                        controller  : 'StaticpageLandingController',
                        controllerAs: 'landing'
                    }
                }
            })
            .state('profile', {
                abstract: true,
                url     : '/profile',
                views   : {
                    'layout@'        : {
                        templateUrl : layoutProvider.layout('minimalist.theme'),
                        controller  : 'ProfileController',
                        controllerAs: 'profile'
                    },
                    'header@profile' : {
                        templateUrl : layoutProvider.layout('minimalist.header'),
                        controller  : 'HeaderController',
                        controllerAs: 'header'
                    },
                    'sidenav@profile': {
                        templateUrl : layoutProvider.layout('minimalist.sidenav'),
                        controller  : 'SidenavController',
                        controllerAs: 'sidenav'
                    },
                    'aside@profile'  : {
                        templateUrl : layoutProvider.layout('minimalist.aside'),
                        controller  : 'AsideController',
                        controllerAs: 'aside'
                    },
                    'footer@profile' : {
                        templateUrl : layoutProvider.layout('minimalist.footer'),
                        controller  : 'FooterController',
                        controllerAs: 'footer'
                    },
                    'main@profile'   : {}
                }
            })
            .state('profile.user', {
                url    : '/{user}',
                data   : {pageName: 'Profile'},
                views  : {
                    'main@profile': {
                        templateUrl : layoutProvider.view('profile.user'),
                        controller  : 'ProfileUserController',
                        controllerAs: '$ctrl'
                    }
                },
                resolve: {
                    loginRequired: loginRequired
                }
            });

        function loginRequired($q, $state, $auth) {
            var deferred = $q.defer();
            if ($auth.isAuthenticated()) {
                deferred.resolve();
            } else {
                $state.go('jwtauth.signin');
            }

            return deferred.promise;
        }

    }

})();

<commit_msg>Modified client.state.js<commit_after>/**
 * client.state.js
 * Created by anonymous on 09/12/15 13:12.
 */

(function() {
    'use strict';

    angular
        .module('client')
        .config(clientState);

    clientState.$inject = ['$stateProvider', '$urlRouterProvider', 'layoutProvider'];

    /* @ngInject */
    function clientState($stateProvider, $urlRouterProvider, layoutProvider) {
        $urlRouterProvider.otherwise('/');

        $stateProvider
            .state('client', {
                abstract: true,
                views   : {
                    'layout@'       : {
                        templateUrl : layoutProvider.layout('minimalist.theme'),
                        controller  : 'ClientController',
                        controllerAs: 'client'
                    },
                    'header@client' : {
                        templateUrl : layoutProvider.layout('minimalist.header'),
                        controller  : 'HeaderController',
                        controllerAs: 'header'
                    },
                    'sidenav@client': {
                        templateUrl : layoutProvider.layout('minimalist.sidenav'),
                        controller  : 'SidenavController',
                        controllerAs: 'sidenav'
                    },
                    'aside@client'  : {
                        templateUrl : layoutProvider.layout('minimalist.aside'),
                        controller  : 'AsideController',
                        controllerAs: 'aside'
                    },
                    'footer@client' : {
                        templateUrl : layoutProvider.layout('minimalist.footer'),
                        controller  : 'FooterController',
                        controllerAs: 'footer'
                    },
                    'main@client'   : {}
                }
            })
            .state('client.landing', {
                url  : '/',
                data : {pageName: 'Welcome'},
                views: {
                    'main@client': {
                        templateUrl : layoutProvider.view('client.landing'),
                        controller  : 'ClientLandingController',
                        controllerAs: 'landing'
                    }
                }
            })
            .state('client.home', {
                url  : '/home',
                data : {pageName: 'Home'},
                views: {
                    'main@client': {
                        templateUrl : layoutProvider.view('client.home'),
                        controller  : 'ClientHomeController',
                        controllerAs: 'home'
                    }
                }
            })
            .state('staticpage', {
                abstract: true,
                url     : '/page',
                views   : {
                    'layout@'           : {
                        templateUrl : layoutProvider.layout('minimalist.theme'),
                        controller  : 'StaticpageController',
                        controllerAs: 'staticpage'
                    },
                    'header@staticpage' : {
                        templateUrl : layoutProvider.layout('minimalist.header'),
                        controller  : 'HeaderController',
                        controllerAs: 'header'
                    },
                    'sidenav@staticpage': {
                        templateUrl : layoutProvider.layout('minimalist.sidenav'),
                        controller  : 'SidenavController',
                        controllerAs: 'sidenav'
                    },
                    'aside@staticpage'  : {
                        templateUrl : layoutProvider.layout('minimalist.aside'),
                        controller  : 'AsideController',
                        controllerAs: 'aside'
                    },
                    'footer@staticpage' : {
                        templateUrl : layoutProvider.layout('minimalist.footer'),
                        controller  : 'FooterController',
                        controllerAs: 'footer'
                    },
                    'main@staticpage'   : {}
                }
            })
            .state('staticpage.landing', {
                url  : '/',
                data : {pageName: 'Landing page'},
                views: {
                    'main@staticpage': {
                        templateUrl : layoutProvider.view('staticpage.landing'),
                        controller  : 'StaticpageLandingController',
                        controllerAs: 'landing'
                    }
                }
            })
            .state('profile', {
                abstract: true,
                url     : '/profile',
                views   : {
                    'layout@'        : {
                        templateUrl : layoutProvider.layout('minimalist.theme'),
                        controller  : 'ProfileController',
                        controllerAs: 'profile'
                    },
                    'header@profile' : {
                        templateUrl : layoutProvider.layout('minimalist.header'),
                        controller  : 'HeaderController',
                        controllerAs: 'header'
                    },
                    'sidenav@profile': {
                        templateUrl : layoutProvider.layout('minimalist.sidenav'),
                        controller  : 'SidenavController',
                        controllerAs: 'sidenav'
                    },
                    'aside@profile'  : {
                        templateUrl : layoutProvider.layout('minimalist.aside'),
                        controller  : 'AsideController',
                        controllerAs: 'aside'
                    },
                    'footer@profile' : {
                        templateUrl : layoutProvider.layout('minimalist.footer'),
                        controller  : 'FooterController',
                        controllerAs: 'footer'
                    },
                    'main@profile'   : {}
                }
            })
            .state('profile.user', {
                url    : '/{user}',
                data   : {pageName: 'Profile'},
                views  : {
                    'main@profile': {
                        templateUrl : layoutProvider.view('profile.user'),
                        controller  : 'ProfileUserController',
                        controllerAs: '$ctrl'
                    }
                },
                resolve: {
                    loginRequired: loginRequired
                }
            });

        function loginRequired($q, $state, $auth) {

            var deferred = $q.defer();

            if ($auth.isAuthenticated()) {
                deferred.resolve();
            } else {
                $state.go('jwtauth.signin');
            }

            return deferred.promise;

        }

    }

})();

<|endoftext|>


<commit_before>$(function(){
	jsNav["vtour"] = function(){

		var resizeVTour= function(){
			// On met la div a la bonne taille
			var SCREEN_WIDTH = (window.innerWidth);
			var SCREEN_HEIGHT = (window.innerHeight);
			var HEADER_HEIGHT = parseInt($("#headerData").css("height").split("px")[0]);
			var FOOTER_HEIGHT = parseInt($("#footerData").css("height").split("px")[0]);

			var height = (SCREEN_HEIGHT - (HEADER_HEIGHT+FOOTER_HEIGHT) - 100);
			$("#divVTour").css({
				"width":SCREEN_WIDTH - 50,
				"height": (height > 200 ? height : 200)
			});
		};

		resizeVTour();
		$(window).unbind("onresize");
		window.onresize = function(event) {
			resizeVTour();
		};

		// SI ONLINE alors recupere sur le site
		/*if(navigator.onLine){
			$("#panoRestaurantSWF").attr("flashvars","browser.useragent="+navigator.userAgent+"&xml=http://www.casino-megeve.com/restaurant-l-equipe/vtour/tour.xml");
			$("#panoRestaurantSWF").attr("src","http://www.casino-megeve.com/restaurant-l-equipe/vtour/tour.swf");
		}else{ */// SINON on prend ce qu'on a en local

			$("#panoRestaurantSWF").attr("flashvars","browser.useragent="+navigator.userAgent+"&xml=data/pano/restaurant/tour.xml");
			$("#panoRestaurantSWF").attr("src","data/pano/restaurant/tour.swf");
			alert($("#panoRestaurantSWF").attr("flashvars"));
		//}
	};

	jsNav["carte"] = function(){
		window.open("http://www.casino-megeve.com/restaurant-l-equipe/carte.pdf");
	};

	if(document.URL.match(/restaurant/gi) != null)
		$("a[data-idjs='vtour']").click();
});<commit_msg>debug<commit_after>$(function(){
	jsNav["vtour"] = function(){

		var resizeVTour= function(){
			// On met la div a la bonne taille
			var SCREEN_WIDTH = (window.innerWidth);
			var SCREEN_HEIGHT = (window.innerHeight);
			var HEADER_HEIGHT = parseInt($("#headerData").css("height").split("px")[0]);
			var FOOTER_HEIGHT = parseInt($("#footerData").css("height").split("px")[0]);

			var height = (SCREEN_HEIGHT - (HEADER_HEIGHT+FOOTER_HEIGHT) - 100);
			$("#divVTour").css({
				"width":SCREEN_WIDTH - 50,
				"height": (height > 200 ? height : 200)
			});
		};

		resizeVTour();
		$(window).unbind("onresize");
		window.onresize = function(event) {
			resizeVTour();
		};

		// SI ONLINE alors recupere sur le site
		/*if(navigator.onLine){
			$("#panoRestaurantSWF").attr("flashvars","browser.useragent="+navigator.userAgent+"&xml=http://www.casino-megeve.com/restaurant-l-equipe/vtour/tour.xml");
			$("#panoRestaurantSWF").attr("src","http://www.casino-megeve.com/restaurant-l-equipe/vtour/tour.swf");
		}else{ */// SINON on prend ce qu'on a en local

			//$("#panoRestaurantSWF").attr("flashvars","browser.useragent="+navigator.userAgent+"&xml=data/pano/restaurant/tour.xml");
			$("#panoRestaurantSWF").attr("src","data/pano/restaurant/tour.swf");
			//alert($("#panoRestaurantSWF").attr("flashvars"));
		//}
	};

	jsNav["carte"] = function(){
		window.open("http://www.casino-megeve.com/restaurant-l-equipe/carte.pdf");
	};

	if(document.URL.match(/restaurant/gi) != null)
		$("a[data-idjs='vtour']").click();
});<|endoftext|>


<commit_before>(function() {
  "use strict";

  var controllers = angular.module('appControllers', [
    'kbLayoutsModule',
    'typingLessonModule'
  ]);

  controllers.controller('MainCtrl', function($rootScope, $scope, kbLayouts, levelManager) {
    var DEFAULT_LAYOUT = "qwerty";
    var DEFAULT_LEVEL = 1;

    $scope.selectedLevel = DEFAULT_LEVEL;
    $scope.selectedLayout = DEFAULT_LAYOUT;
    $scope.layouts = kbLayouts.layouts;
    $scope.levelNumbers = levelManager.levelNumbers;

    $rootScope.rootKeyDown = function(e) {
      $rootScope.$broadcast('keydown', e);
    };

    $rootScope.rootKeyPress = function(e) {
      $rootScope.$broadcast('keypress', e);
    };
  });

  controllers.controller('HomeCtrl', function($scope, $location) {
    var SPACE_KEYCODE = 13;

    $scope.$on('keypress', function(e, kp) {
      var key = kp.charCode || kp.keyCode;
      if (key === SPACE_KEYCODE) {
        $location.url('/layout/qwerty/level/1');
      }
    });
  });

  controllers.controller('TyperCtrl', function($scope, $location, $routeParams, $http, Lesson, levelManager) {
    $scope.lesson = new Lesson();
    $scope.isLevelComplete = false;
    $scope.selectedLayout = $routeParams.layout;
    $scope.selectedLevel = parseInt($routeParams.level);
    $scope.levelNumbers = [];

    // Update page when layout or level changes
    $scope.$watch('selectedLayout', function(cur, prev) {
      if (cur != prev) {
        changeLevel();
      }
    });

    $scope.$watch('selectedLevel', function(cur, prev) {
      if (cur != prev) {
        changeLevel();
      }
    });

    $scope.$watch('isLevelComplete', function(cur) {
      if (cur) {
        var deregEnter = $scope.$on('keypress', function(e, kd) {
          var key = kd.charCode || kd.keyCode;
          if (key === 13) {
            deregEnter();
            $scope.selectedLevel++;
          }
        });
      }
    });

    loadCombos();

    function loadCombos() {
      $http.get(
        '/combos',
        { params: levelManager.getLevelParams($scope.selectedLevel, $scope.selectedLayout) }
      ).success(function(data, status, headers, config) {
        updateLevelNumbers();
        $scope.lesson.start(data.combos);
      }).error(function(data, status, headers, config) {
        console.log("Error requesting /combos");
      });
    }

    function updateLevelNumbers() {
      var total = levelManager.layoutLevels[$scope.selectedLayout].length;
      var numArr = [];
      for (var i = total; i > 0; --i) {
        numArr[i-1] = i;
      }
      $scope.levelNumbers = numArr;
    }

    function changeLevel() {
      $location.url('/layout/' + $scope.selectedLayout  + '/level/' + $scope.selectedLevel);
    }

  });

})();
<commit_msg>Reroutes to level 1 if level does not exist<commit_after>(function() {
  "use strict";

  var controllers = angular.module('appControllers', [
    'kbLayoutsModule',
    'typingLessonModule'
  ]);

  controllers.controller('MainCtrl', function($rootScope, $scope, kbLayouts, levelManager) {
    var DEFAULT_LAYOUT = "qwerty";
    var DEFAULT_LEVEL = 1;

    $scope.selectedLevel = DEFAULT_LEVEL;
    $scope.selectedLayout = DEFAULT_LAYOUT;
    $scope.layouts = kbLayouts.layouts;
    $scope.levelNumbers = levelManager.levelNumbers;

    $rootScope.rootKeyDown = function(e) {
      $rootScope.$broadcast('keydown', e);
    };

    $rootScope.rootKeyPress = function(e) {
      $rootScope.$broadcast('keypress', e);
    };
  });

  controllers.controller('HomeCtrl', function($scope, $location) {
    var SPACE_KEYCODE = 13;

    $scope.$on('keypress', function(e, kp) {
      var key = kp.charCode || kp.keyCode;
      if (key === SPACE_KEYCODE) {
        $location.url('/layout/qwerty/level/1');
      }
    });
  });

  controllers.controller('TyperCtrl', function($scope, $location, $routeParams, $http, Lesson, levelManager) {
    $scope.lesson = new Lesson();
    $scope.isLevelComplete = false;
    $scope.selectedLayout = $routeParams.layout;
    $scope.selectedLevel = parseInt($routeParams.level);
    $scope.levelNumbers = [];

    // Update page when layout or level changes
    $scope.$watch('selectedLayout', function(cur, prev) {
      if (cur != prev) {
        changeLevel();
      }
    });

    $scope.$watch('selectedLevel', function(cur, prev) {
      if (cur != prev) {
        changeLevel();
      }
    });

    $scope.$watch('isLevelComplete', function(cur) {
      if (cur) {
        var deregEnter = $scope.$on('keypress', function(e, kd) {
          var key = kd.charCode || kd.keyCode;
          if (key === 13) {
            deregEnter();
            $scope.selectedLevel++;
          }
        });
      }
    });

    loadCombos();

    function loadCombos() {
      var levelParams = levelManager.getLevelParams($scope.selectedLevel, $scope.selectedLayout);
      // If no level params, go back to lesson 1
      if (!levelParams) {
        changeLevel(1);
        return;
      }

      $http.get(
        '/combos',
        { params: levelParams }
      ).success(function(data, status, headers, config) {
        updateLevelNumbers();
        $scope.lesson.start(data.combos);
      }).error(function(data, status, headers, config) {
        console.log("Error requesting /combos");
      });
    }

    function updateLevelNumbers() {
      var total = levelManager.layoutLevels[$scope.selectedLayout].length;
      var numArr = [];
      for (var i = total; i > 0; --i) {
        numArr[i-1] = i;
      }
      $scope.levelNumbers = numArr;
    }

    function changeLevel(level) {
      $location.url('/layout/' + $scope.selectedLayout + '/level/' + (level || $scope.selectedLevel));
    }

  });

})();
<|endoftext|>


<commit_before>import React from 'react';
import ReactDOM from 'react-dom';
import { DraftailEditor } from 'draftail';

import { IS_IE11, STRINGS } from '../../config/wagtailConfig';

import Icon from '../Icon/Icon';

import Link from './decorators/Link';
import Document from './decorators/Document';
import ImageBlock from './blocks/ImageBlock';
import EmbedBlock from './blocks/EmbedBlock';

import ModalWorkflowSource from './sources/ModalWorkflowSource';

import registry from './registry';

const wrapWagtailIcon = type => {
  if (type.icon) {
    return Object.assign(type, {
      icon: <Icon name={type.icon} />,
    });
  }

  return type;
};

export const initEditor = (fieldName, options = {}) => {
  const field = document.querySelector(`[name="${fieldName}"]`);
  const editorWrapper = document.createElement('div');
  field.parentNode.appendChild(editorWrapper);

  const serialiseInputValue = rawContentState => {
    field.value = JSON.stringify(rawContentState);
  };

  let blockTypes;
  let inlineStyles;
  let entityTypes;

  if (options && options.blockTypes) {
    blockTypes = options.blockTypes.map(wrapWagtailIcon);
  }

  if (options && options.inlineStyles) {
    inlineStyles = options.inlineStyles.map(wrapWagtailIcon);
  }

  if (options && options.entityTypes) {
    entityTypes = options.entityTypes.map(wrapWagtailIcon).map(type =>
      Object.assign(type, {
        source: registry.getSource(type.source),
        strategy: registry.getStrategy(type.type) || null,
        decorator: registry.getDecorator(type.decorator),
        block: registry.getBlock(type.block),
      })
    );
  }

  const enableHorizontalRule = options && options.enableHorizontalRule ? {
    description: STRINGS.HORIZONTAL_LINE,
  } : false;

  const rawContentState = JSON.parse(field.value);

  const editor = (
    <DraftailEditor
      rawContentState={rawContentState}
      onSave={serialiseInputValue}
      placeholder={STRINGS.WRITE_HERE}
      spellCheck={true}
      enableLineBreak={{ description: STRINGS.LINE_BREAK }}
      showUndoControl={{ description: STRINGS.UNDO }}
      showRedoControl={{ description: STRINGS.REDO }}
      // If increasing above 4, we will need to add styles for the extra nesting levels.
      maxListNesting={4}
      // Draft.js + IE 11 presents some issues with pasting rich text. Disable rich paste there.
      stripPastedStyles={IS_IE11}
      {...options}
      blockTypes={blockTypes}
      inlineStyles={inlineStyles}
      entityTypes={entityTypes}
      enableHorizontalRule={enableHorizontalRule}
    />
  );

  const draftailEditor = ReactDOM.render(editor, editorWrapper);

  // Bind editor instance to its field so it can be accessed imperatively elsewhere.
  field.draftailEditor = draftailEditor;
};

registry.registerSources({
  ModalWorkflowSource,
});
registry.registerDecorators({
  Link,
  Document,
});
registry.registerBlocks({
  ImageBlock,
  EmbedBlock,
});

const draftail = Object.assign(
  {
    initEditor,
  },
  registry
);

export default draftail;
<commit_msg>Make it possible to use SVG icons in Draftail<commit_after>import React from 'react';
import ReactDOM from 'react-dom';
import { DraftailEditor } from 'draftail';

import { IS_IE11, STRINGS } from '../../config/wagtailConfig';

import Icon from '../Icon/Icon';

import Link from './decorators/Link';
import Document from './decorators/Document';
import ImageBlock from './blocks/ImageBlock';
import EmbedBlock from './blocks/EmbedBlock';

import ModalWorkflowSource from './sources/ModalWorkflowSource';

import registry from './registry';

const wrapWagtailIcon = type => {
  const isIconFont = type.icon && typeof type.icon === 'string';
  if (isIconFont) {
    return Object.assign(type, {
      icon: <Icon name={type.icon} />,
    });
  }

  return type;
};

export const initEditor = (fieldName, options = {}) => {
  const field = document.querySelector(`[name="${fieldName}"]`);
  const editorWrapper = document.createElement('div');
  field.parentNode.appendChild(editorWrapper);

  const serialiseInputValue = rawContentState => {
    field.value = JSON.stringify(rawContentState);
  };

  let blockTypes;
  let inlineStyles;
  let entityTypes;

  if (options && options.blockTypes) {
    blockTypes = options.blockTypes.map(wrapWagtailIcon);
  }

  if (options && options.inlineStyles) {
    inlineStyles = options.inlineStyles.map(wrapWagtailIcon);
  }

  if (options && options.entityTypes) {
    entityTypes = options.entityTypes.map(wrapWagtailIcon).map(type =>
      Object.assign(type, {
        source: registry.getSource(type.source),
        strategy: registry.getStrategy(type.type) || null,
        decorator: registry.getDecorator(type.decorator),
        block: registry.getBlock(type.block),
      })
    );
  }

  const enableHorizontalRule = options && options.enableHorizontalRule ? {
    description: STRINGS.HORIZONTAL_LINE,
  } : false;

  const rawContentState = JSON.parse(field.value);

  const editor = (
    <DraftailEditor
      rawContentState={rawContentState}
      onSave={serialiseInputValue}
      placeholder={STRINGS.WRITE_HERE}
      spellCheck={true}
      enableLineBreak={{ description: STRINGS.LINE_BREAK }}
      showUndoControl={{ description: STRINGS.UNDO }}
      showRedoControl={{ description: STRINGS.REDO }}
      // If increasing above 4, we will need to add styles for the extra nesting levels.
      maxListNesting={4}
      // Draft.js + IE 11 presents some issues with pasting rich text. Disable rich paste there.
      stripPastedStyles={IS_IE11}
      {...options}
      blockTypes={blockTypes}
      inlineStyles={inlineStyles}
      entityTypes={entityTypes}
      enableHorizontalRule={enableHorizontalRule}
    />
  );

  const draftailEditor = ReactDOM.render(editor, editorWrapper);

  // Bind editor instance to its field so it can be accessed imperatively elsewhere.
  field.draftailEditor = draftailEditor;
};

registry.registerSources({
  ModalWorkflowSource,
});
registry.registerDecorators({
  Link,
  Document,
});
registry.registerBlocks({
  ImageBlock,
  EmbedBlock,
});

const draftail = Object.assign(
  {
    initEditor,
  },
  registry
);

export default draftail;
<|endoftext|>


<commit_before>var HeaderExplain = require('components/explore/HeaderExplain');
var LinkNoClobber = require('components/common/LinkNoClobber');
var LoginButton = require('components/common/LoginButton');
var CreateButton = require('components/common/CreateButton');
var React = require('react');
var ScrollListenerMixin = require('react-scroll-components/ScrollListenerMixin');
var Logo = require('components/common/Logo');

var getLinearInterpolation = require('helpers/getLinearInterpolation');
var getUniqueId = require('react-pick/lib/helpers/getUniqueId');
var joinClasses = require('react/lib/joinClasses');
var userPropType = require('types/userPropType');

require('3rdparty/bootstrap/css/bootstrap.css');
require('./Header.css');

var Header = React.createClass({

  mixins: [ScrollListenerMixin],

  propTypes: {
    currentUser: userPropType
  },

  getInitialState: function() {
    return {
      id: getUniqueId('Header'),
      transition: {start: 0, end: Infinity, scale: 1},
      isExpanded: false
    };
  },

  handleCreateButtonRef: function(button) {
    if (!button) {
      return;
    }

    var headerRect = this.refs['header'].getDOMNode().getBoundingClientRect();
    var buttonRect = button.getDOMNode().getBoundingClientRect();
    var scrollTop = window.scrollY;

    this.setState({
      transition: {
        start: (buttonRect.top + scrollTop) - headerRect.height,
        end: (buttonRect.bottom + scrollTop) - headerRect.height,
        scale: headerRect.height / buttonRect.height
      }
    });
  },

  handleToggleClick: function() {
    this.setState({isExpanded: !this.state.isExpanded});
  },

  renderUserNav: function() {
    if (this.props.currentUser) {
      return [

            {this.props.currentUser.name}

,

Log out

      ];
    } else {
      return [

<LoginButton/>

      ];
    }
  },

  renderCreateButton: function() {
    var buttonTop = getLinearInterpolation(
      this.state.scrollTop,
      this.state.transition.start,
      this.state.transition.end,
      45,
      0
    );

    return (

        <CreateButton
          style={{top:buttonTop}}
          className="Header-create-button navbar-btn"
        />

    );
  },

  render: function() {
    var {children, className, ...otherProps} = this.props;

    return (

              <button
                aria-expanded={this.state.isExpanded+''}
                className="navbar-toggle collapsed"
                onClick={this.handleToggleClick}
                target={'#' + this.state.id}
                type="button">
                Toggle navigation

              </button>

              <Logo className="navbar-brand"/>

                {this.renderCreateButton()}
                {this.renderUserNav()}

        {(this.props.currentUser === null)
          ? <HeaderExplain createButtonRef={this.handleCreateButtonRef}/>
          : null}

    );
  }

});

module.exports = Header;<commit_msg>Fix the create button for logged-in users.<commit_after>var HeaderExplain = require('components/explore/HeaderExplain');
var LinkNoClobber = require('components/common/LinkNoClobber');
var LoginButton = require('components/common/LoginButton');
var CreateButton = require('components/common/CreateButton');
var React = require('react');
var ScrollListenerMixin = require('react-scroll-components/ScrollListenerMixin');
var Logo = require('components/common/Logo');

var getLinearInterpolation = require('helpers/getLinearInterpolation');
var getUniqueId = require('react-pick/lib/helpers/getUniqueId');
var joinClasses = require('react/lib/joinClasses');
var userPropType = require('types/userPropType');

require('3rdparty/bootstrap/css/bootstrap.css');
require('./Header.css');

var Header = React.createClass({

  mixins: [ScrollListenerMixin],

  propTypes: {
    currentUser: userPropType
  },

  getInitialState: function() {
    return {
      id: getUniqueId('Header'),
      transition: {start: 0, end: Infinity, scale: 1},
      isExpanded: false
    };
  },

  isRenderingExplain: function() {
    return this.props.currentUser === null;
  },

  handleCreateButtonRef: function(button) {
    if (!button) {
      return;
    }

    var headerRect = this.refs['header'].getDOMNode().getBoundingClientRect();
    var buttonRect = button.getDOMNode().getBoundingClientRect();
    var scrollTop = window.scrollY;

    this.setState({
      transition: {
        start: (buttonRect.top + scrollTop) - headerRect.height,
        end: (buttonRect.bottom + scrollTop) - headerRect.height,
        scale: headerRect.height / buttonRect.height
      }
    });
  },

  handleToggleClick: function() {
    this.setState({isExpanded: !this.state.isExpanded});
  },

  renderUserNav: function() {
    if (this.props.currentUser) {
      return [

            {this.props.currentUser.name}

,

Log out

      ];
    } else {
      return [

<LoginButton/>

      ];
    }
  },

  renderCreateButton: function() {
    var buttonTop = getLinearInterpolation(
      this.state.scrollTop,
      this.state.transition.start,
      this.state.transition.end,
      45,
      0
    );

    return (

        <CreateButton
          style={this.isRenderingExplain() ? {top:buttonTop} : {}}
          className="Header-create-button navbar-btn"
        />

    );
  },

  render: function() {
    var {children, className, ...otherProps} = this.props;

    return (

              <button
                aria-expanded={this.state.isExpanded+''}
                className="navbar-toggle collapsed"
                onClick={this.handleToggleClick}
                target={'#' + this.state.id}
                type="button">
                Toggle navigation

              </button>

              <Logo className="navbar-brand"/>

                {this.renderCreateButton()}
                {this.renderUserNav()}

        {this.isRenderingExplain() && (
          <HeaderExplain createButtonRef={this.handleCreateButtonRef}/>
        )}

    );
  }

});

module.exports = Header;<|endoftext|>


<commit_before>var data = [4, 8, 15, 16, 23, 42];

var camera, scene, renderer, chart3d, newBar;

// эти методы нужны для D3-шных .append() и .selectAll()
THREE.Object3D.prototype.appendChild = function (c) { this.add(c); return c; };
THREE.Object3D.prototype.querySelectorAll = function () { return []; };

// а этот - для D3-шного .attr()
THREE.Object3D.prototype.setAttribute = function (name, value) {
    var chain = name.split('.');
    var object = this;
    for (var i = 0; i < chain.length - 1; i++) {
        object = object[chain[i]];
    }
    object[chain[chain.length - 1]] = value;
}

init();
update();
animate();

function update () {
    // используем D3 для стоздания 3D столбцов
    d3.select( chart3d )
        .selectAll()
        .data(data)
    .enter().append( newBar )
        .attr("position.x", function(d, i) { return 30 * (i - 3); })
        .attr("position.y", function(d, i) { return d; })
        .attr("scale.y", function(d, i) { return d / 10; })
}

function init () {
    renderer = new THREE.WebGLRenderer();
    renderer.setSize( window.innerWidth, window.innerHeight );
    document.body.appendChild( renderer.domElement );

    camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 1, 1000 );
    camera.position.z = 400;

    scene = new THREE.Scene();

    var light = new THREE.DirectionalLight( 0xffffff );
    light.position.set( 0, 0, 1 );
    scene.add( light );

    var geometry = new THREE.CubeGeometry( 20, 20, 20 );
    var material = new THREE.MeshLambertMaterial( {
        color: 0x4682B4, shading: THREE.FlatShading, vertexColors: THREE.VertexColors } );

    // создаём контейнер для 3D гистограммы
    chart3d = new THREE.Object3D();
  chart3d.rotation.x = 0.6;
  scene.add( chart3d );

    // создаём функцию newBar() для D3
    newBar = function() { return new THREE.Mesh( geometry, material ); }

    window.addEventListener( 'resize', onWindowResize, false );
}

function onWindowResize () {

    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();

    renderer.setSize( window.innerWidth, window.innerHeight );

}

function animate () {

    requestAnimationFrame( animate );

    chart3d.rotation.y += 0.01;

    renderer.render( scene, camera );

}<commit_msg>3d dataviz first shot<commit_after>var data = [];

var camera, scene, renderer, chart3d, newBar;

// эти методы нужны для D3-шных .append() и .selectAll()
THREE.Object3D.prototype.appendChild = function (c) { this.add(c); return c; };
THREE.Object3D.prototype.querySelectorAll = function () { return []; };

// а этот - для D3-шного .attr()
THREE.Object3D.prototype.setAttribute = function (name, value) {
    var chain = name.split('.');
    var object = this;
    for (var i = 0; i < chain.length - 1; i++) {
        object = object[chain[i]];
    }
    object[chain[chain.length - 1]] = value;
}

d3.csv("3d.csv", function(error, csvdata) {
  csvdata.forEach(function(d, j) {

    for (var i = 0; i < 23; i++) {
        data.push([i, j, d[i] ]);
    };

  });

  init();
  update();
  animate();

});

function update () {
    // используем D3 для стоздания 3D столбцов
    d3.select( chart3d )
        .selectAll()
        .data(data)
    .enter().append( newBar )
        .attr("position.x", function(d, i) {   return 30 * (d[1]- 3); })
        .attr("position.y", function(d, i) { return d[2] * 4; })
        .attr("position.z", function(d, i) { return d[0] * 30; })
        .attr("scale.y", function(d, i) { return d[2] * 4 / 10; })
}

function init () {

    renderer = new THREE.WebGLRenderer();
    renderer.setSize( window.innerWidth, window.innerHeight );
    document.body.appendChild( renderer.domElement );

    camera = new THREE.PerspectiveCamera( 60, window.innerWidth / window.innerHeight, 1, 50000 );
    camera.position.z = 1300;
    camera.position.x = 400;
    camera.position.y = -100;

    scene = new THREE.Scene();

    var light = new THREE.DirectionalLight( 0xffffff );
    light.position.set( 0, 0.6, 1 );
    scene.add( light );

    var geometry = new THREE.CubeGeometry( 28, 28, 28 );
    var material = new THREE.MeshLambertMaterial( {
        color: 0x4682B4, shading: THREE.FlatShading, vertexColors: THREE.VertexColors } );

    // создаём контейнер для 3D гистограммы
    chart3d = new THREE.Object3D();
    chart3d.rotation.x = 0.6;
    chart3d.rotation.y += 0.57;
    scene.add( chart3d );

    // создаём функцию newBar() для D3
    newBar = function() { return new THREE.Mesh( geometry, material ); }

    window.addEventListener( 'resize', onWindowResize, false );
}

function onWindowResize () {

    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();

    renderer.setSize( window.innerWidth, window.innerHeight );

}

function animate () {

    requestAnimationFrame( animate );

    renderer.render( scene, camera );

}<|endoftext|>


<commit_before>import _ from 'lodash';
import http from 'https';
import url from 'url';
// import sizeOf from 'image-size';
import ApiDataInstance from './ApiDataInstance';
import { ENTITY } from './CONSTANT';

/*
function getImageSize(imageUrl) {
    return new Promise((resolve, reject) => {
        imageUrl = url.parse(imageUrl);
        https.get(options, (response) => {
            let chuncks = [];
            response.on('data', (chunk) => {
                chunks.push(chunk);
            })
            .on('end', () => {
                let buffer = Buffer.concat(chunks);
                // resolve(sizeOf(buffer));
                resolve({});
            })
            .on('error', (err) => {
                reject(err);
            });
        });
    });
    }
    */

function getResizedImageUrls(imageUrl) {
    let desktop = '';
    let mobile = '';
    let tablet = '';
    // TODO check url pattern
    if (imageUrl && typeof imageUrl === 'string') {
        const matched = imageUrl.match(/(\.[^.]+)?$/);
        let ext = '';
        let url = '';
        if (matched !== null) {
            url = imageUrl.substr(0, matched.index);
            ext = matched[0];
        } else {
            url = imageUrl;
        }
        desktop = url + '-desktop' + ext;
        mobile = url + '-mobile' + ext;
        tablet = url + '-tablet' + ext;
    }
    return {
        desktop,
        mobile,
        tablet
    };
}

const processor = {
    convertBlock(entityMap, block) {
        let alignment = 'center';
        let content;
        let entityRange = block.entityRanges[0];
        const entity = entityMap[entityRange.key];
        const type = entity && entity.type;
        switch (type) {
            case ENTITY.embeddedCode.type:
                alignment = entity.data && entity.data.alignment || alignment;
                content = [ {
                    caption: entity.data.caption,
                    embeddedCode: entity.data.embeddedCode
                }];
                break;
            case ENTITY.slideshow.type:
            case ENTITY.imageDiff.type:
                alignment = entity.data && entity.data.alignment || alignment;
                content = this.convertImagesBlock(entity);
                break;
            case ENTITY.image.type:
                alignment = entity.data && entity.data.alignment || alignment;
                content = [this.convertImageBlock(entity)];
                break;
            default:
                return;
        }
        return new ApiDataInstance({alignment, type, content})
    },

    convertImageBlock(entity) {
        let image = entity.data || {};
        let rtn = {};
        let urls = getResizedImageUrls(image.url);
        Object.keys(urls).forEach((device) => {
            rtn[device] = _.merge({url: urls[device]}, _.pick(image, ['id', 'description']));
        });
        _.set(rtn, 'original', image);
        return rtn;
    },

    convertImagesBlock(entity) {
        let images = Array.isArray(entity.data.images) ? entity.data.images : [];
        return this._convertImagesBlock(images);
    },

    _convertImagesBlock(images) {
        return images.map((image) => {
            let imageSet = {};
            let urls = getResizedImageUrls(image.url);
            Object.keys(urls).forEach((device) => {
                imageSet[device] = _.merge({url: urls[device]}, _.pick(image, ['id', 'description']));
            });
            _.set(imageSet, 'original', image);
            return imageSet;
        });
    }
};

export default processor;
<commit_msg>insert infobox atomic block<commit_after>import _ from 'lodash';
import http from 'https';
import url from 'url';
// import sizeOf from 'image-size';
import ApiDataInstance from './ApiDataInstance';
import { ENTITY } from './CONSTANT';

/*
function getImageSize(imageUrl) {
    return new Promise((resolve, reject) => {
        imageUrl = url.parse(imageUrl);
        https.get(options, (response) => {
            let chuncks = [];
            response.on('data', (chunk) => {
                chunks.push(chunk);
            })
            .on('end', () => {
                let buffer = Buffer.concat(chunks);
                // resolve(sizeOf(buffer));
                resolve({});
            })
            .on('error', (err) => {
                reject(err);
            });
        });
    });
    }
    */

function getResizedImageUrls(imageUrl) {
    let desktop = '';
    let mobile = '';
    let tablet = '';
    // TODO check url pattern
    if (imageUrl && typeof imageUrl === 'string') {
        const matched = imageUrl.match(/(\.[^.]+)?$/);
        let ext = '';
        let url = '';
        if (matched !== null) {
            url = imageUrl.substr(0, matched.index);
            ext = matched[0];
        } else {
            url = imageUrl;
        }
        desktop = url + '-desktop' + ext;
        mobile = url + '-mobile' + ext;
        tablet = url + '-tablet' + ext;
    }
    return {
        desktop,
        mobile,
        tablet
    };
}

const processor = {
    convertBlock(entityMap, block) {
        let alignment = 'center';
        let content;
        let entityRange = block.entityRanges[0];
        const entity = entityMap[entityRange.key];
        const type = entity && entity.type;
        switch (type) {
            case ENTITY.infobox.type:
                alignment = entity.data && entity.data.alignment || alignment;
                content = [ {
                    title: entity.data.title,
                    body: entity.data.body
                }];
                break;
            case ENTITY.embeddedCode.type:
                alignment = entity.data && entity.data.alignment || alignment;
                content = [ {
                    caption: entity.data.caption,
                    embeddedCode: entity.data.embeddedCode
                }];
                break;
            case ENTITY.slideshow.type:
            case ENTITY.imageDiff.type:
                alignment = entity.data && entity.data.alignment || alignment;
                content = this.convertImagesBlock(entity);
                break;
            case ENTITY.image.type:
                alignment = entity.data && entity.data.alignment || alignment;
                content = [this.convertImageBlock(entity)];
                break;
            default:
                return;
        }
        return new ApiDataInstance({alignment, type, content})
    },

    convertImageBlock(entity) {
        let image = entity.data || {};
        let rtn = {};
        let urls = getResizedImageUrls(image.url);
        Object.keys(urls).forEach((device) => {
            rtn[device] = _.merge({url: urls[device]}, _.pick(image, ['id', 'description']));
        });
        _.set(rtn, 'original', image);
        return rtn;
    },

    convertImagesBlock(entity) {
        let images = Array.isArray(entity.data.images) ? entity.data.images : [];
        return this._convertImagesBlock(images);
    },

    _convertImagesBlock(images) {
        return images.map((image) => {
            let imageSet = {};
            let urls = getResizedImageUrls(image.url);
            Object.keys(urls).forEach((device) => {
                imageSet[device] = _.merge({url: urls[device]}, _.pick(image, ['id', 'description']));
            });
            _.set(imageSet, 'original', image);
            return imageSet;
        });
    }
};

export default processor;
<|endoftext|>


<commit_before>(function(){
  'use strict';

  angular.module('app.core')
         .factory('dataLPSservice', DataLPSservice);
  DataLPSservice.$inject=['$q', '$rootScope'];

  /**
   * @name DataLPSservice
   * @desc Uses Local Persistent Storage (LPS) based on IndexedDB; acts asynchronously
   * @param $q
   * @param $rootScope
   * @returns {{loadAll: Function}}
   * @constructor
   */
  function DataLPSservice($q, $rootScope){
    var ePersonStatusEnum = {
      TAXAUTH   : 1,
      LEGALP    : 2,
      NATPERS   : 3,
      PENTREP   : 4,
      FREELANCE : 5,
      properties : {
        1 : { descr : "Податковий орган",  isnatpers : false, },
        2 : { descr : "Юридична особа",    isnatpers : false, },
        3 : { descr : "Фізична особа",     isnatpers : true,  },
        4 : { descr : "ФО - підприємець",  isnatpers : true,  },
        5 : { descr : "Самозайнята особа", isnatpers : true,  },
      },
    };
    if (Object.freeze())
      Object.freeze(ePersonStatusEnum);

    var ePersonAptTypeEnum = {
      APT     : 1,
      OFFICE  : 2,
      properties : {
        1 : { descr : "кв.", },
        2 : { descr : "оф.", },
      },
    };
    if (Object.freeze())
      Object.freeze(ePersonAptTypeEnum);

    var persons = [
      new ePerson("Руденко",  "Олексій",  "Анатолійович", true,     ePersonStatusEnum.NATPERS,    "CH788108", "2694204152", "",
                  "Україна",  "м.Київ",   "", "02031",    "м.Київ", "ДПІ у Шевченківському р-ні",
                  "Кудрявський узвіз",    10, "", 1,      ePersonAptTypeEnum.APT,
                  "+380501112233",        "oleksiy.rudenko@gmailx.com",     'svg-2',  "Principal"
      ),
      new ePerson("Петренко", "Петро",    "Петрович",     true,     ePersonStatusEnum.NATPERS,    "CM888222", "2694203333", "",
                  "Україна",  "м.Київ",   "", "03033",    "м.Київ", "ДПІ у Голосіївському р-ні",
                  "вул.Васильківська",    30, "", 3,      ePersonAptTypeEnum.APT,
                  "+380503334455",        "petro.petrenko@gmailx.com",      'svg-1',  ""
      )
    ];

    // session vars
    var session = {
      declarantCurrent: persons[0],
    };

    // Promise-based API
    // Service interface
    var service = {
      enums : {
        ePersonStatus   : ePersonStatusEnum,
        ePersonAptType  : ePersonAptTypeEnum,
      },
      declarants : {
        loadAll     : declarantsLoadAll,
        getCurrent  : declarantsGetCurrent,
        setCurrent  : declarantsSetCurrent,
      },
    };

    return service;

    /**
     * @name declarantsLoadAll
     * @desc Loads all users
     * @returns {Array}
     */
    function declarantsLoadAll() {
      // Simulate async nature of real remote calls
      return $q.when(persons);
    };

    /**
     * @name declarantsGetCurrent
     * @desc Returns current decalarant (declarantCurrent selected or default)
     * @returns {Object}
     */
    function declarantsGetCurrent() {
      return session.declarantCurrent;
    };
    /**
     * @name declarantsSetCurrent
     * @desc Sets declarantCurrent as current declarant
     * @param entity
     */
    function declarantsSetCurrent(entity) {
      session.declarantCurrent = entity;
      $rootScope.$applyAsync();
    };

  }

  // ==================================================================================================
  /**
   * @name ePerson
   * @desc Person Entity object constructor
   * @param *
   * @returns {Object}
   * @constructor
   */
  function ePerson(nameLast,    // for legal entities: principal name
                   nameFirst,   // for legal entities: abbreviated principal name
                   namePat,     // for legal entities: incorporation form (Ltd, Inc. etc)
                   isUAresident,
                   status,
                   passportNr,
                   idUAtaxCode,
                   idCodeSubst,
                   addrCountry,
                   addrRegion,
                   addrDistrict,
                   addrPO,
                   addrCity,
                   addrCityDistrict,
                   addrStreet,
                   addrBuilding,
                   addrSubBuilding,
                   addrApt,
                   addrAptType,
                   telNr,
                   email,
                   avatarid,
                   comment
    ) {
    this.id           = 0;
    this.isActive     = true;

    this.nameLast	    =	nameLast;
    this.nameFirst	  =	nameFirst;
    this.namePat	    =	namePat;
    this.isUAresident	=	isUAresident;
    this.status	      =	status;
    this.passportNr	  =	passportNr;
    this.idUAtaxCode	=	idUAtaxCode;
    this.idCodeSubst	=	idCodeSubst;
    this.addrCountry	=	addrCountry;
    this.addrRegion	  =	addrRegion;
    this.addrDistrict	=	addrDistrict;
    this.addrPO	      =	addrPO;
    this.addrCity	    =	addrCity;
    this.addrCityDistrict	=	addrCityDistrict;
    this.addrStreet	  =	addrStreet;
    this.addrBuilding	=	addrBuilding;
    this.addrSubBuilding	=	addrSubBuilding;
    this.addrApt	    =	addrApt;
    this.addrAptType	=	addrAptType;
    this.telNr	      =	telNr;
    this.email	      =	email;
    this.avatarid     = avatarid;
    this.comment      = comment;

    this.nameFull = function() {
      return this.nameLast + ' ' + this.nameFirst + ' ' + this.namePat;
    };
    this.nameShort = function() {
      return this.nameFirst + ' ' + this.nameLast;
    };
    this.nameFirstInitial = function() {
      return this.nameFirst.charAt(0);
    };
    this.namePatInitial = function() {
      return this.namePat.charAt(0);
    };
    this.nameInitials = function() {
      return this.nameFirstInitial() + '.' + this.namePatInitial() +'.';
    };
    this.nameLastInitials = function() {
      return this.nameLast + ' ' + this.nameInitials();
    };

    this.nameFullCorp = function() {
      return this.nameLast + ', ' + this.namePat;
    };
    this.nameShortCorp = function() {
      return this.nameFirst + ', ' + this.namePat;
    };
  }

})();
<commit_msg>Make comment more specific<commit_after>(function(){
  'use strict';

  angular.module('app.core')
         .factory('dataLPSservice', DataLPSservice);
  DataLPSservice.$inject=['$q', '$rootScope'];

  /**
   * @name DataLPSservice
   * @desc Uses Local Persistent Storage (LPS) based on IndexedDB; acts asynchronously
   * @param $q
   * @param $rootScope
   * @returns {{loadAll: Function}}
   * @constructor
   */
  function DataLPSservice($q, $rootScope){
    var ePersonStatusEnum = {
      TAXAUTH   : 1,
      LEGALP    : 2,
      NATPERS   : 3,
      PENTREP   : 4,
      FREELANCE : 5,
      properties : {
        1 : { descr : "Податковий орган",  isnatpers : false, },
        2 : { descr : "Юридична особа",    isnatpers : false, },
        3 : { descr : "Фізична особа",     isnatpers : true,  },
        4 : { descr : "ФО - підприємець",  isnatpers : true,  },
        5 : { descr : "Самозайнята особа", isnatpers : true,  },
      },
    };
    if (Object.freeze())
      Object.freeze(ePersonStatusEnum);

    var ePersonAptTypeEnum = {
      APT     : 1,
      OFFICE  : 2,
      properties : {
        1 : { descr : "кв.", },
        2 : { descr : "оф.", },
      },
    };
    if (Object.freeze())
      Object.freeze(ePersonAptTypeEnum);

    var persons = [
      new ePerson("Руденко",  "Олексій",  "Анатолійович", true,     ePersonStatusEnum.NATPERS,    "CH788108", "2694204152", "",
                  "Україна",  "м.Київ",   "", "02031",    "м.Київ", "ДПІ у Шевченківському р-ні",
                  "Кудрявський узвіз",    10, "", 1,      ePersonAptTypeEnum.APT,
                  "+380501112233",        "oleksiy.rudenko@gmailx.com",     'svg-2',  "Principal"
      ),
      new ePerson("Петренко", "Петро",    "Петрович",     true,     ePersonStatusEnum.NATPERS,    "CM888222", "2694203333", "",
                  "Україна",  "м.Київ",   "", "03033",    "м.Київ", "ДПІ у Голосіївському р-ні",
                  "вул.Васильківська",    30, "", 3,      ePersonAptTypeEnum.APT,
                  "+380503334455",        "petro.petrenko@gmailx.com",      'svg-1',  ""
      )
    ];

    // session lifespan private vars
    var session = {
      declarantCurrent: persons[0],
    };

    // Promise-based API
    // Service interface
    var service = {
      enums : {
        ePersonStatus   : ePersonStatusEnum,
        ePersonAptType  : ePersonAptTypeEnum,
      },
      declarants : {
        loadAll     : declarantsLoadAll,
        getCurrent  : declarantsGetCurrent,
        setCurrent  : declarantsSetCurrent,
      },
    };

    return service;

    /**
     * @name declarantsLoadAll
     * @desc Loads all users
     * @returns {Array}
     */
    function declarantsLoadAll() {
      // Simulate async nature of real remote calls
      return $q.when(persons);
    };

    /**
     * @name declarantsGetCurrent
     * @desc Returns current decalarant (declarantCurrent selected or default)
     * @returns {Object}
     */
    function declarantsGetCurrent() {
      return session.declarantCurrent;
    };
    /**
     * @name declarantsSetCurrent
     * @desc Sets declarantCurrent as current declarant
     * @param entity
     */
    function declarantsSetCurrent(entity) {
      session.declarantCurrent = entity;
      $rootScope.$applyAsync();
    };

  }

  // ==================================================================================================
  /**
   * @name ePerson
   * @desc Person Entity object constructor
   * @param *
   * @returns {Object}
   * @constructor
   */
  function ePerson(nameLast,    // for legal entities: principal name
                   nameFirst,   // for legal entities: abbreviated principal name
                   namePat,     // for legal entities: incorporation form (Ltd, Inc. etc)
                   isUAresident,
                   status,
                   passportNr,
                   idUAtaxCode,
                   idCodeSubst,
                   addrCountry,
                   addrRegion,
                   addrDistrict,
                   addrPO,
                   addrCity,
                   addrCityDistrict,
                   addrStreet,
                   addrBuilding,
                   addrSubBuilding,
                   addrApt,
                   addrAptType,
                   telNr,
                   email,
                   avatarid,
                   comment
    ) {
    this.id           = 0;
    this.isActive     = true;

    this.nameLast	    =	nameLast;
    this.nameFirst	  =	nameFirst;
    this.namePat	    =	namePat;
    this.isUAresident	=	isUAresident;
    this.status	      =	status;
    this.passportNr	  =	passportNr;
    this.idUAtaxCode	=	idUAtaxCode;
    this.idCodeSubst	=	idCodeSubst;
    this.addrCountry	=	addrCountry;
    this.addrRegion	  =	addrRegion;
    this.addrDistrict	=	addrDistrict;
    this.addrPO	      =	addrPO;
    this.addrCity	    =	addrCity;
    this.addrCityDistrict	=	addrCityDistrict;
    this.addrStreet	  =	addrStreet;
    this.addrBuilding	=	addrBuilding;
    this.addrSubBuilding	=	addrSubBuilding;
    this.addrApt	    =	addrApt;
    this.addrAptType	=	addrAptType;
    this.telNr	      =	telNr;
    this.email	      =	email;
    this.avatarid     = avatarid;
    this.comment      = comment;

    this.nameFull = function() {
      return this.nameLast + ' ' + this.nameFirst + ' ' + this.namePat;
    };
    this.nameShort = function() {
      return this.nameFirst + ' ' + this.nameLast;
    };
    this.nameFirstInitial = function() {
      return this.nameFirst.charAt(0);
    };
    this.namePatInitial = function() {
      return this.namePat.charAt(0);
    };
    this.nameInitials = function() {
      return this.nameFirstInitial() + '.' + this.namePatInitial() +'.';
    };
    this.nameLastInitials = function() {
      return this.nameLast + ' ' + this.nameInitials();
    };

    this.nameFullCorp = function() {
      return this.nameLast + ', ' + this.namePat;
    };
    this.nameShortCorp = function() {
      return this.nameFirst + ', ' + this.namePat;
    };
  }

})();
<|endoftext|>


<commit_before>exports = module.exports = function(flows) {

  return function prompt(req, res, next) {
    var prompt = req.oauth2.info.prompt;
    var options = req.oauth2.info;
    delete options.prompt;
    options.state = req.oauth2.transactionID;

    switch (prompt) {
    case 'consent':
      options.clientID = req.oauth2.client.id;
      // TODO: Add audience
      break;
    }

    flows.goto(prompt, options, req, res, next);
  };
};

exports['@require'] = [
  'http://i.bixbyjs.org/http/state/Dispatcher'
];
<commit_msg>Handle prompt=none errors.<commit_after>exports = module.exports = function(flows) {
  var oauth2orize = require('oauth2orize');

  return function prompt(req, res, next) {
    var areq = req.oauth2.req
      , prompt = req.oauth2.info.prompt
      , error = 'interaction_required'
      , options;

    if (areq.prompt && areq.prompt.indexOf('none') !== -1) {
      switch (prompt) {
      case 'login':
        error = 'login_required';
        break;
      case 'consent':
        error = 'consent_required';
        break;
        // TODO: Account selection
      }

      return next(new oauth2orize.AuthorizationError('Interaction with user is required to proceed', error, null, 403));
    }

    options = req.oauth2.info;
    delete options.prompt;
    options.state = req.oauth2.transactionID;

    switch (prompt) {
    case 'consent':
      options.clientID = req.oauth2.client.id;
      // TODO: Add audience
      break;
    }

    flows.goto(prompt, options, req, res, next);
  };
};

exports['@require'] = [
  'http://i.bixbyjs.org/http/state/Dispatcher'
];
<|endoftext|>


<commit_before><commit_msg>Update project webtorrent to 0.87.1<commit_after><|endoftext|>


<commit_before>/**
 * Game Controller
 *
 * @param {Object} $scope
 * @param {Object} $routeParams
 * @param {RoomRepository} repository
 * @param {SocketClient} client
 */
function GameController($scope, $routeParams, $location, repository, client)
{
    gamepadListener.start();

    this.$scope     = $scope;
    this.$location  = $location;
    this.repository = repository;
    this.client     = client;

    createjs.Sound.alternateExtensions = ['mp3'];
    createjs.Sound.registerManifest(
        [
            {id:'loose', src:'loose.ogg'},
            {id:'win', src:'win.ogg'}
        ],
        '../sounds/'
    );

    // Binding
    this.onMove        = this.onMove.bind(this);
    this.onPosition    = this.onPosition.bind(this);
    this.onPrinting    = this.onPrinting.bind(this);
    this.onAngle       = this.onAngle.bind(this);
    this.onPoint       = this.onPoint.bind(this);
    this.onBonusPop    = this.onBonusPop.bind(this);
    this.onBonusClear  = this.onBonusClear.bind(this);
    this.onDie         = this.onDie.bind(this);
    this.onScore       = this.onScore.bind(this);
    this.onTrailClear  = this.onTrailClear.bind(this);
    this.onWarmup      = this.onWarmup.bind(this);
    this.endWarmup     = this.endWarmup.bind(this);
    this.onRoundNew    = this.onRoundNew.bind(this);
    this.onRoundEnd    = this.onRoundEnd.bind(this);
    this.onRoundWinner = this.onRoundWinner.bind(this);
    this.onEnd         = this.onEnd.bind(this);
    this.onLeave       = this.onLeave.bind(this);

    this.attachSocketEvents();

    // Hydrate scope:
    this.$scope.sortorder = '-score';

    this.loadGame($routeParams.name);
}

/**
 * Attach socket Events
 */
GameController.prototype.attachSocketEvents = function()
{
    this.client.on('position', this.onPosition);
    this.client.on('printing', this.onPrinting);
    this.client.on('angle', this.onAngle);
    this.client.on('point', this.onPoint);
    this.client.on('bonus:pop', this.onBonusPop);
    this.client.on('bonus:clear', this.onBonusClear);
    this.client.on('die', this.onDie);
    this.client.on('score', this.onScore);
    this.client.on('trail:clear', this.onTrailClear);
    this.client.on('round:new', this.onRoundNew);
    this.client.on('round:end', this.onRoundEnd);
    this.client.on('round:winner', this.onRoundWinner);
    this.client.on('end', this.onEnd);
    this.client.on('game:leave', this.onLeave);
};

/**
 * Attach socket Events
 */
GameController.prototype.detachSocketEvents = function()
{
    this.client.off('position', this.onPosition);
    this.client.off('printing', this.onPrinting);
    this.client.off('angle', this.onAngle);
    this.client.off('point', this.onPoint);
    this.client.off('die', this.onDie);
    this.client.off('score', this.onScore);
    this.client.off('trail:clear', this.onTrailClear);
    this.client.off('round:new', this.onRoundNew);
    this.client.off('round:end', this.onRoundEnd);
    this.client.off('round:winner', this.onRoundWinner);
    this.client.off('end', this.onEnd);
    this.client.off('game:leave', this.onLeave);
};

/**
 * Rooms action
 *
 * @return {Array}
 */
GameController.prototype.loadGame = function(name)
{
    var room = this.repository.get(name),
        avatars;

    if (room) {
        this.room = room;
        this.game = room.newGame();

        avatars = this.game.avatars.filter(function () { return this.local; }).items;

        for (var i = avatars.length - 1; i >= 0; i--) {
            avatars[i].input.on('move', this.onMove);
        }

        this.game.fps.setElement(document.getElementById('fps'));
        this.client.pingLogger.setElement(document.getElementById('ping'));

        // Hydrate scope:
        this.$scope.curvytron.bodyClass = 'game-mode';
        this.$scope.game = this.game;

        this.client.addEvent('loaded');
    } else {
        this.goHome();
    }
};

/**
 * Start warmup
 */
GameController.prototype.displayWarmup = function(time)
{
    var controller = this;

    this.$scope.count       = time/1000;
    this.$scope.countFinish = false;
    this.applyScope();

    var warmupInterval = setInterval(this.onWarmup, 1000);

    setTimeout(function () { controller.endWarmup(warmupInterval); }, time);
};

/**
 * On warmup
 */
GameController.prototype.onWarmup = function()
{
    this.$scope.count--;
    this.$scope.$apply();
};

/**
 * End warmup
 */
GameController.prototype.endWarmup = function(interval)
{
    clearInterval(interval);

    this.$scope.countFinish = true;
    this.applyScope();
};

/**
 * On move
 *
 * @param {Event} e
 */
GameController.prototype.onMove = function(event)
{
    this.client.addEvent('player:move', {avatar: event.detail.avatar.name, move: event.detail.move});
};

/**
 * On position
 *
 * @param {Event} e
 */
GameController.prototype.onPosition = function(e)
{
    var data = e.detail,
        avatar = this.game.avatars.getById(data.avatar);

    if (avatar) {
        avatar.setPosition(data.point);
    }
};

/**
 * On bonus pop
 *
 * @param {Object} data
 */
GameController.prototype.onBonusPop = function(data)
{
    var bonus = new Bonus();
        bonus.unserialize(data);
        bonus.pop();

    this.game.bonuses.add(bonus);
};

/**
 * On bonus pop
 *
 * @param {Object} data
 */
GameController.prototype.onBonusClear = function(data)
{
    var bonus = this.game.bonuses.getById(data.id);
        bonus.clear();
};

/**
 * On printing
 *
 * @param {Event} e
 */
GameController.prototype.onPrinting = function(e)
{
    var data = e.detail,
        avatar = this.game.avatars.getById(data.avatar);

    if (avatar) {
        avatar.setPrinting(data.printing);
    }
};

/**
 * On angle
 *
 * @param {Event} e
 */
GameController.prototype.onAngle = function(e)
{
    var data = e.detail,
        avatar = this.game.avatars.getById(data.avatar);

    if (avatar) {
        avatar.setAngle(data.angle);
    }
};

/**
 * On point
 *
 * @param {Event} e
 */
GameController.prototype.onPoint = function(e)
{
    var data = e.detail,
        avatar = this.game.avatars.getById(data.avatar);

    if (avatar) {
        avatar.addPoint(data.point);
    }
};

/**
 * On die
 *
 * @param {Event} e
 */
GameController.prototype.onDie = function(e)
{
    var data = e.detail,
        avatar = this.game.avatars.getById(data.avatar);

    if (avatar) {
        avatar.die();
        this.applyScope();

        var loose = createjs.Sound.play('loose');
        loose.volume = 0.2;
    }
};

/**
 * On score
 *
 * @param {Event} e
 */
GameController.prototype.onScore = function(e)
{
    var data = e.detail,
        avatar = this.game.avatars.getById(data.avatar);

    if (avatar) {
        avatar.setScore(data.score);
        this.applyScope();
    }
};

/**
 * On trail clear
 *
 * @param {Event} e
 */
GameController.prototype.onTrailClear = function(e)
{
    var data = e.detail,
        avatar = this.game.avatars.getById(data.avatar);

    if (avatar) {
        avatar.trail.clear();
    }
};

/**
 * On round new
 *
 * @param {Game} game
 */
GameController.prototype.onRoundNew = function(e)
{
    document.getElementById('end').style.display        = 'none';
    document.getElementById('game-view').style.display  = 'none';
    document.getElementById('round-view').style.display = 'none';

    this.displayWarmup(this.game.warmupTime);
    this.game.newRound();
};

/**
 * On round new
 *
 * @param {Game} game
 */
GameController.prototype.onRoundEnd = function(e)
{
    this.game.endRound();
};

/**
 * On end
 *
 * @param {Event} e
 */
GameController.prototype.onEnd = function(e)
{
    this.detachSocketEvents();
    paper.view.pause();
    this.repository.start();

    avatars = this.game.avatars.filter(function () { return this.local; }).items;

    for (var i = avatars.length - 1; i >= 0; i--) {
        avatars[i].input.off('move', this.onMove);
    }

    this.game.end();
    this.room.closeGame();
    this.game = null;

    document.getElementById('end').style.display = 'block';
    document.getElementById('game-view').style.display = 'block';
    document.getElementById('round-view').style.display = 'none';

    createjs.Sound.play('win').volume = 0.2;
};

/**
 * On round new
 *
 * @param {Game} game
 */
GameController.prototype.onRoundWinner = function(e)
{
    var data = e.detail,
        avatar = this.game.avatars.getById(data.winner);

    if (avatar) {
        this.$scope.roundWinner = avatar;
        this.applyScope();

        document.getElementById('end').style.display = 'block';
        document.getElementById('round-view').style.display = 'block';
    }
};

/**
 * On leave
 *
 * @param {Event} e
 */
GameController.prototype.onLeave = function(e)
{
    var data = e.detail,
        avatar = this.game.avatars.getById(data.avatar);

    if (avatar) {
        this.game.removeAvatar(avatar);
        this.applyScope();
    }
};

/**
 * Go back to the homepage
 */
GameController.prototype.goHome = function()
{
    this.$location.path('/');
};

/**
 * Apply scope
 */
GameController.prototype.applyScope = function()
{
    try {
        this.$scope.$apply();
    } catch (e) {

    }
};
<commit_msg>add velocity increment/decrement listeners and handlers on game client controller<commit_after>/**
 * Game Controller
 *
 * @param {Object} $scope
 * @param {Object} $routeParams
 * @param {RoomRepository} repository
 * @param {SocketClient} client
 */
function GameController($scope, $routeParams, $location, repository, client)
{
    gamepadListener.start();

    this.$scope     = $scope;
    this.$location  = $location;
    this.repository = repository;
    this.client     = client;

    createjs.Sound.alternateExtensions = ['mp3'];
    createjs.Sound.registerManifest(
        [
            {id:'loose', src:'loose.ogg'},
            {id:'win', src:'win.ogg'}
        ],
        '../sounds/'
    );

    // Binding
    this.onMove        = this.onMove.bind(this);
    this.onPosition    = this.onPosition.bind(this);
    this.onPrinting    = this.onPrinting.bind(this);
    this.onAngle       = this.onAngle.bind(this);
    this.onPoint       = this.onPoint.bind(this);
    this.onBonusPop    = this.onBonusPop.bind(this);
    this.onBonusClear  = this.onBonusClear.bind(this);
    this.onDie         = this.onDie.bind(this);
    this.onScore       = this.onScore.bind(this);
    this.onTrailClear  = this.onTrailClear.bind(this);
    this.onWarmup      = this.onWarmup.bind(this);
    this.endWarmup     = this.endWarmup.bind(this);
    this.onRoundNew    = this.onRoundNew.bind(this);
    this.onRoundEnd    = this.onRoundEnd.bind(this);
    this.onRoundWinner = this.onRoundWinner.bind(this);
    this.onEnd         = this.onEnd.bind(this);
    this.onLeave       = this.onLeave.bind(this);

    this.attachSocketEvents();

    // Hydrate scope:
    this.$scope.sortorder = '-score';

    this.loadGame($routeParams.name);
}

/**
 * Attach socket Events
 */
GameController.prototype.attachSocketEvents = function()
{
    this.client.on('position', this.onPosition);
    this.client.on('printing', this.onPrinting);
    this.client.on('angle', this.onAngle);
    this.client.on('point', this.onPoint);
    this.client.on('bonus:pop', this.onBonusPop);
    this.client.on('bonus:clear', this.onBonusClear);
    this.client.on('die', this.onDie);
    this.client.on('score', this.onScore);
    this.client.on('trail:clear', this.onTrailClear);
    this.client.on('round:new', this.onRoundNew);
    this.client.on('round:end', this.onRoundEnd);
    this.client.on('round:winner', this.onRoundWinner);
    this.client.on('end', this.onEnd);
    this.client.on('game:leave', this.onLeave);
};

/**
 * Attach socket Events
 */
GameController.prototype.detachSocketEvents = function()
{
    this.client.off('position', this.onPosition);
    this.client.off('printing', this.onPrinting);
    this.client.off('angle', this.onAngle);
    this.client.off('point', this.onPoint);
    this.client.off('die', this.onDie);
    this.client.off('score', this.onScore);
    this.client.off('trail:clear', this.onTrailClear);
    this.client.off('round:new', this.onRoundNew);
    this.client.off('round:end', this.onRoundEnd);
    this.client.off('round:winner', this.onRoundWinner);
    this.client.off('end', this.onEnd);
    this.client.off('game:leave', this.onLeave);
};

/**
 * Rooms action
 *
 * @return {Array}
 */
GameController.prototype.loadGame = function(name)
{
    var room = this.repository.get(name),
        avatars;

    if (room) {
        this.room = room;
        this.game = room.newGame();

        avatars = this.game.avatars.filter(function () { return this.local; }).items;

        for (var i = avatars.length - 1; i >= 0; i--) {
            avatars[i].input.on('move', this.onMove);
        }

        this.game.fps.setElement(document.getElementById('fps'));
        this.client.pingLogger.setElement(document.getElementById('ping'));

        // Hydrate scope:
        this.$scope.curvytron.bodyClass = 'game-mode';
        this.$scope.game = this.game;

        this.client.addEvent('loaded');
    } else {
        this.goHome();
    }
};

/**
 * Start warmup
 */
GameController.prototype.displayWarmup = function(time)
{
    var controller = this;

    this.$scope.count       = time/1000;
    this.$scope.countFinish = false;
    this.applyScope();

    var warmupInterval = setInterval(this.onWarmup, 1000);

    setTimeout(function () { controller.endWarmup(warmupInterval); }, time);
};

/**
 * On warmup
 */
GameController.prototype.onWarmup = function()
{
    this.$scope.count--;
    this.$scope.$apply();
};

/**
 * End warmup
 */
GameController.prototype.endWarmup = function(interval)
{
    clearInterval(interval);

    this.$scope.countFinish = true;
    this.applyScope();
};

/**
 * On move
 *
 * @param {Event} e
 */
GameController.prototype.onMove = function(event)
{
    this.client.addEvent('player:move', {avatar: event.detail.avatar.name, move: event.detail.move});
};

/**
 * On position
 *
 * @param {Event} e
 */
GameController.prototype.onPosition = function(e)
{
    var data = e.detail,
        avatar = this.game.avatars.getById(data.avatar);

    if (avatar) {
        avatar.setPosition(data.point);
    }
};

/**
 * On bonus pop
 *
 * @param {Object} data
 */
GameController.prototype.onBonusPop = function(data)
{
    var bonus = new Bonus();
        bonus.unserialize(data);
        bonus.pop();

    this.game.bonuses.add(bonus);
};

/**
 * On bonus pop
 *
 * @param {Object} data
 */
GameController.prototype.onBonusClear = function(data)
{
    var bonus = this.game.bonuses.getById(data.id);
        bonus.clear();
};

/**
 * On printing
 *
 * @param {Event} e
 */
GameController.prototype.onPrinting = function(e)
{
    var data = e.detail,
        avatar = this.game.avatars.getById(data.avatar);

    if (avatar) {
        avatar.setPrinting(data.printing);
    }
};

/**
 * On angle
 *
 * @param {Event} e
 */
GameController.prototype.onAngle = function(e)
{
    var data = e.detail,
        avatar = this.game.avatars.getById(data.avatar);

    if (avatar) {
        avatar.setAngle(data.angle);
    }
};

/**
 * On point
 *
 * @param {Event} e
 */
GameController.prototype.onPoint = function(e)
{
    var data = e.detail,
        avatar = this.game.avatars.getById(data.avatar);

    if (avatar) {
        avatar.addPoint(data.point);
    }
};

/**
 * On die
 *
 * @param {Event} e
 */
GameController.prototype.onDie = function(e)
{
    var data = e.detail,
        avatar = this.game.avatars.getById(data.avatar);

    if (avatar) {
        avatar.die();
        this.applyScope();

        var loose = createjs.Sound.play('loose');
        loose.volume = 0.2;
    }
};

/**
 *
 * @param {Object} data
 */
GameController.prototype.onVelocityUp = function(data)
{
    var avatar = this.game.avatars.getById(data.avatar);

    if (avatar) {
        avatar.upVelocity();
        this.$scope.$apply();
    }
};

/**
 *
 * @param {Object} data
 */
GameController.prototype.onVelocityDown = function(data)
{
    var avatar = this.game.avatars.getById(data.avatar);

    if (avatar) {
        avatar.downVelocity();
        this.$scope.$apply();
    }
};

/**
 * On score
 *
 * @param {Event} e
 */
GameController.prototype.onScore = function(e)
{
    var data = e.detail,
        avatar = this.game.avatars.getById(data.avatar);

    if (avatar) {
        avatar.setScore(data.score);
        this.applyScope();
    }
};

/**
 * On trail clear
 *
 * @param {Event} e
 */
GameController.prototype.onTrailClear = function(e)
{
    var data = e.detail,
        avatar = this.game.avatars.getById(data.avatar);

    if (avatar) {
        avatar.trail.clear();
    }
};

/**
 * On round new
 *
 * @param {Game} game
 */
GameController.prototype.onRoundNew = function(e)
{
    document.getElementById('end').style.display        = 'none';
    document.getElementById('game-view').style.display  = 'none';
    document.getElementById('round-view').style.display = 'none';

    this.displayWarmup(this.game.warmupTime);
    this.game.newRound();
};

/**
 * On round new
 *
 * @param {Game} game
 */
GameController.prototype.onRoundEnd = function(e)
{
    this.game.endRound();
};

/**
 * On end
 *
 * @param {Event} e
 */
GameController.prototype.onEnd = function(e)
{
    this.detachSocketEvents();
    paper.view.pause();
    this.repository.start();

    avatars = this.game.avatars.filter(function () { return this.local; }).items;

    for (var i = avatars.length - 1; i >= 0; i--) {
        avatars[i].input.off('move', this.onMove);
    }

    this.game.end();
    this.room.closeGame();
    this.game = null;

    document.getElementById('end').style.display = 'block';
    document.getElementById('game-view').style.display = 'block';
    document.getElementById('round-view').style.display = 'none';

    createjs.Sound.play('win').volume = 0.2;
};

/**
 * On round new
 *
 * @param {Game} game
 */
GameController.prototype.onRoundWinner = function(e)
{
    var data = e.detail,
        avatar = this.game.avatars.getById(data.winner);

    if (avatar) {
        this.$scope.roundWinner = avatar;
        this.applyScope();

        document.getElementById('end').style.display = 'block';
        document.getElementById('round-view').style.display = 'block';
    }
};

/**
 * On leave
 *
 * @param {Event} e
 */
GameController.prototype.onLeave = function(e)
{
    var data = e.detail,
        avatar = this.game.avatars.getById(data.avatar);

    if (avatar) {
        this.game.removeAvatar(avatar);
        this.applyScope();
    }
};

/**
 * Go back to the homepage
 */
GameController.prototype.goHome = function()
{
    this.$location.path('/');
};

/**
 * Apply scope
 */
GameController.prototype.applyScope = function()
{
    try {
        this.$scope.$apply();
    } catch (e) {

    }
};
<|endoftext|>


<commit_before>/*globals geolib,define*/
/*
 * A `Controller` is a manager for a button on the screen. It will also control the rendering of the things on screen for the given categories.
 */

define([
       'text!../html/no_more.html',
       'text!../html/result.html'
], function(noMoreTemplate, resultTemplate) {
    'use strict';

    var Controller = function(client, button, container) {
        // Categories for the places
        // FIXME
        //this.categories = categories;
        this._id = button.getAttribute('id');
        // Add click listener
        button.onclick = this._renderOption.bind(this);
        this.container = container || $('.content');

        // Container to display the result in
        this.container = container;
        this._client = client;
    };

    /**
     * Display the given option on the screen.
     *
     * @private
     * @return {undefined}
     */
    Controller.prototype._renderOption = function() {
        this._client.getOption(this._id, function(option) {
            if (!option) {
                this.renderNone();
            } else {  // Render the option
                this.renderOption(option);

                // Set event listener
                this.container.on('click', '.result__retry', function(){
                    var opt = this._client.getAnotherOption(this._id);
                    this._renderOption(this._id, opt);
                }.bind(this));
            }
        }.bind(this));
    };

    /**
     * Display the given option.
     *
     * @param {Option} option
     * @return {undefined}
     */
    Controller.prototype.renderOption = function(option) {
      var addressQuery = option.vicinity.split(' ').join('+');
        console.log('option');
        console.log(option);
      var price_string = '';
      for (var i=0; i<option.price_level; i++) {
        price_string += '$';
      }
      var rating_string = '';
      while (option.rating >= 0.5) {
        if (option.rating >= 1) {
            rating_string += '';
            option.rating -= 1;
            continue;
        }
        if (option.rating >= 0.5) {
            rating_string += '';
            option.rating -= 0.5;
        }
      }
      var user_loc = {
        'latitude' : this._client.lat,
        'longitude' : this._client.lng
      };
      var result_loc = {
        'latitude' : option.location.lat,
        'longitude' : option.location.lng
      };
      var distance = Math.round(geolib.getDistance(user_loc, result_loc)/1609.34 * 10) / 10;

      console.log('option');
      console.log(option);

      var $rt = $(resultTemplate);
      $rt.find('.result__name').html(option.name);
      $rt.find('.result__photo').html('');
      $rt.find('.result__type').html(option.type);
      $rt.find('.result__price').html(price_string);
      $rt.find('.result__distance').html(distance + ' miles away');
      $rt.find('.result__ratings').html(rating_string);
      $rt.find('.result__vicinity').html(''+option.vicinity+'');

      this.container.html($rt);

      console.log('Displaying option for', this._id,'(', option.name, ')');
    };

    /**
     * Render a subsequent option.
     *
     * @return {undefined}
     */
    Controller.prototype.renderNext = function() {
        // FIXME
        // TODO
    };

    /**
     * Render the screen for no more options.
     *
     * @return {undefined}
     */
    Controller.prototype.renderNone = function() {
      var $rt = $(noMoreTemplate);
      $('.content').html($rt);

      console.log('No options found!');
    };

    return Controller;
});
<commit_msg>Finished basic controller functionality<commit_after>/*globals geolib,define*/
/*
 * A `Controller` is a manager for a button on the screen. It will also control the rendering of the things on screen for the given categories.
 */

define([
       'text!../html/no_more.html',
       'text!../html/result.html'
], function(noMoreTemplate, resultTemplate) {
    'use strict';

    var Controller = function(client, button, container) {
        // Categories for the places
        this._id = button.getAttribute('id');
        // Add click listener
        button.onclick = this._renderOption.bind(this);
        this.container = container || $('.content');

        // Container to display the result in
        this._client = client;
    };

    /**
     * Display the given option on the screen.
     *
     * @private
     * @return {undefined}
     */
    Controller.prototype._renderOption = function() {
        this._client.getOption(this._id, function(option) {
            if (!option) {
                this.renderNone();
            } else {  // Render the option
                this.renderOption(option);

                // Set event listener
                this.container.on('click', '.result__retry', function(){
                    var opt = this._client.getAnotherOption(this._id);
                    this._renderOption(this._id, opt);
                }.bind(this));
            }
        }.bind(this));
    };

    /**
     * Display the given option.
     *
     * @param {Option} option
     * @return {undefined}
     */
    Controller.prototype.renderOption = function(option) {
      var addressQuery = option.vicinity.split(' ').join('+');
        console.log('option');
        console.log(option);
      var price_string = '';
      for (var i=0; i<option.price_level; i++) {
        price_string += '$';
      }
      var rating_string = '';
      while (option.rating >= 0.5) {
        if (option.rating >= 1) {
            rating_string += '';
            option.rating -= 1;
            continue;
        }
        if (option.rating >= 0.5) {
            rating_string += '';
            option.rating -= 0.5;
        }
      }
      var user_loc = {
        'latitude' : this._client.lat,
        'longitude' : this._client.lng
      };
      var result_loc = {
        'latitude' : option.location.lat,
        'longitude' : option.location.lng
      };
      var distance = Math.round(geolib.getDistance(user_loc, result_loc)/1609.34 * 10) / 10;

      var $rt = $(resultTemplate);
      $rt.find('.result__name').html(option.name);
      $rt.find('.result__photo').html('');
      $rt.find('.result__type').html(option.type);
      $rt.find('.result__price').html(price_string);
      $rt.find('.result__distance').html(distance + ' miles away');
      $rt.find('.result__ratings').html(rating_string);
      $rt.find('.result__vicinity').html(''+option.vicinity+'');

      this.container.html($rt);

      console.log('Displaying option for', this._id,'(', option.name, ')');
    };

    /**
     * Render the screen for no more options.
     *
     * @return {undefined}
     */
    Controller.prototype.renderNone = function() {
      var $rt = $(noMoreTemplate);
      $('.content').html($rt);

      console.log('No options found!');
    };

    return Controller;
});
<|endoftext|>


<commit_before>;(function() {
  "use strict";

  var BaseController = require("BaseController");

  new BaseController({
    siteName: "Deezer",
    play: ".control.control-play",
    pause: ".control.control-pause",
    playNext: ".control.control-next",
    playPrev: ".control.control-prev",
    mute: ".icon-volume-off",
    like: ".player-actions .icon-love",
    dislike: ".player-actions .icon-unlove",
    buttonSwitch: true,

    song: ".player-track-title > span",
    artist: ".heading-2-sub span.player-track-link"
  });
})();
<commit_msg>Fix deezer.<commit_after>;(function() {
  "use strict";

  var BaseController = require("BaseController");

  new BaseController({
    siteName: "Deezer",
    playPause: ".control.control-play",
    playNext: ".control.control-next",
    playPrev: ".control.control-prev",
    mute: ".icon-volume-off",
    like: ".player-actions .icon-love",
    dislike: ".player-actions .icon-unlove",
    playState: ".control.control-play > .svg-icon-pause",

    song: ".player-track-title > a",
    artist: ".player-track-artist > a"
  });
})();
<|endoftext|>


<commit_before>var jsonfile = require('jsonfile');
var path = require('path');
var fs = require('fs');
var fsExt = require('fs-extra');
var execSync = require('child_process').execSync;

var widgetPath;
var devboxPath = path.join(process.mainModule.children[0].paths[1], '/appsngen-dev-box');
var devboxConfigPath = path.join(devboxPath, '/serverConfig.json');
var devboxConfig = jsonfile.readFileSync(devboxConfigPath);
var projectConfig = jsonfile.readFileSync('./.appsngenrc');
var archiveName = path.basename(projectConfig.zipFilePath);

if (devboxConfig && projectConfig) {
    execSync('rm -r ' + path.join(devboxPath, '/widgets'), {
        stdio: 'inherit'
    });
    fs.mkdirSync(path.join(devboxPath, '/widgets'));
    try {
        fsExt.copySync(path.resolve(projectConfig.zipFilePath), path.join(devboxPath, '/widgets/', archiveName));
    } catch (err) {
        console.error(err);
    }
    devboxConfig.widgets = [path.join('/widgets/', archiveName)];
    jsonfile.writeFileSync(devboxConfigPath, devboxConfig);
} else if (!devboxConfig) {
    console.error('DevBox config wasn\'t found.');
} else {
    console.error('Project config wasn\'t found.');
}
//install devbox dependencies(routerhelpers.js require node_modules folder)
execSync('npm install', {
    cwd: devboxPath,
    stdio: 'inherit'
});
execSync('node server.js', {
    cwd: devboxPath,
    stdio: 'inherit'
});
<commit_msg>add catch block to readFileSync call<commit_after>var jsonfile = require('jsonfile');
var path = require('path');
var fs = require('fs');
var fsExt = require('fs-extra');
var execSync = require('child_process').execSync;

var widgetPathw, devboxConfig, projectConfig, archiveName;
var devboxPath = path.join(process.mainModule.children[0].paths[1], '/appsngen-dev-box');
var devboxConfigPath = path.join(devboxPath, '/serverConfig.json');

try {
    devboxConfig = jsonfile.readFileSync(devboxConfigPath);
    projectConfig = jsonfile.readFileSync('./.appsngenrc');
} catch (err) {
    console.error(err.toString());
    return;
}

try {
    archiveName = path.basename(projectConfig.zipFilePath);
    execSync('rm -r ' + path.join(devboxPath, '/widgets'), {
        stdio: 'inherit'
    });
    fs.mkdirSync(path.join(devboxPath, '/widgets'));
    fsExt.copySync(path.resolve(projectConfig.zipFilePath), path.join(devboxPath, '/widgets/', archiveName));
    devboxConfig.widgets = [path.join('/widgets/', archiveName)];
    jsonfile.writeFileSync(devboxConfigPath, devboxConfig);
} catch (err) {
    console.error(err.toString());
    return;
}
//install devbox dependencies(routerhelpers.js require node_modules folder)
execSync('npm install', {
    cwd: devboxPath,
    stdio: 'inherit'
});
execSync('node server.js', {
    cwd: devboxPath,
    stdio: 'inherit'
});<|endoftext|>


<commit_before>/*
Passport-Live is a modern web app for schools that helps them manage passes.
    Copyright (C) 2017  Joseph Hassell

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published
    by the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

email: hi@josephhassell.com
*/

/**
* @module blackoutRESTAPI
*/
var express = require('express');
var router = express.Router();
var passport = require('passport');
var cors = require('cors');
var config = require('config');
var api = require('../../modules/passport-api/blackout.js');

router.use(cors());
router.options('*', cors())

function serializeUser(req, res, done) {
    console.log(req.user[0]);
    //REMOVE SECRET INFO LIKE PASSWORDS
    //delete req.user[0].password;
    //req.user = req.user[0];
    req.user = utils.cleanUser(req.user);
    done();
};
/**
    * Returns all blackouts by the user ID
    * @function newBlackout
    * @api POST /api/blackout/
    * @apiparam {userGroup} userGroup - A Usergroup constant defined in the config
    * @apibody {none}
    * @example
    * <caption>Body Structure (application/json): </caption>
    * {
    *    "date": "2017-07-11",
    *    "periods": "["a", "b". "c"]",
    *    "userId": "1fgsdfdsg879f6f879d79f98d7g8",
    *    "message": "I am sick."
    * }
    */
router.post('/', function newBlackout(req, res, next) {
    var date = req.body.date;
    var periods = req.body.periods;
    var userId = req.body.userId;
    var message = req.body.message;

    api.newBlackout(date, periods, userId, message, function(err, trans) {
        if (err) {
            return next(err);
        }
        res.status(201).json(trans);
    })
})

/**
    * Returns all blackouts by the user ID
    * @function getBlackoutByUserId
    * @api POST /api/blackout/user/:userId
    * @apiparam {string} userId - The ID corresponding to an account
    * @returns {json} - blackout row
    */
router.get('/user/:userId', function getBlackoutByUserId(req, res, next) {
    api.getBlackoutByUserId(req.params.userId, function(err, doc) {
        if(err) {
            return next(err);
        }
        res.json(doc);
    })
})

//select by USER ID AND Day
router.get('/user/:userId/date/:date', function(req, res, next) {
    api.getBlackoutByUserIdAndDate(req.params.userId, req.params.date, function(err, doc) {
        if (err) {
            return next(err);
        }
        res.json(doc);
    })
})

module.exports = router;<commit_msg>Ficed doc<commit_after>/*
Passport-Live is a modern web app for schools that helps them manage passes.
    Copyright (C) 2017  Joseph Hassell

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Affero General Public License as published
    by the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Affero General Public License for more details.

    You should have received a copy of the GNU Affero General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.

email: hi@josephhassell.com
*/

/**
* @module blackoutRESTAPI
*/
var express = require('express');
var router = express.Router();
var passport = require('passport');
var cors = require('cors');
var config = require('config');
var api = require('../../modules/passport-api/blackout.js');

router.use(cors());
router.options('*', cors())

function serializeUser(req, res, done) {
    console.log(req.user[0]);
    //REMOVE SECRET INFO LIKE PASSWORDS
    //delete req.user[0].password;
    //req.user = req.user[0];
    req.user = utils.cleanUser(req.user);
    done();
};
/**
    * Returns all blackouts by the user ID
    * @function newBlackout
    * @api POST /api/blackout/
    * @apiparam {userGroup} userGroup - A Usergroup constant defined in the config
    * @apibody {none}
    * @example
    * <caption>Body Structure (application/json): </caption>
    * {
    *    "date": "2017-07-11",
    *    "periods": ["a", "b". "c"],
    *    "userId": "1fgsdfdsg879f6f879d79f98d7g8",
    *    "message": "I am sick."
    * }
    */
router.post('/', function newBlackout(req, res, next) {
    var date = req.body.date;
    var periods = req.body.periods;
    var userId = req.body.userId;
    var message = req.body.message;

    api.newBlackout(date, periods, userId, message, function(err, trans) {
        if (err) {
            return next(err);
        }
        res.status(201).json(trans);
    })
})

/**
    * Returns all blackouts by the user ID
    * @function getBlackoutByUserId
    * @api POST /api/blackout/user/:userId
    * @apiparam {string} userId - The ID corresponding to an account
    * @returns {json} - blackout row
    */
router.get('/user/:userId', function getBlackoutByUserId(req, res, next) {
    api.getBlackoutByUserId(req.params.userId, function(err, doc) {
        if(err) {
            return next(err);
        }
        res.json(doc);
    })
})

//select by USER ID AND Day
router.get('/user/:userId/date/:date', function(req, res, next) {
    api.getBlackoutByUserIdAndDate(req.params.userId, req.params.date, function(err, doc) {
        if (err) {
            return next(err);
        }
        res.json(doc);
    })
})

module.exports = router;<|endoftext|>


<commit_before>var keystone = require('keystone'),
	async = require('async');

var services = {
	github: require('../../lib/auth/github'),
	facebook: require('../../lib/auth/twitter'),
	google: require('../../lib/auth/google'),
	twitter: require('../../lib/auth/twitter')
}

exports = module.exports = function(req, res) {

	if (!req.params.service) {
		console.log('[auth.service] - You must define the service you wish to authenticate with.');
		return res.redirect('/login');
	}

	services[req.params.service].authenticateUser(req, res);

};
<commit_msg>Adding missing next callback.<commit_after>var keystone = require('keystone'),
	async = require('async');

var services = {
	github: require('../../lib/auth/github'),
	facebook: require('../../lib/auth/twitter'),
	google: require('../../lib/auth/google'),
	twitter: require('../../lib/auth/twitter')
}

exports = module.exports = function(req, res, next) {

	if (!req.params.service) {
		console.log('[auth.service] - You must define the service you wish to authenticate with.');
		return res.redirect('/login');
	}

	services[req.params.service].authenticateUser(req, res, next);

};
<|endoftext|>