text stringlengths 7 3.69M |
|---|
/**
* LINKURIOUS CONFIDENTIAL
* Copyright Linkurious SAS 2012 - 2018
*/
'use strict';
// external libs
const Promise = require('bluebird');
// services
const LKE = require('../../../../services');
const Access = LKE.getAccess();
const Utils = LKE.getUtils();
const Errors = LKE.getErrors();
const GroupDAO = LKE.getGroupDAO();
const UserDAO = LKE.getUserDAO();
const AccessRightDAO = LKE.getAccessRightDAO();
// locals
const api = require('../../api');
/**
* @apiDefine authenticated Any authenticated user can use this API.
*/
/**
* @apiDefine __guest The guest user can use this API if guest mode is allowed.
*/
/**
* @typedef {object} group Group
* @property {number} group.id ID of the group
* @property {string} group.sourceKey Key of the data-source of the group
* @property {string} group.name Name of the group
* @property {boolean} group.builtin Whether the group was created internally by Linkurious
*/
/**
* @typedef {object} preferences Preferences of the user
* @property {boolean} preferences.pinOnDrag Whether to pin nodes automatically when they are moved manually
* @property {string} preferences.locale Language and region identifier of the user (e.g. 'fr_BE' for 'French language in Belgium')
* @property {boolean} preferences.uiWorkspaceSearch Whether to enable search in the workspace
* @property {boolean} preferences.uiExport Whether to show the export tool in menus
* @property {boolean} preferences.uiDesign Whether to show the design panel at all
* @property {boolean} preferences.uiLayout Whether to show the layout button/menu at all
* @property {boolean} preferences.uiEdgeSearch Whether to show edge search tool in the 'find' bar
* @property {boolean} preferences.uiTooltip Whether to show node/edge tooltips in their context menu
* @property {boolean} preferences.uiShortestPath Whether to show the shortest-path tool in the 'find' bar
* @property {boolean} preferences.uiCollapseNode Whether to show the 'collapse' button in the toolbar
* @property {boolean} preferences.uiScreenshot Whether to show the screenshot tool in menus
* @property {boolean} preferences.uiCaptionConfig Whether to show the caption config tab in the design panel
* @property {boolean} preferences.uiTooltipConfig Whether to show the tooltip config tab in the design panel
* @property {boolean} preferences.uiVisualizationPanel Whether to show the visualization panel (visualization name, selection, actions)
* @property {boolean} preferences.uiNodeList Whether to show the nodes list (bottom left)
* @property {boolean} preferences.uiEdgeList Whether to show the edges list (bottom left)
* @property {boolean} preferences.uiSimpleLayout Whether to show a layout button instead of the full layout menu
*/
module.exports = function(app) {
app.all('/api/admin/users*', api.proxy(req => {
// the user needs the action admin.users on any data-source
return Access.canManageUsers(req);
}));
app.all('/api/admin/groups*', api.proxy(req => {
return Access.canManageUsers(req);
}));
app.all('/api/admin/:dataSource/groups*', api.proxy(req => {
// the user needs the action admin.users on `dataSource`
return Access.canManageUsers(req, req.param('dataSource'));
}));
// ------------------------------------------------------------------------------------------
// Users
// ------------------------------------------------------------------------------------------
/** @apiDefine ReturnUser
*
* @apiSuccess {number} id ID of the user
* @apiSuccess {string} username Username of the user
* @apiSuccess {string} email E-mail of the user
* @apiSuccess {string} source Source of the user (`"local"`, `"ldap"`, `"oauth2"`, etc.)
* @apiSuccess {type:group[]} groups Groups the user belongs to
* @apiSuccess {type:preferences} preferences Preferences of the user
* @apiSuccess {object} actions Arrays of authorized actions indexed by data-source key.
* The special key `"*"` lists actions authorized on all the data-sources
* @apiSuccess {object} accessRights Arrays of authorized node categories and edge types indexed by data-source key, by type and by right.
* The special key `"*"` lists access rights authorized on all the data-sources
* @apiSuccess {string} createdAt Creation date in ISO-8601 format
* @apiSuccess {string} updatedAt Last update date in ISO-8601 format
*
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* "id": 1,
* "username": "Unique user",
* "email": "user@linkurio.us",
* "source": "local",
* "groups": [
* {
* "id": 1,
* "name": "admin",
* "builtin": true,
* "sourceKey": "*"
* }
* ],
* "preferences": {
* "pinOnDrag": false,
* "locale": "en-US"
* },
* "actions": {
* "*": [
* "admin.users",
* "admin.alerts",
* "admin.connect",
* "admin.index",
* "admin.app",
* "admin.report",
* "admin.users.delete",
* "admin.config",
* "rawReadQuery",
* "rawWriteQuery"
* ]
* },
* "accessRights": {
* "*": {
* "nodes": {
* "edit": [],
* "write": ["*"]
* },
* "edges": {
* "edit": [],
* "write": ["*"]
* },
* "alerts": {
* "read": ["*"]
* }
* }
* },
* "createdAt": "2016-05-16T08:23:35.730Z",
* "updatedAt": "2016-05-16T08:23:45.730Z"
* }
*/
/** @apiDefine ReturnUserOnCreate
*
* @apiSuccess(Success 201) {number} id ID of the user
* @apiSuccess(Success 201) {string} username Username of the user
* @apiSuccess(Success 201) {string} email E-mail of the user
* @apiSuccess(Success 201) {string} source Source of the user (`"local"`, `"ldap"`, `"oauth2"`, etc.)
* @apiSuccess(Success 201) {type:group[]} groups Groups the user belongs to
* @apiSuccess(Success 201) {type:preferences} preferences Preferences of the user
* @apiSuccess(Success 201) {object} actions Arrays of authorized actions indexed by data-source key.
* The special key `"*"` lists actions authorized on all the data-sources
* @apiSuccess(Success 201) {object} accessRights Arrays of authorized node categories and edge types indexed by data-source key, by type and by right.
* The special key `"*"` lists access rights authorized on all the data-sources
* @apiSuccess(Success 201) {string} createdAt Creation date in ISO-8601 format
* @apiSuccess(Success 201) {string} updatedAt Last update date in ISO-8601 format
*
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 201 Created
* {
* "id": 2,
* "username": "newUser",
* "email": "new@linkurio.us",
* "source": "local",
* "groups": [
* {
* "id": 2,
* "name": "source manager",
* "builtin": true,
* "sourceKey": "584f2569"
* }
* ],
* "preferences": {
* "pinOnDrag": false,
* "locale": "en-US"
* },
* "actions": {
* "*": [],
* "584f2569": [
* "admin.users",
* "admin.alerts",
* "admin.connect",
* "admin.index",
* "rawReadQuery",
* "rawWriteQuery"
* ]
* },
* "accessRights": {
* "*": {
* "nodes": {
* "edit": [],
* "write": []
* },
* "edges": {
* "edit": [],
* "write": []
* },
* "alerts": {
* "read": []
* }
* },
* "584f2569": {
* "nodes": {
* "edit": [],
* "write": ["*"]
* },
* "edges": {
* "edit": [],
* "write": ["*"]
* },
* "alerts": {
* "read": ["*"]
* }
* }
* },
* "createdAt": "2016-05-16T08:23:35.730Z",
* "updatedAt": "2016-05-16T08:23:35.730Z"
* }
*/
/**
* @api {get} /api/admin/users/:id Get a user
* @apiName GetUser
* @apiGroup Users
* @apiVersion 1.0.0
* @apiPermission action:admin.users
*
* @apiDescription Get a user by id.
*
* @apiParam {number} id ID of the user
*
* @apiUse ReturnUser
*/
app.get('/api/admin/users/:id', api.respond(req => {
return UserDAO.getUser(
Utils.tryParsePosInt(req.param('id'), 'id')
);
}));
/**
* @api {post} /api/admin/users Create a user
* @apiName CreateUser
* @apiGroup Users
* @apiPermission action:admin.users
* @apiVersion 1.0.0
*
* @apiDescription Add a new user.
*
* @apiParam {string} username Username of the user
* @apiParam {string} email E-mail of the user
* @apiParam {string} password Password of the user
* @apiParam {number[]} [groups] IDs of the groups the user belong to
*
* @apiUse ReturnUserOnCreate
*/
app.post('/api/admin/users', api.respond(req => {
return UserDAO.createUser(
req.param('username'),
req.param('email'),
req.param('password'),
req.param('groups'),
'local',
Access.getUserCheck(req)
);
}, 201));
/**
* @api {patch} /api/admin/users/:id Update a user
* @apiName UpdateUser
* @apiGroup Users
* @apiPermission action:admin.users
* @apiVersion 1.0.0
*
* @apiDescription Update a user.
*
* @apiParam {number} id ID of the user
* @apiParam {string} [username] New username of the user
* @apiParam {string} [email] New e-mail of the user
* @apiParam {string} [password] New password of the user
* @apiParam {type:preferences} [preferences] New preferences of the user
* @apiParam {number[]} [addedGroups] IDs of the groups to add to the user
* @apiParam {number[]} [removedGroups] IDs of the groups to remove from the user
*
* @apiUse ReturnUser
*/
app.patch('/api/admin/users/:id', api.respond(req => {
return UserDAO.updateUser(
Utils.tryParsePosInt(req.param('id'), 'id'),
{
username: req.param('username'),
password: req.param('password'),
email: req.param('email'),
preferences: req.param('preferences'),
addedGroups: req.param('addedGroups'),
removedGroups: req.param('removedGroups')
},
Access.getUserCheck(req)
);
}));
/**
* @api {delete} /api/admin/users/:id Delete a user
* @apiName DeleteUser
* @apiGroup Users
* @apiPermission action:admin.users.delete
* @apiVersion 1.0.0
*
* @apiDescription Delete a user.
*
* @apiParam {number} id ID of the user
*
* @apiSuccessExample {none} Success-Response:
* HTTP/1.1 204 No Content
*/
app.delete('/api/admin/users/:id', api.respond(req => {
return Access.hasAction(req, 'admin.users.delete').then(() => {
return UserDAO.deleteUser(
Utils.tryParsePosInt(req.param('id'), 'id'),
Access.getUserCheck(req)
);
});
}, 204));
// ------------------------------------------------------------------------------------------
// Groups
// ------------------------------------------------------------------------------------------
/**
* @apiDefine ReturnGroup
*
* @apiSuccess {number} id ID of the group
* @apiSuccess {string} name Name of the group
* @apiSuccess {boolean} builtin Whether the group was created internally by Linkurious
* @apiSuccess {string} sourceKey Key of the data-source
* @apiSuccess {number} userCount Number of users in the group
* @apiSuccess {string} createdAt Creation date in ISO-8601 format
* @apiSuccess {string} updatedAt Last update date in ISO-8601 format
* @apiSuccess {object[]} accessRights List of access rights
* @apiSuccess {string="read","write","edit","do","none"} accessRights.type Type of the right
* @apiSuccess {string="nodeCategory","edgeType","alert","action"} accessRights.targetType Type of the target
* @apiSuccess {string} accessRights.targetName Name of the target (node category, edge label, alert id or action name)
*
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* "id": 30,
* "name": "customGroup",
* "builtin": false,
* "sourceKey": "584f2569",
* "userCount": 2,
* "createdAt": "2016-05-16T08:23:35.730Z",
* "updatedAt": "2016-05-16T08:23:35.730Z",
* "accessRights": [
* {
* "type": "edit",
* "targetType": "nodeCategory",
* "targetName": "Movie"
* },
* {
* "type": "read",
* "targetType": "nodeCategory",
* "targetName": "Person"
* },
* {
* "type": "read",
* "targetType": "edgeType",
* "targetName": "ACTED_IN"
* },
* {
* "type": "do",
* "targetType": "actions",
* "targetName": "admin.connect"
* }
* ]
* }
*/
/**
* @apiDefine ReturnGroupOnCreate
*
* @apiSuccess(Success 201) {number} id ID of the group
* @apiSuccess(Success 201) {string} name Name of the group
* @apiSuccess(Success 201) {boolean} builtin Whether the group was created internally by Linkurious
* @apiSuccess(Success 201) {string} sourceKey Key of the data-source
* @apiSuccess(Success 201) {number} userCount Number of users in the group
* @apiSuccess(Success 201) {string} createdAt Creation date in ISO-8601 format
* @apiSuccess(Success 201) {string} updatedAt Last update date in ISO-8601 format
* @apiSuccess(Success 201) {object[]} accessRights List of access rights
* @apiSuccess(Success 201) {string="read","write","edit","do","none"} accessRights.type Type of the right
* @apiSuccess(Success 201) {string="nodeCategory","edgeType","alert","action"} accessRights.targetType Type of the target
* @apiSuccess(Success 201) {string} accessRights.targetName Name of the target (node category, edge label, alert id or action name)
*
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 201 Created
* {
* "id": 31,
* "name": "newGroup",
* "builtin": false,
* "sourceKey": "584f2569",
* "userCount": 0,
* "createdAt": "2016-05-16T08:23:35.730Z",
* "updatedAt": "2016-05-16T08:23:35.730Z",
* "accessRights": [
* {
* "type": "none",
* "targetType": "nodeCategory",
* "targetName": "Movie"
* },
* {
* "type": "none",
* "targetType": "nodeCategory",
* "targetName": "Person"
* },
* {
* "type": "none",
* "targetType": "edgeType",
* "targetName": "ACTED_IN"
* }
* ]
* }
*/
/**
* @api {get} /api/admin/:dataSource/groups/:id Get a group
* @apiName GetGroup
* @apiGroup Users
* @apiPermission action:admin.users
* @apiVersion 1.0.0
*
* @apiDescription Get a group.
*
* @apiParam {string} dataSource Key of the data-source
* @apiParam {number} id ID of the group
*
* @apiUse ReturnGroup
*/
app.get('/api/admin/:dataSource/groups/:id', api.respond(req => {
return GroupDAO.getGroup(
Utils.tryParsePosInt(req.param('id'), 'id'),
req.param('dataSource')
);
}));
/**
* @api {get} /api/admin/:dataSource/groups Get all groups
* @apiName GetGroups
* @apiGroup Users
* @apiPermission action:admin.users
* @apiVersion 1.0.0
*
* @apiDescription Get all the groups within a data-source.
*
* @apiParam {string} dataSource Key of the data-source
* @apiParam {boolean} [with_access_rights] Whether to include the access rights
*
* @apiSuccess {object[]} groups List of groups
* @apiSuccess {number} groups.id ID of the group
* @apiSuccess {string} groups.name Name of the group
* @apiSuccess {boolean} groups.builtin Whether the group was created internally by Linkurious
* @apiSuccess {string} groups.sourceKey Key of the data-source
* @apiSuccess {number} groups.userCount Number of users in the group
* @apiSuccess {string} groups.createdAt Creation date in ISO-8601 format
* @apiSuccess {string} groups.updatedAt Last update date in ISO-8601 format
* @apiSuccess {object[]} [groups.accessRights] List of access rights
* @apiSuccess {string="read","write","edit","do","none"} groups.accessRights.type Type of the right
* @apiSuccess {string="nodeCategory","edgeType","alert","action"} groups.accessRights.targetType Type of the target
* @apiSuccess {string} groups.accessRights.targetName Name of the target (node category, edge label, alert id or action name)
*
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* [
* {
* "id": 1,
* "name": "admin",
* "builtin": true,
* "sourceKey": "*",
* "userCount": 1,
* "createdAt": "2016-05-16T08:23:35.730Z",
* "updatedAt": "2016-05-16T08:23:35.730Z"
* },
* {
* "id": 2,
* "name": "read",
* "builtin": true,
* "sourceKey": "584f2569",
* "userCount": 1,
* "createdAt": "2016-05-16T08:23:35.730Z",
* "updatedAt": "2016-05-16T08:23:35.730Z"
* },
* {
* "id": 3,
* "name": "read and edit",
* "builtin": true,
* "sourceKey": "584f2569",
* "userCount": 0,
* "createdAt": "2016-05-16T08:23:35.730Z",
* "updatedAt": "2016-05-16T08:23:35.730Z"
* },
* {
* "id": 4,
* "name": "read, edit and delete",
* "builtin": true,
* "sourceKey": "584f2569",
* "userCount": 0,
* "createdAt": "2016-05-16T08:23:35.730Z",
* "updatedAt": "2016-05-16T08:23:35.730Z"
* },
* {
* "id": 5,
* "name": "source manager",
* "builtin": true,
* "sourceKey": "584f2569",
* "userCount": 0,
* "createdAt": "2016-05-16T08:23:35.730Z",
* "updatedAt": "2016-05-16T08:23:35.730Z"
* },
* {
* "id": 6,
* "name": "custom group",
* "builtin": false,
* "sourceKey": "584f2569",
* "userCount": 0,
* "createdAt": "2016-05-16T08:23:35.730Z",
* "updatedAt": "2016-05-16T08:23:35.730Z"
* }
* ]
*/
app.get('/api/admin/:dataSource/groups', api.respond(req => {
return GroupDAO.getGroups(
req.param('dataSource'),
Utils.parseBoolean(req.param('with_access_rights'))
);
}));
/**
* @api {post} /api/admin/:dataSource/groups Create a group
* @apiName CreateGroup
* @apiGroup Users
* @apiPermission action:admin.users
* @apiVersion 1.0.0
*
* @apiDescription Add a new group.
*
* @apiParam {string} dataSource Key of the data-source
* @apiParam {string} name Name of the group
*
* @apiUse ReturnGroupOnCreate
*/
app.post('/api/admin/:dataSource/groups', api.respond(req => {
return GroupDAO.createGroup(
req.param('name'),
req.param('dataSource')
);
}, 201));
/**
* @api {patch} /api/admin/:dataSource/groups/:id Rename a group
* @apiName RenameGroup
* @apiGroup Users
* @apiPermission action:admin.users
* @apiVersion 1.0.0
*
* @apiDescription Rename a group.
*
* @apiParam {string} dataSource Key of the data-source
* @apiParam {number} id ID of the group
* @apiParam {string} name Name of the group
*
* @apiUse ReturnGroup
*/
app.patch('/api/admin/:dataSource/groups/:id', api.respond(req => {
return GroupDAO.renameGroup(
Utils.tryParsePosInt(req.param('id'), 'id'),
req.param('dataSource'),
req.param('name')
);
}));
/**
* @api {delete} /api/admin/:dataSource/groups/:id Delete a group
* @apiName DeleteGroup
* @apiGroup Users
* @apiPermission action:admin.users
* @apiVersion 1.0.0
*
* @apiDescription Delete a group.
*
* @apiParam {string} dataSource Key of the data-source
* @apiParam {number} id ID of the group
*
* @apiSuccessExample {none} Success-Response:
* HTTP/1.1 204 No Content
*/
app.delete('/api/admin/:dataSource/groups/:id', api.respond(req => {
return GroupDAO.deleteGroup(
Utils.tryParsePosInt(req.param('id'), 'id'),
req.param('dataSource')
);
}, 204));
// ------------------------------------------------------------------------------------------
// Access Rights
// ------------------------------------------------------------------------------------------
/**
* @api {get} /api/admin/groups/rights_info Get all access rights options
* @apiName GetAccessRightsInfo
* @apiGroup Users
* @apiPermission action:admin.users
* @apiVersion 1.0.0
*
* @apiDescription Get all the possible access rights options: `types`, `targetTypes` and
* `actions`.
*
* @apiSuccess {string[]} types All the possible right types
* @apiSuccess {string[]} targetTypes All the possible target types
* @apiSuccess {object[]} actions All the possible actions
* @apiSuccess {string} actions.key Key of the action
* @apiSuccess {string} actions.description Description of the action
*
* @apiSuccessExample {json} Success-Response:
* HTTP/1.1 200 OK
* {
* "types": ["read", "edit", "write", "do", "none"],
* "targetTypes": ["nodeCategory", "edgeType", "action", "alert"],
* "actions": ["admin.connect", "admin.index", "admin.users", "admin.alerts", "rawReadQuery", "rawWriteQuery"]
* }
*/
app.get('/api/admin/groups/rights_info', api.respond(() => {
if (!LKE.isEnterprise()) {
return Errors.business('not_implemented', undefined, true);
}
return Promise.resolve({
types: AccessRightDAO.listRightTypes(),
targetTypes: AccessRightDAO.listTargetTypes(),
actions: AccessRightDAO.listActions()
});
}));
/**
* @api {put} /api/admin/:dataSource/groups/:id/access_rights Set access rights
* @apiName PutAccessRights
* @apiGroup Users
* @apiPermission action:admin.users
* @apiVersion 1.0.0
*
* @apiDescription Set access rights on a group. Use `"[no_category]"` as `targetName` to set the
* access right for nodes with no categories.
*
* @apiParam {string} dataSource Key of of the data-source
* @apiParam {number} groupId ID of the group
* @apiParam {object[]} accessRights List of access rights
* @apiParam {string="read","write","edit","do","none"} accessRights.type Type of the right
* @apiParam {string="nodeCategory","edgeType","alert","action"} accessRights.targetType Type of the target
* @apiParam {string} accessRights.targetName Name of the target (node category, edge label, alert id or action name)
* @apiParam {boolean} [validateAgainstSchema] Whether the access rights will be checked to be of node categories or edge types in the schema
*
* @apiSuccessExample {none} Success-Response:
* HTTP/1.1 204 No Content
*/
app.put('/api/admin/:dataSource/groups/:groupId/access_rights', api.respond(req => {
return GroupDAO.setRightsOnGroup(
Utils.tryParsePosInt(req.param('groupId'), 'groupId'),
req.param('dataSource'),
req.param('accessRights'),
req.param('validateAgainstSchema')
);
}, 204));
/**
* @api {delete} /api/admin/:dataSource/groups/:id/access_rights Delete access right
* @apiName DeleteAccessRight
* @apiGroup Users
* @apiPermission action:admin.users
* @apiVersion 1.0.0
*
* @apiDescription Delete an access right from a group.
*
* @apiParam {string} dataSource Key of of the data-source
* @apiParam {number} groupId ID of the group
* @apiParam {string="nodeCategory","edgeType","alert","action"} targetType Type of the target
* @apiParam {string} targetName Name of the target (node category, edge label, alert id or action name)
*
* @apiSuccessExample {none} Success-Response:
* HTTP/1.1 204 No Content
*/
app.delete('/api/admin/:dataSource/groups/:groupId/access_rights', api.respond(req => {
return GroupDAO.deleteRightOnGroup(
Utils.tryParsePosInt(req.param('groupId'), 'groupId'),
req.param('dataSource'),
req.param('targetType'),
req.param('targetName')
);
}, 204));
};
|
export default {
isEmptyObject(object) {
for (let key in object) {
return false;
}
return true; // Empty
},
toggleDocumentScroll() {
let doc = document.getElementsByTagName("html")[0];
doc.classList.toggle("unscrollable");
}
}; |
import Phaser from 'phaser';
export default class IntroScene extends Phaser.Scene {
constructor() {
super('Intro');
}
create() {
this.add.image(400, 300, 'introBg');
this.introText = this.add.text(200, 0, 'Introduction', { fontSize: '34px', fill: '#fff' });
this.createdByText = this.add.text(200, 0, 'In year 2038,\nscience made one more mistake. \n After trying to create a medicine to heal humanity\'s worst enemy,\ncalled Virus-8493, \n one explosion was enough to\nspread the germ and infect thousands of people.\nNowadays, infected people are walking around \n like living-dead creatures, ready to conquer the world \n and extinct human race.\nThey have managed to declare a some kind of\ncaptain among them who cannot \n fill his hunger of human flesh.\nHis name is Slaughter King\nand he will try his best\nso there wont be any HUMAN left on planet Earth....', { fontSize: '20px', fill: '#fff', align: 'center' });
this.zone = this.add.zone(400, 300, 800, 600);
this.keySpace = this.input.keyboard.addKey(Phaser.Input.Keyboard.KeyCodes.SPACE);
this.skipText = this.add.text(10, 10, 'Press Space to skip', { fontSize: '12px', fill: '#fff' });
Phaser.Display.Align.In.Center(
this.introText,
this.zone,
);
Phaser.Display.Align.In.Center(
this.createdByText,
this.zone,
);
this.createdByText.setY(650);
this.introTween = this.tweens.add({
targets: this.introText,
y: -200,
duration: 5000,
delay: 2000,
});
this.createdByTween = this.tweens.add({
targets: this.createdByText,
y: -400,
duration: 25000,
delay: 2000,
onComplete: (() => {
this.scene.start('Title');
}),
});
this.model = this.sys.game.globals.model;
if (this.model.musicOn === true && this.model.bgMusicPlaying === false) {
this.bgMusic = this.sound.add('bgMusic', { volume: 0.5, loop: true });
this.bgMusic.play();
this.model.bgMusicPlaying = true;
this.sys.game.globals.bgMusic = this.bgMusic;
}
}
update() {
if (this.keySpace.isDown) {
this.scene.start('Title');
}
}
} |
import fetch from 'isomorphic-fetch';
import config from './config';
const v2url = `${config.getApiUrl().replace('v1', 'v2')}`;
export const requestIssues = () => {
return fetch(`${v2url}/flaggedIssues`, {
method: 'GET',
headers: {
'x-access-token': config.getToken(),
},
});
};
export const postIssue = (issue) => {
return fetch(`${v2url}/flaggedIssues`, {
method: 'POST',
headers: {
'x-access-token': config.getToken(),
'Content-Type': 'application/json',
},
body: JSON.stringify(issue),
});
};
export const deleteIssue = (id) => {
return fetch(`${v2url}/flaggedIssues/${id}`, {
method: 'DELETE',
headers: {
'x-access-token': config.getToken(),
'Content-Type': 'application/json',
},
});
};
export const updateIssue = (id, issueData) => {
return fetch(`${v2url}/flaggedIssues/${id}`, {
method: 'PUT',
headers: {
'x-access-token': config.getToken(),
'Content-Type': 'application/json',
},
body: JSON.stringify(issueData),
});
};
|
var Matrix4 = require('./KTMatrix4');
var Color = require('./KTColor');
var Vector3 = require('./KTVector3');
var KTMath = require('./KTMath');
function CameraOrtho(width, height, znear, zfar){
this.__ktcamera = true;
this.position = new Vector3(0.0, 0.0, 0.0);
this.upVector = new Vector3(0.0, 1.0, 0.0);
this.lookAt(new Vector3(0.0, 0.0, -1.0));
this.locked = false;
this.width = width;
this.height = height;
this.znear = znear;
this.zfar = zfar;
this.controls = null;
this.setOrtho();
}
module.exports = CameraOrtho;
CameraOrtho.prototype.setOrtho = function(){
var C = 2.0 / this.width;
var R = 2.0 / this.height;
var A = -2.0 / (this.zfar - this.znear);
var B = -(this.zfar + this.znear) / (this.zfar - this.znear);
this.perspectiveMatrix = new Matrix4(
C, 0, 0, 0,
0, R, 0, 0,
0, 0, A, B,
0, 0, 0, 1
);
};
CameraOrtho.prototype.lookAt = function(vector3){
if (!vector3.__ktv3) throw "Can only look to a vector3";
var forward = Vector3.vectorsDifference(this.position, vector3).normalize();
var left = this.upVector.cross(forward).normalize();
var up = forward.cross(left).normalize();
var x = -left.dot(this.position);
var y = -up.dot(this.position);
var z = -forward.dot(this.position);
this.transformationMatrix = new Matrix4(
left.x, left.y, left.z, x,
up.x, up.y, up.z, y,
forward.x, forward.y, forward.z, z,
0, 0, 0, 1
);
return this;
};
CameraOrtho.prototype.setControls = function(cameraControls){
if (!cameraControls.__ktCamCtrls) throw "Is not a valid camera controls object";
var zoom = Vector3.vectorsDifference(this.position, cameraControls.target).length();
this.controls = cameraControls;
cameraControls.camera = this;
cameraControls.zoom = zoom;
cameraControls.angle.x = KTMath.get2DAngle(cameraControls.target.x, cameraControls.target.z,this.position.x, this.position.z);
cameraControls.angle.y = KTMath.get2DAngle(0, this.position.y, zoom, cameraControls.target.y);
cameraControls.setCameraPosition();
return this;
};
|
import React from "react";
import "./App.scss";
import {AppStore} from "./Store";
import {Person} from "./Person";
export const App = () => {
const {name, title} = AppStore.useState(state => state.attributes)
return (
<div className="app">
<p>{name}</p>
<p>{title}</p>
<Person/>
</div>
);
}
|
import React, { Component } from "react";
import { Grid,
Row,
Col,
} from "react-bootstrap";
import { Card } from "components/Card/Card.jsx";
import { FormInputs } from "components/FormInputs/FormInputs.jsx";
import Button from "components/CustomButton/CustomButton.jsx";
import _ from "lodash";
//Redux
import { connect } from 'react-redux';
import {login,getOverview} from '../../redux/actions/actionCreater';
import { bindActionCreators } from 'redux';
import translator from "../../middleware/translator";
//Api
import request from "../../api/request";
import endpoints from "../../api/endpoints";
const { users } = endpoints;
class Login extends Component {
constructor(props){
super(props)
this.state = {email:"",password:"",formError:""};
this.formError = this.formError.bind(this);
this.onChange = this.onChange.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
formError(){
if(this.state.formError.length > 0 ){
return <div className="text-danger text-center">{ this.state.formError}</div>
}else{
return null;
}
}
onChange(event){
var currentState = this.state;
if(event.target.name == 'email'){
this.setState({...currentState,email:event.target.value})
}
if(event.target.name == 'password'){
this.setState({...currentState,password:event.target.value})
}
}
onSubmit(e){
e.preventDefault()
var currentState = this.state;
this.setState({currentState,formError:''})
delete currentState.formError
const actionCreaters = []
actionCreaters.push(this.props.login)
const data = _.pick(currentState,["email","password"])
request(users.getToken,data,'post',actionCreaters).then( () => {
this.props.history.push('/dashboard')
}).catch( err => {
this.setState({formError:err})
})
}
render() {
return (
<div className="content">
<Grid fluid>
<Row>
<Col lg={6} md={8} lgOffset={3} smOffset={2}>
<Card
title={translator("signin")}
content={
<form onSubmit={this.onSubmit}>
{this.formError()}
<FormInputs
ncols={["col-md-12"]}
proprieties={[
{
label: translator("email")+" "+translator("address")+": " ,
type: "email",
name: "email",
value : this.state.email,
onChange : this.onChange,
bsClass: "form-control",
placeholder: "me@mail.com"
}
]}
/>
<FormInputs
ncols={["col-md-12"]}
proprieties={[
{
label: translator("password")+": ",
type: "password",
bsClass: "form-control",
placeholder: "***********",
onChange : this.onChange,
name : "password",
value : this.state.password
}
]}
/>
<Button bsStyle="success" pullRight fill type="submit">
{translator("login")}
</Button>
<div className="clearfix" />
</form>
}
/>
</Col>
</Row>
</Grid>
</div>
);
}
}
const mapDispatchToProps = (dispatch) => {
return bindActionCreators({
login,
getOverview
},dispatch)
}
const mapStateTopProps = state => {
return {
user : state.users.loggedUser
}
}
export default connect(mapStateTopProps,mapDispatchToProps)(Login);
|
/**
* 展示组件的 DataTypes 定义的内容
*
* @file demos/DataTypeExplorer.js
* @author leeight
*/
/* global _hmt, G_PREFIX, G_SOURCE_EXT */
import _ from 'lodash';
import {parse} from 'san-types';
import {defineComponent} from 'san';
import Icon from '../components/Icon';
/* eslint-disable */
const template = `<template>
<table s-if="typeDefs.length" border="1" cellpadding="0" cellspacing="0" class="typedefs">
<tr><th>名称</th><th>类型</th><th>默认值</th><th>描述</th></tr>
<tr s-for="typeDef in typeDefs">
<td>
{{typeDef.name}}
<ui-icon name="bind" title="支持双绑" s-if="typeDef.bindx" />
<ui-icon name="ok" title="必填" s-if="typeDef.required" />
</td>
<td>{{typeDef.type}}</td>
<td>{{typeDef.defaultValue || '-'}}</td>
<td>{{(typeDef.desc || '-') | raw}}</td>
</tr>
</table>
<div s-else>暂无定义,请给组件添加 <code>dataTypes</code> 属性</div>
</template>`;
/* eslint-enable */
function hasF(x) {
return x.bindx || x.required;
}
// 不是所有的组件都在components下面
const folderMap = {
Form: 'forms',
FormDialog: 'forms'
};
export default defineComponent({
template,
components: {
'ui-icon': Icon
},
initData() {
return {
typeDefs: []
};
},
inited() {
this.watch('code', code => {
const key = this.data.get('key');
const pattern = new RegExp('\'' + _.escapeRegExp(key) + '\'\\s*:\\s*([\\.\\/\\w]+)', 'gm');
const match = pattern.exec(code);
if (!match) {
this.noTypeDefs();
return;
}
const compName = match[1];
const ext = typeof G_SOURCE_EXT === 'string' ? G_SOURCE_EXT : '.js';
let moduleId = typeof G_PREFIX === 'object'
? `${G_PREFIX.componentsCode}${compName}`
: `san-xui/x/components/${compName}`;
const folder = folderMap[compName];
if (folder) {
moduleId = moduleId.replace('components', folder);
}
const sourceUrl = window.require.toUrl(moduleId).replace(/\?.*/, '') + ext + '?raw';
fetch(sourceUrl)
.then(response => {
if (response.status === 200) {
return response.text();
}
throw new Error(response.url + ' failed');
})
.then(code => {
const typeDefs = parse(code) || [];
_.each(typeDefs, T => {
T.name = _.kebabCase(T.name);
});
typeDefs.sort((a, b) => {
if (hasF(a) && !hasF(b)) {
return -1;
}
else if (!hasF(a) && hasF(b)) {
return 1;
}
return a.name.localeCompare(b.name);
});
this.data.set('typeDefs', typeDefs);
})
.catch(() => this.noTypeDefs());
});
},
noTypeDefs() {
this.data.set('typeDefs', []);
}
});
|
const data = [
{
type: 'renderTitle',
content: 'html5 新增内容'
},
{
type: 'renderSubTitle',
content: ''
},
{
type: 'renderHtml',
content: `
<codeBlock>
</codeBlock>
`
}
]
export default data
|
import Story from '../entities/StoryClass';
import fetchJsonp from 'fetch-jsonp';
class StoryService {
getStory(id) {
return fetchJsonp(`https://hacker-news.firebaseio.com/v0/item/${id}.json?print=pretty`)
.then(response => response.json())
.then(data => new Story(data))
}
getTopStories(query) {
return fetch(`https://hacker-news.firebaseio.com/v0/${query}.json?print=pretty`)
.then((response) => {
if (response.ok) {
return response.json();
} else {
throw new Error('SOMETHING WENT WRONG :(');
}
})
}
}
const storyData = new StoryService();
export default storyData; |
const jwt = require('jsonwebtoken')
const HttpError = require('../models/error')
const config = require('config')
const auth = (req, res, next) => {
const token = req.header('x-auth-token')
if (!token) {
return next(new HttpError('Unauthorized access denied.', 401))
}
try {
const decoded = jwt.verify(token, config.get("jwtSecret"))
req.user = decoded.user
next()
} catch (error) {
return next(new HttpError('Token is not valid.', 401))
}
}
// Checks if user is Admin, if not, invoke unauthorized access
const checkLevel = (req, res, next) => {
if (req.user.type !== 'admin'){
return next(new HttpError('Unauthorized access denied. No admin privileges.', 401))
}
next()
}
exports.auth = auth
exports.checkLevel = checkLevel
|
//Function select option
var tempHtml,prevOptionTag;
function deleteTeeTime(rowId,teeTimeId) {
//alert(rowId+" "+teeTimeId);
if(teeTimeId == 0){
deleteTeeTimeUtil(rowId);
}else{
/*$('#teeTimeId-'+rowId).val(0);
deleteTeeTimeUtil(rowId);*/
$.post("/tripcaddie/trip/deleteTeeTime.do",{
teeTimeId : teeTimeId
},function(data){
if(data == "success"){
$('#teeTimeId-'+rowId).val(0);
deleteTeeTimeUtil(rowId);
}else{
window.location.href="/tripcaddie/error.do";
}
});
}
}
function initialize(length){
var arrayTdTag;
//var defaultSelectTag,selectHtmlTag;
var selectHtmlTag;
var i,j,optionId;
$('#golfSchedule').hide();
//for each for every body
for(i=1;i<=length;i++){
$('#body'+i+" > tr").each(function() {
j=0;
$('#'+this.id+" > td").each(function() {
arrayTdTag = (this.id).split('-');
selectHtmlTag='player'+j+'-'+arrayTdTag[1]+'-'+arrayTdTag[2];
optionId = $('#'+selectHtmlTag+' option:selected').val();
if(optionId != -1 ){
removeOption(selectHtmlTag, i,optionId);
}
j++;
});
});
}
}
function setOPtion(selectId,option){
$('#'+selectId).val(option).attr('selected',true);
}
function remove_player(selectTagId,index){
var selectedOptionTagOfOther;
var arrayTdTag,i,selectHtmlTag,arrayTrTag;
var arraySelectTag = selectTagId.split('-');
var optionId = $("#"+selectTagId+" option:selected").val();
//optionTag make it as selected which is selected
var selectedOptionTagOfCurrent=null;
if(optionId != -1){
//remove element
selectedOptionTagOfCurrent=makeOptionTag(selectTagId);
$('#'+selectTagId+' > option').each(function(){
unselectOption(selectTagId);
if(this.id == optionId){
$('#'+selectTagId+' option[value = '+this.id+']').remove();
tempHtml=$('#'+selectTagId).html();
}
});
}else{
//Add Element
unselectOption(selectTagId);
$('#'+selectTagId).append(prevOptionTag);
/*$('#'+selectTagId+" > option").each(function(){
if(this.id == -1){
}
});*/
tempHtml=$('#'+selectTagId).html();
}
//alert(tempHtml);
//Set option to all dropdown
$("#body"+arraySelectTag[2]+" > tr").each(function(){ //To get Row
i=0;
arrayTrTag=(this.id).split('-');
//$('#'+arrayTrTag[0]+'-'+arrayTrTag[1]+" > td").each(function(){ //To get column
$('#'+this.id+" > td").each(function(){
arrayTdTag=(this.id).split('-');
//alert(arrayTdTag);
selectHtmlTag='player'+i+'-'+arrayTdTag[1]+'-'+arrayTdTag[2];
//alert(selectHtmlTag);
//Need to add more
if(selectHtmlTag != selectTagId){
if($("#"+selectHtmlTag+" option:selected").val() != -1){
selectedOptionTagOfOther=makeOptionTag(selectHtmlTag);
$('#'+selectHtmlTag).html(tempHtml);
$('#'+selectHtmlTag).append(selectedOptionTagOfOther);
}else{
$('#'+selectHtmlTag).html(tempHtml);
}
}else{
$('#'+selectHtmlTag).html(tempHtml);
if(selectedOptionTagOfCurrent != null){
$('#'+selectHtmlTag).append(selectedOptionTagOfCurrent);
}
}
i++;
});
});
}
function setPrev(selectTagId){
var optionId = $("#"+selectTagId+" option:selected").val();
var optionText = $("#"+selectTagId+" option:selected").text();
optionTag = document.createElement('option');
optionTag.setAttribute("id",optionId);
optionTag.setAttribute("value", optionId);
optionTag.innerHTML=optionText;
}
function makeOptionTag(selectTagId){
var optionId = $("#"+selectTagId+" option:selected").val();
var optionText = $("#"+selectTagId+" option:selected").text();
optionTag = document.createElement('option');
optionTag.setAttribute("id",optionId);
optionTag.setAttribute("value", optionId);
optionTag.setAttribute("selected", "selected");
optionTag.innerHTML=optionText;
return optionTag;
}
function unselectOption(selectTag) {
$('#'+selectTag+" > option").each(function(){
$('#'+selectTag+' option[value = '+this.id+']').removeAttr('selected');
});
}
function removeOption(selectTag,item,optionId){
var j;
$('#body'+item+" > tr").each(function() {
j=0;
$('#'+this.id+" > td").each(function() {
arrayTdTag = (this.id).split('-');
selectHtmlTag='player'+j+'-'+arrayTdTag[1]+'-'+arrayTdTag[2];
if(selectTag != selectHtmlTag){
$('#'+selectHtmlTag+' option[value = '+optionId+']').remove();
}
j++;
});
});
}
function deleteTeeTimeUtil(rowId) {
var j;
var arrRowId = rowId.split('-');
$('#body'+arrRowId[1]+' > tr').each(function(){
j=0;
$('#'+this.id+" > td").each(function(){
arrayTdTag = (this.id).split('-');
selectHtmlTag = 'player'+j+'-'+arrayTdTag[1]+'-'+arrayTdTag[2];
//alert(selectHtmlTag);
setPrev(selectHtmlTag);
unselectOption(selectHtmlTag);
$('#'+selectHtmlTag+' option:first').attr('selected','selected');
remove_player(selectHtmlTag, arrRowId[2]);
j++;
});
});
} |
import React from 'react';
import {Link} from 'react-router-dom';
import './Toolbar.css';
import ToggleButton from '../Sidebar/ToggleButton';
import logo from '../../image2/eb055966-6724-43f8-bbcc-d50648a8de36_200x200(1).png'
const Toolbar = (props) => {
return(
<header className="toolbar">
<nav className="toolbar__navigation">
<div className = "toolbar__toggle-button">
<ToggleButton click={props.toggleClickHandler} />
</div>
<div className="toolbar_logo2">
<img className="title-logo" src={logo} alt=""/>
<p className="paragraph">Trevinho Pencil Arts</p>
</div>
<div className="spacer"/>
<div className="toolbar_navigation-items">
<ul>
<li>
<Link to="/" className="link">Home</Link>
</li>
<li>
<Link to="/about" className="link">About</Link>
</li>
<li>
<Link to="/gallery" className="link">Gallery</Link>
</li>
<li>
<Link to="/cart" className="link">Cart</Link>
</li>
<li>
<Link to="/contact" className="link" >Contact</Link>
</li>
</ul>
</div>
</nav>
</header>
)
}
export default Toolbar;
|
const remote = require('electron').remote;
const Menu = remote.Menu;
const MenuItem = remote.MenuItem;
const ChatActions = require('../../actions/chat-actions.js');
module.exports = function(chat) {
const menu = new Menu();
menu.append(new MenuItem({
label: 'Clear chat messages',
click() {
ChatActions.clearChat(chat);
}
}));
return menu;
};
|
let rates = []
document.addEventListener('DOMContentLoaded', function() {
//USD based
// fetch("https://api.ratesapi.io/api/latest?base=USD").then(response => response.json()).then(data => {
fetch("https://api.exchangerate.host/latest?base=BTC").then(response => response.json()).then(data => {
document.querySelector('#date').innerHTML = "As of: " + data.date;
rates = data.rates;
document.querySelector('#usd').innerHTML = 'US Dollar: ' + rates.USD.toLocaleString("en-US");
document.querySelector('#eur').innerHTML = 'Euro: ' + rates.EUR.toFixed(0);
document.querySelector('#cny').innerHTML = 'Chinese Yuan: ' + rates.CNY.toFixed(0);
document.querySelector('#krw').innerHTML = 'Korean Won: ' + rates.KRW.toFixed(0);
document.querySelector('#jpy').innerHTML = 'Japanese Yen: ' + rates.JPY.toFixed(0);
document.querySelector('#inr').innerHTML = 'Indian Rupee: ' + rates.INR.toFixed(0);
document.querySelector('#aud').innerHTML = 'Australian Dollar: ' + rates.AUD.toFixed(0);
document.querySelector('#gbp').innerHTML = 'British Pound: ' + rates.GBP.toFixed(0);
document.querySelector('#rub').innerHTML = 'Russian Ruble: ' + rates.RUB.toFixed(0);
document.querySelector('#cad').innerHTML = 'Canadian Dollar: ' + rates.CAD.toFixed(0);
document.querySelector('#mxn').innerHTML = 'Mexican Peso: ' + rates.MXN.toFixed(0);
})
})
/* $(document).ready(function () {
$('xdiv').hover(
function () {
$(this).stop().fadeOut(function () {
var $temp = $(this).attr('src');
$(this).attr('src', $(this).attr('data-alt-src'));
$(this).attr('data-alt-src', $temp);
});
$(this).fadeIn();
},
function () {
$(this).stop().fadeOut(function () {
var $temp = $(this).attr('data-alt-src');
$(this).attr('data-alt-src', $(this).attr('src'));
$(this).attr('src', $temp);
});
$(this).fadeIn();
});
}); */ |
import React from 'react';
import ChoiceTile from '../components/ChoiceTile';
class ChoicesContainer extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
this.fetchEncounter = this.fetchEncounter.bind(this);
};
handleClick(e){
e.preventDefault();
if (e.target.dataset.outcome_type == "add_trait") {
this.props.dispatch({type: 'ADD_TRAIT', trait: e.target.dataset.outcome});
} else if (e.target.dataset.outcome_type == "add_item") {
this.props.dispatch({type: 'ADD_ITEM', item: e.target.dataset.outcome});
};
this.updateUser(e.target.dataset.next);
this.fetchEncounter(e.target.dataset.next);
}
updateUser(id) {
let user = this.props.user;
let payload = {
user: user,
new_encounter: id
};
fetch(`/api/v1/users/${user.id}`, {
credentials: 'same-origin',
method: 'PATCH',
headers: { 'Content-Type': 'application/json'},
body: JSON.stringify(payload)
})
};
fetchEncounter(id) {
fetch(`/api/v1/encounters/${id}`)
.then(response => response.json())
.then(data => {
this.props.dispatch({type: 'CHANGE_ENCOUNTER', encounter: data, choices: data["choices"]})
});
};
render() {
let choices;
if (this.props.choices.length > 0) {
choices = this.props.choices.map(choice => {
return(
<ChoiceTile
key={String(Date.now()) + '-' + choice.id}
choice={choice}
handleClick={this.handleClick}
/>
)
});
};
return(
<div className="choices-container">
<ul>
{choices}
</ul>
</div>
);
};
};
export default ChoicesContainer;
|
import loadTypesGenerator from '../generators/constants/load';
const SET_QUESTIONS = 'SET_QUESTIONS'
const ACCEPT_ANSWER_REQUEST = 'ACCEPT_ANSWER_REQUEST';
const ACCEPT_ANSWER_SUCCESS = 'ACCEPT_ANSWER_SUCCESS';
const ACCEPT_ANSWER_FAIL = 'ACCEPT_ANSWE_FAIL';
export default {
...loadTypesGenerator('questions'),
SET_QUESTIONS,
ACCEPT_ANSWER_REQUEST,
ACCEPT_ANSWER_SUCCESS,
ACCEPT_ANSWER_FAIL
}
|
// Convert grammar into JSON format (one time setup)
const LineByLineReader = require('line-by-line');
const jsonfile = require('jsonfile');
const lr = new LineByLineReader('grammar.txt');
const outputFile = 'rules.js';
const jsonObject = {};
let lineNumber = 0;
const TOTAL_LINES = 113;
lr.on('line', (line) =>{
lineNumber++;
jsonObject[lineNumber] = line;
if (lineNumber === TOTAL_LINES){
jsonfile.writeFile(outputFile, jsonObject, {spaces: 2, flag: 'a'}, function(err) {})
}
});
|
define([
"jquery",
"underscore",
"./declare",
"./_EventMixin",
"./_StatefulMixin",
"./registry",
"./parser",
"./_Destroyable"
], function ($, _, declare, _EventMixin, _StatefulMixin,registry, parser, _Destroyable) {
var attachPointAttr = "data-kb-attach-point",
attachEventAttr = "data-kb-attach-event";
function contains(parentNode, childNode) {
if (parentNode.contains) {
return parentNode != childNode && parentNode.contains(childNode);
} else {
return !!(parentNode.compareDocumentPosition(childNode) & 16);
}
}
function checkHover(e,target){
return !contains(target,e.relatedTarget) && !(e.relatedTarget===target);
}
var _WidgetBase = declare(_Destroyable, {
id: "",
baseClass:"",
styleClass:"",
domNode: null,
templateString: null,
_widgetsInTemplate: false,
attachScope: null,
attachPoint: null,
srcNodeRef: null,
init: function (params, srcNodeRef) {
_Destroyable.prototype.init.apply(this,arguments);
declare.mixin(this, params);
if (srcNodeRef) {
if(_.isString(srcNodeRef)){
srcNodeRef = $(srcNodeRef).get(0);
}
this.srcNodeRef = srcNodeRef;
}
this._attachPoints = [];
if (this.attachScope && this.attachPoint) {
this.attachScope[this.attachPoint] = this;
this.attachScope._attachPoints.push(this.attachPoint);
}
this.render();
this._init = true;
return this;
},
template: function () {
var tmpl = "<div></div>";
if (this.templateString) {
this._template = _.template(this.templateString);
tmpl = this._template(this);
}
this.domNode = $.parseHTML(tmpl)[0];
return this;
},
refresh:function(params){
this._rendeded = false;
this.init(params, this.domNode);
},
//render domNode
render: function () {
if (this.srcNodeRef) {
this.id = this.srcNodeRef.id;
}
if (!this.id) {
this.id = registry.getUniqueId();
}
if (!this._rendeded) {
this._rendeded = true;
registry.add(this);
this.template();
this.domNode.setAttribute("id", this.id);
this.domNode.setAttribute("data-kb-widget-id", this.id);
this._attachTemplateNodes(this.domNode);
this._attachTemplateEvents(this.domNode);
if (this.srcNodeRef) {
this._fillContent(this.srcNodeRef);
$(this.srcNodeRef).replaceWith(this.domNode);
}
}
if (this._widgetsInTemplate) {
parser.parse(this.domNode, this);
}
return this;
},
_fillContent: function (/*DomNode*/ source) {
// summary:
// Relocate source contents to templated container node.
// this.containerNode must be able to receive children, or exceptions will be thrown.
// tags:
// protected
var dest = this.containerNode;
if (source && dest) {
while (source.hasChildNodes()) {
dest.appendChild(source.firstChild);
}
}
return this;
},
appendTo: function (el) {
el.appendChild(this.domNode);
return this;
},
prependTo: function (el){
el.insertBefore(this.domNode,el.firstChild);
return this;
},
//dom节点append到页面之后调用
startup: function () {
_.each(this.getChildren(), function (it) {
it.startup();
});
return this;
},
_attachTemplateNodes: function (rootNode) {
var self = this, $rootNode = $(rootNode), prop = $rootNode.attr(attachPointAttr);
if (prop) {
self[prop] = rootNode;
self._attachPoints.push(prop);
}
$rootNode.find("[" + attachPointAttr + "]").each(function (ix, it) {
var $it = $(it);
if (!$it.attr("data-kb-type")) {
prop = $it.attr(attachPointAttr);
self[prop] = it;
self._attachPoints.push(prop);
}
});
return this;
},
_detachTemplateNodes: function () {
_.each(this._attachPoints, function (it) {
delete this[it];
});
this._attachPoints = [];
return this;
},
_attachTemplateEvents: function (rootNode) {
var self = this, $rootNode = $(rootNode), prop = $rootNode.attr(attachEventAttr), pairs;
if (prop) {
pairs = prop.split(',');
_.each(pairs, function (part) {
var pair = part.split(':'), evName = pair[0], fnName = pair[1];
if(evName == "mouseover" || evName == "mouseout"){
$rootNode.on(evName, function (e) {
if(checkHover(e,this)){
self[fnName].apply(self, arguments);
}
});
}else{
$rootNode.on(evName, function (e) {
self[fnName].apply(self, arguments);
});
}
});
}
$rootNode.find("[" + attachEventAttr + "]").each(function (ix, it) {
var $it = $(it);
prop = $it.attr(attachEventAttr);
pairs = prop.split(',');
_.each(pairs, function (part) {
var pair = part.split(':'), evName = pair[0], fnName = pair[1];
if(evName == "mouseover" || evName == "mouseout"){
$it.on(evName, function (e) {
if(checkHover(e,this)){
self[fnName].apply(self, arguments);
}
});
}else{
$it.on(evName, function (e) {
self[fnName].apply(self, arguments);
});
}
});
});
return this;
},
getChildren: function () {
return this.domNode ? registry.findWidgets(this.domNode) : [];
},
destroyChildren: function () {
_.each(this.getChildren(), function (it) {
it.destroy();
});
},
destroy: function () {
//if(!this._destroyed){
_Destroyable.prototype.destroy.apply(this,arguments);
this._detachTemplateNodes();
if (this.domNode) {
$(this.domNode).remove();
this.destroyChildren();
}
registry.remove(this.id);
delete this.domNode;
delete this._attachPoints;
delete this._events;
//}
}
});
var proto = _WidgetBase.prototype;
declare.mixin(proto, _StatefulMixin);
declare.mixin(proto, _EventMixin);
return _WidgetBase;
}); |
// If you want an example of language specs, check out:
// https://github.com/atom/language-javascript/blob/master/spec/javascript-spec.coffee
const path = require('path')
const packageName = 'language-v0'
const command = 'imparato:toggle-line-comment'
describe('Toggle Line Comment', () => {
let editor, buffer, workspaceElement
beforeEach(() => {
workspaceElement = atom.views.getView(atom.workspace)
waitsForPromise(() => {
const filepath = path.join('replica.v0.txt')
return atom.workspace.open(filepath).then((e) => {
editor = e
buffer = e.getBuffer()
})
})
waitsForPromise(() => {
return atom.packages.activatePackage(packageName)
})
})
it('enable comment', () => {
editor.setCursorBufferPosition([1, 0])
atom.commands.dispatch(workspaceElement, command)
expect(buffer.getText()).toBe('Spec :\n(Hey)\n(Having lunch)\n')
})
it('ignore empty lines', () => {
editor.setCursorBufferPosition([3, 0])
atom.commands.dispatch(workspaceElement, command)
expect(buffer.getText()).toBe('Spec :\nHey\n(Having lunch)\n')
})
it('disable comment', () => {
editor.setCursorBufferPosition([2, 0])
atom.commands.dispatch(workspaceElement, command)
expect(buffer.getText()).toBe('Spec :\nHey\nHaving lunch\n')
})
})
|
[{"locale": "en"}, {
"category": "Lu",
"mappings": {
"default": {"default": "bold script capital a", "short": "bold script cap a"},
"mathspeak": {"default": "bold script upper A"}
},
"key": "1D4D0"
}, {
"category": "Lu",
"mappings": {
"default": {"default": "bold script capital b", "short": "bold script cap b"},
"mathspeak": {"default": "bold script upper B"}
},
"key": "1D4D1"
}, {
"category": "Lu",
"mappings": {
"default": {"default": "bold script capital c", "short": "bold script cap c"},
"mathspeak": {"default": "bold script upper C"}
},
"key": "1D4D2"
}, {
"category": "Lu",
"mappings": {
"default": {"default": "bold script capital d", "short": "bold script cap d"},
"mathspeak": {"default": "bold script upper D"}
},
"key": "1D4D3"
}, {
"category": "Lu",
"mappings": {
"default": {"default": "bold script capital e", "short": "bold script cap e"},
"mathspeak": {"default": "bold script upper E"}
},
"key": "1D4D4"
}, {
"category": "Lu",
"mappings": {
"default": {"default": "bold script capital f", "short": "bold script cap f"},
"mathspeak": {"default": "bold script upper F"}
},
"key": "1D4D5"
}, {
"category": "Lu",
"mappings": {
"default": {"default": "bold script capital g", "short": "bold script cap g"},
"mathspeak": {"default": "bold script upper G"}
},
"key": "1D4D6"
}, {
"category": "Lu",
"mappings": {
"default": {"default": "bold script capital h", "short": "bold script cap h"},
"mathspeak": {"default": "bold script upper H"}
},
"key": "1D4D7"
}, {
"category": "Lu",
"mappings": {
"default": {"default": "bold script capital i", "short": "bold script cap i"},
"mathspeak": {"default": "bold script upper I"}
},
"key": "1D4D8"
}, {
"category": "Lu",
"mappings": {
"default": {"default": "bold script capital j", "short": "bold script cap j"},
"mathspeak": {"default": "bold script upper J"}
},
"key": "1D4D9"
}, {
"category": "Lu",
"mappings": {
"default": {"default": "bold script capital k", "short": "bold script cap k"},
"mathspeak": {"default": "bold script upper K"}
},
"key": "1D4DA"
}, {
"category": "Lu",
"mappings": {
"default": {"default": "bold script capital l", "short": "bold script cap l"},
"mathspeak": {"default": "bold script upper L"}
},
"key": "1D4DB"
}, {
"category": "Lu",
"mappings": {
"default": {"default": "bold script capital m", "short": "bold script cap m"},
"mathspeak": {"default": "bold script upper M"}
},
"key": "1D4DC"
}, {
"category": "Lu",
"mappings": {
"default": {"default": "bold script capital n", "short": "bold script cap n"},
"mathspeak": {"default": "bold script upper N"}
},
"key": "1D4DD"
}, {
"category": "Lu",
"mappings": {
"default": {"default": "bold script capital o", "short": "bold script cap o"},
"mathspeak": {"default": "bold script upper O"}
},
"key": "1D4DE"
}, {
"category": "Lu",
"mappings": {
"default": {"default": "bold script capital p", "short": "bold script cap p"},
"mathspeak": {"default": "bold script upper P"}
},
"key": "1D4DF"
}, {
"category": "Lu",
"mappings": {
"default": {"default": "bold script capital q", "short": "bold script cap q"},
"mathspeak": {"default": "bold script upper Q"}
},
"key": "1D4E0"
}, {
"category": "Lu",
"mappings": {
"default": {"default": "bold script capital r", "short": "bold script cap r"},
"mathspeak": {"default": "bold script upper R"}
},
"key": "1D4E1"
}, {
"category": "Lu",
"mappings": {
"default": {"default": "bold script capital s", "short": "bold script cap s"},
"mathspeak": {"default": "bold script upper S"}
},
"key": "1D4E2"
}, {
"category": "Lu",
"mappings": {
"default": {"default": "bold script capital t", "short": "bold script cap t"},
"mathspeak": {"default": "bold script upper T"}
},
"key": "1D4E3"
}, {
"category": "Lu",
"mappings": {
"default": {"default": "bold script capital u", "short": "bold script cap u"},
"mathspeak": {"default": "bold script upper U"}
},
"key": "1D4E4"
}, {
"category": "Lu",
"mappings": {
"default": {"default": "bold script capital v", "short": "bold script cap v"},
"mathspeak": {"default": "bold script upper V"}
},
"key": "1D4E5"
}, {
"category": "Lu",
"mappings": {
"default": {"default": "bold script capital w", "short": "bold script cap w"},
"mathspeak": {"default": "bold script upper W"}
},
"key": "1D4E6"
}, {
"category": "Lu",
"mappings": {
"default": {"default": "bold script capital x", "short": "bold script cap x"},
"mathspeak": {"default": "bold script upper X"}
},
"key": "1D4E7"
}, {
"category": "Lu",
"mappings": {
"default": {"default": "bold script capital y", "short": "bold script cap y"},
"mathspeak": {"default": "bold script upper Y"}
},
"key": "1D4E8"
}, {
"category": "Lu",
"mappings": {
"default": {"default": "bold script capital z", "short": "bold script cap z"},
"mathspeak": {"default": "bold script upper Z"}
},
"key": "1D4E9"
}, {
"category": "Ll",
"mappings": {"default": {"default": "bold script small a", "short": "bold script a"}},
"key": "1D4EA"
}, {
"category": "Ll",
"mappings": {"default": {"default": "bold script small b", "short": "bold script b"}},
"key": "1D4EB"
}, {
"category": "Ll",
"mappings": {"default": {"default": "bold script small c", "short": "bold script c"}},
"key": "1D4EC"
}, {
"category": "Ll",
"mappings": {"default": {"default": "bold script small d", "short": "bold script d"}},
"key": "1D4ED"
}, {
"category": "Ll",
"mappings": {"default": {"default": "bold script small e", "short": "bold script e"}},
"key": "1D4EE"
}, {
"category": "Ll",
"mappings": {"default": {"default": "bold script small f", "short": "bold script f"}},
"key": "1D4EF"
}, {
"category": "Ll",
"mappings": {"default": {"default": "bold script small g", "short": "bold script g"}},
"key": "1D4F0"
}, {
"category": "Ll",
"mappings": {"default": {"default": "bold script small h", "short": "bold script h"}},
"key": "1D4F1"
}, {
"category": "Ll",
"mappings": {"default": {"default": "bold script small i", "short": "bold script i"}},
"key": "1D4F2"
}, {
"category": "Ll",
"mappings": {"default": {"default": "bold script small j", "short": "bold script j"}},
"key": "1D4F3"
}, {
"category": "Ll",
"mappings": {"default": {"default": "bold script small k", "short": "bold script k"}},
"key": "1D4F4"
}, {
"category": "Ll",
"mappings": {"default": {"default": "bold script small l", "short": "bold script l"}},
"key": "1D4F5"
}, {
"category": "Ll",
"mappings": {"default": {"default": "bold script small m", "short": "bold script m"}},
"key": "1D4F6"
}, {
"category": "Ll",
"mappings": {"default": {"default": "bold script small n", "short": "bold script n"}},
"key": "1D4F7"
}, {
"category": "Ll",
"mappings": {"default": {"default": "bold script small o", "short": "bold script o"}},
"key": "1D4F8"
}, {
"category": "Ll",
"mappings": {"default": {"default": "bold script small p", "short": "bold script p"}},
"key": "1D4F9"
}, {
"category": "Ll",
"mappings": {"default": {"default": "bold script small q", "short": "bold script q"}},
"key": "1D4FA"
}, {
"category": "Ll",
"mappings": {"default": {"default": "bold script small r", "short": "bold script r"}},
"key": "1D4FB"
}, {
"category": "Ll",
"mappings": {"default": {"default": "bold script small s", "short": "bold script s"}},
"key": "1D4FC"
}, {
"category": "Ll",
"mappings": {"default": {"default": "bold script small t", "short": "bold script t"}},
"key": "1D4FD"
}, {
"category": "Ll",
"mappings": {"default": {"default": "bold script small u", "short": "bold script u"}},
"key": "1D4FE"
}, {
"category": "Ll",
"mappings": {"default": {"default": "bold script small v", "short": "bold script v"}},
"key": "1D4FF"
}, {
"category": "Ll",
"mappings": {"default": {"default": "bold script small w", "short": "bold script w"}},
"key": "1D500"
}, {
"category": "Ll",
"mappings": {"default": {"default": "bold script small x", "short": "bold script x"}},
"key": "1D501"
}, {
"category": "Ll",
"mappings": {"default": {"default": "bold script small y", "short": "bold script y"}},
"key": "1D502"
}, {
"category": "Ll",
"mappings": {"default": {"default": "bold script small z", "short": "bold script z"}},
"key": "1D503"
}]
|
module.exports = function(grunt) {
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
project: {
partials: 'partials',
sections: 'sections',
},
concat: {
sections: {
src: ['<%= project.sections %>/*.html'],
dest: 'dist/index.html'
},
header: {
src: ['<%= project.partials %>/header.html', 'dist/index.html'],
dest: 'dist/index.html'
},
footer: {
src: ['dist/index.html', '<%= project.partials %>/footer.html'],
dest: 'dist/index.html'
}
}
});
grunt.registerTask('default', ['concat:sections', 'concat:header', 'concat:footer']);
}; |
import { inject as service } from '@ember/service';
import { readOnly } from '@ember/object/computed';
import Component from '@ember/component';
import { computed } from '@ember/object';
import localesMeta from 'croodle/locales/meta';
export default Component.extend({
tagName: 'select',
classNames: [ 'language-select' ],
i18n: service(),
moment: service(),
powerCalendar: service(),
current: readOnly('i18n.locale'),
locales: computed('i18n.locales', function() {
let currentLocale = this.get('i18n.locale');
return this.get('i18n.locales').map(function(locale) {
return {
id: locale,
selected: locale === currentLocale,
text: localesMeta[locale]
};
});
}),
change() {
let locale = this.element.options[this.element.selectedIndex].value;
this.i18n.set('locale', locale);
this.moment.changeLocale(locale);
this.powerCalendar.set('locale', locale);
if (window.localStorage) {
window.localStorage.setItem('locale', locale);
}
}
});
|
import * as React from 'react';
import Button from './Button';
import * as enzyme from 'enzyme';
describe('Hello, Enzyme!', () => {
it('renders', () => {
const wrapper = enzyme.shallow(<Button/>);
expect(wrapper).toHaveLength(1);
});
}); |
import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import Index from '../views/index.vue'
import Second from '../views/second.vue'
import Bottom from '../components/bottom.vue'
import about from '../views/About.vue'
import third from '../views/third.vue'
import login from '../views/login.vue'
import test from '../views/test.vue'
import parameters from '../views/parameters.vue'
Vue.use(VueRouter)
const routes = [
{
path:'/',
name:'Index',
component:Index,
children:[
{
path: '/home',
component: Home
},
{
path: '/about/:num',
component: about
},
{
path: '/second',
component :Second
},
{
path:'/test',
component: test
},
{
path:'/parameters',
component: parameters
}
]
},
{
path: '/third',
component: third
},
{
path: '/login',
component: login
},
{
path:'/second',
name:'Second',
component: Second
},
{
path: '/home',
name: 'Home',
component: Home
},
{
path: '/about',
name: 'About',
// route level code-splitting
// this generates a separate chunk (about.[hash].js) for this route
// which is lazy-loaded when the route is visited.
component: () => import(/* webpackChunkName: "about" */ '../views/About.vue')
},
{
path:'/parameters',
component: parameters
}
]
new Vue({
el:'.body',
router,
render:h => h(Index)
})
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes
})
export default router
|
const { body, validationResult } = require('express-validator');
const { availableProjects } = require('../../services/projectService');
module.exports = async (req, res) => {
try {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({ errors: errors.array() });
}
const result = await availableProjects();
const response = result.map(doc =>
{ return {
id: doc._doc._id,
completed: doc._doc.completed
}
})
return res.status(200).json(response);
} catch (error) {
return res.status(500).json(error);
}
};
|
module.exports = {
attributes: {
id: {
type: Sequelize.STRING,
primaryKey: true,
defaultValue: undefined
},
countryName: {
type: Sequelize.STRING,
allowNull: false
},
countryCode: {
type: Sequelize.STRING,
allowNull: false
},
countryCurencyCode: {
type: Sequelize.STRING,
allowNull: false
}
},
associations: function() {
Country.hasMany(Bank, {
as: 'banks',
foreignKey: 'сountryId'
});
},
options: {
timestamps: true,
tableName: 'currency_countries',
classMethods: {},
instanceMethods: {},
hooks: {}
}
};
|
/* eslint-disable camelcase */
import moment from 'moment';
const { Menu, Meal } = require('../models');
const MenuController = {
addMeal(req, res) {
const date = moment().format('DD-MM-YYYY');
const menu_id = parseInt(moment().format('DDMMYYYY'), Number);
return Meal
.findById(req.body.meal_id)
.then((meal) => {
if (!meal) {
return res.status(404).send({
message: 'Meal Not Found',
});
}
return Menu.create({
menu_id,
meal_id: meal.id,
meal_name: meal.name,
meal_price: meal.price,
meal_image: meal.image,
date,
})
.then(() => res.status(201).json({
status: 'success',
message: 'Meal added successfully.',
}))
.catch(error => res.status(400).json({
error: error.message,
}));
})
.catch(error => res.status(400).send(error));
},
fetchMenu(req, res) {
const date = moment().format('DD-MM-YYYY');
return Menu
.findAll({ where: { date } })
.then(menu => res.status(200).json({
message: 'Success',
date,
data: menu,
}))
.catch(error => res.status(400).send(error));
},
deleteMeal(req, res) {
return Menu
.findAll({ where: { menu_id: req.body.menu_id, meal_id: req.body.meal_id } })
.then((meal) => {
if (!meal) {
return res.status(404).send({
message: 'Meal Not Found',
});
}
return Menu
.destroy({ where: { menu_id: req.body.menu_id, meal_id: req.body.meal_id } })
.then(() => res.status(200).json({
message: 'Meal deleted from menu successfully.',
}))
.catch(error => res.status(400).send(error));
})
.catch(error => res.status(400).send(error));
},
deleteMenu(req, res) {
return Menu
.findAll({ where: { menu_id: req.params.menu_id } })
.then((menu) => {
if (!menu) {
return res.status(400).send({
message: 'Menu Not Found',
});
}
return Menu
.destroy({ where: { menu_id: req.params.menu_id } })
.then(() => res.status(200).json({
message: 'Menu deleted successfully.',
}))
.catch(error => res.status(400).send(error));
})
.catch(error => res.status(400).send(error));
},
};
export default MenuController;
|
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var monthlyPhraseSchema = new Schema({
name: {type: String, required: true},
seikyo: {type: Schema.Types.ObjectId, ref: 'Seikyo', required: true}
});
monthlyPhraseSchema.virtual('created').get(function () {
return this._id.getTimestamp();
});
mongoose.model('MonthlyPhrase', monthlyPhraseSchema);
|
export { default as Profile } from './Profile'
export { default as History } from './History'
export { default as ProjectSetting } from './ProjectSetting'
export { default as ActivitySetting } from './ActivitySetting'
export { default as SelfIntro } from './SelfIntro'
export { default as ProfileSetting } from './ProfileSetting'
export { default as ProfileStack } from './ProfileStack'
export { default as ProjectDetail } from './ProjectDetail'
|
/** @jsx React.DOM */
var React = require('react'),
Router = require('react-router');
var Actions = require('../../../actions'),
ProfileService = require('../../../services/profile'),
AppStateStore = require('../../../stores/appstate'),
Validator = require('validator');
var AuthMixin = require('../../../mixins/auth'),
LocalListenerMixin = require('../../../mixins/locallistener');
// React-router variables
var Link = Router.Link;
var Settings = React.createClass({
mixins: [
AuthMixin,
LocalListenerMixin
],
listeners: {
onCurrentChanged: function(event) {
this.setState({
currentPassword: event.target.value
});
},
onNewChanged: function(event) {
this.setState({
newPassword: event.target.value
});
},
onConfirmNewChanged: function(event) {
this.setState({
confirmNewPassword: event.target.value
});
}
},
getInitialState: function() {
return {
toastMessage: undefined,
currentPassword: '',
newPassword: '',
confirmPassword: ''
};
},
componentDidMount: function() {
Actions.changePageTitle('Settings');
},
componentWillUnmount: function() {
},
onCurrentChanged: function(event){
this.setState({
toastMessage: undefined,
currentPassword: event.target.value
});
},
onNewChanged: function(event){
this.setState({
toastMessage: undefined,
newPassword: event.target.value
});
},
onConfirmNewChanged: function(event){
this.setState({
toastMessage: undefined,
confirmPassword: event.target.value
});
},
onSaveClick: function() {
var component = this;
if (this.state.currentPassword == '' || this.state.newPassword == '' || this.state.confirmPassword == ''){
this.setSate({
toastMessage: 'All fields are required.'
});
} else if (this.state.newPassword != this.state.confirmPassword) {
this.setSate({
toastMessage: 'Passwords did not match.',
confirmPassword: ''
});
} else if (!Validator.matches(this.state.newPassword, /((?=.*\d)(?=.*[a-z]).{6,20})/)) {
this.setState({
toastMessage: 'Password must have one digit, lowercase letter and be between 6 and 20 characters long',
newPassword: '',
confirmPassword: ''
});
// Focus and clear the password box
this.refs.newPassword.getDOMNode().focus();
return;
} else {
ProfileService.updatePassword(
AppStateStore.getSessionData().id,
this.state.currentPassword,
this.state.newPassword,
AppStateStore.getSessionData().sessionToken,
function (res) {
if(res.ok) {
//Everything went smoothly
if(res.body.Result) {
component.setState({
toastMessage: 'Password updated successfully.',
currentPassword: '',
newPassword: '',
confirmPassword: ''
});
console.log('Response from udpatePassword', JSON.stringify(res.body));
} else {
component.setState({
toastMessage: 'Current password is not correct.',
currentPassword: ''
});
this.refs.newPassword.getDOMNode().focus();
console.log('Response from updatePassword', res.body.InfoMessages[0].Text)
}
} else {
//Something went wrong
console.log('Error at udpatePassword', res.Text);
}
});
}
},
render: function() {
return (
<div className="tab-content">
<div className="left wide">
<div className="subtitle">Password</div>
<div className="form">
<div className="field">
<div className="label">Current</div>
<input type="password" id="currentPassword" ref="currentPassword" className="textbox" value={this.state.currentPassword} onChange={this.onCurrentChanged}/>
</div>
<div className="field">
<div className="label">New</div>
<input type="password" id="newPassword" ref="newPassword" className="textbox" value={this.state.newPassword} onChange={this.onNewChanged}/>
</div>
<div className="field">
<div className="label">Confirm new</div>
<input type="password" className="textbox" id="confirmPassword" ref="confirmPassword" value={this.state.confirmPassword} onChange={this.onConfirmNewChanged}/>
</div>
<div className={'flash' + (this.state.toastMessage ? ' visible' : '')}>
{this.state.toastMessage}
</div>
<div className="field btn">
<div className="label"></div>
<button id="save-button" type="button" className="button" onClick={this.onSaveClick}>Save</button>
</div>
</div>
</div>
<div className="right narrow">
<div className="subtitle">Notification</div>
<div className="field">
<div className="label">Send email</div>
<Link to="notice" className="button">Once an hour <i className="fa fa-chevron-down"></i> </Link>
</div>
</div>
</div>
);
}
});
module.exports = Settings;
|
System.config({
baseURL: "./",
defaultJSExtensions: true,
transpiler: false,
paths: {
"github:*": "../jspm_packages/github/*"
},
map: {
"less": "github:aaike/jspm-less-plugin@0.0.5",
"github:aaike/jspm-less-plugin@0.0.5": {
"less.js": "github:distros/less@2.4.0"
}
}
});
|
/* global angular */
/* global window */
'use strict'; // jshint ignore:line
angular.module('lumx.notification', [])
.provider('LxNotificationService', function () {
var notificationOffset;
this.setNotificationOffset = function (value) {
notificationOffset = value;
};
this.$get = ['$injector', '$rootScope', '$timeout', function ($injector, $rootScope, $timeout) {
notificationOffset = notificationOffset || 24;
//
// PRIVATE MEMBERS
//
var notificationList = [],
dialogFilter,
dialog;
//
// NOTIFICATION
//
// private
function getElementHeight(elem) {
return parseFloat(window.getComputedStyle(elem, null).height);
}
// private
function moveNotificationUp() {
var newNotifIndex = notificationList.length - 1;
notificationList[newNotifIndex].height = getElementHeight(notificationList[newNotifIndex].elem[0]);
var upOffset = 0;
for (var idx = newNotifIndex; idx >= 0; idx--) {
if (notificationList.length > 1 && idx !== newNotifIndex) {
upOffset = notificationOffset + notificationList[newNotifIndex].height;
notificationList[idx].margin += upOffset;
notificationList[idx].elem.css('marginBottom', notificationList[idx].margin + 'px');
}
}
}
// private
function deleteNotification(notification) {
var notifIndex = notificationList.indexOf(notification);
var dnOffset = notificationOffset + notificationList[notifIndex].height;
for (var idx = 0; idx < notifIndex; idx++) {
if (notificationList.length > 1) {
notificationList[idx].margin -= dnOffset;
notificationList[idx].elem.css('marginBottom', notificationList[idx].margin + 'px');
}
}
notification.elem.remove();
notificationList.splice(notifIndex, 1);
}
function notify(text, icon, sticky, color) {
var notificationTimeout;
var notification = createElement('<div></div>').addClass('notification');
var notificationText = createElement('<span></span>')
.addClass('notification__content');
notificationText.html(text);
if (angular.isDefined(icon)) {
var notificationIcon = createElement('<i></i>')
.addClass('notification__icon mdi mdi-' + icon);
notification
.addClass('notification--has-icon')
.append(notificationIcon);
}
if (angular.isDefined(color)) {
notification.addClass('notification--' + color);
}
notification.append(notificationText);
var body = getBodyElement()
.append(notification);
var data = { elem: notification, margin: 0 };
notificationList.push(data);
moveNotificationUp();
notification.on('click', function () {
deleteNotification(data);
if (angular.isDefined(notificationTimeout)) {
$timeout.cancel(notificationTimeout);
}
});
if (angular.isUndefined(sticky) || !sticky) {
notificationTimeout = $timeout(function () {
deleteNotification(data);
}, 6000);
}
}
function success(text, sticky) {
notify(text, 'check', sticky, 'green');
}
function error(text, sticky) {
notify(text, 'alert-circle', sticky, 'red');
}
function warning(text, sticky) {
notify(text, 'alert', sticky, 'orange');
}
function info(text, sticky) {
notify(text, 'information-outline', sticky, 'blue');
}
//
// ALERT & CONFIRM
//
// private
function buildDialogHeader(title) {
// DOM elements
var dialogHeader = createElement('<div></div>')
.addClass('dialog__header p++ fs-title');
dialogHeader.html(title);
return dialogHeader;
}
// private
function buildDialogContent(text) {
// DOM elements
var dialogContent = createElement('<div></div>')
.addClass('dialog__content p++ pt0 tc-black-2');
dialogContent.html(text);
return dialogContent;
}
// private
function buildDialogActions(buttons, callback) {
var $compile = $injector.get('$compile');
// DOM elements
var dialogActions = createElement('<div></div>')
.addClass('dialog__actions');
var dialogLastBtn = createElement('<button></button>')
.addClass('btn btn--m btn--blue btn--flat');
dialogLastBtn.html(buttons.ok);
// Cancel button
if (angular.isDefined(buttons.cancel)) {
// DOM elements
var dialogFirstBtn = createElement('<button></button>')
.addClass('btn btn--m btn--red btn--flat');
dialogFirstBtn.html(buttons.cancel);
dialogFirstBtn.attr('lx-ripple', '');
// Compilation
$compile(dialogFirstBtn)($rootScope);
// DOM link
dialogActions.append(dialogFirstBtn);
// Event management
dialogFirstBtn.on('click', function () {
callback(false);
closeDialog();
});
}
// Compilation
dialogLastBtn.attr('lx-ripple', '');
$compile(dialogLastBtn)($rootScope);
// DOM link
dialogActions.append(dialogLastBtn);
// Event management
dialogLastBtn.on('click', function () {
callback(true);
closeDialog();
});
return dialogActions;
}
function confirm(title, text, buttons, callback) {
// DOM elements
dialogFilter = createElement('<div></div>');
dialogFilter.addClass('dialog-filter');
dialog = createElement('<div></div>');
dialog.addClass('dialog dialog--alert');
var dialogHeader = buildDialogHeader(title);
var dialogContent = buildDialogContent(text);
var dialogActions = buildDialogActions(buttons, callback);
// DOM link
var body = getBodyElement().append(dialogFilter);
dialog
.append(dialogHeader)
.append(dialogContent)
.append(dialogActions);
body.append(dialog);
dialog.css('display', 'block');
// Starting animaton
$timeout(function () {
dialogFilter.addClass('dialog-filter--is-shown');
dialog.addClass('dialog--is-shown');
}, 100);
}
function alert(title, text, button, callback) {
// DOM elements
dialogFilter = createElement('<div></div>')
.addClass('dialog-filter');
dialog = createElement('<div></div>')
.addClass('dialog dialog--alert');
var dialogHeader = buildDialogHeader(title);
var dialogContent = buildDialogContent(text);
var dialogActions = buildDialogActions({ ok: button }, callback);
// DOM link
var body = getBodyElement()
.append(dialogFilter);
dialog
.append(dialogHeader)
.append(dialogContent)
.append(dialogActions);
body.append(dialog);
dialog.css('display', 'block');
// Starting animaton
$timeout(function () {
dialogFilter.addClass('dialog-filter--is-shown');
dialog.addClass('dialog--is-shown');
}, 100);
}
// private
function closeDialog() {
// Starting animaton
dialogFilter.removeClass('dialog-filter--is-shown');
dialog.removeClass('dialog--is-shown');
// After animaton
$timeout(function () {
dialogFilter.remove();
dialog.remove();
}, 600);
}
function getBodyElement() {
return createElement(window.document.body);
}
function createElement(element) {
return angular.element(element);
}
// Public API
return {
alert: alert,
confirm: confirm,
error: error,
info: info,
notify: notify,
success: success,
warning: warning
};
}];
}); |
export const saveUserToLS = (user) => {
localStorage.setItem('user',JSON.stringify(user));
}
export const getUserfromLS = () => {
return JSON.parse(localStorage.getItem('user'));
}
|
import React from 'react';
import { NavLink } from 'react-router-dom';
import './index.css';
const Header = () => (
<header>
<div className="center-column">
<h1>你好,微前端!</h1>
</div>
<nav>
<ol className="center-column">
<li>
<NavLink to="/">微应用 A</NavLink>
</li>
<li>
<NavLink to="/app-b">微应用 B</NavLink>
</li>
<li>
<NavLink to="/about">容器内嵌应用 C</NavLink>
</li>
</ol>
</nav>
</header>
);
export default Header; |
import Pjax from "pjax";
import topbar from "topbar";
topbar.config({
barColors: {
"0": "#ffc107"
}
});
class Site {
constructor() {
document.addEventListener("pjax:send", this.handlePjaxSend);
document.addEventListener("pjax:complete", this.handlePjaxComplete);
var pjax = new Pjax();
}
handlePjaxSend() {
topbar.show();
}
handlePjaxComplete() {
topbar.hide();
}
}
new Site();
|
"use strict"
/**
* [touchBtn 手机屏幕按钮]
* @param {[array]} menuChild [菜单选项]
* @param {[array]} canvasWH [游戏画布大小]
* @param {[number]} menuOptionW [菜单按钮宽度]
* @param {[function]} callback [点击回调]
*/
var touchBtn = Class.extend({
ctor:function(){
this._init.apply(this,arguments);
},
_init:function(menuChild,menuOptionW,canvasWH,callback,share){
this._menuBtn = arguments[0]; //所有菜单按钮
this._menuBtnW = arguments[1]; //菜单按钮宽度
this._callback = arguments[arguments.length - 2];//回调函数
this._canvasWH = canvasWH;//游戏画布大小
this._bodyW = document.body.offsetWidth; //可视区域宽
this._bodyH = document.body.offsetHeight; //可视区域高
this._timer = null;//菜单显示隐藏定时器
this._isMenuView = true;//是否显示菜单
this._share = share;//分享回调
this._screenDire = 0;//屏幕状态
this._alertState = true;//是否提示
this._isBtnClick = true;
this._screenMsgBoxImgArr = [rootPath+'release/img/szh.png',rootPath+'release/img/hzs.png'];
this._screenMsgBox = document.createElement('div');
this._screenMsgBox.id = 'screenMsgBox';
this._screenMsgBoxImg = new Image();
this._screenMsgBox.appendChild(this._screenMsgBoxImg);
document.body.appendChild(this._screenMsgBox);
var media = window.matchMedia("(orientation: portrait)");
if(media.matches){//竖屏
this._screenDire = 0;
if(this._canvasWH[0]>this._canvasWH[1]){
this._screenMsgBoxImg.src = this._screenMsgBoxImgArr[0];
this._screenMsgBox.style.display = 'block';
this._screenMsgBox.style.height = '100%';
this._alertState = false;
}
}
else {//横屏
this._screenDire = 1;
if(this._canvasWH[1]>this._canvasWH[0]){
this._screenMsgBoxImg.src = this._screenMsgBoxImgArr[1];
this._screenMsgBox.style.display = 'block';
this._screenMsgBox.style.height = '100%';
this._alertState = false;
}
}
if(this._menuBtn.length>0 && arguments.length>=3){
this._addMenuBtn();
this._screenOrient();
this._screenMsgBoxHide();
}
else{
return;
}
},
/**
* [_screenMsgBoxHide 提示框隐藏]
*/
_screenMsgBoxHide:function(){
this._AddEvent(this._screenMsgBox,'click',function(e){
this.style.display = 'none';
if(e.stopPropagation){
e.stopPropagation();
}
else {
e.cancelBubble = true;
}
})
},
/**
* [_addMenuBtn 创建悬浮菜单按钮]
*/
_addMenuBtn:function(){
this._touchMenuPar = document.createElement('div');//悬浮按钮层
this._touchMenuPar.id = 'touchMenuPar';
this._touchMenuPar.className = 'hideTouchBtn';
this._tocuhMenuBtn = document.createElement('div');//悬浮按钮
this._tocuhMenuBtn.className = 'tocuhMenuBtn';
this._touchMenuPar.appendChild(this._tocuhMenuBtn);
this._touchMenuView = document.createElement('div');//悬浮菜单显示层
this._touchMenuView.className = 'bdsharebuttonbox';
this._touchMenuView.id = 'touchMenuView';
this._touchMenuView.innerHTML = '';
this._touchMenuView.style.width = this._menuBtnW * this._menuBtn.length + 'px';
this._touchMenuView.style.display = 'none';
for(var i=0;i<this._menuBtn.length;i++){//插入菜单按钮
var a = document.createElement('a');
a.innerHTML = this._menuBtn[i];
this._touchMenuView.appendChild(a);
this._touchMenuView.children[i].style.width = this._menuBtnW + 'px';
}
this._touchMenuView.children[1].setAttribute('data-cmd','more');
this._menuBtnEvent();
},
/**
* [_menuBtnEvent 菜单按钮点击事件]
*/
_menuBtnEvent:function(){
var _self = this;
var menuBtn = this._touchMenuView.children;
// for(var i=0;i<menuBtn.length;i++){
// menuBtn[i].index = i;
// this._AddEvent(menuBtn[i],'click',function(e){
// _self._setCallback(e,this);
// },false);
// }
_self._setCallback(menuBtn);
},
/**
* [_setCallback 回调函数]
* @param {[element]} btn [点击按钮]
*/
_setCallback:function(btn){
var _self = this;
var callback = this._callback;
if(callback){
callback(btn);
}
},
/**
* [show 显示悬浮菜单按钮]
*/
show:function(){
var _self = this;
document.body.insertBefore(this._touchMenuPar,document.body.children[0]);
this._touchDown = function(e){
_self._touchStart(e);
}
this._touchClick = function(){
if(_self._isBtnClick){
if(_self._isMenuView){
_self._viewMenu();
}
else {
_self._HideMenu();
}
}
}
this._AddEvent(this._touchMenuPar,'touchstart',this._touchDown,false);
this._AddEvent(this._tocuhMenuBtn,'click',this._touchClick,false);
return this;
},
/**
* [_touchStart 手指按下屏幕]
* @param {[object]} e [触摸屏幕对象]
*/
_touchStart:function(e){
var _self = this;
var oEvent = e || event;
this._touchDownX = oEvent.changedTouches[0].clientX;
this._touchDownY = oEvent.changedTouches[0].clientY;
this._touchPosX = this._touchDownX - this._touchMenuPar.offsetLeft;
this._touchPosY = this._touchDownY - this._touchMenuPar.offsetTop;
this.touchMove = function(oEvent){
_self._touchMove(oEvent);
}
this.touchUp = function(){
_self._touchEnd();
}
this._AddEvent(this._touchMenuPar,'touchmove',this.touchMove,false);
this._AddEvent(this._touchMenuPar,'touchend',this.touchUp,false);
if(oEvent.cancelBubble){
oEvent.cancelBubble = true;
}
else {
oEvent.stopPropagation();
}
},
/**
* [_touchMove 手指按下移动]
* @param {[object]} oEvent [触摸屏幕对象]
*/
_touchMove:function(oEvent){
var _self = this;
this._touchMoveX = oEvent.changedTouches[0].clientX;//获取按下的X坐标
this._touchMoveY = oEvent.changedTouches[0].clientY;//获取按下的Y坐标
var touchBtn = this._touchMenuPar;
var touchBtnW = touchBtn.offsetWidth;//按钮可见宽度
var touchBtnH = touchBtn.offsetHeight;//按钮可见高度
var surplusX = touchBtnW - this._touchPosX;
var surplusY = touchBtnH - this._touchPosY;
touchBtn.style.top = this._touchMoveY - this._touchPosY + 'px';
touchBtn.style.left = this._touchMoveX - this._touchPosX + 'px';
touchBtn.style.bottom = '0px';
touchBtn.style.right = '0px';
// if(this._touchMoveX<=this._touchPosX){
// touchBtn.style.left = '0px';
// touchBtn.className = 'menuViewL';
// }
// else if(this._touchMoveX + surplusX >= this._bodyW){
// touchBtn.style.left = this._bodyW - touchBtnW + 'px';
// touchBtn.className = 'menuViewR';
// }
if(this._touchMoveY<=this._touchPosY){
touchBtn.style.top = '0px';
}
else if(this._touchMoveY + surplusY >= document.body.offsetHeight){
touchBtn.style.top = document.body.offsetHeight - touchBtnH + 'px';
touchBtn.className = 'menuViewR';
}
oEvent.preventDefault();
if(oEvent.cancelBubble){
oEvent.cancelBubble = true;
}
else {
oEvent.stopPropagation();
}
},
/**
* [_touchEnd 手指离开]
*/
_touchEnd:function(){
var _self = this;
var touchBtnR = this._bodyW - this._touchMoveX;
var array = [this._touchMoveX,touchBtnR];
var minVal = Math.min.apply(Math, array);
this._removeEvent(this._touchMenuPar,'touchstart',this._touchDown,false);
this._removeEvent(this._touchMenuPar,'touchmove',this.touchMove,false);
this._removeEvent(this._touchMenuPar,'touchend',this.touchUp,false);
this._AddEvent(this._touchMenuPar,'touchstart',this._touchDown,false);
if(!this._isMenuView){
setTimeout(function(){
if(_self._touchMenuPar.className.indexOf('hideTouchBtn')<0){
_self._touchMenuPar.className += ' hideTouchBtn';
}
},2000)
}
if(this._touchMoveX >= this._bodyW){
this._touchMenuPar.style.left = '';
return;
}
for(var i=0;i<array.length;i++){
if(array[i]==minVal){
this._btnWeltAnim(i);
}
}
},
/**
* [setBtnClass 设置按钮样式]
* @param {[string]} arguments [按钮样式]
*/
setBtnClass:function(){
var btnLen = this._menuBtn.length;
var argLen = arguments.length;
var minVal = btnLen > argLen ? argLen : btnLen;
if(this._menuBtn){
for(var i=0;i<minVal;i++){
this._touchMenuView.children[i].className = arguments[i];
}
this._touchMenuView.children[1].className = arguments[1] + ' bds_more';
}
return this;
},
/**
* [_viewMenu 显示菜单]
*/
_viewMenu:function(){
var _self = this;
var touchBtn = this._touchMenuPar;
var touchView = this._touchMenuView;
var touchBtnL = parseInt(touchBtn.style.left);
touchBtn.appendChild(touchView);
if(this._share){
this._share();
}
touchView.style.display = 'block';
var viewMode = this._menuViewMode || 0;
var count = 0;
switch(viewMode){
case 0:{//左
touchBtn.className = 'menuViewR';
this._isBtnClick = false;
this._timer = setInterval(function(){
count += 1 / touchView.children[0].offsetWidth * touchView.children.length * 60;
touchBtn.style.width = touchBtn.offsetWidth + count + 'px';
if(touchBtn.offsetWidth + count >= touchView.children[0].offsetWidth * touchView.children.length + _self._tocuhMenuBtn.offsetWidth){
clearInterval(_self._timer);
_self._isMenuView = false;
_self._isBtnClick = true;
touchBtn.style.width = touchView.children[0].offsetWidth * touchView.children.length + _self._tocuhMenuBtn.offsetWidth + 'px';
}
},1*60/1000);
}
break;
case 1:{//右
touchBtn.className = 'menuViewL';
this._isBtnClick = false;
this._timer = setInterval(function(){
count += 1 / touchView.children[0].offsetWidth * touchView.children.length * 60;
touchBtn.style.width = touchBtn.offsetWidth + count + 'px';
if(touchBtn.offsetWidth + count >= touchView.children[0].offsetWidth * touchView.children.length + _self._tocuhMenuBtn.offsetWidth){
clearInterval(_self._timer);
_self._isMenuView = false;
_self._isBtnClick = true;
touchBtn.style.width = touchView.children[0].offsetWidth * touchView.children.length + _self._tocuhMenuBtn.offsetWidth + 'px';
}
},1*60/1000);
}
break;
}
},
/**
* [_HideMenuL 隐藏菜单]
*/
_HideMenu:function(){
var _self = this;
var touchBtn = this._touchMenuPar;
var touchBtnW = parseInt(touchBtn.style.width);
var touchView = this._touchMenuView;
touchBtn.appendChild(touchView);
touchView.style.display = 'block';
var viewMode = this._menuViewMode || 0;
var count = 0;
switch(viewMode){
case 0:{//左
touchBtn.className = 'menuViewR';
this._isBtnClick = false;
this._timer = setInterval(function(){
count += 1 / touchView.children[0].offsetWidth * touchView.children.length * 600;
touchBtn.style.width = touchBtnW - count + 'px';
if(touchBtn.offsetWidth <= _self._tocuhMenuBtn.offsetWidth - 4){
clearInterval(_self._timer);
_self._isMenuView = true;
_self._isBtnClick = true;
touchBtn.style.width = _self._tocuhMenuBtn.offsetWidth - 4 + 'px';
}
},1*60/1000);
}
break;
case 1:{//右
touchBtn.className = 'menuViewL';
this._isBtnClick = false;
this._timer = setInterval(function(){
count += 1 / touchView.children[0].offsetWidth * touchView.children.length * 600;
touchBtn.style.width = touchBtnW - count + 'px';
if(touchBtn.offsetWidth <= _self._tocuhMenuBtn.offsetWidth - 4){
clearInterval(_self._timer);
_self._isMenuView = true;
_self._isBtnClick = true;
touchBtn.style.width = _self._tocuhMenuBtn.offsetWidth - 4 + 'px';
}
},1*60/1000);
}
break;
}
},
/**
* [_btnWeltAnim 按钮贴边动画]
* @param {[number]} state [数组索引]
*/
_btnWeltAnim:function(state){
var _self = this;
var touchBtn = this._touchMenuPar;
var updateVal = touchBtn.offsetLeft<0?0:touchBtn.offsetLeft;
switch(state){
case 0:{//向左
_self._menuViewMode = 1;
var count = 0;
touchBtn.className = 'menuViewL';
var timer = setInterval(function(){
count += 1/updateVal * 20 * 40/60*1000;
touchBtn.style.left = updateVal - count + 'px';
if(updateVal - count <= 10 || _self._touchMoveX <= 10){
clearInterval(timer);
_self._touchMoveX = 0;
touchBtn.style.left = '10px';
_self._isMenuView = false;
if(!_self._isMenuView){
setTimeout(function(){
if(_self._touchMenuPar.className.indexOf('hideTouchBtn')<0){
_self._touchMenuPar.className += ' hideTouchBtn';
_self._isMenuView = true;
}
},2000)
}
_self._screenOrient();
}
},1*60/1000)
}
break;
case 1:{//向右
_self._menuViewMode = 0;
var count = 0;
touchBtn.className = 'menuViewR';
var timer = setInterval(function(){
count += 1/updateVal * 20 * 40/60*1000;
touchBtn.style.left = updateVal + count + 'px';
if(updateVal + count + touchBtn.offsetWidth >= _self._bodyW - 10){
clearInterval(timer);
touchBtn.style.left ='';
touchBtn.style.right ='10px';
_self._isMenuView = false;
if(!_self._isMenuView){
setTimeout(function(){
if(_self._touchMenuPar.className.indexOf('hideTouchBtn')<0){
_self._touchMenuPar.className += ' hideTouchBtn';
_self._isMenuView = true;
}
},2000)
}
_self._screenOrient();
}
},1*60/1000)
}
break;
}
},
/**
* [_OrientJudge 旋转前最小位置判断]
*/
_OrientJudge:function(){
this._btnPos = [];
var touchBtn = this._touchMenuPar;
var left = touchBtn.offsetLeft;
var top = touchBtn.offsetTop;
var right = document.body.offsetWidth - left - touchBtn.offsetWidth;
var bottom = document.body.offsetHeight - top - touchBtn.offsetHeight;
this._savePos(0,'left',left,'right',right);
this._savePos(1,'top',top,'bottom',bottom);
},
/**
* [_savePos 保存最小位置]
* @param {[number]} index [数组索引]
* @param {[string]} contVal1Str [对比值1]
* @param {[number]} contVal1 [对比值1]
* @param {[string]} contVal2Str [对比值1]
* @param {[number]} contVal2 [对比值2]
*/
_savePos:function(index,contVal1Str,contVal1,contVal2Str,contVal2){
if(contVal1>=contVal2){
this._btnPos[index] = {
pos:contVal2Str,
posVal:contVal2
}
}
},
/**
* [_screenROrient 屏幕旋转]
*/
_screenOrient:function(){
var _self = this;
var screenDire = 0;
this._OrientJudge();
var gameW = this._canvasWH[0];
var gameH = this._canvasWH[1];
this._screendChange = function(){
var media = window.matchMedia("(orientation: portrait)");
if(media.matches){//竖屏
screenDire = 0;
if(gameW<gameH && _self._alertState){
_self._screenMsgBoxImg.src = _self._screenMsgBoxImgArr[1];
_self._screenMsgBox.style.display = 'block';
_self._screenMsgBox.style.height = '100%';
_self._alertState = false;
}
else {
_self._screenMsgBox.style.display = 'none';
_self._screenMsgBox.style.height = '0px';
}
}
else {//横屏
screenDire = 1;
if(gameW>gameH && _self._alertState){
_self._screenMsgBoxImg.src = _self._screenMsgBoxImgArr[0];
_self._screenMsgBox.style.display = 'block';
_self._screenMsgBox.style.height = '100%';
_self._alertState = false;
}
else {
_self._screenMsgBox.style.display = 'none';
_self._screenMsgBox.style.height = '0px';
}
}
if(screenDire != this._screenDire){
this._screenDire = screenDire;
_self._screenState(this._screenDire);
}
}
this._AddEvent(window,'orientationchange',this._screendChange,false);
this._AddEvent(window,'resize',this._screendChange,false);
},
/**
* [_screenState 屏幕旋转状态]
* @param {[number]} scrDir [旋转状态]
*/
_screenState:function(scrDir){
this._bodyW = document.body.offsetWidth;
this._bodyH = document.body.offsetHeight;
var touchBtn = this._touchMenuPar;
if(parseInt(touchBtn.style.top)>=this._bodyH){
touchBtn.style.top = '';
}
switch(scrDir){
case 0:{//竖屏
}
break;
case 1:{//横屏
touchBtn.style.bottom = this._btnPos[1].posVal + 'px';
touchBtn.style.top = '';
touchBtn.style.right = this._btnPos[0].posVal + 'px';
touchBtn.style.left = '';
}
break;
}
},
/**
* [_AddEvent 事件监听兼容]
* @param {[element]} obj [点击对象]
* @param {[string]} sEv [执行事件]
* @param {[Function]} fn [执行的方法]
* @param {[booloean]} state [执行状态]
*/
_AddEvent: function (obj, sEv, fn, state) {
if (obj.addEventListener) {
obj.addEventListener(sEv, fn, state);
}
else {
obj.attachEvent('on' + sEv, function () {
fn.call(obj, event);
});
}
},
/**
* [_removeEvent 移除事件监听兼容]
* @param {[element]} obj [点击对象]
* @param {[string]} sEv [执行事件]
* @param {[Function]} fn [执行的方法]
* @param {[booloean]} state [执行状态]
*/
_removeEvent: function (obj, sEv, fn, state) {
if (obj.removeEventListener) {
obj.removeEventListener(sEv, fn, state);
}
else {
obj.attachEvent('on' + sEv, fn);
}
}
});
function screenSwitch(){
var canvasWH = arguments;
var array = ['','',''];
var gameTouchBtn = new touchBtn(array,50,canvasWH,btnCallback,share);
gameTouchBtn.setBtnClass('screen','share','more').show();
function btnCallback(btn){
for(var i=0;i<btn.length;i++){
switch(i){
case 0 :{//截图按钮
}
break;
case 1 :{//分享按钮
}
break;
case 2:{//回到游戏列表
}
break;
}
}
_AddEvent(btn[0],'click',function(){
var canvas = document.getElementById("gameCanvas");
// alert(canvas.toDataURL());
if(canvas){
var img = new Image();
img.src = canvas.toDataURL();
img.onload = function(){
var imgMsgBox = document.querySelector('#imgMsgBox');
if(!imgMsgBox){
var imgMsgBox = document.createElement('div');//图片悬浮窗
imgMsgBox.id = 'imgMsgBox';
document.body.appendChild(imgMsgBox);
var imgView = document.createElement('img');//悬浮窗显示的图片
imgView.id = 'imgView';
imgMsgBox.appendChild(imgView);
showScreenshots(img,imgMsgBox,imgView);
}
else {
var imgView = document.querySelector('#imgView');
var closeImgMsgBox = document.querySelector('#closeImgMsgBox');
showScreenshots(img,imgMsgBox,imgView);
}
}
}
else {
alert('没有画布');
}
},false);
_AddEvent(btn[2],'click',function(){
window.history.go(-1);
},false);
}
/**
* [showScreenshots 显示截图]
* @param {[object]} img [图片dom]
* @param {[element]} imgMsgBox [图片消息框]
* @param {[element]} imgView [图片显示层]
*/
function showScreenshots(img,imgMsgBox,imgView){
imgView.src=img.src;
imgMsgBox.style.display = 'block';
_AddEvent(imgMsgBox,'click',function(){
imgMsgBox.style.display = 'none';
},false);
_AddEvent(imgView,'click',function(e){
e.stopPropagation();
e.preventDefault();
},false);
}
function share(){//分享功能
var metaCon;//内容
var metaAbstract;//摘要
var allMeta = document.getElementsByTagName('meta');
for (var i = 0; i < allMeta.length; i++)
{
var metaName = allMeta[i].getAttribute('name');
switch(metaName)
{
case 'keywords':
metaCon = allMeta[i].getAttribute('content');
break;
case 'description':
metaAbstract = allMeta[i].getAttribute('content');
break;
default:
break;
}
}
window._bd_share_config = {
common : {
"bdText" : metaCon,//分享内容
"bdDesc" : metaAbstract,//分享摘要
"bdPic" : window.location.origin + '{{IconURL}}',//分享url地址
"bdMiniList" : ["qzone","tsina","weixin","renren","tqq","sqq"],
"bdStyle" : "0",
"bdSize":"32"
},
share : [{
"bdSize" : 32
}]
}
var addScript = document.createElement('script');
addScript.src = 'http://bdimg.share.baidu.com/static/api/js/share.js?v=89860593.js?cdnversion=' + ~(-new Date()/36e5);
document.getElementsByTagName('head')[0].appendChild(addScript);
}
}
/**
* [_AddEvent 事件监听兼容]
* @param {[element]} obj [点击对象]
* @param {[string]} sEv [执行事件]
* @param {[Function]} fn [执行的方法]
* @param {[booloean]} state [执行状态]
*/
function _AddEvent(obj, sEv, fn, state) {
if (obj.addEventListener) {
obj.addEventListener(sEv, fn, state);
}
else {
obj.attachEvent('on' + sEv, function () {
fn.call(obj, event);
});
}
} |
function solve(input){
let matrix = [];
let snowballDamage = 0;
let killedBunniesCounter = 0;
let hangarRows = input.length - 1;
let hangarCols = input[0].split(' ').length;
let bombBunnies = input[input.length - 1]
.split(' ');
for (let i = 0; i < input.length - 1; i++) {
matrix.push(input[i].split(' ').map(Number));
}
for (let i = 0; i < bombBunnies.length; i++) {
let bombArgs = bombBunnies[i].split(',').map(Number);
let bombRow = bombArgs[0];
let bombCol = bombArgs[1];
let bombValue = matrix[bombRow][bombCol];
if (bombValue > 0){
for (let j = bombRow - 1; j <= bombRow + 1; j++) {
for (let k = bombCol - 1; k <= bombCol + 1; k++) {
if((j >= 0) && (k >= 0) && (j < hangarRows) && (k < hangarCols)){
matrix[j][k] -= bombValue;
}
}
}
killedBunniesCounter++;
snowballDamage += bombValue;
}
}
for (let i = 0; i < matrix.length; i++) {
for (let j = 0; j < matrix[i].length; j++) {
if (matrix[i][j] > 0){
snowballDamage += matrix[i][j];
killedBunniesCounter++;
}
}
}
console.log(snowballDamage);
console.log(killedBunniesCounter);
}
solve(['5 10 15 20',
'10 10 10 10',
'10 15 10 10',
'10 10 10 10',
'2,2 0,1']
); |
function setAnswerAnimation() {
let answerSegment = document.getElementsByClassName('answer-segment');
Array.from(answerSegment).forEach(element => {
element.classList.add('fadeInRight');
element.classList.add('animated');
setTimeout(
() => {
element.classList.remove('fadeInRight');
element.classList.remove('animated');
}, 500)
})
}
export default setAnswerAnimation;
|
define([
// Defaults
"jquery",
"angular",
"angularSanitize"
], function($){
"use strict";
var App = {
init: function(MainApp) {
// init App
// ------------------------------------------------------------------------
MainApp.keepoApp.factory("feeds", function ($http, $q, accessToken) {
return {
get: function (page) {
if (page == undefined) page = 1;
var feed_url = MainApp.baseURL + 'api/v1/feed/latest?page=' + page;
// get the token to access api
return accessToken.get().then(
function (token) {
// token received, now get the feeds data
return $http.get(feed_url, token).then(
function (response) {
return response.data;
},
function (response) {
return $q.reject(response.data);
}
);
}
);
}
}
});
MainApp.keepoApp.directive('body', function ($document, $window, feeds) {
return {
restrict: "E",
link: function (scope, element, attrs) {
var visibleHeight = window.innerHeight;
var threshold = window.innerHeight / 3;
$document.bind("scroll", function () {
var scrollableHeight = element.prop('scrollHeight');
var hiddenContentHeight = scrollableHeight - visibleHeight;
if (hiddenContentHeight - $window.pageYOffset <= threshold) {
// Scroll is almost at the bottom. Loading more rows
if (!scope.loadNew) {
scope.loadNew = true;
var page = 2; // first loaded data
if (scope.feeds != undefined) {
page = (scope.feeds.length / 20) + 2;
}
feeds.get(page).then(function (data) {
if (scope.feeds == undefined) {
scope.feeds = data;
} else {
scope.feeds = scope.feeds.concat(data);
}
scope.loadNew = false;
}, function (data) {
console.log("error when loading new feeds");
// fail to load, reset the hook
scope.loadNew = false;
})
}
}
});
}
};
});
MainApp.keepoApp.directive("adsFeed", function () {
return {
restrict: "E",
replace: true,
templateUrl: "feedAds"
}
});
MainApp.keepoApp.directive("pageFeed", function () {
return {
restrict: "E",
replace: true,
templateUrl: "feedTemplate",
controller: ['$scope', 'feeds', function ($scope, feeds) {
$scope.feeds = [];
$scope.loadNew = false;
}]
}
});
// start up the module
MainApp.keepoApp.run();
angular.bootstrap(document.querySelector("html"), ["keepoApp"]);
}
};
return App;
}); |
import React from 'react'
import { AnimatePresence, motion } from "framer-motion"
export const Modal = ({ isToggled, children, dropdownRef }) => {
return (
<AnimatePresence>
{isToggled &&
<motion.div ref ={dropdownRef} className="z-50 relative"
initial={{ opacity: 0 , height:0, width:0 }}
exit={{ opacity: 0 , height:0 , width:0}}
animate={{ opacity: 1 ,height:"auto" , width:"auto", scale: [0.2, 1, 1, 1, 1],
}}
>
<motion.div initial={{ y: 50 }} exit={{ y: 0 }} animate={{ y: -30 }}
>
{children}
</motion.div>
</motion.div>
}
</AnimatePresence>
)
}
|
let dbutton = document.querySelector("#bg-default");
let rbutton = document.querySelector("#bg-random");
let bg = document.querySelector("body");
// Function to reset background to default color
dbutton.addEventListener("click", function() {
bg.style.backgroundColor = "#353535";
});
// Function to change background to random color
rbutton.addEventListener("click", function() {
let r = pickNumber();
let g = pickNumber();
let b = pickNumber();
bg.style.backgroundColor = "rgb(" + [r, g, b].join(",") + ")";
});
// Function to generate random number 0-256
const pickNumber = () => Math.floor(Math.random() * 257);
|
import Vue from 'vue'
import Vuex from 'vuex'
import { UIUXModule } from './uiux.module'
Vue.use(Vuex)
export const store = new Vuex.Store({
modules: {
uiux: UIUXModule,
}
})
|
/**
* Created by mfaivremacon on 02/09/2015.
*/
Meteor.publish('map_objects', function(game_id) {
return MapObjects.find({game_id: game_id});
});
Meteor.publish('teams', function(game_id) {
return Teams.find({game_id: game_id});
});
// publications to every client without needing a subscription
Meteor.publish(null, function() {
return [
Games.find({}),
Meteor.users.find({}),
Chats.find({type: 'lobby'}, {limit: 10, sort: {time: -1}})
]
});
|
function currentUser () {
const guest = {
id: null,
name: "Guest",
loggedIn: false
}
const node = document.getElementById('current_user')
if (node) {
const data = JSON.parse(node.getAttribute('data'))
return data
} else {
return guest
}
}
export default currentUser |
Object.defineProperty(exports, "__esModule", {
value: !0
}), exports.default = void 0;
var _isEmpty = _interopRequireDefault(require("./isEmpty")), _debounce2 = _interopRequireDefault(require("./debounce"));
function _interopRequireDefault(e) {
return e && e.__esModule ? e : {
default: e
};
}
function _defineProperty(e, t, n) {
return t in e ? Object.defineProperty(e, t, {
value: n,
enumerable: !0,
configurable: !0,
writable: !0
}) : e[t] = n, e;
}
function bindFunc(e, t, n) {
var r = e[t];
e[t] = function(e) {
n && n.call(this, e, _defineProperty({}, t, !0)), r && r.call(this, e);
};
}
var methods = [ "linked", "linkChanged", "unlinked" ], extProps = [ "observer" ], _default = Behavior({
lifetimes: {
created: function created() {
this._debounce = null;
}
},
definitionFilter: function definitionFilter(e) {
var n = e.relations;
if (!(0, _isEmpty.default)(n)) {
var t = function t(e) {
var t = n[e];
methods.forEach(function(e) {
return bindFunc(t, e, t.observer);
}), extProps.forEach(function(e) {
return delete t[e];
});
};
for (var r in n) {
t(r);
}
}
Object.assign(e.methods = e.methods || {}, {
getRelationsName: function getRelationsName(e) {
var t = 0 < arguments.length && void 0 !== e ? e : [ "parent", "child", "ancestor", "descendant" ];
return Object.keys(n || {}).map(function(e) {
return n[e] && t.includes(n[e].type) ? e : null;
}).filter(function(e) {
return !!e;
});
},
debounce: function debounce(e, t, n) {
var r = 1 < arguments.length && void 0 !== t ? t : 0, i = 2 < arguments.length && void 0 !== n && n;
return (this._debounce = this._debounce || (0, _debounce2.default)(e.bind(this), r, i)).call(this);
}
});
}
});
exports.default = _default; |
var React = require('react');
var ReactDOM = require('react-dom');
<% if (router === 'router') { -%>
var Router = require('react-router').Router;
var Route = require('react-router').Route;
var browserHistory = require('react-router').browserHistory;
<% } -%>
var Hello = require('./app/hello');
require('./index.<%- css %>');
ReactDOM.render(
<% if (router === 'router') { -%>
<Router history={browserHistory}>
<Route path="/" component={Hello}/>
</Router>,
<% } else { -%>
<Hello/>,
<% } -%>
document.getElementById('root')
);
|
// We want to create a file that has the schema for our items and creates a model that we can then call upon in our controller
var mongoose = require('mongoose');
// create our schema
var ItemSchema = new mongoose.Schema({
//desired key-values below
name: String,
age: Number
});
// use the schema to create the model
// Note that creating a model CREATES the collection in the database (makes the collection plural)
mongoose.model('Item', ItemSchema);
/* N.b. not exporting anything because this file will be run when we require it i the config file and then since the model is defined we'll be able to access it from our controller
*/ |
import { useState } from 'react';
const Login = ({onLogin}) => {
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const handleSubmit = (e) => {
e.preventDefault();
onLogin(email, password);
}
const handleEmailChange = (e) => {
setEmail(e.target.value);
}
const handlePasswordChange = (e) => {
setPassword(e.target.value);
}
return(
<form className="sign-form" onSubmit={handleSubmit}>
<h2 className="sign-form__title">Вход</h2>
<input className="sign-form__input" type="email" placeholder="Email" onChange={handleEmailChange} required/>
<input className="sign-form__input" type="password" placeholder="Пароль" onChange={handlePasswordChange} required/>
<button className="sign-form__button" type="submit">Войти</button>
</form>
);
};
export default Login; |
import React from 'react';
export default class LinearBinary extends React.Component {
constructor(props) {
super(props);
this.state = {
search: '',
message: '',
}
this.numbers = [89, 30, 25, 32, 72, 70, 51, 42, 25, 24, 53, 55, 78, 50, 13, 40, 48, 32, 26, 2, 14, 33, 45, 72, 56, 44, 21, 88, 27, 68, 15, 62, 93, 98, 73, 28, 16, 46, 87, 28, 65, 38, 67, 16, 85, 63, 23, 69, 64, 91, 9, 70, 81, 27, 97, 82, 6, 88, 3, 7, 46, 13, 11, 64, 76, 31, 26, 38, 28, 13, 17, 69, 90, 1, 6, 7, 64, 43, 9, 73, 80, 98, 46, 27, 22, 87, 49, 83, 6, 39, 42, 51, 54, 84, 34, 53, 78, 40, 14, 5]
}
handleChange = (value) => {
this.setState({
search: value
});
}
// Linear Search
// handleSubmit = (e) => {
// e.preventDefault();
// let numSearches = 0;
// let numMessage = '';
// for (let i = 0; i < this.numbers.length; i++) {
// if (this.numbers[i] === parseFloat(this.state.search)) {
// numSearches = i + 1;
// numMessage = `Number found in ${numSearches} searches.`;
// }
// }
// if (numMessage === ``) {
// numMessage = `Number not found. Searched ${this.numbers.length} times.`;
// }
// this.setState({
// message: numMessage
// });
// }
// Binary Search
handleSubmit = (e) => {
e.preventDefault();
let numMessage = '';
let sortedArray = this.numbers.sort(function(a, b){return a - b});
let result = this.binarySearch(sortedArray, parseFloat(this.state.search));
if (typeof result[0] === 'string') {
numMessage = `${result[0]}. Searched ${result[1]} times.`;
} else {
numMessage = `Item found at position ${result[0]}. Searched ${result[1]} times.`
}
this.setState({
message: numMessage
});
}
binarySearch = (array, value, start, end, counter) => {
var start = start === undefined ? 0 : start;
var end = end === undefined ? array.length : end;
var counter = counter === undefined ? 0 : counter;
if (start > end) {
return -1;
}
counter++;
const index = Math.floor((start + end) / 2);
const item = array[index];
console.log(index, item, counter);
if (item == value) {
return [index, counter];
}
else if (item < value) {
return this.binarySearch(array, value, index + 1, end, counter);
}
else if (item > value) {
return this.binarySearch(array, value, start, index - 1, counter);
}
return ['Item not found', counter];
};
render() {
return (
<>
<h1>Search</h1>
<form onSubmit={(e) => this.handleSubmit(e)}>
<input type="text" id="search" value={this.state.value} onChange={(e) => this.handleChange(e.target.value)}></input>
<button type="submit">Search</button>
</form>
<p className="message">{this.state.message}</p>
</>
);
}
}
|
var vows = require('vows'),
assert = require('assert'),
bits = require('./../sqlbits'),
Empty=bits.Empty,
FROM=bits.FROM,
WHERE=bits.WHERE, AND=bits.AND,OR=bits.OR,
BETWEEN=bits.BETWEEN, IN=bits.IN,
ORDERBY=bits.ORDERBY,
GROUPBY=bits.GROUPBY,
LIMIT=bits.LIMIT, OFFSET=bits.OFFSET,
Param=bits.Param,
Statement=bits.Statement,
$=bits.$,
x//used as an undefined value
;
vows.describe("sqltokens tests")
.addBatch({
"parameters": {
"$ with no args": {
topic: $(),
'should return Param': function(topic){
assert.instanceOf(topic, Param);
},
'shouldn\'t have Param.v': function(topic){
assert.isUndefined(topic.v);
}
},
"$ with one arg that is undefined": {
topic: $(undefined),
'should return aaram': function(topic){
assert.instanceOf(topic, Param);
},
'should have Param.v': function(topic){
assert.isUndefined(topic.v);
}
},
"$ with one arg": {
topic: $(99),
'should return Param': function(topic){
assert.instanceOf(topic, Param);
},
'should have Param.v': function(topic){
assert.isDefined(topic, "v");
},
'should contain the value': function(topic){
assert.equal(topic.v, 99);
}
},
"with ASC": {
topic: $("id").ASC,
'should return Param': function(topic){
assert.instanceOf(topic, Param);
},
'should have ASC assigned to token property': function(topic){
assert.equal('ASC', topic.token);
}
},
"with DESC": {
topic: $("id").DESC,
'should return Param': function(topic){
assert.instanceOf(topic, Param);
},
'should have DESC assigned to token property': function(topic){
assert.equal('DESC', topic.token);
}
},
BOOKEND:{}
},
"IN": {
"with no parameters": {
topic: IN(),
'should return Param': function(topic){
assert.instanceOf(topic, Param);
},
'shouldn\'t have Param.v': function(topic){
assert.isUndefined(topic.v);
}
},
"with []": {
topic: IN([]),
'should return Param': function(topic){
assert.instanceOf(topic, Param);
},
'shouldn\'t have Param.v': function(topic){
assert.isUndefined(topic.v);
}
},
"with [undefined]": {
topic: IN([undefined]),
'should return Param': function(topic){
assert.instanceOf(topic, Param);
},
'shouldn\'t have Param.v': function(topic){
assert.isUndefined(topic.v);
}
},
"with only 1 param which is undefined": {
topic: IN(undefined),
'should return Param': function(topic){
assert.instanceOf(topic, Param);
},
'shouldn\'t have Param.v': function(topic){
assert.isUndefined(topic.v);
}
},
"with only 1 arg": {
topic: IN('1,2,3'),
'Param.v should be an array with the length of 1': function(topic){
assert.isArray(topic.v);
assert.lengthOf(topic.v, 1);
},
'Param.v[0] should be the arg': function(topic){
assert.isArray(topic.v);
assert.equal(topic.v[0], '1,2,3');
}
},
"with only 1 arg that is a Param": {
topic: IN($(1)),
'Param.v should be an array with the length of 1': function(topic){
assert.isArray(topic.v);
assert.lengthOf(topic.v, 1);
},
'Param.v[0] should be the Param': function(topic){
assert.isArray(topic.v);
assert.instanceOf(topic.v[0], Param);
}
},
"passing an array": {
topic: IN([1,2,3]),
'Param.v should contain Params for each item': function(topic){
assert.isArray(topic.v);
assert.lengthOf(topic.v, 3);
topic.v.forEach(function(p){
assert.instanceOf(p, Param);
});
}
},
"multiple undefined values": {
topic: IN([x,x,x]),
'should return Param': function(topic){
assert.instanceOf(topic, Param);
},
'shouldn\'t have Param.v': function(topic){
assert.isUndefined(topic.v);
}
},
"with several parameters": {
topic: IN( $(1), $(2) ),
'Param.v should contain Params for each item': function(topic){
assert.isArray(topic.v);
assert.lengthOf(topic.v, 2);
topic.v.forEach(function(p){
assert.instanceOf(p, Param);
});
}
},
BOOKEND:{}
},
"BETWEEN": {
"with no parameters": {
topic: BETWEEN(),
'should return Param': function(topic){
assert.instanceOf(topic, Param);
},
'shouldn\'t have Param.v': function(topic){
assert.isUndefined(topic.v);
}
},
"with undefined args": {
topic: BETWEEN(undefined),
'should return Param': function(topic){
assert.instanceOf(topic, Param);
},
'shouldn\'t have Param.v': function(topic){
assert.isUndefined(topic.v);
}
},
"passing a min & max": {
topic: BETWEEN(1,2),
'Param.v should hold [min,max]': function(topic){
assert.isArray(topic.v);
assert.instanceOf(topic.v[0], Param);
assert.instanceOf(topic.v[1], Param);
assert.equal(topic.v[0].v, 1);
assert.equal(topic.v[1].v, 2);
}
},
"passing only a min": {
topic: BETWEEN(1),
'Param.v should hold [min]': function(topic){
assert.isArray(topic.v);
assert.instanceOf(topic.v[0], Param);
assert.isUndefined(topic.v[1].v);
assert.equal(topic.v[0].v, 1);
}
},
"passing only a max": {
topic: BETWEEN(undefined, 2),
'Param.v should hold [,max]': function(topic){
assert.isArray(topic.v);
assert.isUndefined(topic.v[0].v);
assert.instanceOf(topic.v[1], Param);
assert.equal(topic.v[1].v, 2);
}
},
BOOKEND:{}
},
"WHERE/AND/OR": {//internally uses the same code
"with no parameters": {
topic: AND(),
'should return Empty': function(topic){
assert.equal(Empty, topic);
}
},
"with a single parameter": {
topic: AND("1=1"),
'should output a Statement with the single expression': function(topic){
assert.instanceOf(topic, Statement);
assert.deepEqual({ token: 'AND', expression: '1=1' }, topic);
}
},
"when valid for output": {
"(WHERE)": {
topic: WHERE("1=1"),
'should have a "WHERE" token': function(topic){
assert.equal("WHERE", topic.token);
}
},
"(AND)": {
topic: AND("1=1"),
'should have an "AND" token': function(topic){
assert.equal("AND", topic.token);
}
},
"(OR)": {
topic: OR("1=1"),
'should have an "OR" token': function(topic){
assert.equal("OR", topic.token);
}
}
},
"with a param": {
topic: AND("1=", $(0)),
'should output a Statement with the expression and the $param': function(topic){
assert.deepEqual({ token: 'AND', expression: '1=', param: {v:0} }, topic);
}
},
"when param references something undefined": {
topic: AND("foo=", $(x)),
'the Statement should be Empty': function(topic){
assert.equal(Empty, topic);
}
},
"when the 2nd arg is a Param that doesn't yield a result": {
topic: AND("foo", IN($(x),$(x))),
'the Statement should be Empty': function(topic){
assert.equal(Empty, topic);
}
},
"with a grouped condition": {
topic: AND("1=", $(1), OR("2=2")),
'should output a group array': function(topic){
assert.isArray(topic);
assert.lengthOf(topic, 2);
assert.deepEqual(topic[0], { token: 'AND', expression: '1=', param: { v: 1 } });
assert.deepEqual(topic[1], { token: 'OR', expression: '2=2' });
assert.equal('AND', topic.token);
}
},
"with an object": {
topic: WHERE({a:1,b:2,c:3}),
'should AND the properties': function(topic){
assert.isArray(topic);
assert.lengthOf(topic, 3);
assert.deepEqual(topic[0], { token: 'AND', expression: 'a=', param: { v: 1 } });
assert.deepEqual(topic[1], { token: 'AND', expression: 'b=', param: { v: 2 } });
assert.deepEqual(topic[2], { token: 'AND', expression: 'c=', param: { v: 3 } });
assert.equal('WHERE', topic.token);
}
},
BOOKEND:{}
},
"FROM":{
"with no parameters": {
topic: FROM(),
'should return Empty': function(topic){
assert.equal(Empty, topic);
}
},
"with undefined args": {
topic: FROM(undefined),
'should return Empty': function(topic){
assert.equal(Empty, topic);
}
},
"with a table specified": {
topic: FROM("customers"),
'should have a "FROM" token': function(topic){
assert.equal("FROM", topic.token);
},
'should add the table as the expression': function(topic){
assert.equal("customers", topic.expression);
}
},
BOOKEND:{}
},
"ORDERBY/GROUPBY": {//internally uses the same code
"with no parameters": {
topic: GROUPBY(),
'should return Empty': function(topic){
assert.equal(Empty, topic);
}
},
"with an undefined arg": {
topic: GROUPBY(undefined),
'should return Empty': function(topic){
assert.equal(Empty, topic);
}
},
"with all undefined args":{
topic: GROUPBY(x,x,x),
'should return Empty': function(topic){
assert.equal(topic, Empty);
}
},
"with a column specified":{
topic: GROUPBY("id"),
'should assign an Array of the arguments to Statement.args': function(topic){
assert.isArray(topic.args);
assert.lengthOf(topic.args, 1);
},
'should the statement and the column': function(topic){
assert.typeOf(topic.args[0], "string");
}
},
"with args specified": {
topic: GROUPBY("id", 1, new Date, $("date"), "type"),
'should ignore non-string or Params values': function(topic){
assert.isArray(topic.args);
topic.args.forEach(function(item){
var isValid = item instanceof Param || typeof item === "string";
assert.isTrue(isValid);
});
}
},
"with an array passed in": {
topic: GROUPBY(["id",1,"date"]),
'should assign an Array of the arguments to Statement.args': function(topic){
assert.isArray(topic.args);
},
'should ignore non-strings': function(topic){
assert.lengthOf(topic.args, 2);
},
'should make all items Param objects': function(topic){
assert.isArray(topic.args);
topic.args.forEach(function(item){
assert.instanceOf(item, Param);
assert.typeOf(item.v, "string");
});
}
},
BOOKEND:{}
},
"LIMIT/OFFSET": {//internally uses the same code
"with no parameters": {
topic: LIMIT(),
'should return 0': function(topic){
assert.equal("0", topic.expression);
}
},
"with undefined args": {
topic: OFFSET(undefined),
'should return 0': function(topic){
assert.equal("0", topic.expression);
}
},
"with the expression": {
"(LIMIT)": {
topic: LIMIT(100),
'should have a "LIMIT" token': function(topic){
assert.equal("LIMIT", topic.token);
}
},
"(OFFSET)": {
topic: OFFSET(99),
'should have an "OFFSET" token': function(topic){
assert.equal("OFFSET", topic.token);
}
}
},
BOOKEND:{}
},
BOOKEND:{}
})
.export(module);
// .run();
/* For ref:
AssertionError
fail
ok
equal
notEqual
deepEqual
notDeepEqual
strictEqual
notStrictEqual
throws
doesNotThrow
ifError
match
matches
isTrue
isFalse
isZero
isNotZero
greater
lesser
inDelta
include
includes
deepInclude
deepIncludes
isEmpty
isNotEmpty
lengthOf
isArray
isObject
isNumber
isBoolean
isNaN
isNull
isNotNull
isUndefined
isDefined
isString
isFunction
typeOf
instanceOf
*/
|
import { GAMME_CHANGED } from '../actions/types';
export default (state = null, action) => {
switch (action.type) {
case GAMME_CHANGED:
console.log('gamme changed');
return { ...state, gamme: action.payload };
default:
return state;
}
}
|
/**
* 暴力解法: 回溯 O(2^n)
* 特征: n[i][j] = n[i - 1][j] + n[i][j - 1]
* 动态规划: 二维数组避免重复计算 空间O(n^2) 时间O(m * n)
*/
/**
* @param {number} m
* @param {number} n
* @return {number}
*/
var uniquePaths = function(m, n) {
let step = [ [0] ];
let min = Math.min(m, n);
let max = Math.max(m, n);
for (let i = 0; i < min; i++) {
step[i] = step[i] || [];
for (let j = 0; j < i; j++) {
step[i - 1] = step[i - 1] || '0'.repeat(min).split('').map(i => {return +i});
step[i][j] = step[i - 1][j] + (+step[i][j - 1] || 0);
}
for (let j = 0; j < i; j++) {
step[j - 1] = step[j - 1] || '0'.repeat(min).split('').map(i => {return +i});
step[j][i] = step[j - 1][i] + (step[j][i - 1] || 0);
}
step[i][i] = i ? step[i][i - 1] + step[i][i - 1] : 1;
}
for (let i = min; i < max; i++) {
for (let j = 0; j < min; j++) {
step[i] = step[i] || [];
step[i][j] = j ? step[i - 1][j] + step[i][j - 1] : step[i - 1][j];
}
}
return step[max -1][min - 1];
};
var uniquePaths = function(m, n) {
const step = '0'.repeat(m).split('').map(i => [+i]);
for (let i = 0; i < m; i++) {
for (let j = 0; j < n; j++) {
if (i === 0 || j === 0) {
step[i][j] = 1;
} else {
step[i][j] = step[i - 1][j] + step[i][j - 1];
}
}
}
return step[m - 1][n -1];
}
console.log(uniquePaths(7, 3)); |
(function($) {
var a = $.scrollTo = function(d, f, e) {
$(window).scrollTo(d, f, e)
};
a.defaults = {
axis: "xy",
duration: parseFloat($.fn.jquery) >= 1.3 ? 0 : 1
};
a.window = function(d) {
return $(window)._scrollable()
};
$.fn._scrollable = function() {
return this.map(function() {
var f = this,
d = !f.nodeName || $.inArray(f.nodeName.toLowerCase(), ["iframe", "#document", "html", "body"]) != -1;
if (!d) {
return f
}
var e = (f.contentWindow || f).document || f.ownerDocument || f;
return $.browser.safari || e.compatMode == "BackCompat" ? e.body: e.documentElement
})
};
$.fn.scrollTo = function(d, f, e) {
if (typeof f == "object") {
e = f;
f = 0
}
if (typeof e == "function") {
e = {
onAfter: e
}
}
if (d == "max") {
d = 9000000000
}
e = $.extend({},
a.defaults, e);
f = f || e.speed || e.duration;
e.queue = e.queue && e.axis.length > 1;
if (e.queue) {
f /= 2
}
e.offset = b(e.offset);
e.over = b(e.over);
return this._scrollable().each(function() {
var g = this,
h = $(g),
l = d,
m,
i = {},
j = h.is("html,body");
switch (typeof l) {
case "number":
case "string":
if (/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(l)) {
l = b(l);
break
}
l = $(l, this);
case "object":
if (l.is || l.style) {
m = (l = $(l)).offset()
}
}
$.each(e.axis.split(""),
function(n, u) {
var p = u == "x" ? "Left": "Top",
o = p.toLowerCase(),
s = "scroll" + p,
r = g[s],
t = a.max(g, u);
if (m) {
i[s] = m[o] + (j ? 0 : r - h.offset()[o]);
if (e.margin) {
i[s] -= parseInt(l.css("margin" + p)) || 0;
i[s] -= parseInt(l.css("border" + p + "Width")) || 0
}
i[s] += e.offset[o] || 0;
if (e.over[o]) {
i[s] += l[u == "x" ? "width": "height"]() * e.over[o]
}
} else {
var q = l[o];
i[s] = q.slice && q.slice( - 1) == "%" ? parseFloat(q) / 100 * t: q
}
if (/^\d+$/.test(i[s])) {
i[s] = i[s] <= 0 ? 0 : Math.min(i[s], t)
}
if (!n && e.queue) {
if (r != i[s]) {
k(e.onAfterFirst)
}
delete i[s]
}
});
k(e.onAfter);
function k(n) {
h.animate(i, f, e.easing, n &&
function() {
n.call(this, d, e)
})
}
}).end()
};
a.max = function(f, j) {
var e = j == "x" ? "Width": "Height",
h = "scroll" + e;
if (!$(f).is("html,body")) {
return f[h] - $(f)[e.toLowerCase()]()
}
var d = "client" + e,
i = f.ownerDocument.documentElement,
g = f.ownerDocument.body;
return Math.max(i[h], g[h]) - Math.min(i[d], g[d])
};
function b(d) {
return typeof d == "object" ? d: {
top: d,
left: d
}
}
})(jQuery);
(function($) {
var b = {
put: function(g, h) { (h || window).location.hash = encodeURIComponent(g)
},
get: function(g) {
var h = ((g || window).location.hash).replace(/^#/, "");
// return $.browser.fx ? h: decodeURIComponent(h)
return decodeURIComponent(h)
}
};
var c = {
id: "__jQuery_history",
init: function() {
var g = '<iframe id="' + this.id + '" style="display:none" src="javascript:false;" />';
$("body").prepend(g);
return this;
},
_document: function() {
return $("#" + this.id)[0].contentWindow.document;
},
put: function(g) {
var h = this._document();
h.open();
h.close();
b.put(g, h)
},
get: function() {
return b.get(this._document());
}
};
var _history = {
appState: undefined,
callback: undefined,
init: function(g) {},
check: function() {},
load: function(g) {}
};
$.history = _history;
var _historyNormal = {
init: function(g) {
_history.callback = g;
var h = b.get();
_history.appState = h;
_history.callback(h);
setInterval(_history.check, 100)
},
check: function() {
var g = b.get();
if (g != _history.appState) {
_history.appState = g;
_history.callback(g)
}
},
load: function(g) {
if (g != _history.appState) {
b.put(g);
_history.appState = g;
_history.callback(g)
}
}
};
var _historyIE = {
init: function(g) {
_history.callback = g;
var h = b.get();
_history.appState = h;
c.init().put(h);
_history.callback(h);
setInterval(_history.check, 100)
},
check: function() {
var g = c.get();
if (g != _history.appState) {
b.put(g);
_history.appState = g;
_history.callback(g)
}
},
load: function(g) {
if (g != _history.appState) {
b.put(g);
c.put(g);
_history.appState = g;
_history.callback(g)
}
}
};
// if ($.browser.msie && ($.browser.version < 8 || document.documentMode < 8)) {
// $.extend(_history, _historyIE)
// } else {
$.extend(_history, _historyNormal);
// }
})(jQuery);
function pageHistory(param) {
var that = this;
this.defaults = $.extend({},param);
for (att in param) {
that[att] = param[att]
}
this.toUrl = function() {
var c = [];
for (att in that) {
if (att != "defaults" && typeof(that[att]) != "function") {
c.push(att + "_" + that[att])
}
}
return c.join("-")
};
this.parseUrl = function(d) {
var c = $.extend({},that.defaults);
$.each(d.split("-"),
function() {
var e = this.split("_");
c[e[0]] = e[1]
});
return c
};
this.update = function(c) {
var d = false;
for (att in c) {
if (typeof(that[att]) == "undefined") {
continue
}
d |= (c[att] != that[att]);
that[att] = c[att]
}
return d
}
}
function parsePagedUrl(pageUrl) {
var result = {},
i,
// f = /\+/g,
h = /([^&=]+)=?([^&]*)/g,
decodeUrl = function(_url) {
return decodeURIComponent(_url.replace(/\+/g, " "))
},
g = pageUrl.split("?").pop();
while (i = h.exec(g)) {
result[decodeUrl(i[1])] = decodeUrl(i[2]);
}
return result;
}
function loadUrl(url, id, page, sort, filter, c) {
if (page > -1) {
url += "&page=" + page
}
if (sort != null) {
url += "&sort=" + sort
}
if (filter != null) {
url += "&filter=" + filter
}
if (typeof userViewStartDate != "undefined" && !!userViewStartDate) {
url += "&StartDate=" + userViewStartDate
}
// $.post(url,function(data) {
// $(id).html(data);
// });
// xuesong 更改post为get
$.get(url,function(data) {
$(id).html(data);
});
if (c != true) {
$.scrollTo(id, 400)
}
}
function loadReputation(page, sort, a) {
loadUrl(iAsk.options.links.userRep +"/?do=show&uid=" + uid, "#rep-page-container", page, sort, null, a)
}
function loadActivity(page, filter, a) {
loadUrl(iAsk.options.links.userActivity+"/?do=show&pagesize=" + activityPageSize + "&uid=" + uid, "#history-table", page, null, filter, a)
}
function loadResponses(page, filter, a) {
loadUrl("/users/responses/show?pagesize=" + responsesPageSize + "&uid=" + uid, "#history-table", page, null, filter, a)
}
function loadAnswers(page, sort) {
loadUrl(iAsk.options.links.userStat+"/?do=answers&pagesize=" + answersPageSize + "&uid=" + uid, "#answers-table", page, sort)
}
function loadQuestions(page, sort) {
loadUrl(iAsk.options.links.userStat+"/?do=questions&pagesize=" + questionsPageSize + "&uid=" + uid, "#questions-table", page, sort)
}
function loadTags(page) {
$.get(iAsk.options.links.userStat+"/?do=tags&pagesize="+tagsPageSize + "&uid=" + uid + "&page=" + page,function(data) {
$("#tags-table").html(data)
})
}
function loadFavorites(page, sort) {
var url = favsUrl + "&pagesize=" + favoritesPageSize + "&uid=" + uid + "&sort=" + sort;
if (page > -1) {
url += "&page=" + page
}
$.get(url, function(data) {
var e = $(data);
$("#favorites-table").html(e)
});
if ($(this).closest(".favorite-pager").length > 0) {
$.scrollTo("#favorites-table", 400)
}
}
$(function() {
var pHistory = null;
if (typeof(questionsSortOrder) != "undefined") {
pHistory = new pageHistory({
qpage: 1,
anpage: 1,
qsort: questionsSortOrder,
ansort: answersSortOrder
})
}
if ($("#favorites-table").length > 0) {
pHistory = new pageHistory({
fpage: 1,
fsort: favoritesSortOrder
})
}
if ($(".user-activity-table").length > 0) {
pHistory = new pageHistory({
apage: 1,
afilter: activityFilter
})
}
if ($(".user-responses-table").length > 0) {
pHistory = new pageHistory({
rpage: 1,
rfilter: responsesFilter
})
}
if ($("#rep-page-container").length > 0) {
pHistory = new pageHistory({
reppage: 1,
repview: reputationView
})
}
if (pHistory != null) {
$.history.init(function(c) {
var b = pHistory.parseUrl(c);
if (pHistory.update({
qpage: b.qpage,
qsort: b.qsort
})) {
loadQuestions(b.qpage, b.qsort)
}
if (pHistory.update({
apage: b.apage,
afilter: b.afilter
})) {
loadActivity(b.apage, b.afilter, true)
}
if (pHistory.update({
reppage: b.reppage,
repview: b.repview
})) {
loadReputation(b.reppage, b.repview)
}
if (pHistory.update({
rpage: b.rpage,
rfilter: b.rfilter
})) {
loadResponses(b.rpage, b.rfilter, true)
}
if (pHistory.update({
anpage: b.anpage,
ansort: b.ansort
})) {
loadAnswers(b.anpage, b.ansort)
}
if (pHistory.update({
fpage: b.fpage,
fsort: b.fsort
})) {
loadFavorites(b.fpage, b.fsort)
}
})
}
$(document).on("click", "#question-pager a, #tabs-question-user a", function (event) {
event.preventDefault();
var u = parsePagedUrl(this.href);
loadQuestions(u.page, u.sort);
pHistory.update({
qpage: u.page,
qsort: u.sort
});
$.history.load(pHistory.toUrl());
return false;
});
$(document).on("click", "#activity-pager a, #tabs-activity a", function (event) {
event.preventDefault();
var c = parsePagedUrl(this.href);
loadActivity(c.page, c.filter, $(this).parent().attr("id") == "tabs-activity");
pHistory.update({
apage: c.page,
afilter: c.filter
});
$.history.load(pHistory.toUrl());
return false
});
$(document).on("click", "#reputation-pager a, #tabs-reputation a", function(event) {
event.preventDefault();
var c = parsePagedUrl(this.href);
loadReputation(c.page, c.sort, $(this).parent().attr("id") == "tabs-reputation");
pHistory.update({
reppage: c.page,
repview: c.sort
});
$.history.load(pHistory.toUrl());
return false
});
$("#responses-pager a, #tabs-responses a").on("click", function (event) {
event.preventDefault();
var c = parsePagedUrl(this.href);
loadResponses(c.page, c.rfilter, $(this).parent().attr("id") == "tabs-responses");
pHistory.update({
rpage: c.page,
rfilter: c.rfilter
});
$.history.load(pHistory.toUrl());
return false
});
$(document).on("click", "#answer-pager a, #tabs-answer-user a", function (event) {
event.preventDefault();
var c = parsePagedUrl(this.href);
loadAnswers(c.page, c.sort);
pHistory.update({
anpage: c.page,
ansort: c.sort
});
$.history.load(pHistory.toUrl());
return false;
});
$(document).on("click", "#tags-pager a",function (event) {
event.preventDefault();
var c = RegExp(/page=([^&]+).*/).exec(this.href);
if (c) {
loadTags(c[1]);
} else {
loadTags(1);
}
$.scrollTo($("#tags-title"), 400);
return false;
});
$(document).on("click", "#favorite-pager a, #tabs-favorite-user a",function(event) {
event.preventDefault();
var c = parsePagedUrl(this.href);
loadFavorites(c.page, c.sort);
pHistory.update({
fpage: c.page,
fsort: c.sort
});
$.history.load(pHistory.toUrl());
return false;
})
});
function initRepGraphs(k, f) {
var l = [],
b = 0,
e = 0,
v = 24 * 60 * 60 * 1000,
c = 30 * v,
m = "rgba(0, 70, 200, 0.2)";
for (var j = 0; j < k.length; j++) {
var r = k[j];
var t = Date.UTC(r[0], r[1] - 1, r[2]);
var n = r[3];
if (n < b) {
b = n
}
if (n > e) {
e = n
}
if (n < 0) {
l.push({
color: "maroon",
x: t,
y: n
})
} else {
l.push([t, n])
}
}
function u() {
var d = [];
d.push({
color: "#bbb",
width: 1,
value: 0,
zIndex: 5
});
if (e > 200) {
d.push({
color: "#aaa",
width: 1,
value: 200,
zIndex: 5
})
}
return d
}
var p = new Date(),
o = l[0][0] || l[0]["x"],
h = Date.UTC(p.getUTCFullYear(), p.getUTCMonth(), p.getUTCDate()),
a = h - c,
q,
w;
if (l.length == 1) {
l.push([o - v, 0])
}
if (o > a) {
o = a
} else {
$("#master-graph, #graph-help").show()
}
q = new Highcharts.Chart({
chart: {
renderTo: "master-graph",
animation: false,
reflow: false,
borderWidth: 0,
marginLeft: 62,
backgroundColor: null,
zoomType: "x",
events: {
selection: g
}
},
series: [{
data: l,
type: "column",
color: "green"
}],
plotOptions: {
series: {
animation: false,
lineWidth: 1,
marker: {
enabled: false
},
shadow: false,
states: {
hover: {
lineWidth: 1
}
},
enableMouseTracking: false
},
column: {
borderWidth: 0,
pointPadding: 0,
groupPadding: 0
}
},
xAxis: {
type: "datetime",
min: o,
max: h,
maxZoom: c,
plotBands: [{
id: "selected-area",
from: a,
to: h,
color: m
}],
title: {
text: null
},
labels: {
formatter: function() {
var d = ((h - o) > (c * 3)) ? "%b '%y": "%b %e";
return Highcharts.dateFormat(d, this.value, false)
}
},
lineWidth: 0
},
yAxis: {
gridLineWidth: 0,
labels: {
enabled: false
},
title: {
text: null
},
plotLines: u(),
min: b,
max: e,
showFirstLabel: false,
endOnTick: false,
startOnTick: false
},
title: {
text: null
},
legend: {
enabled: false
},
tooltip: {
formatter: function() {
return false
}
},
credits: {
enabled: false
},
exporting: {
enabled: false
}
},
function(d) {
s(d)
});
function g(x) {
var i = x.xAxis[0],
d = i.min,
y = i.max,
z = this.xAxis[0];
z.removePlotBand("selected-area");
z.addPlotBand({
id: "selected-area",
from: d,
to: y,
color: m
});
s(this);
return false
}
function s(A) {
var B, C, z = 0,
D = 0,
i = y();
if (!w) {
w = new Highcharts.Chart({
chart: {
renderTo: "detail-graph",
animation: false,
defaultSeriesType: "column"
},
series: [{
name: "rep",
data: i,
color: "green"
}],
plotOptions: {
series: {
animation: false,
cursor: "pointer",
allowPointSelect: true,
shadow: false,
stickyTracking: true,
states: {
hover: {
enabled: true,
brightness: 0.5
}
}
},
column: {
pointPadding: 0.03,
groupPadding: 0,
borderWidth: 0,
events: {
click: x
}
}
},
xAxis: {
type: "datetime",
labels: {
rotation: 0,
formatter: function() {
return Highcharts.dateFormat("%b %e", this.value, false)
}
},
lineWidth: 0,
min: B,
max: C
},
yAxis: {
gridLineWidth: 0,
plotLines: u(),
min: z,
max: D,
title: {
text: "reputation per day"
},
endOnTick: false,
startOnTick: false
},
tooltip: {
style: {
lineHeight: 2,
padding: 10
}
},
title: {
text: null
},
legend: {
enabled: false
},
credits: {
enabled: false
}
})
} else {
w.yAxis[0].setExtremes(z, D, false);
w.xAxis[0].setExtremes(B, C, false);
w.series[0].setData(i)
}
function y() {
var H = [],
G = A.xAxis[0],
F = G.plotLinesAndBands[0].options;
B = F.from;
C = F.to;
$.each(A.series[0].data,
function(I, J) {
if (J.x >= B && J.x < C) {
H.push({
x: J.x,
y: J.y,
color: J.color
});
if (J.y < z) {
z = J.y
}
if (J.y > D) {
D = J.y
}
} else {
if (J.x > C) {
return
}
}
});
if (D > 0 && D < 200) {
D = 200
}
return H
}
var d, E;
function x(G) {
var F = G.point.options;
var H = $(".day-details");
if (H.data("loading") || (d && d.x == F.x && d.y == F.y)) {
return
}
H.html("").data("loading", true).addSpinner();
$.ajax({
type: "GET",
url: "/users/rep-day/{userid}/{epochTime}?sort=time&showFullDates=true".format({
userid: f,
epochTime: (F.x / 1000)
}),
dataType: "html",
success: function(J) {
var I = $(J);
H.html(I);
d = F;
var K = I.height();
if (!E || K > E) {
E = K;
H.css("height", K)
}
},
error: function(I, K, J) {
H.showErrorPopup("An error occurred when loading rep info")
},
complete: function() {
StackExchange.helpers.removeSpinner();
H.data("loading", false)
}
})
}
}
}
function logDate(b, a) {
log((a ? (a + ": ") : "") + new Date(b).toUTCString())
}
function log(a) {
if (typeof console == "object" && typeof console.log == "function") {
console.log(a)
}
}; |
import chai from 'chai';
import chaiHttp from 'chai-http';
import jwt from 'jsonwebtoken';
import fs from 'fs';
import dotenv from 'dotenv';
import index from '../src/index';
chai.use(chaiHttp);
chai.should();
chai.expect();
dotenv.config();
const userToken1 = jwt.sign({
id: 4,
username: 'rafiki',
email: 'rafiki@gmail.com',
role: 'admin'
}, process.env.SECRET_JWT_KEY, { expiresIn: '24h' });
const userToken2 = jwt.sign({
id: 5,
username: 'mufasa',
email: 'mufasa@gmail.com',
role: 'admin'
}, process.env.SECRET_JWT_KEY, { expiresIn: '24h' });
const userToken3 = jwt.sign({
id: 9,
username: 'akpalo',
email: 'akpalo@gmail.com',
role: 'admin'
}, process.env.SECRET_JWT_KEY, { expiresIn: '24h' });
describe('User notifications', () => {
it('A user should be able to get all notifications', (done) => {
chai.request(index)
.get('/api/notifications')
.set('token', userToken1)
.end((err, res) => {
res.status.should.equal(200);
res.body.should.be.an('object');
done();
});
});
it('A user should be notified if they have no notifications', (done) => {
chai.request(index)
.get('/api/notifications')
.set('token', userToken3)
.end((err, res) => {
res.status.should.equal(404);
res.body.should.be.an('object');
res.body.message.should.equal('You are all caught up, you have zero notifications');
done();
});
});
it('A user should be able to get his or her notification preference', (done) => {
chai.request(index)
.get('/api/notifications/config')
.set('token', userToken2)
.end((err, res) => {
res.status.should.equal(200);
res.body.should.be.an('object');
done();
});
});
it('A user should be able to update his or her notification preference', (done) => {
const config = {
inApp: true,
email: false
};
chai.request(index)
.put('/api/notifications/config')
.set('token', userToken2)
.send(config)
.end((err, res) => {
res.status.should.equal(200);
res.body.should.be.an('object');
res.body.config.userId.should.equal(5);
done();
});
});
it('A user should not be able to update his or her notification preference if the right inputs are not provided', (done) => {
const config = {
inApp: 't',
email: 'f'
};
chai.request(index)
.put('/api/notifications/config')
.set('token', userToken2)
.send(config)
.end((err, res) => {
res.status.should.equal(400);
res.body.should.be.an('object');
res.body.Errors.should.be.an('array');
res.body.Errors[0].should.equal(' inApp must be a boolean');
done();
});
});
it('All users should be notified when an author they follow creates an article', (done) => {
chai.request(index)
.post('/api/articles')
.set('token', userToken1)
.set('Content-Type', 'application/json')
.field('title', 'Jungle King')
.field('body', 'The Lion is King')
.field('description', 'All animals know this')
.attach('image', fs.readFileSync(`${__dirname}/mock/sam.jpg`), 'sam.jpg')
.end((err, res) => {
res.body.should.be.an('object');
res.status.should.be.equal(201);
res.body.should.have.property('article');
res.body.article.should.have.property('image');
});
done();
});
it('An author should be notified when a comment is made on his or her article', (done) => {
const comment = { body: 'Good job rafiki' };
chai.request(index)
.post('/api/comments/articles/stay-alive')
.set('token', userToken2)
.send(comment)
.end((err, res) => {
res.body.should.be.an('object');
res.status.should.be.eql(201);
res.body.should.have.property('message');
});
done();
});
it('An author should be notified when his or her article is liked', (done) => {
chai.request(index)
.post('/api/articles/like/stay-alive')
.set('token', userToken2)
.end((err, res) => {
res.body.should.be.an('object');
res.body.should.have.property('liked');
res.body.should.have.property('disliked');
res.body.liked.should.equal(true);
});
done();
});
it('An author should be notified when his or her article is disliked', (done) => {
chai.request(index)
.post('/api/articles/dislike/stay-alive')
.set('token', userToken2)
.end((err, res) => {
res.body.should.be.an('object');
res.body.should.have.property('liked');
res.body.should.have.property('disliked');
res.body.disliked.should.equal(true);
});
done();
});
});
|
import React, { Component } from 'react';
import Item from './item';
import Item2 from './item2';
import Item3 from './item3';
import Item4 from './item4';
import Item5 from './item5';
import Item6 from './item6';
import Item7 from './item7';
import Item8 from './item8';
import Item9 from './item9';
import ItemService from './../services/itemService';
import "./catalog.css";
class Catalog extends Component {
state = {
items: [],
};
render() {
return (
<div className="catalog-page">
{this.state.items.map((x) => (
<Item></Item>
))}
</div>
);
}
//called after the render function is executed (after something has loaded onto the users screen)
componentDidMount(){
//call the service to get the list of items
var service = new ItemService();
var items = service.getCatalog();
this.setState({items: items});
}
}
export default Catalog; |
class Pomodoro{
sessionModify(crement=0){
let time = parseInt(sessionTime.textContent);
if( time == 0 && crement == -1){
return;
}
time = time + crement;
sessionTime.textContent = time.toString();
if(type === 'session' && timerWorkStatus == 0){
clock.textContent = time+":00";
timerHeading.textContent = 'Session';
}
}
breakModify(crement=0){
let time = parseInt(breakTime.textContent);
if((time == 0 && crement == -1) || timerWorkStatus == 1){
return;
}
time = time + crement;
breakTime.textContent = time.toString();
if(type === 'break' && timerWorkStatus == 0){
clock.textContent = time+":00";
timerHeading.textContent = 'Break';
}
}
startTimer(){
timerInterval = setInterval(this.decrementTimerDisplay,1000);
}
pauseTimer(){
clearInterval(timerInterval);
}
stopTimer(){
clearInterval(timerInterval);
if(type === 'session')
clock.textContent = sessionTime.textContent +':00'
else
clock.textContent = breakTime.textContent +':00'
}
resetTimer(){
clearInterval(timerInterval);
clock.textContent = '25:00'
sessionTime.textContent = '25';
breakTime.textContent = '5';
}
decrementTimerDisplay(){
let minutes = parseInt(clock.textContent.slice(0,-3));
let seconds = parseInt(clock.textContent.slice(-2));
let alarmAudio = new Audio('https://onlineclock.net/audio/options/default.mp3');
if(minutes == 0){
clearInterval(timerInterval);
if(type === 'session'){
type = 'break';
pomodoro.breakModify();
}
else{
type = 'session';
pomodoro.sessionModify();
}
alarmAudio.play();
return;
}
if(seconds == 0){
minutes--;
seconds = 59;
}else{
seconds--;
}
if(seconds <= 9){
seconds = "0"+seconds;
}
clock.textContent = minutes.toString()+':'+seconds.toString();
}
}
//query selects and getting elements into vars for linking with button click to modify timer
const sessionUpButton = document.querySelector('#incrementSession');
const sessionDownButton = document.querySelector('#decrementSession');
const breakUpButton = document.querySelector('#incrementBreak');
const breakDownButton = document.querySelector('#decrementBreak')
const playButton = document.querySelector('#play');
const pauseButton = document.querySelector('#pause');
const resetButton = document.querySelector('#reset');
const stopButton = document.querySelector('#stop');
const sessionTime = document.getElementById('sessionPom');
const breakTime = document.getElementById('breakPom');
const clock = document.getElementById('clock');
const timerHeading = document.getElementById('sessionHeading');
const pomodoro = new Pomodoro();
let timerInterval;
let type = 'session'; //indicator for session or break timer type since there is only 1 unified 'shared' timer space
//session starts first on default
let timerWorkStatus = 0; //0 indicates timer isn't currently timing down and 1 is timer is currently timing down. Used so timer
//can't be updated midway while working.
//buttons being linked
playButton.addEventListener('click', button =>{
timerWorkStatus = 1;
pomodoro.startTimer();
});
pauseButton.addEventListener('click', button =>{
pomodoro.pauseTimer();
});
stopButton.addEventListener('click', button =>{
timerWorkStatus = 0;
pomodoro.stopTimer();
});
resetButton.addEventListener('click', button =>{
timerWorkStatus = 0;
pomodoro.resetTimer();
});
sessionUpButton.addEventListener('click', button =>{
pomodoro.sessionModify(1);
});
sessionDownButton.addEventListener('click', button =>{
pomodoro.sessionModify(-1);
});
breakUpButton.addEventListener('click', button =>{
pomodoro.breakModify(1);
});
breakDownButton.addEventListener('click', button =>{
pomodoro.breakModify(-1);
});
|
import React, { useEffect, useState } from 'react';
import {
Container,
Left,
Right,
Top,
Bottom,
Img,
H1,
TContainer,
Block,
SearchContainer,
Search,
Sticky,
Submit,
MainB,
FilterContainer,
Searchs,
Filter,
SelectS,
NoResult,
VscSearchStops,
MBLeft,
MBRight,
MBImage,
MBLTop,
MBLBottom,
MBLH1,
MBLGoTo
} from './DetailsElements';
import courselogo from '../../images/courselogo.png';
import api from '../../api';
import { AiOutlineSearch } from 'react-icons/ai';
import Loader from 'react-loader-spinner';
import axios from 'axios';
const options = [
{ value: 'دسته بندی اول', label: 'دسته بندی اول' },
{ value: 'دسته بندی دوم', label: 'دسته بندی دوم' },
{ value: 'دسته بندی سوم', label: 'دسته بندی سوم' }
]
const token = 'parsur';
const Article = ({ data }) => {
const [article, setArticle] = useState(null);
const [search, setSearch] = useState("");
const [noRes, setNoRes] = useState(null);
useEffect(() => {
api("api/article/show")
.then((data) => {
setArticle([])
setArticle(data.artciles);
})
}, []);
function submit(){
console.log(search);
axios.post('http://sararajabi.com/api/course/search', {
search: search,
}, {
headers: {
'api_key': `${token}`
}
}
)
.then(function (response) {
setArticle(response.data);
if(response.data === ''){
setNoRes(noResult);
setArticle([]);
} else {
setNoRes(null);
}
console.log(response);
})
.catch(function (error) {
console.log(error);
});
}
function handleSearchChaneg(event){
if (event.target.value === "") {
api("api/article/show")
.then((data) => {
setArticle(data.courses);
})
setNoRes(null)
} else {
setSearch(event.target.value);
}
}
const noResult = function () {
return (
<NoResult><VscSearchStops/>متاسفانه نتیجه ای پیدا نشد!</NoResult>
);
}
return article ? (
<Container>
<Left>
<Sticky>
<Top>
<TContainer>
<SearchContainer onSubmit={event => event.preventDefault()}>
<Searchs>
<Search onChange={handleSearchChaneg} type="search" id="search" required="required" placeholder="سرچ کنید..." />
<Submit onClick={()=>submit()} type="submit" value="جستجو"><AiOutlineSearch/></Submit>
</Searchs>
<FilterContainer>
<Filter>
<SelectS options={options} placeholder="دسته بندی اول" />
</Filter>
<Filter>
<SelectS options={options} placeholder="دسته بندی دوم" />
</Filter>
</FilterContainer>
</SearchContainer>
<H1>مقاله ها</H1>
</TContainer>
</Top>
<Bottom>
<Img src={courselogo} alt="course logo" />
</Bottom>
</Sticky>
</Left>
<Right>
{noRes}
{article.map(({ title, id }, i) => {
return( <Block key={i}>
<MainB to={`article/${id}`}>
<MBRight><MBImage/></MBRight>
<MBLeft>
<MBLTop><MBLH1>{title}</MBLH1></MBLTop>
<MBLBottom><MBLGoTo>آغاز مطالعه</MBLGoTo></MBLBottom>
</MBLeft>
</MainB>
</Block> );
})}
{/* <OtherCourses>
<OCTop><H3>دوره های منتخب</H3></OCTop>
<OCHR/>
<OCBottom>
<Suggested>لورم ایپسوم متن ساختگی با تولید سادگی نامفهوم از صنعت چاپ، و با استفاده از طراحان گرافیک است، چاپگرها و متون بلکه روزنامه و مجله در ستون و سطرآنچنان که لازم است، و برای شرایط فعلی تکنولوژی مورد نیاز، و کاربردهای متنوع با هدف بهبود ابزارهای کاربردی می باشد، کتابهای زیادی در شصت و سه درصد گذشته حال و آینده، شناخت فراوان جامعه و متخصصان را می طلبد، تا با نرم افزارها شناخت بیشتری را برای طراحان رایانه ای علی الخصوص طراحان خلاقی، و فرهنگ پیشرو در زبان فارسی ایجاد کرد، در این صورت می توان امید داشت که تمام </Suggested>
<Suggested>لورم ایپسوم متن ساختگی با تولید سادگی نامفهوم از صنعت چاپ، و با استفاده از طراحان گرافیک است، چاپگرها و متون بلکه روزنامه و مجله در ستون و سطرآنچنان که لازم است، و برای شرایط فعلی تکنولوژی مورد نیاز، و کاربردهای متنوع با هدف بهبود ابزارهای کاربردی می باشد، کتابهای زیادی در شصت و سه درصد گذشته حال و آینده، شناخت فراوان جامعه و متخصصان را می طلبد، تا با نرم افزارها شناخت بیشتری را برای طراحان رایانه ای علی الخصوص طراحان خلاقی، و فرهنگ پیشرو در زبان فارسی ایجاد کرد، در این صورت می توان امید داشت که تمام </Suggested>
<Suggested>لورم ایپسوم متن ساختگی با تولید سادگی نامفهوم از صنعت چاپ، و با استفاده از طراحان گرافیک است، چاپگرها و متون بلکه روزنامه و مجله در ستون و سطرآنچنان که لازم است، و برای شرایط فعلی تکنولوژی مورد نیاز، و کاربردهای متنوع با هدف بهبود ابزارهای کاربردی می باشد، کتابهای زیادی در شصت و سه درصد گذشته حال و آینده، شناخت فراوان جامعه و متخصصان را می طلبد، تا با نرم افزارها شناخت بیشتری را برای طراحان رایانه ای علی الخصوص طراحان خلاقی، و فرهنگ پیشرو در زبان فارسی ایجاد کرد، در این صورت می توان امید داشت که تمام </Suggested>
<Suggested>لورم ایپسوم متن ساختگی با تولید سادگی نامفهوم از صنعت چاپ، و با استفاده از طراحان گرافیک است، چاپگرها و متون بلکه روزنامه و مجله در ستون و سطرآنچنان که لازم است، و برای شرایط فعلی تکنولوژی مورد نیاز، و کاربردهای متنوع با هدف بهبود ابزارهای کاربردی می باشد، کتابهای زیادی در شصت و سه درصد گذشته حال و آینده، شناخت فراوان جامعه و متخصصان را می طلبد، تا با نرم افزارها شناخت بیشتری را برای طراحان رایانه ای علی الخصوص طراحان خلاقی، و فرهنگ پیشرو در زبان فارسی ایجاد کرد، در این صورت می توان امید داشت که تمام </Suggested>
<Suggested>لورم ایپسوم متن ساختگی با تولید سادگی نامفهوم از صنعت چاپ، و با استفاده از طراحان گرافیک است، چاپگرها و متون بلکه روزنامه و مجله در ستون و سطرآنچنان که لازم است، و برای شرایط فعلی تکنولوژی مورد نیاز، و کاربردهای متنوع با هدف بهبود ابزارهای کاربردی می باشد، کتابهای زیادی در شصت و سه درصد گذشته حال و آینده، شناخت فراوان جامعه و متخصصان را می طلبد، تا با نرم افزارها شناخت بیشتری را برای طراحان رایانه ای علی الخصوص طراحان خلاقی، و فرهنگ پیشرو در زبان فارسی ایجاد کرد، در این صورت می توان امید داشت که تمام </Suggested>
<Suggested>لورم ایپسوم متن ساختگی با تولید سادگی نامفهوم از صنعت چاپ، و با استفاده از طراحان گرافیک است، چاپگرها و متون بلکه روزنامه و مجله در ستون و سطرآنچنان که لازم است، و برای شرایط فعلی تکنولوژی مورد نیاز، و کاربردهای متنوع با هدف بهبود ابزارهای کاربردی می باشد، کتابهای زیادی در شصت و سه درصد گذشته حال و آینده، شناخت فراوان جامعه و متخصصان را می طلبد، تا با نرم افزارها شناخت بیشتری را برای طراحان رایانه ای علی الخصوص طراحان خلاقی، و فرهنگ پیشرو در زبان فارسی ایجاد کرد، در این صورت می توان امید داشت که تمام </Suggested>
</OCBottom>
</OtherCourses> */}
</Right>
</Container>
) : (
<Container>
<Left>
<Sticky>
<Top>
<TContainer>
<SearchContainer onSubmit={event => event.preventDefault()}>
<Searchs>
<Search onChange={handleSearchChaneg} type="search" id="search" required="required" placeholder="سرچ کنید..." />
<Submit onClick={()=>submit()} type="submit" value="جستجو"><AiOutlineSearch/></Submit>
</Searchs>
<FilterContainer>
<Filter>
<SelectS options={options} placeholder="دسته بندی اول" />
</Filter>
<Filter>
<SelectS options={options} placeholder="دسته بندی دوم" />
</Filter>
</FilterContainer>
</SearchContainer>
<H1>مقاله ها</H1>
</TContainer>
</Top>
<Bottom>
<Img src={courselogo} alt="course logo" />
</Bottom>
</Sticky>
</Left>
<Right>
<div style={{width:"100%", height:"50%", display:"flex"}}>
<Loader
type="Oval"
color="#F4DD4F"
height={150}
width={150}
timeout={3000} //3 secs
style={{margin: "auto"}}
/>
</div>
</Right>
</Container>
);
}
export default Article; |
import React, { PropTypes } from 'react'
import './ColorPyramid.scss'
export const ColorPyramid = (props) => {
return (
<div className='pyramid'>
{props.colors.map((color, i) => {
return (
<div
key={i}
className='pyramid-level'
style={{ borderBottom: '110px solid ' + color,
width: 260 + (120 * i) }} />
)
})}
</div>
)
}
ColorPyramid.propTypes = {
colors: PropTypes.array.isRequired
}
export default ColorPyramid
|
import * as action from '../actions'
const initialState = {
token: '',
currentUser: {},
userList: []
};
function userReducer(state = initialState, action) {
const { type, payload } = action
switch (action.type) {
case 'login/get-start':
return {
...state,
loading: true
}
case 'login/get-success':
return {
...state,
login: payload.login,
loading: false,
error: ''
}
case 'login/get-failed':
return {
...state,
loading: false,
error: payload.error
}
case 'register/get-start':
return {
...state,
loading: true
}
case 'register/get-success':
return {
...state,
login: payload.register,
loading: false,
error: ''
}
case 'register/get-failed':
return {
...state,
loading: false,
error: payload.error
}
default:
return state
}
}
export default userReducer; |
import { db } from '../firebase';
export function getNotes(){
return dispatch => {
//async
db.on('value',(snapshot)=>{
dispatch({
type: 'GETNOTES',
payload: snapshot.val()
});
})
}
}
export function setNotes(note){
return dispatch => {
db.push(note);
}
}
export function deleteNote(id){
return dispatch => {
db.child(id).remove()
}
}
|
define(function (require) {
'use strict';
var TerrainGenerator = require('generator/terrain');
function Terrain () {}
Terrain.prototype = {
generate: function (grid, options) {
return TerrainGenerator.generate(grid, options);
}
};
return new Terrain();
});
|
import React from 'react';
import { Form, Input, Button, Alert, Typography, message } from 'antd';
import { useMutation } from 'react-query';
import { useHistory } from 'react-router-dom';
import Cookies from 'js-cookie';
import { Container, Link } from './SignUp.styles';
import useURLQuery from '../../Utils/useQuery';
import api from '../../Utils/api';
import auth from '../../Utils/auth';
import { API_URL } from '../../Utils/config';
const layout = {
labelCol: { span: 8 },
wrapperCol: { span: 16 },
};
const tailLayout = {
wrapperCol: { offset: 8, span: 16 },
};
const validateMessages = {
required: '${label} is required!',
types: {
email: '${label} is not validate email!',
},
};
const postSignup = async ({ values, invitationId, organizationToJoin }) => {
const url = invitationId ? 'auth/registerUser' : 'auth/register';
const newValues = invitationId
? { ...values, organization: organizationToJoin, invitationId }
: values;
const { data } = await api.post(`${API_URL}${url}`, newValues);
return data;
};
const SignUp = ({ setForm }) => {
const history = useHistory();
const [mutateSignup, { isLoading, error }] = useMutation(postSignup, {
onSuccess: (response) => {
const { tokens, user } = response;
auth.storeToken(tokens.access.token, tokens.refresh.token);
Cookies.set('role', user.role);
history.push('/issues');
},
});
React.useEffect(() => {
if (error) {
renderError();
}
}, [error]);
const query = useURLQuery();
const organizationToJoin = query.get('company');
const token = query.get('token');
const isInvitation = organizationToJoin && token;
const onFinish = async ({ name, email, password, organization }) => {
await mutateSignup({
values: { name, email, password, organization },
invitationId: isInvitation,
organizationToJoin,
});
};
const renderError = () => {
const {
response: { data },
} = error;
return message.error(data.message);
};
return (
<Container>
<Typography.Title level={3}>
{isInvitation ? 'Join organization' : 'Create organization'}
</Typography.Title>
<Form
{...layout}
name="signup"
initialValues={{ remember: true }}
onFinish={onFinish}
validateMessages={validateMessages}
>
<Form.Item label="Name" name="name" rules={[{ required: true }]}>
<Input />
</Form.Item>
<Form.Item label="Email" name="email" rules={[{ type: 'email', required: true }]}>
<Input />
</Form.Item>
<Form.Item label="Password" name="password" rules={[{ required: true }]}>
<Input.Password />
</Form.Item>
{isInvitation ? (
<Alert
message={`Your are joining ${organizationToJoin}`}
type="info"
showIcon
style={{ marginBottom: 18 }}
/>
) : (
<Form.Item label="Organization" name="organization" rules={[{ required: true }]}>
<Input />
</Form.Item>
)}
<Form.Item {...tailLayout}>
<Button type="primary" htmlType="submit" style={{ marginRight: 8 }} loading={isLoading}>
Submit
</Button>
Or <Link onClick={() => setForm('signin')}>sign in!</Link>
</Form.Item>
</Form>
</Container>
);
};
export default SignUp;
|
const mongoose = require("mongoose");
const URI = process.env.MONGO_URI ?
process.env.MONGO_URI :
"mongodb://localhost:27017/voting-app";
mongoose.connect(URI);
// Use native promises
mongoose.Promise = global.Promise;
// Connection/Error events
mongoose.connection.on("connected", () => {
console.log("Mongoose connection open to " + URI);
});
mongoose.connection.on("error", (err) => {
console.log("Mongoose connection error: " + err);
});
mongoose.connection.on("disconnected", () => {
console.log("Mongoose connection disconnected");
});
process.on("SIGINT", () => {
mongoose.connection.close(() => {
console.log("Mongoose connection closed.");
});
});
// Models
require ("./User");
require ("./Poll");
// Export connection.
module.exports = mongoose.connection;
|
import axios from "axios";
import { GET_SIMILAR_TV_SHOWS } from "../types";
export const getSimilarTvShows = id => dispatch => {
axios.get(`/.netlify/functions/getSimilarTvShows?id=${id}`).then(res =>
dispatch({
type: GET_SIMILAR_TV_SHOWS,
payload: res.data
})
);
};
|
$(function () {
var main = new tasks.todos.views.MainView({
el: 'div.container'
});
main.render();
}); |
/*
* productGroupService.js
*
* Copyright (c) 2017 HEB
* All rights reserved.
*
* This software is the confidential and proprietary information
* of HEB.
*/
'use strict';
/**
* Creates the service used to interact with the product group detail.
*/
(function() {
angular.module('productMaintenanceUiApp').service('ProductGroupService', productGroupService);
function productGroupService() {
var self = this;
/**
* Selected product Id
* @type {Long}
*/
self.productGroupTypeCode = null;
/**
* Selected product Id
* @type {Long}
*/
self.selectedProductId = null;
/**
* Selected product group Id
* @type {Long}
*/
self.productGroupId = null;
/**
* Navigate from ecommerce view page to another page or not
* @type {Boolean}
*/
self.returnToListFlag = false;
/**
* Flag display page when navigate from product group type page.
*/
self.navFromProdGrpTypePageFlag = false;
/**
* Flag display page when navigate from product group type page from customer hierarchy.
*/
self.navigateFromCustomerHierPage = false;
/**
* Product group type code
*/
self.productGroupTypeCodeNav = null;
/**
* Data product group name input.
* @type {string}
*/
self.productGroupName = "";
/**
* Data customer hierachy id.
* @type {string}
*/
self.customerHierarchy = "";
/**
* The browser all status.
* @type {boolean}
*/
self.isBrowserAll = false;
/**
* The search text.
* @type {string}
*/
self.customHierarchySearchText='';
self.customerHierarchyId = null;
/**
* List Product received from detail task page.
*/
self.listOfProducts = [];
return {
/**
* Initializes the controller.
*
* @param showFullPanel Whether or not to show the full panel (excludes item status filter). This will add
* things like the MRT tab, the add button for complex search, product description search, etc.
* @param showStatusFilter Whether or not to show the item status filter options.
* @param basicSearchCallback The callback for when the user clicks on a basic search button. Basic
* searches only have one set of criteria.
* @param complexSearchCallback The callback for when the user clicks on the complex search button. Complex
* searches can contain multiple sets of criteria.
*/
init:function() {
},
/**
* Returns ProductGroupTypeCode
*
* @returns {null|*}
*/
getProductGroupTypeCode:function() {
return self.productGroupTypeCode;
},
/**
* Sets the values the product group type code.
*
* @param selectedProductId
*/
setProductGroupTypeCode:function(productGroupTypeCode) {
self.productGroupTypeCode = productGroupTypeCode;
},
/**
* Returns selectedProductId
*
* @returns {null|*}
*/
getSelectedProductId:function() {
return self.selectedProductId;
},
/**
* Sets the values the selected productId
*
* @param selectedProductId
*/
setSelectedProductId:function(selectedProductId) {
self.selectedProductId = selectedProductId;
},
/**
* Returns listOfProducts
*
* @returns {null|*}
*/
getListOfProducts:function() {
return self.listOfProducts;
},
/**
* Sets the values the listOfProducts.
*
* @param listOfProducts
*/
setListOfProducts:function(listOfProducts) {
self.listOfProducts = listOfProducts;
},
/**
* Returns the values productGroupId
*
* @returns {null|*}
*/
getProductGroupId:function() {
return self.productGroupId;
},
/**
* Sets the values the product group Id
*
* @param productGroupId
*/
setProductGroupId:function(productGroupId) {
self.productGroupId = productGroupId;
},
/**
* Returns return to list flag
*
* @returns {true|false}
*/
getReturnToListFlag:function() {
return self.returnToListFlag;
},
/**
* Sets return to list flag.
*
* @param returnToListFlag
*/
setReturnToListFlag:function(returnToListFlag) {
self.returnToListFlag = returnToListFlag;
},
/**
* Returns custom hierarchy level the user has selected for navigation.
*
* @returns selectedCustomHierarchyLevel
*/
getCustomerHierarchyId:function(){
return self.customerHierarchyId;
},
/**
* Sets custom hierarchy level the user has selected for navigation.
*
* @param selectedCustomHierarchyLevel
*/
setCustomerHierarchyId:function(customerHierarchyId){
self.customerHierarchyId = customerHierarchyId;
},
/**
* Return flag display page when navigate from product group type page.
*
* @returns {true|false}
*/
getNavFromProdGrpTypePageFlag:function() {
return self.navFromProdGrpTypePageFlag;
},
/**
* Set flag display page when navigate from product group type page.
*
* @param returnToListFlag
*/
setNavFromProdGrpTypePageFlag:function(navFromProdGrpTypePageFlag) {
self.navFromProdGrpTypePageFlag = navFromProdGrpTypePageFlag;
},
/**
* Return flag display page when navigate from product group type page.
*
* @returns {true|false}
*/
getNavigateFromCustomerHierPage:function() {
return self.navigateFromCustomerHierPage;
},
/**
* Set flag display page when navigate from product group type page.
*
* @param navigateFromCustomerHierPage
*/
setNavigateFromCustomerHierPage:function(navigateFromCustomerHierPage) {
self.navigateFromCustomerHierPage = navigateFromCustomerHierPage;
},
/**
* Return product group type code of product group type.
*
* @returns {true|false}
*/
getProductGroupTypeCodeNav:function() {
return self.productGroupTypeCodeNav;
},
/**
* Set product group type code of product group type.
*
* @param returnToListFlag
*/
setProductGroupTypeCodeNav:function(productGroupTypeCodeNav) {
self.productGroupTypeCodeNav = productGroupTypeCodeNav;
},
/**
* Return product Group Name.
*
* @returns productGroupName
*/
getProductGroupName:function() {
return self.productGroupName;
},
/**
* Set product group name.
*
* @param productGroupName
*/
setProductGroupName:function(productGroupName) {
self.productGroupName = productGroupName;
},
/**
* Return the customer Hierarchy.
*
* @returns customerHierarchy
*/
getCustomerHierarchy:function() {
return self.customerHierarchy;
},
/**
* Set the customer Hierarchy.
*
* @param customerHierarchy
*/
setCustomerHierarchy:function(customerHierarchy) {
self.customerHierarchy = customerHierarchy;
},
/**
* Return the status of browser All.
*
* @returns isBrowserAll
*/
isBrowserAll:function() {
return self.isBrowserAll;
},
/**
* Set thestatus of browser All.
*
* @param isBrowserAll
*/
setBrowserAll:function(isBrowserAll) {
self.isBrowserAll = isBrowserAll;
},
/**
* Return custom Hierarchy Search Text.
*
* @returns customHierarchySearchText
*/
getCustomHierarchySearchText:function() {
return self.customHierarchySearchText;
},
/**
* Set custom Hierarchy Search Text.
*
* @param customHierarchySearchText
*/
setCustomHierarchySearchText:function(customHierarchySearchText) {
self.customHierarchySearchText = customHierarchySearchText;
},
}
}
})();
|
import { useEffect, useState } from "react";
const Counter = (props) => {
let [count,setCount] = useState(0);
useEffect(()=>{
if(count<0){
setCount(15);
}else if(count>15){
setCount(0);
}
},[count]);
return (
<div className="m-5">
<button className="btn btn-sm btn-info mr-2"
onClick={e => setCount(count+1)}>Increase</button>
<strong>{count}</strong>
<button className="btn btn-sm btn-info ml-2"
onClick={e => setCount(count-1)}>Decrease</button>
</div>
);
};
export default Counter; |
/**
* Authors: Diego Ceresuela, Luis Jesús Pellicer, Raúl Piracés.
* Date: 16-05-2016
* Name file: mentions.controller.js
* Description: This file contains methods to attend the "mentions" resource and endpoints.
*/
(function() {
'use strict';
var user_required = require('../../config/policies.config').user_required;
var TweetCommons = require('../../common/tweets');
module.exports = function(app) {
/**
* Get the latest mentions of current user in Twitter, using the correspondent Twitter search API endpoint.
* If there is an error with Twitter, the response contains error status code from Twitter.
*/
app.get('/mentions', user_required.before, function(req, res, next) {
TweetCommons.getUserFromJWT(req, function(user){
if(user) {
TweetCommons.searchMentions(user, function (result) {
// Error in the interaction with Twitter.
if (result.statusCode && result.statusCode != 200) {
res.status(result.statusCode).json({
"error": true,
"data": {
"message": "Cannot search last mentions",
"url": process.env.CURRENT_DOMAIN
}
});
next();
} else {
res.json({
"error": false,
"data": {
"message": "Search mentions successful",
"url": process.env.CURRENT_DOMAIN + "/tweets",
"content": result
}
});
next();
}
});
} else {
res.status(500).json({
"error": true,
"data": {
"message": "Cannot get current user in use",
"url": process.env.CURRENT_DOMAIN
}
});
next();
}
});
}, user_required.after);
// Return middleware.
return function(req, res, next) {
next();
};
};
})(); |
angular.module("MainApp").controller('AccountUnit', ['$scope','$http','$location','$state','commonSalutations', function ($scope, $http, $location,$state,commonSalutations) {
// SAVE USER
$scope.saveAccountUnit = function (formData) {
$http.post('/accountUnit', formData)
.success(function (data, status, headers, config) {
$state.reload();
});
};
// UPDATE USER
$scope.updateAccountUnit = function (formData) {
$http.put('/accountUnit', formData)
.success(function (data, status, headers, config) {
$state.reload();
});
};
$scope.mScope = {} ;
$scope.mScope.validateConfirmPassowrd = function(password,confirmPassword){
if(confirmPassword!=null){
if(password != confirmPassword){
$scope.mScope.mForm.confirmPasswordStatus = false;
}else{
$scope.mScope.mForm.confirmPasswordStatus = true;
}
}
}
$http.get('/accountUnit?status=notDeleted')
.success(function (data, status, headers, config) {
$scope.accountUnits = data;
});
}]) |
function showItem(item) {
$('#item-div')
.html(
JST['item']({ item: item })
);
}
function deltaNum(delta) {
var $num = $('#num');
var val = (+$num.val() || 0) + delta;
$num.val(Math.max(1, val));
}
function addToCart(silient, cb) {
var $num = $('#num');
var num = +$num.val();
if (isNaN(num) || num <= 0) {
return notify('宝贝数量至少为 1 件');
}
$num.val(1);
if (!item.onSale || num > item.store) {
return notify('正在补货中,明天才可以购买哦~');
}
var items = store.get('cartItems');
var itemIn = _.findWhere(items, { id: id });
if (itemIn) {
itemIn.num += num;
} else {
items.push({
id: id,
num: num,
checked: true
});
}
store.set('cartItems', items);
if (!silient) {
notify('已加入购物车');
}
if (cb) {
cb();
}
}
function gotoCart() {
addToCart(true, function () {
link('cart.html');
});
}
/* parse parameters */
var id = +params.id;
var item;
initPage(function () {
$(function () {
/* load item */
fetchProduct({ id: id }, function (_item) {
item = _item;
if (!item) {
notify('宝贝不存在', true);
}
/* title */
setTitle(item.title + ' - Great Me', '宝贝详情');
/* extend item */
calcPrice(item);
/* display item */
showItem(item);
/* ready */
loadReady();
});
});
});
|
import * as model from "./model";
import booksView from "./views/booksView";
import wishlistView from "./views/wishlistView";
import searchView from "./views/searchView";
import bookDescriptionView from "./views/bookDescriptionView";
booksView.render(model.state.books);
// ====================================================================
// Control Search results
// ====================================================================
const controlSearchResults = async () => {
try {
const query = searchView.getQuery();
if (!query) return;
await model.loadSearchResults(query);
booksView.render(model.state.books);
} catch (err) {
console.log(err);
}
};
// ====================================================================
// Control Wishlist
// ====================================================================
const controlAddBookWishlist = (ISBN) => {
let tryAdd = model.addBookWishlist(ISBN);
if (!tryAdd) return;
wishlistView.render(model.state.wishlist);
updateWishListLabel();
if (wishlistView.wishlistIsOpen() == false) {
wishlistView.toggleShow();
setTimeout(() => {
wishlistView.toggleShow();
}, 2000);
}
};
const updateWishListLabel = () => {
let wishlistBooks = model.getWishlist();
if (wishlistBooks.length == 0) {
wishlistView.updateLabel("Wishlist Empty");
} else {
wishlistView.updateLabel(" ");
}
};
const controlDeleteBookWishlist = (ISBN) => {
let del = model.deleteBookWishlist(ISBN);
if (!del) return;
wishlistView.render(model.state.wishlist);
};
updateWishListLabel();
const controlWishListBtn = () => {
wishlistView.toggleShow();
updateWishListLabel();
};
const controlWishListImgInfo = (ISBN) => {
const description = model.getDescriptionWishlist(ISBN);
bookDescriptionView.showDescription(description);
bookDescriptionView.toggleModal();
};
const loadLocalStorage = () => {
wishlistView.render(model.getWishlist());
};
// ====================================================================
// Control Description
// ====================================================================
const controlHideDescription = () => {
bookDescriptionView.closeModal();
};
const controlShowDescription = (ISBN) => {
let description = model.getDescription(ISBN);
bookDescriptionView.showDescription(description);
bookDescriptionView.toggleModal();
};
// ====================================================================
// init view handlers
// ====================================================================
const init = () => {
searchView.addHandlerSearch(controlSearchResults);
booksView.addHandlerAddBookWishlist(controlAddBookWishlist);
wishlistView.addHandlerDeleteBookWishlist(controlDeleteBookWishlist);
wishlistView.addHandlerShowWishListButton(controlWishListBtn);
wishlistView.addHandlerShowInformation(controlWishListImgInfo);
bookDescriptionView.addHandlerHideDescription(controlHideDescription);
bookDescriptionView.addHandlerShowDescription(controlShowDescription);
loadLocalStorage();
};
init();
|
const ITEM_LIMIT = 4;
const projectFetcher = (studioId, offset) =>
fetch(`${process.env.API_HOST}/studios/${studioId}/projects?limit=${ITEM_LIMIT}&offset=${offset}`)
.then(response => response.json())
.then(data => ({items: data, moreToLoad: data.length === ITEM_LIMIT}));
const curatorFetcher = (studioId, offset) =>
fetch(`${process.env.API_HOST}/studios/${studioId}/curators?limit=${ITEM_LIMIT}&offset=${offset}`)
.then(response => response.json())
.then(data => ({items: data, moreToLoad: data.length === ITEM_LIMIT}));
const managerFetcher = (studioId, offset) =>
fetch(`${process.env.API_HOST}/studios/${studioId}/managers?limit=${ITEM_LIMIT}&offset=${offset}`)
.then(response => response.json())
.then(data => ({items: data, moreToLoad: data.length === ITEM_LIMIT}));
const activityFetcher = studioId =>
fetch(`${process.env.API_HOST}/studios/${studioId}/activity`)
.then(response => response.json())
.then(data => ({items: data, moreToLoad: false})); // No pagination on the activity feed
export {
activityFetcher,
projectFetcher,
curatorFetcher,
managerFetcher
};
|
import React from 'react'
import { Field, reduxForm } from 'redux-form'
const SimpleForm = ({ handleSubmit, pristine, reset, submitting }) => {
return <form
className="mt-3"
noValidate
onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="firstName">First Name</label>
<Field
id="firstName"
placeholder="First Name"
className="form-control"
name="firstName"
component="input"
type="text"
/>
</div>
<div className="form-group mt-3">
<label htmlFor="lastName">Last Name</label>
<Field
id="lastName"
placeholder="Last Name"
className="form-control"
name="lastName"
component="input"
type="text" />
</div>
<div className="form-group mt-3">
<label htmlFor="email">Email</label>
<Field
id="email"
placeholder="Email"
className="form-control"
name="email"
component="input"
type="email" />
</div>
<div >
<label>Sex</label>
<div className="form-group form-check">
<Field
id="male"
className="form-check-input"
name="sex"
component="input"
type="radio"
value="male" />
<label
className="form-check-label"
htmlFor="male">Male</label>
</div>
<div className="form-group form-check">
<Field
id="female"
className="form-check-input"
name="sex"
component="input"
type="radio"
value="female" />
<label
className="form-check-label"
htmlFor="female">Female</label>
</div>
<div className="form-group form-check">
<Field
id="other"
className="form-check-input"
name="sex"
component="input"
type="radio"
value="other" />
<label
className="form-check-label"
htmlFor="other">Other</label>
</div>
</div>
<div className="form-group mt-3">
<label htmlFor="favoriteColor">Favorite Color</label>
<div>
<Field
className="form-control"
id="favoriteColor"
name="favoriteColor"
component="select">
<option />
<option value="ff0000">Red</option>
<option value="00ff00">Green</option>
<option value="0000ff">Blue</option>
</Field>
</div>
</div>
<div className="form-group form-check">
<Field
id="employed"
className="form-check-input"
name="employed"
component="input"
type="checkbox" />
<label
className="form-check-label"
htmlFor="employed">Employed</label>
</div>
<div className="form-group">
<label htmlFor="notes">Notes</label>
<div>
<Field
className="form-control"
id="notes"
name="notes"
component="textarea" />
</div>
</div>
<div className="mt-3">
<button
type="submit"
disabled={pristine || submitting}
className="btn btn-secondary">Submit</button>
<button
type="submit"
disabled={pristine || submitting} onClick={reset}
className="btn btn-light ml-3">Clear</button>
</div>
</form>
}
export default reduxForm({
form: 'simple',
forceUnregisterOnUnmount: true,
destroyOnUnmount: false
})(SimpleForm)
export const listing = `
import React from 'react'
import { Field, reduxForm } from 'redux-form'
const SimpleForm = ({ handleSubmit, pristine, reset, submitting }) => {
return <form
className="mt-3"
noValidate
onSubmit={handleSubmit}>
<div className="form-group">
<label htmlFor="firstName">First Name</label>
<Field
id="firstName"
placeholder="First Name"
className="form-control"
name="firstName"
component="input"
type="text"
/>
</div>
<div className="form-group mt-3">
<label htmlFor="lastName">Last Name</label>
<Field
id="lastName"
placeholder="Last Name"
className="form-control"
name="lastName"
component="input"
type="text" />
</div>
<div className="form-group mt-3">
<label htmlFor="email">Email</label>
<Field
id="email"
placeholder="Email"
className="form-control"
name="email"
component="input"
type="email" />
</div>
<div >
<label>Sex</label>
<div className="form-group form-check">
<Field
id="male"
className="form-check-input"
name="sex"
component="input"
type="radio"
value="male" />
<label
className="form-check-label"
htmlFor="male">Male</label>
</div>
<div className="form-group form-check">
<Field
id="female"
className="form-check-input"
name="sex"
component="input"
type="radio"
value="female" />
<label
className="form-check-label"
htmlFor="female">Female</label>
</div>
<div className="form-group form-check">
<Field
id="other"
className="form-check-input"
name="sex"
component="input"
type="radio"
value="other" />
<label
className="form-check-label"
htmlFor="other">Other</label>
</div>
</div>
<div className="form-group mt-3">
<label htmlFor="favoriteColor">Favorite Color</label>
<div>
<Field
className="form-control"
id="favoriteColor"
name="favoriteColor"
component="select">
<option />
<option value="ff0000">Red</option>
<option value="00ff00">Green</option>
<option value="0000ff">Blue</option>
</Field>
</div>
</div>
<div className="form-group form-check">
<Field
id="employed"
className="form-check-input"
name="employed"
component="input"
type="checkbox" />
<label
className="form-check-label"
htmlFor="employed">Employed</label>
</div>
<div className="form-group">
<label htmlFor="notes">Notes</label>
<div>
<Field
className="form-control"
id="notes"
name="notes"
component="textarea" />
</div>
</div>
<div className="mt-3">
<button
type="submit"
disabled={pristine || submitting}
className="btn btn-secondary">Submit</button>
<button
type="submit"
disabled={pristine || submitting} onClick={reset}
className="btn btn-light ml-3">Clear</button>
</div>
</form>
}
export default reduxForm({
form: 'simple',
forceUnregisterOnUnmount: true,
destroyOnUnmount: false
})(SimpleForm)
` |
import React, {useEffect, Fragment} from 'react';
import {useSelector,useDispatch} from 'react-redux';
import Pulse from '../loading/Pulse';
import CategoryModal from './CategoryModal';
import GetUser from '../../globalFunctions/GetUser';
import {getCategories, deleteCategory} from '../../actions/categoryActions';
const Categories = () => {
const user = GetUser();
const dispatch = useDispatch();
const {categories, loading} = useSelector(state => state.category);
useEffect(() => {
//Get user categories
if(user.id){
const all_indicator = 1;
dispatch(getCategories(user.id,all_indicator));
}
},[dispatch, user.id, categories.length])
const contentLoading = (
<Fragment>
<div className="mt-2 w-full sm:w-5/6 md:w-4/5">
<Pulse loadAmount={categories.length > 1 ? parseInt(categories.length / 2) : 1}/>
</div>
</Fragment>
)
let contentLoaded = '';
if(categories.length > 0){
contentLoaded = (
<Fragment>
<div className="mt-2 bg-white w-full sm:w-5/6 md:w-4/5">
<ul className="rounded-lg w-full divide-y divide-gray-700 divide-opacity-25 text-gray-800">
{categories.map(({_id, category_name}) => (
<li key={_id} className="px-4 py-2 flex justify-between font-bold">{category_name}<button type="button" className="bg-red-500 hover:bg-red-700 text-white px-4 py-2 rounded text-xs font-bold outline-none focus:outline-none" onClick={() => dispatch(deleteCategory(_id))}>X</button></li>
))}
</ul>
</div>
</Fragment>
)
} else {
contentLoaded = (
<Fragment>
<div className="mt-2 bg-gray-300 w-full sm:w-5/6 md:w-4/5">
<ul className="rounded-lg w-full text-center text-gray-800">
<li className="px-4 py-2 font-bold">NO RESULTS FOUND</li>
</ul>
</div>
</Fragment>
)
}
return (
<div>
<div className="container mx-auto mt-16">
<div className="flex justify-center">
<div className="w-full sm:w-5/6 md:w-4/5">
<CategoryModal/>
</div>
</div>
<div className="flex justify-center item-center">
{loading === true ? contentLoading : contentLoaded}
</div>
</div>
</div>
)
}
export default Categories; |
import React, { useRef } from "react";
import {
View,
Text,
StyleSheet,
KeyboardAvoidingView,
Platform,
Alert,
} from "react-native";
import { TextInput, Button, HelperText } from "react-native-paper";
import { CustomContext } from "../contexts/CustomContext";
export default function LoginScreen({ navigation }) {
const [isLoading, setIsLoading] = React.useState(false);
const [isEmailValid, setIsEmailValid] = React.useState(true);
const [isPasswordValid, setIsPasswordValid] = React.useState(true);
const [inputs, setInputs] = React.useState({ email: "", password: "" });
const {
state: { isTest },
stateAction: { testSignIn, signIn },
} = React.useContext(CustomContext);
const emailInput = useRef();
const passwordInput = useRef();
const { email, password } = inputs;
function validateEmail(email) {
var re =
/^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
const loginRequest = async (email, password) => {
try {
await signIn(email, password);
navigation.popToTop(); //메인화면으로 이동
} catch (error) {
console.log(error);
if (error.hasOwnProperty("loginFail")) {
Alert.alert("로그인 실패", error.loginFail);
} else {
Alert.alert("로그인 실패", "알수없는 오류입니다.");
}
setIsLoading(false);
}
};
function login() {
console.log(email, password);
const isEmailValid = validateEmail(email);
if (!isEmailValid) {
emailInput.current.focus();
setIsLoading(false);
setIsEmailValid(isEmailValid);
return;
}
const isPasswordValid = password.length >= 8;
if (!isPasswordValid) {
passwordInput.current.focus();
setIsLoading(false);
setIsPasswordValid(isPasswordValid);
return;
}
setIsLoading(true);
if (isTest) {
testSignIn("test");
setIsLoading(false);
navigation.popToTop();
} else {
loginRequest(email, password);
}
}
React.useEffect(() => {}, []);
return (
<View style={styles.container}>
<View style={styles.titleContainer}>
<Text style={styles.titleText}>Login TEST</Text>
</View>
<KeyboardAvoidingView
style={styles.innerContainer}
behavior={Platform.OS === "ios" ? "padding" : "height"}
>
<TextInput
mode="outlined"
left={
<TextInput.Icon
name="email"
color="rgba(0, 0, 0, 0.38)"
size={25}
style={{ backgroundColor: "transparent" }}
/>
}
value={email}
keyboardAppearance="light"
autoCapitalize="none"
autoCorrect={false}
keyboardType="email-address"
returnKeyType="next"
blurOnSubmit={true}
placeholder={"Email"}
ref={emailInput}
onSubmitEditing={() => passwordInput.current.focus()}
onChangeText={(email) => {
setIsEmailValid(true);
setInputs({ ...inputs, email });
}}
style={styles.textInput}
error={!isEmailValid}
/>
<HelperText
type="error"
visible={!isEmailValid}
style={{ display: isEmailValid ? "none" : "flex" }}
>
이메일 형식이 맞는지 확인하세요.
</HelperText>
<TextInput
mode="outlined"
left={
<TextInput.Icon
name="lock"
color="rgba(0, 0, 0, 0.38)"
size={25}
style={{ backgroundColor: "transparent" }}
/>
}
value={password}
keyboardAppearance="light"
autoCapitalize="none"
autoCorrect={false}
secureTextEntry={true}
returnKeyType="done"
blurOnSubmit={true}
placeholder={"Password"}
ref={passwordInput}
onSubmitEditing={() => login()}
onChangeText={(password) => {
setIsPasswordValid(true);
setInputs({ ...inputs, password });
}}
style={styles.textInput}
error={!isPasswordValid}
/>
<HelperText
type="error"
visible={!isPasswordValid}
style={{ display: isPasswordValid ? "none" : "flex" }}
>
이메일 형식이 맞는지 확인하세요. 비밀번호는 최소 8자리입니다.
</HelperText>
<Button
mode="contained"
onPress={login}
labelStyle={styles.loginTextButton}
loading={isLoading}
disabled={isLoading}
style={styles.loginButton}
>
LOGIN
</Button>
</KeyboardAvoidingView>
<View style={styles.helpContainer}>
<Button
mode="text"
labelStyle={{ color: "white" }}
style={{ backgroundColor: "transparent" }}
contentStyle="transparent"
onPress={() => console.log("Account created")}
>
Need help?
</Button>
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
titleContainer: {
flex: 1,
alignItems: "center",
justifyContent: "center",
// marginBottom: 48,
backgroundColor: "red",
},
innerContainer: {
flex: 3,
justifyContent: "flex-start",
alignItems: "center",
backgroundColor: "yellow",
},
helpContainer: {
flex: 1,
alignItems: "center",
backgroundColor: "green",
},
textInput: {
width: "90%",
marginBottom: 20,
},
loginButton: {
width: "90%",
},
titleText: {
color: "black",
fontSize: 30,
},
loginContainer: {
alignItems: "center",
justifyContent: "center",
},
});
|
import { useState, useEffect } from "react";
export const useFetch = (request, initloading, deps) => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(initloading || true);
const [error, setError] = useState(null);
useEffect(() => {
let isCurrent = true;
request()
.then(data => {
if (isCurrent) {
setData(data);
}
})
.catch(err => {
if (isCurrent) {
setError(err);
}
})
.finally(() => {
if (isCurrent) {
setLoading(false);
}
});
return () => {
console.log("cancelling request");
isCurrent = false; // if deps change in the middle of API request, there is no need to resolve it.
};
}, [request, deps]);
return { data, loading, error };
};
|
var express = require("express");
var app = express();
//设置模板位置
app.set("views", "./views");
//设置模板引擎
app.set("view engine", "jade");
app.use(function(request, response, next) {
console.log("receive a request");
//使用模板引擎渲染,data为渲染的对象数据
var data = {};
data = {"book": {"name": "Hello", "price": 12.99}};
response.render("test.jade", data);
//response.end("do you reveice??");
});
app.listen(1024);
console.log('you can visit caoduozi in http://127.0.0.1:1024/');
|
import { Text } from 'native-base';
import React from 'react';
import { View, ImageBackground, StyleSheet, Button } from 'react-native';
import image from '../../assets/image.jpg';
import {signInWithGoogle} from '../store/actions/auth';
import {connect} from 'react-redux';
const LoginScreen = (props) => {
const {signInWithGoogle, navigation} = props;
const onGoogleSignInPressed = () => {
signInWithGoogle().then(res=> !res.error?navigation.push('Home'): '')
}
return (
<View style={styles.container}>
<View style={styles.hiddenHeader} />
<ImageBackground source={image} style={styles.image} resizeMode="cover">
<View style={styles.overlay}>
<Button style={styles.text} onPress={() => {}} title="Sign in With Google" />
</View>
</ImageBackground>
</View>
);
};
LoginScreen.navigationOptions = {
headerShown: false
};
const styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column'
},
hiddenHeader: {},
image: {
flex: 1,
resizeMode: 'cover',
justifyContent: 'center'
},
overlay: {
backgroundColor: 'rgba(255,255,255,0.3)',
height: '100%',
justifyContent: 'center'
},
text: {
color: 'grey',
fontSize: 30,
fontWeight: 'bold'
}
});
const mapStateToProps = (state) => ({
})
export default connect(mapStateToProps, {signInWithGoogle})(LoginScreen);
|
import Color from 'color';
import FlatButton from 'material-ui/FlatButton';
import TextField from 'material-ui/TextField';
import Dialog from 'material-ui/Dialog';
import React, { PureComponent, PropTypes } from 'react';
export class PieceDialog extends PureComponent {
static get propTypes() {
return {
open: PropTypes.bool.isRequired,
onClose: PropTypes.func.isRequired,
onCreate: PropTypes.func.isRequired,
shape: PropTypes.string,
x: PropTypes.number,
y: PropTypes.number,
fill: PropTypes.bool,
fillColor: PropTypes.any,
stroke: PropTypes.bool,
strokeColor: PropTypes.any,
strokeWidth: PropTypes.number,
};
}
get name() {
return this.ref_name.getValue() || null;
}
render() {
const {
open,
shape,
x, y,
fill,
fillColor,
stroke,
strokeColor,
strokeWidth,
onCreate,
onClose,
} = this.props;
const actions = [
<FlatButton
primary
key="create"
label="Create"
onTouchTap={(e) => onCreate(e, {
shape,
x,
y,
fill: fill ? new Color(fillColor).rgbString() : 'none',
stroke: stroke ? new Color(strokeColor).rgbString() : 'none',
strokeWidth,
name: this.name,
})}
/>,
<FlatButton
secondary
key="cancel"
label="Cancel"
onTouchTap={onClose}
/>,
];
return (
<Dialog
actions={actions}
open={open}
title="Piece"
>
<TextField
fullWidth
floatingLabelText="name"
name="name"
ref={(c) => (this.ref_name = c)}
/>
</Dialog>
);
}
}
|
const UserModel = require('../dao/userModel')
const User = {
// 创建用户
create: (userParam, cb) => {
return new UserModel(userParam).save(cb)
},
// 通过名字获取用户
findByName: (username, cb) => {
return UserModel.findByName(username, cb)
}
}
module.exports = User; |
const fs = require('fs')
const Router = require('koa-router')
const ServerRenderer = require('vue-server-renderer')
const serverRender = require('@server/utils/render')
const paths = require('@build/misc/paths')
const clientManifest = require('@public/client/vue-ssr-client-manifest.json')
const { serverEncoding } = require('@build/misc/constants')
const renderer = ServerRenderer.createBundleRenderer(paths.server.bundle, {
inject: false,
clientManifest
})
const template = fs.readFileSync(paths.server.template, serverEncoding)
const router = new Router()
router.get('*', async (ctx) => {
await serverRender(ctx, renderer, template)
})
module.exports = router
|
let GOOBER_ID = '_goober';
let ssr = {
data: ''
};
/**
* Returns the _commit_ target
* @param {Object} [target]
* @returns {HTMLStyleElement|{data: ''}}
*/
export let getSheet = (target) => {
if (typeof window === 'object') {
// Querying the existing target for a previously defined <style> tag
// We're doing a querySelector because the <head> element doesn't implemented the getElementById api
return (
(target ? target.querySelector('#' + GOOBER_ID) : window[GOOBER_ID]) ||
Object.assign((target || document.head).appendChild(document.createElement('style')), {
innerHTML: ' ',
id: GOOBER_ID
})
).firstChild;
}
return target || ssr;
};
|
/**
* Deals with the main high level survey controls: saving, submitting etc.
*/
import gui from './gui';
import connection from './connection';
import settings from './settings';
import { Form } from 'enketo-core';
import { updateDownloadLink } from 'enketo-core/src/js/utils';
import events from './event';
import fileManager from './file-manager';
import { t } from './translator';
import records from './records-queue';
import $ from 'jquery';
import encryptor from './encryptor';
let form;
let formSelector;
let formData;
let formprogress;
const formOptions = {
clearIrrelevantImmediately: false,
printRelevantOnly: settings.printRelevantOnly
};
function init( selector, data ) {
let advice;
let loadErrors = [];
formSelector = selector;
formData = data;
return _initializeRecords()
.then( _checkAutoSavedRecord )
.then( record => {
if ( !data.instanceStr && record && record.xml ) {
records.setActive( records.getAutoSavedKey() );
data.instanceStr = record.xml;
}
if ( data.instanceAttachments ) {
fileManager.setInstanceAttachments( data.instanceAttachments );
}
form = new Form( formSelector, data, formOptions );
loadErrors = form.init();
// Remove loader. This will make the form visible.
// In order to aggregate regular loadErrors and GoTo loaderrors,
// this is placed in between form.init() and form.goTo().
$( '.main-loader' ).remove();
if ( settings.goTo && location.hash ) {
loadErrors = loadErrors.concat( form.goTo( location.hash.substring( 1 ) ) );
}
if ( form.encryptionKey ) {
const saveDraftButton = document.querySelector( '.form-footer#save-draft' );
if ( saveDraftButton ) {
saveDraftButton.remove();
}
if ( !encryptor.isSupported() ) {
loadErrors.unshift( t( 'error.encryptionnotsupported' ) );
}
}
formprogress = document.querySelector( '.form-progress' );
_setEventHandlers();
setLogoutLinkVisibility();
if ( loadErrors.length > 0 ) {
throw loadErrors;
}
return form;
} )
.catch( error => {
if ( Array.isArray( error ) ) {
loadErrors = error;
} else {
loadErrors.unshift( error.message || t( 'error.unknown' ) );
}
advice = ( data.instanceStr ) ? t( 'alert.loaderror.editadvice' ) : t( 'alert.loaderror.entryadvice' );
gui.alertLoadErrors( loadErrors, advice );
} );
}
function _initializeRecords() {
if ( !settings.offline ) {
return Promise.resolve();
}
return records.init();
}
function _checkAutoSavedRecord() {
let rec;
if ( !settings.offline ) {
return Promise.resolve();
}
return records.getAutoSavedRecord()
.then( record => {
if ( record ) {
rec = record;
return gui.confirm( {
heading: t( 'confirm.autosaveload.heading' ),
msg: t( 'confirm.autosaveload.msg' ),
}, {
posButton: t( 'confirm.autosaveload.posButton' ),
negButton: t( 'confirm.autosaveload.negButton' ),
allowAlternativeClose: false
} );
}
} )
.then( confirmed => {
if ( confirmed ) {
return rec;
}
if ( rec ) {
records.removeAutoSavedRecord();
}
} );
}
/**
* Controller function to reset to a blank form. Checks whether all changes have been saved first
* @param {boolean=} confirmed Whether unsaved changes can be discarded and lost forever
*/
function _resetForm( confirmed ) {
let message;
if ( !confirmed && form.editStatus ) {
message = t( 'confirm.save.msg' );
gui.confirm( message )
.then( confirmed => {
if ( confirmed ) {
_resetForm( true );
}
} );
} else {
form.resetView();
form = new Form( formSelector, {
modelStr: formData.modelStr,
external: formData.external
}, formOptions );
const loadErrors = form.init();
// formreset event will update the form media:
form.view.$.trigger( 'formreset' );
if ( records ) {
records.setActive( null );
}
if ( loadErrors.length > 0 ) {
gui.alertLoadErrors( loadErrors );
}
}
}
/**
* Loads a record from storage
*
* @param {string} instanceId [description]
* @param {=boolean?} confirmed [description]
*/
function _loadRecord( instanceId, confirmed ) {
let texts;
let choices;
let loadErrors;
if ( !confirmed && form.editStatus ) {
texts = {
msg: t( 'confirm.discardcurrent.msg' ),
heading: t( 'confirm.discardcurrent.heading' )
};
choices = {
posButton: t( 'confirm.discardcurrent.posButton' ),
};
gui.confirm( texts, choices )
.then( confirmed => {
if ( confirmed ) {
_loadRecord( instanceId, true );
}
} );
} else {
records.get( instanceId )
.then( record => {
if ( !record || !record.xml ) {
return gui.alert( t( 'alert.recordnotfound.msg' ) );
}
form.resetView();
form = new Form( formSelector, {
modelStr: formData.modelStr,
instanceStr: record.xml,
external: formData.external,
submitted: false
}, formOptions );
loadErrors = form.init();
// formreset event will update the form media:
form.view.$.trigger( 'formreset' );
form.recordName = record.name;
records.setActive( record.instanceId );
if ( loadErrors.length > 0 ) {
throw loadErrors;
} else {
gui.feedback( t( 'alert.recordloadsuccess.msg', {
recordName: record.name
} ), 2 );
}
$( '.side-slider__toggle.close' ).click();
} )
.catch( errors => {
console.error( 'load errors: ', errors );
if ( !Array.isArray( errors ) ) {
errors = [ errors.message ];
}
gui.alertLoadErrors( errors, t( 'alert.loaderror.editadvice' ) );
} );
}
}
/**
* Used to submit a form.
* This function does not save the record in the browser storage
* and is not used in offline-capable views.
*/
function _submitRecord() {
const redirect = settings.type === 'single' || settings.type === 'edit' || settings.type === 'view';
let beforeMsg;
let authLink;
let level;
let msg = '';
const include = { irrelevant: false };
form.view.$.trigger( 'beforesave' );
beforeMsg = ( redirect ) ? t( 'alert.submission.redirectmsg' ) : '';
authLink = `<a href="${settings.loginUrl}" target="_blank">${t( 'here' )}</a>`;
gui.alert( `${beforeMsg}<div class="loader-animation-small" style="margin: 40px auto 0 auto;"/>`, t( 'alert.submission.msg' ), 'bare' );
return new Promise( resolve => {
const record = {
'xml': form.getDataStr( include ),
'files': fileManager.getCurrentFiles(),
'instanceId': form.instanceID,
'deprecatedId': form.deprecatedID
};
if ( form.encryptionKey ) {
const formProps = {
encryptionKey: form.encryptionKey,
id: form.view.html.id, // TODO: after enketo-core support, use form.id
version: form.version,
};
resolve( encryptor.encryptRecord( formProps, record ) );
} else {
resolve( record );
}
} )
.then( connection.uploadRecord )
.then( result => {
result = result || {};
level = 'success';
if ( result.failedFiles && result.failedFiles.length > 0 ) {
msg = `${t( 'alert.submissionerror.fnfmsg', {
failedFiles: result.failedFiles.join( ', ' ),
supportEmail: settings.supportEmail
} )}<br/>`;
level = 'warning';
}
// this event is used in communicating back to iframe parent window
document.dispatchEvent( events.SubmissionSuccess() );
if ( redirect ) {
if ( !settings.multipleAllowed ) {
const now = new Date();
const age = 31536000;
const d = new Date();
/**
* Manipulate the browser history to work around potential ways to
* circumvent protection against multiple submissions:
* 1. After redirect, click Back button to load cached version.
*/
history.replaceState( {}, '', `${settings.defaultReturnUrl}?taken=${now.getTime()}` );
/**
* The above replaceState doesn't work in Safari and probably in
* some other browsers (mobile). It shows the
* final submission dialog when clicking Back.
* So we remove the form...
*/
$( 'form.or' ).empty();
$( 'button#submit-form' ).remove();
d.setTime( d.getTime() + age * 1000 );
document.cookie = `${settings.enketoId}=${now.getTime()};path=/single;max-age=${age};expires=${d.toGMTString()};`;
}
msg += t( 'alert.submissionsuccess.redirectmsg' );
gui.alert( msg, t( 'alert.submissionsuccess.heading' ), level );
setTimeout( () => {
location.href = decodeURIComponent( settings.returnUrl || settings.defaultReturnUrl );
}, 1200 );
} else {
msg = ( msg.length > 0 ) ? msg : t( 'alert.submissionsuccess.msg' );
gui.alert( msg, t( 'alert.submissionsuccess.heading' ), level );
_resetForm( true );
}
} )
.catch( result => {
let message;
result = result || {};
console.error( 'submission failed', result );
if ( result.status === 401 ) {
message = t( 'alert.submissionerror.authrequiredmsg', {
here: authLink,
// switch off escaping just for this known safe value
interpolation: {
escapeValue: false
}
} );
} else {
message = result.message || gui.getErrorResponseMsg( result.status );
}
gui.alert( message, t( 'alert.submissionerror.heading' ) );
} );
}
function _getRecordName() {
return records.getCounterValue( settings.enketoId )
.then( count => form.instanceName || form.recordName || `${form.surveyName} - ${count}` );
}
function _confirmRecordName( recordName, errorMsg ) {
const texts = {
msg: '',
heading: t( 'formfooter.savedraft.label' ),
errorMsg
};
const choices = {
posButton: t( 'confirm.save.posButton' ),
negButton: t( 'confirm.default.negButton' )
};
const inputs = `<label><span>${t( 'confirm.save.name' )}</span><span class="or-hint active">${t( 'confirm.save.hint' )}</span><input name="record-name" type="text" value="${recordName}"required /></label>`;
return gui.prompt( texts, choices, inputs )
.then( values => {
if ( values ) {
return values[ 'record-name' ];
}
throw new Error( 'Cancelled by user' );
} );
}
// Save the translations in case ever required in the future, by leaving this comment in:
// t( 'confirm.save.renamemsg', {} )
function _saveRecord( draft = true, recordName, confirmed, errorMsg ) {
const include = { irrelevant: draft };
// triggering "beforesave" event to update possible "timeEnd" meta data in form
form.view.$.trigger( 'beforesave' );
// check recordName
if ( !recordName ) {
return _getRecordName()
.then( name => _saveRecord( draft, name, false, errorMsg ) );
}
// check whether record name is confirmed if necessary
if ( draft && !confirmed ) {
return _confirmRecordName( recordName, errorMsg )
.then( name => _saveRecord( draft, name, true ) )
.catch( () => {} );
}
return new Promise( resolve => {
// build the record object
const record = {
'draft': draft,
'xml': form.getDataStr( include ),
'name': recordName,
'instanceId': form.instanceID,
'deprecateId': form.deprecatedID,
'enketoId': settings.enketoId,
'files': fileManager.getCurrentFiles()
};
// encrypt the record
if ( form.encryptionKey && !draft ) {
const formProps = {
encryptionKey: form.encryptionKey,
id: form.view.html.id, // TODO: after enketo-core support, use form.id
version: form.version,
};
resolve( encryptor.encryptRecord( formProps, record ) );
} else {
resolve( record );
}
} ).then( record => {
// Change file object for database, not sure why this was chosen.
record.files = record.files.map( file => ( typeof file === 'string' ) ? {
name: file
} : {
name: file.name,
item: file
} );
// Save the record, determine the save method
const saveMethod = form.recordName ? 'update' : 'set';
console.log( 'saving record with', saveMethod, record );
return records[ saveMethod ]( record );
} )
.then( () => {
records.removeAutoSavedRecord();
_resetForm( true );
if ( draft ) {
gui.feedback( t( 'alert.recordsavesuccess.draftmsg' ), 3 );
} else {
gui.feedback( t( 'alert.recordsavesuccess.finalmsg' ), 3 );
// The timeout simply avoids showing two messages at the same time:
// 1. "added to queue"
// 2. "successfully submitted"
setTimeout( records.uploadQueue, 5 * 1000 );
}
} )
.catch( error => {
console.error( 'save error', error );
errorMsg = error.message;
if ( !errorMsg && error.target && error.target.error && error.target.error.name && error.target.error.name.toLowerCase() === 'constrainterror' ) {
errorMsg = t( 'confirm.save.existingerror' );
} else if ( !errorMsg ) {
errorMsg = t( 'confirm.save.unkownerror' );
}
gui.alert( errorMsg, 'Save Error' );
} );
}
function _autoSaveRecord() {
// Do not auto-save a record if the record was loaded from storage
// or if the form has enabled encryption
if ( form.recordName || form.encryptionKey ) {
return Promise.resolve();
}
// build the variable portions of the record object
const record = {
'xml': form.getDataStr(),
'files': fileManager.getCurrentFiles().map( file => ( typeof file === 'string' ) ? {
name: file
} : {
name: file.name,
item: file
} )
};
// save the record
return records.updateAutoSavedRecord( record )
.then( () => {
console.log( 'autosave successful' );
} )
.catch( error => {
console.error( 'autosave error', error );
} );
}
function _setEventHandlers() {
const $doc = $( document );
$( 'button#submit-form' ).click( function() {
const $button = $( this );
$button.btnBusyState( true );
setTimeout( () => {
form.validate()
.then( valid => {
if ( valid ) {
if ( settings.offline ) {
return _saveRecord( false );
} else {
return _submitRecord();
}
} else {
gui.alert( t( 'alert.validationerror.msg' ) );
}
} )
.catch( e => {
gui.alert( e.message );
} )
.then( () => {
$button.btnBusyState( false );
} );
}, 100 );
return false;
} );
const draftButton = document.querySelector( 'button#save-draft' );
if ( draftButton ) {
draftButton.addEventListener( 'click', event => {
if ( !event.target.matches( '.save-draft-info' ) ) {
const $button = $( draftButton );
$button.btnBusyState( true );
setTimeout( () => {
_saveRecord( true )
.then( () => {
$button.btnBusyState( false );
} )
.catch( e => {
$button.btnBusyState( false );
throw e;
} );
}, 100 );
}
} );
}
$( 'button#validate-form:not(.disabled)' ).click( function() {
if ( typeof form !== 'undefined' ) {
const $button = $( this );
$button.btnBusyState( true );
setTimeout( () => {
form.validate()
.then( valid => {
$button.btnBusyState( false );
if ( !valid ) {
gui.alert( t( 'alert.validationerror.msg' ) );
} else {
gui.alert( t( 'alert.validationsuccess.msg' ), t( 'alert.validationsuccess.heading' ), 'success' );
}
} )
.catch( e => {
gui.alert( e.message );
} )
.then( () => {
$button.btnBusyState( false );
} );
}, 100 );
}
return false;
} );
$( 'button#close-form:not(.disabled)' ).click( () => {
const msg = t( 'alert.submissionsuccess.redirectmsg' );
document.dispatchEvent( events.Close() );
gui.alert( msg, t( 'alert.closing.heading' ), 'warning' );
setTimeout( () => {
location.href = decodeURIComponent( settings.returnUrl || settings.defaultReturnUrl );
}, 300 );
return false;
} );
$( '.record-list__button-bar__button.upload' ).on( 'click', () => {
records.uploadQueue();
} );
$( '.record-list__button-bar__button.export' ).on( 'click', () => {
const downloadLink = '<a class="vex-dialog-link" id="download-export" href="#">download</a>';
records.exportToZip( form.surveyName )
.then( zipFile => {
gui.alert( t( 'alert.export.success.msg' ) + downloadLink, t( 'alert.export.success.heading' ), 'normal' );
updateDownloadLinkAndClick( document.querySelector( '#download-export' ), zipFile );
} )
.catch( error => {
let message = t( 'alert.export.error.msg', {
errors: error.message,
interpolation: {
escapeValue: false
}
} );
if ( error.exportFile ) {
message += `<p>${t( 'alert.export.error.filecreatedmsg' )}</p>${downloadLink}`;
}
gui.alert( message, t( 'alert.export.error.heading' ) );
if ( error.exportFile ) {
updateDownloadLinkAndClick( document.querySelector( '#download-export' ), error.exportFile );
}
} );
} );
$doc.on( 'click', '.record-list__records__record[data-draft="true"]', function() {
_loadRecord( $( this ).attr( 'data-id' ), false );
} );
$doc.on( 'click', '.record-list__records__record', function() {
$( this ).next( '.record-list__records__msg' ).toggle( 100 );
} );
document.addEventListener( events.ProgressUpdate().type, event => {
if ( event.target.classList.contains( 'or' ) && formprogress && event.detail ) {
formprogress.style.width = `${event.detail}%`;
}
} );
if ( inIframe() && settings.parentWindowOrigin ) {
document.addEventListener( events.SubmissionSuccess().type, postEventAsMessageToParentWindow );
document.addEventListener( events.Edited().type, postEventAsMessageToParentWindow );
document.addEventListener( events.Close().type, postEventAsMessageToParentWindow );
}
document.addEventListener( events.QueueSubmissionSuccess().type, event => {
const successes = event.detail;
gui.feedback( t( 'alert.queuesubmissionsuccess.msg', {
count: successes.length,
recordNames: successes.join( ', ' )
} ), 7 );
} );
if ( settings.offline ) {
document.addEventListener( events.XFormsValueChanged().type, _autoSaveRecord );
}
}
function updateDownloadLinkAndClick( anchor, file ) {
const objectUrl = URL.createObjectURL( file );
anchor.textContent = file.name;
updateDownloadLink( anchor, objectUrl, file.name );
anchor.click();
}
function setLogoutLinkVisibility() {
const visible = document.cookie.split( '; ' ).some( rawCookie => rawCookie.indexOf( '__enketo_logout=' ) !== -1 );
$( '.form-footer .logout' ).toggleClass( 'hide', !visible );
}
/**
* Determines whether the page is loaded inside an iframe
* @return {boolean} [description]
*/
function inIframe() {
try {
return window.self !== window.top;
} catch ( e ) {
return true;
}
}
/**
* Attempts to send a message to the parent window, useful if the webform is loaded inside an iframe.
* @param {{type: string}} event
*/
function postEventAsMessageToParentWindow( event ) {
if ( event && event.type ) {
try {
window.parent.postMessage( JSON.stringify( {
enketoEvent: event.type
} ), settings.parentWindowOrigin );
} catch ( error ) {
console.error( error );
}
}
}
export default {
init,
setLogoutLinkVisibility,
inIframe,
postEventAsMessageToParentWindow
};
|
// @flow
import React from 'react'
import { withState } from 'recompose'
import { storiesOf } from '@kadira/storybook'
import Button from 'components/Button'
import Modal from './'
const MyModal = withState('isShow', 'setShow', false)(
({
isShow,
setShow,
}: {
isShow: boolean,
setShow: (isShow: boolean) => void,
}) => (
<div>
<Button onClick={() => setShow(true)}>Open</Button>
<Modal
theme={{ content: 'animated slideInUp' }}
open={isShow}
title="Hello Modal"
onClose={() => setShow(false)}
actions={[
{
icon: 'fa-check',
label: 'Confirm',
className: 'is-primary',
},
{
icon: 'fa-times',
label: 'Cancel',
onClick: () => setShow(false),
},
]}
>
This is the content
</Modal>
</div>
),
)
storiesOf('Modal', module)
.add('default', () => (
<MyModal />
))
|
"use strict";
var mongoose = require("mongoose");
var CategorySchema = new mongoose.Schema({
name: String,
places: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Place' }]
});
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = mongoose.model('Category', CategorySchema);
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const THREE = SupEngine.THREE;
const engine = {};
exports.default = engine;
const canvasElt = document.querySelector("canvas");
engine.gameInstance = new SupEngine.GameInstance(canvasElt);
const cameraActor = new SupEngine.Actor(engine.gameInstance, "Camera");
cameraActor.setLocalPosition(new THREE.Vector3(0, 0, 10));
const cameraComponent = new SupEngine.componentClasses["Camera"](cameraActor);
new SupEngine.editorComponentClasses["Camera3DControls"](cameraActor, cameraComponent);
const light = new THREE.AmbientLight(0xcfcfcf);
engine.gameInstance.threeScene.add(light);
const spotLight = new THREE.PointLight(0xffffff, 0.2);
cameraActor.threeObject.add(spotLight);
spotLight.updateMatrixWorld(false);
let isTabActive = true;
let animationFrame;
window.addEventListener("message", (event) => {
if (event.data.type === "deactivate" || event.data.type === "activate") {
isTabActive = event.data.type === "activate";
onChangeActive();
}
});
function onChangeActive() {
const stopRendering = !isTabActive;
if (stopRendering) {
if (animationFrame != null) {
cancelAnimationFrame(animationFrame);
animationFrame = null;
}
}
else if (animationFrame == null) {
animationFrame = requestAnimationFrame(tick);
}
}
let lastTimestamp = 0;
let accumulatedTime = 0;
function tick(timestamp = 0) {
accumulatedTime += timestamp - lastTimestamp;
lastTimestamp = timestamp;
const { updates, timeLeft } = engine.gameInstance.tick(accumulatedTime);
accumulatedTime = timeLeft;
if (updates > 0)
engine.gameInstance.draw();
animationFrame = requestAnimationFrame(tick);
}
animationFrame = requestAnimationFrame(tick);
|
const log4js = require('log4js');
const config = require('config');
function initialize() {
log4js.configure(config.get('logging'));
}
module.exports.initialize = initialize;
|
var mongoose = require('mongoose')
var CompanySchema = new mongoose.Schema({
symbol: {
type: String,
required: [true, "can't be blank"],
match: [/^[0-9]+$/, 'is invalid']
},
name: {
type: String,
required: [true, "can't be blank"]
},
abbr: String,
logo: String,
link: String,
tagList: {
type: [{ type: String }],
validate: [tagListLimit, '{PATH} exceeds the limit of 2']
},
records: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Record'
}],
financials: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Financial'
}],
author: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
}
}, { timestamps: true })
CompanySchema.methods.setAbbr = function(){
this.abbr = this.name.substr(0,4)
}
CompanySchema.pre('validate', function(next){
if(!this.abbr){
this.setAbbr()
}
next()
})
CompanySchema.methods.toJSONFor = function(){
return {
updatedAt: this.updatedAt,
symbol: this.symbol,
abbr: this.abbr,
logo: this.logo || 'https://static.productionready.io/images/smiley-cyrus.jpg',
name: this.name,
link: this.link,
tagList: this.tagList
}
}
CompanySchema.methods.toJSONForAdmin = function(){
return {
symbol: this.symbol,
years: this.records.map(record => record.year),
author: this.author.toJSONFor()
}
}
function tagListLimit(val){
return val.length <= 2
}
mongoose.model('Company', CompanySchema)
|
import { mat4, vec3, quat } from "gl-matrix";
import { Renderer, Sprite, LineGeometry, ColorMaterial, CubeGeometry, RotationGeometry, SphereGeometry, PerspectiveCamera, radians, deepCopy, AmbientLight, PointLight, PhongShadingPhongLightingMaterial, PhongShadingBlinnPhongLightingMaterial, GouraudShadingPhongLightingMaterial, GouraudShadingBlinnPhongLightingMaterial, MaterialMultiplexer } from "./engine.ts";
import * as engine from "./engine.ts";
let canvas = document.querySelector("canvas");
canvas.width = window.innerWidth;
canvas.height = window.innerHeight * 0.8;
function main() {
let renderer = new Renderer(canvas);
renderer.viewport = {
x: 0,
y: 0,
width: canvas.width,
height: canvas.height,
};
let world = new Sprite(null, null);
let thirdPersonCameraTheta = 45;
let thirdPersonCameraPhi = 45;
let thirdPersonCameraRadius = 10;
let thirdPersonCamera = new PerspectiveCamera(
[5, 5, 5],
[0, 0, 0],
[0, 0, 1],
radians(42),
canvas.width / canvas.height,
0.1,
1000,
);
let firstPersonCameraTheta = 90;
let firstPersonCameraPhi = 90;
let firstPersonCameraRadius = 10;
let firstPersonCamera = new PerspectiveCamera(
[5, 5, 5],
[0, 0, 0],
[0, 0, 1],
radians(42),
canvas.width / canvas.height,
0.1,
100,
);
let freeCameraPosition = [5, 5, 5];
let freeCameraTheta = 45;
let freeCameraPhi = 45;
let freeCameraRadius = 10;
let freeCamera = new PerspectiveCamera(
[5, 5, 5],
[0, 0, 0],
[0, 0, 1],
radians(60),
canvas.width / canvas.height,
0.1,
100,
);
let camera = thirdPersonCamera;
// initial shading method set to gouraud
let shadingMethod = "gouraud";
// initial lighting method set to phong
let lightingMethod = "phong"
// callback for material multiplexer
function whichMaterial() {
// choose shading and lighting method
if (shadingMethod === "gouraud" && lightingMethod === "phong") {
return "gouraudShadingPhongLighting";
} else if (shadingMethod === "gouraud" && lightingMethod === "blinn-phong") {
return "gouraudShadingBlinnPhongLighting";
} else if (shadingMethod === "phong" && lightingMethod === "phong") {
return "phongShadingPhongLighting";
} else {
return "phongShadingBlinnPhongLighting";
}
}
// materials
let goldMaterials = {
phongShadingPhongLighting: new PhongShadingPhongLightingMaterial(
[0.35, 0.24, 0.19, 1.0],
[0.702, 0.482, 0.384, 1],
[0.628281, 0.555802, 0.366065, 1.0],
[0, 0, 0, 1],
[51.2, 51.2, 51.2, 51.2],
),
phongShadingBlinnPhongLighting: new PhongShadingBlinnPhongLightingMaterial(
[0.35, 0.24, 0.19, 1.0],
[0.702, 0.482, 0.384, 1],
[0.628281, 0.555802, 0.366065, 1.0],
[0, 0, 0, 1],
[51.2, 51.2, 51.2, 51.2],
),
gouraudShadingPhongLighting: new GouraudShadingPhongLightingMaterial(
[0.35, 0.24, 0.19, 1.0],
[0.702, 0.482, 0.384, 1],
[0.628281, 0.555802, 0.366065, 1.0],
[0, 0, 0, 1],
[51.2, 51.2, 51.2, 51.2],
),
gouraudShadingBlinnPhongLighting: new GouraudShadingBlinnPhongLightingMaterial(
[0.35, 0.24, 0.19, 1.0],
[0.702, 0.482, 0.384, 1],
[0.628281, 0.555802, 0.366065, 1.0],
[0, 0, 0, 1],
[51.2, 51.2, 51.2, 51.2],
),
};
let skinMaterials = {
phongShadingPhongLighting: new PhongShadingPhongLightingMaterial(
[0.2125, 0.1275, 0.054, 1.0],
[0.714, 0.4284, 0.18144, 1.0],
[0.393548, 0.271906, 0.166721, 1.0],
[0.0, 0.0, 0.0, 1.0],
[25.6, 25.6, 25.6, 25.6],
),
phongShadingBlinnPhongLighting: new PhongShadingBlinnPhongLightingMaterial(
[0.2125, 0.1275, 0.054, 1.0],
[0.714, 0.4284, 0.18144, 1.0],
[0.393548, 0.271906, 0.166721, 1.0],
[0.0, 0.0, 0.0, 1.0],
[25.6, 25.6, 25.6, 25.6],
),
gouraudShadingPhongLighting: new GouraudShadingPhongLightingMaterial(
[0.2125, 0.1275, 0.054, 1.0],
[0.714, 0.4284, 0.18144, 1.0],
[0.393548, 0.271906, 0.166721, 1.0],
[0.0, 0.0, 0.0, 1.0],
[25.6, 25.6, 25.6, 25.6],
),
gouraudShadingBlinnPhongLighting: new GouraudShadingBlinnPhongLightingMaterial(
[0.2125, 0.1275, 0.054, 1.0],
[0.714, 0.4284, 0.18144, 1.0],
[0.393548, 0.271906, 0.166721, 1.0],
[0.0, 0.0, 0.0, 1.0],
[25.6, 25.6, 25.6, 25.6],
),
};
let clothMaterials = {
phongShadingPhongLighting: new PhongShadingPhongLightingMaterial(
[0.05, 0.05, 0.05, 1.0],
[0.0, 0.2, 0.6, 1.0],
[0.1, 0.2, 0.3, 1.0],
[0.0, 0.0, 0.0, 1.0],
[5, 5, 5, 5],
),
phongShadingBlinnPhongLighting: new PhongShadingBlinnPhongLightingMaterial(
[0.05, 0.05, 0.05, 1.0],
[0.0, 0.2, 0.6, 1.0],
[0.1, 0.2, 0.3, 1.0],
[0.0, 0.0, 0.0, 1.0],
[5, 5, 5, 5],
),
gouraudShadingPhongLighting: new GouraudShadingPhongLightingMaterial(
[0.05, 0.05, 0.05, 1.0],
[0.0, 0.2, 0.6, 1.0],
[0.1, 0.2, 0.3, 1.0],
[0.0, 0.0, 0.0, 1.0],
[5, 5, 5, 5],
),
gouraudShadingBlinnPhongLighting: new GouraudShadingBlinnPhongLightingMaterial(
[0.05, 0.05, 0.05, 1.0],
[0.0, 0.2, 0.6, 1.0],
[0.1, 0.2, 0.3, 1.0],
[0.0, 0.0, 0.0, 1.0],
[5, 5, 5, 5],
),
};
let trousersMaterials = {
phongShadingPhongLighting: new PhongShadingPhongLightingMaterial(
[0.1, 0.1, 0.1, 1.0],
[0.6, 0.0, 0.0, 1.0],
[0.6, 0.6, 0.6, 1.0],
[0.0, 0.0, 0.0, 1.0],
[100, 100, 100, 100],
),
phongShadingBlinnPhongLighting: new PhongShadingBlinnPhongLightingMaterial(
[0.1, 0.1, 0.1, 1.0],
[0.6, 0.0, 0.0, 1.0],
[0.6, 0.6, 0.6, 1.0],
[0.0, 0.0, 0.0, 1.0],
[100, 100, 100, 100],
),
gouraudShadingPhongLighting: new GouraudShadingPhongLightingMaterial(
[0.1, 0.1, 0.1, 1.0],
[0.6, 0.0, 0.0, 1.0],
[0.6, 0.6, 0.6, 1.0],
[0.0, 0.0, 0.0, 1.0],
[100, 100, 100, 100],
),
gouraudShadingBlinnPhongLighting: new GouraudShadingBlinnPhongLightingMaterial(
[0.1, 0.1, 0.1, 1.0],
[0.6, 0.0, 0.0, 1.0],
[0.6, 0.6, 0.6, 1.0],
[0.0, 0.0, 0.0, 1.0],
[100, 100, 100, 100],
),
};
let catMaterials = {
phongShadingPhongLighting: new PhongShadingPhongLightingMaterial(
[0.19225, 0.19225, 0.19225, 1.0],
[0.50754, 0.50754, 0.50754, 1.0],
[0.508273, 0.508273, 0.508273, 1.0],
[0.0, 0.0, 0.0, 1.0],
[51.2, 51.2, 51.2, 51.2],
),
phongShadingBlinnPhongLighting: new PhongShadingBlinnPhongLightingMaterial(
[0.19225, 0.19225, 0.19225, 1.0],
[0.50754, 0.50754, 0.50754, 1.0],
[0.508273, 0.508273, 0.508273, 1.0],
[0.0, 0.0, 0.0, 1.0],
[51.2, 51.2, 51.2, 51.2],
),
gouraudShadingPhongLighting: new GouraudShadingPhongLightingMaterial(
[0.19225, 0.19225, 0.19225, 1.0],
[0.50754, 0.50754, 0.50754, 1.0],
[0.508273, 0.508273, 0.508273, 1.0],
[0.0, 0.0, 0.0, 1.0],
[51.2, 51.2, 51.2, 51.2],
),
gouraudShadingBlinnPhongLighting: new GouraudShadingBlinnPhongLightingMaterial(
[0.19225, 0.19225, 0.19225, 1.0],
[0.50754, 0.50754, 0.50754, 1.0],
[0.508273, 0.508273, 0.508273, 1.0],
[0.0, 0.0, 0.0, 1.0],
[51.2, 51.2, 51.2, 51.2],
),
};
let catSecondMaterials = {
phongShadingPhongLighting: new PhongShadingPhongLightingMaterial(
[0.1745, 0.01175, 0.01175, 0.55],
[0.61424, 0.04136, 0.04136, 0.55],
[0.727811, 0.626959, 0.626959, 0.55],
[0.0, 0.0, 0.0, 1.0],
[76.8, 76.8, 76.8, 76.8],
),
phongShadingBlinnPhongLighting: new PhongShadingBlinnPhongLightingMaterial(
[0.1745, 0.01175, 0.01175, 0.55],
[0.61424, 0.04136, 0.04136, 0.55],
[0.727811, 0.626959, 0.626959, 0.55],
[0.0, 0.0, 0.0, 1.0],
[76.8, 76.8, 76.8, 76.8],
),
gouraudShadingPhongLighting: new GouraudShadingPhongLightingMaterial(
[0.1745, 0.01175, 0.01175, 0.55],
[0.61424, 0.04136, 0.04136, 0.55],
[0.727811, 0.626959, 0.626959, 0.55],
[0.0, 0.0, 0.0, 1.0],
[76.8, 76.8, 76.8, 76.8],
),
gouraudShadingBlinnPhongLighting: new GouraudShadingBlinnPhongLightingMaterial(
[0.1745, 0.01175, 0.01175, 0.55],
[0.61424, 0.04136, 0.04136, 0.55],
[0.727811, 0.626959, 0.626959, 0.55],
[0.0, 0.0, 0.0, 1.0],
[76.8, 76.8, 76.8, 76.8],
),
};
let chromeMaterials = {
phongShadingPhongLighting: new PhongShadingPhongLightingMaterial(
[0.25, 0.25, 0.25, 1.0],
[0.4, 0.4, 0.4, 1.0],
[0.774597, 0.774597, 0.774597, 1.0],
[0.0, 0.0, 0.0, 1.0],
[76.8, 76.8, 76.8, 76.8],
),
phongShadingBlinnPhongLighting: new PhongShadingBlinnPhongLightingMaterial(
[0.25, 0.25, 0.25, 1.0],
[0.4, 0.4, 0.4, 1.0],
[0.774597, 0.774597, 0.774597, 1.0],
[0.0, 0.0, 0.0, 1.0],
[76.8, 76.8, 76.8, 76.8],
),
gouraudShadingPhongLighting: new GouraudShadingPhongLightingMaterial(
[0.25, 0.25, 0.25, 1.0],
[0.4, 0.4, 0.4, 1.0],
[0.774597, 0.774597, 0.774597, 1.0],
[0.0, 0.0, 0.0, 1.0],
[76.8, 76.8, 76.8, 76.8],
),
gouraudShadingBlinnPhongLighting: new GouraudShadingBlinnPhongLightingMaterial(
[0.25, 0.25, 0.25, 1.0],
[0.4, 0.4, 0.4, 1.0],
[0.774597, 0.774597, 0.774597, 1.0],
[0.0, 0.0, 0.0, 1.0],
[76.8, 76.8, 76.8, 76.8],
),
};
let pewterMaterials = {
phongShadingPhongLighting: new PhongShadingPhongLightingMaterial(
[0.105882, 0.058824, 0.113725, 1],
[0.427451, 0.470588, 0.541176, 1],
[0.33333, 0.33333, 0.521569, 1],
[0, 0, 0, 1],
[9.84615, 9.84615, 9.84615, 9.84615],
),
phongShadingBlinnPhongLighting: new PhongShadingBlinnPhongLightingMaterial(
[0.105882, 0.058824, 0.113725, 1],
[0.427451, 0.470588, 0.541176, 1],
[0.33333, 0.33333, 0.521569, 1],
[0, 0, 0, 1],
[9.84615, 9.84615, 9.84615, 9.84615],
),
gouraudShadingPhongLighting: new GouraudShadingPhongLightingMaterial(
[0.105882, 0.058824, 0.113725, 1],
[0.427451, 0.470588, 0.541176, 1],
[0.33333, 0.33333, 0.521569, 1],
[0, 0, 0, 1],
[9.84615, 9.84615, 9.84615, 9.84615],
),
gouraudShadingBlinnPhongLighting: new GouraudShadingBlinnPhongLightingMaterial(
[0.105882, 0.058824, 0.113725, 1],
[0.427451, 0.470588, 0.541176, 1],
[0.33333, 0.33333, 0.521569, 1],
[0, 0, 0, 1],
[9.84615, 9.84615, 9.84615, 9.84615],
),
};
let silverMaterials = {
phongShadingPhongLighting: new PhongShadingPhongLightingMaterial(
[0.23125, 0.23125, 0.23125, 1],
[0.2775, 0.2775, 0.2775, 1],
[0.773911, 0.773911, 0.773911, 1],
[0, 0, 0, 1],
[89.6, 89.6, 89.6, 89.6],
),
phongShadingBlinnPhongLighting: new PhongShadingBlinnPhongLightingMaterial(
[0.23125, 0.23125, 0.23125, 1],
[0.2775, 0.2775, 0.2775, 1],
[0.773911, 0.773911, 0.773911, 1],
[0, 0, 0, 1],
[89.6, 89.6, 89.6, 89.6],
),
gouraudShadingPhongLighting: new GouraudShadingPhongLightingMaterial(
[0.23125, 0.23125, 0.23125, 1],
[0.2775, 0.2775, 0.2775, 1],
[0.773911, 0.773911, 0.773911, 1],
[0, 0, 0, 1],
[89.6, 89.6, 89.6, 89.6],
),
gouraudShadingBlinnPhongLighting: new GouraudShadingBlinnPhongLightingMaterial(
[0.23125, 0.23125, 0.23125, 1],
[0.2775, 0.2775, 0.2775, 1],
[0.773911, 0.773911, 0.773911, 1],
[0, 0, 0, 1],
[89.6, 89.6, 89.6, 89.6],
),
};
let goldMaterial = new MaterialMultiplexer(goldMaterials, whichMaterial);
let skinMaterial = new MaterialMultiplexer(skinMaterials, whichMaterial);
let clothMaterial = new MaterialMultiplexer(clothMaterials, whichMaterial);
let trousersMaterial = new MaterialMultiplexer(trousersMaterials, whichMaterial);
let catMaterial = new MaterialMultiplexer(catMaterials, whichMaterial);
let catSecondMaterial = new MaterialMultiplexer(catSecondMaterials, whichMaterial);
let chromeMaterial = new MaterialMultiplexer(chromeMaterials, whichMaterial);
let pewterMaterial = new MaterialMultiplexer(pewterMaterials, whichMaterial);
let silverMaterial = new MaterialMultiplexer(silverMaterials, whichMaterial);
// material parameters taken from Ayerdi's lib
let xAxis = new Sprite(new LineGeometry([0, 0, 0], [1, 0, 0]), new ColorMaterial([1, 0, 0, 1]));
let yAxis = new Sprite(new LineGeometry([0, 0, 0], [0, 1, 0]), new ColorMaterial([0, 1, 0, 1]));
let zAxis = new Sprite(new LineGeometry([0, 0, 0], [0, 0, 1]), new ColorMaterial([0, 0, 1, 1]));
world.add(xAxis);
world.add(yAxis);
world.add(zAxis);
// reference ball
let ball = new Sprite(new SphereGeometry(2, 32, 32), goldMaterial);
mat4.translate(ball.modelMatrix, ball.modelMatrix, [0, 0, 5]);
world.add(ball);
// Start building ground grid
// let groundMaterial = new ColorMaterial([0.5, 0.5, 0.5, 1]);
for (let i = 0; i < 100; i++) {
let xGround = new Sprite(new LineGeometry([-50, -50 + i, 0], [50, -50 + i, 0]), new ColorMaterial([0.5, 0.5, 0.5, 1]));
let yGround = new Sprite(new LineGeometry([-50 + i, -50, 0], [-50 + i, 50, 0]), new ColorMaterial([0.5, 0.5, 0.5, 1]));
world.add(xGround);
world.add(yGround);
}
// tree
let tree = new Sprite(new RotationGeometry(0.2, 16, [0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 0.2, 1, 0.9, 0.8, 0.7, 0.6, 0.5, 0.4]), chromeMaterial);
mat4.translate(tree.modelMatrix, tree.modelMatrix, [0, 10, 0]);
world.add(tree);
let gyro = new Sprite(new RotationGeometry(1, 20, [0.01, 0.2, 0.4, 0.6, 0.8, 0.6, 0.4, 0.2, 0.1, 0.09, 0.08, 0.07, 0.06, 0.05, 0.04].map(v => 10 * v)), silverMaterial);
let gyroTranslationMatrix = mat4.create();
mat4.fromTranslation(gyroTranslationMatrix, [0, -20, 0]);
world.add(gyro);
// ambient light
let ambientLight = new AmbientLight([0.1, 0.1, 0.1, 1]);
world.add(ambientLight);
let light = new PointLight([3, 3, 0, 1], [3, 3, 0, 1]);
let lightIndicator = new Sprite(new SphereGeometry(0.1, 6, 3), new ColorMaterial([1, 1, 0, 1]));
lightIndicator.add(light);
let skyLight1 = new PointLight([5, 5, 5, 1], [5, 5, 5, 1]);
let skyLight2 = new PointLight([5, 5, 5, 1], [5, 5, 5, 1]);
let skyLightIndicator1 = new Sprite(new SphereGeometry(0.1, 6, 3), new ColorMaterial([1, 1, 1, 1]));
let skyLightIndicator2 = new Sprite(new SphereGeometry(0.1, 6, 3), new ColorMaterial([1, 1, 1, 1]));
skyLightIndicator1.add(skyLight1);
skyLightIndicator2.add(skyLight2);
mat4.translate(skyLightIndicator1.modelMatrix, skyLightIndicator1.modelMatrix, [10, 0, 0]);
mat4.translate(skyLightIndicator2.modelMatrix, skyLightIndicator2.modelMatrix, [-5, 0, 0]);
let lightCenter = new Sprite(null, null);
mat4.translate(lightCenter.modelMatrix, lightCenter.modelMatrix, [0, 2, 5]);
lightCenter.add(skyLightIndicator1);
lightCenter.add(skyLightIndicator2);
world.add(lightCenter);
// camera light
let cameraLight = new PointLight([5, 5, 5, 1], [5, 5, 5, 1]);
world.add(cameraLight);
// random grass block
for (let i = 0; i < 20; i++) {
for (let j = 0; j < 20; j++) {
let random = Math.floor(Math.random() * 10);
if (i < 4 || i > 6) {
if (random < 1) {
let grass2 = new Sprite(new CubeGeometry(1, 1, 2), goldMaterial);
mat4.translate(grass2.modelMatrix, grass2.modelMatrix, [-5.5 + i, -5.5 + j, 1]);
world.add(grass2);
} else if (random < 3) {
let grass = new Sprite(new CubeGeometry(1, 1, 1), goldMaterial);
mat4.translate(grass.modelMatrix, grass.modelMatrix, [-5.5 + i, -5.5 + j, 0.5]);
world.add(grass);
}
}
}
}
// random cloud
let clouds = [];
let cloudAnimations = [];
let cloudMaterial = pewterMaterial;
for (let i = 0; i < 100; i++) {
for (let j = 0; j < 100; j++) {
let random = Math.floor(Math.random() * 70);
if (i < 9 || i > 11) {
if (random < 1) {
let w = Math.floor(1 + Math.random() * 8);
let l = Math.floor(1 + Math.random() * 8);
let cloud = new Sprite(new CubeGeometry(w, l, 1), cloudMaterial);
mat4.translate(cloud.modelMatrix, cloud.modelMatrix, [-49.5 + i, -49.5 + j, 10 + 5 * Math.random()]);
world.add(cloud);
clouds.push(cloud);
let cloudAnimation = new engine.Animation(
{
0: {
translateX: -49.5 + i,
},
0.5: {
translateX: -49.5 + i + 100,
},
0.5000000001: { // go back to start point immediately
translateX: -49.5 + i - 100,
},
1.0: {
translateX: -49.5 + i,
}
}, 50 / Math.random(), engine.linear, 0, Infinity
);
cloudAnimation.start();
cloudAnimations.push(cloudAnimation);
}
}
}
}
// Start building steve
let hip = new Sprite(null, null);
let bodyJoint = new Sprite(null, null);
let body = new Sprite(new CubeGeometry(0.48, 0.24, 0.72), clothMaterial);
let headJoint = new Sprite(null, null);
let head = new Sprite(new CubeGeometry(0.48, 0.48, 0.48), skinMaterial);
let larmJoint = new Sprite(null, null);
let larm = new Sprite(new CubeGeometry(0.24, 0.24, 0.72), skinMaterial);
let armxAxis = new Sprite(new LineGeometry([0, 0, 0], [0.5, 0, 0]), new ColorMaterial([1, 0, 0, 1]));
let armyAxis = new Sprite(new LineGeometry([0, 0, 0], [0, 0.5, 0]), new ColorMaterial([0, 1, 0, 1]));
let armzAxis = new Sprite(new LineGeometry([0, 0, 0], [0, 0, 0.5]), new ColorMaterial([0, 0, 1, 1]));
[armxAxis, armyAxis, armzAxis].forEach(function (axis) {
larmJoint.add(axis);
});
// torch on left hand
let torch = new Sprite(new RotationGeometry(0.5, 20, [0.05, 0.10]), goldMaterial);
mat4.rotateX(torch.modelMatrix, torch.modelMatrix, 1.57);
mat4.translate(torch.modelMatrix, torch.modelMatrix, [0, -0.24, 0]);
larm.add(torch);
mat4.translate(lightIndicator.modelMatrix, lightIndicator.modelMatrix, [0, 0, 0.5]);
torch.add(lightIndicator);
let rarmJoint = new Sprite(null, null);
let rarm = new Sprite(new CubeGeometry(0.24, 0.24, 0.72), skinMaterial);
let llegJoint = new Sprite(null, null);
let lleg = new Sprite(new CubeGeometry(0.24, 0.24, 0.72), trousersMaterial);
let rlegJoint = new Sprite(null, null);
let rleg = new Sprite(new CubeGeometry(0.24, 0.24, 0.72), trousersMaterial);
let capeJoint = new Sprite(null, null);
let cape = new Sprite(new CubeGeometry(0.48, 0.06, 1.08), trousersMaterial);
let angelRing = new Sprite(new engine.TorusGeometry(0.24, 0.06, 32, 32), new ColorMaterial([1, 1, 0, 1]));
mat4.translate(hip.modelMatrix, hip.modelMatrix, [0, 0, 0.72]);
world.add(hip);
mat4.translate(body.modelMatrix, body.modelMatrix, [0, 0, 0.36]);
hip.add(bodyJoint);
bodyJoint.add(body);
// larm
mat4.translate(larmJoint.modelMatrix, larmJoint.modelMatrix, [0.36, 0, 0.24]);
mat4.translate(larm.modelMatrix, larm.modelMatrix, [0, 0, -0.24]);
body.add(larmJoint);
larmJoint.add(larm);
// rarm
mat4.translate(rarmJoint.modelMatrix, rarmJoint.modelMatrix, [-0.36, 0, 0.24]);
mat4.translate(rarm.modelMatrix, rarm.modelMatrix, [0, 0, -0.24]);
body.add(rarmJoint);
rarmJoint.add(rarm);
// lleg
mat4.translate(llegJoint.modelMatrix, llegJoint.modelMatrix, [-0.12, 0, 0]);
mat4.translate(lleg.modelMatrix, lleg.modelMatrix, [0, 0, -0.36]);
hip.add(llegJoint);
llegJoint.add(lleg);
// rleg
mat4.translate(rlegJoint.modelMatrix, rlegJoint.modelMatrix, [0.12, 0, 0]);
mat4.translate(rleg.modelMatrix, rleg.modelMatrix, [0, 0, -0.36]);
hip.add(rlegJoint);
rlegJoint.add(rleg);
// head
mat4.translate(headJoint.modelMatrix, headJoint.modelMatrix, [0, 0, 0.36]);
mat4.translate(head.modelMatrix, head.modelMatrix, [0, 0, 0.24]);
body.add(headJoint);
headJoint.add(head);
// cape
mat4.translate(capeJoint.modelMatrix, capeJoint.modelMatrix, [0, 0.12, 0.36]);
//mat4.rotateX(capeJoint.modelViewMatrix,capeJoint.modelViewMatrix, -0.24);
mat4.translate(cape.modelMatrix, cape.modelMatrix, [0, 0.03, -0.54]);
let capeOriMat = mat4.clone(capeJoint.modelMatrix);
body.add(capeJoint);
capeJoint.add(cape);
mat4.rotateX(angelRing.modelMatrix, angelRing.modelMatrix, 1.57)
mat4.translate(angelRing.modelMatrix, angelRing.modelMatrix, [0, 0.36, 0]);
head.add(angelRing);
// End build steve
// Start build cat
let catBody = new Sprite(new CubeGeometry(0.24, 0.96, 0.36), catMaterial);
let catxAxis = new Sprite(new LineGeometry([0, 0, 0], [0.5, 0, 0]), new ColorMaterial([1, 0, 0, 1]));
let catyAxis = new Sprite(new LineGeometry([0, 0, 0], [0, 2, 0]), new ColorMaterial([0, 1, 0, 1]));
let catzAxis = new Sprite(new LineGeometry([0, 0, 0], [0, 0, 0.5]), new ColorMaterial([0, 0, 1, 1]));
[catxAxis, catyAxis, catzAxis].forEach(function (axis) {
catBody.add(axis);
});
let catHeadJoint = new Sprite(null, null);
let catHead = new Sprite(new CubeGeometry(0.3, 0.3, 0.24), catMaterial);
let catMouth = new Sprite(new CubeGeometry(0.18, 0.06, 0.12), catSecondMaterial);
let catEarL = new Sprite(new CubeGeometry(0.06, 0.12, 0.06), catSecondMaterial);
let catEarR = new Sprite(new CubeGeometry(0.06, 0.12, 0.06), catSecondMaterial);
let catFrontFootLJoint = new Sprite(null, null);
let catFrontFootL = new Sprite(new CubeGeometry(0.12, 0.12, 0.6), catMaterial);
let catFrontFootRJoint = new Sprite(null, null);
let catFrontFootR = new Sprite(new CubeGeometry(0.12, 0.12, 0.6), catMaterial);
let catRearFootLJoint = new Sprite(null, null);
let catRearFootL = new Sprite(new CubeGeometry(0.12, 0.12, 0.36), catMaterial);
let catRearFootRJoint = new Sprite(null, null);
let catRearFootR = new Sprite(new CubeGeometry(0.12, 0.12, 0.36), catMaterial);
let catTailFrontJoint = new Sprite(null, null);
let catTailFront = new Sprite(new CubeGeometry(0.06, 0.48, 0.06), catMaterial);
let catTailRearJoint = new Sprite(null, null);
let catTailRear = new Sprite(new CubeGeometry(0.06, 0.48, 0.06), catMaterial);
mat4.translate(catBody.modelMatrix, catBody.modelMatrix, [0, 0, 0.7]);
// add cat head
mat4.translate(catHeadJoint.modelMatrix, catHeadJoint.modelMatrix, [0, 0.48, 0.09]);
mat4.translate(catHead.modelMatrix, catHead.modelMatrix, [0, 0.15, 0.03]);
mat4.translate(catEarL.modelMatrix, catEarL.modelMatrix, [0.09, -0.09, 0.15]);
mat4.translate(catEarR.modelMatrix, catEarR.modelMatrix, [-0.09, -0.09, 0.15])
mat4.translate(catMouth.modelMatrix, catMouth.modelMatrix, [0, 0.18, -0.06]);
catBody.add(catHeadJoint);
catHeadJoint.add(catHead);
catHead.add(catEarL);
catHead.add(catEarR);
catHead.add(catMouth);
// add Front Left Leg;
mat4.translate(catFrontFootLJoint.modelMatrix, catFrontFootLJoint.modelMatrix, [-0.063, 0.3, 0.12]);
mat4.translate(catFrontFootL.modelMatrix, catFrontFootL.modelMatrix, [0, 0, -0.24]);
catBody.add(catFrontFootLJoint);
catFrontFootLJoint.add(catFrontFootL);
// add Front Right Leg;
mat4.translate(catFrontFootRJoint.modelMatrix, catFrontFootRJoint.modelMatrix, [0.063, 0.3, 0.12]);
mat4.translate(catFrontFootR.modelMatrix, catFrontFootR.modelMatrix, [0, 0, -0.24]);
catBody.add(catFrontFootRJoint);
catFrontFootRJoint.add(catFrontFootR);
// add Rear Left Leg;
mat4.translate(catRearFootLJoint.modelMatrix, catRearFootLJoint.modelMatrix, [-0.063, -0.36, -0.12]);
mat4.translate(catRearFootL.modelMatrix, catRearFootL.modelMatrix, [0, 0, -0.12])
catBody.add(catRearFootLJoint);
catRearFootLJoint.add(catRearFootL);
// add Rear Left Leg;
mat4.translate(catRearFootRJoint.modelMatrix, catRearFootRJoint.modelMatrix, [0.063, -0.36, -0.12]);
mat4.translate(catRearFootR.modelMatrix, catRearFootR.modelMatrix, [0, 0, -0.12])
catBody.add(catRearFootRJoint);
catRearFootRJoint.add(catRearFootR);
// add tail front
mat4.translate(catTailFrontJoint.modelMatrix, catTailFrontJoint.modelMatrix, [0, -0.48, 0.12]);
mat4.translate(catTailFront.modelMatrix, catTailFront.modelMatrix, [0, -0.21, 0]);
catBody.add(catTailFrontJoint);
catTailFrontJoint.add(catTailFront);
// add tail Rear
mat4.translate(catTailRearJoint.modelMatrix, catTailRearJoint.modelMatrix, [0, -0.21, 0]);
mat4.translate(catTailRear.modelMatrix, catTailRear.modelMatrix, [0, -0.21, 0]);
catTailFront.add(catTailRearJoint);
catTailRearJoint.add(catTailRear);
//End Build Cat
let center = new Sprite(null, null);
world.add(center);
mat4.translate(catBody.modelMatrix, catBody.modelMatrix, [1.5, 0, -0.3]);
center.add(catBody);
mat4.rotateX(world.modelMatrix, world.modelMatrix, 6);
mat4.rotateY(world.modelMatrix, world.modelMatrix, -45);
// animations
let walkAnimation = new engine.Animation({
0: {
rotation: 0,
},
0.25: {
rotation: 0.8,
},
0.50: {
rotation: 0,
},
0.75: {
rotation: -0.8,
},
1: {
rotation: 0,
}
}, 0.75, engine.linear, 0, Infinity);
let jumpAnimation = new engine.Animation({
0: {
translate: 0.72,
},
0.5: {
translate: 1.25219 + 0.72,
},
1: {
translate: 0.72,
},
}, 0.3, engine.ease, 0, 1);
let catWalkAnimation = new engine.Animation({
0: {
rotation: 0,
},
0.25: {
rotation: 0.8,
},
0.50: {
rotation: 0,
},
0.75: {
rotation: -0.8,
},
1: {
rotation: 0,
}
}, 0.5, engine.linear, 0, Infinity);
let catTailAnimation = new engine.Animation({
0: {
rotation: 0,
},
0.25: {
rotation: 0.8,
},
0.50: {
rotation: 0,
},
0.75: {
rotation: -0.8,
},
1: {
rotation: 0,
}
}, 0.75, engine.linear, 0, Infinity);
catWalkAnimation.start();
catTailAnimation.start();
// controls
let isDragging = false;
let lastMousePosition;
let stevePosition = [0, 0, 0];
let steveWalking = false;
let steveBending = false;
let steveWalkingDirection = "+y";
let isPressed = Object();
let gyroQuaternion = quat.create();
// start dragging
canvas.addEventListener("mousedown", function (event) {
lastMousePosition = [event.offsetX, event.offsetY];
isDragging = true;
isPressed[event.button] = true;
});
// dragging
document.addEventListener("mousemove", function (event) {
let position = [event.offsetX, event.offsetY];
if (isDragging && isPressed[0]) {
if (camera === thirdPersonCamera) {
thirdPersonCameraTheta += - (position[0] - lastMousePosition[0]) / 2;
thirdPersonCameraPhi += - (position[1] - lastMousePosition[1]) / 2;
thirdPersonCameraPhi = Math.min(Math.max(thirdPersonCameraPhi, 1), 179) % 360;
} else if (camera === freeCamera) {
freeCameraTheta -= - (position[0] - lastMousePosition[0]) / 8;
freeCameraPhi -= - (position[1] - lastMousePosition[1]) / 8;
freeCameraPhi = Math.min(Math.max(freeCameraPhi, 1), 179) % 360;
} else if (camera === firstPersonCamera) {
firstPersonCameraTheta -= - (position[0] - lastMousePosition[0]) / 8;
firstPersonCameraPhi -= - (position[1] - lastMousePosition[1]) / 8;
firstPersonCameraPhi = Math.min(Math.max(firstPersonCameraPhi, 1), 179) % 360;
firstPersonCameraTheta = Math.min(Math.max(firstPersonCameraTheta, 1), 179) % 360;
}
} else if (isDragging && isPressed[2]) {
// quaternion-based rotation
let upVector = vec3.fromValues(
camera.upVector[0],
camera.upVector[1],
camera.upVector[2],
);
vec3.normalize(upVector, upVector);
let viewVector = vec3.fromValues(
camera.lookAt[0] - camera.position[0],
camera.lookAt[1] - camera.position[1],
camera.lookAt[2] - camera.position[2],
);
vec3.normalize(viewVector, viewVector);
let rightVector = vec3.create();
vec3.cross(rightVector, viewVector, upVector);
let deltaQuaternion = quat.create();
quat.setAxisAngle(deltaQuaternion, rightVector, radians(position[1] - lastMousePosition[1]) / 2);
quat.multiply(gyroQuaternion, deltaQuaternion, gyroQuaternion);
quat.setAxisAngle(deltaQuaternion, upVector, radians(position[0] - lastMousePosition[0]) / 2);
quat.multiply(gyroQuaternion, deltaQuaternion, gyroQuaternion)
}
lastMousePosition = position;
});
// prevent right mouse click menu
canvas.addEventListener("contextmenu", function (event) {
event.preventDefault();
return false;
});
// stop dragging
document.addEventListener("mouseup", function (event) {
isDragging = false;
isPressed[event.button] = false;
});
// mouse wheel to scale
canvas.addEventListener("wheel", function (event) {
event.preventDefault();
if (event.deltaY < 0) {
if (camera === thirdPersonCamera) {
thirdPersonCameraRadius *= (-0.25) * event.deltaY;
}
} else {
if (camera === thirdPersonCamera) {
thirdPersonCameraRadius /= 0.25 * event.deltaY;
}
}
thirdPersonCameraRadius = Math.max(Math.min(thirdPersonCameraRadius, 20), 0.01);
})
// press shift to bend
document.addEventListener("keydown", function (event) {
isPressed[event.code] = true;
if (event.code === "ShiftLeft") {
if (camera === thirdPersonCamera || camera === firstPersonCamera) {
steveBending = true;
// bend body
mat4.identity(bodyJoint.modelMatrix);
mat4.rotateX(bodyJoint.modelMatrix, bodyJoint.modelMatrix, 0.4);
// bend head
mat4.identity(headJoint.modelMatrix);
mat4.translate(headJoint.modelMatrix, headJoint.modelMatrix, [0, 0, 0.36]);
mat4.rotateX(headJoint.modelMatrix, headJoint.modelMatrix, -0.4);
} else { // free camera
// freeCameraPosition[2] += 0.1;
// cannot do anything here, because this requires the key BEING pressed
// move to onDraw()
}
} else if (event.code === "ControlLeft") {
if (camera === freeCamera) {
// freeCameraPosition[2] -= 0.1;
// cannot do anything here
}
} else if (event.code === "KeyW" && event.repeat === false) { // it turns out that keydown is not really keydown: it triggers multiple times when you hold the key down
if (camera === thirdPersonCamera || camera === firstPersonCamera) {
steveWalking = true;
steveWalkingDirection = "-y";
walkAnimation.start();
} else {
//
}
} else if (event.code === "KeyS" && event.repeat === false) {
if (camera === thirdPersonCamera || camera === firstPersonCamera) {
steveWalking = true;
steveWalkingDirection = "+y";
walkAnimation.start();
} else { // free camera
// freeCameraPosition[1] -= 0.1
}
} else if (event.code === "Space" && event.repeat === false) {
event.preventDefault();
jumpAnimation.start();
} else if (event.code === "KeyA" && event.repeat === false) {
if (camera === thirdPersonCamera || camera === firstPersonCamera) {
//
} else {
//
}
} else if (event.code === "KeyD" && event.repeat === false) {
//
}
});
document.addEventListener("keyup", function (event) {
isPressed[event.code] = false;
if (event.code === "ShiftLeft") {
steveBending = false;
mat4.identity(bodyJoint.modelMatrix);
mat4.identity(headJoint.modelMatrix);
mat4.translate(headJoint.modelMatrix, headJoint.modelMatrix, [0, 0, 0.36]);
} else if (event.code === "KeyW" || event.code === "KeyS") {
steveWalking = false;
walkAnimation.stop();
} else if (event.code === "KeyV") {
if (camera === thirdPersonCamera) {
camera = firstPersonCamera;
document.querySelector("#which-camera").textContent = "first person";
} else if (camera === firstPersonCamera) {
camera = freeCamera;
document.querySelector("#which-camera").textContent = "free fly";
} else {
camera = thirdPersonCamera;
document.querySelector("#which-camera").textContent = "third person";
}
}
});
function onDraw() {
// body position
stevePosition[2] = jumpAnimation.yield()["translate"];
if (steveWalking) {
if (steveWalkingDirection === "-y") {
stevePosition[1] -= 0.1;
} else if (steveWalkingDirection === "+y") {
stevePosition[1] += 0.1;
}
}
// world rotation
mat4.identity(world.modelMatrix);
// set third person camera
thirdPersonCamera.lookAt = deepCopy(stevePosition);
thirdPersonCamera.position = PerspectiveCamera.getPositionFromSphere(
thirdPersonCamera.lookAt,
radians(thirdPersonCameraTheta),
radians(thirdPersonCameraPhi),
thirdPersonCameraRadius,
);
// set first person camera
if (!steveBending) {
firstPersonCamera.position[0] = stevePosition[0];
firstPersonCamera.position[1] = stevePosition[1] - 0.3;
firstPersonCamera.position[2] = stevePosition[2] - 0.72 + 1.7;
} else {
firstPersonCamera.position[0] = stevePosition[0];
firstPersonCamera.position[1] = stevePosition[1] - 0.3 - 0.3;
firstPersonCamera.position[2] = stevePosition[2] - 0.72 + 1.7 - 0.1;
}
firstPersonCamera.lookAt = PerspectiveCamera.getLookAtFromSphere(
firstPersonCamera.position,
radians(firstPersonCameraTheta),
radians(firstPersonCameraPhi),
firstPersonCameraRadius,
);
// set free camera
if (camera === freeCamera) {
let facingVector = [ // lookAt - position
freeCamera.lookAt[0] - freeCamera.position[0],
freeCamera.lookAt[1] - freeCamera.position[1],
freeCamera.lookAt[2] - freeCamera.position[2]
];
let leftVector = vec3.create();
vec3.cross(leftVector, [0, 0, 1], facingVector); // get a vector perpendicular to facing vector
if (isPressed["KeyW"]) { // fly towards facing vector
freeCameraPosition[0] += 0.04 * facingVector[0];
freeCameraPosition[1] += 0.04 * facingVector[1];
freeCameraPosition[2] += 0.04 * facingVector[2];
}
if (isPressed["KeyS"]) { // fly towards inverse facing vector
freeCameraPosition[0] -= 0.04 * facingVector[0];
freeCameraPosition[1] -= 0.04 * facingVector[1];
freeCameraPosition[2] -= 0.04 * facingVector[2];
}
if (isPressed["KeyA"]) { // fly left, do not change height
freeCameraPosition[0] += 0.04 * leftVector[0];
freeCameraPosition[1] += 0.04 * leftVector[1];
// freeCameraPosition[2] += 0.04 * facingVector[2];
}
if (isPressed["KeyD"]) { // fly right, do not change height
freeCameraPosition[0] -= 0.04 * leftVector[0];
freeCameraPosition[1] -= 0.04 * leftVector[1];
// freeCameraPosition[2] += 0.04 * facingVector[2];
}
if (isPressed["ShiftLeft"]) { // fly upward
freeCameraPosition[2] += 0.2;
}
if (isPressed["ControlLeft"]) { // fly downward
freeCameraPosition[2] -= 0.2;
}
}
freeCamera.position = freeCameraPosition;
freeCamera.lookAt = PerspectiveCamera.getLookAtFromSphere(
freeCamera.position,
radians(freeCameraTheta),
radians(freeCameraPhi),
freeCameraRadius,
);
// set camera light position
mat4.identity(cameraLight.modelMatrix);
mat4.translate(cameraLight.modelMatrix, cameraLight.modelMatrix, camera.position);
mat4.identity(hip.modelMatrix);
mat4.translate(hip.modelMatrix, hip.modelMatrix, stevePosition);
// arm rotation
// let armRotation = document.querySelector("input[id=armPosition]").value / 100;
let armRotation = walkAnimation.yield()["rotation"];
mat4.identity(larmJoint.modelMatrix);
mat4.translate(larmJoint.modelMatrix, larmJoint.modelMatrix, [0.36, 0, 0.24]);
mat4.rotateX(larmJoint.modelMatrix, larmJoint.modelMatrix, armRotation);
mat4.identity(rarmJoint.modelMatrix);
mat4.translate(rarmJoint.modelMatrix, rarmJoint.modelMatrix, [-0.36, 0, 0.24]);
mat4.rotateX(rarmJoint.modelMatrix, rarmJoint.modelMatrix, -armRotation);
// leg rotation
mat4.identity(llegJoint.modelMatrix);
mat4.translate(llegJoint.modelMatrix, llegJoint.modelMatrix, [0.12, 0, 0]);
mat4.rotateX(llegJoint.modelMatrix, llegJoint.modelMatrix, -armRotation);
mat4.identity(rlegJoint.modelMatrix);
mat4.translate(rlegJoint.modelMatrix, rlegJoint.modelMatrix, [-0.12, 0, 0]);
mat4.rotateX(rlegJoint.modelMatrix, rlegJoint.modelMatrix, armRotation);
// cape animation
let angle = animateSin(0.12, 200);
mat4.rotateX(capeJoint.modelMatrix, capeOriMat, angle);
// cloud animation
for (let cloudIndex = 0; cloudIndex < clouds.length; cloudIndex++) {
let cloud = clouds[cloudIndex];
let cloudPosition = vec3.create();
mat4.getTranslation(cloudPosition, cloud.modelMatrix);
mat4.identity(cloud.modelMatrix);
mat4.translate(cloud.modelMatrix, cloud.modelMatrix, [cloudAnimations[cloudIndex].yield()["translateX"], cloudPosition[1], cloudPosition[2]]);
}
// light animation
//mat4.identity(lightIndicator.modelMatrix);
//mat4.translate(lightIndicator.modelMatrix, lightIndicator.modelMatrix, [0, 0, lightAnimation.yield()["translate"]]);
mat4.rotateZ(lightCenter.modelMatrix, lightCenter.modelMatrix, 0.02);
// ball rotation
mat4.rotateX(ball.modelMatrix, ball.modelMatrix, 0.05);
// mat4.translate(ball.modelMatrix, ball.modelMatrix, [0, 0, 5]);
renderer.clear([0, 0, 0, 1]);
renderer.render(world, camera);
requestAnimationFrame(onDraw);
// cat Rotation
mat4.rotateZ(center.modelMatrix, center.modelMatrix, 0.02);
// cat walk
let catWalkArmRotation = catWalkAnimation.yield()["rotation"];
mat4.identity(catFrontFootLJoint.modelMatrix);
mat4.translate(catFrontFootLJoint.modelMatrix, catFrontFootLJoint.modelMatrix, [0, 0.3, 0.12]);
mat4.rotateX(catFrontFootLJoint.modelMatrix, catFrontFootLJoint.modelMatrix, catWalkArmRotation);
mat4.identity(catFrontFootRJoint.modelMatrix);
mat4.translate(catFrontFootRJoint.modelMatrix, catFrontFootRJoint.modelMatrix, [0, 0.3, 0.12]);
mat4.rotateX(catFrontFootRJoint.modelMatrix, catFrontFootRJoint.modelMatrix, -catWalkArmRotation);
mat4.identity(catRearFootLJoint.modelMatrix);
mat4.translate(catRearFootLJoint.modelMatrix, catRearFootLJoint.modelMatrix, [-0.063, -0.36, -0.12]);
mat4.rotateX(catRearFootLJoint.modelMatrix, catRearFootLJoint.modelMatrix, -catWalkArmRotation);
mat4.identity(catRearFootRJoint.modelMatrix);
mat4.translate(catRearFootRJoint.modelMatrix, catRearFootRJoint.modelMatrix, [0.063, -0.36, -0.12]);
mat4.rotateX(catRearFootRJoint.modelMatrix, catRearFootRJoint.modelMatrix, catWalkArmRotation);
// cat tail
let catTailRotation = catTailAnimation.yield()["rotation"];
mat4.identity(catTailFrontJoint.modelMatrix);
mat4.translate(catTailFrontJoint.modelMatrix, catTailFrontJoint.modelMatrix, [0, -0.48, 0.12]);
mat4.rotateX(catTailFrontJoint.modelMatrix, catTailFrontJoint.modelMatrix, -catTailRotation);
mat4.identity(catTailRearJoint.modelMatrix);
mat4.translate(catTailRearJoint.modelMatrix, catTailRearJoint.modelMatrix, [0, -0.21, 0]);
mat4.rotateX(catTailRearJoint.modelMatrix, catTailRearJoint.modelMatrix, catTailRotation);
// gyro
let gyroRotationMatrix = mat4.create();
mat4.fromQuat(gyroRotationMatrix, gyroQuaternion);
let axis = quat.create();
let rotationAngle = quat.getAxisAngle(axis, gyroQuaternion);
mat4.fromRotation(gyroRotationMatrix, rotationAngle, axis);
mat4.multiply(gyro.modelMatrix, gyroTranslationMatrix, gyroRotationMatrix);
ambientLight.ia[0] = parseFloat(document.querySelector("#ambient-light-power-r").value);
ambientLight.ia[1] = parseFloat(document.querySelector("#ambient-light-power-g").value);
ambientLight.ia[2] = parseFloat(document.querySelector("#ambient-light-power-b").value);
let rgb = parseFloat(document.querySelector("#head-light-power-diffuse").value);
cameraLight.id = [rgb, rgb, rgb, 1];
rgb = parseFloat(document.querySelector("#head-light-power-specular").value);
cameraLight.is = [rgb, rgb, rgb, 1];
if (document.querySelector("#torch-switch-on").checked) {
light.id = [3, 3, 0, 1];
light.is = [3, 3, 0, 1];
} else if (document.querySelector("#torch-switch-off").checked) {
light.id = [0, 0, 0, 1];
light.is = [0, 0, 0, 1];
}
}
window.addEventListener("resize", function () {
canvas.width = window.innerWidth;
canvas.height = window.innerHeight * 0.8;
// reset camera aspect ratio
thirdPersonCamera.aspectRatio = canvas.width / canvas.height;
freeCamera.aspectRatio = canvas.width / canvas.height;
firstPersonCamera.aspectRatio = canvas.width / canvas.height;
// update gl.viewport
renderer.viewport.width = canvas.width;
renderer.viewport.height = canvas.height;
});
// reset shading method and lighting method
document.querySelector("#shading-method-gouraud").click();
document.querySelector("#lighting-method-phong").click();
// handlers for changing shading and lighting methods
document.querySelector("#shading-method-phong").addEventListener("click", function () {
shadingMethod = "phong";
});
document.querySelector("#shading-method-gouraud").addEventListener("click", function () {
shadingMethod = "gouraud";
});
document.querySelector("#lighting-method-phong").addEventListener("click", function () {
lightingMethod = "phong";
});
document.querySelector("#lighting-method-blinn-phong").addEventListener("click", function () {
lightingMethod = "blinn-phong";
});
onDraw();
}
function animateSin(limit, speed) {
//==============================================================================
// Calculate the elapsed time
var now = Date.now();
var newAngle = limit + limit * Math.sin(now / speed);
//if (newAngle > 180.0) newAngle = newAngle - 360.0;
//if (newAngle < -180.0) newAngle = newAngle + 360.0;
return newAngle;
}
window.onload = main; |
export const getTenants = state => state.tenants; |
exports.booking_trigger = `CREATE TRIGGER IF NOT EXISTS booking AFTER INSERT ON lecture_booking
BEGIN
DELETE FROM _Variables;
INSERT INTO _Variables(name, int_value, date_value)
SELECT 'lecture', id, DATE(start)
FROM lecture
WHERE id = NEW.lecture_id;
INSERT INTO _Variables(name, int_value, string_value)
SELECT 'course', course.id, course.name
FROM lecture, course
WHERE lecture.course = course.id AND lecture.id = NEW.lecture_id;
INSERT INTO stats_time(date, week, month, year)
SELECT date_value, strftime('%Y-', date(date_value, '-3 days', 'weekday 4')) || ((strftime('%j', date(date_value, '-3 days', 'weekday 4')) - 1) / 7 + 1), strftime('%Y-%m', date_value), strftime('%Y', date_value)
FROM _Variables
WHERE name = 'lecture'
AND NOT EXISTS (
SELECT *
FROM stats_time
WHERE date = (SELECT date_value FROM _Variables WHERE name = 'lecture')
);
INSERT INTO stats_lecture(lecture_id, course_id, course_name)
SELECT l.int_value , c.int_value, c.string_value
FROM _Variables l, _Variables c
WHERE l.name = 'lecture' AND c.name = 'course'
AND NOT EXISTS (
SELECT *
FROM stats_lecture
WHERE lecture_id = NEW.lecture_id
);
INSERT INTO _Variables(name, int_value) VALUES ('tid', (SELECT tid FROM stats_time WHERE date = (SELECT date_value FROM _Variables WHERE name = 'lecture')));
INSERT INTO _Variables(name, int_value) VALUES ('lid', (SELECT lid FROM stats_lecture WHERE lecture_id = NEW.lecture_id));
INSERT INTO stats_usage(tid, lid, booking, cancellations, attendance)
SELECT t.int_value, l.int_value, 0, 0, 0
FROM _Variables t, _Variables l
WHERE t.name = 'tid'
AND l.name = 'lid'
AND NOT EXISTS (
SELECT *
FROM stats_usage
WHERE lid = (SELECT int_value FROM _Variables WHERE name = 'lid')
AND tid = (SELECT int_value FROM _Variables WHERE name = 'tid')
);
UPDATE stats_usage
SET booking = booking + 1
WHERE lid = (SELECT int_value FROM _Variables WHERE name = 'lid')
AND tid = (SELECT int_value FROM _Variables WHERE name = 'tid');
END;`;
exports.cancellation_trigger = `CREATE TRIGGER IF NOT EXISTS cancellation AFTER DELETE ON lecture_booking
WHEN NOT EXISTS (SELECT name FROM _Trigger WHERE name = 'cancellation_trigger')
BEGIN
DELETE FROM _Variables;
INSERT INTO _Variables(name, int_value, date_value)
SELECT 'lecture', id, DATE(start)
FROM lecture
WHERE id = OLD.lecture_id;
INSERT INTO _Variables(name, int_value) VALUES ('tid', (SELECT tid FROM stats_time WHERE date = (SELECT date_value FROM _Variables WHERE name = 'lecture')));
INSERT INTO _Variables(name, int_value) VALUES ('lid', (SELECT lid FROM stats_lecture WHERE lecture_id = OLD.lecture_id));
UPDATE stats_usage
SET cancellations = cancellations + 1
WHERE lid = (SELECT int_value FROM _Variables WHERE name = 'lid')
AND tid = (SELECT int_value FROM _Variables WHERE name = 'tid');
END;`;
exports.convert_trigger = `CREATE TRIGGER IF NOT EXISTS convert AFTER UPDATE OF status ON lecture
WHEN NEW.status = 'distance'
BEGIN
DELETE FROM _Variables;
INSERT INTO _Trigger(name) VALUES ('cancellation_trigger');
INSERT INTO _Variables(name, int_value)
SELECT 'lecture', count(*)
FROM lecture_booking
WHERE lecture_id = OLD.id;
DELETE FROM lecture_booking
WHERE lecture_id = OLD.id;
DELETE FROM waiting_list
WHERE lecture_id = OLD.id;
INSERT INTO _Variables(name, int_value) VALUES ('lid', (SELECT lid FROM stats_lecture WHERE lecture_id = OLD.id));
UPDATE stats_usage
SET booking = 0, cancellations = cancellations + (SELECT int_value FROM _Variables WHERE name = 'lecture'), attendance = 0
WHERE lid = (SELECT int_value FROM _Variables WHERE name = 'lid');
DELETE FROM _Trigger
WHERE name = 'cancellation_trigger';
END;`;
exports.deleteLecture_trigger = `CREATE TRIGGER IF NOT EXISTS deleteLecture BEFORE DELETE ON lecture
BEGIN
DELETE FROM _Variables;
INSERT INTO _Trigger(name) VALUES ('cancellation_trigger');
DELETE FROM lecture_booking
WHERE lecture_id = OLD.id;
DELETE FROM waiting_list
WHERE lecture_id = OLD.id;
INSERT INTO _Variables(name,int_value) VALUES('lid', (SELECT lid FROM stats_lecture WHERE lecture_id = OLD.id));
DELETE FROM stats_usage
WHERE lid = (SELECT int_value FROM _Variables WHERE name = 'lid');
DELETE FROM stats_lecture
WHERE lecture_id = OLD.id;
DELETE FROM _Trigger
WHERE name = 'cancellation_trigger';
END;`;
exports.attendance_trigger = `CREATE TRIGGER IF NOT EXISTS attendance AFTER UPDATE OF status ON lecture_booking
WHEN (NEW.status = 'present' AND OLD.status IS NOT 'present' )
OR (NEW.status = 'absent' AND OLD.status IS NOT 'absent')
BEGIN
DELETE FROM _Variables;
INSERT INTO _Variables(name, int_value) VALUES ('lid', (SELECT lid FROM stats_lecture WHERE lecture_id = OLD.lecture_id));
UPDATE stats_usage
SET attendance = attendance + 1
WHERE lid = (SELECT int_value FROM _Variables WHERE name = 'lid')
AND NEW.status = 'present';
UPDATE stats_usage
SET attendance = attendance -1
WHERE lid = (SELECT int_value FROM _Variables WHERE name = 'lid')
AND NEW.status = 'absent';
END;`;
|
const restaurant = {
name: "Cafe Mocha",
location: "Pokhara, Kathmandu, Biratnagar, Nepalgunj",
categories: ["Italian", "Chinese Cuisine", "Indian", "Organic"],
starterMenu: ["Chicken Lollipop", "Salad", "Bread", "Manchurian"],
mainMenu: ["Pizza", "Pasta", "Risotto"],
openingHours: {
Sun: {
open: 12,
close: 22,
},
Mon: {
open: 11,
close: 23,
},
Tue: {
open: 10,
close: 20,
},
},
order: function (starterIndex, mainIndex) {
return [this.starterMenu[starterIndex], this.mainMenu[mainIndex]];
},
orderDelivery: function ({
starterIndex = 1,
mainIndex = 0,
time = "20.00",
address = "Jaleshwar TownPlanning",
}) {
console.log(`Order recieved! ${this.starterMenu[starterIndex]} and ${this.mainMenu[mainIndex]}
will be delivered to ${address} at ${time}`);
},
//So lets add here another method now. And lets say we want a method to order just pasta. And the
//pasta always needs to have exactly three ingredients.
orderPasta: function (ing1, ing2, ing3) {
console.log(`Here is your delicious pasta with ${ing1}, ${ing2}, ${ing3}`);
//So now lets call this function.
//Now what i want to do here is to actually get these ingredients from a prompt window.
},
};
//Let's now talk about the new way of looping over the arrays.
//And that is the for-of loop.
//And let's say we wanted to loop over our entire menu here which includes both the starterMenu and mainMenu.
//Here we basically at first merge both the arrays which is starterMenu and mainMenu into a new array
//called as menu.
const menu = [...restaurant.starterMenu, ...restaurant.mainMenu];
//After merging both the arrays into menu we create one variable called item inside the for loop.
//Here the item indicates all the individual element of both the arrays.
//Then we select all the item of both the arrays at once by writing const item of menu.
for (const item of menu) console.log(item);
//But if we want the index along with the element of both the arrays then we can also do that.
//But for that we have to use entries methodlike this.
for (const item of menu.entries()) {
console.log(item);
}
console.log([...menu.entries()]);
|
/*
* The requestAnimationFrame loop
*
* This tries to run once per frame in the UI thread. Calling
* `this.onNextTick()` will queue a function to be run on
* the next frame. If, while dequeuing callbacks, we exceed
* a prespecified "threshold", we'll stop and continue on the
* next frame, to make sure we don't fall behind / jitter.
* We log.debug every time we pass the threshold (DONE) and every
* time we miss a frame (TODO).
*
*/
import SinglyLinkedList from '../util/SinglyLinkedList';
import log from '../util/log';
class FrameLoop {
constructor(options) {
if (!options) options = {};
this._FPS = 60;
this._FRAME_DURATION = 1000 / this._FPS;
this._THRESHOLD = this._FRAME_DURATION * 0.6; // browser overhead
this._queue = SinglyLinkedList(); // for upcoming tick
this._nextQueue = SinglyLinkedList(); // for tick after that
this._started = false;
this._inTick = false; // true during step()
this._exceedCount = 0;
this._currentFrame = 0;
// Believe it or not, bind() isn't performant (see CONTRIBUTING.md)
var self = this;
this.stepAndQueue = function() {
self.step();
if (self.onFinish) self.onFinish();
self.queueFrame();
}
}
queueFrame() {
window.setTimeout(this.stepAndQueue,
this._FRAME_DURATION - (this._lastFrameEnd - this._lastFrameStart));
}
start() {
if (this._started)
throw new Error("FrameLoop already started", this);
this._started = false;
this.queueFrame();
}
/**
* True is we're below the threshold.
*/
timeOk() {
return performance.now() - this._lastFrameStart < this._THRESHOLD;
}
/**
* For devel use. Block the thread totally for at least `time` ms.
*/
blockFor(time) {
var now = performance.now();
while (performance.now() - now < time);
}
/**
* Queues a function, context and data to be called on the next tick. It
* will also be called with the DOMHighResTimeStamp for that frame.
*
* @param {function} - the function (callback) to be called - avoid anonymous
* @param {object} - the context (`this`) for that function
* @param {object} - data the function should be called with
*/
onNextTick(func, context, data) {
// re-use `arguments` to avoid creation of new array
(this._inTick ? this._nextQueue : this._queue).push(arguments);
}
step(timestamp) {
var current, data, completed = true;
this._lastFrameStart = timestamp || performance.now();
var finishThreshold = this._lastFrameStart + this._THRESHOLD;
this._currentFrame++;
// Short circuit if the queue is empty
if (this._queue.head) {
// so if any functions call onNextTick, we'll queue them in nextQueue
this._inTick = true;
/*
* KEEP BAREBONES. This is the code that is run more than anything else
*/
for (current = this._queue.head; current; current = current.next) {
// callback.call(context, data, timestamp);
current.data[0].call(current.data[1], current.data[2],
this._lastFrameStart);
// If we exceeded the threshold and didn't complete the queue
if ( performance.now() > finishThreshold && current.next ) {
if (++this._exceedCount === 30)
log.debug('Didn\'t complete all updates for 30 frames in a row!');
this._queue.recycleUntil(current);
completed = false;
break;
}
}
if (completed) {
if (this._exceedCount) {
log.debug("Didn't complete updates for " + this._exceedCount + ' consecutive frame(s) until now');
this._exceedCount = 0;
}
this._queue.recycle();
this._queue = this._nextQueue;
this._nextQueue = SinglyLinkedList();
}
this._inTick = false;
}
this._lastFrameEnd = performance.now();
}
}
export default FrameLoop; |
import './App.css';
const commitments = ['Aprender React', 'Aprender Redux', 'Se esforçar', 'Conseguir emprego']
const task = (value) => {
return (
value.map((task) => {
return <li>{task}</li>
} )
);
}
function App() {
return (
task(commitments)
);
}
export default App;
|
import React from "react";
import { Link } from "react-router-dom";
import styles from "../styles/intro.module.css";
const Home = () => {
return (
<>
<div className={styles.header}>
<div className={styles.logo}>
<i
style={{
paddingLeft: "0.5rem",
paddingRight: "0.5rem",
fontSize: "3.5rem",
}}
className="fas fa-address-book"
></i>
Digital Phone book
</div>
<div className={styles.btn_container}>
<button className={styles.login_btn}>
<Link to="/login">Login</Link>
</button>
<button className={styles.signup_btn}>
<Link to="/signup">Sign Up</Link>
</button>
</div>
</div>
<div className={styles.main_content}>
<span className={styles.text}>Your digital phonebook</span>
<img className={styles.main_img} src="" alt="" />
<div className={styles.description}>
<div>Store all your contacts in one place and never loose them</div>
<div>
Create categories for different types of contacts like - work ,
family and many more...
</div>
<div>And search according to name , email , phone number</div>
</div>
<button className={styles.signup_now}>
<Link to="/signup">Sign Up</Link>
</button>
</div>
</>
);
};
export default Home;
|
import React from 'react'
import {
View,
Text,
} from 'react-native'
import { createStackNavigator } from '@react-navigation/stack'
import { CONTACT_CREATE, CONTACT_INFO, CONTACT_LIST, SETTINGS } from '../constants/routeName'
import Contacts from '../screens/Contacts'
import ContactInfo from '../screens/ContactInfo'
import ContactCreate from '../screens/ContactCreate'
import Settings from '../screens/Settings'
const HomeNavigator = () => {
const HomeStack = createStackNavigator()
return (
<HomeStack.Navigator initialRouteName={CONTACT_LIST}>
<HomeStack.Screen name={CONTACT_LIST} component={Contacts} />
<HomeStack.Screen name={CONTACT_INFO} component={ContactInfo} />
<HomeStack.Screen name={CONTACT_CREATE} component={ContactCreate} />
<HomeStack.Screen name={SETTINGS} component={Settings} />
</HomeStack.Navigator>
);
}
export default HomeNavigator
|
var express = require('express');
var router = express.Router();
router.post('/admin/login', function(req, res){
res.redirect('/admindashboard');
});
router.get('/admindashboard', function(req, res){
res.sendFile('/pages/admin/index.html', {root: './'});
});
module.exports = router; |
import Vue from 'vue'
import Todo from './components/todos.vue'
import mui from 'muife'
new Vue({
el: '#app',
render: h => h(Todo)
}) |
/* eslint-disable no-const-assign */
/* eslint-disable require-jsdoc */
/* eslint-disable no-invalid-this */
/* eslint-disable no-unused-vars */
/* eslint-disable no-undef */
const swiper = new Swiper('.swiper', {
// Optional parameters
direction: 'vertical',
loop: true,
spaceBetween: 30,
effect: 'fade',
// If we need pagination
pagination: {
el: '.swiper-pagination',
type: 'custom',
renderCustom: function(swiper, current, total) {
return '0' + current + ' — ' + '0' + total;
},
},
// Navigation arrows
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
});
// question
const items = document.querySelectorAll('.question-choice');
function toggleAccordion() {
const itemToggle = this.getAttribute('aria-expanded');
for (let i = 0; i < items.length; i++) {
items[i].setAttribute('aria-expanded', 'false');
}
if (itemToggle == 'false') {
this.setAttribute('aria-expanded', 'true');
}
}
items.forEach((item) => item.addEventListener('click', toggleAccordion));
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.