<commit_before>'use strict';

var rgWizardStepDirective = {
    name: 'rgWizardStep',
    directive: function ($rootScope, $log, $timeout) {
        return {
            restrict: 'E',
            require: '^rgWizard',
            transclude: true,
            replace: true,
            scope: {
                watchForChanges: '@',
                setFormDirtyOn: '@',
                onEnterCallback: '&',
                onLeaveCallback: '&'
            },
            templateUrl: '/wizard/rg-wizard-step-template.html',
            link: function (scope, elem, attrs) {
                scope.name = attrs.stepName;
                scope.stepForm = {
                    name: scope.name.replace(/[\s|\W]/g, '') + 'StepForm'
                };
                scope.visible = false;
                this.isLastStep = !angular.isUndefined(attrs.lastStep);

                scope.deregisterFormValidWatch = null;
                scope.deregisterFormDirtyWatch = null;
                scope.deregisterWatchCollection = [];

                scope.getStepForm = function () {
                    return scope[scope.stepForm.name];
                };

                scope.setVisible = function (visible) {
                    scope.visible = visible;

                    if (visible) {
                        $timeout(function () {
                            scope.deregisterFormValidWatch = scope.$watch(scope.stepForm.name + '.$valid', function (newVal, oldVal) {
                                scope.$parent.setCanChangeStep(newVal);
                                //$log.info(scope.name, scope.$id, "watch valid", newVal, oldVal);
                            });
                            scope.deregisterFormDirtyWatch = scope.$watch(scope.stepForm.name + '.$dirty', function (newVal, oldVal) {
                                scope.$parent.setFormIsDirty(newVal);
                                //$log.info(scope.name, scope.$id, "watch dirty", newVal, oldVal);
                            });

                            if (!angular.isUndefined(scope.watchForChanges)) {

                                var watchExpressions = scope.watchForChanges.split('|');

                                for (var i = 0; i < watchExpressions.length; i++) {
                                    var propertyToWatch = watchExpressions[i].trim();

                                    if (propertyToWatch.length === 0)
                                        continue;

                                    var watchExpression = '$parent.$parent.' + propertyToWatch;
                                    scope.deregisterWatchCollection.push(scope.$watchCollection(watchExpression, function (newVal, oldVal) {
                                        var equals = angular.equals(newVal, oldVal);
                                        scope.$parent.setFormIsDirty(!equals);
                                        //$log.info(scope.name, scope.$id, "watch collection dirty", equals, newVal, oldVal);
                                    }));
                                }
                            }

                            //if the step was made invisible before we register the watches
                            //deregister them
                            if(!scope.visible)
                                deregisterWatches();

                        },
                        //the 1s wait is to allow IE11 to catch up
                        500);
                    } else {
                        deregisterWatches();
                    }
                };

                function deregisterWatches() {
                    if (scope.deregisterFormValidWatch !== null)
                        scope.deregisterFormValidWatch();

                    if (scope.deregisterFormDirtyWatch !== null)
                        scope.deregisterFormDirtyWatch();

                    if (scope.deregisterWatchCollection.length > 0) {
                        for (var i = 0; i < scope.deregisterWatchCollection.length; i++)
                            scope.deregisterWatchCollection[i]();
                    }
                }

                scope.onEnterStep = function () {
                    var stepForm = scope.getStepForm();

                    if (!angular.isUndefined(stepForm))
                        scope.$parent.setCanChangeStep(stepForm.$valid);

                    if (!angular.isUndefined(scope.onEnterCallback))
                        scope.onEnterCallback();
                };

                scope.onLeaveStep = function () {

                    if (!angular.isUndefined(scope.onLeaveCallback))
                        scope.onLeaveCallback();

                    scope.getStepForm().$setPristine();
                    scope.$parent.setFormIsDirty(false);
                };

                scope.$parent.registerStep({
                    name: scope.name,
                    isLastStep: this.isLastStep,
                    onEnterStep: scope.onEnterStep,
                    onLeaveStep: scope.onLeaveStep,
                    setVisible: scope.setVisible
                });

                if (!angular.isUndefined(scope.setFormDirtyOn))
                    $rootScope.$on(scope.setFormDirtyOn, function () {
                        if (scope.visible)
                            scope.$parent.setFormIsDirty(true);
                    });
            }
        };
    }
};<commit_msg>tweaked form name regex<commit_after>'use strict';

var rgWizardStepDirective = {
    name: 'rgWizardStep',
    directive: function ($rootScope, $log, $timeout) {
        return {
            restrict: 'E',
            require: '^rgWizard',
            transclude: true,
            replace: true,
            scope: {
                watchForChanges: '@',
                setFormDirtyOn: '@',
                onEnterCallback: '&',
                onLeaveCallback: '&'
            },
            templateUrl: '/wizard/rg-wizard-step-template.html',
            link: function (scope, elem, attrs) {
                scope.name = attrs.stepName;
                scope.stepForm = {
                    name: scope.name.replace(/[\s|\W\d]/g, '') + 'StepForm'
                };
                scope.visible = false;
                this.isLastStep = !angular.isUndefined(attrs.lastStep);

                scope.deregisterFormValidWatch = null;
                scope.deregisterFormDirtyWatch = null;
                scope.deregisterWatchCollection = [];

                scope.getStepForm = function () {
                    return scope[scope.stepForm.name];
                };

                scope.setVisible = function (visible) {
                    scope.visible = visible;

                    if (visible) {
                        $timeout(function () {
                            scope.deregisterFormValidWatch = scope.$watch(scope.stepForm.name + '.$valid', function (newVal, oldVal) {
                                scope.$parent.setCanChangeStep(newVal);
                                //$log.info(scope.name, scope.$id, "watch valid", newVal, oldVal);
                            });
                            scope.deregisterFormDirtyWatch = scope.$watch(scope.stepForm.name + '.$dirty', function (newVal, oldVal) {
                                scope.$parent.setFormIsDirty(newVal);
                                //$log.info(scope.name, scope.$id, "watch dirty", newVal, oldVal);
                            });

                            if (!angular.isUndefined(scope.watchForChanges)) {

                                var watchExpressions = scope.watchForChanges.split('|');

                                for (var i = 0; i < watchExpressions.length; i++) {
                                    var propertyToWatch = watchExpressions[i].trim();

                                    if (propertyToWatch.length === 0)
                                        continue;

                                    var watchExpression = '$parent.$parent.' + propertyToWatch;
                                    scope.deregisterWatchCollection.push(scope.$watchCollection(watchExpression, function (newVal, oldVal) {
                                        var equals = angular.equals(newVal, oldVal);
                                        scope.$parent.setFormIsDirty(!equals);
                                        //$log.info(scope.name, scope.$id, "watch collection dirty", equals, newVal, oldVal);
                                    }));
                                }
                            }

                            //if the step was made invisible before we register the watches
                            //deregister them
                            if(!scope.visible)
                                deregisterWatches();

                        },
                        //the 1s wait is to allow IE11 to catch up
                        500);
                    } else {
                        deregisterWatches();
                    }
                };

                function deregisterWatches() {
                    if (scope.deregisterFormValidWatch !== null)
                        scope.deregisterFormValidWatch();

                    if (scope.deregisterFormDirtyWatch !== null)
                        scope.deregisterFormDirtyWatch();

                    if (scope.deregisterWatchCollection.length > 0) {
                        for (var i = 0; i < scope.deregisterWatchCollection.length; i++)
                            scope.deregisterWatchCollection[i]();
                    }
                }

                scope.onEnterStep = function () {
                    var stepForm = scope.getStepForm();

                    if (!angular.isUndefined(stepForm))
                        scope.$parent.setCanChangeStep(stepForm.$valid);

                    if (!angular.isUndefined(scope.onEnterCallback))
                        scope.onEnterCallback();
                };

                scope.onLeaveStep = function () {

                    if (!angular.isUndefined(scope.onLeaveCallback))
                        scope.onLeaveCallback();

                    scope.getStepForm().$setPristine();
                    scope.$parent.setFormIsDirty(false);
                };

                scope.$parent.registerStep({
                    name: scope.name,
                    isLastStep: this.isLastStep,
                    onEnterStep: scope.onEnterStep,
                    onLeaveStep: scope.onLeaveStep,
                    setVisible: scope.setVisible
                });

                if (!angular.isUndefined(scope.setFormDirtyOn))
                    $rootScope.$on(scope.setFormDirtyOn, function () {
                        if (scope.visible)
                            scope.$parent.setFormIsDirty(true);
                    });
            }
        };
    }
};<|endoftext|>


<commit_before>/* eslint-disable camelcase */

// Client-Side Applications had better use implicit_grant
// see here -> http://wiki.dev.app.360.cn/index.php?title=OAuth2.0%E6%96%87%E6%A1%A3
// But as the website's implicit granted access token expires in such a short time (1200s currently),
// that it is unrealistic to take this approach in a client app.
// So here I implemented an OAuth service with the authorization code approach.

import qs from 'nodelibs/querystring';
import secrets from '../../../secrets.json!';

const AUTHORIZE_ENDPOINT = 'http://login.cc98.org/oauth/authorize';
const TOKEN_ENDPOINT = 'http://login.cc98.org/oauth/token';
const AUTH_SCOPE = 'all*';
const REFRESH_TOKEN_EXPIRY = 1200; // 目前 98 的实现有问题，时间太短，后续会改的

class LoginController {
  constructor($scope, $http, $rootScope, $state, Accounts) {
    // ionic 对 controller as 支持有问题 https://github.com/driftyco/ionic/issues/3058
    $scope.ctrl = this;

    this.$scope = $scope;
    this.$http = $http;
    this.$rootScope = $rootScope;
    this.$state = $state;
    this.Accounts = Accounts;

    if (window.StatusBar) { window.StatusBar.styleDefault(); }
  }

  /**
   * cancel login and return to the state where the user was from
   */
  cancel() {
    if (window.StatusBar) { window.StatusBar.styleLightContent(); }
    this.$state.go(this.$rootScope.fromStateName, this.$rootScope.fromStateParams);
  }

  /**
   * OAuth 登录，采用 Authorization Code 方式
   * @todo 增加 state 参数
   */
  login() {
    this._toggleKeyboardAccessoryBar({show: true});

    let authorizeUrl = AUTHORIZE_ENDPOINT + '?' + qs.stringify({
      response_type: 'code',
      grant_type: 'authorization_code',
      client_id: secrets.client_id,
      redirect_uri: secrets.redirect_uri,
      scope: AUTH_SCOPE
    });
    let ref = window.open(authorizeUrl, '_blank');
    ref.addEventListener('loadstart', (evt) => {
      if (!evt.url.startsWith(secrets.redirect_uri)) { return; }

      this._toggleKeyboardAccessoryBar({show: false});
      ref.close();

      let {code, error} = qs.parse(evt.url.split('?')[1]);
      if (error) {
        alert('Failed to get authorization code!');
      } else {
        this._getTokens(code);
      }
    });
  }

