<commit_before>module.exports = function (fork) {
    fork.use(require("./es7"));

    var types = fork.use(require("../lib/types"));
    var def = types.Type.def;
    var or = types.Type.or;
    var defaults = fork.use(require("../lib/shared")).defaults;

    // Type Annotations
    def("Type").bases("Node");

    def("AnyTypeAnnotation")
      .bases("Type")
      .build();

    def("EmptyTypeAnnotation")
      .bases("Type")
      .build();

    def("MixedTypeAnnotation")
      .bases("Type")
      .build();

    def("VoidTypeAnnotation")
      .bases("Type")
      .build();

    def("NumberTypeAnnotation")
      .bases("Type")
      .build();

    def("NumberLiteralTypeAnnotation")
      .bases("Type")
      .build("value", "raw")
      .field("value", Number)
      .field("raw", String);

    def("StringTypeAnnotation")
      .bases("Type")
      .build();

    def("StringLiteralTypeAnnotation")
      .bases("Type")
      .build("value", "raw")
      .field("value", String)
      .field("raw", String);

    def("BooleanTypeAnnotation")
      .bases("Type")
      .build();

    def("BooleanLiteralTypeAnnotation")
      .bases("Type")
      .build("value", "raw")
      .field("value", Boolean)
      .field("raw", String);

    def("TypeAnnotation")
      .bases("Node")
      .build("typeAnnotation")
      .field("typeAnnotation", def("Type"));

    def("NullableTypeAnnotation")
      .bases("Type")
      .build("typeAnnotation")
      .field("typeAnnotation", def("Type"));

    def("NullLiteralTypeAnnotation")
      .bases("Type")
      .build();

    def("NullTypeAnnotation")
      .bases("Type")
      .build();

    def("ThisTypeAnnotation")
      .bases("Type")
      .build();

    def("ExistsTypeAnnotation")
      .bases("Type")
      .build();

    def("ExistentialTypeParam")
      .bases("Type")
      .build();

    def("FunctionTypeAnnotation")
      .bases("Type")
      .build("params", "returnType", "rest", "typeParameters")
      .field("params", [def("FunctionTypeParam")])
      .field("returnType", def("Type"))
      .field("rest", or(def("FunctionTypeParam"), null))
      .field("typeParameters", or(def("TypeParameterDeclaration"), null));

    def("FunctionTypeParam")
      .bases("Node")
      .build("name", "typeAnnotation", "optional")
      .field("name", def("Identifier"))
      .field("typeAnnotation", def("Type"))
      .field("optional", Boolean);

    def("ArrayTypeAnnotation")
      .bases("Type")
      .build("elementType")
      .field("elementType", def("Type"));

    def("ObjectTypeAnnotation")
      .bases("Type")
      .build("properties", "indexers", "callProperties")
      .field("properties", [def("ObjectTypeProperty")])
      .field("indexers", [def("ObjectTypeIndexer")], defaults.emptyArray)
      .field("callProperties",
        [def("ObjectTypeCallProperty")],
        defaults.emptyArray)
      .field("exact", Boolean, defaults["false"]);

    def("ObjectTypeProperty")
      .bases("Node")
      .build("key", "value", "optional")
      .field("key", or(def("Literal"), def("Identifier")))
      .field("value", def("Type"))
      .field("optional", Boolean)
      .field("variance",
        or("plus", "minus", null),
        defaults["null"]);

    def("ObjectTypeIndexer")
      .bases("Node")
      .build("id", "key", "value")
      .field("id", def("Identifier"))
      .field("key", def("Type"))
      .field("value", def("Type"))
      .field("variance",
        or("plus", "minus", null),
        defaults["null"]);

    def("ObjectTypeCallProperty")
      .bases("Node")
      .build("value")
      .field("value", def("FunctionTypeAnnotation"))
      .field("static", Boolean, defaults["false"]);

    def("QualifiedTypeIdentifier")
      .bases("Node")
      .build("qualification", "id")
      .field("qualification",
        or(def("Identifier"),
          def("QualifiedTypeIdentifier")))
      .field("id", def("Identifier"));

    def("GenericTypeAnnotation")
      .bases("Type")
      .build("id", "typeParameters")
      .field("id", or(def("Identifier"), def("QualifiedTypeIdentifier")))
      .field("typeParameters", or(def("TypeParameterInstantiation"), null));

    def("MemberTypeAnnotation")
      .bases("Type")
      .build("object", "property")
      .field("object", def("Identifier"))
      .field("property",
        or(def("MemberTypeAnnotation"),
          def("GenericTypeAnnotation")));

    def("UnionTypeAnnotation")
      .bases("Type")
      .build("types")
      .field("types", [def("Type")]);

    def("IntersectionTypeAnnotation")
      .bases("Type")
      .build("types")
      .field("types", [def("Type")]);

    def("TypeofTypeAnnotation")
      .bases("Type")
      .build("argument")
      .field("argument", def("Type"));

    def("Identifier")
      .field("typeAnnotation", or(def("TypeAnnotation"), null), defaults["null"]);

    def("TypeParameterDeclaration")
      .bases("Node")
      .build("params")
      .field("params", [def("TypeParameter")]);

    def("TypeParameterInstantiation")
      .bases("Node")
      .build("params")
      .field("params", [def("Type")]);

    def("TypeParameter")
      .bases("Type")
      .build("name", "variance", "bound")
      .field("name", String)
      .field("variance",
        or("plus", "minus", null),
        defaults["null"])
      .field("bound",
        or(def("TypeAnnotation"), null),
        defaults["null"]);

    def("Function")
      .field("returnType",
        or(def("TypeAnnotation"), null),
        defaults["null"])
      .field("typeParameters",
        or(def("TypeParameterDeclaration"), null),
        defaults["null"]);

    def("ClassProperty")
      .build("key", "value", "typeAnnotation", "static")
      .field("value", or(def("Expression"), null))
      .field("typeAnnotation", or(def("TypeAnnotation"), null))
      .field("static", Boolean, defaults["false"])
      .field("variance",
        or("plus", "minus", null),
        defaults["null"]);

    def("ClassImplements")
      .field("typeParameters",
        or(def("TypeParameterInstantiation"), null),
        defaults["null"]);

    def("InterfaceDeclaration")
      .bases("Declaration")
      .build("id", "body", "extends")
      .field("id", def("Identifier"))
      .field("typeParameters",
        or(def("TypeParameterDeclaration"), null),
        defaults["null"])
      .field("body", def("ObjectTypeAnnotation"))
      .field("extends", [def("InterfaceExtends")]);

    def("DeclareInterface")
      .bases("InterfaceDeclaration")
      .build("id", "body", "extends");

    def("InterfaceExtends")
      .bases("Node")
      .build("id")
      .field("id", def("Identifier"))
      .field("typeParameters", or(def("TypeParameterInstantiation"), null));

    def("TypeAlias")
      .bases("Declaration")
      .build("id", "typeParameters", "right")
      .field("id", def("Identifier"))
      .field("typeParameters", or(def("TypeParameterDeclaration"), null))
      .field("right", def("Type"));

    def("DeclareTypeAlias")
      .bases("TypeAlias")
      .build("id", "typeParameters", "right");

    def("TypeCastExpression")
      .bases("Expression")
      .build("expression", "typeAnnotation")
      .field("expression", def("Expression"))
      .field("typeAnnotation", def("TypeAnnotation"));

    def("TupleTypeAnnotation")
      .bases("Type")
      .build("types")
      .field("types", [def("Type")]);

    def("DeclareVariable")
      .bases("Statement")
      .build("id")
      .field("id", def("Identifier"));

    def("DeclareFunction")
      .bases("Statement")
      .build("id")
      .field("id", def("Identifier"));

    def("DeclareClass")
      .bases("InterfaceDeclaration")
      .build("id");

    def("DeclareModule")
      .bases("Statement")
      .build("id", "body")
      .field("id", or(def("Identifier"), def("Literal")))
      .field("body", def("BlockStatement"));

    def("DeclareModuleExports")
      .bases("Statement")
      .build("typeAnnotation")
      .field("typeAnnotation", def("Type"));

    def("DeclareExportDeclaration")
      .bases("Declaration")
      .build("default", "declaration", "specifiers", "source")
      .field("default", Boolean)
      .field("declaration", or(
        def("DeclareVariable"),
        def("DeclareFunction"),
        def("DeclareClass"),
        def("Type"), // Implies default.
        null
      ))
      .field("specifiers", [or(
        def("ExportSpecifier"),
        def("ExportBatchSpecifier")
      )], defaults.emptyArray)
      .field("source", or(
        def("Literal"),
        null
      ), defaults["null"]);

    def("DeclareExportAllDeclaration")
      .bases("Declaration")
      .build("source")
      .field("source", or(
        def("Literal"),
        null
      ), defaults["null"]);
};
<commit_msg>add Babel's NumericLiteralTypeAnnotation (#205)<commit_after>module.exports = function (fork) {
    fork.use(require("./es7"));

    var types = fork.use(require("../lib/types"));
    var def = types.Type.def;
    var or = types.Type.or;
    var defaults = fork.use(require("../lib/shared")).defaults;

    // Type Annotations
    def("Type").bases("Node");

    def("AnyTypeAnnotation")
      .bases("Type")
      .build();

    def("EmptyTypeAnnotation")
      .bases("Type")
      .build();

    def("MixedTypeAnnotation")
      .bases("Type")
      .build();

    def("VoidTypeAnnotation")
      .bases("Type")
      .build();

    def("NumberTypeAnnotation")
      .bases("Type")
      .build();

    def("NumberLiteralTypeAnnotation")
      .bases("Type")
      .build("value", "raw")
      .field("value", Number)
      .field("raw", String);

    // Babylon 6 differs in AST from Flow
    // same as NumberLiteralTypeAnnotation
    def("NumericLiteralTypeAnnotation")
      .bases("Type")
      .build("value", "raw")
      .field("value", Number)
      .field("raw", String);

    def("StringTypeAnnotation")
      .bases("Type")
      .build();

    def("StringLiteralTypeAnnotation")
      .bases("Type")
      .build("value", "raw")
      .field("value", String)
      .field("raw", String);

    def("BooleanTypeAnnotation")
      .bases("Type")
      .build();

    def("BooleanLiteralTypeAnnotation")
      .bases("Type")
      .build("value", "raw")
      .field("value", Boolean)
      .field("raw", String);

    def("TypeAnnotation")
      .bases("Node")
      .build("typeAnnotation")
      .field("typeAnnotation", def("Type"));

    def("NullableTypeAnnotation")
      .bases("Type")
      .build("typeAnnotation")
      .field("typeAnnotation", def("Type"));

    def("NullLiteralTypeAnnotation")
      .bases("Type")
      .build();

    def("NullTypeAnnotation")
      .bases("Type")
      .build();

    def("ThisTypeAnnotation")
      .bases("Type")
      .build();

    def("ExistsTypeAnnotation")
      .bases("Type")
      .build();

    def("ExistentialTypeParam")
      .bases("Type")
      .build();

    def("FunctionTypeAnnotation")
      .bases("Type")
      .build("params", "returnType", "rest", "typeParameters")
      .field("params", [def("FunctionTypeParam")])
      .field("returnType", def("Type"))
      .field("rest", or(def("FunctionTypeParam"), null))
      .field("typeParameters", or(def("TypeParameterDeclaration"), null));

    def("FunctionTypeParam")
      .bases("Node")
      .build("name", "typeAnnotation", "optional")
      .field("name", def("Identifier"))
      .field("typeAnnotation", def("Type"))
      .field("optional", Boolean);

    def("ArrayTypeAnnotation")
      .bases("Type")
      .build("elementType")
      .field("elementType", def("Type"));

    def("ObjectTypeAnnotation")
      .bases("Type")
      .build("properties", "indexers", "callProperties")
      .field("properties", [def("ObjectTypeProperty")])
      .field("indexers", [def("ObjectTypeIndexer")], defaults.emptyArray)
      .field("callProperties",
        [def("ObjectTypeCallProperty")],
        defaults.emptyArray)
      .field("exact", Boolean, defaults["false"]);

    def("ObjectTypeProperty")
      .bases("Node")
      .build("key", "value", "optional")
      .field("key", or(def("Literal"), def("Identifier")))
      .field("value", def("Type"))
      .field("optional", Boolean)
      .field("variance",
        or("plus", "minus", null),
        defaults["null"]);

    def("ObjectTypeIndexer")
      .bases("Node")
      .build("id", "key", "value")
      .field("id", def("Identifier"))
      .field("key", def("Type"))
      .field("value", def("Type"))
      .field("variance",
        or("plus", "minus", null),
        defaults["null"]);

    def("ObjectTypeCallProperty")
      .bases("Node")
      .build("value")
      .field("value", def("FunctionTypeAnnotation"))
      .field("static", Boolean, defaults["false"]);

    def("QualifiedTypeIdentifier")
      .bases("Node")
      .build("qualification", "id")
      .field("qualification",
        or(def("Identifier"),
          def("QualifiedTypeIdentifier")))
      .field("id", def("Identifier"));

    def("GenericTypeAnnotation")
      .bases("Type")
      .build("id", "typeParameters")
      .field("id", or(def("Identifier"), def("QualifiedTypeIdentifier")))
      .field("typeParameters", or(def("TypeParameterInstantiation"), null));

    def("MemberTypeAnnotation")
      .bases("Type")
      .build("object", "property")
      .field("object", def("Identifier"))
      .field("property",
        or(def("MemberTypeAnnotation"),
          def("GenericTypeAnnotation")));

    def("UnionTypeAnnotation")
      .bases("Type")
      .build("types")
      .field("types", [def("Type")]);

    def("IntersectionTypeAnnotation")
      .bases("Type")
      .build("types")
      .field("types", [def("Type")]);

    def("TypeofTypeAnnotation")
      .bases("Type")
      .build("argument")
      .field("argument", def("Type"));

    def("Identifier")
      .field("typeAnnotation", or(def("TypeAnnotation"), null), defaults["null"]);

    def("TypeParameterDeclaration")
      .bases("Node")
      .build("params")
      .field("params", [def("TypeParameter")]);

    def("TypeParameterInstantiation")
      .bases("Node")
      .build("params")
      .field("params", [def("Type")]);

    def("TypeParameter")
      .bases("Type")
      .build("name", "variance", "bound")
      .field("name", String)
      .field("variance",
        or("plus", "minus", null),
        defaults["null"])
      .field("bound",
        or(def("TypeAnnotation"), null),
        defaults["null"]);

    def("Function")
      .field("returnType",
        or(def("TypeAnnotation"), null),
        defaults["null"])
      .field("typeParameters",
        or(def("TypeParameterDeclaration"), null),
        defaults["null"]);

    def("ClassProperty")
      .build("key", "value", "typeAnnotation", "static")
      .field("value", or(def("Expression"), null))
      .field("typeAnnotation", or(def("TypeAnnotation"), null))
      .field("static", Boolean, defaults["false"])
      .field("variance",
        or("plus", "minus", null),
        defaults["null"]);

    def("ClassImplements")
      .field("typeParameters",
        or(def("TypeParameterInstantiation"), null),
        defaults["null"]);

    def("InterfaceDeclaration")
      .bases("Declaration")
      .build("id", "body", "extends")
      .field("id", def("Identifier"))
      .field("typeParameters",
        or(def("TypeParameterDeclaration"), null),
        defaults["null"])
      .field("body", def("ObjectTypeAnnotation"))
      .field("extends", [def("InterfaceExtends")]);

    def("DeclareInterface")
      .bases("InterfaceDeclaration")
      .build("id", "body", "extends");

    def("InterfaceExtends")
      .bases("Node")
      .build("id")
      .field("id", def("Identifier"))
      .field("typeParameters", or(def("TypeParameterInstantiation"), null));

    def("TypeAlias")
      .bases("Declaration")
      .build("id", "typeParameters", "right")
      .field("id", def("Identifier"))
      .field("typeParameters", or(def("TypeParameterDeclaration"), null))
      .field("right", def("Type"));

    def("DeclareTypeAlias")
      .bases("TypeAlias")
      .build("id", "typeParameters", "right");

    def("TypeCastExpression")
      .bases("Expression")
      .build("expression", "typeAnnotation")
      .field("expression", def("Expression"))
      .field("typeAnnotation", def("TypeAnnotation"));

    def("TupleTypeAnnotation")
      .bases("Type")
      .build("types")
      .field("types", [def("Type")]);

    def("DeclareVariable")
      .bases("Statement")
      .build("id")
      .field("id", def("Identifier"));

    def("DeclareFunction")
      .bases("Statement")
      .build("id")
      .field("id", def("Identifier"));

    def("DeclareClass")
      .bases("InterfaceDeclaration")
      .build("id");

    def("DeclareModule")
      .bases("Statement")
      .build("id", "body")
      .field("id", or(def("Identifier"), def("Literal")))
      .field("body", def("BlockStatement"));

    def("DeclareModuleExports")
      .bases("Statement")
      .build("typeAnnotation")
      .field("typeAnnotation", def("Type"));

    def("DeclareExportDeclaration")
      .bases("Declaration")
      .build("default", "declaration", "specifiers", "source")
      .field("default", Boolean)
      .field("declaration", or(
        def("DeclareVariable"),
        def("DeclareFunction"),
        def("DeclareClass"),
        def("Type"), // Implies default.
        null
      ))
      .field("specifiers", [or(
        def("ExportSpecifier"),
        def("ExportBatchSpecifier")
      )], defaults.emptyArray)
      .field("source", or(
        def("Literal"),
        null
      ), defaults["null"]);

    def("DeclareExportAllDeclaration")
      .bases("Declaration")
      .build("source")
      .field("source", or(
        def("Literal"),
        null
      ), defaults["null"]);
};
<|endoftext|>


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

    angular.module('mcontactListApp').controller('ContactListAllCtrl', ['ContactDataSrcv', '$mdDialog', '$rootScope', ContactListAllCtrl]);

    function ContactListAllCtrl(ContactDataSrcv, $mdDialog, $rootScope) {

        /*bind this controller to a vm*/
        var vm = this;

        /*set the page title*/
        $rootScope.pageTitle = 'Lista de contatos';
        /*Set page header color according to contact avatar color*/
        $rootScope.pageHeaderColor = "primary";

        /*Material design colors*/
        var colorsNames = ["red", "pink", "purple", "deep-purple", "indigo", "blue", "light-blue", "cyan", "teal", "green", "light-green", "lime", "yellow", "amber", "orange", "deep-orange"];

        /*Some material design colorsNumbers*/
        var colorsNumbers = ["400", "500", "600", "700", "800", "900"];

        //get contacts from service
        vm.contacts = ContactDataSrcv.contacts

        /************ Dialog for add new contact *************/

        vm.openAddContactDialg = function (ev) {

            vm.contactToEdit = angular.copy(vm.selectedContact);
            $mdDialog.show({
                    controller: ('DialogCtrl', function ($scope) {

                        $scope.newContact = {};
                        $scope.cancelDialg = function () {
                            $scope.newContact = {};
                            $mdDialog.cancel();
                        };

                        $scope.confirmDialg = function (answer) {
                            $mdDialog.hide(answer);
                        };

                    }),
                    templateUrl: 'components/contacts/listAll/contactAdd.dialg.html',
                    parent: angular.element(document.body),
                    targetEvent: ev,
                    fullscreen: true,
                    clickOutsideToClose: false,
                    locals: {
                        contact: vm.contactToEdit
                    }
                })
                .then(function (newContact) {
                    /*Dialog confirmed*/
                    console.log(newContact);

                    // add a avatar color to the contact
                    var colorsNamesIndex = Math.round(Math.random() * (colorsNames.length - 1));
                    var colorsNumbersIndex = Math.round(Math.random() * (colorsNumbers.length - 1));
                    newContact.avatarColor = colorsNames[colorsNamesIndex] + "-" + colorsNumbers[colorsNumbersIndex];

                    //Add an id
                    newContact._id = Date.now();
                    //Add new  contact on service
                    vm.contacts.push(newContact);

                }, function () {

                    /*Dialog canceled*/
                });
        };

        /*Clear search text*/
        vm.clearSearchText = function () {
            vm.searchText = "";

        }

    }

})();<commit_msg>id do novo contato convertido para string<commit_after>(function () {
    'use strict';

    angular.module('mcontactListApp').controller('ContactListAllCtrl', ['ContactDataSrcv', '$mdDialog', '$rootScope', ContactListAllCtrl]);

    function ContactListAllCtrl(ContactDataSrcv, $mdDialog, $rootScope) {

        /*bind this controller to a vm*/
        var vm = this;

        /*set the page title*/
        $rootScope.pageTitle = 'Lista de contatos';
        /*Set page header color according to contact avatar color*/
        $rootScope.pageHeaderColor = "primary";

        /*Material design colors*/
        var colorsNames = ["red", "pink", "purple", "deep-purple", "indigo", "blue", "light-blue", "cyan", "teal", "green", "light-green", "lime", "yellow", "amber", "orange", "deep-orange"];

        /*Some material design colorsNumbers*/
        var colorsNumbers = ["400", "500", "600", "700", "800", "900"];

        //get contacts from service
        vm.contacts = ContactDataSrcv.contacts

        /************ Dialog for add new contact *************/

        vm.openAddContactDialg = function (ev) {

            vm.contactToEdit = angular.copy(vm.selectedContact);
            $mdDialog.show({
                    controller: ('DialogCtrl', function ($scope) {

                        $scope.newContact = {};
                        $scope.cancelDialg = function () {
                            $scope.newContact = {};
                            $mdDialog.cancel();
                        };

                        $scope.confirmDialg = function (answer) {
                            $mdDialog.hide(answer);
                        };

                    }),
                    templateUrl: 'components/contacts/listAll/contactAdd.dialg.html',
                    parent: angular.element(document.body),
                    targetEvent: ev,
                    fullscreen: true,
                    clickOutsideToClose: false,
                    locals: {
                        contact: vm.contactToEdit
                    }
                })
                .then(function (newContact) {
                    /*Dialog confirmed*/
                    console.log(newContact);

                    // add a avatar color to the contact
                    var colorsNamesIndex = Math.round(Math.random() * (colorsNames.length - 1));
                    var colorsNumbersIndex = Math.round(Math.random() * (colorsNumbers.length - 1));
                    newContact.avatarColor = colorsNames[colorsNamesIndex] + "-" + colorsNumbers[colorsNumbersIndex];

                    //Add an id
                    newContact._id = Date.now().toString();
                    //Add new  contact on service
                    vm.contacts.push(newContact);

                }, function () {

                    /*Dialog canceled*/
                });
        };

        /*Clear search text*/
        vm.clearSearchText = function () {
            vm.searchText = "";

        }

    }

})();<|endoftext|>


