code
stringlengths
2
1.05M
import { DatetimeLocal as BasicDatetimeLocal } from '../basic/datetime-local.js'; import { ErrorMessages } from "./messages.js"; export class DatetimeLocal extends BasicDatetimeLocal{ constructor(inputObj) { super(inputObj, ErrorMessages); } get uiClasses() { return 'form-control' } }
'use strict'; angular.module('rchSeanceApp') .directive('inputChoice', function() { return { require: '?ngModel', restrict: 'E', scope: { ngModel: '=', choice1: '@', choice2: '@' }, template: '<div class="btn-group" data-toggle="buttons"><label class="btn btn-primary"><input type="radio" name="options">{{choice1}}</label><label class="btn btn-primary"><input type="radio" name="options">{{choice2}}</label></div>', link: function(scope, elem, attrs, ngModel) { scope.$watch('ngModel', function(newValue, oldValue){ //init if (newValue === scope.choice1) { document.querySelector('.btn-group .btn:first-child').classList.add("active"); document.querySelector('.btn-group .btn:last-child').classList.remove("active"); } else { document.querySelector('.btn-group .btn:last-child').classList.add("active"); document.querySelector('.btn-group .btn:first-child').classList.remove("active"); } }); angular.element(document.querySelector('.btn-group .btn:first-child')).on('click', function(){ scope.$apply(function(){ ngModel.$setViewValue(scope.choice1); }); }); angular.element(document.querySelector('.btn-group .btn:last-child')).on('click', function(){ scope.$apply(function(){ ngModel.$setViewValue(scope.choice2); }); }); } }; } );
const InstagramAPI = require('./instagram-api'); const math = require('mathjs'); const async = require('async'); module.exports = { getBasicUserMediaStatistics: (accessToken) => { return new Promise( (resolve, reject) => { getAllUserMedias(accessToken) .then(data => { const likes = data.map(media => media.likes.count); resolve({ likes: { count: math.sum(likes), average: math.round(math.mean(likes)), median: math.round(math.median(likes)), mode: math.mode(likes) } }); }); } ); } }; /** * Returns all user media concatenating responses from pagination. */ const getAllUserMedias = (accessToken) => { return new Promise((resolve, reject) => { let medias = []; let nextMaxId = null; async.doWhilst( // do (next) => { InstagramAPI.Users.getRecentMedia({ access_token: accessToken, max_id: nextMaxId, count: 50 }).then(function (response, stats) { const pagination = response.data.pagination; nextMaxId = pagination && pagination.next_max_id ? pagination.next_max_id : null; medias = medias.concat(response.data.data); next(null, medias); }); }, // while () => nextMaxId !== null, // then (err, medias) => { return resolve(medias); } ); }); };
"use strict"; var user = require('./../../user'); var usersController = {}; usersController.search = function(req, res, next) { res.render('admin/manage/users', { search_display: '', loadmore_display: 'none', users: [] }); }; usersController.sortByPosts = function(req, res, next) { getUsers('users:postcount', req, res, next); }; usersController.sortByReputation = function(req, res, next) { getUsers('users:reputation', req, res, next); }; usersController.sortByJoinDate = function(req, res, next) { getUsers('users:joindate', req, res, next); }; function getUsers(set, req, res, next) { user.getUsersFromSet(set, 0, 49, function(err, users) { if (err) { return next(err); } res.render('admin/manage/users', { search_display: 'hidden', loadmore_display: 'block', users: users, yourid: req.user.uid }); }); } usersController.getCSV = function(req, res, next) { user.getUsersCSV(function(err, data) { res.attachment('users.csv'); res.setHeader('Content-Type', 'text/csv'); res.end(data); }); }; module.exports = usersController;
"use strict"; var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); }; Object.defineProperty(exports, "__esModule", { value: true }); const LibFs = require("mz/fs"); const program = require("commander"); const LibPath = require("path"); const lib_1 = require("./lib/lib"); const template_1 = require("./lib/template"); const pkg = require('../../package.json'); program.version(pkg.version) .option('-p, --proto <dir>', 'directory of proto files') .option('-i, --import <items>', 'third party proto import path: e.g path1,path2,path3', val => val.split(',')) .option('-o, --output <dir>', 'directory to output service codes') .option('-e, --exclude <items>', 'files or paths in -p shall be excluded: e.g file1,path1,path2,file2', val => val.split(',')) .option('-z, --zipkin', 'need add zipkin plugin') .parse(process.argv); const PROTO_DIR = program.proto === undefined ? undefined : LibPath.normalize(program.proto); const IMPORTS = program.import === undefined ? [] : program.import; const OUTPUT_DIR = program.output === undefined ? undefined : LibPath.normalize(program.output); const EXCLUDES = program.exclude === undefined ? [] : program.exclude; const ZIPKIN = program.zipkin === undefined ? undefined : true; class ClientCLI { constructor() { this._protoFiles = []; } static instance() { return new ClientCLI(); } /** * Read import proto and generate DependencyClients * Only import proto need a client */ run() { return __awaiter(this, void 0, void 0, function* () { console.log('ClientCLI start.'); yield this._validate(); yield this._loadSelfProtos(); yield this._loadProtos(); yield this._genProtoDependencyClients(); }); } _validate() { return __awaiter(this, void 0, void 0, function* () { console.log('ClientCLI validate.'); if (!PROTO_DIR) { throw new Error('--proto is required'); } if (!OUTPUT_DIR) { throw new Error('--output is required'); } let outputStat = yield LibFs.stat(OUTPUT_DIR); if (!outputStat.isDirectory()) { throw new Error('--output is not a directory'); } }); } _loadSelfProtos() { return __awaiter(this, void 0, void 0, function* () { console.log('ClientCLI load self proto file.'); // Package name is same so only need parse one proto const protoFiles = yield lib_1.readProtoList(PROTO_DIR, OUTPUT_DIR); const parseResult = yield lib_1.parseProto(protoFiles[0]); this._packageName = parseResult.package; }); } _loadProtos() { return __awaiter(this, void 0, void 0, function* () { console.log('ClientCLI load proto files.'); if (IMPORTS.length > 0) { for (let i = 0; i < IMPORTS.length; i++) { this._protoFiles = this._protoFiles.concat(yield lib_1.readProtoList(LibPath.normalize(IMPORTS[i]), OUTPUT_DIR)); } } if (this._protoFiles.length === 0) { throw new Error('no proto files found'); } }); } _genProtoDependencyClients() { return __awaiter(this, void 0, void 0, function* () { console.log('ClientCLI generate clients.'); let protoMsgImportInfos = {}; let parseResults = []; for (let i = 0; i < this._protoFiles.length; i++) { let protoFile = this._protoFiles[i]; if (!protoFile) { continue; } let parseResult = {}; parseResult.result = yield lib_1.parseProto(protoFile); parseResult.protoFile = protoFile; parseResults.push(parseResult); let msgImportInfos = lib_1.parseMsgNamesFromProto(parseResult.result, protoFile); Object.assign(protoMsgImportInfos, msgImportInfos); } yield lib_1.mkdir(LibPath.join(OUTPUT_DIR, 'clients')); for (let i = 0; i < parseResults.length; i++) { let protoInfo = parseResults[i]; let services = lib_1.parseServicesFromProto(protoInfo.result); if (services.length === 0) { continue; } /** * Only MS need client & one MS only have one client */ const service = services[0]; // handle excludes let protoFilePath = LibPath.join(protoInfo.protoFile.protoPath, protoInfo.protoFile.relativePath, protoInfo.protoFile.fileName); let shallIgnore = false; if (EXCLUDES.length > 0) { EXCLUDES.forEach((exclude) => { if (protoFilePath.indexOf(LibPath.normalize(exclude)) !== -1) { shallIgnore = true; } }); } if (shallIgnore) { continue; } const protoName = protoInfo.result.package; const ucBaseName = lib_1.ucfirst(protoName); let protoClientInfo = { packageName: this._packageName.toUpperCase(), protoName: protoName, ucProtoName: protoName.toUpperCase(), className: `MS${ucBaseName}Client`, protoFile: protoInfo.protoFile, protoImportPath: lib_1.Proto.genProtoClientImportPath(protoInfo.protoFile).replace(/\\/g, '/'), methodList: {}, useZipkin: ZIPKIN, }; const outputPath = lib_1.Proto.genFullOutputClientPath(protoInfo.protoFile); let methodInfos = this._genMethodInfos(protoInfo.protoFile, service, outputPath, protoMsgImportInfos); protoClientInfo.clientName = service.name; protoClientInfo.methodList = methodInfos; let allMethodImportPath = {}; for (const method of protoClientInfo.methodList) { for (const key of Object.keys(method.protoMsgImportPath)) { for (const value of method.protoMsgImportPath[key]) { lib_1.addIntoRpcMethodImportPathInfos(allMethodImportPath, value, key); } } } const importPath = Object.keys(allMethodImportPath)[0]; protoClientInfo.allMethodImportPath = importPath.replace(/\\/g, '/'); const moduleSet = new Set(allMethodImportPath[importPath]); // check same name protoClientInfo.allMethodImportModule = [...moduleSet]; yield lib_1.mkdir(LibPath.dirname(outputPath)); let content = template_1.TplEngine.render('rpcs/client', Object.assign({}, protoClientInfo)); yield LibFs.writeFile(outputPath, content); } }); } _genMethodInfos(protoFile, service, outputPath, importInfos) { console.log('ClientCLI generate method infos: %s', service.name); let methodKeys = Object.keys(service.methods); if (methodKeys.length === 0) { return; } let methodInfos = []; for (const methodKey of methodKeys) { const method = service.methods[methodKey]; const methodInfo = lib_1.genRpcMethodInfo(protoFile, method, outputPath, importInfos, 'clients'); methodInfos.push(methodInfo); } return methodInfos; } } ClientCLI.instance().run().catch((err) => { console.log('err: ', err.message); });
import test from 'ava'; import sinon from 'sinon'; import { mockImports, resetImports } from '../../utils/test-helpers'; import RunLogger, { __RewireAPI__ as moduleRewireAPI } from './run-logger'; const createMockedLogger = () => { const logger = new RunLogger(); logger.spinner = { start: sinon.stub(), stop: sinon.stub(), message: sinon.stub(), }; return logger; }; test.beforeEach('mock imports', t => { const mocks = { clui: { Spinner: sinon.stub() }, }; t.context = { mocks }; mockImports({ moduleRewireAPI, mocks }); sinon.stub(global.console, 'log'); }); test.afterEach.always('unmock imports', t => { const imports = Object.keys(t.context.mocks); resetImports({ moduleRewireAPI, imports }); global.console.log.restore(); }); test.serial('Should create a run-logger instance', t => { const logger = new RunLogger(); t.is(typeof logger.asObserver, 'function'); }); test.serial('Should return observer', t => { const logger = new RunLogger(); const observer = logger.asObserver(); t.is(typeof observer.next, 'function'); t.is(typeof observer.error, 'function'); }); test.serial('Should log MONGOOSE_CONNECT_START', t => { const logger = createMockedLogger(); const type = 'MONGOOSE_CONNECT_START'; logger.next({ type }); t.true(logger.spinner.stop.calledOnce); t.true(logger.spinner.message.calledOnce); t.true(logger.spinner.start.calledOnce); }); test.serial('Should log MONGOOSE_CONNECT_SUCCESS', t => { const logger = createMockedLogger(); const type = 'MONGOOSE_CONNECT_SUCCESS'; logger.next({ type }); t.true(logger.spinner.stop.calledOnce); t.true( global.console.log.calledWith( sinon.match(/Successfully connected to MongoDB/) ) ); }); test.serial('Should log MONGOOSE_DROP_START', t => { const logger = createMockedLogger(); logger.next({ type: 'MONGOOSE_DROP_START' }); t.true(logger.spinner.stop.calledOnce); t.true(logger.spinner.message.calledOnce); t.true(logger.spinner.start.calledOnce); }); test.serial('Should log MONGOOSE_DROP_SUCCESS', t => { const logger = createMockedLogger(); logger.next({ type: 'MONGOOSE_DROP_SUCCESS' }); t.true(logger.spinner.stop.calledOnce); t.true(global.console.log.calledWith(sinon.match(/Database dropped/))); }); test.serial('Should log ALL_SEEDERS_START', t => { const logger = createMockedLogger(); logger.next({ type: 'ALL_SEEDERS_START' }); t.true(logger.spinner.stop.calledOnce); t.true(global.console.log.calledWith(sinon.match(/Seeding Results/))); }); test.serial('Should log ALL_SEEDERS_FINISH', t => { const logger = createMockedLogger(); logger.next({ type: 'ALL_SEEDERS_FINISH' }); t.true(logger.spinner.stop.calledOnce); t.true(global.console.log.calledWith(sinon.match(/Done/))); }); test.serial('Should log SEEDER_START', t => { const logger = createMockedLogger(); const payload = { name: 'some-name' }; logger.next({ type: 'SEEDER_START', payload }); t.true(logger.spinner.stop.calledOnce); t.true(logger.spinner.message.calledWith(payload.name)); t.true(logger.spinner.start.calledOnce); }); test.serial('Should log SEEDER_SUCCESS', t => { const logger = createMockedLogger(); const payload = { name: 'some-name', results: { run: true, created: '10' } }; logger.next({ type: 'SEEDER_SUCCESS', payload }); t.true(logger.spinner.stop.calledOnce); t.true(global.console.log.calledWith(sinon.match(payload.name))); t.true(global.console.log.calledWith(sinon.match(payload.results.created))); }); test.serial('Should log SEEDER_SUCCESS with run=false', t => { const logger = createMockedLogger(); const payload = { name: 'some-name', results: { run: false, created: '0' } }; logger.next({ type: 'SEEDER_SUCCESS', payload }); t.true(logger.spinner.stop.calledOnce); t.true(global.console.log.calledWith(sinon.match(payload.name))); t.true(global.console.log.calledWith(sinon.match(payload.results.created))); }); test.serial('Should log MONGOOSE_CONNECT_ERROR', t => { const logger = createMockedLogger(); logger.error({ type: 'MONGOOSE_CONNECT_ERROR' }); t.true(logger.spinner.stop.calledOnce); t.true( global.console.log.calledWith(sinon.match(/Unable to connected to MongoDB/)) ); }); test.serial('Should log MONGOOSE_DROP_ERROR', t => { const logger = createMockedLogger(); logger.error({ type: 'MONGOOSE_DROP_ERROR' }); t.true(logger.spinner.stop.calledOnce); t.true(global.console.log.calledWith(sinon.match(/Unable to drop database/))); }); test.serial('Should log SEEDER_ERROR', t => { const logger = createMockedLogger(); const payload = { name: 'some-name' }; logger.error({ type: 'SEEDER_ERROR', payload }); t.true(logger.spinner.stop.calledOnce); t.true(global.console.log.calledWith(sinon.match(payload.name))); }); test.serial('Should log error', t => { sinon.stub(global.console, 'error'); const logger = createMockedLogger(); const payload = { error: 'some-error' }; logger.error({ type: 'some-type', payload }); t.true(logger.spinner.stop.calledOnce); t.true(global.console.error.calledWith(payload.error)); global.console.error.restore(); });
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, View, TouchableHighlight, Navigator } from 'react-native'; import Login from './login'; export default class lbs extends Component { render() { let defaultName = 'FirstPageComponent'; let defaultComponent = Login; return ( <Navigator initialRoute={{ name: defaultName, component: defaultComponent }} configureScene={(route) => { return Navigator.SceneConfigs.HorizontalSwipeJump; }} renderScene={(route, navigator) => { let Component = route.component; return <Component {...route.params} navigator={navigator} /> }} /> ); } } AppRegistry.registerComponent('lbs', () => lbs);
import Express from 'express'; import Logger from 'morgan'; import bodyParser from 'body-parser'; import routes from './routes/index'; const app = Express(); app.use(Logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: false })); app.use('/', routes); app.use((request, response, next) => { const error = new Error('Not Found'); error.status = 404; next(error); }); if (app.get('env') === 'development') { app.use((error, request, response, next) => { response.status(error.status || 500).json({ message: error.message, error }); }); } app.use((error, request, response, next) => { response.status(error.status || 500).json({ message: error.message, error: {} }); }); export default app;
var m = function (){ function p1(arg1/*INTEGER*/){ var $scope1 = $scope + ".p1"; function T1(){ this.field1 = 0; } var i1 = 0;var j1 = 0; var t1 = new T1(); function p2(arg2/*BOOLEAN*/){ var $scope2 = $scope1 + ".p2"; function T2(){ this.field2 = false; } var b = false; var t2 = new T2(); b = arg2; t1.field1 = i1; t2.field2 = b; } p2(true); p2(false); } }();
/** * Capitan * * Copyright brandung GmbH & Co.KG * http://www.brandung.de/ * * Date: 19.08.2015s * MIT License (MIT) * * Polyfill for console methods */ Capitan.Util.consolePolyfill = function () { if (!(window.console && console.log)) { (function () { var noop = function () { }, methods = ['assert', 'clear', 'count', 'debug', 'dir', 'dirxml', 'error', 'exception', 'group', 'groupCollapsed', 'groupEnd', 'info', 'log', 'markTimeline', 'profile', 'profileEnd', 'markTimeline', 'table', 'time', 'timeEnd', 'timeStamp', 'trace', 'warn'], length = methods.length, console = window.console = {}; while (length) { console[methods[length]] = noop; length -= 1; } }()); } }();
/*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2016 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ sap.ui.define([ "sap/ui/core/format/DateFormat", "sap/ui/model/FormatException", "sap/ui/model/odata/type/ODataType", "sap/ui/model/ParseException", "sap/ui/model/ValidateException" ], function (DateFormat, FormatException, ODataType, ParseException, ValidateException) { "use strict"; var oDemoDate = new Date(2014, 10, 27, 13, 47, 26); /* * Returns true if the type uses only the date. * * @param {sap.ui.model.odata.type.DateTimeBase} oType * The type */ function isDateOnly(oType) { return oType.oConstraints && oType.oConstraints.isDateOnly; } /* * Returns the matching locale-dependent error message for the type based on the constraints. * * @param {sap.ui.model.odata.type.DateTimeBase} oType * The type * @returns {string} * The locale-dependent error message */ function getErrorMessage(oType) { return sap.ui.getCore().getLibraryResourceBundle().getText( isDateOnly(oType) ? "EnterDate" : "EnterDateTime", [oType.formatValue(oDemoDate, "string")]); } /* * Returns the formatter. Creates it lazily. * * @param {sap.ui.model.odata.type.DateTimeBase} oType * The type instance * @returns {sap.ui.core.format.DateFormat} * The formatter */ function getFormatter(oType) { var oFormatOptions; if (!oType.oFormat) { oFormatOptions = jQuery.extend({strictParsing : true}, oType.oFormatOptions); if (isDateOnly(oType)) { oFormatOptions.UTC = true; oType.oFormat = DateFormat.getDateInstance(oFormatOptions); } else { delete oFormatOptions.UTC; oType.oFormat = DateFormat.getDateTimeInstance(oFormatOptions); } } return oType.oFormat; } /* * Sets the constraints. * * @param {sap.ui.model.odata.type.DateTimeBase} oType * The type instance * @param {object} [oConstraints] * Constraints, see {@link #constructor} */ function setConstraints(oType, oConstraints) { var iPrecision; oType.oConstraints = undefined; if (oConstraints) { switch (oConstraints.nullable) { case undefined: case true: case "true": break; case false: case "false": oType.oConstraints = oType.oConstraints || {}; oType.oConstraints.nullable = false; break; default: jQuery.sap.log.warning("Illegal nullable: " + oConstraints.nullable, null, oType.getName()); } if (oConstraints.isDateOnly === true) { oType.oConstraints = oType.oConstraints || {}; oType.oConstraints.isDateOnly = true; } iPrecision = oConstraints.precision; if (iPrecision !== undefined) { if (iPrecision === Math.floor(iPrecision) && iPrecision >= 1 && iPrecision <= 12) { oType.oConstraints = oType.oConstraints || {}; oType.oConstraints.precision = iPrecision; } else if (iPrecision !== 0) { jQuery.sap.log.warning("Illegal precision: " + iPrecision, null, oType.getName()); } // else: 0 is the default! } } oType._handleLocalizationChange(); } /** * Base constructor for the primitive types <code>Edm.DateTime</code> and * <code>Edm.DateTimeOffset</code>. * * @param {object} [oFormatOptions] * Type-specific format options; see subtypes * @param {object} [oConstraints] * Constraints; {@link #validateValue validateValue} throws an error if any constraint is * violated * @param {boolean} [oConstraints.isDateOnly=false] * If <code>true</code>, only the date part is used, the time part is always 00:00:00 and * the time zone is UTC to avoid time-zone-related problems * @param {boolean|string} [oConstraints.nullable=true] * If <code>true</code>, the value <code>null</code> is accepted * @param {boolean} [oConstraints.precision=0] * The number of decimal places allowed in the seconds portion of a valid string value * (OData V4 only); only integer values between 0 and 12 are valid (since 1.37.0) * * @abstract * @alias sap.ui.model.odata.type.DateTimeBase * @author SAP SE * @class This is an abstract base class for the OData primitive types * <code>Edm.DateTime</code> and <code>Edm.DateTimeOffset</code>. * @extends sap.ui.model.odata.type.ODataType * @public * @since 1.27.0 * @version 1.38.4 */ var DateTimeBase = ODataType.extend("sap.ui.model.odata.type.DateTimeBase", { constructor : function (oFormatOptions, oConstraints) { ODataType.apply(this, arguments); setConstraints(this, oConstraints); this.oFormat = null; this.oFormatOptions = oFormatOptions; }, metadata : { "abstract" : true } }); /** * Formats the given value to the given target type. * * @param {Date} oValue * The value to be formatted, which is represented in the model as a <code>Date</code> * instance (OData V2) * @param {string} sTargetType * The target type, may be "any" or "string"; see {@link sap.ui.model.odata.type} for more * information * @returns {Date|string} * The formatted output value in the target type; <code>undefined</code> or <code>null</code> * are formatted to <code>null</code> * @throws {sap.ui.model.FormatException} * If <code>sTargetType</code> is not supported * * @public * @since 1.27.0 */ DateTimeBase.prototype.formatValue = function (oValue, sTargetType) { if (oValue === null || oValue === undefined) { return null; } switch (sTargetType) { case "any": return oValue; case "string": return getFormatter(this).format(oValue); default: throw new FormatException("Don't know how to format " + this.getName() + " to " + sTargetType); } }; /** * Parses the given value to a <code>Date</code> instance (OData V2). * * @param {string} sValue * The value to be parsed; the empty string and <code>null</code> are parsed to * <code>null</code> * @param {string} sSourceType * The source type (the expected type of <code>sValue</code>), must be "string"; see * {@link sap.ui.model.odata.type} for more information * @returns {Date} * The parsed value * @throws {sap.ui.model.ParseException} * If <code>sSourceType</code> is not supported or if the given string cannot be parsed to a * Date * * @public * @since 1.27.0 */ DateTimeBase.prototype.parseValue = function (sValue, sSourceType) { var oResult; if (sValue === null || sValue === "") { return null; } switch (sSourceType) { case "string": oResult = getFormatter(this).parse(sValue); if (!oResult) { throw new ParseException(getErrorMessage(this)); } return oResult; default: throw new ParseException("Don't know how to parse " + this.getName() + " from " + sSourceType); } }; /** * Called by the framework when any localization setting is changed. * * @private */ DateTimeBase.prototype._handleLocalizationChange = function () { this.oFormat = null; }; /** * Validates whether the given value in model representation is valid and meets the * defined constraints. * * @param {Date} oValue * The value to be validated * @returns {void} * @throws {sap.ui.model.ValidateException} * If the value is not valid * * @public * @since 1.27.0 */ DateTimeBase.prototype.validateValue = function (oValue) { if (oValue === null) { if (this.oConstraints && this.oConstraints.nullable === false) { throw new ValidateException(getErrorMessage(this)); } return; } else if (oValue instanceof Date) { return; } throw new ValidateException("Illegal " + this.getName() + " value: " + oValue); }; /** * Returns the type's name. * * @abstract * @alias sap.ui.model.odata.type.DateTimeBase#getName * @protected * @see sap.ui.model.Type#getName */ return DateTimeBase; });
/** * returns the sequence with highlighted fragment if the pattern matches, else just the sequence * * @param {string} sequence [description] * @param {string} fragment [fragment which should be highlighted] * * @param {string} pattern [pattern describes which characters are allowed between the fragment characters * https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Global_Objects/RegExp] * * @param {string} htmlTag [an html tag e.g strong, span, b] * @return {string} [returns the sequence with higlighted fragment if the pattern matches, else just the sequence] */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); exports['default'] = highlightFragment; function highlightFragment(sequence, fragment, pattern, htmlTag) { var result = new RegExp(fragment.split('').join(pattern)).exec(sequence); if (result && fragment) { return sequence.slice(0, result.index) + '<' + htmlTag + '>' + result[0] + '</' + htmlTag + '>' + sequence.slice(result.index + result[0].length); } else { return sequence; } } module.exports = exports['default'];
/* --- name: Mif.Tree.Load description: load tree from json license: MIT-Style License (http://mifjs.net/license.txt) copyright: Anton Samoylov (http://mifjs.net) authors: Anton Samoylov (http://mifjs.net) requires: Mif.Tree provides: Mif.Tree.Load ... */ Mif.Tree.Load = { children: function(children, parent, tree){ var i, l; var subChildrens = []; for(i = children.length; i--; ){ var child = children[i]; var node = new Mif.Tree.Node({ tree: tree, parentNode: parent||undefined }, child); if( tree.forest || parent != undefined){ parent.children.unshift(node); }else{ tree.root = node; } var subChildren = child.children; if(subChildren && subChildren.length){ subChildrens.push({children: subChildren, parent: node}); } } for(i = 0, l = subChildrens.length; i < l; i++) { var sub = subChildrens[i]; arguments.callee(sub.children, sub.parent, tree); } if(parent) parent.state.loaded = true; tree.fireEvent('loadChildren', parent); } }; Mif.Tree.implement({ load: function(options){ var tree = this; this.loadOptions = this.loadOptions||$lambda({}); function success(json){ var parent = null; if(tree.forest){ tree.root = new Mif.Tree.Node({ tree: tree, parentNode: null }, {}); parent = tree.root; } Mif.Tree.Load.children(json, parent, tree); Mif.Tree.Draw[tree.forest ? 'forestRoot' : 'root'](tree); tree.$getIndex(); tree.fireEvent('load'); return tree; } options = $extend($extend({ isSuccess: $lambda(true), secure: true, onSuccess: success, method: 'get' }, this.loadOptions()), options); if(options.json) return success(options.json); new Request.JSON(options).send(); return this; } }); Mif.Tree.Node.implement({ load: function(options){ this.$loading = true; options = options||{}; this.addType('loader'); var self = this; function success(json){ Mif.Tree.Load.children(json, self, self.tree); delete self.$loading; self.state.loaded = true; self.removeType('loader'); Mif.Tree.Draw.update(self); self.fireEvent('load'); self.tree.fireEvent('loadNode', self); return self; } options=$extend($extend($extend({ isSuccess: $lambda(true), secure: true, onSuccess: success, method: 'get' }, this.tree.loadOptions(this)), this.loadOptions), options); if(options.json) return success(options.json); new Request.JSON(options).send(); return this; } });
/** * Created by reinvantveer on 2/27/17. */ const sorter = require('../lib/schemaSorter'); const chai = require('chai'); chai.should(); /* eslint-env mocha */ describe('schema diff sorter', () => { describe('the default sorter', () => { it('prefers few B diffs over many A diffs', () => { const diffA = { patch: [ { op: 'remove', path: '/items/properties/bang' }, { op: 'add', path: '/items/properties/column1', value: { type: 'string' } }, { op: 'add', path: '/items/properties/column2', value: { type: 'string' } } ] }; const diffB = { patch: [ { op: 'remove', path: '/items/properties/bang' }, { op: 'add', path: '/items/properties/column1', value: { type: 'string' } } ] }; return sorter(diffA, diffB).should.equal(1); }); it('prefers few A diffs over many B diffs', () => { const diffA = { patch: [ { op: 'remove', path: '/items/properties/bang' }, { op: 'add', path: '/items/properties/column1', value: { type: 'string' } } ] }; const diffB = { patch: [ { op: 'remove', path: '/items/properties/bang' }, { op: 'add', path: '/items/properties/column1', value: { type: 'string' } }, { op: 'add', path: '/items/properties/column2', value: { type: 'string' } } ] }; return sorter(diffA, diffB).should.equal(-1); }); }); describe('the additions preferred sorter prefers', () => { it('A add over replace B', () => { const diffA = { patch: [ { op: 'add', path: '/items/properties/column1', value: { type: 'string' } }, { op: 'add', path: '/items/properties/column2', value: { type: 'string' } } ] }; const diffB = { patch: [ { op: 'remove', path: '/items/properties/bang' }, { op: 'add', path: '/items/properties/column1', value: { type: 'string' } } ] }; return sorter(diffA, diffB, 'preferAdditions').should.equal(-1); }); it('B add over A replace', () => { const diffA = { patch: [ { op: 'remove', path: '/items/properties/bang' }, { op: 'add', path: '/items/properties/column1', value: { type: 'string' } } ] }; const diffB = { patch: [ { op: 'add', path: '/items/properties/column1', value: { type: 'string' } }, { op: 'add', path: '/items/properties/column2', value: { type: 'string' } } ] }; return sorter(diffA, diffB, 'preferAdditions').should.equal(1); }); it('B remove and add over just an A remove', () => { const diffA = { patch: [ { op: 'remove', path: '/items/properties/bang' }, ] }; const diffB = { patch: [ { op: 'remove', path: '/items/properties/column1', value: { type: 'string' } }, { op: 'add', path: '/items/properties/column2', value: { type: 'string' } } ] }; return sorter(diffA, diffB, 'preferAdditions').should.equal(1); }); it('A remove and add over just a B remove', () => { const diffA = { patch: [ { op: 'remove', path: '/items/properties/column2', value: { type: 'string' } }, { op: 'add', path: '/items/properties/column2', value: { type: 'string' } } ] }; const diffB = { patch: [ { op: 'remove', path: '/items/properties/bang' }, ] }; return sorter(diffA, diffB, 'preferAdditions').should.equal(-1); }); it('single A add over plural B adds', () => { const diffA = { patch: [ { op: 'remove', path: '/items/properties/bang' }, { op: 'add', path: '/items/properties/column2', value: { type: 'string' } } ] }; const diffB = { patch: [ { op: 'remove', path: '/items/properties/column1', value: { type: 'string' } }, { op: 'add', path: '/items/properties/column2', value: { type: 'string' } }, { op: 'add', path: '/items/properties/column3', value: { type: 'string' } } ] }; return sorter(diffA, diffB, 'preferAdditions').should.equal(-1); }); it('single A add over plural B adds', () => { const diffA = { patch: [ { op: 'remove', path: '/items/properties/column1', value: { type: 'string' } }, { op: 'add', path: '/items/properties/column2', value: { type: 'string' } }, { op: 'add', path: '/items/properties/column3', value: { type: 'string' } } ] }; const diffB = { patch: [ { op: 'remove', path: '/items/properties/bang' }, { op: 'add', path: '/items/properties/column2', value: { type: 'string' } } ] }; return sorter(diffA, diffB, 'preferAdditions').should.equal(1); }); }); });
import apiMacro from "./helpers/apiMacro"; import cliMacro from "./helpers/cliMacro"; import expected from "./fixtures"; import npmScriptsMacro from "./helpers/npmScriptsMacro"; import test from "ava"; test( "postversion (legacy)", npmScriptsMacro, { postversion: "-a -L" }, "AwesomeProject", expected.version.default, expected.tree.amended ); test( "postversion", npmScriptsMacro, { postversion: "-a" }, "AwesomeProject", expected.version.default, expected.tree.amended ); test( "postversion (Expo)", npmScriptsMacro, { postversion: "-a" }, "my-new-project", expected.version.default, expected.tree.amended ); test( "version (legacy)", npmScriptsMacro, { version: "-a -L" }, "AwesomeProject", expected.version.default, expected.tree.amended ); test( "version", npmScriptsMacro, { version: "-a" }, "AwesomeProject", expected.version.default, expected.tree.amended ); test( "version (Expo)", npmScriptsMacro, { version: "-a" }, "my-new-project", expected.version.default, expected.tree.amended ); test( "CLI (legacy)", cliMacro, ["-a", "-L"], "AwesomeProject", expected.version.default, expected.tree.amended ); test( "CLI", cliMacro, ["-a"], "AwesomeProject", expected.version.default, expected.tree.amended ); test( "CLI (Expo)", cliMacro, ["-a"], "my-new-project", expected.version.default, expected.tree.amended ); test( "API (legacy)", apiMacro, { amend: true, legacy: true }, "AwesomeProject", expected.version.default, expected.tree.amended ); test( "API", apiMacro, { amend: true }, "AwesomeProject", expected.version.default, expected.tree.amended ); test( "API (Expo)", apiMacro, { amend: true }, "my-new-project", expected.version.default, expected.tree.amended );
var exec = require( 'child_process' ).exec , os = require( 'os' ) , path = require( 'path' ) , htmlExtract = require( './html' ) , util = require( '../util' ) , types ; function extractText( filePath, options, cb ) { var execOptions = util.createExecOptions( 'rtf', options ) , escapedPath = filePath.replace( /\s/g, '\\ ' ) ; // Going to output html from unrtf because unrtf does a great job of // going to html, but does a crap job of going to text. It leaves sections // out, strips apostrophes, leaves nasty quotes in for bullets and more // that I've likely not yet discovered. // // textract can go from html to text on its own, so let unrtf go to html // then extract the text from that // // Also do not have to worry about stripping comments from unrtf text // output since HTML comments are not included in output. Also, the // unrtf --quiet option doesn't work. exec( 'unrtf --html --nopict ' + escapedPath, execOptions, function( error, stdout /* , stderr */ ) { var err; if ( error ) { err = new Error( 'unrtf read of file named [[ ' + path.basename( filePath ) + ' ]] failed: ' + error ); cb( err, null ); } else { htmlExtract.extractFromText( stdout.trim(), {}, cb ); } } ); } function testForBinary( options, cb ) { // just non-osx extractor if ( os.platform() === 'darwin' ) { cb( true ); return; } exec( 'unrtf ' + __filename, function( error /* , stdout, stderr */ ) { var msg; if ( error !== null && error.message && error.message.indexOf( 'not found' ) !== -1 ) { msg = 'INFO: \'unrtf\' does not appear to be installed, ' + 'so textract will be unable to extract RTFs.'; cb( false, msg ); } else { cb( true ); } } ); } // rely on native tools on osx if ( os.platform() === 'darwin' ) { types = []; // types = ['application/rtf', 'text/rtf']; } else { types = ['application/rtf', 'text/rtf']; } module.exports = { types: types, extract: extractText, test: testForBinary };
'use strict'; exports.__esModule = true; exports.BsCheckbox = undefined; var _dec, _dec2, _desc, _value, _class, _descriptor, _descriptor2, _descriptor3, _descriptor4, _descriptor5, _descriptor6, _descriptor7, _descriptor8; var _aureliaFramework = require('aurelia-framework'); function _initDefineProp(target, property, descriptor, context) { if (!descriptor) return; Object.defineProperty(target, property, { enumerable: descriptor.enumerable, configurable: descriptor.configurable, writable: descriptor.writable, value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 }); } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { var desc = {}; Object['ke' + 'ys'](descriptor).forEach(function (key) { desc[key] = descriptor[key]; }); desc.enumerable = !!desc.enumerable; desc.configurable = !!desc.configurable; if ('value' in desc || desc.initializer) { desc.writable = true; } desc = decorators.slice().reverse().reduce(function (desc, decorator) { return decorator(target, property, desc) || desc; }, desc); if (context && desc.initializer !== void 0) { desc.value = desc.initializer ? desc.initializer.call(context) : void 0; desc.initializer = undefined; } if (desc.initializer === void 0) { Object['define' + 'Property'](target, property, desc); desc = null; } return desc; } function _initializerWarningHelper(descriptor, context) { throw new Error('Decorating class property failed. Please ensure that transform-class-properties is enabled.'); } var BsCheckbox = exports.BsCheckbox = (_dec = (0, _aureliaFramework.bindable)({ defaultBindingMode: _aureliaFramework.bindingMode.twoWay }), _dec2 = (0, _aureliaFramework.bindable)({ defaultBindingMode: _aureliaFramework.bindingMode.twoWay }), (_class = function () { function BsCheckbox() { _classCallCheck(this, BsCheckbox); _initDefineProp(this, 'name', _descriptor, this); _initDefineProp(this, 'value', _descriptor2, this); _initDefineProp(this, 'checked', _descriptor3, this); _initDefineProp(this, 'model', _descriptor4, this); _initDefineProp(this, 'label', _descriptor5, this); _initDefineProp(this, 'helptext', _descriptor6, this); _initDefineProp(this, 'disabled', _descriptor7, this); _initDefineProp(this, 'inline', _descriptor8, this); } BsCheckbox.prototype.bind = function bind() { if (this.checked === 'true' || this.checked === 'checked') { this.checked = true; } if (!this.model) { this.model = this.value; } }; BsCheckbox.prototype.attached = function attached() { if (this.inline) { this.lbl.classList.add('checkbox-inline'); } else { this.template.classList.add('checkbox'); } if (this.disabled) { this.template.classList.add('disabled'); this.lbl.classList.add('disabled'); } if (this.helptext) { this.input.setAttribute('aria-describedby', this.name + '-help'); } }; return BsCheckbox; }(), (_descriptor = _applyDecoratedDescriptor(_class.prototype, 'name', [_aureliaFramework.bindable], { enumerable: true, initializer: null }), _descriptor2 = _applyDecoratedDescriptor(_class.prototype, 'value', [_dec], { enumerable: true, initializer: null }), _descriptor3 = _applyDecoratedDescriptor(_class.prototype, 'checked', [_dec2], { enumerable: true, initializer: function initializer() { return false; } }), _descriptor4 = _applyDecoratedDescriptor(_class.prototype, 'model', [_aureliaFramework.bindable], { enumerable: true, initializer: null }), _descriptor5 = _applyDecoratedDescriptor(_class.prototype, 'label', [_aureliaFramework.bindable], { enumerable: true, initializer: function initializer() { return ''; } }), _descriptor6 = _applyDecoratedDescriptor(_class.prototype, 'helptext', [_aureliaFramework.bindable], { enumerable: true, initializer: function initializer() { return ''; } }), _descriptor7 = _applyDecoratedDescriptor(_class.prototype, 'disabled', [_aureliaFramework.bindable], { enumerable: true, initializer: function initializer() { return false; } }), _descriptor8 = _applyDecoratedDescriptor(_class.prototype, 'inline', [_aureliaFramework.bindable], { enumerable: true, initializer: function initializer() { return false; } })), _class));
var circleRadii= []; var x,y; //circleRadii [] CIRCLE = new circleRadii[100]; function setup() { createCanvas(600,600); } function draw() { background(0); for(var i = 0;i<5;i++) { circleRadii[i] = { radius: 20, displaycircle: function() { stroke(255); noFill(); x=(width/2)+random(-3,3); y=(height/2)+random(-3,3); ellipse(x,y,20,20); } } circleRadii[i].displaycircle(); } }
import React from 'react'; import ReactDOM from 'react-dom'; import reduxThunk from 'redux-thunk' import { Provider } from 'react-redux'; import { Router, Route, IndexRoute, browserHistory } from 'react-router' import { createStore, applyMiddleware } from 'redux'; import { createLogger } from 'redux-logger' import App from './components/app'; import reducers from './reducers'; import { AUTH_USER } from './actions/types' import MapContainer from './components/map-container' import Signin from './components/auth/signin-container' import Signup from './components/auth/signup-container' import Signout from './components/auth/signout' const logger = createLogger({ collapsed: true }) const enhancer = applyMiddleware(logger, reduxThunk) const store = createStore(reducers, enhancer) const token = localStorage.getItem('token') if (token) { store.dispatch({ type: AUTH_USER }) } ReactDOM.render( <Provider store={store}> <Router history={browserHistory}> <Route path="/" component={App}> <IndexRoute component={MapContainer} /> <Route path="signin" component={Signin} /> <Route path="signup" component={Signup} /> <Route path="signout" component={Signout} /> </Route> <App /> </Router> </Provider> , document.querySelector('.root'));
'use strict'; const _ = require('lodash'); const fuzzy = require('./fuzzy_find'); const service = require('../lib/service'); const dummyService = service('dummy'); exports.find = (config) => { const app = _.get(config, 'app'); const secret = _.get(config, 'secret'); const nameOrId = _.get(config, 'route') || _.get(config, 'routeName'); return fuzzy.search( nameOrId, 'name', `${dummyService}/api/v1/routes`, 'routes', app, secret).then((r) => ({ route: r.id, routeName: _.get(r, 'value') })); }; exports.assertRoute = (options) => { if (!options.route) { throw new Error('Route ID not set. Set a route ID with a --route parameter.'); } return options; };
import React, { Component } from 'react'; import { Radio } from 'synfrastructure'; import ToggleScaffold from '../../common/forms/ToggleScaffold'; class Radios extends Component { constructor(props) { super(props); this.state = { checkedRadio: null, }; } toggleRadio(e) { this.setState({ checkedRadio: e.target.value }); } render() { const cmyk = ['cyan', 'magenta', 'yellow', 'key', 'disabled']; return ( <div className="paper"> <div className="styleguide__title">Radio Inputs</div> <div className="styleguide__row"> {cmyk.map(color => { const colorLabel = `${color.charAt(0).toUpperCase()}${color.substr(1)}`; return ( <ToggleScaffold key={color} label={colorLabel} disabled={color === 'disabled'} > <Radio id={color} value={color} checked={this.state.checkedRadio === color} onChange={this.toggleRadio.bind(this)} disabled={color === 'disabled'} /> </ToggleScaffold> ); })} </div> </div> ); } } export default Radios;
'use strict'; var Sequelize = require('sequelize') var db = require('./index.js'); module.exports = (db) => db.define('reviews', { content: { type: Sequelize.STRING, allowNull: false }, stars: { type: Sequelize.INTEGER, validate: { min: 0, max: 5 } }, }) module.exports.associations = (Review, {Product, User}) => { Review.belongsTo(Product) Review.belongsTo(User) }
const ADD_HISTORY = 'ADD_HISTORY'; const defaultState = []; const reducer = (state = defaultState, action) => { if (action.type === ADD_HISTORY) { if (state.slice(-1).pop() !== action.value) { return [...state, action.value]; } } return state; }; export default reducer;
"use strict"; var _ = require('lodash'); module.exports = function(handlebars){ handlebars.registerHelper("fixClass", function(){ var entries = this; for(var i=0; i<entries.length; i++){ var entry = entries[i]; if(entry.kind === "class"){ var cIndex = _.findIndex(entries, {kind:'constructor',name:entry.name}); if(cIndex > -1){ var c = entries[cIndex]; entry.description = c.description; delete c.description; var tags = _.pluck(entry.customTags, 'tag'); if(tags.indexOf('hide-constructor') > -1){ entries.splice(cIndex, 1); } delete entry.customTags; } } } }); };
import sqlString from 'sqlstring-sqlite'; import { getDb } from '../db.js'; import { formatOrderByClause, formatSelectClause, formatWhereClauses, } from '../utils.js'; import translations from '../../models/gtfs/translations.js'; /* * Returns an array of all translations that match the query parameters. */ export async function getTranslations( query = {}, fields = [], orderBy = [], options = {} ) { const db = options.db ?? (await getDb()); const tableName = sqlString.escapeId(translations.filenameBase); const selectClause = formatSelectClause(fields); const whereClause = formatWhereClauses(query); const orderByClause = formatOrderByClause(orderBy); return db.all( `${selectClause} FROM ${tableName} ${whereClause} ${orderByClause};` ); }
var mongoose = require('mongoose'); var crypto = require('crypto'); var Schema = mongoose.Schema; /* //simplest Schema example var UserSchema = new Schema({ firstName: String, lastName: String, email: String, username: String, password: String }); */ var UserSchema = new Schema({ firstName: { type:String, required:true }, lastName: { type: String, required:true }, email: { type: String, trim: true//, //match: [/.+\@+\.+/, "a valid email is needed"] , index: true }, username: { type: String, trim: true, unique: true, required: true }, password: { type: String, required:true, validate: [ function(password){ return password && password.length >6; }, 'Password should be greater than six characters' ] }, salt:{ type: String }, provider:{ type: String, required: 'Provider is required' }, providerId: String, providerData:{}, created:{ type: Date, default: Date.now }, website:{ type: String, set: function(url){ //get: function(url) //{if you have existing data in a large DB, change to get and if (url.indexOf('http://') !==0 && url.indexOf('https://') !==0 ) { url = 'http://' + url; } return url; } }, role:{ type: String, enum: ['Admin', 'Owner', 'User'] } }); UserSchema.set('toJSON', { getters: true, virtuals: true }); //if you have existing data in a large DB, use getters when converting to JSON UserSchema.virtual('fullName').get(function() { return this.firstName + ' ' + this.lastName; }).set(function(fullName){ var splitName = fullName.split(' '); this.firstName = splitName[0] || ''; this.lastName = splitName[1] || ''; }); UserSchema.statics.findOneByUsername = function(username, callback){ //custom static method this.findOne({ username: new RegExp(username, 'i')}, callback); }; UserSchema.statics.findUniqueUsername = function(username, suffix, callback){ var _this = this; var possibleUsername = username + (suffix || ''); _this.findOne({ username: possibleUsername}, function(err, user){ if (!err){ if(!user){ callback(possbleUsername); } else{ return _this.findUniqueUsername(username, (suffix || 0) + 1, callback); } }else{ callback(null); } }); }; UserSchema.methods.authenticate = function(password){ //custom instance method return this.password === this.hashPassword(password); }; UserSchema.methods.hashPassword = function(password){ return crypto.pbkdf2Sync(password, this.salt, 10000, 64).toString('base64'); //password that is passed in, salt that is belongs to the user }; UserSchema.pre('save', function(next){ if(this.password){ // we do not want to store password as plain text .. EVER! this.salt = new Buffer(crypto.randomBytes(16).toString('base64'), 'base64'); this.password = this.hashPassword(this.password); console.log("time to save"); } next(); }); UserSchema.post('save', function(next){ if (this.isNew){ console.log('A new user was created.'); }else{ console.log('A user udated its info'); } }); UserSchema.set('toJSON', { getters: true, virtuals: true }); mongoose.model('User', UserSchema); //user schema and model
$(function() { $('.collapsible button').on('click', function(){ $(this).parent('dt').next('dd').toggleClass('hidden'); if ($(this).attr('aria-expanded') != 'true'){ $(this).attr('aria-expanded','true'); } else { $(this).attr('aria-expanded','false'); } }); });
'use strict'; const _ = require('lodash'); module.exports = function (db) { var me = { db: db }; require('./extend')(me); for (var i = 0; i < me._resources.length; i++) { var r = me._resources[i]; me[r] = require('./' + r)(me); } return me; };
// TODO: Create the Session Information object //var info = new ActiveXObject("TCObj.SessionInfo"); //info.ApplicationName = WScript.ScriptFullName; // Connect to the Pig Server var app = new ActiveXObject("Pigs.Session"); // TODO: app.SessionInfo = objInfo; // Get the collection of pigs var pigs = app.Pigs; // Get an iterator on the collection of pigs var itPigs = new Enumerator(pigs); // Get the first pig in the iterator var pig = itPigs.item(); // Get the first pig's ship var ship = pig ? pig.Ship : null; // Jump straight into the debugger debugger;
/* @flow */ import { watchPath } from "atom"; import fs from "fs"; import path from "path"; import { bindNodeCallback, empty, from, fromEventPattern, of } from "rxjs"; import { catchError, filter, mergeMap, map } from "rxjs/operators"; import * as A from "../actions"; import NotesFileFilter from "../NotesFileFilter"; import takeUntilDispose from "../takeUntilDispose"; import { showWarningNotification } from "../showWarningNotification"; import type { Action } from "../actions"; import type { State } from "../../flow-types/State"; export default function pathWatcherEpic( action$: rxjs$Observable<Action>, state$: reduxRxjs$StateObservable<State>, { notesFileFilter }: { notesFileFilter: typeof NotesFileFilter } ) { const { dir } = state$.value; const [addHandler, removeHandler] = newEventPatternHandlers(dir); return fromEventPattern(addHandler, removeHandler).pipe( mergeMap(event => from(event)), filter(event => notesFileFilter.isAccepted(event.path)), mergeMap(event => { switch (event.action) { case "deleted": // special case: no need to stat, just pass the filename as is return of(A.fileDeleted(getFilename(dir, event.path))); case "renamed": // special case: no need to stat, pass rename action through directly return of( A.fileRenamed({ filename: getFilename(dir, event.path), oldFilename: getFilename(dir, event.oldPath) }) ); default: { const statFileAsObservable = bindNodeCallback(fs.stat); return statFileAsObservable(event.path).pipe( map(stats => { if (stats.isFile()) { return newFileAction(dir, event, stats); } }), catchError(error => { console.error(error); return empty(); }) ); } } }), filter(Boolean), takeUntilDispose(action$) ); } function newEventPatternHandlers(dir: string) { let watcher; let onWatcherDidError; const addHandler = handler => { // necessary to comply with fromEventPattern's params signature, // that doesnt expect an async fn const innerHandler = async () => { const options = {}; // there are no options, for now just a placeholder for the future watcher = await watchPath(dir, options, handler); onWatcherDidError = watcher.onDidError(error => { showWarningNotification(`Watched notes path ${dir} failed`, error); }); if (global.setProcessInTesting) { global.setProcessInTesting(process, { watcher }); } }; innerHandler(); }; const removeHandler = () => { const innerHandler = async () => { if (watcher) { await watcher.dispose(); } if (onWatcherDidError) { onWatcherDidError.dispose(); } }; innerHandler(); }; return [addHandler, removeHandler]; } function newFileAction( dir: string, event: atom$PathWatcherEvent, stats: fs.Stats ) { switch (event.action) { case "created": return A.fileAdded({ filename: getFilename(dir, event.path), stats }); case "modified": return A.fileChanged({ filename: getFilename(dir, event.path), stats }); } } function getFilename(dir, filePath) { return filePath.replace(dir + path.sep, ""); }
var Helpers = require('./helpers'); var Faker = require('../index'); var definitions = require('../lib/definitions'); var address = { zipCode: function () { return Helpers.replaceSymbolWithNumber(Faker.random.array_element(["#####", '#####-####'])); }, zipCodeFormat: function (format) { return Helpers.replaceSymbolWithNumber(["#####", '#####-####'][format]); }, city: function () { var result; switch (Faker.random.number(4)) { case 0: result = Faker.random.city_prefix() + Faker.random.first_name() + Faker.random.city_suffix(); break; case 1: result = Faker.random.city_prefix() + Faker.random.first_name(); break; case 2: result = Faker.random.first_name() + Faker.random.city_suffix(); break; case 3: result = Faker.random.last_name() + Faker.random.city_suffix(); break; } return result; }, streetName: function () { var result; switch (Faker.random.number(1)) { case 0: result = Faker.random.street_prefix() + " " + Faker.random.last_name(); break; case 1: result = Faker.random.street_prefix() + " " + Faker.random.first_name(); break; } return result; }, // // TODO: change all these methods that accept a boolean to instead accept an options hash. // streetAddress: function (useFullAddress) { if (useFullAddress === undefined) { useFullAddress = false; } var address = ""; switch (Faker.random.number(3)) { case 0: address = Helpers.replaceSymbolWithNumber("###") + " " + this.streetName(); break; case 1: address = Helpers.replaceSymbolWithNumber("##") + " " + this.streetName(); break; case 2: address = Helpers.replaceSymbolWithNumber("#") + " " + this.streetName(); break; } return useFullAddress ? (address + " " + this.secondaryAddress()) : address; }, secondaryAddress: function () { return Helpers.replaceSymbolWithNumber(Faker.random.array_element( [ 'Apt. ###', 'Suite ###' ] )); }, brState: function (useAbbr) { return useAbbr ? Faker.random.br_state_abbr() : Faker.random.br_state(); }, ukCounty: function () { return Faker.random.uk_county(); }, ukCountry: function () { return Faker.random.uk_country(); }, usState: function (useAbbr) { return useAbbr ? Faker.random.us_state_abbr() : Faker.random.us_state(); }, latitude: function () { return (Faker.random.number(180 * 10000) / 10000.0 - 90.0).toFixed(4); }, longitude: function () { return (Faker.random.number(360 * 10000) / 10000.0 - 180.0).toFixed(4); } }; module.exports = address;
version https://git-lfs.github.com/spec/v1 oid sha256:8d8bf1c08b55619646ab0422b016eba8f445c4926c1e013207c4de56412dbfca size 8771
ace.define("ace/theme/monokai",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) { exports.isDark = true; exports.cssClass = "ace-vue-theme"; exports.cssText = `.ace-vue-theme .ace_gutter { background: #2F3129; color: #2c3e50 } .ace-vue-theme .ace_print-margin { width: 1px; background: #555651 } .ace-vue-theme { background-color: #42b983; color: #F8F8F2 } .ace-vue-theme .ace_cursor { color: #F8F8F0 } .ace-vue-theme .ace_marker-layer .ace_selection { background: #49483E } .ace-vue-theme.ace_multiselect .ace_selection.ace_start { box-shadow: 0 0 3px 0px #272822; } .ace-vue-theme .ace_marker-layer .ace_step { background: rgb(102, 82, 0) } .ace-vue-theme .ace_marker-layer .ace_bracket { margin: -1px 0 0 -1px; border: 1px solid #49483E } .ace-vue-theme .ace_marker-layer .ace_active-line { background: #202020 } .ace-vue-theme .ace_gutter-active-line { background-color: #272727 } .ace-vue-theme .ace_marker-layer .ace_selected-word { border: 1px solid #49483E } .ace-vue-theme .ace_invisible { color: #52524d } .ace-vue-theme .ace_entity.ace_name.ace_tag, .ace-vue-theme .ace_keyword, .ace-vue-theme .ace_meta.ace_tag, .ace-vue-theme .ace_storage { color: #F92672 } .ace-vue-theme .ace_punctuation, .ace-vue-theme .ace_punctuation.ace_tag { color: #fff } .ace-vue-theme .ace_constant.ace_character, .ace-vue-theme .ace_constant.ace_language, .ace-vue-theme .ace_constant.ace_numeric, .ace-vue-theme .ace_constant.ace_other { color: #AE81FF } .ace-vue-theme .ace_invalid { color: #F8F8F0; background-color: #F92672 } .ace-vue-theme .ace_invalid.ace_deprecated { color: #F8F8F0; background-color: #AE81FF } .ace-vue-theme .ace_support.ace_constant, .ace-vue-theme .ace_support.ace_function { color: #66D9EF } .ace-vue-theme .ace_fold { background-color: #A6E22E; border-color: #F8F8F2 } .ace-vue-theme .ace_storage.ace_type, .ace-vue-theme .ace_support.ace_class, .ace-vue-theme .ace_support.ace_type { font-style: italic; color: #66D9EF } .ace-vue-theme .ace_entity.ace_name.ace_function, .ace-vue-theme .ace_entity.ace_other, .ace-vue-theme .ace_entity.ace_other.ace_attribute-name, .ace-vue-theme .ace_variable { color: #2c3e50 } .ace-vue-theme .ace_variable.ace_parameter { font-style: italic; color: #FD971F } .ace-vue-theme .ace_string { color: #E6DB74 } .ace-vue-theme .ace_comment { color: #75715E } .ace-vue-theme .ace_indent-guide { background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAEklEQVQImWPQ0FD0ZXBzd/wPAAjVAoxeSgNeAAAAAElFTkSuQmCC) right repeat-y }`; var dom = acequire("../lib/dom"); dom.importCssString(exports.cssText, exports.cssClass); });
var express = require('express'); var path = require('path'); var favicon = require('static-favicon'); var logger = require('morgan'); var cookieParser = require('cookie-parser'); var bodyParser = require('body-parser'); var routes = require('./routes/index'); var users = require('./routes/users'); var app = express(); // view engine setup //app.use('views', path.join(__dirname, '/views')); //app.set('view engine', 'jade'); app.use(favicon()); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded()); app.use(cookieParser()); //app.use(express.static(path.join(__dirname, 'public'))); var staticDir = __dirname + '/public'; app.use(express.static(staticDir)); app.use('/views', express.static(staticDir + '/views')); //app.use('/', routes); //app.use('/users', users); app.use(function(req, res, next){ console.log("This is from Middleware... : %j", req.url); next(); }); app.get('/', function(req, res){ res.sendfile(staticDir + '/views/print.html'); }); /// 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;
'use strict'; /*global SVGjsAnim */ SVGjsAnim.prototype.setupReceiving = function() { var scale = 1.1; var x = 150; var y = 0; var w = 950; var h = 450; this.wistiaObjs.receiving = this.wistiaEmbed('wy0jb1fb5d'); // Heading var heading = this.draw.heading('RECEIVING', this.wistiaObjs.receiving) .move(355, 50); this.headings.receiving = this.draw.set().add(heading); var step = this.steps.receiving = this.draw.step('receiving') .move(x, y) .data({ id: 'step-receiving' }) .setScene(this.scene) .setHeading(heading) .scale(scale); // Dump Truck var truckScale = 0.8; var truckX = -300; var truckY = 285; this.dumpTruck = this.draw.truck(truckX, truckY) .scale(truckScale) .setDumpAt(415, truckY); step.content(this.dumpTruck); // Rock Breaker this.rockBreakerScale = 0.8; this.rockBreakerX = 555; this.rockBreakerY = 285; this.rockBreaker = this.draw.rockBreaker( { x: this.rockBreakerX, y: this.rockBreakerY , scale: this.rockBreakerScale } ); step.content(this.rockBreaker); // Rock Breaker Ore Pile var orePileRockBreaker = this.draw.image('images/ore/ore_pile_2.svg', 86, 37) .move(705, 400) .scale(0.8); step.content(orePileRockBreaker); // Bullets var bulletsGroup = this.bullets.receiving = this.draw.group() .attr({ id: 'bullets-receiving' }) .move(680, 120) .attr({ opacity: 0 }) .scale(0.75); var bullets = [ 'TWO SIDED DUMP\nWITH 80 TONNE\nPOCKET CAPACITY', 'GRIZZLY CAPTURES\nORE >16"', 'ROCK BREAKER BREAKS\nCAPTURED ORE', 'APRON FEEDER\nCONTROLS VOLUME\nMOVING TO CRUSHER' ]; bulletsGroup.add( this.draw.bullets(bullets, 300) ); step.content(bulletsGroup); // Building wall (ore dumps behind) step.content( this.draw.line(249.1, 300, 249.1, 378) .stroke({ width: 12, color: '#0089cf' }) .move(551, 253) ); // Zoom-in var stepToScale = 4 , stepToX = -1620 , stepToY = 50; if (this.isAspectRatio('4:3')) { stepToY = 250; } var zoom = this.draw.zoom({ width: w , height: h , id: 'receiving' , scale: stepToScale , zx: stepToX , zy: stepToY }) .video(605, 63); step.setZoom(zoom); //@TODO create moveContent() step._content.move(119.5, -20); return step; };
const client = require('cheerio-httpcli'); const mysql = require('mysql'); const conn = mysql.createConnection({ host : 'localhost', user : 'root', password : 'Do_you_love_MySQL57?', database: 'spajam2017' }) conn.connect() let animes = [] const isExit = spot_num => { client.fetch(`https://seichimap.jp/spots/${spot_num}`, function (err, $, res) { if(spot_num === 5000){ // 終わった console.log(err) let anime_list = Array.from(new Set(animes)) write_db(anime_list) return false } if(err){ isExit(spot_num + 1) } if(!err){ let spot = { name: $('.detail-info .spots-name').text(), anime: $('.detail-info .spots-anime').text(), address: $('.detail-info .spots-addr').text(), lat: $('.detail-info .spots-distance').attr('data-spot-lat'), lng: $('.detail-info .spots-distance').attr('data-spot-lng'), image: $('.detail-phatos-item img').attr('src') } animes.push(spot.anime) console.log(spot_num, spot) isExit(spot_num + 1) } }) } const write_db = list => { let sql = `INSERT INTO anime (title) values (?) ` conn.query(sql,list[0] , function(err) { list.shift() if(list.length === 0){ conn.end() return false } else { write_db(list) } }) } // start isExit(1)
"use babel" // @flow import type { Info, Suggestion, Range } from "../types" export default function findDestination( info: Info, suggestion: ?Suggestion, ): Range { if (!suggestion) throw new Error("suggestion required") if (info.parseError) throw info.parseError const { exports } = info if (suggestion.type === "binding") { return { start: suggestion.start, end: suggestion.end, } } else if (suggestion.imported) { let target = exports[suggestion.imported] if (!target) { target = exports.default } return target } else { throw new Error("Invalid suggestion type") } }
/* eslint-disable import/no-named-as-default-member */ import func from '../../../../src/evaluate-by-operator/operator/equal'; describe('equal operator', () => { it('should set SYMBOL const', () => { expect(func.SYMBOL).toBe('='); }); it('should correctly process values', () => { expect(func(2, 8.8)).toBe(false); expect(func('2', 8.8)).toBe(false); expect(func(1, '1')).toBe(false); expect(func(void 0, null)).toBe(false); expect(func(0, null)).toBe(false); expect(func(0, void 0)).toBe(false); expect(func(1, 1)).toBe(true); expect(func(null, null)).toBe(true); expect(func(void 0, void 0)).toBe(true); }); });
#!/usr/bin/nodejs /** * LearnYouNode Workshop * Step 03 - Il mio primo I/O * * author: Maurizio Aru * created: 2017.10.26 */ var fs = require('fs'); if (process.argv.length < 3) { console.error("ERROR: arguments missing"); return 1; } var contents = fs.readFileSync(process.argv[2]) var lines = contents.toString().split('\n').length - 1 console.log(lines)
'use strict'; module.exports = function(options, imports, register) { var debug = imports.debug('apps:www'); debug('start'); var app = require('./server/routes')(options, imports); debug('register www'); register(null, { www: app }); };
/** * Imports */ import React from 'react'; import {Button, Icon, Row, Col} from 'react-materialize' import Input from 'components/text_input' export default class NewOidModal extends React.Component { constructor(props) { super(props); this.state = { title: '', form: { name: '', value: '' } } } handleTextInputChange = (name) => { return (e) => { let form = this.state.form; form[name] = e.target.value; this.setState({ form }); } } getData = () => { return this.state.form; } isValid = () => { return true; } /** * Open */ open(options) { this.setState(options); $(this.refs.modal).openModal(); } /** * Close */ close = () => { $(this.refs.modal).closeModal(); } render () { return ( <div ref="modal" className={'noselect modal modal-fixed-header' + (this.props.className ? ' ' + this.props.className : '')}> <div className={"modal-header " + this.props.headerColor}> <h4>{this.props.title}</h4> <div className="modal-close" onClick={this.close}> <Icon>close</Icon> </div> </div> <div className="modal-content"> <Row> <Input label="SMNP OID" s={12} value={this.state.form.value} onChange={this.handleTextInputChange("value")}/> <Input label="DESCRIÇÃO" s={12} value={this.state.form.name} onChange={this.handleTextInputChange("name")}/> </Row> </div> <div className="modal-footer"> <Button waves='light' className="green" onClick={this.props.registerCallback}>ADICIONAR</Button> <Button waves='light' className="blue" onClick={this.close}>CANCELAR</Button> </div> </div> ); } }
'use strict' let co = require('co') let cli = require('heroku-cli-util') let helpers = require('../lib/helpers') let logDisplayer = require('../lib/log_displayer') let Dyno = require('../lib/dyno') function * run (context, heroku) { let opts = { heroku: heroku, app: context.app, command: helpers.buildCommand(context.args), size: context.flags.size, env: context.flags.env, attach: false } if (!opts.command) throw new Error('Usage: heroku run COMMAND\n\nExample: heroku run bash') let dyno = new Dyno(opts) yield dyno.start() if (context.flags.tail) { yield logDisplayer(heroku, { app: context.app, dyno: dyno.dyno.name, tail: true }) } else { cli.log(`Run ${cli.color.cmd('heroku logs --app ' + dyno.opts.app + ' --dyno ' + dyno.dyno.name)} to view the output.`) } } module.exports = { topic: 'run', command: 'detached', description: 'run a detached dyno, where output is sent to your logs', help: ` Example: $ heroku run:detached ls Running ls on app [detached]... up, run.1 Run heroku logs -a app -p run.1 to view the output. `, variableArgs: true, needsAuth: true, needsApp: true, flags: [ {name: 'size', char: 's', description: 'dyno size', hasValue: true}, {name: 'tail', char: 't', description: 'stream logs from the dyno'}, {name: 'env', char: 'e', description: "environment variables to set (use ';' to split multiple vars)", hasValue: true} ], run: cli.command(co.wrap(run)) }
import Vue from 'vue' import Vuex from 'vuex' import createLogger from 'vuex/dist/logger' import vuexI18n from 'vuex-i18n' import { mutations, state } from './mutations' import * as actions from './actions' import * as getters from './getters' import langEn from 'src/lang/en' Vue.use(Vuex) const store = new Vuex.Store({ state, mutations, actions, getters, strict: process.env.NODE_ENV !== 'production', plugins: process.env.NODE_ENV !== 'production' ? [createLogger()] : [] }) Vue.use(vuexI18n.plugin, store) // add translations to the application Vue.i18n.add('en', langEn) // set the start locale to use Vue.i18n.set('en') export default store
"use strict"; var fs = require("fs"), path = require("path"); var config = require("./config"); var utils = require("./utils"); module.exports = function(req, res, next){ res.locals.basedir = req.app.get("views"); res.locals.client_id = config.client_id; res.locals.user = req.cookies.user; res.locals.auth_url = utils.authURL(req.get("User-Agent")); res.locals.service = res.serviceLoad; res.locals.hostname = config.domain; res.locals.port = config.port; res.locals.electron = req.get("User-Agent").indexOf("Electron") > -1; if (req.query && req.query.message){ res.locals.message = req.query.message; } var file = res.path; if (!file){ file = req.path == "/" ? "/index" : req.path; } file = file.substring(1, file.substring(file.length - 1, file.length) == "/" ? file.length - 1 : file.length ); if (fs.existsSync(path.join("static", file))){ res.end(); next(); } else { if (fs.existsSync(path.join("static", file + ".pug"))){ res.render(file, function(error, html){ if (error){ res.end(); console.log(error); } else { res.send(html); next(); } }); } else { res.redirect("/"); } } };
/// <reference path="../Assets/Vectors/Vector2d.ts" /> /// <reference path="Collidable.ts" /> var EndGate; (function (EndGate) { (function (Collision) { /** * Defines a data object that is used to describe a collision event. */ var CollisionData = (function () { /** * Creates a new instance of the CollisionData object. * @param w Initial value of the With component of CollisionData. */ function CollisionData(w) { this.With = w; } return CollisionData; })(); Collision.CollisionData = CollisionData; })(EndGate.Collision || (EndGate.Collision = {})); var Collision = EndGate.Collision; })(EndGate || (EndGate = {}));
/** * Copyright 2014 Qiyi Inc. All rights reserved. * * @file: Simple.Dao.js * @path: js-src/simple/ * @desc: 负责Simple模块远程调用的静态对象 * @author: [email protected] * @date: 2014-7-14 */ define( [ './Simple' ], function(Simple) { Simple.Dao = Arm.create('Dao', { name: 'Simple.Dao', // TODO: ajax list getList: function(data, handle, url) { url = url || './data/list.json'; console.log('Simple.Dao.getList:', arguments); // 不使用this,则在class调用时可以直接调用,而无须闭包调用 // Simple.Dao.ajax(url, 'GET', data, handle); // this.ajax 继承自Base.Dao // 静态方法集合里使用this,要注意this指针可能更改的问题 $.ajax(url, 'GET', data, handle); } }); } );
/** * Sinon.JS 1.10.3, 2014/07/11 * * @author Christian Johansen ([email protected]) * @author Contributors: https://github.com/cjohansen/Sinon.JS/blob/master/AUTHORS * * (The BSD License) * * Copyright (c) 2010-2014, Christian Johansen, [email protected] * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of Christian Johansen nor the names of his contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ this.sinon = (function () { var samsam, formatio; function define(mod, deps, fn) { if (mod == "samsam") { samsam = deps(); } else if (typeof fn === "function") { formatio = fn(samsam); } } define.amd = {}; ((typeof define === "function" && define.amd && function (m) { define("samsam", m); }) || (typeof module === "object" && function (m) { module.exports = m(); }) || // Node function (m) { this.samsam = m(); } // Browser globals )(function () { var o = Object.prototype; var div = typeof document !== "undefined" && document.createElement("div"); function isNaN(value) { // Unlike global isNaN, this avoids type coercion // typeof check avoids IE host object issues, hat tip to // lodash var val = value; // JsLint thinks value !== value is "weird" return typeof value === "number" && value !== val; } function getClass(value) { // Returns the internal [[Class]] by calling Object.prototype.toString // with the provided value as this. Return value is a string, naming the // internal class, e.g. "Array" return o.toString.call(value).split(/[ \]]/)[1]; } /** * @name samsam.isArguments * @param Object object * * Returns ``true`` if ``object`` is an ``arguments`` object, * ``false`` otherwise. */ function isArguments(object) { if (typeof object !== "object" || typeof object.length !== "number" || getClass(object) === "Array") { return false; } if (typeof object.callee == "function") { return true; } try { object[object.length] = 6; delete object[object.length]; } catch (e) { return true; } return false; } /** * @name samsam.isElement * @param Object object * * Returns ``true`` if ``object`` is a DOM element node. Unlike * Underscore.js/lodash, this function will return ``false`` if ``object`` * is an *element-like* object, i.e. a regular object with a ``nodeType`` * property that holds the value ``1``. */ function isElement(object) { if (!object || object.nodeType !== 1 || !div) { return false; } try { object.appendChild(div); object.removeChild(div); } catch (e) { return false; } return true; } /** * @name samsam.keys * @param Object object * * Return an array of own property names. */ function keys(object) { var ks = [], prop; for (prop in object) { if (o.hasOwnProperty.call(object, prop)) { ks.push(prop); } } return ks; } /** * @name samsam.isDate * @param Object value * * Returns true if the object is a ``Date``, or *date-like*. Duck typing * of date objects work by checking that the object has a ``getTime`` * function whose return value equals the return value from the object's * ``valueOf``. */ function isDate(value) { return typeof value.getTime == "function" && value.getTime() == value.valueOf(); } /** * @name samsam.isNegZero * @param Object value * * Returns ``true`` if ``value`` is ``-0``. */ function isNegZero(value) { return value === 0 && 1 / value === -Infinity; } /** * @name samsam.equal * @param Object obj1 * @param Object obj2 * * Returns ``true`` if two objects are strictly equal. Compared to * ``===`` there are two exceptions: * * - NaN is considered equal to NaN * - -0 and +0 are not considered equal */ function identical(obj1, obj2) { if (obj1 === obj2 || (isNaN(obj1) && isNaN(obj2))) { return obj1 !== 0 || isNegZero(obj1) === isNegZero(obj2); } } /** * @name samsam.deepEqual * @param Object obj1 * @param Object obj2 * * Deep equal comparison. Two values are "deep equal" if: * * - They are equal, according to samsam.identical * - They are both date objects representing the same time * - They are both arrays containing elements that are all deepEqual * - They are objects with the same set of properties, and each property * in ``obj1`` is deepEqual to the corresponding property in ``obj2`` * * Supports cyclic objects. */ function deepEqualCyclic(obj1, obj2) { // used for cyclic comparison // contain already visited objects var objects1 = [], objects2 = [], // contain pathes (position in the object structure) // of the already visited objects // indexes same as in objects arrays paths1 = [], paths2 = [], // contains combinations of already compared objects // in the manner: { "$1['ref']$2['ref']": true } compared = {}; /** * used to check, if the value of a property is an object * (cyclic logic is only needed for objects) * only needed for cyclic logic */ function isObject(value) { if (typeof value === 'object' && value !== null && !(value instanceof Boolean) && !(value instanceof Date) && !(value instanceof Number) && !(value instanceof RegExp) && !(value instanceof String)) { return true; } return false; } /** * returns the index of the given object in the * given objects array, -1 if not contained * only needed for cyclic logic */ function getIndex(objects, obj) { var i; for (i = 0; i < objects.length; i++) { if (objects[i] === obj) { return i; } } return -1; } // does the recursion for the deep equal check return (function deepEqual(obj1, obj2, path1, path2) { var type1 = typeof obj1; var type2 = typeof obj2; // == null also matches undefined if (obj1 === obj2 || isNaN(obj1) || isNaN(obj2) || obj1 == null || obj2 == null || type1 !== "object" || type2 !== "object") { return identical(obj1, obj2); } // Elements are only equal if identical(expected, actual) if (isElement(obj1) || isElement(obj2)) { return false; } var isDate1 = isDate(obj1), isDate2 = isDate(obj2); if (isDate1 || isDate2) { if (!isDate1 || !isDate2 || obj1.getTime() !== obj2.getTime()) { return false; } } if (obj1 instanceof RegExp && obj2 instanceof RegExp) { if (obj1.toString() !== obj2.toString()) { return false; } } var class1 = getClass(obj1); var class2 = getClass(obj2); var keys1 = keys(obj1); var keys2 = keys(obj2); if (isArguments(obj1) || isArguments(obj2)) { if (obj1.length !== obj2.length) { return false; } } else { if (type1 !== type2 || class1 !== class2 || keys1.length !== keys2.length) { return false; } } var key, i, l, // following vars are used for the cyclic logic value1, value2, isObject1, isObject2, index1, index2, newPath1, newPath2; for (i = 0, l = keys1.length; i < l; i++) { key = keys1[i]; if (!o.hasOwnProperty.call(obj2, key)) { return false; } // Start of the cyclic logic value1 = obj1[key]; value2 = obj2[key]; isObject1 = isObject(value1); isObject2 = isObject(value2); // determine, if the objects were already visited // (it's faster to check for isObject first, than to // get -1 from getIndex for non objects) index1 = isObject1 ? getIndex(objects1, value1) : -1; index2 = isObject2 ? getIndex(objects2, value2) : -1; // determine the new pathes of the objects // - for non cyclic objects the current path will be extended // by current property name // - for cyclic objects the stored path is taken newPath1 = index1 !== -1 ? paths1[index1] : path1 + '[' + JSON.stringify(key) + ']'; newPath2 = index2 !== -1 ? paths2[index2] : path2 + '[' + JSON.stringify(key) + ']'; // stop recursion if current objects are already compared if (compared[newPath1 + newPath2]) { return true; } // remember the current objects and their pathes if (index1 === -1 && isObject1) { objects1.push(value1); paths1.push(newPath1); } if (index2 === -1 && isObject2) { objects2.push(value2); paths2.push(newPath2); } // remember that the current objects are already compared if (isObject1 && isObject2) { compared[newPath1 + newPath2] = true; } // End of cyclic logic // neither value1 nor value2 is a cycle // continue with next level if (!deepEqual(value1, value2, newPath1, newPath2)) { return false; } } return true; }(obj1, obj2, '$1', '$2')); } var match; function arrayContains(array, subset) { if (subset.length === 0) { return true; } var i, l, j, k; for (i = 0, l = array.length; i < l; ++i) { if (match(array[i], subset[0])) { for (j = 0, k = subset.length; j < k; ++j) { if (!match(array[i + j], subset[j])) { return false; } } return true; } } return false; } /** * @name samsam.match * @param Object object * @param Object matcher * * Compare arbitrary value ``object`` with matcher. */ match = function match(object, matcher) { if (matcher && typeof matcher.test === "function") { return matcher.test(object); } if (typeof matcher === "function") { return matcher(object) === true; } if (typeof matcher === "string") { matcher = matcher.toLowerCase(); var notNull = typeof object === "string" || !!object; return notNull && (String(object)).toLowerCase().indexOf(matcher) >= 0; } if (typeof matcher === "number") { return matcher === object; } if (typeof matcher === "boolean") { return matcher === object; } if (getClass(object) === "Array" && getClass(matcher) === "Array") { return arrayContains(object, matcher); } if (matcher && typeof matcher === "object") { var prop; for (prop in matcher) { if (!match(object[prop], matcher[prop])) { return false; } } return true; } throw new Error("Matcher was not a string, a number, a " + "function, a boolean or an object"); }; return { isArguments: isArguments, isElement: isElement, isDate: isDate, isNegZero: isNegZero, identical: identical, deepEqual: deepEqualCyclic, match: match, keys: keys }; }); ((typeof define === "function" && define.amd && function (m) { define("formatio", ["samsam"], m); }) || (typeof module === "object" && function (m) { module.exports = m(require("samsam")); }) || function (m) { this.formatio = m(this.samsam); } )(function (samsam) { var formatio = { excludeConstructors: ["Object", /^.$/], quoteStrings: true }; var hasOwn = Object.prototype.hasOwnProperty; var specialObjects = []; if (typeof global !== "undefined") { specialObjects.push({ object: global, value: "[object global]" }); } if (typeof document !== "undefined") { specialObjects.push({ object: document, value: "[object HTMLDocument]" }); } if (typeof window !== "undefined") { specialObjects.push({ object: window, value: "[object Window]" }); } function functionName(func) { if (!func) { return ""; } if (func.displayName) { return func.displayName; } if (func.name) { return func.name; } var matches = func.toString().match(/function\s+([^\(]+)/m); return (matches && matches[1]) || ""; } function constructorName(f, object) { var name = functionName(object && object.constructor); var excludes = f.excludeConstructors || formatio.excludeConstructors || []; var i, l; for (i = 0, l = excludes.length; i < l; ++i) { if (typeof excludes[i] === "string" && excludes[i] === name) { return ""; } else if (excludes[i].test && excludes[i].test(name)) { return ""; } } return name; } function isCircular(object, objects) { if (typeof object !== "object") { return false; } var i, l; for (i = 0, l = objects.length; i < l; ++i) { if (objects[i] === object) { return true; } } return false; } function ascii(f, object, processed, indent) { if (typeof object === "string") { var qs = f.quoteStrings; var quote = typeof qs !== "boolean" || qs; return processed || quote ? '"' + object + '"' : object; } if (typeof object === "function" && !(object instanceof RegExp)) { return ascii.func(object); } processed = processed || []; if (isCircular(object, processed)) { return "[Circular]"; } if (Object.prototype.toString.call(object) === "[object Array]") { return ascii.array.call(f, object, processed); } if (!object) { return String((1/object) === -Infinity ? "-0" : object); } if (samsam.isElement(object)) { return ascii.element(object); } if (typeof object.toString === "function" && object.toString !== Object.prototype.toString) { return object.toString(); } var i, l; for (i = 0, l = specialObjects.length; i < l; i++) { if (object === specialObjects[i].object) { return specialObjects[i].value; } } return ascii.object.call(f, object, processed, indent); } ascii.func = function (func) { return "function " + functionName(func) + "() {}"; }; ascii.array = function (array, processed) { processed = processed || []; processed.push(array); var i, l, pieces = []; for (i = 0, l = array.length; i < l; ++i) { pieces.push(ascii(this, array[i], processed)); } return "[" + pieces.join(", ") + "]"; }; ascii.object = function (object, processed, indent) { processed = processed || []; processed.push(object); indent = indent || 0; var pieces = [], properties = samsam.keys(object).sort(); var length = 3; var prop, str, obj, i, l; for (i = 0, l = properties.length; i < l; ++i) { prop = properties[i]; obj = object[prop]; if (isCircular(obj, processed)) { str = "[Circular]"; } else { str = ascii(this, obj, processed, indent + 2); } str = (/\s/.test(prop) ? '"' + prop + '"' : prop) + ": " + str; length += str.length; pieces.push(str); } var cons = constructorName(this, object); var prefix = cons ? "[" + cons + "] " : ""; var is = ""; for (i = 0, l = indent; i < l; ++i) { is += " "; } if (length + indent > 80) { return prefix + "{\n " + is + pieces.join(",\n " + is) + "\n" + is + "}"; } return prefix + "{ " + pieces.join(", ") + " }"; }; ascii.element = function (element) { var tagName = element.tagName.toLowerCase(); var attrs = element.attributes, attr, pairs = [], attrName, i, l, val; for (i = 0, l = attrs.length; i < l; ++i) { attr = attrs.item(i); attrName = attr.nodeName.toLowerCase().replace("html:", ""); val = attr.nodeValue; if (attrName !== "contenteditable" || val !== "inherit") { if (!!val) { pairs.push(attrName + "=\"" + val + "\""); } } } var formatted = "<" + tagName + (pairs.length > 0 ? " " : ""); var content = element.innerHTML; if (content.length > 20) { content = content.substr(0, 20) + "[...]"; } var res = formatted + pairs.join(" ") + ">" + content + "</" + tagName + ">"; return res.replace(/ contentEditable="inherit"/, ""); }; function Formatio(options) { for (var opt in options) { this[opt] = options[opt]; } } Formatio.prototype = { functionName: functionName, configure: function (options) { return new Formatio(options); }, constructorName: function (object) { return constructorName(this, object); }, ascii: function (object, processed, indent) { return ascii(this, object, processed, indent); } }; return Formatio.prototype; }); /*jslint eqeqeq: false, onevar: false, forin: true, nomen: false, regexp: false, plusplus: false*/ /*global module, require, __dirname, document*/ /** * Sinon core utilities. For internal use only. * * @author Christian Johansen ([email protected]) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ var sinon = (function (formatio) { var div = typeof document != "undefined" && document.createElement("div"); var hasOwn = Object.prototype.hasOwnProperty; function isDOMNode(obj) { var success = false; try { obj.appendChild(div); success = div.parentNode == obj; } catch (e) { return false; } finally { try { obj.removeChild(div); } catch (e) { // Remove failed, not much we can do about that } } return success; } function isElement(obj) { return div && obj && obj.nodeType === 1 && isDOMNode(obj); } function isFunction(obj) { return typeof obj === "function" || !!(obj && obj.constructor && obj.call && obj.apply); } function isReallyNaN(val) { return typeof val === 'number' && isNaN(val); } function mirrorProperties(target, source) { for (var prop in source) { if (!hasOwn.call(target, prop)) { target[prop] = source[prop]; } } } function isRestorable (obj) { return typeof obj === "function" && typeof obj.restore === "function" && obj.restore.sinon; } var sinon = { wrapMethod: function wrapMethod(object, property, method) { if (!object) { throw new TypeError("Should wrap property of object"); } if (typeof method != "function") { throw new TypeError("Method wrapper should be function"); } var wrappedMethod = object[property], error; if (!isFunction(wrappedMethod)) { error = new TypeError("Attempted to wrap " + (typeof wrappedMethod) + " property " + property + " as function"); } else if (wrappedMethod.restore && wrappedMethod.restore.sinon) { error = new TypeError("Attempted to wrap " + property + " which is already wrapped"); } else if (wrappedMethod.calledBefore) { var verb = !!wrappedMethod.returns ? "stubbed" : "spied on"; error = new TypeError("Attempted to wrap " + property + " which is already " + verb); } if (error) { if (wrappedMethod && wrappedMethod._stack) { error.stack += '\n--------------\n' + wrappedMethod._stack; } throw error; } // IE 8 does not support hasOwnProperty on the window object and Firefox has a problem // when using hasOwn.call on objects from other frames. var owned = object.hasOwnProperty ? object.hasOwnProperty(property) : hasOwn.call(object, property); object[property] = method; method.displayName = property; // Set up a stack trace which can be used later to find what line of // code the original method was created on. method._stack = (new Error('Stack Trace for original')).stack; method.restore = function () { // For prototype properties try to reset by delete first. // If this fails (ex: localStorage on mobile safari) then force a reset // via direct assignment. if (!owned) { delete object[property]; } if (object[property] === method) { object[property] = wrappedMethod; } }; method.restore.sinon = true; mirrorProperties(method, wrappedMethod); return method; }, extend: function extend(target) { for (var i = 1, l = arguments.length; i < l; i += 1) { for (var prop in arguments[i]) { if (arguments[i].hasOwnProperty(prop)) { target[prop] = arguments[i][prop]; } // DONT ENUM bug, only care about toString if (arguments[i].hasOwnProperty("toString") && arguments[i].toString != target.toString) { target.toString = arguments[i].toString; } } } return target; }, create: function create(proto) { var F = function () {}; F.prototype = proto; return new F(); }, deepEqual: function deepEqual(a, b) { if (sinon.match && sinon.match.isMatcher(a)) { return a.test(b); } if (typeof a != 'object' || typeof b != 'object') { if (isReallyNaN(a) && isReallyNaN(b)) { return true; } else { return a === b; } } if (isElement(a) || isElement(b)) { return a === b; } if (a === b) { return true; } if ((a === null && b !== null) || (a !== null && b === null)) { return false; } if (a instanceof RegExp && b instanceof RegExp) { return (a.source === b.source) && (a.global === b.global) && (a.ignoreCase === b.ignoreCase) && (a.multiline === b.multiline); } var aString = Object.prototype.toString.call(a); if (aString != Object.prototype.toString.call(b)) { return false; } if (aString == "[object Date]") { return a.valueOf() === b.valueOf(); } var prop, aLength = 0, bLength = 0; if (aString == "[object Array]" && a.length !== b.length) { return false; } for (prop in a) { aLength += 1; if (!(prop in b)) { return false; } if (!deepEqual(a[prop], b[prop])) { return false; } } for (prop in b) { bLength += 1; } return aLength == bLength; }, functionName: function functionName(func) { var name = func.displayName || func.name; // Use function decomposition as a last resort to get function // name. Does not rely on function decomposition to work - if it // doesn't debugging will be slightly less informative // (i.e. toString will say 'spy' rather than 'myFunc'). if (!name) { var matches = func.toString().match(/function ([^\s\(]+)/); name = matches && matches[1]; } return name; }, functionToString: function toString() { if (this.getCall && this.callCount) { var thisValue, prop, i = this.callCount; while (i--) { thisValue = this.getCall(i).thisValue; for (prop in thisValue) { if (thisValue[prop] === this) { return prop; } } } } return this.displayName || "sinon fake"; }, getConfig: function (custom) { var config = {}; custom = custom || {}; var defaults = sinon.defaultConfig; for (var prop in defaults) { if (defaults.hasOwnProperty(prop)) { config[prop] = custom.hasOwnProperty(prop) ? custom[prop] : defaults[prop]; } } return config; }, format: function (val) { return "" + val; }, defaultConfig: { injectIntoThis: true, injectInto: null, properties: ["spy", "stub", "mock", "clock", "server", "requests"], useFakeTimers: true, useFakeServer: true }, timesInWords: function timesInWords(count) { return count == 1 && "once" || count == 2 && "twice" || count == 3 && "thrice" || (count || 0) + " times"; }, calledInOrder: function (spies) { for (var i = 1, l = spies.length; i < l; i++) { if (!spies[i - 1].calledBefore(spies[i]) || !spies[i].called) { return false; } } return true; }, orderByFirstCall: function (spies) { return spies.sort(function (a, b) { // uuid, won't ever be equal var aCall = a.getCall(0); var bCall = b.getCall(0); var aId = aCall && aCall.callId || -1; var bId = bCall && bCall.callId || -1; return aId < bId ? -1 : 1; }); }, log: function () {}, logError: function (label, err) { var msg = label + " threw exception: "; sinon.log(msg + "[" + err.name + "] " + err.message); if (err.stack) { sinon.log(err.stack); } setTimeout(function () { err.message = msg + err.message; throw err; }, 0); }, typeOf: function (value) { if (value === null) { return "null"; } else if (value === undefined) { return "undefined"; } var string = Object.prototype.toString.call(value); return string.substring(8, string.length - 1).toLowerCase(); }, createStubInstance: function (constructor) { if (typeof constructor !== "function") { throw new TypeError("The constructor should be a function."); } return sinon.stub(sinon.create(constructor.prototype)); }, restore: function (object) { if (object !== null && typeof object === "object") { for (var prop in object) { if (isRestorable(object[prop])) { object[prop].restore(); } } } else if (isRestorable(object)) { object.restore(); } } }; var isNode = typeof module !== "undefined" && module.exports && typeof require == "function"; var isAMD = typeof define === 'function' && typeof define.amd === 'object' && define.amd; function makePublicAPI(require, exports, module) { module.exports = sinon; sinon.spy = require("./sinon/spy"); sinon.spyCall = require("./sinon/call"); sinon.behavior = require("./sinon/behavior"); sinon.stub = require("./sinon/stub"); sinon.mock = require("./sinon/mock"); sinon.collection = require("./sinon/collection"); sinon.assert = require("./sinon/assert"); sinon.sandbox = require("./sinon/sandbox"); sinon.test = require("./sinon/test"); sinon.testCase = require("./sinon/test_case"); sinon.match = require("./sinon/match"); } if (isAMD) { define(makePublicAPI); } else if (isNode) { try { formatio = require("formatio"); } catch (e) {} makePublicAPI(require, exports, module); } if (formatio) { var formatter = formatio.configure({ quoteStrings: false }); sinon.format = function () { return formatter.ascii.apply(formatter, arguments); }; } else if (isNode) { try { var util = require("util"); sinon.format = function (value) { return typeof value == "object" && value.toString === Object.prototype.toString ? util.inspect(value) : value; }; } catch (e) { /* Node, but no util module - would be very old, but better safe than sorry */ } } return sinon; }(typeof formatio == "object" && formatio)); /* @depend ../sinon.js */ /*jslint eqeqeq: false, onevar: false, plusplus: false*/ /*global module, require, sinon*/ /** * Match functions * * @author Maximilian Antoni ([email protected]) * @license BSD * * Copyright (c) 2012 Maximilian Antoni */ (function (sinon) { var commonJSModule = typeof module !== "undefined" && module.exports && typeof require == "function"; if (!sinon && commonJSModule) { sinon = require("../sinon"); } if (!sinon) { return; } function assertType(value, type, name) { var actual = sinon.typeOf(value); if (actual !== type) { throw new TypeError("Expected type of " + name + " to be " + type + ", but was " + actual); } } var matcher = { toString: function () { return this.message; } }; function isMatcher(object) { return matcher.isPrototypeOf(object); } function matchObject(expectation, actual) { if (actual === null || actual === undefined) { return false; } for (var key in expectation) { if (expectation.hasOwnProperty(key)) { var exp = expectation[key]; var act = actual[key]; if (match.isMatcher(exp)) { if (!exp.test(act)) { return false; } } else if (sinon.typeOf(exp) === "object") { if (!matchObject(exp, act)) { return false; } } else if (!sinon.deepEqual(exp, act)) { return false; } } } return true; } matcher.or = function (m2) { if (!arguments.length) { throw new TypeError("Matcher expected"); } else if (!isMatcher(m2)) { m2 = match(m2); } var m1 = this; var or = sinon.create(matcher); or.test = function (actual) { return m1.test(actual) || m2.test(actual); }; or.message = m1.message + ".or(" + m2.message + ")"; return or; }; matcher.and = function (m2) { if (!arguments.length) { throw new TypeError("Matcher expected"); } else if (!isMatcher(m2)) { m2 = match(m2); } var m1 = this; var and = sinon.create(matcher); and.test = function (actual) { return m1.test(actual) && m2.test(actual); }; and.message = m1.message + ".and(" + m2.message + ")"; return and; }; var match = function (expectation, message) { var m = sinon.create(matcher); var type = sinon.typeOf(expectation); switch (type) { case "object": if (typeof expectation.test === "function") { m.test = function (actual) { return expectation.test(actual) === true; }; m.message = "match(" + sinon.functionName(expectation.test) + ")"; return m; } var str = []; for (var key in expectation) { if (expectation.hasOwnProperty(key)) { str.push(key + ": " + expectation[key]); } } m.test = function (actual) { return matchObject(expectation, actual); }; m.message = "match(" + str.join(", ") + ")"; break; case "number": m.test = function (actual) { return expectation == actual; }; break; case "string": m.test = function (actual) { if (typeof actual !== "string") { return false; } return actual.indexOf(expectation) !== -1; }; m.message = "match(\"" + expectation + "\")"; break; case "regexp": m.test = function (actual) { if (typeof actual !== "string") { return false; } return expectation.test(actual); }; break; case "function": m.test = expectation; if (message) { m.message = message; } else { m.message = "match(" + sinon.functionName(expectation) + ")"; } break; default: m.test = function (actual) { return sinon.deepEqual(expectation, actual); }; } if (!m.message) { m.message = "match(" + expectation + ")"; } return m; }; match.isMatcher = isMatcher; match.any = match(function () { return true; }, "any"); match.defined = match(function (actual) { return actual !== null && actual !== undefined; }, "defined"); match.truthy = match(function (actual) { return !!actual; }, "truthy"); match.falsy = match(function (actual) { return !actual; }, "falsy"); match.same = function (expectation) { return match(function (actual) { return expectation === actual; }, "same(" + expectation + ")"); }; match.typeOf = function (type) { assertType(type, "string", "type"); return match(function (actual) { return sinon.typeOf(actual) === type; }, "typeOf(\"" + type + "\")"); }; match.instanceOf = function (type) { assertType(type, "function", "type"); return match(function (actual) { return actual instanceof type; }, "instanceOf(" + sinon.functionName(type) + ")"); }; function createPropertyMatcher(propertyTest, messagePrefix) { return function (property, value) { assertType(property, "string", "property"); var onlyProperty = arguments.length === 1; var message = messagePrefix + "(\"" + property + "\""; if (!onlyProperty) { message += ", " + value; } message += ")"; return match(function (actual) { if (actual === undefined || actual === null || !propertyTest(actual, property)) { return false; } return onlyProperty || sinon.deepEqual(value, actual[property]); }, message); }; } match.has = createPropertyMatcher(function (actual, property) { if (typeof actual === "object") { return property in actual; } return actual[property] !== undefined; }, "has"); match.hasOwn = createPropertyMatcher(function (actual, property) { return actual.hasOwnProperty(property); }, "hasOwn"); match.bool = match.typeOf("boolean"); match.number = match.typeOf("number"); match.string = match.typeOf("string"); match.object = match.typeOf("object"); match.func = match.typeOf("function"); match.array = match.typeOf("array"); match.regexp = match.typeOf("regexp"); match.date = match.typeOf("date"); sinon.match = match; if (typeof define === "function" && define.amd) { define(["module"], function(module) { module.exports = match; }); } else if (commonJSModule) { module.exports = match; } }(typeof sinon == "object" && sinon || null)); /** * @depend ../sinon.js * @depend match.js */ /*jslint eqeqeq: false, onevar: false, plusplus: false*/ /*global module, require, sinon*/ /** * Spy calls * * @author Christian Johansen ([email protected]) * @author Maximilian Antoni ([email protected]) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen * Copyright (c) 2013 Maximilian Antoni */ (function (sinon) { var commonJSModule = typeof module !== "undefined" && module.exports && typeof require == "function"; if (!sinon && commonJSModule) { sinon = require("../sinon"); } if (!sinon) { return; } function throwYieldError(proxy, text, args) { var msg = sinon.functionName(proxy) + text; if (args.length) { msg += " Received [" + slice.call(args).join(", ") + "]"; } throw new Error(msg); } var slice = Array.prototype.slice; var callProto = { calledOn: function calledOn(thisValue) { if (sinon.match && sinon.match.isMatcher(thisValue)) { return thisValue.test(this.thisValue); } return this.thisValue === thisValue; }, calledWith: function calledWith() { for (var i = 0, l = arguments.length; i < l; i += 1) { if (!sinon.deepEqual(arguments[i], this.args[i])) { return false; } } return true; }, calledWithMatch: function calledWithMatch() { for (var i = 0, l = arguments.length; i < l; i += 1) { var actual = this.args[i]; var expectation = arguments[i]; if (!sinon.match || !sinon.match(expectation).test(actual)) { return false; } } return true; }, calledWithExactly: function calledWithExactly() { return arguments.length == this.args.length && this.calledWith.apply(this, arguments); }, notCalledWith: function notCalledWith() { return !this.calledWith.apply(this, arguments); }, notCalledWithMatch: function notCalledWithMatch() { return !this.calledWithMatch.apply(this, arguments); }, returned: function returned(value) { return sinon.deepEqual(value, this.returnValue); }, threw: function threw(error) { if (typeof error === "undefined" || !this.exception) { return !!this.exception; } return this.exception === error || this.exception.name === error; }, calledWithNew: function calledWithNew() { return this.proxy.prototype && this.thisValue instanceof this.proxy; }, calledBefore: function (other) { return this.callId < other.callId; }, calledAfter: function (other) { return this.callId > other.callId; }, callArg: function (pos) { this.args[pos](); }, callArgOn: function (pos, thisValue) { this.args[pos].apply(thisValue); }, callArgWith: function (pos) { this.callArgOnWith.apply(this, [pos, null].concat(slice.call(arguments, 1))); }, callArgOnWith: function (pos, thisValue) { var args = slice.call(arguments, 2); this.args[pos].apply(thisValue, args); }, "yield": function () { this.yieldOn.apply(this, [null].concat(slice.call(arguments, 0))); }, yieldOn: function (thisValue) { var args = this.args; for (var i = 0, l = args.length; i < l; ++i) { if (typeof args[i] === "function") { args[i].apply(thisValue, slice.call(arguments, 1)); return; } } throwYieldError(this.proxy, " cannot yield since no callback was passed.", args); }, yieldTo: function (prop) { this.yieldToOn.apply(this, [prop, null].concat(slice.call(arguments, 1))); }, yieldToOn: function (prop, thisValue) { var args = this.args; for (var i = 0, l = args.length; i < l; ++i) { if (args[i] && typeof args[i][prop] === "function") { args[i][prop].apply(thisValue, slice.call(arguments, 2)); return; } } throwYieldError(this.proxy, " cannot yield to '" + prop + "' since no callback was passed.", args); }, toString: function () { var callStr = this.proxy.toString() + "("; var args = []; for (var i = 0, l = this.args.length; i < l; ++i) { args.push(sinon.format(this.args[i])); } callStr = callStr + args.join(", ") + ")"; if (typeof this.returnValue != "undefined") { callStr += " => " + sinon.format(this.returnValue); } if (this.exception) { callStr += " !" + this.exception.name; if (this.exception.message) { callStr += "(" + this.exception.message + ")"; } } return callStr; } }; callProto.invokeCallback = callProto.yield; function createSpyCall(spy, thisValue, args, returnValue, exception, id) { if (typeof id !== "number") { throw new TypeError("Call id is not a number"); } var proxyCall = sinon.create(callProto); proxyCall.proxy = spy; proxyCall.thisValue = thisValue; proxyCall.args = args; proxyCall.returnValue = returnValue; proxyCall.exception = exception; proxyCall.callId = id; return proxyCall; } createSpyCall.toString = callProto.toString; // used by mocks sinon.spyCall = createSpyCall; if (typeof define === "function" && define.amd) { define(["module"], function(module) { module.exports = createSpyCall; }); } else if (commonJSModule) { module.exports = createSpyCall; } }(typeof sinon == "object" && sinon || null)); /** * @depend ../sinon.js * @depend call.js */ /*jslint eqeqeq: false, onevar: false, plusplus: false*/ /*global module, require, sinon*/ /** * Spy functions * * @author Christian Johansen ([email protected]) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ (function (sinon) { var commonJSModule = typeof module !== "undefined" && module.exports && typeof require == "function"; var push = Array.prototype.push; var slice = Array.prototype.slice; var callId = 0; if (!sinon && commonJSModule) { sinon = require("../sinon"); } if (!sinon) { return; } function spy(object, property) { if (!property && typeof object == "function") { return spy.create(object); } if (!object && !property) { return spy.create(function () { }); } var method = object[property]; return sinon.wrapMethod(object, property, spy.create(method)); } function matchingFake(fakes, args, strict) { if (!fakes) { return; } for (var i = 0, l = fakes.length; i < l; i++) { if (fakes[i].matches(args, strict)) { return fakes[i]; } } } function incrementCallCount() { this.called = true; this.callCount += 1; this.notCalled = false; this.calledOnce = this.callCount == 1; this.calledTwice = this.callCount == 2; this.calledThrice = this.callCount == 3; } function createCallProperties() { this.firstCall = this.getCall(0); this.secondCall = this.getCall(1); this.thirdCall = this.getCall(2); this.lastCall = this.getCall(this.callCount - 1); } var vars = "a,b,c,d,e,f,g,h,i,j,k,l"; function createProxy(func) { // Retain the function length: var p; if (func.length) { eval("p = (function proxy(" + vars.substring(0, func.length * 2 - 1) + ") { return p.invoke(func, this, slice.call(arguments)); });"); } else { p = function proxy() { return p.invoke(func, this, slice.call(arguments)); }; } return p; } var uuid = 0; // Public API var spyApi = { reset: function () { this.called = false; this.notCalled = true; this.calledOnce = false; this.calledTwice = false; this.calledThrice = false; this.callCount = 0; this.firstCall = null; this.secondCall = null; this.thirdCall = null; this.lastCall = null; this.args = []; this.returnValues = []; this.thisValues = []; this.exceptions = []; this.callIds = []; if (this.fakes) { for (var i = 0; i < this.fakes.length; i++) { this.fakes[i].reset(); } } }, create: function create(func) { var name; if (typeof func != "function") { func = function () { }; } else { name = sinon.functionName(func); } var proxy = createProxy(func); sinon.extend(proxy, spy); delete proxy.create; sinon.extend(proxy, func); proxy.reset(); proxy.prototype = func.prototype; proxy.displayName = name || "spy"; proxy.toString = sinon.functionToString; proxy._create = sinon.spy.create; proxy.id = "spy#" + uuid++; return proxy; }, invoke: function invoke(func, thisValue, args) { var matching = matchingFake(this.fakes, args); var exception, returnValue; incrementCallCount.call(this); push.call(this.thisValues, thisValue); push.call(this.args, args); push.call(this.callIds, callId++); // Make call properties available from within the spied function: createCallProperties.call(this); try { if (matching) { returnValue = matching.invoke(func, thisValue, args); } else { returnValue = (this.func || func).apply(thisValue, args); } var thisCall = this.getCall(this.callCount - 1); if (thisCall.calledWithNew() && typeof returnValue !== 'object') { returnValue = thisValue; } } catch (e) { exception = e; } push.call(this.exceptions, exception); push.call(this.returnValues, returnValue); // Make return value and exception available in the calls: createCallProperties.call(this); if (exception !== undefined) { throw exception; } return returnValue; }, named: function named(name) { this.displayName = name; return this; }, getCall: function getCall(i) { if (i < 0 || i >= this.callCount) { return null; } return sinon.spyCall(this, this.thisValues[i], this.args[i], this.returnValues[i], this.exceptions[i], this.callIds[i]); }, getCalls: function () { var calls = []; var i; for (i = 0; i < this.callCount; i++) { calls.push(this.getCall(i)); } return calls; }, calledBefore: function calledBefore(spyFn) { if (!this.called) { return false; } if (!spyFn.called) { return true; } return this.callIds[0] < spyFn.callIds[spyFn.callIds.length - 1]; }, calledAfter: function calledAfter(spyFn) { if (!this.called || !spyFn.called) { return false; } return this.callIds[this.callCount - 1] > spyFn.callIds[spyFn.callCount - 1]; }, withArgs: function () { var args = slice.call(arguments); if (this.fakes) { var match = matchingFake(this.fakes, args, true); if (match) { return match; } } else { this.fakes = []; } var original = this; var fake = this._create(); fake.matchingAguments = args; fake.parent = this; push.call(this.fakes, fake); fake.withArgs = function () { return original.withArgs.apply(original, arguments); }; for (var i = 0; i < this.args.length; i++) { if (fake.matches(this.args[i])) { incrementCallCount.call(fake); push.call(fake.thisValues, this.thisValues[i]); push.call(fake.args, this.args[i]); push.call(fake.returnValues, this.returnValues[i]); push.call(fake.exceptions, this.exceptions[i]); push.call(fake.callIds, this.callIds[i]); } } createCallProperties.call(fake); return fake; }, matches: function (args, strict) { var margs = this.matchingAguments; if (margs.length <= args.length && sinon.deepEqual(margs, args.slice(0, margs.length))) { return !strict || margs.length == args.length; } }, printf: function (format) { var spy = this; var args = slice.call(arguments, 1); var formatter; return (format || "").replace(/%(.)/g, function (match, specifyer) { formatter = spyApi.formatters[specifyer]; if (typeof formatter == "function") { return formatter.call(null, spy, args); } else if (!isNaN(parseInt(specifyer, 10))) { return sinon.format(args[specifyer - 1]); } return "%" + specifyer; }); } }; function delegateToCalls(method, matchAny, actual, notCalled) { spyApi[method] = function () { if (!this.called) { if (notCalled) { return notCalled.apply(this, arguments); } return false; } var currentCall; var matches = 0; for (var i = 0, l = this.callCount; i < l; i += 1) { currentCall = this.getCall(i); if (currentCall[actual || method].apply(currentCall, arguments)) { matches += 1; if (matchAny) { return true; } } } return matches === this.callCount; }; } delegateToCalls("calledOn", true); delegateToCalls("alwaysCalledOn", false, "calledOn"); delegateToCalls("calledWith", true); delegateToCalls("calledWithMatch", true); delegateToCalls("alwaysCalledWith", false, "calledWith"); delegateToCalls("alwaysCalledWithMatch", false, "calledWithMatch"); delegateToCalls("calledWithExactly", true); delegateToCalls("alwaysCalledWithExactly", false, "calledWithExactly"); delegateToCalls("neverCalledWith", false, "notCalledWith", function () { return true; }); delegateToCalls("neverCalledWithMatch", false, "notCalledWithMatch", function () { return true; }); delegateToCalls("threw", true); delegateToCalls("alwaysThrew", false, "threw"); delegateToCalls("returned", true); delegateToCalls("alwaysReturned", false, "returned"); delegateToCalls("calledWithNew", true); delegateToCalls("alwaysCalledWithNew", false, "calledWithNew"); delegateToCalls("callArg", false, "callArgWith", function () { throw new Error(this.toString() + " cannot call arg since it was not yet invoked."); }); spyApi.callArgWith = spyApi.callArg; delegateToCalls("callArgOn", false, "callArgOnWith", function () { throw new Error(this.toString() + " cannot call arg since it was not yet invoked."); }); spyApi.callArgOnWith = spyApi.callArgOn; delegateToCalls("yield", false, "yield", function () { throw new Error(this.toString() + " cannot yield since it was not yet invoked."); }); // "invokeCallback" is an alias for "yield" since "yield" is invalid in strict mode. spyApi.invokeCallback = spyApi.yield; delegateToCalls("yieldOn", false, "yieldOn", function () { throw new Error(this.toString() + " cannot yield since it was not yet invoked."); }); delegateToCalls("yieldTo", false, "yieldTo", function (property) { throw new Error(this.toString() + " cannot yield to '" + property + "' since it was not yet invoked."); }); delegateToCalls("yieldToOn", false, "yieldToOn", function (property) { throw new Error(this.toString() + " cannot yield to '" + property + "' since it was not yet invoked."); }); spyApi.formatters = { "c": function (spy) { return sinon.timesInWords(spy.callCount); }, "n": function (spy) { return spy.toString(); }, "C": function (spy) { var calls = []; for (var i = 0, l = spy.callCount; i < l; ++i) { var stringifiedCall = " " + spy.getCall(i).toString(); if (/\n/.test(calls[i - 1])) { stringifiedCall = "\n" + stringifiedCall; } push.call(calls, stringifiedCall); } return calls.length > 0 ? "\n" + calls.join("\n") : ""; }, "t": function (spy) { var objects = []; for (var i = 0, l = spy.callCount; i < l; ++i) { push.call(objects, sinon.format(spy.thisValues[i])); } return objects.join(", "); }, "*": function (spy, args) { var formatted = []; for (var i = 0, l = args.length; i < l; ++i) { push.call(formatted, sinon.format(args[i])); } return formatted.join(", "); } }; sinon.extend(spy, spyApi); spy.spyCall = sinon.spyCall; sinon.spy = spy; if (typeof define === "function" && define.amd) { define(["module"], function(module) { module.exports = spy; }); } else if (commonJSModule) { module.exports = spy; } }(typeof sinon == "object" && sinon || null)); /** * @depend ../sinon.js */ /*jslint eqeqeq: false, onevar: false*/ /*global module, require, sinon, process, setImmediate, setTimeout*/ /** * Stub behavior * * @author Christian Johansen ([email protected]) * @author Tim Fischbach ([email protected]) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ (function (sinon) { var commonJSModule = typeof module !== "undefined" && module.exports && typeof require == "function"; if (!sinon && commonJSModule) { sinon = require("../sinon"); } if (!sinon) { return; } var slice = Array.prototype.slice; var join = Array.prototype.join; var proto; var nextTick = (function () { if (typeof process === "object" && typeof process.nextTick === "function") { return process.nextTick; } else if (typeof setImmediate === "function") { return setImmediate; } else { return function (callback) { setTimeout(callback, 0); }; } })(); function throwsException(error, message) { if (typeof error == "string") { this.exception = new Error(message || ""); this.exception.name = error; } else if (!error) { this.exception = new Error("Error"); } else { this.exception = error; } return this; } function getCallback(behavior, args) { var callArgAt = behavior.callArgAt; if (callArgAt < 0) { var callArgProp = behavior.callArgProp; for (var i = 0, l = args.length; i < l; ++i) { if (!callArgProp && typeof args[i] == "function") { return args[i]; } if (callArgProp && args[i] && typeof args[i][callArgProp] == "function") { return args[i][callArgProp]; } } return null; } return args[callArgAt]; } function getCallbackError(behavior, func, args) { if (behavior.callArgAt < 0) { var msg; if (behavior.callArgProp) { msg = sinon.functionName(behavior.stub) + " expected to yield to '" + behavior.callArgProp + "', but no object with such a property was passed."; } else { msg = sinon.functionName(behavior.stub) + " expected to yield, but no callback was passed."; } if (args.length > 0) { msg += " Received [" + join.call(args, ", ") + "]"; } return msg; } return "argument at index " + behavior.callArgAt + " is not a function: " + func; } function callCallback(behavior, args) { if (typeof behavior.callArgAt == "number") { var func = getCallback(behavior, args); if (typeof func != "function") { throw new TypeError(getCallbackError(behavior, func, args)); } if (behavior.callbackAsync) { nextTick(function() { func.apply(behavior.callbackContext, behavior.callbackArguments); }); } else { func.apply(behavior.callbackContext, behavior.callbackArguments); } } } proto = { create: function(stub) { var behavior = sinon.extend({}, sinon.behavior); delete behavior.create; behavior.stub = stub; return behavior; }, isPresent: function() { return (typeof this.callArgAt == 'number' || this.exception || typeof this.returnArgAt == 'number' || this.returnThis || this.returnValueDefined); }, invoke: function(context, args) { callCallback(this, args); if (this.exception) { throw this.exception; } else if (typeof this.returnArgAt == 'number') { return args[this.returnArgAt]; } else if (this.returnThis) { return context; } return this.returnValue; }, onCall: function(index) { return this.stub.onCall(index); }, onFirstCall: function() { return this.stub.onFirstCall(); }, onSecondCall: function() { return this.stub.onSecondCall(); }, onThirdCall: function() { return this.stub.onThirdCall(); }, withArgs: function(/* arguments */) { throw new Error('Defining a stub by invoking "stub.onCall(...).withArgs(...)" is not supported. ' + 'Use "stub.withArgs(...).onCall(...)" to define sequential behavior for calls with certain arguments.'); }, callsArg: function callsArg(pos) { if (typeof pos != "number") { throw new TypeError("argument index is not number"); } this.callArgAt = pos; this.callbackArguments = []; this.callbackContext = undefined; this.callArgProp = undefined; this.callbackAsync = false; return this; }, callsArgOn: function callsArgOn(pos, context) { if (typeof pos != "number") { throw new TypeError("argument index is not number"); } if (typeof context != "object") { throw new TypeError("argument context is not an object"); } this.callArgAt = pos; this.callbackArguments = []; this.callbackContext = context; this.callArgProp = undefined; this.callbackAsync = false; return this; }, callsArgWith: function callsArgWith(pos) { if (typeof pos != "number") { throw new TypeError("argument index is not number"); } this.callArgAt = pos; this.callbackArguments = slice.call(arguments, 1); this.callbackContext = undefined; this.callArgProp = undefined; this.callbackAsync = false; return this; }, callsArgOnWith: function callsArgWith(pos, context) { if (typeof pos != "number") { throw new TypeError("argument index is not number"); } if (typeof context != "object") { throw new TypeError("argument context is not an object"); } this.callArgAt = pos; this.callbackArguments = slice.call(arguments, 2); this.callbackContext = context; this.callArgProp = undefined; this.callbackAsync = false; return this; }, yields: function () { this.callArgAt = -1; this.callbackArguments = slice.call(arguments, 0); this.callbackContext = undefined; this.callArgProp = undefined; this.callbackAsync = false; return this; }, yieldsOn: function (context) { if (typeof context != "object") { throw new TypeError("argument context is not an object"); } this.callArgAt = -1; this.callbackArguments = slice.call(arguments, 1); this.callbackContext = context; this.callArgProp = undefined; this.callbackAsync = false; return this; }, yieldsTo: function (prop) { this.callArgAt = -1; this.callbackArguments = slice.call(arguments, 1); this.callbackContext = undefined; this.callArgProp = prop; this.callbackAsync = false; return this; }, yieldsToOn: function (prop, context) { if (typeof context != "object") { throw new TypeError("argument context is not an object"); } this.callArgAt = -1; this.callbackArguments = slice.call(arguments, 2); this.callbackContext = context; this.callArgProp = prop; this.callbackAsync = false; return this; }, "throws": throwsException, throwsException: throwsException, returns: function returns(value) { this.returnValue = value; this.returnValueDefined = true; return this; }, returnsArg: function returnsArg(pos) { if (typeof pos != "number") { throw new TypeError("argument index is not number"); } this.returnArgAt = pos; return this; }, returnsThis: function returnsThis() { this.returnThis = true; return this; } }; // create asynchronous versions of callsArg* and yields* methods for (var method in proto) { // need to avoid creating anotherasync versions of the newly added async methods if (proto.hasOwnProperty(method) && method.match(/^(callsArg|yields)/) && !method.match(/Async/)) { proto[method + 'Async'] = (function (syncFnName) { return function () { var result = this[syncFnName].apply(this, arguments); this.callbackAsync = true; return result; }; })(method); } } sinon.behavior = proto; if (typeof define === "function" && define.amd) { define(["module"], function(module) { module.exports = proto; }); } else if (commonJSModule) { module.exports = proto; } }(typeof sinon == "object" && sinon || null)); /** * @depend ../sinon.js * @depend spy.js * @depend behavior.js */ /*jslint eqeqeq: false, onevar: false*/ /*global module, require, sinon*/ /** * Stub functions * * @author Christian Johansen ([email protected]) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ (function (sinon) { var commonJSModule = typeof module !== "undefined" && module.exports && typeof require == "function"; if (!sinon && commonJSModule) { sinon = require("../sinon"); } if (!sinon) { return; } function stub(object, property, func) { if (!!func && typeof func != "function") { throw new TypeError("Custom stub should be function"); } var wrapper; if (func) { wrapper = sinon.spy && sinon.spy.create ? sinon.spy.create(func) : func; } else { wrapper = stub.create(); } if (!object && typeof property === "undefined") { return sinon.stub.create(); } if (typeof property === "undefined" && typeof object == "object") { for (var prop in object) { if (typeof object[prop] === "function") { stub(object, prop); } } return object; } return sinon.wrapMethod(object, property, wrapper); } function getDefaultBehavior(stub) { return stub.defaultBehavior || getParentBehaviour(stub) || sinon.behavior.create(stub); } function getParentBehaviour(stub) { return (stub.parent && getCurrentBehavior(stub.parent)); } function getCurrentBehavior(stub) { var behavior = stub.behaviors[stub.callCount - 1]; return behavior && behavior.isPresent() ? behavior : getDefaultBehavior(stub); } var uuid = 0; sinon.extend(stub, (function () { var proto = { create: function create() { var functionStub = function () { return getCurrentBehavior(functionStub).invoke(this, arguments); }; functionStub.id = "stub#" + uuid++; var orig = functionStub; functionStub = sinon.spy.create(functionStub); functionStub.func = orig; sinon.extend(functionStub, stub); functionStub._create = sinon.stub.create; functionStub.displayName = "stub"; functionStub.toString = sinon.functionToString; functionStub.defaultBehavior = null; functionStub.behaviors = []; return functionStub; }, resetBehavior: function () { var i; this.defaultBehavior = null; this.behaviors = []; delete this.returnValue; delete this.returnArgAt; this.returnThis = false; if (this.fakes) { for (i = 0; i < this.fakes.length; i++) { this.fakes[i].resetBehavior(); } } }, onCall: function(index) { if (!this.behaviors[index]) { this.behaviors[index] = sinon.behavior.create(this); } return this.behaviors[index]; }, onFirstCall: function() { return this.onCall(0); }, onSecondCall: function() { return this.onCall(1); }, onThirdCall: function() { return this.onCall(2); } }; for (var method in sinon.behavior) { if (sinon.behavior.hasOwnProperty(method) && !proto.hasOwnProperty(method) && method != 'create' && method != 'withArgs' && method != 'invoke') { proto[method] = (function(behaviorMethod) { return function() { this.defaultBehavior = this.defaultBehavior || sinon.behavior.create(this); this.defaultBehavior[behaviorMethod].apply(this.defaultBehavior, arguments); return this; }; }(method)); } } return proto; }())); sinon.stub = stub; if (typeof define === "function" && define.amd) { define(["module"], function(module) { module.exports = stub; }); } else if (commonJSModule) { module.exports = stub; } }(typeof sinon == "object" && sinon || null)); /** * @depend ../sinon.js * @depend stub.js */ /*jslint eqeqeq: false, onevar: false, nomen: false*/ /*global module, require, sinon*/ /** * Mock functions. * * @author Christian Johansen ([email protected]) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ (function (sinon) { var commonJSModule = typeof module !== "undefined" && module.exports && typeof require == "function"; var push = [].push; var match; if (!sinon && commonJSModule) { sinon = require("../sinon"); } if (!sinon) { return; } match = sinon.match; if (!match && commonJSModule) { match = require("./match"); } function mock(object) { if (!object) { return sinon.expectation.create("Anonymous mock"); } return mock.create(object); } sinon.mock = mock; sinon.extend(mock, (function () { function each(collection, callback) { if (!collection) { return; } for (var i = 0, l = collection.length; i < l; i += 1) { callback(collection[i]); } } return { create: function create(object) { if (!object) { throw new TypeError("object is null"); } var mockObject = sinon.extend({}, mock); mockObject.object = object; delete mockObject.create; return mockObject; }, expects: function expects(method) { if (!method) { throw new TypeError("method is falsy"); } if (!this.expectations) { this.expectations = {}; this.proxies = []; } if (!this.expectations[method]) { this.expectations[method] = []; var mockObject = this; sinon.wrapMethod(this.object, method, function () { return mockObject.invokeMethod(method, this, arguments); }); push.call(this.proxies, method); } var expectation = sinon.expectation.create(method); push.call(this.expectations[method], expectation); return expectation; }, restore: function restore() { var object = this.object; each(this.proxies, function (proxy) { if (typeof object[proxy].restore == "function") { object[proxy].restore(); } }); }, verify: function verify() { var expectations = this.expectations || {}; var messages = [], met = []; each(this.proxies, function (proxy) { each(expectations[proxy], function (expectation) { if (!expectation.met()) { push.call(messages, expectation.toString()); } else { push.call(met, expectation.toString()); } }); }); this.restore(); if (messages.length > 0) { sinon.expectation.fail(messages.concat(met).join("\n")); } else { sinon.expectation.pass(messages.concat(met).join("\n")); } return true; }, invokeMethod: function invokeMethod(method, thisValue, args) { var expectations = this.expectations && this.expectations[method]; var length = expectations && expectations.length || 0, i; for (i = 0; i < length; i += 1) { if (!expectations[i].met() && expectations[i].allowsCall(thisValue, args)) { return expectations[i].apply(thisValue, args); } } var messages = [], available, exhausted = 0; for (i = 0; i < length; i += 1) { if (expectations[i].allowsCall(thisValue, args)) { available = available || expectations[i]; } else { exhausted += 1; } push.call(messages, " " + expectations[i].toString()); } if (exhausted === 0) { return available.apply(thisValue, args); } messages.unshift("Unexpected call: " + sinon.spyCall.toString.call({ proxy: method, args: args })); sinon.expectation.fail(messages.join("\n")); } }; }())); var times = sinon.timesInWords; sinon.expectation = (function () { var slice = Array.prototype.slice; var _invoke = sinon.spy.invoke; function callCountInWords(callCount) { if (callCount == 0) { return "never called"; } else { return "called " + times(callCount); } } function expectedCallCountInWords(expectation) { var min = expectation.minCalls; var max = expectation.maxCalls; if (typeof min == "number" && typeof max == "number") { var str = times(min); if (min != max) { str = "at least " + str + " and at most " + times(max); } return str; } if (typeof min == "number") { return "at least " + times(min); } return "at most " + times(max); } function receivedMinCalls(expectation) { var hasMinLimit = typeof expectation.minCalls == "number"; return !hasMinLimit || expectation.callCount >= expectation.minCalls; } function receivedMaxCalls(expectation) { if (typeof expectation.maxCalls != "number") { return false; } return expectation.callCount == expectation.maxCalls; } function verifyMatcher(possibleMatcher, arg){ if (match && match.isMatcher(possibleMatcher)) { return possibleMatcher.test(arg); } else { return true; } } return { minCalls: 1, maxCalls: 1, create: function create(methodName) { var expectation = sinon.extend(sinon.stub.create(), sinon.expectation); delete expectation.create; expectation.method = methodName; return expectation; }, invoke: function invoke(func, thisValue, args) { this.verifyCallAllowed(thisValue, args); return _invoke.apply(this, arguments); }, atLeast: function atLeast(num) { if (typeof num != "number") { throw new TypeError("'" + num + "' is not number"); } if (!this.limitsSet) { this.maxCalls = null; this.limitsSet = true; } this.minCalls = num; return this; }, atMost: function atMost(num) { if (typeof num != "number") { throw new TypeError("'" + num + "' is not number"); } if (!this.limitsSet) { this.minCalls = null; this.limitsSet = true; } this.maxCalls = num; return this; }, never: function never() { return this.exactly(0); }, once: function once() { return this.exactly(1); }, twice: function twice() { return this.exactly(2); }, thrice: function thrice() { return this.exactly(3); }, exactly: function exactly(num) { if (typeof num != "number") { throw new TypeError("'" + num + "' is not a number"); } this.atLeast(num); return this.atMost(num); }, met: function met() { return !this.failed && receivedMinCalls(this); }, verifyCallAllowed: function verifyCallAllowed(thisValue, args) { if (receivedMaxCalls(this)) { this.failed = true; sinon.expectation.fail(this.method + " already called " + times(this.maxCalls)); } if ("expectedThis" in this && this.expectedThis !== thisValue) { sinon.expectation.fail(this.method + " called with " + thisValue + " as thisValue, expected " + this.expectedThis); } if (!("expectedArguments" in this)) { return; } if (!args) { sinon.expectation.fail(this.method + " received no arguments, expected " + sinon.format(this.expectedArguments)); } if (args.length < this.expectedArguments.length) { sinon.expectation.fail(this.method + " received too few arguments (" + sinon.format(args) + "), expected " + sinon.format(this.expectedArguments)); } if (this.expectsExactArgCount && args.length != this.expectedArguments.length) { sinon.expectation.fail(this.method + " received too many arguments (" + sinon.format(args) + "), expected " + sinon.format(this.expectedArguments)); } for (var i = 0, l = this.expectedArguments.length; i < l; i += 1) { if (!verifyMatcher(this.expectedArguments[i],args[i])) { sinon.expectation.fail(this.method + " received wrong arguments " + sinon.format(args) + ", didn't match " + this.expectedArguments.toString()); } if (!sinon.deepEqual(this.expectedArguments[i], args[i])) { sinon.expectation.fail(this.method + " received wrong arguments " + sinon.format(args) + ", expected " + sinon.format(this.expectedArguments)); } } }, allowsCall: function allowsCall(thisValue, args) { if (this.met() && receivedMaxCalls(this)) { return false; } if ("expectedThis" in this && this.expectedThis !== thisValue) { return false; } if (!("expectedArguments" in this)) { return true; } args = args || []; if (args.length < this.expectedArguments.length) { return false; } if (this.expectsExactArgCount && args.length != this.expectedArguments.length) { return false; } for (var i = 0, l = this.expectedArguments.length; i < l; i += 1) { if (!verifyMatcher(this.expectedArguments[i],args[i])) { return false; } if (!sinon.deepEqual(this.expectedArguments[i], args[i])) { return false; } } return true; }, withArgs: function withArgs() { this.expectedArguments = slice.call(arguments); return this; }, withExactArgs: function withExactArgs() { this.withArgs.apply(this, arguments); this.expectsExactArgCount = true; return this; }, on: function on(thisValue) { this.expectedThis = thisValue; return this; }, toString: function () { var args = (this.expectedArguments || []).slice(); if (!this.expectsExactArgCount) { push.call(args, "[...]"); } var callStr = sinon.spyCall.toString.call({ proxy: this.method || "anonymous mock expectation", args: args }); var message = callStr.replace(", [...", "[, ...") + " " + expectedCallCountInWords(this); if (this.met()) { return "Expectation met: " + message; } return "Expected " + message + " (" + callCountInWords(this.callCount) + ")"; }, verify: function verify() { if (!this.met()) { sinon.expectation.fail(this.toString()); } else { sinon.expectation.pass(this.toString()); } return true; }, pass: function(message) { sinon.assert.pass(message); }, fail: function (message) { var exception = new Error(message); exception.name = "ExpectationError"; throw exception; } }; }()); sinon.mock = mock; if (typeof define === "function" && define.amd) { define(["module"], function(module) { module.exports = mock; }); } else if (commonJSModule) { module.exports = mock; } }(typeof sinon == "object" && sinon || null)); /** * @depend ../sinon.js * @depend stub.js * @depend mock.js */ /*jslint eqeqeq: false, onevar: false, forin: true*/ /*global module, require, sinon*/ /** * Collections of stubs, spies and mocks. * * @author Christian Johansen ([email protected]) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ (function (sinon) { var commonJSModule = typeof module !== "undefined" && module.exports && typeof require == "function"; var push = [].push; var hasOwnProperty = Object.prototype.hasOwnProperty; if (!sinon && commonJSModule) { sinon = require("../sinon"); } if (!sinon) { return; } function getFakes(fakeCollection) { if (!fakeCollection.fakes) { fakeCollection.fakes = []; } return fakeCollection.fakes; } function each(fakeCollection, method) { var fakes = getFakes(fakeCollection); for (var i = 0, l = fakes.length; i < l; i += 1) { if (typeof fakes[i][method] == "function") { fakes[i][method](); } } } function compact(fakeCollection) { var fakes = getFakes(fakeCollection); var i = 0; while (i < fakes.length) { fakes.splice(i, 1); } } var collection = { verify: function resolve() { each(this, "verify"); }, restore: function restore() { each(this, "restore"); compact(this); }, verifyAndRestore: function verifyAndRestore() { var exception; try { this.verify(); } catch (e) { exception = e; } this.restore(); if (exception) { throw exception; } }, add: function add(fake) { push.call(getFakes(this), fake); return fake; }, spy: function spy() { return this.add(sinon.spy.apply(sinon, arguments)); }, stub: function stub(object, property, value) { if (property) { var original = object[property]; if (typeof original != "function") { if (!hasOwnProperty.call(object, property)) { throw new TypeError("Cannot stub non-existent own property " + property); } object[property] = value; return this.add({ restore: function () { object[property] = original; } }); } } if (!property && !!object && typeof object == "object") { var stubbedObj = sinon.stub.apply(sinon, arguments); for (var prop in stubbedObj) { if (typeof stubbedObj[prop] === "function") { this.add(stubbedObj[prop]); } } return stubbedObj; } return this.add(sinon.stub.apply(sinon, arguments)); }, mock: function mock() { return this.add(sinon.mock.apply(sinon, arguments)); }, inject: function inject(obj) { var col = this; obj.spy = function () { return col.spy.apply(col, arguments); }; obj.stub = function () { return col.stub.apply(col, arguments); }; obj.mock = function () { return col.mock.apply(col, arguments); }; return obj; } }; sinon.collection = collection; if (typeof define === "function" && define.amd) { define(["module"], function(module) { module.exports = collection; }); } else if (commonJSModule) { module.exports = collection; } }(typeof sinon == "object" && sinon || null)); /*jslint eqeqeq: false, plusplus: false, evil: true, onevar: false, browser: true, forin: false*/ /*global module, require, window*/ /** * Fake timer API * setTimeout * setInterval * clearTimeout * clearInterval * tick * reset * Date * * Inspired by jsUnitMockTimeOut from JsUnit * * @author Christian Johansen ([email protected]) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ if (typeof sinon == "undefined") { var sinon = {}; } (function (global) { // node expects setTimeout/setInterval to return a fn object w/ .ref()/.unref() // browsers, a number. // see https://github.com/cjohansen/Sinon.JS/pull/436 var timeoutResult = setTimeout(function() {}, 0); var addTimerReturnsObject = typeof timeoutResult === 'object'; clearTimeout(timeoutResult); var id = 1; function addTimer(args, recurring) { if (args.length === 0) { throw new Error("Function requires at least 1 parameter"); } if (typeof args[0] === "undefined") { throw new Error("Callback must be provided to timer calls"); } var toId = id++; var delay = args[1] || 0; if (!this.timeouts) { this.timeouts = {}; } this.timeouts[toId] = { id: toId, func: args[0], callAt: this.now + delay, invokeArgs: Array.prototype.slice.call(args, 2) }; if (recurring === true) { this.timeouts[toId].interval = delay; } if (addTimerReturnsObject) { return { id: toId, ref: function() {}, unref: function() {} }; } else { return toId; } } function parseTime(str) { if (!str) { return 0; } var strings = str.split(":"); var l = strings.length, i = l; var ms = 0, parsed; if (l > 3 || !/^(\d\d:){0,2}\d\d?$/.test(str)) { throw new Error("tick only understands numbers and 'h:m:s'"); } while (i--) { parsed = parseInt(strings[i], 10); if (parsed >= 60) { throw new Error("Invalid time " + str); } ms += parsed * Math.pow(60, (l - i - 1)); } return ms * 1000; } function createObject(object) { var newObject; if (Object.create) { newObject = Object.create(object); } else { var F = function () {}; F.prototype = object; newObject = new F(); } newObject.Date.clock = newObject; return newObject; } sinon.clock = { now: 0, create: function create(now) { var clock = createObject(this); if (typeof now == "number") { clock.now = now; } if (!!now && typeof now == "object") { throw new TypeError("now should be milliseconds since UNIX epoch"); } return clock; }, setTimeout: function setTimeout(callback, timeout) { return addTimer.call(this, arguments, false); }, clearTimeout: function clearTimeout(timerId) { if (!timerId) { // null appears to be allowed in most browsers, and appears to be relied upon by some libraries, like Bootstrap carousel return; } if (!this.timeouts) { this.timeouts = []; } // in Node, timerId is an object with .ref()/.unref(), and // its .id field is the actual timer id. if (typeof timerId === 'object') { timerId = timerId.id } if (timerId in this.timeouts) { delete this.timeouts[timerId]; } }, setInterval: function setInterval(callback, timeout) { return addTimer.call(this, arguments, true); }, clearInterval: function clearInterval(timerId) { this.clearTimeout(timerId); }, setImmediate: function setImmediate(callback) { var passThruArgs = Array.prototype.slice.call(arguments, 1); return addTimer.call(this, [callback, 0].concat(passThruArgs), false); }, clearImmediate: function clearImmediate(timerId) { this.clearTimeout(timerId); }, tick: function tick(ms) { ms = typeof ms == "number" ? ms : parseTime(ms); var tickFrom = this.now, tickTo = this.now + ms, previous = this.now; var timer = this.firstTimerInRange(tickFrom, tickTo); var firstException; while (timer && tickFrom <= tickTo) { if (this.timeouts[timer.id]) { tickFrom = this.now = timer.callAt; try { this.callTimer(timer); } catch (e) { firstException = firstException || e; } } timer = this.firstTimerInRange(previous, tickTo); previous = tickFrom; } this.now = tickTo; if (firstException) { throw firstException; } return this.now; }, firstTimerInRange: function (from, to) { var timer, smallest = null, originalTimer; for (var id in this.timeouts) { if (this.timeouts.hasOwnProperty(id)) { if (this.timeouts[id].callAt < from || this.timeouts[id].callAt > to) { continue; } if (smallest === null || this.timeouts[id].callAt < smallest) { originalTimer = this.timeouts[id]; smallest = this.timeouts[id].callAt; timer = { func: this.timeouts[id].func, callAt: this.timeouts[id].callAt, interval: this.timeouts[id].interval, id: this.timeouts[id].id, invokeArgs: this.timeouts[id].invokeArgs }; } } } return timer || null; }, callTimer: function (timer) { if (typeof timer.interval == "number") { this.timeouts[timer.id].callAt += timer.interval; } else { delete this.timeouts[timer.id]; } try { if (typeof timer.func == "function") { timer.func.apply(null, timer.invokeArgs); } else { eval(timer.func); } } catch (e) { var exception = e; } if (!this.timeouts[timer.id]) { if (exception) { throw exception; } return; } if (exception) { throw exception; } }, reset: function reset() { this.timeouts = {}; }, Date: (function () { var NativeDate = Date; function ClockDate(year, month, date, hour, minute, second, ms) { // Defensive and verbose to avoid potential harm in passing // explicit undefined when user does not pass argument switch (arguments.length) { case 0: return new NativeDate(ClockDate.clock.now); case 1: return new NativeDate(year); case 2: return new NativeDate(year, month); case 3: return new NativeDate(year, month, date); case 4: return new NativeDate(year, month, date, hour); case 5: return new NativeDate(year, month, date, hour, minute); case 6: return new NativeDate(year, month, date, hour, minute, second); default: return new NativeDate(year, month, date, hour, minute, second, ms); } } return mirrorDateProperties(ClockDate, NativeDate); }()) }; function mirrorDateProperties(target, source) { if (source.now) { target.now = function now() { return target.clock.now; }; } else { delete target.now; } if (source.toSource) { target.toSource = function toSource() { return source.toSource(); }; } else { delete target.toSource; } target.toString = function toString() { return source.toString(); }; target.prototype = source.prototype; target.parse = source.parse; target.UTC = source.UTC; target.prototype.toUTCString = source.prototype.toUTCString; for (var prop in source) { if (source.hasOwnProperty(prop)) { target[prop] = source[prop]; } } return target; } var methods = ["Date", "setTimeout", "setInterval", "clearTimeout", "clearInterval"]; if (typeof global.setImmediate !== "undefined") { methods.push("setImmediate"); } if (typeof global.clearImmediate !== "undefined") { methods.push("clearImmediate"); } function restore() { var method; for (var i = 0, l = this.methods.length; i < l; i++) { method = this.methods[i]; if (global[method].hadOwnProperty) { global[method] = this["_" + method]; } else { try { delete global[method]; } catch (e) {} } } // Prevent multiple executions which will completely remove these props this.methods = []; } function stubGlobal(method, clock) { clock[method].hadOwnProperty = Object.prototype.hasOwnProperty.call(global, method); clock["_" + method] = global[method]; if (method == "Date") { var date = mirrorDateProperties(clock[method], global[method]); global[method] = date; } else { global[method] = function () { return clock[method].apply(clock, arguments); }; for (var prop in clock[method]) { if (clock[method].hasOwnProperty(prop)) { global[method][prop] = clock[method][prop]; } } } global[method].clock = clock; } sinon.useFakeTimers = function useFakeTimers(now) { var clock = sinon.clock.create(now); clock.restore = restore; clock.methods = Array.prototype.slice.call(arguments, typeof now == "number" ? 1 : 0); if (clock.methods.length === 0) { clock.methods = methods; } for (var i = 0, l = clock.methods.length; i < l; i++) { stubGlobal(clock.methods[i], clock); } return clock; }; }(typeof global != "undefined" && typeof global !== "function" ? global : this)); sinon.timers = { setTimeout: setTimeout, clearTimeout: clearTimeout, setImmediate: (typeof setImmediate !== "undefined" ? setImmediate : undefined), clearImmediate: (typeof clearImmediate !== "undefined" ? clearImmediate: undefined), setInterval: setInterval, clearInterval: clearInterval, Date: Date }; if (typeof module !== 'undefined' && module.exports) { module.exports = sinon; } /*jslint eqeqeq: false, onevar: false*/ /*global sinon, module, require, ActiveXObject, XMLHttpRequest, DOMParser*/ /** * Minimal Event interface implementation * * Original implementation by Sven Fuchs: https://gist.github.com/995028 * Modifications and tests by Christian Johansen. * * @author Sven Fuchs ([email protected]) * @author Christian Johansen ([email protected]) * @license BSD * * Copyright (c) 2011 Sven Fuchs, Christian Johansen */ if (typeof sinon == "undefined") { this.sinon = {}; } (function () { var push = [].push; sinon.Event = function Event(type, bubbles, cancelable, target) { this.initEvent(type, bubbles, cancelable, target); }; sinon.Event.prototype = { initEvent: function(type, bubbles, cancelable, target) { this.type = type; this.bubbles = bubbles; this.cancelable = cancelable; this.target = target; }, stopPropagation: function () {}, preventDefault: function () { this.defaultPrevented = true; } }; sinon.ProgressEvent = function ProgressEvent(type, progressEventRaw, target) { this.initEvent(type, false, false, target); this.loaded = progressEventRaw.loaded || null; this.total = progressEventRaw.total || null; }; sinon.ProgressEvent.prototype = new sinon.Event(); sinon.ProgressEvent.prototype.constructor = sinon.ProgressEvent; sinon.CustomEvent = function CustomEvent(type, customData, target) { this.initEvent(type, false, false, target); this.detail = customData.detail || null; }; sinon.CustomEvent.prototype = new sinon.Event(); sinon.CustomEvent.prototype.constructor = sinon.CustomEvent; sinon.EventTarget = { addEventListener: function addEventListener(event, listener) { this.eventListeners = this.eventListeners || {}; this.eventListeners[event] = this.eventListeners[event] || []; push.call(this.eventListeners[event], listener); }, removeEventListener: function removeEventListener(event, listener) { var listeners = this.eventListeners && this.eventListeners[event] || []; for (var i = 0, l = listeners.length; i < l; ++i) { if (listeners[i] == listener) { return listeners.splice(i, 1); } } }, dispatchEvent: function dispatchEvent(event) { var type = event.type; var listeners = this.eventListeners && this.eventListeners[type] || []; for (var i = 0; i < listeners.length; i++) { if (typeof listeners[i] == "function") { listeners[i].call(this, event); } else { listeners[i].handleEvent(event); } } return !!event.defaultPrevented; } }; }()); /** * @depend ../../sinon.js * @depend event.js */ /*jslint eqeqeq: false, onevar: false*/ /*global sinon, module, require, ActiveXObject, XMLHttpRequest, DOMParser*/ /** * Fake XMLHttpRequest object * * @author Christian Johansen ([email protected]) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ // wrapper for global (function(global) { if (typeof sinon === "undefined") { global.sinon = {}; } var supportsProgress = typeof ProgressEvent !== "undefined"; var supportsCustomEvent = typeof CustomEvent !== "undefined"; sinon.xhr = { XMLHttpRequest: global.XMLHttpRequest }; var xhr = sinon.xhr; xhr.GlobalXMLHttpRequest = global.XMLHttpRequest; xhr.GlobalActiveXObject = global.ActiveXObject; xhr.supportsActiveX = typeof xhr.GlobalActiveXObject != "undefined"; xhr.supportsXHR = typeof xhr.GlobalXMLHttpRequest != "undefined"; xhr.workingXHR = xhr.supportsXHR ? xhr.GlobalXMLHttpRequest : xhr.supportsActiveX ? function() { return new xhr.GlobalActiveXObject("MSXML2.XMLHTTP.3.0") } : false; xhr.supportsCORS = xhr.supportsXHR && 'withCredentials' in (new sinon.xhr.GlobalXMLHttpRequest()); /*jsl:ignore*/ var unsafeHeaders = { "Accept-Charset": true, "Accept-Encoding": true, "Connection": true, "Content-Length": true, "Cookie": true, "Cookie2": true, "Content-Transfer-Encoding": true, "Date": true, "Expect": true, "Host": true, "Keep-Alive": true, "Referer": true, "TE": true, "Trailer": true, "Transfer-Encoding": true, "Upgrade": true, "User-Agent": true, "Via": true }; /*jsl:end*/ function FakeXMLHttpRequest() { this.readyState = FakeXMLHttpRequest.UNSENT; this.requestHeaders = {}; this.requestBody = null; this.status = 0; this.statusText = ""; this.upload = new UploadProgress(); if (sinon.xhr.supportsCORS) { this.withCredentials = false; } var xhr = this; var events = ["loadstart", "load", "abort", "loadend"]; function addEventListener(eventName) { xhr.addEventListener(eventName, function (event) { var listener = xhr["on" + eventName]; if (listener && typeof listener == "function") { listener.call(this, event); } }); } for (var i = events.length - 1; i >= 0; i--) { addEventListener(events[i]); } if (typeof FakeXMLHttpRequest.onCreate == "function") { FakeXMLHttpRequest.onCreate(this); } } // An upload object is created for each // FakeXMLHttpRequest and allows upload // events to be simulated using uploadProgress // and uploadError. function UploadProgress() { this.eventListeners = { "progress": [], "load": [], "abort": [], "error": [] } } UploadProgress.prototype.addEventListener = function(event, listener) { this.eventListeners[event].push(listener); }; UploadProgress.prototype.removeEventListener = function(event, listener) { var listeners = this.eventListeners[event] || []; for (var i = 0, l = listeners.length; i < l; ++i) { if (listeners[i] == listener) { return listeners.splice(i, 1); } } }; UploadProgress.prototype.dispatchEvent = function(event) { var listeners = this.eventListeners[event.type] || []; for (var i = 0, listener; (listener = listeners[i]) != null; i++) { listener(event); } }; function verifyState(xhr) { if (xhr.readyState !== FakeXMLHttpRequest.OPENED) { throw new Error("INVALID_STATE_ERR"); } if (xhr.sendFlag) { throw new Error("INVALID_STATE_ERR"); } } // filtering to enable a white-list version of Sinon FakeXhr, // where whitelisted requests are passed through to real XHR function each(collection, callback) { if (!collection) return; for (var i = 0, l = collection.length; i < l; i += 1) { callback(collection[i]); } } function some(collection, callback) { for (var index = 0; index < collection.length; index++) { if(callback(collection[index]) === true) return true; } return false; } // largest arity in XHR is 5 - XHR#open var apply = function(obj,method,args) { switch(args.length) { case 0: return obj[method](); case 1: return obj[method](args[0]); case 2: return obj[method](args[0],args[1]); case 3: return obj[method](args[0],args[1],args[2]); case 4: return obj[method](args[0],args[1],args[2],args[3]); case 5: return obj[method](args[0],args[1],args[2],args[3],args[4]); } }; FakeXMLHttpRequest.filters = []; FakeXMLHttpRequest.addFilter = function(fn) { this.filters.push(fn) }; var IE6Re = /MSIE 6/; FakeXMLHttpRequest.defake = function(fakeXhr,xhrArgs) { var xhr = new sinon.xhr.workingXHR(); each(["open","setRequestHeader","send","abort","getResponseHeader", "getAllResponseHeaders","addEventListener","overrideMimeType","removeEventListener"], function(method) { fakeXhr[method] = function() { return apply(xhr,method,arguments); }; }); var copyAttrs = function(args) { each(args, function(attr) { try { fakeXhr[attr] = xhr[attr] } catch(e) { if(!IE6Re.test(navigator.userAgent)) throw e; } }); }; var stateChange = function() { fakeXhr.readyState = xhr.readyState; if(xhr.readyState >= FakeXMLHttpRequest.HEADERS_RECEIVED) { copyAttrs(["status","statusText"]); } if(xhr.readyState >= FakeXMLHttpRequest.LOADING) { copyAttrs(["responseText"]); } if(xhr.readyState === FakeXMLHttpRequest.DONE) { copyAttrs(["responseXML"]); } if(fakeXhr.onreadystatechange) fakeXhr.onreadystatechange.call(fakeXhr, { target: fakeXhr }); }; if(xhr.addEventListener) { for(var event in fakeXhr.eventListeners) { if(fakeXhr.eventListeners.hasOwnProperty(event)) { each(fakeXhr.eventListeners[event],function(handler) { xhr.addEventListener(event, handler); }); } } xhr.addEventListener("readystatechange",stateChange); } else { xhr.onreadystatechange = stateChange; } apply(xhr,"open",xhrArgs); }; FakeXMLHttpRequest.useFilters = false; function verifyRequestOpened(xhr) { if (xhr.readyState != FakeXMLHttpRequest.OPENED) { throw new Error("INVALID_STATE_ERR - " + xhr.readyState); } } function verifyRequestSent(xhr) { if (xhr.readyState == FakeXMLHttpRequest.DONE) { throw new Error("Request done"); } } function verifyHeadersReceived(xhr) { if (xhr.async && xhr.readyState != FakeXMLHttpRequest.HEADERS_RECEIVED) { throw new Error("No headers received"); } } function verifyResponseBodyType(body) { if (typeof body != "string") { var error = new Error("Attempted to respond to fake XMLHttpRequest with " + body + ", which is not a string."); error.name = "InvalidBodyException"; throw error; } } sinon.extend(FakeXMLHttpRequest.prototype, sinon.EventTarget, { async: true, open: function open(method, url, async, username, password) { this.method = method; this.url = url; this.async = typeof async == "boolean" ? async : true; this.username = username; this.password = password; this.responseText = null; this.responseXML = null; this.requestHeaders = {}; this.sendFlag = false; if(sinon.FakeXMLHttpRequest.useFilters === true) { var xhrArgs = arguments; var defake = some(FakeXMLHttpRequest.filters,function(filter) { return filter.apply(this,xhrArgs) }); if (defake) { return sinon.FakeXMLHttpRequest.defake(this,arguments); } } this.readyStateChange(FakeXMLHttpRequest.OPENED); }, readyStateChange: function readyStateChange(state) { this.readyState = state; if (typeof this.onreadystatechange == "function") { try { this.onreadystatechange(); } catch (e) { sinon.logError("Fake XHR onreadystatechange handler", e); } } this.dispatchEvent(new sinon.Event("readystatechange")); switch (this.readyState) { case FakeXMLHttpRequest.DONE: this.dispatchEvent(new sinon.Event("load", false, false, this)); this.dispatchEvent(new sinon.Event("loadend", false, false, this)); this.upload.dispatchEvent(new sinon.Event("load", false, false, this)); if (supportsProgress) { this.upload.dispatchEvent(new sinon.ProgressEvent('progress', {loaded: 100, total: 100})); } break; } }, setRequestHeader: function setRequestHeader(header, value) { verifyState(this); if (unsafeHeaders[header] || /^(Sec-|Proxy-)/.test(header)) { throw new Error("Refused to set unsafe header \"" + header + "\""); } if (this.requestHeaders[header]) { this.requestHeaders[header] += "," + value; } else { this.requestHeaders[header] = value; } }, // Helps testing setResponseHeaders: function setResponseHeaders(headers) { verifyRequestOpened(this); this.responseHeaders = {}; for (var header in headers) { if (headers.hasOwnProperty(header)) { this.responseHeaders[header] = headers[header]; } } if (this.async) { this.readyStateChange(FakeXMLHttpRequest.HEADERS_RECEIVED); } else { this.readyState = FakeXMLHttpRequest.HEADERS_RECEIVED; } }, // Currently treats ALL data as a DOMString (i.e. no Document) send: function send(data) { verifyState(this); if (!/^(get|head)$/i.test(this.method)) { if (this.requestHeaders["Content-Type"]) { var value = this.requestHeaders["Content-Type"].split(";"); this.requestHeaders["Content-Type"] = value[0] + ";charset=utf-8"; } else { this.requestHeaders["Content-Type"] = "text/plain;charset=utf-8"; } this.requestBody = data; } this.errorFlag = false; this.sendFlag = this.async; this.readyStateChange(FakeXMLHttpRequest.OPENED); if (typeof this.onSend == "function") { this.onSend(this); } this.dispatchEvent(new sinon.Event("loadstart", false, false, this)); }, abort: function abort() { this.aborted = true; this.responseText = null; this.errorFlag = true; this.requestHeaders = {}; if (this.readyState > sinon.FakeXMLHttpRequest.UNSENT && this.sendFlag) { this.readyStateChange(sinon.FakeXMLHttpRequest.DONE); this.sendFlag = false; } this.readyState = sinon.FakeXMLHttpRequest.UNSENT; this.dispatchEvent(new sinon.Event("abort", false, false, this)); this.upload.dispatchEvent(new sinon.Event("abort", false, false, this)); if (typeof this.onerror === "function") { this.onerror(); } }, getResponseHeader: function getResponseHeader(header) { if (this.readyState < FakeXMLHttpRequest.HEADERS_RECEIVED) { return null; } if (/^Set-Cookie2?$/i.test(header)) { return null; } header = header.toLowerCase(); for (var h in this.responseHeaders) { if (h.toLowerCase() == header) { return this.responseHeaders[h]; } } return null; }, getAllResponseHeaders: function getAllResponseHeaders() { if (this.readyState < FakeXMLHttpRequest.HEADERS_RECEIVED) { return ""; } var headers = ""; for (var header in this.responseHeaders) { if (this.responseHeaders.hasOwnProperty(header) && !/^Set-Cookie2?$/i.test(header)) { headers += header + ": " + this.responseHeaders[header] + "\r\n"; } } return headers; }, setResponseBody: function setResponseBody(body) { verifyRequestSent(this); verifyHeadersReceived(this); verifyResponseBodyType(body); var chunkSize = this.chunkSize || 10; var index = 0; this.responseText = ""; do { if (this.async) { this.readyStateChange(FakeXMLHttpRequest.LOADING); } this.responseText += body.substring(index, index + chunkSize); index += chunkSize; } while (index < body.length); var type = this.getResponseHeader("Content-Type"); if (this.responseText && (!type || /(text\/xml)|(application\/xml)|(\+xml)/.test(type))) { try { this.responseXML = FakeXMLHttpRequest.parseXML(this.responseText); } catch (e) { // Unable to parse XML - no biggie } } if (this.async) { this.readyStateChange(FakeXMLHttpRequest.DONE); } else { this.readyState = FakeXMLHttpRequest.DONE; } }, respond: function respond(status, headers, body) { this.status = typeof status == "number" ? status : 200; this.statusText = FakeXMLHttpRequest.statusCodes[this.status]; this.setResponseHeaders(headers || {}); this.setResponseBody(body || ""); }, uploadProgress: function uploadProgress(progressEventRaw) { if (supportsProgress) { this.upload.dispatchEvent(new sinon.ProgressEvent("progress", progressEventRaw)); } }, uploadError: function uploadError(error) { if (supportsCustomEvent) { this.upload.dispatchEvent(new sinon.CustomEvent("error", {"detail": error})); } } }); sinon.extend(FakeXMLHttpRequest, { UNSENT: 0, OPENED: 1, HEADERS_RECEIVED: 2, LOADING: 3, DONE: 4 }); // Borrowed from JSpec FakeXMLHttpRequest.parseXML = function parseXML(text) { var xmlDoc; if (typeof DOMParser != "undefined") { var parser = new DOMParser(); xmlDoc = parser.parseFromString(text, "text/xml"); } else { xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async = "false"; xmlDoc.loadXML(text); } return xmlDoc; }; FakeXMLHttpRequest.statusCodes = { 100: "Continue", 101: "Switching Protocols", 200: "OK", 201: "Created", 202: "Accepted", 203: "Non-Authoritative Information", 204: "No Content", 205: "Reset Content", 206: "Partial Content", 300: "Multiple Choice", 301: "Moved Permanently", 302: "Found", 303: "See Other", 304: "Not Modified", 305: "Use Proxy", 307: "Temporary Redirect", 400: "Bad Request", 401: "Unauthorized", 402: "Payment Required", 403: "Forbidden", 404: "Not Found", 405: "Method Not Allowed", 406: "Not Acceptable", 407: "Proxy Authentication Required", 408: "Request Timeout", 409: "Conflict", 410: "Gone", 411: "Length Required", 412: "Precondition Failed", 413: "Request Entity Too Large", 414: "Request-URI Too Long", 415: "Unsupported Media Type", 416: "Requested Range Not Satisfiable", 417: "Expectation Failed", 422: "Unprocessable Entity", 500: "Internal Server Error", 501: "Not Implemented", 502: "Bad Gateway", 503: "Service Unavailable", 504: "Gateway Timeout", 505: "HTTP Version Not Supported" }; sinon.useFakeXMLHttpRequest = function () { sinon.FakeXMLHttpRequest.restore = function restore(keepOnCreate) { if (xhr.supportsXHR) { global.XMLHttpRequest = xhr.GlobalXMLHttpRequest; } if (xhr.supportsActiveX) { global.ActiveXObject = xhr.GlobalActiveXObject; } delete sinon.FakeXMLHttpRequest.restore; if (keepOnCreate !== true) { delete sinon.FakeXMLHttpRequest.onCreate; } }; if (xhr.supportsXHR) { global.XMLHttpRequest = sinon.FakeXMLHttpRequest; } if (xhr.supportsActiveX) { global.ActiveXObject = function ActiveXObject(objId) { if (objId == "Microsoft.XMLHTTP" || /^Msxml2\.XMLHTTP/i.test(objId)) { return new sinon.FakeXMLHttpRequest(); } return new xhr.GlobalActiveXObject(objId); }; } return sinon.FakeXMLHttpRequest; }; sinon.FakeXMLHttpRequest = FakeXMLHttpRequest; })((function(){ return typeof global === "object" ? global : this; })()); if (typeof module !== 'undefined' && module.exports) { module.exports = sinon; } /** * @depend fake_xml_http_request.js */ /*jslint eqeqeq: false, onevar: false, regexp: false, plusplus: false*/ /*global module, require, window*/ /** * The Sinon "server" mimics a web server that receives requests from * sinon.FakeXMLHttpRequest and provides an API to respond to those requests, * both synchronously and asynchronously. To respond synchronuously, canned * answers have to be provided upfront. * * @author Christian Johansen ([email protected]) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ if (typeof sinon == "undefined") { var sinon = {}; } sinon.fakeServer = (function () { var push = [].push; function F() {} function create(proto) { F.prototype = proto; return new F(); } function responseArray(handler) { var response = handler; if (Object.prototype.toString.call(handler) != "[object Array]") { response = [200, {}, handler]; } if (typeof response[2] != "string") { throw new TypeError("Fake server response body should be string, but was " + typeof response[2]); } return response; } var wloc = typeof window !== "undefined" ? window.location : {}; var rCurrLoc = new RegExp("^" + wloc.protocol + "//" + wloc.host); function matchOne(response, reqMethod, reqUrl) { var rmeth = response.method; var matchMethod = !rmeth || rmeth.toLowerCase() == reqMethod.toLowerCase(); var url = response.url; var matchUrl = !url || url == reqUrl || (typeof url.test == "function" && url.test(reqUrl)); return matchMethod && matchUrl; } function match(response, request) { var requestUrl = request.url; if (!/^https?:\/\//.test(requestUrl) || rCurrLoc.test(requestUrl)) { requestUrl = requestUrl.replace(rCurrLoc, ""); } if (matchOne(response, this.getHTTPMethod(request), requestUrl)) { if (typeof response.response == "function") { var ru = response.url; var args = [request].concat(ru && typeof ru.exec == "function" ? ru.exec(requestUrl).slice(1) : []); return response.response.apply(response, args); } return true; } return false; } return { create: function () { var server = create(this); if (!sinon.xhr.supportsCORS) { this.xhr = sinon.useFakeXDomainRequest(); } else { this.xhr = sinon.useFakeXMLHttpRequest(); } server.requests = []; this.xhr.onCreate = function (xhrObj) { server.addRequest(xhrObj); }; return server; }, addRequest: function addRequest(xhrObj) { var server = this; push.call(this.requests, xhrObj); xhrObj.onSend = function () { server.handleRequest(this); if (server.autoRespond && !server.responding) { setTimeout(function () { server.responding = false; server.respond(); }, server.autoRespondAfter || 10); server.responding = true; } }; }, getHTTPMethod: function getHTTPMethod(request) { if (this.fakeHTTPMethods && /post/i.test(request.method)) { var matches = (request.requestBody || "").match(/_method=([^\b;]+)/); return !!matches ? matches[1] : request.method; } return request.method; }, handleRequest: function handleRequest(xhr) { if (xhr.async) { if (!this.queue) { this.queue = []; } push.call(this.queue, xhr); } else { this.processRequest(xhr); } }, log: function(response, request) { var str; str = "Request:\n" + sinon.format(request) + "\n\n"; str += "Response:\n" + sinon.format(response) + "\n\n"; sinon.log(str); }, respondWith: function respondWith(method, url, body) { if (arguments.length == 1 && typeof method != "function") { this.response = responseArray(method); return; } if (!this.responses) { this.responses = []; } if (arguments.length == 1) { body = method; url = method = null; } if (arguments.length == 2) { body = url; url = method; method = null; } push.call(this.responses, { method: method, url: url, response: typeof body == "function" ? body : responseArray(body) }); }, respond: function respond() { if (arguments.length > 0) this.respondWith.apply(this, arguments); var queue = this.queue || []; var requests = queue.splice(0, queue.length); var request; while(request = requests.shift()) { this.processRequest(request); } }, processRequest: function processRequest(request) { try { if (request.aborted) { return; } var response = this.response || [404, {}, ""]; if (this.responses) { for (var l = this.responses.length, i = l - 1; i >= 0; i--) { if (match.call(this, this.responses[i], request)) { response = this.responses[i].response; break; } } } if (request.readyState != 4) { sinon.fakeServer.log(response, request); request.respond(response[0], response[1], response[2]); } } catch (e) { sinon.logError("Fake server request processing", e); } }, restore: function restore() { return this.xhr.restore && this.xhr.restore.apply(this.xhr, arguments); } }; }()); if (typeof module !== 'undefined' && module.exports) { module.exports = sinon; } /** * @depend fake_server.js * @depend fake_timers.js */ /*jslint browser: true, eqeqeq: false, onevar: false*/ /*global sinon*/ /** * Add-on for sinon.fakeServer that automatically handles a fake timer along with * the FakeXMLHttpRequest. The direct inspiration for this add-on is jQuery * 1.3.x, which does not use xhr object's onreadystatehandler at all - instead, * it polls the object for completion with setInterval. Dispite the direct * motivation, there is nothing jQuery-specific in this file, so it can be used * in any environment where the ajax implementation depends on setInterval or * setTimeout. * * @author Christian Johansen ([email protected]) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ (function () { function Server() {} Server.prototype = sinon.fakeServer; sinon.fakeServerWithClock = new Server(); sinon.fakeServerWithClock.addRequest = function addRequest(xhr) { if (xhr.async) { if (typeof setTimeout.clock == "object") { this.clock = setTimeout.clock; } else { this.clock = sinon.useFakeTimers(); this.resetClock = true; } if (!this.longestTimeout) { var clockSetTimeout = this.clock.setTimeout; var clockSetInterval = this.clock.setInterval; var server = this; this.clock.setTimeout = function (fn, timeout) { server.longestTimeout = Math.max(timeout, server.longestTimeout || 0); return clockSetTimeout.apply(this, arguments); }; this.clock.setInterval = function (fn, timeout) { server.longestTimeout = Math.max(timeout, server.longestTimeout || 0); return clockSetInterval.apply(this, arguments); }; } } return sinon.fakeServer.addRequest.call(this, xhr); }; sinon.fakeServerWithClock.respond = function respond() { var returnVal = sinon.fakeServer.respond.apply(this, arguments); if (this.clock) { this.clock.tick(this.longestTimeout || 0); this.longestTimeout = 0; if (this.resetClock) { this.clock.restore(); this.resetClock = false; } } return returnVal; }; sinon.fakeServerWithClock.restore = function restore() { if (this.clock) { this.clock.restore(); } return sinon.fakeServer.restore.apply(this, arguments); }; }()); /** * @depend ../sinon.js * @depend collection.js * @depend util/fake_timers.js * @depend util/fake_server_with_clock.js */ /*jslint eqeqeq: false, onevar: false, plusplus: false*/ /*global require, module*/ /** * Manages fake collections as well as fake utilities such as Sinon's * timers and fake XHR implementation in one convenient object. * * @author Christian Johansen ([email protected]) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ if (typeof module !== "undefined" && module.exports && typeof require == "function") { var sinon = require("../sinon"); sinon.extend(sinon, require("./util/fake_timers")); } (function () { var push = [].push; function exposeValue(sandbox, config, key, value) { if (!value) { return; } if (config.injectInto && !(key in config.injectInto)) { config.injectInto[key] = value; sandbox.injectedKeys.push(key); } else { push.call(sandbox.args, value); } } function prepareSandboxFromConfig(config) { var sandbox = sinon.create(sinon.sandbox); if (config.useFakeServer) { if (typeof config.useFakeServer == "object") { sandbox.serverPrototype = config.useFakeServer; } sandbox.useFakeServer(); } if (config.useFakeTimers) { if (typeof config.useFakeTimers == "object") { sandbox.useFakeTimers.apply(sandbox, config.useFakeTimers); } else { sandbox.useFakeTimers(); } } return sandbox; } sinon.sandbox = sinon.extend(sinon.create(sinon.collection), { useFakeTimers: function useFakeTimers() { this.clock = sinon.useFakeTimers.apply(sinon, arguments); return this.add(this.clock); }, serverPrototype: sinon.fakeServer, useFakeServer: function useFakeServer() { var proto = this.serverPrototype || sinon.fakeServer; if (!proto || !proto.create) { return null; } this.server = proto.create(); return this.add(this.server); }, inject: function (obj) { sinon.collection.inject.call(this, obj); if (this.clock) { obj.clock = this.clock; } if (this.server) { obj.server = this.server; obj.requests = this.server.requests; } return obj; }, restore: function () { sinon.collection.restore.apply(this, arguments); this.restoreContext(); }, restoreContext: function () { if (this.injectedKeys) { for (var i = 0, j = this.injectedKeys.length; i < j; i++) { delete this.injectInto[this.injectedKeys[i]]; } this.injectedKeys = []; } }, create: function (config) { if (!config) { return sinon.create(sinon.sandbox); } var sandbox = prepareSandboxFromConfig(config); sandbox.args = sandbox.args || []; sandbox.injectedKeys = []; sandbox.injectInto = config.injectInto; var prop, value, exposed = sandbox.inject({}); if (config.properties) { for (var i = 0, l = config.properties.length; i < l; i++) { prop = config.properties[i]; value = exposed[prop] || prop == "sandbox" && sandbox; exposeValue(sandbox, config, prop, value); } } else { exposeValue(sandbox, config, "sandbox", value); } return sandbox; } }); sinon.sandbox.useFakeXMLHttpRequest = sinon.sandbox.useFakeServer; if (typeof define === "function" && define.amd) { define(["module"], function(module) { module.exports = sinon.sandbox; }); } else if (typeof module !== 'undefined' && module.exports) { module.exports = sinon.sandbox; } }()); /** * @depend ../sinon.js * @depend stub.js * @depend mock.js * @depend sandbox.js */ /*jslint eqeqeq: false, onevar: false, forin: true, plusplus: false*/ /*global module, require, sinon*/ /** * Test function, sandboxes fakes * * @author Christian Johansen ([email protected]) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ (function (sinon) { var commonJSModule = typeof module !== "undefined" && module.exports && typeof require == "function"; if (!sinon && commonJSModule) { sinon = require("../sinon"); } if (!sinon) { return; } function test(callback) { var type = typeof callback; if (type != "function") { throw new TypeError("sinon.test needs to wrap a test function, got " + type); } function sinonSandboxedTest() { var config = sinon.getConfig(sinon.config); config.injectInto = config.injectIntoThis && this || config.injectInto; var sandbox = sinon.sandbox.create(config); var exception, result; var args = Array.prototype.slice.call(arguments).concat(sandbox.args); try { result = callback.apply(this, args); } catch (e) { exception = e; } if (typeof exception !== "undefined") { sandbox.restore(); throw exception; } else { sandbox.verifyAndRestore(); } return result; }; if (callback.length) { return function sinonAsyncSandboxedTest(callback) { return sinonSandboxedTest.apply(this, arguments); }; } return sinonSandboxedTest; } test.config = { injectIntoThis: true, injectInto: null, properties: ["spy", "stub", "mock", "clock", "server", "requests"], useFakeTimers: true, useFakeServer: true }; sinon.test = test; if (typeof define === "function" && define.amd) { define(["module"], function(module) { module.exports = test; }); } else if (commonJSModule) { module.exports = test; } }(typeof sinon == "object" && sinon || null)); /** * @depend ../sinon.js * @depend test.js */ /*jslint eqeqeq: false, onevar: false, eqeqeq: false*/ /*global module, require, sinon*/ /** * Test case, sandboxes all test functions * * @author Christian Johansen ([email protected]) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ (function (sinon) { var commonJSModule = typeof module !== "undefined" && module.exports && typeof require == "function"; if (!sinon && commonJSModule) { sinon = require("../sinon"); } if (!sinon || !Object.prototype.hasOwnProperty) { return; } function createTest(property, setUp, tearDown) { return function () { if (setUp) { setUp.apply(this, arguments); } var exception, result; try { result = property.apply(this, arguments); } catch (e) { exception = e; } if (tearDown) { tearDown.apply(this, arguments); } if (exception) { throw exception; } return result; }; } function testCase(tests, prefix) { /*jsl:ignore*/ if (!tests || typeof tests != "object") { throw new TypeError("sinon.testCase needs an object with test functions"); } /*jsl:end*/ prefix = prefix || "test"; var rPrefix = new RegExp("^" + prefix); var methods = {}, testName, property, method; var setUp = tests.setUp; var tearDown = tests.tearDown; for (testName in tests) { if (tests.hasOwnProperty(testName)) { property = tests[testName]; if (/^(setUp|tearDown)$/.test(testName)) { continue; } if (typeof property == "function" && rPrefix.test(testName)) { method = property; if (setUp || tearDown) { method = createTest(property, setUp, tearDown); } methods[testName] = sinon.test(method); } else { methods[testName] = tests[testName]; } } } return methods; } sinon.testCase = testCase; if (typeof define === "function" && define.amd) { define(["module"], function(module) { module.exports = testCase; }); } else if (commonJSModule) { module.exports = testCase; } }(typeof sinon == "object" && sinon || null)); /** * @depend ../sinon.js * @depend stub.js */ /*jslint eqeqeq: false, onevar: false, nomen: false, plusplus: false*/ /*global module, require, sinon*/ /** * Assertions matching the test spy retrieval interface. * * @author Christian Johansen ([email protected]) * @license BSD * * Copyright (c) 2010-2013 Christian Johansen */ (function (sinon, global) { var commonJSModule = typeof module !== "undefined" && module.exports && typeof require == "function"; var slice = Array.prototype.slice; var assert; if (!sinon && commonJSModule) { sinon = require("../sinon"); } if (!sinon) { return; } function verifyIsStub() { var method; for (var i = 0, l = arguments.length; i < l; ++i) { method = arguments[i]; if (!method) { assert.fail("fake is not a spy"); } if (typeof method != "function") { assert.fail(method + " is not a function"); } if (typeof method.getCall != "function") { assert.fail(method + " is not stubbed"); } } } function failAssertion(object, msg) { object = object || global; var failMethod = object.fail || assert.fail; failMethod.call(object, msg); } function mirrorPropAsAssertion(name, method, message) { if (arguments.length == 2) { message = method; method = name; } assert[name] = function (fake) { verifyIsStub(fake); var args = slice.call(arguments, 1); var failed = false; if (typeof method == "function") { failed = !method(fake); } else { failed = typeof fake[method] == "function" ? !fake[method].apply(fake, args) : !fake[method]; } if (failed) { failAssertion(this, fake.printf.apply(fake, [message].concat(args))); } else { assert.pass(name); } }; } function exposedName(prefix, prop) { return !prefix || /^fail/.test(prop) ? prop : prefix + prop.slice(0, 1).toUpperCase() + prop.slice(1); } assert = { failException: "AssertError", fail: function fail(message) { var error = new Error(message); error.name = this.failException || assert.failException; throw error; }, pass: function pass(assertion) {}, callOrder: function assertCallOrder() { verifyIsStub.apply(null, arguments); var expected = "", actual = ""; if (!sinon.calledInOrder(arguments)) { try { expected = [].join.call(arguments, ", "); var calls = slice.call(arguments); var i = calls.length; while (i) { if (!calls[--i].called) { calls.splice(i, 1); } } actual = sinon.orderByFirstCall(calls).join(", "); } catch (e) { // If this fails, we'll just fall back to the blank string } failAssertion(this, "expected " + expected + " to be " + "called in order but were called as " + actual); } else { assert.pass("callOrder"); } }, callCount: function assertCallCount(method, count) { verifyIsStub(method); if (method.callCount != count) { var msg = "expected %n to be called " + sinon.timesInWords(count) + " but was called %c%C"; failAssertion(this, method.printf(msg)); } else { assert.pass("callCount"); } }, expose: function expose(target, options) { if (!target) { throw new TypeError("target is null or undefined"); } var o = options || {}; var prefix = typeof o.prefix == "undefined" && "assert" || o.prefix; var includeFail = typeof o.includeFail == "undefined" || !!o.includeFail; for (var method in this) { if (method != "export" && (includeFail || !/^(fail)/.test(method))) { target[exposedName(prefix, method)] = this[method]; } } return target; }, match: function match(actual, expectation) { var matcher = sinon.match(expectation); if (matcher.test(actual)) { assert.pass("match"); } else { var formatted = [ "expected value to match", " expected = " + sinon.format(expectation), " actual = " + sinon.format(actual) ] failAssertion(this, formatted.join("\n")); } } }; mirrorPropAsAssertion("called", "expected %n to have been called at least once but was never called"); mirrorPropAsAssertion("notCalled", function (spy) { return !spy.called; }, "expected %n to not have been called but was called %c%C"); mirrorPropAsAssertion("calledOnce", "expected %n to be called once but was called %c%C"); mirrorPropAsAssertion("calledTwice", "expected %n to be called twice but was called %c%C"); mirrorPropAsAssertion("calledThrice", "expected %n to be called thrice but was called %c%C"); mirrorPropAsAssertion("calledOn", "expected %n to be called with %1 as this but was called with %t"); mirrorPropAsAssertion("alwaysCalledOn", "expected %n to always be called with %1 as this but was called with %t"); mirrorPropAsAssertion("calledWithNew", "expected %n to be called with new"); mirrorPropAsAssertion("alwaysCalledWithNew", "expected %n to always be called with new"); mirrorPropAsAssertion("calledWith", "expected %n to be called with arguments %*%C"); mirrorPropAsAssertion("calledWithMatch", "expected %n to be called with match %*%C"); mirrorPropAsAssertion("alwaysCalledWith", "expected %n to always be called with arguments %*%C"); mirrorPropAsAssertion("alwaysCalledWithMatch", "expected %n to always be called with match %*%C"); mirrorPropAsAssertion("calledWithExactly", "expected %n to be called with exact arguments %*%C"); mirrorPropAsAssertion("alwaysCalledWithExactly", "expected %n to always be called with exact arguments %*%C"); mirrorPropAsAssertion("neverCalledWith", "expected %n to never be called with arguments %*%C"); mirrorPropAsAssertion("neverCalledWithMatch", "expected %n to never be called with match %*%C"); mirrorPropAsAssertion("threw", "%n did not throw exception%C"); mirrorPropAsAssertion("alwaysThrew", "%n did not always throw exception%C"); sinon.assert = assert; if (typeof define === "function" && define.amd) { define(["module"], function(module) { module.exports = assert; }); } else if (commonJSModule) { module.exports = assert; } }(typeof sinon == "object" && sinon || null, typeof window != "undefined" ? window : (typeof self != "undefined") ? self : global)); /** * @depend ../../sinon.js * @depend event.js */ /*jslint eqeqeq: false, onevar: false*/ /*global sinon, module, require, XDomainRequest*/ /** * Fake XDomainRequest object */ if (typeof sinon == "undefined") { this.sinon = {}; } sinon.xdr = { XDomainRequest: this.XDomainRequest }; // wrapper for global (function (global) { var xdr = sinon.xdr; xdr.GlobalXDomainRequest = global.XDomainRequest; xdr.supportsXDR = typeof xdr.GlobalXDomainRequest != "undefined"; xdr.workingXDR = xdr.supportsXDR ? xdr.GlobalXDomainRequest : false; function FakeXDomainRequest() { this.readyState = FakeXDomainRequest.UNSENT; this.requestBody = null; this.requestHeaders = {}; this.status = 0; this.timeout = null; if (typeof FakeXDomainRequest.onCreate == "function") { FakeXDomainRequest.onCreate(this); } } function verifyState(xdr) { if (xdr.readyState !== FakeXDomainRequest.OPENED) { throw new Error("INVALID_STATE_ERR"); } if (xdr.sendFlag) { throw new Error("INVALID_STATE_ERR"); } } function verifyRequestSent(xdr) { if (xdr.readyState == FakeXDomainRequest.UNSENT) { throw new Error("Request not sent"); } if (xdr.readyState == FakeXDomainRequest.DONE) { throw new Error("Request done"); } } function verifyResponseBodyType(body) { if (typeof body != "string") { var error = new Error("Attempted to respond to fake XDomainRequest with " + body + ", which is not a string."); error.name = "InvalidBodyException"; throw error; } } sinon.extend(FakeXDomainRequest.prototype, sinon.EventTarget, { open: function open(method, url) { this.method = method; this.url = url; this.responseText = null; this.sendFlag = false; this.readyStateChange(FakeXDomainRequest.OPENED); }, readyStateChange: function readyStateChange(state) { this.readyState = state; var eventName = ''; switch (this.readyState) { case FakeXDomainRequest.UNSENT: break; case FakeXDomainRequest.OPENED: break; case FakeXDomainRequest.LOADING: if (this.sendFlag){ //raise the progress event eventName = 'onprogress'; } break; case FakeXDomainRequest.DONE: if (this.isTimeout){ eventName = 'ontimeout' } else if (this.errorFlag || (this.status < 200 || this.status > 299)) { eventName = 'onerror'; } else { eventName = 'onload' } break; } // raising event (if defined) if (eventName) { if (typeof this[eventName] == "function") { try { this[eventName](); } catch (e) { sinon.logError("Fake XHR " + eventName + " handler", e); } } } }, send: function send(data) { verifyState(this); if (!/^(get|head)$/i.test(this.method)) { this.requestBody = data; } this.requestHeaders["Content-Type"] = "text/plain;charset=utf-8"; this.errorFlag = false; this.sendFlag = true; this.readyStateChange(FakeXDomainRequest.OPENED); if (typeof this.onSend == "function") { this.onSend(this); } }, abort: function abort() { this.aborted = true; this.responseText = null; this.errorFlag = true; if (this.readyState > sinon.FakeXDomainRequest.UNSENT && this.sendFlag) { this.readyStateChange(sinon.FakeXDomainRequest.DONE); this.sendFlag = false; } }, setResponseBody: function setResponseBody(body) { verifyRequestSent(this); verifyResponseBodyType(body); var chunkSize = this.chunkSize || 10; var index = 0; this.responseText = ""; do { this.readyStateChange(FakeXDomainRequest.LOADING); this.responseText += body.substring(index, index + chunkSize); index += chunkSize; } while (index < body.length); this.readyStateChange(FakeXDomainRequest.DONE); }, respond: function respond(status, contentType, body) { // content-type ignored, since XDomainRequest does not carry this // we keep the same syntax for respond(...) as for FakeXMLHttpRequest to ease // test integration across browsers this.status = typeof status == "number" ? status : 200; this.setResponseBody(body || ""); }, simulatetimeout: function(){ this.status = 0; this.isTimeout = true; // Access to this should actually throw an error this.responseText = undefined; this.readyStateChange(FakeXDomainRequest.DONE); } }); sinon.extend(FakeXDomainRequest, { UNSENT: 0, OPENED: 1, LOADING: 3, DONE: 4 }); sinon.useFakeXDomainRequest = function () { sinon.FakeXDomainRequest.restore = function restore(keepOnCreate) { if (xdr.supportsXDR) { global.XDomainRequest = xdr.GlobalXDomainRequest; } delete sinon.FakeXDomainRequest.restore; if (keepOnCreate !== true) { delete sinon.FakeXDomainRequest.onCreate; } }; if (xdr.supportsXDR) { global.XDomainRequest = sinon.FakeXDomainRequest; } return sinon.FakeXDomainRequest; }; sinon.FakeXDomainRequest = FakeXDomainRequest; })(this); if (typeof module == "object" && typeof require == "function") { module.exports = sinon; } return sinon;}.call(typeof window != 'undefined' && window || {}));
import 'babel-core/polyfill'; import React from 'react'; import ReactDOM from 'react-dom'; import { Router } from 'react-router'; import { Provider } from 'react-redux'; import { ReduxRouter } from 'redux-router'; import createBrowserHistory from 'history/lib/createBrowserHistory' import configureStore from '../common/store/configureStore'; import routes from '../common/routes'; import DevTools from '../server/devtools'; import "../../styles/index.css"; const history = createBrowserHistory(); const initialState = window.__INITIAL_STATE__; const store = configureStore(initialState); const rootElement = document.getElementById('root'); ReactDOM.render( <div> <Provider store={store}> <ReduxRouter> <Router children={routes} history={history} /> </ReduxRouter> </Provider> </div>, document.getElementById('root') ); if (process.env.NODE_ENV !== 'production') { require('../server/createDevToolsWindow')(store); }
(function () { window.Twis = {}; /** * Tweet */ var Tweet = function () {}; Tweet.search = function (keywords, tweets, callback) { if (typeof tweets === 'function') { callback = tweets; tweets = []; } if (keywords.length === 0) { callback(false, tweets); } else { $.ajax({ url: 'https://twitter.com/phoenix_search.phoenix', headers: { 'X-Phx': true }, data: { q: keywords[0], mode: 'relevance' }, success: function (data) { $.each(data.statuses, function (index, tweet) { tweets.push(tweet); }); keywords.shift(); Tweet.search(keywords, tweets, callback); }, error: function () { callback(true, []); } }); } }; Tweet.filter = function (tweets) { var readTweets = JSON.parse(localStorage['readTweets'] || '[]') , filteredTweets = []; $.each(tweets, function (index, tweet) { if (readTweets.indexOf(tweet.id) === -1) { filteredTweets.push(tweet); readTweets.push(tweet.id); localStorage['readTweets'] = JSON.stringify(readTweets); } }); return filteredTweets; }; Tweet.append = function (obj) { var tweetsElm = $('ul#tweets'); if (typeof obj === 'string') { // if obj is error message tweetsElm.append('<li>' + obj + '</li>'); } else { $.each(obj, function (index, tweet) { tweetsElm.append( '<li>' + '<div class="profile-image">' + '<img src="' + tweet.user.profile_image_url + '" height="48" width="48">' + '</div>' + '<div class="content">' + '<div class="name">' + '<span class="screen-name">' + '<a href="https://twitter.com/#!/' + tweet.user.screen_name + '" target="_blank">' + tweet.user.screen_name + '</a>' + '</span>' + '<span class="name">' + tweet.user.name + '</span>' + '</div>' + '<p>' + tweet.text + '</p>' + '<div class="info">' + '<a href="https://twitter.com/#!/' + tweet.user.screen_name + '/status/' + tweet.id_str + '" target="_blank">' + tweet.created_at + '</a>' + '</div>' + '</div>' + '</li>' ); }); } }; Tweet.displayAll = function () { var keywords = Keyword.getAll() , options = { lines: 12, length: 7, width: 4, radius: 10, color: '#000', speed: 1, trail: 60, shadow: false }; new Spinner(options).spin(document.getElementById('loading')); Tweet.search(keywords, function (err, tweetsObj) { var tweets = Tweet.filter(tweetsObj) , obj = null; $('#loading').remove(); if (err) { obj = 'Some errors occurred while searching keywords' } else if (tweets.length === 0) { obj = 'No unread tweets'; } else { obj = tweets; } Tweet.append(obj); }); }; /** * Keyword */ var Keyword = function (keywordStr) { this.keywordStr = keywordStr; }; Keyword.getAll = function () { var keywordsStr = localStorage['keywords'] || '[]' , keywordsAry = JSON.parse(keywordsStr).sort(); return keywordsAry; }; Keyword.getAllObjects = function () { var keywords = Keyword.getAll() , keywordsObj = []; $.each(keywords, function (index, value) { keywordsObj.push(new Keyword(value)); }); return keywordsObj; }; Keyword.displayAll = function () { var keywordsObj = Keyword.getAllObjects(); $.each(keywordsObj, function (index, value) { value.append(); }); }; Keyword.prototype.save = function () { var keywords = Keyword.getAll(); if (keywords.indexOf(this.keywordStr) === -1) { keywords.push(this.keywordStr); localStorage['keywords'] = JSON.stringify(keywords); } }; Keyword.prototype.append = function () { $('ul#keywords').append( '<li>' + '<span class="delete mimic-links" data-keyword="' + this.keywordStr + '">' + 'del' + '</span>' + this.keywordStr + '</li>' ); }; Keyword.prototype.delete = function () { var keywords = Keyword.getAll() , index = keywords.indexOf(this.keywordStr); keywords.splice(index, 1); localStorage['keywords'] = JSON.stringify(keywords); }; // save $('form').on('click', 'button', function (e) { e.preventDefault(); var keywordElm = $('#keyword') , keywordStr = keywordElm.val(); keywordElm.val(''); var keyword = new Keyword(keywordStr); keyword.save(); keyword.append(); }); // delete $('ul#keywords').on('click', 'span.delete', function (e) { var currentElm = $(e.currentTarget) , keywordStr = currentElm.attr('data-keyword'); if (confirm('delete?')) { var keyword = new Keyword(keywordStr); keyword.delete(); currentElm.parent().remove(); } }); Twis.Tweet = Tweet; Twis.Keyword = Keyword; })();
/** * @author mrdoob / http://mrdoob.com/ */ Sidebar.Geometry = function ( editor ) { var signals = editor.signals; var container = new UI.CollapsiblePanel(); container.setCollapsed( editor.config.getKey( 'ui/sidebar/geometry/collapsed' ) ); container.onCollapsedChange( function ( boolean ) { editor.config.setKey( 'ui/sidebar/geometry/collapsed', boolean ); } ); container.setDisplay( 'none' ); var geometryType = new UI.Text().setTextTransform( 'uppercase' ); container.addStatic( geometryType ); // Actions var objectActions = new UI.Select().setPosition('absolute').setRight( '8px' ).setFontSize( '11px' ); objectActions.setOptions( { 'Actions': 'Actions', 'Center': 'Center', 'Convert': 'Convert', 'Flatten': 'Flatten' } ); objectActions.onClick( function ( event ) { event.stopPropagation(); // Avoid panel collapsing } ); objectActions.onChange( function ( event ) { var action = this.getValue(); var object = editor.selected; var geometry = object.geometry; if ( confirm( action + ' ' + object.name + '?' ) === false ) return; switch ( action ) { case 'Center': var offset = geometry.center(); var newPosition = object.position.clone(); newPosition.sub( offset ); editor.execute( new SetPositionCommand( object, newPosition ) ); editor.signals.geometryChanged.dispatch( object ); break; case 'Convert': if ( geometry instanceof THREE.Geometry ) { editor.execute( new SetGeometryCommand( object, new THREE.BufferGeometry().fromGeometry( geometry ) ) ); } break; case 'Flatten': var newGeometry = geometry.clone(); newGeometry.uuid = geometry.uuid; newGeometry.applyMatrix( object.matrix ); var cmds = [ new SetGeometryCommand( object, newGeometry ), new SetPositionCommand( object, new THREE.Vector3( 0, 0, 0 ) ), new SetRotationCommand( object, new THREE.Euler( 0, 0, 0 ) ), new SetScaleCommand( object, new THREE.Vector3( 1, 1, 1 ) ) ]; editor.execute( new MultiCmdsCommand( cmds ), 'Flatten Geometry' ); break; } this.setValue( 'Actions' ); } ); container.addStatic( objectActions ); container.add( new UI.Break() ); // uuid var geometryUUIDRow = new UI.Panel(); var geometryUUID = new UI.Input().setWidth( '115px' ).setFontSize( '12px' ).setDisabled( true ); var geometryUUIDRenew = new UI.Button( '⟳' ).setMarginLeft( '7px' ).onClick( function () { geometryUUID.setValue( THREE.Math.generateUUID() ); editor.execute( new SetGeometryValueCommand( editor.selected, 'uuid', geometryUUID.getValue() ) ); } ); geometryUUIDRow.add( new UI.Text( 'UUID' ).setWidth( '90px' ) ); geometryUUIDRow.add( geometryUUID ); geometryUUIDRow.add( geometryUUIDRenew ); container.add( geometryUUIDRow ); // name var geometryNameRow = new UI.Panel(); var geometryName = new UI.Input().setWidth( '150px' ).setFontSize( '12px' ).onChange( function () { editor.execute( new SetGeometryValueCommand( editor.selected, 'name', geometryName.getValue() ) ); } ); geometryNameRow.add( new UI.Text( 'Name' ).setWidth( '90px' ) ); geometryNameRow.add( geometryName ); container.add( geometryNameRow ); // geometry container.add( new Sidebar.Geometry.Geometry( editor ) ); // buffergeometry container.add( new Sidebar.Geometry.BufferGeometry( editor ) ); // parameters var parameters = new UI.Panel(); container.add( parameters ); // function build() { var object = editor.selected; if ( object && object.geometry ) { var geometry = object.geometry; container.setDisplay( 'block' ); geometryType.setValue( geometry.type ); geometryUUID.setValue( geometry.uuid ); geometryName.setValue( geometry.name ); // parameters.clear(); if ( geometry.type === 'BufferGeometry' || geometry.type === 'Geometry' ) { parameters.add( new Sidebar.Geometry.Modifiers( editor, object ) ); } else if ( Sidebar.Geometry[ geometry.type ] !== undefined ) { parameters.add( new Sidebar.Geometry[ geometry.type ]( editor, object ) ); } } else { container.setDisplay( 'none' ); } } signals.objectSelected.add( build ); signals.geometryChanged.add( build ); return container; }
import { createInventory, createOption, createOptionValue } from 'assets/js/store/modules/inventories/factories'; import inventoriesModule from 'assets/js/store/modules/inventories'; import inventoryFormComponent from 'formwidgets/inventory/components/inventories/form/form'; // // factory // const mount = factory({ components: { 'v-inventory-form': inventoryFormComponent, }, modules: { inventories: inventoriesModule, }, }); // // tests // describe('inventory form', () => { it('form displays the correct header for context', (done) => { vm = mount({ template: '<v-inventory-form />', }); vm.$store.commit('inventories/setInventoryFormContext', 'create'); vm.$nextTick(() => { expect(vm.$el.textContent).to.include('backend.relation.create_name'); vm.$store.commit('inventories/setInventoryFormContext', 'update'); vm.$nextTick(() => { expect(vm.$el.textContent).to.include('backend.relation.update_name'); done(); }); }); }); it('closes when cancel is clicked', () => { vm = mount({ template: '<v-inventory-form />', }, { inventories: { inventoryForm: { isVisible: true, }, }, }); click(vm.$el.querySelector('[data-action=cancel]')); expect(vm.$store.state.inventories.inventoryForm.isVisible).to.be.false; }); it('tracks form data', (done) => { vm = mount({ template: '<v-inventory-form />', }); input('foo', vm.$el.querySelector('[data-input=sku]')); input(5, vm.$el.querySelector('[data-input=quantity]')); vm.$nextTick(() => { expect(vm.$store.state.inventories.inventoryForm.data.sku).to.equal('foo'); expect(vm.$store.state.inventories.inventoryForm.data.quantity).to.equal(5); done(); }); }); it('create a new inventory', (done) => { vm = mount({ template: '<v-inventory-form />', }); input('ABC123', vm.$el.querySelector('[data-input=sku]')); input('10', vm.$el.querySelector('[data-input=quantity]')); click(vm.$el.querySelector('[data-action=confirm]')); setTimeout(() => { expect(vm.$store.state.inventories.inventories).to.deep.equal([ createInventory({ _delete: false, _key: 1, id: null, quantity: 10, sku: 'ABC123', valueKeys: [], }), ]); done(); }, 10); }); it('updates an existing inventory', (done) => { vm = mount({ template: '<v-inventory-form />', }, { inventories: { inventoryForm: { data: createInventory({ _key: 123, id: 1, sku: 'ABC123', quantity: 10, }), }, inventories: [ createInventory({ _key: 123, id: 1, sku: 'ABC123', quantity: 10, }), ], }, }); input('DEF456', vm.$el.querySelector('[data-input=sku]')); input('123', vm.$el.querySelector('[data-input=quantity]')); click(vm.$el.querySelector('[data-action=confirm]')); setTimeout(() => { expect(vm.$store.state.inventories.inventories).to.deep.equal([ createInventory({ _delete: false, _key: 123, id: 1, quantity: 123, sku: 'DEF456', valueKeys: [], }), ]); done(); }, 10); }); it('doesn\'t show select boxes for deleted options', () => { vm = mount({ template: '<v-inventory-form />', }, { inventories: { inventoryForm: { isVisible: true, }, options: [ createOption({ _delete: true, _key: 100, name: 'size' }), createOption({ _delete: false, _key: 200, name: 'color' }), ], }, }); expect(vm.$el.querySelector('[data-option="100"]')).to.be.null; expect(vm.$el.querySelector('[data-option="200"]')).not.to.be.null; }); it('disables deleted values', () => { vm = mount({ template: '<v-inventory-form />', }, { inventories: { inventoryForm: { isVisible: true, }, options: [ createOption({ values: [ createOptionValue({ _delete: true, _key: 100 }), createOptionValue({ _delete: false, _key: 200 }), ], }), ], }, }); expect(vm.$el.querySelector('[data-value="100"]').disabled).to.be.true; expect(vm.$el.querySelector('[data-value="200"]').disabled).to.be.false; }); it('converts empty skus to null', () => { }); });
 $(document).ready(function () { var oldData = [ ['Javascript', 13], ['CSS', 13], ['HTML', 13], ['AngularJS', 4], ['jQuery', 13], ['Java', 18], ['C', 5], ['C#', 4], ['SQL', 6], ['Zurb Foundation Framework', 12], ['Bootstrap Framework', 6], ['chartsJS', 8], ['Visual Studio (Software)', 13] ], oldMonth = $('#oldMonth').val(), currentMonth = new Date().getMonth() + 1; $(function () { highchart(oldData); buildTable(); updateXP(); bindButtons(); }) function bindButtons() { $('#demo').on('click', function () { demoChart(); demoCircle(); }) } function demoChart() { var myGraph = new Chart(document.getElementById("demoChart").getContext("2d")).Line({}, {}), ctx = document.getElementById("demoChart").getContext("2d"), demoData = { labels: ["departmentOne", "departmentTwo", "departmentThree"], datasets: [{ label: "Resolved", fillColor: "red", data: [20, 80, 92] }, { label: "Unresolved", fillColor: "blue", data: [92, 80, 20] }] }; myGraph.destroy(); myGraph = new Chart(document.getElementById("demoChart").getContext("2d")).Bar(demoData, {}); generateLegend(demoData); } function demoCircle() { var myGraph = new Chart(document.getElementById("demoCircle").getContext("2d")).Line({}, {}), ctx = document.getElementById("demoCircle").getContext("2d"), demoCircle = [ { value: 250, color: "#F7464A", highlight: "#FF5A5E", label: "Outgoing Call" }, { value: 80, color: "#46BFBD", highlight: "#5AD3D1", label: "Incoming Call" }, { value: 20, color: "#FDB45C", highlight: "#FFC870", label: "Face To Face" }, ] myGraph.destroy(); myGraph = new Chart(document.getElementById("demoCircle").getContext("2d")).Pie(demoCircle, {}); } function generateLegend(graph) { var legend = '', datasets = graph.datasets; graphClass = "graph-legend"; $('#callLogTitle').html("Call Center Data"); for (var i = 0; i < graph.datasets.length; i++) { legend += '<li class=graph-legend><span id="' + datasets[i].label.replace(/ /g, "-") + '" class="' + graphClass + '" style="background: ' + graph.datasets[i].fillColor + ';" ></span> ' + datasets[i].label + ' <i class="graph-legend fa fa-pie-chart fa-spin"></i></li>'; } $('#legend').html(legend); } function highchart(arrayData) { var data = { chart: { type: 'column' }, title: { text: '' }, xAxis: { type: 'category', labels: { rotation: -45, style: { fontSize: '13px', fontFamily: 'Verdana, sans-serif' } } }, yAxis: { min: 0, title: { text: 'Time in Months' } }, legend: { enabled: true }, tooltip: { pointFormat: 'Experience in months' }, series: [{ name: 'Experience', data: arrayData, dataLabels: { enabled: false, rotation: -90, color: '#FFFFFF', align: 'right', format: '{point.y:.1f}', // one decimal y: 10, // 10 pixels down from the top style: { fontSize: '13px', fontFamily: 'Verdana, sans-serif' } } }] } $('#container').highcharts(data); } function buildTable() { var headerText = '<tr>', headers = ['Job Title', 'Responsibilities', 'Time Worked'], jobs = ['ESTG Programmer', 'TagWorks Freelance Developer'], responsibilities = ["Developed web applications for the Enrollment Services Technology Group. Tested/maintained/developed department websites. (<a href='http://financialaid.utep.edu/'>Financial Aid</a>)", "Freelance web design"], timeWorked = ['1/30/2012-Present',"9/6/2015-Present"]; bodyText = ''; for (var i = 0; i < headers.length; i++) { headerText += '<th>' + headers[i] + '</th>'; } headerText += '</tr>'; for (var j = 0; j < jobs.length; j++) { bodyText += '<tr><td>' + jobs[j] + '</td>' + '<td>' + responsibilities[j] + '</td>' + '<td>' + timeWorked[j] + '</td></tr>'; } $('#tableHeaders').html(headerText); $('#tableBody').html(bodyText); } function updateXP() { if(oldMonth!=currentMonth){ oldMonth = currentMonth; updateData(); } } function updateData(data) { var skillNames = []; } });
describe('unique', function () { var uniqueFilter; beforeEach(module('ui.filters')); beforeEach(inject(function ($filter) { uniqueFilter = $filter('unique'); })); it('should return unique entries based on object equality', function () { var arrayToFilter = [ {key: 'value'}, {key: 'value2'}, {key: 'value'} ]; expect(uniqueFilter(arrayToFilter)).toEqual([ {key: 'value'}, {key: 'value2'} ]); }); it('should return unique entries based on object equality for complex objects', function () { var arrayToFilter = [ {key: 'value', other: 'other1'}, {key: 'value2', other: 'other2'}, {other: 'other1', key: 'value'} ]; expect(uniqueFilter(arrayToFilter)).toEqual([ {key: 'value', other: 'other1'}, {key: 'value2', other: 'other2'} ]); }); it('should return unique entries based on the key provided', function () { var arrayToFilter = [ {key: 'value'}, {key: 'value2'}, {key: 'value'} ]; expect(uniqueFilter(arrayToFilter, 'key')).toEqual([ {key: 'value'}, {key: 'value2'} ]); }); it('should return unique entries based on the key provided for complex objects', function () { var arrayToFilter = [ {key: 'value', other: 'other1'}, {key: 'value2', other: 'other2'}, {key: 'value', other: 'other3'} ]; expect(uniqueFilter(arrayToFilter, 'key')).toEqual([ { key: 'value', other: 'other1' }, { key: 'value2', other: 'other2' } ]); }); it('should return unique primitives in arrays', function () { expect(uniqueFilter([1, 2, 1, 3])).toEqual([1, 2, 3]); }); it('should work correctly for arrays of mixed elements and object equality', function () { expect(uniqueFilter([1, {key: 'value'}, 1, {key: 'value'}, 2, "string", 3])).toEqual([1, {key: 'value'}, 2, "string", 3]); }); it('should work correctly for arrays of mixed elements and a key specified', function () { expect(uniqueFilter([1, {key: 'value'}, 1, {key: 'value'}, 2, "string", 3], 'key')).toEqual([1, {key: 'value'}, 2, "string", 3]); }); it('should return unmodified object if not array', function () { expect(uniqueFilter('string', 'someKey')).toEqual('string'); }); it('should return unmodified array if provided key === false', function () { var arrayToFilter = [ {key: 'value1'}, {key: 'value2'} ]; expect(uniqueFilter(arrayToFilter, false)).toEqual(arrayToFilter); }); });
var glob = require('glob'); var files = glob.sync('./content/*'); var Promise = require("bluebird"); var fs = Promise.promisifyAll(require("fs")); var contentPath = './content/'; var imageNumbers = files.map(function(name) { return parseInt(name.substr(contentPath.length)); }); imageNumbers.sort(function numOrdA(a, b){ return (a-b); }); module.exports = { /** * @param {Number} previous * @returns {data: {String}, id: {String}} object */ getRand: function(previous) { if (previous === undefined) { previous = 0; } //var nextIndex = (imageNumbers.indexOf(previous) || previous) + 1; var nextNumber = (previous + 1); return fs.readFileAsync(contentPath + nextNumber + '.jpg', 'base64').then(function(data) { return {data:data.toString(), id: nextNumber}; }); }, /** * @param {String} data base64 encoded image * @returns {Promise<Number>} id of the image */ save: function(data) { var id = Math.max.apply(imageNumbers, imageNumbers) + 1; return fs.writeFileAsync( contentPath + id + ".jpg", new Buffer(data, "base64")).then(function(){ console.log("image saved ", id); return id; }); }, /** * * @param id */ getLikesFor: function(id) { } };
var client = require('box-view').createClient('<TOKEN>'); function getThumbnail(id, width, height, callback) { client.documents.getThumbnail(id, width, height, function (err, response) { var ms, retry; var retryAfter = response.headers['retry-after'] if (retryAfter) { ms = retryAfter * 1000; retry = getThumbnail.bind(null, id, width, height, callback); return setTimeout(retry, ms); } callback(response); }) } module.exports = getThumbnail;
var gGameview; function startup() { var root = document.getElementById('root'); var clients = { checkers: new GameClientChessCheckers(root, "checkers"), chess: new GameClientChessCheckers(root, "chess"), match: new GameClientMatch(root, "match") } gGameview = new ArtefactGameServerConnectionView(gameServer, ["checkers", "chess", "match"], clients, true); }
var doingFlag = false, //动作执行标志 pos_x = 1, //当前的横坐标 pos_y = 1, //当前的纵坐标 dir = [0,90,180,270,360], //方向列表 dir_now = 0; //当前的方向下标 //通过方向,计算运动后的位置 function positionFoward(dirFoward){ switch(dirFoward){ case 0: if (pos_y === 1) { //边界检测 break; }else{ pos_y--; } break; case 1: if (pos_x === 10) { //边界检测 break; }else{ pos_x++; } break; case 2: if (pos_y === 10) { //边界检测 break; }else{ pos_y++; } break; case 3: if (pos_x === 1) { //边界检测 break; }else{ pos_x--; } break; } } //转向动画 //输入为方向的下标 function animateDir(now_dir,target_dir){ var square = document.getElementById('square'), speed, //转向速度 clockwise, //true顺时针旋转 false逆时针 timer, degree ; //旋转的角度 /* square.style.transform = 'rotate(' + dir[now_dir] + 'deg)'; */ //当前方向与目标方向相同 if(dir[target_dir] == dir[now_dir]){ doingFlag = false; return; }else if( dir[now_dir] - dir[target_dir] > 0 && dir[now_dir] - dir[target_dir] < 270 ){ //now > target 使用逆时针 clockwise = false; }else if( dir[target_dir] - dir[now_dir] == 270){ clockwise = false; now_dir = 4; }else if( dir[now_dir] - dir[target_dir] == 270){ clockwise = true; target_dir = 4; }else{ //now < target 使用顺时针 clockwise = true; } //计算动画速度 if((Math.abs(dir[target_dir] - dir[now_dir])) == 90){ speed = 2; //2ms }else{ speed = 1; //1ms } degree = dir[now_dir]; timer = setInterval(function(){ if(clockwise){ degree++; }else{ degree--; } square.style.transform = 'rotate(' + degree + 'deg)'; if(degree == dir[target_dir]){ clearInterval(timer); doingFlag = false; } },speed); //更新当前方块的方向状态 if(target_dir == 4){ dir_now = 0; }else{ dir_now = target_dir; } } //根据X,Y坐标,相对原位置移动 function move(){ var square = document.getElementById('square'), now_top = parseInt(window.getComputedStyle(square, null).top), //当前方块顶边距 now_left = parseInt(window.getComputedStyle(square, null).left), //当前方块左边距 target_top = 60 + (pos_y - 1) * 61, //移动后方块顶边距 target_left = 60 + (pos_x - 1) * 61, //移动后方块左边距 distance, //保存需要改变的值,top或者left target_distance, x_flag, //布尔量 是否是x方向的移动 timer; //判断需要改变的是左边距还是顶边距 if(target_top == now_top && target_left == now_left){ doingFlag = false; return; }else if(target_top == now_top){ x_flag = true; distance = now_left; target_distance = target_left; }else{ x_flag = false; distance = now_top; target_distance = target_top; } timer = setInterval(function(){ if(x_flag){ if(now_left > target_left){ distance--; }else{ distance++; } square.style.left = distance + 'px'; }else{ if(now_top > target_top){ distance--; }else{ distance++; } square.style.top = distance + 'px'; } if(target_distance == distance){ clearInterval(timer); doingFlag = false; } },1); } //TUN LEF指令 function turnLeft(){ if(dir_now === 0){ animateDir(0,3); }else{ animateDir(dir_now,dir_now-1); } } //TUN RIG指令 function turnRight() { if(dir_now == 3){ animateDir(3,0); }else{ animateDir(dir_now,dir_now+1); } } //TUN BAC指令 function turnBack(){ if(dir_now<2){ animateDir(dir_now,dir_now+2); }else{ animateDir(dir_now,dir_now-2); } } (function(){ var square = document.getElementById('square'), do_btn = document.getElementById('do'), refresh_btn = document.getElementById('refresh'), text_input = document.getElementById('textarea'), row_num = 1; //textarea的内容行数 //初始化 refresh(); //textarea键盘按键被按下事件 text_input.addEventListener('keydown',function(){ setTimeout(function(){ var content = text_input.value, nNum; //若未匹配到换行则正则匹配返回NULL,没有length属性 //故先判断是否有换行 if( content.match(/\n/g) ){ nNum = content.match(/\n/g).length; }else{ nNum = 0; } //行数为换行数+1 //判断换行符的数目是否变化 if(row_num !== nNum + 1){ //更新行标 rowNum(row_num, nNum + 1 ); row_num = nNum + 1; }else{ return; } },0); },false); //执行按钮点击事件 do_btn.addEventListener('click',function(){ if(doingFlag){ return; } doingFlag = true; var square = document.getElementById('square'), finalOrder = [], timer_order, i = 0; finalOrder = parseOrder(); console.log(finalOrder); function delayDo(){ doOrder(finalOrder[i]); if(finalOrder[i+1]){ i++; setTimeout(delayDo,500); }else{ return; } } delayDo(); },false); //Refresh按钮点击事件 refresh_btn.addEventListener('click',refresh,false); function refresh(){ var content = text_input.value, nNum, square = document.getElementById('square'); if(doingFlag){ return; } pos_x = 1; //当前的横坐标 pos_y = 1; //当前的纵坐标 dir_now = 0; //当前的方向下标 square.style.left = 60 + 'px'; square.style.top = 60 + 'px'; square.style.transform = 'rotate(' + 0 + 'deg)'; //若未匹配到换行则正则匹配返回NULL,没有length属性 //故先判断是否有换行 if( content.match(/\n/g) ){ nNum = content.match(/\n/g).length; }else{ nNum = 0; } //行数为换行数+1 //判断换行符的数目是否变化 if(row_num !== nNum + 1){ //更新行标 rowNum(row_num, nNum + 1 ); row_num = nNum + 1; }else{ return; } } }()); //行标更新函数 function rowNum(num_before,num_now){ var leftCol = document.getElementById("leftCol"), topValue; while(num_before !== num_now){ var pNode; if(num_now < num_before){ pNode = leftCol.lastChild; leftCol.removeChild(pNode); num_before--; }else{ pNode = document.createElement("p"); pNode.innerHTML = num_before + 1; leftCol.appendChild(pNode); num_before++; } } if(num_now > 11){ topValue =0 - (num_now - 11) * 22 + 8; console.log(topValue); leftCol.style.top = topValue + 'px'; }else{ leftCol.style.top = 0+'px'; } } //命令解析检错 function parseOrder(){ var text_input = document.getElementById('textarea'), content = text_input.value, //textarea内容 leftCol = document.getElementById("leftCol"), orderLists = [], //逐行解析的内容 numRepeat , //每条指令 移动格数 rowOrderLists, //解析单行指令 finalOrder = [], //最终需执行的命令列表 errFlag = false, //命令非法标志 orders = ["GO","TUN","TRA","MOV","TOP","RIG","BAC","BOT","LEF"]; //正确的指令条目 orderLists = content.split("\n"); //用换行符分割内容 for(i = 0,len = orderLists.length;i<len;i++){ if(orderLists[i].match(/\d/)){ //用正则匹配命令的执行次数 numRepeat = parseInt(orderLists[i].match(/\d/)); if(numRepeat>9){ //如果执行次数超过9次按9次执行 numRepeat = 9; } }else{ numRepeat = 1; //如果没有输入执行次数 默认为1 } rowOrderLists = []; rowOrderLists = orderLists[i].match(/([A-Za-z]+)/g); //正则匹配分解一行命令保存至数组 //命令格式判断 命令为空,GO命令同行还有其他指令,其他运动命令后没有跟方向指令均判断为错误 if( !rowOrderLists || rowOrderLists.length>2 || (rowOrderLists[0] == "GO" && rowOrderLists[1]) || (rowOrderLists[0] !== "GO" && !rowOrderLists[1]) ){ leftCol.getElementsByTagName('p')[i].style.background = '#f00'; }else{ //判断行内的指令是否包换在合法指令数组内 for(var j = 0;j<rowOrderLists.length;j++){ if(orders.indexOf(rowOrderLists[j]) == -1){ leftCol.getElementsByTagName('p')[i].style.background = '#f00'; errFlag = true; break; } } //将合法指令压入最终指令数组中 if(!errFlag){ leftCol.getElementsByTagName('p')[i].style.background = ''; while(numRepeat){ //若指令重复多次,则把指令多次压入 numRepeat--; if(rowOrderLists[1]){ finalOrder.push(rowOrderLists[0]+" "+rowOrderLists[1]); }else{ finalOrder.push(rowOrderLists[0]); } } } errFlag = false; } } return finalOrder; } //根据输入命令执行 function doOrder(order){ //根据输入执行相应函数 switch(order){ //************************************************ case "GO": positionFoward(dir_now); move(); break; case "TUN LEF": turnLeft(); break; case "TUN RIG": turnRight(); break; case "TUN BAC": turnBack(); break; // TRA case "TRA TOP": positionFoward(0); move(); break; case "TRA RIG": positionFoward(1); move(); break; case "TRA BOT": positionFoward(2); move(); break; case "TRA LEF": positionFoward(3); move(); break; // MOV case "MOV TOP": animateDir(dir_now,0); positionFoward(0); move(); break; case "MOV RIG": animateDir(dir_now,1); positionFoward(1); move(); break; case "MOV BOT": animateDir(dir_now,2); positionFoward(2); move(); break; case "MOV LEF": animateDir(dir_now,3); positionFoward(3); move(); break; } }
/** * selenium-webdriver 浏览器器多窗口切换 * 使用getAllWindowHandles() 方法 * * */ require('chromedriver') var webdriver = require('selenium-webdriver') var By = webdriver.By; var driver = new webdriver.Builder().forBrowser('chrome').build(); driver.get("https://www.baidu.com/"); driver.findElement(By.id('kw')).sendKeys('音乐') driver.findElement(By.id('kw')).submit(); driver.sleep(3000) driver.findElement(By.xpath('//*[@id="1"]/h3/a')).click(); //第一个搜索结果 打开新的窗口 driver.getAllWindowHandles().then(function(handles){ console.log(handles.length) driver.switchTo().window(handles[1]).then(function(){ driver.sleep(5000) driver.findElement(By.id('ww')).clear() driver.findElement(By.id('ww')).sendKeys("刘德华") }) })
define(function(require){ var Forms = require('joss/util/Forms'); module('joss/util/Forms'); test('', function() { ok(false); }); });
const Utils = require('./utils'); const backpack = require('./backpacktf'); const Login = require('./login'); const Confirmations = require('./confirmations'); const appConsole = require('./console'); let steam, log, Config, manager, automatic; let communityCookies; let g_RelogInterval = null; exports.checkOfferCount = checkOfferCount; exports.register = (Automatic) => { steam = Automatic.steam; log = Automatic.log; Config = Automatic.config; manager = Automatic.manager; automatic = Automatic; Login.register(Automatic); steam.on('debug', msg => log.debug(msg)); steam.on('sessionExpired', relog); }; function saveCookies(cookies, quiet) { communityCookies = cookies; steam.setCookies(cookies); if (!quiet) log.info("Logged into Steam!"); else log.debug("Logged into Steam: cookies set"); } function getBackpackToken() { let acc = Config.account(); if (acc && acc.bptfToken) { return acc.bptfToken; } return backpack.getToken(); } exports.connect = () => { let acc = Config.account(); let login; if (acc && acc.sentry && acc.oAuthToken) { log.info("Logging into Steam with OAuth token"); login = Login.oAuthLogin(acc.sentry, acc.oAuthToken); } else { login = Login.promptLogin(); } login.then(saveCookies).then(tryLogin).then(getBackpackToken).then(setupTradeManager).catch((err) => { log.error("Cannot login to Steam: " + err.message); tryLogin().then(getBackpackToken).then(setupTradeManager); }); } function tryLogin() { return new Promise((resolve) => { function retry() { return tryLogin().then(resolve); } Login.isLoggedIn().then(resolve).catch(([err, loggedIn, familyView]) => { if (err) { log.error("Cannot check Steam login: " + err); Utils.after.seconds(10).then(retry); } else if (!loggedIn) { log.warn("Saved OAuth token is no longer valid."); Login.promptLogin().then(saveCookies).then(retry); } else if (familyView) { log.warn("This account is protected by Family View."); Login.unlockFamilyView().then(retry); } }); }); } function heartbeatLoop() { function loop(timeout) { setTimeout(heartbeatLoop, timeout); } backpack.heartbeat().then(loop, loop); } function setupTradeManager() { backpack.heartbeat().then((timeout) => { const acc = Config.account(); if (Confirmations.enabled()) { if (acc.identity_secret) { log.info("Starting Steam confirmation checker (accepting " + automatic.confirmationsMode() + ")"); Confirmations.setSecret(acc.identity_secret); } else { log.warn("Trade offers won't be confirmed automatically. In order to automatically accept offers, you should supply an identity_secret. Type help identity_secret for help on how to do this. You can hide this message by typing `confirmations none`."); } } else { log.verbose("Trade confirmations are disabled, not starting confirmation checker."); } // Start the input console log.debug("Launching input console."); appConsole.startConsole(automatic); if (!g_RelogInterval) { g_RelogInterval = setInterval(relog, 1000 * 60 * 60 * 1); // every hour } setTimeout(heartbeatLoop, timeout); manager.setCookies(communityCookies, (err) => { if (err) { log.error("Can't get apiKey from Steam: " + err); process.exit(1); } log.info(`Automatic ready. Sell orders enabled; Buy orders ${automatic.buyOrdersEnabled() ? "enabled" : "disabled (type buyorders toggle to enable, help buyorders for info)"}`); checkOfferCount(); setInterval(checkOfferCount, 1000 * 60 * 3); }); }).catch((timeout) => { if (timeout === "getToken") { backpack.getToken().then(setupTradeManager); } else { Utils.after.timeout(timeout).then(setupTradeManager); } }); } function relog() { const acc = Config.account(); if (acc && acc.sentry && acc.oAuthToken) { log.verbose("Renewing web session"); Login.oAuthLogin(acc.sentry, acc.oAuthToken, true).then((cookies) => { saveCookies(cookies, true); log.verbose("Web session renewed"); }).catch((err) => { log.debug("Failed to relog (checking login): " + err.message); Login.isLoggedIn() .then(() => log.verbose("Web session still valid")) .catch(() => log.warn("Web session no longer valid. Steam could be down or your session might no longer be valid. To refresh it, log out (type logout), restart Automatic, and re-enter your credentials")); }); } else { log.verbose("OAuth token not saved, can't renew web session."); } } function checkOfferCount() { if (manager.apiKey === null) return; return Utils.getJSON({ url: "https://api.steampowered.com/IEconService/GetTradeOffersSummary/v1/?key=" + manager.apiKey }).then(([_, response]) => { if (!response) { log.warn("Cannot get trade offer count: malformed response"); log.debug(`apiKey used: ${manager.apiKey}`); return; } let pending_sent = response.pending_sent_count, pending_received = response.pending_received_count; log.verbose(`${pending_received} incoming offer${pending_received === 1 ? '' : 's'} (${response.escrow_received_count} on hold), ${pending_sent} sent offer${pending_sent === 1 ? '' : 's'} (${response.escrow_sent_count} on hold)`); }).catch((msg) => { log.warn("Cannot get trade offer count: " + msg); log.debug(`apiKey used: ${manager.apiKey}`); }); }
export * from "./user.service"; export * from "./library.service"; export * from "./github.service";
'use strict'; var assign = require('object-assign'); var flatten = require('flat'); exports.Query = Query; function Query(sobject, criteria, tableMeta) { criteria.where = normalizeWhere(criteria.where); criteria.joins = criteria.joins || []; this._select = criteria.select; var children = []; var query = sobject .select(criteria.select) .where(criteria.where) .sort(criteria.sort) .limit(criteria.limit) .skip(criteria.skip); this._query = criteria.joins.reduce(function (subQuery, join) { var parentMeta = tableMeta[join.parent]; // If we don't have metadata on this table/relationship, it's not a valid // join and salesforce will scream. We won't have metadata on the table if // the table wasn't included as a collection if (!parentMeta || !parentMeta.children[join.child]) { return subQuery; } var childCriteria = join.criteria || {}; childCriteria.select = join.select; subQuery = subQuery.include(parentMeta.children[join.child]); var newQuery = new Query(subQuery, childCriteria, tableMeta); children.push({ key: parentMeta.children[join.child], alias: join.alias, select: join.select, children: newQuery._children }); subQuery = newQuery._query; return subQuery.end(); }, query); this._children = children; } Query.prototype.run = function () { var children = this._children; var select = this._select; return this._query.exec({ autoFetch: true }).then(function (rows) { return rows.map(function (row) { return flattenRow(row, children, select); }); }); }; function flattenRow(row, children, select) { var childKeys = {}; children.forEach(function (child) { if (row[child.key]) { childKeys[child.alias] = (row[child.key].records || []).map(function (subRow) { return flattenRow(subRow, child.children, child.select); }); delete row[child.key]; } }); return assign(flatten(mapEnsure(row, select)), childKeys); } function normalizeWhere(fields) { return Object.keys(fields || {}).reduce(function (obj, key) { var val = fields[key]; // If a value is null or it's not an object, we just leave it as is if (!val || typeof val !== 'object') { obj[key] = val; return obj; } // Otherwise, we go through an normalize the different things they can do // to modify the criteria (with like, greaterthan, and such) obj[key] = Object.keys(val).reduce(function (criteria, criteriaKey) { var criteriaValue = val[criteriaKey]; switch (criteriaKey.toLowerCase()) { case 'contains': criteriaKey = '$like'; criteriaValue = '%' + criteriaValue + '%'; break; case 'startsWith': criteriaKey = '$like'; criteriaValue = criteriaValue + '%'; break; case 'endsWith': criteriaKey = '$like'; criteriaValue = '%' + criteriaValue; break; case '!': criteriaKey = '$ne'; break; case 'like': criteriaKey = '$like'; break; case '>': criteriaKey = '$gt'; break; case '<': criteriaKey = '$lt'; break; case '>=': criteriaKey = '$gte'; break; case '<=': criteriaKey = '$lte'; break; } criteria[criteriaKey] = criteriaValue; return criteria; }, {}); return obj; }, {}); } function getValue(obj, key) { var keys = key.split('.'); return keys.reduce(function (obj, key) { if (obj == null) { return null; } return obj[key]; }, obj); } function mapEnsure(obj, select) { return select.reduce(function (newObj, key) { newObj[key] = getValue(obj, key); return newObj; }, {}); }
var express = require('express'); var bodyParser = require('body-parser'); var app = express(); app.use(bodyParser.urlencoded({ extended: false })); app.disable('etag'); app.all('/test', function(req, res) { if (req.headers && req.headers['x-proxied-header']) { res.send('a server response with proxied header value of "'+ req.headers['x-proxied-header'] +'"'); } else { res.send('a server response'); } }); app.post('/test_post', function(req, res) { res.send(req.body.foo); }); app.get('/json', function(req, res) { res.json({"text": "a server response"}); }); app.get('/rewrite', function(req, res) { res.send('a rewritten server response'); }); module.exports = app;
/** * @author weism * copyright 2015 Qcplay All Rights Reserved. */ var s = qc.Serializer; /** * 战斗者的逻辑控制 */ var Fighter = qc.defineBehaviour('qc.demo.Fighter', qc.Behaviour, function() { var self = this; // 是不是宠物 self.isPet = true; // 血量、伤害值、攻击频率、大招冷却时间 self.maxHp = 1000; self.hp = self.maxHp; self.minDamage = 0; self.maxDamage = 0; self.frequency = 3; self.freeze = 0; // 普通攻击的技能 self.skills = []; // 使用的大招 self.bigSkill = null; // 攻击顺序 self.defensers = []; // 是否处于晕眩中 self.stun = false; // 晕眩的特效 self.stunEffect = null; // 下次出招的时间 self.nextRound = Fighter.MAX_VALUE; // 下次出大招的时间点倒计时 self.bigTime = Fighter.MAX_VALUE; // 飘血的预制 self.flyDamage = null; // 移动的目标位置 self.twoPos = [null, null]; // 关联的头像节点 self.icon = null; // 死亡的声音 self.dieAudio = null; }, { // 需要序列化的字段 isPet: s.BOOLEAN, icon: s.NODE, maxHp: s.NUMBER, minDamage: s.NUMBER, maxDamage: s.NUMBER, frequency: s.NUMBER, freeze: s.NUMBER, bigSkill: s.NODE, defensers: s.NODES, stunEffect: s.PREFAB, skills: s.NODES, flyDamage: s.PREFAB, twoPos: s.NODES, dieAudio: s.AUDIO }); Fighter.MAX_VALUE = 999999999999; Object.defineProperties(Fighter.prototype, { /** * @property {number} damage - 普通伤害值 * @readonly */ damage: { get: function() { return this.game.math.random(this.minDamage, this.maxDamage); } }, /** * @property {boolean} die - 是不是死亡了 * @readonly */ die: { get: function() { return this.hp <= 0; } } }); // 初始化处理 Fighter.prototype.awake = function() { var self = this; var parent = self.gameObject.parent; // 记录我当前的位置 self.oldX = parent.x; self.oldY = parent.y; // 记录目标的两个位置 self._twoPos = [new qc.Point(self.twoPos[0].x, self.twoPos[0].y), new qc.Point(self.twoPos[1].x, self.twoPos[1].y)] // 初始隐藏掉 parent.visible = false; } // 帧调度,自动出招 Fighter.prototype.update = function() { var self = this, o = self.gameObject; // 大招播放时不允许出招 if (window.combatUI.ult || !window.combatUI._combating) return; // 对象不处于idle状态,不能出招 if (self.die || o.paused || !o.isPlaying) return; // 处于晕眩状态 if (self.stun) return; if (self.nextRound === Fighter.MAX_VALUE && self.isIdle()) { // 当前对象处于idle状态,需要重置下回合 self.resetRound(); return; } if (self.bigSkill) { self.bigTime -= self.game.time.deltaTime; if (!self.isPet && self.bigTime <= 0) { // 怪物出大招 self.bigAttack(); return; } } // 扣除倒计时,当对象处于idle状态时出招 self.nextRound -= self.game.time.deltaTime; if (self.isIdle() && self.nextRound <= 0) { // 可以出招了 self.nextRound = Fighter.MAX_VALUE; self.commonAttack(); } } // 自动进行普通物理攻击 Fighter.prototype.commonAttack = function() { var self = this; // 使用的技能 var index = self.game.math.random(0, self.skills.length - 1); var skill = self.skills[index]; // 抽取攻击目标 var target = null; for (var i in self.defensers) { var fighter = self.defensers[i].getScript('qc.demo.Fighter'); if (fighter.die) continue; target = self.defensers[i]; break; } if (!target) return; var damage = self.game.math.random(self.minDamage, self.maxDamage); skill.scripts[0].play([target], damage); } // 播放大招 Fighter.prototype.bigAttack = function() { var self = this; if (self.bigTime > 0) return; self.bigTime = (self.freeze + 2) * 1000; self.nextRound = Fighter.MAX_VALUE; // 如果对手都死亡了,别出招了 var win = true; for (var i in self.defensers) { if (self.defensers[i].die) continue; win = false; break; } if (!win) self.bigSkill.scripts[0].play(self.defensers, 0); } // 出招结束,进入下一回合 Fighter.prototype.resetRound = function() { var self = this; // 记录下一次出招的时间 self.nextRound = self.frequency * 1000; } // 重置处理 Fighter.prototype.reset = function() { var self = this; var parent = self.gameObject.parent; // 重置下血量 self.hp = self.maxHp; // 消除状态 self.stun = false; // 下次出招的时间点倒计时 self.bigTime = Fighter.MAX_VALUE; self.nextRound = Fighter.MAX_VALUE; // 设置其位置 parent.x = self.oldX; parent.y = self.oldY; parent.alpha = 1; // 令其出现 var appear = self.gameObject.getScript('qc.demo.FighterAppear'); if (appear) { appear.play(); } } // 受创 Fighter.prototype.receiveDamage = function(damage, effect) { var self = this; var o = self.gameObject; if (self.die) return; self.hp -= damage; // 播放受创动作 if (self.hp > 0) { if (self.isIdle()) { // 攻击过程中不播放受创动作 o.playAnimation('damage'); o.onFinished.addOnce(function() { self.resumeIdle(); }); } } else { // 死亡了 o.playAnimation('death'); o.onFinished.addOnce(function() { // 淡出消失 var ta = o.parent.getScript('qc.TweenAlpha'); ta.resetToBeginning(); ta.playForward(); ta.onFinished.addOnce(function() { o.parent.visible = false; // 通知有人死亡了 window.combatUI.onDie(o); }); }); // 死亡声音 if (self.dieAudio) { var sound = self.game.add.sound(); sound.audio = self.dieAudio; sound.play(); } } // 播放命中特效 var e = null; if (effect) { e = self.game.add.clone(effect, o.parent); e.onFinished.addOnce(function() { e.destroy(); }); } // 播放飘血动画 var fly = self.game.add.clone(self.flyDamage, o.parent); var damageFly = fly.getScript('qc.demo.DamageFly'); damageFly.play(damage); // 返回特效,可能不同的技能需要进行移动等 return e; } // 移动到目标位置 Fighter.prototype.moveTo = function(pos) { // 最多就前进2个位置 var self = this; if (pos !== 1 && pos !== 2) return; // 移动过去 var parent = self.gameObject.parent; var targetPos = self._twoPos[pos - 1]; self.gameObject.playAnimation('move', 1, true); var tp = parent.getScript('qc.TweenPosition'); tp.from = new qc.Point(parent.x, parent.y); tp.to = targetPos; tp.duration = 1.5; tp.onFinished.addOnce(function() { // 回到idle状态 self.resumeIdle(); }); tp.resetToBeginning(); tp.playForward(); } // 回到idle状态 Fighter.prototype.resumeIdle = function() { this.gameObject.colorTint = new qc.Color(0xffffff); if (this.die) return; this.gameObject.playAnimation(this.gameObject.defaultAnimation, 1, true); } // 当前是否表示处于idle状态 Fighter.prototype.isIdle = function() { if (this.die) return false; return this.gameObject.lastAnimationName === this.gameObject.defaultAnimation; } // 赋予晕眩状态 Fighter.prototype.applyStun = function(duration) { var self = this; self.stun = true; // 播放特效 var e = self.game.add.clone(self.stunEffect, self.gameObject.parent); self.game.timer.add((duration + 1) * 1000, function() { self.stun = false; e.destroy(); }); }
require( 'components' ).create( 'navigation-mobile', { initialize: function ( ) { this.$el.on( 'click', this.menuToggle.bind( this ) ) }, menuToggle: function ( event ) { event.preventDefault(); event.stopPropagation(); Rye( '.nav' ).toggleClass( '-opened' ); this.$el.toggleClass( '-opened' ); } } );
 function terrainGeometry() { var _this = this; function clamp(v, min, max) { return v < min ? min : (v > max ? max : v); } function lerp(x, y, t) { return x * (1 - t) + y * t; } function bilinearFilter(x, y, v00, v10, v01, v11) { var v00_10 = lerp(v00, v10, x); var v01_11 = lerp(v01, v11, x); return lerp(v00_10, v01_11, y); } function groundHeight(ix, iy) { return _this.data.geometry.vertices[ix + iy * _this.data.widthSamples].z; } this.data = null; this.getY = function (x, z) { if (!_this.data) { return 0.0; } var data = _this.data; //geometry, width, height, widthSamples, heightSamples var ox = (x + data.width / 2) * (data.widthSamples / data.width); var oy = (z + data.height / 2) * (data.heightSamples / data.height); var fx = Math.floor(ox); var fy = Math.floor(oy); var ix = clamp(fx, 0, data.widthSamples); var iy = clamp(fy, 0, data.heightSamples); // Cheesy bilinear smoothing - we're rendering non-depth tested sprites so Y doesn't need to be super accurate... var y = bilinearFilter(ox - fx, oy - fy, groundHeight(ix, iy), groundHeight(ix + 1, iy), groundHeight(ix, iy + 1), groundHeight(ix + 1, iy + 1)); return y; } } function loadImages(urls, callback, imgArray) { var remaining = urls.length; var images = !imgArray ? [] : imgArray; function handleLoad(url) { console.log("Loaded image from URL " + url); if (--remaining == 0) { callback(images); } } function getImage(i) { if (imgArray) { return imgArray[i]; } var image = new Image(); images[i] = image; return image; }; function loadImage(url) { var image = getImage(i); image.addEventListener("load", function () { handleLoad(url); }); image.src = url; if (image.complete) { --remaining; } } for (var i = 0; i < urls.length; ++i) { loadImage(urls[i]); } if (remaining == 0) { callback(); } } function drawImage(context, img, x, y, flipX, flipY, rotation) { context.strokeStyle = "red"; context.rect(x, y, img.naturalWidth, img.naturalHeight) context.stroke(); context.save(); context.translate(x+img.naturalWidth / 2, y+img.naturalHeight / 2); context.rotate(rotation); context.translate(-img.naturalWidth / 2, -img.naturalHeight / 2); context.drawImage(img, 0, 0); context.restore(); } function nextPowerOf2(v) { v--; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; return v + 1; } function terrainLoader(scene, groundMapUrl, groundHeightUrl, opacityMaskUrl, terrainTypeUrls, testCanvas) { var terrainTypeTextures = []; for (var i = 0; i < terrainTypeUrls.length; ++i) { var texture = THREE.ImageUtils.loadTexture(terrainTypeUrls[i]); texture.wrapS = THREE.RepeatWrapping; texture.wrapT = THREE.RepeatWrapping; texture.minFilter = THREE.NearestFilter; texture.magFilter = THREE.NearestFilter; terrainTypeTextures.push(texture); } var cornerAndEdgeOpacityTexture = THREE.ImageUtils.loadTexture(opacityMaskUrl); cornerAndEdgeOpacityTexture.magFilter = THREE.NearestFilter; cornerAndEdgeOpacityTexture.minFilter = THREE.NearestFilter; cornerAndEdgeOpacityTexture.wrapS = THREE.RepeatWrapping; cornerAndEdgeOpacityTexture.wrapT = THREE.RepeatWrapping; cornerAndEdgeOpacityTexture.generateMipmaps = false; cornerAndEdgeOpacityTexture.needsUpdate = true; cornerAndEdgeOpacityTexture.flipY = false; // ????? https://github.com/threeDart/three.dart/issues/124 see below also var terrain = new terrainGeometry(); // Ground map // This stores (tile type, tile visibility) per layer // R = layer 0 tile type, vis // G = Layer 1 tile type, vis // B = Layer 2 tile type, vis // A = Layer 3 tile type, vis // Temporarily, this is generated as a single RGBA bitmap with colours representing layers. // That's because we only have a var groundMapData = new Image(); var groundHeightData = new Image(); var colourToType = []; colourToType.push({ colour: 0xffffff, type: 0 }); colourToType.push({ colour: 0x000000, type: 1 }); function getTypeFromColour(data, idx) { var colour = (data[idx] << 16) | (data[idx + 1] << 8) | data[idx + 2]; for (var i = 0; i < colourToType.length; ++i) { if (colourToType[i].colour == colour) { return colourToType[i]; } } throw "no type matching colour R: " + data[idx + 0] + " G: " + data[idx + 1] + " B: " + data[idx + 2] + " found at index " + idx; } function canvasImage(canvas, img, w, h) { canvas.width = w !== undefined ? w : img.naturalWidth; canvas.height = h !== undefined ? h : img.naturalHeight; var ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0, canvas.width, canvas.height); return ctx; } function getCanvas(dstCanvas, width, height) { if (dstCanvas) { return dstCanvas; } var canvas = document.createElement("canvas"); canvas.width = width; canvas.height = height; return canvas; } function applyHeightMap(data) { var canvas = document.createElement("canvas"); var ctx = canvasImage(canvas, groundHeightData, data.widthSamples, data.heightSamples); var gd = ctx.getImageData(0, 0, canvas.width, canvas.height); for (var i = 0; i < data.geometry.vertices.length; i++) { data.geometry.vertices[i].z = gd.data[i * 4] / 5; } data.geometry.computeFaceNormals(); data.geometry.computeVertexNormals(); } // The ground map texture stores the tile type for each of the four terrain layers // For the time being, this is simply 0 - as more terrain types are added this function will need to be modified function createGroundMapTextureFromSimpleFormat() { // Can't create a texture direct from processing a canvas with the ground map drawn to it as CANVAS PREMULTIPLIES THE FUCKING ALPHA var data = new Uint8Array(groundMapData.naturalWidth * groundMapData.naturalHeight * 4); var maxIdx = groundMapData.naturalWidth * groundMapData.naturalHeight * 4; var canvas = document.createElement("canvas"); var ctx = canvasImage(canvas, groundMapData); var gd = ctx.getImageData(0, 0, canvas.width, canvas.height); for (var idx = 0; idx < maxIdx; idx += 4) { var terrainType = getTypeFromColour(gd.data, idx); data[idx + 0] = terrainType.type == 0 ? 255 : 0; data[idx + 1] = terrainType.type == 1 ? 255 : 0; data[idx + 2] = terrainType.type == 2 ? 255 : 0; data[idx + 3] = terrainType.type == 3 ? 255 : 0; } var texture = new THREE.DataTexture(data, groundMapData.naturalWidth, groundMapData.naturalHeight, THREE.RGBAFormat); texture.wrapS = THREE.RepeatWrapping; texture.wrapT = THREE.RepeatWrapping; texture.minFilter = THREE.NearestFilter; texture.magFilter = THREE.NearestFilter; texture.needsUpdate = true; return texture; } function getTerrainTypeFromSimpleFormat(data, x, y, w, h) { var rx = x < 0 ? 0 : (x >= w ? w - 1 : x); var ry = y < 0 ? 0 : (y >= h ? h - 1 : y); return getTypeFromColour(data, (rx + ry * w) * 4).type; } function isTerrainTypeVisibleInSimpleFormat(data, x, y, w, h, type) { return getTerrainTypeFromSimpleFormat(data, x, y, w, h) == type; } function determineTerrainTypeCornerOpacityMaskIndexInSimpleFormat(data, x, y, w, h, type) { var c = getTerrainTypeFromSimpleFormat(data, x, y, w, h, type); if (c >= type) { return 0; } var t = isTerrainTypeVisibleInSimpleFormat(data, x + 0, y + 1, w, h, type); var l = isTerrainTypeVisibleInSimpleFormat(data, x + 1, y + 0, w, h, type); var r = isTerrainTypeVisibleInSimpleFormat(data, x - 1, y + 0, w, h, type); var b = isTerrainTypeVisibleInSimpleFormat(data, x + 0, y - 1, w, h, type); var tl = isTerrainTypeVisibleInSimpleFormat(data, x + 1, y + 1, w, h, type) && !(t || l); var tr = isTerrainTypeVisibleInSimpleFormat(data, x - 1, y + 1, w, h, type) && !(t || r); var bl = isTerrainTypeVisibleInSimpleFormat(data, x + 1, y - 1, w, h, type) && !(b || l); var br = isTerrainTypeVisibleInSimpleFormat(data, x - 1, y - 1, w, h, type) && !(b || r); return ((tr ? 1 : 0) | (tl ? 2 : 0) | (bl ? 4 : 0) | (br ? 8 : 0)); } function determineTerrainTypeEdgeOpacityMaskIndexInSimpleFormat(data, x, y, w, h, type) { if (isTerrainTypeVisibleInSimpleFormat(data, x, y, w, h, type)) { return 0; } var t = isTerrainTypeVisibleInSimpleFormat(data, x + 0, y + 1, w, h, type); var l = isTerrainTypeVisibleInSimpleFormat(data, x - 1, y + 0, w, h, type); var r = isTerrainTypeVisibleInSimpleFormat(data, x + 1, y + 0, w, h, type); var b = isTerrainTypeVisibleInSimpleFormat(data, x + 0, y - 1, w, h, type); return ((l ? 1 : 0) | (t ? 2 : 0) | (r ? 4 : 0) | (b ? 8 : 0)); } // The group map corner texture stores the layer types at each of the 4 corners of a texel on the ground map function createGroundMapAdjacencyTextureFromSimpleFormat(determineOpacityMaskFunc) { var canvas = document.createElement("canvas"); var ctx = canvasImage(canvas, groundMapData); var gd = ctx.getImageData(0, 0, canvas.width, canvas.height); var gdc = ctx.getImageData(0, 0, canvas.width, canvas.height); var idx = 0; var w = canvas.width, h = canvas.height; for (var y = 0; y < h; ++y) { for (var x = 0; x < w; ++x, idx += 4) { gdc.data[idx + 0] = determineOpacityMaskFunc(gd.data, x, y, w, h, 0); gdc.data[idx + 1] = determineOpacityMaskFunc(gd.data, x, y, w, h, 1); gdc.data[idx + 2] = determineOpacityMaskFunc(gd.data, x, y, w, h, 2); gdc.data[idx + 3] = 255; //determineOpacityMaskFunc(gd.data, x, y, w, h, 3); // HACK BECAUSE OF STUPID CANVAS ALPHA PREMULTIPLICATION REMOVEME AND PROCESS AS BYTE ARRAY } } ctx.putImageData(gdc, 0, 0); var texture = new THREE.Texture(canvas); texture.wrapS = THREE.RepeatWrapping; texture.wrapT = THREE.RepeatWrapping; texture.minFilter = THREE.NearestFilter; texture.magFilter = THREE.NearestFilter; texture.needsUpdate = true; return texture; } function initializeFromData() { var data = { width: groundMapData.naturalWidth * 4, height: groundMapData.naturalHeight * 4 }; data.widthSamples = data.width / 2; data.heightSamples = data.height / 2; data.geometry = new THREE.PlaneGeometry(data.width, data.height, data.widthSamples - 1, data.heightSamples - 1); applyHeightMap(data); terrain.data = data; var groundMapTexture = createGroundMapTextureFromSimpleFormat(); var groundMapCornerTexture = createGroundMapAdjacencyTextureFromSimpleFormat(determineTerrainTypeCornerOpacityMaskIndexInSimpleFormat); var groundMapEdgeTexture = createGroundMapAdjacencyTextureFromSimpleFormat(determineTerrainTypeEdgeOpacityMaskIndexInSimpleFormat); var groundMapWidth = groundMapData.width; var groundMapHeight = groundMapData.height; var uniforms = { terrainTypeTextures: { type: "tv", value: terrainTypeTextures }, groundMapTexture: { type: "t", value: groundMapTexture}, groundMapCornerTexture: { type: "t", value: groundMapCornerTexture }, groundMapEdgeTexture: { type: "t", value: groundMapEdgeTexture }, cornerAndEdgeOpacityTexture: { type: "t", value: cornerAndEdgeOpacityTexture } }; var vshader = [ "varying vec3 vecNormal;", "varying vec2 vUv;", THREE.ShaderChunk["shadowmap_pars_vertex"], "void main() {", "vec4 worldPosition = modelMatrix * vec4( position, 1.0 );", "vec4 mvPosition = modelViewMatrix * vec4( position, 1.0 );", "vecNormal = normalize(normalMatrix * normal);", THREE.ShaderChunk["shadowmap_vertex"], "vUv = uv;", "gl_Position = projectionMatrix * mvPosition;", "}" ].join("\n"); // The plane seen from above // 1| // | // V| // |______ // 0 U 1 // Flipping issue: https://github.com/mrdoob/three.js/issues/277 // Hmmm... var fshader = [ "varying vec3 vecNormal;", "uniform sampler2D terrainTypeTextures[" + terrainTypeTextures.length + "];", "uniform sampler2D groundMapTexture;", "uniform sampler2D groundMapCornerTexture;", "uniform sampler2D groundMapEdgeTexture;", "uniform sampler2D cornerAndEdgeOpacityTexture;", "uniform vec3 directionalLightDirection;", "varying vec2 vUv;", "const float opU = " + 1.0 / 2048.0 + ";", "const float cornerOpacityV = " + 1.0 / 256.0 + ";", "const float edgeOpacityV = " + 72.0 / 256.0 + ";", "const float opacityMul = " + 255.0 * 72.0 / 2048.0 + ";", THREE.ShaderChunk[ 'common'], THREE.ShaderChunk["shadowmap_pars_fragment"], "void main() {", "vec3 outgoingLight = vec3(1.0);", "vec2 mapUv = vUv;", "vec4 corner = texture2D(groundMapCornerTexture, mapUv);", "vec4 edge = texture2D(groundMapEdgeTexture, mapUv);", "vec4 mid = texture2D(groundMapTexture, mapUv);", // "vec2 uv = (vUv * 64.0) + vec2(0.5/64.0, 0.5/64.0);", // Required to offset the texel lookups correctly "vec2 uvoff = ((uv - floor(uv))) / vec2(32.0, 4.0);", "float t1corner = texture2D(cornerAndEdgeOpacityTexture, vec2(corner.g * opacityMul, cornerOpacityV) + uvoff).r;", "float t1edge = texture2D(cornerAndEdgeOpacityTexture, vec2(edge.g * opacityMul, edgeOpacityV) + uvoff).r;", "float t1Alpha = (mid.g + max(t1corner, t1edge));", // This would be multiplied by (1.0 - t2Alpha) "float t0Alpha = (1.0 - t1Alpha);", //"vec2 uvoff2 = (uv - floor(uv));", "vec4 t0 = texture2D(terrainTypeTextures[0], uv) * t0Alpha;", "vec4 t1 = texture2D(terrainTypeTextures[1], uv) * t1Alpha;", THREE.ShaderChunk["shadowmap_fragment"], //"gl_FragColor = (t0 + t1) * (0.25 + max(0.0, dot(vecNormal, directionalLightDirection) * 0.75));", //"gl_FragColor = (t0 + t1) * vec4(outgoingLight, 1.0); //(0.25 + max(0.0, dot(vecNormal, directionalLightDirection) * 0.75));", "gl_FragColor = (t0 + t1) * (0.25 + max(0.0, dot(vecNormal, directionalLightDirection) * 0.75));", "}" ].join("\n"); var lightUniforms = THREE.UniformsLib['lights']; for (var property in lightUniforms) { uniforms[property] = lightUniforms[property]; } var shadowUniforms = THREE.UniformsLib["shadowmap"]; for (var property in shadowUniforms) { uniforms[property] = shadowUniforms[property]; } var groundMaterial = new THREE.ShaderMaterial({ uniforms: uniforms, //THREE.UniformsUtils.merge(uniforms, THREE.UniformsLib['lights']), vertexShader: vshader, fragmentShader: fshader, lights: true }); var u = THREE.UniformsLib['lights']; groundMaterial.needsUpdate = true; var ground = new THREE.Mesh(data.geometry, groundMaterial); ground.rotation.x = -0.5 * Math.PI; ground.position.set(0, 0, 0); ground.uvsNeedUpdate = true; //ground.castShadow = true; ground.receiveShadow = true; scene.add(ground); } loadImages([groundMapUrl, groundHeightUrl], initializeFromData, [groundMapData, groundHeightData]); return terrain; }
if (typeof module === "object" && module && typeof module.exports === "object") { // Expose jLight as module.exports in loaders that implement the Node // module pattern (including browserify). Do not create the global, since // the user will be storing it themselves locally, and globals are frowned // upon in the Node module world. module.exports = jLight; } // Register as a AMD module else if (typeof define === "function" && define.amd) { define(function() { return jLight; }); } if (typeof win === "object" && typeof win.document === "object") { win.jLight = win.$ = jLight; } }(window));
/*global xDaysAgo, removeByIndex */ /* Thought Constructor * * Method constructs a thought which contains the thought and the timestamp when * it was created. * * @param string thought text of the thought * @param number timeCreated timestamp at time method is used * * return void */ function Thought( thought ) { this.thought = thought; this.timeCreated = new Date(); } /* Negative Thought Constructor * * Method constructs a negative thought which contains the following: * * - thought Thought instance of Thought * - count number represents num of times thought was had * - instances array array of timestamps when the thought was * recorded as had * - rebuttals array array of Thought instances representing equally * opposite positive thoughts * * @param string thought description of the thought * @param number timeCreated timestamp at time method is used * * return void */ function NegativeThought( negThought ) { Thought.call( this, negThought ); this.count = 1; this.instances = [new Date()]; this.rebuttals = []; this.tags = []; } /* Rebuttal Constructor * * Method constructs a positive Thought (see Thought). Right now it has no other * special properties so it's just the same as a Thought. * * return void */ var Rebuttal = Thought; /* Increase Count * * Method increases the count of a negative thought by one and pushes a timestamp * to the instances array at the time the count was increased. * * return void */ NegativeThought.prototype.increaseCount = function() { this.count += 1; this.instances.push( new Date() ); }; /* Decrease Count * * Method decreases the count of a negative thought by one and removes the last a * timestamp from the instances array at the time the count was increased. * * return void */ NegativeThought.prototype.decreaseCount = function() { if ( this.count > 0 ) { this.count -= 1; this.instances.pop(); } }; /* Add Rebuttal * * Method adds a Rebuttal to the rebuttals array of a negative thought. * * @param string rebuttal text of the positive thought * * return void */ NegativeThought.prototype.addRebuttal = function( rebuttal ) { this.rebuttals.push( new Rebuttal( rebuttal ) ); }; /* Remove Rebuttal * * Method removes a Rebuttal from the rebuttals array of a negative thought. * * @param number rebuttalIndex index of the rebuttal that should be * removed. * * return void */ NegativeThought.prototype.removeRebuttal = function( rebuttalIndex ) { removeByIndex( this.rebuttals, rebuttalIndex ); }; /* Instances This Week * * Method returns the number of instances for a thought from the previous 7 days. * * return number */ NegativeThought.prototype.instancesThisWeek = function() { var instance; var lastWeek = xDaysAgo( 7 ); var thisWeekCount = 0; for ( var i = this.instances.length; i < 0; i-- ) { instance = this.instances[i]; if ( instance > lastWeek ) { thisWeekCount += 1; } else { break; } } return thisWeekCount; }; /* Instances This Week * * Method returns the difference between instances in most recent 7 days and * previous 7 days (14 days ago) * * return number */ NegativeThought.prototype.differenceLast2Weeks = function() { //count this week var thisWeekCount = this.instancesThisWeek(); var lastWeek = xDaysAgo( 7 ); var twoWeeksAgo = xDaysAgo( 14 ); var lastWeekCount = 0; var instance; //count last week for ( var i = this.instances.length; i < 0; i-- ) { instance = this.instances[i]; if ( instance < lastWeek && instance > twoWeeksAgo ) { lastWeekCount += 1; } else if ( instance < twoWeeksAgo ) { break; } } return thisWeekCount - lastWeekCount; }; /* Add Tag * * Method adds a tag to a negative thought. * * @param string tags tags to describe thought, comma separated * * return void */ NegativeThought.prototype.addTags = function( tags ) { var tagArray = tags.split( ',' ); for ( var i = 0; i < tagArray.length; i++ ) { var tag = tagArray[i].trim(); this.tags.push( tag ); } }; /* Remove Tag * * Method removes a tag from a negative thought. * * @param number tagIndex index of the tag that should be removed. * * return void */ NegativeThought.prototype.removeTag = function( tagIndex ) { removeByIndex( this.tags, tagIndex ); };
// Declare app level module which depends on views, and components angular.module('myApp', [ 'ngRoute', 'ngMaterial', 'myApp.vendingmachine', 'services' ]). config(['$routeProvider', function($routeProvider) { $routeProvider.otherwise({redirectTo: '/vendingmachine'}); }]);
var express = require('express'); var router = express.Router(); var couch = require('../couch.js'); var _ = require('underscore'); /* GET home page. */ router.get('/', function(req, res, next) { couch.all('auction', {}, function(err, data) { var rows = []; data.rows.sort(function(a, b) { return new Date(b.doc.date_created).getTime() - new Date(a.doc.date_created).getTime(); }); _.each(data.rows, function(auction) { // TODO: if err // only add if the end date has not passed if (new Date().getTime() < new Date(auction.doc.end_date).getTime()) { rows.push(auction); } }); res.render('index', {auctions: rows}); }) }); module.exports = router;
import Joi from 'joi'; // require and configure dotenv, will load vars in .env in PROCESS.ENV require('dotenv').config(); // define validation for all the env vars const envVarsSchema = Joi.object({ NODE_ENV: Joi.string() .allow(['development', 'production', 'test', 'provision']) .default('development'), PORT: Joi.number() .default(4040), MONGOOSE_DEBUG: Joi.boolean() .when('NODE_ENV', { is: Joi.string().equal('development'), then: Joi.boolean().default(true), otherwise: Joi.boolean().default(false) }), JWT_SECRET: Joi.string().required() .description('JWT Secret required to sign'), MONGO_HOST: Joi.string().required() .description('Mongo DB host url'), MONGO_URI: Joi.string().required() .description('Mongo DB URI'), MONGO_PORT: Joi.number() .default(27017) }).unknown() .required(); const { error, value: envVars } = Joi.validate(process.env, envVarsSchema); if (error) { throw new Error(`Config validation error: ${error.message}`); } const config = { env: envVars.NODE_ENV, port: envVars.PORT, mongooseDebug: envVars.MONGOOSE_DEBUG, jwtSecret: envVars.JWT_SECRET, mongo: { host: envVars.MONGO_HOST, port: envVars.MONGO_PORT, uri: envVars.MONGO_URI } }; export default config;
import _extends from 'babel-runtime/helpers/extends'; import React from 'react'; /** * Default row renderer for FlexTable. */ export default function defaultRowRenderer(_ref) { var className = _ref.className; var columns = _ref.columns; var index = _ref.index; var isScrolling = _ref.isScrolling; var onRowClick = _ref.onRowClick; var onRowDoubleClick = _ref.onRowDoubleClick; var onRowMouseOver = _ref.onRowMouseOver; var onRowMouseOut = _ref.onRowMouseOut; var rowData = _ref.rowData; var style = _ref.style; var a11yProps = {}; if (onRowClick || onRowDoubleClick || onRowMouseOver || onRowMouseOut) { a11yProps['aria-label'] = 'row'; a11yProps.role = 'row'; a11yProps.tabIndex = 0; if (onRowClick) { a11yProps.onClick = function () { return onRowClick({ index: index }); }; } if (onRowDoubleClick) { a11yProps.onDoubleClick = function () { return onRowDoubleClick({ index: index }); }; } if (onRowMouseOut) { a11yProps.onMouseOut = function () { return onRowMouseOut({ index: index }); }; } if (onRowMouseOver) { a11yProps.onMouseOver = function () { return onRowMouseOver({ index: index }); }; } } return React.createElement( 'div', _extends({}, a11yProps, { className: className, style: style }), columns ); }
import React from 'react'; import PropTypes from 'prop-types'; const PaginationLink = props => { return ( <button className="btn btn-default" onClick={props.onClick} disabled={props.disabled}>{props.children}</button> ); }; PaginationLink.propTypes = { children: PropTypes.node, disabled: PropTypes.bool.isRequired, onClick: PropTypes.func }; PaginationLink.defaultProps = { disabled: false }; export default PaginationLink;
import invariant from 'invariant'; import { register, attachListeners } from '../ReactTitaniumBridge'; register("tabgroup", "Ti.UI.TabGroup", { factory: props => Ti.UI.createTabGroup(props), create(props, handlers, getChildren) { const children = getChildren(); invariant( children.every(child => child.apiName === 'Ti.UI.Tab'), "Only <tab>s can be children of a <tabgroup>" ); const view = this.factory({ ...props, tabs: children }); attachListeners(view, handlers); return view; } });
/* Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'find', 'gu', { find: 'શોધવું', findOptions: 'વીકલ્પ શોધો', findWhat: 'આ શોધો', matchCase: 'કેસ સરખા રાખો', matchCyclic: 'સરખાવવા બધા', matchWord: 'બઘા શબ્દ સરખા રાખો', notFoundMsg: 'તમે શોધેલી ટેક્સ્ટ નથી મળી', replace: 'રિપ્લેસ/બદલવું', replaceAll: 'બઘા બદલી ', replaceSuccessMsg: '%1 ફેરફારો બાદલાયા છે.', replaceWith: 'આનાથી બદલો', title: 'શોધવું અને બદલવું' } );
 document.addEventListener('DOMContentLoaded', function () {//}, false);
import { resolve } from 'rsvp'; import { then } from 'ember-awesome-macros/promise'; import { computed } from '@ember/object'; import { module, test } from 'qunit'; import { compute } from 'ember-macro-helpers/test-support'; import sinon from 'sinon'; module('Integration | Macro | promise | then', function() { test('still returns a promise when promise is undefined', function(assert) { return compute({ computed: then() }).promise.then(result => { assert.strictEqual(result, undefined); }); }); test('resolves to undefined if property undefined', function(assert) { return compute({ assert, computed: then('promise'), properties: { promise: resolve() }, strictEqual: undefined }).promise; }); test('returns promise.then result', function(assert) { return compute({ assert, computed: then('promise', 'propertyKey'), properties: { promise: resolve({ property: 'test value' }), propertyKey: 'property' }, strictEqual: 'test value' }).promise; }); test('doesn\'t calculate when unnecessary', function(assert) { let callback = sinon.spy(); compute({ computed: then( undefined, computed(callback) ) }); assert.notOk(callback.called); }); });
var shared = require('./shared.karma.conf'); module.exports = function(config) { shared(config); config.set({ frameworks: ['ng-scenario'], files: ['test/e2e/**/*.js'], urlRoot: '/_karma_/', proxies: { '/': 'http://localhost:8000/' } }); };
(function() { 'use strict'; angular .module('smn-ui') .directive('uiTreeViewList', uiTreeViewListDirective); uiTreeViewListDirective.$inject = ['$timeout']; function uiTreeViewListDirective($timeout) { var directive = { require: '^uiTreeView', link: link, restrict: 'E', templateUrl: 'components/tree-view/tree-view-list.directive.html', scope: { list: '=' } }; return directive; function link(scope, element, attrs, ctrl) { } } })();
import { NS } from '../../../instrumented/svgcanvas/namespaces.js' import * as utilities from '../../../instrumented/svgcanvas/utilities.js' import * as coords from '../../../instrumented/svgcanvas/coords.js' describe('coords', function () { let elemId = 1 const root = document.createElement('div') root.id = 'root' root.style.visibility = 'hidden' document.body.append(root) /** * Set up tests with mock data. * @returns {void} */ beforeEach(function () { const svgroot = document.createElementNS(NS.SVG, 'svg') svgroot.id = 'svgroot' root.append(svgroot) this.svg = document.createElementNS(NS.SVG, 'svg') svgroot.append(this.svg) // Mock out editor context. utilities.init( /** * @implements {module:utilities.EditorContext} */ { getSvgRoot: () => { return this.svg }, getDOMDocument () { return null }, getDOMContainer () { return null } } ) coords.init( /** * @implements {module:coords.EditorContext} */ { getGridSnapping () { return false }, getDrawing () { return { getNextId () { return String(elemId++) } } } } ) }) /** * Tear down tests, removing elements. * @returns {void} */ afterEach(function () { while (this.svg.hasChildNodes()) { this.svg.firstChild.remove() } }) it('Test remapElement(translate) for rect', function () { const rect = document.createElementNS(NS.SVG, 'rect') rect.setAttribute('x', '200') rect.setAttribute('y', '150') rect.setAttribute('width', '250') rect.setAttribute('height', '120') this.svg.append(rect) const attrs = { x: '200', y: '150', width: '125', height: '75' } // Create a translate. const m = this.svg.createSVGMatrix() m.a = 1; m.b = 0 m.c = 0; m.d = 1 m.e = 100; m.f = -50 coords.remapElement(rect, attrs, m) assert.equal(rect.getAttribute('x'), '300') assert.equal(rect.getAttribute('y'), '100') assert.equal(rect.getAttribute('width'), '125') assert.equal(rect.getAttribute('height'), '75') }) it('Test remapElement(scale) for rect', function () { const rect = document.createElementNS(NS.SVG, 'rect') rect.setAttribute('width', '250') rect.setAttribute('height', '120') this.svg.append(rect) const attrs = { x: '0', y: '0', width: '250', height: '120' } // Create a translate. const m = this.svg.createSVGMatrix() m.a = 2; m.b = 0 m.c = 0; m.d = 0.5 m.e = 0; m.f = 0 coords.remapElement(rect, attrs, m) assert.equal(rect.getAttribute('x'), '0') assert.equal(rect.getAttribute('y'), '0') assert.equal(rect.getAttribute('width'), '500') assert.equal(rect.getAttribute('height'), '60') }) it('Test remapElement(translate) for circle', function () { const circle = document.createElementNS(NS.SVG, 'circle') circle.setAttribute('cx', '200') circle.setAttribute('cy', '150') circle.setAttribute('r', '125') this.svg.append(circle) const attrs = { cx: '200', cy: '150', r: '125' } // Create a translate. const m = this.svg.createSVGMatrix() m.a = 1; m.b = 0 m.c = 0; m.d = 1 m.e = 100; m.f = -50 coords.remapElement(circle, attrs, m) assert.equal(circle.getAttribute('cx'), '300') assert.equal(circle.getAttribute('cy'), '100') assert.equal(circle.getAttribute('r'), '125') }) it('Test remapElement(scale) for circle', function () { const circle = document.createElementNS(NS.SVG, 'circle') circle.setAttribute('cx', '200') circle.setAttribute('cy', '150') circle.setAttribute('r', '250') this.svg.append(circle) const attrs = { cx: '200', cy: '150', r: '250' } // Create a translate. const m = this.svg.createSVGMatrix() m.a = 2; m.b = 0 m.c = 0; m.d = 0.5 m.e = 0; m.f = 0 coords.remapElement(circle, attrs, m) assert.equal(circle.getAttribute('cx'), '400') assert.equal(circle.getAttribute('cy'), '75') // Radius is the minimum that fits in the new bounding box. assert.equal(circle.getAttribute('r'), '125') }) it('Test remapElement(translate) for ellipse', function () { const ellipse = document.createElementNS(NS.SVG, 'ellipse') ellipse.setAttribute('cx', '200') ellipse.setAttribute('cy', '150') ellipse.setAttribute('rx', '125') ellipse.setAttribute('ry', '75') this.svg.append(ellipse) const attrs = { cx: '200', cy: '150', rx: '125', ry: '75' } // Create a translate. const m = this.svg.createSVGMatrix() m.a = 1; m.b = 0 m.c = 0; m.d = 1 m.e = 100; m.f = -50 coords.remapElement(ellipse, attrs, m) assert.equal(ellipse.getAttribute('cx'), '300') assert.equal(ellipse.getAttribute('cy'), '100') assert.equal(ellipse.getAttribute('rx'), '125') assert.equal(ellipse.getAttribute('ry'), '75') }) it('Test remapElement(scale) for ellipse', function () { const ellipse = document.createElementNS(NS.SVG, 'ellipse') ellipse.setAttribute('cx', '200') ellipse.setAttribute('cy', '150') ellipse.setAttribute('rx', '250') ellipse.setAttribute('ry', '120') this.svg.append(ellipse) const attrs = { cx: '200', cy: '150', rx: '250', ry: '120' } // Create a translate. const m = this.svg.createSVGMatrix() m.a = 2; m.b = 0 m.c = 0; m.d = 0.5 m.e = 0; m.f = 0 coords.remapElement(ellipse, attrs, m) assert.equal(ellipse.getAttribute('cx'), '400') assert.equal(ellipse.getAttribute('cy'), '75') assert.equal(ellipse.getAttribute('rx'), '500') assert.equal(ellipse.getAttribute('ry'), '60') }) it('Test remapElement(translate) for line', function () { const line = document.createElementNS(NS.SVG, 'line') line.setAttribute('x1', '50') line.setAttribute('y1', '100') line.setAttribute('x2', '120') line.setAttribute('y2', '200') this.svg.append(line) const attrs = { x1: '50', y1: '100', x2: '120', y2: '200' } // Create a translate. const m = this.svg.createSVGMatrix() m.a = 1; m.b = 0 m.c = 0; m.d = 1 m.e = 100; m.f = -50 coords.remapElement(line, attrs, m) assert.equal(line.getAttribute('x1'), '150') assert.equal(line.getAttribute('y1'), '50') assert.equal(line.getAttribute('x2'), '220') assert.equal(line.getAttribute('y2'), '150') }) it('Test remapElement(scale) for line', function () { const line = document.createElementNS(NS.SVG, 'line') line.setAttribute('x1', '50') line.setAttribute('y1', '100') line.setAttribute('x2', '120') line.setAttribute('y2', '200') this.svg.append(line) const attrs = { x1: '50', y1: '100', x2: '120', y2: '200' } // Create a translate. const m = this.svg.createSVGMatrix() m.a = 2; m.b = 0 m.c = 0; m.d = 0.5 m.e = 0; m.f = 0 coords.remapElement(line, attrs, m) assert.equal(line.getAttribute('x1'), '100') assert.equal(line.getAttribute('y1'), '50') assert.equal(line.getAttribute('x2'), '240') assert.equal(line.getAttribute('y2'), '100') }) it('Test remapElement(translate) for text', function () { const text = document.createElementNS(NS.SVG, 'text') text.setAttribute('x', '50') text.setAttribute('y', '100') this.svg.append(text) const attrs = { x: '50', y: '100' } // Create a translate. const m = this.svg.createSVGMatrix() m.a = 1; m.b = 0 m.c = 0; m.d = 1 m.e = 100; m.f = -50 coords.remapElement(text, attrs, m) assert.equal(text.getAttribute('x'), '150') assert.equal(text.getAttribute('y'), '50') }) })
var State = require('ampersand-state'); var Aside = State.extend({ props: { target: 'string', src: 'string', alt: 'string', title: 'string', text: 'string', type: 'string', images: 'array', href: 'string', icon: 'string', is_enlargeable: 'boolean' } }); module.exports = Aside;
function selectionSort(array) { var i, j, len, secondLen, min, temp; for (i = 0, len = array.length - 1; i < len; i += 1) { min = i; for (j = i + 1, secondLen = array.length; j < secondLen; j += 1) { if (array[j] < array[min]) { min = j; } } temp = array[i]; array[i] = array[min]; array[min] = temp; } return array; } console.log(selectionSort([3, 2, 1, 8, 5, 6, 4, 7, 9]).join(' ')); console.log(selectionSort([1, 2, 1, 8, 5, 6, -4, 7, 9, 7, 9]).join(' ')); console.log(selectionSort([0]).join(' '));
#!/usr/bin/env node var argv = require('minimist')(process.argv.slice(2)) var bencode = require('bencode') var path = require('path') var fs = require('fs') function onerror () { console.error('usage: rtorrent-session-rectify --old [string] --new [string] --from [path] --to [path]\n') console.error(' --old Exact string to be replaced in old .rtorrent session files') console.error(' (i.e. /home/bt/).\n') console.error(' --new New path to replace in .rtorrent session files') console.error(' (i.e. /home/bt/).\n') console.error(' --from Directory containing .rtorrent session files to update.\n') console.error(' --to Directory to output updated .rtorrent session files.\n') console.error(' --help Show this help message.\n') console.error(' -v Show verbose output.') process.exit(1) } if (argv.help || !argv.old || !argv.new || !argv.from || !argv.to) { onerror() } var oldDir = argv.old var newDir = argv.new var fromDir = path.resolve(argv.from) var toDir = path.resolve(argv.to) var isVerbose = argv.v var hasError = false try { fs.statSync(fromDir).isDirectory() } catch (err) { hasError = true console.error(err.message) } try { fs.statSync(toDir).isDirectory() } catch (err) { hasError = true console.error(err.message) } if (hasError) process.exit(1) fs.readdir(fromDir, function (err, files) { if (err) throw err var filtered = files.filter(function (name) { return /rtorrent$/.test(name) }) console.log('Found ' + filtered.length + ' session files in ' + fromDir) function update (val, len) { if (val === undefined) throw err val = val.toString() if (!len) len = oldDir.length return new Buffer(path.join(newDir, val.slice(len))) } filtered.map(function (name) { var torrent = bencode.decode(fs.readFileSync(path.join(fromDir, name))) torrent.directory = update(torrent.directory) torrent.loaded_file = update(torrent.loaded_file) torrent.tied_to_file = Buffer.concat([new Buffer('/'), update(torrent.tied_to_file, oldDir.length + 1)]) return torrent }) .map(bencode.encode) .forEach(function (bencodedStr, i) { var filename = filtered[i] if (isVerbose) console.log('Updated ' + filename) fs.writeFileSync(path.join(toDir, filename), bencodedStr) }) console.log('Successfully updated ' + filtered.length + ' files.') })
import { createReducer } from 'utils'; // normally this would be imported from /actions, but in trying to keep // this starter kit as small as possible we'll just define it here. import * as types from '../constants/ActionTypes'; const initialState = { costToKeep: 0, costToKeepIsEditable: true, saleWeight: 0, buyWeight: 0, saleUnitValue: 0, buyUnitValue: 0, profit: 0 }; function calculateProfit (state) { const netWeight = state.buyWeight ? (state.saleWeight / state.buyWeight) : 0; const netUnitValue = state.buyUnitValue ? (state.saleUnitValue / state.buyUnitValue) : 0; const grossProfit = netUnitValue ? netWeight / netUnitValue : 0; const netProfit = grossProfit - state.costToKeep; return Object.assign({}, state, { profit: netProfit }); } export default createReducer(initialState, { [types.LOCK_COST_TO_KEEP](state) { return Object.assign({}, state, { costToKeepIsEditable: false }) }, [types.UNLOCK_COST_TO_KEEP](state) { return Object.assign({}, state, { costToKeepIsEditable: false }) }, [types.EDIT_COST_TO_KEEP](state, action) { return Object.assign({}, state, { costToKeep: action.costToKeep }); }, [types.UPDATE_SALE_WEIGHT](state, action) { console.log(state, action) return calculateProfit(Object.assign({}, state, { saleWeight: action.weight })); }, [types.UPDATE_BUY_WEIGHT](state, action) { return calculateProfit(Object.assign({}, state, { buyWeight: action.weight })); }, [types.UPDATE_BUY_UNIT_VALUE](state, action) { return calculateProfit(Object.assign({}, state, { buyUnitValue: action.unitValue })); }, [types.UPDATE_SALE_UNIT_VALUE](state, action) { return calculateProfit(Object.assign({}, state, { saleUnitValue: action.unitValue })); } // [UPDATE_PROFIT]: (state, action) => { // const netWeight = state.buyWeight ? (state.saleWeight / state.buyWeight) : 0; // const netUnitValue = state.buyUnitValue ? (state.saleUnitValue / state.buyUnitValue) : 0; // const grossProfit = newUnitValue ? netWeight / netUnitValue : 0; // state.profit = grossProfit - state.costToKeep; // return state; // } });
process.env.NODE_ENV = 'test'; require("coffee-script"); require(__dirname + "/assert-extra");
'use strict'; // Express Server var express = require('express'), bodyParser = require('body-parser'), methodOverride = require('method-override'), errorHandler = require('error-handler'), https = require('https'), path = require('path'), handlebars = require('express-handlebars'), os = require('os'), moment =require('moment'), networkInterfaces = os.networkInterfaces(), openWeatherAPI = require('./openWeatherAPI'), formWidgetEditor = require('./formWidgetEditor'), helpers = require('./lib/helpers'); //Setting up our express instances; var server = express(); var client = express(); //TODO: for instantiating another //Express Config settings var serverConfig = { baseURL: 'public', port: 9090, baseURLEndPoint: '/weather-widget/api/', handlerBarsViewPath: '/views/server', publicWidgetScr: '/example/widget.js', // serverHost: getIPAddress() serverHost: 'ec2-52-34-148-211.us-west-2.compute.amazonaws.com' }; server.use(bodyParser.urlencoded({extended: false})); server.use(bodyParser.json()); server.use(methodOverride()); server.set('view engine', 'handlebars'); server.engine('handlebars', handlebars({ defaultLayout: __dirname + serverConfig.handlerBarsViewPath + '/layouts/main', partialsDir: __dirname + serverConfig.handlerBarsViewPath + '/partials', helpers: helpers })); server.set('views', __dirname + serverConfig.handlerBarsViewPath); server.use(function(req, res, next){ //Relaxed security rules on the cross resource sharing res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept"); next(); }); server.use(express.static(serverConfig.baseURL)); server.get('/', function (req, res) { res.render('home'); }); server.post('/', function (req, res){ var title = req.body.title, units = req.body.units, showWind = req.body.showWind, lat = req.body.lat, lon = req.body.lon, elemCounter = req.body.elemCounter // console.log('title: ', title, 'units: ', units, 'showWind: ', showWind, 'lat: ', lat, 'lon: ', lon, 'elemCounter: ', elemCounter); if(!checkValidParameters(title, units, showWind)){ res.status(400).send({error: 'One of your input fields has invalid parameters required'}); return; } var snippet_data = generateDynamicScript(title, units, showWind, lat, lon); res.render('layouts/widget-panel', {layout: false, title: title, data: snippet_data, elemCounter: elemCounter}); }); server.post(serverConfig.baseURLEndPoint, function (req, res) { var title = req.body.title, geolocation = { lat: req.body.lat, lon: req.body.lon }, units = req.body.units, showWind = req.body.showWind; if(!checkValidParameters(title, units, showWind)){ res.status(400).send({error: 'One of your input fields has invalid parameters required'}); return; } //Calls external OpenWeather API to get current Weather openWeatherAPI.getCurrentWeatherByGeoLocation(geolocation, units, function (error, data){ if(error){ res.send(error); } console.log('JSON Data returned: ', data); res.render('layouts/widget', {layout: false, widget_title: title, widget_city: data.name, widget_main: data.weather[0].main, widget_weather_icon: fetchWeatherIconClass(data.weather[0].id), widget_description: data.weather[0].description, widget_temp: data.main.temp, widget_showWind: showWind, widget_units: units, widget_speed: data.wind.speed, widget_deg: data.wind.deg, widget_humidity: data.main.humidity, widget_min: data.main.temp_min, widget_max: data.main.temp_max, widget_current_time: moment.unix(data.sys.sunrise).format('LT'),//Unix timestamp on server widget_current_date: moment.unix(data.sys.sunset).format('DD MMM YYYY')//Unix timestamp on server }); }); }); //TODO: Need to do about handling CSS attacks function generateDynamicScript(title, units, showWind, lat, lon){ var params = [title, units, showWind, lat, lon].map(function(item, key){ return generateKeyValuePair('data-'+key, item); }); var scriptId = 'id="script-loader"', scriptType = 'type=\"text/javascript"', scriptSrc = 'src=\"http://' + serverConfig.serverHost + ':' + serverConfig.port + serverConfig.publicWidgetScr + '\"', scriptOpenTag = '<script '+ scriptId +' '+ scriptType + ' '+ scriptSrc+' '+params[0]+' ' +params[1]+' '+params[2]+' '+params[3]+ ' '+params[4]+'>', scriptCloseTag = '</script>', widgetContentTag = '<div id=\"widget-content\"></div>'; return scriptOpenTag.concat(scriptCloseTag, widgetContentTag); } function generateKeyValuePair(key, value){ return key + "=\"" + value + "\""; } //Sourced solutions to get dynamic IP/domain name when hosting // http://blog.bguiz.com/articles/embeddable-widgets-html-javascript function getIPAddress(){ var keys = Object.keys(networkInterfaces); for (var x = 0; x < keys.length; ++x) { var netIf = networkInterfaces[keys[x]]; for (var y = 0; y < netIf.length; ++ y) { var addr = netIf[y]; if (addr.family === 'IPv4' && !addr.internal) { return addr.address; } } } return '127.0.0.1'; } function checkValidParameters(title, units, showWind){ if(!formWidgetEditor.isTitleValid(title)) { return false; } else if(!formWidgetEditor.areUnitsValid(units)) { return false; } else if(!formWidgetEditor.isShowWindValid(showWind)){ return false; } else { return true; } } function fetchWeatherIconClass(weather_icon_id){ var weather_icons_mapping = { 200: "wi wi-thunderstorm", 300: "wi wi-sleet", 500: "wi wi-rain", 600: "wi wi-snow", 741: "wi wi-fog", 800: "wi wi-day-sunny", 801: "wi wi-day-cloudy", 802: "wi wi-cloud", 803: "wi wi-cloudy", 804: "wi wi-cloudy", 900: "wi wi-tornado", 901: "wi wi-storm-showers", 902: "wi wi-hurricane", 903: "wi wi-snowflake-cold", 904: "wi wi-hot", 905: "wi wi-windy", 906: "wi wi-hail" }; return weather_icons_mapping[weather_icon_id]; } //Start up server server.listen(serverConfig.port); console.log("Express Server listening on port: " + serverConfig.port);
/** * Depends of jQuery (yes, it's true) and Tipsy * */ (function(window, $, undefined) { // CROSS-BROWSER JSON SERIALIZATION // FROM http://www.sitepoint.com/javascript-json-serialization/ // if JSON doesn't exit var JSON = window.JSON || {}; // add stringify method (if don't exist) JSON.stringify = JSON.stringify || function (obj) { var t = typeof (obj); if (t != "object" || obj === null) { // simple data type if (t == "string") obj = '"'+obj+'"'; return String(obj); } else { // recurse array or object var n, v, json = [], arr = (obj && obj.constructor == Array); for (n in obj) { v = obj[n]; t = typeof(v); if (t == "string") v = '"'+v+'"'; else if (t == "object" && v !== null) v = JSON.stringify(v); json.push((arr ? "" : '"' + n + '":') + String(v)); } return (arr ? "[" : "{") + String(json) + (arr ? "]" : "}"); } }; // EXTEND JQUERY FUNCTION $.fn.extend({ // with a new "FreebaseTopic" function /** * FreebaseTopic function to explore a topic description * @function * @public * @param reset */ freebaseTopic : function(reset) { // this function instance var freebaseTopic = this, // target $this = freebaseTopic, // freebase READ url freebase_read = "http://www.freebase.com/api/service/mqlread"; // query according the type freebaseTopic.typeQuery = { // for a person "/people/person": [{ "name": null, "/people/person/profession" : [], "/people/person/gender" : null, "/people/person/nationality" : [], "/people/person/date_of_birth" : null, "/people/person/place_of_birth" : null, "/people/person/places_lived" : [], "key": [{ "namespace": "/wikipedia/en_id", "value": null, "optional":"optional" }], "/common/topic/image" : [{ "id" : null, "optional":"optional" }] }], // for an organization "/organization/organization": [{ "name": null, "/organization/organization/headquarters": [], "/organization/organization/legal_structure" : [], "/organization/organization/date_founded" : null, "key": [{ "namespace": "/wikipedia/en_id", "value": null, "optional":"optional" }], "/common/topic/image" : [{ "id" : null, "optional":"optional" }] }] }; /** * Init function * @public */ freebaseTopic.init = function() { // live mouse enter event $this.live("mouseenter", reachTopic); // live mouse leave event $this.live("mouseleave", leaveTopic); // tipsy $this.tipsy({ gravity: "n", html: true, fade: false, live: true, opacity:1, trigger: "hover", fallback: "No data available about this.", title: getTopicDescription, addClass: "fb-topic-tipsy" }); // open link in a other window $this.live("click", function(e) { e.preventDefault(); // if has href if( $(this).attr("href") && $(this).attr("href") != "" ) // if is a link or a button if( $(this).is("a") || $(this).is("button") || $(this).is("input[type=button]") ) // open the link window.open($(this).attr("href")); }); return $this; }; /** * Init topic description when mouse enter * @private */ function reachTopic() { var $topic = $(this); // hover class $topic.addClass("fb-topic-hover"); // we already loaded the topic description if( $topic.data("description") ) { // show topic description showTopic.call(this); // we didn't, we must load it know } else { // load topic from Freebase loadTopic.call(this); } } /** * Leave the topic trigger * @private */ function leaveTopic() { // remove hover class $(this).removeClass("fb-topic-hover"); } /** * Load topic's data from Freebase * @private */ function loadTopic() { var $topic = $(this), data; // data to import data = freebaseTopic.typeQuery[$topic.data("type")]; if(data != undefined) { // add the id data[0].id = $topic.data("mid"); // freebase query data = JSON.stringify( {"query" : data} ); // freeze description $topic.data("description", true); // add class to loading $topic.addClass("fb-topic-loading"); // call the api $.ajax({ // url customized for JSONP callback url: freebase_read+"?callback=?", // data in a query parameter data: {query:data}, // context to retrieve the $topic context: $topic, // cross domain json dataType: "jsonp", // when the query is done success :function(data,textStatus, jqXHR) { // if the query is OK if(data.code == "/api/status/ok") { // save the topic's data $topic.data("description", data.result[0]); // add class to loading $topic.removeClass("fb-topic-loading"); // show the description showTopic.call(this); } } }); } } /** * Show the topic * @private */ function showTopic() { var $topic = $(this); // description loaded and mouse on the trigger yet if( typeof $topic.data("description") == "object" && $topic.hasClass("fb-topic-hover") ) // show tooltips $topic.tipsy("show"); } /** * Get the description of the topic (HTML) * @private */ function getTopicDescription() { var $topic = $(this); if( typeof $topic.data("description") == "object" && $topic.hasClass("fb-topic-hover") ) { var html = ""; // for each property $.each( $topic.data("description"), function(key, value) { html += getPropertyDisplay(key, value); }); // load wikipedia link if( $topic.data("description").key.length > 0 ) $topic.attr("href", "http://en.wikipedia.org/wiki/index.html?curid=" + $topic.data("description").key[0].value) // return the content return html; // no tooltips yet } else return ''; } /** * Get the display of the propertie * * @private * @param string * @param mixed */ function getPropertyDisplay(key, value) { // empty value if(value == null || value.length == 0 || value == "") return""; // display according to the key switch(key) { // FOR /PEOPLE/PERSON case "/people/person/profession" : return "<p>Profession:&nbsp;" + value.join(", ") + "</p>"; break; case "/people/person/gender": return "<p>Gender:&nbsp;" + value + "</p>"; break; case "/people/person/nationality": return "<p>Nationality:&nbsp;" + value.join(", ") + "</p>"; break; case "/people/person/date_of_birth": return "<p>Date of birth:&nbsp;" + value + "</p>"; break; case "/people/person/place_of_birth": return "<p>Place of birth:&nbsp;" + value + "</p>"; break; case "/people/person/places_lived": return "<p>Places lived:&nbsp;" + value.join(", ") + "</p>"; break; // FOR /ORGANIZATION/ORGANIZATION case "/organization/organization/headquarters": return "<p>Headquarters:&nbsp;" + value.join(", ") + "</p>"; break; case "/organization/organization/legal_structure": return "<p>Legal structure:&nbsp;" + value.join(", ") + "</p>"; break; case "/organization/organization/date_founded": return "<p>Date founded:&nbsp;" + value + "</p>"; break; // FOR ALL case "/common/topic/image": return "<p class='image'><img src='http://img.freebase.com/api/trans/image_thumb/" + value[0].id + "?maxheight=120&mode=fit&maxwidth=160' alt='' /></p>"; break; default: return ""; break; } } freebaseTopic.reset = function() { // remove mid $(this).data("mid", "") // remove type .data("type", "") // remove description .data("description", ""); // hide tipsy $(this).tipsy("hide"); return $(this); }; // RESET TOOLTIPS if(reset == "reset") return freebaseTopic.reset(); // INIT THE CLASS else return freebaseTopic.init(); } }); })(window, jQuery);
/* jshint globalstrict: true, camelcase: false */ /* global module, require */ 'use strict'; module.exports = function(grunt) { // load all grunt tasks require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks); grunt.initConfig({ // watch for changes and trigger compass, jshint, uglify and livereload watch: { options: { livereload: true, }, css: { files: ['assets/scss/**/*.{scss,sass}'], tasks: ['compass', 'growl:css'] }, js: { files: '<%= jshint.all %>', tasks: ['jshint', 'uglify', 'growl:js'] }, livereload: { options: { livereload: true }, files: ['style.css', 'assets/js/*.js', '*.html', '*.php', 'assets/images/**/*.{png,jpg,jpeg,gif,webp,svg}'] } }, // compass and scss compass: { dist: { options: { config: 'config.rb', force: true } } }, // javascript linting with jshint jshint: { options: { jshintrc: '.jshintrc' }, all: [ 'Gruntfile.js', 'assets/js/source/**/*.js' ] }, // uglify to concat, minify, and make source maps uglify: { plugins: { options: { sourceMap: 'assets/js/map/source-map-plugins.js.map', sourceMappingURL: 'map/source-map-plugins.js.map' }, files: { 'assets/js/plugins.min.js': [ '!assets/js/vendor/modernizr*.js', '!assets/js/vendor/jquery*.js', 'assets/js/vendor/**/*.js' ] } }, main: { options: { sourceMap: 'assets/js/map/source-map-main.js.map', sourceMappingURL: 'map/source-map-main.js.map' }, files: { 'assets/js/main.min.js': [ 'assets/js/source/**/*.js', 'assets/js/source/main.js' ] } } }, // image optimization imagemin: { dist: { options: { optimizationLevel: 7, progressive: true }, files: [{ expand: true, cwd: 'assets/images/', src: '**/*', dest: 'assets/images/' }] } }, // deploy via rsync deploy: { staging: { src: './', dest: '~/www/dev1/cms/wp-content/themes/spaceadvocates', host: '[email protected]', recursive: true, syncDest: true, exclude: [ '.git*', '.sass-cache', '.DS_Store', '.jshintrc', 'node_modules', 'assets/scss', 'assets/js/source', 'dumps', 'Gruntfile.js', 'package.json', 'README.md', 'config.rb', 'grunt-settings.json', 'grunt-settings-sample.json', '*.sublime-project', '*.sublime-workspace', 'Gemfile', 'Gemfile.lock' ] }, production: { src: './', dest: '~/www/cms/wp-content/themes/spaceadvocates', host: '<%= deploy.staging.host %>', recursive: true, syncDest: true, exclude: '<%= deploy.staging.exclude %>' } }, // desktop notifications when grunt events have fired growl: { css: { title: 'CSS Complete', message: 'Compass has finished running.', image: 'Safari' }, js: { title: 'JS Complete', message: 'JSHint and Uglify have finished running.', image: './assets/images/icon-grunt.png' } } }); // rename tasks grunt.renameTask('rsync', 'deploy'); // register task grunt.registerTask('default', ['watch']); };
angular.module('myApp.directives').directive('gimsQuestionnaireMenu', function($dropdown) { return { restrict: 'E', template: '<div class="btn-group" style="width: 40px">' + ' <button type="button" class="btn btn-default dropdown-toggle btn-sm">' + ' <i class="fa fa-angle-down"></i>' + ' </button><span class="input-group-btn">' + '</div>', link: function(scope, element) { var button = element.find('button'); button.bind('click', function() { $dropdown.open({ button: button, templateUrl: '/template/browse/cell-menu/questionnaire-menu', controller: 'QuestionnaireMenuCtrl', resolve: { questionnaire: function() { return scope.questionnaire; } } }); }); } }; });
/** * Delay for user search component. * Input is debounced to reduce load on the server. * * @constant * @default * @type {string} */ export const SEARCH_DEBOUNCE_DELAY = '400'; export const NEW_AWARD_ID = 'newAwardId';
var should = require('should'); var sinon = require('sinon'); var Category = require('../../lib/endpoints/category'); describe("Category", function() { var cattest, stub; beforeEach(function() { cattest = new Category({ key: 123 }); stub = sinon.stub(cattest, "executeRequest"); }); afterEach(function() { stub.restore(); }); it("should have a config", function() { should.exist(cattest.config); }); it("should have a general endpoint and id endpoint", function() { should.exist(cattest.genEndpoint); should.exist(cattest.idEndpoint); }); describe("getById()", function() { it("should contact id endpoint with id: category/id", function() { cattest.getById("id", null); stub.calledWith("category/id", { key: 123 }, null).should.be.true; }); }); describe("all()", function() { it("should contact general endpoint", function() { cattest.all(null); stub.calledWith("categories", { key: 123 }, null).should.be.true; }); }); });
define([], function() { return function($scope, $toast, $state, $stateParams, $marketSupply, $ionicHistory, $ionicPopup, $loading, localStorageService) { $scope.agentInfo = {}; var warnDialog = function(msg) { $ionicPopup.alert({ title: '注意', template: msg }); }; //返回代理信息 $scope.init = function() { $scope.agentInfo = localStorageService.get('AGENT_INFO'); localStorageService.remove('AGENT_INFO'); }; //删除代理 $scope.deleteAgent = function() { $ionicPopup.confirm({ title: '确定删除代理吗', template: '删除代理不会影响已有交易信息,但是无法与对方发起新的交易', okText: '删除', okType: 'button-assertive', cancelText: '取消', cancelType: 'button-stable' }) .then(function(res) { if(!res) { return; } $loading.show(); $marketSupply.removeAgent($scope.agentInfo.id) .then(function (){ $ionicHistory.goBack(); }) .catch(function (err){ $toast.error(err); }) .finally(function (){ $loading.hide(); }) }); }; //修改代理备注 $scope.modifyRemarkName = function(){ $ionicPopup.prompt({ title: '修改备注', template: '请控制在2-20个字符,允许汉字、英文、数字、"-"和"_"', defaultText: $scope.agentInfo.agent_remark_name, inputPlaceholder: $scope.agentInfo.agent_remark_name || '输入备注名', okText: '确定', cancelText: '取消' }).then(function(value) { if (!angular.isString(value)) return; if (value.trim().length === 0) { warnDialog('备注名不能为空白字符'); } else { $loading.show(); $marketSupply.saveRemarkName($scope.agentInfo.id,value) .then(function (result){ if (angular.isString(value) && value.length > 0) { $scope.agentInfo.agent_remark_name = value; } }) .catch(function (err){ $toast.error(err); }) .finally(function (){ $loading.hide(); }) } }); }; }; });
const {onlineUserStore, chatMessageStore} = require('../../redis/RedisStore') module.exports = { postChatMessages: async function (ctx, next) { let socketId = ctx.socket.id let time = Date.now() let user = await onlineUserStore.get(socketId) ctx.response = Object.assign({}, ctx.req.params, {from: user, time}) await chatMessageStore.set({data: ctx.response, sid: socketId + ':' + time}) next() }, getChatMessages: async function (ctx, next) { let response = await chatMessageStore.getAll({sort: 'reverse'}) ctx.callback(response) } }
/** * Created by zhiyuans on 9/21/2016. */ const mongoose = require('mongoose'); const Schema = mongoose.Schema; const ObjectId = Schema.Types.ObjectId; const commentSchema = new Schema({ eventId: ObjectId, //event外键 userId: ObjectId, //user外键 content: String, time: Date });
/*! * Web Office Workspace - Wow * Copyright(c) 2010. * @author Otávio Fernandes <oaugustus> */ Ext.ns('Wow.workspace'); /** * @class Wow.workspace.ModuleProvider * @extends Ext.util.Observable * Manager of Application UI Modules * @constructor * @param */ Wow.workspace.ModuleProvider = function(){ this.groups = new Ext.util.MixedCollection(); Wow.workspace.ModuleProvider.superclass.constructor.call(this); }; Ext.extend(Wow.workspace.ModuleProvider, Ext.util.Observable, { getModules : function(){ return [ { title: 'Cadastros', items:[ { xtype: 'buttongroup', title: 'Agenda', items:[ { text: 'Empresas', mtype: 'cidade-module', iconCls: 'cidade', mId: 'cidade' }, { text: 'Pessoas', mtype: 'estado-module', iconCls: 'estado', mId: 'estado' }, { text: 'Feriados', mtype: 'estado-module', iconCls: 'estado', mId: 'estado' } ] }, { xtype: 'buttongroup', title: 'Equipamento', items:[ { text: 'Equipamentos', mtype: 'estado-module', iconCls: 'estado', mId: 'estado' }, { text: 'Instala&ccedil;&atilde;o f&iacute;sica', mtype: 'estado-module', iconCls: 'estado', mId: 'estado' }, { text: 'Categorias', mtype: 'estado-module', iconCls: 'estado', mId: 'estado' }, { text: 'Modelos', mtype: 'estado-module', iconCls: 'estado', mId: 'estado' } ] }, { xtype: 'buttongroup', title: 'Estoque', items:[ { text: 'Peças', mtype: 'estado-module', iconCls: 'estado', scale: 'large', mId: 'estado' }, { text: 'Estoque', mtype: 'estado-module', iconCls: 'estado', mId: 'estado' } ] }, { xtype: 'buttongroup', title: 'Preventiva', items:[ { text: 'Grupo', mtype: 'estado-module', iconCls: 'estado', scale: 'large', mId: 'estado' }, { text: '&nbsp;&nbsp;Item&nbsp;&nbsp;', mtype: 'estado-module', iconCls: 'estado', mId: 'estado' }, { text: 'Rotina', mtype: 'estado-module', iconCls: 'estado', mId: 'estado' } ] }, { xtype: 'buttongroup', title: 'Controle de gases', items:[ { text: 'Gases medicinais', mtype: 'estado-module', iconCls: 'estado', scale: 'large', mId: 'estado' }, { text: 'Tanques e Cilindros', mtype: 'estado-module', iconCls: 'estado', mId: 'estado' } ] } ] }/*, { title: 'Grupo 2', xtype: 'officemenugroup', items:[ { title: 'Estado', mtype: 'cidade-module', iconCls: 'estado' } ] }*/ ] } });
module.exports = [ { name: 'A', connections: [ { name: '1', target: 'B' }, ], }, { name: 'B', connections: [ { name: '1', target: 'C' } ] }, { name: 'C', connections: [ { name: '1', target: 'D' } ] }, { name: 'D', connections: [ { name: '1', target: 'E' } ] }, { name: 'E', connections: [ { name: '1', target: 'F' } ] }, { name: 'F', connections: [ { name: '1', target: 'G' } ] }, { name: 'G', connections: [ { name: '1', target: 'H' }, ] }, { name: 'H', connections: [ { name: '1', target: 'I' } ] }, { name: 'I', connections: [ { name: '1', target: 'J' } ] }, { name: 'J', connections: [ { name: '1', target: 'K' }, ] }, { name: 'K', connections: [ { name: '1', target: 'L' } ] }, { name: 'L', connections: [ { name: '1', target: 'M' }, ] }, { name: 'M', connections: [ { name: '1', target: 'N' }, ] }, { name: 'N', connections: [ { name: '1', target: 'A' }, ] } ];
var React = require('react'); var ReactMaskMixin = require('react-mask-mixin'); var UI = require('UI'); var View = UI.View; var List = UI.List; var Content = UI.Content; var Icon = UI.Icon.Icon; var Switch = UI.Form.Switch; var Slider = UI.Form.Slider; var Grid = UI.Grid; var Button = UI.Button.Button; function getImageData(img, width, height) { var canvas = document.createElement("canvas"); canvas.width = width; canvas.height = height; var ctx = canvas.getContext("2d"); ctx.drawImage(img, 0, 0, width, height); return canvas.toDataURL("image/png"); } function getImage(i) { return 'img/app/head/'+i+'.jpg'; } var MaskInput = React.createClass({ mixins: [ReactMaskMixin], render: function() { return <input {...this.props} {...this.mask.props} /> } }) var FormItem = React.createClass({ render: function() { return ( <List.ItemContent> {this.props.icon&&<List.ItemMedia><Icon name={this.props.icon}/></List.ItemMedia>} <List.ItemInner> {this.props.label&&<List.ItemTitle label>{this.props.label}</List.ItemTitle>} <List.ItemInput> {this.props.children} </List.ItemInput> </List.ItemInner> </List.ItemContent> ); } }); var FormInputItem = React.createClass({ render: function() { return ( <FormItem icon={this.props.icon} label={this.props.label}> <input type={this.props.input_type} placeholder={this.props.placeholder} value={this.props.value} onChange={this.props.onChange}/> </FormItem> ); } }); module.exports = React.createClass({ componentWillMount: function() { this.headImageIndex = this.props.data.param.headImageIndex||0; }, doRegister: function() { var userid = this.state.userid.replace(/-/g, ""); if (!(/\d{11}/.test(userid))) { app.showError("Invalid Phone!"); return; } var password = this.state.password; if (password !== this.state.confirmPwd) { app.showError("Please Confirm PassWord"); return; } if (!this.state.username) { app.showError("UserName Empty!"); return; } var head = getImageData(this.refs.head.getDOMNode(), 100,100); var param = { userid: userid, password: password, username: this.state.username, sign: this.state.sign, head: head }; app.socket.emit('USER_REGISTER_RQ', param); }, handleChange: function(type, e) { var state = {}; state[type] = e.target.value; this.setState(state); }, selectHead: function() { app.showView('selectHead', 'left'); }, getInitialState: function() { return { userid: '', password: '', username: '', sign: '' }; }, render: function() { return ( <View.Page title="Register"> <View.PageContent> <Content.ContentBlock> <List.List block> <FormItem icon="ion-android-contact" label="Head:"> <img className={"big_user_head"} src={getImage(this.headImageIndex)} onClick={this.selectHead} ref="head"/> </FormItem> </List.List> </Content.ContentBlock> <Content.ContentBlock> <List.List block> <FormItem icon="icon-form-tel" label="Phone:"> <MaskInput mask="999-9999-9999" placeholder="Input Phone" type="tel" value={this.state.phone} onChange={this.handleChange.bind(this, "userid")}/> </FormItem> <FormInputItem icon="icon-form-name" label="User Name:" input_type="text" placeholder="Input UserName" value={this.state.username} onChange={this.handleChange.bind(this, "username")}/> </List.List> </Content.ContentBlock> <Content.ContentBlock> <List.List block> <FormInputItem icon="icon-form-password" label="PassWord:" input_type="password" placeholder="Input PassWord" value={this.state.password} onChange={this.handleChange.bind(this, "password")}/> <FormInputItem icon="icon-form-password" label="Confirm Pwd:" input_type="password" placeholder="Confirm PassWord" value={this.state.confirmPwd} onChange={this.handleChange.bind(this, "confirmPwd")}/> </List.List> </Content.ContentBlock> <Content.ContentBlock> <List.List block> <FormItem icon="icon-form-comment" label="Sign:"> <textarea placeholder="Input Sign" value={this.state.sign} onChange={this.handleChange.bind(this, "sign")}></textarea> </FormItem> </List.List> </Content.ContentBlock> <Content.ContentBlock> <Grid.Row> <Grid.Col per={100}><Button big fill color="green" onTap={this.doRegister}>Register</Button></Grid.Col> </Grid.Row> </Content.ContentBlock> </View.PageContent> </View.Page> ); } });
/** * 2017-9-24 Jifeng Cheng * parseInt */ //parseInt:将字符串转换成相应进制的数 console.log(parseInt('101', 2)); console.log(parseInt('11', 2)); console.log(parseInt('hello', 2)); //如果字符串不是数字,则输出NaN; console.log(parseInt('0x11', 2)); //parseFloat:只能解析十进制的数字 console.log(parseFloat('11', 2)); console.log(parseFloat('30', 8)); console.log(parseFloat('0101', 10));
/*! qinblog 1.0.0 | http://www.qinblog.net | (c) 2017 qinblog | MIT License */ ;(function() { //path define var path = { uikit : '/Public/common_lib/uikit/', editormd : '/Public/common_lib/editor.md/', user : '/Public/home/js/', user_css : '/Public/home/css/', user_plugins : '/Public/home/js/plugins/', common_lib : '/Public/common_lib/' } // UIKIT plugins head.load( /*表单组件*/ path.uikit + 'css/components/form-advanced.almost-flat.min.css', path.uikit + 'css/components/form-file.almost-flat.min.css', /* 附着组件 */ path.uikit + 'css/components/sticky.almost-flat.min.css', path.uikit + 'js/components/sticky.min.js', /* 工具提示组件 */ path.uikit + 'css/components/tooltip.almost-flat.min.css', path.uikit + 'js/components/tooltip.min.js', /* 灯箱 */ path.uikit + 'js/components/lightbox.min.js', /* 动态分页 */ path.uikit + 'js/components/pagination.min.js', /* 手风琴 */ path.uikit + 'css/components/accordion.almost-flat.min.css', path.uikit + 'js/components/accordion.min.js' ); // Editor.md lib and plugins head.load({editormd : path.editormd + 'editormd.min.js'}, function() { /* style */ head.load(path.editormd + 'css/editormd.min.css', path.editormd + 'css/editormd.preview-dark.min.css'); /* lib */ head.load(path.editormd + 'lib/marked.min.js', path.editormd + 'lib/prettify.min.js', path.editormd + 'lib/raphael.min.js', path.editormd + 'lib/underscore.min.js', path.editormd + 'lib/sequence-diagram.min.js', path.editormd + 'lib/flowchart.min.js', path.editormd + 'lib/jquery.flowchart.min.js'); }); // USER jquery plugins head.load(path.user_plugins + 'qintool/jquery.qintool.min.js'); head.load(path.user_css + 'plugins/comment.min.css'); /* comment system */ // weibo head.load('http://tjs.sjs.sinajs.cn/open/api/js/wb.js?appkey=appkey'); // hello.js github\google\twitter... head.load(path.common_lib + 'helloJS/hello.all.min.js', function(){ var GITHUB_CLIENT_ID = { 'your domain' : 'appkey' }[window.location.hostname]; hello.init({ github : GITHUB_CLIENT_ID },{ redirect_uri : 'your redirect url', }); }); head.load(path.user_plugins + 'comment/jquery.comment.min.js'); // third party plugins head.load(path.common_lib + 'zx_weather.js', path.common_lib + 'baidu.share.js'); head.load(path.common_lib + 'particles/particles.min.js', function() { head.load(path.common_lib + 'particles/app.js'); }); })();
exports.sleep = (ms = 1000) => new Promise(resolve => setTimeout(resolve, ms)) exports.Logger = outEl => { outEl.innerHTML = '' return message => { const container = document.createElement('div') container.innerHTML = message outEl.appendChild(container) outEl.scrollTop = outEl.scrollHeight } } exports.onEnterPress = fn => { return e => { if (event.which == 13 || event.keyCode == 13) { e.preventDefault() fn() } } } exports.catchAndLog = (fn, log) => { return async (...args) => { try { await fn(...args) } catch (err) { console.error(err) log(`<span class="red">${err.message}</span>`) } } }