  _getTokens(code) {
    this.$http({
      method: 'POST',
      url: TOKEN_ENDPOINT,
      data: {
        grant_type: 'authorization_code',
        client_id: secrets.client_id,
        client_secret: secrets.client_secret,
        redirect_uri: secrets.redirect_uri,
        code: code
      },
      headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
      transformRequest: function(obj) {
        var str = [];
        for(var p in obj){
          str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
        }
        return str.join('&');
      }
    }).success(({access_token, expires_in, refresh_token}) => {
      let access_token_expires = new Date((new Date()).getTime() + expires_in * 1000);
      let refresh_token_expires = new Date((new Date()).getTime() + REFRESH_TOKEN_EXPIRY * 1000);

      this.Accounts.setCurrent({
        access_token: access_token,
        refresh_token: refresh_token,
        access_token_expires: access_token_expires,
        refresh_token_expires: refresh_token_expires
      });

      this._return();
    }).error(() => {
      alert('Failed to get access token!');
    });
  }

  /**
   * return to the state which the user was meant to go
   */
  _return() {
    if (window.StatusBar) { window.StatusBar.styleLightContent(); }
    this.$state.go(this.$rootScope.returnToStateName, this.$rootScope.returnToStateParams);
  }

  /**
   * toggle keyboard accessory bar
   * @param  {Object}  params
   * @param  {boolean} params.show set this to true to show the bar or false to hide
   */
  _toggleKeyboardAccessoryBar({show}) {
    // 重新关掉键盘的 AccessoryBar，毕竟只有填表单时用得到
    if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
      window.cordova.plugins.Keyboard.hideKeyboardAccessoryBar(!show);
    }
  }
}

LoginController.$inject = ['$scope', '$http', '$rootScope', '$state', 'Accounts'];

export default LoginController;
<commit_msg>Use more syntax sugar & modify the user data structure<commit_after>/* eslint-disable camelcase */

// Client-Side Applications had better use implicit_grant
// see here -> http://wiki.dev.app.360.cn/index.php?title=OAuth2.0%E6%96%87%E6%A1%A3
// But as the website's implicit granted access token expires in such a short time (1200s currently),
// that it is unrealistic to take this approach in a client app.
// So here I implemented an OAuth service with the authorization code approach.

import qs from 'nodelibs/querystring';
import secrets from '../../../secrets.json!';

const AUTHORIZE_ENDPOINT = 'http://login.cc98.org/oauth/authorize';
const TOKEN_ENDPOINT = 'http://login.cc98.org/oauth/token';
const AUTH_SCOPE = 'all*';
const REFRESH_TOKEN_EXPIRY = 1200; // 目前 98 的实现有问题，时间太短，后续会改的

class LoginController {
  constructor($scope, $http, $rootScope, $state, Accounts) {
    // ionic 对 controller as 支持有问题 https://github.com/driftyco/ionic/issues/3058
    $scope.ctrl = this;

    this.$scope = $scope;
    this.$http = $http;
    this.$rootScope = $rootScope;
    this.$state = $state;
    this.Accounts = Accounts;

    if (window.StatusBar) { window.StatusBar.styleDefault(); }
  }

  /**
   * cancel login and return to the state where the user was from
   */
  cancel() {
    if (window.StatusBar) { window.StatusBar.styleLightContent(); }
    this.$state.go(this.$rootScope.fromStateName, this.$rootScope.fromStateParams);
  }

  /**
   * OAuth 登录，采用 Authorization Code 方式
   * @todo 增加 state 参数
   */
  login() {
    this._toggleKeyboardAccessoryBar({show: true});

    let authorizeUrl = AUTHORIZE_ENDPOINT + '?' + qs.stringify({
      response_type: 'code',
      grant_type: 'authorization_code',
      client_id: secrets.client_id,
      redirect_uri: secrets.redirect_uri,
      scope: AUTH_SCOPE
    });
    let ref = window.open(authorizeUrl, '_blank');
    ref.addEventListener('loadstart', (evt) => {
      if (!evt.url.startsWith(secrets.redirect_uri)) { return; }

      this._toggleKeyboardAccessoryBar({show: false});
      ref.close();

      let {code, error} = qs.parse(evt.url.split('?')[1]);
      if (error) {
        alert('Failed to get authorization code!');
      } else {
        this._getTokens(code);
      }
    });
  }

  _getTokens(code) {
    this.$http({
      method: 'POST',
      url: TOKEN_ENDPOINT,
      data: {
        grant_type: 'authorization_code',
        client_id: secrets.client_id,
        client_secret: secrets.client_secret,
        redirect_uri: secrets.redirect_uri,
        code: code
      },
      headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
      transformRequest: function(obj) {
        let str = [];
        for(let p in obj){
          str.push(encodeURIComponent(p) + '=' + encodeURIComponent(obj[p]));
        }
        return str.join('&');
      }
    }).success(({access_token, expires_in, refresh_token}) => {
      let access_token_expires = (new Date()).getTime() + expires_in * 1000;
      let refresh_token_expires = (new Date()).getTime() + REFRESH_TOKEN_EXPIRY * 1000;

      this.Accounts.setCurrent({
        access_token: access_token,
        refresh_token: refresh_token,
        access_token_expires: access_token_expires,
        refresh_token_expires: refresh_token_expires
      });

      this._return();
    }).error(() => {
      alert('Failed to get access token!');
    });
  }

  /**
   * return to the state which the user was meant to go
   */
  _return() {
    if (window.StatusBar) { window.StatusBar.styleLightContent(); }
    this.$state.go(this.$rootScope.returnToStateName, this.$rootScope.returnToStateParams);
  }

  /**
   * toggle keyboard accessory bar
   * @param  {boolean} options.show set this to true to show the bar or false to hide
   */
  _toggleKeyboardAccessoryBar({show}) {
    // 重新关掉键盘的 AccessoryBar，毕竟只有填表单时用得到
    if (window.cordova && window.cordova.plugins && window.cordova.plugins.Keyboard) {
      window.cordova.plugins.Keyboard.hideKeyboardAccessoryBar(!show);
    }
  }
}

LoginController.$inject = ['$scope', '$http', '$rootScope', '$state', 'Accounts'];

export default LoginController;
<|endoftext|>


<commit_before>/*jshint bitwise: false*/

"use strict";

angular.module("wuw.services")

.factory("Lectures", function($http, $q, Settings) {
    var lectures = JSON.parse(Settings.getSetting('lecturesCache') || '[]');

    var lecturesForGroups = function() {
        var deferred = $q.defer();
        var selectedLectures = JSON.parse(Settings.getSetting("selectedLectures") || "[]");

        $http.post(Settings.getSetting("apiUrl") + "/lectures/groups", {
            "groups": Settings.getSetting("selectedGroups")
        }).
        success(function(data, status, headers, config) {
            var filteredLectures = [];

            for (var i = 0; i < data.length; i++) {
                var lecture = data[i];
                var occursInSelectedLectures = false;

                // check if this lectures is in one of the users selected groups
                for (var k = 0; k < selectedLectures.length; k++) {
                    if (lecture.lectureName === selectedLectures[k].lectureName) {
                        occursInSelectedLectures = true;
                    }
                }

                // add datefield to every lecutre (useable for grouping)
                var d = new Date(lecture.startTime).setHours(0);
                lecture.date = new Date(d).setMinutes(0);

                if (occursInSelectedLectures || selectedLectures.length === 0) {
                    filteredLectures.push(lecture);
                }
            }

            Settings.setSetting('lecturesCache', JSON.stringify(filteredLectures));
            Settings.setSetting('lecturesCacheTime', new Date().getTime());
            lectures = filteredLectures;
            deferred.resolve(filteredLectures);
        }).
        error(function(data, status, headers, config) {
            deferred.reject(data);
        });
        return deferred.promise;
    };

    var fromCache = function() {
        return lectures;
    };

    var secondsSinceCache = function() {
        var cacheTime = Settings.getSetting('lecturesCacheTime');
        if (typeof cacheTime === 'undefined') {
            return Math.pow(2,32) - 1; // highest integer in JS
        }
        var diff = new Date().getTime() - cacheTime;
        return Math.round(diff / 1000);
    };

    var getAllLectureTitles = function() {
        var lectureTitles = [];
        for (var i = 0; i < lectures.length; i++) {
            var lectureTitle = lectures[i].lectureName;

            // check if the lectureTitle is new
            if (lectureTitles.indexOf(lectureTitle) < 0) {
                lectureTitles.push(lectureTitle);
            }
        }
        return lectureTitles;
    };

    var getCurrentLecture = function() {
        var now = new Date().getTime();
        for (var i = 0; i < lectures.length; i++) {
            var start = new Date(lectures[i].startTime).getTime();
            var end   = new Date(lectures[i].endTime).getTime();
            if (start < now && now < end) {
                return lectures[i];
            }
        }
    };

    var getNextLecture = function() {
        var nextLecture;
        var nextLectureDistance = 18446744073709552000;
        for (var i = 0; i < lectures.length; i++) {
            var lectureDistance = new Date(lectures[i].startTime).getTime() - new Date().getTime();
            if (lectureDistance < nextLectureDistance && lectureDistance > 0) {
                nextLectureDistance = lectureDistance;
                nextLecture = lectures[i];
            }
        }
        return nextLecture;
    };

    return {
        lectures: lectures,
        lecturesForGroups: lecturesForGroups,
        fromCache: fromCache,
        getAllLectureTitles: getAllLectureTitles,
        secondsSinceCache: secondsSinceCache,
        getCurrentLecture: getCurrentLecture,
        getNextLecture: getNextLecture
    };
});
<commit_msg>lectures: don't iterate, if user hasn't selected any lectures<commit_after>/*jshint bitwise: false*/

"use strict";

angular.module("wuw.services")