<commit_before>import { call, put, take, takeLatest } from 'redux-saga/effects';
import moment from 'moment';
import { push } from 'react-router-redux';

import { getCurrentTimeURL } from '../../urls';
import { homePage } from '../../localUrls';
import { fetchWithCredentials } from '../../utils/sagas';
import { deleteJwtToken, haveJwtToken } from '../../utils/auth';
import { LOGIN_SUCCESS } from '../LoginForm/constants';

import { getCurrentTimeSuccess } from './actions';
import { LOGOUT } from './constants';

function fetchCurrentTime() {
  return fetchWithCredentials(getCurrentTimeURL(), {
    method: 'GET',
    headers: {
      Accept: 'application/json',
    },
  }).then((response) => response.json())
    .then((response) => moment(response.time));
}

function* sleep(time) {
  yield new Promise((resolve) => setTimeout(resolve, time));
}

function* synchronizeTime() {
// eslint-disable-next-line no-constant-condition
  while (true) {
    if (!haveJwtToken()) yield take(LOGIN_SUCCESS);
    const time = yield call(fetchCurrentTime);
    yield put(getCurrentTimeSuccess(time));
    yield* sleep(5 * 60 * 1000);
  }
}

function* logout() {
  deleteJwtToken();
  yield put(push(homePage()));
}

