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

    function CartController($scope, $timeout, cart) {
        "use strict";
        var vm = this,
          initialized = false;
        vm.show = false;
        vm.projects = [];
        vm.count = 0;
        vm.collapsed = {};

        $scope.$on('cart.update', function () {
            getCart(false);
        });

        function getCart (collapse) {
            cart.all()
              .then(function (data) {
                var prev = vm.count;
                vm.count = 0;
                  vm.projects = data;
                  _.each(data, function(p) {
                      vm.count += p.samples.length;
                      if(collapse){
                        vm.collapsed[p.id] = true;
                      }
                  });
                if (initialized && prev !== vm.count) {
                  vm.animation = 'glow';
                  $timeout(function () {
                    vm.animation = '';
                  }, 3000);
                } else {
                  // This is just to prevent animation on page load.
                  initialized = true;
                }
              });
        }

        getCart(true);
    }

  /**
   * Controller for functions on the cart slider
   * @param CartService The cart service to communicate with the server
   */
    function CartSliderController(CartService, $modal) {
      "use strict";

      var vm = this;

      vm.clear = function(){
        CartService.clear();
      };

      vm.removeProject = function(projectId){
        CartService.removeProject(projectId);
      }

      vm.removeSample = function(projectId,sampleId){
        CartService.removeSample(projectId,sampleId);
      }

    vm.exportToGalaxy = function () {
      CartService.all()
        .then(function (data) {
          if (data != null) {
            var firstProjID = data[0].id

            $modal.open({
              templateUrl: TL.BASE_URL + 'cart/template/galaxy/project/' + firstProjID,
              controller : 'GalaxyDialogCtrl as gCtrl',
              resolve    : {
                openedByCart: function () {
                  return true;
                },
                multiProject: function () {
                  return (data.length > 1)
                }
              }
            });
          }
        });
    }
    }

    function CartDirective() {
        return {
            restrict    : "E",
            templateUrl : "/cart.html",
            replace: true,
            controllerAs: "cart",
            controller  : ['$scope', '$timeout', 'CartService', CartController]
        }
    }

    function CartService(scope, $http, $q) {
        var svc = this,
            urls = {
                all: TL.BASE_URL + "cart",
                add: TL.BASE_URL + "cart/add/samples",
                project: TL.BASE_URL + "cart/project/"
            };

        svc.all = function () {
            return $http.get(urls.all)
              .then(function (response) {
                  if (response.data) {
                      return response.data.projects
                  }
                  else {
                      return [];
                  }
              });
        };

        svc.add = function (samples) {
          var promises = [];

          _.forEach(samples, function(s) {
            promises.push($http.post(urls.add, {projectId: s.project, sampleIds: [s.sample]}));
          });

          $q.all(promises).then(function(){
            scope.$broadcast("cart.update", {});
          });
        };

      svc.clear = function () {
        //fire a DELETE to the server on the cart then broadcast the cart update event
        return $http.delete(urls.all).then(function () {
          scope.$broadcast("cart.update", {});
        });
      };

      svc.removeProject = function(projectId){
        return $http.delete(urls.project+projectId).then(function () {
          scope.$broadcast("cart.update", {});
        })
      };

      svc.removeSample = function(projectId,sampleId){
        return $http.delete(urls.project+projectId+"/samples/"+sampleId).then(function () {
          scope.$broadcast("cart.update", {});
        })
      }

    }

  function GalaxyExportService(CartService, StorageService) {
    "use strict";
    var svc = this;
    var params = {};
    var samples = [];

    function initialize(libraryName, email, authCode, redirectURI) {
      params = {
        "_embedded": {
          "library": {"name": libraryName},
          "user"   : {"email": email},
          "oauth2" : {
            "code"    : authCode,
            "redirect": redirectURI
          },
          "samples": samples
        }
      };
    };

    function addSampleFile(sampleName, sampleFilePath) {
      var sample = _.find(samples, function (sampleItr) {
        return (sampleItr.name == sampleName)
      });
      if (sample == null) {
        sample = {
          "name"     : sampleName,
          "_links"   : {"self": {"href": ""}}, //expected by the tool
          "_embedded": {"sample_files": []}
        };
        samples.push(sample);
      }
      sample._embedded.sample_files.push({'_links': {'self': {'href': sampleFilePath}}});
    };

    function getSampleFormEntities() {
      var sampleFormEntity = {
        "name" : "json_params",
        "value": JSON.stringify(params)
      };
      return [sampleFormEntity];
    };

    svc.exportFromProjSampPage = function (libraryName, email, authCode, redirectURI) {
      initialize(libraryName, email, authCode, redirectURI);

      var samples = StorageService.getSamples()
      _.each(samples, function (sample) {
        _.each(sample.embedded.sample_files, function (sequenceFile) {
          addSampleFile(sample.sample.label, sequenceFile._links.self.href)
        })
      });
      return getSampleFormEntities();
    };

    svc.exportFromCart = function (libraryName, email, authCode, redirectURI) {
      return CartService.all()
        .then(function (data) {
          initialize(libraryName, email, authCode, redirectURI);
          var projects = data;
          _.each(projects, function (project) {
            var samples = project.samples;
            _.each(samples, function (sample) {
              var sequenceFiles = sample.sequenceFiles
              _.each(sequenceFiles, function (sequenceFile) {
                addSampleFile(sample.label, sequenceFile.selfRef);
              })
            })
          });
          return getSampleFormEntities();
        });
    };
  }

  function GalaxyDialogCtrl($modalInstance, $timeout, $scope, CartService, GalaxyExportService, openedByCart, multiProject) {
    "use strict";
    var vm = this;
    vm.showOauthIframe = false;
    vm.showEmailLibInput = true;
    vm.redirectURI = TL.BASE_URL + "galaxy/auth_code";

    vm.upload = function () {
      vm.makeOauth2AuthRequest(TL.galaxyClientID);
      vm.showEmailLibInput = false;
      vm.showOauthIframe = true;
    };

    vm.makeOauth2AuthRequest = function (clientID) {
      var request = buildOauth2Request(clientID, "code", "read", vm.redirectURI);
      vm.iframeSrc = "/api/oauth/authorize" + request;
    }

    function buildOauth2Request(clientID, responseType, scope, redirectURI) {
      return "?&client_id=" + clientID + "&response_type=" + responseType + "&scope=" + scope + "&redirect_uri=" + redirectURI;
    }

    $scope.$on("galaxyAuthCode", function (e, authToken) {

      if (authToken) {
        vm.uploading = true;

        vm.showOauthIframe = false;
        vm.showEmailLibInput = true;

        if (openedByCart) {
          GalaxyExportService.exportFromCart(vm.name, vm.email, authToken, vm.redirectURI).then(sendSampleForm);
        }
        else {
          sendSampleForm(GalaxyExportService.exportFromProjSampPage(vm.name, vm.email, authToken, vm.redirectURI));
        }
      }
    });

    function sendSampleForm(sampleFormEntities) {
      vm.sampleFormEntities = sampleFormEntities;

      if(openedByCart) {
        CartService.clear();
      }

      //$timeout is necessary because it adds a new event to the browser event queue,
      //allowing the full form to be generated before it is submitted.

      //Two timeouts are required now--this is starting to look like a real hack.
      $timeout(function () {
        $timeout(function () {
          document.getElementById("galSubFrm").submit();
          vm.close();
        });
      });
    }

    vm.setName = function (name, orgName) {
      if (multiProject) {
        vm.name = orgName;
      }
      else {
        vm.name = name;
      }
    };
    vm.setEmail = function (email) {
      vm.email = email;
    };
    vm.close = function () {
      $modalInstance.close();
    };

  }

  angular
      .module('irida.cart', [])
      .service('CartService', ['$rootScope', '$http', '$q', CartService])
    .controller('CartSliderController', ['CartService', '$modal', CartSliderController])
    .controller('GalaxyDialogCtrl', ['$modalInstance', '$timeout', '$scope', 'CartService','GalaxyExportService', 'openedByCart', 'multiProject', GalaxyDialogCtrl])
    .service('GalaxyExportService', ['CartService', 'StorageService', GalaxyExportService])
      .directive('cart', [CartDirective])
    ;
})();<commit_msg>Use base URL when getting authorizaton from IRIDA<commit_after>(function () {
    "use strict";

    function CartController($scope, $timeout, cart) {
        "use strict";
        var vm = this,
          initialized = false;
        vm.show = false;
        vm.projects = [];
        vm.count = 0;
        vm.collapsed = {};

        $scope.$on('cart.update', function () {
            getCart(false);
        });

        function getCart (collapse) {
            cart.all()
              .then(function (data) {
                var prev = vm.count;
                vm.count = 0;
                  vm.projects = data;
                  _.each(data, function(p) {
                      vm.count += p.samples.length;
                      if(collapse){
                        vm.collapsed[p.id] = true;
                      }
                  });
                if (initialized && prev !== vm.count) {
                  vm.animation = 'glow';
                  $timeout(function () {
                    vm.animation = '';
                  }, 3000);
                } else {
                  // This is just to prevent animation on page load.
                  initialized = true;
                }
              });
        }

        getCart(true);
    }

  /**
   * Controller for functions on the cart slider
   * @param CartService The cart service to communicate with the server
   */
    function CartSliderController(CartService, $modal) {
      "use strict";

      var vm = this;

      vm.clear = function(){
        CartService.clear();
      };

      vm.removeProject = function(projectId){
        CartService.removeProject(projectId);
      }

      vm.removeSample = function(projectId,sampleId){
        CartService.removeSample(projectId,sampleId);
      }

    vm.exportToGalaxy = function () {
      CartService.all()
        .then(function (data) {
          if (data != null) {
            var firstProjID = data[0].id

            $modal.open({
              templateUrl: TL.BASE_URL + 'cart/template/galaxy/project/' + firstProjID,
              controller : 'GalaxyDialogCtrl as gCtrl',
              resolve    : {
                openedByCart: function () {
                  return true;
                },
                multiProject: function () {
                  return (data.length > 1)
                }
              }
            });
          }
        });
    }
    }

    function CartDirective() {
        return {
            restrict    : "E",
            templateUrl : "/cart.html",
            replace: true,
            controllerAs: "cart",
            controller  : ['$scope', '$timeout', 'CartService', CartController]
        }
    }

    function CartService(scope, $http, $q) {
        var svc = this,
            urls = {
                all: TL.BASE_URL + "cart",
                add: TL.BASE_URL + "cart/add/samples",
                project: TL.BASE_URL + "cart/project/"
            };

        svc.all = function () {
            return $http.get(urls.all)
              .then(function (response) {
                  if (response.data) {
                      return response.data.projects
                  }
                  else {
                      return [];
                  }
              });
        };

        svc.add = function (samples) {
          var promises = [];

          _.forEach(samples, function(s) {
            promises.push($http.post(urls.add, {projectId: s.project, sampleIds: [s.sample]}));
          });

          $q.all(promises).then(function(){
            scope.$broadcast("cart.update", {});
          });
        };

      svc.clear = function () {
        //fire a DELETE to the server on the cart then broadcast the cart update event
        return $http.delete(urls.all).then(function () {
          scope.$broadcast("cart.update", {});
        });
      };

      svc.removeProject = function(projectId){
        return $http.delete(urls.project+projectId).then(function () {
          scope.$broadcast("cart.update", {});
        })
      };

      svc.removeSample = function(projectId,sampleId){
        return $http.delete(urls.project+projectId+"/samples/"+sampleId).then(function () {
          scope.$broadcast("cart.update", {});
        })
      }

    }

  function GalaxyExportService(CartService, StorageService) {
    "use strict";
    var svc = this;
    var params = {};
    var samples = [];

    function initialize(libraryName, email, authCode, redirectURI) {
      params = {
        "_embedded": {
          "library": {"name": libraryName},
          "user"   : {"email": email},
          "oauth2" : {
            "code"    : authCode,
            "redirect": redirectURI
          },
          "samples": samples
        }
      };
    };

    function addSampleFile(sampleName, sampleFilePath) {
      var sample = _.find(samples, function (sampleItr) {
        return (sampleItr.name == sampleName)
      });
      if (sample == null) {
        sample = {
          "name"     : sampleName,
          "_links"   : {"self": {"href": ""}}, //expected by the tool
          "_embedded": {"sample_files": []}
        };
        samples.push(sample);
      }
      sample._embedded.sample_files.push({'_links': {'self': {'href': sampleFilePath}}});
    };

    function getSampleFormEntities() {
      var sampleFormEntity = {
        "name" : "json_params",
        "value": JSON.stringify(params)
      };
      return [sampleFormEntity];
    };

    svc.exportFromProjSampPage = function (libraryName, email, authCode, redirectURI) {
      initialize(libraryName, email, authCode, redirectURI);

      var samples = StorageService.getSamples()
      _.each(samples, function (sample) {
        _.each(sample.embedded.sample_files, function (sequenceFile) {
          addSampleFile(sample.sample.label, sequenceFile._links.self.href)
        })
      });
      return getSampleFormEntities();
    };

    svc.exportFromCart = function (libraryName, email, authCode, redirectURI) {
      return CartService.all()
        .then(function (data) {
          initialize(libraryName, email, authCode, redirectURI);
          var projects = data;
          _.each(projects, function (project) {
            var samples = project.samples;
            _.each(samples, function (sample) {
              var sequenceFiles = sample.sequenceFiles
              _.each(sequenceFiles, function (sequenceFile) {
                addSampleFile(sample.label, sequenceFile.selfRef);
              })
            })
          });
          return getSampleFormEntities();
        });
    };
  }

  function GalaxyDialogCtrl($modalInstance, $timeout, $scope, CartService, GalaxyExportService, openedByCart, multiProject) {
    "use strict";
    var vm = this;
    vm.showOauthIframe = false;
    vm.showEmailLibInput = true;
    vm.redirectURI = TL.BASE_URL + "galaxy/auth_code";

    vm.upload = function () {
      vm.makeOauth2AuthRequest(TL.galaxyClientID);
      vm.showEmailLibInput = false;
      vm.showOauthIframe = true;
    };

    vm.makeOauth2AuthRequest = function (clientID) {
      var request = buildOauth2Request(clientID, "code", "read", vm.redirectURI);
      vm.iframeSrc = TL.BASE_URL + "api/oauth/authorize" + request;
    }

    function buildOauth2Request(clientID, responseType, scope, redirectURI) {
      return "?&client_id=" + clientID + "&response_type=" + responseType + "&scope=" + scope + "&redirect_uri=" + redirectURI;
    }

    $scope.$on("galaxyAuthCode", function (e, authToken) {

      if (authToken) {
        vm.uploading = true;

        vm.showOauthIframe = false;
        vm.showEmailLibInput = true;

        if (openedByCart) {
          GalaxyExportService.exportFromCart(vm.name, vm.email, authToken, vm.redirectURI).then(sendSampleForm);
        }
        else {
          sendSampleForm(GalaxyExportService.exportFromProjSampPage(vm.name, vm.email, authToken, vm.redirectURI));
        }
      }
    });

    function sendSampleForm(sampleFormEntities) {
      vm.sampleFormEntities = sampleFormEntities;

      if(openedByCart) {
        CartService.clear();
      }

      //$timeout is necessary because it adds a new event to the browser event queue,
      //allowing the full form to be generated before it is submitted.

      //Two timeouts are required now--this is starting to look like a real hack.
      $timeout(function () {
        $timeout(function () {
          document.getElementById("galSubFrm").submit();
          vm.close();
        });
      });
    }

    vm.setName = function (name, orgName) {
      if (multiProject) {
        vm.name = orgName;
      }
      else {
        vm.name = name;
      }
    };
    vm.setEmail = function (email) {
      vm.email = email;
    };
    vm.close = function () {
      $modalInstance.close();
    };

  }

  angular
      .module('irida.cart', [])
      .service('CartService', ['$rootScope', '$http', '$q', CartService])
    .controller('CartSliderController', ['CartService', '$modal', CartSliderController])
    .controller('GalaxyDialogCtrl', ['$modalInstance', '$timeout', '$scope', 'CartService','GalaxyExportService', 'openedByCart', 'multiProject', GalaxyDialogCtrl])
    .service('GalaxyExportService', ['CartService', 'StorageService', GalaxyExportService])
      .directive('cart', [CartDirective])
    ;
})();<|endoftext|>