.factory("Lectures", function($http, $q, Settings) {
    var lectures = JSON.parse(Settings.getSetting('lecturesCache') || '[]');

    var lecturesForGroups = function() {
        var deferred = $q.defer();
        var selectedLectures = JSON.parse(Settings.getSetting("selectedLectures") || "[]");

        $http.post(Settings.getSetting("apiUrl") + "/lectures/groups", {
            "groups": Settings.getSetting("selectedGroups")
        }).
        success(function(data, status, headers, config) {

            // if the user hasn't selected lectures, we give him all.
            if (selectedLectures.length === 0) {
                lectures = data;
                deferred.resolve(data);
                return;
            }

            var filteredLectures = [];
            for (var i = 0; i < data.length; i++) {
                var lecture = data[i];
                var occursInSelectedLectures = false;

                // check if this lectures is in one of the users selected groups
                for (var k = 0; k < selectedLectures.length; k++) {
                    if (lecture.lectureName === selectedLectures[k].lectureName) {
                        occursInSelectedLectures = true;
                    }
                }

                // add datefield to every lecutre (useable for grouping)
                var d = new Date(lecture.startTime).setHours(0);
                lecture.date = new Date(d).setMinutes(0);

                if (occursInSelectedLectures) {
                    filteredLectures.push(lecture);
                }
            }

            Settings.setSetting('lecturesCache', JSON.stringify(filteredLectures));
            Settings.setSetting('lecturesCacheTime', new Date().getTime());
            lectures = filteredLectures;
            deferred.resolve(filteredLectures);
        }).
        error(function(data, status, headers, config) {
            deferred.reject(data);
        });
        return deferred.promise;
    };

    var fromCache = function() {
        return lectures;
    };

    var secondsSinceCache = function() {
        var cacheTime = Settings.getSetting('lecturesCacheTime');
        if (typeof cacheTime === 'undefined') {
            return Math.pow(2,32) - 1; // highest integer in JS
        }
        var diff = new Date().getTime() - cacheTime;
        return Math.round(diff / 1000);
    };

    var getAllLectureTitles = function() {
        var lectureTitles = [];
        for (var i = 0; i < lectures.length; i++) {
            var lectureTitle = lectures[i].lectureName;

            // check if the lectureTitle is new
            if (lectureTitles.indexOf(lectureTitle) < 0) {
                lectureTitles.push(lectureTitle);
            }
        }
        return lectureTitles;
    };

    var getCurrentLecture = function() {
        var now = new Date().getTime();
        for (var i = 0; i < lectures.length; i++) {
            var start = new Date(lectures[i].startTime).getTime();
            var end   = new Date(lectures[i].endTime).getTime();
            if (start < now && now < end) {
                return lectures[i];
            }
        }
    };

    var getNextLecture = function() {
        var nextLecture;
        var nextLectureDistance = 18446744073709552000;
        for (var i = 0; i < lectures.length; i++) {
            var lectureDistance = new Date(lectures[i].startTime).getTime() - new Date().getTime();
            if (lectureDistance < nextLectureDistance && lectureDistance > 0) {
                nextLectureDistance = lectureDistance;
                nextLecture = lectures[i];
            }
        }
        return nextLecture;
    };

    return {
        lectures: lectures,
        lecturesForGroups: lecturesForGroups,
        fromCache: fromCache,
        getAllLectureTitles: getAllLectureTitles,
        secondsSinceCache: secondsSinceCache,
        getCurrentLecture: getCurrentLecture,
        getNextLecture: getNextLecture
    };
});
<|endoftext|>


<commit_before>/*jshint bitwise: false*/

"use strict";

angular.module("wuw.services")

.factory("Lectures", function($http, $q, Settings) {
    var lectures = JSON.parse(Settings.getSetting('lecturesCache') || '[]');
    var lecturesWeekly = JSON.parse(Settings.getSetting('lecturesWeeklyCache') || '[]');

    var lecturesThisWeek = function() {
        var deferred = $q.defer();
        var selectedLectures = JSON.parse(Settings.getSetting("selectedLectures") || "[]");

        // if the user hasn't selected courses, reject the request
        if (selectedLectures.length === 0) {
            lectures = [];
            Settings.setSetting('lecturesWeeklyCache', '[]');
            deferred.reject("noLecturesSelected");
            return deferred.promise;
        }

        $http.get(Settings.getSetting("apiUrl") + "/lectures/user/" + Settings.getSetting('uuid'))
        .success(function(data, status, headers, config) {

            // add datefield to every lecutre (useable for grouping)
            for (var i = 0; i < data.length; i++) {
                var d = new Date(data[i].startTime).setHours(0);
                data[i].date = new Date(d).setMinutes(0);
            }

            // add full-calendar specific properties
            var fcPreparedLectures = [];
            for (var j = 0; j < data.length; j++) {
                var l = {
                    fciId: j,
                    title: data[j].lectureName,
                    start: new Date(data[j].startTime),
                    end: new Date(data[j].endTime),
                    rooms: data[j].rooms,
                    docents: data[j].docents,
                    color: data[j].color,
                    stick: true,
                    allDay: false
                };
                fcPreparedLectures.push(l);
            }

            Settings.setSetting('lecturesWeeklyCache', JSON.stringify(fcPreparedLectures));
            Settings.setSetting('lecturesWeeklyCacheTime', new Date().getTime());
            lecturesWeekly = fcPreparedLectures;
            deferred.resolve(fcPreparedLectures);
        }).
        error(function(data, status, headers, config) {
            deferred.reject("httpFailed");
        });
        return deferred.promise;
    };

    var lecturesForGroups = function() {
        var deferred = $q.defer();
        var selectedLectures = JSON.parse(Settings.getSetting("selectedLectures") || "[]");

        // if the user hasn't selected courses, reject the request
        if (selectedLectures.length === 0) {
            lectures = [];
            Settings.setSetting('lecturesCache', '[]');
            deferred.reject("noLecturesSelected");
            return deferred.promise;
        }

        $http.get(Settings.getSetting("apiUrl") + "/lectures/users/" + Settings.getSetting('uuid'))
        .success(function(data, status, headers, config) {

            // add datefield to every lecutre (useable for grouping)
            for (var i = 0; i < data.length; i++) {
                var d = new Date(data[i].startTime).setHours(0);
                data[i].date = new Date(d).setMinutes(0);
            }

            Settings.setSetting('lecturesCache', JSON.stringify(data));
            Settings.setSetting('lecturesCacheTime', new Date().getTime());
            lectures = data;
            deferred.resolve(data);
        }).
        error(function(data, status, headers, config) {
            deferred.reject("httpFailed");
        });
        return deferred.promise;
    };

    /*
        Returns lectures from cache.
        If mode is "weekly" we provide data for easy use in full calendar.
    */
    var fromCache = function(mode) {
        var cached;
        if (mode === "weekly") {
            cached = JSON.parse(Settings.getSetting('lecturesWeeklyCache') || '[]');
            // convert the date-strings to real JS-Dates
            for (var i = 0; i < cached.length; i++) {
                cached[i].start = new Date(cached[i].start);
                cached[i].end = new Date(cached[i].end);
            }
            return cached;
        }
        cached = JSON.parse(Settings.getSetting('lecturesCache') || '[]');
        return cached;
    };

    /*
        Returns how many seconds has passed since we cached the lectures.
    */
    var secondsSinceCache = function(mode) {
        var cacheTime;
        if (mode === "weekly") {
            cacheTime = Settings.getSetting('lecturesWeeklyCacheTime');
        } else {
            cacheTime = Settings.getSetting('lecturesCacheTime');
        }

        if (typeof cacheTime === 'undefined') {
            return Math.pow(2,32) - 1; // highest integer in JS
        }

        var diff = new Date().getTime() - cacheTime;
        var seconds = Math.round(diff / 1000);
        return seconds;
    };

    /*
        Returns the title of all lectures in a distinct manner.
    */
    var getAllLectureTitles = function() {
        return JSON.parse(Settings.getSetting("selectedLectures"));
    };

    /*
        Returns the lecture which is currently running.
    */
    var getCurrentLecture = function() {
        var now = new Date().getTime();
        for (var i = 0; i < lectures.length; i++) {
            var start = new Date(lectures[i].startTime).getTime();
            var end   = new Date(lectures[i].endTime).getTime();
            if (start < now && now < end) {
                return lectures[i];
            }
        }
    };

    /*
        Returns the Users next Lecture.
    */
    var getNextLecture = function() {
        var nextLecture;
        var nextLectureDistance = 18446744073709552000;
        for (var i = 0; i < lectures.length; i++) {
            var lectureDistance = new Date(lectures[i].startTime).getTime() - new Date().getTime();
            if (lectureDistance < nextLectureDistance && lectureDistance > 0) {
                nextLectureDistance = lectureDistance;
                nextLecture = lectures[i];
            }
        }
        return nextLecture;
    };

    /*
        Returns how many lectures the user has selected.
    */
    var getSelectedLecturesLength = function() {
        var selectedLecturesLength = Settings.getSetting('selectedLecturesLength');
        if (typeof selectedLecturesLength === "undefined") {
            selectedLecturesLength = JSON.parse(Settings.getSetting("selectedLectures") || "[]").length;
            Settings.setSetting("selectedLecturesLength", selectedLecturesLength);
            return selectedLecturesLength;
        } else {
            return parseInt(selectedLecturesLength);
        }
    };

    return {
        lectures: lectures,
        lecturesForGroups: lecturesForGroups,
        lecturesThisWeek: lecturesThisWeek,
        fromCache: fromCache,
        getAllLectureTitles: getAllLectureTitles,
        secondsSinceCache: secondsSinceCache,
        getCurrentLecture: getCurrentLecture,
        getNextLecture: getNextLecture,
        getSelectedLecturesLength: getSelectedLecturesLength
    };
});
<commit_msg>use plural in apis<commit_after>/*jshint bitwise: false*/

"use strict";

angular.module("wuw.services")