function* logoutSaga() {
  yield takeLatest(LOGOUT, logout);
}

// All sagas to be loaded
export default [
  synchronizeTime,
  logoutSaga,
];
<commit_msg>Decode jwt token on page load (#77)<commit_after>import { call, put, take, takeLatest } from 'redux-saga/effects';
import moment from 'moment';
import { push } from 'react-router-redux';
import jwtDecode from 'jwt-decode';

import { getCurrentTimeURL } from '../../urls';
import { homePage } from '../../localUrls';
import { fetchWithCredentials } from '../../utils/sagas';
import { deleteJwtToken, getJwtToken, haveJwtToken } from '../../utils/auth';
import { LOGIN_SUCCESS } from '../LoginForm/constants';
import { loginSuccess } from '../LoginForm/actions';

import { getCurrentTimeSuccess } from './actions';
import { LOGOUT } from './constants';

function fetchCurrentTime() {
  return fetchWithCredentials(getCurrentTimeURL(), {
    method: 'GET',
    headers: {
      Accept: 'application/json',
    },
  }).then((response) => response.json())
    .then((response) => moment(response.time));
}

function* sleep(time) {
  yield new Promise((resolve) => setTimeout(resolve, time));
}

function* synchronizeTime() {
// eslint-disable-next-line no-constant-condition
  while (true) {
    if (!haveJwtToken()) yield take(LOGIN_SUCCESS);
    const time = yield call(fetchCurrentTime);
    yield put(getCurrentTimeSuccess(time));
    yield* sleep(5 * 60 * 1000);
  }
}

function* logout() {
  deleteJwtToken();
  yield put(push(homePage()));
}

function* logoutSaga() {
  yield takeLatest(LOGOUT, logout);
}

function* decodeJWT() {
  if (!haveJwtToken()) return;
  yield put(loginSuccess(jwtDecode(getJwtToken()).dat));
}

// All sagas to be loaded
export default [
  synchronizeTime,
  logoutSaga,
  decodeJWT,
];
<|endoftext|>


<commit_before>'use strict';

// Set search path root for resolving partials
exports.root = './public/html';

// Will be printed before the xml/html-string
exports.doctype = '<!DOCTYPE html>';

// Used to log render time to console
exports.logTime = false;

/**
 * Render HTML template + data = HTML
 *
 * @param str tmplStr
 * @param obj data
 * @param func callback(err, HTML-string)
 */
exports.render = function(tmplStr, data, callback) {
	if (exports.logTime)
		console.time('Template render');

	var libxmljs        = require('libxmljs'),
	    resolvedTmplStr = exports.resolvePartials(tmplStr),
	    resolvedTmplStr = resolvedTmplStr.replace(/^\s+|\s+$/g, ''), // trim string
	    doc             = libxmljs.parseXmlString(resolvedTmplStr, {'noblanks': true });

	// First replace all text nodes that are not local
	var textNodes = doc.find('//text[not(@data-localvalue)]');
	for (var i = 0; i < textNodes.length; i++)
		setTextNode(textNodes[i], data);

	// Walk through all nodes with a data-value
	var nodesToFill = doc.find('//*[@data-value]');
	for (var i = 0; i < nodesToFill.length; i++)
		setNodeVal(nodesToFill[i], data);

	// Walk through all the nodes with a data-attribute
	var attribsToFill = doc.find('//*[@data-attribute]');
	for (var i = 0; i < attribsToFill.length; i++)
		setAttrVal(attribsToFill[i], data);

	// Lastly remove all nodes that are marked with removal attribute
	// After we've re-parsed the string
	// The reason we do this is removing nodes triggers a segmentation fault in libxmljs
	// if we do it while working the document. No idea why. / Lilleman 2014-10-11
	// It seems this is the reason: https://github.com/polotek/libxmljs/pull/163 / Lilleman a few minutes later
	// If we did not need to do this double parsing, performance should increase
	// For more information about this issue and possible future salvation: https://github.com/polotek/libxmljs/pull/163
	var doc2 = libxmljs.parseXmlString(doc.root().toString());
	var nodesToRemove = doc2.find('//*[@removethis = "ohyes"]');
	for (var i = 0; i < nodesToRemove.length; i++)
		nodesToRemove[i].remove();

	// We also need to make sure <textarea>-tags are not shortened,
	// since that breaks HTML parsing in many browsers
	var textareaNodes = doc2.find('//textarea');
	for (var i = 0; i < textareaNodes.length; i++)
		if (textareaNodes[i].text() == '')
			textareaNodes[i].text(' ');

	var htmlStr = exports.doctype + doc2.root().toString();

	// Strip that last space from the textareas so it wont turn up in the end output
	htmlStr = htmlStr.replace(' </textarea', '</textarea');

	if (exports.logTime)
		console.timeEnd('Template render');

	if (typeof callback === 'function')
		callback(null, htmlStr);
	else
		console.error('larvitTmpl.js - exports.render() - callback is not passed as a function');
}

/**
 * Resolve partials in a template
 *
 * @param str or obj - doc The document to find and resolve partitials in.
 *                     If it is an object, it have to be an instance of an xml object
 * @param func callback(err, tmplStr)
 */
exports.resolvePartials = function(doc) {
	var xpath = require('xpath'),
	    dom   = require('xmldom').DOMParser,
	    cache = {}; // Caches the resolves

	if (typeof doc === 'string') {
		if (cache[doc] !== undefined)
			return cache[doc];

		doc = new dom().parseFromString(doc);
	}

	var partials = xpath.select('//partial', doc);
	var tmplStr  = doc.toString();

	if ( ! partials.length)
		return tmplStr;

	for (var i = 0; i < partials.length; i++) {
		var partial     = partials[i],
		    partialName = partial.getAttribute('data-template');

		if (exports.root.substring(1, 4) == 'http') {
			// Todo: require from URL via interwebz
			console.error('larvitTmpl.js - resolvePartials() - Support for client side partials not supported yet');
			return new Error('larvitTmpl.js - resolvePartials() - Support for client side partials not supported yet');
		} else {
			// Not http-something, assume local file
			var fs              = require('fs'),
			    partialFilename = exports.root + '/' + partialName;

			var fileData = fs.readFileSync(partialFilename);
			if ( ! fileData) {
				console.error('larvitTmpl.js - resolvePartials() - file not found: ' + partialFilename);
				return new Error('Template partial not found: ' + partialFilename);
			}

			var partialStr = fileData.toString();
			partialStr = exports.resolvePartials(partialStr);
			if ( ! partialStr) {
				console.error('larvitTmpl.js - resolvePartials() - subResolver returned error:');
				console.error(partialStr);

				return new Error('Template subResolver returned error');
			}

			tmplStr = tmplStr.replace(partial.toString(), partialStr);
		}

		// Remove the partial-node as its no longer needed
		partial.parentNode.removeChild(partial);
	}

	cache[doc] = tmplStr;
	return tmplStr;
}

function setTextNode(node, data) {
	var dataKey;

	if (node.attr('data-value'))
		dataKey = node.attr('data-value').value();
	else if (node.attr('data-localvalue'))
		dataKey = node.attr('data-localvalue').value();

	var resolvedData = getValByPath(data, dataKey);
	if (typeof resolvedData == 'string' || typeof resolvedData == 'number') {
		node.name('span');
		node.text(resolvedData.toString());
	}
}

function setNodeVal(node, data) {
	if (node.attr('data-value')) {
		var dataKey      = node.attr('data-value').value(),
		    resolvedData = getValByPath(data, dataKey);

		if (resolvedData === false) {
			// Explicitly remove the node

			node.attr({'removethis':'ohyes'});
		} else if (resolvedData instanceof Array) {
			// Create a new element for each existing part of this array

			renderArray(node, data);
		} else if (resolvedData != undefined) {
			// Simply append the node with some text

			node.text(node.text() + resolvedData.toString());
		}
	} else {
		var error = new Error('setNodeVal() called, but no data-value found');
		console.error(error.stack);
	}
}

function setAttrVal(node, data) {
	var dataKeys = [];

	if (node.attr('data-attribute')) {
		dataKeys = node.attr('data-attribute').value().split(' ');
	} else if (node.attr('data-localattribute')) {
		dataKeys = node.attr('data-localattribute').value().split(' ');
	} else {
		var error = new Error('setAttrVal() called, but no data-attribute or data-localattribute found');
		console.error(error.stack);
	}

	for (var i = 0; i < dataKeys.length; i++) {
		var resolvedData = getValByPath(data, dataKeys[i]);

		if ( ! (resolvedData instanceof Array))
			resolvedData = [resolvedData];

		for (var i2 = 0; i2 < resolvedData.length; i2++) {

			// Make sure the attribute data is valid with a name (thats longer than '') and a value
			if (typeof resolvedData[i2] === 'object' && resolvedData[i2].name != undefined && resolvedData[i2].value != undefined && resolvedData[i2].name.length > 0) {

				if (node.attr(resolvedData[i2].name)) {
					// Attribute exists, append it
					var attribVal = node.attr(resolvedData[i2].name).value();
					attribVal    += ' ' + resolvedData[i2].value;
					node.attr(resolvedData[i2].name).value(attribVal);
				} else {
					// Create a new attribute
					var attrData = {};
					attrData[resolvedData[i2].name] = resolvedData[i2].value;
					node.attr(attrData);
				}
			}
		}
	}
}

function setArrNodeVal(node, data) {
	if (node.attr('data-localvalue')) {
		var localDataKey = node.attr('data-localvalue').value(),
		    localResolvedData = getValByPath(data, localDataKey);

		if (localResolvedData === false)
			node.attr({'removethis':'ohyes'});
		else if (typeof localResolvedData == 'string' || typeof localResolvedData == 'number')
			node.text(node.text() + localResolvedData.toString());
		else if (localResolvedData instanceof Array)
			renderArray(node, localResolvedData);
	} else {
		var error = new Error('setArrNodeVal() called, but no data-localvalue found');
		console.error(error.stack);
	}
}

function renderArray(node, data) {
	var libxmljs = require('libxmljs'),
	    dataKey,
	    resolvedData;

	if (data instanceof Array) {
		resolvedData = data;
	} else {
		if (node.attr('data-localvalue'))
			dataKey = node.attr('data-localValue').value();
		else if (node.attr('data-value'))
			dataKey = node.attr('data-value').value();

		resolvedData = getValByPath(data, dataKey);
	}

	if ( ! (resolvedData instanceof Array)) {
		var errorMsg = 'larvitTmpl - renderArray() called but data could not be resolved as array';
		console.error(errorMsg);
		return new Error(errorMsg);
	}

	for (var i = 0; i < resolvedData.length; i++) {
		var newNode            = node.clone(),
		    localNodesToFill   = newNode.find('./descendant::node()[@data-localvalue]'),
		    localAttribsToFill = newNode.find('./descendant::node()[@data-localattribute]');

		// Loop through data-localvalues
		for (var i2 = 0; i2 < localNodesToFill.length; i2++) {

			// If this is an array, we should produce new nodes first and then populate them
			if (resolvedData[i] instanceof Array) {
				for (var i3 = 0; i3 < resolvedData[i].length; i3++) {
					var localNewNode      = localNodesToFill[i2].clone();
					var addedLocalNewNode = localNodesToFill[i2].addPrevSibling(localNewNode);

					setArrNodeVal(addedLocalNewNode, resolvedData[i][i3]);
				}
				localNodesToFill[i2].attr({'removethis':'ohyes'});
			} else {
				setArrNodeVal(localNodesToFill[i2], resolvedData[i]);
			}
		}

		if (typeof resolvedData[i] == 'string' || typeof resolvedData[i] == 'number')
			newNode.text(resolvedData[i].toString());
		else if (typeof resolvedData[i].value == 'string' || typeof resolvedData[i].value == 'number')
			newNode.text(resolvedData[i].value.toString());

		// Loop through data-localattributes
		for (var i2 = 0; i2 < localAttribsToFill.length; i2++)
			setAttrVal(localAttribsToFill[i2], resolvedData[i]);

		// There might also be a localattribute on the node iteslf
		if (newNode.attr('data-localattribute'))
			setAttrVal(newNode, resolvedData[i]);

		// Lastly, replace text nodes. This must be done lastly, becase otherwise we might override stuff thats been done above
		var textNodes = newNode.find('./descendant-or-self::node()/text');
		for (var i2 = 0; i2 < textNodes.length; i2++)
			setTextNode(textNodes[i2], resolvedData[i]);

		node.addPrevSibling(newNode);
	}

	// Remove the original node
	node.attr({'removethis':'ohyes'});
}

/**
 * Get a deep value from an object by a string path
 * For example:
 * var foo = {'bar': {'lurker': 'someValue'}}
 * getValByPath(foo, 'bar.lurker') returns 'someValue'
 *
 * @param obj obj
 * @param str path
 * @return mixed
 */
function getValByPath(obj, path) {
	if (typeof path === 'string')
		var path = path.split('.');

	if (path.length > 1) {
		var p = path.shift();

		if (typeof obj[p] === 'object')
			return getValByPath(obj[p], path);
		else
			return undefined;

	} else {
		return obj[path[0]];
	}
}<commit_msg>Fixed better debug and made the partial resolver cache work correctly<commit_after>'use strict';

// Set search path root for resolving partials
exports.root = './public/html';

// Will be printed before the xml/html-string
exports.doctype = '<!DOCTYPE html>';

// Used to log render time to console
exports.debug = false;

// Cache used by partials engine
exports.partialCache = {'keys': [], 'results': []};

/**
 * Render HTML template + data = HTML
 *
 * @param str tmplStr
 * @param obj data
 * @param func callback(err, HTML-string)
 */
exports.render = function(tmplStr, data, callback) {
	if (exports.debug === true)
		console.time('Template render');

	var libxmljs        = require('libxmljs'),
	    resolvedTmplStr = exports.resolvePartials(tmplStr),
	    resolvedTmplStr = resolvedTmplStr.replace(/^\s+|\s+$/g, ''), // trim string
	    doc             = libxmljs.parseXmlString(resolvedTmplStr, {'noblanks': true });

	// First replace all text nodes that are not local
	var textNodes = doc.find('//text[not(@data-localvalue)]');
	for (var i = 0; i < textNodes.length; i++)
		setTextNode(textNodes[i], data);

	// Walk through all nodes with a data-value
	var nodesToFill = doc.find('//*[@data-value]');
	for (var i = 0; i < nodesToFill.length; i++)
		setNodeVal(nodesToFill[i], data);

	// Walk through all the nodes with a data-attribute
	var attribsToFill = doc.find('//*[@data-attribute]');
	for (var i = 0; i < attribsToFill.length; i++)
		setAttrVal(attribsToFill[i], data);

	// Lastly remove all nodes that are marked with removal attribute
	// After we've re-parsed the string
	// The reason we do this is removing nodes triggers a segmentation fault in libxmljs
	// if we do it while working the document. No idea why. / Lilleman 2014-10-11
	// It seems this is the reason: https://github.com/polotek/libxmljs/pull/163 / Lilleman a few minutes later
	// If we did not need to do this double parsing, performance should increase
	// For more information about this issue and possible future salvation: https://github.com/polotek/libxmljs/pull/163
	var doc2 = libxmljs.parseXmlString(doc.root().toString());
	var nodesToRemove = doc2.find('//*[@removethis = "ohyes"]');
	for (var i = 0; i < nodesToRemove.length; i++)
		nodesToRemove[i].remove();

	// We also need to make sure <textarea>-tags are not shortened,
	// since that breaks HTML parsing in many browsers
	var textareaNodes = doc2.find('//textarea');
	for (var i = 0; i < textareaNodes.length; i++)
		if (textareaNodes[i].text() == '')
			textareaNodes[i].text(' ');

	var htmlStr = exports.doctype + doc2.root().toString();

	// Strip that last space from the textareas so it wont turn up in the end output
	htmlStr = htmlStr.replace(' </textarea', '</textarea');

	if (exports.debug === true)
		console.timeEnd('Template render');

	if (typeof callback === 'function')
		callback(null, htmlStr);
	else
		console.error('larvitTmpl.js - exports.render() - callback is not passed as a function');
}

/**
 * Resolve partials in a template
 *
 * @param str or obj - doc The document to find and resolve partitials in.
 *                     If it is an object, it have to be an instance of an xml object
 * @param bol        - sub defines if this is a subcall. If it is, this setting should be set to true
 * @param func callback(err, tmplStr)
 */
exports.resolvePartials = function(xmlStr, sub) {
	if (sub !== true && exports.debug === true)
		console.time('Template resolving partials');

	var xpath = require('xpath'),
	    dom   = require('xmldom').DOMParser;

	var cacheIndex = exports.partialCache.keys.indexOf(xmlStr);
	if (cacheIndex !== -1) {
		if (sub !== true && exports.debug === true)
			console.timeEnd('Template resolving partials');

		return exports.partialCache.results[cacheIndex];
	}

	var doc      = new dom().parseFromString(xmlStr),
	    partials = xpath.select('//partial', doc),
	    tmplStr  = doc.toString();

	if ( ! partials.length)
		return tmplStr;

	for (var i = 0; i < partials.length; i++) {
		var partial     = partials[i],
		    partialName = partial.getAttribute('data-template');

		if (exports.root.substring(1, 4) == 'http') {
			// Todo: require from URL via interwebz
			console.error('larvitTmpl.js - resolvePartials() - Support for client side partials not supported yet');
			return new Error('larvitTmpl.js - resolvePartials() - Support for client side partials not supported yet');
		} else {
			// Not http-something, assume local file
			var fs              = require('fs'),
			    partialFilename = exports.root + '/' + partialName;

			var fileData = fs.readFileSync(partialFilename);
			if ( ! fileData) {
				console.error('larvitTmpl.js - resolvePartials() - file not found: ' + partialFilename);
				return new Error('Template partial not found: ' + partialFilename);
			}

			var partialStr = fileData.toString();
			partialStr = exports.resolvePartials(partialStr, true);
			if ( ! partialStr) {
				console.error('larvitTmpl.js - resolvePartials() - subResolver returned error:');
				console.error(partialStr);

				return new Error('Template subResolver returned error');
			}

			tmplStr = tmplStr.replace(partial.toString(), partialStr);
		}

		// Remove the partial-node as its no longer needed
		partial.parentNode.removeChild(partial);
	}

	exports.partialCache.keys.push(xmlStr);
	exports.partialCache.results.push(tmplStr);

	if (sub !== true && exports.debug === true)
		console.timeEnd('Template resolving partials');

	return tmplStr;
}

function setTextNode(node, data) {
	var dataKey;

	if (node.attr('data-value'))
		dataKey = node.attr('data-value').value();
	else if (node.attr('data-localvalue'))
		dataKey = node.attr('data-localvalue').value();

	var resolvedData = getValByPath(data, dataKey);
	if (typeof resolvedData == 'string' || typeof resolvedData == 'number') {
		node.name('span');
		node.text(resolvedData.toString());
	}
}

function setNodeVal(node, data) {
	if (node.attr('data-value')) {
		var dataKey      = node.attr('data-value').value(),
		    resolvedData = getValByPath(data, dataKey);

		if (resolvedData === false) {
			// Explicitly remove the node

			node.attr({'removethis':'ohyes'});
		} else if (resolvedData instanceof Array) {
			// Create a new element for each existing part of this array

			renderArray(node, data);
		} else if (resolvedData != undefined) {
			// Simply append the node with some text

			node.text(node.text() + resolvedData.toString());
		}
	} else {
		var error = new Error('setNodeVal() called, but no data-value found');
		console.error(error.stack);
	}
}

function setAttrVal(node, data) {
	var dataKeys = [];

	if (node.attr('data-attribute')) {
		dataKeys = node.attr('data-attribute').value().split(' ');
	} else if (node.attr('data-localattribute')) {
		dataKeys = node.attr('data-localattribute').value().split(' ');
	} else {
		var error = new Error('setAttrVal() called, but no data-attribute or data-localattribute found');
		console.error(error.stack);
	}

	for (var i = 0; i < dataKeys.length; i++) {
		var resolvedData = getValByPath(data, dataKeys[i]);

		if ( ! (resolvedData instanceof Array))
			resolvedData = [resolvedData];

		for (var i2 = 0; i2 < resolvedData.length; i2++) {

			// Make sure the attribute data is valid with a name (thats longer than '') and a value
			if (typeof resolvedData[i2] === 'object' && resolvedData[i2].name != undefined && resolvedData[i2].value != undefined && resolvedData[i2].name.length > 0) {

				if (node.attr(resolvedData[i2].name)) {
					// Attribute exists, append it
					var attribVal = node.attr(resolvedData[i2].name).value();
					attribVal    += ' ' + resolvedData[i2].value;
					node.attr(resolvedData[i2].name).value(attribVal);
				} else {
					// Create a new attribute
					var attrData = {};
					attrData[resolvedData[i2].name] = resolvedData[i2].value;
					node.attr(attrData);
				}
			}
		}
	}
}

function setArrNodeVal(node, data) {
	if (node.attr('data-localvalue')) {
		var localDataKey = node.attr('data-localvalue').value(),
		    localResolvedData = getValByPath(data, localDataKey);

		if (localResolvedData === false)
			node.attr({'removethis':'ohyes'});
		else if (typeof localResolvedData == 'string' || typeof localResolvedData == 'number')
			node.text(node.text() + localResolvedData.toString());
		else if (localResolvedData instanceof Array)
			renderArray(node, localResolvedData);
	} else {
		var error = new Error('setArrNodeVal() called, but no data-localvalue found');
		console.error(error.stack);
	}
}

function renderArray(node, data) {
	var libxmljs = require('libxmljs'),
	    dataKey,
	    resolvedData;

	if (data instanceof Array) {
		resolvedData = data;
	} else {
		if (node.attr('data-localvalue'))
			dataKey = node.attr('data-localValue').value();
		else if (node.attr('data-value'))
			dataKey = node.attr('data-value').value();

		resolvedData = getValByPath(data, dataKey);
	}

	if ( ! (resolvedData instanceof Array)) {
		var errorMsg = 'larvitTmpl - renderArray() called but data could not be resolved as array';
		console.error(errorMsg);
		return new Error(errorMsg);
	}

	for (var i = 0; i < resolvedData.length; i++) {
		var newNode            = node.clone(),
		    localNodesToFill   = newNode.find('./descendant::node()[@data-localvalue]'),
		    localAttribsToFill = newNode.find('./descendant::node()[@data-localattribute]');

		// Loop through data-localvalues
		for (var i2 = 0; i2 < localNodesToFill.length; i2++) {

			// If this is an array, we should produce new nodes first and then populate them
			if (resolvedData[i] instanceof Array) {
				for (var i3 = 0; i3 < resolvedData[i].length; i3++) {
					var localNewNode      = localNodesToFill[i2].clone();
					var addedLocalNewNode = localNodesToFill[i2].addPrevSibling(localNewNode);

					setArrNodeVal(addedLocalNewNode, resolvedData[i][i3]);
				}
				localNodesToFill[i2].attr({'removethis':'ohyes'});
			} else {
				setArrNodeVal(localNodesToFill[i2], resolvedData[i]);
			}
		}

		if (typeof resolvedData[i] == 'string' || typeof resolvedData[i] == 'number')
			newNode.text(resolvedData[i].toString());
		else if (typeof resolvedData[i].value == 'string' || typeof resolvedData[i].value == 'number')
			newNode.text(resolvedData[i].value.toString());

		// Loop through data-localattributes
		for (var i2 = 0; i2 < localAttribsToFill.length; i2++)
			setAttrVal(localAttribsToFill[i2], resolvedData[i]);

		// There might also be a localattribute on the node iteslf
		if (newNode.attr('data-localattribute'))
			setAttrVal(newNode, resolvedData[i]);

		// Lastly, replace text nodes. This must be done lastly, becase otherwise we might override stuff thats been done above
		var textNodes = newNode.find('./descendant-or-self::node()/text');
		for (var i2 = 0; i2 < textNodes.length; i2++)
			setTextNode(textNodes[i2], resolvedData[i]);

		node.addPrevSibling(newNode);
	}

	// Remove the original node
	node.attr({'removethis':'ohyes'});
}

/**
 * Get a deep value from an object by a string path
 * For example:
 * var foo = {'bar': {'lurker': 'someValue'}}
 * getValByPath(foo, 'bar.lurker') returns 'someValue'
 *
 * @param obj obj
 * @param str path
 * @return mixed
 */
function getValByPath(obj, path) {
	if (typeof path === 'string')
		var path = path.split('.');

	if (path.length > 1) {
		var p = path.shift();

		if (typeof obj[p] === 'object')
			return getValByPath(obj[p], path);
		else
			return undefined;

	} else {
		return obj[path[0]];
	}
}<|endoftext|>


<commit_before>angular.module('Smart_Gardener')
.controller('HomeCtrl', function($scope,$location, plantFactory){
  plantFactory.getPlants()
  .then((res)=>{
    $scope.plants = res.data
    console.log(res);
  })

  $scope.plantById = (id) =>{
    $location.url(`/plant/${id}`)
  }
})
<commit_msg>homeCrtl comments for readability<commit_after>angular.module('Smart_Gardener')
.controller('HomeCtrl', function($scope,$location, plantFactory){
  //loads in plant information
  plantFactory.getPlants()
  .then((res)=>{
    $scope.plants = res.data
    console.log(res);
  })
  //pass plant id as a route param
  $scope.plantById = (id) =>{
    $location.url(`/plant/${id}`)
  }
})
<|endoftext|>


<commit_before>/** @jsx React.DOM */

define(
  [
    'react',
    'backbone',
    'moment'
  ],
  function (React, Backbone, moment) {

    return React.createClass({

      propTypes: {
        message: React.PropTypes.instanceOf(Backbone.Model).isRequired
      },

      getMaintenanceDateTimeMessage: function(message){
        var currentDate = moment();
        var startDate = message.get('start_date');
        var endDate = message.get('end_date');
        var isInMaintenance = currentDate.diff(startDate) > 0;

        var message;
        if(isInMaintenance){
          return (

              {"Maintenance is currently underway and will end on "}
              {endDate.format("MMM Do")} at {endDate.format("h:mma")}

          )
        }

        if(startDate.format("MM D") === endDate.format("MM D")) {
          return (

              {"Maintenance is scheduled to performed on "}
              {startDate.format("MMM Do")} from {startDate.format("h:mma") + "-" + endDate.format("h:mma")}

          )
        }

        return (

            {"Maintenance is scheduled to performed on "}
            {startDate.format("MMM Do")} at {startDate.format("h:mma")}
            {" and ending on "}
            {endDate.format("MMM Do")} at {endDate.format("h:mma")}

        );
      },

      render: function () {
        var message = this.props.message;

        return (

              {message.get('title')}

              {this.getMaintenanceDateTimeMessage(message)}

              {message.get('message')}

        );
      }

    });

  });
<commit_msg>show html in maintenance messages<commit_after>/** @jsx React.DOM */

define(
  [
    'react',
    'backbone',
    'moment'
  ],
  function (React, Backbone, moment) {

    return React.createClass({

      propTypes: {
        message: React.PropTypes.instanceOf(Backbone.Model).isRequired
      },

      getMaintenanceDateTimeMessage: function(message){
        var currentDate = moment();
        var startDate = message.get('start_date');
        var endDate = message.get('end_date');
        var isInMaintenance = currentDate.diff(startDate) > 0;

        var message;
        if(isInMaintenance){
          return (

              {"Maintenance is currently underway and will end on "}
              {endDate.format("MMM Do")} at {endDate.format("h:mma")}

          )
        }

        if(startDate.format("MM D") === endDate.format("MM D")) {
          return (

              {"Maintenance is scheduled to performed on "}
              {startDate.format("MMM Do")} from {startDate.format("h:mma") + "-" + endDate.format("h:mma")}

          )
        }

        return (

            {"Maintenance is scheduled to performed on "}
            {startDate.format("MMM Do")} at {startDate.format("h:mma")}
            {" and ending on "}
            {endDate.format("MMM Do")} at {endDate.format("h:mma")}

        );
      },

      render: function () {
        var message = this.props.message;

        return (

              {message.get('title')}

              {this.getMaintenanceDateTimeMessage(message)}

        );
      }

    });

  });
<|endoftext|>


<commit_before>import React, { View, Image, Text, StyleSheet, ListView, TouchableHighlight } from 'react-native';
import { colors } from '../../styles/global';

export default class CategoryBrowser extends React.Component {

  constructor(props) {
    super(props);

    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      dataSource: ds.cloneWithRows(props.categories)
    }

    this._renderRow = this._renderRow.bind(this);
    this._onSelectCategory = this._onSelectCategory.bind(this);
  }

  _onSelectCategory(category) {
    this.props.onSelectCategory(category);
  }

  _renderRow(category) {
    const slug = category.slug;
    return (
      <TouchableHighlight onPress={() => this._onSelectCategory(slug)} underlayColor="transparent">
        <View style={styles.row}>
          <Image style={styles.catimage} source={{uri: category.image}} />
          <Text style={styles.categoryText}>{category.name}</Text>
        </View>
      </TouchableHighlight>
    );
  }

  render() {
    return (
      <View>
        <Text style={styles.title}>Browse deals by category</Text>
        <ListView
          dataSource={this.state.dataSource}
          renderRow={this._renderRow}
          contentContainerStyle={styles.list}
        />
      </View>
    );
  }

}

