code
stringlengths
2
1.05M
/** * Module that provides formatter to convert result of {@link module:seeq.search search} into JSON. * * @module json */ "use strict"; var util = require("./util"); /** * Format/convert result of {@link module:seeq.search search} into JSON. * * @param {Object} data * Result of {@link module:seeq.search search}. * @param {Object} settings * Format settings. See {@link module:format format} for details. * @return {String} * JSON representing result of search. * @see {@link module:format format} */ module.exports = function(data, settings) { /*jshint boss:true*/ var getLicenseList = util.getLicenseList, getRepository = util.getRepository, bVerbose = settings.verbose, queryList = settings.queryList, out = {}, item, nameMap, nameResult, nI, nK, nN, nQ, sName, sResourceName, resourceResult, resourceResultList, result, resultList, value; for (nI = 0, nK = queryList.length; nI < nK; nI++) { sName = queryList[nI]; nameResult = data[sName]; if (nameResult && typeof nameResult === "object") { out[sName] = nameMap = {}; for (sResourceName in nameResult) { nameMap[sResourceName] = item = {}; item.result = resultList = []; resourceResult = nameResult[sResourceName]; resourceResultList = resourceResult.result; nQ = resourceResultList.length; if (nQ) { for (nN = 0; nN < nQ; nN++) { result = resourceResultList[nN]; item = { name: result.name }; if (value = result.description) { item.description = value; } if (value = result.url) { item.url = value; } if ((value = result.keywords) && value.length) { item.keywords = value; } if (bVerbose) { if (value = result.version) { item.version = value; } if (value = getRepository(result)) { item.repository = value; } if (value = result.language) { item.language = value; } if ((value = getLicenseList(result)) && value.length) { item.license = value; } if (value = result.stars) { item.stars = value; } } resultList.push(item); } } else if (value = resourceResult.error) { item.error = value; } } } } return JSON.stringify(out, null, 4); };
'use strict'; /** * Transform event source mappings, */ const BbPromise = require('bluebird'); const _ = require('lodash'); const utils = require('../utils'); module.exports = function(currentTemplate, aliasStackTemplates, currentAliasStackTemplate) { const stageStack = this._serverless.service.provider.compiledCloudFormationTemplate; const aliasStack = this._serverless.service.provider.compiledCloudFormationAliasTemplate; const stackName = this._provider.naming.getStackName(); const subscriptions = _.assign({}, _.pickBy(_.get(stageStack, 'Resources', {}), [ 'Type', 'AWS::Lambda::EventSourceMapping' ])); this.options.verbose && this._serverless.cli.log('Processing event source subscriptions'); _.forOwn(subscriptions, (subscription, name) => { // Reference alias as FunctionName const functionNameRef = utils.findAllReferences(_.get(subscription, 'Properties.FunctionName')); const functionName = _.replace(_.get(functionNameRef, '[0].ref', ''), /LambdaFunction$/, ''); if (_.isEmpty(functionName)) { // FIXME: Can this happen at all? this._serverless.cli.log(`Strange thing: No function name defined for ${name}`); return; } subscription.Properties.FunctionName = { Ref: `${functionName}Alias` }; subscription.DependsOn = [ `${functionName}Alias` ]; // Make sure that the referenced resource is exported by the stageStack. const resourceRef = utils.findAllReferences(_.get(subscription, 'Properties.EventSourceArn')); // Build the export name let resourceRefName = _.get(resourceRef, '[0].ref'); if (_.has(subscription.Properties, 'EventSourceArn.Fn::GetAtt')) { const attribute = subscription.Properties.EventSourceArn['Fn::GetAtt'][1]; resourceRefName += attribute; } // Add the ref output to the stack if not already done. stageStack.Outputs[resourceRefName] = { Description: 'Alias resource reference', Value: subscription.Properties.EventSourceArn, Export: { Name: `${stackName}-${resourceRefName}` } }; // Add the output to the referenced alias outputs const aliasOutputs = JSON.parse(aliasStack.Outputs.AliasOutputs.Value); aliasOutputs.push(resourceRefName); aliasStack.Outputs.AliasOutputs.Value = JSON.stringify(aliasOutputs); // Replace the reference with the cross stack reference subscription.Properties.EventSourceArn = {}; // Event source ARNs can be volatile - e.g. DynamoDB and must not be referenced // with Fn::ImportValue which does not allow for changes. So we have to register // them for delayed lookup until the base stack has been updated. this.addDeferredOutput(`${stackName}-${resourceRefName}`, subscription.Properties, 'EventSourceArn'); // Remove mapping from stage stack delete stageStack.Resources[name]; }); // Move event subscriptions to alias stack _.defaults(aliasStack.Resources, subscriptions); // Forward inputs to the promise chain return BbPromise.resolve([ currentTemplate, aliasStackTemplates, currentAliasStackTemplate ]); };
$(function() { var inputPassword , inputConfirmPassword , errorPassword , buttonSubmit , isValidPassword , validateForm; inputPassword = $('#password'); inputConfirmPassword = $('#confirm-password'); errorPassword = $('#error-password'); buttonSubmit = $('#submit'); isValidPassword = function() { if (inputConfirmPassword.val() === '') return false; return inputPassword.val() === inputConfirmPassword.val(); }; validateForm = function() { if (!isValidPassword()) { errorPassword.show(); buttonSubmit.addClass('ui-disabled'); } else { errorPassword.hide(); buttonSubmit.removeClass('ui-disabled'); } }; inputPassword.on('keyup', validateForm); inputConfirmPassword.on('keyup', validateForm); });
/** * @author JerryC * @date 16/5/10 * @description */ 'use strict'; const express = require('express'); const app = express(); const cookieParser = require('cookie-parser'); const ssoAuth = require('../index'); const ssoClient = ssoAuth.createClient({ ssoClient: { client: {name: 'siteA', key: '%^&*'} } }); app.use(cookieParser()); app.get('/', function (req, res) { res.send('Hello World!'); }); app.use(express.static('page')); app.get('/verify', ssoClient.middleware.verify(), (err, req, res, next) => { if (err){ return res.status(400).send(err.message); } res.status(200).send(JSON.stringify(req.sso)); }); app.listen(3002, function () { console.log('Example app listening on port 3002!'); });
'use strict'; describe('Controller: ServerDetailCtrl', function () { var $httpBackend, $rootScope, $resource, configuration, $controller, _, ServerDetailCtrl; var scope; // load the controller's module beforeEach(module('kheoApp')); beforeEach(inject(function($injector) { $httpBackend = $injector.get('$httpBackend'); $rootScope = $injector.get('$rootScope'); $resource = $injector.get('$resource'); $controller = $injector.get('$controller'); configuration = $injector.get('configuration'); _ = $injector.get('_'); scope = $rootScope.$new(); ServerDetailCtrl = $controller('ServerDetailCtrl', { '$scope': scope, '$resource': $resource, '$routeParams': { hostname: 'myserver' }, 'configuration': configuration, '_': _ }); $httpBackend.when('GET', configuration.backend + '/servers/myserver').respond(200, readJSON('test/mock/serverDetail.json')); $httpBackend.when('GET', configuration.backend + '/plugins').respond(200, readJSON('test/mock/plugins.json')); })); afterEach(function() { $httpBackend.verifyNoOutstandingExpectation(); $httpBackend.verifyNoOutstandingRequest(); }); it('should retrieve plugins and server on initialization', function () { $httpBackend.expectGET(configuration.backend + '/servers/myserver'); $httpBackend.expectGET(configuration.backend + '/plugins'); $httpBackend.flush(); }); it('should filter properties function of plugin', function() { $httpBackend.flush(); scope.filterPluginProperties(scope.plugins[0]); expect(scope.pluginProperties.length).toBe(3); }); it('should filter keys to exclude type $$hashKey key and @kheo-type', function() { $httpBackend.flush(); var filtered = scope.getKeys(scope.pluginProperties[0]); expect(filtered.hasOwnProperty('type')).toBe(false); expect(filtered.hasOwnProperty('@kheo-type')).toBe(false); expect(filtered.hasOwnProperty('$$hashKey')).toBe(false); }); it('should give string value for a plugin property', function() { $httpBackend.flush(); var stringValue = scope.stringValue(scope.server.serverProperties[0]); expect(stringValue).toBe('key=logo, description=logo'); }); });
"use strict"; var t = require("../../types"); exports.ForInStatement = exports.ForOfStatement = function (node, parent, scope, context, file) { var left = node.left; if (t.isVariableDeclaration(left)) { var declar = left.declarations[0]; if (declar.init) throw file.errorWithNode(declar, "No assignments allowed in for-in/of head"); } };
var gulp = require('gulp'), concat = require('gulp-concat'), uglify = require('gulp-uglify'), jc = require('../jcConfig'), paths = jc.paths; gulp.task('js-top', function () { var topJsScripts = [ paths.bower + '/html5shiv/dist/html5shiv.js' ]; return gulp.src(topJsScripts) .pipe(concat("top.js")) .pipe(uglify()) .pipe(gulp.dest(paths.assets)); }); gulp.task('js-app', function () { var appJsScripts = [ //paths.vendor + '/modernizr/modernizr-custom.js', paths.bower + '/jquery/dist/jquery.js', paths.npm + '/angular/angular.js', paths.npm + '/angular-route/angular-route.js', paths.npm + '/angular-sanitize/angular-sanitize.js', paths.npm + '/angular-touch/angular-touch.js', paths.npm + '/angular-animate/angular-animate.js', paths.bower + '/angularfire/dist/angularfire.js', paths.bower + '/ngstorage/ngStorage.js', paths.partials + '/templates.js', paths.bower + '/bootstrap/js/collapse.js', paths.bower + '/bootstrap/js/transition.js', paths.js + '/config.js', paths.js + '/JcApp.js', paths.js + '/*.js', paths.js + '/**/*.js' ]; return gulp.src(appJsScripts) .pipe(concat("app.js")) .pipe(uglify()) .pipe(gulp.dest(paths.tmp)); }); gulp.task('js-vendor', function () { var vendorScripts, uglifyOptions; vendorScripts = [ paths.bower + '/firebase/firebase.js' ]; uglifyOptions = { mangle: false }; return gulp.src(vendorScripts) .pipe(concat("vendor.js")) .pipe(uglify(uglifyOptions)) .pipe(gulp.dest(paths.tmp)); }); gulp.task('js-bottom', function () { var bottomScripts = [ paths.tmp + '/vendor.js', paths.tmp + '/app.js' ]; return gulp.src(bottomScripts) .pipe(concat("bottom.js")) .pipe(gulp.dest(paths.assets)); });
const elixir = require('laravel-elixir'); require('laravel-elixir-vue-2'); /* |-------------------------------------------------------------------------- | Elixir Asset Management |-------------------------------------------------------------------------- | | Elixir provides a clean, fluent API for defining some basic Gulp tasks | for your Laravel application. By default, we are compiling the Sass | file for your application as well as publishing vendor resources. | */ elixir((mix) => { var bootstrapPath = 'node_modules/bootstrap-sass/assets'; var jqueryPath = 'node_modules/jquery/dist'; mix.sass('app.scss') .copy(bootstrapPath + '/fonts', 'public/fonts') .copy(bootstrapPath + '/javascripts/bootstrap.js', 'resources/assets/js') .copy(jqueryPath + '/jquery.js', 'resources/assets/js') .scripts(['jquery.js', 'bootstrap.js', 'bootstrap-toggle.js']) .scripts('broadcast.js') .styles(['bootstrap-toggle.css', 'custom.css']); });
$(document).ready(function(){ /* // footer hide $('footer').hide(); // random team-member order var members = [ ['Octavio', 'Biologist', 'https://pingendo.com/assets/photos/user_placeholder.png'], ['Franco', 'Phycisist', 'https://pingendo.com/assets/photos/user_placeholder.png'], ['Cezar', 'C.S. Student', 'https://pingendo.com/assets/photos/user_placeholder.png'], ['Carlos', 'Journalist', 'https://pingendo.com/assets/photos/user_placeholder.png'] ]; members.sort(function(a, b){return 0.5 - Math.random()}); for (var i = 0; i<4; i++) { $(".team-member-name").eq(i).text(members[i][0]); $(".team-member-desc").eq(i).text(members[i][1]); $(".team-member-img").eq(i).attr("src",members[i][2]); }; // footer toggle $('#more').on('click', function(){ $('footer').slideToggle(); }); $('#footer-close').on('click', function(){ $('footer').slideToggle(); }); */ // Collapses navbar after click on mobile $('#myNavbar').on("click", "a", null, function () { $('#myNavbar').collapse('hide'); }); // Smooth scroll $('a[href*=\\#]').on('click', function(event){ event.preventDefault(); $('html,body').animate({scrollTop:$(this.hash).offset().top}, 1000); }); });
/* istanbul ignore file */ import { isDefined } from './is' import get from './get' export const isBrowserEnv = () => { if (!isDefined(process)) return true return get(process, 'browser') === true } export const isNodeEnv = () => !isBrowserEnv() export const isTestEnv = () => { const testEnv = get(process, 'env.NODE_ENV') || get(process, 'env.BABEL_ENV') || '' return testEnv.toLowerCase() === 'test' }
$(window).load(function() { $(window).on('keydown', function(evt) { console.log('keycode', evt.which); // slice down if (evt.which === 38) { // down arrow var sliceZ = Session.get('sliceZ'); sliceZ = Math.min(Math.max(sliceZ + 1, 1), Session.get('gridSizeZ')); Session.set('sliceZ', sliceZ); console.log('slice down', sliceZ); } // slice up if (evt.which === 40) { // up arrow var sliceZ = Session.get('sliceZ'); sliceZ = Math.min(Math.max(sliceZ - 1, 1), Session.get('gridSizeZ')); Session.set('sliceZ', sliceZ); console.log('slice up', sliceZ); } // rotate left if (evt.which === 37) { var currentRotationIndex = Session.get('rotationIndex'); var newRotationIndex = (currentRotationIndex + 3) % 4 Session.set('rotationIndex', newRotationIndex); console.log('rotate left', newRotationIndex); } // rotate right if (evt.which === 39) { var currentRotationIndex = Session.get('rotationIndex'); var newRotationIndex = (currentRotationIndex + 5) % 4 Session.set('rotationIndex', newRotationIndex); console.log('rotate right', newRotationIndex); } }); });
window.addEventListener("load",limitaOitoDigitos); function limitaOitoDigitos(numero){ var max_numeros = 8; if(numero.value.length > max_numeros) { numero.value = numero.value.substr(0, max_numeros); } }
var mongoose = require( 'mongoose' ); var crypto = require('crypto'); var jwt = require('jsonwebtoken'); var config = require('../config/config'); var userSchema = new mongoose.Schema({ email: { type: String, unique: true, required: true }, name: { type: String, required: true }, hash: String, salt: String }); userSchema.methods.setPassword = function(password){ this.salt = crypto.randomBytes(16).toString('hex'); this.hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex'); }; userSchema.methods.validPassword = function(password) { var hash = crypto.pbkdf2Sync(password, this.salt, 1000, 64).toString('hex'); return this.hash === hash; }; userSchema.methods.generateJwt = function() { var expiry = new Date(); expiry.setDate(expiry.getDate() + 7); return jwt.sign({ _id: this._id, email: this.email, name: this.name, exp: parseInt(expiry.getTime() / 1000) }, config.secretKey); }; mongoose.model('User', userSchema);
import { combineReducers } from 'redux'; export function error(state = null, action) { switch (action.type) { case 'PRODUCT_LIST_ERROR': return action.error; case 'PRODUCT_LIST_MERCURE_DELETED': return `${action.retrieved['@id']} has been deleted by another user.`; case 'PRODUCT_LIST_RESET': return null; default: return state; } } export function loading(state = false, action) { switch (action.type) { case 'PRODUCT_LIST_LOADING': return action.loading; case 'PRODUCT_LIST_RESET': return false; default: return state; } } export function retrieved(state = null, action) { switch (action.type) { case 'PRODUCT_LIST_SUCCESS': return action.retrieved; case 'PRODUCT_LIST_RESET': return null; case 'PRODUCT_LIST_MERCURE_MESSAGE': return { ...state, 'hydra:member': state['hydra:member'].map(item => item['@id'] === action.retrieved['@id'] ? action.retrieved : item ) }; case 'PRODUCT_LIST_MERCURE_DELETED': return { ...state, 'hydra:member': state['hydra:member'].filter( item => item['@id'] !== action.retrieved['@id'] ) }; default: return state; } } export function eventSource(state = null, action) { switch (action.type) { case 'PRODUCT_LIST_MERCURE_OPEN': return action.eventSource; case 'PRODUCT_LIST_RESET': return null; default: return state; } } export default combineReducers({ error, loading, retrieved, eventSource });
/** * @fileoverview Enforce ES5 or ES6 class for returning value in render function. * @author Mark Orel */ 'use strict'; // ------------------------------------------------------------------------------ // Requirements // ------------------------------------------------------------------------------ const RuleTester = require('eslint').RuleTester; const rule = require('../../../lib/rules/require-render-return'); const parsers = require('../../helpers/parsers'); const parserOptions = { ecmaVersion: 2018, sourceType: 'module', ecmaFeatures: { jsx: true, }, }; // ------------------------------------------------------------------------------ // Tests // ------------------------------------------------------------------------------ const ruleTester = new RuleTester({ parserOptions }); ruleTester.run('require-render-return', rule, { valid: parsers.all([ { // ES6 class code: ` class Hello extends React.Component { render() { return <div>Hello {this.props.name}</div>; } } `, }, { // ES6 class with render property code: ` class Hello extends React.Component { render = () => { return <div>Hello {this.props.name}</div>; } } `, features: ['class fields', 'no-ts-old'], // TODO: FIXME: remove no-ts-old and fix }, { // ES6 class with render property (implicit return) code: ` class Hello extends React.Component { render = () => ( <div>Hello {this.props.name}</div> ) } `, features: ['class fields', 'no-ts-old'], // TODO: FIXME: remove no-ts-old and fix }, { // ES5 class code: ` var Hello = createReactClass({ displayName: 'Hello', render: function() { return <div></div> } }); `, }, { // Stateless function code: ` function Hello() { return <div></div>; } `, }, { // Stateless arrow function code: ` var Hello = () => ( <div></div> ); `, }, { // Return in a switch...case code: ` var Hello = createReactClass({ render: function() { switch (this.props.name) { case 'Foo': return <div>Hello Foo</div>; default: return <div>Hello {this.props.name}</div>; } } }); `, }, { // Return in a if...else code: ` var Hello = createReactClass({ render: function() { if (this.props.name === 'Foo') { return <div>Hello Foo</div>; } else { return <div>Hello {this.props.name}</div>; } } }); `, }, { // Not a React component code: ` class Hello { render() {} } `, }, { // ES6 class without a render method code: 'class Hello extends React.Component {}', }, { // ES5 class without a render method code: 'var Hello = createReactClass({});', }, { // ES5 class with an imported render method code: ` var render = require('./render'); var Hello = createReactClass({ render }); `, }, { // Invalid render method (but accepted by Babel) code: ` class Foo extends Component { render } `, features: ['class fields'], }, ]), invalid: parsers.all([ { // Missing return in ES5 class code: ` var Hello = createReactClass({ displayName: 'Hello', render: function() {} }); `, errors: [ { messageId: 'noRenderReturn', line: 4, }, ], }, { // Missing return in ES6 class code: ` class Hello extends React.Component { render() {} } `, errors: [{ messageId: 'noRenderReturn' }], }, { // Missing return (but one is present in a sub-function) code: ` class Hello extends React.Component { render() { const names = this.props.names.map(function(name) { return <div>{name}</div> }); } } `, errors: [ { messageId: 'noRenderReturn', line: 3, }, ], }, { // Missing return ES6 class render property code: ` class Hello extends React.Component { render = () => { <div>Hello {this.props.name}</div> } } `, features: ['class fields'], errors: [ { messageId: 'noRenderReturn', line: 3, }, ], }, ]), });
/* eslint-disable no-console */ 'use strict' const libp2p = require('../../') const TCP = require('libp2p-tcp') const PeerInfo = require('peer-info') const waterfall = require('async/waterfall') const defaultsDeep = require('@nodeutils/defaults-deep') class MyBundle extends libp2p { constructor (_options) { const defaults = { modules: { transport: [ TCP ] } } super(defaultsDeep(_options, defaults)) } } let node waterfall([ (cb) => PeerInfo.create(cb), (peerInfo, cb) => { peerInfo.multiaddrs.add('/ip4/0.0.0.0/tcp/0') node = new MyBundle({ peerInfo: peerInfo }) node.start(cb) } ], (err) => { if (err) { throw err } console.log('node has started (true/false):', node.isStarted()) console.log('listening on:') node.peerInfo.multiaddrs.forEach((ma) => console.log(ma.toString())) })
import Ember from 'ember'; import Reference from './reference'; import { DEBUG } from '@glimmer/env'; import { deprecate } from '@ember/debug'; import { assertPolymorphicType } from 'ember-data/-debug'; import isEnabled from '../../features'; const { RSVP: { resolve }, get } = Ember; /** A HasManyReference is a low level API that allows users and addon author to perform meta-operations on a has-many relationship. @class HasManyReference @namespace DS */ const HasManyReference = function(store, parentInternalModel, hasManyRelationship) { this._super$constructor(store, parentInternalModel); this.hasManyRelationship = hasManyRelationship; this.type = hasManyRelationship.relationshipMeta.type; this.parent = parentInternalModel.recordReference; // TODO inverse }; HasManyReference.prototype = Object.create(Reference.prototype); HasManyReference.prototype.constructor = HasManyReference; HasManyReference.prototype._super$constructor = Reference; /** This returns a string that represents how the reference will be looked up when it is loaded. If the relationship has a link it will use the "link" otherwise it defaults to "id". Example ```app/models/post.js export default DS.Model.extend({ comments: DS.hasMany({ async: true }) }); ``` ```javascript let post = store.push({ data: { type: 'post', id: 1, relationships: { comments: { data: [{ type: 'comment', id: 1 }] } } } }); let commentsRef = post.hasMany('comments'); // get the identifier of the reference if (commentsRef.remoteType() === "ids") { let ids = commentsRef.ids(); } else if (commentsRef.remoteType() === "link") { let link = commentsRef.link(); } ``` @method remoteType @return {String} The name of the remote type. This should either be "link" or "ids" */ HasManyReference.prototype.remoteType = function() { if (this.hasManyRelationship.link) { return "link"; } return "ids"; }; /** The link Ember Data will use to fetch or reload this has-many relationship. Example ```app/models/post.js export default DS.Model.extend({ comments: DS.hasMany({ async: true }) }); ``` ```javascript let post = store.push({ data: { type: 'post', id: 1, relationships: { comments: { links: { related: '/posts/1/comments' } } } } }); let commentsRef = post.hasMany('comments'); commentsRef.link(); // '/posts/1/comments' ``` @method link @return {String} The link Ember Data will use to fetch or reload this has-many relationship. */ HasManyReference.prototype.link = function() { return this.hasManyRelationship.link; }; /** `ids()` returns an array of the record ids in this relationship. Example ```app/models/post.js export default DS.Model.extend({ comments: DS.hasMany({ async: true }) }); ``` ```javascript let post = store.push({ data: { type: 'post', id: 1, relationships: { comments: { data: [{ type: 'comment', id: 1 }] } } } }); let commentsRef = post.hasMany('comments'); commentsRef.ids(); // ['1'] ``` @method ids @return {Array} The ids in this has-many relationship */ HasManyReference.prototype.ids = function() { let members = this.hasManyRelationship.members.toArray(); return members.map(function(internalModel) { return internalModel.id; }); }; /** The meta data for the has-many relationship. Example ```app/models/post.js export default DS.Model.extend({ comments: DS.hasMany({ async: true }) }); ``` ```javascript let post = store.push({ data: { type: 'post', id: 1, relationships: { comments: { links: { related: { href: '/posts/1/comments', meta: { count: 10 } } } } } } }); let commentsRef = post.hasMany('comments'); commentsRef.meta(); // { count: 10 } ``` @method meta @return {Object} The meta information for the has-many relationship. */ HasManyReference.prototype.meta = function() { return this.hasManyRelationship.meta; }; /** `push` can be used to update the data in the relationship and Ember Data will treat the new data as the canonical value of this relationship on the backend. Example ```app/models/post.js export default DS.Model.extend({ comments: DS.hasMany({ async: true }) }); ``` ``` let post = store.push({ data: { type: 'post', id: 1, relationships: { comments: { data: [{ type: 'comment', id: 1 }] } } } }); let commentsRef = post.hasMany('comments'); commentsRef.ids(); // ['1'] commentsRef.push([ [{ type: 'comment', id: 2 }], [{ type: 'comment', id: 3 }], ]) commentsRef.ids(); // ['2', '3'] ``` @method push @param {Array|Promise} objectOrPromise a promise that resolves to a JSONAPI document object describing the new value of this relationship. @return {DS.ManyArray} */ HasManyReference.prototype.push = function(objectOrPromise) { return resolve(objectOrPromise).then((payload) => { let array = payload; if (isEnabled("ds-overhaul-references")) { deprecate("HasManyReference#push(array) is deprecated. Push a JSON-API document instead.", !Array.isArray(payload), { id: 'ds.references.has-many.push-array', until: '3.0' }); } let useLegacyArrayPush = true; if (typeof payload === "object" && payload.data) { array = payload.data; useLegacyArrayPush = array.length && array[0].data; if (isEnabled('ds-overhaul-references')) { deprecate("HasManyReference#push() expects a valid JSON-API document.", !useLegacyArrayPush, { id: 'ds.references.has-many.push-invalid-json-api', until: '3.0' }); } } if (!isEnabled('ds-overhaul-references')) { useLegacyArrayPush = true; } let internalModels; if (useLegacyArrayPush) { internalModels = array.map((obj) => { let record = this.store.push(obj); if (DEBUG) { let relationshipMeta = this.hasManyRelationship.relationshipMeta; assertPolymorphicType(this.internalModel, relationshipMeta, record._internalModel); } return record._internalModel; }); } else { let records = this.store.push(payload); internalModels = Ember.A(records).mapBy('_internalModel'); if (DEBUG) { internalModels.forEach((internalModel) => { let relationshipMeta = this.hasManyRelationship.relationshipMeta; assertPolymorphicType(this.internalModel, relationshipMeta, internalModel); }); } } this.hasManyRelationship.computeChanges(internalModels); return this.hasManyRelationship.manyArray; }); }; HasManyReference.prototype._isLoaded = function() { let hasData = get(this.hasManyRelationship, 'hasData'); if (!hasData) { return false; } let members = this.hasManyRelationship.members.toArray(); return members.every(function(internalModel) { return internalModel.isLoaded() === true; }); }; /** `value()` synchronously returns the current value of the has-many relationship. Unlike `record.get('relationshipName')`, calling `value()` on a reference does not trigger a fetch if the async relationship is not yet loaded. If the relationship is not loaded it will always return `null`. Example ```app/models/post.js export default DS.Model.extend({ comments: DS.hasMany({ async: true }) }); ``` ```javascript let post = store.push({ data: { type: 'post', id: 1, relationships: { comments: { data: [{ type: 'comment', id: 1 }] } } } }); let commentsRef = post.hasMany('comments'); post.get('comments').then(function(comments) { commentsRef.value() === comments }) ``` @method value @return {DS.ManyArray} */ HasManyReference.prototype.value = function() { if (this._isLoaded()) { return this.hasManyRelationship.manyArray; } return null; }; /** Loads the relationship if it is not already loaded. If the relationship is already loaded this method does not trigger a new load. Example ```app/models/post.js export default DS.Model.extend({ comments: DS.hasMany({ async: true }) }); ``` ```javascript let post = store.push({ data: { type: 'post', id: 1, relationships: { comments: { data: [{ type: 'comment', id: 1 }] } } } }); let commentsRef = post.hasMany('comments'); commentsRef.load().then(function(comments) { //... }); ``` @method load @return {Promise} a promise that resolves with the ManyArray in this has-many relationship. */ HasManyReference.prototype.load = function() { if (!this._isLoaded()) { return this.hasManyRelationship.getRecords(); } return resolve(this.hasManyRelationship.manyArray); }; /** Reloads this has-many relationship. Example ```app/models/post.js export default DS.Model.extend({ comments: DS.hasMany({ async: true }) }); ``` ```javascript let post = store.push({ data: { type: 'post', id: 1, relationships: { comments: { data: [{ type: 'comment', id: 1 }] } } } }); let commentsRef = post.hasMany('comments'); commentsRef.reload().then(function(comments) { //... }); ``` @method reload @return {Promise} a promise that resolves with the ManyArray in this has-many relationship. */ HasManyReference.prototype.reload = function() { return this.hasManyRelationship.reload(); }; export default HasManyReference;
(function () { var canvas; var canvasContext; var scale; var controlSet; var keyCodeTouched = null; var resizeBuffer = $('<canvas width="128" height="128">')[0]; var resizeBufferContext = resizeBuffer.getContext('2d'); disableSmoothing(resizeBufferContext); RuneWizard.setDisplay(RuneWizardCanvas); $(window).resize(function () { var availableHeight = $(window).height() - $('#touchControls').height(); var lesserDimension = Math.min($(window).width(), availableHeight); var newScale = 1; while ((newScale + 1) * 128 <= lesserDimension) { newScale++; } if (newScale != scale) { resizeBufferContext.save(); resizeBufferContext.scale(1 / scale, 1 / scale); resizeBufferContext.drawImage(canvas, 0, 0); resizeBufferContext.restore(); scale = newScale; canvas.width = 128 * scale; canvas.height = 128 * scale; canvasContext = canvas.getContext('2d'); canvasContext.scale(scale, scale); disableSmoothing(canvasContext); canvasContext.drawImage(resizeBuffer, 0, 0); } canvas.style.left = ($(window).width() - canvas.width) / 2 + 'px'; canvas.style.top = (availableHeight - canvas.height) / 2 + 'px'; }); function disableSmoothing(context) { context.imageSmoothingEnabled = false; context.webkitImageSmoothingEnabled = false; context.mozImageSmoothingEnabled = false; } $(window).load(function () { RuneWizard.graphics = $('#graphics')[0]; canvas = $('canvas')[0]; $(window).resize(); $(document).keydown(function (event) { RuneWizard.display.keyPressed(event.which); }); $(document).keyup(function (event) { if ('keyReleased' in RuneWizard.display) { RuneWizard.display.keyReleased(event.which); } }); $('.control').on('mousedown touchstart', function (event) { event.preventDefault(); if (typeof $(this).data('keycode') !== 'undefined') { $(this).addClass('pressed'); keyCodeTouched = Canvas[$(this).data('keycode')]; RuneWizard.display.keyPressed(keyCodeTouched); } }); $(document).on('mouseup touchend', function () { $('#touchControls .control.pressed').removeClass('pressed'); if ('keyReleased' in RuneWizard.display && keyCodeTouched != null) { RuneWizard.display.keyReleased(keyCodeTouched); } keyCodeTouched = null; }); setInterval(function () { var newControlSet = 'disabled'; if (RuneWizard.display == RuneWizardCanvas) { switch (RuneWizardCanvas.stage) { case 0: case 4: newControlSet = 'disabled'; break; case 1: newControlSet = 'title'; break; case 2: newControlSet = 'howToPlay'; break; case 3: newControlSet = 'playerSelect'; break; } } else if (RuneWizard.display == BoardCanvas) { newControlSet = 'board'; } else if (RuneWizard.display == EndingCanvas) { newControlSet = 'disabled'; } if (newControlSet != controlSet) { $('#' + controlSet + 'ControlSet').hide(); $('#' + newControlSet + 'ControlSet').show(); controlSet = newControlSet; } RuneWizard.display.run(); RuneWizard.display.paint(canvasContext); }, 33); }); })();
'use strict'; var tobacco_cessation = function (attrs) { this.name = "tobacco_cessation"; for (var k in attrs) { this[k] = attrs[k]; } }; module.exports = tobacco_cessation;
const overflowRegex = /(auto|scroll|hidden)/ function needScroll(el, dir) { let { scrollTop, scrollLeft, scrollHeight, scrollWidth, clientHeight, clientWidth } = el; switch (dir) { case "left": return scrollLeft > 0 break; case "right": return scrollLeft + clientWidth < scrollWidth break; case "up": return scrollTop > 0 break; case "down": return scrollTop + clientHeight < scrollHeight break; } return false; } function canScroll(el) { let style = el.currentStyle || window.getComputedStyle(el, null); if (el === document.scrollingElement) { return true; } if (el === document.body) { return true; } if (el === document.documentElement) { return true; } return overflowRegex.test(style.overflow + style.overflowY + style.overflowX); } function isScrollable(el, dir) { // dir: left, right, up, down return canScroll(el) && needScroll(el, dir); } export default isScrollable;
'use strict'; const { vec3, mat4 } = require('gl-matrix'); const _ = require('lodash'); const dat = require('dat.gui'); const Shader = require('../Shader'); const GLTF2Loader = require('../GLTF2Loader'); const ShaderLoader = require('../ShaderLoader'); const ImageLoader = require('../ImageLoader'); const getCurTimeMS = () => (new Date()).getTime(); const initialMS = getCurTimeMS(); const getTimeMS = () => getCurTimeMS() - initialMS; const getTimeS = () => getTimeMS() / 1000; const gui = new dat.GUI(); const conf = { useIBL: true, lights: 1, color0: [ 255, 255, 255 ], color1: [ 0, 128, 255 ], color2: [ 255, 0, 255 ] }; gui.add(conf, 'useIBL'); gui.add(conf, 'lights', 0, 3).step(1); gui.addColor(conf, 'color0'); gui.addColor(conf, 'color1'); gui.addColor(conf, 'color2'); const lightPositions = [ vec3.fromValues(0, 5, 0), vec3.fromValues(-3, 5, 0), vec3.fromValues(3, 5, 0) ]; const radians = degrees => degrees * Math.PI / 180; const accessorTypeSizes = { SCALAR: 1, VEC2: 2, VEC3: 3, VEC4: 4, }; const attributeLocations = { POSITION: 0, NORMAL: 1, TEXCOORD_0: 2 }; let first = true; const logOnce = (...args) => { if (first) { console.log(...args); } }; const accessorType2size = type => accessorTypeSizes[type]; const create = () => { /* GLTFS stuff */ let gltf; let buffers; let images; let meshes = []; let cameras = []; let textures = []; /* Pipeline stuff */ let irradianceTexture; let radianceTexture; let brdfTexture; let haveLodSupport = false; let haveFloatSupport = false; function getBufferData (bufferN) { return buffers[bufferN]; } function getBufferViewData (bufferView) { const data = getBufferData(bufferView.buffer); const byteOffset = _.get(bufferView, 'byteOffset', 0); const byteLength = _.get(bufferView, 'byteLength'); return data.slice(byteOffset, byteOffset + byteLength); } function loadBufferView (gl, bufferView, target) { const data = getBufferViewData(bufferView); if (bufferView.target) { target = bufferView.target; } const buffer = gl.createBuffer(); gl.bindBuffer(target, buffer); gl.bufferData(target, data, gl.STATIC_DRAW); return { target, buffer }; } function bindBufferView (gl, bufferViews, bufferViewN) { const { target, buffer } = bufferViews[bufferViewN]; gl.bindBuffer(target, buffer); } function bindTextureAs (gl, shader, name, materialRef, uniform, unit) { const index = _.get(materialRef, [ name, 'index' ]); const textureSpec = gltf.textures[index]; const sampler = textureSpec.sampler ? gltf.samplers[textureSpec.sampler] : { }; const texture = textures[textureSpec.source]; logOnce('sampler', sampler, unit); gl.activeTexture(gl.TEXTURE0 + unit); gl.bindTexture(gl.TEXTURE_2D, texture); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, _.get(sampler, 'magFilter', gl.LINEAR)); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, _.get(sampler, 'minFilter', gl.LINEAR)); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, _.get(sampler, 'wrapS', gl.REPEAT)); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, _.get(sampler, 'wrapT', gl.REPEAT)); shader.uniform1i(uniform, unit); } function setupShaderForMaterialTextured (gl, material, definesMap) { const pbrMetallicRoughness = material.pbrMetallicRoughness; // TODO DamagedHelmet seems to have sRGB albedo and emissive textures. if (false) { definesMap.HAVE_ALBEDO_SRGB = 1; definesMap.HAVE_EMISSIVE_SRGB = 1; definesMap.HAVE_IBL_SRGB = 1; definesMap.GAMME_CORRECT = 1; definesMap.HDR_TONEMAP = 1; } definesMap.HAVE_LIGHTS = conf.lights; definesMap.HAVE_IBL = conf.useIBL ? 1 : 0; definesMap.HAVE_LOD = haveLodSupport ? 1 : 0; if (_.has(material, 'occlusionTexture')) { definesMap.HAVE_OCCLUSION_TEXTURE = 1; } if (_.has(material, 'emissiveTexture')) { definesMap.HAVE_EMISSIVE_TEXTURE = 1; } const shader = getShader(gl, 'textured', definesMap); // Setup shader shader.use(); shader.uniform3fv('camPos', viewPos); gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_CUBE_MAP, irradianceTexture); shader.uniform1i('irradianceSampler', 0); gl.activeTexture(gl.TEXTURE1); gl.bindTexture(gl.TEXTURE_CUBE_MAP, radianceTexture); shader.uniform1i('radianceSampler', 1); gl.activeTexture(gl.TEXTURE2); gl.bindTexture(gl.TEXTURE_2D, brdfTexture); shader.uniform1i('brdfSampler', 2); let unit = 3; bindTextureAs(gl, shader, 'baseColorTexture', pbrMetallicRoughness, 'albedoSampler', unit++); bindTextureAs(gl, shader, 'metallicRoughnessTexture', pbrMetallicRoughness, 'metallicRoughnessSampler', unit++); if (_.has(material, 'occlusionTexture')) { bindTextureAs(gl, shader, 'occlusionTexture', material, 'occlusionSampler', unit++); } if (_.has(material, 'emissiveTexture')) { bindTextureAs(gl, shader, 'emissiveTexture', material, 'emissiveSampler', unit++); } for (let i = 0; i < conf.lights; i++) { const color = _.get(conf, `color${i}`); const position = lightPositions[i]; shader.uniform3fv(`lightPositions[${i}]`, position); shader.uniform3fv(`lightColors[${i}]`, vec3.fromValues(color[0], color[1], color[2])); } return shader; } const setupShaderForMaterial = setupShaderForMaterialTextured; // TODO With webgl2 we can use VertexArrayObject and move load part from draw to load function createMesh (gl, mesh) { const bufferViews = { }; const uploadBufferView = (bufferViewN, target) => { console.log('loading', bufferViewN); if (!_.has(bufferViews, bufferViewN)) { const bufferView = gltf.bufferViews[bufferViewN]; _.set(bufferViews, bufferViewN, loadBufferView(gl, bufferView, target)); } }; _.forEach(mesh.primitives, primitive => { const mode = _.get(primitive, 'mode', 4); if (mode != 4) { throw 'TODO X support primitive of other modes than 4'; } // PREPARE // TODO This step could be moved to init and into a Vertex Array Object _.forEach(primitive.attributes, (accessorN, attribute) => { const accessor = gltf.accessors[accessorN]; // TODO prepare and link properly in gltf instead? if (_.has(attributeLocations, attribute)) { if (_.has(accessor, 'sparse')) { throw 'TODO X support accessors with sparse'; } if (!_.has(accessor, 'bufferView')) { throw 'TODO X support accessors without bufferView'; } uploadBufferView(accessor.bufferView, gl.ARRAY_BUFFER); } else { logOnce('WARN skipping', attribute); } }); if (_.has(primitive, 'indices')) { const accessor = gltf.accessors[primitive.indices]; uploadBufferView(accessor.bufferView, gl.ELEMENT_ARRAY_BUFFER); } }); console.log('loaded', bufferViews); return { draw: function (projection, view, model) { _.forEach(mesh.primitives, primitive => { logOnce('primitive', primitive); const definesMap = { }; const mode = _.get(primitive, 'mode', 4); if (mode != 4) { throw 'TODO X support primitive of other modes than 4'; } // PREPARE // TODO This step could be moved to init and into a Vertex Array Object _.forEach(primitive.attributes, (accessorN, attribute) => { const accessor = gltf.accessors[accessorN]; // TODO prepare and link properly in gltf instead? if (_.has(attributeLocations, attribute)) { const location = attributeLocations[attribute]; _.set(definesMap, `HAVE_${attribute}`, 1); const bufferView = gltf.bufferViews[accessor.bufferView]; bindBufferView(gl, bufferViews, accessor.bufferView); const size = accessorType2size(accessor.type); const componentType = _.get(accessor, 'componentType'); const normalized = _.get(accessor, 'normalized', false); const byteStride = _.get(bufferView, 'byteStride', 0); const byteOffset = _.get(accessor, 'byteOffset', 0); gl.vertexAttribPointer(location, size, componentType, normalized, byteStride, byteOffset); gl.enableVertexAttribArray(location); } else { logOnce('WARN skipping', attribute); } }); if (_.has(primitive, 'indices')) { const accessor = gltf.accessors[primitive.indices]; bindBufferView(gl, bufferViews, accessor.bufferView); } // DRAW const material = _.get(gltf.materials, primitive.material); const shader = setupShaderForMaterial(gl, material, definesMap); shader.uniformMatrix4fv('projection', projection); shader.uniformMatrix4fv('view', view); shader.uniformMatrix4fv('model', model); if (_.has(primitive, 'indices')) { const accessor = gltf.accessors[primitive.indices]; gl.drawElements(gl.TRIANGLES, accessor.count, accessor.componentType, null); } else { const accessor = gltf.accessors[primitive.attributes.POSITION]; gl.drawArrays(gl.TRIANGLES, 0, accessor.count); } // UNLOAD/UNBIND // TODO Unnecessary if we had Vertex Array Objects? _.forEach(primitive.attributes, (accessorN, attribute) => { if (_.has(attributeLocations, attribute)) { const location = attributeLocations[attribute]; gl.disableVertexAttribArray(location); } }); }); } }; } function createImageTexture (gl, image) { console.log('creatingTexture', image, image.width, image.height); const texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); //gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, true); gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, false); gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.REPEAT); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.REPEAT); gl.bindTexture(gl.TEXTURE_2D, null); return texture; } function renderNode (gl, node, projection, view, model) { if (_.has(node, 'translation')) { model = mat4.multiply(mat4.create(), model, mat4.fromTranslation(mat4.create(), node.translation)); } if (_.has(node, 'rotation')) { model = mat4.multiply(mat4.create(), model, mat4.fromQuat(mat4.create(), node.rotation)); } if (_.has(node, 'scale')) { model = mat4.multiply(mat4.create(), model, mat4.fromScaling(mat4.create(), node.scale)); } if (_.has(node, 'matrix')) { model = mat4.multiply(mat4.create(), model, new Float32Array(node.matrix)); } if (_.has(node, 'camera')) { projection = cameras[node.camera]; } if (_.has(node, 'mesh')) { const mesh = meshes[node.mesh]; mesh.draw(projection, view, model); } if (_.has(node, 'children')) { _.forEach(node.children, child => { const node = gltf.nodes[child]; renderNode(gl, node, projection, view, model); }); } } const viewPos = vec3.fromValues(0.0, 0.0, -5.0); function renderScene (gl, scene) { const projection = mat4.perspective(mat4.create(), radians(45), viewport.width / viewport.height, 0.1, 800); const view = mat4.lookAt(mat4.create(), viewPos, [ 0, 0, 0], [ 0, 1, 0 ]); const model = mat4.fromRotation(mat4.create(), radians(20 * getTimeS()), vec3.fromValues(0.0, 1.0, 0.0)); _.forEach(scene.nodes, nodeN => renderNode(gl, gltf.nodes[nodeN], projection, view, model)); } const shaders = { }; const createShader = (gl, name, defines) => { let { vs, fs } = ShaderLoader.load(name); vs = defines + '\n' + vs; fs = defines + '\n' + fs; const shader = new Shader(gl, vs, fs, attributeLocations); return shader; }; const getShader = (gl, name, definesMap) => { const defines = _.map(_.filter(_.toPairs(definesMap), '[1]'), ([ key, value]) => `#define ${key} ${value}`).sort().join('\n'); const path = `${name} ${defines}`; if (!_.has(shaders, path)) { _.set(shaders, path, createShader(gl, name, defines)); } return _.get(shaders, path); }; const loadCubemap = (gl, displayName, paths) => { return Promise.all(_.map(paths, path => ImageLoader.load(path))) .then(images => { const texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_CUBE_MAP, texture); const levels = images.length / 6; for (let i = 0; i < 6; i++) { for (let level = 0; level < levels; level++) { const index = level + levels * i; const image = images[index]; gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image); } } // gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_R, gl.CLAMP_TO_EDGE); // gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); // gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); // linear interpolation in srgb color space .. just great :( /* gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR); gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR); */ gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR); gl.generateMipmap(gl.TEXTURE_CUBE_MAP); if (displayName) { texture.displayName = displayName; } gl.bindTexture(gl.TEXTURE_CUBE_MAP, null); return texture; }); }; const loadBRDF = gl => { return ImageLoader.load(require('../resources/brdfLUT.png')).then(image => { brdfTexture = createImageTexture(gl, image); }); }; const loadCubemaps = gl => { return Promise.all([ loadCubemap(gl, 'irradiance', [ require('../resources/okretnica/irradiance_posx.png'), require('../resources/okretnica/irradiance_negx.png'), require('../resources/okretnica/irradiance_posy.png'), require('../resources/okretnica/irradiance_negy.png'), require('../resources/okretnica/irradiance_posz.png'), require('../resources/okretnica/irradiance_negz.png') ]), loadCubemap(gl, 'radiance', [ require('../resources/okretnica/radiance_posx_0_256x256.png'), require('../resources/okretnica/radiance_posx_1_128x128.png'), require('../resources/okretnica/radiance_posx_2_64x64.png'), require('../resources/okretnica/radiance_posx_3_32x32.png'), require('../resources/okretnica/radiance_posx_4_16x16.png'), require('../resources/okretnica/radiance_posx_5_8x8.png'), require('../resources/okretnica/radiance_posx_6_4x4.png'), require('../resources/okretnica/radiance_posx_7_2x2.png'), require('../resources/okretnica/radiance_posx_8_1x1.png'), require('../resources/okretnica/radiance_negx_0_256x256.png'), require('../resources/okretnica/radiance_negx_1_128x128.png'), require('../resources/okretnica/radiance_negx_2_64x64.png'), require('../resources/okretnica/radiance_negx_3_32x32.png'), require('../resources/okretnica/radiance_negx_4_16x16.png'), require('../resources/okretnica/radiance_negx_5_8x8.png'), require('../resources/okretnica/radiance_negx_6_4x4.png'), require('../resources/okretnica/radiance_negx_7_2x2.png'), require('../resources/okretnica/radiance_negx_8_1x1.png'), require('../resources/okretnica/radiance_posy_0_256x256.png'), require('../resources/okretnica/radiance_posy_1_128x128.png'), require('../resources/okretnica/radiance_posy_2_64x64.png'), require('../resources/okretnica/radiance_posy_3_32x32.png'), require('../resources/okretnica/radiance_posy_4_16x16.png'), require('../resources/okretnica/radiance_posy_5_8x8.png'), require('../resources/okretnica/radiance_posy_6_4x4.png'), require('../resources/okretnica/radiance_posy_7_2x2.png'), require('../resources/okretnica/radiance_posy_8_1x1.png'), require('../resources/okretnica/radiance_negy_0_256x256.png'), require('../resources/okretnica/radiance_negy_1_128x128.png'), require('../resources/okretnica/radiance_negy_2_64x64.png'), require('../resources/okretnica/radiance_negy_3_32x32.png'), require('../resources/okretnica/radiance_negy_4_16x16.png'), require('../resources/okretnica/radiance_negy_5_8x8.png'), require('../resources/okretnica/radiance_negy_6_4x4.png'), require('../resources/okretnica/radiance_negy_7_2x2.png'), require('../resources/okretnica/radiance_negy_8_1x1.png'), require('../resources/okretnica/radiance_posz_0_256x256.png'), require('../resources/okretnica/radiance_posz_1_128x128.png'), require('../resources/okretnica/radiance_posz_2_64x64.png'), require('../resources/okretnica/radiance_posz_3_32x32.png'), require('../resources/okretnica/radiance_posz_4_16x16.png'), require('../resources/okretnica/radiance_posz_5_8x8.png'), require('../resources/okretnica/radiance_posz_6_4x4.png'), require('../resources/okretnica/radiance_posz_7_2x2.png'), require('../resources/okretnica/radiance_posz_8_1x1.png'), require('../resources/okretnica/radiance_negz_0_256x256.png'), require('../resources/okretnica/radiance_negz_1_128x128.png'), require('../resources/okretnica/radiance_negz_2_64x64.png'), require('../resources/okretnica/radiance_negz_3_32x32.png'), require('../resources/okretnica/radiance_negz_4_16x16.png'), require('../resources/okretnica/radiance_negz_5_8x8.png'), require('../resources/okretnica/radiance_negz_6_4x4.png'), require('../resources/okretnica/radiance_negz_7_2x2.png'), require('../resources/okretnica/radiance_negz_8_1x1.png') ]), ]) .then(res => { irradianceTexture = res[0]; radianceTexture = res[1]; }); }; const load = gl => { haveLodSupport = !!gl.getExtension('EXT_shader_texture_lod'); haveFloatSupport = !!gl.getExtension('OES_texture_float') && !!gl.getExtension('OES_texture_float_linear'); console.log('haveLodSupport', haveLodSupport); console.log('haveFloatSupport', haveFloatSupport); return Promise.all([ GLTF2Loader.load('DamagedHelmet').then(res => { gltf = res.gltf; buffers = res.buffers; images = res.images; meshes = _.map(gltf.meshes, mesh => createMesh(gl, mesh)); textures = _.map(images, image => createImageTexture(gl, image)); }), loadCubemaps(gl), loadBRDF(gl) ]); }; let viewport = { width: 640, height: 480 }; const init = (gl, width, height) => { gl.clearColor(0.0, 0.0, 0.0, 1.0); //gl.disable(gl.DEPTH_TEST); gl.enable(gl.DEPTH_TEST); //gl.enable(gl.TEXTURE_2D); gl.disable(gl.BLEND); gl.viewport(0, 0, width, height); viewport = { width, height }; }; const render = (gl) => { gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); const sceneN = gltf.scene || 0; // TODO if no default scene, skip render? renderScene(gl, gltf.scenes[sceneN]); first = false; }; return { load, init, render }; }; module.exports = create;
import {Account, Bank, Category, Operation, Setting} from './Models'; function xhrError(xhr, textStatus, err) { var msg = xhr.responseText; try { msg = JSON.parse(msg).error; } catch(e) { // ignore } alert('xhr error: ' + err + '\n' + msg); } function xhrReject(reject) { return function(xhr, textStatus, xhrError) { var xhrText = xhr.responseText; var error = null; try { error = JSON.parse(xhrText); } catch(e) { // ignore } reject({ code: error.code, content: error.content || null, xhrText, xhrError, }); }; } module.exports = { init() { return new Promise((ok, err) => { $.get('all', ok).fail(xhrReject(err)); }); }, getAccounts: function(bankId, cb) { $.get(`banks/${bankId}/accounts`, function(accounts) { cb(bankId, accounts.map((acc) => new Account(acc))); }).fail(xhrError); }, getOperations: function(accountId, cb) { $.get(`accounts/${accountId}/operations`, function (data) { cb(data.map((o) => new Operation(o))); }).fail(xhrError); }, deleteBank: function(bankId, cb) { $.ajax({ url: 'banks/' + bankId, type: 'DELETE', success: cb, error: xhrError }); }, deleteAccount: function(accountId, cb) { $.ajax({ url: 'accounts/' + accountId, type: 'DELETE', success: cb, error: xhrError }); }, deleteCategory: function(categoryId, replaceByCategoryId, cb) { $.ajax({ url: 'categories/' + categoryId, type: 'DELETE', data: { replaceByCategoryId: replaceByCategoryId }, success: cb, error: xhrError }); }, updateOperation: function(id, newOp) { return new Promise((accept, reject) => { $.ajax({ url: 'operations/' + id, type: 'PUT', data: newOp, success: accept, error: xhrReject(reject) }); }); }, setCategoryForOperation: function(operationId, categoryId) { return this.updateOperation(operationId, {categoryId}); }, setTypeForOperation: function(operationId, typeId) { return this.updateOperation(operationId, {operationTypeID: typeId}); }, mergeOperations: function(toKeepId, toRemoveId) { return new Promise((accept, reject) => { $.ajax({ url: 'operations/' + toKeepId + '/mergeWith/' + toRemoveId, type: 'PUT', success: accept, error: xhrReject(reject) }); }); }, getNewOperations: function(accessId) { return new Promise((accept, reject) => { $.get('accesses/' + accessId + '/fetch/operations', accept) .fail(xhrReject(reject)); }) }, getNewAccounts: function(accessId) { return new Promise((accept, reject) => { $.get('accesses/' + accessId + '/fetch/accounts', accept) .fail(xhrReject(reject)); }) }, getCategories: function(cb) { $.get('categories', function (data) { var categories = [] for (var i = 0; i < data.length; i++) { var c = new Category(data[i]); categories.push(c) } cb(categories); }).fail(xhrError); }, updateWeboob(which) { return new Promise(function(resolve, reject) { $.ajax({ url: 'settings/weboob', type: 'PUT', data: { action: which }, success: resolve, error: xhrReject(reject) }); }); }, importInstance(content) { return new Promise((resolve, reject) => { $.post('all/', {all: content}, resolve) .fail(xhrReject(reject)); }); }, saveSetting(key, value) { return new Promise(function(resolve, reject) { $.post('settings', { key, value }, (data) => { resolve(data); }).fail(xhrReject(reject)); }); }, getSettings() { return new Promise(function(resolve, reject) { $.get('settings', (data) => { let settings = []; for (let pair of data) { settings.push(new Setting(pair)); } resolve(settings); }).fail(xhrReject(reject)); }); }, updateAccess(accessId, access) { $.ajax({ url: 'accesses/' + accessId, type: 'PUT', data: access, error: xhrError }); }, addBank: function(uuid, id, pwd, maybeWebsite) { return new Promise((accept, reject) => { $.post('accesses/', { bank: uuid, login: id, password: pwd, website: maybeWebsite }, accept).fail(xhrReject(reject)); }); }, addCategory: function(category, cb) { $.post('categories', category, cb).fail(xhrError); }, updateCategory: function(id, category, cb) { $.ajax({ url:'categories/' + id, type: 'PUT', data: category, success: cb, error: xhrError }); }, };
module.exports = require('run-object-basis')(require('run-series'))
$("#menu-close").click(function(e) { e.preventDefault(); $("#sidebar-wrapper").toggleClass("active"); }); $("#menu-toggle").click(function(e) { e.preventDefault(); $("#sidebar-wrapper").toggleClass("active"); }); $(function() { $('a[href*=#]:not([href=#],[data-toggle],[data-target],[data-slide])').click(function() { if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') || location.hostname == this.hostname) { var target = $(this.hash); target = target.length ? target : $('[name=' + this.hash.slice(1) + ']'); if (target.length) { $('html,body').animate({ scrollTop: target.offset().top }, 1000); return false; } } }); }); var fixed = false; $(document).scroll(function() { if ($(this).scrollTop() > 250) { if (!fixed) { fixed = true; $('#to-top').show("slow", function() { $('#to-top').css({ position: 'fixed', display: 'block' }); }); } } else { if (fixed) { fixed = false; $('#to-top').hide("slow", function() { $('#to-top').css({ display: 'none' }); }); } } });
var autoplaySpeed = 15000; //15s var tweetHideInterval = null; var photoBombList = []; var nextSlideIndex = 0; // Static functions var slickGoto = function(index) { $('#slick').slick('slickGoTo', index); } var toggleContainers = function(elementId) { switch (elementId) { case 'tweet': console.log('toggle to tweet'); $('#slick').slick('slickPause'); $('#slick').hide(); $('#tweet-img').show(); setTimeout(toggleContainers, autoplaySpeed, 'slick'); break; case 'slick': default: console.log('toggle to slick'); $('#slick').show(); $('#tweet-img').hide(); $('#slick').slick('slickPlay'); slickGoto(nextSlideIndex); break; } }; var setTweet = function(tweet, withImage) { console.log('Displaying tweet ', tweet); if (tweetHideInterval) { clearInterval(tweetHideInterval); } $('#tweet-container').show(); if (withImage) { var entities = tweet.entities || {}; var media = entities.media || []; var image = _.find(media, function(o) { return o.type === 'photo' ;}); if (image) { console.log('Applying a tweet image'); $('#tweet-img').show(); var url = image.media_url_https $('#tweet-img').attr('src', url); } } else { $('#tweet-img').hide(); } $('#tweet-user-pic').attr('src', tweet.user.profile_image_url_https); $('#tweet-user-name').text(tweet.user.screen_name); $('#tweet-text').text(tweet.text); tweetHideInterval = setInterval(function() { $('#tweet-container').hide(); }, autoplaySpeed*2); } $(document).ready(function() { console.log('Starting slick'); $('#slick').slick({ 'slidesToShow': 1, 'slidesToScroll': 1, 'autoplay': true, 'arrows': false, 'lazyLoad': 'progressive', 'pauseOnHover': false, 'pauseOnFocus': false, 'autoplaySpeed': autoplaySpeed }); // On before slide change $('#slick').on('beforeChange', function(event, slick, currentSlide, nextSlide) { console.log('beforeChange', nextSlide); nextSlideIndex = nextSlide; var nextSlideImg = slick.$slides[nextSlide].getElementsByTagName('img')[0]; var nextSlideImgWidth = nextSlideImg.offsetWidth; $('#tweet-container').width(nextSlideImgWidth); if (photoBombList.length > 0) { var tweet = photoBombList.shift(); refreshPhotobombCount(); setTweet(tweet, true); toggleContainers('tweet'); } }); console.log('Connecting to server socket.io'); var socket = io(); socket.on('Tweet', function(tweet) { console.log('Tweet recieved'); setTweet(tweet); }); socket.on('PhotoBomb', function(tweet) { console.log('Image recieved'); photoBombList.push(tweet); refreshPhotobombCount(); }); var refreshPhotobombCount = function() { $('#photo-bomb-count').text(photoBombList.length); console.log('Set photobomb count ', photoBombList.length) } });
exports.sourceNodes = ({ actions, createContentDigest }) => { const node = { id: `parent_childAdditionForFields`, internal: { type: `Parent_ChildAdditionForFields`, }, foo: `run-1`, } node.internal.contentDigest = createContentDigest(node) actions.createNode(node) }
/* eslint-disable import/no-extraneous-dependencies */ // Matching bootstraps level of browser compatibility except for: // // - no support for IE8 // // @see https://github.com/twbs/bootstrap-sass#d-npm--nodejs // @see http://getbootstrap.com/getting-started/#support const autoprefixer = require('autoprefixer')({ browsers: [ 'Android 2.3', 'Android >= 4', 'Chrome >= 20', 'Firefox >= 24', 'Explorer >= 11', 'iOS >= 6', 'Opera >= 12', 'Safari >= 6' ] }); const cssnano = require('cssnano')(); const cssstats = require('cssstats')(); const statsReporter = require('postcss-stats-reporter')(); const src = '<%= dst %>/css/*.css'; module.exports = { dev: { src, options: { map: { inline: false }, processors: [ autoprefixer ] } }, prod: { src, options: { processors: [ autoprefixer, cssnano, cssstats, statsReporter ] } } };
describe("FireLayer.js", function () { var layer = null; beforeEach(function () { layer = new FireLayer(); layer.setCanvas(); }); describe("setCanvas", function () { it("·½·¨´æÔÚ", function () { expect(layer.setCanvas).toBeDefined(); }); it("»ñµÃFireLayerCanvas", function () { spyOn(document, "getElementById"); layer.setCanvas(); expect(document.getElementById).toHaveBeenCalledWith("fireLayerCanvas"); }); it("ÉèÖÃCanvasµÄcss", function () { layer.setCanvas(); var canvas = $(layer.P__canvas); var expectedCss = { "position": "absolute", "top": bomberConfig.canvas.TOP.toString(), "left": bomberConfig.canvas.LEFT.toString(), "z-index": 2 }; expect(canvas.css("top")).toEqual(expectedCss.top); expect(canvas.css("left")).toEqual(expectedCss.left); expect(Number(canvas.css("z-index"))).toEqual(expectedCss["z-index"]); }); }); describe("change", function () { it("Èç¹û²ãÄÚÓÐÔªËØ£¬Ôòµ÷ÓÃsetStateChange", function () { var fakeFire = {}; layer.appendChild(fakeFire); spyOn(layer, "setStateChange"); layer.change(); expect(layer.setStateChange).toHaveBeenCalled(); }); }); describe("²ã³õʼ»¯ºóµ÷ÓõÄAPI²âÊÔ", function () { beforeEach(function () { layer.init(); }); describe("draw", function () { beforeEach(function () { sprite1 = spriteFactory.createBomb(); sprite2 = spriteFactory.createBomb(); layer.appendChild(sprite1).appendChild(sprite2); }); it("µ÷ÓÃÿ¸ö¾«ÁéÀàµÄdraw£¬´«Èë²ÎÊýcontext", function () { spyOn(sprite1, "draw"); spyOn(sprite2, "draw"); layer.draw(); expect(sprite1.draw).toHaveBeenCalledWith(layer.P__context); expect(sprite2.draw).toHaveBeenCalledWith(layer.P__context); }); }); describe("clear", function () { beforeEach(function () { sprite1 = spriteFactory.createBomb(); sprite2 = spriteFactory.createBomb(); layer.appendChild(sprite1).appendChild(sprite2); }); it("Çå³ý»­²¼È«²¿ÇøÓò", function () { spyOn(sprite1, "clear"); spyOn(sprite2, "clear"); layer.clear(); expect(sprite1.clear).toHaveBeenCalledWith(layer.P__context); expect(sprite2.clear).toHaveBeenCalledWith(layer.P__context); }); }); describe("run", function () { function setStateNormal() { layer.setStateNormal(); }; function setStateChange() { layer.setStateChange(); }; it("Èç¹ûP__stateΪnormal£¬Ôò·µ»Ø", function () { setStateNormal(); spyOn(layer, "clear"); layer.run(); expect(layer.clear).not.toHaveBeenCalled(); }); describe("Èç¹ûP__stateΪchange", function () { beforeEach(function () { setStateChange(); }); it("µ÷ÓÃclear", function () { spyOn(layer, "clear"); layer.run(); expect(layer.clear).toHaveBeenCalled(); }); it("µ÷ÓÃdraw", function () { spyOn(layer, "draw"); layer.run(); expect(layer.draw).toHaveBeenCalled(); }); it("»Ö¸´×´Ì¬stateΪnormal", function () { layer.setStateChange(); layer.run(); expect(layer.P__isNormal()).toBeTruthy(); }); }); }); }); });
/* eslint-disable no-unused-vars */ const { defineStep } = require('cucumber'); defineStep('noop', () => { }); defineStep('noop {string}', (noop) => { }); defineStep('ambiguous', () => { }); defineStep('ambiguous', () => { }); defineStep('failed', () => { throw new Error('FAILED'); }); defineStep('passed', () => { }); defineStep('pending', () => 'pending'); defineStep('skipped', () => 'skipped'); defineStep('doc string', (noop) => { }); defineStep('data table', (noop) => { }); defineStep('world', function world() { this.world(); });
var rptbaocaokhachhang = new baseRpt('baocaokhachhang','baocaokhachhang','Báo cáo khách hàng',{ onLoading:function($scope,options){ var $filter = options.$filter; var $location = options.$location; $scope.gotoKH = function(r){ $location.url("dmkh/view/" + r._id); } } }); rptbaocaokhachhang.defaultCondition = function(condition){ var c = new Date(); condition.tu_ngay = new Date(c.getFullYear(),c.getMonth(),1); condition.den_ngay = c; condition.tinh_thanh =""; condition.phu_trach =""; }
'use strict'; angular.module('confusionApp') .controller('MenuController', ['$scope', 'menuFactory', function($scope, menuFactory) { $scope.tab = 1; $scope.filtText = ''; $scope.showDetails = false; $scope.showMenu = false; $scope.message = "Loading ..."; $scope.dishes= {}; menuFactory.getDishes() .then( function(response) { $scope.dishes = response.data; $scope.showMenu = true; }, function(response) { $scope.message = "Error: "+response.status + " " + response.statusText; } ); $scope.select = function(setTab) { $scope.tab = setTab; if (setTab === 2) { $scope.filtText = "appetizer"; } else if (setTab === 3) { $scope.filtText = "mains"; } else if (setTab === 4) { $scope.filtText = "dessert"; } else { $scope.filtText = ""; } }; $scope.isSelected = function (checkTab) { return ($scope.tab === checkTab); }; $scope.toggleDetails = function() { $scope.showDetails = !$scope.showDetails; }; }]) .controller('ContactController', ['$scope', function($scope) { $scope.feedback = {mychannel:"", firstName:"", lastName:"", agree:false, email:"" }; var channels = [{value:"tel", label:"Tel."}, {value:"Email",label:"Email"}]; $scope.channels = channels; $scope.invalidChannelSelection = false; }]) .controller('FeedbackController', ['$scope', function($scope) { $scope.sendFeedback = function() { console.log($scope.feedback); if ($scope.feedback.agree && ($scope.feedback.mychannel === "")) { $scope.invalidChannelSelection = true; console.log('incorrect'); } else { $scope.invalidChannelSelection = false; $scope.feedback = {mychannel:"", firstName:"", lastName:"", agree:false, email:"" }; $scope.feedback.mychannel=""; $scope.feedbackForm.$setPristine(); console.log($scope.feedback); } }; }]) .controller('DishDetailController', ['$scope', '$stateParams', 'menuFactory', function($scope, $stateParams, menuFactory) { $scope.dish = {}; $scope.showDish = false; $scope.message="Loading ..."; menuFactory.getDish(parseInt($stateParams.id,10)) .then( function(response){ $scope.dish = response.data; $scope.showDish=true; }, function(response) { $scope.message = "Error: "+response.status + " " + response.statusText; } ); }]) .controller('DishCommentController', ['$scope', function($scope) { $scope.comment = {rating:5, comment:"", author:"", date:""}; $scope.submitComment = function () { $scope.comment.date = new Date().toISOString(); console.log($scope.comment); $scope.dish.comments.push($scope.comment); $scope.commentForm.$setPristine(); $scope.comment = {rating:5, comment:"", author:"", date:""}; }; }]) // implement the IndexController and About Controller here .controller('IndexController', ['$scope','menuFactory', 'corporateFactory' , function($scope, menuFactory, corporateFactory) { $scope.featuredDish = {}; $scope.showDish = false; $scope.message="Loading ..."; menuFactory.getDish(0) .then( function(response){ $scope.featuredDish = response.data; $scope.showDish = true; }, function(response) { $scope.message = "Error: "+response.status + " " + response.statusText; } ); $scope.promotion = menuFactory.getPromotion(0); $scope.member = corporateFactory.getLeader(3); }]) .controller('AboutController', ['$scope','corporateFactory' , function($scope, corporateFactory) { $scope.leaders = corporateFactory.getLeaders(); }]);
"use strict"; /* eslint-disable no-console */ const log = require("npmlog"); module.exports = output; // istanbul ignore next function output(...args) { log.clearProgress(); console.log(...args); log.showProgress(); }
"use strict"; /* * ooiui/static/js/views/science/StreamTableView.js * View definitions to build a table view of streams * * Dependencies * Partials: * - ooiui/static/js/partials/StreamTable.html * - ooiui/static/js/partials/StreamTableItem.html * Libs * - ooiui/static/lib/underscore/underscore.js * - ooiui/static/lib/backbone/backbone.js * - ooiui/static/js/ooi.js * Usage */ var StreamTableView = Backbone.View.extend({ columns: [ { name: 'plot', label: '' }, { name: 'download', label: '' }, { name : 'array_name', label : 'Array' }, { name : 'site_name', label : 'Site Name' }, { name : 'platform_name', label : 'Platform Name' }, { name : 'assembly_name', label : 'Node' }, { name : 'display_name', label : 'Instrument' }, { name : 'stream_name', label : 'Stream Identifier' }, { name: 'stream_type', label: 'Stream Type' }, { name: 'depth', label: 'Depth (m)' }, { name: 'lat_lon', label: 'Lat / Lon (ddm)' }, { name : 'start', label : 'Start Time' }, { name : 'end', label : 'End Time' }, { name: 'reference_designator', label: 'Reference Designator' } ], tagName: 'tbody', initialize: function() { _.bindAll(this, "render"); this.listenTo(this.collection, 'reset', this.render); this.collection.on("add", this.addOne, this); }, events: { 'click th': 'sortBy' }, sortBy: function(event) { event.stopPropagation(); var eTarget = event.target; if ( !(eTarget.id.indexOf('plot') > -1 || eTarget.id.indexOf('download') > -1) ) { ooi.trigger('StreamTableHeader:sort', eTarget.id.split('-')[1]); } }, template: JST['ooiui/static/js/partials/StreamTable.html'], render: function() { var self = this; this.$el.html(this.template({collection: this.collection, columns: this.columns})); this.$el.find('th').append('<i class="fa fa-sort-desc"></i>'); this.$el.find('th#th-plot > i').remove(); this.$el.find('th#th-download > i').remove(); this.collection.each(function(model) { var streamTableItemView = new StreamTableItemView({ columns: self.columns, model: model }), streamTableItemSubView = new StreamTableItemSubView({ model: model }); self.$el.append(streamTableItemView.el); self.$el.append(streamTableItemSubView.render().el); }); } }); /* model : StreamModel */ var StreamTableItemView = Backbone.View.extend({ tagName: 'tr', attributes: function() { "use strict"; return { 'valign': 'middle', 'class': 'accordion-toggle stream-row', 'data-toggle': 'collapse', 'style': 'cursor: pointer;' } }, events: { 'click .download' : 'onDownload', 'click .plot' : 'onRowClick' }, initialize: function(options) { if(options && options.columns) { this.columns = options.columns; } this.listenTo(this.model, 'change', this.render); this.render(); }, onDownload: function(event) { event.stopPropagation(); event.preventDefault(); var option = $(event.currentTarget).attr("download-type"); ooi.trigger('StreamTableItemView:onClick', {model: this.model, selection: option}); }, focus: function() { this.$el.addClass('highlight').siblings().removeClass('highlight'); }, template: JST['ooiui/static/js/partials/StreamTableItem.html'], render: function() { var attributes = this.model.toJSON(); this.$el.html(this.template({attributes: this.attributes, model: this.model, columns: this.columns})); this.$el.attr('data-target', '#'+this.model.cid); }, onRowClick: function(event) { event.stopPropagation(); ooi.trigger('StreamTableItemView:onRowClick', this); }, }); var StreamTableItemSubView = Backbone.View.extend({ tagName: 'tr', attributes: function() { return { 'class': 'collapse' } }, initialize: function() { "use strict"; this.listenTo(this.model, 'change', this.render); }, template: JST['ooiui/static/js/partials/StreamTableItemSubView.html'], render: function() { "use strict"; this.$el.attr('id', this.model.cid); this.$el.html(this.template({model: this.model.toJSON()})); return this; } });
import { getOwner } from '@ember/application'; import { inject as service } from '@ember/service'; import { computed } from '@ember/object'; import { get } from '@ember/object'; import ListFormController from 'ember-flexberry/controllers/list-form'; export default ListFormController.extend({ /** Name of related edit form route. @property editFormRoute @type String @default 'fd-generation-process-form' */ editFormRoute: 'fd-generation-process-form', /** Service for managing the state of the application. @property appState @type AppStateService */ appState: service(), currentProjectContext: service('fd-current-project-context'), generationService: service('fd-generation'), /** Property to form array of special structures of custom user buttons. @property customButtons @type Array */ customButtons: computed('i18n.locale', function() { let i18n = this.get('i18n'); return [{ buttonName: i18n.t('forms.fd-generation-list-form.generation-button.caption'), buttonAction: 'generationStartButtonClick', buttonClasses: 'generation-start-button', buttonTitle: i18n.t('forms.fd-generation-list-form.generation-button.title') }]; }), actions: { /** Handler for click on generate button. @method actions.generationStartButtonClick */ generationStartButtonClick() { let _this = this; _this.get('appState').loading(); let stagePk = _this.get('currentProjectContext').getCurrentStage(); let adapter = getOwner(this).lookup('adapter:application'); adapter.callFunction('Generate', { project: stagePk.toString() }, null, { withCredentials: true }, (result) => { _this.set('generationService.lastGenerationToken', result); result = result || {}; _this.get('appState').reset(); _this.transitionToRoute(_this.get('editFormRoute'), get(result, 'value')); }, () => { _this.get('appState').reset(); _this.set('error', new Error(_this.get('i18n').t('forms.fd-generation-process-form.connection-error-text'))); }); } }, /** Method to get type and attributes of a component, which will be embeded in object-list-view cell. @method getCellComponent. @param {Object} attr Attribute of projection property related to current table cell. @param {String} bindingPath Path to model property related to current table cell. @param {Object} modelClass Model class of data record related to current table row. @return {Object} Object containing name & properties of component, which will be used to render current table cell. { componentName: 'my-component', componentProperties: { ... } }. */ getCellComponent: function(attr, bindingPath) { if (bindingPath === 'startTime' || bindingPath === 'endTime') { return { componentName: 'object-list-view-cell', componentProperties: { dateFormat: 'DD.MM.YYYY, HH:mm:ss' } }; } return this._super(...arguments); }, });
/** * BuildNavigationActions */ var BuildNavigations = { init: function() { this.createMainNavigation(); this.createSecMenuNavigation(); this.createGuideMenuNavigation(); }, /** * Create main menu navigation */ createMainNavigation: function() { var actions = [], action = {}; var log = document.getElementById('log'); actions = BuildKeyAction.getDefaultActions(); action = new KeyAction(KeyMapping.VK_OK); action.setExecute(function() { log.innerHTML = 'Item main menu selected'; NavigationScreenStatus.setNavigationActions('secondMenu'); alert('Second menu selected'); }); actions.push(action); action = new KeyAction(KeyMapping.VK_LEFT); action.setExecute(function() { log.innerHTML = 'Left main menu pressed'; alert('Do you hide menu?'); }); actions.push(action); action = new KeyAction(KeyMapping.VK_UP); action.setExecute(function() { log.innerHTML = 'Up main menu pressed'; }); actions.push(action); action = new KeyAction(KeyMapping.VK_RIGHT); action.setExecute(function() { log.innerHTML = 'Right main menu pressed'; NavigationScreenStatus.setNavigationActions('secondMenu'); alert('Second menu selected'); }); actions.push(action); action = new KeyAction(KeyMapping.VK_DOWN); action.setExecute(function() { log.innerHTML = 'Down main menu pressed'; }); actions.push(action); //adding main menu navigation NavigationScreenSet.add(new NavigationActionSet('mainMenu', actions)); }, /** * Create second menu navigation */ createSecMenuNavigation: function() { var actions = [], action = {}; var log = document.getElementById('log'); actions = BuildKeyAction.getDefaultActions(); action = new KeyAction(KeyMapping.VK_OK); action.setExecute(function() { log.innerHTML = 'Item second menu selected'; alert('Showing'); }); actions.push(action); action = new KeyAction(KeyMapping.VK_LEFT); action.setExecute(function() { log.innerHTML = 'Left second menu pressed'; NavigationScreenStatus.setNavigationActions('mainMenu'); alert('Main menu selected'); }); actions.push(action); action = new KeyAction(KeyMapping.VK_UP); action.setExecute(function() { log.innerHTML = 'Up second menu pressed'; }); actions.push(action); action = new KeyAction(KeyMapping.VK_RIGHT); action.setExecute(function() { log.innerHTML = 'Right second menu pressed'; alert('Showing? Or do nothing?'); }); actions.push(action); action = new KeyAction(KeyMapping.VK_DOWN); action.setExecute(function() { log.innerHTML = 'Down second menu pressed'; }); actions.push(action); //adding second menu navigation NavigationScreenSet.add(new NavigationActionSet('secondMenu', actions)); }, /** * Create guide menu navigation */ createGuideMenuNavigation: function() { var actions = [], action = {}; var log = document.getElementById('log'); actions = BuildKeyAction.getDefaultActions(); action = new KeyAction(KeyMapping.VK_OK); action.setExecute(function() { log.innerHTML = 'Item guide (EPG) selected'; alert('Showing'); }); actions.push(action); action = new KeyAction(KeyMapping.VK_LEFT); action.setExecute(function() { log.innerHTML = 'Left guide (EPG) pressed'; }); actions.push(action); action = new KeyAction(KeyMapping.VK_UP); action.setExecute(function() { log.innerHTML = 'Up guide (EPG) pressed'; }); actions.push(action); action = new KeyAction(KeyMapping.VK_RIGHT); action.setExecute(function() { log.innerHTML = 'Right guide (EPG) pressed'; }); actions.push(action); action = new KeyAction(KeyMapping.VK_DOWN); action.setExecute(function() { log.innerHTML = 'Down guide (EPG) pressed'; }); actions.push(action); action = new KeyAction(KeyMapping.VK_BACK); action.setExecute(function() { log.innerHTML = 'Back guide (EPG) pressed, Main Menu Selected'; NavigationScreenStatus.setNavigationActions('mainMenu'); alert('Main menu selected'); }); actions.push(action); //adding guide menu navigation NavigationScreenSet.add(new NavigationActionSet('guideMenu', actions)); } };
'use strict'; const assert = require('assert'); const proc = require('process'); const sys = require('system'); const TEXT = 'test123\n'; const TEST_ARGS = ['foo', 'bar', 'baz', '123']; var p; var r; p = proc.spawn([sys.executable, 'test/helper3.js'], {stdin: 'pipe', stdout: 'pipe', stderr: 'pipe'}); p.stdin.write(TEXT); assert.equal(p.stdout.readLine(), TEXT); assert.equal(p.stderr.readLine(), TEXT); p.stdin.close(); p.stdout.close(); p.stderr.close(); r = p.wait(); assert.equal(r.exit_status, 0); assert.equal(r.term_signal, 0); p = proc.spawn([sys.executable, 'test/helper6.js'].concat(TEST_ARGS), {stdin: null, stdout: 'pipe', stderr: 'inherit'}); var data = p.stdout.readLine(); assert.deepEqual(JSON.parse(data), TEST_ARGS); p.stdout.close(); r = p.wait(); assert.equal(r.exit_status, 0); assert.equal(r.term_signal, 0);
import React from 'react'; const Stateless = () => { return ( <div> <p> Stateless functions are ideal. They only render props and sometimes trigger actions. These are the most reusable components and even have a special shorthand syntax. </p> <pre className='language-javascript'><code>{`\ let MyComponent = (props) => { return ( <div className='my-component'> <h3 className='my-component__name'>{props.name}</h3> </div> ); };\ `}</code></pre> </div> ); }; export { Stateless as default };
var gulp = require('gulp'); var paths = require('../paths'); var eslint = require('gulp-eslint'); // runs eslint on all .js files gulp.task('lint', function () { return gulp.src(paths.source) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failOnError()); });
'use strict' const net = require('net') const Promise = require('bluebird') function firstOpenPort(port, max) { max = max || 65535 const err = `no ports open from ${port} to ${max}` return new Promise((res, rej) => (function test() { const server = net.createServer() server.on('error', () => { if ((port += 1) <= max) test() else rej(new Error(err)) }) server.on('listening', server.close) server.on('close', () => res(port)) server.listen(port) })() ) } module.exports = firstOpenPort
import * as React from "react"; import PropTypes from "prop-types"; import { withWrapper } from "../Icon"; const Vector = React.forwardRef(({ size, color, ...props }, ref) => ( <svg width={size} height={size} viewBox="4 4 32 32" xmlns="http://www.w3.org/2000/svg" ref={ref} aria-hidden={!props["aria-label"]} {...props} > <path d="m20 28.947 8.236-7.71.164-.156a10.936 10.936 0 0 0 1.253-1.449C30.502 18.456 31 17.247 31 16.095 31 12.844 29.062 11 25.598 11c-1.595 0-3.343 1.034-4.905 2.534a1 1 0 0 1-1.386 0c-1.562-1.5-3.31-2.534-4.905-2.534C10.938 11 9 12.844 9 16.094c0 1.131.48 2.319 1.302 3.475.518.73 1.092 1.335 1.436 1.629L20 28.948ZM25.598 9C30.145 9 33 11.716 33 16.094c0 1.638-.652 3.22-1.724 4.708a12.92 12.92 0 0 1-1.66 1.881l-8.33 7.8c-.346.337-.81.517-1.286.517s-.94-.18-1.273-.505l-8.321-7.806c-.427-.363-1.113-1.086-1.735-1.962C7.631 19.262 7 17.704 7 16.094 7 11.716 9.855 9 14.402 9c1.981 0 3.874.98 5.598 2.461C21.724 9.98 23.617 9 25.598 9Z" fill={color} fillRule="nonzero" /> </svg> )); Vector.propTypes = { color: PropTypes.string, size: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), "aria-label": PropTypes.string, }; Vector.defaultProps = { color: "currentColor", size: "1em", }; const MdFavoriteHeartEmpty = withWrapper(Vector); MdFavoriteHeartEmpty.groupName = "Actions"; export default MdFavoriteHeartEmpty;
/** * Module dependencies. */ var mongo = require('./mongo.js'); // Handle the :qid parameter exports.loadQueue = function(req, res, next, qid) { mongo.findQueueById(qid, function(err, queue) { if (err) { next(err); } else if (queue) { req.queue = queue; next(); } else { next(new Error('Unknown Queue-ID.')); } }); }; // Handle the :uid parameter exports.loadUser = function(req, res, next, uid) { if ( ! req.queue) { next(new Error('Cannot load user without a queue.')); } mongo.findUserById(req.queue, uid, function(err, user) { if (err) { next(err); } else if (user) { req.user = user; next(); } else { next(new Error('Unknown User-ID.')); } }); }; // The user is placed in the queue, assigned a queue number. // Detects if the user is already in the queue. exports.enter = function(req, res, next) { // Detect XXX // Add new user mongo.addUserToQueue(req.queue, function(err, user) { if (err) next(err); console.log('Ny bruger:'); console.log(user); res.send('XXX new user ' + user.number + '\n'); }); }; // AJAX-endpoint for status data (or a websocket)- Returns the users place in the queue (127 of 1233), expected time left, redirect URL including a hash exports.status = function(req, res) { res.send('XXX: status for user number ' + req.user.number + '\n'); }; // When a user chooses to leave the queue, releasing his place. exports.leave = function(req, res) { res.send('XXX Elvis has left the building!'); }; // XXX Debug code exports.test = function(req, res, next) { mongo.addQueue('Smuk Fest 2015', new Date('2014-10-01'), new Date('2014-11-01'), new Date('2015-01-01'), function(err, queue) { if (err) next(err); console.log(queue); res.send('XXX Testing, one, two!\n' + queue.toString()); }); };
"use strict"; const media_server_1 = require("@bldr/media-server"); function action(port) { media_server_1.runRestApi(port); } module.exports = action;
/* * overlay.js v1.0.0 * Copyright 2014 Joah Gerstenberg (www.joahg.com) */ (function($) { $.fn.overlay = function() { overlay = $(this); overlay.ready(function() { overlay.on('transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd', function(e) { if (!overlay.hasClass('shown')) { overlay.css('visibility', 'hidden'); } }); overlay.on('show', function() { overlay.css('visibility', 'visible'); overlay.addClass('shown'); return true; }); overlay.on('hide', function() { overlay.removeClass('shown'); return true; }); overlay.on('click', function(e) { if (e.target.className === overlay.attr('class')) { return overlay.trigger('hide'); } else { return false; } }) $('a[data-overlay-trigger]').on('click', function() { overlay.trigger('show'); }); }) }; })(jQuery);
'use strict'; var mean = require('meanio'); module.exports = function(System){ return { render:function(req,res){ res.render('index',{ locals: { config: System.config.clean }, user: req.user}); }, aggregatedList:function(req,res) { res.send(res.locals.aggregatedassets); } }; };
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React, { PropTypes, Component } from 'react'; import withStyles from '../../decorators/withStyles'; import styles from './SearchForm.css'; @withStyles(styles) class SearchForm extends Component { static contextTypes = { onSetTitle: PropTypes.func.isRequired, query: PropTypes.string }; constructor(props) { super(props); this.state = { query : '' }; }; doSearch = (event) => { this.setState({ query: event.target.value }); this.props.doSearch(event.target.value); }; render(){ return ( <form className="pure-form"> <input id="search" type="text" ref="searchInput" placeholder="Search Name" value={this.state.query} onChange={this.doSearch}/> </form> ) } } export default SearchForm;
goog.provide('ngeo.DecorateLayerLoading'); goog.require('goog.asserts'); goog.require('ngeo'); /** * Provides a function that adds a 'loading 'property (using * `Object.defineProperty`) to an ol.layer.Group or a layer with * an ol.source.Tile or an ol.source.Image source. * This property is true when the layer is loading and false otherwise. * * Example: * * <span ng-if="layer.loading">please wait</span> * * @typedef {function(ol.layer.Base, angular.Scope)} * @ngdoc service * @ngname ngeoDecorateLayerLoading */ ngeo.DecorateLayerLoading; /** * @param {ol.layer.Base} layer Layer to decorate. * @param {angular.Scope} $scope Scope. */ ngeo.decorateLayerLoading = function(layer, $scope) { let source; /** * @type {Array<string>|null} */ let incrementEvents = null; /** * @type {Array<string>|null} */ let decrementEvents = null; /** * @function * @private */ const incrementLoadCount_ = increment_; /** * @function * @private */ const decrementLoadCount_ = decrement_; layer.set('load_count', 0, true); if (layer instanceof ol.layer.Group) { layer.getLayers().on('add', (olEvent) => { const newLayer = olEvent.element; newLayer.set('parent_group', layer); }); } if (layer instanceof ol.layer.Layer) { source = layer.getSource(); if (source === null) { return; } else if (source instanceof ol.source.Tile) { incrementEvents = ['tileloadstart']; decrementEvents = ['tileloadend', 'tileloaderror']; } else if (source instanceof ol.source.Image) { incrementEvents = ['imageloadstart']; decrementEvents = ['imageloadend', 'imageloaderror']; } else { goog.asserts.fail('unsupported source type'); } source.on(incrementEvents, () => { incrementLoadCount_(layer); $scope.$applyAsync(); }); source.on(decrementEvents, () => { decrementLoadCount_(layer); $scope.$applyAsync(); }); } Object.defineProperty(layer, 'loading', { configurable: true, get: () => /** @type {number} */ (layer.get('load_count')) > 0 }); /** * @function * @param {ol.layer.Base} layer Layer * @private */ function increment_(layer) { let load_count = /** @type {number} */ (layer.get('load_count')); const parent = /** @type {ol.layer.Base} */ (layer.get('parent_group')); layer.set('load_count', ++load_count, true); if (parent) { increment_(parent); } } /** * @function * @param {ol.layer.Base} layer Layer * @private */ function decrement_(layer) { let load_count = /** @type {number} */ (layer.get('load_count')); const parent = /** @type {ol.layer.Base} */ (layer.get('parent_group')); layer.set('load_count', --load_count, true); if (parent) { decrement_(parent); } } }; ngeo.module.value('ngeoDecorateLayerLoading', ngeo.decorateLayerLoading);
$(function() { var $dot, L1, L3, camera, dot, golf, render, renderer, scene, update , click = false , qqq; var size = { 1:970, 2:970 }; var cpos=0, cdate=0, creg=0, alltime=15000; $(document).ready(function(){ formleft(); formright(); consolerize(); loading_func(); }); function consolerize(){ //console.clear(); //console.log("%cClose the console", "color: red; font-style: italic; font-size:38px; text-shadow: 2px 2px 5px black, 0 0 1em orange;"); //console.log("%cEither you will have problems with the site", "color: red; font-style: italic; font-size:25px; text-shadow: 2px 2px 5px black, 0 0 1em orange;"); } $(window).load(function () { consolerize(); setTimeout(load_func,2000); }); $(window).unload(function(){ consolerize(); }); //for load function loading_func(){ consolerize(); $('#preload').css({ 'display':'block' }); $('#main').css({ 'display':'none' }); $('#dot').css({ 'display':'none' }); }; //for suc[?] load function load_func(){ $('#preload').css({ 'display':'none' }); $('#main').css({ 'display':'block' }); $('#dot').css({ 'display':'block' }); $(".qblock").load("tmp/one/loadphp.php"); click = false; scrolling(0); $('section').children().css('margin-left', '-200vw').css('opacity', '0'); displayNav(); consolerize(); var $i = 0; var $max = $('section').length - 1; $('body').bind('mousewheel DOMMouseScroll', function(e) { if(e.originalEvent.detail > 0 || e.originalEvent.deltaY == 100) { if ($i < $max) { $i++; scrolling($i); } } else { if ($i > 0) { $i--; scrolling($i); } } }); fillSection($i); $('body').swipe({ swipeStatus:function(event, phase, direction, distance, duration, fingerCount) { if(phase == 'move') { speed = '0ms'; if(direction == 'left') { //console.log('1'); } else if(direction == 'right') { //console.log('2'); } else if(direction == 'up') { //console.log('3'); } else if(direction == 'down') { //console.log('4-end/'); } } else if (phase == 'end') { //console.log('end'); } }, swipeUp:function(event, direction, distance, duration, fingerCount) { if($i > 0) { scrolling($i-=1); }else { scrolling($i+1); } }, swipeDown:function(event, direction, distance, duration, fingerCount) { if($i < $max) { scrolling($i+=1); }else { scrolling($i-1); } }, threshold: 30, triggerOnTouchEnd: false, allowPageScroll: "vertical", excludedElements: "button, input, select, textarea, .noSwipe" }); $.ajax({ type: "POST", url: "up/createviews.php", data: {'sess':'fekoztrue'}, success: function(data) { console.log(data); } }); var w=$(window).width(); var h=$(window).height(); if((h > 600 & h < 670) & w > 920) { $('.qblock').animate({ 'zoom': '94%', }, 400); } if(w < 800 & h < 450){ $('body,html').animate({ 'zoom': '70%', }, 400); var q; q = w/80*100; $('section').css({ 'position':'absolute', 'width':q, 'height':'auto' }); $('#particles-js').css('display','none'); $('.align_center').css('display','none'); console.log('zoom:70'); } var msg = new Messanger(); }; function Messanger() { this.last = 0; this.timeout = 360; this.comet = 0; var self = this; this.putMessage = function(poset,date,regus) { self.last = 1; if(cpos == poset && cdate == date && creg == regus) console.log("%cREC:there is no new data", "color: red; font-style: italic; font-size:13px; text-shadow: 1px 1px 2px black, 0 0 1em white;"); else { cpos = poset; cdate = date; creg = regus; $('.checkonday').hide(220); $('.checkallusers').hide(220); /*********/ $('.checkonday').html(date+':'+poset); $('.checkallusers').html(regus); /*********/ $('.checkonday').show(450); $('.checkallusers').show(450); } } this.parseData = function(message) { var items = message.split(';'); if (items.length<1) return false; for (var i=0;i<items.length;i++) { eval(items[i]); } setTimeout(self.connection,alltime); } this.connection = function() { self.comet = $.ajax({ type: "GET", url: "tmp/one/onlineload.php", data: {'id':self.last}, dataType: "text", timeout: self.timeout*alltime, success: self.parseData, error: function(){ setTimeout(self.connection,alltime); console.log('error:'); } }); } this.init = function() { //connect self.connection(); } this.init(); } //for scroll , this load(load suc) function fillSection($i) { if($i == 1) { $('.align_center_to_right').animate({ 'margin-top':'65vh', 'right':'-90%' },700); } else if($i == 0) { $('.align_center_to_right').animate({ 'margin':'0', 'right':'-50%' },700); } $('section').eq($i).children().animate({ marginLeft: 0, opacity: 1 }, 300, function() { $('section').not($('section').eq($i)).children().css('margin-left', '-200vw').css('opacity', '0'); }); $('.nav').animate({ right: "5vw" }, 300); updateNav($i); }; function displayNav() { $('body').prepend('<ul class="nav"></ul>'); $length = $('section').length; $i2 = 0; for ($i2; $i2 < $length; $i2++) { $('.nav').prepend('<li></li>'); } foundreq(); }; function updateNav($i) { $('.nav li').not($('.nav li').eq($i)).css('background', 'transparent'); $('.nav li').eq($i).css('background', 'white'); }; function foundreq() { $(".nav li").click(function() { var click = $(this); var q = click.index("li"); scrolling(q); }); $("#goFeedback").click(function() { var Sql_qury = $(".ffeedback").serialize(); $.ajax({ type: "POST", url: "up/feedback.php", data: Sql_qury, success: function(data) { $(".feedback_info").html(data); }, error: function(xhr, str){ $(".feedback_info").html(xhr.responseCode); } }); }); }; function scrolling(Fparam){ $('body,html').animate({ scrollTop: $('section').eq(Fparam).offset().top }, 900, function() { fillSection(Fparam); }); }; //other function formright(){ $dot = $('#dot'); renderer = new THREE.WebGLRenderer({ antialias: true }); camera = new THREE.PerspectiveCamera(75, 1, 0.1, 10000); scene = new THREE.Scene(); scene.add(camera); renderer.setSize(size[1], size[2]); $dot.append(renderer.domElement); camera.position.z = 200; golf = new THREE.MeshPhongMaterial({ color: 0xffffff, shading: THREE.FlatShading, fog: false }); L1 = new THREE.PointLight(0xff0000, 2); L1.position.x = 600; L1.position.y = 1500; L1.position.z = 2000; scene.add(L1); L3 = new THREE.PointLight(0x000000, 0); L3.position.z = 400; scene.add(L3); dot = new THREE.Mesh(new THREE.TetrahedronGeometry(100, 3), golf); scene.add(dot); update = function() { dot.rotation.x += .01; return dot.rotation.y += .02; }; render = function() { requestAnimationFrame(render); renderer.render(scene, camera); return update(); }; render(); $('#dot').click(function() { if(click != true) { qqq = new THREE.PerspectiveCamera(100, 180, 30, 100000000000000); requestAnimationFrame(render); renderer.render(scene, qqq); update(); click += 1; $(".framevideoclick").css({ 'margin-left':'-110px', 'display':'block'}); $(".framevideoclick").animate({ 'margin':'0', 'opacity':'0.7' },700); } else { return false; } }); $('#click3').click(function() { scrolling(1); }); $('#click4').click(function() { scrolling(2); }); }; function formleft(){ particlesJS("particles-js", { "particles": { "number": { "value": 26, "density": { "enable": true, "value_area": 700 } }, "color": { "value": ["#aa73ff", "#f8c210", "#83d238", "#33b1f8"] }, "shape": { "type": "circle", "stroke": { "width": 0, "color": "#000000" }, "polygon": { "nb_sides": 15 }, "image": { "src": "img/github.svg", "width": 100, "height": 100 } }, "opacity": { "value": 0.5, "random": false, "anim": { "enable": false, "speed": 1.5, "opacity_min": 0.15, "sync": false } }, "size": { "value": 2.78, "random": true, "anim": { "enable": true, "speed": 2, "size_min": 0.6, "sync": true } }, "line_linked": { "enable": true, "distance": 110, "color": "#33b1f8", "opacity": 0.41, "width": 1 }, "move": { "enable": true, "speed": 1.6, "direction": "none", "random": false, "straight": false, "out_mode": "out", "bounce": false, "attract": { "enable": false, "rotateX": 600, "rotateY": 1200 } } }, "interactivity": { "detect_on": "canvas", "events": { "onhover": { "enable": false, "mode": "repulse" }, "onclick": { "enable": false, "mode": "push" }, "resize": true }, "modes": { "grab": { "distance": 400, "line_linked": { "opacity": 1 } }, "bubble": { "distance": 400, "size": 40, "duration": 2, "opacity": 8, "speed": 3 }, "repulse": { "distance": 200, "duration": 0.4 }, "push": { "particles_nb": 4 }, "remove": { "particles_nb": 2 } } }, "retina_detect": true }); }; });
import state from './state.js'; import ListrError from './listr-error.js'; class TaskWrapper { constructor(task, errors) { this._task = task; this._errors = errors; } get title() { return this._task.title; } set title(title) { this._task.title = title; this._task.next({ type: 'TITLE', data: title, }); } get output() { return this._task.output; } set output(data) { this._task.output = data; this._task.next({ type: 'DATA', data, }); } report(error) { if (error instanceof ListrError) { for (const error_ of error.errors) { this._errors.push(error_); } } else { this._errors.push(error); } } skip(message) { if (message && typeof message !== 'string') { throw new TypeError(`Expected \`message\` to be of type \`string\`, got \`${typeof message}\``); } if (message) { this._task.output = message; } this._task.state = state.SKIPPED; } run(ctx) { return this._task.run(ctx, this); } } export default TaskWrapper;
var ldap = require('ldapjs'); var LdapLookup = require('./LdapLookup'); ldap.Attribute.settings.guid_format = ldap.GUID_FORMAT_D; var LdapValidator = module.exports = function(options){ this._options = options; this._lookup = new LdapLookup(options); }; LdapValidator.prototype.validate = function (username, password, callback) { this._lookup.search(username, function (err, up) { if(err) return callback(err); if(!up) return callback(null, null); var client = ldap.createClient({ url: this._options.url }); client.bind(up.dn, password, function(err) { if(err) return callback(null, false); callback(null, up); }.bind(this)); }.bind(this)); };
angular.module('smiley', []) .directive('smiley', function () { return { restrict: 'AE', replace: false, template: 'Smile! {{color}} {{size}}', // 'templates/smiley.html', controller: function ($scope, $element, $attrs) { $scope.color = $attrs.color || '#f6eb13'; $scope.size = $attrs.size || '50'; }, scope: {} }; });
angular.module("leaflet-directive") .factory('leafletLayerHelpers', function ($rootScope, $log, leafletHelpers, leafletIterators) { var Helpers = leafletHelpers; var isString = leafletHelpers.isString; var isObject = leafletHelpers.isObject; var isArray = leafletHelpers.isArray; var isDefined = leafletHelpers.isDefined; var $it = leafletIterators; var utfGridCreateLayer = function(params) { if (!Helpers.UTFGridPlugin.isLoaded()) { $log.error('[AngularJS - Leaflet] The UTFGrid plugin is not loaded.'); return; } var utfgrid = new L.UtfGrid(params.url, params.pluginOptions); utfgrid.on('mouseover', function(e) { $rootScope.$broadcast('leafletDirectiveMap.utfgridMouseover', e); }); utfgrid.on('mouseout', function(e) { $rootScope.$broadcast('leafletDirectiveMap.utfgridMouseout', e); }); utfgrid.on('click', function(e) { $rootScope.$broadcast('leafletDirectiveMap.utfgridClick', e); }); utfgrid.on('mousemove', function(e) { $rootScope.$broadcast('leafletDirectiveMap.utfgridMousemove', e); }); return utfgrid; }; var layerTypes = { xyz: { mustHaveUrl: true, createLayer: function(params) { return L.tileLayer(params.url, params.options); } }, mapbox: { mustHaveKey: true, createLayer: function(params) { var version = 3; if(isDefined(params.options.version) && params.options.version === 4) { version = params.options.version; } var url = version === 3? '//{s}.tiles.mapbox.com/v3/' + params.key + '/{z}/{x}/{y}.png': '//api.tiles.mapbox.com/v4/' + params.key + '/{z}/{x}/{y}.png?access_token=' + params.apiKey; return L.tileLayer(url, params.options); } }, geoJSON: { mustHaveUrl: true, createLayer: function(params) { if (!Helpers.GeoJSONPlugin.isLoaded()) { return; } return new L.TileLayer.GeoJSON(params.url, params.pluginOptions, params.options); } }, utfGrid: { mustHaveUrl: true, createLayer: utfGridCreateLayer }, cartodbTiles: { mustHaveKey: true, createLayer: function(params) { var url = '//' + params.user + '.cartodb.com/api/v1/map/' + params.key + '/{z}/{x}/{y}.png'; return L.tileLayer(url, params.options); } }, cartodbUTFGrid: { mustHaveKey: true, mustHaveLayer : true, createLayer: function(params) { params.url = '//' + params.user + '.cartodb.com/api/v1/map/' + params.key + '/' + params.layer + '/{z}/{x}/{y}.grid.json'; return utfGridCreateLayer(params); } }, cartodbInteractive: { mustHaveKey: true, mustHaveLayer : true, createLayer: function(params) { var tilesURL = '//' + params.user + '.cartodb.com/api/v1/map/' + params.key + '/{z}/{x}/{y}.png'; var tileLayer = L.tileLayer(tilesURL, params.options); params.url = '//' + params.user + '.cartodb.com/api/v1/map/' + params.key + '/' + params.layer + '/{z}/{x}/{y}.grid.json'; var utfLayer = utfGridCreateLayer(params); return L.layerGroup([tileLayer, utfLayer]); } }, wms: { mustHaveUrl: true, createLayer: function(params) { return L.tileLayer.wms(params.url, params.options); } }, wmts: { mustHaveUrl: true, createLayer: function(params) { return L.tileLayer.wmts(params.url, params.options); } }, wfs: { mustHaveUrl: true, mustHaveLayer : true, createLayer: function(params) { if (!Helpers.WFSLayerPlugin.isLoaded()) { return; } var options = angular.copy(params.options); if(options.crs && 'string' === typeof options.crs) { /*jshint -W061 */ options.crs = eval(options.crs); } return new L.GeoJSON.WFS(params.url, params.layer, options); } }, group: { mustHaveUrl: false, createLayer: function (params) { var lyrs = []; $it.each(params.options.layers, function(l){ lyrs.push(createLayer(l)); }); return L.layerGroup(lyrs); } }, featureGroup: { mustHaveUrl: false, createLayer: function () { return L.featureGroup(); } }, google: { mustHaveUrl: false, createLayer: function(params) { var type = params.type || 'SATELLITE'; if (!Helpers.GoogleLayerPlugin.isLoaded()) { return; } return new L.Google(type, params.options); } }, china:{ mustHaveUrl:false, createLayer:function(params){ var type = params.type || ''; if(!Helpers.ChinaLayerPlugin.isLoaded()){ return; } return L.tileLayer.chinaProvider(type, params.options); } }, agsBase: { mustHaveLayer : true, createLayer: function (params) { if (!Helpers.AGSBaseLayerPlugin.isLoaded()) { return; } return L.esri.basemapLayer(params.layer, params.options); } }, ags: { mustHaveUrl: true, createLayer: function(params) { if (!Helpers.AGSLayerPlugin.isLoaded()) { return; } var options = angular.copy(params.options); angular.extend(options, { url: params.url }); var layer = new lvector.AGS(options); layer.onAdd = function(map) { this.setMap(map); }; layer.onRemove = function() { this.setMap(null); }; return layer; } }, dynamic: { mustHaveUrl: true, createLayer: function(params) { if (!Helpers.DynamicMapLayerPlugin.isLoaded()) { return; } return L.esri.dynamicMapLayer(params.url, params.options); } }, markercluster: { mustHaveUrl: false, createLayer: function(params) { if (!Helpers.MarkerClusterPlugin.isLoaded()) { $log.error('[AngularJS - Leaflet] The markercluster plugin is not loaded.'); return; } return new L.MarkerClusterGroup(params.options); } }, bing: { mustHaveUrl: false, createLayer: function(params) { if (!Helpers.BingLayerPlugin.isLoaded()) { return; } return new L.BingLayer(params.key, params.options); } }, webGLHeatmap: { mustHaveUrl: false, mustHaveData: true, createLayer: function(params) { if (!Helpers.WebGLHeatMapLayerPlugin.isLoaded()) { return; } var layer = new L.TileLayer.WebGLHeatMap(params.options); if (isDefined(params.data)) { layer.setData(params.data); } return layer; } }, heat: { mustHaveUrl: false, mustHaveData: true, createLayer: function(params) { if (!Helpers.HeatLayerPlugin.isLoaded()) { return; } var layer = new L.heatLayer(); if (isArray(params.data)) { layer.setLatLngs(params.data); } if (isObject(params.options)) { layer.setOptions(params.options); } return layer; } }, yandex: { mustHaveUrl: false, createLayer: function(params) { var type = params.type || 'map'; if (!Helpers.YandexLayerPlugin.isLoaded()) { return; } return new L.Yandex(type, params.options); } }, imageOverlay: { mustHaveUrl: true, mustHaveBounds : true, createLayer: function(params) { return L.imageOverlay(params.url, params.bounds, params.options); } }, // This "custom" type is used to accept every layer that user want to define himself. // We can wrap these custom layers like heatmap or yandex, but it means a lot of work/code to wrap the world, // so we let user to define their own layer outside the directive, // and pass it on "createLayer" result for next processes custom: { createLayer: function (params) { if (params.layer instanceof L.Class) { return angular.copy(params.layer); } else { $log.error('[AngularJS - Leaflet] A custom layer must be a leaflet Class'); } } }, cartodb: { mustHaveUrl: true, createLayer: function(params) { return cartodb.createLayer(params.map, params.url); } } }; function isValidLayerType(layerDefinition) { // Check if the baselayer has a valid type if (!isString(layerDefinition.type)) { $log.error('[AngularJS - Leaflet] A layer must have a valid type defined.'); return false; } if (Object.keys(layerTypes).indexOf(layerDefinition.type) === -1) { $log.error('[AngularJS - Leaflet] A layer must have a valid type: ' + Object.keys(layerTypes)); return false; } // Check if the layer must have an URL if (layerTypes[layerDefinition.type].mustHaveUrl && !isString(layerDefinition.url)) { $log.error('[AngularJS - Leaflet] A base layer must have an url'); return false; } if (layerTypes[layerDefinition.type].mustHaveData && !isDefined(layerDefinition.data)) { $log.error('[AngularJS - Leaflet] The base layer must have a "data" array attribute'); return false; } if(layerTypes[layerDefinition.type].mustHaveLayer && !isDefined(layerDefinition.layer)) { $log.error('[AngularJS - Leaflet] The type of layer ' + layerDefinition.type + ' must have an layer defined'); return false; } if (layerTypes[layerDefinition.type].mustHaveBounds && !isDefined(layerDefinition.bounds)) { $log.error('[AngularJS - Leaflet] The type of layer ' + layerDefinition.type + ' must have bounds defined'); return false ; } if (layerTypes[layerDefinition.type].mustHaveKey && !isDefined(layerDefinition.key)) { $log.error('[AngularJS - Leaflet] The type of layer ' + layerDefinition.type + ' must have key defined'); return false ; } return true; } function createLayer(layerDefinition) { if (!isValidLayerType(layerDefinition)) { return; } if (!isString(layerDefinition.name)) { $log.error('[AngularJS - Leaflet] A base layer must have a name'); return; } if (!isObject(layerDefinition.layerParams)) { layerDefinition.layerParams = {}; } if (!isObject(layerDefinition.layerOptions)) { layerDefinition.layerOptions = {}; } // Mix the layer specific parameters with the general Leaflet options. Although this is an overhead // the definition of a base layers is more 'clean' if the two types of parameters are differentiated for (var attrname in layerDefinition.layerParams) { layerDefinition.layerOptions[attrname] = layerDefinition.layerParams[attrname]; } var params = { url: layerDefinition.url, data: layerDefinition.data, options: layerDefinition.layerOptions, layer: layerDefinition.layer, type: layerDefinition.layerType, bounds: layerDefinition.bounds, key: layerDefinition.key, apiKey: layerDefinition.apiKey, pluginOptions: layerDefinition.pluginOptions, user: layerDefinition.user }; //TODO Add $watch to the layer properties return layerTypes[layerDefinition.type].createLayer(params); } return { createLayer: createLayer }; });
!function(){"use strict";(async()=>{const e=document.getElementById("jsAgree"),t=document.getElementsByClassName("jsExecBtn"),n=t=>{if(!e.checked)return t.preventDefault(),void alert("注意事項に同意してね")};for(const e of t)e.onclick=n})()}();
// Authentication Related Background Tasks /** Processes the authentication response from the OAuth endpoint, dispatching a message to our own server and storing information about the current user. @method processResponse @param {String} resp HTTP response text @param {XMLHttpRequest} xhr server request headers @see controllers/user.js Example Responses: Google: user: { id: '105503159085383028265', name: 'Zephyr Pellerin', given_name: 'Zephyr', family_name: 'Pellerin', link: 'https://plus.google.com/105503159085383028265', picture: 'https://lh6.googleusercontent.com/AK18/.../photo.jpg', gender: 'male', birthday: '1992-01-19', locale: 'en' } **/ function processResponse(resp, xhr) { var user = JSON.parse(resp); // commit some information about the user to localStorage. localStorage.currentUser = resp; // Begin authentication console.log("Sucessfully parsed response from OAuth endpoint"); console.log(user); $.ajax({ type: 'POST', url: Skiplist.remoteURL + '/users', data: user }).done(function (data) { // We could do a lot here. // If the user is new, pop a dialog asking for name, etc. // Otherwise just let the user know he's logged in. }); } /** Serves as a callback to @method initOAuthFlow **/ function onAuthorized() { var url = 'https://www.googleapis.com/oauth2/v2/userinfo'; window.provider.sendSignedRequest(url, processResponse); } /** @method initOAuthFlow @param {String} provider signifies which provider will serve as our OAuth endpoint. **/ function initOAuthFlow(provider) { if(typeof provider != 'string') { throw(new TypeError('Provider should be string')); } var providerId = provider.toLowerCase(); switch (providerId) { case 'google': window.provider = ChromeExOAuth.initBackgroundPage({ 'request_url' : 'https://www.google.com/accounts/OAuthGetRequestToken', 'authorize_url' : 'https://www.google.com/accounts/OAuthAuthorizeToken', 'access_url' : 'https://www.google.com/accounts/OAuthGetAccessToken', 'consumer_key': 'anonymous', 'consumer_secret': 'anonymous', 'scope' : 'https://www.googleapis.com/auth/userinfo.profile', 'app_name' : 'Skiplist' }); window.provider.authorize(onAuthorized); break; case 'github': // stub break; default: throw(new Error('Unrecognized provider')); } }
var express = require('express'); var path = require('path'); var favicon = require('serve-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var routes = require('./routes/index'); var app = express(); var dbConfig = require('./db.js'); var mongoose = require('mongoose'); mongoose.connect(dbConfig.url); // view engine setup app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); // uncomment after placing your favicon in /public //app.use(favicon(path.join(__dirname, 'public', 'favicon.ico'))); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use(cookieParser()); app.use(express.static(path.join(__dirname, 'public'))); // Configuring Passport var passport = require('passport'); var expressSession = require('express-session'); app.use(expressSession({secret: 'mySecretKey'})); app.use(passport.initialize()); app.use(passport.session()); app.use('/', routes); // catch 404 and forward to error handler app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); // error handlers // development error handler // will print stacktrace if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } // production error handler // no stacktraces leaked to user app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: {} }); }); module.exports = app;
/** * Copyright (c) 2016-present JetBridge, LLC. * All rights reserved. * * This source code is licensed under the MIT-style license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; import React, { Component } from 'react'; import { AppRegistry, } from 'react-native'; import RootRouter from './src/components/RootRouter'; class reactobd2 extends Component { render() { return ( <RootRouter /> ); } } AppRegistry.registerComponent('obd2example', () => reactobd2);
/* ************************************ */ /* Define Helper Functions */ /* ************************************ */ function getDisplayElement() { $('<div class = display_stage_background></div>').appendTo('body') return $('<div class = display_stage></div>').appendTo('body') } function addID() { jsPsych.data.addDataToLastTrial({exp_id: 'go_nogo_with_n_back'}) } function evalAttentionChecks() { var check_percent = 1 if (run_attention_checks) { var attention_check_trials = jsPsych.data.getTrialsOfType('attention-check') var checks_passed = 0 for (var i = 0; i < attention_check_trials.length; i++) { if (attention_check_trials[i].correct === true) { checks_passed += 1 } } check_percent = checks_passed / attention_check_trials.length } jsPsych.data.addDataToLastTrial({"att_check_percent": check_percent}) return check_percent } function assessPerformance() { var experiment_data = jsPsych.data.getTrialsOfType('poldrack-single-stim') var missed_count = 0 var trial_count = 0 var rt_array = [] var rt = 0 var correct = 0 //record choices participants made var choice_counts = {} choice_counts[-1] = 0 choice_counts[77] = 0 choice_counts[90] = 0 for (var k = 0; k < possible_responses.length; k++) { choice_counts[possible_responses[k][1]] = 0 } for (var i = 0; i < experiment_data.length; i++) { if (experiment_data[i].trial_id == 'test_trial') { trial_count += 1 key = experiment_data[i].key_press choice_counts[key] += 1 if (experiment_data[i].go_nogo_condition == 'go'){ if (experiment_data[i].key_press == experiment_data[i].correct_response){ correct += 1 } if (experiment_data[i].key_press == -1){ missed_count += 1 } if (experiment_data[i].key_press != -1){ rt = experiment_data[i].rt rt_array.push(rt) } } else if (experiment_data[i].go_nogo_condition == 'nogo'){ if (experiment_data[i].key_press == -1){ correct += 1 } else if (experiment_data[i].key_press != -1){ rt = experiment_data[i].rt rt_array.push(rt) } } } } //calculate average rt var avg_rt = -1 if (rt_array.length !== 0) { avg_rt = math.median(rt_array) } //calculate whether response distribution is okay var responses_ok = true Object.keys(choice_counts).forEach(function(key, index) { if (choice_counts[key] > trial_count * 0.85) { responses_ok = false } }) var missed_percent = missed_count/trial_count var accuracy = correct / trial_count credit_var = (missed_percent < 0.25 && avg_rt > 200 && responses_ok && accuracy > 0.60) jsPsych.data.addDataToLastTrial({final_credit_var: credit_var, final_missed_percent: missed_percent, final_avg_rt: avg_rt, final_responses_ok: responses_ok, final_accuracy: accuracy}) } var getResponse = function() { return correct_response } var getInstructFeedback = function() { return '<div class = centerbox><p class = center-block-text>' + feedback_instruct_text + '</p></div>' } var getCategorizeIncorrectText = function(){ if (go_nogo_condition == 'go'){ return '<div class = fb_box><div class = center-text><font size = 20>Incorrect</font></div></div>'+ prompt_text } else { return '<div class = fb_box><div class = center-text><font size = 20>Letter is '+go_no_go_styles[1]+'</font></div></div>'+ prompt_text } } var getTimeoutText = function(){ if (go_nogo_condition == "go"){ return '<div class = fb_box><div class = center-text><font size = 20>Respond Faster!</font></div></div>'+ prompt_text } else { return '<div class = fb_box><div class = center-text><font size = 20>Correct!</font></div></div>'+ prompt_text } } var getCorrectText = function(){ if (go_nogo_condition == "go"){ return '<div class = fb_box><div class = center-text><font size = 20>Correct!</font></div></div>'+ prompt_text } else { return '<div class = fb_box><div class = center-text><font size = 20>Letter is '+go_no_go_styles[1]+'</font></div></div>'+ prompt_text } } var getFeedback = function() { return '<div class = bigbox><div class = picture_box><p class = block-text><font color="white">' + feedback_text + '</font></p></div></div>' } var randomDraw = function(lst) { var index = Math.floor(Math.random() * (lst.length)) return lst[index] }; var createTrialTypes = function(numTrialsPerBlock, delay){ first_stims = [] for (var i = 0; i < 3; i++){ //so that if delay for the block is 2, the first two stim will have no match (i.e. not yet 2 stim preceding them to be matched.) if (i < delay){ n_back_condition = 'N/A' } else { n_back_condition = n_back_conditions[Math.floor(Math.random() * 5)] } go_nogo_condition = jsPsych.randomization.repeat(['go','go','go','go','go','go','nogo'],1).pop() //To change go:nogo ratio, modify this, "var go_nogo_conditions =", and where there're similar variables. probe = randomDraw(letters) correct_response = possible_responses[1][1] letter_case = randomDraw(['uppercase','lowercase']) if (n_back_condition == 'match'){ correct_response = possible_responses[0][1] probe = first_stims[i - delay].probe } else if (n_back_condition == "mismatch"){ probe = randomDraw('BDGTV'.split("").filter(function(y) {return $.inArray(y, [first_stims[i - delay].probe]) == -1})) correct_response = possible_responses[1][1] } if (go_nogo_condition == 'go'){ probe_color = go_no_go_styles[0] } else { probe_color = go_no_go_styles[1] correct_response = -1 } first_stim = { n_back_condition: n_back_condition, go_nogo_condition: go_nogo_condition, probe: probe, correct_response: correct_response, delay: delay, probe_color: probe_color, letter_case: letter_case } first_stims.push(first_stim) } stims = [] for(var numIterations = 0; numIterations < numTrialsPerBlock/(go_nogo_conditions.length*n_back_conditions.length); numIterations++){ //35 = 7 go_nogo_conditions * 5 n_back_conditions for (var numNBackConds = 0; numNBackConds < n_back_conditions.length; numNBackConds++){ for (var numShapeConds = 0; numShapeConds < go_nogo_conditions.length; numShapeConds++){ go_nogo_condition = go_nogo_conditions[numShapeConds] n_back_condition = n_back_conditions[numNBackConds] stim = { go_nogo_condition: go_nogo_condition, n_back_condition: n_back_condition } stims.push(stim) } } } stims = jsPsych.randomization.repeat(stims,1) stims = first_stims.concat(stims) stim_len = stims.length new_stims = [] for (i = 0; i < stim_len; i++){ if (i < 3){ stim = stims.shift() n_back_condition = stim.n_back_condition go_nogo_condition = stim.go_nogo_condition probe = stim.probe probe_color = stim.probe_color correct_response = stim.correct_response delay = stim.delay letter_case = stim.letter_case } else { stim = stims.shift() n_back_condition = stim.n_back_condition go_nogo_condition = stim.go_nogo_condition letter_case = randomDraw(['uppercase','lowercase']) if (n_back_condition == "match"){ probe = new_stims[i - delay].probe correct_response = possible_responses[0][1] } else if (n_back_condition == "mismatch"){ probe = randomDraw('BDGTV'.split("").filter(function(y) {return $.inArray(y, [new_stims[i - delay].probe]) == -1})) correct_response = possible_responses[1][1] } if (go_nogo_condition == 'go'){ probe_color = go_no_go_styles[0] } else { probe_color = go_no_go_styles[1] correct_response = -1 } } stim = { n_back_condition: n_back_condition, go_nogo_condition: go_nogo_condition, probe: probe, probe_color: probe_color, correct_response: correct_response, delay: delay, letter_case: letter_case } new_stims.push(stim) } return new_stims } var getControlStim = function(){ stim = control_stims.shift() n_back_condition = stim.n_back_condition go_nogo_condition = stim.go_nogo_condition probe = stim.probe probe_color = stim.probe_color correct_response = stim.correct_response delay = stim.delay letter_case = stim.letter_case return task_boards[0]+ preFileType + probe_color + '_' + letter_case + '_' + probe + fileTypePNG + task_boards[1] } var getStim = function(){ stim = stims.shift() n_back_condition = stim.n_back_condition go_nogo_condition = stim.go_nogo_condition probe = stim.probe probe_color = stim.probe_color correct_response = stim.correct_response delay = stim.delay letter_case = stim.letter_case return task_boards[0]+ preFileType + probe_color + '_' + letter_case + '_' + probe.toUpperCase() + fileTypePNG + task_boards[1] } var getResponse = function(){ return correct_response } var appendData = function(){ curr_trial = jsPsych.progress().current_trial_global trial_id = jsPsych.data.getDataByTrialIndex(curr_trial).trial_id current_trial+=1 if (trial_id == 'practice_trial'){ current_block = practiceCount } else if (trial_id == 'test_trial'){ current_block = testCount } jsPsych.data.addDataToLastTrial({ n_back_condition: n_back_condition, go_nogo_condition: go_nogo_condition, go_no_go_style: go_no_go_styles, probe: probe, correct_response: correct_response, delay: delay, current_trial: current_trial, current_block: current_block }) if (jsPsych.data.getDataByTrialIndex(curr_trial).key_press == correct_response){ jsPsych.data.addDataToLastTrial({ correct_trial: 1, }) } else if (jsPsych.data.getDataByTrialIndex(curr_trial).key_press != correct_response){ jsPsych.data.addDataToLastTrial({ correct_trial: 0, }) } } /* ************************************ */ /* Define Experimental Variables */ /* ************************************ */ // generic task variables var run_attention_checks = true var sumInstructTime = 0 //ms var instructTimeThresh = 0 ///in seconds var credit_var = 0 var practice_len = 35 // 25 must be divisible by 25 // 7/31: new ratio 6go:1nogo var exp_len = 420 //300 must be divisible by 25 var numTrialsPerBlock = 70 // 50 must be divisible by 25 and we need to have a multiple of 3 blocks (3,6,9) in order to have equal delays across blocks var numTestBlocks = exp_len / numTrialsPerBlock var practice_thresh = 3 // 3 blocks of 25 trials var accuracy_thresh = 0.75 var rt_thresh = 1000 var missed_thresh = 0.10 var delays = jsPsych.randomization.repeat([1, 2, 3], numTestBlocks / 3) var delay = 1 // this is the delay of the practice block. var pathSource = "/static/experiments/go_nogo_with_n_back/images/" var fileTypePNG = ".png'></img>" var preFileType = "<img class = center src='/static/experiments/go_nogo_with_n_back/images/" var n_back_conditions = jsPsych.randomization.repeat(['match','mismatch','mismatch','mismatch','mismatch'],1) var go_nogo_conditions = jsPsych.randomization.repeat(['go','go','go','go','go','go','nogo'],1) var possible_responses = [['M Key', 77],['Z Key', 90]] var go_no_go_styles = ['solid','outlined'] //has dashed as well var letters = 'BDGTV'.split("") var prompt_text_list = '<ul style="text-align:left;">'+ '<li>Respond if the current letter matches delayed letter.</li>' + '<li>If they match, press the '+possible_responses[0][0]+'</li>' + '<li>If they mismatch, press the '+possible_responses[1][0]+'</li>' + '<li>Do not respond if probe is '+go_no_go_styles[1]+', only respond if '+go_no_go_styles[0]+'!</li>' + '</ul>' var prompt_text = '<div class = prompt_box>'+ '<p class = center-block-text style = "font-size:16px; line-height:80%%;">Match the current letter to the letter that appeared 1 trial ago</p>' + '<p class = center-block-text style = "font-size:16px; line-height:80%%;">If they match, press the '+possible_responses[0][0]+'</p>' + '<p class = center-block-text style = "font-size:16px; line-height:80%%;">If they mismatch, press the '+possible_responses[1][0]+'</p>' + '<p class = center-block-text style = "font-size:16px; line-height:80%%;">Do not respond if probe is '+go_no_go_styles[1]+', only respond if '+go_no_go_styles[0]+'!</p>' + '</div>' var current_trial = 0 var current_block = 0 //PRE LOAD IMAGES HERE var lettersPreload = ['B','D','G','T','V'] var casePreload = ['uppercase','lowercase'] var pathSource = "/static/experiments/go_nogo_with_n_back/images/" var images = [] for(i=0;i<lettersPreload.length;i++){ for(x=0;x<casePreload.length;x++){ for(y=0;y<go_no_go_styles.length;y++){ images.push(pathSource + go_no_go_styles[y] + '_' + casePreload[x] + '_' + lettersPreload[i] + '.png') } } } jsPsych.pluginAPI.preloadImages(images); /* ************************************ */ /* Define Game Boards */ /* ************************************ */ var task_boards = ['<div class = bigbox><div class = centerbox><div class = gng_number><div class = cue-text>','</div></div></div></div>'] var stims = createTrialTypes(practice_len, delay) /* ************************************ */ /* Set up jsPsych blocks */ /* ************************************ */ // Set up attention check node var attention_check_block = { type: 'attention-check', data: { trial_id: "attention_check" }, timing_response: 180000, response_ends_trial: true, timing_post_trial: 200 } var attention_node = { timeline: [attention_check_block], conditional_function: function() { return run_attention_checks } } var end_block = { type: 'poldrack-text', data: { trial_id: "end", }, timing_response: 180000, text: '<div class = centerbox><p class = center-block-text>Thanks for completing this task!</p><p class = center-block-text>Press <i>enter</i> to continue.</p></div>', cont_key: [13], timing_post_trial: 0, on_finish: function(){ assessPerformance() evalAttentionChecks() } }; //Set up post task questionnaire var post_task_block = { type: 'survey-text', data: { exp_id: "go_nogo_with_n_back", trial_id: "post_task_questions" }, questions: ['<p class = center-block-text style = "font-size: 20px">Please summarize what you were asked to do in this task.</p>', '<p class = center-block-text style = "font-size: 20px">Do you have any comments about this task?</p>'], rows: [15, 15], columns: [60,60], timing_response: 360000 }; var feedback_instruct_text = 'Welcome to the experiment. This experiment will take around 15 minutes. Press <i>enter</i> to begin.' var feedback_instruct_block = { type: 'poldrack-text', data: { trial_id: "instruction" }, cont_key: [13], text: getInstructFeedback, timing_post_trial: 0, timing_response: 180000 }; /// This ensures that the subject does not read through the instructions too quickly. If they do it too quickly, then we will go over the loop again. var instructions_block = { type: 'poldrack-instructions', data: { trial_id: "instruction" }, pages: [ '<div class = centerbox>'+ '<div class = centerbox>'+ '<p class = block-text>In this task, you will see a letter on every trial.</p>'+ '<p class = block-text>You will be asked to match the current letter, to the letter that appeared either 1, 2, 3 trials ago depending on the delay given to you for that block.</p>'+ '<p class = block-text>Press the '+possible_responses[0][0]+' if the current and delayed letters match, and the '+possible_responses[1][0]+' if they mismatch.</p>'+ '<p class = block-text>Your delay (the number of trials ago to which you must match the current letter) will change from block to block. You will be given the delay at the start of every block of trials.</p>'+ '<p class = block-text>Capitalization does not matter, so "T" matches with "t".</p><br> '+ '<p class = block-text>For practice, match the current letter to the letter that appeared 1 trial ago.</p> '+ '</div>', "<div class = centerbox>"+ "<p class = block-text>On some trials, the letters will be "+go_no_go_styles[0]+". Other times, the letters will be "+go_no_go_styles[1]+".</p>"+ "<p class = block-text>If the letters are "+go_no_go_styles[1]+", please make no response on that trial. You should still remember the letter, however.</p>"+ "<p class = block-text>A(n) "+go_no_go_styles[1]+" letter will be grey outlined in black.</p>"+ "<p class = block-text>A(n) "+go_no_go_styles[0]+" letter will be solid white.</p>"+ '<p class = block-text>To avoid technical issues, please keep the experiment tab (on Chrome or Firefox) <i>active and in full-screen mode</i> for the whole duration of each task.</p>'+ "</div>", /* '<div class = centerbox>'+ '<p class = block-text>For example, if your delay for the block was 2, and the letters you received for the first 4 trials were '+go_no_go_styles[0]+'_V, '+go_no_go_styles[0]+'_B, '+go_no_go_styles[1]+'_v, and '+go_no_go_styles[0]+'_V, you would respond, no match, no match, no response, and no match.</p> '+ '<p class = block-text>The first letter in that sequence, V, DOES NOT have a preceding trial to match with, so press the '+possible_responses[1][0]+' on those trials.</p> '+ '<p class = block-text>The second letter in that sequence, B, ALSO DOES NOT have a trial 2 ago to match with, so press the '+possible_responses[1][0]+' on those trials.</p>'+ '<p class = block-text>The third letter in that sequence, v, DOES match the letter from 2 trials, V, so if the '+go_no_go_styles[0]+' version of the letter came out, you would press '+possible_responses[0][0]+'. But since the '+go_no_go_styles[1]+' version of the letter came out, please refrain from making a response! You must still commit this letter to memory, however.</p>'+ '<p class = block-text>The fourth letter in that sequence, V, DOES NOT match the letter from 2 trials ago, B, so you would respond no match.</p>'+ '<p class = block-text>We will start practice when you finish instructions. <i>Your delay for practice is 1</i>. Please make sure you understand the instructions before moving on. You will be given a reminder of the rules for practice. <i>This will be removed for test!</i></p>'+ '</div>', */ ], allow_keys: false, show_clickable_nav: true, timing_post_trial: 1000 }; /* This function defines stopping criteria */ var instruction_node = { timeline: [feedback_instruct_block, instructions_block], loop_function: function(data) { for (i = 0; i < data.length; i++) { if ((data[i].trial_type == 'poldrack-instructions') && (data[i].rt != -1)) { rt = data[i].rt sumInstructTime = sumInstructTime + rt } } if (sumInstructTime <= instructTimeThresh * 1000) { feedback_instruct_text = 'Read through instructions too quickly. Please take your time and make sure you understand the instructions. Press <i>enter</i> to continue.' return true } else if (sumInstructTime > instructTimeThresh * 1000) { feedback_instruct_text = 'Done with instructions. Press <i>enter</i> to continue.' return false } } } var start_test_block = { type: 'poldrack-text', data: { trial_id: "instruction" }, timing_response: 180000, text: '<div class = centerbox>'+ '<p class = block-text>We will now begin the test portion.</p>'+ '<p class = block-text>You will be asked to match the current letter, to the letter that appeared either 1, 2, 3 trials ago depending on the delay given to you for that block.</p>'+ '<p class = block-text>Press the '+possible_responses[0][0]+' if they match, and the '+possible_responses[1][0]+' if they mismatch.</p>'+ '<p class = block-text>Your delay (the number of trials ago which you must match the current letter to) will change from block to block.</p>'+ '<p class = block-text><i>Please make no response if the '+go_no_go_styles[1]+' version of the letter came out. You must still commit that letter to memory!</i></p>'+ '<p class = block-text>Capitalization does not matter, so "T" matches with "t".</p> '+ '<p class = block-text>You will no longer receive the rule prompt, so remember the instructions before you continue. Press Enter to begin.</p>'+ '</div>', cont_key: [13], timing_post_trial: 1000, on_finish: function(){ feedback_text = "We will now start the test portion. Your delay for this block of trials is "+delay+". Press enter to begin." } }; var feedback_text = 'Welcome to the experiment. This experiment will take around 15 minutes. Press <i>enter</i> to begin.' var feedback_block = { type: 'poldrack-single-stim', data: { trial_id: "practice-no-stop-feedback" }, choices: [13], stimulus: getFeedback, timing_post_trial: 0, is_html: true, timing_response: 180000, response_ends_trial: true, }; /*var start_control_block = { type: 'poldrack-text', data: { trial_id: "instruction" }, timing_response: 180000, text: '<div class = centerbox>'+ '<p class = block-text>For this block of trials, you do not have to match letters. Instead, indicate whether the current letter is a T (or t).</p>'+ '<p class = block-text>Press the '+possible_responses[0][0]+' if the current letter was a T (or t) and the '+possible_responses[1][0]+' if not.</p> '+ '<p class = block-text>If the '+go_no_go_styles[1]+' version of the letter came out, please make no response on that trial.</p>'+ '<p class = block-text>You will no longer receive the rule prompt, so remember the instructions before you continue. Press Enter to begin.</p>'+ '</div>', cont_key: [13], timing_post_trial: 1000, on_finish: function(){ feedback_text = "We will now start this block. Press enter to begin." } };*/ /* ************************************ */ /* Set up timeline blocks */ /* ************************************ */ var practiceTrials = [] practiceTrials.push(feedback_block) practiceTrials.push(instructions_block) for (i = 0; i < practice_len + 3; i++) { // var fixation_block = { // type: 'poldrack-single-stim', // stimulus: '<div class = centerbox><div class = fixation>+</div></div>', // is_html: true, // choices: 'none', // data: { // trial_id: "practice_fixation" // }, // timing_response: 500, //500 // timing_post_trial: 0, // prompt: prompt_text // } var practice_block = { type: 'poldrack-categorize', stimulus: getStim, is_html: true, choices: [possible_responses[0][1],possible_responses[1][1]], key_answer: getResponse, data: { trial_id: "practice_trial" }, correct_text: getCorrectText, incorrect_text: getCategorizeIncorrectText, timeout_message: getTimeoutText, timing_stim: 1000, //1000 timing_response: 2000, //2000 timing_feedback_duration: 500, //500 show_stim_with_feedback: false, timing_post_trial: 0, on_finish: appendData, prompt: prompt_text } // practiceTrials.push(fixation_block) Block removed for, per note by Patrick, // "this is essential an N-back task with the possibility of needing to “no-go” added on 1/7 of trials, // I think we should mimic the timing of the single task N-back task. Therefore, let’s remove the 500ms fixation period // rom all practice and main task trials. Trials will each be 2000ms." practiceTrials.push(practice_block) } var practiceCount = 0 var practiceNode = { timeline: practiceTrials, loop_function: function(data) { practiceCount += 1 current_trial = 0 var sum_rt = 0 var sum_responses = 0 var correct = 0 var total_trials = 0 var total_go_trials = 0 var missed_response = 0 for (var i = 0; i < data.length; i++){ if (data[i].trial_id == "practice_trial"){ total_trials+=1 if (data[i].rt != -1){ sum_rt += data[i].rt sum_responses += 1 } if (data[i].key_press == data[i].correct_response){ correct += 1 } if (data[i].go_nogo_condition == 'go'){ total_go_trials += 1 if (data[i].rt == -1){ missed_response += 1 } } } } var accuracy = correct / total_trials var missed_responses = missed_response / total_go_trials var ave_rt = sum_rt / sum_responses feedback_text = "<br>Please take this time to read your feedback and to take a short break! Press enter to continue" if (practiceCount == practice_thresh){ feedback_text += '</p><p class = block-text>Done with this practice.' delay = delays.pop() stims = createTrialTypes(numTrialsPerBlock, delay) return false } if (accuracy >= accuracy_thresh){ feedback_text += '</p><p class = block-text>Done with this practice. Press Enter to continue.' delay = delays.pop() stims = createTrialTypes(numTrialsPerBlock, delay) return false } else if (accuracy < accuracy_thresh){ feedback_text += '</p><p class = block-text>We are going to try practice again to see if you can achieve higher accuracy. Remember: <br>' + prompt_text_list if (missed_responses > missed_thresh){ feedback_text += '</p><p class = block-text>You have not been responding to some trials. Please respond on every trial that requires a response.' } if (ave_rt > rt_thresh){ feedback_text += '</p><p class = block-text>You have been responding too slowly.' } feedback_text += '</p><p class = block-text>Redoing this practice. Press Enter to continue.' stims = createTrialTypes(practice_len, delay) return true } } } var testTrials = [] testTrials.push(feedback_block) testTrials.push(attention_node) for (i = 0; i < numTrialsPerBlock + 3; i++) { // var fixation_block = { // type: 'poldrack-single-stim', // stimulus: '<div class = centerbox><div class = fixation>+</div></div>', // is_html: true, // choices: 'none', // data: { // trial_id: "practice_fixation" // }, // timing_response: 500, //500 // timing_post_trial: 0 // } var test_block = { type: 'poldrack-single-stim', stimulus: getStim, is_html: true, data: { "trial_id": "test_trial", }, choices: [possible_responses[0][1],possible_responses[1][1]], timing_stim: 1000, //1000 timing_response: 2000, //2000 timing_post_trial: 0, response_ends_trial: false, on_finish: appendData } // testTrials.push(fixation_block) Block removed for the same reason in practiceNode. testTrials.push(test_block) } var testCount = 0 var testNode = { timeline: testTrials, loop_function: function(data) { testCount += 1 current_trial = 0 var sum_rt = 0 var sum_responses = 0 var correct = 0 var total_trials = 0 var total_go_trials = 0 var missed_response = 0 for (var i = 0; i < data.length; i++){ if (data[i].trial_id == "test_trial"){ total_trials+=1 if (data[i].rt != -1){ sum_rt += data[i].rt sum_responses += 1 } if (data[i].key_press == data[i].correct_response){ correct += 1 } if (data[i].go_nogo_condition == 'go'){ total_go_trials += 1 if (data[i].rt == -1){ missed_response += 1 } } } } var accuracy = correct / total_trials var missed_responses = missed_response / total_go_trials var ave_rt = sum_rt / sum_responses feedback_text = "<br>Please take this time to read your feedback and to take a short break! Press enter to continue" feedback_text += "</p><p class = block-text>You have completed: "+testCount+" out of "+numTestBlocks+" blocks of trials." if (accuracy < accuracy_thresh){ feedback_text += '</p><p class = block-text>Your accuracy is too low. Remember: <br>' + prompt_text_list } if (missed_responses > missed_thresh){ feedback_text += '</p><p class = block-text>You have not been responding to some trials. Please respond on every trial that requires a response.' } if (ave_rt > rt_thresh){ feedback_text += '</p><p class = block-text>You have been responding too slowly.' } if (testCount == numTestBlocks){ feedback_text += '</p><p class = block-text>Done with this test. Press Enter to continue.<br> If you have been completing tasks continuously for an hour or more, please take a 15-minute break before starting again.' return false } else { delay = delays.pop() stims = createTrialTypes(numTrialsPerBlock, delay) feedback_text += "</p><p class = block-text><i>For the next round of trials, your delay is "+delay+"</i>. Press Enter to continue." return true } } } /* ************************************ */ /* Set up Experiment */ /* ************************************ */ var go_nogo_with_n_back_experiment = [] go_nogo_with_n_back_experiment.push(practiceNode); go_nogo_with_n_back_experiment.push(feedback_block); go_nogo_with_n_back_experiment.push(start_test_block); go_nogo_with_n_back_experiment.push(testNode); go_nogo_with_n_back_experiment.push(feedback_block); go_nogo_with_n_back_experiment.push(post_task_block); go_nogo_with_n_back_experiment.push(end_block);
exports.up = function(knex, promise) { return promise.all([ knex.schema.createTable('migration_test_2', function(t) { t.increments(); t.string('name'); }), knex.schema.createTable('migration_test_2_1', function(t) { t.increments(); t.string('name'); }) ]); }; exports.down = function(knex, promise) { return promise.all([knex.schema.dropTable('migration_test_2'), knex.schema.dropTable('migration_test_2.1')]); };
// This file has been autogenerated. exports.setEnvironment = function() { process.env['AZURE_BATCH_ACCOUNT'] = 'batchtestnodesdk'; process.env['AZURE_BATCH_ENDPOINT'] = 'https://batchtestnodesdk.japaneast.batch.azure.com/'; process.env['AZURE_SUBSCRIPTION_ID'] = '603663e9-700c-46de-9d41-e080ff1d461e'; }; exports.scopes = [[function (nock) { var result = nock('http://batchtestnodesdk.japaneast.batch.azure.com:443') .filteringRequestBody(function (path) { return '*';}) .patch('/pools/nodesdktestpool1?api-version=2016-02-01.3.0', '*') .reply(200, "", { 'transfer-encoding': 'chunked', 'last-modified': 'Fri, 01 Apr 2016 05:47:01 GMT', etag: '0x8D359F10BF5ACC5', server: 'Microsoft-HTTPAPI/2.0', 'request-id': '14d2a531-7415-4a05-a1ba-07026787bfed', 'strict-transport-security': 'max-age=31536000; includeSubDomains', dataserviceversion: '3.0', dataserviceid: 'https://batchtestnodesdk.japaneast.batch.azure.com/pools/nodesdktestpool1', date: 'Fri, 01 Apr 2016 05:47:01 GMT', connection: 'close' }); return result; }, function (nock) { var result = nock('https://batchtestnodesdk.japaneast.batch.azure.com:443') .filteringRequestBody(function (path) { return '*';}) .patch('/pools/nodesdktestpool1?api-version=2016-02-01.3.0', '*') .reply(200, "", { 'transfer-encoding': 'chunked', 'last-modified': 'Fri, 01 Apr 2016 05:47:01 GMT', etag: '0x8D359F10BF5ACC5', server: 'Microsoft-HTTPAPI/2.0', 'request-id': '14d2a531-7415-4a05-a1ba-07026787bfed', 'strict-transport-security': 'max-age=31536000; includeSubDomains', dataserviceversion: '3.0', dataserviceid: 'https://batchtestnodesdk.japaneast.batch.azure.com/pools/nodesdktestpool1', date: 'Fri, 01 Apr 2016 05:47:01 GMT', connection: 'close' }); return result; }]];
let _ = require('lodash') let co = require('co') let requireAll = require('require-all') /* global VERSION */ let commands = requireAll({ dirname: `${__dirname}/commands` }) let HELPTEXT = ` Thinker ${VERSION} ============================== A RethinkDB command line tool. Commands: thinker clone Clone a database locally or between remote hosts. thinker sync Synchronize differences between two databases. thinker -h | --help Show this screen. ` // Some notes --> process.stdout.write(" RECORDS INSERTED: Total = #{records_processed} | Per Second = #{rps} | Percent Complete = %#{pc} \r"); module.exports = function (argv) { return co(function *() { let command = _.first(argv['_']) argv['_'] = argv['_'].slice(1) if (commands[command]) { yield commands[command](argv) } else { console.log(HELPTEXT) } process.exit() }) .catch(function (err) { console.log('ERROR') console.log(err) }) }
const Discord = require('discord.js') /** * Handles Guild Specific Settings */ class SettingsManager { constructor () { /** * Settings Schema. * DO NOT MODIFY THIS DIRECTLY. Use the .register() and .unregister() methods instead. * @type {object} */ this.schema = { } /** * Default values for settings. Do not touch either. * @type {object} */ this.defaults = { } /** * Global defaults. * Useful to override defaults without having to change the schema. * @type {object} */ this.globals = { } /** * Like globals, but forced. * @type {object} */ this.overrides = { } // Built-in settings this.register('restrict', { type: Boolean, def: false }) this.register('prefix', { type: String, def: Core.properties.prefix, min: 1 }) this.register('commandChannel', { type: Discord.TextChannel }) this.register('voiceChannel', { type: Discord.VoiceChannel }) this.register('allowNSFW', { type: Boolean, def: false }) this.register('locale', { type: Core.Locale, def: Core.properties.locale }) } /** * Checks if a type is valid. * @param {*} type */ validateType (type) { if (!type) throw new Error('No type specified.') if ([ Boolean, String, Number, Discord.VoiceChannel, Discord.TextChannel, Discord.User, Core.Locale ].indexOf(type) < 0) throw new Error('Invalid type specified.') } /** * Registers a setting parameter to the schema. * @param {string} key - Key of the parameter * @param {object} params - Parameters * @param {*} params.type - Type of the parameter (Boolean, String, Number, etc) * @param {*} params.def - Default value of the parameter. * @param {number} params.min - For numbers, it specifies the minimum value, for strings, the minimum length. * @param {number} params.max - Same as above, but it specifies the maximum value or length. * @param {boolean} params.integer - For the "number" type, only accept integers. */ register (key, params) { this.validateType(params.type) this.schema[key] = params if (params.def != null) this.defaults[key] = params.def else this.defaults[key] = null } /** * Unregisters a setting parameter from the schema. * @param {string} key - Key to remove */ unregister (key) { if (this.defaults[key]) delete this.defaults[key] if (this.schema[key]) delete this.schema[key] } /** * Gets all the parameters from a guild * @param {Discord.Guild} guild */ async getForGuild (guild) { if (guild) { const g = await Core.guilds.getGuild(guild) const gSett = g.data.settings || {} // TODO: Exclude parameters from disabled modules return Object.freeze(Object.assign({}, this.defaults, this.globals, gSett, this.overrides)) } else { return Object.freeze(Object.assign({}, this.defaults, this.globals, this.overrides)) } } /** * Gets a specific parameter from a guild * @param {Discord.Guild} guild * @param {string} key */ async getGuildParam (guild, key) { if (!this.schema[key]) throw new Error(`The parameter "${key}" does not exist.`) const sett = await this.getForGuild(guild) return sett[key] } async setGuildParam (guild, key, value) { if (!this.schema[key]) throw new Error(`The parameter "${key}" does not exist.`) // Fail if an override is set if (this.overrides[key] != null) throw new Error(`This setting was overriden by the bot owner.`) // Get the parameters from the schema const params = this.schema[key] this.validateType(params.type) // Load current parameter let newVal = await this.getGuildParam(guild, key) switch (params.type) { case Boolean: // Positive Answers if (['yes', 'y', 'true', 'on', '1'].indexOf(value.toLowerCase()) >= 0) newVal = true if (['no', 'n', 'false', 'off', '0'].indexOf(value.toLowerCase()) >= 0) newVal = false break case String: newVal = value.toString() if (params.min != null && newVal.length < params.min) throw new Error('Value is too short.') if (params.max != null && newVal.length > params.max) throw new Error('Value is too long.') break case Number: newVal = parseFloat(value) if (params.integer) newVal = parseInt(value) if (params.min != null && newVal < params.min) throw new Error('Value is too low.') if (params.max != null && newVal > params.max) throw new Error('Value is too high.') break case Core.Locale: const loc = value.split('.')[0] const lang = loc.split('_')[0] const country = loc.split('_')[1] const match = Object.keys(Core.locales.loaded).find(l => { if (l.split('_')[0] === lang && l.split('_')[1] === country) return true if (l.split('_')[0] === lang && !country) return true }) if (match) { newVal = match } else { throw new Error('Invalid language.') } break // TODO: Beter handling of these types. case Discord.VoiceChannel: case Discord.TextChannel: case Discord.User: if (value === '*') newVal = undefined else newVal = value.id || value.match(/\d+/)[0] break } const g = await Core.guilds.getGuild(guild) if (!g.data.settings) g.data.settings = {} g.data.settings[key] = newVal await g.saveData() } } module.exports = SettingsManager
/*global module*/ 'use strict'; module.exports = { unit: { configFile: 'karma.conf.js', background: true } };
import DS from 'ember-data'; export default DS.Model.extend({ email: DS.attr('string'), firstName: DS.attr('string'), lastName: DS.attr('string'), lastSignInAt: DS.attr('string'), displayName: Ember.computed('firstName', 'lastName', function () { return [this.get('firstName'), this.get('lastName')].compact().join(' '); }), });
import React from 'react'; import withRoot from 'docs/src/modules/components/withRoot'; import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs'; import markdown from './list-item-secondary-action.md'; function Page() { return <MarkdownDocs markdown={markdown} />; } export default withRoot(Page);
Template.userReservations.helpers({ listRes: function () { return Reservations.find({userId: Meteor.userId()}); }, dateFormat: function (date) { return date.toDateString(); }, selectedReservation: function () { var res = Session.get("selectedRes"); var record = Reservations.findOne({_id: res}); if(res && record) { return record; } else return false; }, getName: function (userId) { return Meteor.users.findOne({_id: userId}).profile.firstName || userId; }, isAdmin: function() { if (Meteor.user().profile) { return Meteor.users.findOne({ _id: Meteor.userId() }).profile.isAdmin; } return false; }, reservation: function () { return Reservations.find({}, {sort: {date: -1}}).fetch(); } }); Template.userReservations.events({ 'click .cancel': function (e, tmp) { e.preventDefault(); var id = e.currentTarget.id; Meteor.call('cancelReservation', Meteor.userId(), id, function (err, res) { if(err) { Session.set("alertMessage", "Date already passed"); Session.set("alertType", "danger"); } }); }, 'click #adminCancel': function (e) { e.preventDefault(); Meteor.call('adminCancelReservation', Meteor.userId(), this._id); } }); Template.userReservations.rendered = function () { Session.setDefault("selectedRes", null); }
'use strict'; System.register(['../models/Negociacao.js', '../models/ListaNegociacao', '../models/Mensagem.js', '../helpers/Bind.js', '../helpers/DateHelper.js', '../views/NegociacoesView.js', '../views/Mensagem.js', '../services/NegociacaoService.js'], function (_export, _context) { "use strict"; var Negociacao, ListaNegociacoes, Mensagem, Bind, DateHelper, NegociacoesView, MensagemView, NegociacaoService, _createClass, NegociacaoController, negociacaoController; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } return { setters: [function (_modelsNegociacaoJs) { Negociacao = _modelsNegociacaoJs.Negociacao; }, function (_modelsListaNegociacao) { ListaNegociacoes = _modelsListaNegociacao.ListaNegociacoes; }, function (_modelsMensagemJs) { Mensagem = _modelsMensagemJs.Mensagem; }, function (_helpersBindJs) { Bind = _helpersBindJs.Bind; }, function (_helpersDateHelperJs) { DateHelper = _helpersDateHelperJs.DateHelper; }, function (_viewsNegociacoesViewJs) { NegociacoesView = _viewsNegociacoesViewJs.NegociacoesView; }, function (_viewsMensagemJs) { MensagemView = _viewsMensagemJs.MensagemView; }, function (_servicesNegociacaoServiceJs) { NegociacaoService = _servicesNegociacaoServiceJs.NegociacaoService; }], execute: function () { _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); NegociacaoController = function () { function NegociacaoController() { _classCallCheck(this, NegociacaoController); var $ = document.querySelector.bind(document); this._ordemAtual = ''; this._inputData = $('#data'); this._inputQuantidade = $('#quantidade'); this._inputValor = $('#valor'); this._listaNegociacoes = new Bind(new ListaNegociacoes(), new NegociacoesView($('#negociacoesView')), 'adiciona', 'esvazia', 'ordena', 'inverteOrdem'); this._mensagem = new Bind(new Mensagem(), new MensagemView($('#mensagemView')), 'texto'); this._ordemAtual = ''; this._service = new NegociacaoService(); this._init(); } _createClass(NegociacaoController, [{ key: '_init', value: function _init() { var _this = this; this._service.lista().then(function (negociacoes) { return negociacoes.forEach(function (dado) { return _this._listaNegociacoes.adiciona(dado); }); }).catch(function (erro) { return _this._mensagem.texto = erro; }); setInterval(function () { _this.importaNegociacoes(); }, 3000); } }, { key: 'adiciona', value: function adiciona(event) { var _this2 = this; event.preventDefault(); var negociacao = this._criaNegociacao(); this._service.cadastra(negociacao).then(function (mensagem) { _this2._listaNegociacoes.adiciona(negociacao); _this2._mensagem.texto = mensagem; _this2._limpaFormulario(); }).catch(function (erro) { return _this2._mensagem.texto = erro; }); } }, { key: '_criaNegociacao', value: function _criaNegociacao() { return new Negociacao(DateHelper.textoParaData(this._inputData.value), parseInt(this._inputQuantidade.value), parseFloat(this._inputValor.value)); } }, { key: '_limpaFormulario', value: function _limpaFormulario() { this._inputData.value = ''; this._inputQuantidade.value = 1; this._inputValor.value = 0.0; this._inputData.focus(); } }, { key: 'apagar', value: function apagar() { var _this3 = this; this._service.apaga().then(function (mensagem) { _this3._mensagem.texto = mensagem; _this3._listaNegociacoes.esvazia(); }).catch(function (erro) { return _this3._mensagem.texto = erro; }); } }, { key: 'importaNegociacoes', value: function importaNegociacoes() { var _this4 = this; this._service.importa(this._listaNegociacoes.negociacoes).then(function (negociacoes) { return negociacoes.forEach(function (negociacao) { _this4._listaNegociacoes.adiciona(negociacao); _this4._mensagem.texto = 'Negociações do período importadas'; }); }).catch(function (erro) { return _this4._mensagem.texto = erro; }); } }, { key: 'ordena', value: function ordena(coluna) { if (this._ordemAtual === coluna) { this._listaNegociacoes.inverteOrdem(); } else { this._listaNegociacoes.ordena(function (a, b) { return a[coluna] - b[coluna]; }); } this._ordemAtual = coluna; } }]); return NegociacaoController; }(); negociacaoController = new NegociacaoController(); function currentInstance() { return negociacaoController; } _export('currentInstance', currentInstance); } }; }); //# sourceMappingURL=NegociacaoController.js.map
import React from 'react' export { Awesome } from './src' const App = () => ( <div> <Awesome onClick={() => { console.log('Nice!')}/> </div> ) export default App
'use babel'; import { CompositeDisposable } from 'atom'; import request from 'request' import SolarCalc from 'solar-calc' import _ from 'underscore-plus'; import MyConfig from './config-schema.json'; // Use raw API rather than navigator due to unavailability in Atom const GEOLOCATION_API = 'https://maps.googleapis.com/maps/api/browserlocation/json?browser=chromium&sensor=true' // Global variables to be accessed and checked from functions var day, sunset, sunrise, daytime_themes, nighttime_themes, lat, lng // Attempting to resolve "this" issue // suggestion implemented (roughly) from here: // https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-context-inside-a-callback var _this // From https://github.com/qwtel/theme-flux-solar // Get a human readable title for the given theme name. function getThemeTitle(themeName = '') { const title = themeName.replace(/-(ui|syntax)/g, '').replace(/-theme$/g, ''); return _.undasherize(_.uncamelcase(title)); } function themeToConfigStringEnum({ metadata: { name } }) { return { value: name, description: getThemeTitle(name), }; } // From https://github.com/as-cii/theme-flux/blob/master/lib/theme-flux.js const loadedThemes = atom.themes.getLoadedThemes(); const uiThemesEnum = loadedThemes .filter(theme => theme.metadata.theme === 'ui') .map(themeToConfigStringEnum); const syntaxThemesEnum = loadedThemes .filter(theme => theme.metadata.theme === 'syntax') .map(themeToConfigStringEnum); export default { config: MyConfig, subscriptions: null, activate(state) { _this = this _this.setup() // TODO: Allow user configurable refresh interval // TODO: Done, I think? Maybe check. interval = atom.config.get('day-and-night.Activation.interval') tock = setInterval(_this.tick, interval * 60 * 1000) // Enumerate the theme options and set in config page _this.config.Appearance.properties.daytime_syntax_theme.enum = _this.config.Appearance.properties.nighttime_syntax_theme.enum = syntaxThemesEnum _this.config.Appearance.properties.daytime_ui_theme.enum = _this.config.Appearance.properties.nighttime_ui_theme.enum = uiThemesEnum console.log(uiThemesEnum) console.log(syntaxThemesEnum) // Calculate the solar times _this.sunTimes(); // Events subscribed to in atom's system can be easily cleaned up with a CompositeDisposable _this.subscriptions = new CompositeDisposable(); // Register command that toggles _this.subscriptions.add(atom.commands.add('atom-workspace', { 'day-and-night:toggle': () => _this.toggle() })); _this.subscriptions.add(_this.subscribeToConfigChanges()); _this.tick() }, // From: https://github.com/Haacked/encourage-atom/blob/master/lib/encourage.js subscribeToConfigChanges() { const subscriptions = new CompositeDisposable(); const appearanceObserver = atom.config.observe( 'day-and-night.Appearance', (value) => { _this.setup() _this.tick() }); subscriptions.add(appearanceObserver); const intervalObserver = atom.config.observe( 'day-and-night.Activation.interval', (value) => { interval = atom.config.get('day-and-night.Activation.interval') clearInterval(tock) tock = setInterval(_this.tick, interval * 60 * 1000) }); subscriptions.add(intervalObserver); return subscriptions; }, deactivate() { _this.subscriptions.dispose(); }, download(url) { return new Promise((resolve, reject) => { request(url, (error, response, body) => { if (!error && response.statusCode == 200) { resolve(body) } else { reject({ reason: 'Unable to download page' }) } }) }) }, // Run general setup functions setup(){ // Save the theme settings so aren't reloaded each time daytime_themes = [ atom.config.get('day-and-night.Appearance.daytime_ui_theme'), atom.config.get('day-and-night.Appearance.daytime_syntax_theme') ] nighttime_themes = [ atom.config.get('day-and-night.Appearance.nighttime_ui_theme'), atom.config.get('day-and-night.Appearance.nighttime_syntax_theme') ] }, serialize(){ return }, // Get the sunrise and sunset times for today and user defined location sunTimes() { // Get the current date now = new Date() // Day is also saved and used to check if new solar times are needed day = now.getDate() // Get the GPS config coordinates from config as backup lat = atom.config.get('day-and-night.Location.latitude') lng = atom.config.get('day-and-night.Location.longitude') // Use Google geolocation API to determine sunrise and sunset _this.download(GEOLOCATION_API).then((html) => { json = JSON.parse(html); console.log(json) lat = json.location.lat lng = json.location.lng // If update is set in config then update the location config if (atom.config.get('day-and-night.Location.update')){ console.log("Updating location config") atom.config.set('day-and-night.Location.latitude', lat) atom.config.set('day-and-night.Location.longitude', lng) } // Use the NPM solar-calc package to determine sunrise and sunset var solar = new SolarCalc(now,lat,lng); sunrise = solar.sunrise sunset = solar.sunset }).catch((error) => { // If there's an error then throw warning atom.notifications.addWarning(error.reason) }) }, // Legacy, for debugging toggle() { _this.setup() _this.tick() }, tick() { console.log("tick") // If the plugin has not been configured then exit, relies on user config if (!atom.config.get('day-and-night.Activation.configured')){ return } // Get the current date and time now = new Date() // Check if the day has changed since sun times last retrieved if (now.getDate() != day){ console.log("Day changed!") _this.sunTimes() } // Do theme changing stuff current_themes = atom.config.get('core.themes') // Apparently copying the array themes = current_themes.slice() if (now >= sunset) { themes = nighttime_themes } else if (now >= sunrise) { themes = daytime_themes } // If there is a change to the themes, then update the config if (themes != current_themes){ atom.config.set('core.themes', themes) } } };
app.controller('createUserController', function ($scope, $location, $rootScope, userService, maskFactory, toast, userFactory) { angular.extend($scope, maskFactory); $rootScope.login = {color: false, menu: false, confirmation: false}; $scope.perfilUser = profileUser(); $scope.user = {status: true}; $scope.save = function (formUser) { if (!formUser.$valid) { $scope.validate = true; return; } $scope.user.user = userFactory.getUser(); userService.save($scope.user).then(function (u) { toast.open('success', 'Usuário cadastrado com sucesso!'); $location.path('/users'); }, function (response) { toast.open('warning', response.message); }); }; $scope.goBack = function (b) { $location.path('/users'); }; });
import { PureComponent } from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import actions from './ndcs-sdgs-meta-provider-actions'; import reducers, { initialState } from './ndcs-sdgs-meta-provider-reducers'; class NdcsSdgsMetaProvider extends PureComponent { componentDidMount() { this.props.getNdcsSdgsMeta(); } render() { return null; } } NdcsSdgsMetaProvider.propTypes = { getNdcsSdgsMeta: PropTypes.func.isRequired }; export { actions, reducers, initialState }; export default connect(null, actions)(NdcsSdgsMetaProvider);
// This is a manifest file that'll be compiled into application.js, which will include all the files // listed below. // // Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts, // or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path. // // It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the // compiled file. // // Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details // about supported directives. // //= require jquery //= require jquery_ujs //= require foundation/foundation //= require foundation //= require d3 //= require highcharts //= require highcharts/highcharts-more //= require_tree . $(document).ready(function(){ $(document).foundation(); });
document.addEventListener('DOMContentLoaded', function() { var btn = document.getElementById('disableBtn'); link.addEventListener('click', function() { localStorage.setItem('trumpExtEnabled'), false); document.getElementById("disableBtn").value = "Enable"; chrome.tabs.query({active: true, currentWindow: true}, function (arrayOfTabs) { chrome.tabs.reload(arrayOfTabs[0].id); }); }); });
angular.module('eBlog') .controller('MypageController', ['$scope', '$state','$http', 'userService','$stateParams', function($scope, $state,$http,userService,$stateParams) { $('.no-write').show(); $('.home-write').hide(); $scope.user = userService.get(); var id = $stateParams.id; init(); $scope.goDetail = function(id) { $state.go('blog.myarticle', { id: id }); }; function init() { $http.get('/blog/api/user/'+id).then(function(resp) { if(resp.data && resp.status && resp.status === 200) { $scope.articleUser = resp.data; } }, function(resp) { console.log('----get user error----'); console.log(resp.data); }); $http.get('/blog/api/article/'+id).then(function(resp) { if(resp.data && resp.status && resp.status === 200) { $scope.articles = resp.data; } }, function(resp) { console.log('----get user articles error----'); console.log(resp.data); }); if($scope.user.id == id) $('#dropdown .third').addClass('active').siblings().removeClass('active'); } }]);
(function($) { var dialog = { opts: null, init: function(options) { dialog.opts = $.extend({ modal: true, width: 600, height: 300, title: 'Title', html: '', buttons: { 'abort': { 'label': 'Abbrechen', 'type': 'info', 'click': function(result) { $(this).modalDialog('close', false); } }, 'ok': { 'label': 'Ok', 'type': 'info', 'click': function() { $(this).modalDialog('close', true); } } }, onClose: function(status) { } }, options); }, open: function() { if(dialog.opts.modal) { $('<div>', {'class': 'modal'}).appendTo("body"); } var head = $('<div>', {'class': 'head'}) .text(dialog.opts.title); var body = $('<div>', {'class': 'body'}).html(dialog.opts.html); var foot = $('<div>', {'class': 'foot'}); $.each(dialog.opts.buttons, function(button, value) { foot.append( $('<span>', {'class': 'btn'}) .text(value.label) .addClass(value.type) .bind('click', value.click) ); }); $('<div>', { 'class': 'dialog', css: { 'width': dialog.opts.width, 'height': dialog.opts.height, 'margin-left': -(dialog.opts.width / 2), 'margin-top': -(dialog.opts.height / 2) } }).append(head, body, foot).appendTo("body").fadeIn(100); dialog.opts.onOpen(); }, close: function(result) { $('.dialog').remove(); $('.modal').remove(); dialog.opts.onClose(result); } }; $.fn.modalDialog = function(options) { if(dialog[options] ) { return dialog[options].apply( this, Array.prototype.slice.call( arguments, 1 )); } else if (typeof options === 'object' || ! options ) { return dialog.init.apply(this, arguments); } else { $.error( 'Method ' + options + ' does not exist.' ); } return this.each(function() { }); }; })(jQuery);
var BASE_CHECKSUM = 0xB19ED489; var LAYER1_OFFSET; var LAYER2_OFFSET; var SPRITE_OFFSET; var HEADER1_OFFSET; var HEADER2_OFFSET; var HEADER3_OFFSET; var HEADER4_OFFSET; var FLAGBASE; var LEVEL_OFFSETS = [ // layer data {"name": "layer1", "bytes": 3, "offset": LAYER1_OFFSET = 0x2E000}, {"name": "layer2", "bytes": 3, "offset": LAYER2_OFFSET = 0x2E600}, {"name": "sprite", "bytes": 2, "offset": SPRITE_OFFSET = 0x2EC00}, // secondary header data {"name": "header1", "bytes": 1, "offset": HEADER1_OFFSET = 0x2F000}, {"name": "header2", "bytes": 1, "offset": HEADER2_OFFSET = 0x2F200}, {"name": "header3", "bytes": 1, "offset": HEADER3_OFFSET = 0x2F400}, {"name": "header4", "bytes": 1, "offset": HEADER4_OFFSET = 0x2F600}, // custom data {"name": "lvflags", "bytes": 1, "offset": FLAGBASE = 0x1FDE0}, ]; var SEC_EXIT_OFFSET_LO = 0x2F800; var SEC_EXIT_OFFSET_HI = 0x2FE00; var SEC_EXIT_OFFSET_X1 = 0x2FA00; var SEC_EXIT_OFFSET_X2 = 0x2FC00; /* Primary header - first five bytes of level data BBBLLLLL CCCOOOOO 3MMMSSSS TTPPPFFF IIVVZZZZ BBB = BG palette LLLLL = Length of level (amount of screens) CCC = BG color OOOOO = Level mode (ignore this, can be used to randomly make levels dark or transparent though) 3 = Layer 3 Priority MMM = Music SSSS = Sprite tileset TT = Time (00 = 0, 01 = 200, 10 = 300, 11 = 400) PPP = Sprite palette FFF = FG palette II = Item memory (ignore this) VV = Vertical scroll (00 = no v-scroll, 01 = v-scroll, 10 = v-scroll only if sprinting/flying/climbing, 11 = no v or h-scroll) ZZZZ = FG/BG tileset Secondary header SSSSYYYY 33TTTXXX MMMMFFBB IUVEEEEE SSSS = Layer 2 scroll settings (see LM) YYYY = Level entrance Y position (ignore this) 33 = Layer 3 settings (00 = none, 01 = tide, 10 = mondo tide, 11 = tileset specific) TTT = Level entrance type (ignore this and pretty much all the below ones too) XXX = Level entrance X position MMMM = Level entrance midway screen FF = Level entrance FG init position BB = Level entrance BG init position I = Disable no-Yoshi intro flag U = Unknown vertical positioning flag V = Vertical positioning flag EEEEE = Level entrance screen number */ var trans_offsets = [ // name pointer {"name": "nameptr", "bytes": 2, "offset": 0x220FC}, ]; var NORMAL_EXIT = 1<<0, SECRET_EXIT = 1<<1, KEY = 1<<2, KEYHOLE = 1<<3; var NO_CASTLE = 0, NORTH_CLEAR = 1, NORTH_PATH = 2; var NO_GHOST = 0, GHOST_HOUSE = 1, GHOST_SHIP = 2; /* 0x0 = Beige/White 0x1 = White/Gold 0x2 = DkBlue/Black* 0x3 = Brown/Gold 0x4 = Black/White (Palette-specific?) 0x5 = LtBlue/DkBlue 0x6 = Gold/Brown* 0x7 = Green/Black* */ var TITLE_TEXT_COLOR = 0x4; var TITLE_DEMO_LEVEL = 0xC7; var SMW_STAGES = [ // stages {"name": "yi1", "world": 1, "exits": 1, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x105, "cpath": NO_CASTLE, "tile": [0x04, 0x28], "out": ["yswitch"]}, {"name": "yi2", "world": 1, "exits": 1, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x106, "cpath": NORTH_PATH, "tile": [0x0A, 0x28], "out": ["yi3"]}, {"name": "yi3", "world": 1, "exits": 1, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 1, "id": 0x103, "cpath": NORTH_CLEAR, "tile": [0x0A, 0x26], "out": ["yi4"]}, {"name": "yi4", "world": 1, "exits": 1, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x102, "cpath": NO_CASTLE, "tile": [0x0C, 0x24], "out": ["c1"]}, {"name": "dp1", "world": 2, "exits": 2, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x015, "cpath": NORTH_PATH, "tile": [0x05, 0x11], "out": ["dp2", "ds1"]}, {"name": "dp2", "world": 2, "exits": 2, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x009, "cpath": NORTH_PATH, "tile": [0x03, 0x0D], "out": ["dgh", "gswitch"]}, {"name": "dp3", "world": 2, "exits": 1, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x005, "cpath": NORTH_CLEAR, "tile": [0x09, 0x0A], "out": ["dp4"]}, {"name": "dp4", "world": 2, "exits": 1, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x006, "cpath": NO_CASTLE, "tile": [0x0B, 0x0C], "out": ["c2"]}, {"name": "ds1", "world": 2, "exits": 2, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 2, "id": 0x00A, "cpath": NO_CASTLE, "tile": [0x05, 0x0E], "out": ["dgh", "dsh"]}, {"name": "ds2", "world": 2, "exits": 1, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x10B, "cpath": NORTH_CLEAR, "tile": [0x11, 0x21], "out": ["dp3"]}, {"name": "vd1", "world": 3, "exits": 2, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x11A, "cpath": NORTH_CLEAR, "tile": [0x06, 0x32], "out": ["vd2", "vs1"]}, {"name": "vd2", "world": 3, "exits": 2, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 1, "id": 0x118, "cpath": NO_CASTLE, "tile": [0x09, 0x30], "out": ["vgh", "rswitch"]}, {"name": "vd3", "world": 3, "exits": 1, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x10A, "cpath": NO_CASTLE, "tile": [0x0D, 0x2E], "out": ["vd4"]}, {"name": "vd4", "world": 3, "exits": 1, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x119, "cpath": NORTH_PATH, "tile": [0x0D, 0x30], "out": ["c3"]}, {"name": "vs1", "world": 3, "exits": 2, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x109, "cpath": NO_CASTLE, "tile": [0x04, 0x2E], "out": ["vs2", "sw2"]}, {"name": "vs2", "world": 3, "exits": 1, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x001, "cpath": NORTH_CLEAR, "tile": [0x0C, 0x03], "out": ["vs3"]}, {"name": "vs3", "world": 3, "exits": 1, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 1, "id": 0x002, "cpath": NORTH_CLEAR, "tile": [0x0E, 0x03], "out": ["vfort"]}, {"name": "cba", "world": 4, "exits": 2, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x00F, "cpath": NORTH_CLEAR, "tile": [0x14, 0x05], "out": ["cookie", "soda"]}, {"name": "soda", "world": 4, "exits": 1, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 2, "id": 0x011, "cpath": NO_CASTLE, "tile": [0x14, 0x08], "out": ["sw3"]}, {"name": "cookie", "world": 4, "exits": 1, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x010, "cpath": NORTH_CLEAR, "tile": [0x17, 0x05], "out": ["c4"]}, {"name": "bb1", "world": 4, "exits": 1, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x00C, "cpath": NO_CASTLE, "tile": [0x14, 0x03], "out": ["bb2"]}, {"name": "bb2", "world": 4, "exits": 1, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x00D, "cpath": NO_CASTLE, "tile": [0x16, 0x03], "out": ["c4"]}, {"name": "foi1", "world": 5, "exits": 2, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x11E, "cpath": NORTH_PATH, "tile": [0x09, 0x37], "out": ["foi2", "fgh"]}, {"name": "foi2", "world": 5, "exits": 2, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 1, "id": 0x120, "cpath": NO_CASTLE, "tile": [0x0B, 0x3A], "out": ["foi3", "bswitch"]}, {"name": "foi3", "world": 5, "exits": 2, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x123, "cpath": NORTH_CLEAR, "tile": [0x09, 0x3C], "out": ["fgh", "c5"]}, {"name": "foi4", "world": 5, "exits": 2, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x11F, "cpath": NORTH_PATH, "tile": [0x05, 0x3A, ], "out": ["foi2", "fsecret"]}, {"name": "fsecret", "world": 5, "exits": 1, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x122, "cpath": NORTH_PATH, "tile": [0x05, 0x3C], "out": ["ffort"]}, {"name": "ci1", "world": 6, "exits": 1, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x022, "cpath": NO_CASTLE, "tile": [0x18, 0x16], "out": ["cgh"]}, {"name": "ci2", "world": 6, "exits": 2, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x024, "cpath": NORTH_PATH, "tile": [0x15, 0x1B], "out": ["ci3", "csecret"]}, {"name": "ci3", "world": 6, "exits": 2, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x023, "cpath": NO_CASTLE, "tile": [0x13, 0x1B], "out": ["ci3", "cfort"]}, {"name": "ci4", "world": 6, "exits": 1, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x01D, "cpath": NORTH_PATH, "tile": [0x0F, 0x1D], "out": ["ci5"]}, {"name": "ci5", "world": 6, "exits": 1, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x01C, "cpath": NORTH_PATH, "tile": [0x0C, 0x1D], "out": ["c6"]}, {"name": "csecret", "world": 6, "exits": 1, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x117, "cpath": NORTH_CLEAR, "tile": [0x18, 0x29], "out": ["c6"]}, {"name": "vob1", "world": 7, "exits": 1, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x116, "cpath": NORTH_CLEAR, "tile": [0x1C, 0x27], "out": ["vob2"]}, {"name": "vob2", "world": 7, "exits": 2, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x115, "cpath": NORTH_PATH, "tile": [0x1A, 0x27], "out": ["bgh", "bfort"]}, {"name": "vob3", "world": 7, "exits": 1, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x113, "cpath": NORTH_PATH, "tile": [0x15, 0x27], "out": ["vob4"]}, {"name": "vob4", "world": 7, "exits": 2, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x10F, "cpath": NORTH_PATH, "tile": [0x15, 0x25], "out": ["sw5", "c7"]}, {"name": "c1", "world": 1, "exits": 1, "castle": 1, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x101, "cpath": NORTH_PATH, "tile": [0x0A, 0x22], "out": ["dp1"]}, {"name": "c2", "world": 2, "exits": 1, "castle": 2, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x007, "cpath": NORTH_PATH, "tile": [0x0D, 0x0C], "out": ["vd1"]}, {"name": "c3", "world": 3, "exits": 1, "castle": 3, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x11C, "cpath": NORTH_PATH, "tile": [0x0D, 0x32], "out": ["cba"]}, {"name": "c4", "world": 4, "exits": 1, "castle": 4, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x00E, "cpath": NORTH_CLEAR, "tile": [0x1A, 0x03], "out": ["foi1"]}, {"name": "c5", "world": 5, "exits": 1, "castle": 5, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x020, "cpath": NORTH_CLEAR, "tile": [0x18, 0x12], "out": ["ci1"]}, {"name": "c6", "world": 6, "exits": 1, "castle": 6, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x01A, "cpath": NORTH_PATH, "tile": [0x0C, 0x1B], "out": ["sgs"]}, {"name": "c7", "world": 7, "exits": 1, "castle": 7, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x110, "cpath": NORTH_PATH, "tile": [0x18, 0x25], "out": ["frontdoor"]}, {"name": "vfort", "world": 3, "exits": 1, "castle": -1, "palace": 0, "ghost": NO_GHOST, "water": 1, "id": 0x00B, "cpath": NORTH_CLEAR, "tile": [0x10, 0x03], "out": ["bb1"]}, {"name": "ffort", "world": 5, "exits": 1, "castle": -1, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x01F, "cpath": NORTH_CLEAR, "tile": [0x16, 0x10], "out": ["sw4"]}, {"name": "cfort", "world": 6, "exits": 1, "castle": -1, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x01B, "cpath": NORTH_CLEAR, "tile": [0x0F, 0x1B], "out": ["ci4"]}, {"name": "bfort", "world": 7, "exits": 1, "castle": -1, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x111, "cpath": NORTH_PATH, "tile": [0x1A, 0x25], "out": ["backdoor"]}, {"name": "dgh", "world": 2, "exits": 2, "castle": 0, "palace": 0, "ghost": GHOST_HOUSE, "water": 0, "id": 0x004, "cpath": NO_CASTLE, "tile": [0x05, 0x0A], "out": ["topsecret", "dp3"]}, {"name": "dsh", "world": 2, "exits": 2, "castle": 0, "palace": 0, "ghost": GHOST_HOUSE, "water": 0, "id": 0x013, "cpath": NO_CASTLE, "tile": [0x07, 0x10], "out": ["ds2", "sw1"]}, {"name": "vgh", "world": 3, "exits": 1, "castle": 0, "palace": 0, "ghost": GHOST_HOUSE, "water": 0, "id": 0x107, "cpath": NORTH_CLEAR, "tile": [0x09, 0x2C], "out": ["vd3"]}, {"name": "fgh", "world": 5, "exits": 2, "castle": 0, "palace": 0, "ghost": GHOST_HOUSE, "water": 0, "id": 0x11D, "cpath": NORTH_CLEAR, "tile": [0x07, 0x37], "out": ["foi1", "foi4"]}, {"name": "cgh", "world": 6, "exits": 1, "castle": 0, "palace": 0, "ghost": GHOST_HOUSE, "water": 0, "id": 0x021, "cpath": NORTH_CLEAR, "tile": [0x15, 0x16], "out": ["ci2"]}, {"name": "sgs", "world": 6, "exits": 1, "castle": 0, "palace": 0, "ghost": GHOST_SHIP, "water": 1, "id": 0x018, "cpath": NORTH_PATH, "tile": [0x0E, 0x17], "out": ["vob1"]}, {"name": "bgh", "world": 7, "exits": 2, "castle": 0, "palace": 0, "ghost": GHOST_HOUSE, "water": 0, "id": 0x114, "cpath": NORTH_PATH, "tile": [0x18, 0x27], "out": ["vob3", "c7"]}, {"name": "sw1", "world": 8, "exits": 2, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x134, "cpath": NO_CASTLE, "tile": [0x15, 0x3A], "out": ["sw1", "sw2"]}, {"name": "sw2", "world": 8, "exits": 2, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 1, "id": 0x130, "cpath": NO_CASTLE, "tile": [0x16, 0x38], "out": ["sw2", "sw3"]}, {"name": "sw3", "world": 8, "exits": 2, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x132, "cpath": NO_CASTLE, "tile": [0x1A, 0x38], "out": ["sw3", "sw4"]}, {"name": "sw4", "world": 8, "exits": 2, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x135, "cpath": NO_CASTLE, "tile": [0x1B, 0x3A], "out": ["sw4", "sw5"]}, {"name": "sw5", "world": 8, "exits": 2, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x136, "cpath": NO_CASTLE, "tile": [0x18, 0x3B], "out": ["sw1", "sp1"]}, {"name": "sp1", "world": 9, "exits": 1, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x12A, "cpath": NORTH_CLEAR, "tile": [0x14, 0x33], "out": ["sp2"]}, {"name": "sp2", "world": 9, "exits": 1, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x12B, "cpath": NORTH_CLEAR, "tile": [0x17, 0x33], "out": ["sp3"]}, {"name": "sp3", "world": 9, "exits": 1, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x12C, "cpath": NORTH_CLEAR, "tile": [0x1A, 0x33], "out": ["sp4"]}, {"name": "sp4", "world": 9, "exits": 1, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x12D, "cpath": NORTH_CLEAR, "tile": [0x1D, 0x33], "out": ["sp5"]}, {"name": "sp5", "world": 9, "exits": 1, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x128, "cpath": NORTH_CLEAR, "tile": [0x1D, 0x31], "out": ["sp6"]}, {"name": "sp6", "world": 9, "exits": 1, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 1, "id": 0x127, "cpath": NORTH_CLEAR, "tile": [0x1A, 0x31], "out": ["sp7"]}, {"name": "sp7", "world": 9, "exits": 1, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x126, "cpath": NORTH_CLEAR, "tile": [0x17, 0x31], "out": ["sp8"]}, {"name": "sp8", "world": 9, "exits": 1, "castle": 0, "palace": 0, "ghost": NO_GHOST, "water": 0, "id": 0x125, "cpath": NORTH_CLEAR, "tile": [0x14, 0x31], "out": ["yi2"]}, // switches {"name": "yswitch", "world": 1, "exits": 0, "castle": 0, "palace": 1, "ghost": NO_GHOST, "water": 0, "id": 0x014, "cpath": NO_CASTLE, "tile": [0x02, 0x11], "out": []}, {"name": "gswitch", "world": 2, "exits": 0, "castle": 0, "palace": 4, "ghost": NO_GHOST, "water": 0, "id": 0x008, "cpath": NO_CASTLE, "tile": [0x01, 0x0D], "out": []}, {"name": "rswitch", "world": 3, "exits": 0, "castle": 0, "palace": 3, "ghost": NO_GHOST, "water": 0, "id": 0x11B, "cpath": NO_CASTLE, "tile": [0x0B, 0x32], "out": []}, {"name": "bswitch", "world": 5, "exits": 0, "castle": 0, "palace": 2, "ghost": NO_GHOST, "water": 0, "id": 0x121, "cpath": NO_CASTLE, "tile": [0x0D, 0x3A], "out": []}, // warps {"name": "warp-sw1", "exits": 0, "id": 0x016, "tile": [0x07, 0x12], "warp": 0x06, "rwarp": 0x0D, "events": [{"stageid": 0x136, "secret": 0}]}, {"name": "warp-sw2", "exits": 0, "id": 0x108, "tile": [0x01, 0x2E], "warp": 0x0E, "rwarp": 0x0F, "events": [{"stageid": 0x134, "secret": 0}, {"stageid": 0x134, "secret": 1}]}, {"name": "warp-sw3", "exits": 0, "id": 0x012, "tile": [0x10, 0x0F], "warp": 0x10, "rwarp": 0x11, "events": [{"stageid": 0x130, "secret": 0}, {"stageid": 0x130, "secret": 1}]}, {"name": "warp-sw4", "exits": 0, "id": 0x01E, "tile": [0x14, 0x10], "warp": 0x12, "rwarp": 0x13, "events": [{"stageid": 0x132, "secret": 0}, {"stageid": 0x132, "secret": 1}]}, {"name": "warp-sw5", "exits": 0, "id": 0x10C, "tile": [0x15, 0x23], "warp": 0x19, "rwarp": 0x15, "events": [{"stageid": 0x135, "secret": 0}, {"stageid": 0x135, "secret": 1}]}, {"name": "warp-sp", "exits": 0, "id": 0x131, "tile": [0x18, 0x38], "warp": 0x16, "rwarp": 0x17, "events": []}, // other {"name": "topsecret", "exits": 0, "id": 0x003, "tile": [0x05, 0x08]}, // {"name": "yhouse", "exits": 0, "id": 0x104, "tile": [0x07, 0x27]}, ]; var PRIMARY_SUBLEVEL_IDS = $.map(SMW_STAGES, function(x){ return x.id }); var SUBMAP_LINKS = { // pipes 0x1: { 'pipe': true, 'from': 'dsh', 'to': 'ds2', 'reach': [0x2] }, 0x2: { 'pipe': true, 'from': 'ds2', 'to': 'dp3', 'reach': [0x9] }, 0x3: { 'pipe': true, 'from': 'vs1', 'to': 'vs2', 'reach': [0xA] }, 0x4: { 'pipe': true, 'from': 'c3', 'to': 'cba', 'reach': [0xA] }, 0x5: { 'pipe': true, 'from': 'ci2', 'to': 'csecret', 'reach': [0x6] }, 0x6: { 'pipe': true, 'from': 'csecret', 'to': 'c6', 'reach': [0xD] }, // screen exits 0x7: { 'pipe': false, 'from': 'yi1', 'to': 'yswitch', 'reach': [] }, 0x8: { 'pipe': false, 'from': 'c1', 'to': 'dp1', 'reach': [0x1, 0x9] }, 0x9: { 'pipe': false, 'from': 'c2', 'to': 'vd1', 'reach': [0x3, 0x4] }, 0xA: { 'pipe': false, 'from': 'c4', 'to': 'foi1', 'reach': [0xB, 0xC] }, 0xB: { 'pipe': false, 'from': 'fsecret', 'to': 'ffort', 'reach': [] }, 0xC: { 'pipe': false, 'from': 'foi3', 'to': 'c5', 'reach': [0x5, 0xD] }, 0xD: { 'pipe': false, 'from': 'sgs', 'to': 'vob1', 'reach': [] }, }; var OFFSCREEN_EVENT_NUMBERS = 0x268E4; var OFFSCREEN_LOCATIONS = 0x2693C; var LAYER1_EVENT_LOCATIONS = 0x2585D; var TRANSLEVEL_EVENTS = 0x2D608; var DESTRUCTION_EVENT_NUMBERS = 0x265D6; var DESTRUCTION_EVENT_COORDS = 0x265B6; var DESTRUCTION_EVENT_VRAM = 0x26587; // koopa kid boss room sublevels, indexed by castle # var KOOPA_KID_SUBLEVELS = [ 0x1F6, 0x0E5, 0x1F2, 0x0D9, 0x0CC, 0x0D3, 0x1EB ]; var NO_YOSHI_GHOST = 0, NO_YOSHI_CASTLE_DAY = 1, NO_YOSHI_PLAINS = 2, NO_YOSHI_STARS = 3, NO_YOSHI_ICE = 4, NO_YOSHI_CASTLE_NIGHT = 5, NO_YOSHI_DISABLED = 6; /* $00B3D8: Yoshi's Island palettes 4-7, colors 1-7. $00B410: Main map palettes 4-7, colors 1-7. $00B448: Star World palettes 4-7, colors 1-7. $00B480: Vanilla Dome / Valley of Bowser palettes 4-7, colors 1-7. $00B4B8: Forest of Illusion palettes 4-7, colors 1-7. $00B4F0: Special World palettes 4-7, colors 1-7. $00B732: Yoshi's Island [special] palettes 4-7, colors 1-7. $00B76A: Main map [special] palettes 4-7, colors 1-7. $00B7A2: Star World [special] palettes 4-7, colors 1-7. $00B7DA: Vanilla Dome / Valley of Bowser [special] palettes 4-7, colors 1-7. $00B812: Forest of Illusion [special] palettes 4-7, colors 1-7. $00B84A: Special World [special] palettes 4-7, colors 1-7. */ var OVERWORLD_MAPS = [ {submapid: 0, palette: 0, ug: 0, palette_addr: [0x3410, 0x376A], xmin: 0x00, xmax: 0x1F, ymin: 0x00, ymax: 0x1F, name: 'MAIN'}, {submapid: 1, palette: 1, ug: 0, palette_addr: [0x33D8, 0x3732], xmin: 0x00, xmax: 0x0F, ymin: 0x20, ymax: 0x29, name: 'YI'}, {submapid: 2, palette: 2, ug: 1, palette_addr: [0x3480, 0x37DA], xmin: 0x00, xmax: 0x0F, ymin: 0x2B, ymax: 0x34, name: 'VD'}, {submapid: 3, palette: 3, ug: 0, palette_addr: [0x34B8, 0x3812], xmin: 0x00, xmax: 0x0F, ymin: 0x35, ymax: 0x3F, name: 'FOI'}, {submapid: 4, palette: 2, ug: 1, palette_addr: [0x3480, 0x37DA], xmin: 0x10, xmax: 0x1F, ymin: 0x20, ymax: 0x29, name: 'VOB'}, {submapid: 5, palette: 4, ug: 1, palette_addr: [0x34F0, 0x384A], xmin: 0x10, xmax: 0x1F, ymin: 0x2B, ymax: 0x34, name: 'SP'}, {submapid: 6, palette: 5, ug: 1, palette_addr: [0x3448, 0x37A2], xmin: 0x10, xmax: 0x1F, ymin: 0x35, ymax: 0x3F, name: 'SW'}, ]; var OFFSCREEN_EVENT_TILES = { 'dp1': 0x00, 'c1': 0x05, 'dp3': 0x08, 'vs2': 0x10, 'ds2': 0x13, 'cba': 0x14, 'csecret': 0x1D, 'vob1': 0x1F, 'yswitch': 0x20, 'vd1': 0x26, }; var LAYER2_NONE = 0, LAYER2_BACKGROUND = 1, LAYER2_INTERACT = 2; var LEVEL_MODES = { 0x00: { maxscreens: 0x20, boss: 0, horiz: 1, layer2: LAYER2_BACKGROUND }, 0x01: { maxscreens: 0x10, boss: 0, horiz: 1, layer2: LAYER2_NONE }, 0x02: { maxscreens: 0x10, boss: 0, horiz: 1, layer2: LAYER2_INTERACT }, // 0x03: { maxscreens: 0x0D, boss: 0, horiz: 0, layer2: LAYER2_INTERACT }, // 0x04: { maxscreens: 0x0D, boss: 0, horiz: 0, layer2: LAYER2_INTERACT }, // 0x05: { maxscreens: 0x0E, boss: 0, horiz: 1, layer2: LAYER2_INTERACT }, // 0x06: { maxscreens: 0x0E, boss: 0, horiz: 1, layer2: LAYER2_INTERACT }, 0x07: { maxscreens: 0x0E, boss: 0, horiz: 0, layer2: LAYER2_NONE }, 0x08: { maxscreens: 0x0E, boss: 0, horiz: 0, layer2: LAYER2_INTERACT }, 0x09: { maxscreens: 0x00, boss: 1, horiz: 1, layer2: LAYER2_BACKGROUND }, 0x0A: { maxscreens: 0x1C, boss: 0, horiz: 0, layer2: LAYER2_BACKGROUND }, 0x0B: { maxscreens: 0x00, boss: 1, horiz: 1, layer2: LAYER2_BACKGROUND }, 0x0C: { maxscreens: 0x20, boss: 0, horiz: 1, layer2: LAYER2_BACKGROUND }, 0x0D: { maxscreens: 0x1C, boss: 0, horiz: 0, layer2: LAYER2_BACKGROUND }, // dark bg vert 0x0E: { maxscreens: 0x20, boss: 0, horiz: 1, layer2: LAYER2_BACKGROUND }, // dark bg horiz 0x0F: { maxscreens: 0x10, boss: 0, horiz: 1, layer2: LAYER2_NONE }, 0x10: { maxscreens: 0x00, boss: 1, horiz: 1, layer2: LAYER2_BACKGROUND }, 0x11: { maxscreens: 0x20, boss: 0, horiz: 1, layer2: LAYER2_BACKGROUND }, // "weird" horiz // 0x12: { maxscreens: 0x00, boss: 0, horiz: 1, layer2: LAYER2_INTERACT }, // 0x13: { maxscreens: 0x00, boss: 0, horiz: 1, layer2: LAYER2_INTERACT }, // 0x14: { maxscreens: 0x00, boss: 0, horiz: 1, layer2: LAYER2_INTERACT }, // 0x15: { maxscreens: 0x00, boss: 0, horiz: 1, layer2: LAYER2_INTERACT }, // 0x16: { maxscreens: 0x00, boss: 0, horiz: 1, layer2: LAYER2_INTERACT }, // 0x17: { maxscreens: 0x00, boss: 0, horiz: 1, layer2: LAYER2_INTERACT }, // 0x18: { maxscreens: 0x00, boss: 0, horiz: 1, layer2: LAYER2_INTERACT }, // 0x19: { maxscreens: 0x00, boss: 0, horiz: 1, layer2: LAYER2_INTERACT }, // 0x1A: { maxscreens: 0x00, boss: 0, horiz: 1, layer2: LAYER2_INTERACT }, // 0x1B: { maxscreens: 0x00, boss: 0, horiz: 1, layer2: LAYER2_INTERACT }, // 0x1C: { maxscreens: 0x00, boss: 0, horiz: 1, layer2: LAYER2_INTERACT }, // 0x1D: { maxscreens: 0x00, boss: 0, horiz: 1, layer2: LAYER2_INTERACT }, 0x1E: { maxscreens: 0x20, boss: 0, horiz: 1, layer2: LAYER2_BACKGROUND }, // trans (layer1) horiz 0x1F: { maxscreens: 0x10, boss: 0, horiz: 1, layer2: LAYER2_NONE }, // trans (layer2) horiz }; var Y_ENTRANCES = [0x00, 0x03, 0x06, 0x08, 0x0A, 0x0B, 0x0C, 0x0E, 0x11, 0x13, 0x15, 0x16, 0x17, 0x19, 0x10, 0x10]; var X_ENTRANCES = [0x01, 0x08, 0x00, 0x0E, 0x01, 0x07, 0x00]; var VALID_FGP_BY_TILESET = { 0x0: [0, 1, 3, 4, 5, 7], // Normal 1 0x1: [ 3, 4, 5, 7], // Castle 1 0x2: [ 1, 2, 3, 4, 5, 7], // Rope 1 0x3: [ 2, 3, 4, 5, 7], // Underground 1 0x4: [ 1, 2, 3, 4, 5, 7], // Switch Palace 1 0x5: [ 4, 5, ], // Ghost House 1 0x6: [ 1, 2, 3, 4, 5, 7], // Rope 2 0x7: [0, 1, 3, 4, 5, 7], // Normal 2 0x8: [ 1, 2, 3, 4, 5, 7], // Rope 3 0x9: [ 1, 2, 3, 4, 5, 7], // Underground 2 0xA: [ 1, 2, 3, 4, 5, 7], // Switch Palace 2 0xB: [ 3, 4, 5, 7], // Castle 2 0xC: [ ], // Cloud/Forest 0xD: [ 4, 5, ], // Ghost House 2 0xE: [ 2, 3, 4, 5, 7], // Underground 3 }; var VALID_BGP_BY_LAYER2 = { 0xFFDD44: [0, 1, 2, 3, 5, 6, 7], // Clouds 0xFFEC82: [0, 2, 3, 5, 6, 7], // Bushes 0xFFEF80: [ 1, 3, 5, 6 ], // Ghost House 0xFFDE54: [0, 1, 2, 3, 5, 6, 7], // Small Hills 0xFFF45A: [ 1, 3, 6, ], // Castle 0xFFE674: [0, 1, 2, 3, 5, 6, 7], // Bonus 0xFFDAB9: [ 4, ], // Water 0xFFE8EE: [0, 1, 2, 3, 4, 5, 6, 7], // Empty/Layer 2 0xFFE7C0: [0, 1, 2, 3, 5, 6, 7], // Mountains 0xFFE103: [0, 1, 2, 3, 5, 6, 7], // Castle Pillars 0xFFDF59: [0, 1, 2, 3, 5, 6, 7], // Mountains & Clouds 0xFFE8FE: [ 1, 6, ], // Cave 0xFFD900: [ 1, ], // P. Hills 0xFFE472: [0, 1, 2, 3, 5, 6, 7], // Big Hills 0xFFE684: [ 1, 3, 5, 6, ], // Stars 0xFFF175: [0, 1, 2, 3, 5, 6 ], // Ghost Ship 0xFFDC71: [0, 1, 2, 3, 5, 6, 7], // Hills & Clouds 0x06861B: [0, 1, 2, 3, 4, 5, 6, 7], // Ghost House Exit }; var VALID_BGC_BY_LAYER2 = { 0xFFDD44: [0, 1, 2, 3, 4, 5, 6, 7], // Clouds 0xFFEC82: [0, 1, 2, 3, 4, 5, 6, 7], // Bushes 0xFFEF80: [ 3, 4, ], // Ghost House 0xFFDE54: [0, 1, 2, 3, 4, 5, 6, 7], // Small Hills 0xFFF45A: [0, 1, 2, 3, 4, 5, 6, 7], // Castle 0xFFE674: [0, 1, 2, 3, 4, 5, 6, 7], // Bonus 0xFFDAB9: [ 2, 3, 5, ], // Water 0xFFE8EE: [ 3, 5, ], // Empty/Layer 2 0xFFE7C0: [0, 1, 2, 3, 4, 5, 6, 7], // Mountains 0xFFE103: [0, 1, 2, 3, 4, 5, 6, 7], // Castle Pillars 0xFFDF59: [0, 1, 2, 3, 4, 5, 6, 7], // Mountains & Clouds 0xFFE8FE: [0, 1, 2, 3, 4, 5, 6, 7], // Cave 0xFFD900: [0, 1, 2, 3, 4, 5, 6, 7], // P. Hills 0xFFE472: [0, 1, 2, 3, 4, 5, 6, 7], // Big Hills 0xFFE684: [ 2, 3, 4, 5, ], // Stars 0xFFF175: [ 2, 3, 4, 5, ], // Ghost Ship 0xFFDC71: [0, 1, 2, 3, 4, 5, 6, 7], // Hills & Clouds 0x06861B: [0, 1, 2, 3, 4, 5, 6, 7], // Ghost House Exit }; // first element is a simple indoors/outdoors bool to // make sure indoor and outdoor bgs aren't swapped var GFX_REQ_BY_LAYER2 = { 0xFFDD44: [0, 0x19, null], // Clouds 0xFFEC82: [0, 0x19, null], // Bushes 0xFFEF80: [1, 0x0C, 4], // Ghost House 0xFFDE54: [0, 0x19, null], // Small Hills 0xFFF45A: [1, 0x1B, 0x18], // Castle (Blocks) // 0xFFE674: [1, 0x1B, null], // Bonus 0xFFDAB9: [0, 0x0D, 3], // Water // 0xFFE8EE: null, // Empty/Layer 2 0xFFE7C0: [0, 0x19, null], // Mountains 0xFFE103: [1, 0x1B, 1], // Castle Pillars 0xFFDF59: [0, 0x19, null], // Mountains & Clouds 0xFFE8FE: [1, 0x0C, 3], // Cave 0xFFD900: [0, 0x1B, null], // P. Hills 0xFFE472: [0, 0x19, null], // Big Hills 0xFFE684: [0, 0x0C, 2], // Stars // 0xFFF175: [1, 0x0C, null], // Ghost Ship 0xFFDC71: [0, 0x19, null], // Hills & Clouds // 0x06861B: null, // Ghost House Exit }; var BG_CAN_VSCROLL = { 0xFFDD44: true, 0xFFEF80: true, 0xFFF45A: true, 0xFFE7C0: true, 0xFFDF59: true, 0xFFE8FE: true, 0xFFE684: true, 0xFFF175: true, }; var UNUSED_LEVELS = [ // names and data taken from https://tcrf.net/Super_Mario_World_(SNES)/Unused_levels { layer1: 0x0302BD, layer2: 0xFFD900, sprite: 0x03C50E, name: 'Mushroom Scales' }, { layer1: 0x0304EB, layer2: 0x030464, sprite: 0x03C575, name: 'Lava Cave' }, { layer1: 0x030263, layer2: 0xFFDD44, sprite: 0x03C500, name: 'Ride Among the Clouds' }, // SMB3 1-4 ]; var SWITCH_OBJECTS = [ null, 0x8B, 0x8C, 0x8D, 0x8A ]; var SP4_SPRITES = [ { id: 0x09, sp4: null, water: 0, tide: 0, name: 'Green Parakoopa', pos: [[43, 21], [30, 22], [20, 22]], }, { id: 0x1C, sp4: null, water: 0, tide: 0, name: 'Bullet Bill', pos: [[32, 23], [32, 22], [32, 21]], }, { id: 0x0D, sp4: 0x02, water: 0, tide: 0, name: 'Bob-omb', pos: [[32, 23]], }, { id: 0x13, sp4: 0x02, water: 0, tide: 0, name: 'Spiny', pos: [[32, 23]], }, { id: 0x1B, sp4: 0x04, water: 0, tide: 0, name: 'Football', pos: [[32, 23]], }, { id: 0x1D, sp4: 0x02, water: 0, tide: 0, name: 'Bouncing Fire', pos: [[32, 23], [22, 23], [12, 23]], }, { id: 0x1F, sp4: 0x03, water: 0, tide: 0, name: 'Magikoopa', pos: [[7, 22]], }, { id: 0x26, sp4: 0x03, water: 0, tide: 0, name: 'Thwomp', pos: [[33, 14], [36, 14], [39, 14]], }, { id: 0x27, sp4: 0x03, water: 0, tide: 0, name: 'Thwimp', pos: [[14, 21], [33, 14]], }, { id: 0x28, sp4: 0x11, water: 0, tide: 0, name: 'Big Boo', pos: [[38, 21]], }, { id: 0x37, sp4: 0x11, water: 0, tide: 0, name: 'Boo', pos: [[35, 21], [14, 21], [38, 19]], }, { id: 0x3A, sp4: 0x06, water: 1, tide: 0, name: 'Urchin (Short)', pos: [[29, 21], [34, 21]], }, { id: 0x3B, sp4: 0x06, water: 1, tide: 0, name: 'Urchin (Full)', pos: [[39, 19], [34, 22]], }, { id: 0x3D, sp4: 0x06, water: 1, tide: 0, name: 'Rip Van Fish', pos: [[14, 23], [39, 21]], }, { id: 0x3F, sp4: 0x02, water: 0, tide: 0, name: 'Para-Goomba', pos: [[33, 14], [35, 15], [37, 14], [37, 15]], }, { id: 0x40, sp4: 0x02, water: 0, tide: 0, name: 'Para-Bomb', pos: [[33, 14], [35, 15], [37, 14], [37, 15]], }, { id: 0x4B, sp4: 0x02, water: 0, tide: 0, name: 'Pipe Lakitu', pos: [[35, 23]], }, { id: 0x4D, sp4: 0x09, water: 0, tide: 0, name: 'Ground Mole', pos: [[24, 23], [28, 23], [32, 23], [36, 23]], }, // { id: 0x4E, sp4: 0x09, water: 0, tide: 0, name: 'Wall Mole', pos: [[24, 25], [28, 25], [32, 25], [36, 25]], }, { id: 0x51, sp4: 0x0E, water: 0, tide: 0, name: 'Ninji', pos: [[34, 23], [35, 23], [36, 23], [37, 23]], }, // { id: 0x52, sp4: 0x11, water: 0, tide: 0, name: 'Moving Hole', pos: [[12, 24], [12, 24], [24, 24]], }, { id: 0x6E, sp4: 0x23, water: 0, tide: 0, name: 'Dino Rhino (Big)', pos: [[28, 22], [36, 22]], }, { id: 0x6F, sp4: 0x23, water: 0, tide: 0, name: 'Dino Torch (Small)', pos: [[37, 23], [34, 23], [31, 23]], }, { id: 0x70, sp4: 0x09, water: 0, tide: 0, name: 'Pokey', pos: [[37, 19], [35, 19]], }, { id: 0x71, sp4: 0x09, water: 0, tide: 0, name: 'Super Koopa (Red)', pos: [[34, 18], [24, 18]], }, { id: 0x72, sp4: 0x09, water: 0, tide: 0, name: 'Super Koopa (Yellow)', pos: [[34, 18], [24, 18]], }, { id: 0x73, sp4: 0x09, water: 0, tide: 0, name: 'Super Koopa (Feather)', pos: [[32, 23], [30, 23], [30, 23], [31, 23]], }, { id: 0x86, sp4: 0x02, water: 0, tide: 0, name: 'Wiggler', pos: [[29, 23], [27, 23], [25, 23]], }, { id: 0x90, sp4: 0x11, water: 0, tide: 0, name: 'Green Gas Bubble', pos: [[35, 18]], }, { id: 0x99, sp4: 0x0E, water: 0, tide: 0, name: 'Volcano Lotus', pos: [[36, 23], [37, 23]], }, { id: 0x9E, sp4: 0x03, water: 0, tide: 0, name: 'Ball n Chain', pos: [[32, 19]], }, { id: 0x9F, sp4: 0x20, water: 0, tide: 0, name: 'Banzai Bill', pos: [[38, 19], [41, 19]], }, { id: 0xA4, sp4: 0x05, water: 0, tide: 1, name: 'Floating Spike Ball', pos: [[36, 23], [35, 23]], }, { id: 0xA8, sp4: 0x04, water: 0, tide: 0, name: 'Blargg', pos: [[33, 24], [31, 24]], }, { id: 0xAA, sp4: 0x03, water: 0, tide: 0, name: 'Fishbone', pos: [[30, 21], [30, 22], [30, 23]], }, { id: 0xAB, sp4: 0x20, water: 0, tide: 0, name: 'Rex', pos: [[27, 22], [29, 22], [37, 22]], }, { id: 0xB0, sp4: 0x11, water: 0, tide: 0, name: 'Buddy Boo Line', pos: [[31, 21]], }, { id: 0xB2, sp4: 0x03, water: 0, tide: 0, name: 'Falling Spike', pos: [[33, 14], [35, 14], [37, 14]], }, { id: 0xBB, sp4: 0x03, water: 0, tide: 0, name: 'Moving Grey Block', pos: [[14, 24], [30, 24]], }, // SPECIAL { id: 0xBE, sp4: 0x04, water: 0, tide: 0, name: 'Swoop', pos: [[29, 21], [31, 21], [37, 14]], }, { id: 0xBF, sp4: 0x20, water: 0, tide: 0, name: 'Mega Mole', pos: [[24, 22], [30, 22], [36, 22]], }, { id: 0xC3, sp4: 0x06, water: 0, tide: 1, name: 'Porcu-Puffer', pos: [[14, 24], [30, 24], [37, 24]], }, { id: 0xC9, sp4: null, water: 0, tide: 0, name: 'Bullet Bill Generator', pos: [[39, 22], [39, 23]], }, { id: 0xCA, sp4: 0x06, water: 0, tide: 0, name: 'Torpedo Ted Generator', pos: [[30, 20]], }, { id: 0xCB, sp4: 0x11, water: 0, tide: 0, name: 'Eerie Generator', pos: [[1, 0]], }, { id: 0xCF, sp4: 0x06, water: 0, tide: 1, name: 'Dolphin Left Generator', pos: [[1, 0]], }, { id: 0xD0, sp4: 0x06, water: 0, tide: 1, name: 'Dolphin Right Generator', pos: [[1, 0]], }, { id: 0xD3, sp4: 0x09, water: 0, tide: 0, name: 'Super Koopa Generator', pos: [[1, 0]], }, // { id: 0xD4, sp4: 0x02, water: 0, tide: 0, name: 'Bubble Generator', pos: [[1, 0]], }, { id: 0xD5, sp4: 0x05, water: 0, tide: 0, name: 'Bullet Bill L/R Generator', pos: [[1, 0]], }, { id: 0xD6, sp4: null, water: 0, tide: 0, name: 'Multi Bullet Generator', pos: [[1, 0]], }, { id: 0xD7, sp4: 0x05, water: 0, tide: 0, name: 'Diagonal Bullet Generator', pos: [[1, 0]], }, { id: 0xE1, sp4: 0x11, water: 0, tide: 0, name: 'Boo Ceiling', pos: [[1, 0]], }, { id: 0xE5, sp4: 0x11, water: 0, tide: 0, name: 'Boo Cloud (SGS room2)', pos: [[1, 0]], }, { id: 0xE2, sp4: 0x11, water: 0, tide: 0, name: 'Boo Ring CCW', pos: [[26, 20], [10, 20], [39, 21]], }, { id: 0xE3, sp4: 0x11, water: 0, tide: 0, name: 'Boo Ring CW', pos: [[26, 20], [10, 20], [39, 21]], }, ]; var SPRITE_MEMORY = { 0x5F: 0x01, // 0x64: 0x01, 0x54: 0x02, 0x5E: 0x03, 0x60: 0x04, 0x9F: 0x04, 0x28: 0x05, 0x88: 0x06, 0xC5: 0x09, 0x86: 0x0A, 0x28: 0x0B, 0x90: 0x0D, 0xAE: 0x11, } var TILESET_SPECIFIC_SPRITES = [ 0x0D, 0x11, 0x13, 0x14, 0x15, 0x16, 0x18, 0x1B, 0x1D, 0x1E, 0x1F, 0x20, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2E, 0x30, 0x31, 0x32, 0x33, 0x34, 0x37, 0x38, 0x39, 0x3A, 0x3B, 0x3C, 0x3D, 0x3F, 0x40, 0x41, 0x42, 0x43, 0x44, 0x46, 0x47, 0x48, 0x49, 0x4A, 0x4B, 0x4C, 0x4D, 0x4E, 0x51, 0x52, 0x54, 0x55, 0x56, 0x57, 0x58, 0x5B, 0x5C, 0x5D, 0x5E, 0x5F, 0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67, 0x68, 0x6A, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x7A, 0x7D, 0x86, 0x87, 0x8A, 0x8B, 0x8D, 0x8F, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x97, 0x98, 0x99, 0x9A, 0x9B, 0x9C, 0x9D, 0x9E, 0x9F, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0xA6, 0xA8, 0xA9, 0xAA, 0xAB, 0xAC, 0xAD, 0xAE, 0xAF, 0xB0, 0xB2, 0xB3, 0xB4, 0xB6, 0xB7, 0xB8, 0xBA, 0xBB, 0xBC, 0xBE, 0xBF, 0xC0, 0xC2, 0xC3, 0xC4, 0xC5, 0xC6, 0xDE, 0xE0, 0xE2, 0xE3, 0x8C, 0xA0, 0xCA, 0xCB, 0xCC, 0xCD, 0xCE, 0xCF, 0xD0, 0xD1, 0xD3, 0xD4, 0xD6, 0xD7, 0xD8, 0xE1, 0xE5, 0xE6, ]; var SPRITE_SETS = [ { // on ground 0x00: { origin: [0,0], }, 0x01: { origin: [0,0], }, 0x02: { origin: [0,0], }, 0x03: { origin: [0,0], }, 0x04: { origin: [0,0], }, 0x05: { origin: [0,0], }, 0x06: { origin: [0,0], }, 0x07: { origin: [0,0], }, 0x09: { origin: [0,0], }, 0x0C: { origin: [0,0], }, 0x0D: { origin: [0,0], sp4: [0x02], }, 0x0F: { origin: [0,0], }, 0x10: { origin: [0,0], }, 0x11: { origin: [0,0], sp4: [0x04], }, 0x13: { origin: [0,0], sp4: [0x02], }, 0x1D: { origin: [0,0], sp4: [0x02], weight: 2, }, 0x2E: { origin: [0,0], sp4: [0x04], }, 0x30: { origin: [0,0], sp3: [0x12], sp4: [0x03], weight: 3, }, 0x31: { origin: [0,0], sp3: [0x12], sp4: [0x03], weight: 2, }, 0x32: { origin: [0,0], sp3: [0x12], weight: 3, }, 0x3D: { origin: [0,0], sp4: [0x06], weight: 2, }, 0x51: { origin: [0,0], sp4: [0x0E], weight: 3, }, 0x6E: { origin: [0,0], sp4: [0x23], weight: 2, }, 0x6F: { origin: [0,0], sp4: [0x23], weight: 2, }, 0x70: { origin: [0,4], sp4: [0x09], weight: 2, }, 0x73: { origin: [0,0], sp4: [0x09], weight: 2, }, 0x86: { origin: [0,0], sp4: [0x02], weight: 3, }, 0x99: { origin: [0,0], sp4: [0x09, 0x0E], weight: 2, }, 0x9A: { origin: [0,0], sp4: [0x09], }, 0xA2: { origin: [0,0], sp3: [0x24], weight: 4, }, 0xAB: { origin: [0,0], sp4: [0x20], weight: 4, }, 0xBC: { origin: [0,0], sp3: [0x12], weight: 4, }, }, { // chucks 0x46: { origin: [0,0], sp3: [0x13], sp4: [0x05], }, 0x91: { origin: [0,0], sp3: [0x13], weight: 3, }, 0x92: { origin: [0,0], sp3: [0x13], }, 0x93: { origin: [0,0], sp3: [0x13], weight: 2, }, 0x94: { origin: [0,0], sp3: [0x13], sp4: [0x06, 0x09], }, 0x97: { origin: [0,0], sp3: [0x13], sp4: [0x04, 0x0E], }, 0x98: { origin: [0,0], sp3: [0x13], sp4: [0x09, 0x0E], }, }, { // flying/swimming infinitely left 0x08: { origin: [0,0], }, 0x1C: { origin: [0,1], }, 0x38: { origin: [0,0], sp3: [0x06], sp4: [0x11] }, 0x39: { origin: [0,0], sp3: [0x06], sp4: [0x11] }, 0x9F: { origin: [1,1], sp4: [0x20], }, 0xAA: { origin: [0,0], sp4: [0x03], weight: 3, }, 0xB3: { origin: [0,0], sp3: [0x12], }, 0xC2: { origin: [0,0], sp4: [0x06], }, }, { // flying/swimming (not on ground, whatever!) 0x0A: { origin: [0,1], }, 0x0B: { origin: [0,1], }, 0x15: { origin: [0,0], sp3: [0x13], water: 1, weight: 2, }, 0x16: { origin: [0,0], sp3: [0x13], water: 1, weight: 2, }, 0x18: { origin: [0,0], sp3: [0x13], water: 1, }, 0x28: { origin: [1,1], sp4: [0x11], weight: 3, }, 0x33: { origin: [0,2], sp4: [0x03, 0x04, 0x0E, 0x22], }, 0x37: { origin: [0,0], sp4: [0x11], weight: 3, }, // 0x3A: { origin: [0,0], sp4: [0x06], }, // 0x3B: { origin: [0,0], sp4: [0x06], }, // 0x3C: { origin: [0,0], sp4: [0x06], }, 0x3F: { origin: [0,1], sp4: [0x02], weight: 2, }, 0x40: { origin: [0,0], sp4: [0x02], weight: 2, }, 0x71: { origin: [0,0], sp4: [0x09], weight: 2, }, 0x72: { origin: [0,0], sp4: [0x09], weight: 2, }, 0x90: { origin: [1,1], sp4: [0x11], }, // 0x9D: { origin: [0,0], sp3: [0x13], sp4: [0x02], weight: 3, }, 0xAF: { origin: [0,0], sp4: [0x11], weight: 2, }, 0xB0: { origin: [0,0], sp4: [0x11], weight: 3, }, 0xB6: { origin: [0,0], sp4: [0x03, 0x22], weight: 2, }, }, { // from a pipe 0x4B: { origin: [0,0], sp4: [0x02], weight: 3, }, 0x4F: { origin: [0,0], }, 0x50: { origin: [0,0], weight: 2, }, }, { // kinda... stationary stuff 0x1B: { origin: [0,0], sp4: [0x04, 0x0E], }, 0x20: { origin: [0,0], sp4: [0x03], weight: 2, }, 0x48: { origin: [0,0], sp4: [0x05], }, 0xDA: { origin: [0,0], }, 0xDB: { origin: [0,0], }, 0xDC: { origin: [0,0], }, 0xDD: { origin: [0,0], }, }, { // line-guided 0x65: { origin: [0,0], sp4: [0x05], }, 0x66: { origin: [0,0], sp4: [0x05], }, 0x67: { origin: [0,0], sp3: [0x12], }, 0x68: { origin: [0,0], sp4: [0x05], }, }, ]; var BIG_BOO_SPRITES = [ { id: 0xCB, x: 0, y: 0 }, // { id: 0xE1, x: 0, y: 0 }, { id: 0xB0 }, { id: 0xB0 }, { id: 0xB0 }, ]; var GOOD_SPRITE_TILESETS = [0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0xA, 0xC, 0xE]; var QUESTION_BLOCK_IDS = [0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38]; var HAMMER_CAN_KILL = [ // castle enemies 0x26, 0x27, // water enemies 0xC3, 0x44, 0x3A, 0x3B, 0x3C, // ghost enemies 0x37, 0x38, 0x39, 0x28, // bone enemies 0xAA, 0x30, 0x31, 0x32, // other 0xBF, ]; var CI2_ROOM_OFFSETS = [ [0x06, 0x08, 0x0A], // room 1 [0x0C, 0x0E, 0x10], // room 2 [0x00, 0x02], // room 3 ]; var CI2_ALL_OFFSETS = $.map(CI2_ROOM_OFFSETS, function(x){ return x; }); var CI2_LAYER_OFFSETS = { 'layer1': snesAddressToOffset(0x05DB08), // 'layer2': snesAddressToOffset(0x05DB2C), 'sprite': snesAddressToOffset(0x05DB1A), }; var SUBLEVEL_DUPLICATES = { 0x0DE: 0x0F9, // dgh room 2 0x0E1: 0x0E0, // vfort room 2 0x0EC: 0x013, // dsh room 1 0x0EE: 0x013, 0x0F2: 0x0ED, // dsh room 2 0x0F6: 0x022, // ci1 copies 0x0F5: 0x022, 0x0D1: 0x022, 0x0D0: 0x022, 0x1FB: 0x107, // vgh room 1 0x1D9: 0x114, // bgh room 1 0x1DB: 0x1DC, // bgh left room 0x1E8: 0x11D, // fgh room 1 0x1E9: 0x11D, 0x1C5: 0x1C4, // gnarly room 2 }; var DONT_SHUFFLE_EXITS = [ 0x11D, ]; var STAR_PATTERNS = [ [ // credit: Dotsarecool " x xxxx xxxx x ", "x x x x x x x x x ", "x xx x xx x ", "x x x ", "x xx x ", "x x x x ", " x xxxxxx x ", ], [ // credit: Dotsarecool " ", " xx xx ", "xx x xx xx xx x", " x xx x xx x x", " x xxxx xxxx x ", " xx xx xx xx ", " xxxxx ", ], [ // credit: Dotsarecool " x x x xx xx x ", " x x x x x x x x x x ", " x x x x x x x x x x ", " xx xxx xx xx xxx ", " x x x x x x x x ", " x x x x x x x x ", " x x x x x x x x ", ], [ // credit: Dotsarecool " x x xxxxxxxx ", " x x xxx x x ", " xxxx x xxx x ", " xx x x x x xxx ", " x x xx x ", " xx x x x x ", " x xxxx xxx xx ", ], [ // credit: Dotsarecool " x x x x ", "x x x x x x x x", "x xxxxx xxx xxxxx x", "x xxx x x xxx x", "x xxx x x xxx x", "x x x x x x x x", " x xxx x ", ], [ " x xxxx ", " x x ", " x x ", " x xxxxxx ", " x xx ", " x x ", " x xxx ", ], ]; var KEY_CAN_REPLACE = [ // koopas and goombas (not flying to avoid dropping in a pit) 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x09, 0x0C, 0xBD, 0x0F, 0x10, 0xDA, 0xDB, 0xDC, 0xDD, 0xDF, // chucks 0x91, 0x92, 0x93, 0x94, 0x95, 0x97, 0x98, // other enemies (some tileset specific) 0x0D, 0x11, 0x13, 0x26, 0x27, 0x46, 0x4E, 0x51, 0x6E, 0x6F, 0x70, 0x71, 0x72, 0x73, 0x86, 0x99, 0x9F, 0xAB, 0xBE, 0xBF, 0x3D, // powerups 0x74, 0x75, 0x76, 0x77, 0x78, // special case - bubbles and exploding blocks 0x9D, 0x4C, // other 0x2C, 0x2D, 0x2F, ]; var KEY_REPLACEMENTS = [ // koopas and goombas 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x09, 0x0C, 0xBD, 0x0F, 0x10, 0xDA, 0xDB, 0xDC, 0xDD, 0xDF, // powerups 0x78, // other 0x21, ]; var AUTOSCROLL_ROOMS = [ // good rooms 0x011, 0x111, 0x12D, 0x1CD, // maybe less good rooms? 0x126, 0x1CC, 0x01B, 0x11C, ]; // priority from greatest (most likely to be replaced) to least var REPLACEABLE_SPRITES = [ 0x02, 0x03, 0x04, 0x05, 0x07, 0x06, 0xAB, 0x1D, 0x4F, 0x50, 0x48, 0x22, 0x23, 0x24, 0x25, 0x11, 0x13, 0x15, 0x16, 0x27, 0x31, 0x38, 0x3D, 0x68, 0x6F, 0x71, 0x72, 0x4C, 0x33, 0xBC, 0x93, 0xB3, 0xAA, 0xAB, 0xC2, 0x6D, ]; var STATIC_WATER_TILES = [ 0x01, 0x18, 0x19, ]; var NO_WATER_STAGES = [ // do not add water to these stages 0x01A, 0x0DC, 0x111, 0x1CF, 0x134, 0x1F8, 0x0C7, 0x1E3, 0x1E2, 0x1F2, 0x0D3, 0x0CC, // this is blacklisted in the first pass (water bowser) 0x1C7, // do not remove water from these stages ]; var BOSSES = { 0x29: 'koopa kid', 0xA9: 'reznor', 0xA0: 'bowser', 0xC5: 'big boo', }; var TIME_VALUES = [0, 200, 300, 400]; var VSCROLL_TYPE = ['no-v', 'always', 'locked', 'no-v/h']; var LAYER3_TYPE = ['none', 'tide', 'mondo', '???'];
(function($) { //Mobile Dropdown Navigation $('#menu-main-navigation').tinyNav({header: 'Navigation'}); //End //Home-Page Boxes Ordering $('.cell--bk-widget').insertAfter('.cell--square:eq(3)'); $('.cell--promo-bkg').insertAfter('.cell--square:eq(4)'); $('.cell--square').not(':first').css('height', '300px'); $('.cell--square:eq(5), .cell--square:eq(6)').css('margin-top', '-4em'); $('.cell__square-banner:eq(0), .cell__square-banner:eq(1)').css('margin-top', '3em'); //End // Our Places - Side Widget $('.widget').on('click touch', '#our-places-btn', function() { $('.widget').toggleClass('is-open'); }); //End // Single Room Slider $('.flexslider').flexslider({ animation: "slide", initDelay: 1000 }); //End // Gallery Pages $('#gallery').magnificPopup({ delegate: 'a', // child items selector, by clicking on it popup will open type: 'image', gallery:{ enabled:true } }); //End //Our Places PopUp $('.ourPlaces-popup-btn').magnificPopup({ type:'inline', midClick: true }); //End //Newsletter PopUp $('.newsLetter-popup-btn').magnificPopup({ type:'inline', closeOnBgClick: false, midClick: true }); //End //RESDIARY BOOKING food and drink page //The Set PopUp $('.resDiary-popup-btn').magnificPopup({ type:'inline', closeOnBgClick: false, midClick: true }); //End var endDate = new Date(); //Booking Widget End Datepicker $('.datepicker-end').pickadate({ format: 'dd/mmm/yy', formatSubmit: 'mm/dd/yyyy', min: endDate, hiddenName: true, onOpen: function(){ //Get date set in 'Arrival' box var dateObject = $('.datepicker-start').pickadate('get','select'); //Increase the date by 1 day var nextDate = new Date(dateObject.year, dateObject.month, (dateObject.date + 1)); //Assign to the 'Departure' input this.set('select', nextDate); } }); //Booking Widget Start Datepicker $('.datepicker-start').pickadate({ format: 'dd/mmm/yy', formatSubmit: 'mm/dd/yyyy', hiddenName: true, min: endDate }); //End //Neighbourhood Filter var $allSquares = $('.square-group').find('.all'); $("#select--areas, #select--types").on('change',function() { var $a = $("#select--areas").val(), $b = $("#select--types").val(); $allSquares.hide().filter("." + $a + '.' + $b).show(); }); //End })(jQuery); // Booking Widget function bookOnlineUrl() { var formUrl = document.getElementById('form-url').value; var checkInVal = document.getElementById('start_hidden').value; var checkOutVal = document.getElementById('end_hidden').value; var guestsVal = document.getElementsByName('guests')[0].value; var areaVal = document.getElementById('area').value; var propertyTypeVal = document.getElementById('propertyType').value; var checkIn = checkInVal; var checkOut = checkOutVal; var newUrl = formUrl + '/search?' + 'in=' + checkIn + '&out=' + checkOut + '&guests=' + guestsVal + '&area=' + areaVal + '&propertytype=' + propertyTypeVal; window.open(newUrl); return false; } //End //Newsletter Validation function validate_signup(frm) { var emailAddress = frm.Email.value; var errorString = ''; if (emailAddress === '' || emailAddress.indexOf('@') == -1) { errorString = 'Please enter your email address'; } var els = frm.getElementsByTagName('input'); for (var i = 0; i < els.length; i++) { if (els[i].className == 'text') { if (els[i].value === '') { errorString = 'Please complete all required fields.'; } } } var isError = false; if (errorString.length > 0) isError = true; if (isError) alert(errorString); return !isError; } //End //SVG Fallback using Modernizr (IE8 and Android <=2.3) if (!Modernizr.svg) { var imgs = document.querySelectorAll('.logo-svg'),//document.getElementsByClassName doesn't work on IE8 svgExtension = /.*\.svg$/; if(imgs[0].src.match(svgExtension)) { imgs[0].src = imgs[0].src.slice(0, -3) + 'png'; } } //End
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M1 3.5h2.02C1.13 5.82 0 8.78 0 12s1.13 6.18 3.02 8.5H1V22h5v-5H4.5v2.91c-1.86-2.11-3-4.88-3-7.91s1.14-5.79 3-7.91V7H6V2H1v1.5zm12.85 8.12-2.68-5.37c-.37-.74-1.27-1.04-2.01-.67-.75.38-1.05 1.28-.68 2.02l4.81 9.6-3.24.8c-.33.09-.59.33-.7.66L9 19.78l6.19 2.25c.5.17 1.28.02 1.75-.22l5.51-2.75c.89-.45 1.32-1.48 1-2.42l-1.43-4.27c-.27-.82-1.04-1.37-1.9-1.37h-4.56c-.31 0-.62.07-.89.21l-.82.41" }), 'SwipeVertical'); exports.default = _default;
var searchData= [ ['detailcontroller',['DetailController',['../classDetailController.html',1,'']]], ['detailcontroller_2ephp',['detailController.php',['../detailController_8php.html',1,'']]], ['detailmodel_2ephp',['detailModel.php',['../detailModel_8php.html',1,'']]], ['detailsitemodel_2ephp',['DetailSiteModel.php',['../DetailSiteModel_8php.html',1,'']]], ['detailsiteremplissage_2ephp',['DetailSiteRemplissage.php',['../DetailSiteRemplissage_8php.html',1,'']]], ['detailview_2ephp',['detailView.php',['../detailView_8php.html',1,'']]], ['disconnect',['Disconnect',['../classArcheoPDO.html#a872bf37047ac3c88f223ee09e0464d28',1,'ArcheoPDO']]], ['displaydeconnexion',['DisplayDeconnexion',['../classUserController.html#a3236e398d5a6dacd18740fdedc8c3f29',1,'UserController']]], ['displaydetailview',['DisplayDetailView',['../classDetailController.html#a9f86c923984a8a14890a5b5a74d6747c',1,'DetailController']]], ['displaymapview',['displayMapView',['../classMap.html#a071b0a13bf443b369d8f14567ac49f1f',1,'Map']]], ['displayresultsearchview',['DisplayResultSearchView',['../classSearchController.html#a68ab90cf69065e355f8b9e9e023ad368',1,'SearchController\DisplayResultSearchView()'],['../classSearchModel.html#ad3a49bd5b6df2acd84cf3ff4f2568cb3',1,'SearchModel\DisplayResultSearchView()']]], ['displaysearchview',['DisplaySearchView',['../classSearchController.html#a79cce4afdc955c3bbe507fef15f9cfcf',1,'SearchController']]], ['displaysitesview',['DisplaySitesView',['../classSitesController.html#a816b3be90b55f6ab00001a7719beb6db',1,'SitesController']]], ['displaystatsview',['DisplayStatsView',['../classStats.html#a8283b7e12c9c60c298a4407212204494',1,'Stats']]] ];
var Employee = require("../domain/employee"); export default class EmployeeService { constructor() {} GetUser(loginName, passWord) { var model = new Employee(); model.LoginName = loginName; model.PassWord = passWord; return model; } }
describe("FizzBuzz", function() { var fizzBuzz; beforeEach(function() { fizzBuzz = new FizzBuzz(); }); it("knows that 3 is divisible by 3", function() { expect(fizzBuzz.isDivisibleByThree(3)).toBe(true); }); it("knows that 1 is not divisible by 3", function() { expect(fizzBuzz.isDivisibleByThree(1)).toBe(false); }); it("knows that 5 is divisible by 5", function() { expect(fizzBuzz.isDivisibleByFive(5)).toBe(true); }) it("knows that 1 is not divisible by 5", function() { expect(fizzBuzz.isDivisibleByFive(1)).toBe(false); }) it("knows that 15 is divisible by 15", function() { expect(fizzBuzz.isDivisibleByFifteen(15)).toBe(true); }) it("knows that 1 is not divisible by 15", function() { expect(fizzBuzz.isDivisibleByFifteen(1)).toBe(false); }) describe("playing will return", function(){ it("1", function() { expect(fizzBuzz.play(1)).toEqual(1); }); it("Fizz", function() { expect(fizzBuzz.play(3)).toEqual("Fizz"); }); it("Buzz", function() { expect(fizzBuzz.play(5)).toEqual("Buzz"); }); it("FizzBuzz", function() { expect(fizzBuzz.play(15)).toEqual("FizzBuzz"); }) }) });
(function() { var CopyDialog, Dialog, fs, path, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; path = require('path'); fs = require('fs-plus'); Dialog = require('./dialog'); module.exports = CopyDialog = (function(_super) { __extends(CopyDialog, _super); function CopyDialog(initialPath) { this.initialPath = initialPath; CopyDialog.__super__.constructor.call(this, { prompt: 'Enter the new path for the duplicate.', initialPath: atom.project.relativize(this.initialPath), select: true, iconClass: 'icon-arrow-right' }); } CopyDialog.prototype.onConfirm = function(newPath) { var activeEditor, error, repo; newPath = atom.project.resolve(newPath); if (!newPath) { return; } if (this.initialPath === newPath) { this.close(); return; } if (!this.isNewPathValid(newPath)) { this.showError("'" + newPath + "' already exists."); return; } activeEditor = atom.workspace.getActiveEditor(); if ((activeEditor != null ? activeEditor.getPath() : void 0) !== this.initialPath) { activeEditor = null; } try { if (fs.isDirectorySync(this.initialPath)) { fs.copySync(this.initialPath, newPath); } else { fs.copy(this.initialPath, newPath, function() { return atom.workspace.open(newPath, { activatePane: true, initialLine: activeEditor != null ? activeEditor.getCursor().getBufferRow() : void 0, initialColumn: activeEditor != null ? activeEditor.getCursor().getBufferColumn() : void 0 }); }); } if (repo = atom.project.getRepo()) { repo.getPathStatus(this.initialPath); repo.getPathStatus(newPath); } return this.close(); } catch (_error) { error = _error; return this.showError("" + error.message + "."); } }; CopyDialog.prototype.isNewPathValid = function(newPath) { var newStat, oldStat; try { oldStat = fs.statSync(this.initialPath); newStat = fs.statSync(newPath); return this.initialPath.toLowerCase() === newPath.toLowerCase() && oldStat.dev === newStat.dev && oldStat.ino === newStat.ino; } catch (_error) { return true; } }; return CopyDialog; })(Dialog); }).call(this);
import HttpServer from './HttpServer.js' import LambdaFunctionPool from './LambdaFunctionPool.js' export default class Lambda { #httpServer = null #lambdas = new Map() #lambdaFunctionNamesKeys = new Map() #lambdaFunctionPool = null constructor(serverless, options, v3Utils) { if (v3Utils) { this.log = v3Utils.log this.progress = v3Utils.progress this.writeText = v3Utils.writeText this.v3Utils = v3Utils } this.#httpServer = new HttpServer(options, this, v3Utils) this.#lambdaFunctionPool = new LambdaFunctionPool( serverless, options, v3Utils, ) } _create(functionKey, functionDefinition) { this.#lambdas.set(functionKey, functionDefinition) this.#lambdaFunctionNamesKeys.set(functionDefinition.name, functionKey) } create(lambdas) { lambdas.forEach(({ functionKey, functionDefinition }) => { this._create(functionKey, functionDefinition) }) } get(functionKey) { const functionDefinition = this.#lambdas.get(functionKey) return this.#lambdaFunctionPool.get(functionKey, functionDefinition) } getByFunctionName(functionName) { const functionKey = this.#lambdaFunctionNamesKeys.get(functionName) return this.get(functionKey) } listFunctionNames() { const functionNames = Array.from(this.#lambdaFunctionNamesKeys.keys()) return functionNames } listFunctionNamePairs() { const funcNamePairs = Array.from(this.#lambdaFunctionNamesKeys).reduce( (obj, [key, value]) => Object.assign(obj, { [key]: value }), // Be careful! Maps can have non-String keys; object literals can't. {}, ) return funcNamePairs } start() { return this.#httpServer.start() } // stops the server stop(timeout) { return this.#httpServer.stop(timeout) } cleanup() { return this.#lambdaFunctionPool.cleanup() } }
/** * Copyright 2013-present, Novivia, Inc. * All rights reserved. */ import {ApplicationError} from "../../types/errors"; import {parseErrorStack} from "../"; describe( "parseErrorStack", () => { it( "should work on native errors", () => { const parsedStack = parseErrorStack( (new TypeError("RegularTypeError")).stack, ); expect(parsedStack).toBeInstanceOf(Array); expect(parsedStack.length).toBeGreaterThanOrEqual(1); }, ); it( "should work on custom errors", () => { const parsedStack = parseErrorStack( (new ApplicationError("error1")).stack, ); expect(parsedStack).toBeInstanceOf(Array); expect(parsedStack.length).toBeGreaterThanOrEqual(1); }, ); }, );
import { assert } from 'chai'; import getGitHubEventHeader from './getGitHubEventHeader'; describe('getGitHubEventHeader', () => { it('should return value of header X-GitHub-Event', () => { const result = getGitHubEventHeader({ 'X-GitHub-Event': 'foo', }); assert.deepEqual(result, 'foo'); }); it('should return value of header x-github-event', () => { const result = getGitHubEventHeader({ 'x-github-event': 'foo', }); assert.deepEqual(result, 'foo'); }); it('should return value of header X-GITHUB-EVENT', () => { const result = getGitHubEventHeader({ 'X-GITHUB-EVENT': 'foo', }); assert.deepEqual(result, 'foo'); }); });
import _ from 'lodash' // eslint-disable-line import moment from 'moment' import Backbone from 'backbone' import {smartSync} from 'fl-server-utils' const dbUrl = process.env.DATABASE_URL if (!dbUrl) console.log('Missing process.env.DATABASE_URL') export default function createStripeCustomer(User) { class StripeCustomer extends Backbone.Model { url = `${dbUrl}/stripe_customers` schema = () => ({ stripeId: 'Text', createdDate: 'DateTime', user: () => ['belongsTo', User], }) defaults() { return {createdDate: moment.utc().toDate()} } } StripeCustomer.prototype.sync = smartSync(dbUrl, StripeCustomer) return StripeCustomer }
'use strict'; angular.module('ngGcBaseAppService', [ 'ngGcHttpProviderConfig', 'ngGcLocationProviderConfig', 'ngGcRavenInitializer', 'ngGcLogInitializer', 'ngGcGaInitializer', 'ngGcRavenConfigService', 'ngGcExceptionHandlerProviderConfig' ]);
module.exports = require("npm:dashdash@1.14.1/lib/dashdash.js");
$(function() { $('.api-call form').each(function() { $(this).submit(function() { var urlparams = {} $(this).siblings('.urlparam').each(function() { urlparams[$(this).attr('name')] = $(this).val(); }); var resultsPre = $(this).siblings('.api-call-results:first'); var action = $.tmpl($(this).attr('action'), urlparams).text(); var url = window.location.protocol + '//' + window.location.host + action; var method = $(this).attr('method').toUpperCase(); var oauth_params = {}; var form_params = OAuth.decodeForm($(this).serialize()); for (var p = 0; p < form_params.length; p++) { oauth_params[form_params[p][0]] = form_params[p][1]; } oauth_params.oauth_version = '1.0'; oauth_params.oauth_consumer_key = $('#oauth-consumer').val(); oauth_params.oauth_timestamp = OAuth.timestamp(); oauth_params.oauth_nonce = OAuth.nonce(8); oauth_params.oauth_signature_method = 'HMAC-SHA1'; var oauth_message = { method: method, action: url, parameters: oauth_params }; var oauth_user = { consumerSecret: $('#oauth-secret').val() } OAuth.SignatureMethod.sign(oauth_message, oauth_user); var options = { url: url, complete: function(xhr) { var results = xhr.status + ' ' + xhr.statusText + '\n' + xhr.responseText; var prettyResults = results; var regex = /url": "([\w\-\\\/\.]+)"/g; link = regex.exec(results); while (link != null) { var url = link[1]; prettyResults = prettyResults.replace(url, '<a href="' + url.replace(/\\\//g, '/') + '" target="_blank">' + url + '</a>'); link = regex.exec(results); } resultsPre.html(prettyResults); }, headers: { 'Authorization': OAuth.getAuthorizationHeader('', oauth_message.parameters), }, }; if (method == 'POST') { options.dataType = 'json'; options.iframe = true; /* Can't send Authorization header with iframe POST. */ options.data = oauth_message.parameters; } $(this).ajaxSubmit(options); return false; }); }); });
/* * @name Distance 2D * @description Move the mouse across the image to obscure * and reveal the matrix. Measures the distance from the mouse * to each circle and sets the size proportionally. */ let max_distance; function setup() { createCanvas(710, 400); noStroke(); max_distance = dist(0, 0, width, height); } function draw() { background(0); for (let i = 0; i <= width; i += 20) { for (let j = 0; j <= height; j += 20) { let size = dist(mouseX, mouseY, i, j); size = (size / max_distance) * 66; ellipse(i, j, size, size); } } }
// Generated by CoffeeScript 1.6.3 (function() { var Backbone, Project, RESTController, app, async, bootstrap, express, kb, _ref, _ref1, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; Backbone = require('backbone'); async = require('async'); if (typeof window !== "undefined" && window !== null) { kb = require('knockback'); Project = (function(_super) { __extends(Project, _super); function Project() { _ref = Project.__super__.constructor.apply(this, arguments); return _ref; } Project.prototype.urlRoot = '/projects'; Project.prototype.sync = require('backbone-http').sync(Project); return Project; })(Backbone.Model); window.AppViewModel = (function() { function AppViewModel() { var _this = this; this.projects = kb.collectionObservable(new Backbone.Collection()); Project.find({ $limit: 3, $sort: '-name' }, function(err, models) { return _this.projects.collection().reset(models); }); } AppViewModel.prototype.onSave = function(vm) { return vm.model().save(function() {}); }; return AppViewModel; })(); } if (typeof window === "undefined" || window === null) { express = require('express'); app = express(); app.use(express.bodyParser()); app.use(express["static"](__dirname)); app.get('/', function(req, res) { return res.sendfile('./index.html'); }); app.listen(3000); Project = (function(_super) { __extends(Project, _super); function Project() { _ref1 = Project.__super__.constructor.apply(this, arguments); return _ref1; } Project.prototype.urlRoot = 'mongodb://localhost:27017/demo/projects'; Project.prototype.sync = require('backbone-mongo').sync(Project); return Project; })(Backbone.Model); RESTController = require('backbone-rest'); new RESTController(app, { model_type: Project, route: '/projects' }); bootstrap = function(index, callback) { return Project.findOrCreate({ index: index, name: "Project " + index }, callback); }; async.each([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], bootstrap, function() { return Project.find({ $limit: 5, $sort: 'name' }, function(err, models) { var model, _i, _len, _results; _results = []; for (_i = 0, _len = models.length; _i < _len; _i++) { model = models[_i]; _results.push(console.log("find: " + (model.get('name')))); } return _results; }); }); } }).call(this);
const Speech = require('@google-cloud/speech'); const record = require('node-record-lpcm16'); const config = require('../config'); const options = { config: { // Configure these settings based on the audio you're transcribing encoding: 'LINEAR16', sampleRate: 16000, languageCode: 'fi-FI', }, }; module.exports.listen = function listen() { // Instantiates a client const speech = Speech({ projectId: config.google.speech.projectId, keyFilename: config.google.credentialsFile, }); return new Promise((resolve, reject) => { // Create a recognize stream const recognizeStream = speech.createRecognizeStream(options) .on('error', reject) .on('data', (data) => { if (data.endpointerType === 'ENDPOINTER_EVENT_UNSPECIFIED') { resolve(data.results); record.stop(); } }); // Start recording and send the microphone input to the Speech API record.start({ sampleRate: 16000 }).pipe(recognizeStream); }); };
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ //@ts-check 'use strict'; /** * @type {{ load: (modules: string[], resultCallback: (result, configuration: object) => any, options: object) => unknown }} */ const bootstrapWindow = (() => { // @ts-ignore (defined in bootstrap-window.js) return window.MonacoBootstrapWindow; })(); bootstrapWindow.load(['vs/code/electron-browser/issue/issueReporterMain'], function (issueReporter, configuration) { issueReporter.startup(configuration); }, { forceEnableDeveloperKeybindings: true, disallowReloadKeybinding: true });
import { VISITOR_KEYS } from './symbols' import fromHtmlAttribute from './fromHtmlAttribute' const HTML_ELEMENT_PROPERTIES = ['tagName', 'ownerDocument', 'textContent'] class HTMLElementNode { static [VISITOR_KEYS] = ['childNodes', 'attributes'] constructor(originalNode) { this.originalNode = originalNode this.childNodes = originalNode.childNodes ? Array.from(originalNode.childNodes).map(childNode => fromHtmlElement(childNode), ) : null this.attributes = originalNode.attributes ? Array.from(originalNode.attributes).map(attribute => fromHtmlAttribute(attribute), ) : null HTML_ELEMENT_PROPERTIES.forEach(property => { this[property] = originalNode[property] }) } } function fromHtmlElement(htmlNode) { return new HTMLElementNode(htmlNode) } export default fromHtmlElement
"use strict" var expect = require('chai').expect; var mapper = require('../assets/js/lib/template/mapper'); //===================================================== //============================= We will test the stores //===================================================== var mokeModel = { attributes: { firstName: { type: 'String', required: true, maxLength: 40, minLength: 4, }, lastName: 'String', email: { type: 'email', required: true, unique: true }, age: { type: 'integer', min: 18 }, city:"string" } } describe("models mapper", function() { // log the file you are working on describe("waterLine 2 BackBone", function() { //log the function it("using moke model", function(){ var bbModel = mapper("mokeModel",mokeModel); // http://backbonejs.org/#Model-attributes expect(true).to.be.true; }) //log the action around the function you are trying to test }); });
'use strict'; var path = require('path'); var gulp = require('gulp'); var eslint = require('gulp-eslint'); var excludeGitignore = require('gulp-exclude-gitignore'); var mocha = require('gulp-mocha'); var istanbul = require('gulp-istanbul'); var nsp = require('gulp-nsp'); var plumber = require('gulp-plumber'); gulp.task('static', function () { return gulp.src('**/*.js') .pipe(excludeGitignore()) .pipe(eslint({ rules: { "linebreak-style": "off", "indent": ["error", 4] } })) .pipe(eslint.format()) .pipe(eslint.failAfterError()); }); gulp.task('nsp', function (cb) { nsp({package: path.resolve('package.json')}, cb); }); gulp.task('pre-test', function () { return gulp.src('generators\**\*.js') .pipe(excludeGitignore()) .pipe(istanbul({ includeUntested: true })) .pipe(istanbul.hookRequire()); }); gulp.task('test', ['pre-test'], function (cb) { var mochaErr; gulp.src('test/**/*.js') .pipe(plumber()) .pipe(mocha({reporter: 'spec'})) .on('error', function (err) { mochaErr = err; }) .pipe(istanbul.writeReports()) .on('end', function () { cb(mochaErr); }); }); gulp.task('watch', function () { gulp.watch(['generators\**\*.js', 'test/**'], ['test']); }); gulp.task('prepublish', ['nsp']); gulp.task('default', [/*'static',*/ 'test']);
/** * CORS middleware for koa2 * * @param {Object} [options] * - {String|Function(ctx)} origin `Access-Control-Allow-Origin`, default is request Origin header * - {Array} exposeHeaders `Access-Control-Expose-Headers` * - {String|Number} maxAge `Access-Control-Max-Age` in seconds * - {Boolean} credentials `Access-Control-Allow-Credentials` * - {Array} allowMethods `Access-Control-Allow-Methods`, default is ['GET', 'PUT', 'POST', 'DELETE', 'HEAD', 'OPTIONS'] * - {Array} allowHeaders `Access-Control-Allow-Headers` * @return {Function} * @api public */ module.exports = function crossOrigin(options = {}) { const defaultOptions = { allowMethods: ['GET', 'PUT', 'POST', 'DELETE', 'HEAD', 'OPTIONS'], }; // set defaultOptions to options for (let key in defaultOptions) { if (!Object.prototype.hasOwnProperty.call(options, key)) { options[key] = defaultOptions[key]; } } return async function (ctx, next) { let origin; if (typeof options.origin === 'function') { origin = options.origin(ctx); } else { origin = options.origin || ctx.get('Origin') || '*'; } if (!origin) { return await next(); } // Access-Control-Allow-Origin ctx.set('Access-Control-Allow-Origin', origin); if (ctx.method === 'OPTIONS') { // Preflight Request if (!ctx.get('Access-Control-Request-Method')) { return await next(); } // Access-Control-Max-Age if (options.maxAge) { ctx.set('Access-Control-Max-Age', String(options.maxAge)); } // Access-Control-Allow-Credentials if (options.credentials === true) { // When used as part of a response to a preflight request, // this indicates whether or not the actual request can be made using credentials. ctx.set('Access-Control-Allow-Credentials', 'true'); } // Access-Control-Allow-Methods if (options.allowMethods) { ctx.set('Access-Control-Allow-Methods', options.allowMethods.join(',')); } // Access-Control-Allow-Headers if (options.allowHeaders) { ctx.set('Access-Control-Allow-Headers', options.allowHeaders.join(',')); } else { ctx.set('Access-Control-Allow-Headers', ctx.get('Access-Control-Request-Headers')); } ctx.status = 204; // No Content } else { // Request // Access-Control-Allow-Credentials if (options.credentials === true) { if (origin === '*') { // `credentials` can't be true when the `origin` is set to `*` ctx.remove('Access-Control-Allow-Credentials'); } else { ctx.set('Access-Control-Allow-Credentials', 'true'); } } // Access-Control-Expose-Headers if (options.exposeHeaders) { ctx.set('Access-Control-Expose-Headers', options.exposeHeaders.join(',')); } try { await next(); } catch (err) { throw err; } } }; };
/** * @author Vadim Semenov <i@sedictor.ru> * @date 10/12/12 * @time 1:24 PM * @description LogLog algorithm implementation * @url http://algo.inria.fr/flajolet/Publications/DuFl03-LNCS.pdf * @license MIT, see LICENSE-MIT.md */ function generateWords(count) { var result = []; while (count > 0) { var word = ''; for (var j = 0; j < (parseInt(Math.random() * (8 - 1)) + 1); j++) { // from 1char to 8chars word += String.fromCharCode(parseInt(Math.random() * (122 - 97)) + 97); // a-z } for (var i = 0; i < Math.random() * 100; i++) { result.push(word); count--; } } return result; } function cardinality(arr) { var t = {}, r = 0; for (var i = 0, l = arr.length; i < l; i++) { if (!t.hasOwnProperty(arr[i])) { t[arr[i]] = 1; r++; } } return r; } function LogLog(arr) { var HASH_LENGTH = 32, // bites HASH_K = 5; // HASH_LENGTH = 2 ^ HASH_K /** * Jenkins hash function * * @url http://en.wikipedia.org/wiki/Jenkins_hash_function * * @param {String} str * @return {Number} Hash */ function hash(str) { var hash = 0; for (var i = 0, l = str.length; i < l; i++) { hash += str.charCodeAt(i); hash += hash << 10; hash ^= hash >> 6; } hash += hash << 3; hash ^= hash >> 6; hash += hash << 16; return hash; } /** * Offset of first 1-bit * * @example 00010 => 4 * * @param {Number} bites * @return {Number} */ function scan1(bites) { if (bites == 0) { return HASH_LENGTH - HASH_K; } var offset = parseInt(Math.log(bites) / Math.log(2)); offset = HASH_LENGTH - HASH_K - offset; return offset; } /** * @param {String} $bites * @param {Number} $start >=1 * @param {Number} $end <= HASH_LENGTH * * @return {Number} slice of $bites */ function getBites(bites, start, end) { var r = bites >> (HASH_LENGTH - end); r = r & (Math.pow(2, end - start + 1) - 1); return r; } var M = []; for (i = 0, l = arr.length; i < l; i++) { var h = hash(arr[i]), j = getBites(h, 1, HASH_K) + 1, k = getBites(h, HASH_K + 1, HASH_LENGTH); k = scan1(k); if (typeof M[j] == 'undefined' || M[j] < k) { M[j] = k; } } var alpha = 0.77308249784697296; // (Gamma(-1/32) * (2^(-1/32) - 1) / ln2)^(-32) var E = 0; for (var i = 1; i <= HASH_LENGTH; i++) { if (typeof M[i] != 'undefined') { E += M[i]; } } E /= HASH_LENGTH; E = alpha * HASH_LENGTH * Math.pow(2, E); return parseInt(E); } var words = generateWords(1000000); console.log("Number of words"); console.log(words.length); console.log("------\nPrecision") var s = (new Date()).getTime(); console.log(cardinality(words)); console.log('time:', (new Date()).getTime() - s + 'ms'); console.log("------\nLogLog") var s = (new Date()).getTime(); console.log(LogLog(words)); console.log('time:', (new Date()).getTime() - s + 'ms');
/*! * Start Bootstrap - Grayscale Bootstrap Theme (http://startbootstrap.com) * Code licensed under the Apache License v2.0. * For details, see http://www.apache.org/licenses/LICENSE-2.0. */ // jQuery to collapse the navbar on scroll $(window).scroll(function() { if ($(".navbar").offset().top > 50) { $(".navbar-fixed-top").addClass("top-nav-collapse"); } else { $(".navbar-fixed-top").removeClass("top-nav-collapse"); } }); // jQuery for page scrolling feature - requires jQuery Easing plugin $(function() { $('a.page-scroll').bind('click', function(event) { var $anchor = $(this); $('html, body').stop().animate({ scrollTop: $($anchor.attr('href')).offset().top }, 1500, 'easeInOutExpo'); event.preventDefault(); }); }); // jQuery for page scrolling feature - requires jQuery Easing plugin for the submenu in drop downs $(function() { $('a.page-scroll-submenu').bind('click', function(event) { var $anchor = $(this); $('html, body').stop().animate({ scrollTop: $($anchor.attr('href')).offset().top }, 1500, 'easeInOutExpo'); event.preventDefault(); }); }); // Closes the Responsive Menu on Menu Item Click $('.navbar-collapse ul li a').click(function() { $('.navbar-toggle:visible').click(); }); // Google Maps Scripts // When the window has finished loading create our google map below google.maps.event.addDomListener(window, 'load', init); function init() { // Basic options for a simple Google Map // For more options see: https://developers.google.com/maps/documentation/javascript/reference#MapOptions var mapOptions = { // How zoomed in you want the map to start at (always required) zoom: 16, // The latitude and longitude to center the map (always required) center: new google.maps.LatLng(46.233755, 6.055636), // CERN // Disables the default Google Maps UI components disableDefaultUI: true, scrollwheel: false, draggable: false, // How you would like to style the map. // This is where you would paste any style found on Snazzy Maps. styles: [ { "featureType": "all", "elementType": "all", "stylers": [ { "invert_lightness": true }, { "saturation": 10 }, { "lightness": 30 }, { "gamma": 0.5 }, { "hue": "#435158" } ] } ] }; // Get the HTML DOM element that will contain your map // We are using a div with id="map" seen below in the <body> var mapElement = document.getElementById('map'); // Create the Google Map using out element and options defined above var map = new google.maps.Map(mapElement, mapOptions); // Custom Map Marker Icon - Customize the map-marker.png file to customize your icon var image = 'img/map-marker.png'; var myLatLng = new google.maps.LatLng(46.233755, 6.055636); /*var beachMarker = new google.maps.Marker({ position: myLatLng, map: map, icon: image });*/ } $(document).ready(function(d){ $(".dropdown .dropdown-menu li").hover(function(){ //Mouse IN $(".dropdown .dropdown-menu li").removeClass("active"); $(this).addClass("active"); }, function(){ //Mouse Out $(".dropdown .dropdown-menu li").removeClass("active"); } ); });
'use strict'; /** * Validate that a given XML document conforms to a given XML schema. XML Schema Definition (XSD) is the expected schema format. * * @param {document} xmlDocument xml to validate * @param {document} schemaDocument schema to enforce * @param {string} schemaFolderId if your schema utilizes <import> or <include> tags which refer to sub-schemas by file name (as opposed to URL), * provide the Internal Id of File Cabinet folder containing these sub-schemas as the schemaFolderId argument * @throws {nlobjError} error containsing validation failure message = (s) - limited to first 10 * * @since 2014.1 */ exports.nlapiValidateXML = (xmlDocument, schemaDocument, schemaFolderId) => { if (!xmlDocument) { throw nlapiCreateError('SSS_DOCUMENT_ARG_REQD'); } else if (!schemaDocument) { throw nlapiCreateError('SSS_SCHEMA_ARG_REQD'); } else { // FIXME validate XML generate by xmldom return true; } };
const db = require('APP/db') const Category = db.model('categories') const Product = db.model('products') module.exports = require('express').Router() .get('/', (req, res, next) => { Category.findAll({}) .then(planets => { res.json(planets) }) .catch(next) }) .get('/:categoryId', (req, res, next) => { Product.findAll({ where: { category_id: req.params.categoryId } }) .then(products => res.json(products)) .catch(next) })
(function() { function Score() { this.Container_constructor(); // Basically: super(); // Layout this.width = properties.TOP1_WIDTH; this.height = properties.TOP1_HEIGHT; this.txt; this.setup(); } // Basically: ... Button extends Container ... (below returns a prototype) var p = createjs.extend(Score, createjs.Container); p.setup = function() { var fontSize = this.height * 0.40; var font = fontSize + "px " + properties.FONT; // TODO: make a global font var text = new createjs.Text("0", font, "#FFF"); text.textBaseline = "middle"; text.textAlign = "center"; // cordinates for the text to be drawn text.x = this.width/2; text.y = this.height/2; // Note: this refers to the container this.txt = this.addChild(text); // Container class method // Container initial cordinates this.x = 0; this.y = layout.TOP1; // Disable interaction with child (only interact as a whole) this.mouseChildren = false; } ; // Allows things out of scope to use this now (all of the above cannot be called directly) window.Score = createjs.promote(Score, "Container"); }());