<commit_before>import { Grid, Row, Col, Jumbotron, Button, ButtonGroup } from 'react-bootstrap';

export default class startScreen extends React.Component {
  render() {
    return (

        <Jumbotron className="introduction">
          <Grid className="introduction__container">

Bli student och lär dig japanska!

                Ta del av Gakuseis inlärningsmaterial och lär dig japanska redan idag!

Det tar bara en sekund att registrera och inga personuppgifter krävs

          </Grid>
        </Jumbotron>
        <Jumbotron className="text-center">

Gakusei erbjuder många funktioner som underlättar ditt lärande

          <Button
            href={`login${this.props.location.search}`}
            bsStyle="success"
            bsSize="large"
          >
            Testa redan nu!
          </Button>
        </Jumbotron>
        <Grid className="about-features">
          <Row className="features_prev">
            <Col
              xs={12}
              md={6}
              lg={4}
              className="text-center"
            >

Ett bra komplement till undervisning

Olika sorters övningar, anpassade efter japanskaundervisning på högskolenivå.

                <Button
                  bsStyle="success"
                  href="http://daigaku.se/gakusei2.html"
                >
                  Läs mer
                </Button>

            </Col>
            <Col
              xs={12}
              md={6}
              lg={4}
              className="text-center"
            >

Gakusei överallt

Öva med Gakusei på mobilen! Fungerar lika på mobila enheter som på laptops.

            </Col>

            <Col
              xs={12}
              md={6}
              lg={4}
              className="text-center"
            >

Anonymitet

Gakusei lagrar ingen personlig data om sina användare, det enda som behövs är ett användarnamn.

            </Col>

            <Col
              xs={12}
              md={6}
              lg={4}
              className="text-center"
            >

                2 quizar

Prova våra quizar och se vad du kan om Japan.

              <Button
                href={`login${this.props.location.search}`}
                bsStyle="success"
              >
                Registrera nu!
              </Button>
            </Col>

            <Col
              xs={12}
              md={6}
              lg={4}
              className="text-center"
            >

            </Col>
            <Col
              xs={12}
              md={6}
              lg={4}
              className="text-center"
            >

Smart inlärningsteknologi

                Vårt system kommer ihåg hur du har svarat på frågor, på så sätt kan vi anpassa inlärningsmaterialet
                efter dig.

                <Button
                  bsStyle="success"
                  href="http://daigaku.se/gakusei2.html"
                >
                  Läs mer
                </Button>

            </Col>
          </Row>
        </Grid>
        <Jumbotron>
          <Grid>
            <Row>
              <Col
                xs={12}
                md={8}
              >

Daigaku Sverige utvecklar Gakusei

                  Daigaku Sverige har som mål att främja undervisning i, och forskning om japanska. Idag måste man i
                  stor utsträckning lära sig japanska via engelska. Vi tror att det skulle vara en fördel om åtminstone
                  en del inlärning kan ske direkt från svenska till japanska. Därför har vi skapat Gakusei, den första
                  webbapplikationen som lär dig japanska via svenska!

                  <Button
                    bsStyle="success"
                    href="http://daigaku.se/"
                  >
                    Läs mer
                  </Button>

              </Col>
              <Col
                xs={6}
                md={4}
                className="text-center"
              >

              </Col>
            </Row>
          </Grid>
        </Jumbotron>
        <Jumbotron className="text-center">

Utöka din kunskap med Gakusei!

          <Button
            href={`login${this.props.location.search}`}
            bsStyle="success"
            bsSize="large"
          >
            Registrera dig nu!
          </Button>
        </Jumbotron>

    );
  }
}
<commit_msg>language stuff<commit_after>import { Grid, Row, Col, Jumbotron, Button, ButtonGroup } from 'react-bootstrap';

export default class startScreen extends React.Component {
  render() {
    return (

        <Jumbotron className="introduction">
          <Grid className="introduction__container">

Bli student och lär dig japanska!

                Ta del av Gakuseis inlärningsmaterial och lär dig japanska redan idag!

Det tar bara en sekund att registrera och inga personuppgifter krävs

          </Grid>
        </Jumbotron>
        <Jumbotron className="text-center">

Gakusei erbjuder många funktioner som underlättar ditt lärande

          <Button
            href={`login${this.props.location.search}`}
            bsStyle="success"
            bsSize="large"
          >
            Testa redan nu!
          </Button>
        </Jumbotron>
        <Grid className="about-features">
          <Row className="features_prev">
            <Col
              xs={12}
              md={6}
              lg={4}
              className="text-center"
            >

Ett bra komplement till undervisning

Olika sorters övningar, anpassade efter japanskaundervisning på högskolenivå.

                <Button
                  bsStyle="success"
                  href="http://daigaku.se/gakusei2.html"
                >
                  Läs mer
                </Button>

            </Col>
            <Col
              xs={12}
              md={6}
              lg={4}
              className="text-center"
            >

Gakusei överallt

Öva med Gakusei på mobilen! Fungerar lika på mobila enheter som på laptops.

            </Col>

            <Col
              xs={12}
              md={6}
              lg={4}
              className="text-center"
            >

Anonymitet

Gakusei lagrar ingen personlig data om sina användare, det enda som behövs är ett användarnamn.

            </Col>

            <Col
              xs={12}
              md={6}
              lg={4}
              className="text-center"
            >

                2 quizar

Prova våra quizar och se vad du kan om Japan.

              <Button
                href={`login${this.props.location.search}`}
                bsStyle="success"
              >
                Registrera dig nu!
              </Button>
            </Col>

            <Col
              xs={12}
              md={6}
              lg={4}
              className="text-center"
            >

            </Col>
            <Col
              xs={12}
              md={6}
              lg={4}
              className="text-center"
            >

Smart inlärningsteknologi

                Vårt system kommer ihåg hur du har svarat på frågor, på så sätt kan vi anpassa inlärningsmaterialet
                efter dig.

                <Button
                  bsStyle="success"
                  href="http://daigaku.se/gakusei2.html"
                >
                  Läs mer
                </Button>

            </Col>
          </Row>
        </Grid>
        <Jumbotron>
          <Grid>
            <Row>
              <Col
                xs={12}
                md={8}
              >

Daigaku Sverige utvecklar Gakusei

                  Daigaku Sverige har som mål att främja undervisning i, och forskning om japanska. Idag måste man i
                  stor utsträckning lära sig japanska via engelska. Vi tror att det skulle vara en fördel om åtminstone
                  en del inlärning kan ske direkt från svenska till japanska. Därför har vi skapat Gakusei, den första
                  webbapplikationen som lär dig japanska via svenska!

                  <Button
                    bsStyle="success"
                    href="http://daigaku.se/"
                  >
                    Läs mer
                  </Button>

              </Col>
              <Col
                xs={6}
                md={4}
                className="text-center"
              >

              </Col>
            </Row>
          </Grid>
        </Jumbotron>
        <Jumbotron className="text-center">

Utöka din kunskap med Gakusei!

          <Button
            href={`login${this.props.location.search}`}
            bsStyle="success"
            bsSize="large"
          >
            Registrera dig nu!
          </Button>
        </Jumbotron>

    );
  }
}
<|endoftext|>