const styles = StyleSheet.create({
  title: {
    color: colors.textLight,
    fontSize: 16,
    fontWeight: 'bold',
    alignSelf: 'center',
    margin: 10
  },
  list: {
    justifyContent: 'center',
    flexDirection: 'row',
    flexWrap: 'wrap'
  },
  row: {
    flex: 1,
    justifyContent: 'center',
    padding: 5,
    margin: 3,
    height: 100,
    backgroundColor: '#fff',
    alignItems: 'center',
    borderWidth: 0.5,
    borderRadius: 2,
    borderColor: '#ddd'
  },
  catimage: {
    width: 128,
    height: 48,
    marginBottom: 5
  },
  categoryText: {
    color: colors.textNormal,
    fontSize: 12
  }
});
<commit_msg>Fixed category browser scrolling<commit_after>import React, { View, Image, Text, StyleSheet, ListView, TouchableHighlight } from 'react-native';
import { colors } from '../../styles/global';

export default class CategoryBrowser extends React.Component {

  constructor(props) {
    super(props);

    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      dataSource: ds.cloneWithRows(props.categories)
    }

    this._renderRow = this._renderRow.bind(this);
    this._onSelectCategory = this._onSelectCategory.bind(this);
  }

  _onSelectCategory(category) {
    this.props.onSelectCategory(category);
  }

  _renderRow(category) {
    const slug = category.slug;
    return (
      <TouchableHighlight onPress={() => this._onSelectCategory(slug)} underlayColor="transparent">
        <View style={styles.row}>
          <Image style={styles.catimage} source={{uri: category.image}} />
          <Text style={styles.categoryText}>{category.name}</Text>
        </View>
      </TouchableHighlight>
    );
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.title}>Browse deals by category</Text>
        <ListView
          dataSource={this.state.dataSource}
          renderRow={this._renderRow}
          contentContainerStyle={styles.list}
        />
      </View>
    );
  }

}

