text
stringlengths
7
3.69M
const evJson = JSON.parse(process.env.npm_config_argv) const key = evJson.original[2] !=undefined ? evJson.original[2].slice(2) : '' var chalk = require('chalk'); const util = require('util'); const _exec = require('child_process').exec const exec = util.promisify(_exec); async function runExec(cmd1,cmd2) { console.log('Creating an optimized production build...'); const { error, stdout, stderr } = await exec(cmd1); console.log('----------'); if(error){ console.error(`exec error: ${error}`); process.exit(1) }else { console.log(chalk.green('Compiled successfully.')); _exec(cmd2,(error, stdout, stderr) => { if(error){ console.error(chalk.red(`exec error: ${error}`)); process.exit(1) }else { console.log(chalk.green('upload successfully!')); process.exit(0) } }) } } // `scp -i ${key} -r ./build/* ubuntu@54.222.161.75:/var/www/gemiimain/` // cp -r ./build/* ../gemiimain/ runExec(`sudo npm run build`,'sudo cp -r ./build/* ../gemiimain/')
import Axios from "axios"; import * as Constants from "../utils/constants"; import { headers } from "../utils/utils"; export async function FetchProducts() { try { var res = await Axios({ method: "get", headers: headers(), url: Constants.BASE_URL + "/products/get_products.php", validateStatus: () => true, }); // console.log(res); if (!res.data["error"]) { return res.data["data"]; } else { return null; } // return response.data // alert(res); } catch (error) { // console.log(res); return null; } } export async function AddProducts(data) { try { let response = await Axios.post( Constants.BASE_URL + "/products/add_product.php", { product_name: data.product_name, product_price: data.product_price, size_id: data.size_id, category_id: data.category_id, }, { headers: headers(), } ); console.log(response.data); return response.data; } catch (error) { console.log(error.response.data); return error.response.data; } } export async function UpdateProduct(data) { try { var res = await Axios({ method: 'post', headers: headers(), url: Constants.BASE_URL + "/products/update_product.php", validateStatus: () => true, data: { product_id: data.product_id, product_name: data.product_name, product_price: data.product_price, category_id: data.category_id } }) console.log('API: ', res) } catch (error) { console.log('API Error: ', error.res.data) } }
app.factory('restServ',function($resource,constServ){ var justElem = {method: 'GET'}; var readAllElem = {method: 'GET', isArray: true}; var readAllWithElem = {method: 'GET', isArray: true, params: {id: '@id'}}; var readElem = {method: 'GET', params: {id: '@id'}}; var updateElem = {method: 'PUT', params: {id: '@id'}}; var updateAllElem = {method: 'PUT', isArray: true, params: {id: '@id'}}; var deleteElem = {method: 'DELETE', params: {id: '@id'}}; var createElem = {method: 'POST'}; return { get: function(crud){ var rtn = {}; if((typeof crud === 'object') && (crud !== null)){rtn = crud;} else { var length = crud.length; for(var i = 0;i < length;i++){ switch(crud.charAt(i)){ case 'x': rtn.just = justElem; break; case 'c': rtn.create = createElem; break; case 'r': rtn.get = readElem; break; case 'u': rtn.update = updateElem; break; case 'd': rtn.delete = deleteElem; break; case 'a': rtn.getAll = readAllElem; break; case 'w': rtn.getWith = readAllWithElem; break; case 'v': rtn.updateAll = updateAllElem; break; default: rtn = crud; } } } return rtn; }, getCrud: function(url,crud,bool){ var useUrl = constServ.getUrl()+url; if(bool) useUrl = url; return $resource(useUrl,{},this.get(crud)); } }; });
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; //import App from './App'; //import Registration from './registraion'; //import Example from './methods'; //import Table from './table'; import * as serviceWorker from './serviceWorker'; //import { BrowserRouter as Router, Route, Switch , IndexRoute, hashHistory, browserHistory } from 'react-router-dom'; //import indexrouter from './indexroute'; import Weather from './weatherdata/weather'; //ReactDOM.render(<App />, document.getElementById('root')); /*ReactDOM.render( <Router> <Switch> { indexrouter.map((props,key)=>{ return( <Route path={props.path} key={key} component={props.component}/> ); })} </Switch> </Router>, document.getElementById('root') );*/ ReactDOM.render(<Weather />, document.getElementById('root')); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: http://bit.ly/CRA-PWA serviceWorker.unregister();
const path = require("path"); const { create } = require("babel-test"); const { fixtures } = create({ plugins: [["macros"]], }); fixtures("classnames", path.join(__dirname, "__fixtures__"));
let lastMod = document.lastModified; // Display the last modified document.getElementById('last-mod').textContent = lastMod;
import React from "react"; import LoaderButton from "../../components/LoaderButton/LoaderButton"; import "./Home.css"; const Home = () => { return ( <div className="Home"> <div className="lander"> <h1>SRover</h1> <p className="text-muted">SRover - A Mars Rover app</p> <p> <LoaderButton size="lg" href="/rovers" variant="outline-info"> Check out the Rovers </LoaderButton> </p> </div> </div> ); }; export default Home;
// JavaScript - Node v8.1.3 Test.expect(isReallyNaN(37) === false); Test.expect(isReallyNaN('37') === false); Test.expect(isReallyNaN(NaN) === true); Test.expect(isReallyNaN(undefined) === false);
const Sequelize = require('sequelize'); module.exports = function(sequelize, DataTypes) { return sequelize.define('SalesShipment', { entity_id: { autoIncrement: true, type: DataTypes.INTEGER.UNSIGNED, allowNull: false, primaryKey: true, comment: "Entity ID" }, store_id: { type: DataTypes.SMALLINT.UNSIGNED, allowNull: true, comment: "Store ID", references: { model: 'store', key: 'store_id' } }, total_weight: { type: DataTypes.DECIMAL(12,4), allowNull: true, comment: "Total Weight" }, total_qty: { type: DataTypes.DECIMAL(12,4), allowNull: true, comment: "Total Qty" }, email_sent: { type: DataTypes.SMALLINT.UNSIGNED, allowNull: true, comment: "Email Sent" }, send_email: { type: DataTypes.SMALLINT.UNSIGNED, allowNull: true, comment: "Send Email" }, order_id: { type: DataTypes.INTEGER.UNSIGNED, allowNull: false, comment: "Order ID", references: { model: 'sales_order', key: 'entity_id' } }, customer_id: { type: DataTypes.INTEGER, allowNull: true, comment: "Customer ID" }, shipping_address_id: { type: DataTypes.INTEGER, allowNull: true, comment: "Shipping Address ID" }, billing_address_id: { type: DataTypes.INTEGER, allowNull: true, comment: "Billing Address ID" }, shipment_status: { type: DataTypes.INTEGER, allowNull: true, comment: "Shipment Status" }, increment_id: { type: DataTypes.STRING(50), allowNull: true, comment: "Increment ID" }, created_at: { type: DataTypes.DATE, allowNull: false, defaultValue: Sequelize.Sequelize.fn('current_timestamp'), comment: "Created At" }, updated_at: { type: DataTypes.DATE, allowNull: false, defaultValue: Sequelize.Sequelize.fn('current_timestamp'), comment: "Updated At" }, packages: { type: DataTypes.TEXT, allowNull: true, comment: "Packed Products in Packages" }, shipping_label: { type: DataTypes.BLOB, allowNull: true, comment: "Shipping Label Content" }, customer_note: { type: DataTypes.TEXT, allowNull: true, comment: "Customer Note" }, customer_note_notify: { type: DataTypes.SMALLINT.UNSIGNED, allowNull: true, comment: "Customer Note Notify" } }, { sequelize, tableName: 'sales_shipment', timestamps: false, indexes: [ { name: "PRIMARY", unique: true, using: "BTREE", fields: [ { name: "entity_id" }, ] }, { name: "SALES_SHIPMENT_INCREMENT_ID_STORE_ID", unique: true, using: "BTREE", fields: [ { name: "increment_id" }, { name: "store_id" }, ] }, { name: "SALES_SHIPMENT_STORE_ID", using: "BTREE", fields: [ { name: "store_id" }, ] }, { name: "SALES_SHIPMENT_TOTAL_QTY", using: "BTREE", fields: [ { name: "total_qty" }, ] }, { name: "SALES_SHIPMENT_ORDER_ID", using: "BTREE", fields: [ { name: "order_id" }, ] }, { name: "SALES_SHIPMENT_CREATED_AT", using: "BTREE", fields: [ { name: "created_at" }, ] }, { name: "SALES_SHIPMENT_UPDATED_AT", using: "BTREE", fields: [ { name: "updated_at" }, ] }, { name: "SALES_SHIPMENT_SEND_EMAIL", using: "BTREE", fields: [ { name: "send_email" }, ] }, { name: "SALES_SHIPMENT_EMAIL_SENT", using: "BTREE", fields: [ { name: "email_sent" }, ] }, ] }); };
'use strict'; var _commander = require('commander'); var _commander2 = _interopRequireDefault(_commander); var _package = require('../package.json'); var _package2 = _interopRequireDefault(_package); var _commands = require('../lib/commands'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } // Parse the arguments var version = _package2.default.version; var author = _package2.default.author; var description = _package2.default.description; // Setup the program _commander2.default.version(version); _commander2.default.command('login').description('Logs in to the auto-deploy-server').option('-u --username <username>', 'Username on auto-deploy-server').option('-p --password <password>', 'Password on auto-deploy-server').option('-t --token <token>', 'API Token on auto-deploy-server').action(_commands.login); _commander2.default.command('init').description('Initialises the target server(s) for automated deployment').action(_commands.init); _commander2.default.command('deploy [env]').description('Deploys the project to the remote server for the given environment').action(_commands.deploy); _commander2.default.parse(process.argv);
const ServerErrors = require('../../helpers/ServerErrors'); const { Comment } = require('../../schemas/Comment'); const { YouBike } = require('../../schemas/YouBike'); const ClientErrors = require('../../helpers/ClientErrors'); async function model(args) { try { await findSite(args.site_id); const result = await createComment(args); return Promise.resolve(result); } catch (err) { return Promise.reject(err); } } // 搜尋增加評論的站場是否存在 async function findSite(site_id) { try { const result = await YouBike.findOne({ where: { id: site_id }, raw: true }); if (!result) return Promise.reject(new ClientErrors.SiteNotFound()); return Promise.resolve(); } catch (err) { return Promise.reject(new ServerErrors.MySQLError(err.stack)); } }; // 增加評論 async function createComment(args) { try { const result = await Comment.create({ site_id: args.site_id, uid: args.user.id, comment: args.comment }); return Promise.resolve({ comment: { id: result.id, comment: args.comment } }); } catch (err) { return Promise.reject(new ServerErrors.MySQLError(err.stack)); } } module.exports = model;
app.controller('CalendarController', [ '$scope', '$rootScope', 'EventsService', 'localStorageService', function ($scope, $rootScope, EventsService, localStorageService) { $scope.calendars = []; $scope.events = []; $scope.hasEvents = false; $scope.calendarEvents = []; $scope.multiDayEvents = []; var d = new Date(); $scope.yesterday = new Date(d.setDate(d.getDate() - 1)); $scope.init = function init (calendars) { $scope.calendars = calendars; setDefaultCalendar(); }; $scope.savePreferences = function savePreferences (cb) { var temp = []; for(var i = 0; i < $scope.calendars.length; i++) { if($scope.calendars[i].selected == true) { temp.push($scope.calendars[i]); } } localStorageService.set( 'cal', JSON.stringify(angular.copy(temp))); fetchEvents(); if(cb) { cb(); } }; $scope.cancel = function cancel (callback) { resetCalendarsStatus(); setDefaultCalendarsStatus(getSavedCalendars()); if(callback) { callback(); } }; $scope.select = function (calendar) { checkUncheckCalendar(calendar); }; $scope.$on('cardbox.close', function () { resetCalendarsStatus(); setDefaultCalendarsStatus(getSavedCalendars()); }); $scope.$watchCollection('calendarEvents', function () { // $scope.events = []; // for( var i = 0; i < $scope.calendarEvents.length; i++) { // // for (var a in $scope.calendarEvents[i]) { // $scope.events.push($scope.calendarEvents[i][a]); // } // } // if($scope.events.length > 0) { // $scope.hasEvents = true; // } // $scope.events.sort(function (a, b) { // a = new Date(a.date); // b = new Date(b.date); // return a < b ? -1 : a > b ? 1 : 0; // }); var tempEvents = []; for(var i in $scope.calendarEvents) { var exist = false; for(var a in tempEvents) { if(tempEvents[a].date.toString() == $scope.calendarEvents[i].date.toString()) { exist = true; for(var k in $scope.calendarEvents[i].events) { var evtExist = false; for(var z in tempEvents[a].events) { if(tempEvents[a].events[z].id == $scope.calendarEvents[i].events[k].id) { evtExist = true; break; } } if(evtExist == false) { tempEvents[a].events.push($scope.calendarEvents[i].events[k]); } } break; } } if(exist == false) { tempEvents.push($scope.calendarEvents[i]); } } // // console.log(tempEvents); if($scope.calendarEvents.length) { $scope.hasEvents = true; } // $scope.calendarEvents = tempEvents; }); function setDefaultCalendar() { var saved = getSavedCalendars(); if(!saved || saved == null) { $scope.calendars[0].selected = true; var temp = []; temp.push($scope.calendars[0]); localStorageService.set( 'cal', JSON.stringify(angular.copy(temp))); } else { setDefaultCalendarsStatus(saved); } fetchEvents(); } function checkUncheckCalendar(calendar) { for(var i =0; i < $scope.calendars.length; i++) { if($scope.calendars[i].id == calendar.id) { // First time loaded if(!$scope.calendars[i].selected || $scope.calendars[i].selected == 'undefined') { $scope.calendars[i].selected = true; } else { // if user make changed $scope.calendars[i].selected = !$scope.calendars[i].selected; } } } } function getSavedCalendars() { return JSON.parse(localStorageService.get('cal')); } function setDefaultCalendarsStatus(calendars) { for(var i =0; i < calendars.length; i++) { setDefaultCalendarStatus(calendars[i]); } } function setDefaultCalendarStatus(calendar) { for( var i = 0; i < $scope.calendars.length; i++) { if(calendar.id == $scope.calendars[i].id) { $scope.calendars[i].selected = calendar.selected || false; break; } } } function resetCalendarsStatus() { for (var i = 0; i <$scope.calendars.length; i++) { $scope.calendars[i].selected = false; } } function fetchEvents () { $scope.calendarEvents = []; $scope.hasEvents = false; for (var i = 0; i < $scope.calendars.length; i++) { if($scope.calendars[i].selected == true) { EventsService.events($scope.calendars[i].id) .then(function (res) { $scope.me = res.me; $scope.multiDayEvents = []; for(var c in res.events) { var evt = transformDates(res.events[c]); evt = removeDeclinedEvents(evt); checkMultiDayEvent(evt); // evt.events = onlyHourlyEvents(evt); // if(evt.events.length > 0) { // $scope.calendarEvents.push(evt); // } $scope.calendarEvents.push(evt); } addMultiDayEvents(); }); } } } function removeDeclinedEvents(evt) { for(var i in evt.events){ if(removeEvent(evt.events[i].attendees)) { evt.events.splice(i, 1); } } return evt; } function removeEvent(att) { for(var i in att) { if(att[i].email == $scope.me && att[i].responseStatus == 'declined') { return true } } return false; } function onlyHourlyEvents(evt) { var result = []; for (var i in evt.events){ if(evt.events[i].allDay) { continue; } else { result.push(evt.events[i]); } } return result; } function checkMultiDayEvent(evt) { for(var i in evt.events) { if(evt.events[i].allDay === true) { var startDate = new Date(evt.events[i].start.date); var endDate = new Date(new Date(evt.events[i].end.date)); if(startDate < endDate) { $scope.multiDayEvents.push(evt.events[i]); } } } } function transformDates(evt) { evt.date = new Date(evt.date); for(var i in evt.events) { var startDate = new Date(evt.events[i].start.date); var endDate = new Date(evt.events[i].end.date); endDate.setDate(endDate.getDate() - 1); evt.events[i].start.date = startDate; evt.events[i].end.date = endDate; } return evt; } function addMultiDayEvents() { for (var i in $scope.multiDayEvents) { var endDate = $scope.multiDayEvents[i].end.date; var startDate = $scope.multiDayEvents[i].start.date; addNewEventDay(startDate, endDate); pushEvent($scope.multiDayEvents[i]); } } function addNewEventDay(startDate, endDate) { var firstDay= new Date(startDate); while(endDate > firstDay) { var day = { date: new Date(firstDay.setDate(firstDay.getDate() + 1)), events: [] }; $scope.calendarEvents.push(day); } } function pushEvent(evt) { for(var i in $scope.calendarEvents) { var exist = false; for(var a in $scope.calendarEvents[i].events) { if($scope.calendarEvents[i].events[a].id == evt.id) { exist = true; break; } } var evtStartDate = new Date(evt.start.date); var evtEndDate = new Date(evt.end.date); var calDate = new Date($scope.calendarEvents[i].date); if(exist == false) { if(calDate >= evtStartDate && calDate <= evtEndDate) { $scope.calendarEvents[i].events.push(evt); } } } } }]);
import sinon from 'sinon'; import ProjectDbService from '../../../../api/services/workspace/project.db.service'; import * as db from '../../../../utils/dbUtils'; import * as crypt from '../../../../utils/encryptionUtils'; const { assert } = sinon; describe('Project DB Service', () => { let executeQueryStub; let guidStub; afterEach(() => { executeQueryStub && executeQueryStub.restore(); guidStub && guidStub.restore(); }); describe('getProject', () => { it('should return project', async () => { const service = new ProjectDbService(); executeQueryStub = sinon.stub(db, 'executeQuery').resolves({ recordset: [{ project_id: 'project_id', project_name: 'project_name', workspace_id: 'workspace_id', config: '{}', items: '{}' }] }); const result = await service.getProject('project_id'); assert.match(result, { projectId: 'project_id', projectName: 'project_name', workspaceId: 'workspace_id', config: {}, items: {} }); assert.match(executeQueryStub.callCount, 1); assert.match(executeQueryStub.args[0][1][0].value, 'project_id'); }); it('should return null if no project', async () => { const service = new ProjectDbService(); executeQueryStub = sinon.stub(db, 'executeQuery').resolves({ recordset: [] }); const result = await service.getProject('project_id'); assert.match(result, null); assert.match(executeQueryStub.callCount, 1); assert.match(executeQueryStub.args[0][1][0].value, 'project_id'); }); }); describe('updateProject', () => { it('should update project and return', async () => { const service = new ProjectDbService(); const project = { projectId: 'project_id', projectName: 'updated_project_name', workspaceId: 'workspace_id', config: { prop2: 'prop_1' }, items: { prop2: 'prop_2'} }; executeQueryStub = sinon.stub(db, 'executeQuery'); executeQueryStub.onCall(0).resolves(); executeQueryStub.onCall(1).resolves({ recordset: [{ project_id: 'project_id', project_name: 'updated_project_name', workspace_id: 'workspace_id', config: JSON.stringify(project.config), items: JSON.stringify(project.items) }] }); const result = await service.updateProject('workspace_id', 'project_id', project); assert.match(result, project); assert.match(executeQueryStub.callCount, 2); assert.match(executeQueryStub.args[0][1][0].value, 'workspace_id'); assert.match(executeQueryStub.args[0][1][1].value, 'project_id'); assert.match(executeQueryStub.args[0][1][2].value, 'updated_project_name'); assert.match(executeQueryStub.args[0][1][3].value, JSON.stringify(project.config)); assert.match(executeQueryStub.args[0][1][4].value, JSON.stringify(project.items)); assert.match(executeQueryStub.args[1][1][0].value, 'project_id'); }); }); describe('initiateProject', () => { it('should initiate project without default and return', async () => { const service = new ProjectDbService(); const project = { projectId: 'project_id', projectName: 'project_name', workspaceId: 'workspace_id', config: {}, items: {} }; executeQueryStub = sinon.stub(db, 'executeQuery'); executeQueryStub.onCall(0).resolves(); executeQueryStub.onCall(1).resolves({ recordset: [{ project_id: 'project_id', project_name: 'project_name', workspace_id: 'workspace_id', config: JSON.stringify(project.config), items: JSON.stringify(project.items) }] }); guidStub = sinon.stub(crypt, 'guid').returns('project_id'); const result = await service.initiateProject('workspace_id'); assert.match(result, project); assert.match(executeQueryStub.callCount, 2); assert.match(executeQueryStub.args[0][1][0].value, 'workspace_id'); assert.match(executeQueryStub.args[0][1][1].value, 'project_id'); assert.match(executeQueryStub.args[0][1][2].value, 'Untitled Project'); assert.match(executeQueryStub.args[0][1][3].value, JSON.stringify(project.config)); assert.match(executeQueryStub.args[0][1][4].value, JSON.stringify(project.items)); assert.match(executeQueryStub.args[1][1][0].value, 'project_id'); assert.match(guidStub.callCount, 1); }); it('should initiate project with default and return', async () => { const service = new ProjectDbService(); const project = { projectId: 'project_id', projectName: 'new-project-name', workspaceId: 'workspace_id', config: {}, items: {} }; executeQueryStub = sinon.stub(db, 'executeQuery'); executeQueryStub.onCall(0).resolves(); executeQueryStub.onCall(1).resolves({ recordset: [{ project_id: 'project_id', project_name: 'new-project-name', workspace_id: 'workspace_id', config: JSON.stringify(project.config), items: JSON.stringify(project.items) }] }); guidStub = sinon.stub(crypt, 'guid').returns('project_id'); const result = await service.initiateProject('workspace_id', 'new-project-name'); assert.match(result, project); assert.match(executeQueryStub.callCount, 2); assert.match(executeQueryStub.args[0][1][0].value, 'workspace_id'); assert.match(executeQueryStub.args[0][1][1].value, 'project_id'); assert.match(executeQueryStub.args[0][1][2].value, 'new-project-name'); assert.match(executeQueryStub.args[0][1][3].value, JSON.stringify(project.config)); assert.match(executeQueryStub.args[0][1][4].value, JSON.stringify(project.items)); assert.match(executeQueryStub.args[1][1][0].value, 'project_id'); assert.match(guidStub.callCount, 1); }); }); });
import keyMirror from 'keymirror'; export default keyMirror({ ON_CHANGE_INPUT: null, FORM_SUBMITTED: null, ON_REMOVE: null, ON_ROW_INPUT_EDIT: null, });
import React from 'react'; import './App.css'; import Canvas from './components/Canvas'; import BoardPoint from './components/BoardPoint'; class App extends React.Component { constructor(props){ super(props); this.state = { points : 0, } } pointsHandler = (points) =>{ this.setState({ points:points, }) } render(){ return( <div className="container"> <BoardPoint points={this.state.points}/> <Canvas pointsHandler={this.pointsHandler}/> </div> ); } } export default App;
import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import Helmet from 'react-helmet'; import * as fetchPostArticle from '../actions/fetchPostArticle'; class PostArticle extends Component { static propTypes = { dispatch: PropTypes.func.isRequired, params: PropTypes.object.isRequired, postArticle: PropTypes.object.isRequired, } static readyOnActions = (dispatch, params) => Promise.all([ dispatch(fetchPostArticle.fetchPostArticleIfNeeded(params.id)), ]) componentDidMount() { const { dispatch, params } = this.props; PostArticle.readyOnActions(dispatch, params); } getArticle = () => { const { postArticle, params } = this.props; return postArticle[params.id]; } displayArticle = () => { const postArticle = this.getArticle(); if (!postArticle || postArticle.readyState === fetchPostArticle.POSTARTICLE_FETCHING) { return <p>Loading...</p>; } if (postArticle.readyState === fetchPostArticle.POSTARTICLE_FETCH_FAILED) { return <p>Failed to fetch article</p>; } return ( <div> <h3>{postArticle.article.title}</h3> <p>{postArticle.article.body}</p> </div> ); } render() { return ( <div> <Helmet title="Article" /> {this.displayArticle()} </div> ); } } function mapStateToProps({ postArticle }) { return { postArticle, }; } export default connect(mapStateToProps)(PostArticle);
//import connection const connection = require('../connection'); const getMentorsData = callback => { const sql = 'select * from mentors;'; connection.query(sql, (err, result) => { if (err) { callback(err); } else { callback(result.rows); } }); }; module.exports = getMentorsData;
import router from 'fosjsrouting'; import translator from 'bazinga-translator'; import { Controller } from 'stimulus'; import { fetch, ok } from '../lib/http'; import { formatNumber } from '../lib/intl'; export default class extends Controller { static classes = ['subscribe', 'unsubscribe']; static targets = ['label', 'subscribers']; static values = { errorValue: Boolean, forum: String, loading: Boolean, subscribers: Number, subscribed: Boolean, }; connect() { this.formEl = this.element.closest('.subscribe-form'); } async subscribe(event) { if (this.errorValue) { return; } event.preventDefault(); const url = router.generate(this.subscribedValue ? 'unsubscribe' : 'subscribe', { forum_name: this.forumValue, _format: 'json', }); try { this.loadingValue = true; const response = await fetch(url, { method: 'POST', body: new FormData(this.formEl), }); await ok(response); this.subscribedValue = !this.subscribedValue; this.subscribersValue += (this.subscribedValue ? 1 : -1); } catch (e) { console && console.log(e); this.errorValue = true; this.element.click(); } finally { this.loadingValue = false; } } loadingValueChanged(loading) { this.element.blur(); this.element.disabled = loading; } subscribedValueChanged(subscribed) { if (subscribed) { this.element.classList.add(this.unsubscribeClass); this.element.classList.remove(this.subscribeClass); } else { this.element.classList.add(this.subscribeClass); this.element.classList.remove(this.unsubscribeClass); } this.labelTarget.innerText = subscribed ? translator.trans('action.unsubscribe') : translator.trans('action.subscribe'); } subscribersValueChanged(subscribers) { this.subscribersTarget.innerText = formatNumber(subscribers); this.subscribersTarget.setAttribute('aria-label', translator.transChoice( 'forum.subscriber_count', subscribers, { formatted_count: formatNumber(subscribers) } )); } }
import React, {PureComponent} from 'react'; import {Button, Grid, Form} from 'semantic-ui-react' import utlis from '../Utilities'; export default class Login extends PureComponent { constructor(props) { super(props); this.state = { email: '', password: '', submitting: false }; this.inputChanged = this.inputChanged.bind(this); this.submit = this.submit.bind(this); } submit() { this.setState({submitting: true}); this.props.api.login(this.state) .then(res => { this.setState({submitting: false}); this.props.updateStore({ user: res.data.user, access_token: res.data.access_token, signedIn: true }, true).then(() => { axios.defaults.headers.common['Authorization'] = 'Bearer ' + this.props.access_token; this.props.init(); this.props.history.replace('/'); toastr.success('You have logged in.'); }); }) .catch(err => { toastr.error('Invalid Email or Password!'); this.setState({submitting: false}); }); }; inputChanged(e, target) { this.state[target.name] = target.value; this.setState(this.state); } render() { return ( <Grid columns='equal'> <Grid.Column> </Grid.Column> <Grid.Column width={8}> <Form> <Form.Input required label='Email' type='email' name="email" onChange={this.inputChanged}/> <Form.Input required label='Password' type='password' name="password" onChange={this.inputChanged}/> <Button loading={this.state.submitting} primary type='submit' onClick={this.submit}>Submit</Button> </Form> </Grid.Column> <Grid.Column> </Grid.Column> </Grid> ); } }
import React from 'react'; import PropTypes from 'prop-types'; import {Redirect} from 'react-router-dom'; import {JobForYouWrapper} from '../../wrapper'; import {CollectionCard} from '../../component/collectionCard'; import {TagSidebar} from '../../component/tag'; import {FilterRow} from '../../component/filter'; import {languageHelper} from '../../../../tool/language-helper'; import {removeUrlSlashSuffix} from '../../../../tool/remove-url-slash-suffix'; import {MDBRow, MDBCol} from 'mdbreact'; import classes from '../../index.module.css'; class CampusReact extends React.Component { constructor(props) { super(props); // state this.state = {}; // i18n this.text = CampusReact.i18n[languageHelper()]; } render() { const pathname = removeUrlSlashSuffix(this.props.location.pathname); if (pathname) { return (<Redirect to={pathname} />); } return ( <div> <div className="cell-wall" style={{backgroundColor: '#F3F5F7'}} > <div className="cell-membrane" > <MDBRow style={{marginTop: '2vw'}}> <MDBCol className="px-0" size="10"> <FilterRow number={9} /> <JobForYouWrapper /> </MDBCol> <MDBCol className={classes.sidebar} size="2"> <CollectionCard number={99} /> <TagSidebar tags={['面试经历', '删库经历', '跑路经历']} /> </MDBCol> </MDBRow> </div> </div> </div> ); } } CampusReact.i18n = [ {}, {} ]; CampusReact.propTypes = { // self // React Router match: PropTypes.object.isRequired, history: PropTypes.object.isRequired, location: PropTypes.object.isRequired }; export const Campus = CampusReact;
import React from "react"; import {BrowserRouter as Router, Switch, Route} from "react-router-dom"; import Home from "./home/home"; import Login from "./login/login"; const AppRouter = ({ authService, loggedIn, firebaseAuth, fbDatabase, ImageInput, }) => { return ( // <Router> // <Switch> // {loggedIn ? ( // <> // <Route exact path='/'> // <Home // ImageInput={ImageInput} // firebaseAuth={firebaseAuth} // fbDatabase={fbDatabase} // /> // </Route> // </> // ) : ( // <Route exact path='/'> // <Login firebaseAuth={firebaseAuth} authService={authService}/> // </Route> // )} // </Switch> // </Router> <Router> <Switch> <Route exact path='/home'> <Home ImageInput={ImageInput} firebaseAuth={firebaseAuth} fbDatabase={fbDatabase} /> </Route> <Route exact path='/'> <Login firebaseAuth={firebaseAuth} authService={authService} /> </Route> </Switch> </Router> ); }; export default AppRouter;
const connection = require("./connection"); async function getNumberOfRecords(){ const sqlQuery2 = `select count(*) from all_words`; const result = await connection.query(sqlQuery2); return result } const orm = { countRecords: function(cb) { const sqlQuery = `select count(*) from all_words` connection.query(sqlQuery,function(err,data){ if(err) cb(err,null) cb(null,data) }) }, selectAllCategories: function(cb){ const sqlQuery = `select * from all_categories` connection.query(sqlQuery,function(err,data){ if(err) cb(err,null) cb(null,data) }) }, addNewCategory: function(categoryName,cb){ const sqlQuery = `insert into all_categories(name) value('${categoryName}')`; connection.query(sqlQuery,function(err,data){ if(err) cb(err,null) cb(null,data) }) }, selectAll: function(cb) { connection.query("select * from all_words",function(err,data){ if(err) cb(err,null) cb(null,data) }) }, insertOne: function(category,word_name,word_meaning,full_english_meaning,cb){ console.log(full_english_meaning); const sqlQuery1 = `insert into all_words(english_word,meaning,full_english_meaning,category) values('${word_name}',"${word_meaning}","${full_english_meaning}",'${category}')`; connection.query(sqlQuery1,function(err,data){ if(err) cb(err,null) cb(null,data) }) }, deleteOne: function(id,cb){ const sqlQuery = `delete from all_words where id=${id}` connection.query(sqlQuery,function(err,data){ if(err) cb(err,null) cb(null,data) }) }, deleteCategory: function(categoryName,cb){ const sqlQuery = `delete from all_categories where name='${categoryName}'`; connection.query(sqlQuery,function(err,data){ if(err) cb(err,null) cb(null,data) }) } }; module.exports = orm;
var circleData = { 4: { 'message': 'Light Shaking Expected', 'color': '#7efbdf' }, 5: { 'message': 'Moderate Shaking Expected', 'color': '#95f879' }, 6: { 'message': 'Strong Shaking Expected', 'color': '#f7f835' }, 7: { 'message': 'Very Strong Shaking Expected', 'color': '#fdca2c' }, 8: { 'message': 'Severe Shaking Expected', 'color': '#ff701f' }, 9: { 'message': 'Violent Shaking Expected', 'color': '#ec2516' }, 10: { 'message': 'Extreme Shaking Expected', 'color': '#c81e11' } }
// MENU ACTIONS function setActiveMenu(menu) { state.menus.active = menu; renderMenus(); } // HUD ACTIONS function setScore(score) { state.game.score = score; renderScoreHud(); } function incrementScore(inc) { if (isInGame()) { state.game.score = Math.max(state.game.score += inc, 0); renderScoreHud(); } } function setCubeCount(count) { state.game.cubeCount = count; renderScoreHud(); } function incrementCubeCount(inc) { if (isInGame()) { state.game.cubeCount += inc; renderScoreHud(); } } // GAME ACTIONS function setGameMode(mode) { state.game.mode = mode; } function resetGame() { resetAllTargets(); state.game.time = 0; resetAllCooldowns(); setScore(0); setCubeCount(0); spawnTime = getSpawnDelay(); } function pauseGame() { isInGame() && setActiveMenu(MENU.PAUSE); } function resumeGame() { isPaused() && setActiveMenu(null); } function endGame() { setActiveMenu(MENU.SCORE); handleCanvasPointerUp(); // 如果需要更新高分,在渲染分数菜单后。 state.game.score > getHighScore() && setHighScore(state.game.score); } // KEYBOARD SHORTCUTS window.addEventListener("keydown", ({ key }) => key === "p" && (isPaused() ? resumeGame() : pauseGame()));
(function(){ 'use strict'; angular.module('app') .controller('SubjectController', subjectController); subjectController.$inject = ['loginService', 'subjectService', '$uibModal','appConstants']; function subjectController(loginService, subjectService, $uibModal, appConstants) { var self = this; //variables self.list = {}; //variables and methods for search and Pagination's panel self.totalSubjects = 0; self.showSearch = true; self.textSearch = ""; self.begin = 0; self.currentPage = 1; self.subjectsPerPage = appConstants.numberOfEntitiesPerPage; self.numberToDisplaySubjectsOnPage = [5,10,15,20]; self.pageChanged = pageChanged; //methods self.getSubjects = getSubjects; self.deleteSubject = deleteSubject; self.showAddSubjectForm = showAddSubjectForm; self.showEditSubjectForm = showEditSubjectForm; activate(); function activate() { isLogged(); getSubjects().then(pageChanged); } function isLogged() { loginService.isLogged(); } function getSubjects() { return subjectService.getSubjects().then(function(response) { self.list = response.data; self.totalSubjects = response.data.length; }); } function deleteSubject(subject_id) { var modalInstance = $uibModal.open({ templateUrl: 'app/modal/templates/confirm-delete-dialog.html', controller: 'modalController as modal', backdrop: true }); modalInstance.result.then(function() { subjectService.deleteSubject(subject_id).then(deleteSubjectComplete); }); } function deleteSubjectComplete(response) { if(response.data.response == "ok") { $uibModal.open({ templateUrl: 'app/modal/templates/confirm-dialog.html', controller: 'modalController as modal', backdrop: true }); activate(); } if(response.status === 400) { $uibModal.open({ templateUrl: 'app/modal/templates/forbidden-confirm-dialog.html', controller: 'modalController as modal', backdrop: true }); } } function pageChanged() { self.begin = ((self.currentPage - 1) * self.subjectsPerPage); self.showSearch = (self.currentPage == 1) ? true : false; self.textSearch = (self.currentPage == 1) ? self.textSearch : ""; } function showAddSubjectForm() { var modalInstance = $uibModal.open({ templateUrl: 'app/admin/subject/add-subject.html', controller: 'SubjectModalController as subjects', backdrop: false, resolve: { currentSubject: {} } }); modalInstance.result.then(function() { $uibModal.open({ templateUrl: 'app/modal/templates/confirm-dialog.html', controller: 'modalController as modal', backdrop: true }); activate(); }) } function showEditSubjectForm(subject) { var modalInstance = $uibModal.open({ templateUrl: 'app/admin/subject/edit-subject.html', controller: 'SubjectModalController as subjects', backdrop: false, resolve: { //the variable is needed to store data of current subject // to fill up the form of editing subject currentSubject: subject } }); modalInstance.result.then(function() { $uibModal.open({ templateUrl: 'app/modal/templates/confirm-dialog.html', controller: 'modalController as modal', backdrop: true }); activate(); }) } } }());
import React, { Component } from "react"; import scriptLoader from "react-async-script-loader"; import GoogleLogoutButton from "../../components/google_auth/GoogleLogoutButton"; class GoogleLogoutButtonContainer extends Component { constructor(props) { super(props); this.signOut = this.signOut.bind(this); } initGoogButton() { window.gapi.load("auth2", () => { this.auth2 = window.gapi.auth2.init({ client_id: "254472747355-6umtrkcedqn00tg7ec17l705ftttam0r.apps.googleusercontent.com", cookiepolicy: "single_host_origin" }); }); } componentDidMount() { const { isScriptLoaded, isScriptLoadSucceed } = this.props; if (isScriptLoaded && isScriptLoadSucceed) { this.initGoogButton(); } } componentDidUpdate(prevProps, prevState) { if (!prevProps.isScriptLoaded && this.props.isScriptLoaded) { if (this.props.isScriptLoadSucceed) { this.initGoogButton(); } } } signOut() { var auth2 = window.gapi.auth2.getAuthInstance(); auth2 .signOut() .then(() => { localStorage.removeItem("goog_avatar_url"); localStorage.removeItem("goog_name"); localStorage.removeItem("goog_email"); }) .then(() => this.props.googleLogoutAction()) .then(() => this.props.history.push("/")); } render() { return <GoogleLogoutButton signOut={this.signOut} />; } } export default scriptLoader(["https://apis.google.com/js/client:platform.js"])( GoogleLogoutButtonContainer );
import { Card, CardContent, Grid, Typography, Modal, Backdrop, Fade, } from "@material-ui/core"; import React from "react"; import classes from "./workSamplesTab.module.css"; import sampele from "../../../../../assets/img/home/sampel.png"; import { Star, DateRange, Close, Visibility } from "@material-ui/icons"; import modal from "../../../../../assets/img/home/modal.png"; const WorkSamplesTab = () => { const [open, setOpen] = React.useState(false); const handleOpen = () => { setOpen(true); }; const handleClose = () => { setOpen(false); }; return ( <React.Fragment> <Modal aria-labelledby="transition-modal-title" aria-describedby="transition-modal-description" className={classes.modal} open={open} onClose={handleClose} closeAfterTransition BackdropComponent={Backdrop} BackdropProps={{ timeout: 500, }} > <Fade in={open}> <div className={classes.paper}> <Grid container> <Grid xs={12} md={12} className={classes.close}> <Close onClick={handleClose} style={{ cursor: "pointer", alignSelf: "self-end", marginBottom: ".5rem", }} /> </Grid> <Grid item xs={12} md={4}> <div> <h3 id="transition-modal-title">طراحی پوستر مسابقات کشوری</h3> <p id="transition-modal-description"> react-transition-group animates me. react-transition-group animates me. react-transition-group animates me. </p> </div> <div style={{ fontSize: "13px", marginBottom: "1rem" }}> <span>نوع پروژه:</span> <span>خصوصی</span> </div> <div style={{ fontSize: "13px" }}> <span>لینک مشاهده:</span> <span> {" "} <a href="">https://parkjob.ir/profile/designila</a> </span> </div> <div className={classes.boxSvg}> <div> <DateRange /> <span>1400/02/06 - 1400/01/12</span> </div> <div> <Star /> <span>250</span> </div> <div> <Visibility /> <span>425</span> </div> </div> <h3>سایر نمونه کارها</h3> {[1, 2, 3, 4].map((item) => ( <div className={classes.sampel} key={item}> <div className={classes.imgSampel}> {/* <img src={} alt="sampel-pic" /> */} </div> <p className={classes.textSize}> طراحی ست اداری شرکت همیاران </p> </div> ))} </Grid> <Grid item xs={12} md={8} direction="column" style={{ padding: "1rem", borderRight: "2px solid #C4CAD0", display: "flex", justifyContent: "space-between", }} > {/* <Close className={classes.Close} onClick={handleClose} style={{ cursor: "pointer", alignSelf: "self-end", marginBottom: ".5rem", }} /> */} <div style={{ borderRadius: "1rem", width: "100%", height: "100%", }} > {" "} <img src={modal} alt="modal-pic" style={{ width: "100%", height: "100%", }} /> </div> <div className={classes.DivImgSamples} style={{ display: "flex", justifyContent: "space-between", margin: "1rem", alignItems: "center", }} > {[1, 2, 3, 4, 5].map((item) => ( <div className={classes.imgSampels} key={item}> {/* <img src="" alt="" /> */} </div> ))} </div> </Grid> </Grid> </div> </Fade> </Modal> <Grid item md={4} xs={12}> <Card className={classes.WorkSamplesCard} onClick={handleOpen}> <img src={sampele} alt="pic-sampel" /> <CardContent> <h4 className={classes.title}>title</h4> <Typography className={classes.content} style={{ padding: ".5rem" }} > content </Typography> <div className={classes.boxHeader}> <div> <span>250</span> <span> <Star /> </span> </div> <div> <span>1400/4/6</span> <span> <DateRange /> </span> </div> </div> </CardContent> </Card> </Grid> </React.Fragment> ); }; export default WorkSamplesTab;
(function(){ const ctx = $('#canvas')[0].getContext('2d'); const showDisconnect = function(server) { const disconnect = function() { clearInterval(window.takeReadingIntervalID); server.disconnect(); $("#disconnect").hide(); $("#connect").show(); }; $("#disconnect").click(disconnect); $("#connect").hide(); $("#disconnect").show(); }; const tagIdentifier = 0xaa80; const tempAServiceAddr = 'f000aa00-0451-4000-b000-000000000000'; const tempAValueAddr = 'f000aa01-0451-4000-b000-000000000000'; const tempBServiceAddr = 'f000bb00-0451-4000-b000-000000000000'; const tempBValueAddr = 'f000bb01-0451-4000-b000-000000000000'; var service; var chartDataA = []; var chartDataB = []; var myChart = new Chart(ctx, { type: 'line', data: { datasets: [{ label: 'Temperature A', fill: false, borderColor: 'red', data : chartDataA }, { label: 'Temperature B', fill: false, borderColor: 'blue', data : chartDataB }] }, options: { scales: { xAxes: [{ type: 'linear', position: 'bottom' }] } } }); var startTime = Date.now(); const drawGraph = function(valueA, valueB) { chartDataA.push({x: (Date.now() - startTime)/1000, y:valueA}); chartDataB.push({x: (Date.now() - startTime)/1000, y:valueB}); myChart.update(); } const computeTemp = function(byteArray) { // javascript integers are 32bits so this should work // There is a DataView object that would might be better to try here it allows // the user to control the endianess of the value can can read from any buffer var temp100 = byteArray.getUint8(3) << 24 | byteArray.getUint8(2) << 16 | byteArray.getUint8(1) << 8 | byteArray.getUint8(0); // the temperature data is returned in celcius times 100 so we need to divide return temp100/ 100.0; }; const readTemp = function(byteArrayA, byteArrayB) { var valueA = computeTemp(byteArrayA); var valueB = computeTemp(byteArrayB); $("#tempA > .value").text(valueA); $("#tempB > .value").text(valueB); drawGraph(valueA, valueB); }; const connect = function() { let request = navigator.bluetooth.requestDevice({ filters: [{ namePrefix: "Thermoscope"}], optionalServices: [tempAServiceAddr, tempBServiceAddr] }) let characteristicA, characteristicB; // Step 2: Connect to it request.then(function(device) { return device.gatt.connect(); }) // Step 3: Get the Service .then(function(server) { showDisconnect(server); window.server = server; return server.getPrimaryService(tempAServiceAddr); }) .then(function(service){ return service.getCharacteristic(0x0001); }) .then(function(_characteristicA){ characteristicA = _characteristicA; // get second service return server.getPrimaryService(tempBServiceAddr); }) .then(function(service){ return service.getCharacteristic(0x0001); }) .then(function(characteristicB){ startTime = Date.now(); const takeReading = function() { let arrayA; characteristicA.readValue() .then(function(_arrayA){ arrayA = _arrayA; return characteristicB.readValue(); }) .then(function(arrayB){ readTemp(arrayA, arrayB); }); }; window.takeReadingIntervalID = setInterval(takeReading,600); }) .catch(function(error) { console.error('Connection failed!', error); }); }; $('#connect').click(connect); })();
const gulp = require('gulp'); const browserSync = require('browser-sync').create(); const reload = browserSync.reload; gulp.task('watch', () => { gulp.watch('app/**/*.html', gulp.parallel('app.html')); gulp.watch('app/**/*.css', gulp.parallel('app.css')); gulp.watch('app/**/*.js', gulp.parallel('app.js')); gulp.watch('app/**/*.*', gulp.parallel('app.assets')); }); gulp.task('start.server', function(done) { browserSync.init({ server: { baseDir: 'public' } }); gulp.watch('app/**/*').on('change', browserSync.reload); done(); }); // gulp.task('js-watch', ['js'], function (done) { // browserSync.reload(); // done(); // }); gulp.task('server', gulp.series('start.server', 'watch'));
import React, { useState } from 'react'; import { useDispatch, useSelector } from 'react-redux'; import { animated, useSpring } from 'react-spring'; import { reDoAll } from '../redux/actions/DressingRoomActions'; export default function RightContentDR(props) { let { hairstyle, necklaces, topclothes, botclothes, handbags, shoes, background } = useSelector(state => state.DressingRoomReducer.choosenList); const dispatch = useDispatch(); const [redoBtn, setRedoBtn] = useState(true); const { redoScale } = useSpring({ from: { redoScale: 0 }, redoScale: redoBtn ? 1 : 0, config: { duration: 1000 } }); const hairStyleAnim = useSpring({ from: { transform: 'translateY(-5%) scale(0.2)' }, background: `url(${hairstyle})`, transform: 'translateX(0%) scale(0.15)', config: { duration: 500 }, reset: true }) const necklacesAnim = useSpring({ from: { transform: 'translateY(10%) scale(1)' }, background: `url(${necklaces})`, transform: 'translateX(0%) scale(0.5)', config: { duration: 500 }, reset: true }) const topClothAnim = useSpring({ from: { transform: 'translateX(-150%) scale(0) rotate(90deg)', opacity: 0.5 }, background: `url(${topclothes})`, transform: 'translateX(0%) scale(0.5) rotate(0)', opacity: 1, config: { duration: 1000 }, reset: true }); const botClothAnim = useSpring({ from: { transform: 'translateX(-150%) scale(0) rotate(-90deg)', opacity: 0.5 }, background: `url(${botclothes})`, opacity: 1, transform: 'translateX(0%) scale(0.5) rotate(0)', config: { duration: 1000 }, reset: true }) const handbagsAnim = useSpring({ from: { transform: 'scale(0.45)', opacity: 0.5 }, background: `url(${handbags})`, transform: 'scale(0.5)', opacity: 1, config: { duration: 1000 }, reset: true }) const shoesAnim = useSpring({ from: { transform: 'scale(0.6)' }, background: `url(${shoes})`, transform: 'scale(0.5)', config: { duration: 500 }, reset: true }) const backgroundAnim = useSpring({ from: { transform: 'scale(0.47)', opacity: 0.5 }, backgroundImage: `url(${background})`, transform: 'scale(0.5)', opacity: 1, config: { duration: 1000 }, reset: true }) return ( <div className="contain"> <animated.button style={{ transform: redoScale.interpolate({ range: [0, 0.25, 0.35, 0.45, 0.55, 0.65, 0.75, 1], output: [1, 0.97, 0.9, 1.1, 0.9, 1.1, 1.03, 1] }).interpolate(value => `scale(${value})`), boxShadow: 'none' }} className="btn btn-danger btn-sm ml-4 mt-2" onClick={() => { setRedoBtn(!redoBtn); dispatch(reDoAll()); }}>Chọn lại <i className="fa fa-redo-alt"></i></animated.button> <div className="body" /> <div className="model" /> <animated.div style={hairStyleAnim} className="hairstyle" /> <animated.div style={necklacesAnim} className="necklace" /> <animated.div style={topClothAnim} className="bikinitop" /> <animated.div style={botClothAnim} className="bikinibottom" /> <animated.div style={handbagsAnim} className="handbag" /> <animated.div style={shoesAnim} className="feet" /> <animated.div style={backgroundAnim} className="background" /> </div > ) }
/* --------------------------- INTUIT CONFIDENTIAL --------------------------- utils.js Written by Date Revised by Date Summary of changes Jason Harris 11/11/08 Added methods to handle enabling/disabling elements. Lane Roathe 06/22/10 [DE1411] check window.viewController usage to fix deferred printing (Some reports do not have a viewController or attached method) Lane Roathe 08/30/10 [S692] Add export button Copyright 2008-2010 Intuit, Inc All rights reserved. Unauthorized reproduction is a violation of applicable law. This material contains certain confidential and proprietary information and trade secrets of Intuit, Inc. RESTRICTED RIGHTS LEGEND Use, duplication, or disclosure by the Government is subject to restrictions as set forth in subdivision (b) (3) (ii) of the Rights in Technical Data and Computer Software clause at 52.227-7013. Intuit, Inc P.O. Box 7850 Mountain View, CA 94039-7850 ----------------------------- INTUIT CONFIDENTIAL ------------------------- */ function deepCopy(obj){ var seenObjects = []; var mappingArray = []; var f = function(simpleObject) { var indexOf = seenObjects.indexOf(simpleObject); if (indexOf == -1) { if(simpleObject instanceof Array) { seenObjects.push(simpleObject); var newArray = []; mappingArray.push(newArray); for(var i=0,len=simpleObject.length; i<len; i++) newArray.push(f(simpleObject[i])); return newArray; } else if(typeof simpleObject == 'object' && simpleObject !== null) { seenObjects.push(simpleObject); var newObject = {}; mappingArray.push(newObject); for (var p in simpleObject) newObject[p] = f(simpleObject[p]); if(simpleObject.constructor) newObject.constructor = simpleObject.constructor; return newObject; } else { return simpleObject; } } else { return mappingArray[indexOf]; } }; return f(obj); } function ElementIsEnabled(element) { if (!element) return false; var classNames = element.className.split(' '); for (var i = 0; i < classNames.length; ++i) { var className = classNames[i]; if (className == "enabled") return true; if (className == "disabled") return false; } return true; } function SetElementEnabled(elementID, enabled, title) { var element = document.getElementById(elementID); if (element) { var classNames = element.className.split(' '); var filteredClassNames = new Array(); for (var i = 0; i < classNames.length; ++i) { var className = classNames[i]; if (className == "enabled" || className == "disabled" || 0 == className.length) continue; filteredClassNames.push(className); } filteredClassNames.push(enabled ? "enabled" : "disabled"); element.className = filteredClassNames.join(' '); element.title = title; } } function EnableAddToSourceList() { SetElementEnabled("AddToSourceList", true, null); } function DisableAddToSourceList() { SetElementEnabled("AddToSourceList", false, "This report is already in the source list"); } function ClickSourceList(element) { var result = ElementIsEnabled(element); DisableAddToSourceList(); return result; } function readCookie(name) { // stolen from http://www.quirksmode.org/js/cookies.html var nameEQ = name + "="; var ca = document.cookie.split(';'); for(var i=0;i < ca.length;i++) { var c = ca[i]; while (c.charAt(0)==' ') c = c.substring(1,c.length); if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length); } return null; } function SortTables(cssSelector, sortColumnIndex, sortDirection) { var tables = $$(cssSelector); for (var i = 0; i < tables.length; ++i) { var table = tables[i]; // var indexAndOrder = readCookie("table-sort " + table.id); var index = 0; var order = 1; /* if (null !== indexAndOrder) { indexAndOrder = indexAndOrder.split(' '); index = parseInt(indexAndOrder[0]) + 1; order = parseInt(indexAndOrder[1]); } */ TableKit.Sortable.sort(table.id, index, order); } } function CurrencyMenuInit() { var currencySelector = $("#currencyTypeSelect"); if (currencySelector.length) { currencySelector.change( function() { var popup = $(this); var currencyID = popup.val(); if( window.viewController ) window.viewController.SelectCurrencyID(currencyID); }); } } function SettingsButtonInit() { var settingsButton = $(".settingsButton"); if (settingsButton.length) { settingsButton.click(function() { if (window.viewController) window.viewController.InvokeSettings(); return false; }); } var settingsButton = $(".exportButton"); if (settingsButton.length) { settingsButton.click(function() { if (window.viewController) window.viewController.InvokeExport(); return false; }); } } $(SettingsButtonInit); // intercept the ESC key to prevent crashing var ESC = 27; (function($) { $(document).bind("keyup",function(e) { if(e.keyCode == ESC) { e.preventDefault(); e.stopPropagation(); } return false; }); })(jQuery);
OperacionesManager.module("ContratoApp.Aumento", function(Aumento, OperacionesManager, Backbone, Marionette, $, _){ Aumento.Controller = { crear: function(codigo){ var aumentoLayout = new Aumento.Layout(); var contrato = OperacionesManager.request("contratos:entity", codigo); var aumentoLateral = new Aumento.Contrato({ model: contrato }); var aumentoPrincipal = new Aumento.Principal({ model: contrato }); aumentoLayout.on("show", function(){ aumentoLayout.lateral.show(aumentoLateral); aumentoLayout.principal.show(aumentoPrincipal); }); OperacionesManager.regions.main.show(aumentoLayout); }, listar: function(codigo){ console.log(codigo); var aumentoLayout = new Aumento.Layout(); var contrato = OperacionesManager.request("contratos:entity", codigo); var aumentoLateral = new Aumento.Contrato({ model: contrato }); var aumentoPrincipal = new Aumento.Aumento({ model: contrato }); aumentoLayout.on("show", function(){ aumentoLayout.lateral.show(aumentoLateral); aumentoLayout.principal.show(aumentoPrincipal); }); OperacionesManager.regions.main.show(aumentoLayout); }, } });
angular.module('dynamic-sports.directives', []);
function validateUserForm() { var name = document.getElementById("name").value; var pass = document.getElementById("pass").value; var cpass = document.getElementById("cpass").value; var phone = document.getElementById("phone").value; var email = document.getElementById("email").value; var error = document.getElementById("uerror"); var birthday = document.getElementById("birthday"); var address = document.getElementById("address"); var patt = /^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/; var res = patt.test(email); if (name == "" || email == "" || phone == "" || pass == "" || cpass == "" || birthday == "" || address == "") { error.innerHTML = "ALL fields required js"; return false; } else if (!isNaN(name)) { error.innerHTML = "User Name should be start with string"; return false; } else if (name.length < 5) { error.innerHTML = "User Name should be 5 characters long"; return false; } else if (phone.length != 11) { error.innerHTML = "Invalid Phone Number"; return false; } else if (!res) { error.innerHTML = "Email format is not correct"; return false; } else if (pass.length < 6) { error.innerHTML = "Password should be 8 characters long"; return false; } else if (pass.value != cpass.value) { error.innerHTML = "Password should be same"; return false; } } function validateLoginForm() { var pass = document.getElementById("pass").value; var email = document.getElementById("email").value; var error = document.getElementById("error"); var patt = /^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/; var res = patt.test(email); if (email == "" || pass == "") { error.innerHTML = "ALL fields required js"; return false; } else if (!res) { error.innerHTML = "Email format is not correct"; return false; } else if (pass.length < 6) { error.innerHTML = "Password should be 6 characters long"; return false; } }
import React from 'react' import { Link } from 'gatsby' import EpicTalksList from '../TalksList/EpicTalksList' const Nursing = () => { return ( <> <h2>Lazarus Battle <span style={{ float: 'right' }}><Link to="/app/home">back</Link></span> </h2> <EpicTalksList track="Nursing Track" /> </> ) } export default Nursing
import Vue from 'vue' import App from './App.vue' import vuetify from './plugins/vuetify' import VueRouter from 'vue-router'; import Vuelidate from 'vuelidate' Vue.use(Vuelidate); import Home from "./views/Home"; import Workouts from "./views/Workouts"; import Profile from "./views/Profile"; import Routines from "./views/Routines"; import LogIn from "./views/LogIn"; import Register from "./views/Register"; import RoutineDetail from "./views/RoutineDetail"; import CreateRoutine from "./views/CreateRoutine"; import Error404 from "./views/Error404"; import Exercises from "./views/Exercises"; import CreateExercise from "./views/CreateExercise"; import EditExercise from "./views/EditExercise"; import ValidateEmail from "./views/ValidateEmail"; import CreateCycleExercise from "./components/CreateCycleExercise"; import Setup from "./views/Setup"; export {router}; Vue.use(VueRouter); Vue.config.productionTip = false const router = new VueRouter({ routes: [ {path: '/', component: LogIn}, {path: '/Home', component: Home}, {path: '/Workouts', component: Workouts}, {path: '/Profile', component: Profile}, {path: '/Routines', component: Routines}, {path: '/Exercises', component: Exercises}, {path: '/RoutineDetail', component: RoutineDetail, name: 'RoutineDetailPath', props: true}, {path: '/CreateRoutine', component: CreateRoutine, name: 'CreateRoutinePath', props: true}, {path: '/CreateExercise', component: CreateExercise}, {path: '/EditExercise', component: EditExercise, name: 'EditExercisePath', props: true}, {path: '/Register', component: Register}, {path: '/ValidateEmail', component: ValidateEmail}, {path: '/CreateCycleExercise', component: CreateCycleExercise}, {path: '/Setup', component: Setup}, {path: '/*', component: Error404}, ] }) router.beforeEach((to, from, next) => { if (isLogged() || isValidPath(to.path)) { next(); } else { next({ path: '/', }) } }); function isLogged() { return localStorage.getItem('securityToken'); } function isValidPath(path) { return path.localeCompare('/') === 0 || path.localeCompare('/Register') === 0 || path.localeCompare('/ValidateEmail') === 0; } new Vue({ router, vuetify, render: h => h(App) }).$mount('#app')
const tableTool = async page => { try { const selector = '.table-tool__manager > p'; const getCurrentSize = async () => { return { x: await page.evaluate(selector => ( document.querySelector(selector).innerText.match(/\d+/g)[0] ), selector), y: await page.evaluate(selector => ( document.querySelector(selector).innerText.match(/\d+/g)[1] ), selector) }; }; const previousSize = await getCurrentSize(); await page.evaluate(() => ( document.querySelectorAll('.table-tool__plus')[0].click() )) await page.evaluate(() => ( document.querySelectorAll('.table-tool__plus')[1].click() )) const currentSize = await getCurrentSize(); if( parseInt(currentSize.x) === parseInt(previousSize.x) + 1 && parseInt(currentSize.y) === parseInt(previousSize.y) + 1 ) { return 'Tool test passed' } else { return 'Tool test failure' } } catch (e) { console.error('Testing tool failure.' + 'Tool is not working correctly.' + 'Error msg:', e) } }; module.exports = tableTool;
//************************************Callbacks************************************ //Boot up sequence window.currentVersion = 34; let AlwaysOn; let isLoaded; try { AlwaysOn = localStorage.getItem("bc-cursed-always-on"); } catch (err) { console.log(err); } LoginListener(); async function LoginListener() { while (!isLoaded) { try { while ((!window.CurrentScreen || window.CurrentScreen == "Login") && !isLoaded) { await new Promise(r => setTimeout(r, 2000)); } isLoaded = true; //Initialize base functions InitBasedFns(); //AlwaysOn if (AlwaysOn == "enabled") { CursedStarter(); TryPopTip(31); } } catch (err) { console.log(err); } await new Promise(r => setTimeout(r, 2000)); } } /** Starts the script */ function CursedStarter() { try { //Cleans the existing chatlog document.querySelectorAll(".ChatMessage:not([verified=true]").forEach(msg => { let verifiedAtt = document.createAttribute("verified"); verifiedAtt.value = "true"; msg.setAttributeNode(verifiedAtt); }); // Just restarts if the curse already exists (prevents dupes) if (window.cursedConfigInit && cursedConfig.isRunning == false) { //Runs the script cursedConfig.isRunning = true; cursedConfig.onRestart = true; popChatSilent("Curse restarted.", "System"); } else if (!window.cursedConfigInit) { //Base configs window.cursedConfigInit = { hasPublicAccess: true, hasCursedKneel: false, hasCursedSpeech: true, hasCursedOrgasm: false, isMute: false, disaledOnMistress: false, enabledOnMistress: false, hasEntryMsg: false, hasFullMuteChat: false, hasSound: false, hasRestrainedPlay: false, hasNoMaid: false, hasNoContractions: false, hasFullPublic: false, hasAntiAFK: false, hasRestrainedSpeech: false, canReceiveNotes: false, hasCaptureMode: false, hasReminders: false, hasForcedSensDep: false, isLockedNewSub: false, isLockedNewLover: false, isLockedOwner: false, hasDollTalk: false, hasForcedMeterLocked: false, hasForcedMeterOff: false, hasDCPrevention: false, cannotOrgasm: false, forbidorgasm: false, hasBlockedOOC: false, hasSecretOrgasm: false, hasNoEasyEscape: false, hasFullLengthMode: false, owners: Player.Ownership ? [Player.Ownership.MemberNumber.toString()] : [], mistresses: Player.Ownership ? [Player.Ownership.MemberNumber.toString()] : [], blacklist: [], bannedWords: [], sentences: [{ ident: "yes", text: "Yes, %target%" }, { ident: "no", text: "No, %target%" }, { ident: "rephrase", text: "May this be rephrased into a yes or no question, %target%?" }, { ident: "greetings", text: "Greetings, %target%, it is good to see you." }, { ident: "leave", text: "May %self% be excused, %target%?" }, { ident: "service", text: "How may %self% be useful for you today, %target%?" },], cursedAppearance: [], cursedPresets: [], savedColors: [], charData: [], reminders: [], reminderInterval: 300000, entryMsg: "", say: "", sound: "", self: "I", targets: [{ ident: "miss", text: "miss" }, { ident: "mistress", text: "mistress" }], capture: { capturedBy: "", Valid: 0 }, mistressIsHere: false, ownerIsHere: false, seenTips: [], slaveIdentifier: Player.Name, commandChar: "#", vibratorIntensity: 3, orgasms: 0, strikes: 0, lastPunishmentAmount: 0, strikeStartTime: Date.now(), punishmentsDisabled: false, warned: [], toUpdate: [], mustRefresh: false, isRunning: false, isSilent: false, isClassic: false, isEatingCommands: false, isLooseOwner: false, mustRetype: true, hasRestraintVanish: false, canLeash: false, hasWardrobeV2: false, hasIntenseVersion: false, wasLARPWarned: false, hasFullCurse: false, disabledCommands: [], optinCommands: [{command: 'forcedsay', isEnabled: false}, {command: 'disableblocking', isEnabled: false}], chatlog: [], savedSilent: [], chatStreak: 0, shouldPopSilent: false, hasForward: false, onRestart: true, hasHiddenDisplay: false, }; window.cursedConfig = { ...cursedConfigInit }; window.oldStorage = null; window.oldVersion = null; window.vibratorGroups = ["ItemButt", "ItemFeet", "ItemVulva", "ItemNipples", "ItemVulvaPiercings", "ItemNipplesPiercings", "ItemDevices"]; window.brokenVibratingItems = ["MermaidSuit", "AnalHook"]; //Tries to load configs try { oldStorage = JSON.parse(localStorage.getItem(`bc-cursedConfig-${Player.MemberNumber}`)); oldVersion = JSON.parse(localStorage.getItem(`bc-cursedConfig-version-${Player.MemberNumber}`)); } catch (err) { console.log(err); } //Pull config from log or create if (!oldStorage) { SendChat("The curse awakens on " + Player.Name + "."); popChatSilent("Welcome to the curse! The curse allows for many mysterious things to happen... have fun discovering them. The help command should be able to get you started (" + cursedConfig.commandChar + cursedConfig.slaveIdentifier + " help). You can also get tips by using this command: " + cursedConfig.commandChar + cursedConfig.slaveIdentifier + " tip . There is an official discord if you have anything to say: https://discord.gg/9dtkVFP . Please report any issues or bug you encounter to ace (12401) - Ace__#5558.", "System"); try { localStorage.setItem(`bc-cursedConfig-version-${Player.MemberNumber}`, currentVersion); } catch (err) { console.log(err); } } else { //Load previous data, takes care of upgrades or downgrades cursedConfig = { ...cursedConfig, ...oldStorage }; //Set name immediately let user = cursedConfig.charData.filter(c => c.Number == Player.MemberNumber); if (user.length > 0 && user[0].Nickname) { if (Player.Name != user[0].Nickname && !user[0].SavedName) { cursedConfig.charData.filter(c => c.Number == Player.MemberNumber)[0].SavedName = Player.Name; } Player.Name = cursedConfig.hasIntenseVersion && ChatRoomSpace != "LARP" ? user[0].Nickname : user[0].SavedName; } if (oldVersion > currentVersion) { alert("WARNING! Downgrading the curse to an old version is not supported. This may cause issues with your settings. Please reinstall the latest version. (Ignore this message if downgrading was the recommended action to a problem.) Error: V03"); } if (oldVersion != currentVersion) { localStorage.setItem(`bc-cursedConfig-version-${Player.MemberNumber}`, currentVersion); alert("IMPORTANT! Please make sure you refreshed your page after updating."); //Update messages after alert so they are not lost if wearer refreshes on alert and storage was updated SendChat("The curse following " + Player.Name + " has changed."); popChatSilent("You have loaded an updated version of the curse, make sure you have refreshed your page before using this version. Please report any new bugs. This update may have introduced new features, don't forget to use the help command to see the available commands. (" + cursedConfig.commandChar + cursedConfig.slaveIdentifier + " help)", "System"); } else if (oldVersion == currentVersion) { SendChat("The curse follows " + Player.Name + "."); popChatSilent("Have fun~ Please report any issues or bug you encounter to ace (12401) - Ace__#5558.", "System"); } if (curseTips.find(T => !cursedConfig.seenTips.includes(T.ID) && !T.isContextual)) { popChatSilent("There are unseen tips available. Use '" + cursedConfig.commandChar + cursedConfig.slaveIdentifier + " tip' to see one", "System"); } } if (cursedConfig.hasIntenseVersion) { popChatSilent("Intense mode is on (risky).", "System"); } //Resets Strikes when it has been a week if (cursedConfig.strikeStartTime + 604800000 < Date.now()) { popChatSilent("A new week has begun, your strikes have reset. (Might be a good time to check for updates!)", "System"); cursedConfig.strikeStartTime = Date.now(); cursedConfig.strikes = 0; cursedConfig.lastPunishmentAmount = 0; } //Enables the hidden curse item to display who has the curse if (AssetFemale3DCG.filter(G => G.Group == "ItemHidden")[0] && AssetFemale3DCG.filter(G => G.Group == "ItemHidden")[0].Asset) { AssetFemale3DCG.filter(G => G.Group == "ItemHidden")[0].Asset.push({ Name: "Curse", Visible: false, Value: -1 }); AssetFemale3DCG.filter(G => G.Group == "ItemHidden")[0].Asset.push({ Name: "Curse" + currentVersion, Visible: false, Value: -1 }); AssetLoadAll(); InventoryAdd(Player, "Curse", "ItemHidden"); InventoryAdd(Player, "Curse" + currentVersion, "ItemHidden"); // Always re-enable the version tip to promote staying up to date cursedConfig.seenTips = cursedConfig.seenTips.filter(ST => ST !== 49); } // DC Prevention if (cursedConfig.hasIntenseVersion && cursedConfig.hasDCPrevention && !Player.CanWalk() && cursedConfig.lastChatroom) { const roomToGoTo = cursedConfig.lastChatroom; delete cursedConfig.lastChatroom; SendToRoom(roomToGoTo); NotifyOwners("DC prevention enabled, the wearer was sent back to the room she was previously locked in. If this is not a room you should be locked in, please disable the curse, relog and go into another room before reactivating the curse, avoid disturbing others.", true); TryPopTip(43); } //Runs the script cursedConfig.isRunning = true; cursedConfig.onRestart = true; InitHelpMsg(); InitAlteredFns(); InitCleanup(); //Cleans up the arrays/migrations CursedCheckUp(); //Initial check ChatlogProcess(); //Chatlog handling ReminderProcess(); //Reminders handling } } catch (err) { console.error(err); } } /** Stops the script */ function CursedStopper() { try { if (cursedConfig.isRunning) { cursedConfig.isRunning = false; popChatSilent("Curse stopped", "System"); } } catch (err) { console.error(err); } } /** Intense Mode Switch On */ function CursedIntenseOn() { try { if (!cursedConfig.hasIntenseVersion) { cursedConfig.hasIntenseVersion = true; TryPopTip(2); popChatSilent("Intense mode activated (risky).", "System"); } } catch (err) { console.error(err); } } /** Intense Mode Switch Off */ function CursedIntenseOff() { try { if (cursedConfig.hasIntenseVersion) { cursedConfig.hasIntenseVersion = false; cursedConfig.say = ""; cursedConfig.hasFullMuteChat = false; popChatSilent("Intense mode deactivated (safe).", "System"); } } catch (err) { console.error(err); } } /** Always on mode to start on load switch on */ function AlwaysOnTurnOn() { localStorage.setItem("bc-cursed-always-on", "enabled"); } /** Always on mode to start on load switch off */ function AlwaysOnTurnOff() { localStorage.setItem("bc-cursed-always-on", "disabled"); }
import React, { useState } from "react"; import { withStyles } from "@material-ui/core/styles"; import Alert from "@material-ui/lab/Alert"; import { pink } from "@material-ui/core/colors"; import { TextField, FormControlLabel, Checkbox } from "@material-ui/core"; import Button from "@material-ui/core/Button"; import SocialButton from "./SocialButton"; import facebookIcon from "../assets/facebookIcon.png"; import googleIcon from "../assets/googleIcon.png"; import twitterIcon from "../assets/twitterIcon.png"; const OrangeCheckbox = withStyles({ root: { color: pink[600], "&$checked": { color: pink[600] } }, checked: {} })((props) => <Checkbox color="default" {...props} />); const ColoredTextField = withStyles({ root: { "& label.Mui-focused": { color: "#f50057" }, "& .MuiInput-underline:after": { borderBottomColor: "#f50057" }, "& .MuiOutlinedInput-root": { "&.Mui-focused fieldset": { borderColor: "#f50057" } } } })(TextField); const LoginForm = (props) => { // State const [email, setEmail] = useState(""); const [password, setPassword] = useState(""); const [isChecked, setIsChecked] = useState(false); const [showAlert, setShowAlert] = useState(false); const [isFormValid, setIsFormValid] = useState(false); const [errorMessage, setErrorMessage] = useState( "Please fill in all form fields." ); const submitForm = (e) => { e.preventDefault(); // Reset state setShowAlert(false); let isValid = false; // Form Validation if (email !== "" && password !== "") { if (isEmail(email) && password.length >= 6) isValid = true; else if (!isEmail(email)) setErrorMessage("Invalid email address."); else if (password.length < 6) setErrorMessage("Password must be at least 6 symbols."); else setErrorMessage("Incorrect email or password."); } else { setErrorMessage("Please fill in all form fields"); } // Save credentials in local storage // if(isChecked){ // localStorage.setItem('email', email); // } // Update state if (isValid) setIsFormValid(true); else setIsFormValid(false); setShowAlert(true); }; // Change alert messages on invalid form let alert = ( <Alert style={{ marginBottom: "15px" }} severity="error"> {errorMessage} </Alert> ); // Change alert messages on valid form if (isFormValid) { alert = ( <Alert style={{ marginBottom: "15px" }} severity="success"> Successfully logged in. </Alert> ); } return ( <div className="login-container"> <form onSubmit={(e) => submitForm(e)} className="login-form"> <h1 className="form-heading">Log in with</h1> <div className="social-buttons"> <SocialButton platform="Facebook" src={facebookIcon} /> <SocialButton platform="Google" src={googleIcon} /> <SocialButton platform="Twitter" src={twitterIcon} /> </div> <p className="line-break-label ">or</p> {/* Alert */} {showAlert && alert} <div className="form-controls"> <ColoredTextField className="form-field" value={email} onChange={(e) => setEmail(e.target.value)} id="email-field" label="Email" variant="outlined" size="small" /> <ColoredTextField className="form-field" value={password} onChange={(e) => setPassword(e.target.value)} type="password" id="password-field" label="Password" variant="outlined" size="small" /> <div className="checkbox"> <FormControlLabel control={ <OrangeCheckbox checked={isChecked} title="checkbox" onChange={(e) => setIsChecked(e.target.checked)} name="checkbox" id="checkbox" /> } label="Remember me " /> </div> </div> <Button id="submit-button" type="submit" className="submit-button" variant="outlined" color="primary" fullWidth size="large" > Log in </Button> <div className="change-auth"> Don't have an account?{" "} <a href="#" className="sign-up-link"> Sign Up </a> </div> </form> </div> ); }; const isEmail = (email) => { let regEmail = /^(([^<>()\[\]\\.,;:\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,}))$/; if (!regEmail.test(email)) { return false; } else { return true; } }; export default LoginForm;
/** * This script automatically creates The default Outlet Types when an * empty database is used for the first time. You can use this * technique to insert data into any List you have defined. * * Alternatively, you can export a custom function for the update: * module.exports = function(done) { ... } */ exports.create = { Gallery: [ { "_id": "5abcf4ff841ed62488974761", "key": "ktt-gallery", "name": "KTT Gallery", "publishedDate": "2018-03-29T14:15:27.000Z", "__v": 5, "images": [ { "public_id": "qgkasabhzfug6c5si8xm", "version": 1522928963, "signature": "ce40c1bb19d04bc8e72d4ee7a44a12f980c5c76a", "width": 809, "height": 1080, "format": "jpg", "resource_type": "image", "url": "http://res.cloudinary.com/hjmavbxvc/image/upload/v1522928963/qgkasabhzfug6c5si8xm.jpg", "secure_url": "https://res.cloudinary.com/hjmavbxvc/image/upload/v1522928963/qgkasabhzfug6c5si8xm.jpg", "_id": "5ac60d4182c9596914ec5b06" }, { "public_id": "hcx56peozjfkokittgcl", "version": 1522928960, "signature": "7df652331a6b64a42b045da70437dfec0290decb", "width": 960, "height": 720, "format": "jpg", "resource_type": "image", "url": "http://res.cloudinary.com/hjmavbxvc/image/upload/v1522928960/hcx56peozjfkokittgcl.jpg", "secure_url": "https://res.cloudinary.com/hjmavbxvc/image/upload/v1522928960/hcx56peozjfkokittgcl.jpg", "_id": "5ac60d4182c9596914ec5b05" }, { "public_id": "uwrfupbctnggqbxp6n4u", "version": 1522928964, "signature": "de9b388251a39eab142d221470077b53bd3dafe7", "width": 768, "height": 1024, "format": "jpg", "resource_type": "image", "url": "http://res.cloudinary.com/hjmavbxvc/image/upload/v1522928964/uwrfupbctnggqbxp6n4u.jpg", "secure_url": "https://res.cloudinary.com/hjmavbxvc/image/upload/v1522928964/uwrfupbctnggqbxp6n4u.jpg", "_id": "5ac60d4182c9596914ec5b04" }, { "public_id": "a2t7mwyeo2okdjyc20yr", "version": 1522928964, "signature": "565f26ab1b4a804e323de49473735baed9538581", "width": 768, "height": 1024, "format": "jpg", "resource_type": "image", "url": "http://res.cloudinary.com/hjmavbxvc/image/upload/v1522928964/a2t7mwyeo2okdjyc20yr.jpg", "secure_url": "https://res.cloudinary.com/hjmavbxvc/image/upload/v1522928964/a2t7mwyeo2okdjyc20yr.jpg", "_id": "5ac60d4182c9596914ec5b03" }, { "public_id": "as5nrxhgefvyqjb4npdz", "version": 1522928963, "signature": "fc74452ac55667ccb3b58c9c8b83f0b0e33e5ef8", "width": 1080, "height": 810, "format": "jpg", "resource_type": "image", "url": "http://res.cloudinary.com/hjmavbxvc/image/upload/v1522928963/as5nrxhgefvyqjb4npdz.jpg", "secure_url": "https://res.cloudinary.com/hjmavbxvc/image/upload/v1522928963/as5nrxhgefvyqjb4npdz.jpg", "_id": "5ac60d4182c9596914ec5b02" }, { "public_id": "jszrtiuaqt7spp3x1dls", "version": 1522928965, "signature": "1cf9dea7e88a5bd02c4d8291351692cb18a24759", "width": 768, "height": 1024, "format": "jpg", "resource_type": "image", "url": "http://res.cloudinary.com/hjmavbxvc/image/upload/v1522928965/jszrtiuaqt7spp3x1dls.jpg", "secure_url": "https://res.cloudinary.com/hjmavbxvc/image/upload/v1522928965/jszrtiuaqt7spp3x1dls.jpg", "_id": "5ac60d4182c9596914ec5b01" }, { "public_id": "fsbaooqkcvnjltgofwpr", "version": 1522928964, "signature": "c333edb751445865160479bb52393aca7ff323a2", "width": 720, "height": 960, "format": "jpg", "resource_type": "image", "url": "http://res.cloudinary.com/hjmavbxvc/image/upload/v1522928964/fsbaooqkcvnjltgofwpr.jpg", "secure_url": "https://res.cloudinary.com/hjmavbxvc/image/upload/v1522928964/fsbaooqkcvnjltgofwpr.jpg", "_id": "5ac60d4182c9596914ec5b00" }, { "public_id": "nbvrurfoyeujdeocpstg", "version": 1522928963, "signature": "a8192a356d7b11283868665d8f74140c948ea051", "width": 768, "height": 1024, "format": "jpg", "resource_type": "image", "url": "http://res.cloudinary.com/hjmavbxvc/image/upload/v1522928963/nbvrurfoyeujdeocpstg.jpg", "secure_url": "https://res.cloudinary.com/hjmavbxvc/image/upload/v1522928963/nbvrurfoyeujdeocpstg.jpg", "_id": "5ac60d4182c9596914ec5aff" }, { "public_id": "isjimg0gguyadqdnluxj", "version": 1522928963, "signature": "39a594ad92cdc36f2bd44c109ba885608d2ab0f8", "width": 720, "height": 960, "format": "jpg", "resource_type": "image", "url": "http://res.cloudinary.com/hjmavbxvc/image/upload/v1522928963/isjimg0gguyadqdnluxj.jpg", "secure_url": "https://res.cloudinary.com/hjmavbxvc/image/upload/v1522928963/isjimg0gguyadqdnluxj.jpg", "_id": "5ac60d4182c9596914ec5afe" }, { "public_id": "yonos0pqt84reqlec53m", "version": 1522928965, "signature": "f0f6d9292a5a6e34af885f5fc4d6e00b4a9bfd65", "width": 960, "height": 960, "format": "jpg", "resource_type": "image", "url": "http://res.cloudinary.com/hjmavbxvc/image/upload/v1522928965/yonos0pqt84reqlec53m.jpg", "secure_url": "https://res.cloudinary.com/hjmavbxvc/image/upload/v1522928965/yonos0pqt84reqlec53m.jpg", "_id": "5ac60d4182c9596914ec5afd" }, { "public_id": "xu8ujpx3ibdy1ijaallg", "version": 1522928961, "signature": "b59cb99e5cee8ee2b40c224cbfc6aec0761c586a", "width": 480, "height": 480, "format": "jpg", "resource_type": "image", "url": "http://res.cloudinary.com/hjmavbxvc/image/upload/v1522928961/xu8ujpx3ibdy1ijaallg.jpg", "secure_url": "https://res.cloudinary.com/hjmavbxvc/image/upload/v1522928961/xu8ujpx3ibdy1ijaallg.jpg", "_id": "5ac60d4182c9596914ec5afc" }, { "public_id": "f5z6zjrov1cjbunrf7p2", "version": 1522928962, "signature": "4a6a8be64725e465b81b5644d8440004d383d20c", "width": 809, "height": 1080, "format": "jpg", "resource_type": "image", "url": "http://res.cloudinary.com/hjmavbxvc/image/upload/v1522928962/f5z6zjrov1cjbunrf7p2.jpg", "secure_url": "https://res.cloudinary.com/hjmavbxvc/image/upload/v1522928962/f5z6zjrov1cjbunrf7p2.jpg", "_id": "5ac60d4182c9596914ec5afb" }, { "public_id": "b6jnlleuxtptlweo7g67", "version": 1522928964, "signature": "0cd4b4f70e9ec5b869850064bf53dc5c76173f4d", "width": 1080, "height": 1080, "format": "jpg", "resource_type": "image", "url": "http://res.cloudinary.com/hjmavbxvc/image/upload/v1522928964/b6jnlleuxtptlweo7g67.jpg", "secure_url": "https://res.cloudinary.com/hjmavbxvc/image/upload/v1522928964/b6jnlleuxtptlweo7g67.jpg", "_id": "5ac60d4182c9596914ec5afa" }, { "public_id": "chauecklpvtqtzqvxwjo", "version": 1522928961, "signature": "d0a671bb01306d44ba8fd454502f885e695671ee", "width": 960, "height": 743, "format": "jpg", "resource_type": "image", "url": "http://res.cloudinary.com/hjmavbxvc/image/upload/v1522928961/chauecklpvtqtzqvxwjo.jpg", "secure_url": "https://res.cloudinary.com/hjmavbxvc/image/upload/v1522928961/chauecklpvtqtzqvxwjo.jpg", "_id": "5ac60d4182c9596914ec5af9" }, { "public_id": "ajhupl0chl3ebgwl70ja", "version": 1522928961, "signature": "1a86b19300eb5dcf09ecd302054685ac0b5004a5", "width": 720, "height": 720, "format": "jpg", "resource_type": "image", "url": "http://res.cloudinary.com/hjmavbxvc/image/upload/v1522928961/ajhupl0chl3ebgwl70ja.jpg", "secure_url": "https://res.cloudinary.com/hjmavbxvc/image/upload/v1522928961/ajhupl0chl3ebgwl70ja.jpg", "_id": "5ac60d4182c9596914ec5af8" } ] } ] };
// @flow const Rx = require('rxjs/Rx') const axios = require('axios') const _ = require('lodash') const event = require('../event') const INTERVAL = process.env.NODE_ENV === "production" ? 1000 * 60 * 60 : 1000 * 1 // 1 hour or 1 second const Source$ = Rx.Observable .interval(INTERVAL) .exhaustMap(() => Promise.all(['tt4179452', 'tt3530232', 'tt2575988'].map((id: string) => axios('https://tv-v2.api-fetch.website/show/' + id)))) .map(resps => resps.map(resp => resp.data)) .map(resps => resps.map(show => show.episodes.map(episode => Object.assign({}, episode, {title: show.title})))) .map(showEpisodes => _.flatten(showEpisodes)) .pairwise() .map(([a, b]) => _.differenceBy(b, a, 'tvdb_id')) .flatMap(episodes => episodes) .map(event.bind({}, "popcorn-time")) .publishReplay() .refCount() module.exports = Source$
const { clickIconButtonByPath, typeInTextFieldByLabel, clickButtonByLabel, } = require('./action-shortcuts') async function rebarLogin(page, { username, password }) { // Click burger menu await clickIconButtonByPath(page, { iconPathD: 'M3,6H21V8H3V6M3,11H21V13H3V11M3,16H21V18H3V16Z', }) // Click log in, wait for log in await clickButtonByLabel(page, { label: 'Log In' }) await page.waitForXPath('//h2[text()="Log In"]') // Populate credentials await typeInTextFieldByLabel(page, { label: 'E-Mail Address', value: username, }) await typeInTextFieldByLabel(page, { label: 'Password', value: password, }) // Click login button await clickButtonByLabel(page, { label: 'Log In', order: 2 }) // Wait to log in, for now just dumb wait for two seconds await page.waitFor(2000) // Click burger menu await clickIconButtonByPath(page, { iconPathD: 'M3,6H21V8H3V6M3,11H21V13H3V11M3,16H21V18H3V16Z', }) // Verify current user const currentUser = (await page.$x( '//em[text()="' + username + '"]/parent::div/parent::div/parent::div/label[text()="Current User"]', ))[0] expect(currentUser != null).toBe(true) } module.exports = rebarLogin
app.controller("SupplierInfoController",function($scope,$http) { $http({method:'GET',url:'supplierinformation'}).success(function(response) { console.log(response); $scope.supplierlist = response; }); $scope.selectCustomer = function(){ console.log("Hiiii"); } $scope.viewdata=function(id){ console.log("id"); console.log(id); $http({method:'GET',url:'selectedsupplierinfo',params:{id:id}}).success(function(data) { console.log(data); $scope.supplierlist1 = data; }); } });
export default fire;
import React,{Component} from 'react' class RefDemo extends React.Component{ constructor(){ super() this.inputRef= React.createRef(); this.cbRef=null; this.setcbRef=element=>{ this.cbRef=element } this.handleClick=this.handleClick.bind(this) } componentDidMount(){ // this.inputRef.current.focus() // console.log(this.inputRef) if(this.cbRef){ this.cbRef.focus() } } handleClick=()=>{ alert(this.inputRef.current.value) } render(){ return( <div> <label> UserName: <input type="text" ref={this.inputRef}/></label> <h2> <label> CUserName: <input type="text" ref={this.setcbRef}/></label> <button onClick={this.handleClick}>click</button></h2> </div> ) } } export default RefDemo
var parse = require('url').parse; /** * filter logging the URL requested */ filter = function(request, response, chain) { var url = parse(request.url); console.log(request.method + " " + url.pathname); chain.doFilter(request, response); }; exports.filter = filter;
(function(){ angular.module('app') .controller('SubmissionsController',['$route','$log','$http', '$routeParams', '$location', SubmissionsController]); function SubmissionsController($route,$log,$http,$routeParams,$location){ var vm = this; vm.items = []; vm.submission = {title:"",url:"",points:"",user_id:1,text:""}; vm.raiz = 'https://damp-savannah-3340.herokuapp.com'; vm.username = []; vm.getSubmissions = function () { $http({ method: 'GET', url: vm.raiz +'/submissions', headers: { 'Accept': 'application/json' } }).success(function (data, status) { vm.items = data; console.log(data); $log.debug(data); }).error(function (data, status) { alert("Error"); }) } vm.getSubmission = function () { $http({ method: 'GET', url: vm.raiz + '/submissions/'+$routeParams.id, headers: { 'Accept': 'application/json' } }).success(function (data, status) { vm.submission = data; console.log(data); $log.debug(data); }).error(function (data, status) { alert("Error"); }) } vm.getusername = function (id){ $http({ method: 'GET', url: vm.raiz + '/users/'+id, headers: { 'Accept': 'application/json' } }).success(function (data, status) { vm.username.push(data.name); }).error(function (data, status) { alert("Error"); }) } vm.guardar = function (){ $http({ method:'PUT', url :vm.raiz + '/submissions/' + vm.submission.id, headers:{ 'Accept': 'application/json' }, data:vm.submission }).success(function(){ alert("Guardado"); $location.url(vm.raiz + '/submissions') }).error(function(){ alert("Error"); }); } vm.nuevo = function (){ $http({ method:'POST', url :vm.raiz + '/submissions/', headers:{ 'Accept': 'application/json' }, data:vm.submission }).success(function(){ alert("Guardado"); $location.url(vm.raiz + '/submissions') }).error(function(){ alert("Error"); }); } vm.borrar = function(id){ $http({ method:'DELETE', url: vm.raiz + '/submissions/' + id, headers:{ 'Accept':'application/json' } }).success(function(){ alert("Borrado"); $location.url(vm.raiz + '/submissions') }).error(function(){ alert("Error"); }); } vm.votar = function(id){ $http({ method:'POST', url : vm.raiz + '/submissions/' + id + '/vote', data:{userid : 1}, headers:{ 'Accept': 'application/json' } }).success(function(){ alert('Votado'); $location.url(vm.raiz + '/submissions') }).error(function (data, status) { alert(data + " " + status); }) } } }());
module.exports = { reactStrictMode: true, poweredByHeader: false, i18n: { locales: ["en-US", "es-US"], defaultLocale: "en-US", }, async redirects() { return [ { source: "/signin", destination: "/api/auth/signin", permanent: true, }, ]; }, images: { domains: ["media.graphcms.com"], }, experimental: { staticPageGenerationTimeout: 600 } };
const config = require("config"); let _ENV = process.env.NODE_ENV || config.get('env') const { createLogger, format, addColors, transports } = require('winston'); const { combine, timestamp, label, printf, colorize } = format; const myFormat = printf(info => { return `${info.timestamp} [${info.label}] ${info.level}: ${info.message}`; }); const myCustomLevels = { levels: { error: 0, warn: 1, info: 2, debug: 3, }, colors: { error: 'red', warn: 'yellow', info: 'blue', debug: 'violet' } }; const logger = createLogger({ format: combine( colorize(), label({ label: _ENV }), timestamp(), myFormat ), levels: myCustomLevels.levels, transports: [new transports.Console()] }); addColors(myCustomLevels) module.exports = logger;
var visibleMenu = false; function showmenu(){ if(!visibleMenu){ document.getElementById('toolbar').style.visibility = "visible"; } else{ document.getElementById('toolbar').style.visibility = "hidden"; } visibleMenu = !visibleMenu; } function highlightCurrent(currIndex){ var navDoc = document.getElementsByTagName('nav').toolbar; for(let i=1; i<navDoc.children.length; i++){ if(currIndex == i){ navDoc.children[i].className = "current"; } else{ navDoc.children[i].className = ""; } } }
/** classe para criar um objeto com os dados do XML. [arg1] String _fileURL - Label do botão. [arg2] Function _callBack - Tipo da função a ser executada no evento clique. **/ function DataObject(_fileURL, _callBack){ this.fileURL = _fileURL; this.callBack = _callBack || function(){}; var _that = this; this.content = new Array(); this.modelEffortObj = new Object(); /** - create (construtor) Pega o xml indicado. Se sucesso: Executa a função de conversão para objeto com ele. Executa a função _callBack; **/ this.create = function() { $.ajax({ type: "GET", url: _that.fileURL, dataType: "xml", success: function(_xml){ _that.convertXML2Obj(_xml); _that.callBack(); } }); } /** - convertXML2Obj Transforma o objeto recebido do XML em objeto JS; [arg] Objeto _xml - Conteúdo do XML. // **/ this.convertXML2Obj = function(_xml) { // Sesssão $(_xml).find('section').each(function( index ) { var nodeSection = $(_xml).find('section')[index]; var nodeQuestion = $(nodeSection).find('question')[0]; var nodeButton = $(nodeSection).find('button')[0]; var nodeOptions = $(nodeSection).find('options')[0]; var curSection = _that.getNewSection(); var cs = curSection[0]; cs.name = $(nodeSection).attr('id'); cs.question = $(nodeQuestion).attr('question'); cs.description = $(nodeQuestion).attr('description'); cs.typeInput = $(nodeQuestion).attr('typeInput'); cs.button = new Object(); cs.button.name = $(nodeButton).attr('name'); cs.button.action = $(nodeButton).attr('action'); cs.button.enable = $(nodeButton).attr('enable'); // Options $(nodeOptions).find('option').each(function( optionIndex ) { var nodeOption = $(nodeOptions).find('option')[optionIndex]; var nodeSubOptions = $(nodeOption).find('suboptions')[0]; curSection[1].push(new Object()); var op = curSection[1][optionIndex]; //op.value = $(nodeOption).attr("value"); op.value = $(nodeOption).find("value").text(); op.label = $(nodeOption).attr("label"); op.description = $(nodeOption).attr("description"); if( $(nodeOption).find("price")[0] ){ var priceNode = $(nodeOption).find("price")[0]; op.price = parseInt( $(priceNode).attr("price") ); } if( $(nodeOption).find("effortPrice")[0] ){ op.effortPrice = _that.getEffortObject($(nodeOption).find("effortPrice")[0].attributes); } if( $(nodeOption).find("effort")[0] ) { op.effort = _that.getEffortObject($(nodeOption).find("effort")[0].attributes); } if( $(nodeOption).find("days")[0] ){ var daysNode = $(nodeOption).find("days")[0]; op.days = parseInt( $(daysNode).attr("days") ); } op.subOptions = new Array(); // Suboptions $(nodeSubOptions).find('suboption').each(function( subIndex ) { var nodeSubOption = $(nodeSubOptions).find('suboption')[subIndex]; op.subOptions.push(new Object()); var so = op.subOptions[subIndex]; so.type = $(nodeSubOption).attr('type'); so.label = $(nodeSubOption).attr('label'); so.choices = new Array(); $(nodeSubOption).find('choice').each(function( subChoicesIndex ) { var nodeSubOptionChoice = $(nodeSubOption).find('choice')[subChoicesIndex]; var soc = so; soc.choices.push(new Object()); soc.choices[subChoicesIndex].label = $(nodeSubOptionChoice).attr('label'); if($(nodeSubOptionChoice).attr('value') != undefined) soc.choices[subChoicesIndex].value = $(nodeSubOptionChoice).attr('value'); // console.log(soc.choices[subChoicesIndex].value); if( $(nodeSubOptionChoice).find("subprice")[0] ){ var priceNode = $(nodeSubOptionChoice).find("subprice")[0]; soc.choices[subChoicesIndex].price = parseInt( $(priceNode).attr("price") ); } if( $(nodeSubOptionChoice).find("subeffort")[0] ) { soc.choices[subChoicesIndex].effort = _that.getEffortObject( $(nodeSubOptionChoice).find("subeffort")[0].attributes ); } if( $(nodeSubOptionChoice).find("subdays")[0] ){ var daysNode = $(nodeSubOptionChoice).find("subdays")[0]; soc.choices[subChoicesIndex].days = parseInt( $(daysNode).attr("days") ); } }); }); }) }); } /** - getContent Retorna content; **/ this.getContent = function(){ return this.content; } /** - getNewSection Retorna umma array com 2 indíces. [0] com os atributos / [1] com as opções; **/ this.getNewSection = function() { var dc = _that.content; dc.push(new Array()); dc[dc.length-1].push(new Object()); dc[dc.length-1].push(new Array()); return dc[dc.length-1]; } /** - getEffortObject Retorna um objeto com os atributos do effort. **/ this.getEffortObject = function(_nodeOptionAttributes) { var _newObject = new Object(); _obj = _nodeOptionAttributes; for(var w = 0; w < _obj.length; w++){ _newObject[_obj[w].name] = parseInt( _obj[w].value ); this.modelEffortObj.price = 0; if(this.modelEffortObj[_obj[w].name] == null) this.modelEffortObj[_obj[w].name] = 0; } return _newObject; } // // // this.create(); };
import Vue from 'vue' import store from './store/index' const bus = new Vue({ data: { map: null, locationTarget: null, rightFold: false, rightMenu: 'groupList' }, methods: { initMap(currentLocation, groups) { // if(currentLocation.lat === 0 || currentLocation.lng === 0) { // currentLocation = {lat: -33.8688, lng: 151.2195} // } this.rightMenu = 'groupList' this.map = new google.maps.Map(document.getElementById('map'), { center: {lat:currentLocation.lat, lng:currentLocation.lng}, zoom: 13, mapTypeId: 'roadmap' }); this.initSearchBox(document.getElementById('pac-input')) groups.forEach((item, key)=> { this.setMarker({ lat: item.lat ,lng: item.lng }, item ) }) }, initSearchBox (input) { // Create the search box and link it to the UI element. const map = this.map const searchBox = new google.maps.places.SearchBox(input); // map.controls[google.maps.ControlPosition.TOP_LEFT].push(input); // Bias the SearchBox results towards current map's viewport. let markers = [] const bounds_changed = () => { searchBox.setBounds(map.getBounds()); } const places_changed = () => { const places = searchBox.getPlaces() if (places.length == 0) return; // Clear out the old markers. markers.forEach(marker => marker.setMap(null)) markers = []; // For each place, get the icon, name and location. const bounds = new google.maps.LatLngBounds(); places.forEach(place => { if (!place.geometry) return; const icon = { url: place.icon, size: new google.maps.Size(71, 71), origin: new google.maps.Point(0, 0), anchor: new google.maps.Point(17, 34), scaledSize: new google.maps.Size(25, 25) }; // Create a marker for each place. markers.push(new google.maps.Marker({map, icon, title: place.name, position: place.geometry.location})) if (this.locationTarget !== null) { const location = place.geometry.location this.locationTarget.$emit('getLocation', { lat: location.lat(), lng: location.lng() }) } place.geometry.viewport ? bounds.union(place.geometry.viewport) : bounds.extend(place.geometry.location) }); map.fitBounds(bounds); } map.addListener('bounds_changed', bounds_changed); searchBox.addListener('places_changed', places_changed); }, initLocation (target) { this.map.setZoom(18); this.locationTarget = target }, memberLocation(Location, data) { var $this = this this.map.setZoom(18); this.map.setCenter({lat: Location.lat, lng: Location.lng}); var marker = new google.maps.Marker({ position: Location, map: this.map, title: "hle", icon: 'http://maps.google.com/mapfiles/ms/icons/yellow.png' }); var contentString = '<div id="content">'+ '<div id="siteNotice">'+ '</div>'+ '<h3 id="firstHeading" class="firstHeading">'+data.nickname+'</h3>'+ '<div id="bodyContent">'+ '<p>'+data.place+'</p>'+ '</div>'+ '</div>'; var infowindow = new google.maps.InfoWindow({ content: contentString }); marker.addListener('mouseover', function() { infowindow.open($this.map, marker); }); marker.addListener('mouseout', function() { infowindow.close($this.map, marker); }); }, setLocation(Location) { if(Location.lat === 0 || Location.lng === 0) { alert('지도에 등록된 그룹이 아닙니다.') return } this.map.setZoom(18); this.map.setCenter({lat: Location.lat, lng: Location.lng}); }, setMarker(Location, data) { if(Location.lat === 0 || Location.lng === 0) { return } var $this = this var marker = new google.maps.Marker({ position: Location, map: this.map, title: "hle", icon: 'http://maps.google.com/mapfiles/ms/icons/orange-dot.png' }); var contentString = '<div id="content">'+ '<div id="siteNotice">'+ '</div>'+ '<h3 id="firstHeading" class="firstHeading">'+data.name+'</h3>'+ '<div id="bodyContent">'+ '<p>'+data.place+'</p>'+ '</div>'+ '</div>'; var infowindow = new google.maps.InfoWindow({ content: contentString }); marker.addListener('mouseover', function() { infowindow.open($this.map, marker); }); marker.addListener('mouseout', function() { infowindow.close($this.map, marker); }); // console.log($this.rightFold) marker.addListener('click', async () => { store.dispatch('getGroupInfo', { cgidx: data.cgidx }) store.dispatch('getGroupMemberRelation', {commit: 'getGroupMemberRelation'}) this.rightMenu = 'groupInfo' this.rightFold = true }); }, } }) export default bus
/** * Res is a resource manager ,you can define images,fonts ,sound's name and path * When game init , the resource which define in Res will load first */ var Res = { "images":[ {"src":"../public/resource/background.png","name":"background"},//背景图片 {"src":"../public/resource/fighter_hero.png","name":"fighter_hero"}, {"src":"../public/resource/enemy_turn_button.png","name":"enemy_turn_button"}, {"src":"../public/resource/fishman_baby.png","name":"fishman_baby"}, {"src":"../public/resource/freshwater_crocodile.png","name":"freshwater_crocodile"}, {"src":"../public/resource/ogre.png","name":"ogre"}, {"src":"../public/resource/1.jpg","name":"1"}, {"src":"../public/resource/2.jpg","name":"2"}, {"src":"../public/resource/3.jpg","name":"3"}, {"src":"../public/resource/4.jpg","name":"4"}, {"src":"../public/resource/5.jpg","name":"5"} ], "fonts":[], "sound":[] };
$(document).ready(function() { $('.tab__item').click(function() { var tab_id = $(this).attr('data-tab'); $('.tab__item').removeClass('tab__item_active'); $('.tab-content').removeClass('tab-content_active fade'); $(this).addClass('tab__item_active'); if ($(this).attr('id') == 'first') { $(this).addClass('tab__item_bank_active').removeClass('tab__item_bank'); $('#second').removeClass('tab__item_interac_active').addClass('tab__item_interac'); $('#third').removeClass('tab__item_card_active').addClass('tab__item_card'); } else if ($(this).attr('id') == 'second') { $(this).addClass('tab__item_interac_active').removeClass('tab__item_interac'); $('#first').removeClass('tab__item_bank_active').addClass('tab__item_bank'); $('#third').removeClass('tab__item_card_active').addClass('tab__item_card'); } else if ($(this).attr('id') == 'third') { $(this).addClass('tab__item_card_active').removeClass('tab__item_card'); $('#first').removeClass('tab__item_bank_active').addClass('tab__item_bank'); $('#second').removeClass('tab__item_interac_active').addClass('tab__item_interac'); } $('#' + tab_id).addClass('tab-content_active fade'); }); });
v = 45; alert(v); function sayHello(o) { document.write("姓名:" + o.name + " " + "年龄:" + o.age + "</br>"); } var obj = new Object(); obj.name = "zhuzhi"; obj.age = 20; sayHello(obj); function fun(a) { console.log("a=" + a); //a(obj); } //函数参数也可以是函数 fun(sayHello); fun(function () { alert("Hello") }); //函数返回值可以是任意数据类型,甚至是一个函数 function fun3() { function fun4() { alert("我是fun4"); return 3; } return fun4(); } var a = fun3(); alert(a); a(); (function () { alert("我是立即执行函数"); })();
import { useRef } from "react"; import { debounce } from "call-func"; const useDebounce = (func, defaultDelay, scope) => { const _debounce = useRef(); if (!_debounce.current) { _debounce.current = debounce(func, defaultDelay); } return (...args) => _debounce.current({ scope, args }); }; export default useDebounce;
import { BehaviorSubject } from "rxjs"; export const token$ = new BehaviorSubject(localStorage.getItem("token")); //skapar nytt storage med värdet som finns i localStorage, skapar en observable som vi sparar i vår token$. skapar en ny instans med nyckelordet new. //funktion uppdaterar vårt storage med vårt nya token, detta är en action. export function updateToken(token) { if (token) { localStorage.setItem("token", token); } else { localStorage.removeItem("token"); } token$.next(token); //uppdaterar värdet med next } /*------ COMMENTS ------*/ // getitem = hämtar // setItem = lokala minnet, för att inte behöva logga in hela tiden // removeItem = tar bort token från lokala minnet // token$ = variabeln som blir instansen, är en Observable // token = (kan heta vad som helst) det långa lösenordet vi får ifrån servern
import React, {useState} from 'react'; import PropTypes from 'prop-types'; import Panel from '@vkontakte/vkui/dist/components/Panel/Panel'; import PanelHeader from '@vkontakte/vkui/dist/components/PanelHeader/PanelHeader'; import Button from '@vkontakte/vkui/dist/components/Button/Button'; import Group from '@vkontakte/vkui/dist/components/Group/Group'; import Div from '@vkontakte/vkui/dist/components/Div/Div'; import { ReactComponent as YourSvg } from '../svg/samara.svg'; const Start = ({id}) => ( <Panel id={id}> <PanelHeader>Самара</PanelHeader> <Group title="Navigation Example"> <Div> <YourSvg/> </Div> </Group> </Panel> ); export default Start;
#!/usr/bin/env node import args from 'args' import micro from 'micro-core' import { resolve } from 'path' // babel import preset2015 from 'babel-preset-es2015' import transformAsync from 'babel-plugin-transform-async-to-generator' import transformRuntime from 'babel-plugin-transform-runtime' import alias from 'babel-plugin-module-alias' args .option(['p', 'port'], 'Port to listen on', 3000, parseInt) .option(['H', 'host'], 'Host to listen on', '0.0.0.0') .option(['n', 'no-babel'], 'Skip Babel transformation') const flags = args.parse(process.argv) let file = args.sub.pop() if (!file) { try { let packageJson = require(resolve(process.cwd(), 'package.json')) file = packageJson.main } catch (e) { if ('MODULE_NOT_FOUND' !== e.code) { console.error(`> \u001b[31mError!\u001b[39m ${e.message}`) process.exit(1) } } } if (!file) { console.error(`\n> \u001b[31mError!\u001b[39m Please supply a file.`) args.showHelp() process.exit(1) } if ('/' !== file[0]) { file = resolve(process.cwd(), file) } if (!flags.noBabel) { // FIXME: is there a better way to point the `babel-runtime` // to the runtime contained in the micro installation? const path = require.resolve('babel-runtime/package') .replace(/[\\\/]package.json$/, '') require('babel-register')({ presets: [preset2015], plugins: [ transformAsync, transformRuntime, [alias, [ { src: path, expose: 'babel-runtime' } ]] ] }) } let mod try { mod = require(file).default } catch (e) { if ('MODULE_NOT_FOUND' === e.code) { console.error(`> \u001b[31mError!\u001b[39m "${file}" does not exist.`) } else { console.error(`> \u001b[31mError!\u001b[39m ${e.message}`) } process.exit(1) } if ('function' !== typeof mod) { console.error(`> \u001b[31mError!\u001b[39m "${file}" does not export a function.`) process.exit(1) } const port = flags.port || 3000 const host = flags.host || '0.0.0.0' micro(mod).listen(port, host, (err) => { if (err) { console.error(err.stack) process.exit(1) } console.log(`> \u001b[96mReady!\u001b[39m Listening on ${host}:${port}.`) }) // TODO: test listen error // add success message
const { prompt } = require("enquirer"); const tymlogger = require("tymlogger"); const fs = require("fs"); const path = require("path"); const log = new tymlogger(); let projectJSONTemplate = require("./template/project.template"); const { stringify } = require("querystring"); let GAME_NAME = ""; let EMULATOR_PATH = ""; function InitElizabethProject () { let GAME_PATH = path.resolve(process.cwd(), GAME_NAME); let PROJECT_JSON_PATH = path.resolve(GAME_PATH, "Project.json"); let CODE_DIRECTORY = path.resolve(GAME_PATH, "Code"); let RESOURCES_DIRECTORY = path.resolve(GAME_PATH, "Resources"); let JOYHANDLER_PATH = path.resolve(GAME_PATH, "Code", "JoyHandler.c"); let SPLASH_PATH = path.resolve(GAME_PATH, "Resources", "SplashScreen.png"); let JOYHANDLER_TEMPLATE = path.resolve(__dirname, "template", "joyhandler.template.c"); let SPLASH_TEMPLATE = path.resolve(__dirname, "template", "splash.template.png"); log.write("Create Directory..."); fs.mkdirSync(GAME_PATH); log.write("Create Project.json..."); projectJSONTemplate.name = GAME_NAME; projectJSONTemplate.emulator = EMULATOR_PATH; const rawData = JSON.stringify(projectJSONTemplate); fs.writeFileSync(PROJECT_JSON_PATH, rawData); log.write("Create Code/ Directory..."); fs.mkdirSync(CODE_DIRECTORY); let codeFile = fs.readFileSync(JOYHANDLER_TEMPLATE); fs.writeFileSync(JOYHANDLER_PATH, codeFile); log.write("Create Resources/ Directory..."); fs.mkdirSync(RESOURCES_DIRECTORY); let splashFile = fs.readFileSync(SPLASH_TEMPLATE); fs.writeFileSync(SPLASH_PATH, splashFile); log.success("Done!"); } module.exports = function () { log.success("Elizabeth CLI v" + require("../package.json").version); log.write("==========================================="); log.write("Init new project"); prompt( { type: "input", name: "gameName", message: "Game name" } ).then(response => { GAME_NAME = response.gameName; prompt( { type: "input", name: "emulatorpath", message: "Emulator path" } ).then(response => { EMULATOR_PATH = response.emulatorpath; prompt( { type: "confirm", name: "confirmed", message: "Done?" } ).then(response => { if (response.confirmed) { InitElizabethProject(); } else { log.write("Quit..."); process.exit(); } }); }); }); }
$(document).ready(function() { // remove bounce animation when hover $(".fa-arrow-down").mouseenter( function() { $("#arrow-down").removeClass("bounce"); }).mouseleave( function() { $("#arrow-down").addClass("bounce"); }); // hide / show nav bar depending on window location var old_position; $(window).scroll(function() { // hide if position > 120 var current_position = $(this).scrollTop(); if (current_position < 100) { $('.navbar').show(); } else { // show if scrolling up if (current_position < old_position) { $('.navbar').fadeIn(); } else { $('.navbar').fadeOut(); } } // save old position old_position = current_position; }); // add pulse animation when mouse on arrow $(".placeholder").mouseenter( function() { $(this).addClass("animated pulse"); }).mouseleave( function() { $(this).removeClass("animated pulse"); }); function scroll_function(obj) { var href = $(obj).attr('href'); console.log(href); $('html,body').animate({ scrollTop: $(href).offset().top }, 'slow'); return false; } // scrolling when clicking on navbar buttons and arrow $(".navbar-left > li, #arrow-down").children().click(function(){ return scroll_function(this); } ); });
#!/usr/bin node // // External Dependencies // import express from 'express'; import bodyParser from 'body-parser'; // // Project Dependencies // const low = require('lowdb') const FileAsync = require('lowdb/adapters/FileAsync') // Create non-blocking database instance and start server const adapter = new FileAsync('db/tables.json'); var app = express(); app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); // ================= // Helper Methods // // ================= const setDefaultHeaders = response => { // Manage CORS to accept the preflight Options request (in case the UI ever runs on a remote server) response.header("Access-Control-Allow-Origin", "*"); response.header("Access-Control-Allow-Methods", "OPTIONS, GET"); response.header("Access-Control-Allow-Headers", "Origin, Content-Type, Access-Control-Request-Headers, Access-Control-Request-Method") return response; } const handleSingleBookingGET = (request, response, next) => { const requestedBooking = request.db.get('bookings') .find({ roomNumber: request.params.roomNumber }) .value(); console.log('Fetched Booking:') console.log(requestedBooking) if (!requestedBooking) { return response.status(404).send(`Error: Booking of roomNumber ${request.params.roomNumber} could not be found`); } else { return response.status(200).send(requestedBooking); } } const errorHandler = (err, req, res, _next) => { res.status(500).send({ error: 'Internal Server error' }); console.log('Internal Server error', err) // All logs will be stored in /var/log/messages in PRODUCTION } // ======================== // END of Helper Methods // // ======================== low(adapter) .then(db => { // Reset DB to default bookings //db.setState(default_bookings) //db.write() app.use((req, res, next) => { res = setDefaultHeaders(res); // Inject DB into request object req.db = db; next(); }); app.get("/provisioning/bookings/:roomNumber", handleSingleBookingGET); app.use(errorHandler); const port = 8000; const listener = app.listen(port, function () { console.log('Express HTTP server listening on port ' + listener.address().port); }); }) .catch((error) => { // TODO: In production we would raise an alarm here in order to call out ASG support to look at service recovery console.log(error) }); module.exports = app;
/** * 文件读取 */ var fs = require('fs'); // 读取文件 fs.readFile('f:/a.txt', function (err, data) { if (err) { return console.log('文件读取失败'); } // 因为计算机中所有的数据最终保存的都是二进制数据 // 所以可以通过调用toString()方法将二进制数据转换为人类可以识别的字符 console.log(data.toString()); });
/// /// basicAnimation.js /// /// Basic animation example. /// function draw(canvas) { helper.clear(canvas) // Clear canvas and set size var text = "Hello World"; var ctx=canvas[0].getContext("2d"); var x = 0; ctx.strokeStyle = "1px #FF0000"; helper.setupAnimation(); (function animloop(){ requestAnimFrame(animloop); helper.clear(canvas,"#FFFFFF",true); x += canvas.width() / 100; ctx.fillRect(x % canvas.width(), x % canvas.height(), canvas.width()/5, canvas.height()/5); })(); }
let tournmentController = require('./tournment'); module.exports = [ { path: '/', method: 'post', allUsers: true, controller: tournmentController.createTournment }, { path: '/:id/get-tournment', method: 'get', public: true, controller: tournmentController.getTournmentById }, { path: '/get-tournments', method: 'get', public: true, controller: tournmentController.getTournments }, { path: '/:id/edit', method: 'put', allUsers: true, controller: tournmentController.editTournment }, { path: '/:id/delete-tournment', method: 'delete', allUsers: true, controller: tournmentController.deleteTournment }, { path: '/:id/enable-disable-tournment', method: 'put', allUsers: true, controller: tournmentController.enableDisableTournment }, ]
(function($) { var main = { initialize: function () { main.objectFit(); main.callFitVid(); main.modal(); main.contentTabs(); main.neighborhoodDropDown(); main.neighborhoodMap(); main.mobileNav(); main.headerSearch(); main.select2(); main.booking(); main.footer(); main.elementInView(); main.businessListingsJSON(); main.maps(); main.shareThis(); main.videoPlayer(); }, //--------------------------------------------------------------------------------------------- // Initialize objectfit //--------------------------------------------------------------------------------------------- objectFit: function() { if ( ! Modernizr.objectfit ) { $('.object-fit').each(function () { var src = jQuery(this).attr('src'); jQuery(this).parent().css({ "background-image" : "url('" + src + "')", "background-size" : "cover", "background-position": "center center" }); jQuery(this).css({ "opacity" : "0" }); }); } }, //--------------------------------------------------------------------------------------------- // IF FITVID EXISTS, CALL FITVID TO MAKE RESPONSIVE //--------------------------------------------------------------------------------------------- callFitVid: function() { if($('.fitvid').length > 0) { $('.fitvid').fitVids(); } }, //--------------------------------------------------------------------------------------------- // MODAL JS //--------------------------------------------------------------------------------------------- modal: function() { $( '*[data-dismiss="modal"]' ).click(function() { $('.modal').modal('hide') }); //For each element that has a data-wrapper="modal" attrib $( '*[data-wrapper="modal"]' ).each(function() { //Get the value stored in the data-id attribute var dataID = $(this).attr("data-id"); //And then, wrap some html around it and use that value as a class and ID for the modal div $( this ).wrap( '<div class="modal ' + dataID + ' fade" id="' + dataID + '" role="dialog" aria-hidden="true"><div class="modal-dialog"><div class="modal-content"></div></div></div>' ); }); $('.modal').each(function() { $(this).prepend('<div class="modal-close" data-dismiss="modal"></div>'); }); }, //--------------------------------------------------------------------------------------------- // CONTENT TABS //--------------------------------------------------------------------------------------------- contentTabs: function() { $('.content-tabs .content-tabs--link').click(function(){ var tab_id = $(this).attr('data-tab'); $('.content-tabs .content-tabs--link').removeClass('current'); $('.content-tabs--content').removeClass('current'); $(this).addClass('current'); $('[data-content="'+tab_id+'"]').addClass('current'); }) }, //--------------------------------------------------------------------------------------------- // NAVIGATION - NEIGHBORHOOD DROPDOWN //--------------------------------------------------------------------------------------------- neighborhoodDropDown: function() { function neighborhoodDropDown() { $('.navigation--dropdown__neighborhoods').each(function() { var headerWidth = $('.header--block').outerWidth(); var headerOffset = $('.header--block').offset(); var ddOffset = $('.header .navigation--primary').offset(); var ddLeft = ((ddOffset.left - headerOffset.left) * -1); $('.navigation--dropdown__neighborhoods').css('width', headerWidth).css('left', ddLeft + 'px'); }); }; $(window).load(function () { neighborhoodDropDown(); }).resize(function () { neighborhoodDropDown(); }); }, //--------------------------------------------------------------------------------------------- // NAVIGATION - NEIGHBORHOOD MAP //--------------------------------------------------------------------------------------------- neighborhoodMap: function() { $(".menu-neighborhood--nav > ul > .navigation--primary--subitem").hover(function () { var hoverClass = $(this).children('a').attr('class'); $('.menu-neighborhood--map').toggleClass(hoverClass); }); }, //--------------------------------------------------------------------------------------------- // NAVIGATION - MOBILE NAV //--------------------------------------------------------------------------------------------- mobileNav: function() { //Build the nav container $('body').append('<nav class="mobile-nav"></nav>'); //Inject a close button $('.mobile-nav').append('<button class="mobile-nav--close"></button>'); //Inject the desktop navs inside the container $('.header .language-selector').clone().appendTo('.mobile-nav'); $('.header--toolbox .btn--booking').clone().appendTo('.mobile-nav'); $('.mobile-nav').append('<div class="navigation--secondary--mobile">' + $('.header .navigation--secondary--selector').html() + '</div>'); $('.mobile-nav').append('<div class="navigation--primary--mobile">' + $('.header .navigation--primary').html() + '</div>'); $('.header .utility-links').clone().appendTo('.mobile-nav'); //Remove the superflous dropdown data, just because it's kinda messy and unneeded $('.mobile-nav .navigation--dropdown').remove(); //Trigger the nav open $(".mobile-nav--trigger, .mobile-nav--close").click(function () { $('.mobile-nav').toggleClass('open'); }); $('.mobile-nav .btn--booking').click(function(){ window.location = $(this).attr('data-link'); }); }, //--------------------------------------------------------------------------------------------- // HEADER SEARCH //--------------------------------------------------------------------------------------------- headerSearch: function() { function headerSearchWidth() { var viewportWidth = $(window).outerWidth(); var rowWidth = $('.header--row').outerWidth(); var toolboxWidth = $('.header--toolbox').outerWidth(); enquire.register("screen and (max-width:767px)", { match : function() { $('.header .header--search').css('width', (viewportWidth - (15 * 2))); //gutters }, unmatch : function() { //$('.header .header--search').css('width', ''); } }); enquire.register("screen and (min-width:768px)", { match : function() { $('.header .header--search').css('width', ((rowWidth - toolboxWidth) + 46)); //46 is the width of the trigger button }, unmatch : function() { $('.header .header--search').css('width', ''); } }); } $(window).load(function () { headerSearchWidth(); }).resize(function () { headerSearchWidth(); }); $('.header--search--trigger, .header--search--close').click(function() { $('.header').toggleClass('search-open'); }); }, //--------------------------------------------------------------------------------------------- // BOOKING //--------------------------------------------------------------------------------------------- booking: function() { $(".btn--booking").click(function () { $('.booking-widget').toggleClass('open'); }) }, //--------------------------------------------------------------------------------------------- // SELECT2 - JQUERY SELECT FIELD REPLACEMENT //--------------------------------------------------------------------------------------------- select2: function() { $('select').select2({ minimumResultsForSearch: Infinity }); }, //--------------------------------------------------------------------------------------------- // FOOTER //--------------------------------------------------------------------------------------------- footer: function() { var $animation_elements = $('.footer'); var $window = $(window); function check_if_in_view() { var window_height = $window.height(); var window_top_position = $window.scrollTop(); var window_bottom_position = (window_top_position + window_height); $.each($animation_elements, function() { var $element = $(this); var element_height = $element.outerHeight(); var element_top_position = $element.offset().top + 64; var element_bottom_position = (element_top_position + element_height); //check to see if this current container is within viewport if ((element_bottom_position >= window_top_position) && (element_top_position <= window_bottom_position)) { $element.addClass('in-view'); } if (element_top_position > window_bottom_position) { $element.removeClass('in-view'); } }); } $window.on('scroll resize', check_if_in_view); $window.trigger('scroll'); }, //--------------------------------------------------------------------------------------------- // ELEMENT IN VIEW //--------------------------------------------------------------------------------------------- elementInView: function() { var $animation_elements = $('.business-listings'); var $window = $(window); function check_if_in_view() { var window_height = $window.height(); var window_top_position = $window.scrollTop(); var window_bottom_position = (window_top_position + window_height); $.each($animation_elements, function() { var $element = $(this); var element_height = $element.outerHeight(); var element_top_position = $element.offset().top; var element_bottom_position = (element_top_position + element_height); //check to see if this current container is within viewport if ((element_bottom_position >= window_top_position) && (element_top_position <= window_bottom_position)) { $element.addClass('in-view'); } if (element_top_position > window_bottom_position) { $element.removeClass('in-view'); } if (element_bottom_position < window_top_position) { $element.removeClass('in-view'); } //check to see if container is below viewport if (element_top_position >= window_bottom_position) { $element.addClass('below-view'); } if (element_top_position < window_bottom_position) { $element.removeClass('below-view'); } //check to see if container is above viewport if (element_bottom_position <= window_top_position) { $element.addClass('above-view'); } if (element_bottom_position > window_top_position) { $element.removeClass('above-view'); } //check to see if container top is in viewport if ((element_top_position >= window_top_position) && (element_top_position <= window_bottom_position)) { $element.addClass('top-in-view'); } if (element_top_position < window_top_position) { $element.removeClass('top-in-view'); } //check to see if container bottom is in viewport if ((element_bottom_position >= window_top_position) && (element_bottom_position <= window_bottom_position)) { $element.addClass('bottom-in-view'); } if ((element_bottom_position > window_bottom_position) || (element_bottom_position < window_top_position)){ $element.removeClass('bottom-in-view'); } }); } $window.on('scroll resize ready', check_if_in_view); $window.trigger('scroll'); }, //--------------------------------------------------------------------------------------------- // BUILD THE BUSINESS LISTINGS JSON //--------------------------------------------------------------------------------------------- businessListingsJSON: function() { if ($('.business-listings').length > 0){ //Build the Business Listings JSON for Google Maps var blRun = 1; if (typeof locations === 'undefined') { window.locations = []; } $('.business-listings--item').each(function() { var blTitle = $(this).find('.business-listings--item--title').text(), blLat = $(this).attr('data-lat'), blLong = $(this).attr('data-long'), blMarker = 'pin-teal-star'; window.locations.push([eval(blRun), blTitle, blLat, blLong, blMarker]); blRun++; }); } }, //--------------------------------------------------------------------------------------------- // MAPS //--------------------------------------------------------------------------------------------- maps: function() { if (typeof locations === 'undefined') { var locations = window.locations; } if ($("#map").length > 0){ window.map = new google.maps.Map(document.getElementById('map'), { mapTypeId: google.maps.MapTypeId.ROADMAP, styles: [ { "featureType": "landscape.natural", "elementType": "geometry.fill", "stylers": [ { "visibility": "on" }, { "color": "#e0efef" } ] }, { "featureType": "poi", "elementType": "geometry.fill", "stylers": [ { "visibility": "on" }, { "color": "#bedcdf" } ] }, { "featureType": "road", "elementType": "geometry", "stylers": [ { "lightness": 100 }, { "visibility": "simplified" } ] }, { "featureType": "road", "elementType": "labels", "stylers": [ { "visibility": "off" } ] }, { "featureType": "transit.line", "elementType": "geometry", "stylers": [ { "visibility": "on" }, { "lightness": 700 } ] }, { "featureType": "water", "elementType": "all", "stylers": [ { "color": "#80aaad" } ] } ] }); //var infowindow = new google.maps.InfoWindow(); var bounds = new google.maps.LatLngBounds(); var infobox = []; //Build the infobox container $('body').append('<div class="infobox-wrapper"></div>'); for (i = 0; i < locations.length; i++) { marker = new google.maps.Marker({ position: new google.maps.LatLng(locations[i][2], locations[i][3]), map: map, icon: '/sites/all/themes/custom/washington/media/images/map-markers/'+locations[i][4]+'.png', markerid: locations[i][0], }); bounds.extend(marker.position); //Add the actual infobox $('.infobox-wrapper').append('<div id="infobox-'+locations[i][0]+'" class="infobox">'+locations[i][1]+'</div>'); infobox.push(new InfoBox({ content: document.getElementById("infobox-" + locations[i][0]), disableAutoPan: false, maxWidth: 150, pixelOffset: new google.maps.Size(-140, -60), alignBottom: true, zIndex: null, boxStyle: { opacity: 1, width: "280px" }, //closeBoxMargin: "12px 4px 2px 2px", closeBoxURL: '', infoBoxClearance: new google.maps.Size(1, 1) })); google.maps.event.addListener(marker, 'click', function() { var curMarker = this, thisID = this.markerid; //Close the infoboxes that don't match $.each(infobox, function(i, e) { if(e !== curMarker) { e.close(); } }); infobox[thisID].open(map, this); }); } map.fitBounds(bounds); var listener = google.maps.event.addListener(map, "idle", function () { //map.setZoom(14); google.maps.event.removeListener(listener); }); } }, //--------------------------------------------------------------------------------------------- // SHARE THIS //--------------------------------------------------------------------------------------------- shareThis: function() { if ($(".sharethis").length > 0){ var documentURL = window.location.href, documentTitle = encodeURIComponent(document.title); $('.sharethis').html(''+ '<ul class="sharethis--networks rrssb-buttons clearfix">'+ '<li class="rrssb-facebook"><a href="https://www.facebook.com/sharer/sharer.php?u='+documentURL+'" class="sharethis--facebook popup"></a>'+ '</li>'+ '<li class="rrssb-twitter"><a href="https://twitter.com/intent/tweet?text='+documentTitle+encodeURIComponent(' | ')+documentURL+'" class="sharethis--twitter popup"></a></li>'+ '<li class="rrssb-pinterest"><a href="http://pinterest.com/pin/create/button/?url='+documentURL+'" class="sharethis--pinterest popup"></a></li>'+ '</ul>'); } $('.sharethis').click(function() { $(this).addClass('open'); }); }, //--------------------------------------------------------------------------------------------- // VIDEO PLAYER //--------------------------------------------------------------------------------------------- videoPlayer: function() { var fbVideoInt = 0; $('.videoplayer').each(function() { //For each instance of video player //If it happens to be facebook if ($(this).data('source') == 'facebook') { //Let's set the video width at 75% of viewport. This may not be ideal on smaller devices. Let's come back to this later. var videoWidth = Math.ceil($(window).width() * .75); //Establish the unique ID var fbID = "fb-video--" + fbVideoInt; //Inject the container div into the page $('body').append('<div style="position: absolute; transform:translateX(-9000px) translateY(-9000px);"><div id="' + fbID + '"><div class="fb-video" data-href="' + $(this).data('video') +'" data-width="' + videoWidth + '" data-allowfullscreen="true" data-autoplay="true"></div></div></div>'); //Update the trigger href to the unique ID $(this).attr('href', '#' + fbID); } }); $('.videoplayer').fancybox({ openEffect : 'none', closeEffect : 'none', helpers : { media : {} }, afterClose : function() { if ($(this.element).data('source') == 'facebook') { $($(this.element).attr('href')).css('display', 'block'); FB.XFBML.parse(); } } }); } } $(document).ready(main.initialize); }(jQuery));
import React from "react"; import { asEditorWidget } from "@episerver/react-to-dijit-adapter"; import StringStatistics from "../Util/StringStatistics"; const TextAreaWithStatistics = ({ onChange, value }) => { const result = StringStatistics(value); return ( <> <textarea className="dijitTextBox dijitTextArea" onChange={(e) => onChange(e.target.value)} value={value} style={{ width: "600px" }}/> <div style={{ fontSize: "12px", color: "#333" }}>characters: {result.characters}, words: {result.words}, paragraphs: {result.paragraphs}</div> </> ); }; export default asEditorWidget(TextAreaWithStatistics);
import React, { useState, useContext, useEffect } from 'react'; import { Text, View, TouchableOpacity, SafeAreaView } from 'react-native'; import { FontAwesome as Icon } from '@expo/vector-icons/'; import Slider from 'react-native-slider'; import styles from "../../styles/trackStyles"; import { ColorContext } from '../../functions/providers/ColorContext'; import { UserContext } from '../../functions/providers/UserContext'; import dayjs from "dayjs"; import utc from "dayjs/plugin/utc"; dayjs.extend(utc); const now = dayjs().local().format('DDMMYYYY'); // console.log('Current timestamp: ', now); export default function Track(props) { const { navigation } = props; const { color } = useContext(ColorContext); const { userID, moods, createMood, updateMood } = useContext(UserContext); // console.log('Existing timestamp:', dayjs(mood.moodID.timeCreated).format('DDMMYYYY')); // .filter or .reduce for mood array, for loop in one line const [created, setCreated] = useState(false); const [anxiety, setAnxiety] = useState(5); const [anxietyView, setAnxietyView] = useState(.5); const [energy, setEnergy] = useState(5); const [energyView, setEnergyView] = useState(.5); const [activity, setActivity] = useState(5); const [activityView, setActivityView] = useState(.5); const [stress, setStress] = useState(5); const [stressView, setStressView] = useState(.5); useEffect(() => { if ( moods.length != 0 && now == dayjs(moods[moods.length-1].timeCreated).format('DDMMYYYY') ) { setCreated(true); setAnxiety(moods[moods.length-1].anxiety); setAnxietyView(moods[moods.length-1].anxiety / 10); setEnergy(moods[moods.length-1].energy); setEnergyView(moods[moods.length-1].energy / 10); setActivity(moods[moods.length-1].activity); setActivityView(moods[moods.length-1].activity / 10); setStress(moods[moods.length-1].stress); setStressView(moods[moods.length-1].stress / 10); } }, []) const submit = () => { if (created) { updateMood(userID, moods[moods.length-1].id, anxiety, energy, activity, stress, () => { }); } else { createMood(userID, anxiety, energy, activity, stress, () => { }); } navigation.goBack() }; return ( <View style={{ ...styles.container, backgroundColor: color.background }} > <Header navigation={navigation} /> <View style={{ width: '90%', justifyContent: 'center' }}> <View style={{ ...styles.sliderspace, backgroundColor: color.backgrounds }} > <Text style={{ fontSize: 20, marginBottom: 10 }}> Anxiety </Text> <View> <Slider value={anxietyView} onValueChange={(val) => { setAnxiety(Math.round(val * 100) / 10); setAnxietyView(val); }} thumbStyle={{ height: 40, width: 40, borderRadius: 20, backgroundColor: color.highlight }} minimumTrackTintColor={color.primaryText} maximumTrackTintColor={color.primary} /> </View> </View> <View style={{ ...styles.sliderspace, backgroundColor: color.backgrounds }} > <Text style={{ fontSize: 20, marginBottom: 10 }}> Energy </Text> <View> <Slider value={energyView} onValueChange={(val) => { setEnergy(Math.round(val * 100) / 10); setEnergyView(val); }} thumbStyle={{ height: 40, width: 40, borderRadius: 20, backgroundColor: color.highlight }} minimumTrackTintColor={color.primaryText} maximumTrackTintColor={color.primary} /> </View> </View> <View style={{ ...styles.sliderspace, backgroundColor: color.backgrounds }} > <Text style={{ fontSize: 20, marginBottom: 10 }}> Activity </Text> <View> <Slider value={activityView} onValueChange={(val) => { setActivity(Math.round(val * 100) / 10); setActivityView(val); }} thumbStyle={{ height: 40, width: 40, borderRadius: 20, backgroundColor: color.highlight }} minimumTrackTintColor={color.primaryText} maximumTrackTintColor={color.primary} /> </View> </View> <View style={{ ...styles.sliderspace, backgroundColor: color.backgrounds }} > <Text style={{ fontSize: 20, marginBottom: 10 }}> Stress </Text> <View> <Slider value={stressView} onValueChange={(val) => { setStress(Math.round(val * 100) / 10); setStressView(val); }} thumbStyle={{ height: 40, width: 40, borderRadius: 20, backgroundColor: color.highlight }} minimumTrackTintColor={color.primaryText} maximumTrackTintColor={color.primary} /> </View> </View> </View> <TouchableOpacity onPress={() => { submit() }} style={{ ...styles.button, backgroundColor: color.primary }} > <Text style={{ fontSize: 20, color: color.inactive }} > Complete </Text> </TouchableOpacity> </View> ); } const Header = (props) => { const { navigation } = props; const { color } = useContext(ColorContext); return ( <View style={{ backgroundColor: color.primary, width: '100%' }}> <SafeAreaView> <View style={{ ...styles.header, backgroundColor: color.primary }} > <TouchableOpacity style={{ position: 'relative', left: 5 }} onPress={() => navigation.goBack()} > <Icon name="chevron-left" color={color.primaryText} size={28} /> </TouchableOpacity> <Text style={styles.headerText}>Mood Tracker</Text> </View> </SafeAreaView> </View> ); };
function solve(arr, str) { if (str === 'asc') { return arr.sort((a,b)=>a-b); } else if (str === 'desc') { return arr.sort((a, b) => b - a); } } console.log(solve([3,1,2,10],'asc'));
import React from 'react' import { Route, Routes } from 'react-router-dom' import LoginCreate from './LoginCreate' import LoginForm from './LoginForm' import LoginPasswordLost from './LoginPasswordLost' import LoginPasswordReset from './LoginPasswordReset' function Login() { return ( <Routes> <Route path="/" element={<LoginForm/>}/> <Route path="/criar" element={<LoginCreate/>}/> <Route path="/perdeu" element={<LoginPasswordLost/>}/> <Route path="/resetar" element={<LoginPasswordReset/>}/> </Routes> ) } export default Login
import { Button } from '@material-ui/core' import React from 'react' import './Login.css' import {auth, provider} from './firebase.js' import { useStateValue } from './StateProvider' import {actionTypes} from './reducer' function Login() { //useStateValue const [state, dispatch] = useStateValue() const login = ()=>{ //login... auth.signInWithPopup(provider) .then(result =>{ // console.log(result.user.email)------------------------ login detail dispatch({ type:actionTypes.SET_USER, user: result.user }) }) .catch(error => alert(error.message)) } return ( <div className='login'> <div className="login__image"> <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/0/05/Facebook_Logo_%282019%29.png/600px-Facebook_Logo_%282019%29.png" alt=""/> <img src="https://www.logo.wine/a/logo/Facebook/Facebook-Logo.wine.svg" alt=""/> </div> <Button onClick={login}>Login</Button> </div> ) } export default Login
import React, { useState } from "react"; import { NavLink } from "react-router-dom"; import { toolTip, toolTipCopy } from "../../app/app-helpers"; import { useProfileState } from "../profile-context"; import { useAuthState } from "../../auth/auth-context"; import TablePaginator from "../../app/components/TablePaginator"; import ReactGA from "react-ga"; export default function ObservationsTable() { const { userAddress } = useAuthState(); const { profileData } = useProfileState(); const [range, setRange] = useState({ start: 0, end: 10 }); const renderYourObservationsRows = () => { const { start, end } = range; const rangeData = profileData.observation_history.slice(start, end); return rangeData.map(observation => ( <tr key={profileData.observation_history.indexOf(observation)} className="table__body-row" > <td className="table__table-data">{observation.observation_time}</td> <td className="table__table-data"> <NavLink className="app__nav-link" to={`/object/${observation.object_norad_number}`} > {toolTip(observation.object_name, observation.object_norad_number)} </NavLink> </td> <td className="table__table-data"> {observation.observation_position_error ? observation.observation_position_error.toString().substring(0, 5) : null} </td> <td className="table__table-data"> {observation.observation_time_difference ? observation.observation_time_difference.toString().substring(0, 5) : null} </td> <td className="table__table-data app__hide-on-mobile"> {observation.observation_cross_track_error} </td> <td className="table__table-data"> {/* {observation.observation_weight ? observation.observation_weight.toString().substring(0, 5) : null} */} TBD </td> </tr> )); }; return profileData.observation_history ? ( <section className="profile__your-observations-wrapper"> <h2 className="profile__sub-heading"> {userAddress === profileData.user_address ? "YOUR OBSERVATIONS" : "OBSERVATIONS"} </h2> {profileData.observation_history.length !== 0 ? ( <table className="table"> <thead className="table__header"> <tr> <td className="table__header-text"> {toolTip("DATE", toolTipCopy.date)} </td> <td className="table__header-text"> {toolTip("OBJECT", toolTipCopy.object)} </td> <td className="table__header-text"> <div className="app__hide-on-mobile"> {toolTip("POSITION ERR.", toolTipCopy.position_error)} </div> <p className="app__hide-on-desktop">POS ERR.</p> </td> <td className="table__header-text"> <div className="app__hide-on-mobile"> {toolTip("TIME ERR.", toolTipCopy.time_error)} </div> <p className="app__hide-on-desktop">TIME ERR.</p> </td> <td className="table__header-text"> <div className="app__hide-on-mobile"> {toolTip("CROSS TRACK ERR.", toolTipCopy.cross_track_error)} </div> </td> <td className="table__header-text"> <div className="app__hide-on-mobile"> {toolTip("WEIGHT", toolTipCopy.weight)} </div> <p className="app__hide-on-desktop">WT.</p> </td> </tr> </thead> <tbody className="table__body">{renderYourObservationsRows()}</tbody> </table> ) : ( <div className="profile__none-yet-wrapper"> <NavLink className="app__nav-link" to="/how"> <p className="profile__none-yet-text">None yet</p> <span className="app__yellow-button--small" onClick={() => { ReactGA.event({ category: "Internal Link", action: "Clicked Learn", label: "Clicked Learn How on Profile Page" }); }} > Learn how to track Satellites </span> </NavLink> </div> )} {profileData.observation_history.length > 10 ? ( <TablePaginator tableDataLength={profileData.observation_history.length} range={range} setRange={setRange} /> ) : null} </section> ) : null; }
import React, { useState, useEffect} from 'react'; import Highcharts from "highcharts"; import HighchartsReact from "highcharts-react-official"; import axios from 'axios'; function FedCompareBarGraphComponent(props) { const income = props.income; const [bidenFedTaxes, setBidenFedTaxes] = useState(0); const [trumpFedTaxes, setTrumpFedTaxes] = useState(0); function handleResponse(response) { console.log(response); setBidenFedTaxes(response.data.user_biden_tax); setTrumpFedTaxes(response.data.user_trump_tax); } useEffect(() => { axios.get('/federalTaxComparison', { params: { income: income } }) .then(handleResponse); }, [income]); const options = { chart: { type: 'column' }, title: { text: 'Federal Tax Liability' }, subtitle: { text: 'Biden v. Trump' }, xAxis: { type: 'category', }, yAxis: { min: 0, title: { text: 'Tax Liability (US$)' } }, legend: { enabled: false }, colors: [ 'blue', 'red' ], plotOptions: { column: { colorByPoint: true } }, series: [{ data: [ ['Biden', bidenFedTaxes], ['Trump', trumpFedTaxes] ], }] }; return ( <React.Fragment> <HighchartsReact highcharts={Highcharts} options={options} /> </React.Fragment> ) } export default FedCompareBarGraphComponent;
import React from 'react'; import styled from 'styled-components'; import Flip from 'react-reveal/Flip'; import { colors } from '../../../styles/colors'; import { desktop } from '../../../styles/responsive'; const Card = ({ icon, heading, text, id }) => { return ( <Flip top> <Container> <Icon icon={icon} last={id === 'card-2'} /> <Heading>{heading}</Heading> <Text>{text}</Text> </Container> </Flip> ); } const Container = styled.div` background-color: white; margin-top: 5rem; padding: 1.5rem; padding-top: 4rem; border-radius: 0.5rem; position: relative; @media ${desktop} { margin: 0 0.75rem; text-align: left; height: 15rem; } @media only screen and (min-width: 1100px) { height: 12rem; } @media only screen and (min-width: 1240px) { height: auto; padding: 4rem 1.8rem 2.1rem; } `; const Icon = styled.span` position: absolute; left: 50%; transform: translateX(-50%); width: 4.8rem; height: 4.8rem; top: -2.4rem; background: ${colors['very-dark-blue']} ${({ icon }) => `url(${icon})`} no-repeat center; background-size: ${({ last }) => last ? "54%" : "45%"}; border-radius: 50%; z-index: 1; &:last-child { background-size: 100%; } @media ${desktop} { transform: none; left: 10%; } `; const Heading = styled.h3` margin-bottom: 0.75rem; @media ${desktop} { line-height: 1.4rem; } `; const Text = styled.p` line-height: 1.5rem; `; export default Card;
import React, { Component } from 'react'; class Account extends Component { constructor(props) { super(props); } render() { return ( <div className="col-sm-9"> <div className="card"> <div className="card-header">Account Settings</div> <div className="card-body"> <form> <div className="form-group"> <label htmlFor="inputEmail">Email</label> <input type="email" className="form-control" id="email" /> </div> <button type="submit" className="btn btn-primary"> Change Email </button> </form> <hr/> <form> <div className="form-group"> <label htmlFor="oldPassword">Old Password</label> <input type="password" className="form-control" id="oldPassword" placeholder="Old Password" /> </div> <div className="form-group"> <label htmlFor="newPassword1">New Password</label> <input type="password" className="form-control" id="newPassword1" placeholder="New Password" /> </div> <div className="form-group"> <label htmlFor="newPassword2">Confirm New Password</label> <input type="password" className="form-control" id="newPassword2" placeholder="Confirm New Password" /> </div> <button type="submit" className="btn btn-primary"> Change Password </button> </form> </div> </div> </div> ); } } export default Account;
import React, { useCallback } from 'react'; import { useHistory } from 'react-router-dom'; import classNames from 'classnames'; import s from './search-input.module.css'; export const SearchInput = (props) => { const history = useHistory(); const handleKeyUp = useCallback((ev) => { if (ev.keyCode === 13) { history.push(`/search?query=${encodeURIComponent(ev.currentTarget.value)}`); } }, [history]); return ( <div className={classNames(props.className, s.searchInput)}> <input type="search" onKeyUp={handleKeyUp} value={props.value} onChange={props.onChange} placeholder="Поиск..." className={s.input} /> </div> ); };
import { writable } from 'svelte/store'; export const openhabState = writable({}); export const test = writable('hello');
'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } var Bacon = _interopDefault(require('baconjs')); var infestines = require('infestines'); var Observable = Bacon.Observable; function countArray(template) { var c = 0; for (var i = 0, n = template.length; i < n; ++i) { c += count(template[i]); }return c; } function countObject(template) { var c = 0; for (var k in template) { c += count(template[k]); }return c; } function countTemplate(template) { if (infestines.isArray(template)) return countArray(template);else if (infestines.isObject(template)) return countObject(template);else return 0; } function count(template) { if (template instanceof Observable) return 1;else return countTemplate(template); } function invoke(xs) { if (!(xs instanceof Array)) return xs; var nm1 = xs.length - 1; var f = xs[nm1]; return f instanceof Function ? f.apply(void 0, xs.slice(0, nm1)) : xs; } var applyLast = function applyLast(args) { if (infestines.isArray(args)) { var last = args[args.length - 1]; if (last instanceof Function) { return last.apply(null, args.slice(0, -1)); } } return args; }; var combine = function combine(template) { return Bacon.combineTemplate(template).map(applyLast).skipDuplicates(infestines.identicalU); }; var lift1Shallow = function lift1Shallow(fn) { return function (x) { return x instanceof Observable ? x.map(fn).skipDuplicates(infestines.identicalU) : fn(x); }; }; var lift1 = function lift1(fn) { return function (x) { if (x instanceof Observable) { return x.map(fn).skipDuplicates(infestines.identicalU); } var n = countTemplate(x); if (0 === n) return fn(x); return combine([x, fn]); }; }; function lift(fn) { var fnN = fn.length; switch (fnN) { case 0: return fn; case 1: return lift1(fn); default: return infestines.arityN(fnN, function () { var xsN = arguments.length, xs = Array(xsN); for (var i = 0; i < xsN; ++i) { xs[i] = arguments[i]; }var n = countArray(xs); if (0 === n) return fn.apply(null, xs); xs.push(fn); return combine(xs); }); } } var bacon_combines = function () { for (var _len = arguments.length, template = Array(_len), _key = 0; _key < _len; _key++) { template[_key] = arguments[_key]; } var n = countArray(template); switch (n) { case 0: return invoke(template); case 1: return template.length === 2 && template[0] instanceof Observable && template[1] instanceof Function ? template[0].map(template[1]).skipDuplicates(infestines.identicalU) : combine(template); default: return combine(template); } }; exports.lift1Shallow = lift1Shallow; exports.lift1 = lift1; exports.lift = lift; exports['default'] = bacon_combines;
$(document).ready(function (){ $('.SubmitForm').on('click', function(e, a, b) { var files = document.getElementById('file-input').files; if (!files.length) { alert('Please select a file!'); return; } var file = files[0]; //var start = parseInt(opt_startByte) || 0; var start = 0; //var stop = parseInt(opt_stopByte) || file.size - 1; var stop = file.size - 1; var reader = new FileReader(); // If we use onloadend, we need to check the readyState. reader.onloadend = function(evt) { if (evt.target.readyState == FileReader.DONE) { // DONE == 2 var data = _.reduce(evt.target.result, function(sum, byte) { return sum + ' 0x' + String(byte).charCodeAt(0).toString(16); }, ''); //alert(['Read bytes: ', start + 1, ' - ', stop + 1, ' of ', file.size, ' byte file'].join('')); var row = $('#RoDetailsForm'); var metadata = {}; metadata.TITLE = row.find('#title_input').val(); metadata.CREATOR = row.find('#creator_input').val(); metadata.ABSTRACT = row.find('#abstract_input').val(); metadata.RIGHTS_HOLDER = row.find('#rights_holder_input').val(); metadata.LICENSE = row.find('#license_input').val(); metadata.FILE_NAME = row.find('#dataset-name').val(); metadata.FILE_SIZE = row.find('#dataset-size').val(); metadata.FILE_TYPE = row.find('#dataset-type').val(); metadata.LAST_MODIFIED_DATE = row.find('#dataset-modified-date').val(); metadata.DATA_BYTES = data; //alert(JSON.stringify(metadata,null, " ")); var xmlhttp = new XMLHttpRequest(); var apiprefix = "./../rest"; var url = apiprefix + "/rorequest"; xmlhttp.onreadystatechange=function() { if (!library) var library = {}; library.json = { replacer: function(match, pIndent, pKey, pVal, pEnd) { var key = '<span class=json-key>'; var val = '<span class=json-value>'; var str = '<span class=json-string>'; var r = pIndent || ''; if (pKey) r = r + key + pKey.replace(/[": ]/g, '') + '</span>: '; if (pVal) r = r + (pVal[0] == '"' ? str : val) + pVal + '</span>'; return r + (pEnd || ''); }, prettyPrint: function(obj) { var jsonLine = /^( *)("[\w]+": )?("[^"]*"|[\w.+-]*)?([,[{])?$/mg; return JSON.stringify(obj, null, 3) .replace(/&/g, '&amp;').replace(/\\"/g, '&quot;') .replace(/</g, '&lt;').replace(/>/g, '&gt;') .replace(jsonLine, library.json.replacer); } }; if (xmlhttp.readyState < 4) { // while waiting response from server document.getElementById('status_div_code').innerHTML = "\n" + "Loading..."; document.getElementById('status_div').className = "status_loading"; } else if (xmlhttp.readyState === 4) { // 4 = Response from server has been completely loaded. if (xmlhttp.status == 200 && xmlhttp.status < 300) { // http status between 200 to 299 are all successful document.getElementById('status_div_code').innerHTML = "\n" + library.json.prettyPrint(JSON.parse(xmlhttp.responseText)); document.getElementById('status_div').className = "status_successful"; } else { document.getElementById('status_div_code').innerHTML = "\n" + library.json.prettyPrint(JSON.parse(xmlhttp.responseText)); document.getElementById('status_div').className = "status_error"; } } } //xmlhttp.setRequestHeader('Content-Type', 'application/json'); xmlhttp.open("POST", url, true); xmlhttp.send(JSON.stringify(metadata)); } }; var blob; if (file.slice) { blob = file.slice(start, stop + 1); }else if (file.webkitSlice) { blob = file.webkitSlice(start, stop + 1); } else if (file.mozSlice) { blob = file.mozSlice(start, stop + 1); } console.log('reader: ', reader); reader.readAsBinaryString(blob); }); $('.ResetForm').on('click', function(e, a, b) { document.getElementById('status_div').className = "status_hidden"; }); });
const React = require('react'); import App from '../client/components/App'; import axios from 'axios'; const ReactDOMServer = require('react-dom/server'); const getData = (bookId, respData) => { if (bookId) { return { books: [respData], currentBookId: bookId }; } return respData; }; const getUrl = (bookId) => { if (bookId) { return `http://localhost:8080/api/books/${bookId}`; } return `http://localhost:8080/api/books`; }; export default () => { return axios.get(getUrl(bookId)) .then(resp => { const data = getData(bookId, resp.data); return { markup: ReactDOMServer.renderToString( <App initialData={data} /> ), data: data, } }) };
/** * Copyright (c) Benjamin Ansbach - all rights reserved. * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ const Abstract = require('./Abstract'); const P_VER = Symbol('ver'); const P_VER_A = Symbol('verA'); /** * Holds information about a nodes version. */ class NetProtocol extends Abstract { /** * Constructor * * @param {Object} data */ static createFromRPC(data) { let netProtocol = new NetProtocol(data); netProtocol[P_VER] = parseInt(data.ver, 10); netProtocol[P_VER_A] = parseInt(data.ver_a, 10); return netProtocol; } /** * Gets the wallets protocol version. * * @returns {Number} */ get ver() { return this[P_VER]; } /** * Gets the miners protocol version. * * @returns {Number} */ get verA() { return this[P_VER_A]; } } module.exports = NetProtocol;
var webpack = require('webpack') var WebpackDevServer = require('webpack-dev-server') var config = require('./dev-webpack') new WebpackDevServer(webpack(config), config.devServer) .listen(config.devServer.port, 'localhost', function(err) { if (err) { console.log(err); } });
 angular.module('ngApp.home').controller('HomeAirportPickupCancelController', function ($scope, config, $uibModal) { $scope.cancel = 'Cancel'; function init() { } init(); });
({ doInit : function(component, event, helper){ $A.createComponent("c:InsertProspectCmp", { }, function(newCmp) { if (component.isValid()) { component.set("v.body", newCmp); } }); }, NavigateComponent : function(component, event, helper) { var navigateto=event.getParam("navigateto"); var group=event.getParam("group"); var zip=event.getParam("zip"); var sicval=event.getParam("sicval"); if(group!=undefined||zip!=undefined||sicval!=undefined){ component.set("v.group",group); component.set("v.zipdata",zip); component.set("v.sicCode",sicval); } $A.createComponent(navigateto, { "group":component.get("v.group"), "zipdata" : component.get("v.zipdata"), "sicCode": component.get("v.sicCode"), }, function(newCmp) { if (component.isValid()) { component.set("v.body", newCmp); } }); } })
//SalaryCalcCore _c = city <- userSelect; _abd = amountBeforeDeduction <- userInput; _sb = siBase = function(){ if(_abd > _c.siBaseMaxLimit) { return _c.siBaseMaxLimit; } if(_abd < _c.siBaseMinLimit) { return _c.siBaseMinLimit; } return _abd; }; _pb = phfBase = function(){ if(_abd > _c.phfBaseMaxLimit) { return _c.phfBaseMaxLimit; } if(_abd < _c.phfBaseMinLimit) { return _c.phfBaseMinLimit; } return _abd; }; _si[i].ee = _sb * city.siFactor[i].ee; //i=[0..4] _si[i].er = _sb * city.siFactor[i].er; //i=[0..4] _pf = phfFactor = {]; _pf.ee = city.phfFactor + additionPhfFactorEe; _pf.er = city.phfFactor + additionPhfFactorEr; _phf.ee = _pb * _pf.ee; _phf.er = _pb * _pf.er; _abt = _abd - _si[i].ee - phf.ee;
import Layout from '../views/layout/Layout' const warehouse = [{ path: '/Reminder', component: Layout, name: 'Reminder', redirect: '/Reminder/List', meta: { title: 'ReminderSet', icon: 'el-icon-notebook-2', code: '10' }, children: [ { path: 'list', name: 'list', meta: { title: 'memorandum', icon: 'el-icon-notebook-2', code: '10_1' }, component: () => import('@/views/reminder/memorandum') }, ] }] export default warehouse
angular.module('quizz-admin').controller('CampaignModalController', [ '$scope', '$routeParams', '$modalInstance', 'campaignService', 'campaign', function($scope, $routeParams, $modalInstance, campaignService, campaign) { $scope.campaign = campaign || {status: 'PAUSED'}; $scope.campaign['quizID'] = $routeParams.quizID; $scope.save = function (form) { if(form.$invalid) { $scope.notValidForm = true; return; } campaignService.createCampaign($scope.campaign, function(response) { // TODO console.log(response); $modalInstance.close(); }, function(error) { //TODO: show error console.log(error); $modalInstance.close(); }); $modalInstance.close($scope.campaign); }; $scope.close = function () { $modalInstance.dismiss('cancel'); }; }]);
const { manifest: { theme_color }, } = require('../../site-settings') module.exports = [ 'gatsby-plugin-fastclick', 'gatsby-plugin-transition-link', { resolve: 'gatsby-plugin-nprogress', options: { // Setting a color is optional. color: theme_color, // Disable the loading spinner. showSpinner: false, }, }, ]
const mongoose = require("mongoose"); const bcrypt = require('bcryptjs'); const jwt = require('jsonwebtoken'); const Details = new mongoose.Schema({ Name:{ type: String, required: 'Name is required', minlength: [3, 'Name must be atleast 3 character long'] }, Email:{ type: String, required: 'Email is required' }, UserName:{ type: String, required: 'Username is required', unique: true }, Password:{ type: String, required: 'Password is required', minlength: [8, 'Password must be atleast 8 character long'] }, IsAdmin:{ type: Boolean, default: false }, saltSecret: String, Events:[{ title:{ type:String }, date:{ type:String } }], Semester:[{ SemesterName:{ type: String, }, Courses:[{ CourseName:{ type: String, }, CreditHrs:{ type: Number, }, Classes :[{ type: String }] }] }] }); // Custom validation for email Details.path('Email').validate((val) => { emailRegex = /^([a-zA-Z0-9_]+)@?(students)\.(au)\.(edu)\.pk$/; return emailRegex.test(val); }, 'Email must be on the students.au.edu.pk domain.'); Details.path('Name').validate((val) => { nameRegex = /^([a-zA-Z ]+)$/; return nameRegex.test(val); }, 'Name must be alphabets.'); // Events Details.pre('save', function (next) { if(!this.isModified('Password')) return next(); bcrypt.genSalt(10, (err, salt) => { bcrypt.hash(this.Password, salt, (err, hash) => { // console.log("In pre function ",this.Password); this.Password = hash; this.saltSecret = salt; next(); }); }); }); // Methods Details.methods.verifyPassword = function (Password) { return bcrypt.compareSync(Password, this.Password); }; Details.methods.generateJwt = function () { return jwt.sign({ _id: this._id, Name: this.Name, Username: this.UserName, IsAdmin: this.IsAdmin}, process.env.JWT_SECRET // { // expiresIn: process.env.JWT_EXP // } ); } const details = mongoose.model("Details", Details); module.exports = details;
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ var Util = require('./Util.class.js') /** * A 24-bit color ("True Color") that can be displayed in a pixel, given three primary color components. * @type {Color} */ module.exports = (function () { // CONSTRUCTOR /** * Construct a Color object. * Valid parameters: * - new Color([60, 120, 240]) // [red, green, blue] * - new Color([192]) // [grayscale] * - new Color() // (black, rgb(0,0,0)) * The RGB array may be an array of length 3 or 1, containing integers 0–255. * If array length is 3, the components are red, green, and blue, in that order. * If the length is 1, the red, green, and blue components are equal to that number, * which will produce a grayscale color. * If no argument is given, the color will be black (#000000). * @constructor * @param {Array<number>=[0]} $rgb an array of 1 or 3 integers in [0,255] */ function Color($rgb) { var self = this if (arguments.length >= 1 && $rgb.length >= 3) { ; } else if (arguments.length >= 1) { return Color.call(self, [ $rgb[0], $rgb[0], $rgb[0] ]) } else /* if (arguments.length < 1) */ { return Color.call(self, [0]) } /** * The red component of this color. An integer in [0,255]. * @type {number} */ self._RED = $rgb[0] /** * The green component of this color. An integer in [0,255]. * @type {number} */ self._GREEN = $rgb[1] /** * The blue component of this color. An integer in [0,255]. * @type {number} */ self._BLUE = $rgb[2] var _max = Math.max(self._RED, self._GREEN, self._BLUE) / 255 var _min = Math.min(self._RED, self._GREEN, self._BLUE) / 255 var _chroma = _max - _min /** * The HSV-space hue of this color, or what "color" this color is. * A number bound by [0, 360). * @type {number} */ self._HSV_HUE = (function () { if (_chroma === 0) return 0 var rgb_norm = [ self._RED / 255 , self._GREEN / 255 , self._BLUE / 255 ] return [ function (r, g, b) { return ((g - b) / _chroma + 6) % 6 * 60 } , function (r, g, b) { return ((b - r) / _chroma + 2) * 60 } , function (r, g, b) { return ((r - g) / _chroma + 4) * 60 } ][rgb_norm.indexOf(_max)].apply(null, rgb_norm) /* * Exercise: prove: * _HSV_HUE === Math.atan2(Math.sqrt(3) * (g - b), 2*r - g - b) */ })() /** * The brightness of this color. A lower value means the color is closer to black, a higher * value means the color is more true to its hue. * A number bound by [0, 1]. * @type {number} */ self._HSV_VAL = (function () { return _max })() /** * The vividness of this color. A lower saturation means the color is closer to white, * a higher saturation means the color is more true to its hue. * A number bound by [0, 1]. * @type {number} */ self._HSV_SAT = (function () { if (_chroma === 0) return 0 // avoid div by 0 return _chroma / self._HSV_VAL })() /** * The Hue of this color. Identical to `this._HSV_HUE`. * A number bound by [0, 360). * @type {number} */ self._HSL_HUE = (function () { return self._HSV_HUE })() /** * How "white" or "black" the color is. A lower luminosity means the color is closer to black, * a higher luminosity means the color is closer to white. * A number bound by [0, 1]. * @type {number} */ self._HSL_LUM = (function () { return 0.5 * (_max + _min) })() /** * The amount of "color" in the color. A lower saturation means the color is more grayer, * a higher saturation means the color is more colorful. * A number bound by [0, 1]. * @type {number} */ self._HSL_SAT = (function () { if (_chroma === 0) return 0 // avoid div by 0 return _chroma / ((self._HSL_LUM <= 0.5) ? 2*self._HSL_LUM : (2 - 2*self._HSL_LUM)) /* * Exercise: prove: * _HSL_SAT === _chroma / (1 - Math.abs(2*self._HSL_LUM - 1)) * Proof: * denom == (function (x) { * if (x <= 0.5) return 2x * else return 2 - 2x * })(_HSL_LUM) * Part A. Let x <= 0.5. Then 2x - 1 <= 0, and |2x - 1| == -(2x - 1). * Then 1 - |2x - 1| == 1 + (2x - 1) = 2x. // * Part B. Let 0.5 < x. Then 1 < 2x - 1, and |2x - 1| == 2x - 1. * Then 1 - |2x - 1| == 1 - (2x - 1) = 2 - 2x. // */ })() /** * The Hue of this color. Identical to `this._HSV_HUE`. * A number bound by [0, 360). * @type {number} */ self._HWB_HUE = (function () { return self._HSV_HUE })() /** * The amount of White in this color. A higher white means the color is closer to #fff, * a lower white means the color has a true hue (more colorful). * A number bound by [0, 1]. * @type {number} */ self._HWB_WHT = (function () { return _min })() /** * The amount of Black in this color. A higher black means the color is closer to #000, * a lower black means the color has a true hue (more colorful). * A number bound by [0, 1]. * @type {number} */ self._HWB_BLK = (function () { return 1 - _max })() } // ACCESSOR FUNCTIONS /** * Get the red component of this color. * @return {number} the red component of this color */ Color.prototype.red = function red() { return this._RED } /** * Get the green component of this color. * @return {number} the green component of this color */ Color.prototype.green = function green() { return this._GREEN } /** * Get the blue component of this color. * @return {number} the blue component of this color */ Color.prototype.blue = function blue() { return this._BLUE } /** * Get the hsv-hue of this color. * @return {number} the hsv-hue of this color */ Color.prototype.hsvHue = function hsvHue() { return this._HSV_HUE } /** * Get the hsv-saturation of this color. * @return {number} the hsv-saturation of this color */ Color.prototype.hsvSat = function hsvSat() { return this._HSV_SAT } /** * Get the hsv-value of this color. * @return {number} the hsv-value of this color */ Color.prototype.hsvVal = function hsvVal() { return this._HSV_VAL } /** * Get the hsl-hue of this color. * @return {number} the hsl-hue of this color */ Color.prototype.hslHue = function hslHue() { return this._HSL_HUE } /** * Get the hsl-saturation of this color. * @return {number} the hsl-saturation of this color */ Color.prototype.hslSat = function hslSat() { return this._HSL_SAT } /** * Get the hsl-luminosity of this color. * @return {number} the hsl-luminosity of this color */ Color.prototype.hslLum = function hslLum() { return this._HSL_LUM } /** * Get the hwb-hue of this color. * @return {number} the hwb-hue of this color */ Color.prototype.hwbHue = function hwbHue() { return this._HWB_HUE } /** * Get the hwb-white of this color. * @return {number} the hwb-white of this color */ Color.prototype.hwbWht = function hwbWht() { return this._HWB_WHT } /** * Get the hwb-black of this color. * @return {number} the hwb-black of this color */ Color.prototype.hwbBlk = function hwbBlk() { return this._HWB_BLK } // Convenience getter functions. /** * Return an array of RGB components (in that order). * @return {Array<number>} an array of RGB components */ Color.prototype.rgb = function rgb() { return [this.red(), this.green(), this.blue()] } /** * Return an array of HSV components (in that order). * @return {Array<number>} an array of HSV components */ Color.prototype.hsv = function hsv() { return [this.hsvHue(), this.hsvSat(), this.hsvVal()] } /** * Return an array of HSL components (in that order). * @return {Array<number>} an array of HSL components */ Color.prototype.hsl = function hsl() { return [this.hslHue(), this.hslSat(), this.hslLum()] } /** * Return an array of HWB components (in that order). * @return {Array<number>} an array of HWB components */ Color.prototype.hwb = function hwb() { return [this.hwbHue(), this.hwbWht(), this.hwbBlk()] } // METHODS /** * Return a new color that is the complement of this color. * The complement of a color is the difference between that color and white (#fff). * @return {Color} a new Color object that corresponds to this color’s complement */ Color.prototype.complement = function complement() { return new Color([ 255 - this.red() , 255 - this.green() , 255 - this.blue() ]) } /** * Return a new color that is a hue-rotation of this color. * @param {number} a the number of degrees to rotate * @return {Color} a new Color object corresponding to this color rotated by `a` degrees */ Color.prototype.rotate = function rotate(a) { var newhue = (this.hsvHue() + a) % 360 return Color.fromHSV(newhue, this.hsvSat(), this.hsvVal()) } /** * Return a new color that is the inverse of this color. * The inverse of a color is that color with a hue rotation of 180 degrees. * @return {Color} a new Color object that corresponds to this color’s inverse */ Color.prototype.invert = function invert() { return this.rotate(180) } /** * Return a new color that is a more saturated (more colorful) version of this color by a percentage. * This method calculates saturation in the HSL space. * A parameter of 1.0 returns a color with full saturation, and 0.0 returns an identical color. * A negative number will {@link Color.desaturate()|desaturate} this color. * @param {number} p must be between -1.0 and 1.0; the value by which to saturate this color * @param {boolean=} relative true if the saturation added is relative * @return {Color} a new Color object that corresponds to this color saturated by `p` */ Color.prototype.saturate = function saturate(p, relative) { var newsat = this.hslSat() + (relative ? (this.hslSat() * p) : p) newsat = Math.min(Math.max(0, newsat), 1) return Color.fromHSL(this.hslHue(), newsat, this.hslLum()) } /** * Return a new color that is a less saturated version of this color by a percentage. * A parameter of 1.0 returns a grayscale color, and 0.0 returns an identical color. * @see Color.saturate() * @param {number} p must be between -1.0 and 1.0; the value by which to desaturate this color * @param {boolean=} relative true if the saturation subtracted is relative * @return {Color} a new Color object that corresponds to this color desaturated by `p` */ Color.prototype.desaturate = function desaturate(p, relative) { return this.saturate(-p, relative) } /** * Return a new color that is a lighter version of this color by a percentage. * This method calculates with luminosity in the HSL space. * A parameter of 1.0 returns white (#fff), and 0.0 returns an identical color. * A negative parameter will {@link Color.darken()|darken} this color. * * Set `relative = true` to specify the amount as relative to the color’s current luminosity. * For example, if `$color` has an HSL-lum of 0.5, then calling `$color.lighten(0.5)` will return * a new color with an HSL-lum of 1.0, because the argument 0.5 is simply added to the color’s luminosity. * However, calling `$color.lighten(0.5, true)` will return a new color with an HSL-lum of 0.75, * because the argument 0.5, relative to the color’s current luminosity of 0.5, results in * an added luminosity of 0.25. * * @param {number} p must be between -1.0 and 1.0; the amount by which to lighten this color * @param {boolean=} relative true if the luminosity added is relative * @return {Color} a new Color object that corresponds to this color lightened by `p` */ // CHANGED DEPRECATED v2 remove Color.prototype.brighten = function brighten(p, relative) { return this.lighten(p, relative) } Color.prototype.lighten = function lighten(p, relative) { var newlum = this.hslLum() + (relative ? (this.hslLum() * p) : p) newlum = Math.min(Math.max(0, newlum), 1) return Color.fromHSL(this.hslHue(), this.hslSat(), newlum) } /** * Return a new color that is a darker version of this color by a percentage. * A parameter of 1.0 returns black (#000), and 0.0 returns an identical color. * @see Color.lighten() * @param {number} p must be between -1.0 and 1.0; the amount by which to darken this color * @param {boolean=} relative true if the luminosity subtracted is relative * @return {Color} a new Color object that corresponds to this color darkened by `p` */ Color.prototype.darken = function darken(p, relative) { return this.lighten(-p, relative) } /** * Mix (average) another color with this color, with a given weight favoring that color. * If `w == 0.0`, return exactly this color. * `w == 1.0` return exactly the other color. * `w == 0.5` (default if omitted) return a perfectly even mix. * In other words, `w` is "how much of the other color you want." * Note that `color1.mix(color2, w)` returns the same result as `color2.mix(color1, 1-w)`. * When param `flag` is provided, this method uses a more mathematically accurate calculation, * thus providing a more aesthetically accurate mix. * TODO This will be the default behavior starting in v2. * @see https://www.youtube.com/watch?v=LKnqECcg6Gw * @param {Color} $color the second color * @param {number=0.5} w between 0.0 and 1.0; the weight favoring the other color * @param {flag=} flag if truthy, will use a more accurate calculation * @return {Color} a mix of the two given colors */ Color.prototype.mix = function mix($color, w, flag) { if (arguments.length >= 2) { ; } else return this.mix($color, 0.5) // /** // * Helper function. Average two numbers, with a weight favoring the 2nd number. // * The result will always be between the two numbers. // * @param {number} a 1st number // * @param {number} b 2nd number // * @param {number} w number between [0,1]; weight of 2nd number // * @return {number} the weighted average of `a` and `b` // */ // function average(a, b, w) { // return (a * (1-w)) + (b * w) // } // return new Color([ // average(this.red(), $color.red(), w) // , average(this.green(), $color.green(), w) // , average(this.blue(), $color.blue(), w) // ].map(Math.round)) if (flag) { return new Color([ (1-w) * Math.pow(this.red() , 2) + w * Math.pow($color.red() , 2) , (1-w) * Math.pow(this.green(), 2) + w * Math.pow($color.green(), 2) , (1-w) * Math.pow(this.blue() , 2) + w * Math.pow($color.blue() , 2) ].map(function (n) { return Math.round(Math.sqrt(n)) })) } return new Color([ (1-w) * this.red() + w * $color.red() , (1-w) * this.green() + w * $color.green() , (1-w) * this.blue() + w * $color.blue() ].map(Math.round)) } /** * Compare this color with another color. * Return `true` if they are the same color. * @param {Color} $color a Color object * @return {boolean} true if the argument is the same color as this color */ Color.prototype.equals = function equals($color) { return (this.hsvSat()===0 && $color.hsvSat()===0 && (this.hsvVal() === $color.hsvVal())) // NOTE speedy || ( (this.red() === $color.red()) && (this.green() === $color.green()) && (this.blue() === $color.blue()) ) } /** * Return the *contrast ratio* between two colors. * More info can be found at * {@link https://www.w3.org/TR/WCAG/#contrast-ratiodef} * @param {Color} $color the second color to check * @return {number} the contrast ratio of this color with the argument */ Color.prototype.contrastRatio = function contrastRatio($color) { /** * Return the relative lumance of a color. * @param {Color} c a Color object * @return {number} the relative lumance of the color */ function luma(c) { /** * A helper function. * @param {number} p a decimal representation of an rgb component of a color * @return {number} the output of some mathematical function of `p` */ function coef(p) { return (p <= 0.03928) ? p/12.92 : Math.pow((p + 0.055)/1.055, 2.4) } return 0.2126*coef(c.red() /255) + 0.7152*coef(c.green()/255) + 0.0722*coef(c.blue() /255) } var both = [luma(this), luma($color)] return (Math.max.apply(null, both) + 0.05) / (Math.min.apply(null, both) + 0.05) } /** * Return a string representation of this color. * If `space === 'hex'`, return `#rrggbb` * If `space === 'hsv'`, return `hsv(h, s, v)` * If `space === 'hsl'`, return `hsl(h, s, l)` * If `space === 'hwb'`, return `hwb(h, w, b)` * If `space === 'rgb'`, return `rgb(r, g, b)` (default) * The format of the numbers returned will be as follows: * - all HEX values will be base 16 integers in [00,FF], two digits * - HSV/HSL/HWB-hue values will be base 10 decimals in [0,360) rounded to the nearest 0.1 * - HSV/HSL-sat/val/lum and HWB-wht/blk values will be base 10 decimals in [0,1] rounded to the nearest 0.01 * - all RGB values will be base 10 integers in [0,255], one to three digits * IDEA may change the default to 'hex' instead of 'rgb', once browsers support ColorAlpha hex (#rrggbbaa) * https://drafts.csswg.org/css-color/#hex-notation * @param {string='rgb'} space represents the space in which this color exists * @return {string} a string representing this color. */ Color.prototype.toString = function toString(space) { if (space === 'hex') { var r = Util.toHex(this.red()) var g = Util.toHex(this.green()) var b = Util.toHex(this.blue()) return '#' + r + g + b // return `#${r}${g}${b}` // CHANGED ES6 } if (space === 'hsv') { var h = Math.round(this.hsvHue() * 10) / 10 var s = Math.round(this.hsvSat() * 100) / 100 var v = Math.round(this.hsvVal() * 100) / 100 return 'hsv(' + h + ', ' + s + ', ' + v + ')' // return `hsv(${h}, ${s}, ${v})` // CHANGED ES6 } if (space === 'hsl') { var h = Math.round(this.hslHue() * 10) / 10 var s = Math.round(this.hslSat() * 100) / 100 var l = Math.round(this.hslLum() * 100) / 100 return 'hsl(' + h + ', ' + s + ', ' + l + ')' // return `hsl(${h}, ${s}, ${l})` // CHANGED ES6 } if (space === 'hwb') { var h = Math.round(this.hwbHue() * 10) / 10 var w = Math.round(this.hwbWht() * 100) / 100 var b = Math.round(this.hwbBlk() * 100) / 100 return 'hwb(' + h + ', ' + w + ', ' + b + ')' // return `hwb(${h}, ${w}, ${b})` // CHANGED ES6 } var r = this.red() var g = this.green() var b = this.blue() return 'rgb(' + r + ', ' + g + ', ' + b + ')' // return `rgb(${r}, ${g}, ${b})` // CHANGED ES6 } // STATIC MEMBERS /** * Return a new Color object, given hue, saturation, and value in HSV-space. * The HSV-hue must be between 0 and 360. * The HSV-saturation must be between 0.0 and 1.0. * The HSV-value must be between 0.0 and 1.0. * The given argument must be an array of these three values in order. * Or, you may pass 3 values as 3 separate arguments. * CHANGED DEPRECATED starting in v2, argument must be Array<number>(3) * @param {(number|Array<number>)} hue must be between 0 and 360; hue in HSV-space || an Array of HSV components * @param {number=} sat must be between 0.0 and 1.0; saturation in HSV-space * @param {number=} val must be between 0.0 and 1.0; brightness in HSV-space * @return {Color} a new Color object with hsv(hue, sat, val) */ Color.fromHSV = function fromHSV(hue, sat, val) { if (Array.isArray(hue)) { return Color.fromHSV(hue[0], hue[1], hue[2]) } var c = sat * val var x = c * (1 - Math.abs(hue/60 % 2 - 1)) var m = val - c var rgb; if ( 0 <= hue && hue < 60) { rgb = [c, x, 0] } else if ( 60 <= hue && hue < 120) { rgb = [x, c, 0] } else if (120 <= hue && hue < 180) { rgb = [0, c, x] } else if (180 <= hue && hue < 240) { rgb = [0, x, c] } else if (240 <= hue && hue < 300) { rgb = [x, 0, c] } else if (300 <= hue && hue < 360) { rgb = [c, 0, x] } return new Color(rgb.map(function (el) { return Math.round((el + m) * 255) })) } /** * Return a new Color object, given hue, saturation, and luminosity in HSL-space. * The HSL-hue must be between 0 and 360. * The HSL-saturation must be between 0.0 and 1.0. * The HSL-luminosity must be between 0.0 and 1.0. * The given argument must be an array of these three values in order. * Or, you may pass 3 values as 3 separate arguments. * CHANGED DEPRECATED starting in v2, argument must be Array<number>(3) * @param {(number|Array<number>)} hue must be between 0 and 360; hue in HSL-space || an Array of HSL components * @param {number=} sat must be between 0.0 and 1.0; saturation in HSL-space * @param {number=} lum must be between 0.0 and 1.0; luminosity in HSL-space * @return {Color} a new Color object with hsl(hue, sat, lum) */ Color.fromHSL = function fromHSL(hue, sat, lum) { if (Array.isArray(hue)) { return Color.fromHSL(hue[0], hue[1], hue[2]) } var c = sat * (1 - Math.abs(2*lum - 1)) var x = c * (1 - Math.abs(hue/60 % 2 - 1)) var m = lum - c/2 var rgb; if ( 0 <= hue && hue < 60) { rgb = [c, x, 0] } else if ( 60 <= hue && hue < 120) { rgb = [x, c, 0] } else if (120 <= hue && hue < 180) { rgb = [0, c, x] } else if (180 <= hue && hue < 240) { rgb = [0, x, c] } else if (240 <= hue && hue < 300) { rgb = [x, 0, c] } else if (300 <= hue && hue < 360) { rgb = [c, 0, x] } return new Color(rgb.map(function (el) { return Math.round((el + m) * 255) })) } /** * Return a new Color object, given hue, white, and black in HWB-space. * Credit for formula is due to https://drafts.csswg.org/css-color/#hwb-to-rgb * The HWB-hue must be between 0 and 360. * The HWB-white must be between 0.0 and 1.0. * The HWB-black must be between 0.0 and 1.0. * The given argument must be an array of these three values in order. * Or, you may pass 3 values as 3 separate arguments. * CHANGED DEPRECATED starting in v2, argument must be Array<number>(3) * @param {(number|Array<number>)} hue must be between 0 and 360; hue in HWB-space || an Array of HWB components * @param {number=} wht must be between 0.0 and 1.0; white in HWB-space * @param {number=} blk must be between 0.0 and 1.0; black in HWB-space * @return {Color} a new Color object with hwb(hue, wht, blk) */ Color.fromHWB = function fromHWB(hue, wht, blk) { if (Array.isArray(hue)) { return Color.fromHWB(hue[0], hue[1], hue[2]) } return Color.fromHSV(hue, 1 - wht / (1 - blk), 1 - blk) // HWB -> RGB: /* var rgb = Color.fromHSL(hue, 1, 0.5).rgb().map(function (el) { return el / 255 }) for (var i = 0; i < 3; i++) { rgb[i] *= (1 - white - black); rgb[i] += white; } return new Color(rgb.map(function (el) { return Math.round(el * 255) })) */ } /** * Return a new Color object, given a string. * The string may have either of the following formats: * 1. `#rrggbb`, with hexadecimal RGB components (in base 16, out of ff, lowercase). The `#` must be included. * 2. `rgb(r,g,b)` or `rgb(r, g, b)`, with integer RGB components (in base 10, out of 255). * 3. `hsv(h,s,v)` or `hsv(h, s, v)`, with decimal HSV components (in base 10). * 4. `hsl(h,s,l)` or `hsl(h, s, l)`, with decimal HSL components (in base 10). * 5. `hwb(h,w,b)` or `hwb(h, w, b)`, with decimal HWB components (in base 10). * @param {string} str a string of one of the forms described * @return {Color} a new Color object constructed from the given string */ Color.fromString = function fromString(str) { if (str.slice(0,1) === '#' && str.length === 7) { return new Color([ str.slice(1,3) , str.slice(3,5) , str.slice(5,7) ].map(Util.toDec)) } if (str.slice(0,4) === 'rgb(') { return new Color(Util.components(4, str)) } if (str.slice(0,4) === 'hsv(') { return Color.fromHSV.apply(null, Util.components(4, str)) } if (str.slice(0,4) === 'hsl(') { return Color.fromHSL.apply(null, Util.components(4, str)) } if (str.slice(0,4) === 'hwb(') { return Color.fromHWB.apply(null, Util.components(4, str)) } return null } /** * Mix (average) a set of 2 or more colors. The average will be weighted evenly. * If two colors $a and $b are given, calling this static method, `Color.mix([$a, $b])`, * is equivalent to calling `$a.mix($b)` without a weight. * However, calling `Color.mix([$a, $b, $c])` with 3 or more colors yields an even mix, * and will *NOT* yield the same results as calling `$a.mix($b).mix($c)`, which yields an uneven mix. * Note that the order of the given colors does not change the result, that is, * `Color.mix([$a, $b])` will return the same result as `Color.mix([$b, $a])`. * When param `flag` is provided, this method uses a more mathematically accurate calculation, * thus providing a more aesthetically accurate mix. * TODO This will be the default behavior starting in v2. * @param {Array<Color>} $colors an array of Color objects, of length >=2 * @param {flag=} flag if truthy, will use a more accurate calculation * @return {Color} a mix of the given colors */ Color.mix = function mix($colors, flag) { return new Color([ $colors.map(function ($c) { return $c.red() }) , $colors.map(function ($c) { return $c.green() }) , $colors.map(function ($c) { return $c.blue() }) ].map(function ($arr) { if (flag) return Math.round(Math.sqrt($arr.reduce(function (a, b) { return a*a + b*b }) / $colors.length)) return Math.round($arr.reduce(function (a, b) { return a + b }) / $colors.length) })) } return Color })() },{"./Util.class.js":3}],2:[function(require,module,exports){ var Util = require('./Util.class.js') var Color = require('./Color.class.js') /** * A 32-bit color that can be displayed in a pixel, given three primary color components * and a transparency component. * @type {ColorAlpha} * @extends Color */ module.exports = (function () { // CONSTRUCTOR /** * Construct a ColorAlpha object. * Valid parameters: * - new ColorAlpha([60, 120, 240], 0.7) // [red, green, blue], alpha (translucent, rgba(r, g, b, alpha)) * - new ColorAlpha([192], 0.7) // [grayscale], alpha (translucent, rgba(r, r, r, alpha)) * - new ColorAlpha([60, 120, 240]) // [red, green, blue] (opaque, rgba(r, g, b, 1.0)) * - new ColorAlpha([192]) // [grayscale] (opaque, rgba(r, r, r, 1.0)) * - new ColorAlpha(0.7) // alpha (rgba(0, 0, 0, alpha), translucent black) * - new ColorAlpha() // (rgba(0, 0, 0, 0.0), transparent) * You may pass both an RGB array and an alpha, or either one, or neither. * See {@see Color} for specs on the RGB array. The alpha must be a (decimal) number 0–1. * If RGB is given, alpha defaults to 1.0 (opaque). * If no RGB is given, alpha defaults to 0.0 (transparent). * @constructor * @param {Array<number>=[0]} $rgb an array of 1 or 3 integers in [0,255] * @param {number=(1|0)} alpha a number in [0,1]; the alpha, or opacity, of this color */ function ColorAlpha($rgb, alpha) { var self = this if (arguments.length >= 2 && $rgb.length >= 3) { ; } else if (arguments.length >= 2) { return ColorAlpha.call(self, [$rgb[0], $rgb[0], $rgb[0]], alpha) } else if (arguments.length >= 1 && $rgb instanceof Array) { return ColorAlpha.call(self, $rgb, 1) } else if (arguments.length >= 1) { return ColorAlpha.call(self, [0], $rgb) } else /* if (arguments.length < 1) */ { return ColorAlpha.call(self, 0) } // call the super. if alpha===0 then this color’s rgb will be [0,0,0]. if (alpha !== 0) Color.call(self, $rgb) else Color.call(self) /** * The alpha component of this color. An number in [0,1]. * @type {number} */ self._ALPHA = alpha } ColorAlpha.prototype = Object.create(Color.prototype) ColorAlpha.prototype.constructor = ColorAlpha // ACCESSOR FUNCTIONS /** * Get the alpha (opacity) of this color. * @return {number} the alpha of this color */ ColorAlpha.prototype.alpha = function alpha() { return this._ALPHA } // Convenience getter functions. /** * Return an array of RGBA components (in that order). * @return {Array<number>} an array of RGBA components */ ColorAlpha.prototype.rgba = function rgba() { return this.rgb().concat(this.alpha()) } /** * Return an array of HSVA components (in that order). * @return {Array<number>} an array of HSVA components */ ColorAlpha.prototype.hsva = function hsva() { return this.hsv().concat(this.alpha()) } /** * Return an array of HSLA components (in that order). * @return {Array<number>} an array of HSLA components */ ColorAlpha.prototype.hsla = function hsla() { return this.hsl().concat(this.alpha()) } /** * Return an array of HWBA components (in that order). * @return {Array<number>} an array of HWBA components */ ColorAlpha.prototype.hwba = function hwba() { return this.hwb().concat(this.alpha()) } // METHODS /** * @override * @return {ColorAlpha} the complement of this color */ ColorAlpha.prototype.complement = function complement() { return new ColorAlpha(Color.prototype.complement.call(this).rgb(), this.alpha()) } /** * @override * @param {number} a the number of degrees to rotate * @return {ColorAlpha} a new color corresponding to this color rotated by `a` degrees */ ColorAlpha.prototype.rotate = function rotate(a) { return new ColorAlpha(Color.prototype.rotate.call(this, a).rgb(), this.alpha()) } /** * @override * @param {number} p must be between -1.0 and 1.0; the value by which to saturate this color * @param {boolean=} relative true if the saturation added is relative * @return {ColorAlpha} a new ColorAlpha object that corresponds to this color saturated by `p` */ ColorAlpha.prototype.saturate = function saturate(p, relative) { return new ColorAlpha(Color.prototype.saturate.call(this, p, relative).rgb(), this.alpha()) } /** * @override * @param {number} p must be between -1.0 and 1.0; the amount by which to lighten this color * @param {boolean=} relative true if the luminosity added is relative * @return {ColorAlpha} a new ColorAlpha object that corresponds to this color lightened by `p` */ // CHANGED DEPRECATED v2 remove ColorAlpha.prototype.brighten = function brighten(p, relative) { return this.lighten(p, relative) } ColorAlpha.prototype.lighten = function lighten(p, relative) { return new ColorAlpha(Color.prototype.lighten.call(this, p, relative).rgb(), this.alpha()) } /** * Return a new color with the complemented alpha of this color. * An alpha of, for example, 0.7, complemented, is 0.3 (the complement with 1.0). * @return {ColorAlpha} a new ColorAlpha object with the same color but complemented alpha */ ColorAlpha.prototype.negative = function negative() { return new ColorAlpha(this.rgb(), 1 - this.alpha()) } /** * @override * @param {Color} $color the second color; may also be an instance of ColorAlpha * @param {number=0.5} w between 0.0 and 1.0; the weight favoring the other color * @param {flag=} flag if truthy, will use a more accurate mixing calculation * @return {ColorAlpha} a mix of the two given colors */ ColorAlpha.prototype.mix = function mix($color, w, flag) { var newColor = Color.prototype.mix.call(this, $color, w, flag) var newAlpha = (function compoundOpacity(a, b) { return 1 - ( (1-a) * (1-b) ) })(this.alpha(), ($color instanceof ColorAlpha) ? $color.alpha() : 1) return new ColorAlpha(newColor.rgb(), newAlpha) } /** * @override * @param {ColorAlpha} $colorAlpha a ColorAlpha object * @return {boolean} true if the argument is the same color as this color */ ColorAlpha.prototype.equals = function equals($colorAlpha) { var sameAlphas = (this.alpha() === $color.alpha()) // NOTE speedy return sameAlphas && (this.alpha()===0 || Color.prototype.equals.call(this, $colorAlpha)) } /** * Return a string representation of this color. * If `space === 'hex'`, return `#rrggbbaa` * If `space === 'hsva'`, return `hsva(h, s, v, a)` * If `space === 'hsla'`, return `hsla(h, s, l, a)` * If `space === 'hwba'`, return `hwba(h, w, b, a)` // NOTE not supported yet * If `space === 'rgba'`, return `rgba(r, g, b, a)` (default) * The format of the numbers returned will be as follows: * - all HEX values for RGB, and hue/sat/val/lum will be of the same format as described in * {@link Color#toString} * - all alpha values will be base 10 decimals in [0,1], rounded to the nearest 0.001 * IDEA may change the default to 'hex' instead of 'rgba', once browsers support ColorAlpha hex (#rrggbbaa) * https://drafts.csswg.org/css-color/#hex-notation * @override * @param {string='rgba'} space represents the space in which this color exists * @return {string} a string representing this color. */ ColorAlpha.prototype.toString = function toString(space) { var a = Math.round(this.alpha() * 1000) / 1000 // CHANGED v2 remove 'hexa' if (space === 'hex' || space==='hexa') { return Color.prototype.toString.call(this, 'hex') + Util.toHex(Math.round(this.alpha()*255)) } if (space === 'hsva') { return 'hsva(' + Color.prototype.toString.call(this, 'hsv').slice(4, -1) + ', ' + a + ')' // return `hsva(${Color.prototype.toString.call(this, 'hsv').slice(4, -1)}, ${a})` // CHANGED ES6 } if (space === 'hsla') { return 'hsla(' + Color.prototype.toString.call(this, 'hsl').slice(4, -1) + ', ' + a + ')' // return `hsla(${Color.prototype.toString.call(this, 'hsl').slice(4, -1)}, ${a})` // CHANGED ES6 } if (space === 'hwba') { return 'hwba(' + Color.prototype.toString.call(this, 'hwb').slice(4, -1) + ', ' + a + ')' // return `hwba(${Color.prototype.toString.call(this, 'hwb').slice(4, -1)}, ${a})` // CHANGED ES6 } return 'rgba(' + Color.prototype.toString.call(this, 'rgb').slice(4, -1) + ', ' + a + ')' // return `rgba(${Color.prototype.toString.call(this, 'rgb').slice(4, -1)}, ${a})` // CHANGED ES6 } // STATIC MEMBERS /** * Return a new ColorAlpha object, given hue, saturation, and value in HSV-space, * and an alpha component. * The alpha must be between 0.0 and 1.0. * The first argument must be an array of these three values in order. * Or, you may pass 3 values as the first 3 arguments. * CHANGED DEPRECATED starting in v2, first argument must be Array<number>(3) * @see Color.fromHSV * @param {(number|Array<number>)} hue must be between 0 and 360; hue in HSV-space || an Array of HSV components * @param {number} sat must be between 0.0 and 1.0; saturation in HSV-space || alpha (opacity) * @param {number=} val must be between 0.0 and 1.0; brightness in HSV-space * @param {number=} alpha must be between 0.0 and 1.0; alpha (opacity) * @return {ColorAlpha} a new ColorAlpha object with hsva(hue, sat, val, alpha) */ ColorAlpha.fromHSVA = function fromHSVA(hue, sat, val, alpha) { if (Array.isArray(hue)) { return Color.fromHSVA(hue[0], hue[1], hue[2], sat) } return new ColorAlpha(Color.fromHSV([hue, sat, val]).rgb(), alpha) } /** * Return a new ColorAlpha object, given hue, saturation, and luminosity in HSL-space, * and an alpha component. * The alpha must be between 0.0 and 1.0. * The first argument must be an array of these three values in order. * Or, you may pass 3 values as the first 3 arguments. * CHANGED DEPRECATED starting in v2, first argument must be Array<number>(3) * @see Color.fromHSL * @param {(number|Array<number>)} hue must be between 0 and 360; hue in HSL-space || an Array of HSL components * @param {number} sat must be between 0.0 and 1.0; saturation in HSL-space || alpha (opacity) * @param {number=} lum must be between 0.0 and 1.0; luminosity in HSL-space * @param {number=} alpha must be between 0.0 and 1.0; alpha (opacity) * @return {ColorAlpha} a new ColorAlpha object with hsla(hue, sat, lum, alpha) */ ColorAlpha.fromHSLA = function fromHSLA(hue, sat, lum, alpha) { if (Array.isArray(hue)) { return Color.fromHSVA(hue[0], hue[1], hue[2], sat) } return new ColorAlpha(Color.fromHSL([hue, sat, lum]).rgb(), alpha) } /** * Return a new ColorAlpha object, given hue, white, and black in HWB-space, * and an alpha component. * The alpha must be between 0.0 and 1.0. * The first argument must be an array of these three values in order. * Or, you may pass 3 values as the first 3 arguments. * CHANGED DEPRECATED starting in v2, first argument must be Array<number>(3) * @see Color.fromHWB * @param {(number|Array<number>)} hue must be between 0 and 360; hue in HWB-space || an Array of HWB components * @param {number} wht must be between 0.0 and 1.0; white in HWB-space || alpha (opacity) * @param {number=} blk must be between 0.0 and 1.0; black in HWB-space * @param {number=} alpha must be between 0.0 and 1.0; alpha (opacity) * @return {ColorAlpha} a new ColorAlpha object with hwba(hue, wht, blk, alpha) */ ColorAlpha.fromHWBA = function fromHWBA(hue, wht, blk, alpha) { if (Array.isArray(hue)) { return Color.fromHSVA(hue[0], hue[1], hue[2], wht) } return new ColorAlpha(Color.fromHWB([hue, wht, blk]).rgb(), alpha) } /** * Return a new ColorAlpha object, given a string. * The string may have any of the formats described in * {@link Color.fromString}, or it may have either of the following formats, * with the alpha component as a base 10 decimal between 0.0 and 1.0. * 1. `#rrggbbaa`, where `aa` is alpha * 2. `rgba(r,g,b,a)` or `rgba(r, g, b, a)`, where `a` is alpha * 3. `hsva(h,s,v,a)` or `hsva(h, s, v, a)`, where `a` is alpha * 4. `hsla(h,s,l,a)` or `hsla(h, s, l, a)`, where `a` is alpha * 4. `hwba(h,w,b,a)` or `hwba(h, w, b, a)`, where `a` is alpha * @see Color.fromString * @param {string} str a string of one of the forms described * @return {ColorAlpha} a new ColorAlpha object constructed from the given string */ ColorAlpha.fromString = function fromString(str) { var is_opaque = Color.fromString(str) if (is_opaque) { return new ColorAlpha(is_opaque.rgb()) } if (str.slice(0,1) === '#' && str.length === 9) { return new ColorAlpha([ str.slice(1,3) , str.slice(3,5) , str.slice(5,7) ].map(Util.toDec), Util.toDec(str.slice(7,9))/255) } if (str.slice(0,5) === 'rgba(') { var comps = Util.components(5, str) return new ColorAlpha(comps.slice(0,3), comps[3]) } if (str.slice(0,5) === 'hsva(') { return ColorAlpha.fromHSVA.apply(null, Util.components(5, str)) } if (str.slice(0,5) === 'hsla(') { return ColorAlpha.fromHSLA.apply(null, Util.components(5, str)) } if (str.slice(0,5) === 'hwba(') { return ColorAlpha.fromHWBA.apply(null, Util.components(5, str)) } return null } /** * ColorAlpha equivalent of `Color.mix`. * @see Color.mix * @param {Array<Color>} $colors an array of Color (or ColorAlpha) objects, of length >=2 * @return {ColorAlpha} a mix of the given colors */ ColorAlpha.mix = function mix($colors) { var newColor = Color.mix($colors, true) var newAlpha = 1 - $colors.map(function ($c) { return ($c instanceof ColorAlpha) ? $c.alpha() : 1 }).reduce(function (a, b) { return (1-a) * (1-b) }) return new ColorAlpha(newColor.rgb(), newAlpha) } return Color })() },{"./Color.class.js":1,"./Util.class.js":3}],3:[function(require,module,exports){ /** * A utility class for performing calculations. Contains only static members. * This class is *not* exported with the package. * @type {Util} */ module.exports = (function () { // CONSTRUCTOR function Util() {} // ACCESSOR FUNCTIONS // METHODS // STATIC MEMBERS /** * Convert a decimal number to a hexadecimal number, as a string. * The given number must be an integer within 0–255. * The returned string is in lowercase. * @param {number} n an integer in base 10 * @return {string} an integer in base 16 as a string */ Util.toHex = function toHex(n) { return '0123456789abcdef'.charAt((n - n % 16) / 16) + '0123456789abcdef'.charAt(n % 16) } /** * Convert a hexadecimal number (as a string) to a decimal number. * The hexadecimal number must be a string of exactly 2 characters, * each of which is a digit `0–9` or `a–f`. * @param {string} n a number in base 16 as a string * @return {number} a number in base 10 */ Util.toDec = function toDec(n) { var tens, ones for (var i = 0; i < 16; i++) { if ('0123456789abcdef'.charAt(i) === n.slice(0,1)) tens = i*16 if ('0123456789abcdef'.charAt(i) === n.slice(1,2)) ones = i } return tens + ones } /** * Return an array of comma-separated numbers extracted from a string. * The string must be of the form `xxx(a, b, c, ...)` or `xxx(a,b,c,...)`, where * `a`, `b`, and `c`, etc. are numbers, and `xxx` is any `n-1` number of characters * (if n===4 then `xxx` must be 3 characters). * Any number of prefixed characters and comma-separated numbers may be given. Spaces are optional. * Examples: * ``` * components(4, 'rgb(20, 32,044)') === [20, 32, 44] * components(5, 'hsva(310,0.7, .3, 1/2)') === [310, 0.7, 0.3, 0.5] * ``` * @param {number} n the starting point of extraction * @param {string} s the string to dissect * @return {Array<number>} an array of numbers */ Util.components = function components(n, s) { return s.slice(n, -1).split(',').map(function (el) { return +el }) } return Util })() },{}],4:[function(require,module,exports){ module.exports = { Color: require('./Color.class.js') , ColorAlpha: require('./ColorAlpha.class.js') } },{"./Color.class.js":1,"./ColorAlpha.class.js":2}],5:[function(require,module,exports){ var Page = require('sitepage').Page var Util = require('./Util.class.js') module.exports = class ConfPage extends Page { /** * Any page or subpage within a ConfSite. * Construct a ConfPage object, given a name and url. * @see ConfSite * @constructor * @extends Page * @param {string} name name of this page * @param {string} url url of this page */ constructor(name, url) { super({ name: name, url: url }) /** @private */ this._icon = null /** @private */ this._is_hidden = false } /** * Set the icon for this page. * @param {string} key the keyword for the icon */ setIcon(key) { this._icon = Util.ICON_DATA.find(($icon) => $icon.content===key) return this } /** * Get the icon of this page. * @param {boolean=} fallback if true, get the unicode code point * @return {string} if fallback, the unicode code point, else, the keyword of the icon */ getIcon(fallback) { return (this._icon) ? Util.iconToString(this._icon, fallback) : '' } /** * Hide or show this page. * @param {boolean=true} bool hides or shows this page * @return {Page} this page */ hide(bool) { this._is_hidden = (arguments.length) ? bool : true return this } /** * Get the hidden status of this page. * @return {boolean} true if this page is hidden; false otherwise */ isHidden() { return this._is_hidden } } },{"./Util.class.js":17,"sitepage":21}],6:[function(require,module,exports){ var Page = require('sitepage').Page var Color = require('csscolor').Color var ConfPage = require('./ConfPage.class.js') module.exports = class ConfSite extends Page { /** * A conference site. * A site hosting a series of conferences, * with a name, url, slogan, logo, and color scheme. * Construct a ConfSite object, given a name and url. * @constructor * @extends Page * @param {string} name name of this site * @param {string} url url of the landing page for this site * @param {string} slogan the tagline, or slogan, of this site */ constructor(name, url, slogan) { super({ name: name, url: url }) super.description(slogan) /** @private */ this._logo = '' /** @private */ this._colors = {} /** @private */ this._conferences = {} /** @private */ this._conf_curr_key = null /** @private */ this._conf_prev_key = null /** @private */ this._conf_next_key = null } /** * Overwrite superclass description() method. * This method only gets the description, it does not set it. * TODO: update this to an ES6 getter once {@link Page#description()} is updated. * @override * @param {*} arg any argument * @return {string} the description of this site */ description(arg) { return super.description() } /** * Get the slogan of this site. * The slogan is very brief, and is fixed for the entire series of conferences. * @return {string} the slogan of this site */ get slogan() { return this.description() || '' } /** * Set or get the logo of this site. * @param {string=} logo url of the logo file * @return {(ConfSite|string)} this site || url of the logo */ logo(logo) { if (arguments.length) { this._logo = logo return this } else return this._logo } /** * Set or get the colors for this site. * @param {Color=} $primary a Color object for the primary color * @param {Color=} $secondary a Color object for the secondary color * @return {(ConfSite|Object)} this || a CSS style object containg custom properties and color string values */ colors($primary, $secondary) { if (arguments.length) { this._colors = ConfSite.colorStyles($primary, $secondary) return this } else return this._colors } /** * Add a conference to this site. * @param {string} conf_label key for accessing the conference, usually a year * @param {Conference} $conference the conference to add * @return {ConfSite} this site */ addConference(conf_label, $conference) { this._conferences[conf_label] = $conference return this } /** * Retrieve a conference of this site. * @param {string} conf_label key for accessing the conference, usually a year * @return {Conference} the specified conference */ getConference(conf_label) { return this._conferences[conf_label] } /** * Return an object representing all conferences of this site. * FIXME this should return a deep clone, not a shallow clone * @return {Object} shallow clone of this site’s conferences object */ getConferencesAll() { //- NOTE returns shallow clone (like arr.slice()) return Object.assign({}, this._conferences) } /** * Set or get the current conference of this site. * If setting, provide the argument key for accessing the added conference. * If getting, provide no argument. * The current conference is the conference that is being promoted this cycle. * @param {string=} conf_label key for accessing the conference * @return {(ConfSite|Conference)} this site || the current conference */ currentConference(conf_label) { if (arguments.length) { this._conf_curr_key = conf_label return this } else { return this.getConference(this._conf_curr_key) } } /** * Set or get the previous conference of this site. * If setting, provide the argument key for accessing the added conference. * If getting, provide no argument. * The previous conference is the conference that was promoted last cycle. * @param {string=} conf_label key for accessing the conference * @return {(ConfSite|Conference)} this site || the previous conference */ prevConference(conf_label) { if (arguments.length) { this._conf_prev_key = conf_label return this } else return this.getConference(this._conf_prev_key) } /** * Set or get the next conference of this site. * If setting, provide the argument key for accessing the added conference. * If getting, provide no argument. * The next conference is the conference that will be promoted next cycle. * @param {string=} conf_label key for accessing the conference * @return {(ConfSite|Conference)} this site || the next conference */ nextConference(conf_label) { if (arguments.length) { this._conf_next_key = conf_label return this } else return this.getConference(this._conf_next_key) } /** * Initialize this site: add the proper pages. * This method should only be called once; it resets pages every time called. * @return {ConfSite} this site */ init() { var self = this function pageTitle() { return this.name() + ' | ' + self.name() } return self .removeAll() //- NOTE IMPORTANT .add(new ConfPage('Home', 'index.html') .title(self.name()) .description(self.slogan) .setIcon('home') ) .add(new ConfPage('Registration', 'registration.html') .title(pageTitle) .description(`Register for ${self.name()} here.`) .setIcon('shopping_cart') ) .add(new ConfPage('Program', 'program.html') .title(pageTitle) .description(`Program and agenda of ${self.name()}.`) .setIcon('event') ) .add(new ConfPage('Location', 'location.html') .title(pageTitle) .description(`Location and where to stay for ${self.name()}.`) .setIcon('flight') ) .add(new ConfPage('Speakers', 'speakers.html') .title(pageTitle) .description(`Current and prospective speakers at ${self.name()}.`) .setIcon('account_box') ) .add(new ConfPage('Sponsor', 'sponsor.html') .title(pageTitle) .description(`Sponsors of ${self.name()}.`) .setIcon('people') ) .add(new ConfPage('Exhibit', 'exhibit.html') .title(pageTitle) .description(`Exhibitors at ${self.name()}.`) .setIcon('work') ) .add(new ConfPage('About', 'about.html') .title(pageTitle) .description(`About ${self.name()}.`) .setIcon('info_outline') ) .add(new ConfPage('Contact', 'contact.html') .title(pageTitle) .description(`Contact us for questions and comments about ${self.name()}.`) .setIcon('email') ) } /** * Generate a color palette and return a style object with custom properties. * @param {Color} $primary the primary color for the site * @param {Color} $secondary the secondary color for the site * @return {Object<string>} a style object containg custom properties and color string values */ static colorStyles($primary, $secondary) { let primary_s2 = $primary.darken(2/3, true) let primary_s1 = $primary.darken(1/3, true) let primary_t1 = $primary.darken(1/3, true).lighten(1/3, false) // one-third to white let primary_t2 = $primary.darken(2/3, true).lighten(2/3, false) // two-thirds to white let secondary_s2 = $secondary.darken(2/3, true) let secondary_s1 = $secondary.darken(1/3, true) let secondary_t1 = $secondary.darken(1/3, true).lighten(1/3, false) // one-third to white let secondary_t2 = $secondary.darken(2/3, true).lighten(2/3, false) // two-thirds to white let _g1 = $primary.mix($secondary, 1/4).desaturate(7/8, true) let _g2 = $secondary.mix($primary, 1/4).desaturate(7/8, true) let gray_dk_s2 = _g1.lighten( 1/12 - _g1.hslLum(), false) let gray_dk_s1 = _g1.lighten( 2/12 - _g1.hslLum(), false) let gray_dk = _g1.lighten( 3/12 - _g1.hslLum(), false) let gray_dk_t1 = _g1.lighten( 4/12 - _g1.hslLum(), false) let gray_dk_t2 = _g1.lighten( 5/12 - _g1.hslLum(), false) let gray_lt_s2 = _g2.lighten( 7/12 - _g2.hslLum(), false) let gray_lt_s1 = _g2.lighten( 8/12 - _g2.hslLum(), false) let gray_lt = _g2.lighten( 9/12 - _g2.hslLum(), false) let gray_lt_t1 = _g2.lighten(10/12 - _g2.hslLum(), false) let gray_lt_t2 = _g2.lighten(11/12 - _g2.hslLum(), false) return { '--color-primary' : $primary.toString('hex'), '--color-secondary': $secondary.toString('hex'), '--color-gray_dk' : gray_dk.toString('hex'), '--color-gray_lt' : gray_lt.toString('hex'), '--color-primary-shade2' : primary_s2.toString('hex'), '--color-primary-shade1' : primary_s1.toString('hex'), '--color-primary-tint1' : primary_t1.toString('hex'), '--color-primary-tint2' : primary_t2.toString('hex'), '--color-secondary-shade2': secondary_s2.toString('hex'), '--color-secondary-shade1': secondary_s1.toString('hex'), '--color-secondary-tint1' : secondary_t1.toString('hex'), '--color-secondary-tint2' : secondary_t2.toString('hex'), '--color-gray_dk-shade2' : gray_dk_s2.toString('hex'), '--color-gray_dk-shade1' : gray_dk_s1.toString('hex'), '--color-gray_dk-tint1' : gray_dk_t1.toString('hex'), '--color-gray_dk-tint2' : gray_dk_t2.toString('hex'), '--color-gray_lt-shade2' : gray_lt_s2.toString('hex'), '--color-gray_lt-shade1' : gray_lt_s1.toString('hex'), '--color-gray_lt-tint1' : gray_lt_t1.toString('hex'), '--color-gray_lt-tint2' : gray_lt_t2.toString('hex'), } } } },{"./ConfPage.class.js":5,"csscolor":4,"sitepage":21}],7:[function(require,module,exports){ module.exports = class Conference { /** * A conference event. * It may have a name, theme, dates, (promoted) location, * passes, sessions, venues, speakers, * supporter levels and supporters, exhibitors, contact information, * important dates, organizers, and other properties. * Construct a Conference object. * The name, url, theme, start date, end date, and promoted location * are immutable and must be provided during construction. * @constructor * @param {Object=} $confinfo an object with the following immutable properties: * @param {string} $confinfo.name the name of this conference * @param {string} $confinfo.url the url of this conference * @param {string} $confinfo.theme the theme, or slogan, of this conference * @param {Date} $confinfo.start_date the starting date of this conference * @param {Date} $confinfo.end_date the ending date of this conference * @param {Object} $confinfo.promo_loc the promoted location of this conference * @param {string} $confinfo.promo_loc.text the promoted location displayed/abbreviated text (eg, "Portland, OR") * @param {string=} $confinfo.promo_loc.alt the accessible text of the location (eg, "Portland, Oregon") */ constructor($confinfo = {}) { /** @private @final */ this._NAME = $confinfo.name /** @private @final */ this._URL = $confinfo.url /** @private @final */ this._THEME = $confinfo.theme /** @private @final */ this._START = $confinfo.start_date /** @private @final */ this._END = $confinfo.end_date /** @private @final */ this._PROMO_LOC = $confinfo.promo_loc /** @private */ this._reg_periods = [] /** @private */ this._passes = [] /** @private */ this._sessions = [] /** @private */ this._venues = {} /** @private */ this._speakers = [] /** @private */ this._supporter_levels = [] /** @private */ this._supporter_lists = {} /** @private */ this._supporters = [] /** @private */ this._exhibitors = [] /** @private */ this._important_dates = [] /** @private */ this._organizers = [] /** @private */ this._social = {} /** @private */ this._regpd_curr_index = NaN /** @private */ this._venue_conf_key = '' } /** * Get the name of this conference. * @return {string} the name of this conference */ get name() { return this._NAME } /** * Get the URL of this conference. * @return {string} the URL of this conference */ get url() { return this._URL } /** * Get the theme of this conference. * The theme is a one-sentence or one-phrase slogan, * and may be changed from year to year (from conference to conference). * @return {string} the theme of this conference */ get theme() { return this._THEME || '' } /** * Get the start date of this conference. * @return {Date} the start date of this conference */ get startDate() { return this._START || new Date() } /** * Get the end date of this conference. * @return {Date} the end date of this conference */ get endDate() { return this._END || new Date() } /** * Get the promoted location of this conference. * The promoted location is not necessarily the actual postal address of the conference, * but rather a major city nearest to the conference used for * promotional and advertising purposes. * @return {{text:string, alt:string}} the promoted location for this conference */ get promoLoc() { return this._PROMO_LOC || {} } /** * Add a registration period to this conference. * @param {RegistrationPeriod} $registrationPeriod the registration period to add */ addRegistrationPeriod($registrationPeriod) { this._reg_periods.push($registrationPeriod) return this } /** * Retrieve a registration period of this conference. * @param {string} name the name of the registration period * @return {?RegistrationPeriod} the specified registration period */ getRegistrationPeriod(name) { return this._reg_periods.find(($registrationPeriod) => $registrationPeriod.name===name) || null } /** * Retrieve all registration periods of this conference. * @return {Array<RegistrationPeriod>} a shallow array of all registration periods of this conference. */ getRegistrationPeriodsAll() { return this._reg_periods.slice() } /** * Set or get the current registration period. * The current registration period is the registration period that is active at this time. * @param {string=} reg_period_name the name of the registration period to set current * @return {(Conference|RegistrationPeriod)} this conference || the set current registration period */ currentRegistrationPeriod(reg_period_name) { if (arguments.length) { this._regpd_curr_index = this._reg_periods.indexOf(this.getRegistrationPeriod(reg_period_name)) return this } else return this._reg_periods[this._regpd_curr_index] } /** * Add a pass to this conference. * @param {Pass} $pass the pass to add */ addPass($pass) { this._passes.push($pass) return this } /** * Retrieve a pass of this conference. * @param {string} name the name of the pass * @return {?Pass} the specified pass */ getPass(name) { return this._passes.find(($pass) => $pass.name===name) || null } /** * Retrieve all passes of this conference. * @return {Array<Pass>} a shallow array of all passes of this conference */ getPassesAll() { return this._passes.slice() } /** * Add a session to this conference. * @param {Session} $session the session to add */ addSession($session) { this._sessions.push($session) return this } /** * Retrieve a session of this conference. * @param {string} name the name of the session * @return {?Session} the specified session */ getSession(name) { return this._sessions.find(($session) => $session.name===name) || null } /** * Retrieve all sessions of this conference. * @return {Array<Session>} a shallow array of all sessions of this conference */ getSessionsAll() { return this._sessions.slice() } /** * Add a venue to this conference. * @param {string} venue_label key for accessing the venue * @param {Place} $place the venue to add */ addVenue(venue_label, $place) { this._venues[venue_label] = $place return this } /** * Retrieve a venue of this conference. * @param {string} venue_label the key for accessing the venue * @return {Place} the specified venue */ getVenue(venue_label) { return this._venues[venue_label] } /** * Retrieve all venues of this conference. * @return {Object<Place>} a shallow copy of the venues object of this conference */ getVenuesAll() { //- NOTE returns shallow clone (like arr.slice()) return Object.assign({}, this._venues) } /** * Set or get the official conference venue for this conference. * The official conference venue is the venue at which this conference is held. * @param {string} venue_label the key for accessing the venue * @return {(Conference|Place)} this conference || the set conference venue */ officialVenue(venue_label) { if (arguments.length) { this._venue_conf_key = venue_label return this } else return this.getVenue(this._venue_conf_key) } /** * Add a speaker to this conference. * @param {Person} $person the speaker to add */ addSpeaker($person) { this._speakers.push($person) return this } /** * Retrieve a speaker of this conference. * @param {string} id the id of the speaker * @return {?Person} the specified speaker */ getSpeaker(id) { return this._speakers.find(($person) => $person.id===id) || null } /** * Retrieve all speakers of this conference. * @return {Array<Person>} a shallow array of all speakers of this conference */ getSpeakersAll() { return this._speakers.slice() } /** * Add a supporter level to this conference. * @param {SupporterLevel} $supporterLevel the supporter level to add * @return {Conference} this conference */ addSupporterLevel($supporterLevel) { this._supporter_levels.push($supporterLevel) return this } /** * Retrieve a supporter level of this conference. * @param {string} name the name of the supporter level * @return {?SupporterLevel} the specified supporter level */ getSupporterLevel(name) { return this._supporter_levels.find(($supporterLevel) => $supporterLevel.name===name) || null } /** * Retrieve all supporter levels of this conference. * @return {Array<SupporterLevel>} a shallow array of all supporter levels of this conference */ getSupporterLevelsAll() { return this._supporter_levels.slice() } /** * Add a named subarray of supporter levels to this conference. * @param {string} type the name of the subarray * @param {Array<string>} supporter_level_names an array of pre-existing SupporterLevel names * @return {Conference} this conference */ addSupporterLevelQueue(type, supporter_level_names) { this._supporter_lists[type] = supporter_level_names return this } /** * Get a named subarray of supporter levels of this conference. * @param {string} type the name of the subarray * @return {Array<SupporterLevel>} the array of SupporterLevel objects belonging to the type */ getSupporterLevelQueue(type) { return (this._supporter_lists[type] || []).map((el) => this.getSupporterLevel(el)) } /** * Add a supporter to this conference. * @param {Supporter} $supporter the supporter to add * @return {Conference} this conference */ addSupporter($supporter) { this._supporters.push($supporter) return this } /** * Retrieve a supporter of this conference. * @param {string} name the name of the supporter * @return {?Supporter} the specified supporter */ getSupporter(name) { return this._supporters.find(($supporter) => $supporter.name===name) || null } /** * Retrieve all supporters of this conference. * @return {Array<Supporter>} a shallow array of all supporters of this conference */ getSupportersAll() { return this._supporters.slice() } /** * Add an exhibitor to this conference. * @param {Exhibitor} $exhibitor the exhibitor to add * @return {Conference} this conference */ addExhibitor($exhibitor) { this._exhibitors.push($exhibitor) return this } /** * Retrieve an exhibitor of this conference. * @param {string} name the name of the exhibitor * @return {?Exhibitor} the specified exhibitor */ getExhibitor(name) { return this._exhibitors.find(($exhibitor) => $exhibitor.name===name) || null } /** * Retrieve all exhibitors of this conference. * @return {Array<Exhibitor>} a shallow array of all exhibitors of this conference */ getExhibitorsAll() { return this._exhibitors.slice() } /** * Add an important date to this conference. * @param {ImportantDate} $importantDate the important date to add */ addImportantDate($importantDate) { this._important_dates.push($importantDate) return this } /** * Retrieve an important date of this conference. * @param {string} name the name of the important date * @return {?ImportantDate} the specified important date */ getImportantDate(name) { return this._important_dates.find(($importantDate) => $importantDate.name===name) || null } /** * Retrieve all important dates of this conference. * @return {Array<ImportantDate>} a shallow array of all important dates of this conference */ getImportantDatesAll() { return this._important_dates.slice() } /** * Add an organizer of this conference. * An organizer is a chairperson, steering committee member, or other person who is * responsible for organizing the conference. * @param {Person} $person the organizer to add */ addOrganizer($person) { this._organizers.push($person) return this } /** * Retrieve an organizer of this conference. * @param {string} id the name of the organizer * @return {?Person} the specified organizer */ getOrganizer(id) { return this._organizers.find(($person) => $person.id===id) || null } /** * Retrieve all organizers of this conference. * @return {Array<Person>} a shallow array of all organizers of this conference */ getOrganizersAll() { return this._organizers.slice() } /** * Add a social network profile to this conference. * @param {string} network_name the name of the social network * @param {string} url the URL of this conference’s profile on the network * @param {string=} text optional advisory text * @return {Conference} this conference */ addSocial(network_name, url, text) { this._social[network_name] = { url: url, text: text } return this } /** * Retrieve a social network profile of this conference. * @param {string} network_name the name of the social network * @return {Object} an object representing the social network profile */ getSocial(network_name) { return this._social[network_name] } /** * Return an object representing all social network profiles of this conference. * @return {Object} shallow clone of this conference’s social object */ getSocialAll() { //- NOTE returns shallow clone (like arr.slice()) return Object.assign({}, this._social) // shallow clone this.social into {} } // setPrice(reg_period, pass, membership, price) { // reg_period = reg_period.name || reg_period // pass = pass.name || pass // membership = membership.name || membership // this.registration = this.registration || {} // this.registration[reg_period][pass][membership] = price // return this // } /** * NOTE: TYPE DEFINITION * A group of sessions, all of which share the same date (excluding time of day). * Contains two properties: * - `datestr` - a string representing the date by which the sessions are grouped * - `sessions` - an array of those sessions * @typedef {Object} SessionGroup * @property {string} datestr - string in 'YYYY-MM-DD' format of all the sessions in the group * @property {Array<Session>} sessions - an array whose members all have the same date */ /** * Categorize all the sessions of this conference by date and return the grouping. * Sessions with the same date (excluding time of day) are grouped together. * @see Session * @param {boolean=} starred if true, only consider sessions that are starred * @return {Array<SessionGroup>} an array grouping the sessions together */ groupSessions(starred) { let all_sessions = this.getSessionsAll().filter(($session) => (starred) ? $session.isStarred() : true) let $groupings = [] function equalDays(date1, date2) { return date1.toISOString().slice(0,10) === date2.toISOString().slice(0,10) } all_sessions.forEach(function ($session) { if (!$groupings.find(($sessionGroup) => equalDays($sessionGroup.dateday, $session.startDate))) { $groupings.push({ dateday : $session.startDate, sessions: all_sessions.filter((_event) => equalDays(_event.startDate, $session.startDate)), }) } }) return $groupings } } },{}],8:[function(require,module,exports){ module.exports = class Exhibitor { /** * An organization exhibiting at a conference or series of conferences. * Assigned at the site level, not at an individual conference. * Construct a new Exhibitor object, given an (immutable) name. * @constructor * @param {string} name the name of the exhibiting organization */ constructor(name) { /** @private @final */ this._NAME = name /** @private */ this._url = '' /** @private */ this._img = '' /** @private */ this._description = '' /** @private */ this._booth = NaN /** @private */ this._is_sponsor = false } /** * Get the name of this exhibitor. * @return {string} the name of this exhibitor */ get name() { return this._NAME } /** * Set or get the URL of this exhibitor. * @param {string=} url the URL of this exhibitor * @return {(Exhibitor|string)} this exhibitor || the URL of this exhibitor */ url(url) { if (arguments.length) { this._url = url return this } else return this._url } /** * Set or get the image of this exhibitor. * @param {string=} img the image of this exhibitor * @return {(Exhibitor|string)} this exhibitor || the image of this exhibitor */ img(img) { if (arguments.length) { this._img = img return this } else return this._img } /** * Set a short, html-friendly description for this exhibitor. * @param {string} html html-friendly content * @return {Exhibitor} this exhibitor */ setDescription(html) { this._description = html return this } /** * Get the description of this exhibitor. * @param {boolean=} unescaped whether or not the returned string should be escaped * @return {string} the description of this exhibitor */ getDescription(unescaped) { return ((unescaped) ? '<!-- warning: unescaped code -->' : '') + this._description } /** * Set or get the booth number of this exhibitor. * @param {number=} num the booth number of this exhibitor * @return {(Exhibitor|number)} this exhibitor || the booth number of this exhibitor */ booth(num) { if (arguments.length) { this._booth = num return this } else return this._booth } /** * Set or get whether this exhibitor is also a sponsor. * @see Supporter * @param {boolean=} flag `true` if this exhibitor is also a sponsor * @return {(Exhibitor|boolean)} this exhibitor || `true` if this exhibitor is also a sponsor */ isSponsor(flag) { if (arguments.length) { this._is_sponsor = flag return this } else return this._is_sponsor } } },{}],9:[function(require,module,exports){ module.exports = class ImportantDate { /** * An important date. * Construct an ImportantDate object. * The name and start time must be provided during construction * and are immutable. End time is optional. * @constructor * @param {Object=} $actioninfo an object with the following immutable properties: * @param {string} $actioninfo.name the name of the important date * @param {Date} $actioninfo.start_time the start time of the important date * @param {Date=} $actioninfo.end_time the start end of the important date */ constructor($actioninfo = {}) { /** @private @final */ this._NAME = $actioninfo.name /** @private @final */ this._START = $actioninfo.start_time /** @private @final */ this._END = $actioninfo.end_time /** @private */ this._url = '' /** @private */ this._is_starred = false } /** * Get the name of this important date. * @return {string} the name of this important date */ get name() { return this._NAME } /** * Return the start date value of this important date. * @return {Date} the start date of this important date */ get startTime() { return this._START || new Date() } /** * Return the end date value of this important date. * @return {?Date} the end date of this important date */ get endTime() { return this._END || null } /** * Set or get the url of this important date. * @param {string=} url the url of this important date * @return {(ImportantDate|string)} this important date || the url of this important date */ url(url) { if (arguments.length) { this._url = url return this } else return this._url } /** * Mark this important date as starred. * @param {boolean=true} bool if true, mark as starred * @return {ImportantDate} this important date */ star(bool) { this._is_starred = (arguments.length) ? bool : true return this } /** * Get the starred status of this important date. * @return {boolean} whether this important date is starred */ isStarred() { return this._is_starred } } },{}],10:[function(require,module,exports){ module.exports = class Pass { /** * A set of prices for registration. * Constructs a Pass object. * @constructor * @param {string} name the name or type of the pass */ constructor(name) { /** @private @final */ this._NAME = name /** @private */ this._description = '' /** @private */ this._fineprint = '' /** @private */ this._attend_types = [] /** @private */ this._is_starred = false } /** * Get the name of this pass. * @return {string} the name of this pass */ get name() { return this._NAME } /** * Set or get the description of this pass. * @param {string=} text the description of this pass * @return {(Pass|string)} this pass || the description of this pass */ description(text) { if (arguments.length) { this._description = text return this } else return this._description } /** * Set or get the fine print of this pass. * @param {string=} text the fine print of this pass * @return {(Pass|string)} this pass || the fine print of this pass */ fineprint(text) { if (arguments.length) { this._fineprint = text return this } else return this._fineprint } /** * Add an attendee type to this pass. * @param {Pass.AttendeeType} $attendeeType the attendee type to add */ addAttendeeType($attendeeType) { this._attend_types.push($attendeeType) return this } // /** // * REVIEW: use this method if class AttendeeType is removed. // * Add an attendee type to this pass. // * @param {string} name the name of the attendee type // * @param {boolean} is_featured whether this attendee type is marked as “featured” // */ // addAttendeeType(name, is_featured) { // this._attend_types.push({name: name, isFeatured: is_featured}) // return this // } /** * Retrieve an attendee type of this pass. * @param {string} name the name of the attendee type to get * @return {?Pass.AtendeeType} the specified attendee type */ getAttendeeType(name) { return this._attend_types.find(($attendeeType) => $attendeeType.name===name) || null } /** * Retreive all attendee types of this pass. * @return {Array<Pass.AttendeeType>} a shallow array of all attendee types of this pass */ getAttendeeTypesAll() { return this._attend_types.slice() } /** * Mark this pass as starred. * @param {boolean=true} bool if true, mark as starred * @return {Pass} this pass */ star(bool = true) { this._is_starred = bool return this } /** * Get the starred status of this pass. * @return {boolean} whether this pass is starred */ isStarred() { return this._is_starred } /** * REVIEW may not need this class * An Attendee Type ("Member", "Non-Member", etc) of a pass. * @inner */ static get AttendeeType() { return class { /** * An Attendee Type ("Member", "Non-Member", etc) of a pass. * Construct an AttendeeType object, given a name and * a boolean specifying whether the object is featured. * Both name and “featured” are immutable. * @constructor * @param {string} name the name of the attendee type * @param {boolean} is_featured whether this attendee type is marked as “featured” */ constructor(name, is_featured) { /** @private @final */ this._NAME = name /** @private @final */ this._IS_FEATURED = is_featured } /** * Get the name of this attendee type. * @return {string} the name of this attendee type */ get name() { return this._NAME } /** * Get whether this attendee type is featured. * @return {boolean} whether this attendee type is featured */ get isFeatured() { return this._IS_FEATURED } } } } },{}],11:[function(require,module,exports){ var Util = require('./Util.class.js') module.exports = class Person { /** * A person. * Can be used for any role on the suite. * Constructs a Person object. * @constructor * @param {string} id a unique identifier of the person * @param {Object=} $name an object containing the following: * @param {string} $name.honorific_prefix a prefix, if any (e.g. 'Mr.', 'Ms.', 'Dr.') * @param {string} $name.given_name the person’s first name * @param {string} $name.additional_name the person’s middle name or initial * @param {string} $name.family_name the person’s last name * @param {string} $name.honorific_suffix the suffix, if any (e.g. 'M.D.', 'P.ASCE') */ constructor(id, $name = {}) { /** @private @final */ this._ID = id /** @private @final */ this._NAME = { honorific_prefix: $name.honorific_prefix, given_name : $name.given_name, additional_name : $name.additional_name, family_name : $name.family_name, honorific_suffix: $name.honorific_suffix, } /** @private */ this._jobTitle = '' /** @private */ this._affiliation = '' /** @private */ this._img = '' /** @private */ this._email = '' /** @private */ this._telephone = '' /** @private */ this._url = '' /** @private */ this._social = {} /** @private */ this._is_starred = false } /** * Get the id of this person. * @return {string} the unique id of this person */ get id() { return this._ID } /** * Get the name object of this person. * @return {Object} a shallow object representing this person’s name */ get name() { //- NOTE returns shallow clone (like arr.slice()) return Object.assign({}, this._NAME) } /** * Set or get this person’s job title. * @param {string=} text the job title * @return {(Person|string)} this person || the job title */ jobTitle(text) { if (arguments.length) { this._jobTitle = text return this } else return this._jobTitle } /** * Set or get this person’s affiliation. * @param {string=} text the affiliation * @return {(Person|string)} this person || the affiliation */ affiliation(text) { if (arguments.length) { this._affiliation = text return this } else return this._affiliation } /** * Set or get this person’s headshot image. * @param {string=} text the url pointing to the headshot image * @return {(Person|string)} this person || the headshot image url */ img(url) { if (arguments.length) { this._img = url return this } else return this._img } /** * Set or get this person’s email address. * @param {string=} text the email address * @return {(Person|string)} this person || the email address */ email(text) { if (arguments.length) { this._email = text return this } else return this._email } /** * Set or get this person’s telephone number. * @param {string=} text the telephone number * @return {(Person|string)} this person || the telephone number */ phone(text) { if (arguments.length) { this._telephone = text return this } else return this._telephone } /** * Set or get this person’s homepage. * @param {string=} text the homepage * @return {(Person|string)} this person || the homepage */ url(text) { if (arguments.length) { this._url = text return this } else return this._url } /** * Add a social network profile to this person. * @param {string} network_name the name of the social network * @param {string} url the URL of this person’s profile on the network * @param {string=} text optional advisory text * @return {Person} this person */ addSocial(network_name, url, text) { this._social[network_name] = { url: url, text: text } return this } /** * Retrieve a social network profile of this person. * @param {string} network_name the name of the social network * @return {Object} an object representing the social network profile */ getSocial(network_name) { return this._social[network_name] } /** * Return an object representing all social network profiles of this person. * @return {Object} shallow clone of this person’s social object */ getSocialAll() { //- NOTE returns shallow clone (like arr.slice()) return Object.assign({}, this._social) // shallow clone this.social into {} } /** * Mark this person as starred. * @param {boolean=true} bool if true, mark as starred * @return {Person} this person */ star(bool) { this._is_starred = (arguments.length) ? bool : true return this } /** * Get the starred status of this person. * @return {boolean} whether this person is starred */ isStarred() { return this._is_starred } /** * Output this person’s name and other information as HTML. * NOTE: remember to wrap this output with an `[itemscope=""][itemtype="https://schema.org/Person"]`. * Also remember to unescape this code, or else you will get `&lt;`s and `&gt;`s. * @param {Person.Format} format how to display the output * @return {string} a string representing an HTML DOM snippet */ html(format) { switch (format) { case Person.Format.NAME: return ` <span itemprop="name"> <span itemprop="givenName">${this.name.given_name}</span> <span itemprop="familiyName">${this.name.family_name}</span> </span> ` break; case Person.Format.FULL_NAME: return ` <span itemprop="name"> <span itemprop="givenName">${this.name.given_name}</span> <span itemprop="additionalName">${this.name.additional_name}</span> <span itemprop="familiyName">${this.name.family_name}</span> </span> ` break; case Person.Format.ENTIRE_NAME: var output = this.html(Person.Format.FULL_NAME) // using `var` because `let` works poorly in `switch` if (this.name.honorific_prefix) { output = `<span itemprop="honorificPrefix">${this.name.honorific_prefix}</span> ${output}` } if (this.name.honorific_suffix) { output = `${output}, <span itemprop="honorificSuffix">${this.name.honorific_suffix}</span>` } return output break; case Person.Format.AFFILIATION: return `${this.html(Person.Format.ENTIRE_NAME)}, <span class="-fs-t" itemprop="affiliation" itemscope="" itemtype="http://schema.org/Organization"> <span itemprop="name">${this.affiliation()}</span> </span> ` break; case Person.Format.CONTACT: var output = ` <a href="mailto:${this.email()}">${this.html(Person.Format.NAME)}</a> ` if (this.jobTitle()) { output = `${output}, <span itemprop="jobTitle">${this.jobTitle()}</span>` } if (this.phone()) { output = `${output} | <a href="tel:${this.phone()}" itemprop="telephone">${this.phone()}</a>` } return output break; default: return this.toString() } } /** * Enum for name formats. * @enum {String} */ static get Format() { return { /** First Last */ NAME : 'name', /** First Middle Last */ FULL_NAME : 'full', /** Px. First Middle Last, Sx. */ ENTIRE_NAME: 'entire', /** First Middle Last, Affiliation */ AFFILIATION: 'affiliation', /** First Last, Director of ... | 555-555-5555 */ CONTACT : 'contact', } } } },{"./Util.class.js":17}],12:[function(require,module,exports){ var Util = require('./Util.class.js') module.exports = class Place { /** * A place. * Mostly used for hotel & venue locations. * Constructs a Place object. * @constructor * @param {string} name the name of the place * @param {Object=} $placeinfo an object containing the following: * @param {string} $placeinfo.street_address the street and number, eg: '1801 Alexander Bell Drive' * @param {string} $placeinfo.address_locality the city name, eg: 'Reston' * @param {string} $placeinfo.address_region the state code *[1], eg: 'VA' * @param {string} $placeinfo.postal_code the zip code, eg: '22901-4382' * @param {string} $placeinfo.country the country code *[1], eg: 'US' * @param {string} $placeinfo.telephone the telephone number (no spaces), eg: '+1-800-548-2723' * @param {string} $placeinfo.url the URL of homepage, eg: 'http://www.asce.org/' * *[1] zip, state, and country codes should match the ISO-3166 standard format. see https://en.wikipedia.org/wiki/ISO_3166 */ constructor(name, $placeinfo = {}) { /** @private @final */ this._NAME = name /** @private @final */ this._STREET_ADDRESS = $placeinfo.street_address /** @private @final */ this._ADDRESS_LOCALITY = $placeinfo.address_locality /** @private @final */ this._ADDRESS_REGION = $placeinfo.address_region /** @private @final */ this._POSTAL_CODE = $placeinfo.postal_code /** @private @final */ this._ADDRESS_COUNTRY = $placeinfo.address_country /** @private @final */ this._TELEPHONE = $placeinfo.telephone /** @private @final */ this._URL = $placeinfo.url } /** * Get the name of this place. * @return {string} the name of this place */ get name() { return this._NAME } /** * Get the street address of this place. * @return {string} the street address of this place */ get streetAddress() { return this._STREET_ADDRESS } /** * Get the address locality (city/town) of this place. * @return {string} the address locality (city/town) of this place */ get addressLocality() { return this._ADDRESS_LOCALITY } /** * Get the address region (state/province) of this place. * @return {string} the address region (state/province) of this place */ get addressRegion() { return this._ADDRESS_REGION } /** * Get the postal (zip) code of this place. * @return {string} the postal (zip) code of this place */ get postalCode() { return this._POSTAL_CODE } /** * Get the country of this place. * @return {string} the country of this place */ get addressCountry() { return this._ADDRESS_COUNTRY } /** * Get the telephone number for this place. * @return {string} the telephone number for this place */ get telephone() { return this._TELEPHONE } /** * Get the URL for the homepage of this place. * @return {string} the URL for the homepage of this place */ get url() { return this._URL } /** * Output this person’s name and other information as HTML. * NOTE: remember to wrap this output with an `[itemscope=""][itemtype="https://schema.org/Place"]`. * Also remember to unescape this code, or else you will get `&lt;`s and `&gt;`s. * @return {string} a string representing an HTML DOM snippet */ html() { let $name = `<b class="h-Clearfix" itemprop="name">${this.name}</b>` if (this.url) $name = `<a href="${this.url}" itemprop="url">${$name}</a>` return ` ${$name} <span itemprop="address" itemscope="" itemtype="https://schema.org/PostalAddress"> <span class="h-Clearfix" itemprop="streetAddress">${this.streetAddress}</span> <span itemprop="addressLocality">${this.addressLocality}</span>, <span itemprop="addressRegion">${this.addressRegion}</span> <span class="h-Clearfix" itemprop="postalCode">${this.postalCode}</span> ${(this.addressCountry) ? `<span class="h-Clearfix" itemprop="addressCountry">${this.addressCountry}</span>` : ''} </span> ${(this.telephone) ? `<a href="tel:${this.telephone}" itemprop="telephone">${this.telephone}</a>` : ''} ` } } },{"./Util.class.js":17}],13:[function(require,module,exports){ var Util = require('./Util.class.js') module.exports = class RegistrationPeriod { /** * REVIEW may not need this class * An interval of dates in which registration prices are set. * Assigned at the conference level. * Construct a RegistrationPeriod object. * The name, start date, and end date * are immutable and must be provided during construction. * @constructor * @param {Object=} $periodinfo an object with the following immutable properties: * @param {string} $periodinfo.name the name of the registration period (e.g., 'Early Bird') * @param {Date} $periodinfo.start_date the date on which this registration period starts * @param {Date} $periodinfo.end_date the date on which this registration period ends */ constructor($periodinfo = {}) { /** @private @final */ this._NAME = $periodinfo.name /** @private @final */ this._START = $periodinfo.start_date /** @private @final */ this._END = $periodinfo.end_date /** @private */ this._icon = null } /** * Get the name of this registration period. * @return {string} the name of this registration period */ get name() { return this._NAME } /** * Get the start date of this registration period. * @return {Date} the start date of this registration period */ get startDate() { return this._START || new Date() } /** * Get the end date of this registration period. * @return {Date} the end date of this registration period */ get endDate() { return this._END || new Date() } /** * Set the icon of this registration period. * REVIEW: if icons are the same suite-wide, this can be removed. * @param {string} key the keyword of the icon to set */ setIcon(key) { this._icon = Util.ICON_DATA.find((item) => item.content===key) return this } /** * Get the icon of this registration period. * REVIEW: if icons are the same suite-wide, this can be removed. * @param {boolean=} fallback if true, get the unicode code point * @return {string} if fallback, the unicode code point, else, the keyword of the icon */ getIcon(fallback) { return (this._icon) ? Util.iconToString(this._icon, fallback) : '' } } },{"./Util.class.js":17}],14:[function(require,module,exports){ module.exports = class Session { /** * A program event. * Construct a Session object. * The name, start date, and end date * are immutable and must be provided during construction. * @constructor * @param {Object=} $eventinfo an object with the following immutable properties: * @param {string} $eventinfo.name the name of the session * @param {Date} $eventinfo.start_date the start date of the session * @param {Date} $eventinfo.end_date the end date of the session */ constructor($eventinfo = {}) { /** @private */ this._NAME = $eventinfo.name /** @private */ this._START = $eventinfo.start_date /** @private */ this._END = $eventinfo.end_date /** @private */ this._url = '' /** @private */ this._is_starred = false } /** * Get the name of this session. * @return {string} the name of this session */ get name() { return this._NAME } /** * Get the start date of this session. * @return {Date} the start date of this session */ get startDate() { return this._START || new Date() } /** * Get the end date of this session. * @return {Date} the end date of this session */ get endDate() { return this._END || new Date() } /** * Set or get the url of this session. * @param {string=} url the url of this session * @return {(Session|string)} this session || the url of this session */ url(url) { if (arguments.length) { this._url = url return this } else return this._url } /** * Mark this session as starred. * @param {boolean=true} bool if true, mark as starred * @return {Session} this session */ star(bool) { this._is_starred = (arguments.length) ? bool : true return this } /** * Get the starred status of this session. * @return {boolean} whether this session is starred */ isStarred() { return this._is_starred } } },{}],15:[function(require,module,exports){ module.exports = class Supporter { /** * An organization supporting a conference or series of conferences. * Assigned at the site level, not at an individual conference. * Construct a supporter object, given an (immutable) name. * @constructor * @param {string} name the name of the supporting organization */ constructor(name) { /** @private @final */ this._NAME = name /** @private */ this._url = '' /** @private */ this._img = '' /** @private */ this._level = '' } /** * Get the name of this supporter. * @return {string} the name of this supporter */ get name() { return this._NAME } /** * Set or get the URL of this supporter. * @param {string=} url the URL of this supporter * @return {(Supporter|string)} this supporter || the URL of this suppoter */ url(url) { if (arguments.length) { this._url = url return this } else return this._url } /** * Set or get the image of this supporter. * @param {string=} img the image of this supporter * @return {(Supporter|string)} this supporter || the image of this suppoter */ img(img) { if (arguments.length) { this._img = img return this } else return this._img } /** * Set or get the supporter level in which this supporter belongs. * @see SupporterLevel * @param {string=} level a string matching a the name of a SupporterLevel; the level this supporter belongs in * @return {(Supporter|string)} this supporter || name of the corresponding SupporterLevel object */ level(level) { if (arguments.length) { this._level = level return this } else return this._level } } },{}],16:[function(require,module,exports){ module.exports = class SupporterLevel { /** * A group of supporters with a similar level of support or donation. * Assigned at the site level, not at an individual conference. * Construct a SupporterLevel object, given an (immutable) name. * @constructor * @param {string} name the name of the level (e.g. 'Gold') */ constructor(name) { /** @private @final */ this._NAME = name /** @private */ this._size = SupporterLevel.LogoSize.DEFAULT } /** * Get the name of this supporter level. * @return {string} the name of this supporter level */ get name() { return this._NAME } /** * Set or get the sizing of this supporter level. * The sizing informs the size of the supporter logo in this supporter level. * @param {SupporterLevel.LogoSize=} size the sizing of this supporter level’s logos * @return {(SupporterLevel|SupporterLevel.LogoSize)} this supporter level | the sizing */ size(size = SupporterLevel.LogoSize.DEFAULT) { if (arguments.length) { this._size = size return this } else return this._size } /** * Enum for supporter level logo sizes. * @enum {string} */ static get LogoSize() { return { /** Logo size for top-level supporters. */ LARGE : 'lrg', /** Logo size for mid-level supporters. */ MEDIUM: 'med', /** Logo size for low-level supporters. */ SMALL : 'sml', /** Default value. */ get DEFAULT() { return this.LARGE }, } } } },{}],17:[function(require,module,exports){ module.exports = class Util { /** * A set of static values and functions used site-wide. * @private * @constructor */ constructor() {} /** * List of full month names in English. * @type {Array<string>} */ static get MONTH_NAMES() { return [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ] } /** * List of full day names in English. * @type {Array<string>} */ static get DAY_NAMES() { return [ 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', ] } /** * NOTE: Type Definition * @typedef {Object} StateObj * @property {string} index - the postal code for the state * @property {string} name - the name of the state * @property {number} pop - population in people * @property {number} area - area in square km * @property {Util.Region} region - region of US */ /** * List of US State objects. * @type {Array<StateObj>} */ static get STATE_DATA() { return [ { index: 'AL', name: 'Alabama', pop: 4779736, area: 52419, region: Util.Region.SOUTH }, { index: 'AK', name: 'Alaska', pop: 710231, area: 663267, region: Util.Region.WEST }, { index: 'AZ', name: 'Arizona', pop: 6392017, area: 113998, region: Util.Region.SOUTHWEST }, { index: 'AR', name: 'Arkansas', pop: 2915918, area: 53179, region: Util.Region.SOUTH }, { index: 'CA', name: 'California', pop: 37253956, area: 163696, region: Util.Region.WEST }, { index: 'CO', name: 'Colorado', pop: 5029196, area: 104094, region: Util.Region.WEST }, { index: 'CT', name: 'Connecticut', pop: 3574097, area: 5543, region: Util.Region.NORTHEAST }, { index: 'DE', name: 'Delaware', pop: 897934, area: 2489, region: Util.Region.NORTHEAST }, { index: 'FL', name: 'Florida', pop: 18801310, area: 65755, region: Util.Region.SOUTH }, { index: 'GA', name: 'Georgia', pop: 9687653, area: 59425, region: Util.Region.SOUTH }, { index: 'HI', name: 'Hawaii', pop: 1360301, area: 10931, region: Util.Region.WEST }, { index: 'ID', name: 'Idaho', pop: 1567582, area: 83570, region: Util.Region.WEST }, { index: 'IL', name: 'Illinois', pop: 12830632, area: 57914, region: Util.Region.MIDWEST }, { index: 'IN', name: 'Indiana', pop: 6483802, area: 36418, region: Util.Region.MIDWEST }, { index: 'IA', name: 'Iowa', pop: 3046355, area: 56272, region: Util.Region.MIDWEST }, { index: 'KS', name: 'Kansas', pop: 2853118, area: 82277, region: Util.Region.MIDWEST }, { index: 'KY', name: 'Kentucky', pop: 4339367, area: 40409, region: Util.Region.SOUTH }, { index: 'LA', name: 'Louisiana', pop: 4533372, area: 51840, region: Util.Region.SOUTH }, { index: 'ME', name: 'Maine', pop: 1328361, area: 35385, region: Util.Region.NORTHEAST }, { index: 'MD', name: 'Maryland', pop: 5773552, area: 12407, region: Util.Region.NORTHEAST }, { index: 'MA', name: 'Massachusetts', pop: 6547629, area: 10555, region: Util.Region.NORTHEAST }, { index: 'MI', name: 'Michigan', pop: 9883640, area: 96716, region: Util.Region.MIDWEST }, { index: 'MN', name: 'Minnesota', pop: 5303925, area: 86939, region: Util.Region.MIDWEST }, { index: 'MS', name: 'Mississippi', pop: 2967297, area: 48430, region: Util.Region.SOUTH }, { index: 'MO', name: 'Missouri', pop: 5988927, area: 69704, region: Util.Region.MIDWEST }, { index: 'MT', name: 'Montana', pop: 989415, area: 147042, region: Util.Region.WEST }, { index: 'NE', name: 'Nebraska', pop: 1826341, area: 77354, region: Util.Region.MIDWEST }, { index: 'NV', name: 'Nevada', pop: 2700551, area: 110561, region: Util.Region.WEST }, { index: 'NH', name: 'New Hampshire', pop: 1316470, area: 9350, region: Util.Region.NORTHEAST }, { index: 'NJ', name: 'New Jersey', pop: 8791894, area: 8721, region: Util.Region.NORTHEAST }, { index: 'NM', name: 'New Mexico', pop: 2059179, area: 121589, region: Util.Region.SOUTHWEST }, { index: 'NY', name: 'New York', pop: 19378102, area: 54556, region: Util.Region.NORTHEAST }, { index: 'NC', name: 'North Carolina', pop: 9535483, area: 53819, region: Util.Region.SOUTH }, { index: 'ND', name: 'North Dakota', pop: 672591, area: 70700, region: Util.Region.MIDWEST }, { index: 'OH', name: 'Ohio', pop: 11536504, area: 44825, region: Util.Region.MIDWEST }, { index: 'OK', name: 'Oklahoma', pop: 3751351, area: 69898, region: Util.Region.SOUTHWEST }, { index: 'OR', name: 'Oregon', pop: 3831074, area: 98381, region: Util.Region.WEST }, { index: 'PA', name: 'Pennsylvania', pop: 12702379, area: 46055, region: Util.Region.NORTHEAST }, { index: 'RI', name: 'Rhode Island', pop: 1052567, area: 1545, region: Util.Region.NORTHEAST }, { index: 'SC', name: 'South Carolina', pop: 4625364, area: 32020, region: Util.Region.SOUTH }, { index: 'SD', name: 'South Dakota', pop: 814180, area: 77117, region: Util.Region.MIDWEST }, { index: 'TN', name: 'Tennessee', pop: 6346105, area: 42143, region: Util.Region.SOUTH }, { index: 'TX', name: 'Texas', pop: 25145561, area: 268581, region: Util.Region.SOUTHWEST }, { index: 'UT', name: 'Utah', pop: 2763885, area: 84899, region: Util.Region.WEST }, { index: 'VT', name: 'Vermont', pop: 625741, area: 9614, region: Util.Region.NORTHEAST }, { index: 'VA', name: 'Virginia', pop: 8260405, area: 42774, region: Util.Region.SOUTH }, { index: 'WA', name: 'Washington', pop: 6971406, area: 71300, region: Util.Region.WEST }, { index: 'WV', name: 'West Virginia', pop: 1854304, area: 24230, region: Util.Region.SOUTH }, { index: 'WI', name: 'Wisconsin', pop: 5686986, area: 65498, region: Util.Region.MIDWEST }, { index: 'WY', name: 'Wyoming', pop: 563626, area: 97814, region: Util.Region.WEST }, ] } /** * NOTE: Type Definition * @typedef {Object} Icon * @property {string} content - the keyword used for the ligature * @property {string} fallback - unicode code point * @property {string} html - html entity */ /** * List of icon objects used in Conf styles. * @type {Array<Icon>} */ static get ICON_DATA() { return [ { content: 'home' , fallback: '\uE88A', html: '&#xE88A;' }, // Home page { content: 'shopping_cart' , fallback: '\uE8CC', html: '&#xE8CC;' }, // Registration page { content: 'event' , fallback: '\uE878', html: '&#xE878;' }, // Program page { content: 'flight' , fallback: '\uE539', html: '&#xE539;' }, // Location page { content: 'account_box' , fallback: '\uE851', html: '&#xE851;' }, // Speakers page { content: 'people' , fallback: '\uE7FB', html: '&#xE7FB;' }, // Sponsor page { content: 'work' , fallback: '\uE8F9', html: '&#xE8F9;' }, // Exhibit page { content: 'info_outline' , fallback: '\uE88F', html: '&#xE88F;' }, // About page { content: 'email' , fallback: '\uE0BE', html: '&#xE0BE;' }, // Contact page / social list icon email { content: 'stars' , fallback: '\uE8D0', html: '&#xE8D0;' }, // Early Bird registration period icon { content: 'date_range' , fallback: '\uE916', html: '&#xE916;' }, // Advance registration period icon { content: 'account_balance' , fallback: '\uE84F', html: '&#xE84F;' }, // Onsite registration period icon { content: 'insert_drive_file' , fallback: '\uE24D', html: '&#xE24D;' }, // generic page file (only used in Docs) { content: 'arrow_upward' , fallback: '\uE5D8', html: '&#xE5D8;' }, // "return to top" button { content: 'phone' , fallback: '\uE0CD', html: '&#xE0CD;' }, // social list icon phone { content: 'phone_iphone' , fallback: '\uE325', html: '&#xE325;' }, // social list icon phone / mobile app callout { content: 'explore' , fallback: '\uE87A', html: '&#xE87A;' }, // social list icon homepage { content: 'expand_more' , fallback: '\uE5CF', html: '&#xE5CF;' }, // main menu drop-down ] } /** * Data for social media networks. * @type {Object<{name:string, icon}>} */ static get SOCIAL_DATA() { return { twitter: { name: 'Twitter', icon: Util.ICON_DATA[-1], // toURL: (handle = '') => `https://twitter.com/${(handle)}`, }, facebook: { name: 'Faceboook', icon: Util.ICON_DATA[-1], }, google: { name: 'Google+', icon: Util.ICON_DATA[-1], }, linkedin: { name: 'LinkedIn', icon: Util.ICON_DATA[-1], }, youtube: { name: 'YouTube', icon: Util.ICON_DATA[-1], }, } } /** * Display a Date object as a string of the format 'HH:MMrr', where * - 'HH' is the 12-hour format hour of day ('1'–'12') * - 'MM' is the minutes of the hour * - 'rr' is 'am' or 'pm' (“Ante Meridiem” or “Post Meridiem”) * @param {Date} date the datetime to display * @return {string} a string of the format HH:MM[am|pm] */ static hourTime12(date) { var hour = '' + ((date.getHours() - 1)%12 + 1) var minute = ((date.getMinutes() < 10) ? '0' : '') + date.getMinutes() var meridiem = (date.getHours() < 12) ? 'am' : 'pm' return hour + ((minute !== '00') ? `:${minute}` : '') + meridiem } /** * Display a Date object as a string of the format 'HHHH:MM', where * - 'HHHH' is the 24-hour format hour of day ('00'–'23') * - 'MM' is the minutes of the hour * @param {Date} date the datetime to display * @return {string} a string of the format HHHH:MM */ static hourTime24(date) { var hour = ((date.getHours() < 10) ? '0' : '') + date.getHours() var minute = ((date.getMinutes() < 10) ? '0' : '') + date.getMinutes() return hour + ':' + minute } /** * Return an abbreviated form of a date. * The format is 'MMM DD', where * - 'MMM' is the first 3 letters of the month in English * - 'DD' is the date (one or two digits) * @param {Date} date the datetime to display * @return {string} a string of the format 'MMM DD' */ static monthDay(date) { return Util.MONTH_NAMES[date.getUTCMonth()].slice(0,3) + ' ' + date.getUTCDate() } /** * Return a URL-friendly string. * @param {string} str a string to convert * @return {string} a URL-safe variant of the string given */ static toURL(str) { return encodeURIComponent(str.toLowerCase().replace(/[\W]+/g, '-')) } /** * Return a new Date object from a given datetime string. * @param {string} str a string in any acceptable datetime format * @return {Date} a new Date object representation of the argument */ static toDate(str) { return (str) ? new Date(str) : new Date() } /** * Remove an item from an array. * This method is destructive: it modifies the given argument. * @param {Array} arr the array to modify * @param {unknown} item the item to remove from the array */ static spliceFromArray(arr, item) { var index = arr.indexOf(item) if (index >= 0) arr.splice(index, 1) } /** * Return a string part of an icon. * @param {Object} icon the icon object to parse * @param {string} icon.content the keyword of the icon * @param {string} icon.fallback the unicode codepoint of the icon * @param {boolean=} fb true if the fallback is preferred over the content * @return {string} `icon.fallback` if fallback==true, else `icon.content` */ static iconToString(icon, fb) { return (fb) ? icon.fallback : icon.content } /** * Enum for state regions * @enum {string} */ static get Region() { return { SOUTH : 's', WEST : 'w', SOUTHWEST: 'sw', NORTHEAST: 'ne', MIDWEST : 'mw', } } } },{}],18:[function(require,module,exports){ module.exports = { Util : require('./_models/Util.class.js'), ConfSite : require('./_models/ConfSite.class.js'), ConfPage : require('./_models/ConfPage.class.js'), Conference : require('./_models/Conference.class.js'), RegistrationPeriod: require('./_models/RegistrationPeriod.class.js'), Pass : require('./_models/Pass.class.js'), Session : require('./_models/Session.class.js'), Place : require('./_models/Place.class.js'), Person : require('./_models/Person.class.js'), SupporterLevel : require('./_models/SupporterLevel.class.js'), Supporter : require('./_models/Supporter.class.js'), Exhibitor : require('./_models/Exhibitor.class.js'), ImportantDate : require('./_models/ImportantDate.class.js'), } },{"./_models/ConfPage.class.js":5,"./_models/ConfSite.class.js":6,"./_models/Conference.class.js":7,"./_models/Exhibitor.class.js":8,"./_models/ImportantDate.class.js":9,"./_models/Pass.class.js":10,"./_models/Person.class.js":11,"./_models/Place.class.js":12,"./_models/RegistrationPeriod.class.js":13,"./_models/Session.class.js":14,"./_models/Supporter.class.js":15,"./_models/SupporterLevel.class.js":16,"./_models/Util.class.js":17}],19:[function(require,module,exports){ /** * A Page is an object with a name and url. * Both the name and url are immutable (cannot be changed). * The url is used as the page identifier; that is, no two pages within * the same structure may have the same url. * @type {Page} */ module.exports = (function () { // CONSTRUCTOR /** * Construct a Page object, given a name and url. * @constructor * @param {Object} $pageinfo an object with `name` and `url` properties * @param {string} $pageinfo.name the name of this page * @param {string} $pageinfo.url the url (and ID) of this page */ function Page($pageinfo) { var self = this $pageinfo = $pageinfo || {} // NOTE constructor overloading self._NAME = $pageinfo.name self._URL = $pageinfo.url self._title = '' self._description = '' self._keywords = [] self._is_hidden = false self._pages = [] } // ACCESSOR FUNCTIONS /** * Get the name of this page. * @return {string} the name of this page */ Page.prototype.name = function name() { return this._NAME } /** * Get the url of this page. * @return {string} the url of this page */ Page.prototype.url = function url() { return this._URL } /** * Set or get the title of this page. * Set the argument, if given, as the title, and return this page. * Otherwise, return the title of this page. * The `title` should be a more official and formal version of the `name`. * @param {(function():string|string=)} arg the title to set, or function to call * @return {(Page|string)} this page || the title of this page */ Page.prototype.title = function title(arg) { if (arguments.length) { this._title = (typeof arg === 'function') ? arg.call(this) : arg return this } else return this._title } /** * Set or get the description of this page. * Set the argument, if given, as the description, and return this page. * Otherwise, return the description of this page. * @param {(function():string|string=)} arg the description to set, or function to call * @return {(Page|string)} this page || the description of this page */ Page.prototype.description = function description(arg) { if (arguments.length) { this._description = (typeof arg === 'function') ? arg.call(this) : arg return this } else return this._description } /** * Set or get the keywords of this page. * Set the argument, if given, as the keywords, and return this page. * Otherwise, return the keywords of this page. * @param {(function():string|Array=)} arg the keywords to set, or function to call * @return {(Page|string)} this page || the keywords of this page */ Page.prototype.keywords = function keywords(arg) { if (arguments.length) { this._keywords = (typeof arg === 'function') ? arg.call(this) : arg return this } else return this._keywords.slice() } /** * Hide or show this page. * @param {boolean=true} bool hides or shows this page * @return {Page} this page */ Page.prototype.hide = function hide(bool) { this._is_hidden = (arguments.length) ? bool : true return this } /** * Get the hidden status of this page. * @return {boolean} true if this page is hidden; false otherwise */ Page.prototype.isHidden = function isHidden() { return this._is_hidden } // METHODS /** * Add a sub-page to this page. * A sub-page is another page acting a child of this page in a tree/hierarchy. * @param {Page} $page an instance of the Page class */ Page.prototype.add = function add($page) { this._pages.push($page) return this } /** * Remove a sub-page from this page. * @param {(function():string|string)} arg the url of the page to remove, or function to call * @return {Page} this page */ Page.prototype.remove = function remove(arg) { var index = this._pages.indexOf((function (self) { var page if (typeof arg === 'function') { page = arg.call(self) } else if (typeof arg === 'string') { page = self.find(arg) } else { page = arg } return page })(this)) if (index >= 0) this._pages.splice(index, 1) return this } /** * Remove all sub-pages from this page. * @return {Page} this page */ Page.prototype.removeAll = function removeAll() { this._pages = [] return this } /** * Find and return a descendant of this page. * @param {string} url the url of the page to find * @return {?Page} the page found, else `null` */ Page.prototype.find = function find(url) { return this._pages.find(function (item) { return item._URL === url }) || (function (self) { var ancestor = self._pages.find(function (item) { return item.find(url) }) return (ancestor) ? ancestor.find(url) : null })(this) } /** * Return a shallow copy of all sub-pages of this page. * * This function is non-destructive. For example, assigning * `$page.findAll()[0] = null` will set the first element of * a shallow array to `null`, but will not affect the original children of `$page`. * @return {Array<Page>} a shallow array containing all sub-pages of this page */ Page.prototype.findAll = function findAll() { return this._pages.slice() } // STATIC MEMBERS return Page })() },{}],20:[function(require,module,exports){ var Page = require('./Page.class.js') /** * A StyleGuide object has a name and url, and a set of preset pages. * @type {StyleGuide} * @extends Page */ module.exports = (function () { // CONSTRUCTOR /** * Construct a StyleGuide object, given a name and url. * @constructor * @param {string} name the name of this styleguide * @param {string} url the url of the landing page of this styleguide */ function StyleGuide(name, url) { var self = this Page.call(self, { name: name, url: url }) self._was_initialized = false } StyleGuide.prototype = Object.create(Page.prototype) StyleGuide.prototype.constructor = StyleGuide // ACCESSOR FUNCTIONS // METHODS /** * Initialize and add starting pages to this styleguide, then return it. * * Should be called every time `new StyleGuide()` is called, * but AFTER `.title()` and `.description()` are called on it. * This is because the pages initialized require the title * and description of this style guide. E.g. this is the proper order: * ``` * var sg = new StyleGuide('Example Style Guide', '//example.com/style-guide/') * .title('Style Guide of Example Dot Com') * .description('A reference for standard styles at Example Dot Com.') * .init() * ``` * @return {StyleGuide} this styleguide */ StyleGuide.prototype.init = function init() { var self = this if (!self._was_initialized) { self._was_initialized = true return self .add(new Page({ name: self.name(), url: 'index.html' }) .description(self.description()) ) .add(new Page({ name: 'Visual Design', url: 'visual.html' }) .description('Color and font schemes, look-and-feel, overall voice and tone.') ) .add(new Page({ name: 'Base Typography', url: 'base.html' }) .description('Bare, unstyled HTML elements. No classes.') .add(new Page({ name: 'Table of Contents' , url: 'base.html#table-contents' })) .add(new Page({ name: 'Headings & Paragraphs', url: 'base.html#headings-paragraphs' })) .add(new Page({ name: 'Lists' , url: 'base.html#lists' })) .add(new Page({ name: 'Tables' , url: 'base.html#tables' })) .add(new Page({ name: 'Text-Level Elements' , url: 'base.html#text-level-elements' }) .add(new Page({ name: 'Links' , url: 'base.html#links' })) .add(new Page({ name: 'Stress' , url: 'base.html#stress' })) .add(new Page({ name: 'Documentation', url: 'base.html#documentation' })) .add(new Page({ name: 'Data' , url: 'base.html#data' })) ) .add(new Page({ name: 'Embedded Elements' , url: 'base.html#embedded-elements' })) .add(new Page({ name: 'Forms' , url: 'base.html#forms' })) .add(new Page({ name: 'Interactive Elements', url: 'base.html#interactive-elements' })) ) .add(new Page({ name: 'Objects', url: 'obj.html' }) .description('Patterns of structure that can be reused many times for many different purposes.') ) .add(new Page({ name: 'Components', url: 'comp.html' }) .description('Patterns of look-and-feel that are each only used for one purpose.') ) .add(new Page({ name: 'Helpers', url: 'help.html' }) .description('Somewhat explicit classes used for enhancing default styles.') ) .add(new Page({ name: 'Atoms', url: 'atom.html' }) .description('Very specific classes used for creating anomalies or fixing broken styles.') ) } else return } // STATIC MEMBERS return StyleGuide })() },{"./Page.class.js":19}],21:[function(require,module,exports){ module.exports = { Page: require('./Page.class.js') , StyleGuide: require('./StyleGuide.class.js') } },{"./Page.class.js":19,"./StyleGuide.class.js":20}],22:[function(require,module,exports){ var Color = require('csscolor').Color var ConfSite = require('neo').ConfSite $('input.js-picker').change(function () { var primary = Color.fromString($('input.js-picker-primary').val()) var secondary = Color.fromString($('input.js-picker-secondary').val()) var styleobj = ConfSite.colorStyles(primary, secondary) for (var prop in styleobj) { document.querySelector('body').style.setProperty(prop, styleobj[prop]) } }) },{"csscolor":4,"neo":18}]},{},[22]);
import React from 'react'; import { MemoryRouter } from 'react-router-dom'; import { mount } from 'enzyme'; import chai, { expect } from 'chai'; import sinon from 'sinon'; import sinonChai from 'sinon-chai'; import { ProcessMapsPage } from './processMapsPage'; import * as statusTypes from '../constants/status'; chai.use(sinonChai); describe('<ProcessMapsPage />', () => { const requiredProps = { fetchMapIds: () => {}, agent: 'foo', process: 'bar', maps: {}, classes: { circular: '' } }; it('calls fetch on mount', () => { const props = { ...requiredProps, fetchMapIds: sinon.spy() }; const processMapsPage = mount(<ProcessMapsPage {...props} />); expect(props.fetchMapIds.callCount).to.equal(1); expect(props.fetchMapIds.getCall(0).args[0]).to.equal('foo'); expect(props.fetchMapIds.getCall(0).args[1]).to.equal('bar'); const progress = processMapsPage.find('CircularProgress'); expect(progress).to.have.lengthOf(1); }); it('renders on loading', () => { const props = { ...requiredProps, fetchMapIds: sinon.spy(), maps: { status: statusTypes.LOADING } }; const processMapsPage = mount(<ProcessMapsPage {...props} />); expect(props.fetchMapIds.callCount).to.equal(1); expect(props.fetchMapIds.getCall(0).args[0]).to.equal('foo'); expect(props.fetchMapIds.getCall(0).args[1]).to.equal('bar'); const progress = processMapsPage.find('CircularProgress'); expect(progress).to.have.lengthOf(1); }); it('renders on failed', () => { const props = { ...requiredProps, fetchMapIds: sinon.spy(), maps: { status: statusTypes.FAILED, error: 'unreachable' } }; const processMapsPage = mount(<ProcessMapsPage {...props} />); expect(props.fetchMapIds.callCount).to.equal(1); expect(props.fetchMapIds.getCall(0).args[0]).to.equal('foo'); expect(props.fetchMapIds.getCall(0).args[1]).to.equal('bar'); const error = processMapsPage.find('Typography'); expect(error).to.have.lengthOf(1); expect(error.contains('failed to load: unreachable')).to.be.true; }); it('renders on success', () => { const props = { ...requiredProps, fetchMapIds: sinon.spy(), maps: { status: statusTypes.LOADED, mapIds: ['foo', 'bar'] } }; const processMapsPage = mount( <MemoryRouter> <ProcessMapsPage {...props} /> </MemoryRouter> ); expect(props.fetchMapIds.callCount).to.equal(1); expect(props.fetchMapIds.getCall(0).args[0]).to.equal('foo'); expect(props.fetchMapIds.getCall(0).args[1]).to.equal('bar'); const links = processMapsPage.find('NavLink'); expect(links).to.have.lengthOf(4); expect(links.contains('foo')).to.be.true; expect(links.contains('bar')).to.be.true; }); it('re renders when agent or process props changes', () => { const props = { ...requiredProps, fetchMapIds: sinon.spy(), maps: { status: statusTypes.LOADED, mapIds: [] } }; const processMapsPage = mount(<ProcessMapsPage {...props} />); processMapsPage.setProps({ ...props, agent: 'crazy' }); expect(props.fetchMapIds.callCount).to.equal(2); expect(props.fetchMapIds.getCall(1).args[0]).to.equal('crazy'); expect(props.fetchMapIds.getCall(1).args[1]).to.equal('bar'); processMapsPage.setProps({ ...props, process: 'crazy' }); expect(props.fetchMapIds.callCount).to.equal(3); expect(props.fetchMapIds.getCall(2).args[0]).to.equal('foo'); expect(props.fetchMapIds.getCall(2).args[1]).to.equal('crazy'); }); it('does not re renders when other props changes', () => { const props = { fetchMapIds: sinon.spy(), maps: { status: statusTypes.LOADED, mapIds: [] } }; const processMapsPage = mount( <ProcessMapsPage {...requiredProps} {...props} /> ); processMapsPage.setProps({ ...props, something: 'else' }); expect(props.fetchMapIds.callCount).to.equal(1); }); });
import React from 'react' import Alert from '@material-ui/lab/Alert'; const styles = { alert: { left: '0', pointerEvents: 'none', position: 'fixed', top: 0, width: '100%', zIndex: '1500', } } const AlertMessage = (props) => { return ( <Alert style={styles.alert} severity={props.severity}>{props.message}</Alert> ) } export default AlertMessage
function Menu() { var props = { time: {value: 1, writable: false, enumerable: false}, sound: {value: true, writable: true, enumerable: false}, music: {value: true, writable: true, enumerable: false} }; if (this instanceof Menu) { // called with new as constructor Object.defineProperties(this, props); } else { // called as fabric function return Object.create(Menu.prototype, props); } } Object.defineProperties(Menu.prototype, { toggleSound: { value: function() { this.sound = !this.sound; return this.sound; }, writable: false, configurable: true } }) var k = 1/1000; var loopTime = 0.01*1000;// = 10 ms var $water = $('#water'); var $tamaPic = $('#tamapic'); var $screen = $('#screen'); var happydream = null; var tamaVars = { hunger: 50, happyness: 50, diabetes: 0, illness: 0, insalubrity: 0, utp: 0, //What? training: 0, age: 1, weight: 100, name: 'bouh', gender: 'Boy', generation: 1, state: -1, animation: 'main', busy: false, doingbullshit: 0, tidy: true, water:-50, dung:0, sick: false, theme: 'default' }; var tamaRules = { // TODO: Clean this part up to make it more verbose. E.g. k is defined // in line 1! loop: { hunger: -1*k, happyness: -0.25*k-tamaVars.doingbullshit*4*k, illness: +0.5*k + tamaVars.diabetes/2*k, utp: +2*k, insalubrity: (tamaVars.utp) / 25*k, training: 0-tamaVars.doingbullshit*4*k, age: 1/8640000 // 1 year = 1 earth day }, actualizing:function() { this.loop.hunger = -1*k; this.loop.happyness = -0.05*k-tamaVars.doingbullshit*4*k; this.loop.illness = +0.5*k + tamaVars.diabetes/2*k; this.loop.utp = 0; this.loop.insalubrity = (tamaVars.utp / 25)*k; this.loop.training = -tamaVars.doingbullshit*4*k; this.loop.age = 1/8640000; } }; var tamaControls = { currentTabId: '', lights: true, HungerMeter: function(actualizing) { $('#hungerbar').progressbar( { value: tamaVars.hunger }); $('#happybar').progressbar( { value: tamaVars.happyness }); $('#trainingbar').progressbar( { value: tamaVars.training }); $('#trainingbar div, #happybar div, #hungerbar div').css({background: '#01c5ed'}); $('#age').html(Math.floor(tamaVars.age) + ' years'); $('#weight').html(Math.round(tamaVars.weight) / 100 + ' g'); $('#name').html(tamaVars.name); $('#gender').html(tamaVars.gender); //$('#generation').html(tamaVars.generation); if(!actualizing) { this.toggle('#li0-content'); } }, FeedingTime: function(type) { if(type && tamaVars.state >= 1 && !tamaVars.busy) { if(type == 'food' && tamaVars.hunger <=97) { tama.add('hunger', 10); tama.add('utp', 10); tama.add('weight', 5, true); // According to conventions, it should be addSprites … tamaControls.addsprites('food', 1000); tamaControls.evolve('eat', true, 2000); } else if(type == 'snack' && tamaVars.hunger <=97) { tama.add('hunger', 5); tama.add('utp', 5); tama.add('weight', 2.5, true); tama.add('happyness', 5); tama.add('diabetes', 2.5); tamaControls.addsprites('snack', 1000); tamaControls.evolve('eat', true, 2000); } else if(type == 'food' || type == 'snack' && tamaVars.hunger >=98) { tamaControls.evolve('no', true, 4000); } } this.toggle('#li1-content'); }, Toilet: function() { if(!tamaVars.busy) { tamaVars.insalubrity = 0; tama.cleaning(true); } }, GamingTime: function() { if(tamaVars.state >= 1 && !tamaVars.busy) { if(tamaVars.hunger >= 30){ tamaControls.evolve('play', true, 6000); tamaControls.addsprites('play', 6000); tama.add('hunger', -10); tama.add('weight', -5, true); tama.add('happyness', 5); tama.add('training', 0.5); } else{ tamaControls.evolve('no', true, 4000); } } }, Discipline: function(type) { if(tamaVars.state >= 1) { tamaVars.doingbullshit = 0; tama.add('training', 1); } }, Health: function() { if(tamaVars.state >= 1) { tamaVars.illness = 0; tama.add('diabetes', -25); } }, Lights: function() { if(tamaControls.lights) { if(tamaVars.happyness <= 50){ $screen.css('background-color', '#777777'); $tamaPic.attr('src', 'img/chars/0'+state+'/sleep.gif'); $("#li1").toggle(); $("#li2").toggle(); $("#li3").toggle(); $("#li4").toggle(); $("#li5").toggle(); tamaControls.lights = false; happydream = setInterval(function(){tama.add('happyness', 0.5);}, 15000); } else{ tamaControls.evolve('no', true, 4000); } } else { $screen.css('background-color', '#fff'); $tamaPic.attr('src', 'img/chars/0'+state+'/main.gif'); $("#li1").toggle(); $("#li2").toggle(); $("#li3").toggle(); $("#li4").toggle(); $("#li5").toggle(); tamaControls.lights = true; clearInterval(happydream); } }, toggle: function(id) { if(this.currentTabId !== '') { $(this.currentTabId).toggle(false); } if(this.currentTabId == id) { $(id).toggle(false); this.currentTabId = ''; } else { $(id).toggle(true); this.currentTabId = id; } }, evolve: function(state, animation, time) { if(tamaVars.state != state && !tamaVars.busy) { if(animation) { $tamaPic.attr('src', 'img/chars/0'+tamaVars.state+'/'+state+'.gif'); tamaVars.busy = true; setTimeout(function() { $tamaPic.attr('src', 'img/chars/0'+tamaVars.state+'/main.gif'); tamaVars.busy = false; }, time); } else { switch(state) { case -2: $tamaPic.attr('src', 'img/chars/death/main.gif'); break; case -1: $tamaPic.attr('src', 'img/chars/00/main.gif'); break; case 0: $tamaPic.attr('src', 'img/chars/00/hach.gif'); break; default: if(tamaVars.sick) { if(state == 'sick') { state = tamaVars.state; $tamaPic.attr('src', './img/chars/0'+state+'/sick.gif'); } else { state = tamaVars.state; $tamaPic.attr('src', './img/chars/0'+state+'/main.gif'); } } else if(!tamaVars.tidy) { if(state == 'unhp') { state = tamaVars.state; $tamaPic.attr('src', './img/chars/0'+state+'/unhp.gif'); } else { state = tamaVars.state; $tamaPic.attr('src', './img/chars/0'+state+'/main.gif'); } } else { $tamaPic.attr('src', './img/chars/0'+state+'/main.gif'); } break; } tamaVars.state = state; } } }, addsprites: function(type, time) { switch(type) { // FIXME: Get rid of setTimeout! Use requestAnimationFrame instead! case 'food': buffer = "<img class=\"food\" src=\"./img/other/food.gif\" />"; $screen.append(buffer); if(time) { setTimeout(function(){$('.food').remove();}, time); } break; case 'snack': buffer = "<img class=\"food\" src=\"./img/other/snack.gif\" />"; $screen.append(buffer); setTimeout(function(){$('.food').remove();}, time); break; case 'play': buffer = "<img id=\"stars1\" class=\"play\" src=\"./img/other/stars.gif\" />"; buffer += "<img id=\"stars2\" class=\"play\" src=\"./img/other/stars.gif\" />"; $screen.append(buffer); setTimeout(function(){$('.play').remove();}, time); break; case 'sick': if(time >= 0) { buffer = "<img class=\"skull\" src=\"./img/other/skull.gif\" />"; $screen.append(buffer); } else { $('.skull').remove(); } break; default: break; } } }; var tama = { counter: 0, moving: false, clock: { si: null, start: function() { tama.clock.si = setInterval(function() { tama.main(); }, loopTime); }, stop: function() { tama.clock.si = clearInterval(tama.clock.si); }, reset: function() { tama.counter = 0; } }, init: function() { tama.clock.start(); }, main: function() { tamaRules.actualizing(); tamaControls.HungerMeter(true); tama.counter++; tama.add('hunger', tamaRules.loop.hunger); tama.add('happyness', tamaRules.loop.happyness); tama.add('illness', tamaRules.loop.illness); tama.add('insalubrity', tamaRules.loop.insalubrity); tama.add('utp', tamaRules.loop.utp); tama.add('training', tamaRules.loop.training); tama.add('age', tamaRules.loop.age); if(Math.random()*(1*100)+1 == 1) tamaVars.doingbullshit = 1; this.growing(); this.pooping(); this.cleaning(); this.beingsick(); this.doingbullshit(); this.dead(); }, add: function(prop, value, nolimit) { var tmp = tamaVars[prop] += value; if((tamaVars[prop] > 100 || tamaVars[prop] < 0) && !nolimit) { tamaVars[prop] -= tamaVars[prop] % 100; } }, growing:function() { switch(this.counter) { case 300: state = 0; break; case 500: state = 1; break; case 51840000: state = 2; break; case 95040000: state = 3; break; case 146880000: state = 4; break; default: state = tamaVars.state; break; } tamaControls.evolve(state); }, cleaning:function(init) { if(init) { tamaVars.busy = true; tamaVars.water = 210; $water.css('left', tamaVars.water+'px'); } { if(tamaVars.water >= -50) { tamaVars.water -= 5; $water.css('left', tamaVars.water+'px'); if(tamaVars.water === -50) { tamaVars.busy = false; $('.dung').remove(); tamaVars.dung = 0; } } } }, pooping:function() { var d = tamaVars.insalubrity; if(d > 12 && tamaVars.dung < 1) { this.dung(); } else if(d > 25 && tamaVars.dung < 2) { this.dung(); } else if(d > 37 && tamaVars.dung < 3) { this.dung(); } else if(d > 50 && tamaVars.dung < 4) { this.dung(); } else if(d > 62 && tamaVars.dung < 5) { this.dung(); } else if(d > 75 && tamaVars.dung < 6) { this.dung(); } else if(d > 87 && tamaVars.dung < 7) { this.dung(); } else if(d > 100 && tamaVars.dung < 8) { this.dung(); } }, dung:function() { buffer = "<img class=\"dung\" style=\"top: "+Math.floor((Math.random()*(200-13))+1)+"px; left: "+Math.floor((Math.random()*(200-13))+1)+"px;\" src=\"./img/other/dung.gif\" />"; $screen.append(buffer); tamaVars.dung++; tamaVars.utp = 0; }, beingsick:function() { if(tamaVars.illness >= 50 && !tamaVars.sick) { tamaVars.sick = true; tamaControls.evolve('sick'); tamaControls.addsprites('sick', 1); } if(tamaVars.illness < 50 && tamaVars.sick) { tamaControls.evolve('unsick'); tamaControls.addsprites('sick', -1); tamaVars.sick = false; } }, doingbullshit:function() { if(tamaVars.doingbullshit == 1 && tamaVars.tidy) { tamaVars.tidy = false; tamaControls.evolve('unhp'); } if(tamaVars.doingbullshit === 0 && !tamaVars.tidy) { tamaControls.evolve('hp'); tamaVars.tidy = true; } }, dead:function() { score = 2; if(tamaVars.hunger <= 10) score--; if(tamaVars.happyness <= 10) score--; if(tamaVars.illness >= 90) score--; if(tamaVars.insalubrity >= 90) score--; if(tamaVars.training <= 10) score--; if(score <= 0) { tamaControls.evolve(-2); tama.clock.stop(); //$('#defeat').css('display', 'block'); $('#time').html(Math.round(tama.counter/(1000/loopTime))); var defeat = document.getElementById("defeat"); var timedefeat = document.getElementById("time"); var seconds = document.getElementById("seconds"); alert(defeat.textContent + ' ' + timedefeat.textContent + ' ' + seconds.textContent + '.'); } }, help:function() { $('#li7-content').toggle(); } };
import React from 'react' import {Table, Button} from 'antd' import {highLight} from '../config' function SearchTable (props) { const { className, data, total, currentPage, pageSize, onChangePage, onChangePageSize, onShowContext, onShowAllText, highLightWords } = props; const columns = [ { title: 'left', dataIndex: 'left', key: 'id', align: 'right', render: (text, record) => ( <div> {highLight(text, highLightWords)} <div className="textId"> <strong>{record.displayId}</strong> </div> </div> ) }, { title: 'mid', dataIndex: 'mid', align: 'center', render: text => <span style={{color: "red"}}>{text}</span> }, { title: 'right', dataIndex: 'right', key: 'id', align: 'left', render: (text, record) => ( <div> {highLight(text, highLightWords)} <div className="tableButton"> <Button className="context" size="small" onClick={() => onShowContext(record.id)}>上下文</Button> <Button className="context" size="small" onClick={() => onShowAllText(record.id.split(".")[0], record.section)}>原文</Button> </div> </div> ) }, ]; const pagination = { pageSize: pageSize, total: total, onChange: onChangePage, current: currentPage, size: 'normal', showSizeChanger: true, showQuickJumper: true, onShowSizeChange: onChangePageSize } return ( <div className={className}> <Table columns={columns} dataSource={data} size="small" pagination={pagination} rowKey="id" /> </div> ) } export default SearchTable;
$(document).ready(function(){ console.log("jQuery has loaded"); var pacman = {}; pacman.x=$(document).width()*0.026; pacman.y=$(document).height()*0.01; $(document).on('keydown', controls); function controls(event){ console.log(event.which); lastKey=event.which; switch(lastKey){ case 65: $('#pacman').css({ 'left': (pacman.x -= 1) + '%' }); break; case 87: $('#pacman').css({ 'top': (pacman.y -= 1) + '%' }); break; case 68: $('#pacman').css({ 'left': (pacman.x += 1) + '%' }); break; case 83: $('#pacman').css({ 'top': (pacman.y += 1) + '%' }); break; case false: $('#pacman').css({ 'left':((pacman.x) += 1) + '%' }) break; } } })
/** * Koin Websocket Server * * @author Ashraful Sharif<sharif.ashraful@gmail.com> */ var Promise = require( "bluebird" ); var ws = require( "ws" ); var uuidv1 = require( "uuid/v1" ); var url = require( "url" ); var fs = require( "fs" ); var path = require( "path" ); var _ = require( "underscore" ); var Utils = require( "./lib/utils" ); var Rpc = require( "./lib/rpc-client" ); function WebsocketServer( ) { var me = this; me.config = require( "./config/app.json" ); me.webSocketMap = { }; me.endpoints = { }; me.rpc = new Rpc( ); // Token will be checked from koin-site through rpc module function verifyToken( ) { } // Verify websocket client before connect function verifyClient( info, next ) { var query = url.parse( info.req.url, true ).query; // Verify tocken // if( !query.token ) { // return next( false, 403, "Not valid token" ); //} next( true ); } me.run = function run( ) { Promise.resolve( ).then( function loadEndpoints( ) { return new Promise( function( resolve, reject ) { fs.readdir( "endpoints", function( err, endpointNames ) { if( err ) { reject( err ); } else { _.each( endpointNames, function endpointName( name ) { console.log( "Loading Endpoint: ", name ); var handler = require( "./endpoints/" + name + "/index.js" ); me.endpoints[ name ] = handler; }); resolve( ); } // me.endpoints[ "getExchanges" ].execute( ) }); }); }).then( function initWebsocket( ) { const wss = new ws.Server({ host: me.config.host, port: me.config.port, verifyClient: verifyClient }); wss.on( "connection", function( socket ) { var id = uuidv1( ); console.log( "websocket " + id + " connected" ); me.webSocketMap[ id ] = socket; socket.on( "close", function( ) { delete me.webSocketMap[ id ]; console.log( "websocket " + id + " disconnected" ); }); socket.on( "message", function( data ) { try { data = JSON.parse( data ); // console.log( data ); if( me.endpoints[ data.id ] ) { var requestSchema = require( "./endpoints/" + data.id + "/schemas/request.json" ); // Validate Request Schema var validation = Utils.validateReqSchema( data, requestSchema ); if( validation !== true ) { socket.send( JSON.stringify({ errors: [{ "title": "BAD REQUEST", "message": validation.message, "code": validation.code, "status": validation.code }] })); } else { me.endpoints[ data.id ].execute( data, function ( err, response ) { if( err ) { socket.send( JSON.stringify({ errors: [{ "title": "Internal Error", "message": err.message, "code": 500, "status": 500 }]})); } else { var responseSchema = require( "./endpoints/" + data.id + "/schemas/response.json" ); // Validate Response Schema validation = Utils.validateResSchema( response, responseSchema ); if( validation !== true ) { socket.send( JSON.stringify({ errors: [{ "title": "BAD RESPONSE", "message": validation.message, "code": validation.code, "status": validation.code }] })); } else { socket.send( JSON.stringify( response ) ); } } }); } } else { socket.send( JSON.stringify({ errors: [{ "title": "NOT FOUND", "message": "The server could not find what was requested", "code": "404", "status": "404" }] })); } } catch( ex ) { console.log( ex.stack ); } }); }); }); }; me.run( ); } /** * Global variable */ global.app = new WebsocketServer( ); module.exports = app;
var socket = new WebSocket( "ws://localhost:1234" ); var form = document.getElementById("form"), input = document.getElementById("input"), output = document.getElementById("output"); function newElement(tag, content) { var elem = document.createElement(tag), text = document.createTextNode(content); elem.appendChild(text); return elem; } socket.onmessage = function(event) { console.log('Message received: ' + event.data); var msg = newElement('p', event.data); output.appendChild(msg); }; form.onsubmit = function(event) { event.preventDefault(); socket.send( input.value ); };
import React, { Component } from 'react' import Container from 'react-bootstrap/Container' import Row from 'react-bootstrap/Row' import Col from 'react-bootstrap/Col' import Carousel from 'react-bootstrap/Carousel' import Image from 'react-bootstrap/Image' import styled from 'styled-components' import Media from 'react-bootstrap/Media' const StyledTitle = styled.div` text-align: center; margin-bottom: 6rem; & .intro-title { font-size: 14px; font-weight: bold; letter-spacing: 1.4px; color: #008ed6; text-transform: uppercase; } & .title { font-size: 2.5rem; font-weight: 600; line-height: 1.33; color: #fff; } & .split-line { position: relative; width: 40px; padding: 10px 0; display: block; margin: auto; &:before { content: '';position: absolute;width: 45%;height: 2px;background-color: #008ed6;bottom: -2px;left: 0; } &:after { content: '';position: absolute;width: 45%;height: 2px;background-color: #008ed6;bottom: -2px;right: 0; } } ` const StyledCaption = styled.div` width: 100%; & .carousel-caption {padding: 5rem 0;text-align: left;left: 2%;right: 2%;bottom: initial;top: 0;} & .comment { &-content { font-size: 1.3rem; margin-bottom: 2rem; } &-user { h5 { font-size: .8rem; opacity: .8; } p { font-size: 1rem; margin: 0; } } } & .carousel-indicators li{ border-radius: 50%; background-color: transparent; height: 7px; width: 7px; border: 1px solid rgba(255, 255, 255, .8); &.active { background-color: #fff; height: 14px; width: 14px; margin-top: -3px; } } ` export default class carouselStory extends Component { render () { return ( <div> <Row> <StyledCaption> <Carousel className='w-100' controls={false}> <Carousel.Item interval={500}> <Image src={ require( '../assets/warstwa-8.png' ) } alt="lucid" className='w-100'/> <Carousel.Caption> <Container> <Row> <Col> <StyledTitle> <h2 className='intro-title'>dip into the details</h2> <h3 className='title'>Beautiful on every device</h3> <span className='split-line'></span> </StyledTitle> </Col> </Row> <Row> <Col className="comment"> <p className="comment-content">Once upon a time all the Rivers combined to protest against the action of the Sea in making their waters salt. “When we come to you,” said they to the Sea.</p> <Media> <Image width={ 64 } height={ 64 } src={ require( '../assets/warstwa-7.png' ) } className="mr-3" alt="Generic placeholder" roundedCircle /> <Media.Body className="comment-user"> <h5>John Doe</h5> <p>CEO, THE RIVERS COMPANY</p> </Media.Body> </Media> </Col> <Col className="comment"> <p className="comment-content">A shoe is not only a design, but it's a part of your body language, the way you walk. The way you're going to move is quite dictated by your shoes.</p> <Media> <Image width={ 64 } height={ 64 } src={ require( '../assets/warstwa-16.png' ) } className="mr-3" alt="Generic placeholder" roundedCircle /> <Media.Body className="comment-user"> <h5>Dean Winchester</h5> <p>UX DESIGNER, GOOGLE INC.</p> </Media.Body> </Media> </Col> </Row> </Container> </Carousel.Caption> </Carousel.Item> <Carousel.Item interval={ 500 }> <Image src={ require( '../assets/warstwa-8.png' ) } alt="lucid" className='w-100' /> <Carousel.Caption> <Container> <Row> <Col> <StyledTitle> <h2 className='intro-title'>dip into the details</h2> <h3 className='title'>Beautiful on every device</h3> <span className='split-line'></span> </StyledTitle> </Col> </Row> <Row> <Col className="comment"> <p className="comment-content">Once upon a time all the Rivers combined to protest against the action of the Sea in making their waters salt. “When we come to you,” said they to the Sea.</p> <Media> <Image width={ 64 } height={ 64 } src={ require( '../assets/warstwa-7.png' ) } className="mr-3" alt="Generic placeholder" roundedCircle /> <Media.Body className="comment-user"> <h5>John Doe</h5> <p>CEO, THE RIVERS COMPANY</p> </Media.Body> </Media> </Col> <Col className="comment"> <p className="comment-content">A shoe is not only a design, but it's a part of your body language, the way you walk. The way you're going to move is quite dictated by your shoes.</p> <Media> <Image width={ 64 } height={ 64 } src={ require( '../assets/warstwa-16.png' ) } className="mr-3" alt="Generic placeholder" roundedCircle /> <Media.Body className="comment-user"> <h5>Dean Winchester</h5> <p>UX DESIGNER, GOOGLE INC.</p> </Media.Body> </Media> </Col> </Row> </Container> </Carousel.Caption> </Carousel.Item> <Carousel.Item interval={ 500 }> <Image src={ require( '../assets/warstwa-8.png' ) } alt="lucid" className='w-100' /> <Carousel.Caption> <Container> <Row> <Col> <StyledTitle> <h2 className='intro-title'>dip into the details</h2> <h3 className='title'>Beautiful on every device</h3> <span className='split-line'></span> </StyledTitle> </Col> </Row> <Row> <Col className="comment"> <p className="comment-content">Once upon a time all the Rivers combined to protest against the action of the Sea in making their waters salt. “When we come to you,” said they to the Sea.</p> <Media> <Image width={ 64 } height={ 64 } src={ require( '../assets/warstwa-7.png' ) } className="mr-3" alt="Generic placeholder" roundedCircle /> <Media.Body className="comment-user"> <h5>John Doe</h5> <p>CEO, THE RIVERS COMPANY</p> </Media.Body> </Media> </Col> <Col className="comment"> <p className="comment-content">A shoe is not only a design, but it's a part of your body language, the way you walk. The way you're going to move is quite dictated by your shoes.</p> <Media> <Image width={ 64 } height={ 64 } src={ require( '../assets/warstwa-16.png' ) } className="mr-3" alt="Generic placeholder" roundedCircle /> <Media.Body className="comment-user"> <h5>Dean Winchester</h5> <p>UX DESIGNER, GOOGLE INC.</p> </Media.Body> </Media> </Col> </Row> </Container> </Carousel.Caption> </Carousel.Item> <Carousel.Item interval={ 500 }> <Image src={ require( '../assets/warstwa-8.png' ) } alt="lucid" className='w-100' /> <Carousel.Caption> <Container> <Row> <Col> <StyledTitle> <h2 className='intro-title'>dip into the details</h2> <h3 className='title'>Beautiful on every device</h3> <span className='split-line'></span> </StyledTitle> </Col> </Row> <Row> <Col className="comment"> <p className="comment-content">Once upon a time all the Rivers combined to protest against the action of the Sea in making their waters salt. “When we come to you,” said they to the Sea.</p> <Media> <Image width={ 64 } height={ 64 } src={ require( '../assets/warstwa-7.png' ) } className="mr-3" alt="Generic placeholder" roundedCircle /> <Media.Body className="comment-user"> <h5>John Doe</h5> <p>CEO, THE RIVERS COMPANY</p> </Media.Body> </Media> </Col> <Col className="comment"> <p className="comment-content">A shoe is not only a design, but it's a part of your body language, the way you walk. The way you're going to move is quite dictated by your shoes.</p> <Media> <Image width={ 64 } height={ 64 } src={ require( '../assets/warstwa-16.png' ) } className="mr-3" alt="Generic placeholder" roundedCircle /> <Media.Body className="comment-user"> <h5>Dean Winchester</h5> <p>UX DESIGNER, GOOGLE INC.</p> </Media.Body> </Media> </Col> </Row> </Container> </Carousel.Caption> </Carousel.Item> <Carousel.Item interval={ 500 }> <Image src={ require( '../assets/warstwa-8.png' ) } alt="lucid" className='w-100' /> <Carousel.Caption> <Container> <Row> <Col> <StyledTitle> <h2 className='intro-title'>dip into the details</h2> <h3 className='title'>Beautiful on every device</h3> <span className='split-line'></span> </StyledTitle> </Col> </Row> <Row> <Col className="comment"> <p className="comment-content">Once upon a time all the Rivers combined to protest against the action of the Sea in making their waters salt. “When we come to you,” said they to the Sea.</p> <Media> <Image width={ 64 } height={ 64 } src={ require( '../assets/warstwa-7.png' ) } className="mr-3" alt="Generic placeholder" roundedCircle /> <Media.Body className="comment-user"> <h5>John Doe</h5> <p>CEO, THE RIVERS COMPANY</p> </Media.Body> </Media> </Col> <Col className="comment"> <p className="comment-content">A shoe is not only a design, but it's a part of your body language, the way you walk. The way you're going to move is quite dictated by your shoes.</p> <Media> <Image width={ 64 } height={ 64 } src={ require( '../assets/warstwa-16.png' ) } className="mr-3" alt="Generic placeholder" roundedCircle /> <Media.Body className="comment-user"> <h5>Dean Winchester</h5> <p>UX DESIGNER, GOOGLE INC.</p> </Media.Body> </Media> </Col> </Row> </Container> </Carousel.Caption> </Carousel.Item> </Carousel> </StyledCaption> </Row> </div> ) } }
// Expressoes Regulares // As expressoes regulares são estruturas formadas por um sequência de // caracteres que especificam um padão formal // Instancia // Forma Literal var regExp = /<expressão regular>/; // Quando criada de forma literal é necessario utilizar / / no lugar de "" // para a criação da expressão regular. // Contrutor var regExp = new RegExp("<expressão regular>"); // RegExp API // exec // Executa a RegExp, retornando os detalhes // [ '9999-9999', index: 0, input: '9999-9999' ] // test // Testa a RegExp, retornando true ou false // Exemplos // exec e test var regExp = /9999-9999/; var telefone = '9999-9999'; console.log(regExp.exec(telefone)); // [ '9999-9999', index: 0, input: '9999-9999' ] // Retorna os detalhes, como qual foi o index do regex que ele encontrou o input. console.log(regExp.test(telefone)); // true // Retorna somente se o input foi encontrado no regex ou não. // Escape \ var regExp = /\(48\) 9999-9999/; // Alguns caracteres como () são caracteres especiais que tem um significado // dentro de um regex, como "caracteres reservados", então é necessario "escapar" // estes caracteres especiais utilizando \ para que eles se tornem literais // na expressão regular. var telefone = '(48) 9999-9999'; console.log(regExp.test(telefone)); // true // Inicio e Fim ^ $ var regExp = /^\(48\) 9999-9999$/; var telefone = 'O telefone é (48) 9999-9999, tratar com João'; console.log(regExp.exec(telefone)); // null console.log(regExp.test(telefone)); // false telefone = '(48) 9999-9999'; console.log(regExp.exec(telefone)); // [ '9999-9999', index: 0, input: '9999-9999' ] console.log(regExp.test(telefone)); // true // Grupos de caracteres // [abc] - Aceita qualquer caractere dentro do grupo, neste caso a, b e c // [^abc] - Não aceita qualquer caractere dentro do grupo, neste caso a, b ou c // [0-9] - Aceita qualquer caractere entre 0 e 9 // [^0-9] - Não aceita qualquer caractere entre 0 e 9 // O ^ dentro de um grupo indica negação daquele grupo, ou seja, não irá // aceitar os valores do grupo. // O - dentro do grupo indica o range, ou seja, de qual a qual caractere // eu vou aceitar, ou negar, no regex. Isso serve para não ter que adicionar // todos os numeros de 0 a 9 ou todos os caracteres de A a B por exemplo. var regExp = /^\([0-9][0-9]\) [0-9][0-9][0-9][0-9]-[0-9][0-9][0-9][0-9]$/; var telefone = "(80) 9876-1234"; console.log(regExp.test(telefone)); // true // Quantificadores // Os quantificadores podem ser aplicados a caracteres, grupos, conjuntos ou metacaracteres. // {n} - Quantifica um número específico // {n,} - Quantifica um número mínimo // {n,m} - Quantifica um número mínimo e um número máximo // ? - Zero ou um (faz o caracter ter carater opcional) // * - Zero ou mais // + - Um ou mais // Para definir somente maximo deve ser adicionado {0,m} ao regex. // Exemplo {n} var regExp = /^\([0-9]{2}\) [0-9]{4}-[0-9]{4}$/; var telefone = "(80) 9876-1234"; console.log(regExp.test(telefone)); // true // Exemplo {n,m} var regExp = /^\([0-9]{2}\) [0-9]{4,5}-[0-9]{4}$/; var telefone1 = "(80) 9876-1234"; console.log(regExp.test(telefone1)); // true var telefone2 = "(80) 99876-1234"; console.log(regExp.test(telefone2)); // true // Exemplo ? var regExp = /^\([0-9]{2}\) [0-9]{4,5}-?[0-9]{4}$/; var telefone1 = "(80) 9876-1234"; console.log(regExp.test(telefone1)); // true var telefone2 = "(80) 98761234"; console.log(regExp.test(telefone2)); // true // Exemplo + var regExp = /<table><tr>(<td>\([0-9]{2}\) [0-9]{4,5}-?[0-9]{4}<\/td>)+<\/tr><\/table>/; var telefone = "<table>\ <tr>\ <td>(80) 999778899</td>\ <td>(90) 99897-8877</td>\ <td>(70) 98767-9999</td>\ </tr>\ </table>"; regExp.test(telefone); // true // Exemplo * var regExp = /<table><tr>(<td>\([0-9]{2}\) [0-9]{4,5}-?[0-9]{4}<\/td>)*<\/tr><\/table>/; var telefone = "<table>\ <tr>\ </tr>\ </table>"; regExp.test(telefone); // true // Metacaracteres // . - Representa qualquer caractere // \w - Representa o confjunto [a-zA-Z0-9_] // \W - Representa o conjunto [^a-zA-Z0-9_] // \d - Representa o conjunto [0-9] // \D - Representa o conjunto [^0-9] // \s - Representa um espaço em branco // \S - Representa um não espaço em branco // \n - Representa uma quebra de linha // \t - Representa um tab // ... // Exemplo var regExp = /<table><tr>(<td>\(\d{2}\)\s\d{4,5}-?\d{4}<\/td>)+<\/tr><\/table>/; var telefone = "<table>\ <tr>\ <td>(80) 999778899</td>\ <td>(90) 99897-8877</td>\ <td>(70) 98767-9999</td>\ </tr>\ </table>"; regExp.test(telefone); // true // String API // match - Executa uma busca na String e retorna um array contendo // os dados encontrados, ou null. // split - Divide a String com base em uma outra String fixa ou // expressão regular. // replace - Substitui partes da String com base em uma outra // String fixa ou expressão regular. // Modificadores // i - Case-insensitive matching // g - Global matching // m - Multiline matching // Exemplo match var regExp = /\(\d{2}\)\s\d{4,5}-?\d{4}/g; // Se o g não fosse adicionado no final o match não iria // pegar todos os telefones, somente o primeiro. // Na forma de contrutor seria: var regExp = new RegExp('\(\d{2}\)\s\d{4,5}-?\d{4}', g); // O modificador é o segundo parametro do contrutor. var telefone = "<table>\ <tr>\ <td>(80) 999778899</td>\ <td>(90) 99897-8877</td>\ <td>(70) 98767-9999</td>\ </tr>\ </table>"; telefone.match(regExp); // [ '(80) 999778899', '(90) 99897-8877', '(70) 98767-9999' ] // Se não houvesse o modificador g, o retorno seria '(80) 999778899' // Exemplo replace var regExp = /\(\d{2}\)\s\d{4,5}-?\d{4}/g; var telefone = "<table>\ <tr>\ <td>(80) 999778899</td>\ <td>(90) 99897-8877</td>\ <td>(70) 98767-9999</td>\ </tr>\ </table>"; telefone.replace(regExp, 'telefone'); // "<table><tr><td>telefone</td><td>telefone</td><td>telefone</td></tr></table>" // Referencias // Expressões Regulares // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions
var searchData= [ ['introducció',['Introducció',['../md_docs_HARDCODE_Jocs_de_proves.html',1,'']]] ];