<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/*
 * toolbar for lenya
 */

FCKConfig.ToolbarSets["Lenya"] = [
	['Source','DocProps','-','Lenya_save','Preview','-','Templates'],
	['Cut','Copy','Paste','PasteText','PasteWord','-','Print'],
	['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'],
	['Bold','Italic','Underline','StrikeThrough','-','Subscript','Superscript'],
	['OrderedList','UnorderedList','-','Outdent','Indent'],
	['JustifyLeft','JustifyCenter','JustifyRight','JustifyFull'],
	['Link', 'Lenya_insertLink','Unlink','Anchor'],
	['Image', 'Lenya_insertImage','Table','Rule','Smiley','SpecialChar','PageBreak'],
	['Form','Checkbox','Radio','TextField','Textarea','Select','Button','ImageButton','HiddenField'],
	'/',
	['Style','FontFormat','FontName','FontSize'],
	['TextColor','BGColor'],
	['About']
  ];

 /*
 * plugin for save in lenya
 */
FCKConfig.Plugins.Add( 'fck_lenya_glue', 'de,en', '../../plugins/' ) ;

/*
 * disable uploads since it needs to be done from within Lenya
 */
FCKConfig.ImageUpload = false;
FCKConfig.LinkUpload  = false;
FCKConfig.FlashUpload = false;
<commit_msg>Disable browsing button in built in image and link windows since we now use plugins.<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/*
 * toolbar for lenya
 */

FCKConfig.ToolbarSets["Lenya"] = [
	['Source','DocProps','-','Lenya_save','Preview','-','Templates'],
	['Cut','Copy','Paste','PasteText','PasteWord','-','Print'],
	['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'],
	['Bold','Italic','Underline','StrikeThrough','-','Subscript','Superscript'],
	['OrderedList','UnorderedList','-','Outdent','Indent'],
	['JustifyLeft','JustifyCenter','JustifyRight','JustifyFull'],
	['Link', 'Lenya_insertLink','Unlink','Anchor'],
	['Image', 'Lenya_insertImage','Table','Rule','Smiley','SpecialChar','PageBreak'],
	['Form','Checkbox','Radio','TextField','Textarea','Select','Button','ImageButton','HiddenField'],
	'/',
	['Style','FontFormat','FontName','FontSize'],
	['TextColor','BGColor'],
	['About']
  ];

 /*
 * plugin for save in lenya
 */
FCKConfig.Plugins.Add( 'fck_lenya_glue', 'de,en', '../../plugins/' ) ;

/*
 * disable uploads since it needs to be done from within Lenya
 */
FCKConfig.ImageUpload = false;
FCKConfig.LinkUpload  = false;
FCKConfig.FlashUpload = false;

/*
 * disable server browsing since we now use plugins for that
 */
FCKConfig.ImageBrowser = false;
FCKConfig.LinkBrowser = false;

<|endoftext|>


<commit_before>import React, { Component } from 'react';
import {
  Col,
  Progress,
  Card,
  CardBlock,
  Form,
  FormGroup,
  InputGroup,
  Label,
  Input,
  Button,
  InputGroupAddon
} from 'reactstrap';
import { connect } from 'react-redux';
import { fetchQuestions } from '../../actions';
import RichTextEditor from 'react-rte';
import PropTypes from 'prop-types';
import brace from 'brace';
import AceEditor from 'react-ace';

import 'brace/mode/c_cpp';
import 'brace/snippets/c_cpp';
import 'brace/ext/language_tools';
import 'brace/theme/tomorrow';

class Question extends Component {
  static propTypes = {
    onChange: PropTypes.func
  };

  constructor(state) {
    super(state)

    this.state = {
      value: RichTextEditor.createValueFromString(this.props.question.instructions, 'html')
    }
  }

  onChange = (value) => {
    this.setState({value});
  };

  render() {
    return (
      <Card key={this.props.question._id}>
        <CardBlock>
          <Form>
            <FormGroup>
              Title
              <Input type="text" defaultValue={this.props.question.title}/>
            </FormGroup>
            <FormGroup>
              Instructions
              <RichTextEditor onChange={this.onChange} value={this.state.value} />
            </FormGroup>
            <FormGroup>
              Tags
              <Input type="text" defaultValue={this.props.question.tags}/>
            </FormGroup>
            <FormGroup>
              Class Name
              <InputGroup>
                <Input type="text" defaultValue={this.props.question.className}/>
                <InputGroupAddon>.c</InputGroupAddon>
              </InputGroup>
            </FormGroup>
            <FormGroup check>

                <Input type="checkbox"/>
                Read Only

            </FormGroup>
            <FormGroup>
              Code
              <AceEditor
                mode="c_cpp"
                theme="tomorrow"
                name={this.props.question._id}
                editorProps={{$blockScrolling: true}}
                enableBasicAutocompletion={true}
                enableLiveAutocompletion={true}
                enableSnippets={true}
                value={this.props.question.code}
              />
            </FormGroup>
            <FormGroup>
              Expected Output
              <Input type="text" defaultValue={this.props.question.expectedOutput}/>
            </FormGroup>
            <Button color="primary">Save Question</Button>
          </Form>
        </CardBlock>
      </Card>
    )
  }
}

/*
hints: [String],
codeEvaluator: String,
topic: { type: mongoo
*/

export default Question;
<commit_msg>Make code editor full width<commit_after>import React, { Component } from 'react';
import {
  Col,
  Progress,
  Card,
  CardBlock,
  Form,
  FormGroup,
  InputGroup,
  Label,
  Input,
  Button,
  InputGroupAddon
} from 'reactstrap';
import { connect } from 'react-redux';
import { fetchQuestions } from '../../actions';
import RichTextEditor from 'react-rte';
import PropTypes from 'prop-types';
import brace from 'brace';
import AceEditor from 'react-ace';

import 'brace/mode/c_cpp';
import 'brace/snippets/c_cpp';
import 'brace/ext/language_tools';
import 'brace/theme/tomorrow';

class Question extends Component {
  static propTypes = {
    onChange: PropTypes.func
  };

  constructor(state) {
    super(state)

    this.state = {
      value: RichTextEditor.createValueFromString(this.props.question.instructions, 'html')
    }
  }

  onChange = (value) => {
    this.setState({value});
  };

  render() {
    return (
      <Card key={this.props.question._id}>
        <CardBlock>
          <Form>
            <FormGroup>
              Title
              <Input type="text" defaultValue={this.props.question.title}/>
            </FormGroup>
            <FormGroup>
              Instructions
              <RichTextEditor onChange={this.onChange} value={this.state.value} />
            </FormGroup>
            <FormGroup>
              Tags
              <Input type="text" defaultValue={this.props.question.tags}/>
            </FormGroup>
            <FormGroup>
              Class Name
              <InputGroup>
                <Input type="text" defaultValue={this.props.question.className}/>
                <InputGroupAddon>.c</InputGroupAddon>
              </InputGroup>
            </FormGroup>
            <FormGroup check>

                <Input type="checkbox"/>
                Read Only

            </FormGroup>
            <FormGroup>
              Code
              <AceEditor
                mode="c_cpp"
                theme="tomorrow"
                name={this.props.question._id}
                editorProps={{$blockScrolling: true}}
                enableBasicAutocompletion={true}
                enableLiveAutocompletion={true}
                enableSnippets={true}
                value={this.props.question.code}
                width="100%"
              />
            </FormGroup>
            <FormGroup>
              Expected Output
              <Input type="text" defaultValue={this.props.question.expectedOutput}/>
            </FormGroup>
            <Button color="primary">Save Question</Button>
          </Form>
        </CardBlock>
      </Card>
    )
  }
}

/*
hints: [String],
codeEvaluator: String,
topic: { type: mongoo
*/

export default Question;
<|endoftext|>


<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/*
 * toolbar for lenya
 */

FCKConfig.ToolbarSets["Lenya"] = [
	['Source','DocProps','-','Lenya_save','Preview','-','Templates'],
	['Cut','Copy','Paste','PasteText','PasteWord','-','Print'],
	['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'],
	['Bold','Italic','Underline','StrikeThrough','-','Subscript','Superscript'],
	['OrderedList','UnorderedList','-','Outdent','Indent'],
	['JustifyLeft','JustifyCenter','JustifyRight','JustifyFull'],
	['Link', 'Lenya_insertLink','Unlink','Anchor'],
	['Image', 'Lenya_insertImage','Table','Rule','Smiley','SpecialChar','PageBreak'],
	['Form','Checkbox','Radio','TextField','Textarea','Select','Button','ImageButton','HiddenField'],
	'/',
	['Style','FontFormat','FontName','FontSize'],
	['TextColor','BGColor'],
	['About']
  ];

 /*
 * plugin for save in lenya
 */
FCKConfig.Plugins.Add( 'fck_lenya_glue', 'de,en', '../../plugins/' ) ;

/*
 * disable uploads since it needs to be done from withing Lenya
 */
FCKConfig.ImageUpload = false;
FCKConfig.LinkUpload  = false;
FCKConfig.FlashUpload = false;
<commit_msg>fixed typo in comment<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements.  See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License.  You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/*
 * toolbar for lenya
 */

FCKConfig.ToolbarSets["Lenya"] = [
	['Source','DocProps','-','Lenya_save','Preview','-','Templates'],
	['Cut','Copy','Paste','PasteText','PasteWord','-','Print'],
	['Undo','Redo','-','Find','Replace','-','SelectAll','RemoveFormat'],
	['Bold','Italic','Underline','StrikeThrough','-','Subscript','Superscript'],
	['OrderedList','UnorderedList','-','Outdent','Indent'],
	['JustifyLeft','JustifyCenter','JustifyRight','JustifyFull'],
	['Link', 'Lenya_insertLink','Unlink','Anchor'],
	['Image', 'Lenya_insertImage','Table','Rule','Smiley','SpecialChar','PageBreak'],
	['Form','Checkbox','Radio','TextField','Textarea','Select','Button','ImageButton','HiddenField'],
	'/',
	['Style','FontFormat','FontName','FontSize'],
	['TextColor','BGColor'],
	['About']
  ];

 /*
 * plugin for save in lenya
 */
FCKConfig.Plugins.Add( 'fck_lenya_glue', 'de,en', '../../plugins/' ) ;

/*
 * disable uploads since it needs to be done from within Lenya
 */
FCKConfig.ImageUpload = false;
FCKConfig.LinkUpload  = false;
FCKConfig.FlashUpload = false;
<|endoftext|>