const styles = StyleSheet.create({
  container: {
    flex: 1
  },
  title: {
    color: colors.textLight,
    fontSize: 16,
    fontWeight: 'bold',
    alignSelf: 'center',
    margin: 10
  },
  list: {
    justifyContent: 'center',
    flexDirection: 'row',
    flexWrap: 'wrap',
  },
  row: {
    flex: 1,
    justifyContent: 'center',
    padding: 5,
    margin: 3,
    height: 100,
    backgroundColor: '#fff',
    alignItems: 'center',
    borderWidth: 0.5,
    borderRadius: 2,
    borderColor: '#ddd'
  },
  catimage: {
    width: 128,
    height: 48,
    marginBottom: 5
  },
  categoryText: {
    color: colors.textNormal,
    fontSize: 12
  }
});
<|endoftext|>


<commit_before>// TODO: Make this entire thing cleaner

var formatsData = require('Pokemon-Showdown/data/formats-data').BattleFormatsData
var pokedex = require('Pokemon-Showdown/data/pokedex').BattlePokedex
var items = require('Pokemon-Showdown/data/items').BattleItems
var doublesFormatsData = Object.create(formatsData)
var formats = require('Pokemon-Showdown/config/formats').Formats

var formatHandlers = {
    'Doubles OU': 'Uber',
    'Doubles UU': 'OU',
}

var banlists = {}

for (var pokemonid in doublesFormatsData) {
    doublesFormatsData[pokemonid] = Object.create(doublesFormatsData[pokemonid])
    doublesFormatsData[pokemonid].tier = 'NU'
}

formats.forEach(function searchFormats(format) {
    var tier = formatHandlers[format.name]
    if (tier) {
        format.banlist.forEach(function applyBanlist(entry) {
            var id = toId(entry)
            var item = items[id]
            if (item && item.megaEvolves) {
                doublesFormatsData[toId(item.megaStone)].tier = tier
            }
            var pokemon = doublesFormatsData[id]
            if (pokemon) {
                pokemon.tier = tier
            }
        })
    }
})