.factory("Lectures", function($http, $q, Settings) {
    var lectures = JSON.parse(Settings.getSetting('lecturesCache') || '[]');
    var lecturesWeekly = JSON.parse(Settings.getSetting('lecturesWeeklyCache') || '[]');

    var lecturesThisWeek = function() {
        var deferred = $q.defer();
        var selectedLectures = JSON.parse(Settings.getSetting("selectedLectures") || "[]");

        // if the user hasn't selected courses, reject the request
        if (selectedLectures.length === 0) {
            lectures = [];
            Settings.setSetting('lecturesWeeklyCache', '[]');
            deferred.reject("noLecturesSelected");
            return deferred.promise;
        }

        $http.get(Settings.getSetting("apiUrl") + "/lectures/users/" + Settings.getSetting('uuid'))
        .success(function(data, status, headers, config) {

            // add datefield to every lecutre (useable for grouping)
            for (var i = 0; i < data.length; i++) {
                var d = new Date(data[i].startTime).setHours(0);
                data[i].date = new Date(d).setMinutes(0);
            }

            // add full-calendar specific properties
            var fcPreparedLectures = [];
            for (var j = 0; j < data.length; j++) {
                var l = {
                    fciId: j,
                    title: data[j].lectureName,
                    start: new Date(data[j].startTime),
                    end: new Date(data[j].endTime),
                    rooms: data[j].rooms,
                    docents: data[j].docents,
                    color: data[j].color,
                    stick: true,
                    allDay: false
                };
                fcPreparedLectures.push(l);
            }

            Settings.setSetting('lecturesWeeklyCache', JSON.stringify(fcPreparedLectures));
            Settings.setSetting('lecturesWeeklyCacheTime', new Date().getTime());
            lecturesWeekly = fcPreparedLectures;
            deferred.resolve(fcPreparedLectures);
        }).
        error(function(data, status, headers, config) {
            deferred.reject("httpFailed");
        });
        return deferred.promise;
    };

    var lecturesForGroups = function() {
        var deferred = $q.defer();
        var selectedLectures = JSON.parse(Settings.getSetting("selectedLectures") || "[]");

        // if the user hasn't selected courses, reject the request
        if (selectedLectures.length === 0) {
            lectures = [];
            Settings.setSetting('lecturesCache', '[]');
            deferred.reject("noLecturesSelected");
            return deferred.promise;
        }

        $http.get(Settings.getSetting("apiUrl") + "/lectures/users/" + Settings.getSetting('uuid'))
        .success(function(data, status, headers, config) {

            // add datefield to every lecutre (useable for grouping)
            for (var i = 0; i < data.length; i++) {
                var d = new Date(data[i].startTime).setHours(0);
                data[i].date = new Date(d).setMinutes(0);
            }

            Settings.setSetting('lecturesCache', JSON.stringify(data));
            Settings.setSetting('lecturesCacheTime', new Date().getTime());
            lectures = data;
            deferred.resolve(data);
        }).
        error(function(data, status, headers, config) {
            deferred.reject("httpFailed");
        });
        return deferred.promise;
    };

    /*
        Returns lectures from cache.
        If mode is "weekly" we provide data for easy use in full calendar.
    */
    var fromCache = function(mode) {
        var cached;
        if (mode === "weekly") {
            cached = JSON.parse(Settings.getSetting('lecturesWeeklyCache') || '[]');
            // convert the date-strings to real JS-Dates
            for (var i = 0; i < cached.length; i++) {
                cached[i].start = new Date(cached[i].start);
                cached[i].end = new Date(cached[i].end);
            }
            return cached;
        }
        cached = JSON.parse(Settings.getSetting('lecturesCache') || '[]');
        return cached;
    };

    /*
        Returns how many seconds has passed since we cached the lectures.
    */
    var secondsSinceCache = function(mode) {
        var cacheTime;
        if (mode === "weekly") {
            cacheTime = Settings.getSetting('lecturesWeeklyCacheTime');
        } else {
            cacheTime = Settings.getSetting('lecturesCacheTime');
        }

        if (typeof cacheTime === 'undefined') {
            return Math.pow(2,32) - 1; // highest integer in JS
        }

        var diff = new Date().getTime() - cacheTime;
        var seconds = Math.round(diff / 1000);
        return seconds;
    };

    /*
        Returns the title of all lectures in a distinct manner.
    */
    var getAllLectureTitles = function() {
        return JSON.parse(Settings.getSetting("selectedLectures"));
    };

    /*
        Returns the lecture which is currently running.
    */
    var getCurrentLecture = function() {
        var now = new Date().getTime();
        for (var i = 0; i < lectures.length; i++) {
            var start = new Date(lectures[i].startTime).getTime();
            var end   = new Date(lectures[i].endTime).getTime();
            if (start < now && now < end) {
                return lectures[i];
            }
        }
    };

    /*
        Returns the Users next Lecture.
    */
    var getNextLecture = function() {
        var nextLecture;
        var nextLectureDistance = 18446744073709552000;
        for (var i = 0; i < lectures.length; i++) {
            var lectureDistance = new Date(lectures[i].startTime).getTime() - new Date().getTime();
            if (lectureDistance < nextLectureDistance && lectureDistance > 0) {
                nextLectureDistance = lectureDistance;
                nextLecture = lectures[i];
            }
        }
        return nextLecture;
    };

    /*
        Returns how many lectures the user has selected.
    */
    var getSelectedLecturesLength = function() {
        var selectedLecturesLength = Settings.getSetting('selectedLecturesLength');
        if (typeof selectedLecturesLength === "undefined") {
            selectedLecturesLength = JSON.parse(Settings.getSetting("selectedLectures") || "[]").length;
            Settings.setSetting("selectedLecturesLength", selectedLecturesLength);
            return selectedLecturesLength;
        } else {
            return parseInt(selectedLecturesLength);
        }
    };

    return {
        lectures: lectures,
        lecturesForGroups: lecturesForGroups,
        lecturesThisWeek: lecturesThisWeek,
        fromCache: fromCache,
        getAllLectureTitles: getAllLectureTitles,
        secondsSinceCache: secondsSinceCache,
        getCurrentLecture: getCurrentLecture,
        getNextLecture: getNextLecture,
        getSelectedLecturesLength: getSelectedLecturesLength
    };
});
<|endoftext|>


<commit_before>define(function(require, exports, module) {
    module.exports = {
        "basic" : {
            "baseUrl" : "https://test.namie-tablet.org/",
            "cellId" : "kizuna01",
            "boxName" : "data",
            "odataName" : "odata",
            "pcsVersion" : "1.3.20",
            // view category (ex. news, dojo, letter, posting, ope ..).
            "mode" : "news"
        },
        "logger" : {
            "enable" : true,
            "threshold" : "DEBUG",
            "patternLayout" : "%d{yyyy/MM/dd HH:mm:ss,SSS} %c [%p] %m{1}",
            "useConsoleLog" : true
        },
        "googleAnalytics" : {
            "trackingId" : "UA-56712876-2"
        }
    };
});
<commit_msg>NAM-500 appConfigのpcsVersion を削除 担当：増田<commit_after>define(function(require, exports, module) {
    module.exports = {
        "basic" : {
            "baseUrl" : "https://test.namie-tablet.org/",
            "cellId" : "kizuna01",
            "boxName" : "data",
            "odataName" : "odata",
            // view category (ex. news, dojo, letter, posting, ope ..).
            "mode" : "news"
        },
        "logger" : {
            "enable" : true,
            "threshold" : "DEBUG",
            "patternLayout" : "%d{yyyy/MM/dd HH:mm:ss,SSS} %c [%p] %m{1}",
            "useConsoleLog" : true
        },
        "googleAnalytics" : {
            "trackingId" : "UA-56712876-2"
        }
    };
});
<|endoftext|>


