code
stringlengths
2
1.05M
(function(){ 'use strict'; angular .module('users') .controller('EmailChangeCtrl', ['$rootScope', '$scope', '$state', '$location', '$translate', 'restFulService', 'config', 'errorService', function($rootScope, $scope, $state, $location, $translate, restFulService, config, errorService){ $scope.show = { message: false }; // Si falta alguno de los 3 parametros if ($state.params.token === '' || $state.params.tokenId === '' || $state.params.userId === '') $location.path('error'); // Se valida que el token exista en la DB restFulService.get('emailChange/validate/' + $state.params.token +'/'+ $state.params.tokenId +'/'+ $state.params.userId) .then(function(response){ $scope.email = response.email; $rootScope.user.email = response.email; $scope.show.message = true; }) .catch(function(err){ $location.path('error/' + err.status); }); }]); }());
import Vue from 'vue' import * as types from './mutation-types' export default { [types.PUT] (state, { key, value }) { Vue.set(state, key, value) }, [types.REMOVE] (state, { key }) { Vue.delete(state, key) }, [types.SYNC] (state, { records }) { // Delete existing keys - Cognito datastore is the source of truth for (const key in state) { Vue.delete(state, key) } // Assign keys from Cognito datastore for (const record of records) { if (!record.value) continue Vue.set(state, record.key, record.value) } } }
'use strict'; describe('Service: scenarioFactory', function () { // load the service's module beforeEach(module('testerApp')); // instantiate service var scenarioFactory; beforeEach(inject(function (_scenarioFactory_) { scenarioFactory = _scenarioFactory_; })); it('should do something', function () { expect(!!scenarioFactory).toBe(true); }); });
const _ = require('lodash'); module.exports = () => (hook) => { const sequelize = hook.app.get('sequelize'); const eventId = hook.result.id; const quotasToAdd = hook.data.quota.map(quota => _.merge(quota, { eventId })); const quotaModel = hook.app.get('models').quota; return sequelize.transaction(t => { return quotaModel.destroy({ where: { eventId } }, { transaction: t }).then(() => { return quotaModel.bulkCreate(quotasToAdd, { updateOnDuplicate: true }, { transaction: t }) .then(() => { return quotaModel.findAll({ where: { eventId, deletedAt: null }, order: [ ['sortId', 'ASC'], ], include: [{ attributes: ['firstName', 'lastName', 'email', 'createdAt'], model: sequelize.models.signup, required: false }] }, { transaction: t }); }); }); }).then((quota) => { hook.result.dataValues.quota = quota; return hook; }).catch((error => { throw new Error('Quota update failed:', error); })); };
'use strict'; /** * @ngdoc function * @name teamDjApp.controller:AboutCtrl * @description * # AboutCtrl * Controller of the teamDjApp */ angular.module('teamDjApp') .controller('AboutCtrl', function ($rootScope) { $rootScope.activetab = 'about'; });
module("Unit - Party",{ setup: function(){ var mod = this; Ember.run(this,function(){ var appController = App.__container__.lookup("controller:application") ; mod.appC = appController ; mod.store = appController.store ; resetTests(mod.store).then(function(){ mod.baseParty = mod.store.createRecord('party',{ name: 'baseparty', size: 2, phone_number: '3125551212', time_taken: '2013-11-05T20:15:15' }) ; }) ; }) ; wait() ; }, teardown: function(){ destroy(this.store, this.appC) ; return wait() ; } }) ; asyncTest("party.notified", 2, function() { var party = this.baseParty; equal(false, party.get('notified'), "initially, party.notified should be false") ; Ember.run(function(){ party.set('time_notified', '2013-11-05T20:35:15') ; equal(true, party.get('notified'), "after setting time_notified, party.notified should be true") ; start() ; }); }); asyncTest("party.seated", 2, function() { var party = this.baseParty; equal(false, party.get('seated'), "initially, party.seated should be false") ; Ember.run(function(){ party.set('time_seated', '2013-11-05T20:35:15') ; equal(true, party.get('seated'), "after setting time_seated, party.seated should be true") ; start() ; }); }); asyncTest("party.waiting depends on party.time_seated", 3, function() { var party = this.baseParty; equal(true, party.get('waiting'), "initially, party.waiting should be true") ; Ember.run(function(){ party.set('time_seated', '2013-11-05T20:35:15') ; equal(false, party.get('waiting'), "after setting time_seated, party.waiting should be false") ; party.set('time_seated', null) ; equal(true, party.get('waiting'), "after setting time_seated to null, party.waiting should be true") ; start() ; }); }); asyncTest("party.waiting depends on party.time_cancelled", function() { var party = this.baseParty; equal(party.get('waiting'), true, "initially, party.waiting should be true") ; Ember.run(function(){ party.set('time_cancelled', '2013-11-05T20:35:15') ; equal(party.get('waiting'), false, "after setting time_cancelled, party.waiting should be false") ; party.set('time_cancelled', null) ; equal(party.get('waiting'), true, "after setting time_cancelled to null, party.waiting should be true") ; start() ; }); }); asyncTest("party.waiting depends on party.time_cancelled and party.time_seated", function() { var party = this.baseParty; equal(party.get('waiting'), true, "initially, party.waiting should be true") ; Ember.run(function(){ party.set('time_seated', '2013-11-05T20:35:15') ; equal(party.get('waiting'), false, "after setting time_seated, party.waiting should be false") ; party.set('time_cancelled', '2013-11-05T20:40:15') ; equal(party.get('waiting'), false, "after setting time_cancelled, party.waiting should still be false") ; party.set('time_cancelled', null) ; equal(party.get('waiting'), false, "after setting time_cancelled to null, party.waiting should still be false") ; party.set('time_seated', null) ; equal(party.get('waiting'), true, "after setting time_seated and time_cancelled to null, party.waiting should be true") ; start() ; }); }); asyncTest("party.countdown should count down seconds", function(){ var party = this.baseParty ; var now = moment() ; Ember.run(function(){ party.set('time_notified',now.subtract('minute',1).format("YYYY-MM-DDTHH:mm:ss")) ; var rem = Math.round(party.get('countdown')/1000) ; ok(Math.abs(rem-(4*60)) <= 1, "countdown should equal 4 min give or take a second") ; start() ; }); }) ; asyncTest("party.countdown should count up if negative", function(){ var party = this.baseParty ; Ember.run(function(){ var now = moment() ; party.set('time_notified',now.subtract('minute',7).format("YYYY-MM-DDTHH:mm:ss")) ; var rem = Math.round(party.get('countdown')/1000) ; ok(Math.abs(rem-(2*60)) <= 1, "countup should equal 2 min give or take a second") ; }); Ember.run(function(){ var now = moment() ; party.set('time_notified',now.subtract('minute',9).format("YYYY-MM-DDTHH:mm:ss")) ; var rem = Math.round(party.get('countdown')/1000) ; ok(Math.abs(rem-(4*60)) <= 1, "countup should equal 4 min give or take a second") ; start() ; }); }) ; asyncTest("party.overdue", function(){ var party = this.baseParty ; var now = moment() ; equal(party.get('overdue'), false, "Party should not be initially overdue") ; Ember.run(function(){ party.set('time_notified',now.subtract('minute',3).format("YYYY-MM-DDTHH:mm:ss")) ; equal(party.get('overdue'), false, "Party should not be overdue at 3 min") ; }); Ember.run(function(){ party.set('time_notified',now.subtract('minute',7).format("YYYY-MM-DDTHH:mm:ss")) ; equal(party.get('overdue'), true, "Party should be overdue at 7 min") ; start() ; }); }) ;
/** @jsx jsx */ import { Editor } from 'slate' import { jsx } from '../../..' export const run = editor => { Editor.delete(editor, { reverse: true }) } export const input = ( <editor> <block>Hello</block> <block> <block> <cursor /> world! </block> </block> </editor> ) export const output = ( <editor> <block> Hello <cursor /> world! </block> </editor> )
/******************************************************************************* * bars coming out from a circle */ function VizRadialBars(variant) { this.dampen = true; this.hasVariants = true; this.variants = [[false], [true]]; this.vary(variant); } VizRadialBars.prototype.resize = function() {} VizRadialBars.prototype.vary = function(variant) { this.variant = variant; this.fade = this.variants[variant][0]; } VizRadialBars.prototype.draw = function(spectrum) { ctx.save(); ctx.clearRect(0, 0, cv.width, cv.height) ctx.translate(cv.width / 2, cv.height / 2); ctx.rotate(allRotate); for (var i = 0; i < bandCount; i++) { ctx.rotate(rotateAmount); var hue = Math.floor(360.0 / bandCount * i); if (this.fade) { var brightness = constrain(Math.floor(spectrum[i] / 1.5), 25, 99); ctx.fillStyle = bigColorMap[hue * 100 + brightness]; ctx.fillRect(-bandWidth / 2, centerRadius, bandWidth, Math.max(2, spectrum[i] * heightMultiplier)); } else { var avg = 0; avg = (spectrum[i] + lastVolumes[i]) / 2; ctx.fillStyle = bigColorMap[hue * 100 + 50]; ctx.fillRect(-bandWidth / 2, centerRadius + avg, bandWidth, 2); ctx.fillStyle = bigColorMap[hue * 100 + 99]; ctx.fillRect(-bandWidth / 2, centerRadius, bandWidth, spectrum[i] * heightMultiplier); } } allRotate += 0.002; ctx.restore(); }
processGoogleToken({"newToken":"AE3Dx9aK3LQnhKzNv0kv9PYihJmwErt6SUKSiCdFy2nuPqU9RIHm72lwytcOh_wVXg","validLifetimeSecs":86400,"freshLifetimeSecs":86400,"1p_jar":"2018-1-31-12","pucrd":"CgwIABAAGAMgACgAOAESAhgH"});
// line comment // line comment with prefix space /** * block comment */ function test () { var a = 'ok' var error }
import Route from '@ember/routing/route'; import { inject as service } from '@ember/service'; import { isBlank } from '@ember/utils'; export default Route.extend({ /** Service that get current project contexts. @property currentProjectContext @type {Class} @default service() */ currentProjectContext: service('fd-current-project-context'), /** List exist subsystems. @property subsystems @type Array */ subsystems: undefined, /** A hook you can implement to convert the URL into the model for this route. [More info](http://emberjs.com/api/classes/Ember.Route.html#method_model). @method model */ model: function() { const subsystems = this.get('subsystems'); const stage = this.get('currentProjectContext').getCurrentStage(); const adapter = this.get('store').adapterFor('application'); const data = { 'project': stage, 'moduleSettingTypes': subsystems }; return adapter.callAction('GetCurrentModuleSettings', data, null, { withCredentials: true }).then((subsystemsSettings) => { let currentSubsystemsSettings = JSON.parse(subsystemsSettings.value); let updateSubsystemsSettings = {}; for (let prop in currentSubsystemsSettings) { let value = currentSubsystemsSettings[prop]; let newValue = !isBlank(value) ? JSON.parse(value) : {}; updateSubsystemsSettings[prop] = newValue; } return updateSubsystemsSettings; }); }, init() { this._super(...arguments); this.set('subsystems', ['GisSubsystemSettings'/*, 'SecuritySubsystemSettings', 'AuditSubsystemSettings'*/]); }, /** A hook you can use to setup the controller for the current route. [More info](https://www.emberjs.com/api/ember/release/classes/Route/methods/setupController?anchor=setupController). @method setupController @param {<a href="https://emberjs.com/api/ember/release/classes/Controller">Controller</a>} controller */ setupController(controller) { this._super(...arguments); controller.set('routeName', this.get('routeName')); } });
var searchData= [ ['incomelinks',['incomeLinks',['../classDAGraphNode.html#abdf9c01751f27d2294ce2bd00f197778',1,'DAGraphNode']]] ];
import layout from '../templates/components/input-for'; import FormControl from './form-control'; import Ember from 'ember'; const { get, set, isPresent, computed } = Ember; export default FormControl.extend({ layout, classNameBindings: ['hasValue'], init() { this._super(...arguments); let field = get(this, 'field'); this.hasValue = computed(`data.${field}`, 'placeholder', () => { if (isPresent(get(this, 'placeholder'))) { return true; } return isPresent(get(this, `data.${field}`)); }); }, didReceiveAttrs() { this._super(...arguments); if (!get(this, 'type')) { set(this, 'type', 'text'); } } });
"use strict"; (function () { var app = angular.module("storeProducts", []); app.directive("productTitle", function () { return { restrict: "A", templateUrl: "product-title.html" } }); app.directive("productDescription", function () { return { restrict: "E", templateUrl: "product-description.html" } }); app.directive("productSpecs", function () { return { restrict: "E", templateUrl: "product-specs.html" } }); app.directive("productReviews", function () { return { restrict: "E", templateUrl: "product-reviews.html" } }); app.directive("productReviewsForm", function () { return { restrict: "E", templateUrl: "product-reviews-form.html" } }); app.directive("productPanels", function () { return { restrict: "E", templateUrl: "product-panels.html", controller: function () { this.tab = 1; this.setTab = function (setTab) { this.tab = setTab; }; this.isSet = function (setValue) { return this.tab === setValue; }; this.setActive = function (activeValue) { return this.tab === activeValue; }; }, controllerAs: "navTab" } }); app.directive("productGallery", function () { return { restrict: "E", templateUrl: "product-gallery.html", controller: function () { this.currentImage = 0; this.setCurrent = function (currentValue) { this.currentImage = currentValue || 0; }; this.toggleCurrent = function (toggleValue) { if (this.currentImage === toggleValue) { return false; } this.currentImage = toggleValue || 0; }; this.setActive = function (activeValue) { return this.currentImage === activeValue; }; }, controllerAs: "gallery" } }); app.directive("productButton", function () { return { restrict: "E", templateUrl: "product-button.html" }; }); })();
var diff = require('../'); var left = { left: 'yes', right: 'no', }; var right = { left: { toString: true, }, right: 'no', }; console.log(diff(left, right)); // eslint-disable-line no-console
/* * This file is part of the hyyan/woo-poly-integration plugin. * (c) Hyyan Abo Fakher <tiribthea4hyyan@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ (function ($, document, HYYAN_WPI_VARIABLES) { /** * Construct variables * * @param {jQuery} $ * @param {document} document * @param {object} data * * @returns {Variables} */ var Variables = function ($, document, data) { this.$ = $; this.document = document; this.data = data; this._dialog = this._createDialog(); }; Variables.prototype = { /** Constructor */ constructor: Variables, init: function () { var self = this; $('#post_lang_choice').change(function () { self.shouldAlert(); }); $('#product-type').change(function () { self.shouldAlert(); }); } /** * Check if we should alert the user * * @returns {Boolean} */ , shouldAlert: function () { var type = this.getCurrentProduct(); var lang = this.getCurrentLanguage(); if (type === 'variable' && lang !== this.data['defaultLang']) { this._dialog.dialog('open'); /* Disable Saving */ this._changeSaveBoxState(true); return true; } this._changeSaveBoxState(false); return false; } /** * Get current product language * * @returns {String} */ , getCurrentLanguage: function () { return this.$('#post_lang_choice').val(); } /** * Get current product type * * @returns {string} */ , getCurrentProduct: function () { return this.$('#product-type').val(); } /** * Change the state of save box from disable to enable and vs * * @param {boolean} enable */ , _changeSaveBoxState: function (enable) { this.$('#submitdiv *').attr('disabled', enable); } /** * Create dialog * * @returns {objet} */ , _createDialog: function () { /* This variable */ var self = this; /* Fix the z-index */ this.$('<style>.ui-dialog { z-index: 1000 !important ;}</style>') .appendTo($('head')); /* Create dialog */ var dialog = this.$("<div id='woo-poly-variables-dialog'/>") .html('<p>' + self.data['content'] + '</p>') .attr('title', self.data['title']) .appendTo("body"); dialog.dialog({ dialogClass: "wp-dialog", autoOpen: false, modal: true, width: 400, height: 250, position: { my: "center", at: "center" }, buttons: [ { text: 'Got It', click: function () { $(this).dialog('close'); } } ] }); return dialog; } }; // bootstrap $(document).ready(function ($) { new Variables($, document, HYYAN_WPI_VARIABLES).init(); }); })(jQuery, document, HYYAN_WPI_VARIABLES);
ml.module('three.extras.objects.ImmediateRenderObject') .requires('three.Three', 'three.core.Object3D') .defines(function(){ /** * @author alteredq / http://alteredqualia.com/ */ THREE.ImmediateRenderObject = function ( ) { THREE.Object3D.call( this ); this.render = function ( renderCallback ) { }; }; THREE.ImmediateRenderObject.prototype = Object.create( THREE.Object3D.prototype ); });
const initialState = { types: [], running: [], performatives: [] } const reduce = (state = initialState, action) => { switch (action.type) { case 'ADD_TYPES': return { ...state, types: [...state.types, ...action.types] }; case 'ADD_RUNNING': return { ...state, running: [...state.running, ...action.runningAgents] }; case 'UPDATE_TYPES': return { ...state, types: action.types }; case 'UPDATE_RUNNING': return { ...state, running: action.running }; case 'START_AGENT': return { ...state, running: [...state.running, action.agent] }; case 'STOP_AGENT': const running = state.running.filter(agent => agent.id.name !== action.name); return { ...state, running }; case 'SET_PERFORMATIVES': return { ...state, performatives: action.performatives } default: return state; } }; export default reduce;
module.exports = require('material-ui/Dialog');
'use strict'; const chai = require('chai'); const Sequelize = require('@sequelize/core'); const Op = Sequelize.Op; const expect = chai.expect; const Support = require('../support'); const DataTypes = require('@sequelize/core/lib/data-types'); const dialect = Support.getTestDialect(); const _ = require('lodash'); const promiseProps = require('p-props'); const sortById = function (a, b) { return a.id < b.id ? -1 : 1; }; describe(Support.getTestDialectTeaser('Includes with schemas'), () => { describe('findAll', () => { afterEach(async function () { await this.sequelize.dropSchema('account'); }); beforeEach(async function () { this.fixtureA = async function () { await this.sequelize.dropSchema('account'); await this.sequelize.createSchema('account'); const AccUser = this.sequelize.define('AccUser', {}, { schema: 'account' }); const Company = this.sequelize.define('Company', { name: DataTypes.STRING, }, { schema: 'account' }); const Product = this.sequelize.define('Product', { title: DataTypes.STRING, }, { schema: 'account' }); const Tag = this.sequelize.define('Tag', { name: DataTypes.STRING, }, { schema: 'account' }); const Price = this.sequelize.define('Price', { value: DataTypes.FLOAT, }, { schema: 'account' }); const Customer = this.sequelize.define('Customer', { name: DataTypes.STRING, }, { schema: 'account' }); const Group = this.sequelize.define('Group', { name: DataTypes.STRING, }, { schema: 'account' }); const GroupMember = this.sequelize.define('GroupMember', {}, { schema: 'account' }); const Rank = this.sequelize.define('Rank', { name: DataTypes.STRING, canInvite: { type: DataTypes.INTEGER, defaultValue: 0, }, canRemove: { type: DataTypes.INTEGER, defaultValue: 0, }, canPost: { type: DataTypes.INTEGER, defaultValue: 0, }, }, { schema: 'account' }); this.models = { AccUser, Company, Product, Tag, Price, Customer, Group, GroupMember, Rank, }; AccUser.hasMany(Product); Product.belongsTo(AccUser); Product.belongsToMany(Tag, { through: 'product_tag' }); Tag.belongsToMany(Product, { through: 'product_tag' }); Product.belongsTo(Tag, { as: 'Category' }); Product.belongsTo(Company); Product.hasMany(Price); Price.belongsTo(Product); AccUser.hasMany(GroupMember, { as: 'Memberships' }); GroupMember.belongsTo(AccUser); GroupMember.belongsTo(Rank); GroupMember.belongsTo(Group); Group.hasMany(GroupMember, { as: 'Memberships' }); await this.sequelize.sync({ force: true }); const [groups, companies, ranks, tags] = await Promise.all([ Group.bulkCreate([ { name: 'Developers' }, { name: 'Designers' }, { name: 'Managers' }, ]).then(() => Group.findAll()), Company.bulkCreate([ { name: 'Sequelize' }, { name: 'Coca Cola' }, { name: 'Bonanza' }, { name: 'NYSE' }, { name: 'Coshopr' }, ]).then(() => Company.findAll()), Rank.bulkCreate([ { name: 'Admin', canInvite: 1, canRemove: 1, canPost: 1 }, { name: 'Trustee', canInvite: 1, canRemove: 0, canPost: 1 }, { name: 'Member', canInvite: 1, canRemove: 0, canPost: 0 }, ]).then(() => Rank.findAll()), Tag.bulkCreate([ { name: 'A' }, { name: 'B' }, { name: 'C' }, { name: 'D' }, { name: 'E' }, ]).then(() => Tag.findAll()), ]); for (const i of [0, 1, 2, 3, 4]) { const [user, products] = await Promise.all([ AccUser.create(), Product.bulkCreate([ { title: 'Chair' }, { title: 'Desk' }, { title: 'Bed' }, { title: 'Pen' }, { title: 'Monitor' }, ]).then(() => Product.findAll()), ]); const groupMembers = [ { AccUserId: user.id, GroupId: groups[0].id, RankId: ranks[0].id }, { AccUserId: user.id, GroupId: groups[1].id, RankId: ranks[2].id }, ]; if (i < 3) { groupMembers.push({ AccUserId: user.id, GroupId: groups[2].id, RankId: ranks[1].id }); } await Promise.all([ GroupMember.bulkCreate(groupMembers), user.setProducts([ products[i * 5 + 0], products[i * 5 + 1], products[i * 5 + 3], ]), products[i * 5 + 0].setTags([ tags[0], tags[2], ]), products[i * 5 + 1].setTags([ tags[1], ]), products[i * 5 + 0].setCategory(tags[1]), products[i * 5 + 2].setTags([ tags[0], ]), products[i * 5 + 3].setTags([ tags[0], ]), products[i * 5 + 0].setCompany(companies[4]), products[i * 5 + 1].setCompany(companies[3]), products[i * 5 + 2].setCompany(companies[2]), products[i * 5 + 3].setCompany(companies[1]), products[i * 5 + 4].setCompany(companies[0]), Price.bulkCreate([ { ProductId: products[i * 5 + 0].id, value: 5 }, { ProductId: products[i * 5 + 0].id, value: 10 }, { ProductId: products[i * 5 + 1].id, value: 5 }, { ProductId: products[i * 5 + 1].id, value: 10 }, { ProductId: products[i * 5 + 1].id, value: 15 }, { ProductId: products[i * 5 + 1].id, value: 20 }, { ProductId: products[i * 5 + 2].id, value: 20 }, { ProductId: products[i * 5 + 3].id, value: 20 }, ]), ]); } }; await this.sequelize.createSchema('account'); }); it('should support an include with multiple different association types', async function () { await this.sequelize.dropSchema('account'); await this.sequelize.createSchema('account'); const AccUser = this.sequelize.define('AccUser', {}, { schema: 'account' }); const Product = this.sequelize.define('Product', { title: DataTypes.STRING, }, { schema: 'account' }); const Tag = this.sequelize.define('Tag', { name: DataTypes.STRING, }, { schema: 'account' }); const Price = this.sequelize.define('Price', { value: DataTypes.FLOAT, }, { schema: 'account' }); const Group = this.sequelize.define('Group', { name: DataTypes.STRING, }, { schema: 'account' }); const GroupMember = this.sequelize.define('GroupMember', {}, { schema: 'account' }); const Rank = this.sequelize.define('Rank', { name: DataTypes.STRING, canInvite: { type: DataTypes.INTEGER, defaultValue: 0, }, canRemove: { type: DataTypes.INTEGER, defaultValue: 0, }, }, { schema: 'account' }); AccUser.hasMany(Product); Product.belongsTo(AccUser); Product.belongsToMany(Tag, { through: 'product_tag' }); Tag.belongsToMany(Product, { through: 'product_tag' }); Product.belongsTo(Tag, { as: 'Category' }); Product.hasMany(Price); Price.belongsTo(Product); AccUser.hasMany(GroupMember, { as: 'Memberships' }); GroupMember.belongsTo(AccUser); GroupMember.belongsTo(Rank); GroupMember.belongsTo(Group); Group.hasMany(GroupMember, { as: 'Memberships' }); await this.sequelize.sync({ force: true }); const [groups, ranks, tags] = await Promise.all([ Group.bulkCreate([ { name: 'Developers' }, { name: 'Designers' }, ]).then(() => Group.findAll()), Rank.bulkCreate([ { name: 'Admin', canInvite: 1, canRemove: 1 }, { name: 'Member', canInvite: 1, canRemove: 0 }, ]).then(() => Rank.findAll()), Tag.bulkCreate([ { name: 'A' }, { name: 'B' }, { name: 'C' }, ]).then(() => Tag.findAll()), ]); for (const i of [0, 1, 2, 3, 4]) { const [user, products] = await Promise.all([ AccUser.create(), Product.bulkCreate([ { title: 'Chair' }, { title: 'Desk' }, ]).then(() => Product.findAll()), ]); await Promise.all([ GroupMember.bulkCreate([ { AccUserId: user.id, GroupId: groups[0].id, RankId: ranks[0].id }, { AccUserId: user.id, GroupId: groups[1].id, RankId: ranks[1].id }, ]), user.setProducts([ products[i * 2 + 0], products[i * 2 + 1], ]), products[i * 2 + 0].setTags([ tags[0], tags[2], ]), products[i * 2 + 1].setTags([ tags[1], ]), products[i * 2 + 0].setCategory(tags[1]), Price.bulkCreate([ { ProductId: products[i * 2 + 0].id, value: 5 }, { ProductId: products[i * 2 + 0].id, value: 10 }, { ProductId: products[i * 2 + 1].id, value: 5 }, { ProductId: products[i * 2 + 1].id, value: 10 }, { ProductId: products[i * 2 + 1].id, value: 15 }, { ProductId: products[i * 2 + 1].id, value: 20 }, ]), ]); const users = await AccUser.findAll({ include: [ { model: GroupMember, as: 'Memberships', include: [ Group, Rank, ], }, { model: Product, include: [ Tag, { model: Tag, as: 'Category' }, Price, ], }, ], order: [ [AccUser.rawAttributes.id, 'ASC'], ], }); for (const user of users) { expect(user.Memberships).to.be.ok; user.Memberships.sort(sortById); expect(user.Memberships.length).to.equal(2); expect(user.Memberships[0].Group.name).to.equal('Developers'); expect(user.Memberships[0].Rank.canRemove).to.equal(1); expect(user.Memberships[1].Group.name).to.equal('Designers'); expect(user.Memberships[1].Rank.canRemove).to.equal(0); user.Products.sort(sortById); expect(user.Products.length).to.equal(2); expect(user.Products[0].Tags.length).to.equal(2); expect(user.Products[1].Tags.length).to.equal(1); expect(user.Products[0].Category).to.be.ok; expect(user.Products[1].Category).not.to.be.ok; expect(user.Products[0].Prices.length).to.equal(2); expect(user.Products[1].Prices.length).to.equal(4); } } }); it('should support many levels of belongsTo', async function () { const A = this.sequelize.define('a', {}, { schema: 'account' }); const B = this.sequelize.define('b', {}, { schema: 'account' }); const C = this.sequelize.define('c', {}, { schema: 'account' }); const D = this.sequelize.define('d', {}, { schema: 'account' }); const E = this.sequelize.define('e', {}, { schema: 'account' }); const F = this.sequelize.define('f', {}, { schema: 'account' }); const G = this.sequelize.define('g', {}, { schema: 'account' }); const H = this.sequelize.define('h', {}, { schema: 'account' }); A.belongsTo(B); B.belongsTo(C); C.belongsTo(D); D.belongsTo(E); E.belongsTo(F); F.belongsTo(G); G.belongsTo(H); let b; const singles = [ B, C, D, E, F, G, H, ]; await this.sequelize.sync(); await A.bulkCreate([ {}, {}, {}, {}, {}, {}, {}, {}, ]); let previousInstance; for (const model of singles) { const instance = await model.create({}); if (previousInstance) { await previousInstance[`set${_.upperFirst(model.name)}`](instance); previousInstance = instance; continue; } previousInstance = b = instance; } let as = await A.findAll(); await Promise.all(as.map(a => a.setB(b))); as = await A.findAll({ include: [ { model: B, include: [ { model: C, include: [ { model: D, include: [ { model: E, include: [ { model: F, include: [ { model: G, include: [ { model: H }, ], }, ], }, ], }, ], }, ], }, ], }, ], }); expect(as.length).to.be.ok; for (const a of as) { expect(a.b.c.d.e.f.g.h).to.be.ok; } }); it('should support ordering with only belongsTo includes', async function () { const User = this.sequelize.define('SpecialUser', {}, { schema: 'account' }); const Item = this.sequelize.define('Item', { test: DataTypes.STRING }, { schema: 'account' }); const Order = this.sequelize.define('Order', { position: DataTypes.INTEGER }, { schema: 'account' }); User.belongsTo(Item, { as: 'itemA', foreignKey: 'itemA_id' }); User.belongsTo(Item, { as: 'itemB', foreignKey: 'itemB_id' }); User.belongsTo(Order); await this.sequelize.sync(); await Promise.all([ User.bulkCreate([{}, {}, {}]), Item.bulkCreate([ { test: 'abc' }, { test: 'def' }, { test: 'ghi' }, { test: 'jkl' }, ]), Order.bulkCreate([ { position: 2 }, { position: 3 }, { position: 1 }, ]), ]); const [users, items, orders] = await Promise.all([ User.findAll(), Item.findAll({ order: ['id'] }), Order.findAll({ order: ['id'] }), ]); await Promise.all([ users[0].setItemA(items[0]), users[0].setItemB(items[1]), users[0].setOrder(orders[2]), users[1].setItemA(items[2]), users[1].setItemB(items[3]), users[1].setOrder(orders[1]), users[2].setItemA(items[0]), users[2].setItemB(items[3]), users[2].setOrder(orders[0]), ]); const as = await User.findAll({ include: [ { model: Item, as: 'itemA', where: { test: 'abc' } }, { model: Item, as: 'itemB' }, Order], order: [ [Order, 'position'], ], }); expect(as.length).to.eql(2); expect(as[0].itemA.test).to.eql('abc'); expect(as[1].itemA.test).to.eql('abc'); expect(as[0].Order.position).to.eql(1); expect(as[1].Order.position).to.eql(2); }); it('should include attributes from through models', async function () { const Product = this.sequelize.define('Product', { title: DataTypes.STRING, }, { schema: 'account' }); const Tag = this.sequelize.define('Tag', { name: DataTypes.STRING, }, { schema: 'account' }); const ProductTag = this.sequelize.define('ProductTag', { priority: DataTypes.INTEGER, }, { schema: 'account' }); Product.belongsToMany(Tag, { through: ProductTag }); Tag.belongsToMany(Product, { through: ProductTag }); await this.sequelize.sync({ force: true }); await Promise.all([ Product.bulkCreate([ { title: 'Chair' }, { title: 'Desk' }, { title: 'Dress' }, ]), Tag.bulkCreate([ { name: 'A' }, { name: 'B' }, { name: 'C' }, ]), ]); const [products0, tags] = await Promise.all([ Product.findAll(), Tag.findAll(), ]); await Promise.all([ products0[0].addTag(tags[0], { through: { priority: 1 } }), products0[0].addTag(tags[1], { through: { priority: 2 } }), products0[1].addTag(tags[1], { through: { priority: 1 } }), products0[2].addTag(tags[0], { through: { priority: 3 } }), products0[2].addTag(tags[1], { through: { priority: 1 } }), products0[2].addTag(tags[2], { through: { priority: 2 } }), ]); const products = await Product.findAll({ include: [ { model: Tag }, ], order: [ ['id', 'ASC'], [Tag, 'id', 'ASC'], ], }); expect(products[0].Tags[0].ProductTag.priority).to.equal(1); expect(products[0].Tags[1].ProductTag.priority).to.equal(2); expect(products[1].Tags[0].ProductTag.priority).to.equal(1); expect(products[2].Tags[0].ProductTag.priority).to.equal(3); expect(products[2].Tags[1].ProductTag.priority).to.equal(1); expect(products[2].Tags[2].ProductTag.priority).to.equal(2); }); it('should support a required belongsTo include', async function () { const User = this.sequelize.define('User', {}, { schema: 'account' }); const Group = this.sequelize.define('Group', {}, { schema: 'account' }); User.belongsTo(Group); await this.sequelize.sync({ force: true }); await Promise.all([ Group.bulkCreate([{}, {}]), User.bulkCreate([{}, {}, {}]), ]); const [groups, users0] = await Promise.all([ Group.findAll(), User.findAll(), ]); await users0[2].setGroup(groups[1]); const users = await User.findAll({ include: [ { model: Group, required: true }, ], }); expect(users.length).to.equal(1); expect(users[0].Group).to.be.ok; }); it('should be possible to extend the on clause with a where option on a belongsTo include', async function () { const User = this.sequelize.define('User', {}, { schema: 'account' }); const Group = this.sequelize.define('Group', { name: DataTypes.STRING, }, { schema: 'account' }); User.belongsTo(Group); await this.sequelize.sync({ force: true }); await Promise.all([ Group.bulkCreate([ { name: 'A' }, { name: 'B' }, ]), User.bulkCreate([{}, {}]), ]); const [groups, users0] = await Promise.all([ Group.findAll(), User.findAll(), ]); await Promise.all([ users0[0].setGroup(groups[1]), users0[1].setGroup(groups[0]), ]); const users = await User.findAll({ include: [ { model: Group, where: { name: 'A' } }, ], }); expect(users.length).to.equal(1); expect(users[0].Group).to.be.ok; expect(users[0].Group.name).to.equal('A'); }); it('should be possible to extend the on clause with a where option on a belongsTo include', async function () { const User = this.sequelize.define('User', {}, { schema: 'account' }); const Group = this.sequelize.define('Group', { name: DataTypes.STRING, }, { schema: 'account' }); User.belongsTo(Group); await this.sequelize.sync({ force: true }); await Promise.all([ Group.bulkCreate([ { name: 'A' }, { name: 'B' }, ]), User.bulkCreate([{}, {}]), ]); const [groups, users0] = await Promise.all([ Group.findAll(), User.findAll(), ]); await Promise.all([ users0[0].setGroup(groups[1]), users0[1].setGroup(groups[0]), ]); const users = await User.findAll({ include: [ { model: Group, required: true }, ], }); for (const user of users) { expect(user.Group).to.be.ok; } }); it('should be possible to define a belongsTo include as required with child hasMany with limit', async function () { const User = this.sequelize.define('User', {}, { schema: 'account' }); const Group = this.sequelize.define('Group', { name: DataTypes.STRING, }, { schema: 'account' }); const Category = this.sequelize.define('Category', { category: DataTypes.STRING, }, { schema: 'account' }); User.belongsTo(Group); Group.hasMany(Category); await this.sequelize.sync({ force: true }); await Promise.all([ Group.bulkCreate([ { name: 'A' }, { name: 'B' }, ]), User.bulkCreate([{}, {}]), Category.bulkCreate([{}, {}]), ]); const [groups, users0, categories] = await Promise.all([ Group.findAll(), User.findAll(), Category.findAll(), ]); const promises = [ users0[0].setGroup(groups[1]), users0[1].setGroup(groups[0]), ]; for (const group of groups) { promises.push(group.setCategories(categories)); } await Promise.all(promises); const users = await User.findAll({ include: [ { model: Group, required: true, include: [ { model: Category }, ], }, ], limit: 1, }); expect(users.length).to.equal(1); for (const user of users) { expect(user.Group).to.be.ok; expect(user.Group.Categories).to.be.ok; } }); it('should be possible to define a belongsTo include as required with child hasMany with limit and aliases', async function () { const User = this.sequelize.define('User', {}, { schema: 'account' }); const Group = this.sequelize.define('Group', { name: DataTypes.STRING, }, { schema: 'account' }); const Category = this.sequelize.define('Category', { category: DataTypes.STRING, }, { schema: 'account' }); User.belongsTo(Group, { as: 'Team' }); Group.hasMany(Category, { as: 'Tags' }); await this.sequelize.sync({ force: true }); await Promise.all([ Group.bulkCreate([ { name: 'A' }, { name: 'B' }, ]), User.bulkCreate([{}, {}]), Category.bulkCreate([{}, {}]), ]); const [groups, users0, categories] = await Promise.all([ Group.findAll(), User.findAll(), Category.findAll(), ]); const promises = [ users0[0].setTeam(groups[1]), users0[1].setTeam(groups[0]), ]; for (const group of groups) { promises.push(group.setTags(categories)); } await Promise.all(promises); const users = await User.findAll({ include: [ { model: Group, required: true, as: 'Team', include: [ { model: Category, as: 'Tags' }, ], }, ], limit: 1, }); expect(users.length).to.equal(1); for (const user of users) { expect(user.Team).to.be.ok; expect(user.Team.Tags).to.be.ok; } }); it('should be possible to define a belongsTo include as required with child hasMany which is not required with limit', async function () { const User = this.sequelize.define('User', {}, { schema: 'account' }); const Group = this.sequelize.define('Group', { name: DataTypes.STRING, }, { schema: 'account' }); const Category = this.sequelize.define('Category', { category: DataTypes.STRING, }, { schema: 'account' }); User.belongsTo(Group); Group.hasMany(Category); await this.sequelize.sync({ force: true }); await Promise.all([ Group.bulkCreate([ { name: 'A' }, { name: 'B' }, ]), User.bulkCreate([{}, {}]), Category.bulkCreate([{}, {}]), ]); const [groups, users0, categories] = await Promise.all([ Group.findAll(), User.findAll(), Category.findAll(), ]); const promises = [ users0[0].setGroup(groups[1]), users0[1].setGroup(groups[0]), ]; for (const group of groups) { promises.push(group.setCategories(categories)); } await Promise.all(promises); const users = await User.findAll({ include: [ { model: Group, required: true, include: [ { model: Category, required: false }, ], }, ], limit: 1, }); expect(users.length).to.equal(1); for (const user of users) { expect(user.Group).to.be.ok; expect(user.Group.Categories).to.be.ok; } }); it('should be possible to extend the on clause with a where option on a hasOne include', async function () { const User = this.sequelize.define('User', {}, { schema: 'account' }); const Project = this.sequelize.define('Project', { title: DataTypes.STRING, }, { schema: 'account' }); User.hasOne(Project, { as: 'LeaderOf' }); await this.sequelize.sync({ force: true }); await Promise.all([ Project.bulkCreate([ { title: 'Alpha' }, { title: 'Beta' }, ]), User.bulkCreate([{}, {}]), ]); const [projects, users0] = await Promise.all([ Project.findAll(), User.findAll(), ]); await Promise.all([ users0[1].setLeaderOf(projects[1]), users0[0].setLeaderOf(projects[0]), ]); const users = await User.findAll({ include: [ { model: Project, as: 'LeaderOf', where: { title: 'Beta' } }, ], }); expect(users.length).to.equal(1); expect(users[0].LeaderOf).to.be.ok; expect(users[0].LeaderOf.title).to.equal('Beta'); }); it('should be possible to extend the on clause with a where option on a hasMany include with a through model', async function () { const Product = this.sequelize.define('Product', { title: DataTypes.STRING, }, { schema: 'account' }); const Tag = this.sequelize.define('Tag', { name: DataTypes.STRING, }, { schema: 'account' }); const ProductTag = this.sequelize.define('ProductTag', { priority: DataTypes.INTEGER, }, { schema: 'account' }); Product.belongsToMany(Tag, { through: ProductTag }); Tag.belongsToMany(Product, { through: ProductTag }); await this.sequelize.sync({ force: true }); await Promise.all([ Product.bulkCreate([ { title: 'Chair' }, { title: 'Desk' }, { title: 'Dress' }, ]), Tag.bulkCreate([ { name: 'A' }, { name: 'B' }, { name: 'C' }, ]), ]); const [products0, tags] = await Promise.all([ Product.findAll(), Tag.findAll(), ]); await Promise.all([ products0[0].addTag(tags[0], { priority: 1 }), products0[0].addTag(tags[1], { priority: 2 }), products0[1].addTag(tags[1], { priority: 1 }), products0[2].addTag(tags[0], { priority: 3 }), products0[2].addTag(tags[1], { priority: 1 }), products0[2].addTag(tags[2], { priority: 2 }), ]); const products = await Product.findAll({ include: [ { model: Tag, where: { name: 'C' } }, ], }); expect(products.length).to.equal(1); expect(products[0].Tags.length).to.equal(1); }); it('should be possible to extend the on clause with a where option on nested includes', async function () { const User = this.sequelize.define('User', { name: DataTypes.STRING, }, { schema: 'account' }); const Product = this.sequelize.define('Product', { title: DataTypes.STRING, }, { schema: 'account' }); const Tag = this.sequelize.define('Tag', { name: DataTypes.STRING, }, { schema: 'account' }); const Price = this.sequelize.define('Price', { value: DataTypes.FLOAT, }, { schema: 'account' }); const Group = this.sequelize.define('Group', { name: DataTypes.STRING, }, { schema: 'account' }); const GroupMember = this.sequelize.define('GroupMember', {}, { schema: 'account' }); const Rank = this.sequelize.define('Rank', { name: DataTypes.STRING, canInvite: { type: DataTypes.INTEGER, defaultValue: 0, }, canRemove: { type: DataTypes.INTEGER, defaultValue: 0, }, }, { schema: 'account' }); User.hasMany(Product); Product.belongsTo(User); Product.belongsToMany(Tag, { through: 'product_tag' }); Tag.belongsToMany(Product, { through: 'product_tag' }); Product.belongsTo(Tag, { as: 'Category' }); Product.hasMany(Price); Price.belongsTo(Product); User.hasMany(GroupMember, { as: 'Memberships' }); GroupMember.belongsTo(User); GroupMember.belongsTo(Rank); GroupMember.belongsTo(Group); Group.hasMany(GroupMember, { as: 'Memberships' }); await this.sequelize.sync({ force: true }); const [groups, ranks, tags] = await Promise.all([ Group.bulkCreate([ { name: 'Developers' }, { name: 'Designers' }, ]).then(() => Group.findAll()), Rank.bulkCreate([ { name: 'Admin', canInvite: 1, canRemove: 1 }, { name: 'Member', canInvite: 1, canRemove: 0 }, ]).then(() => Rank.findAll()), Tag.bulkCreate([ { name: 'A' }, { name: 'B' }, { name: 'C' }, ]).then(() => Tag.findAll()), ]); for (const i of [0, 1, 2, 3, 4]) { const [user, products] = await Promise.all([ User.create({ name: 'FooBarzz' }), Product.bulkCreate([ { title: 'Chair' }, { title: 'Desk' }, ]).then(() => Product.findAll()), ]); await Promise.all([ GroupMember.bulkCreate([ { UserId: user.id, GroupId: groups[0].id, RankId: ranks[0].id }, { UserId: user.id, GroupId: groups[1].id, RankId: ranks[1].id }, ]), user.setProducts([ products[i * 2 + 0], products[i * 2 + 1], ]), products[i * 2 + 0].setTags([ tags[0], tags[2], ]), products[i * 2 + 1].setTags([ tags[1], ]), products[i * 2 + 0].setCategory(tags[1]), Price.bulkCreate([ { ProductId: products[i * 2 + 0].id, value: 5 }, { ProductId: products[i * 2 + 0].id, value: 10 }, { ProductId: products[i * 2 + 1].id, value: 5 }, { ProductId: products[i * 2 + 1].id, value: 10 }, { ProductId: products[i * 2 + 1].id, value: 15 }, { ProductId: products[i * 2 + 1].id, value: 20 }, ]), ]); const users = await User.findAll({ include: [ { model: GroupMember, as: 'Memberships', include: [ Group, { model: Rank, where: { name: 'Admin' } }, ], }, { model: Product, include: [ Tag, { model: Tag, as: 'Category' }, { model: Price, where: { value: { [Op.gt]: 15, }, }, }, ], }, ], order: [ ['id', 'ASC'], ], }); for (const user of users) { expect(user.Memberships.length).to.equal(1); expect(user.Memberships[0].Rank.name).to.equal('Admin'); expect(user.Products.length).to.equal(1); expect(user.Products[0].Prices.length).to.equal(1); } } }); it('should be possible to use limit and a where with a belongsTo include', async function () { const User = this.sequelize.define('User', {}, { schema: 'account' }); const Group = this.sequelize.define('Group', { name: DataTypes.STRING, }, { schema: 'account' }); User.belongsTo(Group); await this.sequelize.sync({ force: true }); const results = await promiseProps({ groups: Group.bulkCreate([ { name: 'A' }, { name: 'B' }, ]).then(() => { return Group.findAll(); }), users: User.bulkCreate([{}, {}, {}, {}]).then(() => { return User.findAll(); }), }); await Promise.all([ results.users[1].setGroup(results.groups[0]), results.users[2].setGroup(results.groups[0]), results.users[3].setGroup(results.groups[1]), results.users[0].setGroup(results.groups[0]), ]); const users = await User.findAll({ include: [ { model: Group, where: { name: 'A' } }, ], limit: 2, }); expect(users.length).to.equal(2); for (const user of users) { expect(user.Group.name).to.equal('A'); } }); it('should be possible use limit, attributes and a where on a belongsTo with additional hasMany includes', async function () { await this.fixtureA(); const products = await this.models.Product.findAll({ attributes: ['title'], include: [ { model: this.models.Company, where: { name: 'NYSE' } }, { model: this.models.Tag }, { model: this.models.Price }, ], limit: 3, order: [ ['id', 'ASC'], ], }); expect(products.length).to.equal(3); for (const product of products) { expect(product.Company.name).to.equal('NYSE'); expect(product.Tags.length).to.be.ok; expect(product.Prices.length).to.be.ok; } }); it('should be possible to use limit and a where on a hasMany with additional includes', async function () { await this.fixtureA(); const products = await this.models.Product.findAll({ include: [ { model: this.models.Company }, { model: this.models.Tag }, { model: this.models.Price, where: { value: { [Op.gt]: 5 }, }, }, ], limit: 6, order: [ ['id', 'ASC'], ], }); expect(products.length).to.equal(6); for (const product of products) { expect(product.Tags.length).to.be.ok; expect(product.Prices.length).to.be.ok; for (const price of product.Prices) { expect(price.value).to.be.above(5); } } }); it('should be possible to use limit and a where on a hasMany with a through model with additional includes', async function () { await this.fixtureA(); const products = await this.models.Product.findAll({ include: [ { model: this.models.Company }, { model: this.models.Tag, where: { name: ['A', 'B', 'C'] } }, { model: this.models.Price }, ], limit: 10, order: [ ['id', 'ASC'], ], }); expect(products.length).to.equal(10); for (const product of products) { expect(product.Tags.length).to.be.ok; expect(product.Prices.length).to.be.ok; for (const tag of product.Tags) { expect(['A', 'B', 'C']).to.include(tag.name); } } }); it('should support including date fields, with the correct timezone', async function () { const User = this.sequelize.define('user', { dateField: Sequelize.DATE, }, { timestamps: false, schema: 'account' }); const Group = this.sequelize.define('group', { dateField: Sequelize.DATE, }, { timestamps: false, schema: 'account' }); User.belongsToMany(Group, { through: 'group_user' }); Group.belongsToMany(User, { through: 'group_user' }); await this.sequelize.sync(); const user = await User.create({ dateField: Date.UTC(2014, 1, 20) }); const group = await Group.create({ dateField: Date.UTC(2014, 1, 20) }); await user.addGroup(group); const users = await User.findAll({ where: { id: user.id, }, include: [Group], }); if (dialect === 'sqlite') { expect(new Date(users[0].dateField).getTime()).to.equal(Date.UTC(2014, 1, 20)); expect(new Date(users[0].groups[0].dateField).getTime()).to.equal(Date.UTC(2014, 1, 20)); } else { expect(users[0].dateField.getTime()).to.equal(Date.UTC(2014, 1, 20)); expect(users[0].groups[0].dateField.getTime()).to.equal(Date.UTC(2014, 1, 20)); } }); }); describe('findOne', () => { it('should work with schemas', async function () { const UserModel = this.sequelize.define('User', { Id: { type: DataTypes.INTEGER, primaryKey: true, }, Name: DataTypes.STRING, UserType: DataTypes.INTEGER, Email: DataTypes.STRING, PasswordHash: DataTypes.STRING, Enabled: { type: DataTypes.BOOLEAN, }, CreatedDatetime: DataTypes.DATE, UpdatedDatetime: DataTypes.DATE, }, { schema: 'hero', tableName: 'User', timestamps: false, }); const UserIdColumn = { type: Sequelize.INTEGER, references: { model: UserModel, key: 'Id' } }; const ResumeModel = this.sequelize.define('Resume', { Id: { type: Sequelize.INTEGER, primaryKey: true, }, UserId: UserIdColumn, Name: Sequelize.STRING, Contact: Sequelize.STRING, School: Sequelize.STRING, WorkingAge: Sequelize.STRING, Description: Sequelize.STRING, PostType: Sequelize.INTEGER, RefreshDatetime: Sequelize.DATE, CreatedDatetime: Sequelize.DATE, }, { schema: 'hero', tableName: 'resume', timestamps: false, }); UserModel.hasOne(ResumeModel, { foreignKey: 'UserId', as: 'Resume', }); ResumeModel.belongsTo(UserModel, { foreignKey: 'UserId', }); await this.sequelize.dropSchema('hero'); await this.sequelize.createSchema('hero'); await this.sequelize.sync({ force: true }); await UserModel.findOne({ where: { Id: 1, }, include: [{ model: ResumeModel, as: 'Resume', }], }); await this.sequelize.dropSchema('hero'); }); }); });
// Generated by CoffeeScript 1.10.0 var EsyFile; EsyFile = (function() { function EsyFile() {} EsyFile.prototype["delete"] = function(filepath) { var file; if (File(filepath)) { file = File(filepath); } return file.remove(); }; EsyFile.prototype.append = function(filepath, content) { var file; file = File(filepath); file.open("a"); file.write(content); file.close(); return file; }; EsyFile.prototype.buildExtendScript = function(filepath, destinations) { var content, destination, i, len, read, results; content = this.read(filepath); content = content.replace("debug = true", "debug = false"); read = (function(_this) { return function(str, p1) { return _this.read((_this.path(filepath)) + "/" + p1); }; })(this); content = content.replace(/#include \"(.*)\";/g, read); if (typeof destinations === "string") { destinations = [destinations]; } results = []; for (i = 0, len = destinations.length; i < len; i++) { destination = destinations[i]; results.push(this.create("" + (destination.toString()), content)); } return results; }; EsyFile.prototype.create = function(filepath, content, overwrite) { var file; if (content == null) { content = ""; } if (overwrite == null) { overwrite = true; } if (overwrite) { this["delete"](filepath); } file = File(filepath); file.open("w"); file.write(content); file.close(); return file; }; EsyFile.prototype.exists = function(filepath) { var file; file = File(filepath); if (file.created) { return file; } else { return false; } }; EsyFile.prototype.read = function(filepath) { var content, file; file = File(filepath); file.open("r"); content = file.read(); file.close(); return content; }; EsyFile.prototype.folderName = function(filepath) { var folderName; folderName = this.filename(filepath); return folderName; }; EsyFile.prototype.fileName = function(filepath) { var filename; filename = filepath.substr(filepath.lastIndexOf('/') + 1); return filename; }; EsyFile.prototype.path = function(filepath) { var filename; filename = filepath.substr(0, filepath.lastIndexOf('/')); return filename; }; return EsyFile; })();
'use strict'; module.exports = { '+': 'Pass', '-': 'Fail', '~': 'SoftFail', '?': 'Neutral' };
import config from './config/env'; import Promise from 'bluebird'; import logger from './config/logger'; // import csv from 'fast-csv'; import fs from 'fs'; import request from 'request'; // import rp from 'request-promise'; import cheerio from 'cheerio'; import _ from 'lodash'; import moment from 'moment'; function downloadStockProfile(stockId, season) { const uri = config.sinaLink.replace('{stockId}', stockId); logger.info(`downloading ${uri}, ( ${season.year}, ${season.season})`); const options = { uri, method: 'POST', headers: config.browser.headers, form: season, json: true, }; return new Promise((resolve) => { request(options).on('response', (res) => { if (res.statusCode !== 200) { resolve(res.statusCode); } else { resolve('done'); } }).on('error', (e) => { logger.error(JSON.stringify(e)); resolve('skip'); }) .pipe(fs.createWriteStream(`./sample/${stockId}_${season.year}_${season.season}.html`)) .on('finish', () => { resolve('done'); }); }); } function isStockProfileGood(stockId, marketCapMin) { const uri = config.tickerLink.replace('{stockId}', stockId); logger.info(`getting ${uri}`); const options = { uri, method: 'GET', headers: config.browser.headers, json: true, }; return new Promise((resolve) => { request(options, (error, response, body) => { if (error) { // in case ticker block my programe, any error will give as true response resolve(true); } if (response && response.statusCode !== 200) { // in case ticker block my programe, any error will give as true response resolve(true); } else if (body && body[0]) { const { lastTradePrice, lastClosePrice, MktCap } = body[0]; const isHighMarkCap = parseFloat(MktCap) >= marketCapMin; const changePer = (parseFloat(lastTradePrice) - parseFloat(lastClosePrice)) / parseFloat(lastClosePrice); const isChangePerGood = changePer < config.marketChangePerMin[0] && changePer >= config.marketChangePerMin[1]; logger.info(`changePer, isChangePerGood : ${changePer} , ${isChangePerGood}`); resolve(isHighMarkCap && isChangePerGood); } else { resolve(true); } }); }); } function getLastTradeDay() { const uri = config.tickerLink.replace('{stockId}', '5'); logger.info(`getting ${uri}`); const options = { uri, method: 'GET', headers: config.browser.headers, json: true, }; return new Promise((resolve) => { const today = moment().format('YYYYMMDD'); request(options, (error, response, body) => { if (error) { // in case ticker block my programe, any error will try today resolve(today); } if (response && response.statusCode !== 200) { // in case ticker block my programe, any error will try today resolve(today); } else if (body) { const { lastTradeDateUTC } = body[0]; resolve(moment(lastTradeDateUTC).format('YYYYMMDD')); } else { resolve(today); } }); }); } function getDayTradeInfo(tradeDay, stockId, type) { const uri = config.aastockTradeLink.replace('{stockId}', stockId).replace('{date}', tradeDay).replace('{type}', type); logger.info(`getDayTradeInfo: ${uri}`); const options = { uri, method: 'GET', headers: config.browser.headers, json: true, }; return new Promise((resolve) => { request(options, (error, response, body) => { if (error) { resolve(null); } if (response && response.statusCode !== 200) { resolve(null); } else { // const pct = body && body.stat ? parseFloat(body.stat.pctRaw) : 0; resolve(body || null); } }); }); } async function isTradeInfoAbnormal(tradeDay, stockId, factor) { try { const ultraBuy = await getDayTradeInfo(tradeDay, stockId, config.aastockTradeType.buy[0]); const ultraSell = await getDayTradeInfo(tradeDay, stockId, config.aastockTradeType.sell[0]); const buyTurnOvers = _.map(ultraBuy.tslog, (n) => (_.parseInt(n.turnover.replace(/,/g, '')))); const sellTurnOvers = _.map(ultraSell.tslog, (n) => (_.parseInt(n.turnover.replace(/,/g, '')))); const topBuyTurnOver = _.max(buyTurnOvers) || 0; const topSellTurnOver = _.max(sellTurnOvers) || 0; logger.info(`topBuyTurnOver: ${topBuyTurnOver}, topSellTurnOver: ${topSellTurnOver}`); return topBuyTurnOver > topSellTurnOver * factor; } catch (ex) { logger.error('error', ex); return false; } } // async function isDownTrend(tradeDay, stockId) { // try { // logger.info('isDownTrend : %s, %s', tradeDay, stockId); // const buyResult = await Promise.reduce( // config.aastockTradeType.buy, // async (r, type) => { // const dayTradeInfo = await getDayTradeInfo(tradeDay, stockId, type); // const pctRaw = dayTradeInfo ? dayTradeInfo.stat.pctRaw : 0; // return r + pctRaw; // }, // 0, // ); // const sellResult = await Promise.reduce( // config.aastockTradeType.sell, // async (r, type) => { // const dayTradeInfo = await getDayTradeInfo(tradeDay, stockId, type); // const pctRaw = dayTradeInfo ? dayTradeInfo.stat.pctRaw : 0; // return r + pctRaw; // }, // 0, // ); // logger.info(`buyResult: ${buyResult}, sellResult: ${sellResult}`); // const isSellMore = sellResult >= buyResult; // return isSellMore || !isTradeInfoAbnormal(tradeDay, stockId, 1); // } catch (ex) { // logger.error('error', ex); // return false; // } // } async function isDayTradeInfoGood(tradeDay, stockId) { try { logger.info('isDayTradeInfoGood : %s, %s', tradeDay, stockId); const buyResult = await Promise.reduce( config.aastockTradeType.buy, async (r, type) => { const dayTradeInfo = await getDayTradeInfo(tradeDay, stockId, type); const pctRaw = dayTradeInfo ? dayTradeInfo.stat.pctRaw : 0; return r + pctRaw; }, 0, ); const sellResult = await Promise.reduce( config.aastockTradeType.sell, async (r, type) => { const dayTradeInfo = await getDayTradeInfo(tradeDay, stockId, type); const pctRaw = dayTradeInfo ? dayTradeInfo.stat.pctRaw : 0; return r + pctRaw; }, 0, ); logger.info(`buyResult: ${buyResult}, sellResult: ${sellResult}`); const isBuyMore = buyResult >= sellResult; return isBuyMore; } catch (ex) { logger.error('error', ex); return false; } } function readSingleStock(stockId, season) { return new Promise((resolve) => { const cbHtml = fs.readFileSync(`./sample/${stockId}_${season.year}_${season.season}.html`).toString(); const $ = cheerio.load(cbHtml); let result = $('.tab05 > tbody > tr').map((i, element) => ({ date: $(element).find('td:nth-of-type(1)').text() .trim(), volume: $(element).find('td:nth-of-type(5)').text() .trim(), open: $(element).find('td:nth-of-type(7)').text() .trim(), close: $(element).find('td:nth-of-type(2)').text() .trim(), })).get(); result = result.splice(1); resolve(result); }); } async function getFromDataFile(stockId) { return new Promise((resolve) => { try { const data = fs.readFileSync(`./data/${stockId}.dat`).toString(); const [maxVolume, avgVolume] = data.split(','); resolve({ maxVolume: parseFloat(maxVolume), avgVolume: parseFloat(avgVolume) }); } catch (ex) { resolve(null); } }); } async function getRealTime(stockId) { const uri = config.realTimeLink.replace('{stockId}', stockId); logger.info(`getting ${uri}`); const options = { uri, method: 'GET', headers: config.browser.headers, json: true, }; return new Promise((resolve) => { request(options, (error, response, body) => { if (error) { // in case ticker block my programe, any error will try today resolve(0); } if (response && response.statusCode !== 200) { // in case ticker block my programe, any error will try today resolve(0); } else if (body) { const realTimeVolume = body.split(',')[12]; resolve(parseFloat(realTimeVolume)); } else { resolve(0); } }); }); } // async function writeStockData(stockId, maxVolume, avgVolume) { // return new Promise((resolve) => { // fs.writeFile(`./data/${stockId}.dat`, `${maxVolume},${avgVolume}`, (err) => { // if (err) { // logger.info('unable to write file: %s', JSON.stringify(err)); // } // resolve(); // }); // }); // } async function readStock(stockId, factor) { try { const result = await Promise.reduce( config.stockSeasons, async (r, season) => ([...r, ...await readSingleStock(stockId, season)]), [], ); // check if get highest volume const todayVolume = _.parseInt(result[0].volume); logger.info('stockId : %s', stockId); logger.info('today volume : %s', todayVolume); let cb = false; if (todayVolume !== 0) { const intStocks = _.map(result, (n) => _.parseInt(n.volume)); const maxVolume = _.max(intStocks); const sortedStocks = intStocks.sort((a, b) => (b - a)); logger.info('sortedStocks : %s', JSON.stringify(sortedStocks)); const no3Volume = sortedStocks.length >= 3 ? sortedStocks.slice(2, 3) : sortedStocks[sortedStocks.length - 1]; logger.info('no3Volume : %s', no3Volume); const isTop3Volume = (todayVolume >= no3Volume && no3Volume !== 0); logger.info('max volume : %s', maxVolume); const isHighestVolume = (todayVolume === maxVolume && todayVolume !== 0); const volumesExcludeToday = intStocks.slice(1); const avgVolume = _.mean(volumesExcludeToday); logger.info('avgVolume : %s', avgVolume); const isGoodAvgVolume = todayVolume >= factor * avgVolume; logger.info(`todayVolume : ${todayVolume}`); logger.info(`factor * avgVolume : ${factor * avgVolume}`); logger.info(`isGoodAvgVolume : ${isGoodAvgVolume}`); // await writeStockData(stockId, maxVolume, avgVolume); // const isNotDrop = parseFloat(result[0].close) >= parseFloat(result[0].open); cb = isHighestVolume || isGoodAvgVolume || isTop3Volume ? { stockId, maxVolume, isHighestVolume, todayVolume, avgVolume, isGoodAvgVolume, isTop3Volume } : false; } return cb; } catch (ex) { logger.error('error', ex); return false; } } export default { downloadStockProfile, isStockProfileGood, readStock, getLastTradeDay, isTradeInfoAbnormal, isDayTradeInfoGood, getRealTime, getFromDataFile, };
window.theme = window.theme || {}; /* ================ SLATE ================ */ window.theme = window.theme || {}; theme.Sections = function Sections() { this.constructors = {}; this.instances = []; $(document) .on('shopify:section:load', this._onSectionLoad.bind(this)) .on('shopify:section:unload', this._onSectionUnload.bind(this)) .on('shopify:section:select', this._onSelect.bind(this)) .on('shopify:section:deselect', this._onDeselect.bind(this)) .on('shopify:block:select', this._onBlockSelect.bind(this)) .on('shopify:block:deselect', this._onBlockDeselect.bind(this)); }; theme.Sections.prototype = _.assignIn({}, theme.Sections.prototype, { _createInstance: function(container, constructor) { var $container = $(container); var id = $container.attr('data-section-id'); var type = $container.attr('data-section-type'); constructor = constructor || this.constructors[type]; if (_.isUndefined(constructor)) { return; } var instance = _.assignIn(new constructor(container), { id: id, type: type, container: container }); this.instances.push(instance); }, _onSectionLoad: function(evt) { var container = $('[data-section-id]', evt.target)[0]; if (container) { this._createInstance(container); } }, _onSectionUnload: function(evt) { this.instances = _.filter(this.instances, function(instance) { var isEventInstance = (instance.id === evt.detail.sectionId); if (isEventInstance) { if (_.isFunction(instance.onUnload)) { instance.onUnload(evt); } } return !isEventInstance; }); }, _onSelect: function(evt) { // eslint-disable-next-line no-shadow var instance = _.find(this.instances, function(instance) { return instance.id === evt.detail.sectionId; }); if (!_.isUndefined(instance) && _.isFunction(instance.onSelect)) { instance.onSelect(evt); } }, _onDeselect: function(evt) { // eslint-disable-next-line no-shadow var instance = _.find(this.instances, function(instance) { return instance.id === evt.detail.sectionId; }); if (!_.isUndefined(instance) && _.isFunction(instance.onDeselect)) { instance.onDeselect(evt); } }, _onBlockSelect: function(evt) { // eslint-disable-next-line no-shadow var instance = _.find(this.instances, function(instance) { return instance.id === evt.detail.sectionId; }); if (!_.isUndefined(instance) && _.isFunction(instance.onBlockSelect)) { instance.onBlockSelect(evt); } }, _onBlockDeselect: function(evt) { // eslint-disable-next-line no-shadow var instance = _.find(this.instances, function(instance) { return instance.id === evt.detail.sectionId; }); if (!_.isUndefined(instance) && _.isFunction(instance.onBlockDeselect)) { instance.onBlockDeselect(evt); } }, register: function(type, constructor) { this.constructors[type] = constructor; $('[data-section-type=' + type + ']').each(function(index, container) { this._createInstance(container, constructor); }.bind(this)); } }); window.slate = window.slate || {}; /** * iFrames * ----------------------------------------------------------------------------- * Wrap videos in div to force responsive layout. * * @namespace iframes */ slate.rte = { /** * Wrap tables in a container div to make them scrollable when needed * * @param {object} options - Options to be used * @param {jquery} options.$tables - jquery object(s) of the table(s) to wrap * @param {string} options.tableWrapperClass - table wrapper class name */ wrapTable: function(options) { options.$tables.wrap('<div class="' + options.tableWrapperClass + '"></div>'); }, /** * Wrap iframes in a container div to make them responsive * * @param {object} options - Options to be used * @param {jquery} options.$iframes - jquery object(s) of the iframe(s) to wrap * @param {string} options.iframeWrapperClass - class name used on the wrapping div */ wrapIframe: function(options) { options.$iframes.each(function() { // Add wrapper to make video responsive $(this).wrap('<div class="' + options.iframeWrapperClass + '"></div>'); // Re-set the src attribute on each iframe after page load // for Chrome's "incorrect iFrame content on 'back'" bug. // https://code.google.com/p/chromium/issues/detail?id=395791 // Need to specifically target video and admin bar this.src = this.src; }); } }; window.slate = window.slate || {}; /** * A11y Helpers * ----------------------------------------------------------------------------- * A collection of useful functions that help make your theme more accessible * to users with visual impairments. * * * @namespace a11y */ slate.a11y = { /** * For use when focus shifts to a container rather than a link * eg for In-page links, after scroll, focus shifts to content area so that * next `tab` is where user expects if focusing a link, just $link.focus(); * * @param {JQuery} $element - The element to be acted upon */ pageLinkFocus: function($element) { var focusClass = 'js-focus-hidden'; $element.first() .attr('tabIndex', '-1') .focus() .addClass(focusClass) .one('blur', callback); function callback() { $element.first() .removeClass(focusClass) .removeAttr('tabindex'); } }, /** * If there's a hash in the url, focus the appropriate element */ focusHash: function() { var hash = window.location.hash; // is there a hash in the url? is it an element on the page? if (hash && document.getElementById(hash.slice(1))) { this.pageLinkFocus($(hash)); } }, /** * When an in-page (url w/hash) link is clicked, focus the appropriate element */ bindInPageLinks: function() { $('a[href*=#]').on('click', function(evt) { this.pageLinkFocus($(evt.currentTarget.hash)); }.bind(this)); }, /** * Traps the focus in a particular container * * @param {object} options - Options to be used * @param {jQuery} options.$container - Container to trap focus within * @param {jQuery} options.$elementToFocus - Element to be focused when focus leaves container * @param {string} options.namespace - Namespace used for new focus event handler */ trapFocus: function(options) { var eventName = options.namespace ? 'focusin.' + options.namespace : 'focusin'; if (!options.$elementToFocus) { options.$elementToFocus = options.$container; } options.$container.attr('tabindex', '-1'); options.$elementToFocus.focus(); $(document).off('focusin'); $(document).on(eventName, function(evt) { if (options.$container[0] !== evt.target && !options.$container.has(evt.target).length) { options.$container.focus(); } }); }, /** * Removes the trap of focus in a particular container * * @param {object} options - Options to be used * @param {jQuery} options.$container - Container to trap focus within * @param {string} options.namespace - Namespace used for new focus event handler */ removeTrapFocus: function(options) { var eventName = options.namespace ? 'focusin.' + options.namespace : 'focusin'; if (options.$container && options.$container.length) { options.$container.removeAttr('tabindex'); } $(document).off(eventName); } }; /** * Image Helper Functions * ----------------------------------------------------------------------------- * A collection of functions that help with basic image operations. * */ theme.Images = (function() { /** * Preloads an image in memory and uses the browsers cache to store it until needed. * * @param {Array} images - A list of image urls * @param {String} size - A shopify image size attribute */ function preload(images, size) { if (typeof images === 'string') { images = [images]; } for (var i = 0; i < images.length; i++) { var image = images[i]; this.loadImage(this.getSizedImageUrl(image, size)); } } /** * Loads and caches an image in the browsers cache. * @param {string} path - An image url */ function loadImage(path) { new Image().src = path; } /** * Swaps the src of an image for another OR returns the imageURL to the callback function * @param image * @param element * @param callback */ function switchImage(image, element, callback) { var size = this.imageSize(element.src); var imageUrl = this.getSizedImageUrl(image.src, size); if (callback) { callback(imageUrl, image, element); // eslint-disable-line callback-return } else { element.src = imageUrl; } } /** * +++ Useful * Find the Shopify image attribute size * * @param {string} src * @returns {null} */ function imageSize(src) { var match = src.match(/.+_((?:pico|icon|thumb|small|compact|medium|large|grande)|\d{1,4}x\d{0,4}|x\d{1,4})(@{1}?\d{1}?x{1}?)*[_\.]/); if (match !== null) { if (match[2] !== undefined) { return match[1] + match[2]; } else { return match[1]; } } else { return null; } } /** * +++ Useful * Adds a Shopify size attribute to a URL * * @param src * @param size * @returns {*} */ function getSizedImageUrl(src, size) { if (size == null) { return src; } if (size === 'master') { return this.removeProtocol(src); } var match = src.match(/\.(jpg|jpeg|gif|png|bmp|bitmap|tiff|tif)(\?v=\d+)?$/i); if (match != null) { var prefix = src.split(match[0]); var suffix = match[0]; return this.removeProtocol(prefix[0] + '_' + size + suffix); } return null; } function removeProtocol(path) { return path.replace(/http(s)?:/, ''); } return { preload: preload, loadImage: loadImage, switchImage: switchImage, imageSize: imageSize, getSizedImageUrl: getSizedImageUrl, removeProtocol: removeProtocol }; })(); /** * Currency Helpers * ----------------------------------------------------------------------------- * A collection of useful functions that help with currency formatting * * Current contents * - formatMoney - Takes an amount in cents and returns it as a formatted dollar value. * * Alternatives * - Accounting.js - http://openexchangerates.github.io/accounting.js/ * */ theme.Currency = (function() { var moneyFormat = '${{amount}}'; // eslint-disable-line camelcase function formatMoney(cents, format) { if (typeof cents === 'string') { cents = cents.replace('.', ''); } var value = ''; var placeholderRegex = /\{\{\s*(\w+)\s*\}\}/; var formatString = (format || moneyFormat); function formatWithDelimiters(number, precision, thousands, decimal) { thousands = thousands || ','; decimal = decimal || '.'; if (isNaN(number) || number == null) { return 0; } number = (number / 100.0).toFixed(precision); var parts = number.split('.'); var dollarsAmount = parts[0].replace(/(\d)(?=(\d\d\d)+(?!\d))/g, '$1' + thousands); var centsAmount = parts[1] ? (decimal + parts[1]) : ''; return dollarsAmount + centsAmount; } switch (formatString.match(placeholderRegex)[1]) { case 'amount': value = formatWithDelimiters(cents, 2); break; case 'amount_no_decimals': value = formatWithDelimiters(cents, 0); break; case 'amount_with_comma_separator': value = formatWithDelimiters(cents, 2, '.', ','); break; case 'amount_no_decimals_with_comma_separator': value = formatWithDelimiters(cents, 0, '.', ','); break; case 'amount_no_decimals_with_space_separator': value = formatWithDelimiters(cents, 0, ' '); break; } return formatString.replace(placeholderRegex, value); } return { formatMoney: formatMoney } })(); /** * Variant Selection scripts * ------------------------------------------------------------------------------ * * Handles change events from the variant inputs in any `cart/add` forms that may * exist. Also updates the master select and triggers updates when the variants * price or image changes. * * @namespace variants */ slate.Variants = (function() { /** * Variant constructor * * @param {object} options - Settings from `product.js` */ function Variants(options) { this.$container = options.$container; this.product = options.product; this.singleOptionSelector = options.singleOptionSelector; this.originalSelectorId = options.originalSelectorId; this.enableHistoryState = options.enableHistoryState; this.currentVariant = this._getVariantFromOptions(); $(this.singleOptionSelector, this.$container).on('change', this._onSelectChange.bind(this)); } Variants.prototype = _.assignIn({}, Variants.prototype, { /** * Get the currently selected options from add-to-cart form. Works with all * form input elements. * * @return {array} options - Values of currently selected variants */ _getCurrentOptions: function() { var currentOptions = _.map($(this.singleOptionSelector, this.$container), function(element) { var $element = $(element); var type = $element.attr('type'); var currentOption = {}; if (type === 'radio' || type === 'checkbox') { if ($element[0].checked) { currentOption.value = $element.val(); currentOption.index = $element.data('index'); return currentOption; } else { return false; } } else { currentOption.value = $element.val(); currentOption.index = $element.data('index'); return currentOption; } }); // remove any unchecked input values if using radio buttons or checkboxes currentOptions = _.compact(currentOptions); return currentOptions; }, /** * Find variant based on selected values. * * @param {array} selectedValues - Values of variant inputs * @return {object || undefined} found - Variant object from product.variants */ _getVariantFromOptions: function() { var selectedValues = this._getCurrentOptions(); var variants = this.product.variants; var found = _.find(variants, function(variant) { return selectedValues.every(function(values) { return _.isEqual(variant[values.index], values.value); }); }); return found; }, /** * Event handler for when a variant input changes. */ _onSelectChange: function() { var variant = this._getVariantFromOptions(); this.$container.trigger({ type: 'variantChange', variant: variant }); if (!variant) { return; } this._updateMasterSelect(variant); this._updateImages(variant); this._updatePrice(variant); this._updateSKU(variant); this.currentVariant = variant; if (this.enableHistoryState) { this._updateHistoryState(variant); } }, /** * Trigger event when variant image changes * * @param {object} variant - Currently selected variant * @return {event} variantImageChange */ _updateImages: function(variant) { var variantImage = variant.featured_image || {}; var currentVariantImage = this.currentVariant.featured_image || {}; if (!variant.featured_image || variantImage.src === currentVariantImage.src) { return; } this.$container.trigger({ type: 'variantImageChange', variant: variant }); }, /** * Trigger event when variant price changes. * * @param {object} variant - Currently selected variant * @return {event} variantPriceChange */ _updatePrice: function(variant) { if (variant.price === this.currentVariant.price && variant.compare_at_price === this.currentVariant.compare_at_price) { return; } this.$container.trigger({ type: 'variantPriceChange', variant: variant }); }, /** * Trigger event when variant sku changes. * * @param {object} variant - Currently selected variant * @return {event} variantSKUChange */ _updateSKU: function(variant) { if (variant.sku === this.currentVariant.sku) { return; } this.$container.trigger({ type: 'variantSKUChange', variant: variant }); }, /** * Update history state for product deeplinking * * @param {variant} variant - Currently selected variant * @return {k} [description] */ _updateHistoryState: function(variant) { if (!history.replaceState || !variant) { return; } var newurl = window.location.protocol + '//' + window.location.host + window.location.pathname + '?variant=' + variant.id; window.history.replaceState({path: newurl}, '', newurl); }, /** * Update hidden master select of variant change * * @param {variant} variant - Currently selected variant */ _updateMasterSelect: function(variant) { $(this.originalSelectorId, this.$container).val(variant.id); } }); return Variants; })(); /* ================ GLOBAL ================ */ /*============================================================================ Drawer modules ==============================================================================*/ theme.Drawers = (function() { function Drawer(id, position, options) { var defaults = { close: '.js-drawer-close', open: '.js-drawer-open-' + position, openClass: 'js-drawer-open', dirOpenClass: 'js-drawer-open-' + position }; this.nodes = { $parent: $('html').add('body'), $page: $('#PageContainer') }; this.config = $.extend(defaults, options); this.position = position; this.$drawer = $('#' + id); if (!this.$drawer.length) { return false; } this.drawerIsOpen = false; this.init(); } Drawer.prototype.init = function() { $(this.config.open).on('click', $.proxy(this.open, this)); this.$drawer.on('click', this.config.close, $.proxy(this.close, this)); }; Drawer.prototype.open = function(evt) { // Keep track if drawer was opened from a click, or called by another function var externalCall = false; // Prevent following href if link is clicked if (evt) { evt.preventDefault(); } else { externalCall = true; } // Without this, the drawer opens, the click event bubbles up to nodes.$page // which closes the drawer. if (evt && evt.stopPropagation) { evt.stopPropagation(); // save the source of the click, we'll focus to this on close this.$activeSource = $(evt.currentTarget); } if (this.drawerIsOpen && !externalCall) { return this.close(); } // Add is-transitioning class to moved elements on open so drawer can have // transition for close animation this.$drawer.prepareTransition(); this.nodes.$parent.addClass(this.config.openClass + ' ' + this.config.dirOpenClass); this.drawerIsOpen = true; // Set focus on drawer slate.a11y.trapFocus({ $container: this.$drawer, namespace: 'drawer_focus' }); // Run function when draw opens if set if (this.config.onDrawerOpen && typeof this.config.onDrawerOpen === 'function') { if (!externalCall) { this.config.onDrawerOpen(); } } if (this.$activeSource && this.$activeSource.attr('aria-expanded')) { this.$activeSource.attr('aria-expanded', 'true'); } this.bindEvents(); return this; }; Drawer.prototype.close = function() { if (!this.drawerIsOpen) { // don't close a closed drawer return; } // deselect any focused form elements $(document.activeElement).trigger('blur'); // Ensure closing transition is applied to moved elements, like the nav this.$drawer.prepareTransition(); this.nodes.$parent.removeClass(this.config.dirOpenClass + ' ' + this.config.openClass); this.drawerIsOpen = false; // Remove focus on drawer slate.a11y.removeTrapFocus({ $container: this.$drawer, namespace: 'drawer_focus' }); this.unbindEvents(); }; Drawer.prototype.bindEvents = function() { this.nodes.$parent.on('keyup.drawer', $.proxy(function(evt) { // close on 'esc' keypress if (evt.keyCode === 27) { this.close(); return false; } else { return true; } }, this)); // Lock scrolling on mobile this.nodes.$page.on('touchmove.drawer', function() { return false; }); this.nodes.$page.on('click.drawer', $.proxy(function() { this.close(); return false; }, this)); }; Drawer.prototype.unbindEvents = function() { this.nodes.$page.off('.drawer'); this.nodes.$parent.off('.drawer'); }; return Drawer; })(); /* ================ MODULES ================ */ window.theme = window.theme || {}; theme.Header = (function() { var selectors = { body: 'body', navigation: '#AccessibleNav', siteNavHasDropdown: '.site-nav--has-dropdown', siteNavChildLinks: '.site-nav__child-link', siteNavActiveDropdown: '.site-nav--active-dropdown', siteNavLinkMain: '.site-nav__link--main', siteNavChildLink: '.site-nav__link--last' }; var config = { activeClass: 'site-nav--active-dropdown', childLinkClass: 'site-nav__child-link' }; var cache = {}; function init() { cacheSelectors(); cache.$parents.on('click.siteNav', function(evt) { var $el = $(this); if (!$el.hasClass(config.activeClass)) { // force stop the click from happening evt.preventDefault(); evt.stopImmediatePropagation(); } showDropdown($el); }); // check when we're leaving a dropdown and close the active dropdown $(selectors.siteNavChildLink).on('focusout.siteNav', function() { setTimeout(function() { if ($(document.activeElement).hasClass(config.childLinkClass) || !cache.$activeDropdown.length) { return; } hideDropdown(cache.$activeDropdown); }); }); // close dropdowns when on top level nav cache.$topLevel.on('focus.siteNav', function() { if (cache.$activeDropdown.length) { hideDropdown(cache.$activeDropdown); } }); cache.$subMenuLinks.on('click.siteNav', function(evt) { // Prevent click on body from firing instead of link evt.stopImmediatePropagation(); }); } function cacheSelectors() { cache = { $nav: $(selectors.navigation), $topLevel: $(selectors.siteNavLinkMain), $parents: $(selectors.navigation).find(selectors.siteNavHasDropdown), $subMenuLinks: $(selectors.siteNavChildLinks), $activeDropdown: $(selectors.siteNavActiveDropdown) }; } function showDropdown($el) { $el.addClass(config.activeClass); // close open dropdowns if (cache.$activeDropdown.length) { hideDropdown(cache.$activeDropdown); } cache.$activeDropdown = $el; // set expanded on open dropdown $el.find(selectors.siteNavLinkMain).attr('aria-expanded', 'true'); setTimeout(function() { $(window).on('keyup.siteNav', function(evt) { if (evt.keyCode === 27) { hideDropdown($el); } }); $(selectors.body).on('click.siteNav', function() { hideDropdown($el); }); }, 250); } function hideDropdown($el) { // remove aria on open dropdown $el.find(selectors.siteNavLinkMain).attr('aria-expanded', 'false'); $el.removeClass(config.activeClass); // reset active dropdown cache.$activeDropdown = $(selectors.siteNavActiveDropdown); $(selectors.body).off('click.siteNav'); $(window).off('keyup.siteNav'); } function unload() { $(window).off('.siteNav'); cache.$parents.off('.siteNav'); cache.$subMenuLinks.off('.siteNav'); cache.$topLevel.off('.siteNav'); $(selectors.siteNavChildLink).off('.siteNav'); $(selectors.body).off('.siteNav'); } return { init: init, unload: unload }; })(); window.theme = window.theme || {}; theme.MobileNav = (function() { var classes = { mobileNavOpenIcon: 'mobile-nav--open', mobileNavCloseIcon: 'mobile-nav--close', subNavLink: 'mobile-nav__sublist-link', return: 'mobile-nav__return-btn', subNavActive: 'is-active', subNavClosing: 'is-closing', navOpen: 'js-menu--is-open', subNavShowing: 'sub-nav--is-open', thirdNavShowing: 'third-nav--is-open', subNavToggleBtn: 'js-toggle-submenu' }; var cache = {}; var isTransitioning; var $activeSubNav; var $activeTrigger; var menuLevel = 1; // Breakpoints from src/stylesheets/global/variables.scss.liquid var mediaQuerySmall = 'screen and (max-width: 749px)'; function init() { cacheSelectors(); cache.$mobileNavToggle.on('click', toggleMobileNav); cache.$subNavToggleBtn.on('click.subNav', toggleSubNav); // Close mobile nav when unmatching mobile breakpoint enquire.register(mediaQuerySmall, { unmatch: function() { closeMobileNav(); } }); } function toggleMobileNav() { if (cache.$mobileNavToggle.hasClass(classes.mobileNavCloseIcon)) { closeMobileNav(); } else { openMobileNav(); } } function cacheSelectors() { cache = { $pageContainer: $('#PageContainer'), $siteHeader: $('.site-header'), $mobileNavToggle: $('.js-mobile-nav-toggle'), $mobileNavContainer: $('.mobile-nav-wrapper'), $mobileNav: $('#MobileNav'), $subNavToggleBtn: $('.' + classes.subNavToggleBtn) }; } function openMobileNav() { var translateHeaderHeight = cache.$siteHeader.outerHeight() + cache.$siteHeader.offset().top; cache.$mobileNavContainer .prepareTransition() .addClass(classes.navOpen); cache.$mobileNavContainer.css({ transform: 'translate3d(0, ' + translateHeaderHeight + 'px, 0)' }); cache.$pageContainer.css({ transform: 'translate3d(0, ' + cache.$mobileNavContainer[0].scrollHeight + 'px, 0)' }); slate.a11y.trapFocus({ $container: cache.$mobileNav, namespace: 'navFocus' }); cache.$mobileNavToggle .addClass(classes.mobileNavCloseIcon) .removeClass(classes.mobileNavOpenIcon); // close on escape $(window).on('keyup.mobileNav', function(evt) { if (evt.which === 27) { closeMobileNav(); } }); } function closeMobileNav() { cache.$mobileNavContainer.prepareTransition().removeClass(classes.navOpen); cache.$mobileNavContainer.css({ transform: 'translate3d(0, -100%, 0)' }); cache.$pageContainer.removeAttr('style'); cache.$mobileNavContainer.one('TransitionEnd.navToggle webkitTransitionEnd.navToggle transitionend.navToggle oTransitionEnd.navToggle', function() { slate.a11y.removeTrapFocus({ $container: cache.$mobileNav, namespace: 'navFocus' }); }); cache.$mobileNavToggle .addClass(classes.mobileNavOpenIcon) .removeClass(classes.mobileNavCloseIcon); $(window).off('keyup.mobileNav'); } function toggleSubNav(evt) { if (isTransitioning) { return; } var $toggleBtn = $(evt.currentTarget); var isReturn = $toggleBtn.hasClass(classes.return); isTransitioning = true; if (isReturn) { // Close all subnavs by removing active class on buttons $('.' + classes.subNavToggleBtn + '[data-level="' + (menuLevel - 1) + '"]') .removeClass(classes.subNavActive); if ($activeTrigger && $activeTrigger.length) { $activeTrigger.removeClass(classes.subNavActive); } } else { $toggleBtn.addClass(classes.subNavActive); } $activeTrigger = $toggleBtn; goToSubnav($toggleBtn.data('target')); } function goToSubnav(target) { /*eslint-disable shopify/jquery-dollar-sign-reference */ var $targetMenu = target ? $('.mobile-nav__dropdown[data-parent="' + target + '"]') : cache.$mobileNav; menuLevel = $targetMenu.data('level') ? $targetMenu.data('level') : 1; if ($activeSubNav && $activeSubNav.length) { $activeSubNav .prepareTransition() .addClass(classes.subNavClosing); } $activeSubNav = $targetMenu; var $elementToFocus = target ? $targetMenu.find('.' + classes.subNavLink + ':first') : $activeTrigger; /*eslint-enable shopify/jquery-dollar-sign-reference */ var translateMenuHeight = $targetMenu.outerHeight(); var openNavClass = menuLevel > 2 ? classes.thirdNavShowing : classes.subNavShowing; cache.$mobileNavContainer .css('height', translateMenuHeight) .removeClass(classes.thirdNavShowing) .addClass(openNavClass); if (!target) { // Show top level nav cache.$mobileNavContainer .removeClass(classes.thirdNavShowing) .removeClass(classes.subNavShowing); } // Focusing an item in the subnav early forces element into view and breaks the animation. cache.$mobileNavContainer.one('TransitionEnd.subnavToggle webkitTransitionEnd.subnavToggle transitionend.subnavToggle oTransitionEnd.subnavToggle', function() { slate.a11y.trapFocus({ $container: $targetMenu, $elementToFocus: $elementToFocus, namespace: 'subNavFocus' }); cache.$mobileNavContainer.off('.subnavToggle'); isTransitioning = false; }); // Match height of subnav cache.$pageContainer.css({ transform: 'translate3d(0, ' + translateMenuHeight + 'px, 0)' }); $activeSubNav.removeClass(classes.subNavClosing); } return { init: init, closeMobileNav: closeMobileNav }; })(jQuery); window.theme = window.theme || {}; theme.Search = (function() { var selectors = { search: '.search', searchSubmit: '.search__submit', searchInput: '.search__input', siteHeader: '.site-header', siteHeaderSearchToggle: '.site-header__search-toggle', siteHeaderSearch: '.site-header__search', searchDrawer: '.search-bar', searchDrawerInput: '.search-bar__input', searchHeader: '.search-header', searchHeaderInput: '.search-header__input', searchHeaderSubmit: '.search-header__submit', mobileNavWrapper: '.mobile-nav-wrapper' }; var classes = { focus: 'search--focus', mobileNavIsOpen: 'js-menu--is-open' }; function init() { if (!$(selectors.siteHeader).length) { return; } initDrawer(); searchSubmit(); $(selectors.searchHeaderInput).add(selectors.searchHeaderSubmit).on('focus blur', function() { $(selectors.searchHeader).toggleClass(classes.focus); }); $(selectors.siteHeaderSearchToggle).on('click', function() { var searchHeight = $(selectors.siteHeader).outerHeight(); var searchOffset = $(selectors.siteHeader).offset().top - searchHeight; $(selectors.searchDrawer).css({ height: searchHeight + 'px', top: searchOffset + 'px' }); }); } function initDrawer() { // Add required classes to HTML $('#PageContainer').addClass('drawer-page-content'); $('.js-drawer-open-top').attr('aria-controls', 'SearchDrawer').attr('aria-expanded', 'false'); theme.SearchDrawer = new theme.Drawers('SearchDrawer', 'top', { onDrawerOpen: searchDrawerFocus }); } function searchDrawerFocus() { searchFocus($(selectors.searchDrawerInput)); if ($(selectors.mobileNavWrapper).hasClass(classes.mobileNavIsOpen)) { theme.MobileNav.closeMobileNav(); } } function searchFocus($el) { $el.focus(); // set selection range hack for iOS $el[0].setSelectionRange(0, $el[0].value.length); } function searchSubmit() { $(selectors.searchSubmit).on('click', function(evt) { var $el = $(evt.target); var $input = $el.parents(selectors.search).find(selectors.searchInput); if ($input.val().length === 0) { evt.preventDefault(); searchFocus($input); } }); } return { init: init }; })(); (function() { var selectors = { backButton: '.return-link' }; var $backButton = $(selectors.backButton); if (!document.referrer || !$backButton.length || !window.history.length) { return; } $backButton.one('click', function(evt) { evt.preventDefault(); var referrerDomain = urlDomain(document.referrer); var shopDomain = urlDomain(window.location.href); if (shopDomain === referrerDomain) { history.back(); } return false; }); function urlDomain(url) { var anchor = document.createElement('a'); anchor.ref = url; return anchor.hostname; } })(); theme.Slideshow = (function() { this.$slideshow = null; var classes = { wrapper: 'slideshow-wrapper', slideshow: 'slideshow', currentSlide: 'slick-current', video: 'slideshow__video', videoBackground: 'slideshow__video--background', closeVideoBtn: 'slideshow__video-control--close', pauseButton: 'slideshow__pause', isPaused: 'is-paused' }; function slideshow(el) { this.$slideshow = $(el); this.$wrapper = this.$slideshow.closest('.' + classes.wrapper); this.$pause = this.$wrapper.find('.' + classes.pauseButton); this.settings = { accessibility: true, arrows: false, dots: true, fade: true, draggable: true, touchThreshold: 20, autoplay: this.$slideshow.data('autoplay'), autoplaySpeed: this.$slideshow.data('speed') }; this.$slideshow.on('beforeChange', beforeChange.bind(this)); this.$slideshow.on('init', slideshowA11y.bind(this)); this.$slideshow.slick(this.settings); this.$pause.on('click', this.togglePause.bind(this)); } function slideshowA11y(event, obj) { var $slider = obj.$slider; var $list = obj.$list; var $wrapper = this.$wrapper; var autoplay = this.settings.autoplay; // Remove default Slick aria-live attr until slider is focused $list.removeAttr('aria-live'); // When an element in the slider is focused // pause slideshow and set aria-live. $wrapper.on('focusin', function(evt) { if (!$wrapper.has(evt.target).length) { return; } $list.attr('aria-live', 'polite'); if (autoplay) { $slider.slick('slickPause'); } }); // Resume autoplay $wrapper.on('focusout', function(evt) { if (!$wrapper.has(evt.target).length) { return; } $list.removeAttr('aria-live'); if (autoplay) { // Manual check if the focused element was the video close button // to ensure autoplay does not resume when focus goes inside YouTube iframe if ($(evt.target).hasClass(classes.closeVideoBtn)) { return; } $slider.slick('slickPlay'); } }); // Add arrow key support when focused if (obj.$dots) { obj.$dots.on('keydown', function(evt) { if (evt.which === 37) { $slider.slick('slickPrev'); } if (evt.which === 39) { $slider.slick('slickNext'); } // Update focus on newly selected tab if ((evt.which === 37) || (evt.which === 39)) { obj.$dots.find('.slick-active button').focus(); } }); } } function beforeChange(event, slick, currentSlide, nextSlide) { var $slider = slick.$slider; var $currentSlide = $slider.find('.' + classes.currentSlide); var $nextSlide = $slider.find('.slideshow__slide[data-slick-index="' + nextSlide + '"]'); if (isVideoInSlide($currentSlide)) { var $currentVideo = $currentSlide.find('.' + classes.video); var currentVideoId = $currentVideo.attr('id'); theme.SlideshowVideo.pauseVideo(currentVideoId); $currentVideo.attr('tabindex', '-1'); } if (isVideoInSlide($nextSlide)) { var $video = $nextSlide.find('.' + classes.video); var videoId = $video.attr('id'); var isBackground = $video.hasClass(classes.videoBackground); if (isBackground) { theme.SlideshowVideo.playVideo(videoId); } else { $video.attr('tabindex', '0'); } } } function isVideoInSlide($slide) { return $slide.find('.' + classes.video).length; } slideshow.prototype.togglePause = function() { var slideshowSelector = getSlideshowId(this.$pause); if (this.$pause.hasClass(classes.isPaused)) { this.$pause.removeClass(classes.isPaused); $(slideshowSelector).slick('slickPlay'); } else { this.$pause.addClass(classes.isPaused); $(slideshowSelector).slick('slickPause'); } }; function getSlideshowId($el) { return '#Slideshow-' + $el.data('id'); } return slideshow; })(); // Youtube API callback // eslint-disable-next-line no-unused-vars function onYouTubeIframeAPIReady() { theme.SlideshowVideo.loadVideos(); } theme.SlideshowVideo = (function() { var autoplayCheckComplete = false; var autoplayAvailable = false; var playOnClickChecked = false; var playOnClick = false; var youtubeLoaded = false; var videos = {}; var videoPlayers = []; var videoOptions = { ratio: 16 / 9, playerVars: { // eslint-disable-next-line camelcase iv_load_policy: 3, modestbranding: 1, autoplay: 0, controls: 0, showinfo: 0, wmode: 'opaque', branding: 0, autohide: 0, rel: 0 }, events: { onReady: onPlayerReady, onStateChange: onPlayerChange } }; var classes = { playing: 'video-is-playing', paused: 'video-is-paused', loading: 'video-is-loading', loaded: 'video-is-loaded', slideshowWrapper: 'slideshow-wrapper', slide: 'slideshow__slide', slideBackgroundVideo: 'slideshow__slide--background-video', slideDots: 'slick-dots', videoChrome: 'slideshow__video--chrome', videoBackground: 'slideshow__video--background', playVideoBtn: 'slideshow__video-control--play', closeVideoBtn: 'slideshow__video-control--close', currentSlide: 'slick-current', slickClone: 'slick-cloned', supportsAutoplay: 'autoplay', supportsNoAutoplay: 'no-autoplay' }; /** * Public functions */ function init($video) { if (!$video.length) { return; } videos[$video.attr('id')] = { id: $video.attr('id'), videoId: $video.data('id'), type: $video.data('type'), status: $video.data('type') === 'chrome' ? 'closed' : 'background', // closed, open, background videoSelector: $video.attr('id'), $parentSlide: $video.closest('.' + classes.slide), $parentSlideshowWrapper: $video.closest('.' + classes.slideshowWrapper), controls: $video.data('type') === 'background' ? 0 : 1, slideshow: $video.data('slideshow') }; if (!youtubeLoaded) { // This code loads the IFrame Player API code asynchronously. var tag = document.createElement('script'); tag.src = 'https://www.youtube.com/iframe_api'; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); } } function customPlayVideo(playerId) { // Do not autoplay just because the slideshow asked you to. // If the slideshow asks to play a video, make sure // we have done the playOnClick check first if (!playOnClickChecked && !playOnClick) { return; } if (playerId && typeof videoPlayers[playerId].playVideo === 'function') { privatePlayVideo(playerId); } } function pauseVideo(playerId) { if (videoPlayers[playerId] && typeof videoPlayers[playerId].pauseVideo === 'function') { videoPlayers[playerId].pauseVideo(); } } function loadVideos() { for (var key in videos) { if (videos.hasOwnProperty(key)) { var args = $.extend({}, videoOptions, videos[key]); args.playerVars.controls = args.controls; videoPlayers[key] = new YT.Player(key, args); } } initEvents(); youtubeLoaded = true; } function loadVideo(key) { if (!youtubeLoaded) { return; } var args = $.extend({}, videoOptions, videos[key]); args.playerVars.controls = args.controls; videoPlayers[key] = new YT.Player(key, args); initEvents(); } /** * Private functions */ function privatePlayVideo(id, clicked) { var videoData = videos[id]; var player = videoPlayers[id]; var $slide = videos[id].$parentSlide; if (playOnClick) { // playOnClick means we are probably on mobile (no autoplay). // setAsPlaying will show the iframe, requiring another click // to play the video. setAsPlaying(videoData); } else if (clicked || (autoplayCheckComplete && autoplayAvailable)) { // Play if autoplay is available or clicked to play $slide.removeClass(classes.loading); setAsPlaying(videoData); player.playVideo(); return; } // Check for autoplay if not already done if (!autoplayCheckComplete) { autoplayCheckFunction(player, $slide); } } function setAutoplaySupport(supported) { var supportClass = supported ? classes.supportsAutoplay : classes.supportsNoAutoplay; $(document.documentElement).addClass(supportClass); if (!supported) { playOnClick = true; } autoplayCheckComplete = true; } function autoplayCheckFunction(player, $slide) { // attempt to play video player.playVideo(); autoplayTest(player) .then(function() { setAutoplaySupport(true); }) .fail(function() { // No autoplay available (or took too long to start playing). // Show fallback image. Stop video for safety. setAutoplaySupport(false); player.stopVideo(); }) .always(function() { autoplayCheckComplete = true; $slide.removeClass(classes.loading); }); } function autoplayTest(player) { var deferred = $.Deferred(); var wait; var timeout; wait = setInterval(function() { if (player.getCurrentTime() <= 0) { return; } autoplayAvailable = true; clearInterval(wait); clearTimeout(timeout); deferred.resolve(); }, 500); timeout = setTimeout(function() { clearInterval(wait); deferred.reject(); }, 4000); // subjective. test up to 8 times over 4 seconds return deferred; } function playOnClickCheck() { // Bail early for a few instances: // - small screen // - device sniff mobile browser if (playOnClickChecked) { return; } if ($(window).width() < 750) { playOnClick = true; } else if (window.mobileCheck()) { playOnClick = true; } if (playOnClick) { // No need to also do the autoplay check setAutoplaySupport(false); } playOnClickChecked = true; } // The API will call this function when each video player is ready function onPlayerReady(evt) { evt.target.setPlaybackQuality('hd1080'); var videoData = getVideoOptions(evt); playOnClickCheck(); // Prevent tabbing through YouTube player controls until visible $('#' + videoData.id).attr('tabindex', '-1'); sizeBackgroundVideos(); // Customize based on options from the video ID switch (videoData.type) { case 'background-chrome': case 'background': evt.target.mute(); // Only play the video if it is in the active slide if (videoData.$parentSlide.hasClass(classes.currentSlide)) { privatePlayVideo(videoData.id); } break; } videoData.$parentSlide.addClass(classes.loaded); } function onPlayerChange(evt) { var videoData = getVideoOptions(evt); switch (evt.data) { case 0: // ended setAsFinished(videoData); break; case 1: // playing setAsPlaying(videoData); break; case 2: // paused setAsPaused(videoData); break; } } function setAsFinished(videoData) { switch (videoData.type) { case 'background': videoPlayers[videoData.id].seekTo(0); break; case 'background-chrome': videoPlayers[videoData.id].seekTo(0); closeVideo(videoData.id); break; case 'chrome': closeVideo(videoData.id); break; } } function setAsPlaying(videoData) { var $slideshow = videoData.$parentSlideshowWrapper; var $slide = videoData.$parentSlide; $slide.removeClass(classes.loading); // Do not change element visibility if it is a background video if (videoData.status === 'background') { return; } $('#' + videoData.id).attr('tabindex', '0'); switch (videoData.type) { case 'chrome': case 'background-chrome': $slideshow .removeClass(classes.paused) .addClass(classes.playing); $slide .removeClass(classes.paused) .addClass(classes.playing); break; } // Update focus to the close button so we stay within the slide $slide.find('.' + classes.closeVideoBtn).focus(); } function setAsPaused(videoData) { var $slideshow = videoData.$parentSlideshowWrapper; var $slide = videoData.$parentSlide; if (videoData.type === 'background-chrome') { closeVideo(videoData.id); return; } // YT's events fire after our click event. This status flag ensures // we don't interact with a closed or background video. if (videoData.status !== 'closed' && videoData.type !== 'background') { $slideshow.addClass(classes.paused); $slide.addClass(classes.paused); } if (videoData.type === 'chrome' && videoData.status === 'closed') { $slideshow.removeClass(classes.paused); $slide.removeClass(classes.paused); } $slideshow.removeClass(classes.playing); $slide.removeClass(classes.playing); } function closeVideo(playerId) { var videoData = videos[playerId]; var $slideshow = videoData.$parentSlideshowWrapper; var $slide = videoData.$parentSlide; var classesToRemove = [classes.pause, classes.playing].join(' '); $('#' + videoData.id).attr('tabindex', '-1'); videoData.status = 'closed'; switch (videoData.type) { case 'background-chrome': videoPlayers[playerId].mute(); setBackgroundVideo(playerId); break; case 'chrome': videoPlayers[playerId].stopVideo(); setAsPaused(videoData); // in case the video is already paused break; } $slideshow.removeClass(classesToRemove); $slide.removeClass(classesToRemove); } function getVideoOptions(evt) { return videos[evt.target.h.id]; } function startVideoOnClick(playerId) { var videoData = videos[playerId]; // add loading class to slide videoData.$parentSlide.addClass(classes.loading); videoData.status = 'open'; switch (videoData.type) { case 'background-chrome': unsetBackgroundVideo(playerId, videoData); videoPlayers[playerId].unMute(); privatePlayVideo(playerId, true); break; case 'chrome': privatePlayVideo(playerId, true); break; } // esc to close video player $(document).on('keydown.videoPlayer', function(evt) { if (evt.keyCode === 27) { closeVideo(playerId); } }); } function sizeBackgroundVideos() { $('.' + classes.videoBackground).each(function(index, el) { sizeBackgroundVideo($(el)); }); } function sizeBackgroundVideo($player) { var $slide = $player.closest('.' + classes.slide); // Ignore cloned slides if ($slide.hasClass(classes.slickClone)) { return; } var slideWidth = $slide.width(); var playerWidth = $player.width(); var playerHeight = $player.height(); // when screen aspect ratio differs from video, video must center and underlay one dimension if (slideWidth / videoOptions.ratio < playerHeight) { playerWidth = Math.ceil(playerHeight * videoOptions.ratio); // get new player width $player.width(playerWidth).height(playerHeight).css({ left: (slideWidth - playerWidth) / 2, top: 0 }); // player width is greater, offset left; reset top } else { // new video width < window width (gap to right) playerHeight = Math.ceil(slideWidth / videoOptions.ratio); // get new player height $player.width(slideWidth).height(playerHeight).css({ left: 0, top: (playerHeight - playerHeight) / 2 }); // player height is greater, offset top; reset left } $player .prepareTransition() .addClass(classes.loaded); } function unsetBackgroundVideo(playerId) { // Switch the background-chrome to a chrome-only player once played $('#' + playerId) .removeAttr('style') .removeClass(classes.videoBackground) .addClass(classes.videoChrome); videos[playerId].$parentSlideshowWrapper .removeClass(classes.slideBackgroundVideo) .addClass(classes.playing); videos[playerId].$parentSlide .removeClass(classes.slideBackgroundVideo) .addClass(classes.playing); videos[playerId].status = 'open'; } function setBackgroundVideo(playerId) { // Switch back to background-chrome when closed var $player = $('#' + playerId) .addClass(classes.videoBackground) .removeClass(classes.videoChrome); videos[playerId].$parentSlide .addClass(classes.slideBackgroundVideo); videos[playerId].status = 'background'; sizeBackgroundVideo($player); } function initEvents() { $(document).on('click.videoPlayer', '.' + classes.playVideoBtn, function(evt) { var playerId = $(evt.currentTarget).data('controls'); startVideoOnClick(playerId); }); $(document).on('click.videoPlayer', '.' + classes.closeVideoBtn, function(evt) { var playerId = $(evt.currentTarget).data('controls'); closeVideo(playerId); }); // Listen to resize to keep a background-size:cover-like layout $(window).on('resize.videoPlayer', $.debounce(250, function() { if (youtubeLoaded) { sizeBackgroundVideos(); } })); } function removeEvents() { $(document).off('.videoPlayer'); $(window).off('.videoPlayer'); } return { init: init, loadVideos: loadVideos, loadVideo: loadVideo, playVideo: customPlayVideo, pauseVideo: pauseVideo, removeEvents: removeEvents }; })(); /* ================ TEMPLATES ================ */ (function() { var $filterBy = $('#BlogTagFilter'); if (!$filterBy.length) { return; } $filterBy.on('change', function() { location.href = $(this).val(); }); })(); window.theme = theme || {}; theme.customerTemplates = (function() { function initEventListeners() { // Show reset password form $('#RecoverPassword').on('click', function(evt) { evt.preventDefault(); toggleRecoverPasswordForm(); }); // Hide reset password form $('#HideRecoverPasswordLink').on('click', function(evt) { evt.preventDefault(); toggleRecoverPasswordForm(); }); } /** * * Show/Hide recover password form * */ function toggleRecoverPasswordForm() { $('#RecoverPasswordForm').toggleClass('hide'); $('#CustomerLoginForm').toggleClass('hide'); } /** * * Show reset password success message * */ function resetPasswordSuccess() { var $formState = $('.reset-password-success'); // check if reset password form was successfully submited. if (!$formState.length) { return; } // show success message $('#ResetSuccess').removeClass('hide'); } /** * * Show/hide customer address forms * */ function customerAddressForm() { var $newAddressForm = $('#AddressNewForm'); if (!$newAddressForm.length) { return; } // Initialize observers on address selectors, defined in shopify_common.js if (Shopify) { // eslint-disable-next-line no-new new Shopify.CountryProvinceSelector('AddressCountryNew', 'AddressProvinceNew', { hideElement: 'AddressProvinceContainerNew' }); } // Initialize each edit form's country/province selector $('.address-country-option').each(function() { var formId = $(this).data('form-id'); var countrySelector = 'AddressCountry_' + formId; var provinceSelector = 'AddressProvince_' + formId; var containerSelector = 'AddressProvinceContainer_' + formId; // eslint-disable-next-line no-new new Shopify.CountryProvinceSelector(countrySelector, provinceSelector, { hideElement: containerSelector }); }); // Toggle new/edit address forms $('.address-new-toggle').on('click', function() { $newAddressForm.toggleClass('hide'); }); $('.address-edit-toggle').on('click', function() { var formId = $(this).data('form-id'); $('#EditAddress_' + formId).toggleClass('hide'); }); $('.address-delete').on('click', function() { var $el = $(this); var formId = $el.data('form-id'); var confirmMessage = $el.data('confirm-message'); // eslint-disable-next-line no-alert if (confirm(confirmMessage || 'Are you sure you wish to delete this address?')) { Shopify.postLink('/account/addresses/' + formId, {parameters: {_method: 'delete'}}); } }); } /** * * Check URL for reset password hash * */ function checkUrlHash() { var hash = window.location.hash; // Allow deep linking to recover password form if (hash === '#recover') { toggleRecoverPasswordForm(); } } return { init: function() { checkUrlHash(); initEventListeners(); resetPasswordSuccess(); customerAddressForm(); } }; })(); /*================ SECTIONS ================*/ window.theme = window.theme || {}; theme.Cart = (function() { var selectors = { edit: '.js-edit-toggle' }; var config = { showClass: 'cart__update--show', showEditClass: 'cart__edit--active', cartNoCookies: 'cart--no-cookies' }; function Cart(container) { this.$container = $(container); this.$edit = $(selectors.edit, this.$container); if (!this.cookiesEnabled()) { this.$container.addClass(config.cartNoCookies); } this.$edit.on('click', this._onEditClick.bind(this)); } Cart.prototype = _.assignIn({}, Cart.prototype, { onUnload: function() { this.$edit.off('click', this._onEditClick); }, _onEditClick: function(evt) { var $evtTarget = $(evt.target); var $updateLine = $('.' + $evtTarget.data('target')); $evtTarget.toggleClass(config.showEditClass); $updateLine.toggleClass(config.showClass); }, cookiesEnabled: function() { var cookieEnabled = navigator.cookieEnabled; if (!cookieEnabled){ document.cookie = 'testcookie'; cookieEnabled = (document.cookie.indexOf('testcookie') !== -1); } return cookieEnabled; } }); return Cart; })(); window.theme = window.theme || {}; theme.Filters = (function() { var constants = { SORT_BY: 'sort_by' }; var selectors = { filterSelection: '.filters-toolbar__input--filter', sortSelection: '.filters-toolbar__input--sort', defaultSort: '.collection-header__default-sort' }; function Filters(container) { var $container = this.$container = $(container); this.$filterSelect = $(selectors.filterSelection, $container); this.$sortSelect = $(selectors.sortSelection, $container); this.$selects = $(selectors.filterSelection, $container).add($(selectors.sortSelection, $container)); this.defaultSort = this._getDefaultSortValue(); this._resizeSelect(this.$selects); this.$selects.removeClass('hidden'); this.$filterSelect.on('change', this._onFilterChange.bind(this)); this.$sortSelect.on('change', this._onSortChange.bind(this)); } Filters.prototype = _.assignIn({}, Filters.prototype, { _onSortChange: function(evt) { var sort = this._sortValue(); if (sort.length) { window.location.search = sort; } else { // clean up our url if the sort value is blank for default window.location.href = window.location.href.replace(window.location.search, ''); } this._resizeSelect($(evt.target)); }, _onFilterChange: function(evt) { window.location.href = this.$filterSelect.val() + window.location.search; this._resizeSelect($(evt.target)); }, _getSortValue: function() { return this.$sortSelect.val() || this.defaultSort; }, _getDefaultSortValue: function() { return $(selectors.defaultSort, this.$container).val(); }, _sortValue: function() { var sort = this._getSortValue(); var query = ''; if (sort !== this.defaultSort) { query = constants.SORT_BY + '=' + sort; } return query; }, _resizeSelect: function($selection) { $selection.each(function() { var $this = $(this); var arrowWidth = 10; // create test element var text = $this.find('option:selected').text(); var $test = $('<span>').html(text); // add to body, get width, and get out $test.appendTo('body'); var width = $test.width(); $test.remove(); // set select width $this.width(width + arrowWidth); }); }, onUnload: function() { this.$filterSelect.off('change', this._onFilterChange); this.$sortSelect.off('change', this._onSortChange); } }); return Filters; })(); window.theme = window.theme || {}; theme.HeaderSection = (function() { function Header() { theme.Header.init(); theme.MobileNav.init(); theme.Search.init(); } Header.prototype = _.assignIn({}, Header.prototype, { onUnload: function() { theme.Header.unload(); } }); return Header; })(); theme.Maps = (function() { var config = { zoom: 14 }; var apiStatus = null; var mapsToLoad = []; var errors = { addressNoResults: theme.strings.addressNoResults, addressQueryLimit: theme.strings.addressQueryLimit, addressError: theme.strings.addressError, authError: theme.strings.authError }; var selectors = { section: '[data-section-type="map"]', map: '[data-map]', mapOverlay: '[data-map-overlay]' }; var classes = { mapError: 'map-section--load-error', errorMsg: 'map-section__error errors text-center' }; // Global function called by Google on auth errors. // Show an auto error message on all map instances. // eslint-disable-next-line camelcase, no-unused-vars window.gm_authFailure = function() { if (Shopify.designMode) { $(selectors.section).addClass(classes.mapError); $(selectors.map).remove(); $(selectors.mapOverlay).after('<div class="' + classes.errorMsg + '">' + theme.strings.authError + '</div>'); } } function Map(container) { this.$container = $(container); this.$map = this.$container.find(selectors.map); this.key = this.$map.data('api-key'); if (typeof this.key === 'undefined') { return; } if (apiStatus === 'loaded') { this.createMap(); } else { mapsToLoad.push(this); if (apiStatus !== 'loading') { apiStatus = 'loading'; if (typeof window.google === 'undefined') { $.getScript('https://maps.googleapis.com/maps/api/js?key=' + this.key) .then(function() { apiStatus = 'loaded'; initAllMaps(); }); } } } } function initAllMaps() { // API has loaded, load all Map instances in queue $.each(mapsToLoad, function(index, instance) { instance.createMap(); }); } function geolocate($map) { var deferred = $.Deferred(); var geocoder = new google.maps.Geocoder(); var address = $map.data('address-setting'); geocoder.geocode({address: address}, function(results, status) { if (status !== google.maps.GeocoderStatus.OK) { deferred.reject(status); } deferred.resolve(results); }); return deferred; } Map.prototype = _.assignIn({}, Map.prototype, { createMap: function() { var $map = this.$map; return geolocate($map) .then(function(results) { var mapOptions = { zoom: config.zoom, center: results[0].geometry.location, draggable: false, clickableIcons: false, scrollwheel: false, disableDoubleClickZoom: true, disableDefaultUI: true }; var map = this.map = new google.maps.Map($map[0], mapOptions); var center = this.center = map.getCenter(); //eslint-disable-next-line no-unused-vars var marker = new google.maps.Marker({ map: map, position: map.getCenter() }); google.maps.event.addDomListener(window, 'resize', $.debounce(250, function() { google.maps.event.trigger(map, 'resize'); map.setCenter(center); $map.removeAttr('style'); })); }.bind(this)) .fail(function() { var errorMessage; switch (status) { case 'ZERO_RESULTS': errorMessage = errors.addressNoResults; break; case 'OVER_QUERY_LIMIT': errorMessage = errors.addressQueryLimit; break; case 'REQUEST_DENIED': errorMessage = errors.authError; break; default: errorMessage = errors.addressError; break; } // Show errors only to merchant in the editor. if (Shopify.designMode) { $map .parent() .addClass(classes.mapError) .html('<div class="' + classes.errorMsg + '">' + errorMessage + '</div>'); } }); }, onUnload: function() { if (this.$map.length === 0) { return; } google.maps.event.clearListeners(this.map, 'resize'); } }); return Map; })(); /* eslint-disable no-new */ theme.Product = (function() { function Product(container) { var $container = this.$container = $(container); var sectionId = $container.attr('data-section-id'); this.settings = { // Breakpoints from src/stylesheets/global/variables.scss.liquid mediaQueryMediumUp: 'screen and (min-width: 750px)', mediaQuerySmall: 'screen and (max-width: 749px)', bpSmall: false, enableHistoryState: $container.data('enable-history-state') || false, namespace: '.slideshow-' + sectionId, sectionId: sectionId, sliderActive: false, zoomEnabled: false }; this.selectors = { addToCart: '#AddToCart-' + sectionId, addToCartText: '#AddToCartText-' + sectionId, comparePrice: '#ComparePrice-' + sectionId, originalPrice: '#ProductPrice-' + sectionId, SKU: '.variant-sku', originalPriceWrapper: '.product-price__price-' + sectionId, originalSelectorId: '#ProductSelect-' + sectionId, productImageWraps: '.product-single__photo', productPrices: '.product-single__price-' + sectionId, productThumbImages: '.product-single__thumbnail--' + sectionId, productThumbs: '.product-single__thumbnails-' + sectionId, saleClasses: 'product-price__sale product-price__sale--single', saleLabel: '.product-price__sale-label-' + sectionId, singleOptionSelector: '.single-option-selector-' + sectionId } // Stop parsing if we don't have the product json script tag when loading // section in the Theme Editor if (!$('#ProductJson-' + sectionId).html()) { return; } this.productSingleObject = JSON.parse(document.getElementById('ProductJson-' + sectionId).innerHTML); this.settings.zoomEnabled = $(this.selectors.productImageWraps).hasClass('js-zoom-enabled'); this._initBreakpoints(); this._stringOverrides(); this._initVariants(); this._initImageSwitch(); this._setActiveThumbnail(); } Product.prototype = _.assignIn({}, Product.prototype, { _stringOverrides: function() { theme.productStrings = theme.productStrings || {}; $.extend(theme.strings, theme.productStrings); }, _initBreakpoints: function() { var self = this; enquire.register(this.settings.mediaQuerySmall, { match: function() { // initialize thumbnail slider on mobile if more than three thumbnails if ($(self.selectors.productThumbImages).length > 3) { self._initThumbnailSlider(); } // destroy image zooming if enabled if (self.settings.zoomEnabled) { $(self.selectors.productImageWraps).each(function( index ) { _destroyZoom(this); }); } self.settings.bpSmall = true; }, unmatch: function() { if (self.settings.sliderActive) { self._destroyThumbnailSlider(); } self.settings.bpSmall = false; } }); enquire.register(this.settings.mediaQueryMediumUp, { match: function() { if (self.settings.zoomEnabled) { $(self.selectors.productImageWraps).each(function( index ) { _enableZoom(this); }); } } }); }, _initVariants: function() { var options = { $container: this.$container, enableHistoryState: this.$container.data('enable-history-state') || false, singleOptionSelector: this.selectors.singleOptionSelector, originalSelectorId: this.selectors.originalSelectorId, product: this.productSingleObject }; this.variants = new slate.Variants(options); this.$container.on('variantChange' + this.settings.namespace, this._updateAddToCart.bind(this)); this.$container.on('variantImageChange' + this.settings.namespace, this._updateImages.bind(this)); this.$container.on('variantPriceChange' + this.settings.namespace, this._updatePrice.bind(this)); this.$container.on('variantSKUChange' + this.settings.namespace, this._updateSKU.bind(this)); }, _initImageSwitch: function() { if (!$(this.selectors.productThumbImages).length) { return; } var self = this; $(this.selectors.productThumbImages).on('click', function(evt) { evt.preventDefault(); var $el = $(this); var imageId = $el.data('thumbnail-id'); self._switchImage(imageId); self._setActiveThumbnail(imageId); }); }, _setActiveThumbnail: function(imageId) { var activeClass = 'active-thumb'; // If there is no element passed, find it by the current product image if (typeof imageId === 'undefined') { imageId = $(this.selectors.productImageWraps + ":not('.hide')").data('image-id'); } var $thumbnail = $(this.selectors.productThumbImages + "[data-thumbnail-id='" + imageId + "']"); $(this.selectors.productThumbImages).removeClass(activeClass); $thumbnail.addClass(activeClass); }, _switchImage: function(imageId) { var $newImage = $( this.selectors.productImageWraps + "[data-image-id='" + imageId + "']", this.$container); var $otherImages = $( this.selectors.productImageWraps + ":not([data-image-id='" + imageId + "'])", this.$container); $newImage.removeClass('hide'); $otherImages.addClass('hide'); }, _initThumbnailSlider: function() { var options = { slidesToShow: 4, slidesToScroll: 3, infinite: false, prevArrow: '.thumbnails-slider__prev--' + this.settings.sectionId, nextArrow: '.thumbnails-slider__next--' + this.settings.sectionId, responsive: [ { breakpoint: 321, settings: { slidesToShow: 3 } } ] }; $(this.selectors.productThumbs).slick(options); this.settings.sliderActive = true; }, _destroyThumbnailSlider: function() { $(this.selectors.productThumbs).slick('unslick'); this.settings.sliderActive = false; }, _updateAddToCart: function(evt) { var variant = evt.variant; if (variant) { $(this.selectors.productPrices) .removeClass('visibility-hidden') .attr('aria-hidden', 'true'); if (variant.available) { $(this.selectors.addToCart).prop('disabled', false); $(this.selectors.addToCartText).text(theme.strings.addToCart); } else { // The variant doesn't exist, disable submit button and change the text. // This may be an error or notice that a specific variant is not available. $(this.selectors.addToCart).prop('disabled', true); $(this.selectors.addToCartText).text(theme.strings.soldOut); } } else { $(this.selectors.addToCart).prop('disabled', true); $(this.selectors.addToCartText).text(theme.strings.unavailable); $(this.selectors.productPrices) .addClass('visibility-hidden') .attr('aria-hidden', 'false'); } }, _updateImages: function(evt) { var variant = evt.variant; var imageId = variant.featured_image.id this._switchImage(imageId); this._setActiveThumbnail(imageId); }, _updatePrice: function(evt) { var variant = evt.variant; // Update the product price $(this.selectors.originalPrice).html(theme.Currency.formatMoney(variant.price, theme.moneyFormat)); // Update and show the product's compare price if necessary if (variant.compare_at_price > variant.price) { $(this.selectors.comparePrice) .html(theme.Currency.formatMoney(variant.compare_at_price, theme.moneyFormat)) .removeClass('hide'); $(this.selectors.originalPriceWrapper).addClass(this.selectors.saleClasses); $(this.selectors.saleLabel).removeClass('hide'); } else { $(this.selectors.comparePrice).addClass('hide'); $(this.selectors.saleLabel).addClass('hide'); $(this.selectors.originalPriceWrapper).removeClass(this.selectors.saleClasses); } }, _updateSKU: function(evt) { var variant = evt.variant; // Update the sku $(this.selectors.SKU).html(variant.sku); }, onUnload: function() { this.$container.off(this.settings.namespace); } }); function _enableZoom(el) { var zoomUrl = $(el).data('zoom'); $(el).zoom({ url: zoomUrl }); } function _destroyZoom(el) { $(el).trigger('zoom.destroy'); } return Product; })(); theme.Quotes = (function() { var config = { mediaQuerySmall: 'screen and (max-width: 749px)', mediaQueryMediumUp: 'screen and (min-width: 750px)', slideCount: 0 }; var defaults = { accessibility: true, arrows: false, dots: true, autoplay: false, touchThreshold: 20, slidesToShow: 3, slidesToScroll: 3 }; function Quotes(container) { var $container = this.$container = $(container); var sectionId = $container.attr('data-section-id'); var wrapper = this.wrapper = '.quotes-wrapper'; var slider = this.slider = '#Quotes-' + sectionId; var $slider = $(slider, wrapper); var sliderActive = false; var mobileOptions = $.extend({}, defaults, { slidesToShow: 1, slidesToScroll: 1, adaptiveHeight: true }); config.slideCount = $slider.data('count'); // Override slidesToShow/Scroll if there are not enough blocks if (config.slideCount < defaults.slidesToShow) { defaults.slidesToShow = config.slideCount; defaults.slidesToScroll = config.slideCount; } $slider.on('init', this.a11y.bind(this)); enquire.register(config.mediaQuerySmall, { match: function() { initSlider($slider, mobileOptions); } }); enquire.register(config.mediaQueryMediumUp, { match: function() { initSlider($slider, defaults); } }); function initSlider(sliderObj, args) { if (sliderActive) { sliderObj.slick('unslick'); sliderActive = false; } sliderObj.slick(args); sliderActive = true; } } Quotes.prototype = _.assignIn({}, Quotes.prototype, { onUnload: function() { enquire.unregister(config.mediaQuerySmall); enquire.unregister(config.mediaQueryMediumUp); $(this.slider, this.wrapper).slick('unslick'); }, onBlockSelect: function(evt) { // Ignore the cloned version var $slide = $('.quotes-slide--' + evt.detail.blockId + ':not(.slick-cloned)'); var slideIndex = $slide.data('slick-index'); // Go to selected slide, pause autoplay $(this.slider, this.wrapper).slick('slickGoTo', slideIndex); }, a11y: function(event, obj) { var $list = obj.$list; var $wrapper = $(this.wrapper, this.$container); // Remove default Slick aria-live attr until slider is focused $list.removeAttr('aria-live'); // When an element in the slider is focused set aria-live $wrapper.on('focusin', function(evt) { if ($wrapper.has(evt.target).length) { $list.attr('aria-live', 'polite'); } }); // Remove aria-live $wrapper.on('focusout', function(evt) { if ($wrapper.has(evt.target).length) { $list.removeAttr('aria-live'); } }); } }); return Quotes; })(); theme.slideshows = {}; theme.SlideshowSection = (function() { function SlideshowSection(container) { var $container = this.$container = $(container); var sectionId = $container.attr('data-section-id'); var slideshow = this.slideshow = '#Slideshow-' + sectionId; $('.slideshow__video', slideshow).each(function() { var $el = $(this); theme.SlideshowVideo.init($el); theme.SlideshowVideo.loadVideo($el.attr('id')); }); theme.slideshows[slideshow] = new theme.Slideshow(slideshow); } return SlideshowSection; })(); theme.SlideshowSection.prototype = _.assignIn({}, theme.SlideshowSection.prototype, { onUnload: function() { delete theme.slideshows[this.slideshow]; }, onBlockSelect: function(evt) { var $slideshow = $(this.slideshow); // Ignore the cloned version var $slide = $('.slideshow__slide--' + evt.detail.blockId + ':not(.slick-cloned)'); var slideIndex = $slide.data('slick-index'); // Go to selected slide, pause autoplay $slideshow.slick('slickGoTo', slideIndex).slick('slickPause'); }, onBlockDeselect: function() { // Resume autoplay $(this.slideshow).slick('slickPlay'); } }); $(document).ready(function() { var sections = new theme.Sections(); sections.register('cart-template', theme.Cart); sections.register('product', theme.Product); sections.register('collection-template', theme.Filters); sections.register('product-template', theme.Product); sections.register('header-section', theme.HeaderSection); sections.register('map', theme.Maps); sections.register('slideshow-section', theme.SlideshowSection); sections.register('quotes', theme.Quotes); }); theme.init = function() { theme.customerTemplates.init(); // Theme-specific selectors to make tables scrollable var tableSelectors = '.rte table,' + '.custom__item-inner--html table'; slate.rte.wrapTable({ $tables: $(tableSelectors), tableWrapperClass: 'scrollable-wrapper', }); // Theme-specific selectors to make iframes responsive var iframeSelectors = '.rte iframe[src*="youtube.com/embed"],' + '.rte iframe[src*="player.vimeo"],' + '.custom__item-inner--html iframe[src*="youtube.com/embed"],' + '.custom__item-inner--html iframe[src*="player.vimeo"]'; slate.rte.wrapIframe({ $iframes: $(iframeSelectors), iframeWrapperClass: 'video-wrapper' }); // Common a11y fixes slate.a11y.pageLinkFocus($(window.location.hash)); $('.in-page-link').on('click', function(evt) { slate.a11y.pageLinkFocus($(evt.currentTarget.hash)); }); $('a[href="#"]').on('click', function(evt) { evt.preventDefault(); }); }; $(theme.init);
'use strict'; // Test specific configuration // =========================== module.exports = { // MongoDB connection options mongo: { uri: 'mongodb://localhost/conversionrobot-test' } };
window.ProseMirror = require("prosemirror/dist/edit").ProseMirror require("prosemirror/dist/menu/menubar") // Load menubar module require( "prosemirror/dist/markdown/to_markdown" ) require( "prosemirror/dist/markdown/from_markdown" ) window.ProseMirrorUtils = {}; window.ProseMirrorUtils.defaultschema = require( "prosemirror/dist/model/defaultschema") window.ProseMirrorUtils.schema = require( "prosemirror/dist/model/schema") window.ProseMirrorUtils.commandSet = require( "prosemirror/dist/edit/command").CommandSet window.ProseMirrorUtils.menu = require ( "prosemirror/dist/menu/menu" )
const SHADERS = require('../chunks/index.js') module.exports = /* glsl */ ` precision highp float; ${SHADERS.math.PI} ${SHADERS.sky} ${SHADERS.rgbm} ${SHADERS.gamma} ${SHADERS.encodeDecode} uniform vec3 uSunPosition; varying vec2 vTexCoord0; uniform bool uRGBM; void main() { //Texture coordinates to Normal is Based on //http://gl.ict.usc.edu/Data/HighResProbes/ // u=[0,2], v=[0,1], // theta=pi*(u-1), phi=pi*v // (Dx,Dy,Dz) = (sin(phi)*sin(theta), cos(phi), -sin(phi)*cos(theta)). float u = vTexCoord0.x; float v = 1.0 - vTexCoord0.y; // uv's a Y flipped in WebGL float theta = PI * (u * 2.0 - 1.0); float phi = PI * v; float x = sin(phi) * sin(theta); float y = cos(phi); float z = -sin(phi) * cos(theta); vec3 N = vec3(x, y, z); vec3 color = sky(uSunPosition, N); if (uRGBM) { gl_FragColor = encodeRGBM(color); } else { gl_FragColor.rgb = color; gl_FragColor.a = 1.0; } } `
var Q = require("q"); var quin = require("../quin"); var testGroup = { setUp: function (callback) { callback(); }, tearDown: function (callback) { callback(); }, "wrap() returns a wrapper function when supplied a promise": function (test) { var one = Q.denodeify(oneInput); //quin promise wrappers var validateMessage = quin.wrap(one); test.equal(typeof validateMessage, "function"); test.done(); }, "inject() returns a wrapper function when supplied a promise": function (test) { var one = Q.denodeify(oneInput); //quin promise wrappers var validateMessage = quin.inject(one); test.equal(typeof validateMessage, "function"); test.done(); }, "inject() can deal with no injected values": function (test) { var one = Q.denodeify(oneInput); var hasOne = quin.inject(one); one("in").then(hasOne).done(function () { test.done(); }); }, "inject() can deal with one injected value": function (test) { var one = Q.denodeify(oneInput); var expected = "value"; var hasTwo = quin.inject(Q.denodeify(verifyExtra), expected); one("in").then(hasTwo).done(function (injected) { test.equal(expected, injected); test.done(); }); }, "inject() can deal with more than one injected value": function (test) { var one = Q.denodeify(oneInput); var hasThree = quin.inject(Q.denodeify(returnsExtraAndMore), "extra", "more"); one("in").then(hasThree).done(function (obj) { test.equal(obj.more, "more"); test.equal(obj.extra, "extra"); test.done(); }); }, "inject() can deal with a null injected value": function (test) { var one = Q.denodeify(oneInput); var expected = null; var hasTwo = quin.inject(Q.denodeify(verifyExtra), expected); one("in").then(hasTwo).done(function (injected) { test.equal(expected, injected); test.done(); }); }, "inject() returns a null if a null promise was provided": function (test) { var one = Q.denodeify(oneInput); var expected = null; var hasTwo = quin.inject(null, expected); one("in").then(hasTwo).done(function () { test.done(); }); }, "inject() returns a function that can be called at the base of a promise chain": function (test) { var expected = "value"; var one = Q.denodeify(oneInput); var two = quin.denodeify(verifyExtra, expected); var newBase = quin.inject(one, "in"); newBase().then(two).done(function () { test.done(); }); }, "inject() returns a function that can be called at the base of a promise chain with a parameter": function (test) { var expected = "value"; var one = Q.denodeify(oneInput); var verify = quin.denodeify(verifyExtra, expected); var newBase = quin.inject(one); newBase("in").then(verify).done(function () { test.done(); }); }, "denodify() returns a promise if a standard callback is provided": function (test) { var expected = "validated"; var one = quin.denodeify(oneInput); var two = quin.denodeify(oneInput); var verify = quin.denodeify(verifyChain, test, expected); one(expected).then(two).then(verify).done(); }, //"all() injects dependency into all items in array": function (test: nodeunit.Test): void { // var expected = "validated"; // var one = quin.denodeify(oneInput); // var promise = Q.denodeify(twoInputs); // var two = quin.all([promise, promise], "injected"); // var verify = quin.denodeify(verifyChain, test, expected); // one(expected) // .then(two) // .then(verify) // .done(); //}, "Input from the top of the chain gets to the bottom with wrap": function (test) { //plain promises var getMessage = Q.denodeify(oneInput); var validate = Q.denodeify(twoInputs); //quin promise wrappers var validateMessage = quin.wrap(validate); var deleteMessage = quin.wrap(Q.denodeify(threeInputs)); var complete = quin.wrap(Q.denodeify(verifyChain)); getMessage("finished").then(validateMessage("a")).then(deleteMessage("a", "b")).then(complete(test, "finished")).done(); }, "Input from the top of the chain gets to the bottom with inject": function (test) { var context = console; //plain promises var getMessage = Q.denodeify(oneInput); var validate = Q.denodeify(twoInputs); var del = Q.denodeify(threeInputs); var final = Q.denodeify(verifyChain); //quin promises var validateMessage = quin.inject(validate, "a"); var deleteMessage = quin.inject(del, "a", "b"); var complete = quin.inject(final, test, "finished"); getMessage("finished").then(validateMessage).then(deleteMessage).then(complete).done(); }, "README example works": function (test) { var messageService = new MockService(); //plain old promises var getMessage = Q.denodeify(getIt); var validateMessage = Q.denodeify(validateIt); var del = Q.denodeify(deleteIt); //quin returns a promise proxy injecting the extra dependency var deleteMessage = quin.inject(del, messageService); //The purpose and the flow of the chain is easier to read now. getMessage(messageService).then(validateMessage).then(deleteMessage).done(function () { test.done(); }); } }; exports.activityTests = testGroup; //Test Functions function showResults(writer, result, cb) { cb(null); } function oneInput(input, cb) { cb(null, input); } function twoInputs(extra, input, cb) { cb(null, input); } function threeInputs(extra, more, input, cb) { cb(null, input); } function verifyChain(test, expected, actual, cb) { test.equal(expected, actual); test.done(); cb(null, ""); } function verifyExtra(extra, input, cb) { cb(null, extra); } function returnsExtraAndMore(extra, more, input, cb) { cb(null, { extra: extra, more: more }); } //README functions //needs the messageService so we pass it in at the start of the chain function getIt(messageService, cb) { messageService.getMsg(function (err, msg) { cb(null, msg); }); } //this function does not know or care about the messageService function validateIt(msg, cb) { if (msg.isGood == false) { cb(new Error("INVALID"), null); } cb(null, msg); } //this function needs the messageService to do it's work function deleteIt(messageService, msg, cb) { messageService.deleteMsg(msg, function () { cb(null, msg); }); } var MockService = (function () { function MockService() { } MockService.prototype.getMsg = function (cb) { cb(null, { id: "abc", isGood: true }); }; MockService.prototype.deleteMsg = function (msg, cb) { cb(null); }; return MockService; })(); //# sourceMappingURL=quin-test.js.map
import estap from '../../lib'; const test = estap(); estap.disableAutorun(); test('should pass', t => { t.pass(); });
import { connect } from 'react-redux' import SignUpForm from '../components/SignUpForm' import { signUpUser } from '../actions/SignUpFormActions' const mapStateToProps = (state, ownProps) => { return {} } const mapDispatchToProps = (dispatch) => { return { onSignUpFormSubmit: (name) => { event.preventDefault(); dispatch(signUpUser(name)) } } } const SignUpFormContainer = connect( mapStateToProps, mapDispatchToProps )(SignUpForm) export default SignUpFormContainer
/** * @author xialeistudio<home.xialei@gmail.com> */ window.onload = function() { cc.game.onStart = function() { cc.view.adjustViewPort(true); cc.view.setDesignResolutionSize(320, 504, cc.ResolutionPolicy.SHOW_ALL); cc.view.resizeWithBrowserSize(true); //load resources cc.LoaderScene.preload( [ 'res/background.png', 'res/hero1.png', 'res/bullet1.png', 'res/enemy1.png', 'res/bullet2.png', 'res/game_music.mp3', 'res/bullet.mp3', 'res/enemy1_down.mp3' ] , function() { /** * 游戏场景 * @type {void|*} */ var GameScene = cc.Scene.extend({ _enemies: [],//敌机列表 _enemyBullets: [],//敌机子弹 _plane: null,//我方飞机 _planeBullets: [],//我房子弹 _gameLayer: null, _hitCount: 0, life: 10, updateGame: function() { //我方子弹打中敌方飞机,敌方飞机和子弹消失 var planeRect = this._plane.getBoundingBox(); var _this = this; this._planeBullets.forEach(function(bullect) { var bulletRect = bullect.getBoundingBox(); _this._enemies.forEach(function(enemy) { var enemyRect = enemy.getBoundingBox(); if (cc.rectIntersectsRect(bulletRect, enemyRect)) { //移除敌方飞机和子弹 _this._hitCount++; cc.audioEngine.playEffect('res/enemy1_down.mp3'); var enemyName = enemy.getTag(); _this._enemies.splice(_this._enemies.indexOf(enemy), 1); _this._gameLayer.removeChild(enemy); //_this._enemyBullets.forEach(function(enemyBullet) { // if (enemyBullet.getTag().indexOf(enemyName) !== -1) { // _this._enemyBullets.splice(_this._enemyBullets.indexOf(enemyBullet), 1); // _this._gameLayer.removeChild(enemyBullet); // } //}); } }); }); //敌方子弹打中我方飞机,10次 this._enemyBullets.forEach(function(enemyBullet, enemyBulletIndex) { var bulletRect = enemyBullet.getBoundingBox(); if (cc.rectIntersectsRect(bulletRect, planeRect)) { _this.life--; if (_this.life <= 0) { cc.log('game over'); } // 移除子弹 _this._enemyBullets.splice(enemyBulletIndex, 1); _this._gameLayer.removeChild(enemyBullet); } }); //敌方飞机撞上我方飞机,游戏结束 this._enemies.forEach(function(enemy, enemyIndex) { var enemyRect = enemy.getBoundingBox(); if (cc.rectIntersectsRect(planeRect, enemyRect)) { _this.lift = 0; cc.log('game over'); // 移除飞机 _this._enemyBullets.splice(enemyIndex, 1); _this._gameLayer.removeChild(enemy); } }); _this._gameLayer.setHit(_this._hitCount); _this._gameLayer.setLife(_this.life); }, onEnter: function() { this._super(); var gameOver = false; var _this = this; //游戏层 _this._gameLayer = new GameLayer(); _this._gameLayer.init(); this.addChild(_this._gameLayer); // 音乐 cc.audioEngine.playMusic('res/game_music.mp3'); //添加飞机 this._plane = new PlaneSprite(); _this._gameLayer.addChild(this._plane); //子弹 var fireBullet = function() { //cc.log('fireBullet'); if (gameOver) { return; } var bullet = new PlaneBulletSprite(); var planeBulletSpeed = 2; bullet.setPosition(_this._plane.getPosition().x, 126 + 15); bullet.schedule(function() { this.setPosition(this.getPosition().x, this.getPosition().y + planeBulletSpeed); if (this.getPosition().x < 0 || this.getPosition().x > 320 - 5 / 2 || this.getPosition().y > 504) { _this._planeBullets.splice(_this._planeBullets.indexOf(this), 1); _this._gameLayer.removeChild(this); } }, 0, null, 0); _this._gameLayer.addChild(bullet); _this._planeBullets.push(bullet); cc.audioEngine.playEffect('res/bullet.mp3'); }; this.schedule(fireBullet, 0.3, null, 0); //敌机 var enemyPlaneAction = function() { //cc.log('enemyPlane'); if (gameOver) { return; } var enemyPlane = new EnemyPlaneSprite(); var enemyPlaneSpeed = 1; var originX = Math.random(); enemyPlane.setTag('enemy-' + Math.random()); enemyPlane.setPosition(originX * 320, 480); enemyPlane.schedule(function() { this.setPosition(this.getPosition().x, this.getPosition().y - enemyPlaneSpeed); if (this.getPosition().x < 0 || this.getPosition().x > 320 - 5 / 2 || this.getPosition().y < 0) { _this._enemies.splice(_this._enemies.indexOf(this), 1); _this._gameLayer.removeChild(this); } }, 0, null, 0); //敌机生成子弹 enemyPlane.schedule(function() { var bullet = new EnemyPlaneBulletSprite(); var bulletSpeed = 2; bullet.setPosition(this.getPosition().x + 57 / 2, this.getPosition().y); //敌机子弹动作 bullet.schedule(function() { bullet.setPosition(bullet.getPosition().x, bullet.getPosition().y - bulletSpeed); if (bullet.getPosition().x < 0 || bullet.getPosition().x > 320 - 5 / 2 || bullet.getPosition().y > 504 || bullet.getPosition().y < 0) { _this._enemyBullets.splice(_this._enemyBullets.indexOf(bullet), 1); _this._gameLayer.removeChild(bullet); } }, 0, null, 0); _this._gameLayer.addChild(bullet); bullet.setTag('enemybullet-' + enemyPlane.getTag()); _this._enemyBullets.push(bullet); }, 1, null, 0); _this._gameLayer.addChild(enemyPlane); _this._enemies.push(enemyPlane); }; this.schedule(enemyPlaneAction, 2, null, 0); // 更新游戏 this.schedule(this.updateGame); } }); /** * 游戏层 * @type {void|*} */ var GameLayer = cc.Layer.extend({ _lifeLabel: null, _hitLabel: null, init: function() { this._super(); var size = cc.director.getWinSize(); var layer = cc.Layer.create(); //添加背景 var bg = cc.Sprite.create('res/background.png'); bg.setAnchorPoint(0, 0); bg.setPosition(0, 0); layer.addChild(bg); //敌机浮层 this._lifeLabel = cc.LabelTTF.create('life: 10', 'Arial', 16, null, cc.TEXT_ALIGNMENT_RIGHT, cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM); this._lifeLabel.setPosition(size.width - 10, size.height - 30); this._lifeLabel.setAnchorPoint(1, 0); layer.addChild(this._lifeLabel); //生命浮层 this._hitLabel = cc.LabelTTF.create('hit: 0', 'Arial', 16, null, cc.TEXT_ALIGNMENT_RIGHT, cc.VERTICAL_TEXT_ALIGNMENT_BOTTOM); this._hitLabel.setPosition(size.width - 10, size.height - 50); this._hitLabel.setAnchorPoint(1, 0); layer.addChild(this._hitLabel); this.addChild(layer); return true; }, setHit: function(number) { this._hitLabel.setString('hit: ' + number); }, setLife: function(number) { this._lifeLabel.setString('life: ' + number); } }); /** * 飞机 * @type {void|*} */ var PlaneSprite = cc.Sprite.extend({ ctor: function() { this._super(); var size = cc.director.getWinSize(); this.initWithFile('res/hero1.png'); //this.setAnchorPoint(0, 0); this.setPosition(size.width / 2, 63); var _this = this; //注册事件 var listener = cc.EventListener.create({ event: cc.EventListener.TOUCH_ONE_BY_ONE, swallowTouches: true, onTouchBegan: function(touch, event) { //cc.log('on touch began'); return true; }, onTouchMoved: function(touch, event) { //cc.log('on touch move'); var point = touch.getLocation(); //边界监测 if (point.x > size.width - 102 / 2) { point.x = size.width - 102 / 2; } if (point.x <= 61) { point.x = 61; } _this.setPositionX(point.x); }, onTouchEnded: function(touch, event) { } }); cc.eventManager.addListener(listener, this); } }); /** * 飞机子弹 * @type {void|*} */ var PlaneBulletSprite = cc.Sprite.extend({ ctor: function() { this._super(); //var size = cc.director.getWinSize(); this.initWithFile('res/bullet1.png'); } }); /** * 敌机 * @type {void|*} */ var EnemyPlaneSprite = cc.Sprite.extend({ ctor: function() { this._super(); this.initWithFile('res/enemy1.png'); this.setAnchorPoint(0, 0); } }); /** * 敌机子弹 * @type {void|*} */ var EnemyPlaneBulletSprite = cc.Sprite.extend({ ctor: function() { this._super(); this.initWithFile('res/bullet2.png'); } }); cc.director.runScene(new GameScene); }, this); }; cc.game.run("gameCanvas"); };
'use strict'; /** Load Node.js modules. */ var fs = require('fs'); /** Load other modules. */ var _ = require('lodash-compat'); /** Used to minify variables and string values to a single character. */ var minNames = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'.split(''); minNames.push.apply(minNames, minNames.map(function(value) { return value + value; })); /** Used to protect the specified properties from getting minified. */ var propWhitelist = _.union( _.keys(_), _.keys(_.prototype), _.keys(_.support), _.keys(_.templateSettings), [ 'BYTES_PER_ELEMENT', 'NEGATIVE_INFINITY', 'POSITIVE_INFINITY', 'Array', 'ArrayBuffer', 'Boolean', 'Cache', 'Date', 'Error', 'Float32Array', 'Float64Array', 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Math', 'Number', 'Object', 'RegExp', 'Set', 'String', 'TypeError', 'Uint8Array', 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', 'WinRTError', '__actions__', '__chain__', '__data__', '__dir__', '__filtered__', '__iteratees__', '__takeCount__', '__views__', '__wrapped__', 'add', 'args', 'amd', 'buffer', 'byteLength', 'cache', 'cancel', 'clearTimeout', 'count', 'createDocumentFragment', 'criteria', 'data', 'delete', 'document', 'done', 'end', 'exports', 'func', 'get', 'global', 'has', 'hash', 'index', 'iteratee', 'leading', 'length', 'limit', 'maxWait', 'name', 'nodeType', 'omission', 'placeholder', 'self', 'separator', 'set', 'setTimeout', 'size', 'source', 'sourceURL', 'start', 'thisArg', 'trailing', 'type', 'value', 'window' ]); /*----------------------------------------------------------------------------*/ /** * Pre-process a given lodash `source`, preparing it for minification. * * @param {string} [source=''] The source to process. * @param {Object} [options={}] The options object. * @returns {string} Returns the processed source. */ function preprocess(source, options) { source || (source = ''); options || (options = {}); // Remove unrecognized JSDoc tags so the Closure Compiler won't complain. source = source.replace(/@(?:alias|category)\b.*/g, ''); if (options.isTemplate) { return source; } // Remove whitespace from `_.template` related regexes. source = source.replace(/(reEmptyString\w+\s*=)([\s\S]+?)(?=[,;]\n)/g, function(match, left, value) { return left + value.replace(/\s|\\n/g, ''); }); // Remove whitespace from `_.template`. source = source.replace(/^( *)function template\b[\s\S]+?\n\1}/m, function(snippet) { // Remove whitespace from string literals. snippet = snippet.replace(/^((?:[ "'$\w]+:)?\s*)"[^"\n\\]*?(?:\\.[^"\n\\]*?)*"|'[^'\n\\]*?(?:\\.[^'\n\\]*?)*'/gm, function(string, left) { // Clip `string` after an object literal property name or leading spaces. if (left) { string = string.slice(left.length); } // Avoids removing the '\n' of the `stringEscapes` object. string = string.replace(/\[object |delete |else (?!{)|function | in | instanceof |return\s+["'$\w]|throw |typeof |use strict|var |# |(["'])(?:\\n| )\1|\\\\n|\\n|\s+/g, function(match) { return match == false || match == '\\n' ? '' : match; }); // Unclip `string`. return (left || '') + string; }); // Remove newline from double-quoted strings. snippet = snippet .replace('"__p += \'"', '"__p+=\'"') .replace('"\';\\n"', '"\';"'); // Add a newline back so "evaluate" delimiters can support single line comments. snippet = snippet.replace('";__p+=\'"', '";\\n__p+=\'"'); // Remove default `sourceURL` value. return snippet.replace(/^( *var\s+sourceURL\s*=\s*)[\s\S]+?(?=;\n$)/m, function(match, left) { return left + "'sourceURL' in options ? '//# sourceURL=' + options.sourceURL + '\\n' : ''"; }); }); // Minify internal properties. (function() { var funcNames = [ 'baseSortBy', 'baseSortByOrder', 'compareAscending', 'compareMultiple', 'sortBy' ]; var props = [ 'criteria', 'index', 'value' ]; // Minify properties used in `funcNames` functions. var snippets = source.match(RegExp('^( *)(?:var|function) +(?:' + funcNames.join('|') + ')\\b[\\s\\S]+?\\n\\1}', 'gm')); _.each(snippets, function(snippet) { var modified = snippet; _.each(props, function(prop, index) { var minName = minNames[index], reBracketProp = RegExp("\\['(" + prop + ")'\\]", 'g'), reDotProp = RegExp('\\.' + prop + '\\b', 'g'), rePropColon = RegExp("([^?\\s])\\s*([\"'])?\\b" + prop + "\\2\\s*:", 'g'); modified = modified .replace(reBracketProp, "['" + minName + "']") .replace(reDotProp, "['" + minName + "']") .replace(rePropColon, "$1'" + minName + "':"); }); // Replace with modified snippet. source = source.replace(snippet, function() { return modified; }); }); }()); // Add brackets to whitelisted properties so the Closure Compiler won't mung them. // See http://code.google.com/closure/compiler/docs/api-tutorial3.html#export. return source.replace(RegExp('(["\'])(?:(?!\\1)[^\\n\\\\]|\\\\.)*\\1|\\.(' + propWhitelist.join('|') + ')\\b', 'g'), function(match, quote, prop) { return quote ? match : "['" + prop + "']"; }); } /*----------------------------------------------------------------------------*/ // Export `preprocess`. if (module != require.main) { module.exports = preprocess; } // Read the lodash source file from the first argument if the script was invoked // by the command-line (e.g. `node pre-compile.js source.js`) and write to the same file. else if (_.size(process.argv) > 2) { (function() { var filePath = path.normalize(_.last(process.argv)), isTemplate = _.includes(process.argv, '-t') || _.includes(process.argv, '--template'), source = fs.readFileSync(filePath, 'utf8'); fs.writeFileSync(filePath, preprocess(source, { 'isTemplate': isTemplate }), 'utf8'); }()); }
Ember.TEMPLATES["unit-controllers"] = Ember.Handlebars.compile( '<div class="unit-controllers">{{render "rendered" someModel className="asd"}}</div>' ); //-------------------------------------------------------------------------- module("templates - controllers - full environment", { setup: function() { var container = new Ember.Container(); container.register("template:rendered", Ember.Handlebars.compile("controller stub"), {instantiate: false}); container.register("view:rendered", Ember.View); container.register("controller:rendered", Ember.Controller); var view = Ember.View.create({ controller: Ember.Controller.create({ container: container }), template: Ember.TEMPLATES["unit-controllers"] }); Ember.run(function() { view.appendTo("#qunit-fixture"); }); } }); test("template renders correctly", function() { equal(Ember.$("#qunit-fixture .unit-controllers").text(), "controller stub"); }); module("templates - controllers - stubbing helper", { setup: function() { sinon.stub(Ember.Handlebars.helpers, 'render').returns(new Handlebars.SafeString("controller stub")); var view = Ember.View.create({ template: Ember.TEMPLATES["unit-controllers"] }); Ember.run(function() { view.appendTo("#qunit-fixture"); }); } }); test("template renders correctly", function() { equal(Ember.$("#qunit-fixture .unit-controllers").text(), "controller stub"); });
'use babel' import util from 'util' import { exec } from 'child_process' import applescript from 'applescript' import { Errors } from './constants' const runscript = (file) => new Promise((resolve, reject) => { applescript.execFile(file, (error, result) => { if (error) { reject(error) } try { if (result) { resolve(JSON.parse(result)) } else { reject(new Error(Errors.NO_DATA)) } } catch (e) { reject(new Error(Errors.JSON_PARSE_ERROR)) } }); }) const getState = () => runscript(`${__dirname}/scripts/getState.applescript`) const getTrack = () => runscript(`${__dirname}/scripts/getTrack.applescript`) export default { getState, getTrack }
/*! * CanJS - 2.2.5 * http://canjs.com/ * Copyright (c) 2015 Bitovi * Wed, 22 Apr 2015 15:03:29 GMT * Licensed MIT */ /*can@2.2.5#view/elements*/ var can = require('../util/util.js'); require('./view.js'); var doc = typeof document !== 'undefined' ? document : null; var selectsCommentNodes = doc && function () { return can.$(document.createComment('~')).length === 1; }(); var elements = { tagToContentPropMap: { option: doc && 'textContent' in document.createElement('option') ? 'textContent' : 'innerText', textarea: 'value' }, attrMap: can.attr.map, attrReg: /([^\s=]+)[\s]*=[\s]*/, defaultValue: can.attr.defaultValue, tagMap: { '': 'span', colgroup: 'col', table: 'tbody', tr: 'td', ol: 'li', ul: 'li', tbody: 'tr', thead: 'tr', tfoot: 'tr', select: 'option', optgroup: 'option' }, reverseTagMap: { col: 'colgroup', tr: 'tbody', option: 'select', td: 'tr', th: 'tr', li: 'ul' }, getParentNode: function (el, defaultParentNode) { return defaultParentNode && el.parentNode.nodeType === 11 ? defaultParentNode : el.parentNode; }, setAttr: can.attr.set, getAttr: can.attr.get, removeAttr: can.attr.remove, contentText: function (text) { if (typeof text === 'string') { return text; } if (!text && text !== 0) { return ''; } return '' + text; }, after: function (oldElements, newFrag) { var last = oldElements[oldElements.length - 1]; if (last.nextSibling) { can.insertBefore(last.parentNode, newFrag, last.nextSibling); } else { can.appendChild(last.parentNode, newFrag); } }, replace: function (oldElements, newFrag) { elements.after(oldElements, newFrag); if (can.remove(can.$(oldElements)).length < oldElements.length && !selectsCommentNodes) { can.each(oldElements, function (el) { if (el.nodeType === 8) { el.parentNode.removeChild(el); } }); } } }; can.view.elements = elements; module.exports = elements;
import Resolver from 'ember/resolver'; var CustomResolver = Resolver.extend({ moduleNameLookupPatterns: Ember.computed(function() { var defaults = this._super(); return defaults.concat([ this.podBasedComponentsInResource ]); }), podBasedComponentsInResource: function(parsedName) { var podPrefix = this.namespace.podModulePrefix || this.namespace.modulePrefix; if (parsedName.type === 'component' || parsedName.fullNameWithoutType.match(/^components/)) { var nameWithoutComponent = parsedName.fullNameWithoutType.replace(/components\//, ''); var slash = nameWithoutComponent.lastIndexOf('/'); if (slash > 0) { podPrefix = podPrefix + "/" + nameWithoutComponent.substr(0, slash); parsedName.fullNameWithoutType = nameWithoutComponent.substr(slash + 1); return this.podBasedLookupWithPrefix(podPrefix, parsedName); } } }, podBasedComponentsInSubdir: function(parsedName) { var podPrefix = this.namespace.modulePrefix; // this.namespace.podModulePrefix || this.namespace.modulePrefix podPrefix = podPrefix + '/components'; if (parsedName.type === 'component' || parsedName.fullNameWithoutType.match(/^components/)) { return this.podBasedLookupWithPrefix(podPrefix, parsedName); } } }); export default CustomResolver
import Element from '../../../shared/Element'; import Elements from '../../../shared/Elements'; import link from '../../../shared/link'; import { isNormalElement } from '../../../shared/helper'; export function createElements(elements, parent) { elements.forEach( element => appendElement(element, parent) ); return parent; } export function appendElement(element, parent) { parent.appendChild(createElement(element, parent)); } export function createElement(element) { const {props, tag, children} = element; let node; if (Element.isInstance(element)) { node = document.createElement(tag); createElements(children, node); // children if (isNormalElement(element)) { // only link normal nodes link(node, element); } setProps(node, { tag, type: props.type , props }); // props } else if (Elements.isInstance(element)) { const node = document.createDocumentFragment(); // package createElements(element, node); } else { node = document.createTextNode(element); } return node; } const acceptValue = (tag) => ['input', 'textarea', 'option', 'select', 'progress'].includes(tag); const mustUseProp = (tag, type, attr) => ( (attr === 'value' && acceptValue(tag)) && type !== 'button' || (attr === 'selected' && tag === 'option') || (attr === 'checked' && tag === 'input') || (attr === 'muted' && tag === 'video') ); export function setProps(node, {tag, type, props}) { Object.keys(props).forEach((name) => { if (mustUseProp(tag, type, name)) { node[name] = props[name]; } else { node.setAttribute(name, props[name]); } }); } export function setStyle(node, styles) { Object.assign(node.style, styles); }
(function () { 'use strict'; angular .module('mainApp', []); })();
const Rebase = require('../../../src/rebase'); const React = require('react'); const ReactDOM = require('react-dom'); const firebase = require('firebase'); require('firebase/firestore'); var dummyCollection = require('../../fixtures/dummyCollection'); var firebaseConfig = require('../../fixtures/config'); describe('get()', function() { var base; var testApp; var collectionPath = 'testCollection'; var collectionRef; var app; function seedCollection() { const docs = dummyCollection.map((doc, index) => { const docRef = collectionRef.doc(`doc-${index + 1}`); return docRef.set(doc); }); return Promise.all(docs); } beforeAll(() => { testApp = firebase.initializeApp(firebaseConfig, 'DB_CHECK'); collectionRef = testApp.firestore().collection(collectionPath); var mountNode = document.createElement('div'); mountNode.setAttribute('id', 'mount'); document.body.appendChild(mountNode); }); afterAll(done => { var mountNode = document.getElementById('mount'); mountNode.parentNode.removeChild(mountNode); testApp.delete().then(done); }); beforeEach(done => { app = firebase.initializeApp(firebaseConfig); var db = firebase.firestore(app); base = Rebase.createClass(db); seedCollection().then(done); }); afterEach(done => { ReactDOM.unmountComponentAtNode(document.body); Promise.all([ collectionRef.get().then(docs => { const deleteOps = []; docs.forEach(doc => { deleteOps.push(doc.ref.delete()); }); return Promise.all(deleteOps); }), app.delete() ]) .then(done) .catch(err => done.fail(err)); }); it('get() validates endpoint', done => { try { base.get('').then(() => { done.fail('error should thrown'); }); } catch (err) { expect(err).not.toBeNull(err); done(); } }); describe('Async tests', function() { it('get() resolves with data from a collection', done => { base .get(collectionPath) .then(data => { expect(data.length).toEqual(5); done(); }) .catch(err => done.fail(err)); }); it('get() resolves with data from a collection query', done => { base .get(`${collectionPath}`, { query: ref => ref .where('id', '<', 5) .where('id', '>', 2) .orderBy('id') }) .then(data => { expect(data.length).toEqual(2); expect(data[0].name).toEqual('Document 3'); expect(data[1].name).toEqual('Document 4'); done(); }) .catch(err => done.fail(err)); }); it('get() rejects if collection query returns no results', done => { base .get(`${collectionPath}`, { query: ref => ref.where('id', '>', 5).orderBy('id') }) .then(data => { done.fail('query should reject'); }) .catch(err => { expect(err.message).toEqual('No Result'); done(); }); }); it('get() rejects if document does not exist', done => { base .get(`${collectionPath}/nodoc`) .then(data => { done.fail('query should reject'); }) .catch(err => { expect(err.message).toEqual('No Result'); done(); }); }); it('get() resolves with a document', done => { base .get(`${collectionPath}/doc-1`) .then(data => { expect(data.name).toEqual(dummyCollection[0].name); done(); }) .catch(err => done.fail(err)); }); it('get() accepts a document reference', done => { const docRef = app .firestore() .collection('testCollection') .doc('doc-1'); base .get(docRef) .then(data => { expect(data.name).toEqual(dummyCollection[0].name); done(); }) .catch(err => done.fail(err)); }); it('get() accepts a collection reference', done => { const testRef = app.firestore().collection('testCollection'); base .get(testRef) .then(data => { expect(data[0].name).toEqual(dummyCollection[0].name); done(); }) .catch(err => done.fail(err)); }); it('get() rejects Promise when read fails or is denied', done => { base .get('/readFail') .then(() => { done.fail('Promise should reject'); }) .catch(err => { expect(err.code).toContain('permission-denied'); done(); }); }); }); });
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var informationCircled = exports.informationCircled = { "viewBox": "0 0 512 512", "children": [{ "name": "g", "attribs": {}, "children": [{ "name": "path", "attribs": { "d": "M480,253C478.3,129.3,376.7,30.4,253,32S30.4,135.3,32,259c1.7,123.7,103.3,222.6,227,221C382.7,478.3,481.7,376.7,480,253\r\n\t\tz M256,111.9c17.7,0,32,14.3,32,32s-14.3,32-32,32c-17.7,0-32-14.3-32-32S238.3,111.9,256,111.9z M300,395h-88v-11h22V224h-22v-12\r\n\t\th66v172h22V395z" }, "children": [{ "name": "path", "attribs": { "d": "M480,253C478.3,129.3,376.7,30.4,253,32S30.4,135.3,32,259c1.7,123.7,103.3,222.6,227,221C382.7,478.3,481.7,376.7,480,253\r\n\t\tz M256,111.9c17.7,0,32,14.3,32,32s-14.3,32-32,32c-17.7,0-32-14.3-32-32S238.3,111.9,256,111.9z M300,395h-88v-11h22V224h-22v-12\r\n\t\th66v172h22V395z" }, "children": [] }] }] }] };
var webpack = require('webpack'); var path = require('path'); module.exports = { devtool: 'eval', entry: [ 'webpack-dev-server/client?http://127.0.0.1:3000', // WebpackDevServer host and port 'webpack/hot/only-dev-server', './src/js/index.js' // Your appʼs entry point ], output: { path: path.join(__dirname, 'build'), filename: 'bundle.js', publicPath: '/static/' }, module: { loaders: [ { test: /\.less$/, loader: 'style-loader!css-loader!less-loader' }, { test: /\.css$/, loader: 'style-loader!css-loader' }, { test: /\.(png|jpg)$/, loader: 'url-loader?limit=8192'}, { test: /\.js?$/, loaders: ['react-hot', 'babel'], include: [path.join(__dirname, 'src/js')]} ] }, resolve: { root: [path.resolve(__dirname)], extensions: ['', '.js', '.jsx'] }, plugins: [ new webpack.HotModuleReplacementPlugin() ] };
import { expect } from 'chai'; import request from '../src/reqwest-fetch'; /* eslint func-names: 0 */ /* eslint prefer-arrow-callback: 0 */ describe('reqwest-fetch', function () { it('should accept json response', function () { this.timeout(10000); const test = request({ url: 'https://o.hahoo.cn/test.json' }) .then(function (res) { expect(res.body).to.eql({ foo: 'bar' }); }); return test; }); });
$.extend( $.fn, { // http://jqueryvalidation.org/validate/ validate: function( options ) { // If nothing is selected, return nothing; can't chain anyway if ( !this.length ) { if ( options && options.debug && window.console ) { console.warn( "Nothing selected, can't validate, returning nothing." ); } return; } // Check if a validator for this form was already created var validator = $.data( this[ 0 ], "validator" ); if ( validator ) { return validator; } // Add novalidate tag if HTML5. this.attr( "novalidate", "novalidate" ); validator = new $.validator( options, this[ 0 ] ); $.data( this[ 0 ], "validator", validator ); if ( validator.settings.onsubmit ) { this.on( "click.validate", ":submit", function( event ) { if ( validator.settings.submitHandler ) { validator.submitButton = event.target; } // Allow suppressing validation by adding a cancel class to the submit button if ( $( this ).hasClass( "cancel" ) ) { validator.cancelSubmit = true; } // Allow suppressing validation by adding the html5 formnovalidate attribute to the submit button if ( $( this ).attr( "formnovalidate" ) !== undefined ) { validator.cancelSubmit = true; } } ); // Validate the form on submit this.on( "submit.validate", function( event ) { if ( validator.settings.debug ) { // Prevent form submit to be able to see console output event.preventDefault(); } function handle() { var hidden, result; if ( validator.settings.submitHandler ) { if ( validator.submitButton ) { // Insert a hidden input as a replacement for the missing submit button hidden = $( "<input type='hidden'/>" ) .attr( "name", validator.submitButton.name ) .val( $( validator.submitButton ).val() ) .appendTo( validator.currentForm ); } result = validator.settings.submitHandler.call( validator, validator.currentForm, event ); if ( validator.submitButton ) { // And clean up afterwards; thanks to no-block-scope, hidden can be referenced hidden.remove(); } if ( result !== undefined ) { return result; } return false; } return true; } // Prevent submit for invalid forms or custom submit handlers if ( validator.cancelSubmit ) { validator.cancelSubmit = false; return handle(); } if ( validator.form() ) { if ( validator.pendingRequest ) { validator.formSubmitted = true; return false; } return handle(); } else { validator.focusInvalid(); return false; } } ); } return validator; }, // http://jqueryvalidation.org/valid/ valid: function() { var valid, validator, errorList; if ( $( this[ 0 ] ).is( "form" ) ) { valid = this.validate().form(); } else { errorList = []; valid = true; validator = $( this[ 0 ].form ).validate(); this.each( function() { valid = validator.element( this ) && valid; errorList = errorList.concat( validator.errorList ); } ); validator.errorList = errorList; } return valid; }, // http://jqueryvalidation.org/rules/ rules: function( command, argument ) { var element = this[ 0 ], settings, staticRules, existingRules, data, param, filtered; if ( command ) { settings = $.data( element.form, "validator" ).settings; staticRules = settings.rules; existingRules = $.validator.staticRules( element ); switch ( command ) { case "add": $.extend( existingRules, $.validator.normalizeRule( argument ) ); // Remove messages from rules, but allow them to be set separately delete existingRules.messages; staticRules[ element.name ] = existingRules; if ( argument.messages ) { settings.messages[ element.name ] = $.extend( settings.messages[ element.name ], argument.messages ); } break; case "remove": if ( !argument ) { delete staticRules[ element.name ]; return existingRules; } filtered = {}; $.each( argument.split( /\s/ ), function( index, method ) { filtered[ method ] = existingRules[ method ]; delete existingRules[ method ]; if ( method === "required" ) { $( element ).removeAttr( "aria-required" ); } } ); return filtered; } } data = $.validator.normalizeRules( $.extend( {}, $.validator.classRules( element ), $.validator.attributeRules( element ), $.validator.dataRules( element ), $.validator.staticRules( element ) ), element ); // Make sure required is at front if ( data.required ) { param = data.required; delete data.required; data = $.extend( { required: param }, data ); $( element ).attr( "aria-required", "true" ); } // Make sure remote is at back if ( data.remote ) { param = data.remote; delete data.remote; data = $.extend( data, { remote: param } ); } return data; } } ); // Custom selectors $.extend( $.expr[ ":" ], { // http://jqueryvalidation.org/blank-selector/ blank: function( a ) { return !$.trim( "" + $( a ).val() ); }, // http://jqueryvalidation.org/filled-selector/ filled: function( a ) { return !!$.trim( "" + $( a ).val() ); }, // http://jqueryvalidation.org/unchecked-selector/ unchecked: function( a ) { return !$( a ).prop( "checked" ); } } ); // Constructor for validator $.validator = function( options, form ) { this.settings = $.extend( true, {}, $.validator.defaults, options ); this.currentForm = form; this.init(); }; // http://jqueryvalidation.org/jQuery.validator.format/ $.validator.format = function( source, params ) { if ( arguments.length === 1 ) { return function() { var args = $.makeArray( arguments ); args.unshift( source ); return $.validator.format.apply( this, args ); }; } if ( arguments.length > 2 && params.constructor !== Array ) { params = $.makeArray( arguments ).slice( 1 ); } if ( params.constructor !== Array ) { params = [ params ]; } $.each( params, function( i, n ) { source = source.replace( new RegExp( "\\{" + i + "\\}", "g" ), function() { return n; } ); } ); return source; }; $.extend( $.validator, { defaults: { messages: {}, groups: {}, rules: {}, errorClass: "error", pendingClass: "pending", validClass: "valid", errorElement: "label", focusCleanup: false, focusInvalid: true, errorContainer: $( [] ), errorLabelContainer: $( [] ), onsubmit: true, ignore: ":hidden", ignoreTitle: false, onfocusin: function( element ) { this.lastActive = element; // Hide error label and remove error class on focus if enabled if ( this.settings.focusCleanup ) { if ( this.settings.unhighlight ) { this.settings.unhighlight.call( this, element, this.settings.errorClass, this.settings.validClass ); } this.hideThese( this.errorsFor( element ) ); } }, onfocusout: function( element ) { if ( !this.checkable( element ) && ( element.name in this.submitted || !this.optional( element ) ) ) { this.element( element ); } }, onkeyup: function( element, event ) { // Avoid revalidate the field when pressing one of the following keys // Shift => 16 // Ctrl => 17 // Alt => 18 // Caps lock => 20 // End => 35 // Home => 36 // Left arrow => 37 // Up arrow => 38 // Right arrow => 39 // Down arrow => 40 // Insert => 45 // Num lock => 144 // AltGr key => 225 var excludedKeys = [ 16, 17, 18, 20, 35, 36, 37, 38, 39, 40, 45, 144, 225 ]; if ( event.which === 9 && this.elementValue( element ) === "" || $.inArray( event.keyCode, excludedKeys ) !== -1 ) { return; } else if ( element.name in this.submitted || this.isValidElement( element ) ) { this.element( element ); } }, onclick: function( element ) { // Click on selects, radiobuttons and checkboxes if ( element.name in this.submitted ) { this.element( element ); // Or option elements, check parent select in that case } else if ( element.parentNode.name in this.submitted ) { this.element( element.parentNode ); } }, highlight: function( element, errorClass, validClass ) { if ( element.type === "radio" ) { this.findByName( element.name ).addClass( errorClass ).removeClass( validClass ); } else { $( element ).addClass( errorClass ).removeClass( validClass ); } }, unhighlight: function( element, errorClass, validClass ) { if ( element.type === "radio" ) { this.findByName( element.name ).removeClass( errorClass ).addClass( validClass ); } else { $( element ).removeClass( errorClass ).addClass( validClass ); } } }, // http://jqueryvalidation.org/jQuery.validator.setDefaults/ setDefaults: function( settings ) { $.extend( $.validator.defaults, settings ); }, messages: { required: "This field is required.", remote: "Please fix this field.", email: "Please enter a valid email address.", url: "Please enter a valid URL.", date: "Please enter a valid date.", dateISO: "Please enter a valid date ( ISO ).", number: "Please enter a valid number.", digits: "Please enter only digits.", equalTo: "Please enter the same value again.", maxlength: $.validator.format( "Please enter no more than {0} characters." ), minlength: $.validator.format( "Please enter at least {0} characters." ), rangelength: $.validator.format( "Please enter a value between {0} and {1} characters long." ), range: $.validator.format( "Please enter a value between {0} and {1}." ), max: $.validator.format( "Please enter a value less than or equal to {0}." ), min: $.validator.format( "Please enter a value greater than or equal to {0}." ) }, autoCreateRanges: false, prototype: { init: function() { this.labelContainer = $( this.settings.errorLabelContainer ); this.errorContext = this.labelContainer.length && this.labelContainer || $( this.currentForm ); this.containers = $( this.settings.errorContainer ).add( this.settings.errorLabelContainer ); this.submitted = {}; this.valueCache = {}; this.pendingRequest = 0; this.pending = {}; this.invalid = {}; this.reset(); var groups = ( this.groups = {} ), rules; $.each( this.settings.groups, function( key, value ) { if ( typeof value === "string" ) { value = value.split( /\s/ ); } $.each( value, function( index, name ) { groups[ name ] = key; } ); } ); rules = this.settings.rules; $.each( rules, function( key, value ) { rules[ key ] = $.validator.normalizeRule( value ); } ); function delegate( event ) { var validator = $.data( this.form, "validator" ), eventType = "on" + event.type.replace( /^validate/, "" ), settings = validator.settings; if ( settings[ eventType ] && !$( this ).is( settings.ignore ) ) { settings[ eventType ].call( validator, this, event ); } } $( this.currentForm ) .on( "focusin.validate focusout.validate keyup.validate", ":text, [type='password'], [type='file'], select, textarea, [type='number'], [type='search'], " + "[type='tel'], [type='url'], [type='email'], [type='datetime'], [type='date'], [type='month'], " + "[type='week'], [type='time'], [type='datetime-local'], [type='range'], [type='color'], " + "[type='radio'], [type='checkbox'], [contenteditable]", delegate ) // Support: Chrome, oldIE // "select" is provided as event.target when clicking a option .on( "click.validate", "select, option, [type='radio'], [type='checkbox']", delegate ); if ( this.settings.invalidHandler ) { $( this.currentForm ).on( "invalid-form.validate", this.settings.invalidHandler ); } // Add aria-required to any Static/Data/Class required fields before first validation // Screen readers require this attribute to be present before the initial submission http://www.w3.org/TR/WCAG-TECHS/ARIA2.html $( this.currentForm ).find( "[required], [data-rule-required], .required" ).attr( "aria-required", "true" ); }, // http://jqueryvalidation.org/Validator.form/ form: function() { this.checkForm(); $.extend( this.submitted, this.errorMap ); this.invalid = $.extend( {}, this.errorMap ); if ( !this.valid() ) { $( this.currentForm ).triggerHandler( "invalid-form", [ this ] ); } this.showErrors(); return this.valid(); }, checkForm: function() { this.prepareForm(); for ( var i = 0, elements = ( this.currentElements = this.elements() ); elements[ i ]; i++ ) { this.check( elements[ i ] ); } return this.valid(); }, // http://jqueryvalidation.org/Validator.element/ element: function( element ) { var cleanElement = this.clean( element ), checkElement = this.validationTargetFor( cleanElement ), result = true; if ( checkElement === undefined ) { delete this.invalid[ cleanElement.name ]; } else { this.prepareElement( checkElement ); this.currentElements = $( checkElement ); result = this.check( checkElement ) !== false; if ( result ) { this.invalid[ checkElement.name ] = false; } else { this.invalid[ checkElement.name ] = true; } } // Add aria-invalid status for screen readers $( element ).attr( "aria-invalid", !result ); if ( !this.numberOfInvalids() ) { // Hide error containers on last error this.toHide = this.toHide.add( this.containers ); } this.showErrors(); return result; }, // http://jqueryvalidation.org/Validator.showErrors/ showErrors: function( errors ) { if ( errors ) { // Add items to error list and map $.extend( this.errorMap, errors ); this.errorList = []; for ( var name in errors ) { this.errorList.push( { message: errors[ name ], element: this.findByName( name )[ 0 ] } ); } // Remove items from success list this.successList = $.grep( this.successList, function( element ) { return !( element.name in errors ); } ); } if ( this.settings.showErrors ) { this.settings.showErrors.call( this, this.errorMap, this.errorList ); } else { this.defaultShowErrors(); } }, // http://jqueryvalidation.org/Validator.resetForm/ resetForm: function() { if ( $.fn.resetForm ) { $( this.currentForm ).resetForm(); } this.submitted = {}; this.prepareForm(); this.hideErrors(); var i, elements = this.elements() .removeData( "previousValue" ) .removeAttr( "aria-invalid" ); if ( this.settings.unhighlight ) { for ( i = 0; elements[ i ]; i++ ) { this.settings.unhighlight.call( this, elements[ i ], this.settings.errorClass, "" ); } } else { elements.removeClass( this.settings.errorClass ); } }, numberOfInvalids: function() { return this.objectLength( this.invalid ); }, objectLength: function( obj ) { /* jshint unused: false */ var count = 0, i; for ( i in obj ) { if ( obj[ i ] ) { count++; } } return count; }, hideErrors: function() { this.hideThese( this.toHide ); }, hideThese: function( errors ) { errors.not( this.containers ).text( "" ); this.addWrapper( errors ).hide(); }, valid: function() { return this.size() === 0; }, // Check if the given element is valid // return // true If the field is valid // false If the field is invalid // undefined If the field is not validated yet. // // Note that this method assumes that you have // already called `validate()` on your form isValidElement: function( element ) { return this.invalid[ element.name ] === undefined ? undefined : !this.invalid[ element.name ]; }, size: function() { return this.errorList.length; }, focusInvalid: function() { if ( this.settings.focusInvalid ) { try { $( this.findLastActive() || this.errorList.length && this.errorList[ 0 ].element || [] ) .filter( ":visible" ) .focus() // Manually trigger focusin event; without it, focusin handler isn't called, findLastActive won't have anything to find .trigger( "focusin" ); } catch ( e ) { // Ignore IE throwing errors when focusing hidden elements } } }, findLastActive: function() { var lastActive = this.lastActive; return lastActive && $.grep( this.errorList, function( n ) { return n.element.name === lastActive.name; } ).length === 1 && lastActive; }, elements: function() { var validator = this, rulesCache = {}; // Select all valid inputs inside the form (no submit or reset buttons) return $( this.currentForm ) .find( "input, select, textarea, [contenteditable]" ) .not( ":submit, :reset, :image, :disabled" ) .not( this.settings.ignore ) .filter( function() { var name = this.name || $( this ).attr( "name" ); // For contenteditable if ( !name && validator.settings.debug && window.console ) { console.error( "%o has no name assigned", this ); } // Set form expando on contenteditable if ( this.hasAttribute( "contenteditable" ) ) { this.form = $( this ).closest( "form" )[ 0 ]; } // Select only the first element for each name, and only those with rules specified if ( name in rulesCache || !validator.objectLength( $( this ).rules() ) ) { return false; } rulesCache[ name ] = true; return true; } ); }, clean: function( selector ) { return $( selector )[ 0 ]; }, errors: function() { var errorClass = this.settings.errorClass.split( " " ).join( "." ); return $( this.settings.errorElement + "." + errorClass, this.errorContext ); }, reset: function() { this.successList = []; this.errorList = []; this.errorMap = {}; this.toShow = $( [] ); this.toHide = $( [] ); this.currentElements = $( [] ); }, prepareForm: function() { this.reset(); this.toHide = this.errors().add( this.containers ); }, prepareElement: function( element ) { this.reset(); this.toHide = this.errorsFor( element ); }, elementValue: function( element ) { var val, $element = $( element ), type = element.type; if ( type === "radio" || type === "checkbox" ) { return this.findByName( element.name ).filter( ":checked" ).val(); } else if ( type === "number" && typeof element.validity !== "undefined" ) { return element.validity.badInput ? false : $element.val(); } if ( element.hasAttribute( "contenteditable" ) ) { val = $element.text(); } else { val = $element.val(); } if ( typeof val === "string" ) { return val.replace( /\r/g, "" ); } return val; }, check: function( element ) { element = this.validationTargetFor( this.clean( element ) ); var rules = $( element ).rules(), rulesCount = $.map( rules, function( n, i ) { return i; } ).length, dependencyMismatch = false, val = this.elementValue( element ), result, method, rule; // If a normalizer is defined for this element, then // call it to retreive the changed value instead // of using the real one. // Note that `this` in the normalizer is `element`. if ( typeof rules.normalizer === "function" ) { val = rules.normalizer.call( element, val ); if ( typeof val !== "string" ) { throw new TypeError( "The normalizer should return a string value." ); } // Delete the normalizer from rules to avoid treating // it as a pre-defined method. delete rules.normalizer; } for ( method in rules ) { rule = { method: method, parameters: rules[ method ] }; try { result = $.validator.methods[ method ].call( this, val, element, rule.parameters ); // If a method indicates that the field is optional and therefore valid, // don't mark it as valid when there are no other rules if ( result === "dependency-mismatch" && rulesCount === 1 ) { dependencyMismatch = true; continue; } dependencyMismatch = false; if ( result === "pending" ) { this.toHide = this.toHide.not( this.errorsFor( element ) ); return; } if ( !result ) { this.formatAndAdd( element, rule ); return false; } } catch ( e ) { if ( this.settings.debug && window.console ) { console.log( "Exception occurred when checking element " + element.id + ", check the '" + rule.method + "' method.", e ); } if ( e instanceof TypeError ) { e.message += ". Exception occurred when checking element " + element.id + ", check the '" + rule.method + "' method."; } throw e; } } if ( dependencyMismatch ) { return; } if ( this.objectLength( rules ) ) { this.successList.push( element ); } return true; }, // Return the custom message for the given element and validation method // specified in the element's HTML5 data attribute // return the generic message if present and no method specific message is present customDataMessage: function( element, method ) { return $( element ).data( "msg" + method.charAt( 0 ).toUpperCase() + method.substring( 1 ).toLowerCase() ) || $( element ).data( "msg" ); }, // Return the custom message for the given element name and validation method customMessage: function( name, method ) { var m = this.settings.messages[ name ]; return m && ( m.constructor === String ? m : m[ method ] ); }, // Return the first defined argument, allowing empty strings findDefined: function() { for ( var i = 0; i < arguments.length; i++ ) { if ( arguments[ i ] !== undefined ) { return arguments[ i ]; } } return undefined; }, defaultMessage: function( element, method ) { return this.findDefined( this.customMessage( element.name, method ), this.customDataMessage( element, method ), // 'title' is never undefined, so handle empty string as undefined !this.settings.ignoreTitle && element.title || undefined, $.validator.messages[ method ], "<strong>Warning: No message defined for " + element.name + "</strong>" ); }, formatAndAdd: function( element, rule ) { var message = this.defaultMessage( element, rule.method ), theregex = /\$?\{(\d+)\}/g; if ( typeof message === "function" ) { message = message.call( this, rule.parameters, element ); } else if ( theregex.test( message ) ) { message = $.validator.format( message.replace( theregex, "{$1}" ), rule.parameters ); } this.errorList.push( { message: message, element: element, method: rule.method } ); this.errorMap[ element.name ] = message; this.submitted[ element.name ] = message; }, addWrapper: function( toToggle ) { if ( this.settings.wrapper ) { toToggle = toToggle.add( toToggle.parent( this.settings.wrapper ) ); } return toToggle; }, defaultShowErrors: function() { var i, elements, error; for ( i = 0; this.errorList[ i ]; i++ ) { error = this.errorList[ i ]; if ( this.settings.highlight ) { this.settings.highlight.call( this, error.element, this.settings.errorClass, this.settings.validClass ); } this.showLabel( error.element, error.message ); } if ( this.errorList.length ) { this.toShow = this.toShow.add( this.containers ); } if ( this.settings.success ) { for ( i = 0; this.successList[ i ]; i++ ) { this.showLabel( this.successList[ i ] ); } } if ( this.settings.unhighlight ) { for ( i = 0, elements = this.validElements(); elements[ i ]; i++ ) { this.settings.unhighlight.call( this, elements[ i ], this.settings.errorClass, this.settings.validClass ); } } this.toHide = this.toHide.not( this.toShow ); this.hideErrors(); this.addWrapper( this.toShow ).show(); }, validElements: function() { return this.currentElements.not( this.invalidElements() ); }, invalidElements: function() { return $( this.errorList ).map( function() { return this.element; } ); }, showLabel: function( element, message ) { var place, group, errorID, error = this.errorsFor( element ), elementID = this.idOrName( element ), describedBy = $( element ).attr( "aria-describedby" ); if ( error.length ) { // Refresh error/success class error.removeClass( this.settings.validClass ).addClass( this.settings.errorClass ); // Replace message on existing label error.html( message ); } else { // Create error element error = $( "<" + this.settings.errorElement + ">" ) .attr( "id", elementID + "-error" ) .addClass( this.settings.errorClass ) .html( message || "" ); // Maintain reference to the element to be placed into the DOM place = error; if ( this.settings.wrapper ) { // Make sure the element is visible, even in IE // actually showing the wrapped element is handled elsewhere place = error.hide().show().wrap( "<" + this.settings.wrapper + "/>" ).parent(); } if ( this.labelContainer.length ) { this.labelContainer.append( place ); } else if ( this.settings.errorPlacement ) { this.settings.errorPlacement( place, $( element ) ); } else { place.insertAfter( element ); } // Link error back to the element if ( error.is( "label" ) ) { // If the error is a label, then associate using 'for' error.attr( "for", elementID ); } // If the element is not a child of an associated label, then it's necessary // to explicitly apply aria-describedby else if ( error.parents( "label[for='" + this.escapeCssMeta( elementID ) + "']" ).length === 0 ) { errorID = error.attr( "id" ); // Respect existing non-error aria-describedby if ( !describedBy ) { describedBy = errorID; } else if ( !describedBy.match( new RegExp( "\\b" + this.escapeCssMeta( errorID ) + "\\b" ) ) ) { // Add to end of list if not already present describedBy += " " + errorID; } $( element ).attr( "aria-describedby", describedBy ); // If this element is grouped, then assign to all elements in the same group group = this.groups[ element.name ]; if ( group ) { $.each( this.groups, function( name, testgroup ) { if ( testgroup === group ) { $( "[name='" + this.escapeCssMeta( name ) + "']", this.currentForm ) .attr( "aria-describedby", error.attr( "id" ) ); } } ); } } } if ( !message && this.settings.success ) { error.text( "" ); if ( typeof this.settings.success === "string" ) { error.addClass( this.settings.success ); } else { this.settings.success( error, element ); } } this.toShow = this.toShow.add( error ); }, errorsFor: function( element ) { var name = this.escapeCssMeta( this.idOrName( element ) ), describer = $( element ).attr( "aria-describedby" ), selector = "label[for='" + name + "'], label[for='" + name + "'] *"; // 'aria-describedby' should directly reference the error element if ( describer ) { selector = selector + ", #" + this.escapeCssMeta( describer ) .replace( /\s+/g, ", #" ); } return this .errors() .filter( selector ); }, // See https://api.jquery.com/category/selectors/, for CSS // meta-characters that should be escaped in order to be used with JQuery // as a literal part of a name/id or any selector. escapeCssMeta: function( string ) { return string.replace( /([\\!"#$%&'()*+,./:;<=>?@\[\]^`{|}~])/g, "\\$1" ); }, idOrName: function( element ) { return this.groups[ element.name ] || ( this.checkable( element ) ? element.name : element.id || element.name ); }, validationTargetFor: function( element ) { // If radio/checkbox, validate first element in group instead if ( this.checkable( element ) ) { element = this.findByName( element.name ); } // Always apply ignore filter return $( element ).not( this.settings.ignore )[ 0 ]; }, checkable: function( element ) { return ( /radio|checkbox/i ).test( element.type ); }, findByName: function( name ) { return $( this.currentForm ).find( "[name='" + this.escapeCssMeta( name ) + "']" ); }, getLength: function( value, element ) { switch ( element.nodeName.toLowerCase() ) { case "select": return $( "option:selected", element ).length; case "input": if ( this.checkable( element ) ) { return this.findByName( element.name ).filter( ":checked" ).length; } } return value.length; }, depend: function( param, element ) { return this.dependTypes[ typeof param ] ? this.dependTypes[ typeof param ]( param, element ) : true; }, dependTypes: { "boolean": function( param ) { return param; }, "string": function( param, element ) { return !!$( param, element.form ).length; }, "function": function( param, element ) { return param( element ); } }, optional: function( element ) { var val = this.elementValue( element ); return !$.validator.methods.required.call( this, val, element ) && "dependency-mismatch"; }, startRequest: function( element ) { if ( !this.pending[ element.name ] ) { this.pendingRequest++; $( element ).addClass( this.settings.pendingClass ); this.pending[ element.name ] = true; } }, stopRequest: function( element, valid ) { this.pendingRequest--; // Sometimes synchronization fails, make sure pendingRequest is never < 0 if ( this.pendingRequest < 0 ) { this.pendingRequest = 0; } delete this.pending[ element.name ]; $( element ).removeClass( this.settings.pendingClass ); if ( valid && this.pendingRequest === 0 && this.formSubmitted && this.form() ) { $( this.currentForm ).submit(); this.formSubmitted = false; } else if ( !valid && this.pendingRequest === 0 && this.formSubmitted ) { $( this.currentForm ).triggerHandler( "invalid-form", [ this ] ); this.formSubmitted = false; } }, previousValue: function( element ) { return $.data( element, "previousValue" ) || $.data( element, "previousValue", { old: null, valid: true, message: this.defaultMessage( element, "remote" ) } ); }, // Cleans up all forms and elements, removes validator-specific events destroy: function() { this.resetForm(); $( this.currentForm ) .off( ".validate" ) .removeData( "validator" ); } }, classRuleSettings: { required: { required: true }, email: { email: true }, url: { url: true }, date: { date: true }, dateISO: { dateISO: true }, number: { number: true }, digits: { digits: true }, creditcard: { creditcard: true } }, addClassRules: function( className, rules ) { if ( className.constructor === String ) { this.classRuleSettings[ className ] = rules; } else { $.extend( this.classRuleSettings, className ); } }, classRules: function( element ) { var rules = {}, classes = $( element ).attr( "class" ); if ( classes ) { $.each( classes.split( " " ), function() { if ( this in $.validator.classRuleSettings ) { $.extend( rules, $.validator.classRuleSettings[ this ] ); } } ); } return rules; }, normalizeAttributeRule: function( rules, type, method, value ) { // Convert the value to a number for number inputs, and for text for backwards compability // allows type="date" and others to be compared as strings if ( /min|max/.test( method ) && ( type === null || /number|range|text/.test( type ) ) ) { value = Number( value ); // Support Opera Mini, which returns NaN for undefined minlength if ( isNaN( value ) ) { value = undefined; } } if ( value || value === 0 ) { rules[ method ] = value; } else if ( type === method && type !== "range" ) { // Exception: the jquery validate 'range' method // does not test for the html5 'range' type rules[ method ] = true; } }, attributeRules: function( element ) { var rules = {}, $element = $( element ), type = element.getAttribute( "type" ), method, value; for ( method in $.validator.methods ) { // Support for <input required> in both html5 and older browsers if ( method === "required" ) { value = element.getAttribute( method ); // Some browsers return an empty string for the required attribute // and non-HTML5 browsers might have required="" markup if ( value === "" ) { value = true; } // Force non-HTML5 browsers to return bool value = !!value; } else { value = $element.attr( method ); } this.normalizeAttributeRule( rules, type, method, value ); } // 'maxlength' may be returned as -1, 2147483647 ( IE ) and 524288 ( safari ) for text inputs if ( rules.maxlength && /-1|2147483647|524288/.test( rules.maxlength ) ) { delete rules.maxlength; } return rules; }, dataRules: function( element ) { var rules = {}, $element = $( element ), type = element.getAttribute( "type" ), method, value; for ( method in $.validator.methods ) { value = $element.data( "rule" + method.charAt( 0 ).toUpperCase() + method.substring( 1 ).toLowerCase() ); this.normalizeAttributeRule( rules, type, method, value ); } return rules; }, staticRules: function( element ) { var rules = {}, validator = $.data( element.form, "validator" ); if ( validator.settings.rules ) { rules = $.validator.normalizeRule( validator.settings.rules[ element.name ] ) || {}; } return rules; }, normalizeRules: function( rules, element ) { // Handle dependency check $.each( rules, function( prop, val ) { // Ignore rule when param is explicitly false, eg. required:false if ( val === false ) { delete rules[ prop ]; return; } if ( val.param || val.depends ) { var keepRule = true; switch ( typeof val.depends ) { case "string": keepRule = !!$( val.depends, element.form ).length; break; case "function": keepRule = val.depends.call( element, element ); break; } if ( keepRule ) { rules[ prop ] = val.param !== undefined ? val.param : true; } else { delete rules[ prop ]; } } } ); // Evaluate parameters $.each( rules, function( rule, parameter ) { rules[ rule ] = $.isFunction( parameter ) && rule !== "normalizer" ? parameter( element ) : parameter; } ); // Clean number parameters $.each( [ "minlength", "maxlength" ], function() { if ( rules[ this ] ) { rules[ this ] = Number( rules[ this ] ); } } ); $.each( [ "rangelength", "range" ], function() { var parts; if ( rules[ this ] ) { if ( $.isArray( rules[ this ] ) ) { rules[ this ] = [ Number( rules[ this ][ 0 ] ), Number( rules[ this ][ 1 ] ) ]; } else if ( typeof rules[ this ] === "string" ) { parts = rules[ this ].replace( /[\[\]]/g, "" ).split( /[\s,]+/ ); rules[ this ] = [ Number( parts[ 0 ] ), Number( parts[ 1 ] ) ]; } } } ); if ( $.validator.autoCreateRanges ) { // Auto-create ranges if ( rules.min != null && rules.max != null ) { rules.range = [ rules.min, rules.max ]; delete rules.min; delete rules.max; } if ( rules.minlength != null && rules.maxlength != null ) { rules.rangelength = [ rules.minlength, rules.maxlength ]; delete rules.minlength; delete rules.maxlength; } } return rules; }, // Converts a simple string to a {string: true} rule, e.g., "required" to {required:true} normalizeRule: function( data ) { if ( typeof data === "string" ) { var transformed = {}; $.each( data.split( /\s/ ), function() { transformed[ this ] = true; } ); data = transformed; } return data; }, // http://jqueryvalidation.org/jQuery.validator.addMethod/ addMethod: function( name, method, message ) { $.validator.methods[ name ] = method; $.validator.messages[ name ] = message !== undefined ? message : $.validator.messages[ name ]; if ( method.length < 3 ) { $.validator.addClassRules( name, $.validator.normalizeRule( name ) ); } }, methods: { // http://jqueryvalidation.org/required-method/ required: function( value, element, param ) { // Check if dependency is met if ( !this.depend( param, element ) ) { return "dependency-mismatch"; } if ( element.nodeName.toLowerCase() === "select" ) { // Could be an array for select-multiple or a string, both are fine this way var val = $( element ).val(); return val && val.length > 0; } if ( this.checkable( element ) ) { return this.getLength( value, element ) > 0; } return value.length > 0; }, // http://jqueryvalidation.org/email-method/ email: function( value, element ) { // From https://html.spec.whatwg.org/multipage/forms.html#valid-e-mail-address // Retrieved 2014-01-14 // If you have a problem with this implementation, report a bug against the above spec // Or use custom methods to implement your own email validation return this.optional( element ) || /^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.test( value ); }, // http://jqueryvalidation.org/url-method/ url: function( value, element ) { // Copyright (c) 2010-2013 Diego Perini, MIT licensed // https://gist.github.com/dperini/729294 // see also https://mathiasbynens.be/demo/url-regex // modified to allow protocol-relative URLs return this.optional( element ) || /^(?:(?:(?:https?|ftp):)?\/\/)(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})).?)(?::\d{2,5})?(?:[/?#]\S*)?$/i.test( value ); }, // http://jqueryvalidation.org/date-method/ date: function( value, element ) { return this.optional( element ) || !/Invalid|NaN/.test( new Date( value ).toString() ); }, // http://jqueryvalidation.org/dateISO-method/ dateISO: function( value, element ) { return this.optional( element ) || /^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/.test( value ); }, // http://jqueryvalidation.org/number-method/ number: function( value, element ) { return this.optional( element ) || /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test( value ); }, // http://jqueryvalidation.org/digits-method/ digits: function( value, element ) { return this.optional( element ) || /^\d+$/.test( value ); }, // http://jqueryvalidation.org/minlength-method/ minlength: function( value, element, param ) { var length = $.isArray( value ) ? value.length : this.getLength( value, element ); return this.optional( element ) || length >= param; }, // http://jqueryvalidation.org/maxlength-method/ maxlength: function( value, element, param ) { var length = $.isArray( value ) ? value.length : this.getLength( value, element ); return this.optional( element ) || length <= param; }, // http://jqueryvalidation.org/rangelength-method/ rangelength: function( value, element, param ) { var length = $.isArray( value ) ? value.length : this.getLength( value, element ); return this.optional( element ) || ( length >= param[ 0 ] && length <= param[ 1 ] ); }, // http://jqueryvalidation.org/min-method/ min: function( value, element, param ) { return this.optional( element ) || value >= param; }, // http://jqueryvalidation.org/max-method/ max: function( value, element, param ) { return this.optional( element ) || value <= param; }, // http://jqueryvalidation.org/range-method/ range: function( value, element, param ) { return this.optional( element ) || ( value >= param[ 0 ] && value <= param[ 1 ] ); }, // http://jqueryvalidation.org/equalTo-method/ equalTo: function( value, element, param ) { // Bind to the blur event of the target in order to revalidate whenever the target field is updated // TODO find a way to bind the event just once, avoiding the unbind-rebind overhead var target = $( param ); if ( this.settings.onfocusout ) { target.off( ".validate-equalTo" ).on( "blur.validate-equalTo", function() { $( element ).valid(); } ); } return value === target.val(); }, // http://jqueryvalidation.org/remote-method/ remote: function( value, element, param ) { if ( this.optional( element ) ) { return "dependency-mismatch"; } var previous = this.previousValue( element ), validator, data, optionDataString; if ( !this.settings.messages[ element.name ] ) { this.settings.messages[ element.name ] = {}; } previous.originalMessage = this.settings.messages[ element.name ].remote; this.settings.messages[ element.name ].remote = previous.message; param = typeof param === "string" && { url: param } || param; optionDataString = $.param( $.extend( { data: value }, param.data ) ); if ( previous.old === optionDataString ) { return previous.valid; } previous.old = optionDataString; validator = this; this.startRequest( element ); data = {}; data[ element.name ] = value; $.ajax( $.extend( true, { mode: "abort", port: "validate" + element.name, dataType: "json", data: data, context: validator.currentForm, success: function( response ) { var valid = response === true || response === "true", errors, message, submitted; validator.settings.messages[ element.name ].remote = previous.originalMessage; if ( valid ) { submitted = validator.formSubmitted; validator.prepareElement( element ); validator.formSubmitted = submitted; validator.successList.push( element ); delete validator.invalid[ element.name ]; validator.showErrors(); } else { errors = {}; message = response || validator.defaultMessage( element, "remote" ); errors[ element.name ] = previous.message = $.isFunction( message ) ? message( value ) : message; validator.invalid[ element.name ] = true; validator.showErrors( errors ); } previous.valid = valid; validator.stopRequest( element, valid ); } }, param ) ); return "pending"; } } } );
var db = require('../models'); function index(req, res) { db.User.find({}, function(err, allUsers) { //TODO: handle the errors. // TODO: Send this array as a json object res.json(allUsers); }); } function create(req, res) { // TODO: Consider creating an obect literal then passing in that object rather than just the req.body db.User.create(req.body, function(err, user) { if (err) { console.log('error', err); } // remove console logs from production console.log(user); res.json(user); }); } function destroy(req, res) { db.User.findOneAndRemove({ _id: req.params.userId }, function(err, foundUser) { //TODO: Handle ERR res.json(foundUser); }); } function update(req, res) { // remove console logs from production console.log('Updating user', req.body); var updateUser = { userName: req.body.userName, email: req.body.email, passwordDigest: req.body.passwordDigest, } db.User.findOneAndUpdate({_id: req.params.userId}, updateUser, function(err, foundUser) { if (err) {console.log('usersController.update.error', err);} res.json(foundUser); }); } module.exports = { index: index, create: create, destroy: destroy, update: update };
// WebHelp 5.10.001 var garrSortChar=new Array(); var gaFtsStop=new Array(); var gaFtsStem=new Array(); var gbWhLang=false; garrSortChar[0] = 0; garrSortChar[1] = 1; garrSortChar[2] = 2; garrSortChar[3] = 3; garrSortChar[4] = 4; garrSortChar[5] = 5; garrSortChar[6] = 6; garrSortChar[7] = 7; garrSortChar[8] = 8; garrSortChar[9] = 40; garrSortChar[10] = 41; garrSortChar[11] = 42; garrSortChar[12] = 43; garrSortChar[13] = 44; garrSortChar[14] = 9; garrSortChar[15] = 10; garrSortChar[16] = 11; garrSortChar[17] = 12; garrSortChar[18] = 13; garrSortChar[19] = 14; garrSortChar[20] = 15; garrSortChar[21] = 16; garrSortChar[22] = 17; garrSortChar[23] = 18; garrSortChar[24] = 19; garrSortChar[25] = 20; garrSortChar[26] = 21; garrSortChar[27] = 22; garrSortChar[28] = 23; garrSortChar[29] = 24; garrSortChar[30] = 25; garrSortChar[31] = 26; garrSortChar[32] = 38; garrSortChar[33] = 45; garrSortChar[34] = 46; garrSortChar[35] = 47; garrSortChar[36] = 48; garrSortChar[37] = 49; garrSortChar[38] = 50; garrSortChar[39] = 33; garrSortChar[40] = 51; garrSortChar[41] = 52; garrSortChar[42] = 53; garrSortChar[43] = 88; garrSortChar[44] = 54; garrSortChar[45] = 34; garrSortChar[46] = 55; garrSortChar[47] = 56; garrSortChar[48] = 115; garrSortChar[49] = 119; garrSortChar[50] = 121; garrSortChar[51] = 123; garrSortChar[52] = 125; garrSortChar[53] = 126; garrSortChar[54] = 127; garrSortChar[55] = 128; garrSortChar[56] = 129; garrSortChar[57] = 130; garrSortChar[58] = 57; garrSortChar[59] = 58; garrSortChar[60] = 89; garrSortChar[61] = 90; garrSortChar[62] = 91; garrSortChar[63] = 59; garrSortChar[64] = 60; garrSortChar[65] = 131; garrSortChar[66] = 148; garrSortChar[67] = 150; garrSortChar[68] = 154; garrSortChar[69] = 158; garrSortChar[70] = 168; garrSortChar[71] = 171; garrSortChar[72] = 173; garrSortChar[73] = 175; garrSortChar[74] = 185; garrSortChar[75] = 187; garrSortChar[76] = 189; garrSortChar[77] = 191; garrSortChar[78] = 193; garrSortChar[79] = 197; garrSortChar[80] = 214; garrSortChar[81] = 216; garrSortChar[82] = 218; garrSortChar[83] = 220; garrSortChar[84] = 225; garrSortChar[85] = 230; garrSortChar[86] = 240; garrSortChar[87] = 242; garrSortChar[88] = 244; garrSortChar[89] = 246; garrSortChar[90] = 252; garrSortChar[91] = 61; garrSortChar[92] = 62; garrSortChar[93] = 63; garrSortChar[94] = 64; garrSortChar[95] = 66; garrSortChar[96] = 67; garrSortChar[97] = 131; garrSortChar[98] = 148; garrSortChar[99] = 150; garrSortChar[100] = 154; garrSortChar[101] = 158; garrSortChar[102] = 168; garrSortChar[103] = 171; garrSortChar[104] = 173; garrSortChar[105] = 175; garrSortChar[106] = 185; garrSortChar[107] = 187; garrSortChar[108] = 189; garrSortChar[109] = 191; garrSortChar[110] = 193; garrSortChar[111] = 197; garrSortChar[112] = 214; garrSortChar[113] = 216; garrSortChar[114] = 218; garrSortChar[115] = 220; garrSortChar[116] = 225; garrSortChar[117] = 230; garrSortChar[118] = 240; garrSortChar[119] = 242; garrSortChar[120] = 244; garrSortChar[121] = 246; garrSortChar[122] = 252; garrSortChar[123] = 68; garrSortChar[124] = 69; garrSortChar[125] = 70; garrSortChar[126] = 71; garrSortChar[127] = 27; garrSortChar[128] = 114; garrSortChar[129] = 28; garrSortChar[130] = 82; garrSortChar[131] = 170; garrSortChar[132] = 85; garrSortChar[133] = 112; garrSortChar[134] = 109; garrSortChar[135] = 110; garrSortChar[136] = 65; garrSortChar[137] = 113; garrSortChar[138] = 223; garrSortChar[139] = 86; garrSortChar[140] = 213; garrSortChar[141] = 29; garrSortChar[142] = 255; garrSortChar[143] = 30; garrSortChar[144] = 31; garrSortChar[145] = 80; garrSortChar[146] = 81; garrSortChar[147] = 83; garrSortChar[148] = 84; garrSortChar[149] = 111; garrSortChar[150] = 36; garrSortChar[151] = 37; garrSortChar[152] = 79; garrSortChar[153] = 229; garrSortChar[154] = 222; garrSortChar[155] = 87; garrSortChar[156] = 212; garrSortChar[157] = 32; garrSortChar[158] = 254; garrSortChar[159] = 251; garrSortChar[160] = 39; garrSortChar[161] = 72; garrSortChar[162] = 97; garrSortChar[163] = 98; garrSortChar[164] = 99; garrSortChar[165] = 100; garrSortChar[166] = 73; garrSortChar[167] = 101; garrSortChar[168] = 74; garrSortChar[169] = 102; garrSortChar[170] = 133; garrSortChar[171] = 93; garrSortChar[172] = 103; garrSortChar[173] = 35; garrSortChar[174] = 104; garrSortChar[175] = 75; garrSortChar[176] = 105; garrSortChar[177] = 92; garrSortChar[178] = 122; garrSortChar[179] = 124; garrSortChar[180] = 76; garrSortChar[181] = 106; garrSortChar[182] = 107; garrSortChar[183] = 108; garrSortChar[184] = 77; garrSortChar[185] = 120; garrSortChar[186] = 199; garrSortChar[187] = 94; garrSortChar[188] = 116; garrSortChar[189] = 117; garrSortChar[190] = 118; garrSortChar[191] = 78; garrSortChar[192] = 131; garrSortChar[193] = 131; garrSortChar[194] = 131; garrSortChar[195] = 131; garrSortChar[196] = 131; garrSortChar[197] = 131; garrSortChar[198] = 131; garrSortChar[199] = 150; garrSortChar[200] = 158; garrSortChar[201] = 158; garrSortChar[202] = 158; garrSortChar[203] = 158; garrSortChar[204] = 175; garrSortChar[205] = 175; garrSortChar[206] = 175; garrSortChar[207] = 175; garrSortChar[208] = 154; garrSortChar[209] = 193; garrSortChar[210] = 197; garrSortChar[211] = 197; garrSortChar[212] = 197; garrSortChar[213] = 197; garrSortChar[214] = 197; garrSortChar[215] = 95; garrSortChar[216] = 197; garrSortChar[217] = 230; garrSortChar[218] = 230; garrSortChar[219] = 230; garrSortChar[220] = 230; garrSortChar[221] = 246; garrSortChar[222] = 227; garrSortChar[223] = 224; garrSortChar[224] = 131; garrSortChar[225] = 131; garrSortChar[226] = 131; garrSortChar[227] = 131; garrSortChar[228] = 131; garrSortChar[229] = 131; garrSortChar[230] = 131; garrSortChar[231] = 150; garrSortChar[232] = 158; garrSortChar[233] = 158; garrSortChar[234] = 158; garrSortChar[235] = 158; garrSortChar[236] = 175; garrSortChar[237] = 175; garrSortChar[238] = 175; garrSortChar[239] = 175; garrSortChar[240] = 154; garrSortChar[241] = 193; garrSortChar[242] = 197; garrSortChar[243] = 197; garrSortChar[244] = 197; garrSortChar[245] = 197; garrSortChar[246] = 197; garrSortChar[247] = 96; garrSortChar[248] = 197; garrSortChar[249] = 230; garrSortChar[250] = 230; garrSortChar[251] = 230; garrSortChar[252] = 230; garrSortChar[253] = 246; garrSortChar[254] = 227; garrSortChar[255] = 250; gaFtsStop[0] = "a"; gaFtsStop[1] = "about"; gaFtsStop[2] = "after"; gaFtsStop[3] = "against"; gaFtsStop[4] = "all"; gaFtsStop[5] = "also"; gaFtsStop[6] = "among"; gaFtsStop[7] = "an"; gaFtsStop[8] = "and"; gaFtsStop[9] = "are"; gaFtsStop[10] = "as"; gaFtsStop[11] = "at"; gaFtsStop[12] = "be"; gaFtsStop[13] = "became"; gaFtsStop[14] = "because"; gaFtsStop[15] = "been"; gaFtsStop[16] = "between"; gaFtsStop[17] = "but"; gaFtsStop[18] = "by"; gaFtsStop[19] = "can"; gaFtsStop[20] = "come"; gaFtsStop[21] = "do"; gaFtsStop[22] = "during"; gaFtsStop[23] = "each"; gaFtsStop[24] = "early"; gaFtsStop[25] = "for"; gaFtsStop[26] = "form"; gaFtsStop[27] = "found"; gaFtsStop[28] = "from"; gaFtsStop[29] = "had"; gaFtsStop[30] = "has"; gaFtsStop[31] = "have"; gaFtsStop[32] = "he"; gaFtsStop[33] = "her"; gaFtsStop[34] = "his"; gaFtsStop[35] = "however"; gaFtsStop[36] = "in"; gaFtsStop[37] = "include"; gaFtsStop[38] = "into"; gaFtsStop[39] = "is"; gaFtsStop[40] = "it"; gaFtsStop[41] = "its"; gaFtsStop[42] = "late"; gaFtsStop[43] = "later"; gaFtsStop[44] = "made"; gaFtsStop[45] = "many"; gaFtsStop[46] = "may"; gaFtsStop[47] = "me"; gaFtsStop[48] = "med"; gaFtsStop[49] = "more"; gaFtsStop[50] = "most"; gaFtsStop[51] = "near"; gaFtsStop[52] = "no"; gaFtsStop[53] = "non"; gaFtsStop[54] = "not"; gaFtsStop[55] = "of"; gaFtsStop[56] = "on"; gaFtsStop[57] = "only"; gaFtsStop[58] = "or"; gaFtsStop[59] = "other"; gaFtsStop[60] = "over"; gaFtsStop[61] = "several"; gaFtsStop[62] = "she"; gaFtsStop[63] = "some"; gaFtsStop[64] = "such"; gaFtsStop[65] = "than"; gaFtsStop[66] = "that"; gaFtsStop[67] = "the"; gaFtsStop[68] = "their"; gaFtsStop[69] = "then"; gaFtsStop[70] = "there"; gaFtsStop[71] = "these"; gaFtsStop[72] = "they"; gaFtsStop[73] = "this"; gaFtsStop[74] = "through"; gaFtsStop[75] = "to"; gaFtsStop[76] = "under"; gaFtsStop[77] = "until"; gaFtsStop[78] = "use"; gaFtsStop[79] = "was"; gaFtsStop[80] = "we"; gaFtsStop[81] = "were"; gaFtsStop[82] = "when"; gaFtsStop[83] = "where"; gaFtsStop[84] = "which"; gaFtsStop[85] = "who"; gaFtsStop[86] = "with"; gaFtsStop[87] = "you"; gaFtsStem[0] = "ed"; gaFtsStem[1] = "es"; gaFtsStem[2] = "er"; gaFtsStem[3] = "e"; gaFtsStem[4] = "s"; gaFtsStem[5] = "ingly"; gaFtsStem[6] = "ing"; gaFtsStem[7] = "ly"; // as javascript 1.3 support unicode instead of ISO-Latin-1 // need to transfer come code back to ISO-Latin-1 for compare purpose // Note: Different Language(Code page) maybe need different array: var gaUToC=new Array(); gaUToC[8364]=128; gaUToC[8218]=130; gaUToC[402]=131; gaUToC[8222]=132; gaUToC[8230]=133; gaUToC[8224]=134; gaUToC[8225]=135; gaUToC[710]=136; gaUToC[8240]=137; gaUToC[352]=138; gaUToC[8249]=139; gaUToC[338]=140; gaUToC[381]=142; gaUToC[8216]=145; gaUToC[8217]=146; gaUToC[8220]=147; gaUToC[8221]=148; gaUToC[8226]=149; gaUToC[8211]=150; gaUToC[8212]=151; gaUToC[732]=152; gaUToC[8482]=153; gaUToC[353]=154; gaUToC[8250]=155; gaUToC[339]=156; gaUToC[382]=158; gaUToC[376]=159; var gsBiggestChar=""; function getBiggestChar() { if(gsBiggestChar.length==0) { if(garrSortChar.length<256) gsBiggestChar=String.fromCharCode(255); else { var nBiggest=0; var nBigChar=0; for(var i=0;i<=255;i++) { if(garrSortChar[i]>nBiggest) { nBiggest=garrSortChar[i]; nBigChar=i; } } gsBiggestChar=String.fromCharCode(nBigChar); } } return gsBiggestChar; } function getCharCode(str,i) { var code=str.charCodeAt(i) return code; } function compare(strText1,strText2) { var strt1=strText1.toLowerCase(); var strt2=strText2.toLowerCase(); if(strt1<strt2) return -1; if(strt1>strt2) return 1; return 0; } gbWhLang=true;
import { buildUrl, contentUrl, profileUrl } from 'shared/util/url_factory'; import gql from 'graphql-tag'; import { memo } from 'react'; import { useQuery } from '@apollo/client'; const CONTENT_AND_USER_QUERY = gql` query ContentAndUserQuery($username: String!, $name: String!) { fetchContentHead(username: $username, name: $name) { username section album name thumb title createdAt updatedAt comments_count comments_updated } fetchPublicUserDataHead(username: $username) { description favicon google_analytics logo name theme title username viewport } } `; // NOTE: Keep in sync with index.html for service workers! export default function HTMLHead(props) { const { appName, assetPathsByType, nonce, publicUrl, req } = props; // The username is either the first part of the path (e.g. hostname.com/mime/section/album/name) // or if we're on a user that has a `hostname` defined then it's implicit in the url // (e.g. hostname.com/section/album/name) and we figure it out in the user resolver. const splitPath = req.path.split('/'); const probableContentUsername = splitPath[1]; const probableContentName = splitPath[splitPath.length - 1]; const { loading, data } = useQuery(CONTENT_AND_USER_QUERY, { variables: { username: decodeURIComponent(probableContentUsername), name: decodeURIComponent(probableContentName), }, }); if (loading) { return null; } // XXX(mime): terrible hack until i figure out what's going on. // seems that having the same query twice in a tree while doing SSR will prevent rendering of the first // component. in this case, HTMLHead's data will be missing. const contentOwner = data.fetchPublicUserDataHead; const content = data.fetchContentHead; let description, favicon, rss, theme, title, username, webmentionUrl; const repliesUrl = content && buildUrl({ pathname: '/api/social/comments', searchParams: { resource: contentUrl(content) } }); const repliesAttribs = content && { 'thr:count': content.comments_count, 'thr:updated': new Date(content.comments_updated).toISOString(), }; let viewport = 'width=device-width, initial-scale=1'; if (contentOwner) { username = contentOwner.username; const resource = profileUrl(username, req); description = <meta name="description" content={contentOwner.description || 'Hello, world.'} />; favicon = contentOwner.favicon; const feedUrl = buildUrl({ pathname: '/api/social/feed', searchParams: { resource } }); rss = <link rel="alternate" type="application/atom+xml" title={title} href={feedUrl} />; theme = contentOwner.theme && <link rel="stylesheet" href={contentOwner.theme} />; title = contentOwner.title; viewport = contentOwner.viewport || viewport; webmentionUrl = buildUrl({ req, pathname: '/api/social/webmention', searchParams: { resource } }); } if (!theme) { theme = <link rel="stylesheet" href="/css/themes/pixel.css" />; } if (!title) { title = appName; } return ( <head> <meta charSet="utf-8" /> <link rel="author" href={`${publicUrl}humans.txt`} /> {contentOwner ? <link rel="author" href={contentUrl({ username, section: 'main', name: 'about' })} /> : null} <link rel="icon" href={favicon || `${publicUrl}favicon.ico`} /> <link rel="apple-touch-icon" href={favicon || `${publicUrl}favicon.ico`} /> {assetPathsByType['css'].map((path) => ( <link nonce={nonce} rel="stylesheet" key={path} href={path} /> ))} {theme} <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500" /> <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" /> <link rel="search" href={buildUrl({ pathname: '/api/opensearch', searchParams: { username } })} type="application/opensearchdescription+xml" title={title} /> <link rel="canonical" href={content && contentUrl(content, req)} /> {rss} {!content && <meta name="robots" content="noindex" />} <meta name="viewport" content={viewport} /> <meta name="theme-color" content="#000000" /> <meta name="generator" content="Hello, world. https://github.com/mimecuvalo/helloworld" /> <meta property="csp-nonce" content={nonce} /> <script nonce={nonce} dangerouslySetInnerHTML={{ __html: `__webpack_nonce__ = '${nonce}'`, }} /> {description} <OpenGraphMetadata contentOwner={contentOwner} content={content} title={title} req={req} /> <StructuredMetaData contentOwner={contentOwner} content={content} nonce={nonce} title={title} req={req} /> <link rel="alternate" type="application/json+oembed" href={buildUrl({ pathname: '/api/social/oembed', searchParams: { resource: content && contentUrl(content) }, })} title={content?.title} /> {content && webmentionUrl ? <link rel="webmention" href={webmentionUrl} /> : null} {content?.comments_count ? ( <link rel="replies" type="application/atom+xml" href={repliesUrl} {...repliesAttribs} /> ) : null} {/* manifest.json provides metadata used when your web app is added to the homescreen on Android. See https://developers.google.com/web/fundamentals/web-app-manifest/ */} <link rel="manifest" href={`${publicUrl}manifest.json`} /> {/* Notice the use of publicUrl in the tags above. It will be replaced with the URL of the `public` folder during the build. Only files inside the `public` folder can be referenced from the HTML. Unlike "/favicon.ico" or "favicon.ico", "${publicUrl}favicon.ico" will work correctly both with client-side routing and a non-root public URL. Learn how to configure a non-root public URL by running `npm run build`. */} <title>{(content?.title ? content.title + ' – ' : '') + title}</title> {/* XXX(mime): Material UI's server-side rendering for CSS doesn't allow for inserting CSS the same way we do Apollo's data (see apolloStateFn in HTMLBase). So for now, we just do a string replace, sigh. See related hacky code in server/app/app.js */} <style id="jss-ssr" nonce={nonce} dangerouslySetInnerHTML={{ __html: `<!--CSS-SSR-REPLACE-->` }} /> {contentOwner ? <GoogleAnalytics nonce={nonce} contentOwner={contentOwner} /> : null} </head> ); } // This needs to be filled out by the developer to provide content for the site. // Learn more here: http://ogp.me/ const OpenGraphMetadata = memo(function OpenGraphMetadata({ contentOwner, content, title, req }) { const thumb = buildThumb(contentOwner, content, req); return ( <> <meta property="og:title" content={content?.title} /> <meta property="og:description" content={contentOwner?.description} /> <meta property="og:type" content="website" /> <meta property="og:url" content={content && contentUrl(content, req)} /> <meta property="og:site_name" content={title} /> <meta property="og:image" content={thumb} /> </> ); }); function buildThumb(contentOwner, content, req) { let thumb; if (content?.thumb) { thumb = content.thumb; if (!/^https?:/.test(thumb)) { thumb = buildUrl({ req, pathname: thumb }); } } if (!thumb) { thumb = buildUrl({ req, pathname: contentOwner?.logo || contentOwner?.favicon }); } return thumb; } // This needs to be filled out by the developer to provide content for the site. // Learn more here: https://developers.google.com/search/docs/guides/intro-structured-data function StructuredMetaData({ contentOwner, content, title, req, nonce }) { const url = buildUrl({ req, pathname: '/' }); const thumb = buildThumb(contentOwner, content, req); return ( <script nonce={nonce} type="application/ld+json" dangerouslySetInnerHTML={{ __html: ` { "@context": "http://schema.org", "@type": "NewsArticle", "mainEntityOfPage": { "@type": "WebPage", "@id": "${contentUrl(content, req)}" }, "headline": "${content?.title}", "image": [ "${thumb}" ], "datePublished": "${new Date(content?.createdAt || new Date()).toISOString()}", "dateModified": "${new Date(content?.updatedAt || new Date()).toISOString()}", "author": { "@type": "Person", "name": "${content?.username}" }, "publisher": { "@type": "Organization", "name": "${title}", "logo": { "@type": "ImageObject", "url": "${url}favicon.ico" } }, "description": "${contentOwner?.description}" } `, }} /> ); } // TODO(mime): meh, lame that this is in the <head> but I don't feel like moving this to HTMLBase where we don't have // contentOwner currently. function GoogleAnalytics({ nonce, contentOwner }) { return ( <script nonce={nonce} async dangerouslySetInnerHTML={{ __html: ` var _gaq = _gaq || []; _gaq.push(['_setAccount', '${contentOwner.google_analytics}']); _gaq.push(['_trackPageview']); (function() { var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true; ga.src = 'https://ssl.google-analytics.com/ga.js'; var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s); })(); `, }} /> ); }
angular.module('VoltronApp.services', []). factory('voltronAPIservice', function($http) { var voltronAPI = {}; function createRequest(requestType, data) { return {type: "request", request: requestType, data: data} } voltronAPI.request = function(request) { return $http({ method: 'POST', url: '/api/request', data: request }); } voltronAPI.disassemble_format = function(data) { res = voltronAPI.request(createRequest('disassemble', {address: address, count: count})) return $http({ method: 'POST', url: '/api/request', data: createRequest('format_disasm', {disassembly: res.data.disassembly}) }); } voltronAPI.disassemble = function(address, count) { return voltronAPI.request(createRequest('disassemble', {address: address, count: count})) } voltronAPI.command = function(command) { return voltronAPI.request(createRequest('command', {command: command})) } voltronAPI.targets = function() { return voltronAPI.request(createRequest('targets', {})) } voltronAPI.memory = function(address, length) { return voltronAPI.request(createRequest('memory', {address: address, length: length})) } voltronAPI.registers = function() { return voltronAPI.request(createRequest('registers', {})) } voltronAPI.stack = function(length) { return voltronAPI.request(createRequest('stack', {length: length})) } voltronAPI.state = function() { return voltronAPI.request(createRequest('state', {})) } voltronAPI.version = function() { return voltronAPI.request(createRequest('version', {})) } return voltronAPI; });
define("#base/0.9.2/attrs-debug", ["./util"], function(require, exports) { // Attrs // ----------------- // Thanks to: // - http://documentcloud.github.com/backbone/#Model // - http://yuilibrary.com/yui/docs/api/classes/AttributeCore.html // - https://github.com/berzniz/backbone.getters.setters var Util = require('./util'); // 负责 attributes 的初始化 // attributes 是与实例相关的状态信息,可读可写,发生变化时,会自动触发相关事件 exports.initAttrs = function(config) { // Keep existed attrs. if (!this.hasOwnProperty('attrs')) { this.attrs = {}; } var attrs = this.attrs; // Only merge all inherited attributes once. if (!attrs.__defaults) { attrs.__defaults = Util.getInherited(this, 'attrs', normalize); Util.merge(attrs, attrs.__defaults); } var options = { silent: true }; for (var key in attrs) { // only merge recognized attributes, and delete it from config // after merged. if (config && config.hasOwnProperty(key)) { this.set(key, config[key], options); delete config[key]; } // automatically register `_onChangeX` method as // 'change:x' handler. var eventKey = getChangeEventKey(key); if (this[eventKey]) { this.on('change:' + key, this[eventKey]); } } }; // Get the value of an attribute. exports.get = function(key) { var attr = this.attrs[key] || {}; var val = attr.value; return attr.getter ? attr.getter.call(this, val, key) : val; }; // Set a hash of model attributes on the object, firing `"change"` unless // you choose to silence it. exports.set = function(key, val, options) { var attrs = {}; // set("key", val, options) if (Util.isString(key)) { attrs[key] = val; } // set({ "key": val, "key2": val2 }, options) else { attrs = key; options = val; } options || (options = {}); var now = this.attrs; var silent = options.silent; for (key in attrs) { var attr = now[key] || ( now[key] = {} ); val = attrs[key]; // invoke validator if (attr.validator) { var ex = attr.validator.call(this, val, key); if (ex !== true) { if (options.error) { options.error.call(this, ex); } continue; } } // invoke setter if (attr.setter) { val = attr.setter.call(this, val, key); } // set finally var prev = this.get(key); if (Util.isPlainObject(prev) && Util.isPlainObject(val)) { val = Util.merge(Util.merge({}, prev), val); } now[key].value = val; // invoke change event if (!silent && this.trigger && prev !== val) { this.trigger('change:' + key, val, prev, key); } } }; // Helpers // ------- var ATTR_SPECIAL_KEYS = ['value', 'getter', 'setter', 'validator']; // normalize `attrs` to // // { // value: 'xx', // getter: fn, // setter: fn, // validator: fn // } // function normalize(attrs) { // clone it attrs = Util.merge({}, attrs); for (var key in attrs) { var attr = attrs[key]; if (Util.isPlainObject(attr) && hasOwnProperties(attr, ATTR_SPECIAL_KEYS)) { continue; } attrs[key] = { value: attr }; } return attrs; } function hasOwnProperties(object, properties) { for (var i = 0, len = properties.length; i < len; i++) { if (object.hasOwnProperty(properties[i])) { return true; } } return false; } function getChangeEventKey(key) { return '_onChange' + key.charAt(0).toUpperCase() + key.substring(1); } });
var MNote = (function() { function MNote(label) { if (label == '' || label == null) { label = 'Note'; } var uiElement = document.createElement('span'); $(uiElement).addClass('MNote').css({ 'transform' : MNumber.random(-8, 8) }).html(label); return uiElement; }; return MNote; })();
/** * @author mrdoob / http://mrdoob.com/ * @author ryg / http://farbrausch.de/~fg * @author mraleph / http://mrale.ph/ * @author daoshengmu / http://dsmu.me/ */ THREE.SoftwareRenderer = function ( parameters ) { console.log( 'THREE.SoftwareRenderer', THREE.REVISION ); parameters = parameters || {}; var canvas = parameters.canvas !== undefined ? parameters.canvas : document.createElement( 'canvas' ); var context = canvas.getContext( '2d', { alpha: parameters.alpha === true } ); var shaders = {}; var textures = {}; var canvasWidth, canvasHeight; var canvasWBlocks, canvasHBlocks; var viewportXScale, viewportYScale, viewportZScale; var viewportXOffs, viewportYOffs, viewportZOffs; var clearColor = new THREE.Color( 0x000000 ); var imagedata, data, zbuffer; var numBlocks, blockMaxZ, blockFlags; var BLOCK_ISCLEAR = (1 << 0); var BLOCK_NEEDCLEAR = (1 << 1); var subpixelBits = 4; var subpixelBias = (1 << subpixelBits) - 1; var blockShift = 3; var blockSize = 1 << blockShift; var maxZVal = (1 << 24); // Note: You want to size this so you don't get overflows. var rectx1 = Infinity, recty1 = Infinity; var rectx2 = 0, recty2 = 0; var prevrectx1 = Infinity, prevrecty1 = Infinity; var prevrectx2 = 0, prevrecty2 = 0; var projector = new THREE.Projector(); var vector1 = new THREE.Vector3(); var vector2 = new THREE.Vector3(); var vector3 = new THREE.Vector3(); var texCoord1 = new THREE.Vector2(); var texCoord2 = new THREE.Vector2(); var texCoord3 = new THREE.Vector2(); this.domElement = canvas; this.autoClear = true; // WebGLRenderer compatibility this.supportsVertexTextures = function () {}; this.setFaceCulling = function () {}; this.setClearColor = function ( color, alpha ) { clearColor.set( color ); cleanColorBuffer(); }; this.setPixelRatio = function () {}; this.setSize = function ( width, height ) { canvasWBlocks = Math.floor( width / blockSize ); canvasHBlocks = Math.floor( height / blockSize ); canvasWidth = canvasWBlocks * blockSize; canvasHeight = canvasHBlocks * blockSize; var fixScale = 1 << subpixelBits; viewportXScale = fixScale * canvasWidth / 2; viewportYScale = -fixScale * canvasHeight / 2; viewportZScale = maxZVal / 2; viewportXOffs = fixScale * canvasWidth / 2 + 0.5; viewportYOffs = fixScale * canvasHeight / 2 + 0.5; viewportZOffs = maxZVal / 2 + 0.5; canvas.width = canvasWidth; canvas.height = canvasHeight; context.fillStyle = clearColor.getStyle(); context.fillRect( 0, 0, canvasWidth, canvasHeight ); imagedata = context.getImageData( 0, 0, canvasWidth, canvasHeight ); data = imagedata.data; zbuffer = new Int32Array( data.length / 4 ); numBlocks = canvasWBlocks * canvasHBlocks; blockMaxZ = new Int32Array( numBlocks ); blockFlags = new Uint8Array( numBlocks ); for ( var i = 0, l = zbuffer.length; i < l; i ++ ) { zbuffer[ i ] = maxZVal; } for ( var i = 0; i < numBlocks; i ++ ) { blockFlags[ i ] = BLOCK_ISCLEAR; } cleanColorBuffer(); }; this.setSize( canvas.width, canvas.height ); this.clear = function () { rectx1 = Infinity; recty1 = Infinity; rectx2 = 0; recty2 = 0; for ( var i = 0; i < numBlocks; i ++ ) { blockMaxZ[ i ] = maxZVal; blockFlags[ i ] = (blockFlags[ i ] & BLOCK_ISCLEAR) ? BLOCK_ISCLEAR : BLOCK_NEEDCLEAR; } }; this.render = function ( scene, camera ) { if ( this.autoClear === true ) this.clear(); var renderData = projector.projectScene( scene, camera, false, false ); var elements = renderData.elements; for ( var e = 0, el = elements.length; e < el; e ++ ) { var element = elements[ e ]; var material = element.material; var shader = getMaterialShader( material ); if ( element instanceof THREE.RenderableFace ) { if ( !element.uvs ) { drawTriangle( element.v1.positionScreen, element.v2.positionScreen, element.v3.positionScreen, null, null, null, shader, element, material ); } else { drawTriangle( element.v1.positionScreen, element.v2.positionScreen, element.v3.positionScreen, element.uvs[0], element.uvs[1], element.uvs[2], shader, element, material ); } } else if ( element instanceof THREE.RenderableSprite ) { var scaleX = element.scale.x * 0.5; var scaleY = element.scale.y * 0.5; vector1.copy( element ); vector1.x -= scaleX; vector1.y += scaleY; vector2.copy( element ); vector2.x -= scaleX; vector2.y -= scaleY; vector3.copy( element ); vector3.x += scaleX; vector3.y += scaleY; if ( material.map ) { texCoord1.set( 0, 1 ); texCoord2.set( 0, 0 ); texCoord3.set( 1, 1 ); drawTriangle( vector1, vector2, vector3, texCoord1, texCoord2, texCoord3, shader, element, material ); } else { drawTriangle( vector1, vector2, vector3, null, null, null, shader, element, material ); } vector1.copy( element ); vector1.x += scaleX; vector1.y += scaleY; vector2.copy( element ); vector2.x -= scaleX; vector2.y -= scaleY; vector3.copy( element ); vector3.x += scaleX; vector3.y -= scaleY; if ( material.map ) { texCoord1.set( 1, 1 ); texCoord2.set( 0, 0 ); texCoord3.set( 1, 0 ); drawTriangle( vector1, vector2, vector3, texCoord1, texCoord2, texCoord3, shader, element, material ); } else { drawTriangle( vector1, vector2, vector3, null, null, null, shader, element, material ); } } } finishClear(); var x = Math.min( rectx1, prevrectx1 ); var y = Math.min( recty1, prevrecty1 ); var width = Math.max( rectx2, prevrectx2 ) - x; var height = Math.max( recty2, prevrecty2 ) - y; /* // debug; draw zbuffer for ( var i = 0, l = zbuffer.length; i < l; i++ ) { var o = i * 4; var v = (65535 - zbuffer[ i ]) >> 3; data[ o + 0 ] = v; data[ o + 1 ] = v; data[ o + 2 ] = v; data[ o + 3 ] = 255; } */ if ( x !== Infinity ) { context.putImageData( imagedata, 0, 0, x, y, width, height ); } prevrectx1 = rectx1; prevrecty1 = recty1; prevrectx2 = rectx2; prevrecty2 = recty2; }; function cleanColorBuffer() { var size = canvasWidth * canvasHeight * 4; for ( var i = 0; i < size; i+=4 ) { data[ i ] = clearColor.r * 255 | 0; data[ i+1 ] = clearColor.g * 255 | 0; data[ i+2 ] = clearColor.b * 255 | 0; data[ i+3 ] = 255; } context.fillStyle = clearColor.getStyle(); context.fillRect( 0, 0, canvasWidth, canvasHeight ); } function getPalette( material, bSimulateSpecular ) { var i = 0, j = 0; var diffuseR = material.color.r * 255; var diffuseG = material.color.g * 255; var diffuseB = material.color.b * 255; var palette = new Uint8Array(256*3); if ( bSimulateSpecular ) { while(i < 204) { palette[j++] = Math.min( i * diffuseR / 204, 255 ); palette[j++] = Math.min( i * diffuseG / 204, 255 ); palette[j++] = Math.min( i * diffuseB / 204, 255 ); ++i; } while(i < 256) { // plus specular highlight palette[j++] = Math.min( diffuseR + (i - 204) * (255 - diffuseR) / 82, 255 ); palette[j++] = Math.min( diffuseG + (i - 204) * (255 - diffuseG) / 82, 255 ); palette[j++] = Math.min( diffuseB + (i - 204) * (255 - diffuseB) / 82, 255 ); ++i; } } else { while(i < 256) { palette[j++] = Math.min( i * diffuseR / 255, 255 ); palette[j++] = Math.min( i * diffuseG / 255, 255 ); palette[j++] = Math.min( i * diffuseB / 255, 255 ); ++i; } } return palette; } function basicMaterialShader( buffer, depthBuf, offset, depth, u, v, n, face, material ) { var colorOffset = offset * 4; var texture = textures[ material.map.id ]; if ( !texture.data ) return; var tdim = texture.width; var isTransparent = material.transparent; var tbound = tdim - 1; var tdata = texture.data; var tIndex = (((v * tdim) & tbound) * tdim + ((u * tdim) & tbound)) * 4; if ( !isTransparent ) { buffer[ colorOffset ] = tdata[tIndex]; buffer[ colorOffset + 1 ] = tdata[tIndex+1]; buffer[ colorOffset + 2 ] = tdata[tIndex+2]; buffer[ colorOffset + 3 ] = material.opacity * 255; depthBuf[ offset ] = depth; } else { var opaci = tdata[tIndex+3] * material.opacity; var texel = (tdata[tIndex] << 16) + (tdata[tIndex+1] << 8) + tdata[tIndex+2]; if(opaci < 250) { var backColor = (buffer[colorOffset] << 16) + (buffer[colorOffset + 1] << 8) + buffer[colorOffset + 2]; texel = texel * opaci + backColor * (1-opaci); } buffer[ colorOffset ] = (texel & 0xff0000) >> 16; buffer[ colorOffset + 1 ] = (texel & 0xff00) >> 8; buffer[ colorOffset + 2 ] = texel & 0xff; buffer[ colorOffset + 3 ] = material.opacity * 255; } } function lightingMaterialShader( buffer, depthBuf, offset, depth, u, v, n, face, material ) { var colorOffset = offset * 4; var texture = textures[ material.map.id ]; if ( !texture.data ) return; var tdim = texture.width; var isTransparent = material.transparent; var cIndex = (n > 0 ? (~~n) : 0) * 3; var tbound = tdim - 1; var tdata = texture.data; var tIndex = (((v * tdim) & tbound) * tdim + ((u * tdim) & tbound)) * 4; if ( !isTransparent ) { buffer[ colorOffset ] = (material.palette[cIndex] * tdata[tIndex]) >> 8; buffer[ colorOffset + 1 ] = (material.palette[cIndex+1] * tdata[tIndex+1]) >> 8; buffer[ colorOffset + 2 ] = (material.palette[cIndex+2] * tdata[tIndex+2]) >> 8; buffer[ colorOffset + 3 ] = material.opacity * 255; depthBuf[ offset ] = depth; } else { var opaci = tdata[tIndex+3] * material.opacity; var foreColor = ((material.palette[cIndex] * tdata[tIndex]) << 16) + ((material.palette[cIndex+1] * tdata[tIndex+1]) << 8 ) + (material.palette[cIndex+2] * tdata[tIndex+2]); if(opaci < 250) { var backColor = buffer[ colorOffset ] << 24 + buffer[ colorOffset + 1 ] << 16 + buffer[ colorOffset + 2 ] << 8; foreColor = foreColor * opaci + backColor * (1-opaci); } buffer[ colorOffset ] = (foreColor & 0xff0000) >> 16; buffer[ colorOffset + 1 ] = (foreColor & 0xff00) >> 8; buffer[ colorOffset + 2 ] = (foreColor & 0xff); buffer[ colorOffset + 3 ] = material.opacity * 255; } } function onMaterialUpdate ( event ) { var material = event.target; material.removeEventListener( 'update', onMaterialUpdate ); delete shaders[ material.id ]; } function getMaterialShader( material ) { var id = material.id; var shader = shaders[ id ]; if ( shaders[ id ] === undefined ) { material.addEventListener( 'update', onMaterialUpdate ); if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.MeshLambertMaterial || material instanceof THREE.MeshPhongMaterial || material instanceof THREE.SpriteMaterial ) { if ( material instanceof THREE.MeshLambertMaterial ) { // Generate color palette if ( !material.palette ) { material.palette = getPalette( material, false ); } } else if ( material instanceof THREE.MeshPhongMaterial ) { // Generate color palette if ( !material.palette ) { material.palette = getPalette( material, true ); } } var string; if ( material.map ) { var texture = new THREE.SoftwareRenderer.Texture(); texture.fromImage( material.map.image ); material.map.addEventListener( 'update', function ( event ) { texture.fromImage( event.target.image ); } ); textures[ material.map.id ] = texture; if ( material instanceof THREE.MeshBasicMaterial || material instanceof THREE.SpriteMaterial ) { shader = basicMaterialShader; } else { shader = lightingMaterialShader; } } else { if ( material.vertexColors === THREE.FaceColors ) { string = [ 'var colorOffset = offset * 4;', 'buffer[ colorOffset ] = face.color.r * 255;', 'buffer[ colorOffset + 1 ] = face.color.g * 255;', 'buffer[ colorOffset + 2 ] = face.color.b * 255;', 'buffer[ colorOffset + 3 ] = material.opacity * 255;', 'depthBuf[ offset ] = depth;' ].join('\n'); } else { string = [ 'var colorOffset = offset * 4;', 'buffer[ colorOffset ] = material.color.r * 255;', 'buffer[ colorOffset + 1 ] = material.color.g * 255;', 'buffer[ colorOffset + 2 ] = material.color.b * 255;', 'buffer[ colorOffset + 3 ] = material.opacity * 255;', 'depthBuf[ offset ] = depth;' ].join('\n'); } shader = new Function( 'buffer, depthBuf, offset, depth, u, v, n, face, material', string ); } } else { var string = [ 'var colorOffset = offset * 4;', 'buffer[ colorOffset ] = u * 255;', 'buffer[ colorOffset + 1 ] = v * 255;', 'buffer[ colorOffset + 2 ] = 0;', 'buffer[ colorOffset + 3 ] = 255;', 'depthBuf[ offset ] = depth;' ].join('\n'); shader = new Function( 'buffer, depthBuf, offset, depth, u, v', string ); } shaders[ id ] = shader; } return shader; } function clearRectangle( x1, y1, x2, y2 ) { var xmin = Math.max( Math.min( x1, x2 ), 0 ); var xmax = Math.min( Math.max( x1, x2 ), canvasWidth ); var ymin = Math.max( Math.min( y1, y2 ), 0 ); var ymax = Math.min( Math.max( y1, y2 ), canvasHeight ); var offset = ( xmin + ymin * canvasWidth ) * 4 + 3; var linestep = ( canvasWidth - ( xmax - xmin ) ) * 4; for ( var y = ymin; y < ymax; y ++ ) { for ( var x = xmin; x < xmax; x ++ ) { data[ offset += 4 ] = 0; } offset += linestep; } } function drawTriangle( v1, v2, v3, uv1, uv2, uv3, shader, face, material ) { // TODO: Implement per-pixel z-clipping if ( v1.z < -1 || v1.z > 1 || v2.z < -1 || v2.z > 1 || v3.z < -1 || v3.z > 1 ) return; // https://gist.github.com/2486101 // explanation: http://pouet.net/topic.php?which=8760&page=1 // 28.4 fixed-point coordinates var x1 = (v1.x * viewportXScale + viewportXOffs) | 0; var x2 = (v2.x * viewportXScale + viewportXOffs) | 0; var x3 = (v3.x * viewportXScale + viewportXOffs) | 0; var y1 = (v1.y * viewportYScale + viewportYOffs) | 0; var y2 = (v2.y * viewportYScale + viewportYOffs) | 0; var y3 = (v3.y * viewportYScale + viewportYOffs) | 0; // Z values (.28 fixed-point) var z1 = (v1.z * viewportZScale + viewportZOffs) | 0; var z2 = (v2.z * viewportZScale + viewportZOffs) | 0; var z3 = (v3.z * viewportZScale + viewportZOffs) | 0; // UV values var bHasUV = false; var tu1, tv1, tu2, tv2, tu3, tv3; if ( uv1 && uv2 && uv3 ) { bHasUV = true; tu1 = uv1.x; tv1 = 1-uv1.y; tu2 = uv2.x; tv2 = 1-uv2.y; tu3 = uv3.x; tv3 = 1-uv3.y; } // Normal values var bHasNormal = false; var n1, n2, n3, nz1, nz2, nz3; if ( face.vertexNormalsModel ) { bHasNormal = true; n1 = face.vertexNormalsModel[0]; n2 = face.vertexNormalsModel[1]; n3 = face.vertexNormalsModel[2]; nz1 = n1.z * 255; nz2 = n2.z * 255; nz3 = n3.z * 255; } // Deltas var dx12 = x1 - x2, dy12 = y2 - y1; var dx23 = x2 - x3, dy23 = y3 - y2; var dx31 = x3 - x1, dy31 = y1 - y3; // Bounding rectangle var minx = Math.max( ( Math.min( x1, x2, x3 ) + subpixelBias ) >> subpixelBits, 0 ); var maxx = Math.min( ( Math.max( x1, x2, x3 ) + subpixelBias ) >> subpixelBits, canvasWidth ); var miny = Math.max( ( Math.min( y1, y2, y3 ) + subpixelBias ) >> subpixelBits, 0 ); var maxy = Math.min( ( Math.max( y1, y2, y3 ) + subpixelBias ) >> subpixelBits, canvasHeight ); rectx1 = Math.min( minx, rectx1 ); rectx2 = Math.max( maxx, rectx2 ); recty1 = Math.min( miny, recty1 ); recty2 = Math.max( maxy, recty2 ); // Block size, standard 8x8 (must be power of two) var q = blockSize; // Start in corner of 8x8 block minx &= ~(q - 1); miny &= ~(q - 1); // Constant part of half-edge functions var minXfixscale = (minx << subpixelBits); var minYfixscale = (miny << subpixelBits); var c1 = dy12 * ((minXfixscale) - x1) + dx12 * ((minYfixscale) - y1); var c2 = dy23 * ((minXfixscale) - x2) + dx23 * ((minYfixscale) - y2); var c3 = dy31 * ((minXfixscale) - x3) + dx31 * ((minYfixscale) - y3); // Correct for fill convention if ( dy12 > 0 || ( dy12 == 0 && dx12 > 0 ) ) c1 ++; if ( dy23 > 0 || ( dy23 == 0 && dx23 > 0 ) ) c2 ++; if ( dy31 > 0 || ( dy31 == 0 && dx31 > 0 ) ) c3 ++; // Note this doesn't kill subpixel precision, but only because we test for >=0 (not >0). // It's a bit subtle. :) c1 = (c1 - 1) >> subpixelBits; c2 = (c2 - 1) >> subpixelBits; c3 = (c3 - 1) >> subpixelBits; // Z interpolation setup var dz12 = z1 - z2, dz31 = z3 - z1; var invDet = 1.0 / (dx12*dy31 - dx31*dy12); var dzdx = (invDet * (dz12*dy31 - dz31*dy12)); // dz per one subpixel step in x var dzdy = (invDet * (dz12*dx31 - dx12*dz31)); // dz per one subpixel step in y // Z at top/left corner of rast area var cz = ( z1 + ((minXfixscale) - x1) * dzdx + ((minYfixscale) - y1) * dzdy ) | 0; // Z pixel steps var fixscale = (1 << subpixelBits); dzdx = (dzdx * fixscale) | 0; dzdy = (dzdy * fixscale) | 0; var dtvdx, dtvdy, cbtu, cbtv; if ( bHasUV ) { // UV interpolation setup var dtu12 = tu1 - tu2, dtu31 = tu3 - tu1; var dtudx = (invDet * (dtu12*dy31 - dtu31*dy12)); // dtu per one subpixel step in x var dtudy = (invDet * (dtu12*dx31 - dx12*dtu31)); // dtu per one subpixel step in y var dtv12 = tv1 - tv2, dtv31 = tv3 - tv1; dtvdx = (invDet * (dtv12*dy31 - dtv31*dy12)); // dtv per one subpixel step in x dtvdy = (invDet * (dtv12*dx31 - dx12*dtv31)); // dtv per one subpixel step in y // UV at top/left corner of rast area cbtu = ( tu1 + (minXfixscale - x1) * dtudx + (minYfixscale - y1) * dtudy ); cbtv = ( tv1 + (minXfixscale - x1) * dtvdx + (minYfixscale - y1) * dtvdy ); // UV pixel steps dtudx = dtudx * fixscale; dtudy = dtudy * fixscale; dtvdx = dtvdx * fixscale; dtvdy = dtvdy * fixscale; } var dnxdx, dnzdy, cbnz; if ( bHasNormal ) { // Normal interpolation setup var dnz12 = nz1 - nz2, dnz31 = nz3 - nz1; var dnzdx = (invDet * (dnz12*dy31 - dnz31*dy12)); // dnz per one subpixel step in x var dnzdy = (invDet * (dnz12*dx31 - dx12*dnz31)); // dnz per one subpixel step in y // Normal at top/left corner of rast area cbnz = ( nz1 + (minXfixscale - x1) * dnzdx + (minYfixscale - y1) * dnzdy ); // Normal pixel steps dnzdx = (dnzdx * fixscale); dnzdy = (dnzdy * fixscale); } // Set up min/max corners var qm1 = q - 1; // for convenience var nmin1 = 0, nmax1 = 0; var nmin2 = 0, nmax2 = 0; var nmin3 = 0, nmax3 = 0; var nminz = 0, nmaxz = 0; if (dx12 >= 0) nmax1 -= qm1*dx12; else nmin1 -= qm1*dx12; if (dy12 >= 0) nmax1 -= qm1*dy12; else nmin1 -= qm1*dy12; if (dx23 >= 0) nmax2 -= qm1*dx23; else nmin2 -= qm1*dx23; if (dy23 >= 0) nmax2 -= qm1*dy23; else nmin2 -= qm1*dy23; if (dx31 >= 0) nmax3 -= qm1*dx31; else nmin3 -= qm1*dx31; if (dy31 >= 0) nmax3 -= qm1*dy31; else nmin3 -= qm1*dy31; if (dzdx >= 0) nmaxz += qm1*dzdx; else nminz += qm1*dzdx; if (dzdy >= 0) nmaxz += qm1*dzdy; else nminz += qm1*dzdy; // Loop through blocks var linestep = canvasWidth - q; var scale = 1.0 / (c1 + c2 + c3); var cb1 = c1; var cb2 = c2; var cb3 = c3; var cbz = cz; var qstep = -q; var e1x = qstep * dy12; var e2x = qstep * dy23; var e3x = qstep * dy31; var ezx = qstep * dzdx; var etux, etvx; if ( bHasUV ) { etux = qstep * dtudx; etvx = qstep * dtvdx; } var enzx; if ( bHasNormal ) { enzx = qstep * dnzdx; } var x0 = minx; for ( var y0 = miny; y0 < maxy; y0 += q ) { // New block line - keep hunting for tri outer edge in old block line dir while ( x0 >= minx && x0 < maxx && cb1 >= nmax1 && cb2 >= nmax2 && cb3 >= nmax3 ) { x0 += qstep; cb1 += e1x; cb2 += e2x; cb3 += e3x; cbz += ezx; if ( bHasUV ) { cbtu += etux; cbtv += etvx; } if ( bHasNormal ) { cbnz += enzx; } } // Okay, we're now in a block we know is outside. Reverse direction and go into main loop. qstep = -qstep; e1x = -e1x; e2x = -e2x; e3x = -e3x; ezx = -ezx; if ( bHasUV ) { etux = -etux; etvx = -etvx; } if ( bHasNormal ) { enzx = -enzx; } while ( 1 ) { // Step everything x0 += qstep; cb1 += e1x; cb2 += e2x; cb3 += e3x; cbz += ezx; if ( bHasUV ) { cbtu += etux; cbtv += etvx; } if ( bHasNormal ) { cbnz += enzx; } // We're done with this block line when at least one edge completely out // If an edge function is too small and decreasing in the current traversal // dir, we're done with this line. if (x0 < minx || x0 >= maxx) break; if (cb1 < nmax1) if (e1x < 0) break; else continue; if (cb2 < nmax2) if (e2x < 0) break; else continue; if (cb3 < nmax3) if (e3x < 0) break; else continue; // We can skip this block if it's already fully covered var blockX = x0 >> blockShift; var blockY = y0 >> blockShift; var blockId = blockX + blockY * canvasWBlocks; var minz = cbz + nminz; // farthest point in block closer than closest point in our tri? if ( blockMaxZ[ blockId ] < minz ) continue; // Need to do a deferred clear? var bflags = blockFlags[ blockId ]; if ( bflags & BLOCK_NEEDCLEAR) clearBlock( blockX, blockY ); blockFlags[ blockId ] = bflags & ~( BLOCK_ISCLEAR | BLOCK_NEEDCLEAR ); // Offset at top-left corner var offset = x0 + y0 * canvasWidth; // Accept whole block when fully covered if ( cb1 >= nmin1 && cb2 >= nmin2 && cb3 >= nmin3 ) { var maxz = cbz + nmaxz; blockMaxZ[ blockId ] = Math.min( blockMaxZ[ blockId ], maxz ); var cy1 = cb1; var cy2 = cb2; var cyz = cbz; var cytu, cytv; if ( bHasUV ) { cytu = cbtu; cytv = cbtv; } var cynz; if ( bHasNormal ) { cynz = cbnz; } for ( var iy = 0; iy < q; iy ++ ) { var cx1 = cy1; var cx2 = cy2; var cxz = cyz; var cxtu; var cxtv; if ( bHasUV ) { cxtu = cytu; cxtv = cytv; } var cxnz; if ( bHasNormal ) { cxnz = cynz; } for ( var ix = 0; ix < q; ix ++ ) { var z = cxz; if ( z < zbuffer[ offset ] ) { shader( data, zbuffer, offset, z, cxtu, cxtv, cxnz, face, material ); } cx1 += dy12; cx2 += dy23; cxz += dzdx; if ( bHasUV ) { cxtu += dtudx; cxtv += dtvdx; } if ( bHasNormal ) { cxnz += dnzdx; } offset++; } cy1 += dx12; cy2 += dx23; cyz += dzdy; if ( bHasUV ) { cytu += dtudy; cytv += dtvdy; } if ( bHasNormal ) { cynz += dnzdy; } offset += linestep; } } else { // Partially covered block var cy1 = cb1; var cy2 = cb2; var cy3 = cb3; var cyz = cbz; var cytu, cytv; if ( bHasUV ) { cytu = cbtu; cytv = cbtv; } var cynz; if ( bHasNormal ) { cynz = cbnz; } for ( var iy = 0; iy < q; iy ++ ) { var cx1 = cy1; var cx2 = cy2; var cx3 = cy3; var cxz = cyz; var cxtu; var cxtv; if ( bHasUV ) { cxtu = cytu; cxtv = cytv; } var cxnz; if ( bHasNormal ) { cxnz = cynz; } for ( var ix = 0; ix < q; ix ++ ) { if ( ( cx1 | cx2 | cx3 ) >= 0 ) { var z = cxz; if ( z < zbuffer[ offset ] ) { shader( data, zbuffer, offset, z, cxtu, cxtv, cxnz, face, material ); } } cx1 += dy12; cx2 += dy23; cx3 += dy31; cxz += dzdx; if ( bHasUV ) { cxtu += dtudx; cxtv += dtvdx; } if ( bHasNormal ) { cxnz += dnzdx; } offset++; } cy1 += dx12; cy2 += dx23; cy3 += dx31; cyz += dzdy; if ( bHasUV ) { cytu += dtudy; cytv += dtvdy; } if ( bHasNormal ) { cynz += dnzdy; } offset += linestep; } } } // Advance to next row of blocks cb1 += q*dx12; cb2 += q*dx23; cb3 += q*dx31; cbz += q*dzdy; if ( bHasUV ) { cbtu += q*dtudy; cbtv += q*dtvdy; } if ( bHasNormal ) { cbnz += q*dnzdy; } } } function clearBlock( blockX, blockY ) { var zoffset = blockX * blockSize + blockY * blockSize * canvasWidth; var poffset = zoffset * 4; var zlinestep = canvasWidth - blockSize; var plinestep = zlinestep * 4; for ( var y = 0; y < blockSize; y ++ ) { for ( var x = 0; x < blockSize; x ++ ) { zbuffer[ zoffset ++ ] = maxZVal; data[ poffset ++ ] = clearColor.r * 255 | 0; data[ poffset ++ ] = clearColor.g * 255 | 0; data[ poffset ++ ] = clearColor.b * 255 | 0; data[ poffset ++ ] = 255; } zoffset += zlinestep; poffset += plinestep; } } function finishClear( ) { var block = 0; for ( var y = 0; y < canvasHBlocks; y ++ ) { for ( var x = 0; x < canvasWBlocks; x ++ ) { if ( blockFlags[ block ] & BLOCK_NEEDCLEAR ) { clearBlock( x, y ); blockFlags[ block ] = BLOCK_ISCLEAR; } block ++; } } } }; THREE.SoftwareRenderer.Texture = function() { var canvas; this.fromImage = function( image ) { if( !image || image.width <= 0 || image.height <= 0 ) return; if ( canvas === undefined ) { canvas = document.createElement( 'canvas' ); } var size = image.width > image.height ? image.width : image.height; size = THREE.Math.nextPowerOfTwo( size ); if ( canvas.width != size || canvas.height != size) { canvas.width = size; canvas.height = size; } var ctx = canvas.getContext('2d'); ctx.clearRect( 0, 0, size, size ); ctx.drawImage( image, 0, 0, size, size ); var imgData = ctx.getImageData( 0, 0, size, size ); this.data = imgData.data; this.width = size; this.height = size; this.srcUrl = image.src; }; };
class msvidctl_msvidaudiorendererdevices_1 { constructor() { // IMSVidAudioRenderer Item (Variant) {get} this.Parameterized = undefined; // int Count () {get} this.Count = undefined; } // void Add (IMSVidAudioRenderer) Add(IMSVidAudioRenderer) { } // void Remove (Variant) Remove(Variant) { } } module.exports = msvidctl_msvidaudiorendererdevices_1;
/** * Created by Administrator on 2015/1/6. */ var grunt = require("grunt"); var htmlConverter = require("../tasks/lib/text").init(grunt); describe("Test JSON Converter",function(){ it("should convert JSON to cmd module",function(){ var code = JSON.stringify({test:"test",value:1,number:2.2}); var e = 'define("test",[],"{\\\"test\\\":\\\"test\\\",\\\"value\\\":1,\\\"number\\\":2.2}");'; expect(htmlConverter.html2js(code,"test")).toEqual(e); }); it("should convert JSON file to cmd module",function(){ var src = "test/fixture/no-modifier.json"; var dest = "test/tmp/no-modifier.json"; var output = htmlConverter.htmlConverter({ src : src, dest : dest },{}); expect(grunt.file.read(dest+".js")).toEqual(grunt.file.read("test/expect/no-modifier.json.js")); }) });
/*global jQuery:true*/ (function($, window){ "use strict"; function MaxlengthInput( el ){ var self = this; this.el = el; this.$el = $(el); // prevent double init if( this.$el.data( "MaxlengthInput" ) ){ return; } this.$el.data( "MaxlengthInput", this); this.maxlength = this.$el.attr("maxlength"); this.$el .bind("keydown", function(event){ // prevent extra text entry based on the maxlength self.onKeydown(event); }) .bind("paste", function(event){ // prevent extra characters in the form element from pastes self.onPaste(event); }); } MaxlengthInput.allowedKeys = [ 9, // Tab 27, // Escape 8, // Backspace 39, // ArrowRight 37, // ArrowLeft 38, // ArrowUp 40 // ArrowDown ]; MaxlengthInput.returnRegex = /\r\n|\n/g; // TODO shared behavior with NumericInput MaxlengthInput.prototype.isKeyAllowed = function( event ) { var isAllowed = false, key = event.keyCode; // indexOf not supported everywhere for arrays $.each(MaxlengthInput.allowedKeys, function(i, e){ if( e === key ) { isAllowed = true; } }); return event.altKey || event.ctrlKey || event.metaKey || isAllowed; }; MaxlengthInput.prototype.onKeydown = function( event ){ var self = this; if( this.isKeyAllowed( event ) ){ return; } // if any character would put us at the if(this.valueLength() >= this.maxlength){ event.preventDefault(); return; } // if the user hits return and that would put the length above // the max, prevent the return character addition if(event.keyCode == 13 && this.valueLength() + 2 > this.maxlength){ event.preventDefault(); return; } setTimeout(function(){ self.alterValue(); }); }; MaxlengthInput.prototype.alterValue = function(){ var newValue = this.el .value .replace(MaxlengthInput.returnRegex, "\r\n") .slice(0, this.maxlength); return this.el.value = newValue; }; MaxlengthInput.prototype.onPaste = function( e ){ var self = this; // force the text to look right after the paste has applied setTimeout(function(){ self.alterValue(); }); }; MaxlengthInput.prototype.valueLength = function(check){ return (check || this.el.value) .replace(MaxlengthInput.returnRegex, "__") .length; }; window.MaxlengthInput = MaxlengthInput; }(jQuery, this));
'use strict'; // This file is auto-generated using scripts/doc-sync.js /** * Visible page viewport * * @param {number} scrollX X scroll offset in CSS pixels. * @param {number} scrollY Y scroll offset in CSS pixels. * @param {number} contentsWidth Contents width in CSS pixels. * @param {number} contentsHeight Contents height in CSS pixels. * @param {number} pageScaleFactor Page scale factor. * @param {number} minimumPageScaleFactor Minimum page scale factor. * @param {number} maximumPageScaleFactor Maximum page scale factor. */ exports.Viewport = function Viewport(props) { this.scrollX = props.scrollX; this.scrollY = props.scrollY; this.contentsWidth = props.contentsWidth; this.contentsHeight = props.contentsHeight; this.pageScaleFactor = props.pageScaleFactor; this.minimumPageScaleFactor = props.minimumPageScaleFactor; this.maximumPageScaleFactor = props.maximumPageScaleFactor; };
version https://git-lfs.github.com/spec/v1 oid sha256:3027fc57c3d0f37949a71c0e7f6cecae9198b13aa8ac666d1a752323b776547f size 97712
var myWindow = { screenX: window.screenX, screenY: window.screenY, location: window.location.pathname, screenW: window.screen.width, screenZ: window.screen.height, render: function() { var ele = document.getElementById("location"); ele.value = this.location; ele = document.getElementById("sx"); ele.value = this.screenX; ele = document.getElementById("sy"); ele.value = this.screenY; ele = document.getElementById("sw"); ele.value = this.screenW; ele = document.getElementById("sz"); ele.value = this.screenZ; } }; myWindow.render();
import { module, test } from 'qunit'; import { setupApplicationTest } from 'travis/tests/helpers/setup-application-test'; import jobPage from 'travis/tests/pages/job'; import topPage from 'travis/tests/pages/top'; import signInUser from 'travis/tests/helpers/sign-in-user'; import { enableFeature } from 'ember-feature-flags/test-support'; import { percySnapshot } from 'ember-percy'; import { setupMirage } from 'ember-cli-mirage/test-support'; module('Acceptance | jobs/debug', function (hooks) { setupApplicationTest(hooks); setupMirage(hooks); test('debugging job', async function (assert) { enableFeature('debugBuilds'); const currentUser = this.server.create('user', { confirmed_at: Date.now() }); this.server.create('allowance', {subscription_type: 1}); this.server.create('user', {login: 'travis-ci'}); this.server.create('allowance', {subscription_type: 1}); signInUser(currentUser); let repo = this.server.create('repository', { slug: 'travis-ci/travis-web', private: true, owner: { login: 'travis-ci', id: 1 } }); let branch = this.server.create('branch', { name: 'acceptance-tests' }); let gitUser = this.server.create('git-user', { name: 'Mr T' }); let commit = this.server.create('commit', { author: gitUser, committer: gitUser, branch: 'acceptance-tests', message: 'This is a message', branch_is_default: true }); let build = this.server.create('build', { repository: repo, state: 'failed', commit, branch }); let job = this.server.create('job', { number: '1234.1', repository: repo, state: 'failed', commit, build }); commit.job = job; job.save(); commit.save(); this.server.create('log', { id: job.id }); const requestBodies = []; this.server.post(`/job/${job.id}/debug`, function (schema, request) { const parsedRequestBody = JSON.parse(request.requestBody); requestBodies.push(parsedRequestBody); }); await jobPage .visit() .debugJob(); assert.deepEqual(requestBodies.pop(), { quiet: true }); assert.equal(topPage.flashMessage.text, 'The job was successfully restarted in debug mode but make sure to watch the log for a host to connect to.'); percySnapshot(assert); }); });
var net = require('net'); var HOST = '128.197.50.236'; var PORT = 55000; var n=1; var client = new net.Socket(); var RollingSpider = new require('rolling-spider'); var quad = new RollingSpider({ logger: console.log }); var flying = false; var inFlip = false; var land = false; var count=0; var prevControls; quad.connect(function(err) { if (err) console.log(err); quad.setup(function(err) { if (err) console.log(err); quad.flatTrim(); quad.startPing(); quad.flatTrim(); client.connect(PORT, HOST, function() { console.log('CONNECTED TO: ' + HOST + ':' + PORT); // Write a message to the socket as soon as the client is connected, the server will receive it as message from the client // client.write('I am Chuck Norris!'); }); // Add a 'data' event handler for the client socket // data is what the server sent to this socket client.on('data', function(data) { console.log('DATA: ' + data); if (data == 3 && flying == false){ quad.flatTrim(); quad.takeoff(); console.log('takeoff'); flying = true; count=0; } else if (data == 2 && flying==true && count<3){ count=count+1; } else if (data == 2 && flying== true && count >= 3){ quad.land(); flying = false; console.log('landing'); count=0; } else if (data == 6 && flying== true && inFlip == false){ inFlip = true; quad.frontFlip(flipDone); console.log('frontflip'); count=0; } else if (data == 11 && flying== true && inFlip == false){ inFlip = true; quad.backFlip(flipDone); console.log('backflip'); count=0; } else quad.hover(); // Close the client socket completely //client.destroy(); }); }); }); function flipDone() { inFlip = false; } // Add a 'clos joystick.on('data', function(buf) { /* var controls = parseControls(buf); if (!prevControls) prevControls = controls; if (prevControls.buttons[0] === 0 && controls.buttons[0] === 1) { if (flying) { quad.land(); flying = false; } else { quad.flatTrim(); quad.takeoff(); flying = true; } } if (prevControls.view === 8 && controls.view !== 8) switch (controls.view) { case 0: inFlip = true; quad.frontFlip(flipDone); break; case 2: inFlip = true; quad.rightFlip(flipDone); break; case 4: inFlip = true; quad.backFlip(flipDone); break; case 6: inFlip = true; quad.leftFlip(flipDone); break; } prevControls = controls; if (flying && !inFlip) { if (controls.buttons[1]) { quad.driveStepsRemaining = 1; quad.speeds = { yaw: 100 * (controls.yaw - 128) / 128, pitch: -100 * (controls.pitch - 512) / 512, roll: 100 * (controls.roll - 512) / 512, altitude: 100 * (controls.throttle - 128) / 128 } } else quad.hover(); } // console.log(JSON.stringify(controls)); }); joystick.on('error', function() { quad.land(); }); }); }); function flipDone() { inFlip = false; } function parseControls(buf) { var ch = buf.toString('hex').match(/.{1,2}/g).map(function(c) { return parseInt(c, 16); }); return { roll: ((ch[1] & 0x03) << 8) + ch[0], pitch: ((ch[2] & 0x0f) << 6) + ((ch[1] & 0xfc) >> 2), yaw: ch[3], view: (ch[2] & 0xf0) >> 4, throttle: -ch[5] + 255, buttons: [ (ch[4] & 0x01) >> 0, (ch[4] & 0x02) >> 1, (ch[4] & 0x04) >> 2, (ch[4] & 0x08) >> 3, (ch[4] & 0x10) >> 4, (ch[4] & 0x20) >> 5, (ch[4] & 0x40) >> 6, (ch[4] & 0x80) >> 7, (ch[6] & 0x01) >> 0, (ch[6] & 0x02) >> 1, (ch[6] & 0x04) >> 2, (ch[6] & 0x08) >> 3 ] } }e' event handler for the client socket client.on('close', function() { console.log('Connection closed'); }); */ //var hid = require('node-hid'); // console.log(hid.devices()); // Logitech Extreme 3D Pro's vendorID and productID: 1133:49685 (i.e. 046d:c215) //var joystick = new hid.HID(1133, 49685); // console.log(joystick);
import React from 'react'; import classes from 'classnames'; import Feed from 'src/components/Feed'; import equip from './equip'; const Content = ({ isFetching, posts, postCount, lastUpdated }) => ( <div> {isFetching && posts.length === 0 && <h2>Loading...</h2> } {!isFetching && posts.length === 0 && <h2>Empty.</h2> } {postCount > 0 && <div> {lastUpdated && <sub className={classes('pa3', 'top-075', 'grey-text')}> Last updated at {new Date(lastUpdated).toLocaleTimeString()} </sub> } <Feed style={{ opacity: isFetching ? 0.5 : 1 }} /> </div> } </div> ); export default equip(Content);
import path from 'path' import webpack from 'webpack' import UglifyJsPlugin from 'uglifyjs-webpack-plugin' const config = { mode: process.env.NODE_ENV, entry: [ './src/index.js' ], output: { path: path.resolve(__dirname, 'dist'), filename: process.env.NODE_ENV === 'production' ? 'threesixty.min.js' : 'threesixty.js', library: 'threesixty', libraryTarget: 'umd', umdNamedDefine: true }, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: [ { loader: 'babel-loader' } ] } ] }, plugins: [ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify(process.env.NODE_ENV) } }), ], optimization: { minimizer: [ new UglifyJsPlugin({ uglifyOptions: { ie8: false, warnings: false, }, }) ] }, } export default config
import { normalizeToInterval } from './format.js' import { client } from '../plugins/Platform.js' export const FOCUSABLE_SELECTOR = [ 'a[href]:not([tabindex="-1"]):not(.q-focus__clone)', 'area[href]:not([tabindex="-1"]):not(.q-focus__clone)', 'input:not([disabled]):not([tabindex="-1"]):not(.q-focus__clone)', 'select:not([disabled]):not([tabindex="-1"]):not(.q-focus__clone)', 'textarea:not([disabled]):not([tabindex="-1"]):not(.q-focus__clone)', 'button:not([disabled]):not([tabindex="-1"]):not(.q-focus__clone)', 'iframe:not([tabindex="-1"]):not(.q-focus__clone)', '[tabindex]:not([tabindex="-1"]):not(.q-focus__clone)', '[contenteditable]:not([tabindex="-1"]):not(.q-focus__clone):not([contenteditable="false"])', '.q-tab.q-focusable:not(.q-focus__clone)' ].join(',') export const KEY_SKIP_SELECTOR = [ 'input:not([disabled])', 'select:not([disabled])', 'select:not([disabled]) *', 'textarea:not([disabled])', '[contenteditable]:not([contenteditable="false"])', '[contenteditable]:not([contenteditable="false"]) *', '.q-key-group-navigation--ignore-key', '.q-key-group-navigation--ignore-key *', '.q-focus__clone' ].join(',') export const EDITABLE_SELECTOR = [ 'input:not(.q-focus__clone):not([disabled]):not([readonly]):not([type="button"]):not([type="checkbox"]):not([type="file"]):not([type="hidden"]):not([type="image"]):not([type="radio"]):not([type="range"]):not([type="reset"]):not([type="submit"])', 'textarea:not(.q-focus__clone):not([disabled]):not([readonly])', '[contenteditable]:not(.q-focus__clone):not([contenteditable="false"])', '[contenteditable]:not(.q-focus__clone):not([contenteditable="false"]) *' ].join(',') let scrollOffset = 0 let managedFocusFn export function managedFocus (el) { if (managedFocusFn === void 0) { const scrollIntoView = typeof el.scrollIntoViewIfNeeded === 'function' ? target => { target.scrollIntoViewIfNeeded(false) } : target => { target.scrollIntoView() } managedFocusFn = client.is.ios === true || client.is.nativeMobile === true || window.matchMedia('(display-mode: standalone)').matches === true ? el => { const elIsEditable = el.matches(EDITABLE_SELECTOR) if ( el === document.body || (elIsEditable !== true && el.tabIndex < 0) ) { el !== document.activeElement && el.focus({ preventScroll: true }) return } const elInPortal = el.matches('.q-dialog *, .q-menu *, .q-tooltip *, .q-stepper__step-content *') const clone = el.cloneNode(true) const parent = el.parentNode const scrollingElement = document.scrollingElement || document.documentElement const initialScrollTop = scrollingElement.scrollTop clone.setAttribute('tabindex', -1) clone.removeAttribute('id') clone.removeAttribute('autofocus') clone.removeAttribute('data-autofocus') clone.classList.add('q-focus__clone') parent.insertBefore(clone, el) el !== document.activeElement && el.focus({ preventScroll: true }) setTimeout(() => { clone.remove() if (el && el === document.activeElement && elIsEditable === true) { elInPortal === true && scrollIntoView(el) const { top, bottom } = el.getBoundingClientRect(), height = window.visualViewport !== void 0 ? window.visualViewport.height : window.innerHeight let finalScrollTop = scrollingElement.scrollTop if (top < 0) { finalScrollTop += top - 32 } else if (top > 0 && bottom > height) { finalScrollTop += bottom - height + 64 } requestAnimationFrame(() => { scrollingElement.scrollTop = finalScrollTop }) if (el.qRestoreScrollSet !== true && elInPortal !== true) { scrollOffset += finalScrollTop - initialScrollTop const restoreScrollFn = () => { if (el) { el.qRestoreScrollSet = void 0 el.removeEventListener('blur', restoreScrollFn) } if (scrollingElement.scrollTop !== finalScrollTop) { scrollOffset = 0 } else if (scrollOffset !== 0) { requestAnimationFrame(() => { const { activeElement } = document if ( !activeElement || (activeElement.matches(EDITABLE_SELECTOR) !== true && activeElement.tabIndex < 0) ) { scrollingElement.scrollTop -= scrollOffset scrollOffset = 0 } }) } } el.qRestoreScrollSet = true el.addEventListener('blur', restoreScrollFn) } } }, 200) } : el => { const elInPortal = el.matches('.q-dialog *, .q-menu *, .q-tooltip *, .q-stepper__step-content *') const elIsEditable = el.matches(EDITABLE_SELECTOR) el !== document.activeElement && el.focus({ preventScroll: true }) if (elInPortal === true && elIsEditable === true) { setTimeout(() => { el && el === document.activeElement && scrollIntoView(el) }, 200) } } } managedFocusFn(el) } export function changeFocusedElement (list, to, direction = 1, managed, noWrap, start) { const lastIndex = list.length - 1 if (noWrap === true && (to > lastIndex || to < 0)) { return } const index = normalizeToInterval(to, 0, lastIndex) if (index === start || index > lastIndex) { return } const initialEl = document.activeElement const focusFn = managed === true ? () => { managedFocus(list[index]) } : () => { list[index].focus() } if (initialEl !== null) { initialEl._qKeyNavIgnore = true focusFn() initialEl._qKeyNavIgnore = false } else { focusFn() } if (document.activeElement !== list[index]) { changeFocusedElement(list, index + direction, direction, managed, noWrap, start === void 0 ? index : start) } }
var express = require('express'); var router = express.Router(); // use auth_token cookie to secure the angular /app files //TODO this needs to be reworked since someone could spoof //a legitimate cookie named auth_token. Need to actually verify //the cookie router.use('/', function (req, res, next) { if (!req.cookies.auth_token) { return res.redirect('/login?returnUrl=' + encodeURIComponent('/app' + req.path)); } next(); }); // serve angular app files from the '/app' route router.use('/', express.static('app')); module.exports = router;
var mongoose = require("../../database/"); var UserSchema = mongoose.Schema({ username: String, password: String, lastLoginTime: Date, createTime: Date, userType: String, // admin,normal projectList: [ { _id: Object, name: String } ] }); module.exports = UserSchema;
define(['angular'], function(angular) { 'use strict'; return angular.module('biomsef.filter', [ ]); });
export const ic_picture_in_picture_alt_outline = {"viewBox":"0 0 24 24","children":[{"name":"path","attribs":{"d":"M0 0h24v24H0V0z","fill":"none"},"children":[]},{"name":"path","attribs":{"d":"M19 11h-8v6h8v-6zm-2 4h-4v-2h4v2zm4-12H3c-1.1 0-2 .88-2 1.98V19c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V4.98C23 3.88 22.1 3 21 3zm0 16.02H3V4.97h18v14.05z"},"children":[]}]};
/** * Controller module. * This is the unique master controller, with tiny controllers for each view. * Our project is not large scaled, so our controllers can all stay together * happily like a family. * @module shell */ 'use strict'; var helpers = require('./helpers'); var model = require('./model'); // var page = require('page'); var pubSub = require('pubsub-js'); var notie = require('notie'); /* Views */ var views = {}; views.peopleList = require('./views/people-list'); views.chat = require('./views/chat'); views.account = require('./views/account'); var configMap = { }; var isTesting = true; var _testing = function() { // model.people.login('Alfred'); }; /////////////////////////// // VIEWS EVENTS HANDLERS // /////////////////////////// /* ACCOUNT */ var _onSignClick = function() { var currentUser = model.people.getCurrentUser(); if(currentUser.getIsAnon()) { notie.input('Please sign-in with a nickname: ', 'Sign-in', 'Cancel', 'text', 'Nickname', function(userName) { if( (userName.length < 3) || (userName.length > 12) ) { notie.alert(3, 'Sorry, username must be between 3 and 12 characters'); } else { model.people.login(userName); document.qs('.account .sign').textContent = '... Processing ...'; } }); } else { model.people.logout(); } return false; }; /* PEOPLE LIST */ var onSetChatee = function(personId) { model.chat.setChatee(personId); }; /* CHAT */ var onSubmitMsg = function(msgText) { if(!model.chat.getChatee()) { return; } model.chat.sendMsg(msgText); }; //////////////////////////////////// // RENDERING VIEWS WHEN USER LOGS IN // //////////////////////////////////// var onLogin = function() { //people-list views.peopleList.init(); views.peopleList.bind('setChatee', onSetChatee); //chat views.chat.init(); views.chat.bind('submitMsg', onSubmitMsg); }; /** * PUBLIC FUNCTIONS */ var configModule = function(inputMap) { helpers.configMap(inputMap, configMap); }; var init = function() { //Account views.account.init(); views.account.bind('onSignClick', _onSignClick); //People list //When user is logged in pubSub.subscribe('login', onLogin); if(isTesting) { _testing(); } }; module.exports = { /** configures the module configMap */ configModule: configModule, /** init shell module */ init: init };
Ext.define("Com.GatotKaca.ERP.module.Personal.view.grids.Experience",{extend:"Com.GatotKaca.ERP.module.HumanResources.view.grids.Experience",alias:"widget.gridprexperience",id:"gridprexperience",title:"Experiences",store:"Com.GatotKaca.ERP.module.Personal.store.Experience"});
'use strict'; const chalk = require('chalk'); const inquirer = require('inquirer'); const labels = require('./labels'); module.exports = { multipleWordsInput: (input) => { // node index.js add Super Mario World returns Super Mario World return input.splice(3).join(' '); }, calculateGames: (games) => { return console.log(chalk.cyan(games.length) + ` ${labels.log.gamesInCollection}`); }, gameAdded: (game) => { return console.log(chalk.yellow(chalk.bold(game) + ` ${labels.log.insertedIntoCollection}`)); }, gameRemoved: (game) => { return console.log(chalk.yellow(chalk.bold(game) + ` ${labels.log.removedFromCollection}`)); }, console: (type, message, style) => { if (type === 'log') { console.log( style ? chalk[style](chalk.dim(message)) : chalk.dim(message) ); } if (type === 'warning') { console.log( style ? chalk[style](chalk.yellow(message)) : chalk.yellow(message) ); } if (type === 'success') { console.log( style ? chalk[style](chalk.green(message)) : chalk.green(message) ); } if (type === 'error') { console.log( style ? chalk[style](chalk.red(message)) : chalk.red(message) ); } }, dialog: async (dialogType, dialogMessage, dialogName, dialogChoices, dialogPageSize, dialogNoSelectionMessage) => { return await inquirer.prompt([{ type: dialogType, message: dialogMessage, name: dialogName, choices: dialogChoices, pageSize: dialogPageSize, validate: (answer) => { if (answer.length < 1) { return dialogNoSelectionMessage; } return true; } }]); }, getMatchedGame: (gameFromDB, gamesFromAPI) => { for (const item of gamesFromAPI) { if (gameFromDB.title === item.title && gameFromDB.platform === item.platform) { module.exports.console('success', `${item.title} | ${item.platform}`); return item; } } module.exports.console('error', `${gameFromDB.title} | ${gameFromDB.platform}`); return null; } };
var os = require('os'); var url = require('url'); var http = require('http'); var attempt = require('attempt'); var log4js = require('log4js'); var logger = log4js.getLogger(); var healthcheck = require('serverdzen-module'); var config = require('config'); var argv = process.argv.slice(2); if (!argv || argv.length == 0) { throw "Error: please, provide your userkey as first parameter!"; } var userKey = argv[0]; function registerMachine(callback) { var data = { 'UserKey': userKey, 'ComputerName': os.hostname(), 'OS': os.type() + ' ' + os.release() }; sendPOST(data, '/machine', callback); } function sendHealthcheck(hc, callback) { sendPOST(hc, '/', callback); } function sendPOST(postData, path, callback) { var data = JSON.stringify(postData); var options = getOpts(config.get('api.url'), 'POST', path, data); var req = http.request(options, function (res) { var resData = ''; res.setEncoding('utf8'); res.on('data', function (chunk) { resData += chunk; }); res.on('end', function () { callback(res.statusCode != 200 ? res.statusCode : null, resData); }); }); req.on('error', function (err) { callback(err); }); req.write(data); req.end(); } function getOpts(apiUrl, method, path, data) { var options = url.parse(apiUrl + '/v'+config.get('api.v')+path); options.method = method; options.headers = { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(data) } return options; } attempt( { retries: 5, interval: 3000 }, function() { registerMachine(this); }, function(err, res) { if (err) { logger.error(err); throw err; } logger.debug(res); var machineContainer = JSON.parse(res); (function gatherHealthCheck(timeout) { logger.debug('Getting healthcheck...') healthcheck.getHealthcheck(machineContainer.Key, userKey, function (err, res) { if (err) throw err; logger.debug('Healthcheck: ' + JSON.stringify(res)); logger.debug('Sending data to API...'); sendHealthcheck(res, function (err, data) { if (err) { logger.error(err); } else { var json = JSON.parse(data); logger.debug('Got response: ' + data); var newInterval = json.Interval * 1000; if (newInterval != timeout) { logger.debug('Changing data collection interval: '); timeout = newInterval; } } }); }); setTimeout(function () { gatherHealthCheck(timeout); }, timeout); })(machineContainer.Settings.Interval * 1000); });
var formatLocale = d3_format.formatLocale({decimal: ".", thousands: " ", grouping: [3], currency: ["R", ""]}); var formats = { currency: formatLocale.format("$,.0f"), percent: function(n) { if (n === null) return ""; else return formatLocale.format(",.1f")(n) + "%"; }, num: function(n, name) { if (n === null) return ""; else return formatLocale.format(",.1f")(n) + (name ? " " + name : ""); }, terse: function(n, f) { var format; if (n === null) { return ""; } else { if (Math.abs(n) >= 1000 * 1000 * 1000) { format = d3.formatPrefix(1000 * 1000); return f(format.scale(n)) + format.symbol; } else if (Math.abs(n) >= 1000) { format = d3.formatPrefix(1000); return f(format.scale(n)) + format.symbol; } else { return f(n); } } }, }; function wrapText(text, width) { // see https://bl.ocks.org/mbostock/7555321 text.each(function() { var text = d3.select(this), words = text.text().split(/\s+/).reverse(), word, line = [], lineNumber = 0, lineHeight = 1.1, // ems x = text.attr("x"), y = text.attr("y"), dy = parseFloat(text.attr("dy")), tspan = text.text(null).append("tspan").attr("y", y).attr("dy", dy + "em"); while (word = words.pop()) { line.push(word); tspan.text(line.join(" ")); if (tspan.node().getComputedTextLength() > width) { line.pop(); tspan.text(line.join(" ")); line = [word]; tspan = text.append("tspan").attr("x", x).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word); } } }); } var tooltip = d3.select("body").append("div") .attr("class", "chart-tooltip") .style("opacity", 0); function showTooltip(html) { tooltip .style("opacity", 1) .html(html); moveTooltip(); } function moveTooltip() { var height = tooltip.node().getBoundingClientRect().height; tooltip .style("left", (d3.event.pageX) + "px") .style("top", (d3.event.pageY - 20 - height) + "px"); } function hideTooltip() { tooltip.style("opacity", 0); } var HorizontalGroupedBarChart = function() { var self = this; self.discover = function(profileData) { // find all charts $('.chart-container[data-chart^=grouped-bar-]').each(function() { var chart = new HorizontalGroupedBarChart(); chart.init(this, profileData); $(window).on('resize', _.debounce(chart.drawChart, 300)); }); }; self.init = function(container, profileData) { self.container = $(container); self.name = self.container.data('chart').substring(12); // find nested data var data = profileData.indicators; _.each(self.name.split("."), function(p) { data = data[p]; }); self.data = data.values; self.drawChart(); }; self.setDimensions = function(items) { var container_width = self.container.width(); var container_height = (items > 5 ? 10 : 13) * items; var narrow = document.documentElement.clientWidth < 768; if ($('body').hasClass('print')) container_width = 550; self.margin = {top: 10, right: 0, bottom: 10, left: narrow ? 120 : 200}; self.width = container_width - self.margin.left - self.margin.right; self.height = container_height - self.margin.top - self.margin.bottom; self.y0 = d3.scale.ordinal() .rangeRoundBands([0, self.height], 0.2); self.y1 = d3.scale.ordinal(); self.x = d3.scale.linear() .range([0, self.width]); self.yAxis = d3.svg.axis() .scale(self.y0) .orient("left") .tickSize(0, 0) .tickPadding(10); }; self.color = d3.scale.ordinal() .range(["#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf"]); self.drawChart = function() { var data = self.data, name = self.name, dates = _.keys(_.countBy(data, function(data) { return data.date; })).reverse(), items = _.keys(_.countBy(data, function(data) { return data.item; })); self.container.empty(); self.setDimensions(dates.length * items.length); self.svg = d3.select(self.container[0]).append("svg") .attr("width", self.width + self.margin.left + self.margin.right) .attr("height", self.height + self.margin.top + self.margin.bottom) .append("g") .attr("transform", "translate(" + self.margin.left + "," + self.margin.top + ")") .attr("class", "grouped-bar"); var groupedData = []; items.forEach(function(item){ var val =[]; data.forEach(function (d) { if(item == d.item){ val.push(d); } }); groupedData.push({item: item, values: val}); }); self.y0.domain(groupedData.map(function(d) { return d.item; })); self.y1.domain(dates).rangeRoundBands([0, self.y0.rangeBand()]); self.x.domain([0, d3.max(data, function(d) { return d.percent; })]); // Draw the y-axis self.svg.append("g") .attr("class", "y axis") .call(self.yAxis) .selectAll(".tick text") .call(wrapText, self.margin.left - 10); // Create the groups var group = self.svg.selectAll(".group") .data(groupedData) .enter().append("g") .attr("class", "group") .attr("transform", function(d) { return "translate(0," + self.y0(d.item) + ")"; }); // Draw the bars group.selectAll(".chart-bar") .data(function(d) { return d.values; }) .enter().append("rect") .attr("class", "chart-bar") .attr("y", function(d) { return self.y1(d.date); }) .attr("height", self.y1.rangeBand() - 1) .attr("width", function(d) { return self.x(d.percent); }) .style("fill", function (d) { return self.color(d.date); }) .on("mouseover", function(d) { showTooltip(self.formatTooltip(d)); }) .on("mousemove", moveTooltip) .on("mouseout", hideTooltip); var legend = self.svg.selectAll(".legend") .data(dates) .enter().append("g") .attr("class", "legend") .attr("transform", function(d, i) { return "translate(0," + (self.height - (dates.length - i + 1) * 20) + ")"; }); legend.append("rect") .attr("x", self.width - 18) .attr("width", 18) .attr("height", 18) .style("fill", function (d) { return self.color(d); }); legend.append("text") .attr("x", self.width - 24) .attr("y", 9) .attr("dy", ".35em") .style("text-anchor", "end") .text(function(d) { return d; }); }; self.formatTooltip = function(d) { return "<b>" + d.date + ":</b> " + formats.percent(d.percent) + "<br>" + formats.currency(d.amount); }; }; var VerticalBarChart = function() { var self = this; self.discover = function() { // find all charts $('.chart-container[data-chart^=column-]').each(function() { var chart = new VerticalBarChart(); chart.init(this); $(window).on('resize', _.debounce(chart.drawChart, 300)); }); }; self.init = function(container) { self.container = $(container); self.name = self.container.data('chart').substring(7); // find nested data var data = profileData.indicators; _.each(self.name.split("."), function(p) { data = data[p]; }); self.data = data; // earliest to latest self.data.values.reverse(); // establish format self.format = formats[self.container.data('unit') || "currency"]; self.unit_name = self.container.data('unit-name'); self.drawChart(); }; self.setDimensions = function() { var container_width = self.container.width(); var container_height = 150; if ($('body').hasClass('print')) container_width = 300; self.margin = {top: 20, right: 0, bottom: 25, left: 0}; self.width = container_width - self.margin.left - self.margin.right; self.height = container_height - self.margin.top - self.margin.bottom; self.x = d3.scale.ordinal() .rangeRoundBands([0, self.width], 0.3, 0.1); self.y = d3.scale.linear() .range([self.height, 0]); self.xAxis = d3.svg.axis() .scale(self.x) .orient("bottom") .tickSize(0, 0) .tickPadding(10); }; self.drawChart = function() { var data = self.data.values, comparisons = self.data.comparisons; self.container.empty(); self.setDimensions(); self.svg = d3.select(self.container[0]).append("svg") .attr("width", self.width + self.margin.left + self.margin.right) .attr("height", self.height + self.margin.top + self.margin.bottom) .append("g") .attr("transform", "translate(" + self.margin.left + "," + self.margin.top + ")"); self.x.domain(data.map(function(d) { return d.date; })); self.y.domain([ Math.min(d3.min(data, function(d) { return d.result; }), 0), Math.max(d3.max(data, function(d) { return d.result; }), 0) ]); // Draw the x-axis self.svg.append("g") .attr("class", "x axis") .attr("transform", "translate(0," + self.height + ")") .call(self.xAxis); // Draw the zero line self.svg.append("g") .attr("class", "x axis zero") .attr("transform", "translate(0," + self.y(0) + ")") .call(self.xAxis.tickFormat("").tickSize(0)); // Draw the columns self.svg.selectAll(".chart-column") .data(data) .enter().append("rect") .attr("x", function(d) { return self.x(d.date); }) .attr("width", self.x.rangeBand()) .attr("y", function(d) { return self.y(Math.max(d.result, 0)); }) .attr("height", function(d) { return Math.abs(self.y(d.result) - self.y(0)); }) .attr("class", function(d) { return "chart-column " + d.rating; }) .on("mouseover", function(d) { showTooltip(self.formatTooltip(d, comparisons && comparisons[d.date])); }) .on("mousemove", moveTooltip) .on("mouseout", hideTooltip); // Add the labels self.svg.selectAll("text.bar") .data(data) .enter().append("text") .attr("class", "column-label") .attr("text-anchor", "middle") .attr("x", function(d) { return self.x(d.date) + self.x.rangeBand()/2; }) .attr("y", function(d) { return self.y(Math.max(d.result, 0)) - 5; }) .text(function(d) { return formats.terse(d.result, self.format); }); }; self.formatTooltip = function(d, comparisons) { var t = "<b>" + d.date + ":</b> " + self.format(d.result, self.unit_name); if (comparisons && comparisons.length > 0) { t += '<ul class="comparatives">'; t += _.map(comparisons, function(cmp) { return '<li>' + cmp.comparison + ' similar municipalities ' + cmp.place + ': ' + self.format(cmp.value, self.unit_name) + '</li>'; }).join(' '); } return t; }; }; var IncomeSplitPieChart = function() { var self = this; self.discover = function() { // find all charts $('#income-split-pie').each(function() { var chart = new IncomeSplitPieChart(); chart.init(this); $(window).on('resize', _.debounce(chart.drawChart, 300)); }); }; self.init = function(container) { self.container = $(container); self.color = d3.scale.ordinal() .range(["#bcbd22", "#17becf"]); self.data = [{ name: "From Government", amount: profileData.indicators.revenue_sources.government.amount, }, { name: "Generated locally", amount: profileData.indicators.revenue_sources.local.amount, }]; self.drawChart(); }; self.drawChart = function() { self.container.empty(); self.setDimensions(); self.svg = d3.select(self.container[0]).append("svg") .attr("width", self.width) .attr("height", self.height) .append("g") .attr("transform", "translate(" + self.width / 2 + "," + self.height / 2 + ")") .attr("class", "pie"); var arc = d3.svg.arc() .outerRadius(self.radius - 10) .innerRadius(0); var pie = d3.layout.pie() .sort(null) .value(function(d) { return d.amount; }); var g = self.svg.selectAll(".arc") .data(pie(self.data)) .enter().append("g") .attr("class", "arc"); g.append("path") .attr("d", arc) .style("fill", function(d) { return self.color(d.data.name); }); }; self.setDimensions = function() { self.width = self.container.width(); if ($('body').hasClass('print')) self.width = 100; self.width = Math.min(self.width, 150); self.height = self.width; self.radius = Math.min(self.width, self.height) / 2; }; }; $(function() { new VerticalBarChart().discover(); new IncomeSplitPieChart().discover(); });
// change these variables var data_source_name = ""; // end changes if(a=="view"){ (function (u,c,p,a,r,q) { if (!utag.ut) utag.ut = {}; r = function (w, x, y, z) { // read cookie x = w + "="; y = document.cookie.split(';'); for (var i = 0; i < y.length; i++) { z = y[i]; while (z.charAt(0) == ' ') z = z.substring(1, z.length); if (z.indexOf(x) == 0) return z.substring(x.length, z.length); } return ""; }; q = function (x, y, z) { // set cookie if (typeof z == "number") z = new Date(z); document.cookie = x + "=" + y + ";path=/;domain=" + utag.cfg.domain + ";expires=" + (z?z.toGMTString():""); //b["cp."+x] = y; // add cookie to udo }; utag.ut.hppv = function (w,x,y,z,r,q,c) { if (!utag.ut.getPPVid) return; c = "utag_ppv"; r = function (w, x, y, z) { // read cookie x = w + "="; y = document.cookie.split(';'); for (var i = 0; i < y.length; i++) { z = y[i]; while (z.charAt(0) == ' ') z = z.substring(1, z.length); if (z.indexOf(x) == 0) return z.substring(x.length, z.length); } return ""; }; q = function (x, y, z) { // set cookie if (typeof z == "number") z = new Date(z); document.cookie = x + "=" + y + ";path=/;domain=" + utag.cfg.domain + ";expires=" + (z?z.toGMTString():""); //b["cp."+x] = y; // add cookie to udo }; w = Math.max( Math.max(document.body.scrollHeight, document.documentElement.scrollHeight), Math.max(document.body.offsetHeight, document.documentElement.offsetHeight), Math.max(document.body.clientHeight, document.documentElement.clientHeight) ), x = (window.pageYOffset || (document.documentElement.scrollTop || document.body.scrollTop)) +(window.innerHeight || (document.documentElement.clientHeight || document.body.clientHeight)); y = Math.min(Math.round(x / w * 100), 100); z = (r(c).indexOf(',') > -1) ? r(c).split(',', 4) : []; q(c, ((y > 0) ? (((z.length > 0) ? (z[0]) : escape(utag.ut.getPPVid)) + ',' + ((y > ((z.length > 1) ? parseInt(z[1]) : (0))) ? y : ((z.length > 1) ? parseInt(z[1]) : (0))) + ',' + ((z.length > 2) ? parseInt(z[2]) : (y)) + ',' + ((x > ((z.length > 3) ? parseInt(z[3]) : (0))) ? x : ((z.length > 3) ? parseInt(z[3]) : (0)))) : '')); }; c = "utag_ppv"; p = p ? p : '-'; a = (r(c).indexOf(',') > -1) ? r(c).split(',', 4) : []; if (a.length < 4) { for (i=3; i>0; i--) { a[i] = (i < a.length) ? (a[i - 1]) : (''); } a[0] = ''; } a[0] = unescape(a[0]); q(c, escape(p)); if (!utag.ut.getPPVid) { utag.ut.getPPVid = (p) ? (p) : document.location.href; q(c, escape(utag.ut.getPPVid)); if (window.addEventListener) { window.addEventListener('load', utag.ut.hppv, false); window.addEventListener('scroll', utag.ut.hppv, false); window.addEventListener('resize', utag.ut.hppv, false); } else if (window.attachEvent) { window.attachEvent('onload', utag.ut.hppv); window.attachEvent('onscroll', utag.ut.hppv); window.attachEvent('onresize', utag.ut.hppv); } } b[u] = (p != '-') ? (a) : (a[1]); })(data_source_name); }
import ValidationHandler from 'src/handler/ValidationHandler.js' import { EventMapping } from 'src/helper/EventMapping.js' //import jquery from 'jquery' import jquery from 'libs/jquery-3.4.1.dev.js'; import { CharacterClassOptions } from 'src/model/page/CharacterClassOptions.js' import { ArraySet } from 'src/model/ArraySet.js' import { AttributeScores, FREEPOINTS_NAME, SCORES_NAME } from 'src/model/page/AttributeScores.js' import { ATTRIBUTES_NAME } from './AttributeScores' export var CHARACTER_UPDATE_ATTRIBS = ['success', 'character'] export var CHARACTER_DATA_ATTRIBS = ['charname', 'pos_x', 'pos_y', 'health', 'charclass', 'free_points', 'attributes'] // 2 arrays of the same length to allow looping for creating each line of the table // Fortitude, Intellect, Awareness, Arcana, Agility // TODO This does not belong in the model, refactor/dynamically generate! export const EVENTS = { SET_DETAILS: 'set-details', // For full setter calls CONFIRM_DETAILS: 'confirm-details', // For first-time setting of stats, in response to server confirmation SET_ATTRIB_SCORES: 'set-attribute-scores', //Any attrib score updates SET_CLASS_OPTIONS: 'set-class-options' // Any class option update } const INVALID_CHAR_UPDATE_DATA_ERROR = 'Character update data is invalid: ' // TODO Remove this export var CLASS_OPTIONS = [ { id: 'fighter', text: 'Fighter' }, { id: 'spellcaster', text: 'Spellcaster' } ] export const CHARACTER_JSON_NAME = 'character' export const ATTRIBUTES_JSON_NAME = 'attributes' export const CHARNAME_JSON_NAME = 'charname' export const POSITION_JSON_NAME = 'position' export const POSITION_X_JSON_NAME = 'pos_x' export const POSITION_Y_JSON_NAME = 'pos_y' export const HEALTH_JSON_NAME = 'health' export const CHARCLASS_JSON_NAME = 'charclass' export default class CharacterDetails extends EventMapping { constructor (characterClassOptions, attributeScores, minScoreValue, maxScoreValue, posX, posY, health, freePoints) { super(EVENTS) if (characterClassOptions === undefined || !characterClassOptions instanceof CharacterClassOptions) { throw new RangeError('Character class options required!') } if (attributeScores === undefined) { throw new RangeError('Attribute scores JSON required!') } if (minScoreValue === undefined) { throw new RangeError('Minimum attribute score value required!') } if (maxScoreValue === undefined) { a throw new RangeError('Maximum attribute score value required!') } if (posX === undefined || posY === undefined) { throw new RangeError('Position attributes posX and posY are required!') } if (health === undefined) { throw new RangeError('Character health value required!') } if (freePoints === undefined) { throw new RangeError('Free attribute points value required!') } // Boolean to check if us/the user has confirmed these to be set correctly this.charname = ''; this.charclass = ''; this.posX = posX; this.posY = posY; this.health = health; this.attributeClassOptions = characterClassOptions; this.defaultAttributeScores = new AttributeScores(attributeScores, minScoreValue, maxScoreValue, freePoints); this.attributeScores = new AttributeScores(attributeScores, minScoreValue, maxScoreValue, freePoints); // We cannot trust our character details until they are confirmed by the server this.detailsConfirmed = false; } isDetailsConfirmed() { return this.detailsConfirmed; } setDetailsConfirmed(detailsConfirmed) { this.detailsConfirmed = detailsConfirmed; } onceCharacterDetailsConfirmed (onConfirmedCb) { // Single-shot mapping for setting of the details to something this.once(EVENTS.CONFIRM_DETAILS, onConfirmedCb); } getAttributeNames () { let attribNames = Object.keys(this.getAttributeScores()) return attribNames } /** * Do all expected details exist? * @returns {boolean} */ characterDetailsExist () { // TODO String validation let nameGood = (this.charname !== undefined && this.charname !== null) let attributes = (this.attributeScores !== undefined && this.attributeScores !== null) let charclassGood = (this.charclass !== undefined && this.charclass !== null) let healthGood = (this.health !== undefined && this.health !== null) //TODO Validate Attributes return (nameGood && attributes && charclassGood && healthGood) }; getCharacterClassOptions () { return this.attributeClassOptions; } setCharacterClassOptions (characterClassOptions) { if (characterClassOptions !== undefined && characterClassOptions !== null && characterClassOptions !== {}) { let charClassOptions = CharacterClassOptions.fromOptionsList(characterClassOptions) this.attributeClassOptions = charClassOptions this.emit(EVENTS.SET_CLASS_OPTIONS, charClassOptions) console.info('Character class options set!') } else { throw new RangeError('Invalid character class options.') } } isCharacterClassOptionsDefined () { let charclassOptions = this.getCharacterClassOptions() return (charclassOptions !== undefined && charclassOptions.length > 0) } /** * Checks scores are valid and that all expected default keys are provided * @param JSON score name-value mappings i.e { A:1, B:2 } * @returns {boolean} whether all attributes are valid and recognised */ validateAttributeScores (scoresJson) { if (!this.getDefaultAttributeScores().size > 0) { throw new RangeError('Default attribute scores are undefined!') } scoresJson.validate() this.getDefaultAttributeScores().keys().forEach(key => { if (!scoresJson.has(key)) { throw new RangeError('Missing default attribute score key/value pair: ' + key) } }) } // Checks for the presence of data for character update // Example JSON //{"charname":"roo","pos_x":10,"pos_y":10,"health":100, // "charclass":"fighter","free_points":5, // "attributeScores": {"STR":1,"DEX":1,"CON":1,"INT":1,"WIS":1,"CHA":1}}; static validateJson (updateJSON) { console.log('CharacterDetails validating: ' + JSON.stringify(updateJSON)) if (ValidationHandler.notUndefOrNull(updateJSON)) { let characterDataExists = ValidationHandler.checkDataAttributes(updateJSON, [CHARACTER_JSON_NAME]) let characterData = updateJSON[CHARACTER_JSON_NAME] let positionData = characterData[POSITION_JSON_NAME] let coreAttribs = [ CHARNAME_JSON_NAME, POSITION_JSON_NAME, HEALTH_JSON_NAME, CHARCLASS_JSON_NAME, ATTRIBUTES_JSON_NAME ] let positionAttribs = [POSITION_X_JSON_NAME, POSITION_Y_JSON_NAME] let coreDataExists = characterDataExists && ValidationHandler.checkDataAttributes(characterData, coreAttribs) let positionExists = characterDataExists && ValidationHandler.checkDataAttributes(positionData, positionAttribs) let attributesExist = characterDataExists && AttributeScores.validateAttributesJson(characterData) if (!characterDataExists) { throw new RangeError('\'character\' data not defined') } if (!coreDataExists) { throw new RangeError('Core attributes data not defined, expected: ' + JSON.stringify(coreAttribs)) } if (!positionExists) { throw new RangeError('Position data: ' + JSON.stringify(positionData) + ' does not contain expected attribs: ' + positionAttribs) } if (!attributesExist) { throw new RangeError('\'attributes\' data not defined') } return characterDataExists && coreDataExists && positionExists && attributesExist } else { throw new RangeError('updateJSON undefined') } } updateAttributeScores (scoresJson) { let currentScoresMap = this.getAttributeScores().getScores(); if (currentScoresMap.length > 0) { console.debug('Updating scores: ' + JSON.stringify(scoreAttributes)); let updatedCount = 0; currentScoresMap.keys().forEach(attribName => { console.debug('Setting CharacterDetails: ' + attribName + ' ' + scoresJson[attribName]) this.attributeScores.setScore(attribName, scoresJson[attribName]) updatedCount++ }); console.debug(this.getAttributeScores()) if (updatedCount > 0) { this.emit(EVENTS.SET_ATTRIB_SCORES, this.getAttributeScores()) } else { console.warn('Attribute scores not updated!') } } else { console.log('No existing scores to update!'); console.trace(); } } updateAttributes (attributesJson) { let free_points = attributesJson[FREEPOINTS_NAME] this.attributeScores.setFreePoints(free_points) let scoresJson = attributesJson[SCORES_NAME] this.updateAttributeScores(scoresJson) } setFromJson (characterDetailsJson) { if (CharacterDetails.validateJson(characterDetailsJson)) { console.debug('Setting CharacterDetails from data: ' + JSON.stringify(characterDetailsJson)); let characterData = characterDetailsJson[CHARACTER_JSON_NAME]; let charname = characterData[CHARNAME_JSON_NAME]; this.setCharacterName(charname); let charclass = characterData[CHARCLASS_JSON_NAME]; this.setCharacterClass(charclass); let position = characterData[POSITION_JSON_NAME]; this.posX = position[POSITION_X_JSON_NAME]; this.posY = position[POSITION_Y_JSON_NAME]; this.health = characterData[HEALTH_JSON_NAME]; // Copy each of the stat attribs over this.setAttributesFromJson(characterData); this.emit(EVENTS.SET_DETAILS) // If this is the first time updating these details, we can confirm their validity if (!this.detailsConfirmed) this.emit(EVENTS.CONFIRM_DETAILS); return this; } else { throw new RangeError(INVALID_CHAR_UPDATE_DATA_ERROR + JSON.stringify(characterDetailsJson)) } }; getCharacterName () { return this.charname } setCharacterName (charname) { this.charname = charname } getCharacterClass () { return this.charclass } setCharacterClass (charclass) { this.charclass = charclass } getPosition () { return [this.posX, this.posY]; } getHealth() { return this.health; } /* * * @param attributeScoresJson i.e { A:1, B:2} */ setAttributeScores (attributeScores) { if (attributeScores instanceof AttributeScores) { attributeScores.validate() let existingDefaults = this.getDefaultAttributeScores(); let existingDefaultScores = existingDefaults.getScores(); // Set defaults on first set call if (existingDefaultScores.size === 0) { this.defaultAttributeScores = AttributeScores.fromJson(attributeScores.getJson()) } this.attributeScores = attributeScores this.emit(EVENTS.SET_ATTRIB_SCORES, this.getAttributeScores()) } else { throw new RangeError('Expected an instance of AttributeScores! received: ' + attributeScores) } } /** * Extracts the 'attributes' JSON living underneath the 'character' json data * returns a JSON object with 'attributes' as it's only key */ extractAttributesJson(characterDetailsJson) { let characterJson = ValidationHandler.validateAndGetAttribute(characterDetailsJson, CHARACTER_JSON_NAME); let attribsJson = ValidationHandler.validateAndGetAttribute(characterJson, ATTRIBUTES_NAME); return { [ATTRIBUTES_NAME] : attribsJson }; } /* * @param attribsJson, json data containing an attributes object keyed by it's name */ setAttributesFromJson (attribsJson) { if (AttributeScores.validateAttributesJson(attribsJson)) { this.setAttributeScores(AttributeScores.fromJson(attribsJson)); } } getDefaultAttributeScores () { return this.defaultAttributeScores } getAttributeScores () { return this.attributeScores } // Grabs Character Name, Class, and Attribute values getJson () { return { 'character': { 'charname': this.charname, 'charclass': this.charclass, 'position': { 'pos_x': this.posX, 'pos_y': this.posY }, 'health': this.health, 'attributes': this.attributeScores.getJson()['attributes'] } } } static isValidCharacterUpdateData (updateJSON) { if (ValidationHandler.notUndefOrNull(updateJSON)) { return ValidationHandler.checkDataAttributes(updateJSON, CHARACTER_UPDATE_ATTRIBS) //if (bodyValid) { //let contentValid = CharacterDetails.validateJson(updateJSON); //} } return false } } export { CharacterDetails }
const watson = require('watson-developer-cloud'); const API_KEY = '1b72f2aaaf9d29cd93d4805592c8991c828f9169'; // Put API key here // Connect to Watson Alchemy Language service if (API_KEY) { var alchemy = watson.alchemy_language({ api_key: API_KEY }); } else { console.error('Could not connect to Alchemy API - No API key'); } /** * Uses the Watson Alchemy API to generate a tag-cloud for target. * target should be an object with one of the properties html, url or text. */ module.exports = target => new Promise((resolve, reject) => { if (!target || !(target.html || target.url || target.text)) { reject('Could not invoke Alchemy API - No target'); } if (!alchemy) { reject('No Alchemy connection'); } // Refer to the following link for more information: // http://www.ibm.com/watson/developercloud/alchemy-language/api/v1/?node#entities var parameters = Object.assign({ structuredEntities: 0, emotion: 1 }, target); // Make API call alchemy.entities(parameters, function (err, res) { if (!err && res && Array.isArray(res.entities)) { resolve(res.entities); } reject(err || 'No results'); }); })
const webpack = require('webpack') const express = require('express') const path = require('path') const webpackDevMiddleware = require('webpack-dev-middleware') const webpackConfig = require('../build/webpack.config.js') const config = require('../project.config.js') const compiler = webpack(webpackConfig) const server = express() // Add conditional based on ENV server.use( webpackDevMiddleware( compiler, { stats: { colors: true, modules: false, chunks: false, }, resolve: { modules: [ 'node_modules', path.resolve(config.src) ] } } ) ) server.use(require('webpack-hot-middleware')(compiler)) server.listen(config.port, () => { console.log(`Server running on port ${config.port}`) }) module.exports = server
import Expr from './Expr' export default class ColorByWavelengthExpr extends Expr { constructor(value, $loc) { super('colorByWavelength', $loc) this.value = value } _evaluateInternal(e) { return e.evalColorByWavelength(this) } }
import React, { Component, PropTypes } from 'react'; /*** Third Party Components ***/ import Dialog from 'react-toolbox/lib/dialog'; import { Button, IconButton } from 'react-toolbox/lib/button'; import Icon from 'react-fa'; import style from './style.scss'; class NavButton extends Component { constructor(props) { super(props); this.state = { open: false }; } handleOpen = () => { this.setState({ open: true }); }; handleClose = () => { this.setState({ open: false }); }; render() { return ( <div className={`${style.root} ${this.props.className}`} > <IconButton className={style.navBars} neutral={false} onClick={this.handleOpen}> <Icon name={this.state.open ? 'times-circle-o' : 'bars'} /> </IconButton> <Dialog active={this.state.open} onOverlayClick={this.handleClose} className={style.dialog} > <Button flat label="What is this?" target="_blank" neutral={false} className={style.link} /> <Button flat label="Why?" target="_blank" neutral={false} className={style.link} /> <Button flat label="Contact" target="_blank" neutral={false} className={style.link} /> </Dialog> </div> ); } } export default NavButton;
import clone from "clone"; const initialState = { busy: false }; export default function(state = initialState, action) { const { type, payload } = action; switch (type) { case "BUSY": { const newState = clone(state); newState.busy = payload; const stateCopy = { ...state }; return newState; } } return state; }
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var ObjectId = Schema.Types.ObjectId; /** * Connect Mongodb */ mongoose.connect('mongodb://localhost/speedyfx'); /** * Schemas */ var UserSchema = new Schema({ uid: { type: String, required: true, trim: true, index: { unique: true, dropDups: true} }, pwd: { type: String, required: true, select: false }, nick: { type: String, required: true, trim: true }, email: { type: String, required: true, trim: true }, gender: { type: String, enum: ['male', 'female'] }, image: String, status: String, address: String, phone: String }); var ContactSchema = new Schema({ uid: { type: String, required: true, index: true }, cid: { type: String, required: true, index: true }, alias: { type: String, 'default': '' }, black: { type: Boolean, required: true, 'default': false } }); var MessageSchema = new Schema({ uid: { type: String, required: true, index: true }, mid: { type: String, required: true, index: true }, msg: { type: String, required: true }, time: { type: String, required: true, 'default': Date.now } }); /** * Models */ var User = module.exports.User = mongoose.model('user', UserSchema); var Contact = module.exports.Contact = mongoose.model('contact', ContactSchema); var Message = module.exports.Message = mongoose.model('message', MessageSchema); /** * Create query condition expression */ module.exports.Q = function Q(fields, params) { var r = {}; for (var i in fields) { // required condition if (fields[i]) { if (params[i] === undefined) return null; else r[i] = params[i]; } // optional condition else { if (params[i] != undefined) r[i] = params[i]; } } return r; }; /** * Create selection filter expression */ module.exports.F = function F(def, params) { if (params.filter) return params.filter.replace(/,/g, ' '); else return def; }; /** * Create update setter expression */ module.exports.S = function S(fields, params) { var r = {}; for (var i in fields) { // required fields if (fields[i]) { if (params[i] === undefined) return null; else r[i] = params[i]; } // optional fields else { if (params[i] != undefined) r[i] = params[i]; } } return { $set: r }; }; /** * Extract field from query result and make array */ module.exports.asArray = function asArray(doc, field) { var r = []; doc.forEach(function (obj, index, array) { if (obj[field] != undefined) r.push(obj[field]); }); return r; }; module.exports.toArray = function toArray(doc) { var r = []; doc.forEach(function (obj, index, array) { r.push(obj.toObject()); }); return r; };
import 'rxjs/add/operator/combineLatest'; import 'rxjs/add/operator/take'; import 'rxjs/add/operator/skip'; import 'rxjs/add/operator/withLatestFrom'; import 'rxjs/add/operator/concat'; import 'rxjs/add/operator/share'; export default function(...observables) { return source => { const published = source.share(); return published .combineLatest(...observables) .take(1) .concat(published.skip(1).withLatestFrom(...observables)); }; }
(function ($, window) { $.fn.twitterify = function (options) { return this.each(function () { new window.twitterify.Twitterifier(this, options) .init() .load(); }); }; }(jQuery, window));
'use strict'; /** * Module dependencies */ var flipflopsPolicy = require('../policies/flipflops.server.policy'), flipflops = require('../controllers/flipflops.server.controller'); module.exports = function(app) { // Flipflops Routes app.route('/api/flipflops').all(flipflopsPolicy.isAllowed) .get(flipflops.list) .post(flipflops.create); app.route('/api/flipflops/:flipflopId').all(flipflopsPolicy.isAllowed) .get(flipflops.read) .put(flipflops.update) .delete(flipflops.delete); app.route('/api/topic').all(flipflopsPolicy.isAllowed) .get(flipflops.fetchTopic); app.route('/api/topic/:topicId').all(flipflopsPolicy.isAllowed) .put(flipflops.updateTopic); app.route('/api/upload').all(flipflopsPolicy.isAllowed) .post(flipflops.upload); app.route('/api/judge').all(flipflopsPolicy.isAllowed) .get(flipflops.judge); app.route('/api/judge/:flipflopId').all(flipflopsPolicy.isAllowed) .put(flipflops.update); // Finish by binding the Flipflop middleware app.param('flipflopId', flipflops.flipflopByID); app.param('topicId', flipflops.topicByID); };
(function (angular) { "use strict"; angular .module("Cerberus.TemplateEditor") .controller("Cerberus.TemplateEditor.Controller.ComponentEditor.Navigation.Link", function () { }); })(window.angular);
'use strict' import React, { PropTypes } from 'react'; import { Button } from 'antd'; import { Link } from 'react-router'; import * as actions from '../action/note' class Notes_item extends React.Component{ onDeleteNote (event) { event.preventDefault() this.props.onDeleteNote(this.props.note._id) } render() { let date = this.props.note.date; let postDate = 'posted @' + date; let deleteChoice if (this.props.note.isLogin) { deleteChoice = ( <span className="deleteNote" onClick={ this.onDeleteNote.bind(this) }> 删除 </span> ) } return ( <div> <div className="notes_item" > <h4><Link to={ '/note/' + this.props.note._id }>{ this.props.note.title }</Link></h4> <p>{ this.props.note.content.substr(0,50) + '...' }</p> <span className="tag"> <span>{ '作者:' + this.props.note.author }&nbsp;&nbsp;</span> <span className="tag-left">{ postDate }</span> <span className="tag-right">浏览({ this.props.note.pv || 0 }){' '}留言({ this.props.note.commentCnt || 0})</span> { deleteChoice } </span> </div> </div> ); } } export default Notes_item;
Package.describe({ summary: "Sentinel role based authorization." }); Package.on_use(function (api) { var both = ['client', 'server']; api.use(['coffeescript', 'underscore', 'accounts-base'], both); api.add_files('sentinel.litcoffee', both); api.export && api.export('Sentinel'); });
/* * * ToolPage reducer * */ import { fromJS } from 'immutable'; import { DEFAULT_ACTION, REAL_WORLD_EXAMPLE, CONTRIBUTED_BY, LEARN_MORE, SET_CHOSEN_SECTION, RESET_TOOL_STATE, SET_EXPAND_ALL } from './constants'; const initialState = fromJS({ expandAll: false, chosenSection: REAL_WORLD_EXAMPLE, }); function toolPageReducer(state = initialState, action) { switch (action.type) { case DEFAULT_ACTION: return state; case RESET_TOOL_STATE: return initialState; case SET_CHOSEN_SECTION: return state.set('chosenSection', action.chosenSection); case SET_EXPAND_ALL: return state.set('expandAll', action.isExpandAll); default: return state; } } export default toolPageReducer;
'use strict'; const DateRange = require('../../../api/lib/DateRange'); const moment = require('moment'); describe('DateRange', () => { describe('constructor', () => { it('should assign properties correctly', () => { var from = new Date(); var to = new Date(); var result = new DateRange(from, to); expect(result).to.have.property('from', from); expect(result).to.have.property('to', to); }); }); describe('contains', () => { it('should return true if the date falls within the date range', () => { var date = new Date(); var from = moment(date).subtract(1, 'second').toDate(); var to = moment(date).add(1, 'second').toDate(); var dateRange = new DateRange(from, to); expect(dateRange.contains(date)).to.equal(true); expect(dateRange.contains(from)).to.equal(true); expect(dateRange.contains(to)).to.equal(true); }); it('should return false if the date falls outside the date range', () => { var date = new Date(); var from = moment(date).subtract(1, 'second').toDate(); var to = moment(date).add(1, 'second').toDate(); var dateRange = new DateRange(from, to); expect(dateRange.contains(moment(from).subtract(1, 'second').toDate())).to.equal(false); expect(dateRange.contains(moment(to).add(1, 'second').toDate())).to.equal(false); }); }); describe('widen', () => { it('should return a DateRange from the earliest point, to the latest point of n DateRanges', () => { const r1 = new DateRange(new Date('2016/01/01'), new Date('2016/01/02')); const r2 = new DateRange(new Date('2016/01/03'), new Date('2016/01/04')); const r3 = new DateRange(new Date('2016/01/05'), new Date('2016/01/06')); const result = DateRange.widen(r3,r2,r1); expect(result.from).to.equal(r1.from); expect(result.to).to.equal(r3.to); }); it('should return the same result regardless of argument order', () => { const r1 = new DateRange(new Date('2016/01/01'), new Date('2016/01/02')); const r2 = new DateRange(new Date('2016/01/03'), new Date('2016/01/04')); const r3 = new DateRange(new Date('2016/01/05'), new Date('2016/01/06')); const result = DateRange.widen(r3,r2,r1); const result2 = DateRange.widen(r1,r3,r2); expect(result.from).to.equal(result2.from); expect(result.to).to.equal(result2.to); }); it('should work with overlapping ranges', () => { const r1 = new DateRange(new Date('2016/01/01'), new Date('2016/01/02')); const r2 = new DateRange(new Date('2015/12/03'), new Date('2016/01/02')); const r3 = new DateRange(new Date('2016/01/01'), new Date('2016/02/06')); const result = DateRange.widen(r3,r2,r1); expect(result.from).to.equal(r2.from); expect(result.to).to.equal(r3.to); }); }); });
//This snippet is a sample of using a JavaScript client library to access a public API //require the https module to enable a connection to the https protocol URL of the public API let http = require('http'); let key = require('./modules/auth.js'); let _key = key; let location = 'Lagos'; //Use the GET method to send a request to the API which will pass the response to the callback const request = http.get('http://api.apixu.com/v1/current.json?key='+_key+'&q='+location, function(response){ let weatherData = ""; //console.log(response.statusCode); //Call a data event that will be used to retrieve the data sent from the API in JSON format to the callback response.on("data", function(data){ weatherData += data; if (response.statusCode === 200) { try{ weatherInfo = JSON.parse(weatherData); console.log(weatherInfo); }catch(e){ console.log("We encountered error while processing your request"); } }else { console.log("There was an error in your request! Try again later"); } }).on("error", function(e){ console.error("The API is unavailable"); }); }); request.end(); //check for weather current condition text (current.condition.text) //weather locaation
taskName = "Problem3.DeepCopy"; function Main(bufferElement) { function createDeepCopy(obj) { if (obj === null || typeof obj !== 'object') { return obj; } var copy = obj.constructor(); for (var prop in obj) { copy[prop] = createDeepCopy(obj[prop]); } return copy; } var person = { firstName: 'Pesho', lastName: 'Peshov', marks: { C1: 6, C2: 6, COOP: 5, HTML: 4, CSS: 6 } }, copy = createDeepCopy(person); person.marks.COOP = 4; WriteLine('Person COOP: ' + person.marks.COOP); WriteLine('Copy COOP' + copy.marks.COOP); }
var HTTP = require("q-io/http"); HTTP.read('http://localhost:1337') .then(JSON.parse) .then(function(response) { console.log(response); }) .done();
(function () { // The default state core singleton for {@link SceneJS.View} nodes var defaultCore = { type:"view", stateId:SceneJS._baseStateId++, scissorTestEnabled:false }; var coreStack = []; var stackLen = 0; SceneJS_events.addListener( SceneJS_events.SCENE_COMPILING, function (params) { params.engine.display.view = defaultCore; stackLen = 0; }); /** * @class Scene graph node which configures view parameters such as depth range, scissor test and viewport * @extends SceneJS.Node * void depthRange(floatzNear, floatzFar) zNear: Clamped to the range 0 to 1 Must be <= zFar zFar: Clamped to the range 0 to 1. void scissor(int x, int y, long width, long height) void viewport(int x, int y, long width, long height) */ SceneJS.View = SceneJS_NodeFactory.createNodeType("view"); SceneJS.View.prototype._init = function (params) { if (params.scissorTestEnabled != undefined) { this.setScissorTestEnabled(params.scissorTestEnabled); } else if (this._core.useCount == 1) { // This node defines the core this.setScissorTestEnabled(false); } }; /** * Enable or disables scissor test. * * When enabled, the scissor test will discards fragments that are outside the scissor box. * * Scissor test is initially disabled. * * @param scissorTestEnabled Specifies whether scissor test is enabled or not * @return {*} */ SceneJS.View.prototype.setScissorTestEnabled = function (scissorTestEnabled) { if (this._core.scissorTestEnabled != scissorTestEnabled) { this._core.scissorTestEnabled = scissorTestEnabled; this._engine.display.imageDirty = true; } return this; }; /** * Get whether or not scissor test is enabled. * Initial value will be false. * * @return Boolean */ SceneJS.View.prototype.getScissorTestEnabled = function () { return this._core.scissorTestEnabled; }; SceneJS.View.prototype._compile = function (ctx) { this._engine.display.view = coreStack[stackLen++] = this._core; this._compileNodes(ctx); this._engine.display.view = (--stackLen > 0) ? coreStack[stackLen - 1] : defaultCore; }; })();
"use strict"; define(['dou', 'build/ComponentRegistry'], function (dou, ComponentRegistry) { describe('ComponentRegistry', function () { var componentRegistry; var specs = [ { type: 'A', name: 'Component A', description: 'description for Component A', defaults: { attr1: '1', attr2: 'A', attr3: 100 }, shape_factory: dou.define({ }), handle_factory: dou.define({ }), toolbox_image: 'toolbox_small.png' }, { type: 'B', name: 'Component B', description: 'description for Component B', defaults: { attr1: '2', attr2: 'B', attr3: 200 }, shape_factory: dou.define({ }), handle_factory: dou.define({ }), toolbox_image: 'toolbox_small.png' } ]; beforeEach(function() { componentRegistry = new ComponentRegistry(); specs.forEach(function(spec) { componentRegistry.register(spec); }); }); afterEach(function() { componentRegistry.dispose() }); describe('register', function() { it('should ', function () { componentRegistry.register({ type: 'C', name: 'Component C', description: 'description for Component C', defaults: { attr1: '3', attr2: 'C', attr3: 300 }, shape_factory: dou.define({ }), handle_factory: dou.define({ }), toolbox_image: 'toolbox_small.png' }); var specs = componentRegistry.list(); Object.keys(specs).length.should.equal(3); }); }); describe('list', function() { it('should return list of registered component specs.', function () { var specs = componentRegistry.list(); var inst = new ComponentRegistry(); specs.length.should.equal(2); }); }); describe('get', function() { it('should get component spec by type of spec as a key', function () { var spec = componentRegistry.get('B'); spec.name.should.equal('Component B'); spec.defaults.attr2.should.equal('B'); }); it('should not be able to change attributes of regietered spec.', function () { var spec = componentRegistry.get('B'); var origin = spec.name; spec.name = origin + ' Changed'; var spec = componentRegistry.get('B'); spec.name.should.equal(origin); }); }); }); });
'use strict'; var git = require('../') console.log('git.short() => ' + git.short()); // 75bf4ee console.log('git.long() => ' + git.long()); // 75bf4eea9aa1a7fd6505d0d0aa43105feafa92ef console.log('git.branch() => ' + git.branch()); // master // console.log('git.tag() => ', git.tag()); // console.log('git.log() => ', git.log()); console.log('git.message() => ' + git.message()); // initial commit
import { message } from 'antd' import { changePasswordAction } from '../request/password' export const changePassword = (data, cb) => (dispatch, getState) => { dispatch(changePasswordAction(data)).then(action => { action.data.body.opResult == '1' ? message.success('密码修改成功!') : message.error('密码修改失败,请重试!') if (cb) cb() }) }
// https://github.com/jgthms/bulma/issues/238 thanks! document.getElementById("nav-toggle").addEventListener("click", toggleNav); function toggleNav() { var nav = document.getElementById("nav-menu"); var className = nav.getAttribute("class"); if(className == "nav-right nav-menu") { nav.className = "nav-right nav-menu is-active"; } else { nav.className = "nav-right nav-menu"; } } // for the random quote in the header var txtFile = new XMLHttpRequest(); txtFile.open("GET", "/quotes.txt", true); txtFile.onreadystatechange = function () { if (txtFile.readyState === 4) { if (txtFile.status === 200) { allText = txtFile.responseText; lines = txtFile.responseText.split("\n"); randLine = lines[Math.floor((Math.random() * lines.length) + 1)]; document.getElementById('quote').innerHTML = randLine || "Intelligence is the ability to adapt to change."; // fallback quote } } }; txtFile.send(null); document.getElementById("search-text").addEventListener("keydown", function(e) { // search if (e.keyCode == 13) { searchHandler(); } }, false); function searchHandler() { var searchInput = document.getElementById('search-text'); var text = searchInput.value; // add site:example.com in the placeholder window.location.href = "https://www.google.com/search?q=site:wangxin1248.github.io " + text; }
var gulp = require('gulp'), watch = require('gulp-watch'), run = require('gulp-run'), sourcemaps = require('gulp-sourcemaps'), rename = require('gulp-rename'), mochify = require('mochify'), to5 = require('gulp-6to5'); gulp.task('6to5', function() { return gulp.src('**/*.es6') .pipe(sourcemaps.init()) .pipe(to5({ experimental: true, loose: 'all' })) .pipe(sourcemaps.write()) .pipe(rename({ extname: '.js' })) .pipe(gulp.dest('./')); }); gulp.task('test', ['6to5'], function() { mochify('./test.js', { reporter: 'tap' }).bundle(); }); gulp.task('default', ['test'], function() { gulp.watch('**/*.es6', ['test']); });
/** * TPPLeague Admin Commands * TPPLeague - https://tppleague.me/ * * This command namespace is used internally by the client to communicate * for the Adventure Builder / TPPLeague Administration room(s). * * For the API, see chat-plugins/COMMANDS.md * * @license MIT license */ /* global Rooms */ 'use strict'; const proxy = require("../save-proxy.js"); const LEAGUE_CONFIG_FILE = require.resolve("../config/league/league_setup.json"); const DEL_TIMEOUT = 1000*60*2; var delConfirm = {}; if (!global.LeagueSetup) global.LeagueSetup = proxy(LEAGUE_CONFIG_FILE, '\t'); /* global LeagueSetup */ const alpha = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"; function createToken() { let id = ""; for (let i = 0; i < 11; i++) { id += alpha[Math.floor(Math.random()*alpha.length)]; } return id; } function confirmToken(token) { // If we have a confirmation token // console.log(`confirmToken(${token}) => delConfirm[]=${delConfirm[token]} => ${delConfirm[token] + DEL_TIMEOUT} > ${Date.now()} => ${delConfirm[token] + DEL_TIMEOUT > Date.now()}`); if (token) { // If the confirmation token is valid and is in date if (delConfirm[token] && delConfirm[token] + DEL_TIMEOUT > Date.now()) { // Allow the deletion to go through delete delConfirm[token]; return true; } if (delConfirm[token] + DEL_TIMEOUT > Date.now()) { delete delConfirm[token]; } } return false; } function commandCheck(ctx) { if (ctx.cmdToken === '!') { ctx.errorReply("You cannot broadcast this command."); return false; } if (Rooms.global.lockdown) { ctx.connection.send(`|queryresponse|adventbuilder|{"err":"lockdown"}`); return false; } if (!ctx.user.registered) { ctx.connection.send(`|queryresponse|adventbuilder|{"err":"unregistered"}`); return false; } return true; } function createTrainerID() { let id = require("crypto").randomBytes(4); let secretId = id.readUInt16LE(0); let trainerId = id.readUInt16LE(2); return [secretId, trainerId]; } // function sendFormats(){ // let list = [ // // ValidatorRules // 'Nickname Clause','Item Clause','Ability Clause','-ate Clause','OHKO Clause', // 'Evasion Abilities Clause','Evasion Moves Clause','Moody Clause','Swagger Clause', // 'Baton Pass Clause','Baton Pass Speed Clause', // // Battle Rules // 'Endless Battle Clause','Sleep Clause Mod','Freeze Clause Mod','Same Type Clause', // 'Mega Rayquaza Clause', // 'HP Percentage Mod','Exact HP Mod', // //'Groundsource Mod', // ]; // this.sendReply(`|adventbuilder|league-extra-formats|${JSON.stringify()}`); // } function getGymInfo(json){ json = json || {}; json.elites = {}; json.gyms = {}; Object.keys(LeagueSetup.elites).forEach((key)=>{ if (LeagueSetup.elites[key].isHidden) return; json.elites[key] = { name: LeagueSetup.elites[key].name, types: LeagueSetup.elites[key].types, battletype: LeagueSetup.elites[key].battletype, avatar: LeagueSetup.elites[key].avatar, isChamp: LeagueSetup.elites[key].isChamp, banlist: LeagueSetup.elites[key].banlist, }; }); Object.keys(LeagueSetup.gyms).forEach((key)=>{ if (LeagueSetup.gyms[key].isHidden) return; json.gyms[key] = { name: LeagueSetup.gyms[key].name, types: LeagueSetup.gyms[key].types, battletype: LeagueSetup.gyms[key].battletype, avatar: LeagueSetup.gyms[key].avatar, badge: LeagueSetup.gyms[key].badge, banlist: LeagueSetup.gyms[key].banlist, trialdesc: LeagueSetup.gyms[key].trialdesc, }; }); return json; } function LeagueSetupSend(msg) { if (!msg) return; if (!msg.room) msg.room = Rooms.global; switch (msg.type) { case 'new': { switch (msg.event) { case 'gym' : { if (!LeagueSetup.gyms[msg.userid]) { LeagueSetup.gyms[msg.userid] = { name: msg.username || msg.userid, types: [], battletype: 'singles', avatar: 167, // Questionmark Napoleon pending: [], }; LeagueSetup.markDirty(); } return LeagueSetup.gyms[msg.userid]; } case 'elite': { if (!LeagueSetup.elites[msg.userid]) { LeagueSetup.elites[msg.userid] = { isChamp: false, types: [], battletype: 'singles', name: "", avatar: 167, // Questionmark Napoleon pending: [], }; LeagueSetup.markDirty(); } return LeagueSetup.elites[msg.userid]; } case 'hallOfFame': { if (typeof msg.user === 'string') msg.user = Users.get(msg.user); let hof = LeagueSetup.hallOfFame[msg.type || 'singles']; let chall = LeagueSetup.challengers[msg.user.userid]; let entry = { num: hof.length+1, name: msg.user.name, trainerid: chall.trainerid, team: msg.team, }; hof.unshift(entry); LeagueSetup.markDirty(); return entry; } } } return; case 'e4fight': { console.log(msg.otherInfo); if (!msg.p1) return msg.room.add('|html|<div class="broadcast-red">Unable to determine elite member! Tustin, you fucked it up!</div>'); if (!msg.p2) return msg.room.add('|html|<div class="broadcast-red">Unable to determine challenger! Tustin, you fucked it up!</div>'); if (!LeagueSetup.challengers[msg.p2]) return msg.room.add(`|error|Unable to ${msg.event} challenger: Challenger has no league challenge!`); let user = Users.get(msg.p2); let elite = Users.get(msg.p1) || {}; if (!LeagueSetup.challengers[msg.p2].e4wins) LeagueSetup.challengers[msg.p2].e4wins = {}; switch(msg.event) { case 'restart': // A challenger failed their e4 fight LeagueSetup.challengers[msg.p2].e4wins = {}; LeagueSetup.markDirty(); setTimeout(()=>msg.room.add(`|html|<div class="broadcast-blue">The challenger ${user.name} has lost the battle against ${elite.name}. The challenger will have to restart their Elite Four run.</div>`), 4000); return; case 'advance': // A challenger advanced in their e4 fight LeagueSetup.challengers[msg.p2].e4wins[msg.p1] = true; LeagueSetup.markDirty(); let adv = "The challenger may advance to the next Elite Member!"; if (Object.keys(LeagueSetup.challengers[msg.p2].e4wins).length >= 4) { adv = "The challenger is ready to challenge the League Champion!"; } setTimeout(()=>msg.room.add(`|html|<div class="broadcast-blue">The challenger ${user.name} has won the battle against ${elite.name}. ${adv}</div>`), 4000); return; case 'complete': { // A challenger has defeated the champion and has become champion himself! let hof = LeagueSetup.send({ type:"new", event:"hallOfFame", user:user, type: msg.otherInfo[0], team: msg.otherInfo[1], }); let settings = LeagueSetup.send({type:"new", event:"elite", userid: user.userid, username: user.name}); settings.isChamp = true; settings.isFormerChamp = false; settings.avatar = user.avatar; LeagueSetup.elites[elite.userid].isFormerChamp = true; LeagueSetup.elites[elite.userid].isHidden = true; let num = hof.num; num = num + (['th','st','nd','rd'][num%10]||'th'); if (num==='11st'||num==='12nd'||num==='13rd') num=num.slice(0,2)+"th"; setTimeout(()=>msg.room.add(`|html|<div class="broadcast-blue"><b>The challenger ${user.name} has won against ${elite.name}! Congratuations to our new ${num} TPPLeague Champion, ${user.name}!</b></div>`), 4000); Rooms.global.add(`|html|<div class="broadcast-blue"><b>Congratuations to our new ${num} TPPLeague Champion, ${user.name}!</b></div>`); BotManager.announceNotify(`Congratuations to our new ${num} TPPLeague Champion, ${user.name}!`); } return; } } return; case 'champion': { switch (msg.event) { case 'prep': BotManager.announceNotify(`TPPLeague Champion Battle will be beginning soon!`); Users.users.forEach(curUser => curUser.send('|champnotify|notify') ); return; case 'begin': BotManager.announceNotify(`TPPLeague Champion Battle has begun! https://tppleague.me/${msg.battleid}`); return; case 'ongoing': //sent about every 10 rounds BotManager.announce(`TPPLeague Champion Battle is in progress! https://tppleague.me/${msg.battleid}`); return; case 'finished': BotManager.announce(`TPPLeague Champion Battle has completed! https://tppleague.me/${msg.battleid}`); Users.users.forEach(curUser => curUser.send('|champnotify|finished') ); return; case 'finished-lose': BotManager.announce(`TPPLeague Champion Battle has completed! The Champion has defended their title! https://tppleague.me/${msg.battleid}`); Users.users.forEach(curUser => curUser.send('|champnotify|finished') ); return; } } return; } } LeagueSetup.send = LeagueSetupSend; // Note: this always runs on hotpatch exports.commands = { adventbuilder : { reload : function() { if (!this.can('hotpatch')) return false; try { let setup = proxy(LEAGUE_CONFIG_FILE, '\t'); LeagueSetup.dispose(); global.LeagueSetup = setup; LeagueSetup.send = LeagueSetupSend; } catch (e) { if (e.name === 'SyntaxError') { this.errorReply("League Setup file is malformatted! Fix your JSON!"); this.errorReply(e.message); } else { this.errorReply("Unexpected error while reloading league setup: "+e.message); } return; } return this.sendReply("The TPPLeague setup has been reloaded from disk."); }, request : { // /adventbuilder request options options : function(target, room, user) { if (!commandCheck(this)) return; let opts = []; if (LeagueSetup.admins.includes(user.userid)) { opts.push("league-admin"); } opts.push("view-league"); if (LeagueSetup.elites[user.userid]) { if (LeagueSetup.elites[user.userid].isChamp) { opts.push("league-champ"); } else { opts.push("league-elite"); } } if (LeagueSetup.gyms[user.userid]) { opts.push("league-gym"); } if (LeagueSetup.challengers[user.userid]) { opts.push("league-challenge"); } else { opts.push("league-challenge:new"); } this.connection.send(`|queryresponse|adventbuilder|${JSON.stringify( {screen:"opts", info:opts} )}`); }, 'league-admin': function(target, room, user) { if (!commandCheck(this)) return; if (!LeagueSetup.admins.includes(this.user.userid)) return this.connection.send(`|queryresponse|adventbuilder|{"err":"unauthed"}`); let json = { options: LeagueSetup.options, elites: LeagueSetup.elites, gyms: LeagueSetup.gyms, challengers: LeagueSetup.challengers }; let resp = { screen: 'league-admin', info: json, }; this.connection.send(`|queryresponse|adventbuilder|${JSON.stringify( resp )}`); }, 'league-champ': 'league-elite', 'league-elite': function(target, room, user) { if (!commandCheck(this)) return; if (!LeagueSetup.elites[user.userid]) return this.connection.send(`|queryresponse|adventbuilder|{"err":"unauthed"}`); let resp = { screen: 'league-elite', options: LeagueSetup.options, info: LeagueSetup.elites[user.userid], user: { name: this.user.name, avatar: this.user.avatar, }, }; this.connection.send(`|queryresponse|adventbuilder|${JSON.stringify(resp)}`); }, 'league-gym': function(target, room, user) { if (!commandCheck(this)) return; if (!LeagueSetup.gyms[user.userid]) return this.connection.send(`|queryresponse|adventbuilder|{"err":"unauthed"}`); let resp = { screen: 'league-gym', options: LeagueSetup.options, info: LeagueSetup.gyms[user.userid], user: { name: this.user.name, avatar: this.user.avatar, }, }; this.connection.send(`|queryresponse|adventbuilder|${JSON.stringify(resp)}`); }, 'view-league': function(target, room, user) { if (this.cmdToken === '!') { this.errorReply("You cannot broadcast this command."); return false; } let resp = { screen: 'view-league', league: getGymInfo(), }; this.connection.send(`|queryresponse|adventbuilder|${JSON.stringify(resp)}`); }, 'league-challenge': function(target, room, user) { if (!commandCheck(this)) return; if (!LeagueSetup.challengers[user.userid]) return this.connection.send(`|queryresponse|adventbuilder|{"err":"unauthed"}`); let resp = { screen: 'league-challenge', //must clone this, so we don't modify the original below info: Object.assign({}, LeagueSetup.challengers[user.userid]), league: getGymInfo(), user: { name: this.user.name, avatar: this.user.avatar, }, }; // Gen 7 trainer ids: secretid + trainerid * 65536, last 6 digits let trid = resp.info.trainerid; resp.info.trainerid = String(trid[0] + trid[1] * 65536).substr(-6); this.connection.send(`|queryresponse|adventbuilder|${JSON.stringify(resp)}`); }, }, 'new' : { // /adventbuilder new league-challenge - Creates a new league challenge for this user 'league-challenge': function(target, room, user) { if (!commandCheck(this)) return; if (LeagueSetup.challengers[this.user.userid]) return this.connection.send(`|queryresponse|adventbuilder|{"err":"League Challenge already exists for this user."}`); LeagueSetup.challengers[user.userid] = { teams : {}, badges: {}, trainerid: createTrainerID(), startdate: Date.now(), }; LeagueSetup.markDirty(); let resp = { welcome: "league-challenge", }; this.connection.send(`|queryresponse|adventbuilder|${JSON.stringify(resp)}`); this.parse('/adventbuilder request league-challenge'); }, }, 'del' : { // /adventbuilder del league-challenge [confirmtoken] - Deletes the user's league challenge 'league-challenge': function(target) { if (!commandCheck(this)) return; if (!LeagueSetup.challengers[this.user.userid]) return this.connection.send(`|queryresponse|adventbuilder|{"err":"unauthed"}`); if (!confirmToken(target)) { let confirmid = createToken(); delConfirm[confirmid] = Date.now(); return this.connection.send(`|queryresponse|adventbuilder|${JSON.stringify({ confirm:confirmid, cmd:this.message })}`); } delete LeagueSetup.challengers[this.user.userid]; LeagueSetup.markDirty(); this.connection.send(`|queryresponse|adventbuilder|{"success":"League Challenge has been forfeited successfully."}`); this.parse('/adventbuilder request options'); }, }, // /adventbuilder teamcommit [type]|[oldid]|[newid]|[teamstring] - Commits a saved team. teamcommit : function(target, room, user) { if (!commandCheck(this)) return; target = target.split('|'); let type; switch (target[0]) { case 'elite': type = "elites"; break; case 'gym': type = "gyms"; break; case 'trainer': type = "challengers"; break; } if (!LeagueSetup[type][user.userid]) return this.errorReply("Cannot commit team: unauthorized access."); let save = LeagueSetup[type][user.userid]; let oldid = target[1]; let newid = target[2]; if (newid != oldid) { delete save.teams[oldid]; } save.teams[newid] = target.slice(3).join('|'); LeagueSetup.markDirty(); }, commit : { // /adventbuilder commit leagueopts [json] - Sent by the Admin screen to commit league-wide options leagueopts : function(target){ if (!commandCheck(this)) return; if (!LeagueSetup.admins.includes(this.user.userid)) return this.connection.send(`|queryresponse|adventbuilder|{"err":"unauthed"}`); try { let obj = JSON.parse(target); let save = LeagueSetup.options; Object.keys(obj).forEach((key)=> save[key] = obj[key] ); } catch (e) { console.log("Illegal commit: "+target); console.log("Error: ", e); return this.popupReply('Illegal commit. Please use the "TPPLeague" tab. If you were using that tab, please report this error to Tustin2121.'); } LeagueSetup.markDirty(); this.connection.send(`|queryresponse|adventbuilder|{"success":"League Options saved!"}`); this.parse('/adventbuilder request league-admin'); }, // /adventbuilder commit rmchal [username] [confirmtoken] - Sent by the Admin screen to remove a challenger rmchal : function(target){ if (!commandCheck(this)) return; if (!LeagueSetup.admins.includes(this.user.userid)) return this.connection.send(`|queryresponse|adventbuilder|{"err":"unauthed"}`); target = target.split(" "); let other = { userid: toId(target[0]), name: target[0] }; if (!LeagueSetup.challengers[other.userid]) { other = Users.get(target[0]) || { userid: toId(target[0]), name: target[0] }; } if (!LeagueSetup.challengers[other.userid]) return this.connection.send(`|queryresponse|adventbuilder|{"err":"There is no Challenger profile for '${other.name}'"}`); if (!confirmToken(target[1])) { let confirmid = createToken(); delConfirm[confirmid] = Date.now(); return this.connection.send(`|queryresponse|adventbuilder|${JSON.stringify({ confirm:confirmid, cmd:this.message })}`); } delete LeagueSetup.challengers[other.userid]; LeagueSetup.markDirty(); this.connection.send(`|queryresponse|adventbuilder|{"success":"Challenger profile for '${other.name}' deleted!"}`); this.parse('/adventbuilder request league-admin'); }, // /adventbuilder commit addgym [username] - Sent by the Admin screen to add a new gymleader addgym : function(target){ if (!commandCheck(this)) return; if (!LeagueSetup.admins.includes(this.user.userid)) return this.connection.send(`|queryresponse|adventbuilder|{"err":"unauthed"}`); let other = { userid: toId(target), name: target }; if (!LeagueSetup.gyms[other.userid]) { other = Users.get(target) || { userid: toId(target), name: target }; } if (LeagueSetup.gyms[other.userid]) return this.connection.send(`|queryresponse|adventbuilder|{"err":"Gym already exists for user ${other.name}."}`); LeagueSetup.send({type:"new", event:"gym", userid: other.userid, username: other.name}); this.connection.send(`|queryresponse|adventbuilder|{"success":"Gym for '${other.name}' added!"}`); this.parse('/adventbuilder request league-admin'); }, // /adventbuilder commit rmgym [username] [confirmtoken] - Sent by the Admin screen to remove a gymleader rmgym : function(target){ if (!commandCheck(this)) return; if (!LeagueSetup.admins.includes(this.user.userid)) return this.connection.send(`|queryresponse|adventbuilder|{"err":"unauthed"}`); target = target.split(" "); let other = { userid: toId(target[0]), name: target[0] }; if (!LeagueSetup.gyms[other.userid]) { other = Users.get(target[0]) || { userid: toId(target[0]), name: target[0] }; } if (!LeagueSetup.gyms[other.userid]) return this.connection.send(`|queryresponse|adventbuilder|{"err":"There is no Gym for '${other.name}'"}`); if (!confirmToken(target[1])) { let confirmid = createToken(); delConfirm[confirmid] = Date.now(); return this.connection.send(`|queryresponse|adventbuilder|${JSON.stringify({ confirm:confirmid, cmd:this.message })}`); } delete LeagueSetup.gyms[other.userid]; LeagueSetup.markDirty(); this.connection.send(`|queryresponse|adventbuilder|{"success":"Gym for '${other.name}' deleted!"}`); this.parse('/adventbuilder request league-admin'); }, // /adventbuilder commit addelite [username] - Sent by the Admin screen to add a new elite member addelite : function(target){ if (!commandCheck(this)) return; if (!LeagueSetup.admins.includes(this.user.userid)) return this.connection.send(`|queryresponse|adventbuilder|{"err":"unauthed"}`); let other = { userid: toId(target), name: target }; if (!LeagueSetup.elites[other.userid]) { other = Users.get(target) || { userid: toId(target), name: target }; } if (LeagueSetup.elites[other.userid]) return this.connection.send(`|queryresponse|adventbuilder|{"err":"Elite settings already exist for user ${other.name}."}`); LeagueSetup.send({type:"new", event:"elite", userid: other.userid, username: other.name}); this.connection.send(`|queryresponse|adventbuilder|{"success":"Elite for '${other.name}' added!"}`); this.parse('/adventbuilder request league-admin'); }, // /adventbuilder commit rmelite [username] [confirmtoken] - Sent by the Admin screen to remove an elite member rmelite : function(target){ if (!commandCheck(this)) return; if (!LeagueSetup.admins.includes(this.user.userid)) return this.connection.send(`|queryresponse|adventbuilder|{"err":"unauthed"}`); target = target.split(" "); let other = { userid: toId(target[0]), name: target[0] }; if (!LeagueSetup.elites[other.userid]) { other = Users.get(target[0]) || { userid: toId(target[0]), name: target[0] }; } if (!LeagueSetup.elites[other.userid]) return this.connection.send(`|queryresponse|adventbuilder|{"err":"There is no Elite settings for '${other.name}'"}`); if (!confirmToken(target[1])) { let confirmid = createToken(); delConfirm[confirmid] = Date.now(); return this.connection.send(`|queryresponse|adventbuilder|${JSON.stringify({ confirm:confirmid, cmd:this.message })}`); } delete LeagueSetup.elites[other.userid]; LeagueSetup.markDirty(); this.connection.send(`|queryresponse|adventbuilder|{"success":"Elite for '${other.name}' deleted!"}`); this.parse('/adventbuilder request league-admin'); }, // /adventbuilder commit promotechamp [username] - Sent by the Admin screen to set an elite member as chamption promotechamp : function(target){ if (!commandCheck(this)) return; if (!LeagueSetup.admins.includes(this.user.userid)) return this.connection.send(`|queryresponse|adventbuilder|{"err":"unauthed"}`); let other = { userid: toId(target), name: target }; if (!LeagueSetup.elites[other.userid]) { other = Users.get(target) || { userid: toId(target), name: target }; } if (!LeagueSetup.elites[other.userid]) return this.connection.send(`|queryresponse|adventbuilder|{"err":"There is no Elite settings for '${other.name}"}'`); LeagueSetup.elites[other.userid].isChamp = true; LeagueSetup.markDirty(); this.connection.send(`|queryresponse|adventbuilder|{"success":"Elite '${other.name}' has been promoted to Champion!"}`); this.parse('/adventbuilder request league-admin'); }, // /adventbuilder commit demotechamp [username] - Sent by the Admin screen to unset am elite member as champion demotechamp : function(target){ if (!commandCheck(this)) return; if (!LeagueSetup.admins.includes(this.user.userid)) return this.connection.send(`|queryresponse|adventbuilder|{"err":"unauthed"}`); let other = { userid: toId(target), name: target }; if (!LeagueSetup.elites[other.userid]) { other = Users.get(target) || { userid: toId(target), name: target }; } if (!LeagueSetup.elites[other.userid]) return this.connection.send(`|queryresponse|adventbuilder|{"err":"There is no Elite settings for '${other.name}"}'`); LeagueSetup.elites[other.userid].isChamp = false; LeagueSetup.markDirty(); this.connection.send(`|queryresponse|adventbuilder|{"success":"Elite '${other.name}' has been demoted to Elite Four member!"}`); this.parse('/adventbuilder request league-admin'); }, // /adventbuilder commit elite {json} - Sent by the Elite settings screen to commit changed made by the screen elite : function(target) { if (!commandCheck(this)) return; if (!LeagueSetup.elites[this.user.userid]) return this.connection.send(`|queryresponse|adventbuilder|{"err":"unauthed"}`); let errors = []; try { let obj = JSON.parse(target); let save = LeagueSetup.elites[this.user.userid]; // Limit the values we save, and validate them on the way in. if (obj.name) { if (LeagueSetup.options.titleRename) { save.name = Chat.escapeHTML(obj.name.substr(0, 32)); } else if (obj.name !== save.name) { errors.push("Changing of E4 titles is not allowed at this time by League Admin mandate."); } } if (obj.types) { let val = obj.types //TODO validate save.types = val; } if (obj.bgimg) { let val = obj.bgimg; save.bgimg = Config.stadium.background().convertToId(val); } if (obj.bgmusic) { let val = obj.bgmusic; if (Config.stadium.music().isValidBattle(val)) { save.bgmusic = val; } else { errors.push("Background music is not valid."); } } if (obj.battletype) { let val = obj.battletype; if (/singles|doubles|triples/.test(val)) { save.battletype = val; } else { errors.push("Battle type is not valid."); } } if (obj.ruleset) { let val = obj.ruleset; if (Array.isArray(val) && val.every(x => typeof x == 'string')) { save.ruleset = val.map(x=>x.trim()).filter(x => !!x); } else { errors.push("Ruleset is invalid."); } } if (obj.banlist) { let val = obj.banlist; if (Array.isArray(val) && val.every(x => typeof x == 'string')) { save.banlist = val.map(x=>x.trim()).filter(x => !!x); } else { errors.push("Banlist is invalid."); } } save.avatar = this.user.avatar; //Save off the avatar for later use by others LeagueSetup.markDirty(); } catch (e) { console.log("Illegal commit: "+target); console.log("Error: ", e); return this.popupReply('Illegal commit. Please use the "TPPLeague" tab. If you were using that tab, please report this error to Tustin2121.'); } let repl = { success: "Settings saved!" }; if (errors.length) { repl.success = "Settings saved with the following caveats:\n\n- "+errors.join("\n- "); } this.connection.send(`|queryresponse|adventbuilder|${JSON.stringify(repl)}`); this.parse('/adventbuilder request league-elite'); }, // /adventbuilder commit gym {json} - Sent by the Gym settings screen to commit changed made by the screen gym : function(target) { if (!commandCheck(this)) return; if (!LeagueSetup.gyms[this.user.userid]) return this.connection.send(`|queryresponse|adventbuilder|{"err":"unauthed"}`); let errors = []; try { let obj = JSON.parse(target); let save = LeagueSetup.gyms[this.user.userid]; // Limit the values we save // Limit the values we save, and validate them on the way in. if (obj.name) { if (LeagueSetup.options.gymRename){ save.name = Chat.escapeHTML(obj.name.substr(0, 16)); } else if (obj.name !== save.name) { errors.push("Changing of gym names is not allowed at this time by League Admin mandate."); } } if (obj.badge) { if (LeagueSetup.options.badgeRename) { let val = obj.badge; if (val === 'undefined' || val === '') val = undefined; else val = val.replace(/[^a-zA-Z- ]/, "").substr(0, 32); // Check badged uniqueness { let dup = false; Object.keys(LeagueSetup.gyms).forEach((g)=>{ if (val === LeagueSetup.gyms[g].badge) { dup = true; } }); if (dup) { val = save.badge; errors.push("Badge name is not unique."); } } if (save.badge !== val) { let old = save.badge; save.badge = val; // Object.keys(LeagueSetup.challengers).forEach((c)=>{ // if (LeagueSetup.challengers[c].badges[old] === 1) { // delete LeagueSetup.challengers[c].badges[old]; // LeagueSetup.challengers[c].badges[val] = 1; // } // }); } } else if (obj.badge !== save.badge) { errors.push("Changing of badge names is not allowed at this time by League Admin mandate."); } } if (obj.types) { let val = obj.types; //TODO validate save.types = val; } if (obj.bgimg) { let val = obj.bgimg; save.bgimg = Config.stadium.background().convertToId(val); } if (obj.bgmusic) { let val = obj.bgmusic; if (Config.stadium.music().isValidBattle(val)) { save.bgmusic = val; } else { errors.push("Background music is not valid."); } } if (obj.battletype) { let val = obj.battletype; if (/singles|doubles|triples|trial/.test(val)) { save.battletype = val; } else { errors.push("Battle type is not valid."); } } if (obj.ruleset) { let val = obj.ruleset; if (Array.isArray(val) && val.every(x => typeof x == 'string')) { save.ruleset = val.map(x=>x.trim()).filter(x => !!x); } else { errors.push("Ruleset is invalid."); } } if (obj.banlist) { let val = obj.banlist; if (Array.isArray(val) && val.every(x => typeof x == 'string')) { save.banlist = val.map(x=>x.trim()).filter(x => !!x); } else { errors.push("Banlist is invalid."); } } if (obj.trialdesc) { var val = obj.trialdesc; if (val === 'undefined' || val === '') val = undefined; else val = val.trim().substr(0, 1000); save.trialdesc = val; } save.avatar = this.user.avatar; //Save off the avatar for later use by others LeagueSetup.markDirty(); } catch (e) { console.log("Illegal commit: "+target); console.log("Error: ", e); return this.popupReply('Illegal commit. Please use the "TPPLeague" tab. If you were using that tab, please report this error to Tustin2121.'); } let repl = { success: "Settings saved!" }; if (errors.length) { repl.success = "Settings saved with the following caveats:\n\n- "+errors.join("\n- "); } this.connection.send(`|queryresponse|adventbuilder|${JSON.stringify(repl)}`); this.parse('/adventbuilder request league-gym'); }, }, }, adventbuilderhelp : [ '/adventbuilder - Command used internally by the Adventure Builder. Use the "TPPLeague" tab instead.', ], pendingchallenges : function(target) { if (this.cmdToken === '!') return this.errorReply('You cannot broadcast this command.'); let silent = (target === 'silent'); // if (Rooms.global.lockdown) return this.errorReply('The server is in lockdown. You cannot hand out badges at this time.'); if (!this.user.registered) { if (!silent) this.errorReply('Please log in first.'); return; } let gym = LeagueSetup.gyms[this.user.userid]; if (gym) { if (gym.pending.length) { this.sendReply("Challengers waiting to fight your gym: "+gym.pending.join(",")); } else if (!silent) { this.sendReply("There are no challengers waiting to fight your gym right now."); } } gym = LeagueSetup.elites[this.user.userid]; if (gym) { if (gym.pending.length) { this.sendReply("Challengers waiting to fight your E4 team: "+gym.pending.join(",")); } else if (!silent) { this.sendReply("There are no challengers waiting to fight your E4 team right now."); } } }, pendingchallengeshelp : [ '/pendingchallenges - Show any pending challenges you have.', ], givebadge : function(target) { if (this.cmdToken === '!') return this.errorReply('You cannot broadcast this command.'); if (Rooms.global.lockdown) return this.errorReply('The server is in lockdown. You cannot hand out badges at this time.'); if (!this.user.registered) return this.errorReply('Please log in first.'); if (!LeagueSetup.options.badgeGive) return this.errorReply("No badges are allowed to be handed out at this time, by League Administration mandate."); let gym = LeagueSetup.gyms[this.user.userid]; if (!gym && !LeagueSetup.admins.includes(this.user.userid)) { return this.errorReply("You are not a registered gym leader."); } let badge = gym.badge; let other = null; let admin = ""; if (this.room.battle) { if (!this.room.battle.ended) return this.errorReply(`But the battle in this room isn't finished!`); if (this.room.battle.format === 'tppleaguegym' && this.room.battle.p1 === this.user) { other = this.room.battle.p2; } } if (!other) { if (!target) return this.errorReply(`No target user.`); let b = this.splitTarget(target); if (!this.targetUser) return this.errorReply(`User is not online to recieve their badge.`); other = this.targetUser; if (b) { if (LeagueSetup.admins.includes(this.user.userid)) { badge = b; admin = ", on behalf of the League Administration,"; } else { return this.errorReply("Only League Administrators can hand out arbitrary badges."); } } } if (!badge) { return this.errorReply(`You have not defined a badge for your gym.`); } if (Date.now() < (gym.lastBadgeGivenTime || 0)+1000*60*6){ // 6 minnutes return this.errorReply(`You are giving out badges too quickly. Legit fights do not last 30 seconds after all.`); } if (other === this.user || other.userid === this.user.userid) { return this.errorReply('You cannot give your own badge to yourself, cheater.'); } let challenge = LeagueSetup.challengers[other.userid]; if (!challenge) { // other.sendTo(this.room, `|html|<div class="message-error">${this.user.name} is attempting to give you a TPPLeague badge, but you do not have a TPPLeague challenge set up to recieve the badge. If you wish to recieve this badge, please user the TPPLeague button on the main menu to begin a league challenge.</div>`); return this.errorReply(`${other.name} does not have a TPPLeague challenge set up. Cannot give badge.`); } if (challenge.badges[badge]) { return this.errorReply(`${other.name} already owns the ${badge} Badge.`); } gym.lastBadgeGivenTime = Date.now(); challenge.badges[badge] = 1; LeagueSetup.markDirty(); this.add(`|html|<div class="infobox badgeget" for="${other.userid}" style="text-align:center;"><p style='font-weight:bold;'>${this.user.name}${admin} presents ${other.name} with the ${badge} Badge!</p><img src="/badges/${badge}.png" width="80" height="80"/></div>`); other.send(`|badgeget|${badge}`); this.parse('/savereplay silent'); }, givebadgehelp: [ '/givebadge [user] - If you are a gym leader, gives your gym badge to the named user. User must be present.', ], };
/** Data comes from a docker inspect command output */ function Container(data) { for (d in data) { this[d] = data[d]; } } Container.prototype.name = function() { return this.Name.ltrim('/'); } Container.prototype.shortName = function() { return this.name(); } Container.prototype.shortId = function() { return this.Id.substr(0, 12); } Container.prototype.links = function() { if (this.HostConfig == undefined || this.HostConfig.Links == undefined) { return []; } return this.HostConfig.Links.reduce(function (arr, str) { var name = str.split(':')[0]; if (arr.indexOf(name) < 0) { arr.push(name); } return arr; }, []); } Container.prototype.linksShortNames = function() { if (this.HostConfig == undefined || this.HostConfig.Links == undefined) { return {}; } return this.HostConfig.Links.reduce(function (arr, str) { var parts = str.split(':'); var name = parts[0]; var sname = parts.last().split('/').last(); if (!(name in arr) || sname.length < arr[name].length) { arr[name] = sname; } return arr; }, {}); } Container.prototype.stringPorts = function() { if (this.NetworkSettings == undefined || this.NetworkSettings.Ports == undefined) { return [] } var ports = [] for (ph in this.NetworkSettings.Ports) { var list = this.NetworkSettings.Ports[ph] ports = ports.concat(list.map(function(o) { return o.HostIp+':'+o.HostPort+'->'+ph })) } return ports } module.exports = Container;
/* globals mocha, chai */ import {jml, glue, nbsp, $, $$, body} from '../src/jml.js'; mocha.setup('bdd'); mocha.globals(['jml', 'glue', 'nbsp']); window.jml = jml; window.glue = glue; window.nbsp = nbsp; window.$ = $; window.$$ = $$; window.body = body; window.assert = chai.assert; window.expect = chai.expect;
let webpack = require('webpack'); let path = require( 'path'); const AssetsPlugin = require('assets-webpack-plugin'); let projectRoot = process.cwd(); let assetsPath = path.join(projectRoot, "public", "build"); let publicPath = `/build/`; let host = "0.0.0.0"; let config = { devServer: { inline: true, host, port: 3100, hot: true, disableHostCheck: true, contentBase: assetsPath, watchOptions: { poll: true } }, cache: false, // devtool: 'cheap-module-eval-source-map', devtool: 'eval', mode: "development", context: process.cwd(), entry: { bundle: [ path.resolve(projectRoot, './webpack/util/polyfills.js'), path.resolve(projectRoot, './src/client/index.js'), ] }, target: 'web', output: { path: assetsPath, // Note: Physical files are only output by the production build task `npm run build`. publicPath: publicPath, pathinfo: false, filename: 'bundle/[name].js', chunkFilename: 'bundle/chunk-[name].js', hotUpdateChunkFilename: '[hash].hot-update.js', // use for AssetsPlugin to filter out hot updates }, plugins: [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('development'), 'process.env.BROWSER': true, }), new webpack.HotModuleReplacementPlugin(), new webpack.DllReferencePlugin({ context: path.join(projectRoot, "src" , "client"), manifest: require("../dll/commons-manifest.json") }), new AssetsPlugin({ fullPath: true, path: path.join(projectRoot, './dev') }) ], module: { noParse: /ffmpeg/, rules: [ { test: /\.s[ac]ss$/i, include: [ path.resolve(projectRoot, './src/shared/'), path.resolve(projectRoot, './node_modules/bootstrap-sass/assets/stylesheets/'), ], use: [ "style-loader", "css-loader?url=false", "sass-loader", ], }, { test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: "url-loader" , options: { limit: 10000, mimetype: 'application/font-woff', name: 'fonts/[name].[ext]' }, include: [ path.resolve(projectRoot, './src/shared/fonts/') , path.resolve(projectRoot, './node_modules/bootstrap-sass/assets/fonts/') , path.resolve(projectRoot, './node_modules/font-awesome/fonts/') , ], }, { test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: "file-loader" , options: { name: 'fonts/[name].[ext]' }, include: [ path.resolve(projectRoot, './src/shared/fonts/') , path.resolve(projectRoot, './node_modules/bootstrap-sass/assets/fonts/') , path.resolve(projectRoot, './node_modules/font-awesome/fonts/') , ], }, { test: /(\.jsx)|(\.js)$/i, exclude: [/node_modules/, /ffmpeg/], include: [ path.join(projectRoot, "src" , "client"), path.join(projectRoot, "src" , "shared") ], use: [ { loader: 'babel-loader', options: { cacheDirectory: true, babelrc: false, presets: [ "@babel/preset-react", [ "@babel/preset-env", { "modules": false, "debug": true, "loose": true, "targets": { "browsers": [ "last 2 Chrome versions", "last 2 ChromeAndroid versions", "last 2 Edge versions", "last 2 Firefox versions", "last 2 FirefoxAndroid versions", "last 2 iOS versions", "last 2 Opera versions", "last 2 Safari versions", "ie >= 11" ] }, } ], ], plugins: [ "@babel/plugin-syntax-dynamic-import", "@babel/plugin-proposal-object-rest-spread", "@babel/plugin-proposal-class-properties", ], }, } ], }, ] }, resolveLoader: { modules: [ "node_modules" ], }, resolve: { modules: [ "node_modules" ], unsafeCache : true, }, profile: true } module.exports = config;
import * as types from '../../mutation-types' import lazyLoader from './lazyLoader' const state = { items: [ { name: 'Home', path: '/', meta: { label: ['主頁面'], link: 'Home.vue', icon: ['fas', 'home'], permission: 99 }, components: lazyLoader('Home') }, { name: 'Server Status', path: '/status', meta: { label: ['伺服器'], link: 'Server.vue', icon: ['fas', 'server'], permission: 99 }, components: lazyLoader('Server') }, { name: 'Files', path: '/files', meta: { label: ['檔案庫'], link: 'File.vue', icon: ['fas', 'database'], permission: 0 }, components: lazyLoader('File') }, { name: 'Monit', path: '/monit', meta: { label: ['監視器'], link: 'Monit.vue', icon: ['fas', 'video'], permission: 1 }, components: lazyLoader('Monit') }, { name: 'Todo List', path: '/todos', meta: { label: ['待辦事項'], link: 'Todos.vue', icon: ['fas', 'calendar-check'], permission: 2 }, components: lazyLoader('Todos') }, { name: 'Post', path: '/post', meta: { label: ['新增文章'], link: 'Post.vue', icon: ['fas', 'file'], permission: 3 }, components: lazyLoader('Post/Add') }, { name: 'Post List', path: '/post-list', meta: { label: ['文章列表'], link: 'Post.vue', icon: ['fas', 'list-alt'], permission: 3 }, components: lazyLoader('Post/List') }, { name: 'News', path: '/news', meta: { label: ['新增新聞'], link: 'News.vue', icon: ['fas', 'plus'], permission: 2 }, components: lazyLoader('News/Add') }, { name: 'News List', path: '/news-list', meta: { label: ['新聞列表'], link: 'News.vue', icon: ['fas', 'newspaper'], permission: 2 }, components: lazyLoader('News/List') } ] } const mutations = { [types.EXPAND_MENU] (state, menuItem) { if (menuItem.index > -1) { if (state.items[menuItem.index] && state.items[menuItem.index].meta) { state.items[menuItem.index].meta.expanded = menuItem.expanded } } else if (menuItem.item && 'expanded' in menuItem.item.meta) { menuItem.item.meta.expanded = menuItem.expanded } } } export default { state, mutations }