function toId(name) {
    return name.toLowerCase().replace(/[^a-z0-9]/g, "")
}

function searchTier(formatsData, pokemonid, findMega) {
    var pokemon = pokedex[pokemonid]
    var tiers = {
        Uber: 0,
        OU: 1,
        BL: 1,
        UU: 2,
        BL2: 2,
        RU: 3,
        BL3: 3,
        NU: 4,
        BL4: 4,
        PU: 5,
        New: 5,
        NFE: 5,
        LC: 5,
        'LC Uber': 5,
    }
    var reverseTier = ['Uber', 'OU', 'UU', 'RU', 'NU', 'PU']
    var evos = pokemon.evos || []
    if (findMega) {
        evos = evos.concat(pokemon.otherFormes || [])
    }
    var toSearch = evos.map(function recursiveSearch(evo) {
        return searchTier(formatsData, evo, findMega)
    }).concat(formatsData[pokemonid].tier)
    return reverseTier[Math.min.apply(Math, toSearch.map(function toTierValue(tier) {
        if (tier.charAt(0) === '(') {
            tier = tier.slice(1, -1)
        }
        return tiers[tier]
    }))]
}

function hasMega(pokemon) {
    if (pokemon.species === 'Rayquaza') {
        return false // too broken
    }
    if (pokemon.otherFormes) {
        for (var i = 0; i < pokemon.otherFormes.length; i++) {
            var id = pokemon.otherFormes[i]
            var forme = pokedex[id]
            if (forme.forme.substring(0, 4) === 'Mega') {
                return formatsData[id].tier !== "Unreleased"
            }
        }
        return false
    }
    var evos = pokemon.evos || []
    for (var i = 0; i < evos.length; i++) {
        if (hasMega(pokedex[evos[i]])) {
            return true
        }
    }
    return false
}

function gen(num) {
    if (num <= 151) return 1
    if (num <= 251) return 2
    if (num <= 386) return 3
    if (num <= 493) return 4
    if (num <= 649) return 5
    return 6
}

var banned = {
    burmy: 1, caterpie: 1, combee: 1, kricketot: 1, magikarp: 1, scatterbug: 1,
    sunkern: 1, tynamo: 1, weedle: 1, wurmple: 1
}
var legendaries = {
    articuno: 1, zapdos: 1, moltres: 1, mewtwo: 1, mew: 1, raikou: 1,
    entei: 1, suicune: 1, lugia: 1, hooh: 1, celebi: 1, regirock: 1,
    regice: 1, registeel: 1, latias: 1, latios: 1, kyogre: 1, groudon: 1,
    rayquaza: 1, jirachi: 1, deoxys: 1, deoxysattack: 1, deoxysdefense: 1,
    deoxysspeed: 1, uxie: 1, mesprit: 1, azelf: 1, dialga: 1, palkia: 1,
    heatran: 1, regigigas: 1, manaphy: 1, giratina: 1, giratinaorigin: 1,
    cresselia: 1, darkrai: 1, shaymin: 1, shayminsky: 1, arceus: 1,
    victini: 1, cobalion: 1, terrakion: 1, virizion: 1, tornadus: 1,
    thundurus: 1, tornadustherian: 1, thundurustherian: 1, reshiram: 1,
    zekrom: 1, landorus: 1, landorustherian: 1, kyurem: 1, kyuremblack: 1,
    kyuremwhite: 1, keldeo: 1, meloetta: 1, genesect: 1, xerneas: 1,
    yveltal: 1, zygarde: 1, diancie: 1, hoopa: 1, hoopaunbound: 1,
    silvally: 1, tapukoko: 1, tapulele: 1, tapubulu: 1, tapufini: 1,
    solgaleo: 1, lunala: 1, nihilego: 1, buzzwole: 1, pheromosa: 1,
    xurkitree: 1, celesteela: 1, kartana: 1, guzzlord: 1, necrozma: 1,
    magearna: 1
}

var fs = require('fs')
var output = fs.openSync('_data/pokemon.yml', 'w')

for (var pokemonid in formatsData) {
    var pokemon = pokedex[pokemonid]
    var format = formatsData[pokemonid]
    if (!legendaries[pokemonid] && (pokemon.prevo || !pokemon.evos || pokemon.forme || format.isNonstandard || banned[pokemonid])) continue

    var mega = false
    var tier = format.tier
    fs.writeSync(output, '- name: ' + pokemon.species + '\n')
    fs.writeSync(output, '  legendary: ' + !!legendaries[pokemonid] + '\n')
    fs.writeSync(output, '  color: ' + pokemon.color + '\n')
    fs.writeSync(output, '  types: [' + pokemon.types.join(', ') + ']\n')
    var tier = searchTier(formatsData, pokemonid, false)
    fs.writeSync(output, '  tier: ' + searchTier(formatsData, pokemonid, false) + '\n')
    fs.writeSync(output, '  doublesTier: ' + searchTier(doublesFormatsData, pokemonid, false) + '\n')
    fs.writeSync(output, '  gen: ' + gen(pokemon.num) + '\n')
    fs.writeSync(output, '  mega:\n')
    if (hasMega(pokemon)) {
        fs.writeSync(output, '    tier: ' + (searchTier(formatsData, pokemonid, true) || tier) + '\n')
        fs.writeSync(output, '    doublesTier: ' + (searchTier(doublesFormatsData, pokemonid, true) || tier) + '\n')
    }
    fs.writeSync(output, '\n')
}

fs.close(output)
<commit_msg>Ban legendary Pokemon with evolutions<commit_after>// TODO: Make this entire thing cleaner

var formatsData = require('Pokemon-Showdown/data/formats-data').BattleFormatsData
var pokedex = require('Pokemon-Showdown/data/pokedex').BattlePokedex
var items = require('Pokemon-Showdown/data/items').BattleItems
var doublesFormatsData = Object.create(formatsData)
var formats = require('Pokemon-Showdown/config/formats').Formats

var formatHandlers = {
    'Doubles OU': 'Uber',
    'Doubles UU': 'OU',
}

var banlists = {}

for (var pokemonid in doublesFormatsData) {
    doublesFormatsData[pokemonid] = Object.create(doublesFormatsData[pokemonid])
    doublesFormatsData[pokemonid].tier = 'NU'
}

formats.forEach(function searchFormats(format) {
    var tier = formatHandlers[format.name]
    if (tier) {
        format.banlist.forEach(function applyBanlist(entry) {
            var id = toId(entry)
            var item = items[id]
            if (item && item.megaEvolves) {
                doublesFormatsData[toId(item.megaStone)].tier = tier
            }
            var pokemon = doublesFormatsData[id]
            if (pokemon) {
                pokemon.tier = tier
            }
        })
    }
})

function toId(name) {
    return name.toLowerCase().replace(/[^a-z0-9]/g, "")
}

function searchTier(formatsData, pokemonid, findMega) {
    var pokemon = pokedex[pokemonid]
    var tiers = {
        Uber: 0,
        OU: 1,
        BL: 1,
        UU: 2,
        BL2: 2,
        RU: 3,
        BL3: 3,
        NU: 4,
        BL4: 4,
        PU: 5,
        New: 5,
        NFE: 5,
        LC: 5,
        'LC Uber': 5,
    }
    var reverseTier = ['Uber', 'OU', 'UU', 'RU', 'NU', 'PU']
    var evos = pokemon.evos || []
    if (findMega) {
        evos = evos.concat(pokemon.otherFormes || [])
    }
    var toSearch = evos.map(function recursiveSearch(evo) {
        return searchTier(formatsData, evo, findMega)
    }).concat(formatsData[pokemonid].tier)
    return reverseTier[Math.min.apply(Math, toSearch.map(function toTierValue(tier) {
        if (tier.charAt(0) === '(') {
            tier = tier.slice(1, -1)
        }
        return tiers[tier]
    }))]
}

function hasMega(pokemon) {
    if (pokemon.species === 'Rayquaza') {
        return false // too broken
    }
    if (pokemon.otherFormes) {
        for (var i = 0; i < pokemon.otherFormes.length; i++) {
            var id = pokemon.otherFormes[i]
            var forme = pokedex[id]
            if (forme.forme.substring(0, 4) === 'Mega') {
                return formatsData[id].tier !== "Unreleased"
            }
        }
        return false
    }
    var evos = pokemon.evos || []
    for (var i = 0; i < evos.length; i++) {
        if (hasMega(pokedex[evos[i]])) {
            return true
        }
    }
    return false
}

function gen(num) {
    if (num <= 151) return 1
    if (num <= 251) return 2
    if (num <= 386) return 3
    if (num <= 493) return 4
    if (num <= 649) return 5
    return 6
}

var banned = {
    burmy: 1, caterpie: 1, combee: 1, kricketot: 1, magikarp: 1, scatterbug: 1,
    sunkern: 1, tynamo: 1, weedle: 1, wurmple: 1, typenull: 1, cosmog: 1,
}
var legendaries = {
    articuno: 1, zapdos: 1, moltres: 1, mewtwo: 1, mew: 1, raikou: 1,
    entei: 1, suicune: 1, lugia: 1, hooh: 1, celebi: 1, regirock: 1,
    regice: 1, registeel: 1, latias: 1, latios: 1, kyogre: 1, groudon: 1,
    rayquaza: 1, jirachi: 1, deoxys: 1, deoxysattack: 1, deoxysdefense: 1,
    deoxysspeed: 1, uxie: 1, mesprit: 1, azelf: 1, dialga: 1, palkia: 1,
    heatran: 1, regigigas: 1, manaphy: 1, giratina: 1, giratinaorigin: 1,
    cresselia: 1, darkrai: 1, shaymin: 1, shayminsky: 1, arceus: 1,
    victini: 1, cobalion: 1, terrakion: 1, virizion: 1, tornadus: 1,
    thundurus: 1, tornadustherian: 1, thundurustherian: 1, reshiram: 1,
    zekrom: 1, landorus: 1, landorustherian: 1, kyurem: 1, kyuremblack: 1,
    kyuremwhite: 1, keldeo: 1, meloetta: 1, genesect: 1, xerneas: 1,
    yveltal: 1, zygarde: 1, diancie: 1, hoopa: 1, hoopaunbound: 1,
    silvally: 1, tapukoko: 1, tapulele: 1, tapubulu: 1, tapufini: 1,
    solgaleo: 1, lunala: 1, nihilego: 1, buzzwole: 1, pheromosa: 1,
    xurkitree: 1, celesteela: 1, kartana: 1, guzzlord: 1, necrozma: 1,
    magearna: 1
}

var fs = require('fs')
var output = fs.openSync('_data/pokemon.yml', 'w')

for (var pokemonid in formatsData) {
    var pokemon = pokedex[pokemonid]
    var format = formatsData[pokemonid]
    if (!legendaries[pokemonid] && (pokemon.prevo || !pokemon.evos || pokemon.forme || format.isNonstandard || banned[pokemonid])) continue

    var mega = false
    var tier = format.tier
    fs.writeSync(output, '- name: ' + pokemon.species + '\n')
    fs.writeSync(output, '  legendary: ' + !!legendaries[pokemonid] + '\n')
    fs.writeSync(output, '  color: ' + pokemon.color + '\n')
    fs.writeSync(output, '  types: [' + pokemon.types.join(', ') + ']\n')
    var tier = searchTier(formatsData, pokemonid, false)
    fs.writeSync(output, '  tier: ' + searchTier(formatsData, pokemonid, false) + '\n')
    fs.writeSync(output, '  doublesTier: ' + searchTier(doublesFormatsData, pokemonid, false) + '\n')
    fs.writeSync(output, '  gen: ' + gen(pokemon.num) + '\n')
    fs.writeSync(output, '  mega:\n')
    if (hasMega(pokemon)) {
        fs.writeSync(output, '    tier: ' + (searchTier(formatsData, pokemonid, true) || tier) + '\n')
        fs.writeSync(output, '    doublesTier: ' + (searchTier(doublesFormatsData, pokemonid, true) || tier) + '\n')
    }
    fs.writeSync(output, '\n')
}