<commit_before>OV.DetailsSidebarPanel = class extends OV.SidebarPanel
{
    constructor (parentDiv)
    {
        super (parentDiv);
    }

    GetTitle ()
    {
        return 'Details';
    }

    AddElementProperties (element)
    {
        this.Clear ();
        let table = $('<div>').addClass ('ov_property_table').appendTo (this.contentDiv);
        let boundingBox = OV.GetBoundingBox (element);
        let size = OV.SubCoord3D (boundingBox.max, boundingBox.min);
        this.AddProperty (table, new OV.Property (OV.PropertyType.Integer, 'Vertex Count', element.VertexCount ()));
        this.AddProperty (table, new OV.Property (OV.PropertyType.Integer, 'Triangle Count', element.TriangleCount ()));
        this.AddProperty (table, new OV.Property (OV.PropertyType.Number, 'Size X', size.x));
        this.AddProperty (table, new OV.Property (OV.PropertyType.Number, 'Size Y', size.y));
        this.AddProperty (table, new OV.Property (OV.PropertyType.Number, 'Size Z', size.z));
        this.AddCalculatedProperty (table, 'Volume', () => {
            const volume = OV.CalculateVolume (element);
            if (volume === null) {
                return null;
            }
            return new OV.Property (OV.PropertyType.Number, null, volume);
        });
        this.AddCalculatedProperty (table, 'Surface Area', () => {
            const volume = OV.CalculateSurfaceArea (element);
            if (volume === null) {
                return null;
            }
            return new OV.Property (OV.PropertyType.Number, null, volume);
        });
        if (element.PropertyGroupCount () > 0) {
            let customTable = $('<div>').addClass ('ov_property_table ov_property_table_custom').appendTo (this.contentDiv);
            for (let i = 0; i < element.PropertyGroupCount (); i++) {
                const propertyGroup = element.GetPropertyGroup (i);
                this.AddPropertyGroup (customTable, propertyGroup);
                for (let j = 0; j < propertyGroup.PropertyCount (); j++) {
                    const property = propertyGroup.GetProperty (j);
                    this.AddPropertyInGroup (customTable, property);
                }
            }
        }
        this.Resize ();
    }

    AddMaterialProperties (material)
    {
        function AddTextureMap (obj, table, name, map)
        {
            if (map === null || map.name === null) {
                return;
            }
            let fileName = OV.GetFileName (map.name);
            obj.AddProperty (table, new OV.Property (OV.PropertyType.Text, name, fileName));
        }

        this.Clear ();
        let table = $('<div>').addClass ('ov_property_table').appendTo (this.contentDiv);
        this.AddProperty (table, new OV.Property (OV.PropertyType.Text, 'Source', material.isDefault ? 'Default' : 'Model'));
        this.AddProperty (table, new OV.Property (OV.PropertyType.Color, 'Color', material.color));
        this.AddProperty (table, new OV.Property (OV.PropertyType.Percent, 'Opacity', material.opacity));
        AddTextureMap (this, table, 'Diffuse Map', material.diffuseMap);
        AddTextureMap (this, table, 'Specular Map', material.specularMap);
        AddTextureMap (this, table, 'Bump Map', material.bumpMap);
        AddTextureMap (this, table, 'Normal Map', material.normalMap);
        AddTextureMap (this, table, 'Emissive Map', material.emissiveMap);
        AddTextureMap (this, table, 'Metallic Map', material.metalnessMap);
        this.Resize ();
    }

    AddPropertyGroup (table, propertyGroup)
    {
        let row = $('<div>').addClass ('ov_property_table_row group').appendTo (table);
        row.html (propertyGroup.name).attr ('title', propertyGroup.name);
    }

    AddProperty (table, property)
    {
        let row = $('<div>').addClass ('ov_property_table_row').appendTo (table);
        let nameColum = $('<div>').addClass ('ov_property_table_cell ov_property_table_name').appendTo (row);
        let valueColumn = $('<div>').addClass ('ov_property_table_cell ov_property_table_value').appendTo (row);
        nameColum.html (property.name + ':').attr ('title', property.name);
        this.DisplayPropertyValue (property, valueColumn);
        return row;
    }

    AddPropertyInGroup (table, property)
    {
        let row = this.AddProperty (table, property);
        row.addClass ('ingroup');
    }

    AddCalculatedProperty (table, name, calculateValue)
    {
        let row = $('<div>').addClass ('ov_property_table_row').appendTo (table);
        let nameColum = $('<div>').addClass ('ov_property_table_cell ov_property_table_name').appendTo (row);
        let valueColumn = $('<div>').addClass ('ov_property_table_cell ov_property_table_value').appendTo (row);
        nameColum.html (name + ':').attr ('title', name);

        let calculateButton = $('<div>').addClass ('ov_property_table_button').html ('Calculate...').appendTo (valueColumn);
        calculateButton.click (() => {
            valueColumn.empty ();
            valueColumn.html ('Please wait...');
            OV.RunTaskAsync (() => {
                let propertyValue = calculateValue ();
                if (propertyValue === null) {
                    valueColumn.html ('-');
                } else {
                    this.DisplayPropertyValue (propertyValue, valueColumn);
                }
            });
        });
    }

    DisplayPropertyValue (property, targetDiv)
    {
        targetDiv.empty ();
        let valueText = null;
        if (property.type === OV.PropertyType.Text) {
            valueText = property.value;
        } else if (property.type === OV.PropertyType.Integer) {
            valueText = property.value.toLocaleString ();
        } else if (property.type === OV.PropertyType.Number) {
            valueText = property.value.toLocaleString (undefined, {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2
            });
        } else if (property.type === OV.PropertyType.Boolean) {
            valueText = property.value ? 'Yes' : 'No';
        } else if (property.type === OV.PropertyType.Percent) {
            valueText = parseInt (property.value * 100, 10).toString () + '%';
        } else if (property.type === OV.PropertyType.Color) {
            let hexString = '#' + OV.ColorToHexString (property.value);
            let colorCircle = OV.CreateInlineColorCircle (property.value);
            colorCircle.appendTo (targetDiv);
            $('<span>').html (hexString).appendTo (targetDiv);
        }
        if (valueText !== null) {
            targetDiv.html (valueText).attr ('title', valueText);
        }
    }
};
<commit_msg>Show material type in sidebar.<commit_after>OV.DetailsSidebarPanel = class extends OV.SidebarPanel
{
    constructor (parentDiv)
    {
        super (parentDiv);
    }

    GetTitle ()
    {
        return 'Details';
    }

    AddElementProperties (element)
    {
        this.Clear ();
        let table = $('<div>').addClass ('ov_property_table').appendTo (this.contentDiv);
        let boundingBox = OV.GetBoundingBox (element);
        let size = OV.SubCoord3D (boundingBox.max, boundingBox.min);
        this.AddProperty (table, new OV.Property (OV.PropertyType.Integer, 'Vertex Count', element.VertexCount ()));
        this.AddProperty (table, new OV.Property (OV.PropertyType.Integer, 'Triangle Count', element.TriangleCount ()));
        this.AddProperty (table, new OV.Property (OV.PropertyType.Number, 'Size X', size.x));
        this.AddProperty (table, new OV.Property (OV.PropertyType.Number, 'Size Y', size.y));
        this.AddProperty (table, new OV.Property (OV.PropertyType.Number, 'Size Z', size.z));
        this.AddCalculatedProperty (table, 'Volume', () => {
            const volume = OV.CalculateVolume (element);
            if (volume === null) {
                return null;
            }
            return new OV.Property (OV.PropertyType.Number, null, volume);
        });
        this.AddCalculatedProperty (table, 'Surface Area', () => {
            const volume = OV.CalculateSurfaceArea (element);
            if (volume === null) {
                return null;
            }
            return new OV.Property (OV.PropertyType.Number, null, volume);
        });
        if (element.PropertyGroupCount () > 0) {
            let customTable = $('<div>').addClass ('ov_property_table ov_property_table_custom').appendTo (this.contentDiv);
            for (let i = 0; i < element.PropertyGroupCount (); i++) {
                const propertyGroup = element.GetPropertyGroup (i);
                this.AddPropertyGroup (customTable, propertyGroup);
                for (let j = 0; j < propertyGroup.PropertyCount (); j++) {
                    const property = propertyGroup.GetProperty (j);
                    this.AddPropertyInGroup (customTable, property);
                }
            }
        }
        this.Resize ();
    }

    AddMaterialProperties (material)
    {
        function AddTextureMap (obj, table, name, map)
        {
            if (map === null || map.name === null) {
                return;
            }
            let fileName = OV.GetFileName (map.name);
            obj.AddProperty (table, new OV.Property (OV.PropertyType.Text, name, fileName));
        }

        this.Clear ();
        let table = $('<div>').addClass ('ov_property_table').appendTo (this.contentDiv);
        let typeString = null;
        if (material.type === OV.MaterialType.Phong) {
            typeString = 'Phong';
        } else if (material.type === OV.MaterialType.Physical) {
            typeString = 'Physical';
        }
        this.AddProperty (table, new OV.Property (OV.PropertyType.Text, 'Source', material.isDefault ? 'Default' : 'Model'));
        this.AddProperty (table, new OV.Property (OV.PropertyType.Text, 'Type', typeString));
        this.AddProperty (table, new OV.Property (OV.PropertyType.Color, 'Color', material.color));
        this.AddProperty (table, new OV.Property (OV.PropertyType.Percent, 'Opacity', material.opacity));
        AddTextureMap (this, table, 'Diffuse Map', material.diffuseMap);
        AddTextureMap (this, table, 'Specular Map', material.specularMap);
        AddTextureMap (this, table, 'Bump Map', material.bumpMap);
        AddTextureMap (this, table, 'Normal Map', material.normalMap);
        AddTextureMap (this, table, 'Emissive Map', material.emissiveMap);
        AddTextureMap (this, table, 'Metallic Map', material.metalnessMap);
        this.Resize ();
    }

    AddPropertyGroup (table, propertyGroup)
    {
        let row = $('<div>').addClass ('ov_property_table_row group').appendTo (table);
        row.html (propertyGroup.name).attr ('title', propertyGroup.name);
    }

    AddProperty (table, property)
    {
        let row = $('<div>').addClass ('ov_property_table_row').appendTo (table);
        let nameColum = $('<div>').addClass ('ov_property_table_cell ov_property_table_name').appendTo (row);
        let valueColumn = $('<div>').addClass ('ov_property_table_cell ov_property_table_value').appendTo (row);
        nameColum.html (property.name + ':').attr ('title', property.name);
        this.DisplayPropertyValue (property, valueColumn);
        return row;
    }

    AddPropertyInGroup (table, property)
    {
        let row = this.AddProperty (table, property);
        row.addClass ('ingroup');
    }

    AddCalculatedProperty (table, name, calculateValue)
    {
        let row = $('<div>').addClass ('ov_property_table_row').appendTo (table);
        let nameColum = $('<div>').addClass ('ov_property_table_cell ov_property_table_name').appendTo (row);
        let valueColumn = $('<div>').addClass ('ov_property_table_cell ov_property_table_value').appendTo (row);
        nameColum.html (name + ':').attr ('title', name);

        let calculateButton = $('<div>').addClass ('ov_property_table_button').html ('Calculate...').appendTo (valueColumn);
        calculateButton.click (() => {
            valueColumn.empty ();
            valueColumn.html ('Please wait...');
            OV.RunTaskAsync (() => {
                let propertyValue = calculateValue ();
                if (propertyValue === null) {
                    valueColumn.html ('-');
                } else {
                    this.DisplayPropertyValue (propertyValue, valueColumn);
                }
            });
        });
    }

    DisplayPropertyValue (property, targetDiv)
    {
        targetDiv.empty ();
        let valueText = null;
        if (property.type === OV.PropertyType.Text) {
            valueText = property.value;
        } else if (property.type === OV.PropertyType.Integer) {
            valueText = property.value.toLocaleString ();
        } else if (property.type === OV.PropertyType.Number) {
            valueText = property.value.toLocaleString (undefined, {
                minimumFractionDigits: 2,
                maximumFractionDigits: 2
            });
        } else if (property.type === OV.PropertyType.Boolean) {
            valueText = property.value ? 'Yes' : 'No';
        } else if (property.type === OV.PropertyType.Percent) {
            valueText = parseInt (property.value * 100, 10).toString () + '%';
        } else if (property.type === OV.PropertyType.Color) {
            let hexString = '#' + OV.ColorToHexString (property.value);
            let colorCircle = OV.CreateInlineColorCircle (property.value);
            colorCircle.appendTo (targetDiv);
            $('<span>').html (hexString).appendTo (targetDiv);
        }
        if (valueText !== null) {
            targetDiv.html (valueText).attr ('title', valueText);
        }
    }
};
<|endoftext|>


<commit_before>/**
 * Monkey-patch necessary for getting S3 uploads to works. Ensures that the XHR
 * is opened only after options.method and options.url have been resolved.
 */