<commit_before>/*
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * TERMS OF REPRODUCTION USE
 *
 * 1. Provide a link back to the original repository (this repository), as
 * 		in, https://github.com/ConnerGDavis/Plugbot, that is well-visible
 * 		wherever the source is being reproduced.  For example, should you
 * 		display it on a website, you should provide a link above/below that
 *		which the users use, titled something such as "ORIGINAL AUTHOR".
 *
 * 2. Retain these three comments:  the GNU GPL license statement, this comment,
 * 		and that below it, that details the author and purpose.
 *
 * Thanks for playing fair!  You'll fare better than WOLVES, that's for sure.
 */

/**
 * NOTE:  This is all procedural as hell because prototypes and any
 * 			OOP techniques in Javascript are stupid and confusing.
 *
 * @author Conner Davis ([VIP] ♫Łŏġïç®) & Harrison Schneidman ([VIDJ] EXƎ)
 * @version 0.2.0a
 */

// Triggers
var autowoot = true;
var autoqueue = true;
var hideVideo = false;
var userList = true;
var points = 0;
var highScore = 0;

// API listeners
function initAPIListeners()
{
	API.addEventListener(API.DJ_ADVANCE, djAdvanced);
	API.addEventListener(API.VOTE_UPDATE, function(obj) {
		populateUserlist();
	});
	API.addEventListener(API.USER_JOIN, function(user) {
		populateUserlist();
	});
	API.addEventListener(API.USER_LEAVE, function(user) {
		populateUserlist();
	})
}