fs.close(output)
<|endoftext|>


<commit_before>var Dog = Dog || {};

Dog.Main = (function() {
	// scene vars
	var scene, camera, renderer, orbitControls;

	// canvas capture vars
	var canvasImageData;
	var getCanvasImageData = false;
	var ONCE = 'once';

	// texture vars
	var textureBumpMapLoader, textureMapBump;

	// Should scene show helpers
	var USE_HELPERS = true;

	// Objects
	var hero;
	var sphere;
	var topVertIndexes = [];
	var animationSpeed = 2;
	var animOffset = 0;
	var elements = [];
	var elementsContainer;

	var ORIGIN = {
		x: 0,
		y: 0
	}

	var spotLight1;

	function setup() {

		textureBumpMapLoader = new THREE.TextureLoader();

		// init scene
		scene = new THREE.Scene();

		// init camera
		camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000);
		camera.position.x = -400;
		camera.position.y = 440;
		camera.position.z = 400;

		// console.log('Main.js', camera.position);

		camera.lookAt(0, 0, 0)

		// init renderer
		renderer = new THREE.WebGLRenderer({
			antialias: true,
			alpha: true
		});
		renderer.setSize(window.innerWidth, window.innerHeight);
		renderer.autoClear = false;
		renderer.shadowMap.enabled = true;

		document.body.appendChild(renderer.domElement);

		// add controls
		orbitControls = new THREE.OrbitControls(camera, renderer.domElement);

		// add window resize handler
		window.addEventListener('resize', onWindowResize, false);

		if (USE_HELPERS) scene.add(new THREE.AxisHelper(500));

		init();
	}

	function init() {

		// add content
		addLighting();
		addFloor();
		addElements();

		// init keyboard listener
		initKeyboard();

		// render
		render();
	}

	function animateElements() {
		for (var i = 0; i < elements.length; i++) {
			var element = elements[i];

			var elementRadius = Dog.Utils.distance({
				x: element.position.x,
				y: element.position.z
			}, ORIGIN);

			var elementAngle = Dog.Utils.angleBetweenPointsInRad({
				x: element.position.x,
				y: element.position.z
			}, ORIGIN);

			// Normalize to positive angle
			elementAngle += Math.PI;

			var speed = 0.005;

			elementAngle = (elementAngle + speed) % (Math.PI * 2);

			var maxCirc = 2 * (Math.PI * 2) * elementRadius;

			var elementCirc = 2 * (elementAngle - Dog.Utils.degToRad(animOffset)) * elementRadius;

			var distanceRoundCirc = Dog.Utils.map(elementCirc, 0, maxCirc, 0, (Math.PI * 4));

			element.position.x = Math.cos(elementAngle) * elementRadius;
			element.position.z = Math.sin(elementAngle) * elementRadius;

			var newScale = element.scaleClone.x * Dog.Utils.map(Math.sin(distanceRoundCirc), -1, 1, 0.3, 1.3);
			element.scale.x = element.scale.y = element.scale.z = newScale;
		}
	}

	function initKeyboard() {
		// listen for keystrokes
		document.body.addEventListener("keyup", function(event) {
			// console.info('event.keyCode', event.keyCode);

			switch (event.keyCode) {
				case 80: // p
					exportCanvasImageDataToPNG();
					break;
			}
		});
	}

	// gets image data
	function exportCanvasImageDataToPNG() {
		getCanvasImageData = true;
		render(ONCE);

		var win = window.open("", "Canvas Image");
		var canvas = renderer.domElement;
		var src = canvas.toDataURL("image/png");

		win.document.write("");
	}

	function onWindowResize() {
		// Update camera and renderer
		camera.aspect = window.innerWidth / window.innerHeight;
		camera.updateProjectionMatrix();

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

	function addLighting() {

		// Add a light
		spotLight1 = new THREE.DirectionalLight(0xffffff, 0.75);
		spotLight1.position.set(Dog.Utils.randomRange(300, 500), Dog.Utils.randomRange(300, 500), Dog.Utils.randomRange(300, 500));
		spotLight1.position.set(0, 400, 0);
		spotLight1.target.position.set(0, 0, 0);

		var shadowSize = 600;

		spotLight1.castShadow = true;
		spotLight1.shadow.mapSize.width = shadowSize * 2;
		spotLight1.shadow.mapSize.height = shadowSize * 2;
		spotLight1.shadow.camera.near = 100;
		spotLight1.shadow.camera.far = 1000;
		spotLight1.shadow.camera.left = -shadowSize / 2;
		spotLight1.shadow.camera.right = shadowSize / 2;
		spotLight1.shadow.camera.top = shadowSize / 2;
		spotLight1.shadow.camera.bottom = -shadowSize / 2;

		// if (USE_HELPERS) scene.add(new THREE.CameraHelper(spotLight1.shadow.camera));

		scene.add(spotLight1);

		// helper
		if (USE_HELPERS) scene.add(new THREE.DirectionalLightHelper(spotLight1));

		// add another spotlight
		var spotLight2 = new THREE.DirectionalLight(0xffffff, 0.125);
		spotLight2.position.set(Dog.Utils.randomRange(-300, -500), Dog.Utils.randomRange(-300, -500), Dog.Utils.randomRange(-300, -500));
		spotLight2.target.position.set(0, 0, 0);

		scene.add(spotLight2);

		// helper
		if (USE_HELPERS) scene.add(new THREE.DirectionalLightHelper(spotLight2));

		// Add and additional AmbientLight
		scene.add(new THREE.AmbientLight(0x555555));
	}

	function addElements() {

		var sphereRadius = 10;

		var howMany = 250; // 250

		var donutRadius = 200;
		var innerRadiusMax = 60;

		elementsContainer = new THREE.Object3D();
		scene.add(elementsContainer);

		var geometry = new THREE.SphereBufferGeometry(sphereRadius, 32, 32);

		for (var i = 0; i < 360; i += 15) {

			var material = new THREE.MeshPhongMaterial({
				color: new THREE.Color('hsl(' + i + ', 100%, 50%)'),
				shading: THREE.SmoothShading,
				emissive: 0x000000,
				specular: 0x666666,
				shininess: 60,
			});

			var angleDonut = Dog.Utils.degToRad(i);

			var howManyPerSlice = 14;

			for (var j = 0; j < howManyPerSlice; j++) {
				var element = new THREE.Mesh(geometry, material);

				element.index = i;

				// Position
				element.position.x = Math.cos(angleDonut) * donutRadius;
				element.position.z = Math.sin(angleDonut) * donutRadius;

				// Rotation
				element.rotation.y = -angleDonut;

				// Move on local axis
				var angleInner = ((Math.PI * 2) / howManyPerSlice) * j;

				element.translateX(Math.cos(angleInner) * innerRadiusMax);
				element.translateY(Math.sin(angleInner) * innerRadiusMax);

				// Scale relative to distance
				element.scale.x = element.scale.y = element.scale.z = Dog.Utils.map(element.position.length(), donutRadius - innerRadiusMax, donutRadius + innerRadiusMax, 0.9, 1.2);

				element.scaleClone = element.scale.clone();

				// Shadow
				element.receiveShadow = true;
				element.castShadow = true;

				element.positionClone = element.position.clone();

				elementsContainer.add(element);

				if (USE_HELPERS) element.add(new THREE.AxisHelper(25));

				elements.push(element);
			}
		}
	}

	function addFloor() {
		var floorMaterial = new THREE.MeshPhongMaterial({
			color: 0xeeeeee,
			shading: THREE.FlatShading,
			emissive: 0x666666,
			specular: 0x111111,
			shininess: 30,
		});

		var floorGeometry = new THREE.PlaneBufferGeometry(10000, 10000);
		var floor = new THREE.Mesh(floorGeometry, floorMaterial);
		floor.receiveShadow = true;
		floor.rotation.x = -Math.PI / 2;
		floor.position.y = -200;
		scene.add(floor);
	}

	function render(howManyTimes) {
		/* If we are rendering for an exportCanvasImageDataToPNG then DO NOT requestAnimationFrame as can speed up animations that are called on render */

		if (howManyTimes !== ONCE) requestAnimationFrame(render);

		animOffset = (animOffset < 360) ? animOffset += animationSpeed : 0;

		animateElements();
		// elementsContainer.rotation.y -= 0.01;

		renderer.clear();
		renderer.render(scene, camera);
		orbitControls.update();

		if (getCanvasImageData === true) {
			canvasImageData = renderer.domElement.toDataURL();
			getCanvasImageData = false;
		}
	}

	return {
		init: function() {
			setup();
		}
	};
})();<commit_msg>24 - Encapsulated elements in a slice object.<commit_after>var Dog = Dog || {};