/*jshint ignore:start */
(function($, Dropzone) {

        __hasProp = {}.hasOwnProperty,
        __extends = function(child, parent) {
            for (var key in parent) {
                if (__hasProp.call(parent, key)) child[key] = parent[key];
            }

            function ctor() {
                this.constructor = child;
            }
            ctor.prototype = parent.prototype;
            child.prototype = new ctor();
            child.__super__ = parent.prototype;
            return child;
        },
        __slice = [].slice;

        extend = function() {
            var key, object, objects, target, val, _i, _len;
            target = arguments[0], objects = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
            for (_i = 0, _len = objects.length; _i < _len; _i++) {
                object = objects[_i];
                for (key in object) {
                    val = object[key];
                    target[key] = val;
                }
            }
            return target;
        };

        /**
         * Get the url to use for the upload request.
         *
         * NOTE: This is a hack to get S3 uploads to work.
         */
        Dropzone.prototype.getUrl = function(file) {
            var self = this;
            if (this.options.signedUrlFrom) {
                return $.ajax({
                    type: 'POST',
                    url: self.options.signedUrlFrom,
                    data: JSON.stringify({
                        name: file.destination || file.name,
                        type: file.type || 'application/octet-stream'
                    }),
                    contentType: 'application/json',
                    dataType: 'json',
                }).success(function(url) {
                  self.options.signedUrlFrom = null;
                    return self.options.url = url;
                });
            } else {
                return this.options.url;
            }
        };

        Dropzone.prototype.uploadFiles = function(files) {
            var file, formData, handleError, headerName, headerValue, headers, input, inputName, inputType, key, option, progressObj, response, updateProgress, value, xhr, _i, _j, _k, _l, _len, _len1, _len2, _len3, _len4, _m, _ref, _ref1, _ref2, _ref3, _ref4,
                _this = this;
            xhr = new XMLHttpRequest();
            for (_i = 0, _len = files.length; _i < _len; _i++) {
                file = files[_i];
                file.xhr = xhr;
            }

            // Defer sending the xhr until the URL has been resolved.
            // NOTE: This will only work with multipleUploads turned off
            $.when(_this.getUrl(files[0])).done(function(uploadUrl) {
                    xhr.open(_this.options.method, _this.options.url, true);
                    xhr.withCredentials = !! _this.options.withCredentials;
                    response = null;
                    handleError = function() {
                        var _j, _len1, _results;
                        _results = [];
                        for (_j = 0, _len1 = files.length; _j < _len1; _j++) {
                            file = files[_j];
                            _results.push(_this._errorProcessing(files, response || _this.options.dictResponseError.replace("{{statusCode}}", xhr.status), xhr));
                        }
                        return _results;
                    };
                    updateProgress = function(e) {
                        var allFilesFinished, progress, _j, _k, _l, _len1, _len2, _len3, _results;
                        if (e != null) {
                            progress = 100 * e.loaded / e.total;
                            for (_j = 0, _len1 = files.length; _j < _len1; _j++) {
                                file = files[_j];
                                file.upload = {
                                    progress: progress,
                                    total: e.total,
                                    bytesSent: e.loaded
                                };
                            }
                        } else {
                            allFilesFinished = true;
                            progress = 100;
                            for (_k = 0, _len2 = files.length; _k < _len2; _k++) {
                                file = files[_k];
                                if (!(file.upload.progress === 100 && file.upload.bytesSent === file.upload.total)) {
                                    allFilesFinished = false;
                                }
                                file.upload.progress = progress;
                                file.upload.bytesSent = file.upload.total;
                            }
                            if (allFilesFinished) {
                                return;
                            }
                        }
                        _results = [];
                        for (_l = 0, _len3 = files.length; _l < _len3; _l++) {
                            file = files[_l];
                            _results.push(_this.emit("uploadprogress", file, progress, file.upload.bytesSent));
                        }
                        return _results;
                    };
                    xhr.onload = function(e) {
                        var _ref;
                        if (files[0].status === Dropzone.CANCELED) {
                            return;
                        }
                        if (xhr.readyState !== 4) {
                            return;
                        }
                        response = xhr.responseText;
                        if (xhr.getResponseHeader("content-type") && ~xhr.getResponseHeader("content-type").indexOf("application/json")) {
                            try {
                                response = JSON.parse(response);
                            } catch (_error) {
                                e = _error;
                                response = "Invalid JSON response from server.";
                            }
                        }
                        updateProgress();
                        if (!((200 <= (_ref = xhr.status) && _ref < 300))) {
                            return handleError();
                        } else {
                            return _this._finished(files, response, e);
                        }
                    };
                    xhr.onerror = function() {
                        if (files[0].status === Dropzone.CANCELED) {
                            return;
                        }
                        return handleError();
                    };
                    progressObj = (_ref = xhr.upload) != null ? _ref : xhr;
                    progressObj.onprogress = updateProgress;
                    headers = {
                        "Accept": "application/json",
                        "Cache-Control": "no-cache",
                        "X-Requested-With": "XMLHttpRequest"
                    };
                    if (_this.options.headers) {
                        extend(headers, _this.options.headers);
                    }
                    for (headerName in headers) {
                        headerValue = headers[headerName];
                        xhr.setRequestHeader(headerName, headerValue);
                    }

                    formData = new FormData();
                    if (_this.options.params) {
                        _ref1 = _this.options.params;
                        for (key in _ref1) {
                            value = _ref1[key];
                            formData.append(key, value);
                        }
                    }
                    for (_j = 0, _len1 = files.length; _j < _len1; _j++) {
                        file = files[_j];
                        _this.emit("sending", file, xhr, formData);
                    }
                    if (_this.options.uploadMultiple) {
                        _this.emit("sendingmultiple", files, xhr, formData);
                    }
                    if (_this.options.signedUrlFrom) {
                        return xhr.send(files[0]);
                    } else {
                    if (_this.element.tagName === "FORM") {
                        _ref2 = _this.element.querySelectorAll("input, textarea, select, button");
                        for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) {
                            input = _ref2[_k];
                            inputName = input.getAttribute("name");
                            inputType = input.getAttribute("type");
                            if (input.tagName === "SELECT" && input.hasAttribute("multiple")) {
                                _ref3 = input.options;
                                for (_l = 0, _len3 = _ref3.length; _l < _len3; _l++) {
                                    option = _ref3[_l];
                                    if (option.selected) {
                                        formData.append(inputName, option.value);
                                    }
                                }
                            } else if (!inputType || ((_ref4 = inputType.toLowerCase()) !== "checkbox" && _ref4 !== "radio") || input.checked) {
                                formData.append(inputName, input.value);
                            }
                        }
                    }
                    for (_m = 0, _len4 = files.length; _m < _len4; _m++) {
                        file = files[_m];
                        formData.append("" + _this.options.paramName + (_this.options.uploadMultiple ? "[]" : ""), file, file.name);
                    }
                    return xhr.send(formData);
                }
            });
    };
})(jQuery, Dropzone);
/*jshint ignore:end */
<commit_msg>Fixed an uploading bug, now everything should happily work together.<commit_after>/**
 * Monkey-patch necessary for getting S3 uploads to works. Ensures that the XHR
 * is opened only after options.method and options.url have been resolved.
 */
/*jshint ignore:start */
(function($, Dropzone) {

        __hasProp = {}.hasOwnProperty,
        __extends = function(child, parent) {
            for (var key in parent) {
                if (__hasProp.call(parent, key)) child[key] = parent[key];
            }

            function ctor() {
                this.constructor = child;
            }
            ctor.prototype = parent.prototype;
            child.prototype = new ctor();
            child.__super__ = parent.prototype;
            return child;
        },
        __slice = [].slice;

        extend = function() {
            var key, object, objects, target, val, _i, _len;
            target = arguments[0], objects = 2 <= arguments.length ? __slice.call(arguments, 1) : [];
            for (_i = 0, _len = objects.length; _i < _len; _i++) {
                object = objects[_i];
                for (key in object) {
                    val = object[key];
                    target[key] = val;
                }
            }
            return target;
        };

        /**
         * Get the url to use for the upload request.
         *
         * NOTE: This is a hack to get S3 uploads to work.
         */
        Dropzone.prototype.getUrl = function(file) {
            var self = this;
            if (this.options.signedUrlFrom) {
                return $.ajax({
                    type: 'POST',
                    url: self.options.signedUrlFrom,
                    data: JSON.stringify({
                        name: file.destination || file.name,
                        type: file.type || 'application/octet-stream'
                    }),
                    contentType: 'application/json',
                    dataType: 'json',
                }).success(function(url) {
                  self.options.signedUrlFrom = null;
                    return self.options.url = url;
                });
            } else {
                return this.options.url;
            }
        };

        Dropzone.prototype.uploadFiles = function(files) {
            var file, formData, handleError, headerName, headerValue, headers, input, inputName, inputType, key, option, progressObj, response, updateProgress, value, xhr, _i, _j, _k, _l, _len, _len1, _len2, _len3, _len4, _m, _ref, _ref1, _ref2, _ref3, _ref4,
                _this = this, wasSigned = this.options.signedUrlFrom;
            xhr = new XMLHttpRequest();
            for (_i = 0, _len = files.length; _i < _len; _i++) {
                file = files[_i];
                file.xhr = xhr;
            }

            // Defer sending the xhr until the URL has been resolved.
            // NOTE: This will only work with multipleUploads turned off
            $.when(_this.getUrl(files[0])).done(function(uploadUrl) {
                    xhr.open(_this.options.method, _this.options.url, true);
                    xhr.withCredentials = !! _this.options.withCredentials;
                    response = null;
                    handleError = function() {
                        var _j, _len1, _results;
                        _results = [];
                        for (_j = 0, _len1 = files.length; _j < _len1; _j++) {
                            file = files[_j];
                            _results.push(_this._errorProcessing(files, response || _this.options.dictResponseError.replace("{{statusCode}}", xhr.status), xhr));
                        }
                        return _results;
                    };
                    updateProgress = function(e) {
                        var allFilesFinished, progress, _j, _k, _l, _len1, _len2, _len3, _results;
                        if (e != null) {
                            progress = 100 * e.loaded / e.total;
                            for (_j = 0, _len1 = files.length; _j < _len1; _j++) {
                                file = files[_j];
                                file.upload = {
                                    progress: progress,
                                    total: e.total,
                                    bytesSent: e.loaded
                                };
                            }
                        } else {
                            allFilesFinished = true;
                            progress = 100;
                            for (_k = 0, _len2 = files.length; _k < _len2; _k++) {
                                file = files[_k];
                                if (!(file.upload.progress === 100 && file.upload.bytesSent === file.upload.total)) {
                                    allFilesFinished = false;
                                }
                                file.upload.progress = progress;
                                file.upload.bytesSent = file.upload.total;
                            }
                            if (allFilesFinished) {
                                return;
                            }
                        }
                        _results = [];
                        for (_l = 0, _len3 = files.length; _l < _len3; _l++) {
                            file = files[_l];
                            _results.push(_this.emit("uploadprogress", file, progress, file.upload.bytesSent));
                        }
                        return _results;
                    };
                    xhr.onload = function(e) {
                        var _ref;
                        if (files[0].status === Dropzone.CANCELED) {
                            return;
                        }
                        if (xhr.readyState !== 4) {
                            return;
                        }
                        response = xhr.responseText;
                        if (xhr.getResponseHeader("content-type") && ~xhr.getResponseHeader("content-type").indexOf("application/json")) {
                            try {
                                response = JSON.parse(response);
                            } catch (_error) {
                                e = _error;
                                response = "Invalid JSON response from server.";
                            }
                        }
                        updateProgress();
                        if (!((200 <= (_ref = xhr.status) && _ref < 300))) {
                            return handleError();
                        } else {
                            return _this._finished(files, response, e);
                        }
                    };
                    xhr.onerror = function() {
                        if (files[0].status === Dropzone.CANCELED) {
                            return;
                        }
                        return handleError();
                    };
                    progressObj = (_ref = xhr.upload) != null ? _ref : xhr;
                    progressObj.onprogress = updateProgress;
                    headers = {
                        "Accept": "application/json",
                        "Cache-Control": "no-cache",
                        "X-Requested-With": "XMLHttpRequest"
                    };
                    if (_this.options.headers) {
                        extend(headers, _this.options.headers);
                    }
                    for (headerName in headers) {
                        headerValue = headers[headerName];
                        xhr.setRequestHeader(headerName, headerValue);
                    }

                    formData = new FormData();
                    if (_this.options.params) {
                        _ref1 = _this.options.params;
                        for (key in _ref1) {
                            value = _ref1[key];
                            formData.append(key, value);
                        }
                    }
                    for (_j = 0, _len1 = files.length; _j < _len1; _j++) {
                        file = files[_j];
                        _this.emit("sending", file, xhr, formData);
                    }
                    if (_this.options.uploadMultiple) {
                        _this.emit("sendingmultiple", files, xhr, formData);
                    }
                    if (wasSigned) {
                        return xhr.send(files[0]);
                    } else {
                    if (_this.element.tagName === "FORM") {
                        _ref2 = _this.element.querySelectorAll("input, textarea, select, button");
                        for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) {
                            input = _ref2[_k];
                            inputName = input.getAttribute("name");
                            inputType = input.getAttribute("type");
                            if (input.tagName === "SELECT" && input.hasAttribute("multiple")) {
                                _ref3 = input.options;
                                for (_l = 0, _len3 = _ref3.length; _l < _len3; _l++) {
                                    option = _ref3[_l];
                                    if (option.selected) {
                                        formData.append(inputName, option.value);
                                    }
                                }
                            } else if (!inputType || ((_ref4 = inputType.toLowerCase()) !== "checkbox" && _ref4 !== "radio") || input.checked) {
                                formData.append(inputName, input.value);
                            }
                        }
                    }
                    for (_m = 0, _len4 = files.length; _m < _len4; _m++) {
                        file = files[_m];
                        formData.append("" + _this.options.paramName + (_this.options.uploadMultiple ? "[]" : ""), file, file.name);
                    }
                    return xhr.send(formData);
                }
            });
    };
})(jQuery, Dropzone);
/*jshint ignore:end */
<|endoftext|>