// Display UI
function displayUI()
{
	$('#plugbot-ui').remove();
	$('#playback').css('z-index', '8'); // hack to make the buttons usable

	$('#playback').append('

');
		$("#plugbot-ui").animate({"height": "64px"}, {duration: "slow" });
		$('#plugbot-ui').append(
			'' +
			'' +
			'' +
			''
		);

	$('body').append('

');
}

// Some on-click listeners for the UI buttons
function initUIListeners()
{
	$("#plugbot-btn-userlist").on("click", function() {
		userList = !userList;
		$(this).attr("src", userList ? 'http://i.imgur.com/IGcMP.png' : 'http://i.imgur.com/pAFJS.png');
		$("#plugbot-userlist").css("visibility", userList ? ("visible") : ("hidden"));

		console.log('Userlist is now ' + (userList ? 'enabled' : 'disabled'));
	});
	$("#plugbot-btn-woot").on("click", function() {
		autowoot = !autowoot;
		$(this).attr("src", autowoot ? 'http://i.imgur.com/fWb8n.png' : 'http://i.imgur.com/uyUtA.png');
		if (autowoot)
			$("#button-vote-positive").click();

		console.log('Auto-woot is now ' + (autowoot ? 'enabled' : 'disabled'));
	});

	$("#plugbot-btn-hidevideo").on("click", function() {
		hideVideo = !hideVideo;
		$(this).attr("src", hideVideo ? 'http://i.imgur.com/lwpfH.png' : 'http://i.imgur.com/jbJDe.png');
		if (hideVideo)
			$("#yt-frame").animate({"height": "0px"}, {duration: "fast"});
		else
			$("#yt-frame").animate({"height": "271px"}, {duration: "fast"});
	});

	$("#plugbot-btn-queue").on("click", function() {
		autoqueue = !autoqueue;
		$(this).attr("src", autoqueue ? 'http://i.imgur.com/IxK27.png' : 'http://i.imgur.com/W5ncS.png');
		if (autoqueue)
			$("#button-dj-waitlist-join").click();
		else
			$("#button-dj-waitlist-leave").click();

		console.log('Auto-queue is now ' + (autoqueue ? 'enabled' : 'disabled'));
	});

}
function newSong()
{
	points = 0;
	highScore = 0;
	populateUserlist();
}
function djAdvanced(obj)
{
	if (autowoot)
		$("#button-vote-positive").click();

	if ($("#button-dj-waitlist-join").css("display") === "block" && autoqueue)
		$("#button-dj-waitlist-join").click();

	$("#yt-frame").css("height", "271px");
	$("#plugbot-btn-hidevideo").attr("src", ROOT_DIR + 'hidevideo.png');
	if (hideVideo)
		{
		hideVideo = !hideVideo;
		$("#plugbot-btn-queue").attr("src", hideVideo ? 'http://i.imgur.com/lwpfH.png' : 'http://i.imgur.com/jbJDe.png');
	}
	newSong();
}

function populateUserlist()
{
	points = 0;
	var userNames = new Array()
	for (var i = 0; i < API.getUsers().length; i++)
	{
		userNames[i] = API.getUsers()[i];
	}
	//userNames.sort();
	$('#plugbot-userlist').empty();
	for (var i = 0; i < userNames.length; i++)
	{
		var user = userNames[i];
		refreshList(user.username, user.vote)
	}
	if(points > highScore)
	{
		highScore = points;
	}
	//$('#plugbot-userlist').append('
High Score: ' + highScore + '
');
	$('body').append('

');
}

function refreshList(username, vote)
{
	console.log(vote);

	var colour;
	switch (vote)
	{
		case 1:
			colour = "3FFF00";
			points++;
			break;
		case 0:
			colour = "FFFFFF";
			break;
		case -1:
			colour = "ED1C24";
			break;
	}
	$('#plugbot-userlist').append('
' + username + '
');
}

function isSebastian() { return API.getSelf().username == "Sebastian[BOT]"; }
function isBoris() { return API.getSelf().username == "BorisYeltsin[BOT]"; }

// On init

$('head').prepend('<link href="http://wlsandd.net78.net/plugbot/plugbot.css" rel="stylesheet" type="text/css" />');

$("#button-vote-positive").click();
$("#button-dj-waitlist-join").click();

$("#plugbot-userlist").empty();
initAPIListeners();
populateUserlist();
displayUI();
initUIListeners();<commit_msg>Boris is back :D<commit_after>/*
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/*
 * TERMS OF REPRODUCTION USE
 *
 * 1. Provide a link back to the original repository (this repository), as
 * 		in, https://github.com/ConnerGDavis/Plugbot, that is well-visible
 * 		wherever the source is being reproduced.  For example, should you
 * 		display it on a website, you should provide a link above/below that
 *		which the users use, titled something such as "ORIGINAL AUTHOR".
 *
 * 2. Retain these three comments:  the GNU GPL license statement, this comment,
 * 		and that below it, that details the author and purpose.
 *
 * Thanks for playing fair!  You'll fare better than WOLVES, that's for sure.
 */

/**
 * NOTE:  This is all procedural as hell because prototypes and any
 * 			OOP techniques in Javascript are stupid and confusing.
 *
 * @author Conner Davis ([VIP] ♫Łŏġïç®) & Harrison Schneidman ([VIDJ] EXƎ)
 * @version 0.2.0a
 */

// Triggers
var autowoot = true;
var autoqueue = true;
var hideVideo = false;
var userList = true;

// DJ Battles
var points = 0;
var highScore = 0;

// API listeners
function initAPIListeners()
{
	API.addEventListener(API.DJ_ADVANCE, djAdvanced);
	API.addEventListener(API.VOTE_UPDATE, function(obj) {
		populateUserlist();
	});
	API.addEventListener(API.USER_JOIN, function(user) {
		populateUserlist();
		if (isBoris())
			API.sendChat("Welcome to " + $("#current-room-value").text() + ", " + user.username + "!");
	});
	API.addEventListener(API.USER_LEAVE, function(user) {
		populateUserlist();
	})
}

// Display UI
function displayUI()
{
	$('#plugbot-ui').remove();
	$('#playback').css('z-index', '8'); // hack to make the buttons usable

	$('#playback').append('

');
		$("#plugbot-ui").animate({"height": "64px"}, {duration: "slow" });
		$('#plugbot-ui').append(
			'' +
			'' +
			'' +
			''
		);

	$('body').append('

');
}

// Some on-click listeners for the UI buttons
function initUIListeners()
{
	$("#plugbot-btn-userlist").on("click", function() {
		userList = !userList;
		$(this).attr("src", userList ? 'http://i.imgur.com/IGcMP.png' : 'http://i.imgur.com/pAFJS.png');
		$("#plugbot-userlist").css("visibility", userList ? ("visible") : ("hidden"));
		console.log('Userlist is now ' + (userList ? 'enabled' : 'disabled'));
	});
	$("#plugbot-btn-woot").on("click", function() {
		autowoot = !autowoot;
		$(this).attr("src", autowoot ? 'http://i.imgur.com/fWb8n.png' : 'http://i.imgur.com/uyUtA.png');
		if (autowoot)
			$("#button-vote-positive").click();
		console.log('Auto-woot is now ' + (autowoot ? 'enabled' : 'disabled'));
	});

	$("#plugbot-btn-hidevideo").on("click", function() {
		hideVideo = !hideVideo;
		$(this).attr("src", hideVideo ? 'http://i.imgur.com/lwpfH.png' : 'http://i.imgur.com/jbJDe.png');
		$("#yt-frame").animate({"height": (hideVideo ? "0px" : "271px")}, {duration: "fast"});
	});

	$("#plugbot-btn-queue").on("click", function() {
		autoqueue = !autoqueue;
		$(this).attr("src", autoqueue ? 'http://i.imgur.com/IxK27.png' : 'http://i.imgur.com/W5ncS.png');
		$("#button-dj-waitlist-" (autoqueue ? "join" : "leave")).click();
		console.log('Auto-queue is now ' + (autoqueue ? 'enabled' : 'disabled'));
	});

}

function djAdvanced(obj)
{
	if (autowoot)
		$("#button-vote-positive").click();

	if ($("#button-dj-waitlist-join").css("display") === "block" && autoqueue)
		$("#button-dj-waitlist-join").click();

	$("#yt-frame").css("height", "271px");
	$('#plugbot-btn-hidevideo').attr('src', 'http://i.imgur.com/jbJDe.png');
	hideVideo = false;

	points = 0;
	highScore = 0;
	populateUserlist();
}

function populateUserlist()
{
	points = 0;
	var userNames = new Array()
	for (var i = 0; i < API.getUsers().length; i++)
	{
		userNames[i] = API.getUsers()[i];
	}
	//userNames.sort();
	$('#plugbot-userlist').empty();
	for (var i = 0; i < userNames.length; i++)
	{
		var user = userNames[i];
		refreshList(user.username, user.vote)
	}
	if(points > highScore)
	{
		highScore = points;
	}
	//$('#plugbot-userlist').append('
High Score: ' + highScore + '
');
	$('body').append('

');
}

function refreshList(username, vote)
{
	var colour;
	switch (vote)
	{
		case 1:
			colour = "3FFF00";
			points++;
			break;
		case 0:
			colour = "FFFFFF";
			break;
		case -1:
			colour = "ED1C24";
			break;
	}
	$('#plugbot-userlist').append('
' + username + '
');
}

function isSebastian() { return API.getSelf().username == "Sebastian[BOT]"; }
function isBoris() { return API.getSelf().username == "BorisYeltsin[BOT]"; }

// On init

$('head').prepend('<link href="http://wlsandd.net78.net/plugbot/plugbot.css" rel="stylesheet" type="text/css" />');

$("#button-vote-positive").click();
$("#button-dj-waitlist-join").click();

$("#plugbot-userlist").empty();
initAPIListeners();
populateUserlist();
displayUI();
initUIListeners();

if (isBoris())
{
	window.setInterval(function() {
		API.sendChat("Please remember to view our rules at http://tinyurl.com/892sf9j");
	}, (1000 * 60 * 30));
}
<|endoftext|>


<commit_before>import React, { Component } from 'react';
import questionSet from '../../data/questionSet';
import axios from 'axios';
import { Button } from 'semantic-ui-react';
import { Redirect } from 'react-router-dom';

const find = (id) => questionSet.find(p => p.id === id);

class Questions extends Component {
  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleInputChange = this.handleInputChange.bind(this);
    this.state = {
      answer: '',
      submitResponse: false,
      questionsLeft: 0, // TODO need some way to stop at the last question and go to the final page
    };
  }

  //submit question and answer to reviews route
  handleSubmit(e) {
    e.preventDefault;
    let answer = this.state.answer;
    console.log(this.refs.input);
    let question = find(Number(this.props.match.params.id) - 1).questionText;
    let review_id; // TODO where is the review_id? how can we access it here? componentDidMount?
    console.log("answer", answer); // TODO this is coming back undefined no matter how I try to get it
    console.log("question", question);

    // on question submits save review_id and question and answer to responses table
    axios.patch(`/api/add-response/${review_id}`, {
      // review_id: review_id,
      question: question,
      response: answer,
    })
    .then((res) => {
      console.log('response posted', res)
      // TODO go to the next question
      this.setState({ submitResponse: true});
      // TODO what happens when this gets to the end of the questions? --- it should change what the next page is.
      // BUT HOW? - switch statement? ie case "next" case "submit" etc
    })
    .catch((err) => {
      console.log('response error', err);
    })

  }

  handleInputChange(e) {
    this.setState({ answer: e.target.value })
  }

  render() {
    console.log("props", this.props);
    const { match } = this.props
    const question = find(Number(match.params.id) - 1)
    const nextQuestion = question.id+1;
    console.log("next question id", nextQuestion, question);
    // TODO why isn't the mission_id available?
    const casefile = match.params.casefile_id;
    const article = match.params.article_id;
    const submitResponse = this.state.submitResponse;
    console.log("submitResponse", submitResponse);

    return (

        <form onSubmit={(e) => this.handleSubmit(e)}>

{question.questionText}

          <input type="text" className="question--short"
            defaultValue={this.state.answer}
            onChange={this.handleInputChange}
          />
          <button className="button Questions__submit-button">
            Save and Continue
          </button>
        </form>
        {submitResponse && (
          <Redirect to={`/mission/1/casefile/${casefile}/article/${article}/question/${nextQuestion}`}/>
        )}

    );
  }
}

// <Route exact path="/mission/:id/casefile/:casefile_id/article/:article_id/question/:id" component={Questions} />

export default Questions;
<commit_msg>pass reviewid to server from state<commit_after>import React, { Component } from 'react';
import questionSet from '../../data/questionSet';
import axios from 'axios';
import { Button } from 'semantic-ui-react';
import { Redirect } from 'react-router-dom';

const find = (id) => questionSet.find(p => p.id === id);

class Questions extends Component {
  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this);
    this.handleInputChange = this.handleInputChange.bind(this);
    this.state = {
      answer: '',
      submitResponse: false,
      questionsLeft: 0, // TODO need some way to stop at the last question and go to the final page
    };
  }

  //submit question and answer to reviews route
  handleSubmit(e) {
    e.preventDefault;

    const answer = this.state.answer;
    const question = find(Number(this.props.match.params.id) - 1).questionText;
    const { reviewId } = this.props;

    // on question submits save review_id and question and answer to responses table
    axios.patch(`/api/add-response/${reviewId}`, {
      review_id: reviewId,
      question: question,
      response: answer,
    })
    .then((res) => {
      console.log('response posted', res)
      // TODO go to the next question
      this.setState({ submitResponse: true});
      // TODO what happens when this gets to the end of the questions? --- it should change what the next page is.
      // BUT HOW? - switch statement? ie case "next" case "submit" etc
    })
    .catch((err) => {
      console.log('response error', err);
    })
  }

  handleInputChange(e) {
    this.setState({ answer: e.target.value })
  }

  render() {
    console.log("props", this.props);
    const { match } = this.props
    const question = find(Number(match.params.id) - 1)
    const nextQuestion = question.id+1;
    console.log("next question id", nextQuestion, question);
    // TODO why isn't the mission_id available?
    const casefile = match.params.casefile_id;
    const article = match.params.article_id;
    const submitResponse = this.state.submitResponse;
    console.log("submitResponse", submitResponse);

    return (

        <form onSubmit={(e) => this.handleSubmit(e)}>

{question.questionText}

          <input type="text" className="question--short"
            defaultValue={this.state.answer}
            onChange={this.handleInputChange}
          />
          <button className="button Questions__submit-button">
            Save and Continue
          </button>
        </form>
        {submitResponse && (
          <Redirect to={`/mission/1/casefile/${casefile}/article/${article}/question/${nextQuestion}`}/>
        )}

    );
  }
}

// <Route exact path="/mission/:id/casefile/:casefile_id/article/:article_id/question/:id" component={Questions} />

export default Questions;
<|endoftext|>


<commit_before>#!/usr/bin/env seed

Seed.import_namespace("Clutter", "0.8");
Seed.import_namespace("GLib");

const RIPPLE_S = 2000;
const RIPPLE_W = 8;
const RIPPLE_G = 2;
const RIPPLE_N = 3;
const RIPPLE_MIND = 450;
const RIPPLE_MAXD = 2000;
const RIPPLE_WX = Clutter.cogl_double_to_fixed(RIPPLE_W);

const SCREEN_W = 640;
const SCREEN_H = 480;

function deg_to_rad(x)
{
	return (((x) * 1024.0) / 360.0);
}

function alpha_func(alpha)
{
	var timeline = alpha.get_timeline();
	var frame = timeline.get_current_frame();
	var n_frames = timeline.num_frames;
	var fps = timeline.fps;
	var duration = n_frames/fps;
	var time = frame/fps;

	if ((time/=duration) < (1/2.75))
		return Clutter.ALPHA_MAX_ALPHA*(7.5625*time*time);
	else if (time < (2/2.75))
		return Clutter.ALPHA_MAX_ALPHA*(7.5625 *
										(time-=(1.5/2.75))*time+0.75);
	else if (time < (2.5/2.75))
		return Clutter.ALPHA_MAX_ALPHA*(7.5625 *
										(time-=(2.25/2.75))*time+0.9375);
	else
		return Clutter.ALPHA_MAX_ALPHA*(7.5625 *
										(time-=(2.625/2.75))*time+0.984375);
}

Clutter.init(null, null);

var template = new Clutter.EffectTemplate.for_duration(RIPPLE_S, alpha_func);

function destroy_actor(actor)
{
	actor.destroy();
}

function circle_paint (actor)
{
	var radius = Clutter.cogl_double_to_fixed(actor.width/2);

	actor.fill_color.alpha = actor.opacity;

	Clutter.cogl_color(actor.fill_color);
	Clutter.cogl_path_move_to(radius, radius);
	Clutter.cogl_path_arc(radius, radius, radius, radius,
						  deg_to_rad(0),
						  deg_to_rad(360));
	Clutter.cogl_path_line_to(radius - RIPPLE_WX/2, radius);
	Clutter.cogl_path_arc(radius, radius,
						  radius-RIPPLE_WX/2, radius-RIPPLE_WX/2,
						  deg_to_rad(0),
						  deg_to_rad(360));
	Clutter.cogl_path_close();
	Clutter.cogl_path_fill();
}

function ripple(stage, x, y)
{
	var transp = new Clutter.Color();

	var n = parseInt(Math.random()*RIPPLE_N , 10) + 1;

	for (i = 0; i < n; i++)
	{
		var actor = new Clutter.Rectangle({color: transp});

		actor.fill_color = new Clutter.Color({red: 0xff,
											  green: 0xff,
											  blue: 0xff});

		var size = ((RIPPLE_W * 2) * (i+1)) + (RIPPLE_G * i);

		actor.width = actor.height = size;
		actor.set_anchor_point_from_gravity(Clutter.Gravity.CENTER);
		actor.x = x;
		actor.y = y;
		actor.opacity = 0x80;

		stage.add_actor(actor);

		actor.signal["paint"].connect(circle_paint);
		Clutter.effect_scale(template,actor,
							 SCREEN_W / RIPPLE_W,
							 SCREEN_W / RIPPLE_W);
		Clutter.effect_fade(template, actor,
							0x00,
							destroy_actor);
	}
}

var stage = new Clutter.Stage();

stage.width = SCREEN_W;
stage.height = SCREEN_H;
stage.color = {};

stage.signal["button_press_event"].connect(
	function(stage, event)
	{
		ripple(stage, event.button.x, event.button.y);

		return true;
	});

stage.show();

function random_ripple()
{
	ripple(stage, Math.random()*SCREEN_W, Math.random()*SCREEN_H);
	GLib.timeout_add(Math.random()*RIPPLE_MAXD + RIPPLE_MIND, random_ripple);

	return false;
}

random_ripple();
Clutter.main();

<commit_msg>Small fix.<commit_after>#!/usr/bin/env seed

Seed.import_namespace("Clutter", "0.8");
Seed.import_namespace("GLib");

const RIPPLE_S = 2000;
const RIPPLE_W = 8;
const RIPPLE_G = 2;
const RIPPLE_N = 3;
const RIPPLE_MIND = 450;
const RIPPLE_MAXD = 2000;
const RIPPLE_WX = Clutter.double_to_fixed(RIPPLE_W);

const SCREEN_W = 640;
const SCREEN_H = 480;

function deg_to_rad(x)
{
	return (((x) * 1024.0) / 360.0);
}

function alpha_func(alpha)
{
	var timeline = alpha.get_timeline();
	var frame = timeline.get_current_frame();
	var n_frames = timeline.num_frames;
	var fps = timeline.fps;
	var duration = n_frames/fps;
	var time = frame/fps;

	if ((time/=duration) < (1/2.75))
		return Clutter.ALPHA_MAX_ALPHA*(7.5625*time*time);
	else if (time < (2/2.75))
		return Clutter.ALPHA_MAX_ALPHA*(7.5625 *
										(time-=(1.5/2.75))*time+0.75);
	else if (time < (2.5/2.75))
		return Clutter.ALPHA_MAX_ALPHA*(7.5625 *
										(time-=(2.25/2.75))*time+0.9375);
	else
		return Clutter.ALPHA_MAX_ALPHA*(7.5625 *
										(time-=(2.625/2.75))*time+0.984375);
}

Clutter.init(null, null);

var template = new Clutter.EffectTemplate.for_duration(RIPPLE_S, alpha_func);

function destroy_actor(actor)
{
	actor.destroy();
}

function circle_paint (actor)
{
	var radius = Clutter.cogl_double_to_fixed(actor.width/2);

	actor.fill_color.alpha = actor.opacity;

	Clutter.cogl_color(actor.fill_color);
	Clutter.cogl_path_move_to(radius, radius);
	Clutter.cogl_path_arc(radius, radius, radius, radius,
						  deg_to_rad(0),
						  deg_to_rad(360));
	Clutter.cogl_path_line_to(radius - RIPPLE_WX/2, radius);
	Clutter.cogl_path_arc(radius, radius,
						  radius-RIPPLE_WX/2, radius-RIPPLE_WX/2,
						  deg_to_rad(0),
						  deg_to_rad(360));
	Clutter.cogl_path_close();
	Clutter.cogl_path_fill();
}

function ripple(stage, x, y)
{
	var transp = new Clutter.Color();

	var n = parseInt(Math.random()*RIPPLE_N , 10) + 1;

	for (i = 0; i < n; i++)
	{
		var actor = new Clutter.Rectangle({color: transp});

		actor.fill_color = new Clutter.Color({red: 0xff,
											  green: 0xff,
											  blue: 0xff});

		var size = ((RIPPLE_W * 2) * (i+1)) + (RIPPLE_G * i);

		actor.width = actor.height = size;
		actor.set_anchor_point_from_gravity(Clutter.Gravity.CENTER);
		actor.x = x;
		actor.y = y;
		actor.opacity = 0x80;

		stage.add_actor(actor);

		actor.signal["paint"].connect(circle_paint);
		Clutter.effect_scale(template,actor,
							 SCREEN_W / RIPPLE_W,
							 SCREEN_W / RIPPLE_W);
		Clutter.effect_fade(template, actor,
							0x00,
							destroy_actor);
	}
}

var stage = new Clutter.Stage();

stage.width = SCREEN_W;
stage.height = SCREEN_H;
stage.color = {};

stage.signal["button_press_event"].connect(
	function(stage, event)
	{
		ripple(stage, event.button.x, event.button.y);

		return true;
	});

stage.show();

function random_ripple()
{
	ripple(stage, Math.random()*SCREEN_W, Math.random()*SCREEN_H);
	GLib.timeout_add(Math.random()*RIPPLE_MAXD + RIPPLE_MIND, random_ripple);

	return false;
}

random_ripple();
Clutter.main();

<|endoftext|>


<commit_before>import Vue from 'vue'
import Vuex from '../../src'

Vue.use(Vuex)

const INCREMENT = 'INCREMENT'
const DECREMENT = 'DECREMENT'

const state = {
  count: 0
}

const actions = {
  increment: INCREMENT,
  decrement: DECREMENT,
  incrementIfOdd: () => (dispatch, state) => {
    if (state.count % 2 === 1) {
      dispatch(INCREMENT)
    }
  },
  incrementAsync: () => (dispatch, state) => {
    setTimeout(() => {
      dispatch(INCREMENT)
    }, 1000)
  }
}

const mutations = {
  [INCREMENT] (state) {
    state.count++
  },
  [DECREMENT] (state) {
    state.count--
  }
}

export default new Vuex({
  state,
  actions,
  mutations
})
<commit_msg>comments<commit_after>import Vue from 'vue'
import Vuex from '../../src'

Vue.use(Vuex)

// mutation types
// optional if you don't like constants.
const INCREMENT = 'INCREMENT'
const DECREMENT = 'DECREMENT'

// root state object.
// each Vuex instance is just a single state tree.
const state = {
  count: 0
}

// actions are what components will be able to
// call as vuex.actions.xxx
// note these are not the final functions the
// components will be calling.
const actions = {

  // for simple actions that just dispatches a single mutation,
  // we can just provide the mutation type.
  increment: INCREMENT,
  decrement: DECREMENT,

  // for conditional actions that depend on the state,
  // we can provide a thunk (a function that returns a function)
  // the returned function will get two arguments,
  // the first being the dispatch function and the second is
  // the state tree.
  incrementIfOdd: () => (dispatch, state) => {
    if (state.count % 2 === 1) {
      dispatch(INCREMENT)
    }
  },

  // we also use thunks for async actions.
  // you can dispatch multiple mutations inside a thunk action.
  incrementAsync: () => dispatch => {
    setTimeout(() => {
      dispatch(INCREMENT)
    }, 1000)
  }
}

// mutations are operations that actually mutates the state.
// each mutation handler gets the entire state tree as the
// first argument, followed by additional payload arguments.
// mutations can be recorded by middlewares.
const mutations = {
  [INCREMENT] (state) {
    state.count++
  },
  [DECREMENT] (state) {
    state.count--
  }
}

// A Vuex instance is created by combining the state, the actions,
// and the mutations. Because the actions and mutations are just
// functions that do not depend on the instance itself, they can
// be easily tested.
//
// You can also provide middlewares, which is just an array of
// objects containing before/after hooks that will get called for
// each mutation.
export default new Vuex({
  state,
  actions,
  mutations
})
<|endoftext|>


<commit_before>L.TimeDimension.Layer.ImageOverlay = L.TimeDimension.Layer.extend({

    initialize: function(layer, options) {
        L.TimeDimension.Layer.prototype.initialize.call(this, layer, options);
        this._layers = {};
        this._defaultTime = 0;
        this._timeCacheBackward = this.options.cacheBackward || this.options.cache || 0;
        this._timeCacheForward = this.options.cacheForward || this.options.cache || 0;
        this._getUrlFunction = this.options.getUrlFunction;

        this._baseLayer.on('load', (function() {
            this._baseLayer.setLoaded(true);
            this.fire('timeload', {
                time: this._defaultTime
            });
        }).bind(this));
    },

    eachLayer: function(method, context) {
        for (var prop in this._layers) {
            if (this._layers.hasOwnProperty(prop)) {
                method.call(context, this._layers[prop]);
            }
        }
        return L.TimeDimension.Layer.prototype.eachLayer.call(this, method, context);
    },

    _onNewTimeLoading: function(ev) {
        var layer = this._getLayerForTime(ev.time);
        if (!this._map.hasLayer(layer)) {
            this._map.addLayer(layer);
        }
    },

    isReady: function(time) {
        var layer = this._getLayerForTime(time);
        return layer.isLoaded();
    },

    _update: function() {
        if (!this._map)
            return;
        var time = map.timeDimension.getCurrentTime();
        var layer = this._getLayerForTime(time);
        if (this._currentLayer == null) {
            this._currentLayer = layer;
        }
        if (!this._map.hasLayer(layer)) {
            this._map.addLayer(layer);
        } else {
            this._showLayer(layer, time);
        }
    },

    _showLayer: function(layer, time) {
        if (this._currentLayer && this._currentLayer !== layer) {
            this._currentLayer.hide();
            this._map.removeLayer(this._currentLayer);
        }
        layer.show();
        if (this._currentLayer && this._currentLayer === layer) {
            return;
        }
        this._currentLayer = layer;
        // Cache management
        var times = this._getLoadedTimes();
        var strTime = String(time);
        var index = times.indexOf(strTime);
        var remove = [];
        // remove times before current time
        if (this._timeCacheBackward > -1) {
            var objectsToRemove = index - this._timeCacheBackward;
            if (objectsToRemove > 0) {
                remove = times.splice(0, objectsToRemove);
                this._removeLayers(remove);
            }
        }
        if (this._timeCacheForward > -1) {
            index = times.indexOf(strTime);
            var objectsToRemove = times.length - index - this._timeCacheForward - 1;
            if (objectsToRemove > 0) {
                remove = times.splice(index + this._timeCacheForward + 1, objectsToRemove);
                this._removeLayers(remove);
            }
        }
    },

    _getLayerForTime: function(time) {
        if (time == 0 || time == this._defaultTime) {
            return this._baseLayer;
        }
        if (this._layers.hasOwnProperty(time)) {
            return this._layers[time];
        }
        var url = this._getUrlFunction(this._baseLayer.getURL(), time);
        imageBounds = this._baseLayer._bounds;

        var newLayer = L.imageOverlay(url, imageBounds);
        this._layers[time] = newLayer;
        newLayer.on('load', (function(layer, time) {
            layer.setLoaded(true);
            if (map.timeDimension && time == map.timeDimension.getCurrentTime() && !map.timeDimension.isLoading()) {
                this._showLayer(layer, time);
            }
            this.fire('timeload', {
                time: time
            });
        }).bind(this, newLayer, time));

        // Hack to hide the layer when added to the map.
        // It will be shown when timeload event is fired from the map (after all layers are loaded)
        newLayer.onAdd = (function(map) {
            Object.getPrototypeOf(this).onAdd.call(this, map);
            this.hide();
        }).bind(newLayer);
        return newLayer;
    },

    _getLoadedTimes: function() {
        var result = [];
        for (var prop in this._layers) {
            if (this._layers.hasOwnProperty(prop)) {
                result.push(prop);
            }
        }
        return result.sort();
    },

    _removeLayers: function(times) {
        for (var i = 0, l = times.length; i < l; i++) {
            this._map.removeLayer(this._layers[times[i]]);
            delete this._layers[times[i]];
        }
    },

});

L.timeDimension.layer.imageOverlay = function(layer, options) {
    return new L.TimeDimension.Layer.ImageOverlay(layer, options);
};

L.ImageOverlay.include({
    _visible: true,
    _loaded: false,

    _originalUpdate: L.imageOverlay.prototype._update,

    _update: function() {
        if (!this._visible && this._loaded) {
            return;
        }
        this._originalUpdate();
    },

    setLoaded: function(loaded) {
        this._loaded = loaded;
    },

    isLoaded: function() {
        return this._loaded;
    },

    hide: function() {
        this._visible = false;
        if (this._image && this._image.style)
            this._image.style.display = 'none';
    },

    show: function() {
        this._visible = true;
        if (this._image && this._image.style)
            this._image.style.display = 'block';
    },

    getURL: function() {
        return this._url;
    },

});

var map = L.map('map', {
    zoom: 15,
    timeDimension: true,
    timeDimensionOptions: {
        timeInterval: "2014-01-01/2014-12-31",
        period: "PT1H",
        validTimeRange: "06:00/15:00",
        currentTime: Date.parse("2014-08-01T12:00:00Z")
    },
    timeDimensionControl: false,
    timeDimensionControlOptions: {
        autoPlay: false,
        playerOptions: {
            buffer: 10,
            transitionTime: 500,
            loop: true,
        }
    },
    center: [38.70, 1.15],
});

// Add image layer
var imageUrl = 'http://www.socib.es/users/mobims/imageArchive/clm/sirena/clm/c04/2014/01/11/clm_s_04_2014-01-01-12-00.png',
    imageBounds = [
        [38.69, 1.1675],
        [38.71, 1.1325]
    ];

var imageLayer = L.imageOverlay(imageUrl, imageBounds);
var getSirenaImageUrl = function(baseUrl, time) {
    var beginUrl = baseUrl.substring(0, baseUrl.lastIndexOf("/") - 10);
    beginUrl = beginUrl + new Date(time).format('yyyy/mm/dd');
    var strTime = new Date(time).format('yyyy-mm-dd-HH-MM');
    var initFileUrl = baseUrl.substring(baseUrl.lastIndexOf("/"), baseUrl.length - 20);
    url = beginUrl + initFileUrl + strTime + '.png';
    return url;
};

var testImageTimeLayer = L.timeDimension.layer.imageOverlay(imageLayer, {
    getUrlFunction: getSirenaImageUrl
});
testImageTimeLayer.addTo(map);

// Create wind chart
$.getJSON('js/example10-data.json', function(data) {
    // Create the chart
    $('#chart').highcharts('StockChart', {
        rangeSelector: {
            selected: 2
        },
        title: {
            text: 'Wind average at Cala Millor'
        },

        tooltip: {
            formatter: function() {
                var s = '' + Highcharts.dateFormat('%A %b %e, %Y', this.x) + '';
                $.each(this.points, function(i, point) {
                    s += '
Wind: ' + point.y.toFixed(2) + ' m/s';
                });
                return s;
            },
            shared: true
        },
        series: [{
            name: 'WIND',
            data: data,
        }],
        plotOptions: {
            series: {
                cursor: 'pointer',
                point: {
                    events: {
                        click: function(event) {
                            var day = new Date(event.point.x);
                            day.setUTCHours(12, 0, 0);
                            map.timeDimension.setCurrentTime(day.getTime());
                        }
                    }
                }
            }
        }
    });
});

// basic custom control
var controlContainer = $("#mapcontrol");
map.timeDimension.on('timeload', function(data) {
    var date = new Date(map.timeDimension.getCurrentTime());
    controlContainer.find('span.date').html(date.format("dd/mm/yyyy", true));
    controlContainer.find('span.time').html(date.format("HH:MM", true));
    if (data.time == map.timeDimension.getCurrentTime()) {
        $('#map').removeClass('map-loading');
    }
});
map.timeDimension.on('timeloading', function(data) {
    if (data.time == map.timeDimension.getCurrentTime()) {
        $('#map').addClass('map-loading');
    }
});
controlContainer.find('.btn-prev').click(function() {
    map.timeDimension.previousTime();
});
controlContainer.find('.btn-next').click(function() {
    map.timeDimension.nextTime();
});
var player = new L.TimeDimension.Player({}, map.timeDimension);
controlContainer.find('.btn-play').click(function() {
    var btn = $(this);
    if (player.isPlaying()) {
        btn.removeClass("btn-pause");
        btn.addClass("btn-play");
        btn.html("Play");
        player.stop();
    } else {
        btn.removeClass("btn-play");
        btn.addClass("btn-pause");
        btn.html("Pause");
        player.start();
    }
});

map.timeDimension.setCurrentTime(new Date(2014, 0, 1, 13, 00).getTime());<commit_msg>Add opacity to example 10. ImageOverlay with options<commit_after>L.TimeDimension.Layer.ImageOverlay = L.TimeDimension.Layer.extend({

    initialize: function(layer, options) {
        L.TimeDimension.Layer.prototype.initialize.call(this, layer, options);
        this._layers = {};
        this._defaultTime = 0;
        this._timeCacheBackward = this.options.cacheBackward || this.options.cache || 0;
        this._timeCacheForward = this.options.cacheForward || this.options.cache || 0;
        this._getUrlFunction = this.options.getUrlFunction;

        this._baseLayer.on('load', (function() {
            this._baseLayer.setLoaded(true);
            this.fire('timeload', {
                time: this._defaultTime
            });
        }).bind(this));
    },

    eachLayer: function(method, context) {
        for (var prop in this._layers) {
            if (this._layers.hasOwnProperty(prop)) {
                method.call(context, this._layers[prop]);
            }
        }
        return L.TimeDimension.Layer.prototype.eachLayer.call(this, method, context);
    },

    _onNewTimeLoading: function(ev) {
        var layer = this._getLayerForTime(ev.time);
        if (!this._map.hasLayer(layer)) {
            this._map.addLayer(layer);
        }
    },

    isReady: function(time) {
        var layer = this._getLayerForTime(time);
        return layer.isLoaded();
    },

    _update: function() {
        if (!this._map)
            return;
        var time = map.timeDimension.getCurrentTime();
        var layer = this._getLayerForTime(time);
        if (this._currentLayer == null) {
            this._currentLayer = layer;
        }
        if (!this._map.hasLayer(layer)) {
            this._map.addLayer(layer);
        } else {
            this._showLayer(layer, time);
        }
    },

    _showLayer: function(layer, time) {
        if (this._currentLayer && this._currentLayer !== layer) {
            this._currentLayer.hide();
            this._map.removeLayer(this._currentLayer);
        }
        layer.show();
        if (this._currentLayer && this._currentLayer === layer) {
            return;
        }
        this._currentLayer = layer;
        // Cache management
        var times = this._getLoadedTimes();
        var strTime = String(time);
        var index = times.indexOf(strTime);
        var remove = [];
        // remove times before current time
        if (this._timeCacheBackward > -1) {
            var objectsToRemove = index - this._timeCacheBackward;
            if (objectsToRemove > 0) {
                remove = times.splice(0, objectsToRemove);
                this._removeLayers(remove);
            }
        }
        if (this._timeCacheForward > -1) {
            index = times.indexOf(strTime);
            var objectsToRemove = times.length - index - this._timeCacheForward - 1;
            if (objectsToRemove > 0) {
                remove = times.splice(index + this._timeCacheForward + 1, objectsToRemove);
                this._removeLayers(remove);
            }
        }
    },

    _getLayerForTime: function(time) {
        if (time == 0 || time == this._defaultTime) {
            return this._baseLayer;
        }
        if (this._layers.hasOwnProperty(time)) {
            return this._layers[time];
        }
        var url = this._getUrlFunction(this._baseLayer.getURL(), time);
        imageBounds = this._baseLayer._bounds;

        var newLayer = L.imageOverlay(url, imageBounds, this._baseLayer.options);
        this._layers[time] = newLayer;
        newLayer.on('load', (function(layer, time) {
            layer.setLoaded(true);
            if (map.timeDimension && time == map.timeDimension.getCurrentTime() && !map.timeDimension.isLoading()) {
                this._showLayer(layer, time);
            }
            this.fire('timeload', {
                time: time
            });
        }).bind(this, newLayer, time));

        // Hack to hide the layer when added to the map.
        // It will be shown when timeload event is fired from the map (after all layers are loaded)
        newLayer.onAdd = (function(map) {
            Object.getPrototypeOf(this).onAdd.call(this, map);
            this.hide();
        }).bind(newLayer);
        return newLayer;
    },

    _getLoadedTimes: function() {
        var result = [];
        for (var prop in this._layers) {
            if (this._layers.hasOwnProperty(prop)) {
                result.push(prop);
            }
        }
        return result.sort();
    },

    _removeLayers: function(times) {
        for (var i = 0, l = times.length; i < l; i++) {
            this._map.removeLayer(this._layers[times[i]]);
            delete this._layers[times[i]];
        }
    },

});

L.timeDimension.layer.imageOverlay = function(layer, options) {
    return new L.TimeDimension.Layer.ImageOverlay(layer, options);
};

L.ImageOverlay.include({
    _visible: true,
    _loaded: false,

    _originalUpdate: L.imageOverlay.prototype._update,

    _update: function() {
        if (!this._visible && this._loaded) {
            return;
        }
        this._originalUpdate();
    },

    setLoaded: function(loaded) {
        this._loaded = loaded;
    },

    isLoaded: function() {
        return this._loaded;
    },

    hide: function() {
        this._visible = false;
        if (this._image && this._image.style)
            this._image.style.display = 'none';
    },

    show: function() {
        this._visible = true;
        if (this._image && this._image.style)
            this._image.style.display = 'block';
    },

    getURL: function() {
        return this._url;
    },

});

var map = L.map('map', {
    zoom: 15,
    timeDimension: true,
    timeDimensionOptions: {
        timeInterval: "2014-01-01/2014-12-31",
        period: "PT1H",
        validTimeRange: "06:00/15:00",
        currentTime: Date.parse("2014-08-01T12:00:00Z")
    },
    timeDimensionControl: false,
    timeDimensionControlOptions: {
        autoPlay: false,
        playerOptions: {
            buffer: 10,
            transitionTime: 500,
            loop: true,
        }
    },
    center: [38.70, 1.15],
});

// Add image layer
var imageUrl = 'http://www.socib.es/users/mobims/imageArchive/clm/sirena/clm/c04/2014/01/11/clm_s_04_2014-01-01-12-00.png',
    imageBounds = [
        [38.69, 1.1675],
        [38.71, 1.1325]
    ];

var imageLayer = L.imageOverlay(imageUrl, imageBounds, {
    opacity: 0.5
});

var getSirenaImageUrl = function(baseUrl, time) {
    var beginUrl = baseUrl.substring(0, baseUrl.lastIndexOf("/") - 10);
    beginUrl = beginUrl + new Date(time).format('yyyy/mm/dd');
    var strTime = new Date(time).format('yyyy-mm-dd-HH-MM');
    var initFileUrl = baseUrl.substring(baseUrl.lastIndexOf("/"), baseUrl.length - 20);
    url = beginUrl + initFileUrl + strTime + '.png';
    return url;
};

var testImageTimeLayer = L.timeDimension.layer.imageOverlay(imageLayer, {
    getUrlFunction: getSirenaImageUrl
});
testImageTimeLayer.addTo(map);

// Create wind chart
$.getJSON('js/example10-data.json', function(data) {
    // Create the chart
    $('#chart').highcharts('StockChart', {
        rangeSelector: {
            selected: 2
        },
        title: {
            text: 'Wind average at Cala Millor'
        },

        tooltip: {
            formatter: function() {
                var s = '' + Highcharts.dateFormat('%A %b %e, %Y', this.x) + '';
                $.each(this.points, function(i, point) {
                    s += '
Wind: ' + point.y.toFixed(2) + ' m/s';
                });
                return s;
            },
            shared: true
        },
        series: [{
            name: 'WIND',
            data: data,
        }],
        plotOptions: {
            series: {
                cursor: 'pointer',
                point: {
                    events: {
                        click: function(event) {
                            var day = new Date(event.point.x);
                            day.setUTCHours(12, 0, 0);
                            map.timeDimension.setCurrentTime(day.getTime());
                        }
                    }
                }
            }
        }
    });
});

// basic custom control
var controlContainer = $("#mapcontrol");
map.timeDimension.on('timeload', function(data) {
    var date = new Date(map.timeDimension.getCurrentTime());
    controlContainer.find('span.date').html(date.format("dd/mm/yyyy", true));
    controlContainer.find('span.time').html(date.format("HH:MM", true));
    if (data.time == map.timeDimension.getCurrentTime()) {
        $('#map').removeClass('map-loading');
    }
});
map.timeDimension.on('timeloading', function(data) {
    if (data.time == map.timeDimension.getCurrentTime()) {
        $('#map').addClass('map-loading');
    }
});
controlContainer.find('.btn-prev').click(function() {
    map.timeDimension.previousTime();
});
controlContainer.find('.btn-next').click(function() {
    map.timeDimension.nextTime();
});
var player = new L.TimeDimension.Player({}, map.timeDimension);
controlContainer.find('.btn-play').click(function() {
    var btn = $(this);
    if (player.isPlaying()) {
        btn.removeClass("btn-pause");
        btn.addClass("btn-play");
        btn.html("Play");
        player.stop();
    } else {
        btn.removeClass("btn-play");
        btn.addClass("btn-pause");
        btn.html("Pause");
        player.start();
    }
});

map.timeDimension.setCurrentTime(new Date(2014, 0, 1, 13, 00).getTime());<|endoftext|>


<commit_before>define(['Ti/_', 'Ti/_/browser', 'Ti/_/Evented', 'Ti/_/lang', 'Ti/Locale', 'Ti/_/dom', 'Ti/UI'],
	function(_, browser, Evented, lang, Locale, dom, UI) {

	var doc = document,
		midName = 'ti:mid',
		matches = doc.cookie.match(new RegExp('(?:^|; )' + midName + '=([^;]*)')),
		mid = matches ? decodeURIComponent(matches[1]) : void 0,
		unloaded,
		on = require.on,
		deviceCapabilities = tizen.systeminfo.getCapabilities(),
		hiddenIFrame = dom.create('iframe', { id: 'urlOpener', style: { display: 'none' } }, doc.body),
		wifiNetworkPropertyValueChangeListenerId, batteryValueChangeListenerId;

	mid || (mid = localStorage.getItem(midName));
	mid || localStorage.setItem(midName, mid = _.uuid());

	function saveMid() {
		if (!unloaded) {
			unloaded = 1;
			// expire cookie in 20 years... forever in mobile terms
			doc.cookie = midName + '=' + encodeURIComponent(mid) + '; expires=' + (new Date(Date.now() + 63072e7)).toUTCString();
			localStorage.setItem(midName, mid);
		}
	};

	// initialize values that should be initialized via fucntions with callbacks
	function initPlatformData() {
		//Get our application info.
		//Workaround for simulator. It throws exception because id is undefined. On Emulator works fine.
		try {
			Platform.constants.__values__.id = tizen.application.getAppInfo().id; //The unique ID for an installed application.
		} catch (e) {
			Platform.constants.__values__.id = 'ID001'; //The unique ID for an installed application.
		}

		if(deviceCapabilities.wifi) {
			tizen.systeminfo.getPropertyValue('WIFI_NETWORK', onSuccessWifiNetworkCallback, onErrorCallback);
			// subscribing to WiFi property changes
			wifiNetworkPropertyValueChangeListenerId = tizen.systeminfo.addPropertyValueChangeListener('WIFI_NETWORK', onSuccessWifiNetworkCallback);
		}

		// Get model property
		tizen.systeminfo.getPropertyValue('BUILD', onSuccessModelCallback, onErrorCallback);

		// Get battery info
		tizen.systeminfo.getPropertyValue('BATTERY', onSuccessBatteryCallback, onErrorCallback);
		batteryValueChangeListenerId = tizen.systeminfo.addPropertyValueChangeListener('BATTERY', onSuccessBatteryCallback);
	};

	function onErrorCallback(error) {
		Ti.API.error('An error occurred ' + error.message);
	};

	// Callback to update WiFi's IP address
	function onSuccessWifiNetworkCallback(wifiNetwork) {
		//receive SystemInfoWifiNetwork
		try {
			if (wifiNetwork.status === 'ON') {
				Platform.constants.__values__.address = wifiNetwork.ipAddress;
			} else {
				Platform.constants.__values__.address = void 0;
			}
			Ti.API.info('Platform.address is set to ' + Platform.address);
		} catch (e) {
			Ti.API.error('Error on getting WifiNetwork info. Error: ' + e.message);
			Platform.constants.__values__.address = void 0;
		}
	}

	// Callback to set Model
	function onSuccessModelCallback(build) {
		try {
			Platform.constants.__values__.model = build.model;
		} catch (e) {
			Ti.API.info('Error on getting model info. Error: ' + e.message);
			Platform.constants.__values__.model = void 0;
		}
	}

	function onSuccessBatteryCallback(battery) {
		try {
			Platform.constants.__values__.batteryMonitoring = true;
			Platform.constants.__values__.batteryLevel = battery.level * 100;
			Platform.constants.__values__.batteryState = battery.isCharging
				? Platform.BATTERY_STATE_CHARGING
				: (battery.level === 1 ? Platform.BATTERY_STATE_FULL : Platform.BATTERY_STATE_UNPLUGGED);
		} catch (e) {
			Ti.API.error('Error on getting battery info. Error: ' + e.message);
			Platform.constants.__values__.batteryMonitoring = false;
			Platform.constants.__values__.batteryLevel = void 0;
			Platform.constants.__values__.batteryState = Platform.BATTERY_STATE_UNKNOWN;
		}
	}

	on(window, 'beforeunload', saveMid);
	on(window, 'unload', saveMid);

	var nav = navigator,
		battery = nav.battery || nav.webkitBattery || nav.mozBattery,
		Platform = lang.setObject('Ti.Platform', Evented, {

			canOpenURL: function(url) {
				return !!url;
			},

			createUUID: _.uuid,

			is24HourTimeFormat: function() {
				return false;
			},

			openURL: function(url){
				if (/^([tel|sms|mailto])/.test(url)) {
					hiddenIFrame.contentWindow.location.href = url;
				} else {
					var win = UI.createWindow({
							layout: UI._LAYOUT_CONSTRAINING_VERTICAL,
							backgroundColor: '#888'
						}),
						backButton = UI.createButton({
							top: 2,
							bottom: 2,
							title: 'Close'
						}),
						webview = UI.createWebView({
							width: UI.FILL,
							height: UI.FILL
						});
					backButton.addEventListener('singletap', function(){
						win.close();
					});
					win.add(backButton);
					win.add(webview);
					win.open();
					setTimeout(function(){
						webview.url = url;
					}, 1);
				}
			},

			properties: {
				batteryMonitoring: false
			},

			constants: {
				BATTERY_STATE_CHARGING: 1,
				BATTERY_STATE_FULL: 2,
				BATTERY_STATE_UNKNOWN: -1,
				BATTERY_STATE_UNPLUGGED: 0,
				address: void 0,
				architecture: deviceCapabilities.platformCoreCpuArch,
				availableMemory: void 0,
				batteryLevel: void 0,
				batteryMonitoring: false,
				batteryState: void 0,
				isBrowser: true,
				id: mid,
				locale: Locale,
				macaddress: void 0,
				model: nav.userAgent,
				name: deviceCapabilities.platformName,
				netmask: void 0,
				osname: 'tizen',
				ostype: nav.platform,
				runtime: browser.runtime,
				processorCount: void 0,
				username: void 0,
				version: deviceCapabilities.platformVersion
			}

		});

	battery && require.on(battery, 'chargingchange', function() {
		Platform.batteryMonitoring && Platform.fireEvent('battery', {
			level: Platform.batteryLevel,
			state: Platform.batteryState
		});
	});

	initPlatformData();
	return Platform;

});
<commit_msg>Fixed Ti.Platform, remove extra try catch blocks<commit_after>define(['Ti/_', 'Ti/_/browser', 'Ti/_/Evented', 'Ti/_/lang', 'Ti/Locale', 'Ti/_/dom', 'Ti/UI'],
	function(_, browser, Evented, lang, Locale, dom, UI) {

	var doc = document,
		midName = 'ti:mid',
		matches = doc.cookie.match(new RegExp('(?:^|; )' + midName + '=([^;]*)')),
		mid = matches ? decodeURIComponent(matches[1]) : void 0,
		unloaded,
		on = require.on,
		deviceCapabilities = tizen.systeminfo.getCapabilities(),
		hiddenIFrame = dom.create('iframe', { id: 'urlOpener', style: { display: 'none' } }, doc.body);

	mid || (mid = localStorage.getItem(midName));
	mid || localStorage.setItem(midName, mid = _.uuid());

	function saveMid() {
		if (!unloaded) {
			unloaded = 1;
			// expire cookie in 20 years... forever in mobile terms
			doc.cookie = midName + '=' + encodeURIComponent(mid) + '; expires=' + (new Date(Date.now() + 63072e7)).toUTCString();
			localStorage.setItem(midName, mid);
		}
	};

	// initialize values that should be initialized via fucntions with callbacks
	function initPlatformData() {
		//Get our application info.
		//Workaround for simulator. It throws exception because id is undefined. On Emulator works fine.
		try {
			Platform.constants.__values__.id = tizen.application.getAppInfo().id; //The unique ID for an installed application.
		} catch (e) {
			Platform.constants.__values__.id = 'ID001'; //The unique ID for an installed application.
		}

		if(deviceCapabilities.wifi) {
			tizen.systeminfo.getPropertyValue('WIFI_NETWORK', onSuccessWifiNetworkCallback, onErrorCallback);
			// subscribing to WiFi property changes
			tizen.systeminfo.addPropertyValueChangeListener('WIFI_NETWORK', onSuccessWifiNetworkCallback);
		}

		// Get model property
		tizen.systeminfo.getPropertyValue('BUILD', onSuccessModelCallback, onErrorCallback);

		// Get battery info
		tizen.systeminfo.getPropertyValue('BATTERY', onSuccessBatteryCallback, onErrorCallback);
		tizen.systeminfo.addPropertyValueChangeListener('BATTERY', onSuccessBatteryCallback);
	};

	function onErrorCallback(error) {
		Ti.API.error('An error occurred ' + error.message);
	};

	// Callback to update WiFi's IP address
	function onSuccessWifiNetworkCallback(wifiNetwork) {
		//receive SystemInfoWifiNetwork
		if (wifiNetwork.status === 'ON') {
			Platform.constants.__values__.address = wifiNetwork.ipAddress;
		} else {
			Platform.constants.__values__.address = void 0;
		}
		Ti.API.info('Platform.address is set to ' + Platform.address);
	}

	// Callback to set Model
	function onSuccessModelCallback(build) {
		Platform.constants.__values__.model = build.model;
	}

	function onSuccessBatteryCallback(battery) {
		Platform.constants.__values__.batteryMonitoring = true;
		Platform.constants.__values__.batteryLevel = battery.level * 100;
		Platform.constants.__values__.batteryState = battery.isCharging
			? Platform.BATTERY_STATE_CHARGING
			: (battery.level === 1 ? Platform.BATTERY_STATE_FULL : Platform.BATTERY_STATE_UNPLUGGED);
	}

	on(window, 'beforeunload', saveMid);
	on(window, 'unload', saveMid);

	var nav = navigator,
		battery = nav.battery || nav.webkitBattery || nav.mozBattery,
		Platform = lang.setObject('Ti.Platform', Evented, {

			canOpenURL: function(url) {
				return !!url;
			},

			createUUID: _.uuid,

			is24HourTimeFormat: function() {
				return false;
			},

			openURL: function(url){
				if (/^([tel|sms|mailto])/.test(url)) {
					hiddenIFrame.contentWindow.location.href = url;
				} else {
					var win = UI.createWindow({
							layout: UI._LAYOUT_CONSTRAINING_VERTICAL,
							backgroundColor: '#888'
						}),
						backButton = UI.createButton({
							top: 2,
							bottom: 2,
							title: 'Close'
						}),
						webview = UI.createWebView({
							width: UI.FILL,
							height: UI.FILL
						});
					backButton.addEventListener('singletap', function(){
						win.close();
					});
					win.add(backButton);
					win.add(webview);
					win.open();
					setTimeout(function(){
						webview.url = url;
					}, 1);
				}
			},

			properties: {
				batteryMonitoring: false
			},

			constants: {
				BATTERY_STATE_CHARGING: 1,
				BATTERY_STATE_FULL: 2,
				BATTERY_STATE_UNKNOWN: -1,
				BATTERY_STATE_UNPLUGGED: 0,
				address: void 0,
				architecture: deviceCapabilities.platformCoreCpuArch,
				availableMemory: void 0,
				batteryLevel: void 0,
				batteryMonitoring: false,
				batteryState: void 0,
				isBrowser: true,
				id: mid,
				locale: Locale,
				macaddress: void 0,
				model: nav.userAgent,
				name: deviceCapabilities.platformName,
				netmask: void 0,
				osname: 'tizen',
				ostype: nav.platform,
				runtime: browser.runtime,
				processorCount: void 0,
				username: void 0,
				version: deviceCapabilities.platformVersion
			}

		});

	battery && require.on(battery, 'chargingchange', function() {
		Platform.batteryMonitoring && Platform.fireEvent('battery', {
			level: Platform.batteryLevel,
			state: Platform.batteryState
		});
	});

	initPlatformData();
	return Platform;

});
<|endoftext|>