Dog.Main = (function() {
	// scene vars
	var scene, camera, renderer, orbitControls;

	// canvas capture vars
	var canvasImageData;
	var getCanvasImageData = false;
	var ONCE = 'once';

	// texture vars
	var textureBumpMapLoader, textureMapBump;

	// Should scene show helpers
	var USE_HELPERS = false;

	// Objects
	var hero;
	var sphere;
	var topVertIndexes = [];
	var animationSpeed = 2;
	var animOffset = 0;
	var slices = [];
	var elementsContainer;

	var ORIGIN = {
		x: 0,
		y: 0
	}

	var spotLight1;

	function setup() {

		textureBumpMapLoader = new THREE.TextureLoader();

		// init scene
		scene = new THREE.Scene();

		// init camera
		camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 1, 10000);
		camera.position.x = -400;
		camera.position.y = 440;
		camera.position.z = 400;

		// console.log('Main.js', camera.position);

		camera.lookAt(0, 0, 0);

		// init renderer
		renderer = new THREE.WebGLRenderer({
			antialias: true,
			alpha: true
		});
		renderer.setSize(window.innerWidth, window.innerHeight);
		renderer.autoClear = false;
		renderer.shadowMap.enabled = true;

		document.body.appendChild(renderer.domElement);

		// add controls
		orbitControls = new THREE.OrbitControls(camera, renderer.domElement);

		// add window resize handler
		window.addEventListener('resize', onWindowResize, false);

		if (USE_HELPERS) scene.add(new THREE.AxisHelper(500));

		init();
	}

	function init() {

		// add content
		addLighting();
		addFloor();
		addElements();

		// init keyboard listener
		initKeyboard();

		// render
		render();
	}

	function animateElements() {
		for (var i = 0; i < slices.length; i++) {
			var slice = slices[i];

			var elementRadius = Dog.Utils.distance({
				x: slice.position.x,
				y: slice.position.z
			}, ORIGIN);

			var elementAngle = Dog.Utils.angleBetweenPointsInRad({
				x: slice.position.x,
				y: slice.position.z
			}, ORIGIN);

			// Normalize to positive angle
			elementAngle += Math.PI;

			var speed = 0.005;

			elementAngle = (elementAngle + speed) % (Math.PI * 2);

			var maxCirc = 2 * (Math.PI * 2) * elementRadius;

			var elementCirc = 2 * (elementAngle - Dog.Utils.degToRad(animOffset)) * elementRadius;

			var distanceRoundCirc = Dog.Utils.map(elementCirc, 0, maxCirc, 0, (Math.PI * 4));

			slice.position.x = Math.cos(elementAngle) * elementRadius;
			slice.position.z = Math.sin(elementAngle) * elementRadius;

			slice.rotation.y = -elementAngle;

			slice.rotation.z = Dog.Utils.map(Math.sin(distanceRoundCirc), -1, 1, -(Math.PI / 4), (Math.PI / 4));

			for (var j = 0; j < slice.children.length; j++) {
				var element = slice.children[j];
				var newScale = element.scaleClone.x * Dog.Utils.map(Math.sin(distanceRoundCirc), -1, 1, 0.3, 1.3);
				element.scale.x = element.scale.y = element.scale.z = newScale;
			}
		}
	}

	function initKeyboard() {
		// listen for keystrokes
		document.body.addEventListener("keyup", function(event) {
			// console.info('event.keyCode', event.keyCode);

			switch (event.keyCode) {
				case 80: // p
					exportCanvasImageDataToPNG();
					break;
			}
		});
	}

	// gets image data
	function exportCanvasImageDataToPNG() {
		getCanvasImageData = true;
		render(ONCE);

		var win = window.open("", "Canvas Image");
		var canvas = renderer.domElement;
		var src = canvas.toDataURL("image/png");

		win.document.write("");
	}

	function onWindowResize() {
		// Update camera and renderer
		camera.aspect = window.innerWidth / window.innerHeight;
		camera.updateProjectionMatrix();

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

	function addLighting() {

		// Add a light
		spotLight1 = new THREE.DirectionalLight(0xffffff, 0.75);
		spotLight1.position.set(Dog.Utils.randomRange(300, 500), Dog.Utils.randomRange(300, 500), Dog.Utils.randomRange(300, 500));
		spotLight1.position.set(0, 400, 0);
		spotLight1.target.position.set(0, 0, 0);

		var shadowSize = 600;

		spotLight1.castShadow = true;
		spotLight1.shadow.mapSize.width = shadowSize * 2;
		spotLight1.shadow.mapSize.height = shadowSize * 2;
		spotLight1.shadow.camera.near = 100;
		spotLight1.shadow.camera.far = 1000;
		spotLight1.shadow.camera.left = -shadowSize / 2;
		spotLight1.shadow.camera.right = shadowSize / 2;
		spotLight1.shadow.camera.top = shadowSize / 2;
		spotLight1.shadow.camera.bottom = -shadowSize / 2;

		// if (USE_HELPERS) scene.add(new THREE.CameraHelper(spotLight1.shadow.camera));

		scene.add(spotLight1);

		// helper
		if (USE_HELPERS) scene.add(new THREE.DirectionalLightHelper(spotLight1));

		// add another spotlight
		var spotLight2 = new THREE.DirectionalLight(0xffffff, 0.125);
		spotLight2.position.set(Dog.Utils.randomRange(-300, -500), Dog.Utils.randomRange(-300, -500), Dog.Utils.randomRange(-300, -500));
		spotLight2.target.position.set(0, 0, 0);

		scene.add(spotLight2);

		// helper
		if (USE_HELPERS) scene.add(new THREE.DirectionalLightHelper(spotLight2));

		// Add and additional AmbientLight
		scene.add(new THREE.AmbientLight(0x555555));
	}

	function addElements() {

		var sphereRadius = 10;

		var howMany = 250; // 250

		var donutRadius = 200;
		var innerRadiusMax = 60;

		elementsContainer = new THREE.Object3D();
		scene.add(elementsContainer);

		var geometry = new THREE.SphereBufferGeometry(sphereRadius, 32, 32);

		for (var i = 0; i < 360; i += 15) {
			var slice = new THREE.Object3D();
			elementsContainer.add(slice);

			var material = new THREE.MeshPhongMaterial({
				color: new THREE.Color('hsl(' + i + ', 100%, 50%)'),
				shading: THREE.SmoothShading,
				emissive: 0x000000,
				specular: 0x666666,
				shininess: 60,
			});

			var angleDonut = Dog.Utils.degToRad(i);

			var howManyPerSlice = 14;

			slice.position.x = Math.cos(angleDonut) * donutRadius;
			slice.position.z = Math.sin(angleDonut) * donutRadius;

			slice.rotation.y = -angleDonut;

			slices.push(slice);

			if (USE_HELPERS) slice.add(new THREE.AxisHelper(25));

			for (var j = 0; j < howManyPerSlice; j++) {

				var element = new THREE.Mesh(geometry, material);

				element.index = i;

				// Move on local axis
				var angleInner = ((Math.PI * 2) / howManyPerSlice) * j;

				element.position.x = Math.cos(angleInner) * innerRadiusMax;
				element.position.y = Math.sin(angleInner) * innerRadiusMax;

				var distance = slice.position.length() + element.position.x;

				// Scale relative to distance
				element.scale.x = element.scale.y = element.scale.z = Dog.Utils.map(distance, (donutRadius - innerRadiusMax), (donutRadius + innerRadiusMax), 0.7, 1.2);

				// console.log('Main.js', 'element.position.length()', element.position.length());

				element.scaleClone = element.scale.clone();

				// Shadow
				element.receiveShadow = true;
				element.castShadow = true;

				element.positionClone = element.position.clone();

				slice.add(element);

				if (USE_HELPERS) element.add(new THREE.AxisHelper(25));

			}
		}
	}

	function addFloor() {
		var floorMaterial = new THREE.MeshPhongMaterial({
			color: 0xeeeeee,
			shading: THREE.FlatShading,
			emissive: 0x666666,
			specular: 0x111111,
			shininess: 30,
		});

		var floorGeometry = new THREE.PlaneBufferGeometry(10000, 10000);
		var floor = new THREE.Mesh(floorGeometry, floorMaterial);
		floor.receiveShadow = true;
		floor.rotation.x = -Math.PI / 2;
		floor.position.y = -200;
		scene.add(floor);
	}

	function render(howManyTimes) {
		/* If we are rendering for an exportCanvasImageDataToPNG then DO NOT requestAnimationFrame as can speed up animations that are called on render */

		if (howManyTimes !== ONCE) requestAnimationFrame(render);

		animOffset = (animOffset < 360) ? animOffset += animationSpeed : 0;

		animateElements();

		renderer.clear();
		renderer.render(scene, camera);
		orbitControls.update();

		if (getCanvasImageData === true) {
			canvasImageData = renderer.domElement.toDataURL();
			getCanvasImageData = false;
		}
	}

	return {
		init: function() {
			setup();
		}
	};
})();<|endoftext|>


<commit_before>import VueRecaptcha from '../../src'
import { mount } from 'avoriaz'

const WIDGET_ID = 'widgetId'

function createMock () {
  return {
    render: jest.fn(function (ele, options) {
      // Save the callback
      this._verify = options.callback
      this._expire = options['expired-callback']
      return WIDGET_ID
    }),
    execute: jest.fn(function () {
      this._verify()
    }),
    reset: jest.fn()
  }
}

describe('Example spec', () => {
  let wrapper
  let verify
  let expired
  beforeEach(() => {
    window.grecaptcha = createMock()
    verify = jest.fn()
    expired = jest.fn()
    wrapper = mount(VueRecaptcha, {
      propsData: { sitekey: 'sitekey' }
    })
    wrapper.vm.$on('verify', verify)
    wrapper.vm.$on('expired', expired)
  })

  it('Should render recaptcha', () => {
    expect(window.grecaptcha.render).toBeCalled()
    expect(wrapper.vm.$widgetId).toBe(WIDGET_ID)
  })

  it('Should call execute', () => {
    wrapper.vm.execute()
    expect(window.grecaptcha.execute).toBeCalledWith(WIDGET_ID)
  })

  it('Should call reset', () => {
    wrapper.vm.reset()
    expect(window.grecaptcha.reset).toBeCalledWith(WIDGET_ID)
  })

  it('Should emit verify', () => {
    window.grecaptcha._verify()
    expect(verify).toBeCalled()
  })

  it('Should emit expired', () => {
    window.grecaptcha._expire()
    expect(expired).toBeCalled()
  })
})
<commit_msg>spec: Fix<commit_after>import VueRecaptcha from '../../src'
import { mount } from '@vue/test-utils'

const WIDGET_ID = 'widgetId'

function createMock () {
  return {
    render: jest.fn(function (ele, options) {
      // Save the callback
      this._verify = options.callback
      this._expire = options['expired-callback']
      return WIDGET_ID
    }),
    execute: jest.fn(function () {
      this._verify()
    }),
    reset: jest.fn()
  }
}

describe('Example spec', () => {
  let wrapper
  let verify
  let expired
  beforeEach(() => {
    window.grecaptcha = createMock()
    verify = jest.fn()
    expired = jest.fn()
    wrapper = mount(VueRecaptcha, {
      propsData: { sitekey: 'sitekey' }
    })
    wrapper.vm.$on('verify', verify)
    wrapper.vm.$on('expired', expired)
  })

  it('Should render recaptcha', () => {
    expect(window.grecaptcha.render).toBeCalled()
    expect(wrapper.vm.$widgetId).toBe(WIDGET_ID)
  })

  it('Should call execute', () => {
    wrapper.vm.execute()
    expect(window.grecaptcha.execute).toBeCalledWith(WIDGET_ID)
  })

  it('Should call reset', () => {
    wrapper.vm.reset()
    expect(window.grecaptcha.reset).toBeCalledWith(WIDGET_ID)
  })

  it('Should emit verify', () => {
    window.grecaptcha._verify()
    expect(verify).toBeCalled()
  })

  it('Should emit expired', () => {
    window.grecaptcha._expire()
    expect(expired).toBeCalled()
  })
})
<|endoftext|>


<commit_before>var locastyle = (function() {
  'use strict';

  function init() {
    locastyle.breakpoints.init();
    loadModules();
    locastyle.general.init();
    locastyle.sidebars.init();
    locastyle.btnGroup.init();
    locastyle.datepicker.init();
    locastyle.form.togglePasswordField();
  }

  function loadModules() {
    var modules = getModules();
    for (var i in modules) {
      locastyle[modules[i]].init();
      // I know it is a console.log, let it to be here for a while
      console.log("Locastyle: module [" + modules[i] + "] successfully initialized.")
    }
  }

  function getModules() {
    var modules = [];
    $("[data-ls-module]").each(function () {
      var module = $(this).data("ls-module");
      if ( !( modules.indexOf(module) > -1 ) ) {
        modules.push(module);
      }
    })
    return modules;
  }

  return {
    init: init
  };

}());

var ls = locastyle;

$(window).load(function() {
  locastyle.init();
});<commit_msg>jshint initializer<commit_after>var locastyle = (function() {
  'use strict';

  function init() {
    locastyle.breakpoints.init();
    loadModules();
    locastyle.general.init();
    locastyle.sidebars.init();
    locastyle.btnGroup.init();
    locastyle.datepicker.init();
    locastyle.form.togglePasswordField();
  }

  function loadModules() {
    var modules = getModules();
    for (var i in modules) {
      locastyle[modules[i]].init();
      // I know it is a console.log, let it to be here for a while
      console.log("Locastyle: module [" + modules[i] + "] successfully initialized.");
    }
  }

  function getModules() {
    var modules = [];
    $("[data-ls-module]").each(function () {
      var module = $(this).data("ls-module");
      if ( modules.indexOf(module) === -1 ) {
        modules.push(module);
      }
    });
    return modules;
  }

  return {
    init: init
  };

}());

var ls = locastyle;

$(window).load(function() {
  locastyle.init();
});<|endoftext|>