<commit_before>var countbutton = document.getElementById('wordcount_button');
var topwordsbutton = document.getElementById('topwords_button');
var topcharactersbutton = document.getElementById('topcharacters_button');

var input_area = document.getElementById('words_textarea');

countbutton.onclick=function(){
  wordCount();
  input_area.onkeydown=function(){ wordCount() }
};

topwordsbutton.onclick=function(){
  topWords();
  input_area.onkeydown=function(){ topWords() }
};

topcharactersbutton.onclick=function(){
  topcharacters();
  input_area.onkeydown=function(){ topcharacters() }
};

function wordCount() {

  document.getElementById('all_text').innerHTML='';

  var words = document.getElementById("words_textarea").value.trim().split(' ');

  var para = document.createElement("p");

  if (words.length > 1) {
    var count = document.createTextNode('Your document is ' + words.length + ' words long.');
  } else if (words.length = 1) {
    var count = document.createTextNode('Your document is ' + words.length + ' word long.');
  } else if (words[0] === "") {
    var count = document.createTextNode('Your document is 0 words long.');
  }

  para.appendChild(count);

  var element = document.getElementById("all_text");
  element.appendChild(para);
}

function topWords() {

  document.getElementById('all_text').innerHTML='';

  var words = document.getElementById("words_textarea").value.trim().split(' ');

  var counts = [];

  for (i=0;i<=words.length - 1;i++) {
    var found = false;
    var current_word = words[i].toLowerCase();

    for (n=0;n<=counts.length - 1;n++) {
      if (counts[n][0] == current_word) {
        counts[n][1] += 1;
        found = true;
        break;
      }
    }

    if (found == false) {
      counts.push([current_word,1]);
    }
  }

  var sorted = counts.sort(function(a,b) {
    return b[1] - a[1]
  });

  function createTable() {
    var element = document.getElementById("all_text");

    var tbl=document.createElement('table');

    tbl.style.width='100%';

    tbl.setAttribute('border','1');

    var tbdy=document.createElement('tbody');

    var tr=document.createElement('tr');
    var word = document.createElement('td');
    word.innerHTML="Word"
    var countword = document.createElement('td');
    countword.innerHTML="Count"
    var suggestions = document.createElement('td');
    suggestions.innerHTML="Suggestions"
    tr.appendChild(word)
    tr.appendChild(countword)
    tr.appendChild(suggestions)
    tbdy.appendChild(tr);
    tbl.appendChild(tbdy);
    element.appendChild(tbl)

    for(i=0;i<=counts.length - 1;i++) {
      var tr=document.createElement('tr');
      var word = document.createElement('td');
      word.innerHTML=counts[i][0]
      var countword = document.createElement('td');
      countword.innerHTML=counts[i][1]

      if (i<=4) {
        var suggestion = document.createElement('td');
        $.getJSON('http://words.bighugelabs.com/api/2/dafe2e8acd88d00e5096b17ca16157a7/' + counts[i][0] + '/json', {}, function(data) {
          suggestion.innerHTML= 'data[0][0] + data[0][1]'
        });
      }

      tr.appendChild(word)
      tr.appendChild(countword)
      tr.appendChild(suggestion)
      tbdy.appendChild(tr);
    }
    tbl.appendChild(tbdy);
    element.appendChild(tbl)
  }
  createTable()
}

function topcharacters() {
  document.getElementById('all_text').innerHTML='';

  var characters = document.getElementById("words_textarea").value.trim().split('');

  var counts = [];

  for (i=0;i<=characters.length - 1;i++) {
    var found = false;
    var current_letter = characters[i].toLowerCase();

    for (n=0;n<=counts.length - 1;n++) {
      if (counts[n][0] == current_letter) {
        counts[n][1] += 1;
        found = true;
        break;
      }
    }

    if (found == false) {
      counts.push([current_letter,1]);
    }
  }

  var sorted = counts.sort(function(a,b) {
    return b[1] - a[1]
  });

  function createTable() {
    var element = document.getElementById("all_text");

    var tbl=document.createElement('table');

    tbl.style.width='100%';

    tbl.setAttribute('border','1');

    var tbdy=document.createElement('tbody');

    var tr=document.createElement('tr');
    var word = document.createElement('td');
    word.innerHTML="Character"
    var countword = document.createElement('td');
    countword.innerHTML="Count"
    tr.appendChild(word)
    tr.appendChild(countword)
    tbdy.appendChild(tr);
    tbl.appendChild(tbdy);
    element.appendChild(tbl)

    for(i=0;i<=counts.length - 1;i++){
      var tr=document.createElement('tr');
      var word = document.createElement('td');
      word.innerHTML=counts[i][0]
      var countword = document.createElement('td');
      countword.innerHTML=counts[i][1]
      tr.appendChild(word)
      tr.appendChild(countword)
      tbdy.appendChild(tr);
    }
    tbl.appendChild(tbdy);
    element.appendChild(tbl)
  }
  createTable()
}
<commit_msg>all counts greater than three have synonym suggestion<commit_after>var countbutton = document.getElementById('wordcount_button');
var topwordsbutton = document.getElementById('topwords_button');
var topcharactersbutton = document.getElementById('topcharacters_button');

var input_area = document.getElementById('words_textarea');

countbutton.onclick=function(){
  wordCount();
  input_area.onkeydown=function(){ wordCount() }
};

topwordsbutton.onclick=function(){
  topWords();
  input_area.onkeydown=function(){ topWords() }
};

topcharactersbutton.onclick=function(){
  topcharacters();
  input_area.onkeydown=function(){ topcharacters() }
};

function wordCount() {

  document.getElementById('all_text').innerHTML='';

  var words = document.getElementById("words_textarea").value.trim().split(' ');

  var para = document.createElement("p");

  if (words.length > 1) {
    var count = document.createTextNode('Your document is ' + words.length + ' words long.');
  } else if (words.length = 1) {
    var count = document.createTextNode('Your document is ' + words.length + ' word long.');
  } else if (words[0] === "") {
    var count = document.createTextNode('Your document is 0 words long.');
  }

  para.appendChild(count);

  var element = document.getElementById("all_text");
  element.appendChild(para);
}

function topWords() {

  document.getElementById('all_text').innerHTML='';

  var words = document.getElementById("words_textarea").value.trim().split(' ');

  var counts = [];

  for (i=0;i<=words.length - 1;i++) {
    var found = false;
    var current_word = words[i].toLowerCase();

    for (n=0;n<=counts.length - 1;n++) {
      if (counts[n][0] == current_word) {
        counts[n][1] += 1;
        found = true;
        break;
      }
    }

    if (found == false) {
      counts.push([current_word,1]);
    }
  }

  var sorted = counts.sort(function(a,b) {
    return b[1] - a[1]
  });

  function createTable() {
    var element = document.getElementById("all_text");

    var tbl=document.createElement('table');

    tbl.style.width='100%';

    tbl.setAttribute('border','1');

    var tbdy=document.createElement('tbody');

    var tr=document.createElement('tr');
    var word = document.createElement('td');
    word.innerHTML="Word"
    var countword = document.createElement('td');
    countword.innerHTML="Count"
    var suggestions = document.createElement('td');
    suggestions.innerHTML="Suggestions"
    tr.appendChild(word)
    tr.appendChild(countword)
    tr.appendChild(suggestions)
    tbdy.appendChild(tr);
    tbl.appendChild(tbdy);
    element.appendChild(tbl)

    for(i=0;i<=counts.length - 1;i++) {
      var tr=document.createElement('tr');
      var word = document.createElement('td');
      word.innerHTML=counts[i][0]
      var countword = document.createElement('td');
      countword.innerHTML=counts[i][1]

      if (counts[i][1] >= 3) {
        var suggestion = document.createElement('td');
        $.getJSON('http://words.bighugelabs.com/api/2/dafe2e8acd88d00e5096b17ca16157a7/' + counts[i][0] + '/json', {}, function(data) {
          suggestion.innerHTML= 'data[0][0] + data[0][1]'
        });
      }

      tr.appendChild(word)
      tr.appendChild(countword)
      tr.appendChild(suggestion)
      tbdy.appendChild(tr);
    }
    tbl.appendChild(tbdy);
    element.appendChild(tbl)
  }
  createTable()
}

function topcharacters() {
  document.getElementById('all_text').innerHTML='';

  var characters = document.getElementById("words_textarea").value.trim().split('');

  var counts = [];

  for (i=0;i<=characters.length - 1;i++) {
    var found = false;
    var current_letter = characters[i].toLowerCase();

    for (n=0;n<=counts.length - 1;n++) {
      if (counts[n][0] == current_letter) {
        counts[n][1] += 1;
        found = true;
        break;
      }
    }

    if (found == false) {
      counts.push([current_letter,1]);
    }
  }

  var sorted = counts.sort(function(a,b) {
    return b[1] - a[1]
  });

  function createTable() {
    var element = document.getElementById("all_text");

    var tbl=document.createElement('table');

    tbl.style.width='100%';

    tbl.setAttribute('border','1');

    var tbdy=document.createElement('tbody');

    var tr=document.createElement('tr');
    var word = document.createElement('td');
    word.innerHTML="Character"
    var countword = document.createElement('td');
    countword.innerHTML="Count"
    tr.appendChild(word)
    tr.appendChild(countword)
    tbdy.appendChild(tr);
    tbl.appendChild(tbdy);
    element.appendChild(tbl)

    for(i=0;i<=counts.length - 1;i++){
      var tr=document.createElement('tr');
      var word = document.createElement('td');
      word.innerHTML=counts[i][0]
      var countword = document.createElement('td');
      countword.innerHTML=counts[i][1]
      tr.appendChild(word)
      tr.appendChild(countword)
      tbdy.appendChild(tr);
    }
    tbl.appendChild(tbdy);
    element.appendChild(tbl)
  }
  createTable()
}
<|endoftext|>


<commit_before>define([
   'underscore'
  ,'getAtoms'
  ,'getBonds'
  ,'Atom'
  ,'Bond'
  // Modules below are ignored and not passed to the function.
  ,'three'
  ,'detector'
  ,'stats'
  ,'trackballControls'
  ,'keyboardState'
  ,'fullScreen'
  ,'windowResize'
  ], function( _, getAtoms, getBonds, Atom, Bond ){
  return function( mmCIF ){
    // Detector
    if ( !Detector.webgl ) Detector.addGetWebGLMessage();
    // Globals
    var container, scene, camera, renderer, controls, stats;
    var keyboard = new THREEx.KeyboardState();
    var clock = new THREE.Clock();

    // Functions
    var init = function(){

      ////////////
      // Set-up //
      ////////////

      // Create a scene
      scene = new THREE.Scene();

      // Camera
      var SCREEN_WIDTH = window.innerWidth, SCREEN_HEIGHT = window.innerHeight;
      var VIEW_ANGLE = 35, ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT, NEAR = 1, FAR = 10000;
      camera = new THREE.PerspectiveCamera( VIEW_ANGLE, ASPECT, NEAR, FAR );
      scene.add( camera );
      camera.position.set( 0, 150, 400 );
      camera.lookAt( scene.position );

      // Renderer
      renderer = new THREE.WebGLRenderer({ antialias: true });
      renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT );
      // renderer.setClearColorHex( 0xBBBBBB, 1 );
      container = document.createElement( 'div' );
      document.body.appendChild( container );
      container.appendChild( renderer.domElement );

      // Events
      THREEx.WindowResize( renderer, camera );
      THREEx.FullScreen.bindKey({ charCode: 'm'.charCodeAt( 0 ) });

      // Controls
      controls = new THREE.TrackballControls( camera );

      // Stats
      stats = new Stats();
      stats.domElement.style.position = 'absolute';
      stats.domElement.style.bottom = '0px';
      stats.domElement.style.zIndex = 100;
      container.appendChild( stats.domElement );

      // Lights
      var topLight = new THREE.PointLight( 0xf8f8f8 );
      topLight.position.set( 0, 500, 0 );
      scene.add( topLight );

      var bottomLight = new THREE.PointLight( 0xf8f8f8 );
      bottomLight.position.set( 0, -500, 0 );
      scene.add( bottomLight );

      var farLight = new THREE.PointLight( 0xc6c6c6 );
      farLight.position.set( 0, 0, -500 );
      scene.add( farLight );

      var nearLight = new THREE.PointLight( 0xc6c6c6 );
      nearLight.position.set( 0, 0, 500 );
      scene.add( nearLight );

      // add directional light source
      // var farDirectionalLight = new THREE.DirectionalLight( 0xf2f2f2 );
      // farDirectionalLight.position.set( 0, 0, -250 );
      // scene.add( farDirectionalLight );

      // var nearDirectionalLight = new THREE.DirectionalLight( 0xf2f2f2 );
      // nearDirectionalLight.position.set( 0, 0, 250 );
      // scene.add( nearDirectionalLight );

      // HELPERS
      var cameraHelper = new THREE.CameraHelper( camera );
      scene.add( cameraHelper );

      var topLightHelper = new THREE.PointLightHelper( topLight );
      scene.add( topLightHelper );

      var bottomLightHelper = new THREE.PointLightHelper( bottomLight );
      scene.add( bottomLightHelper );

      var farLightHelper = new THREE.PointLightHelper( farLight, 100 );
      scene.add( farLightHelper );

      var nearLightHelper = new THREE.PointLightHelper( nearLight, 20 );
      scene.add( nearLightHelper );

      // var farDirectionalLightHelper = new THREE.DirectionalLightHelper( farDirectionalLight, 20 );
      // scene.add( farDirectionalLightHelper );

      // var nearDirectionalLightHelper = new THREE.DirectionalLightHelper( nearDirectionalLight, 20 );
      // scene.add( nearDirectionalLightHelper );

      ///////////////////
      // Custom Shapes //
      ///////////////////

      // Parse mmCIF json
      var atomsList = getAtoms( mmCIF );
      var bondsList = getBonds( mmCIF );
      // Add multiple spheres to the scene using the createSphere function
      _.each( atomsList, function( atomObject ){
        var atom = new Atom( atomObject );
        scene.add( atom );
      });
      // Add bonds between atoms to the scene using the createBonds function
      _.each( bondsList, function( bondObject ){
        var bond = new Bond( bondObject, atomsList );
        scene.add( bond );
      });
    };

    var animate = function(){
      requestAnimationFrame( animate );
      render();
      update();
    };

    var update = function(){
      controls.update();
      stats.update();
    };

    var render = function(){
      renderer.render( scene, camera );
    };

    // Run
    init();
    animate();
  };
});<commit_msg>Altered zoom speed so it's now smoother.<commit_after>define([
   'underscore'
  ,'getAtoms'
  ,'getBonds'
  ,'Atom'
  ,'Bond'
  // Modules below are ignored and not passed to the function.
  ,'three'
  ,'detector'
  ,'stats'
  ,'trackballControls'
  ,'keyboardState'
  ,'fullScreen'
  ,'windowResize'
  ], function( _, getAtoms, getBonds, Atom, Bond ){
  return function( mmCIF ){
    // Detector
    if ( !Detector.webgl ) Detector.addGetWebGLMessage();
    // Globals
    var container, scene, camera, renderer, controls, stats;
    var keyboard = new THREEx.KeyboardState();
    var clock = new THREE.Clock();

    // Functions
    var init = function(){

      ////////////
      // Set-up //
      ////////////

      // Create a scene
      scene = new THREE.Scene();

      // Camera
      var SCREEN_WIDTH = window.innerWidth, SCREEN_HEIGHT = window.innerHeight;
      var VIEW_ANGLE = 35, ASPECT = SCREEN_WIDTH / SCREEN_HEIGHT, NEAR = 1, FAR = 10000;
      camera = new THREE.PerspectiveCamera( VIEW_ANGLE, ASPECT, NEAR, FAR );
      scene.add( camera );
      camera.position.set( 0, 150, 400 );
      camera.lookAt( scene.position );

      // Renderer
      renderer = new THREE.WebGLRenderer({ antialias: true });
      renderer.setSize( SCREEN_WIDTH, SCREEN_HEIGHT );
      // renderer.setClearColorHex( 0xBBBBBB, 1 );
      container = document.createElement( 'div' );
      document.body.appendChild( container );
      container.appendChild( renderer.domElement );

      // Events
      THREEx.WindowResize( renderer, camera );
      THREEx.FullScreen.bindKey({ charCode: 'm'.charCodeAt( 0 ) });

      // Controls
      controls = new THREE.TrackballControls( camera, renderer.domElement );
      // controls.noZoom = true;
      controls.zoomSpeed = 0.05;

      // Stats
      stats = new Stats();
      stats.domElement.style.position = 'absolute';
      stats.domElement.style.bottom = '0px';
      stats.domElement.style.zIndex = 100;
      container.appendChild( stats.domElement );

      // Lights
      var topLight = new THREE.PointLight( 0xf8f8f8 );
      topLight.position.set( 0, 500, 0 );
      scene.add( topLight );

      var bottomLight = new THREE.PointLight( 0xf8f8f8 );
      bottomLight.position.set( 0, -500, 0 );
      scene.add( bottomLight );

      var farLight = new THREE.PointLight( 0xc6c6c6 );
      farLight.position.set( 0, 0, -500 );
      scene.add( farLight );

      var nearLight = new THREE.PointLight( 0xc6c6c6 );
      nearLight.position.set( 0, 0, 500 );
      scene.add( nearLight );

      // add directional light source
      // var farDirectionalLight = new THREE.DirectionalLight( 0xf2f2f2 );
      // farDirectionalLight.position.set( 0, 0, -250 );
      // scene.add( farDirectionalLight );

      // var nearDirectionalLight = new THREE.DirectionalLight( 0xf2f2f2 );
      // nearDirectionalLight.position.set( 0, 0, 250 );
      // scene.add( nearDirectionalLight );

      // HELPERS

      scene.add( new THREE.AxisHelper() );

      var cameraHelper = new THREE.CameraHelper( camera );
      scene.add( cameraHelper );

      var topLightHelper = new THREE.PointLightHelper( topLight );
      scene.add( topLightHelper );

      var bottomLightHelper = new THREE.PointLightHelper( bottomLight );
      scene.add( bottomLightHelper );

      var farLightHelper = new THREE.PointLightHelper( farLight, 100 );
      scene.add( farLightHelper );

      var nearLightHelper = new THREE.PointLightHelper( nearLight, 20 );
      scene.add( nearLightHelper );

      // var farDirectionalLightHelper = new THREE.DirectionalLightHelper( farDirectionalLight, 20 );
      // scene.add( farDirectionalLightHelper );

      // var nearDirectionalLightHelper = new THREE.DirectionalLightHelper( nearDirectionalLight, 20 );
      // scene.add( nearDirectionalLightHelper );

      ///////////////////
      // Custom Shapes //
      ///////////////////

      // Parse mmCIF json
      var atomsList = getAtoms( mmCIF );
      var bondsList = getBonds( mmCIF );
      // Add multiple spheres to the scene using the createSphere function
      _.each( atomsList, function( atomObject ){
        var atom = new Atom( atomObject );
        scene.add( atom );
      });
      // Add bonds between atoms to the scene using the createBonds function
      _.each( bondsList, function( bondObject ){
        var bond = new Bond( bondObject, atomsList );
        scene.add( bond );
      });
    };

    var animate = function(){
      requestAnimationFrame( animate );
      render();
      update();
    };

    var update = function(){
      controls.update();
      stats.update();
    };

    var render = function(){
      renderer.render( scene, camera );
    };

    // Run
    init();
    animate();
  };
});<|endoftext|>