code
stringlengths
2
1.05M
"use strict"; describe("Response Handlers", () => { const expect = require("chai").expect; const ValidationError = require("../index.js").ValidationError; const responseHandlers = require("../index.js").responseHandlers; describe(".success()", () => { let response = null; beforeEach(() => { response = { status() { return this; }, json() { return this; } }; }); it("should return handler function", () => { expect(typeof responseHandlers.success()).to.eql("function"); }); it("should set status code 200 on response", (done) => { response.status = function _status(status) { expect(status).to.equal(200); done(); return this; }; responseHandlers.success(response)(); }); it("should set the passed status code on response", (done) => { response.status = function _status(status) { expect(status).to.equal(204); done(); return this; }; responseHandlers.success(response, 204)(); }); it("should set 200 in case the passed status code is not a success valid one", (done) => { response.status = function _status(status) { expect(status).to.equal(200); done(); return this; }; responseHandlers.success(response, 404)(); }); it("should send data as json", (done) => { const data = {the: "answer"}; response.json = function _json(sent) { expect(sent).to.deep.equal(data); done(); return this; }; responseHandlers.success(response)(data); }); }); describe(".error()", () => { let response = null; let logger = null; beforeEach(() => { response = { status() { return this; }, json() { return this; } }; logger = { error() { // no op }, fatal() { // no op } }; }); it("should return handler function", () => { expect(typeof responseHandlers.error()).to.eql("function"); }); it("should not blow if logger is not given", () => { function sut() { responseHandlers.error(response)("h"); } expect(sut).not.to.throw(); }); it("should not blow if error is not given", () => { function sut() { responseHandlers.error(response, logger)(); } expect(sut).not.to.throw(); }); it("should not blow if error is an empty array", () => { function sut() { responseHandlers.error(response, logger)([]); } expect(sut).not.to.throw(); }); it("should set status code 500 for generic error", (done) => { response.status = function _status(status) { expect(status).to.equal(500); done(); return this; }; const err = new Error("hello"); responseHandlers.error(response, logger)(err); }); it("should set status code 400 for validation error", (done) => { response.status = function _status(status) { expect(status).to.equal(400); done(); return this; }; const err = new ValidationError("HI", "hello"); responseHandlers.error(response, logger)(err); }); it("should set status code of the validation error", (done) => { response.status = function _status(status) { expect(status).to.equal(404); done(); return this; }; const err = new ValidationError("HI", "hello", 404); responseHandlers.error(response, logger)(err); }); it("should set status code 404 for an error with type NOT_FOUND", (done) => { response.status = function _status(status) { expect(status).to.equal(404); done(); return this; }; const err = new Error("hello"); err.code = "HI"; err.type = "NOT_FOUND"; responseHandlers.error(response, logger)(err); }); it("should set status code 400 for an error with type INVALID", (done) => { response.status = function _status(status) { expect(status).to.equal(400); done(); return this; }; const err = new Error("hello"); err.code = "HI"; err.type = "INVALID"; responseHandlers.error(response, logger)(err); }); it("should set status code 400 for an error with type not recognised", (done) => { response.status = function _status(status) { expect(status).to.equal(400); done(); return this; }; const err = new Error("hello"); err.code = "HI"; err.type = "NEW_ERR_TYPE"; responseHandlers.error(response, logger)(err); }); it("should set status code 409 (conflict) for a duplicated index error", (done) => { response.status = function _status(status) { expect(status).to.equal(409); done(); return this; }; const err = {message: "E11000 duplicate key error index: betterez_core.stations.$name_1_accountId_1 dup key"}; responseHandlers.error(response, logger)(err); }); it("should not fail if no logger", (done) => { response.json = function _json(sent) { expect(sent).to.deep.equal({code: "hello", message: "hello"}); done(); return this; }; const err = new Error("hello"); responseHandlers.error(response, null)(err); }); it("should send error message as json", (done) => { response.json = function _json(sent) { expect(sent).to.deep.equal({code: "hello", message: "hello"}); done(); return this; }; const err = new Error("hello"); responseHandlers.error(response, logger)(err); }); it("should send error message as json for error with type and code", (done) => { response.json = function _json(sent) { expect(sent).to.deep.equal({code: "HI", message: "hello", context: {}}); done(); return this; }; const err = new Error("hello"); err.code = "HI"; err.type = "TYPE"; responseHandlers.error(response, logger)(err); }); it("should log fatal if err is 500", (done) => { const _logger = { fatal() { expect(1).to.be.eql(1); } }; response.json = function _json(sent) { expect(sent).to.deep.equal({ code: "hello", message: "hello" }); done(); return this; }; const err = new Error("hello"); responseHandlers.error(response, _logger)(err); }); it("should set status code 400 for several validation errors", (done) => { response.status = function _status(status) { expect(status).to.equal(400); done(); return this; }; const errs = [new ValidationError("HI", "hello"), new ValidationError("BYE", "bye")]; responseHandlers.error(response, logger)(errs); }); it("should log error if err is 400", (done) => { const _logger = { error() { expect(1).to.be.eql(1); } }; response.status = function _status(status) { expect(status).to.equal(400); done(); return this; }; const errs = [new ValidationError("HI", "hello"), new ValidationError("BYE", "bye")]; responseHandlers.error(response, _logger)(errs); }); it("should send error messages as json for several validation errors", (done) => { response.json = function _json(sent) { expect(sent).to.deep.equal({code: "HI", message: "hello, bye", context: {}}); done(); return this; }; const errs = [new ValidationError("HI", "hello"), new ValidationError("BYE", "bye")]; responseHandlers.error(response, logger)(errs); }); }); describe(".createError()", () => { it("should return an error called with no params", () => { expect(responseHandlers.createError()).to.be.instanceof(Error); }); it("should return an error called with a string", () => { expect(responseHandlers.createError("foo")).to.be.instanceof(Error); }); it("should return the same Error if called with an Error", () => { const err = new Error("this is an error"); expect(responseHandlers.createError(err)).to.be.eql(err); }); it("should return the same Error if called with a ValidationError without message", () => { const err = new ValidationError("code"); expect(responseHandlers.createError(err)).to.be.deep.equal(err); }); }); describe("_isMongoDbConflict()", () => { it("should return true for a duplicated index error", () => { const err = {message: "E11000 duplicate key error index: betterez_core.stations.$name_1_accountId_1 dup key"}; expect(responseHandlers._isMongoDbConflict(err)).to.be.eql(true); }); it("should return false for another non-mongo generic error", () => { const err = new Error("any error!"); expect(responseHandlers._isMongoDbConflict(err)).to.be.eql(false); }); it("should return true for a duplicated collection error", () => { const err = {message: "E11000 duplicate key error collection: database_name.collection.$indexName dup key"}; expect(responseHandlers._isMongoDbConflict(err)).to.be.eql(true); }); }); });
'use strict'; /** * @ngInject */ function Routes($stateProvider, $locationProvider, $urlRouterProvider) { $locationProvider.html5Mode(true); $stateProvider .state('Home', { url: '/', controller: 'HomeCtrl as home', templateUrl: 'home.html', title: '๊ณ ๋ ค๋Œ€ํ•™๊ต ์—ฐ๊ตฌํฌํ„ธ ๊ณต๋™๊ธฐ๊ธฐ ๋„คํŠธ์›Œํฌ ๋งต' }); $urlRouterProvider.otherwise('/'); } module.exports = Routes;
const syntaxHighlight = require("@11ty/eleventy-plugin-syntaxhighlight"); const markdownIt = require("markdown-it"); const createSlide = require("./plugins/create-slide"); module.exports = function(eleventyConfig) { eleventyConfig.addPlugin(syntaxHighlight); eleventyConfig.addPassthroughCopy("assets"); eleventyConfig.setLibrary("md", markdownIt({}).use(createSlide)); return { passthroughFileCopy: true, }; };
/*! (c) 2012 Uzi Kilon, Splunk Inc. Backbone Poller 0.3.0 https://github.com/uzikilon/backbone-poller Backbone Poller may be freely distributed under the MIT license. */ // (function (root, factory) { // 'use strict'; // if (typeof define == 'function' && define.amd) { // define(['underscore', 'backbone'], factory); // } // else if (typeof require === 'function' && typeof exports === 'object') { // module.exports = factory(require('underscore'), require('backbone')); // } // else { // root.Backbone.Poller = factory(root._, root.Backbone); // } // }(this, function (_, Backbone) { module.exports = function(){ 'use strict'; // Default settings var defaults = { delay: 1000, backoff: false, condition: function () { return true; } }; // Available events var events = ['start', 'stop', 'fetch', 'success', 'error', 'complete' ]; var pollers = []; function findPoller(model) { return _.find(pollers, function (poller) { return poller.model === model; }); } var PollingManager = { // **Backbone.Poller.get(model[, options])** // <pre> // Returns a singleton instance of a poller for a model // Stops it if running // If options.autostart is true, will start it // Returns a poller instance // </pre> get: function (model, options) { var poller = findPoller(model); if (!poller) { poller = new Poller(model, options); pollers.push(poller); } else { poller.set(options); } if (options && options.autostart === true) { poller.start({silent: true}); } return poller; }, // **Backbone.Poller.size()** // <pre> // Returns the number of instantiated pollers // </pre> size: function () { return pollers.length; }, // **Backbone.Poller.reset()** // <pre> // Stops all pollers and removes from the pollers pool // </pre> reset: function () { while (pollers.length) { pollers.pop().stop(); } } }; function Poller(model, options) { this.model = model; this.set(options); } _.extend(Poller.prototype, Backbone.Events, { // **poller.set([options])** // <pre> // Reset poller options and stops the poller // </pre> set: function (options) { this.options = _.extend({}, defaults, options || {}); if (this.options.flush) { this.off(); } _.each(events, function (name) { var callback = this.options[name]; if (_.isFunction(callback)) { this.off(name, callback, this); this.on(name, callback, this); } }, this); if (this.model instanceof Backbone.Model) { this.model.on('destroy', this.stop, this); } return this.stop({silent: true}); }, // // **poller.start([options])** // <pre> // Start the poller // Returns a poller instance // Triggers a 'start' events unless options.silent is set to true // </pre> start: function (options) { if (!this.active()) { options && options.silent || this.trigger('start', this.model); this.options.active = true; if (this.options.delayed) { delayedRun(this); } else { run(this); } } return this; }, // **poller.stop([options])** // <pre> // Stops the poller // Aborts any running XHR call // Returns a poller instance // Triggers a 'stop' events unless options.silent is set to true // </pre> stop: function (options) { options && options.silent || this.trigger('stop', this.model); this.options.active = false; this.xhr && this.xhr.abort && this.xhr.abort(); this.xhr = null; clearTimeout(this.timeoutId); this.timeoutId = null; return this; }, // **poller.active()** // <pre> // Returns a boolean for poller status // </pre> active: function () { return this.options.active === true; } }); function run(poller) { if (validate(poller)) { var options = _.extend({}, poller.options, { success: function (model, resp) { poller.trigger('success', model, resp); delayedRun(poller); }, error: function (model, resp) { if (poller.options.continueOnError) { poller.trigger('error', model, resp); delayedRun(poller); } else { poller.stop({silent: true}); poller.trigger('error', model, resp); } } }); poller.trigger('fetch', poller.model); poller.xhr = poller.model.fetch(options); } } function getDelay(poller) { if (!poller.options.backoff) { return poller.options.delay; } poller._backoff = poller._backoff ? Math.min(poller._backoff * 1.1, 30) : 1; return Math.round(poller.options.delay * poller._backoff); } function delayedRun(poller) { if (validate(poller)) { poller.timeoutId = _.delay(run, getDelay(poller), poller); } } function validate(poller) { if (! poller.options.active) { return false; } if (poller.options.condition(poller.model) !== true) { poller.stop({silent: true}); poller.trigger('complete', poller.model); return false; } return true; } PollingManager.getDelay = getDelay; // test hook PollingManager.prototype = Poller.prototype; // test hook return PollingManager; } // ));
'use strict'; const common = require('../common'); const noop = () => {}; const TTY = process.binding('tty_wrap').TTY = function() {}; TTY.prototype = { setBlocking: noop, getWindowSize: noop }; const { WriteStream } = require('tty'); const methods = [ 'cursorTo', 'moveCursor', 'clearLine', 'clearScreenDown' ]; methods.forEach((method) => { require('readline')[method] = common.mustCall(); const writeStream = new WriteStream(1); writeStream[method](1, 2); });
var _hmt = _hmt || []; (function() { var hm = document.createElement("script"); hm.src = "//hm.baidu.com/hm.js?29e357192159be39f03d0477711f79c3"; var s = document.getElementsByTagName("script")[0]; s.parentNode.insertBefore(hm, s); })();
/* global monaco */ import { getOffsetAt, locToRange, getCurrentWord } from '../comm'; import { request } from '../provider-child'; export default function renameProvider() { monaco.languages.registerRenameProvider('lua', { provideRenameEdits(model, position, newName, token) { return new Promise((resolve, reject) => { const offset = getOffsetAt(model, position); const word = getCurrentWord(model, offset); request('reference', { word, offset, modelId: model.id }) .then(locs => resolve({ edits: locs.map(loc => ({ resource: model.uri, range: locToRange(loc), newText: newName, })), }) ) .catch(() => reject('You cannot rename this element.')); }); }, }); }
// enter file of limited Konva version with only core functions // @ts-ignore var Konva = require('./_CoreInternals').Konva; // add Konva to global variable Konva._injectGlobal(Konva); // @ts-ignore exports['default'] = Konva; Konva.default = Konva; // @ts-ignore module.exports = exports['default'];
import React from 'react' import { Editor } from 'slate' import {ย observer } from 'mobx-react'; import Popover from 'react-popover'; import classnames from 'classnames' import { Icon, noop } from '../helpers'; import { } from './styles.scss'; import schema from './schema' const markIcons = [ ['bold', 'bold'], ['code', 'code'], ['italic', 'italic'], ['underlined', 'underline'], ]; const blockIcons = [ ['blockquote', 'quote-left'], ['heading', 'header'] ]; const generateButtons = (onClick = noop, isActive = noop) => ([type, icon], i) => ( <MarkButton key={i} icon={icon} isActive={isActive(type)} onClick={() => onClick(type)} /> ); const hasType = set => type => set.some(entry => entry.type === type); const MarkBar = ({ isOpen, position, selectionMarks, selectionBlocks, onClickMark = noop, onClickBlock = noop, }) => { const popoverBody = ( <div className="popover-content"> <div className="icon-group mark-icons"> {markIcons.map(generateButtons(onClickMark, hasType(selectionMarks)))} </div> { true && <div className="icon-group block-icons"> {blockIcons.map(generateButtons(onClickBlock, hasType(selectionBlocks)))} </div> } </div> ); return ( <Popover isOpen={isOpen} body={popoverBody}> <span className="popover-dummy" style={position} /> </Popover> ); }; const MarkButton = ({ icon, onClick = noop, isActive }) => ( <span onMouseDown={e => e.preventDefault() || onClick() }> <Icon className={classnames('mark-icon', { 'active': isActive })} type={icon} /> </span> ); const MediaIcons = ({ selectionPosition = { top: -100 }, isExpanded, onClickExpand = noop, onClickMediaIcon = noop, icons }) => ( <div className={classnames('media-icons', { 'is-expanded': isExpanded })} style={{top: selectionPosition.top }}> <span onClick={e => e.preventDefault() ||ย onClickExpand()}> <Icon className="expand-button" type="plus-circle" /> </span> </div> ); @observer export default class Main extends React.PureComponent { onPaste = (e, { text }, state) => { store.doMaybeInsertLink(text); } getOverlay = () => { const { store } = this.props; const { isBlurred, isCollapsed, startBlock, endBlock } = store.slateState; const { selectionPosition } = store; return ( <div className="overlay"> <MarkBar isOpen={!isBlurred && !isCollapsed} position={selectionPosition} selectionMarks={store.slateState.marks} selectionBlocks={store.slateState.blocks} onClickMark={store.doToggleMark} onClickBlock={store.doSetBlockType} /> </div> ) } render() { const { store } = this.props; return ( <div className="container"> { this.getOverlay() } <div className="row instructions"> <h1 className="col-sm-12">How to</h1> <p className="col-sm-12">Mark text to show the hovering menu. Paste a link to create a preview.</p> </div> <div className="row"> <div className="editor-container" > <Editor schema={schema} state={store.slateState} onChange={store.doUpdateSlateState} onPaste={this.onPaste} onKeyDown={this.onKeyDown} /> </div> </div> </div> ); } }
/** * Module dependencies. */ var express = require('express'); var compress = require('compression'); var session = require('express-session'); var bodyParser = require('body-parser'); var logger = require('morgan'); var errorHandler = require('errorhandler'); var lusca = require('lusca'); var dotenv = require('dotenv'); var MongoStore = require('connect-mongo/es5')(session); var flash = require('express-flash'); var path = require('path'); var mongoose = require('mongoose'); var passport = require('passport'); var expressValidator = require('express-validator'); var sass = require('node-sass-middleware'); var multer = require('multer'); var upload = multer({ dest: path.join(__dirname, 'uploads') }); //ROSS CODE var methodOverride = require('method-override'); /** * Load environment variables from .env file, where API keys and passwords are configured. * * Default path: .env (You can remove the path argument entirely, after renaming `.env.example` to `.env`) */ dotenv.load({ path: '.env.example' }); /** * Controllers (route handlers). */ var homeController = require('./controllers/home'); var userController = require('./controllers/user'); var apiController = require('./controllers/api'); var contactController = require('./controllers/contact'); //Added Code ************ var nodejsController = require('./controllers/nodejs'); var expressjsController = require('./controllers/expressjs'); var mongodbController = require('./controllers/mongodb'); var classcatalogController = require('./controllers/classcatalog/classcatalog'); var studentsController = require('./controllers/classcatalog/students'); var professorsController = require('./controllers/classcatalog/professors'); var sectionsController = require('./controllers/classcatalog/sections'); var coursesController = require('./controllers/classcatalog/courses'); var bootstrapController = require('./controllers/bootstrap'); /** * API keys and Passport configuration. */ var passportConfig = require('./config/passport'); /** * Create Express server. */ var app = express(); /** * Connect to MongoDB. */ mongoose.connect(process.env.MONGODB || process.env.MONGOLAB_URI); mongoose.connection.on('error', function() { console.log('MongoDB Connection Error. Please make sure that MongoDB is running.'); process.exit(1); }); /** * Express configuration. */ app.set('port', process.env.PORT || 3000); app.set('views', path.join(__dirname, 'views')); app.set('view engine', 'jade'); app.use(compress()); app.use(sass({ src: path.join(__dirname, 'public'), dest: path.join(__dirname, 'public'), sourceMap: true })); app.use(logger('dev')); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(expressValidator()); app.use(session({ resave: true, saveUninitialized: true, secret: process.env.SESSION_SECRET, store: new MongoStore({ url: process.env.MONGODB || process.env.MONGOLAB_URI, autoReconnect: true }) })); app.use(passport.initialize()); app.use(passport.session()); app.use(flash()); app.use(function(req, res, next) { if (req.path === '/api/upload') { next(); } else { lusca.csrf()(req, res, next); } }); app.use(lusca.xframe('SAMEORIGIN')); app.use(lusca.xssProtection(true)); app.use(function(req, res, next) { res.locals.user = req.user; next(); }); app.use(function(req, res, next) { // After successful login, redirect back to /api, /contact or / if (/(api)|(contact)|(^\/$)/i.test(req.path)) { req.session.returnTo = req.path; } next(); }); app.use(express.static(path.join(__dirname, 'public'), { maxAge: 31557600000 })); //ADDED CODE app.use(methodOverride('_method')); /** * Primary app routes. */ app.get('/', homeController.index); app.get('/login', userController.getLogin); app.post('/login', userController.postLogin); app.get('/logout', userController.logout); app.get('/forgot', userController.getForgot); app.post('/forgot', userController.postForgot); app.get('/reset/:token', userController.getReset); app.post('/reset/:token', userController.postReset); app.get('/signup', userController.getSignup); app.post('/signup', userController.postSignup); app.get('/contact', contactController.getContact); app.post('/contact', contactController.postContact); app.get('/account', passportConfig.isAuthenticated, userController.getAccount); app.post('/account/profile', passportConfig.isAuthenticated, userController.postUpdateProfile); app.post('/account/password', passportConfig.isAuthenticated, userController.postUpdatePassword); app.post('/account/delete', passportConfig.isAuthenticated, userController.postDeleteAccount); app.get('/account/unlink/:provider', passportConfig.isAuthenticated, userController.getOauthUnlink); /** * ADDED CODE ********************** */ app.get('/nodejs', nodejsController.index); app.get('/expressjs', expressjsController.index); app.get('/mongodb', mongodbController.index); app.get('/bootstrap', bootstrapController.index); app.get('/classcatalog/index', classcatalogController.index); app.get('/classcatalog/sections', sectionsController.index); app.get('/classcatalog/createsection', sectionsController.create); app.get('/classcatalog/professors', professorsController.index); app.get('/classcatalog/createprofessor', professorsController.create); app.post('/classcatalog/createprofessor', professorsController.post); app.get('/classcatalog/courses', coursesController.index); app.get('/classcatalog/createcourse', coursesController.create); app.post('/classcatalog/createcourse', coursesController.post); app.get('/classcatalog/students', studentsController.index); app.get('/classcatalog/createstudent', studentsController.create); app.post('/classcatalog/createstudent', studentsController.post); /** * API examples routes. */ app.get('/api', apiController.getApi); app.get('/api/lastfm', apiController.getLastfm); app.get('/api/nyt', apiController.getNewYorkTimes); app.get('/api/aviary', apiController.getAviary); app.get('/api/steam', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.getSteam); app.get('/api/stripe', apiController.getStripe); app.post('/api/stripe', apiController.postStripe); app.get('/api/scraping', apiController.getScraping); app.get('/api/twilio', apiController.getTwilio); app.post('/api/twilio', apiController.postTwilio); app.get('/api/clockwork', apiController.getClockwork); app.post('/api/clockwork', apiController.postClockwork); app.get('/api/foursquare', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.getFoursquare); app.get('/api/tumblr', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.getTumblr); app.get('/api/facebook', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.getFacebook); app.get('/api/github', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.getGithub); app.get('/api/twitter', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.getTwitter); app.post('/api/twitter', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.postTwitter); app.get('/api/venmo', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.getVenmo); app.post('/api/venmo', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.postVenmo); app.get('/api/linkedin', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.getLinkedin); app.get('/api/instagram', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.getInstagram); app.get('/api/yahoo', apiController.getYahoo); app.get('/api/paypal', apiController.getPayPal); app.get('/api/paypal/success', apiController.getPayPalSuccess); app.get('/api/paypal/cancel', apiController.getPayPalCancel); app.get('/api/lob', apiController.getLob); app.get('/api/bitgo', apiController.getBitGo); app.post('/api/bitgo', apiController.postBitGo); app.get('/api/upload', apiController.getFileUpload); app.post('/api/upload', upload.single('myFile'), apiController.postFileUpload); app.get('/api/pinterest', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.getPinterest); app.post('/api/pinterest', passportConfig.isAuthenticated, passportConfig.isAuthorized, apiController.postPinterest); /** * OAuth authentication routes. (Sign in) */ app.get('/auth/instagram', passport.authenticate('instagram')); app.get('/auth/instagram/callback', passport.authenticate('instagram', { failureRedirect: '/login' }), function(req, res) { res.redirect(req.session.returnTo || '/'); }); app.get('/auth/facebook', passport.authenticate('facebook', { scope: ['email', 'user_location'] })); app.get('/auth/facebook/callback', passport.authenticate('facebook', { failureRedirect: '/login' }), function(req, res) { res.redirect(req.session.returnTo || '/'); }); app.get('/auth/github', passport.authenticate('github')); app.get('/auth/github/callback', passport.authenticate('github', { failureRedirect: '/login' }), function(req, res) { res.redirect(req.session.returnTo || '/'); }); app.get('/auth/google', passport.authenticate('google', { scope: 'profile email' })); app.get('/auth/google/callback', passport.authenticate('google', { failureRedirect: '/login' }), function(req, res) { res.redirect(req.session.returnTo || '/'); }); app.get('/auth/twitter', passport.authenticate('twitter')); app.get('/auth/twitter/callback', passport.authenticate('twitter', { failureRedirect: '/login' }), function(req, res) { res.redirect(req.session.returnTo || '/'); }); app.get('/auth/linkedin', passport.authenticate('linkedin', { state: 'SOME STATE' })); app.get('/auth/linkedin/callback', passport.authenticate('linkedin', { failureRedirect: '/login' }), function(req, res) { res.redirect(req.session.returnTo || '/'); }); /** * OAuth authorization routes. (API examples) */ app.get('/auth/foursquare', passport.authorize('foursquare')); app.get('/auth/foursquare/callback', passport.authorize('foursquare', { failureRedirect: '/api' }), function(req, res) { res.redirect('/api/foursquare'); }); app.get('/auth/tumblr', passport.authorize('tumblr')); app.get('/auth/tumblr/callback', passport.authorize('tumblr', { failureRedirect: '/api' }), function(req, res) { res.redirect('/api/tumblr'); }); app.get('/auth/venmo', passport.authorize('venmo', { scope: 'make_payments access_profile access_balance access_email access_phone' })); app.get('/auth/venmo/callback', passport.authorize('venmo', { failureRedirect: '/api' }), function(req, res) { res.redirect('/api/venmo'); }); app.get('/auth/steam', passport.authorize('openid', { state: 'SOME STATE' })); app.get('/auth/steam/callback', passport.authorize('openid', { failureRedirect: '/login' }), function(req, res) { res.redirect(req.session.returnTo || '/'); }); app.get('/auth/pinterest', passport.authorize('pinterest', { scope: 'read_public write_public' })); app.get('/auth/pinterest/callback', passport.authorize('pinterest', { failureRedirect: '/login' }), function(req, res) { res.redirect('/api/pinterest'); }); /** * Error Handler. */ app.use(errorHandler()); /** * Start Express server. */ app.listen(app.get('port'), function() { console.log('Express server listening on port %d in %s mode', app.get('port'), app.get('env')); }); module.exports = app;
'use strict'; /** * * @param {number} wordsPerMinute * @returns {Function} */ module.exports = function fromWords(wordsPerMinute){ wordsPerMinute = wordsPerMinute || 200; /** * @returns {number} Time needed to read these words, in milliseconds */ return function (wordCount){ var minutes = wordCount / wordsPerMinute; return Math.ceil(minutes * 60 * 1000); }; };
var util = require('util'); var Stream = require('stream'); var Buffer = require('buffer').Buffer; /** * A Readable stream for a string or Buffer. * * This works for both strings and Buffers. */ function StringReader(str) { this.data = str; } util.inherits(StringReader, Stream); module.exports = StringReader; StringReader.prototype.open = StringReader.prototype.resume = function () { if (this.encoding && Buffer.isBuffer(this.data)) { this.emit('data', this.data.toString(this.encoding)); } else { this.emit('data', this.data); } this.emit('end'); this.emit('close'); } StringReader.prototype.setEncoding = function (encoding) { this.encoding = encoding; } StringReader.prototype.pause = function () { } StringReader.prototype.destroy = function () { delete this.data; }
import Angular from "angular"; import HomeRoute from "./home.route"; const module = Angular.module('swamp.home', []) .config(HomeRoute); export default module.name;
var assert = require( 'assert' ); module.exports = { description: 'skips a dead branch', code: function ( code ) { assert.equal( code.indexOf( 'obj.foo = function' ), -1, code ); } }
/*! * UI development toolkit for HTML5 (OpenUI5) * (c) Copyright 2009-2017 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ sap.ui.define(['jquery.sap.global', './ListItemBaseRenderer', 'sap/ui/core/Renderer'], function(jQuery, ListItemBaseRenderer, Renderer) { "use strict"; /** * ObjectListItem renderer. * @namespace */ var ObjectListItemRenderer = Renderer.extend(ListItemBaseRenderer); /** * Renders the HTML for single line of Attribute and Status. * * @param {sap.ui.core.RenderManager} * rm The RenderManager that can be used for writing to the render output buffer * @param {sap.m.ObjectListItem} * oLI An object to be rendered * @param {sap.m.ObjectAttribute} * oAttribute An attribute to be rendered * @param {sap.m.ObjectStatus} * oStatus A status to be rendered */ ObjectListItemRenderer.renderAttributeStatus = function(rm, oLI, oAttribute, oStatus) { if (!oAttribute && !oStatus || (oAttribute && oAttribute._isEmpty() && oStatus && oStatus._isEmpty())) { return; // nothing to render } rm.write("<div"); // Start attribute row container rm.addClass("sapMObjLAttrRow"); rm.writeClasses(); rm.write(">"); if (oAttribute && !oAttribute._isEmpty()) { rm.write("<div"); rm.addClass("sapMObjLAttrDiv"); // Add padding to push attribute text down since it will be raised up due // to markers height if (oStatus && (!oStatus._isEmpty())) { if (oStatus instanceof Array) { rm.addClass("sapMObjAttrWithMarker"); } } rm.writeClasses(); if (!oStatus || oStatus._isEmpty()) { rm.addStyle("width", "100%"); rm.writeStyles(); } rm.write(">"); rm.renderControl(oAttribute); rm.write("</div>"); } if (oStatus && !oStatus._isEmpty()) { rm.write("<div"); rm.addClass("sapMObjLStatusDiv"); // Object marker icons (flag, favorite) are passed as an array if (oStatus instanceof Array && oStatus.length > 0) { rm.addClass("sapMObjStatusMarker"); } rm.writeClasses(); if (!oAttribute || oAttribute._isEmpty()) { rm.addStyle("width", "100%"); rm.writeStyles(); } rm.write(">"); if (oStatus instanceof Array) { while (oStatus.length > 0) { rm.renderControl(oStatus.shift()); } } else { rm.renderControl(oStatus); } rm.write("</div>"); } rm.write("</div>"); // Start attribute row container }; /** * Renders the HTML for the given control, using the provided * {@link sap.ui.core.RenderManager}. * * @param {sap.ui.core.RenderManager} * oRenderManager The RenderManager that can be used for writing to the * Render-Output-Buffer * @param {sap.ui.core.Control} * oControl An object representation of the control that should be * rendered */ ObjectListItemRenderer.renderLIAttributes = function(rm, oLI) { rm.addClass("sapMObjLItem"); rm.addClass("sapMObjLListModeDiv"); }; ObjectListItemRenderer.renderLIContent = function(rm, oLI) { var oObjectNumberAggregation = oLI.getAggregation("_objectNumber"), sTitleDir = oLI.getTitleTextDirection(), sIntroDir = oLI.getIntroTextDirection(); // Introductory text at the top of the item, like "On behalf of Julie..." if (oLI.getIntro()) { rm.write("<div"); rm.addClass("sapMObjLIntro"); rm.writeClasses(); rm.writeAttribute("id", oLI.getId() + "-intro"); rm.write(">"); rm.write("<span"); //sets the dir attribute to "rtl" or "ltr" if a direction //for the intro text is provided explicitly if (sIntroDir !== sap.ui.core.TextDirection.Inherit) { rm.writeAttribute("dir", sIntroDir.toLowerCase()); } rm.write(">"); rm.writeEscaped(oLI.getIntro()); rm.write("</span>"); rm.write("</div>"); } // Container for fields placed on the top half of the item, below the intro. This // includes title, number, and number units. rm.write("<div"); // Start Top row container rm.addClass("sapMObjLTopRow"); rm.writeClasses(); rm.write(">"); if (!!oLI.getIcon()) { rm.write("<div"); rm.addClass("sapMObjLIconDiv"); rm.writeClasses(); rm.write(">"); rm.renderControl(oLI._getImageControl()); rm.write("</div>"); } // Container for a number and a units qualifier. rm.write("<div"); // Start Number/units container rm.addClass("sapMObjLNumberDiv"); rm.writeClasses(); rm.write(">"); if (oObjectNumberAggregation && oObjectNumberAggregation.getNumber()) { oObjectNumberAggregation.setTextDirection(oLI.getNumberTextDirection()); rm.renderControl(oObjectNumberAggregation); } rm.write("</div>"); // End Number/units container // Title container displayed to the left of the number and number units container. rm.write("<div"); // Start Title container rm.addStyle("display","-webkit-box"); rm.addStyle("overflow","hidden"); rm.writeStyles(); rm.write(">"); var oTitleText = oLI._getTitleText(); if (oTitleText) { //sets the text direction of the title, //by delegating the RTL support to sap.m.Text oTitleText.setTextDirection(sTitleDir); oTitleText.setText(oLI.getTitle()); oTitleText.addStyleClass("sapMObjLTitle"); rm.renderControl(oTitleText); } rm.write("</div>"); // End Title container rm.write("</div>"); // End Top row container if (!(sap.ui.Device.browser.internet_explorer && sap.ui.Device.browser.version < 10)) { rm.write("<div style=\"clear: both;\"></div>"); } // Bottom row container. if (oLI._hasBottomContent()) { rm.write("<div"); // Start Bottom row container rm.addClass("sapMObjLBottomRow"); rm.writeClasses(); rm.write(">"); var aAttribs = oLI._getVisibleAttributes(); var statuses = []; var markers = oLI._getVisibleMarkers(); markers._isEmpty = function() { return !(markers.length); }; if (!markers._isEmpty()) {// add markers only if the array is not empty, otherwise it brakes the layout BCP: 1670363254 statuses.push(markers); } statuses.push(oLI.getFirstStatus()); statuses.push(oLI.getSecondStatus()); while (aAttribs.length > 0) { this.renderAttributeStatus(rm, oLI, aAttribs.shift(), statuses.shift()); } while (statuses.length > 0) { this.renderAttributeStatus(rm, oLI, null, statuses.shift()); } rm.write("</div>"); // End Bottom row container } }; /** * Gets ObjectListItem`s inner nodes IDs, later used in aria labelledby attribute. * * @param {sap.m.ObjectListItem} * oLI An object representation of the control * @returns {String} ObjectListItem`s inner nodes IDs */ ObjectListItemRenderer.getAriaLabelledBy = function(oLI) { var aLabelledByIds = [], oFirstStatus = oLI.getFirstStatus(), oSecondStatus = oLI.getSecondStatus(); if (oLI.getIntro()) { aLabelledByIds.push(oLI.getId() + "-intro"); } if (oLI.getTitle()) { aLabelledByIds.push(oLI.getId() + "-titleText"); } if (oLI.getNumber()) { aLabelledByIds.push(oLI.getId() + "-ObjectNumber"); } if (oLI.getAttributes()) { oLI.getAttributes().forEach(function(attribute) { if (!attribute._isEmpty()) { aLabelledByIds.push(attribute.getId()); } }); } if (oFirstStatus && !oFirstStatus._isEmpty()) { aLabelledByIds.push(oFirstStatus.getId()); } if (oSecondStatus && !oSecondStatus._isEmpty()) { aLabelledByIds.push(oSecondStatus.getId()); } if (oLI.getMarkers()) { oLI.getMarkers().forEach(function(marker) { aLabelledByIds.push(marker.getId() + "-text"); }); } return aLabelledByIds.join(" "); }; return ObjectListItemRenderer; }, /* bExport= */ true);
/* * grunt-contrib-sass * http://gruntjs.com/ * * Copyright (c) 2014 Sindre Sorhus, contributors * Licensed under the MIT license. */ 'use strict'; module.exports = function (grunt) { grunt.initConfig({ jshint: { options: { jshintrc: '.jshintrc' }, all: [ 'Gruntfile.js', 'tasks/*.js', '<%= nodeunit.tests %>' ] }, clean: { test: ['tmp'] }, htmlmin: { options: { removeComments: true, collapseWhitespace: true }, compile: { files: { 'tmp/test.html': ['test/fixtures/test.html'] } }, empty: { files: { 'tmp/idontexist.html': ['test/fixtures/idontexist.html'] } } }, nodeunit: { tests: ['test/*_test.js'] } }); grunt.loadTasks('tasks'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-nodeunit'); grunt.loadNpmTasks('grunt-contrib-internal'); grunt.registerTask('test', ['jshint', 'clean', 'htmlmin', 'nodeunit']); grunt.registerTask('default', ['test', 'build-contrib']); };
var jr = require( "jackrabbit" ); var sp = require( "serialport" ); var loggly = require( "loggly" ); var config = require( "./configuration" ); exports.jackrabbit = function () { return jr( config.rabbitURL, 1 ); }; exports.logger = function ( tag ) { return loggly.createClient( { token: config.logglyToken, subdomain: config.logglySubdomain, tags: [ tag ] } ); }; exports.serialport = function () { return new sp.SerialPort( config.serialAddress, { baudrate: config.serialRate, parser: sp.parsers.readline( "\n" ) } ); };
const { promises: fs } = require('fs'); const MILLISECONDS = 1000; /** * Check to see if file has expired based on the given TTL. * * @example checkCacheExpiry('temp/cache.txt', 1800).catch(() => console.log('Cache has expired.')); * @param {String} path File path to check. * @param {Number} ttl TTL (Time to live) in seconds. * @return {Object} Promise * @public */ const checkCacheExpiry = (path, ttl) => fs.stat(path).then(stats => { const ttlInMilliseconds = ttl * MILLISECONDS; if (new Date(stats.mtime).getTime() + ttlInMilliseconds < Date.now()) { return Promise.reject(new Error('Cache has expired.')); } return stats; }); module.exports = checkCacheExpiry;
// delete cookie en cas de bug // document.cookie = "active=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;"; // Fonction qui retourne la valeur du cookie que l'on recherche function getCookie(cname) { var name = cname + "="; var decodedCookie = decodeURIComponent(document.cookie); var ca = decodedCookie.split(';'); for(var i = 0; i <ca.length; i++) { var c = ca[i]; while (c.charAt(0) == ' ') { c = c.substring(1); } if (c.indexOf(name) == 0) { return c.substring(name.length, c.length); } } return ""; } if(document.cookie.indexOf("active=") >= 0){ // On rรฉcupรจre l'id de la section qui รฉtait active var id_section_active = getCookie("active"); // On vรฉrifie si la section existe dans le document var id_section_found = $(id_section_active).length >= 0 ? true : false; if(id_section_found){ // On enlรจve la classe active ร  toutes les sections $(".section").each(function(){ var active = $(this).hasClass("active"); if(active){ $(this).removeClass( 'active' ); } }); // On rajoute la classe active ร  la section qui รฉtait active avant le refresh $(id_section_active).addClass('active'); // On met la nav du menu active en consรฉquence $('li.nav-item > a').not(".btn").each(function(){ $(this).parent().removeClass( 'active' ); if($(this).attr('href') == id_section_active){ $(this).parent().addClass('active'); } }); } } // On cache toutes les sections qui ne possรจde pas la classe active $(".section").each(function(){ var active = $(this).hasClass("active"); if(!active){ $(this).hide(); } }); // global. currently active menu item var current_item = 0; var section_hide_time = 50; var section_show_time = 50; //Switch section $("a", 'nav').not(".btn").click(function() { var new_section = $( $(this).attr('href') ); $('a', 'nav').parent().removeClass( 'active' ); $(this).parent().addClass( 'active' ); $('.section:visible').fadeOut( section_hide_time, function() { new_section.addClass('active'); new_section.fadeIn( section_show_time ); var new_section_id = "#" + new_section.attr('id'); document.cookie = "active=" + new_section_id; }); }); // Incremente le compteur du bootcampomรจtre $(".incremente").click(function() { if(parseInt($(".compteur_bootcamp").text()) < 100){ var objdata = "incremente"; $.ajax({ url: "./update_bootcamp.php", type: 'POST', data: { type: "incremente"}, success:function() { var compteur = parseInt($(".compteur_bootcamp").text()) + 1; $(".compteur_bootcamp").text(compteur); } }); } }); // Decremente le compteur du bootcampomรจtre $(".decremente").click(function() { if(parseInt($(".compteur_bootcamp").text()) > 0){ var objdata = "decremente"; $.ajax({ url: "./update_bootcamp.php", type: 'POST', data: { type: "decremente"}, success:function() { var compteur = parseInt($(".compteur_bootcamp").text()) - 1; $(".compteur_bootcamp").text(compteur); } }); } }); // Sรฉlรฉctionne la checkbox quand on clique sur une ligne du tableau des dรฉmos $('.table_demos tr').click(function(e){ // Checkbox ร  cocher ou ร  dรฉcocher var input = $(this).children('td').children('.form-group').children('input'); var element = e.target||event.srcElement; if(element.name !== input.attr('name')){ // Si la checkbox est dรฉjร  cochรฉ on la dรฉcoche if(input.is(':checked')){ input.prop('checked', false); } else{ // Sinon on la coche input.prop('checked', true); } } }); // affiche la div d'aide quand on passe la souris sur le logo de l'aide (page demos) $('.img_aide').hover(function(){ if($(".bloc_help").css('visibility') == "hidden"){ $(".bloc_help").css('visibility', 'visible'); }else{ $(".bloc_help").css('visibility', 'hidden'); } }); // Copie le lien de la demos dans le presse papier var clip = new Clipboard('.btn'); clip.on('success', function(e) { $('.copied').show(); $('.copied').fadeOut(1000); }); // Evite le rechargement de la page quand on clique sur le bouton copier coller $('.copy-paste').click(function(e){ e.preventDefault(); return 0; }); // Switch section // $("a", 'nav').not(".btn").click(function() // { // if( ! $(this).hasClass('active') ) { // current_item = this; // // close all visible divs with the class of .section // $('.section:visible').fadeOut( section_hide_time, function() { // $('a', 'nav').removeClass( 'active' ); // $(current_item).addClass( 'active' ); // var new_section = $( $(current_item).attr('href') ); // new_section.fadeIn( section_show_time ); // } ); // } // return false; // });
/** * Created by michaelsilvestre on 1/03/15. */ var crypto = require('crypto'); function genUuid(callback) { if (typeof(callback) !== 'function') { return uuidFromBytes(crypto.randomBytes(16)); } crypto.randomBytes(16, function(err, rnd) { if (err) return callback(err); callback(null, uuidFromBytes(rnd)); }); } function uuidFromBytes(rnd) { rnd[6] = (rnd[6] & 0x0f) | 0x40; rnd[8] = (rnd[8] & 0x3f) | 0x80; rnd = rnd.toString('hex').match(/(.{8})(.{4})(.{4})(.{4})(.{12})/); rnd.shift(); return rnd.join('-'); } module.exports = genUuid;
var http = require('http'); var fs = require('fs'); var formidable = require("formidable"); var util = require('util'); var processAllFieldsOfTheForm = function (req, res) { var form = new formidable.IncomingForm(); form.parse(req, function (err, fields, files) { res.writeHead(200, { 'content-type': 'text/html' }); var text = fieldsToHtmlIfKeys(fields); res.write(text); res.end(`<pre>${util.inspect({ fields: fields, files: files })}</pre>`); }); }; var fieldsToHtmlIfKeys = function (fields) { if (!fields) return; var text = ''; var borderStyle = ''; if (fields.color) { text += `<div style="color:${fields.color};">`; borderStyle = `border: 5px ${fields['border-style'] || 'inset'} ${fields.color};`; } if (fields.name) { var tag = fields.tag || 'h1'; text += `<${tag}>${fields.name}</${tag}>`; } if (fields.color) { text += '</div>'; } if (fields.image) { text += `<br /><div><img src=${fields.image} style="width:33%; ${borderStyle}"/></div><br /><br /><br />`; } return text; } var server = http.createServer(processAllFieldsOfTheForm); var port = process.env.PORT || 3000; server.listen(port); console.log(`Server listening on ${port}`);
var classMensajes = [ [ "Mensajes", "classMensajes.html#a35ea792bfc9e0906a1f3ad5520be4735", null ], [ "Mensajes", "classMensajes.html#a024b1e59811c21e05e2a5fbe8f8ddfd2", null ], [ "~Mensajes", "classMensajes.html#a7f21f5e74c8b485187e83241e8d1c10e", null ], [ "agregarMensaje", "classMensajes.html#ac9cef976098cfebde8e682bdd91d6695", null ], [ "getEmisor", "classMensajes.html#aafaa164b11c9afd52a27bd64be3f847e", null ], [ "getMensaje", "classMensajes.html#a635b359e1f79ffcf0ecd3931524f4df7", null ], [ "getTamanio", "classMensajes.html#abb73e0ae442301ff55f77121432572dc", null ], [ "toString", "classMensajes.html#a1b69bfdd70493bfa3e5fde215e881636", null ] ];
/*------------------------------------------------------------------------------ Function: eCSStender.css3-selectors.js Author: Aaron Gustafson (aaron at easy-designs dot net) Creation Date: 2009-09-17 Version: 0.3 Homepage: http://github.com/easy-designs/eCSStender.css3-selectors.js License: MIT License Note: If you change or improve on this script, please let us know by emailing the author (above) with a link to your demo page. ------------------------------------------------------------------------------*/ (function(e){ if ( typeof e == 'undefined' ){ return; } var // aliases $ = e.methods.findBySelector, supported = e.isSupported, embedCSS = e.embedCSS, style = e.applyWeightedStyle, embed = function( selector, properties, medium ) { var style_block = EMPTY, prop; for ( prop in properties ) { if ( e.isInheritedProperty( properties, prop ) ) { continue; }; style_block += prop + COLON + properties[prop] + SEMICOL; } if ( style_block != EMPTY ) { embedCSS( selector + CURLY_O + style_block + CURLY_C, medium ); } }, inline = function( selector, properties, medium, specificity ) { if ( notScreen( medium ) ){ return; } try { var $els = $( selector ), i = $els.length; while ( i-- ) { style( $els[i], properties, specificity ); } } catch(e) { throw new Error( LIB_ERROR + selector ); } }, eFunc = function(){}, // methods notScreen = function( medium ) { return medium != 'screen'; }, cleanNth = function( selector ) { return selector.replace( re_nth, '$1$2$3$4$5' ); }, // Event stuff // Based on John Resig's work addEvent = function( el, evt, handler ) { if ( el.addEventListener ) { addEvent = function( el, evt, handler ) { el.addEventListener( evt, handler, false ); }; } else { addEvent = function( el, evt, handler ) { var E = 'e'; el[E+evt+handler] = handler; el[evt+handler] = function(){ var e = window.event; e.target = e.srcElement; e.preventDefault = function(){ this.returnValue = false; }; e.stopPropagation = function(){ this.cancelBubble = true; }; el[E+evt+handler]( e ); }; el.attachEvent( 'on'+evt, el[evt+handler] ); }; } addEvent( el, evt, handler ); }, // strings EASY = 'net.easy-designs.', SELECTOR = 'selector', PROPERTIES = 'properties', SPECIFICITY = 'specificity', CLICK = 'click', EVERYTHING = '*', EMPTY = '', CURLY_O = '{', CURLY_C = '}', PAREN_O = '(', PAREN_C = ')', COLON = ':', SEMICOL = ';', HYPHEN = '-', DOT = '.', LIB_ERROR = 'Your chosen selector library does not support this selector: ', // Regular Expressions re_nth = /(.*\()\s*(?:(\d+n?|odd|even)\s*(\+|-)?\s*(\d+)?)\s*(\).*)/g, // elements div = document.createElement('div'), para = document.createElement('p'); // define our selector engine or die if ( ! ( $ instanceof Function ) ) { throw new Error('eCSStender.methods.findBySelector is not defined. eCSStender.css3-selectors.js is quitting.'); } // CLASSES // compound class selection (no other class selections seem to be an issue) e.register( { fingerprint: EASY + 'compound-class-selector', selector: /(?:\.\S+){2,}/, test: function(){ // the markup var d = div.cloneNode(true), p = para.cloneNode(true); p.className = 'foo'; d.appendChild( p ); // the test return ( supported( SELECTOR, 'div p.bar.foo', d, p ) ); } }, EVERYTHING, function( selector, properties, medium, specificity ){ // we need to invert the selection and get anything without the first class var regex = /((?:\.\S+){2,})/, classes = selector.replace( regex, '$1' ), false_positive, matches, j; // get the classes classes = classes.split('.'); classes.shift(); false_positive = classes.pop(); // re-apply all affected styles matches = e.lookup( { selector: new RegExp( '\\.' + false_positive ), specificity: specificity, media: medium }, EVERYTHING ); for ( j=0; j<matches.length; j++ ) { inline( matches[j][SELECTOR], matches[j][PROPERTIES], medium, matches[j][SPECIFICITY] ); } } ); // PSEUDO CLASSES // attribute selectors (function(){ var selectors = ['div p[title]', // attribute 'div p[title="a b-c"]', // attribute value 'div p[title*=a]', // substring 'div p[title~=a]', // contains 'div p[title^=a]', // starts with 'div p[title$=c]', // ends with 'div p[title|=c]'], // part of hyphen-separated list i = selectors.length, d = div.cloneNode(true), p = para.cloneNode(true); p.setAttribute('title','a b-c'); d.appendChild( p ); while ( i-- ) { (function(selector){ e.register( { fingerprint: EASY + 'attribute-selector-' + i, selector: /\[.*\]/, test: function(){ return ! supported( SELECTOR, selector, d, p ); } }, EVERYTHING, inline ); })(selectors[i]); } })(); // :root (function(){ var re_root = /^\s?(?:html)?:root/, HTML = 'html'; function normal( selector, properties, medium, specificity ) { if ( notScreen(medium) || ! selector.match( re_root ) ){ return; } inline( selector, properties, medium, specificity); } function modified( selector, properties, medium, specificity ) { if ( notScreen(medium) || ! selector.match( re_root ) ){ return; } selector = selector.replace( re_root, HTML ); inline( selector, properties, medium, specificity); } e.register( { fingerprint: EASY + 'root', selector: /:root/, test: function(){ // the markup html = document.getElementsByTagName(HTML)[0]; // the test return ( ! supported( SELECTOR, ':root', false, html ) ); } }, EVERYTHING, function( selector, properties, medium, specificity ){ if ( notScreen(medium) ){ return; } var func = normal; try { $( selector ); } catch(e) { func = modified; } func( selector, properties, medium, specificity ); return func; } ); })(); // nth-child e.register( { fingerprint: EASY + 'nth-child', selector: /:nth-child\(\s*(?:even|odd|[+-]?\d+|[+-]?\d*?n(?:\s*[+-]\s*\d*)?)\s*\)/, test: function(){ // the markup var d = div.cloneNode(true), p = para.cloneNode(true); d.appendChild( p ); // the test return ( ! supported( SELECTOR, 'div p:nth-child( 2n + 1 )', d, p ) ); } }, EVERYTHING, function( selector, properties, medium, specificity ) { selector = cleanNth( selector ); // secondary test to see if the browser just doesn't like spaces in the parentheses var calc = 'p:nth-child(2n+1)', d = div.cloneNode(true), p = para.cloneNode(true), func = inline; d.appendChild( p ); // embedding is the way to go if ( ( supported( SELECTOR, 'p:nth-child(odd)', d, p ) && ! supported( SELECTOR, calc, d, p ) && selector.match( /:nth-child\(\s*(?:even|odd)\s*\)/ ) != null ) || supported( SELECTOR, calc, d, p ) ) { func = embed; } func( selector, properties, medium, specificity ); return func; } ); // :nth-last-child e.register( { fingerprint: EASY + 'nth-last-child', selector: /:nth-last-child\(\s*(?:even|odd|[+-]?\d*?|[+-]?\d*?n(?:\s*[+-]\s*\d*?)?)\s*\)/, test: function(){ // the markup var d = div.cloneNode(true), p = para.cloneNode(true); d.appendChild( p ); // the test return ( ! supported( SELECTOR, 'div p:nth-last-child( 2n + 1 )', d, p ) ); } }, EVERYTHING, function( selector, properties, medium, specificity ){ selector = cleanNth( selector ); // secondary test to see if the browser just doesn't like spaces in the parentheses var calc = 'p:nth-last-child(2n+1)', d = div.cloneNode(true), p = para.cloneNode(true), func = inline; d.appendChild( p ); // embedding is the way to go if ( ( supported( SELECTOR, 'p:nth-last-child(odd)', d, p ) && ! supported( SELECTOR, calc, d, p ) && selector.match( /:nth-last-child\(\s*(?:even|odd)\s*\)/ ) != null ) || supported( SELECTOR, calc, d, p ) ) { func = embed; } func( selector, properties, medium, specificity ); return func; } ); // :nth-of-type, :nth-last-of-type e.register( { fingerprint: EASY + 'nth-of-type', selector: /:nth-(?:last-)?of-type\(\s*(?:even|odd|[+-]?\d*?|[+-]?\d*?n(?:\s*[+-]\s*\d*?)?)\s*\)/, test: function(){ // the markup var d = div.cloneNode(true), p = para.cloneNode(true); d.appendChild( p ); // the test return ( ! supported( SELECTOR, 'div p:nth-of-type( 2n + 1 )', d, p ) ); } }, EVERYTHING, inline ); // :(first|last|only)-child (function(){ var selectors = { 'div :first-child': /:first-child/, 'div :last-child': /:last-child/, 'div :only-child': /:only-child/ }, selector, d = div.cloneNode(true), p = para.cloneNode(true); d.appendChild( p ); for ( selector in selectors ) { (function( selector, lookup ){ e.register( { fingerprint: EASY + lookup.toString().replace(/[\/:]/g,''), selector: lookup, test: function(){ return ! supported( SELECTOR, selector, d, p ); } }, EVERYTHING, inline ); })( selector, selectors[selector] ); } })(); // :(first|last|only)-of-type (function(){ var selectors = { 'div p:first-of-type': /:first-of-type/, 'div p:last-of-type': /:last-of-type/, 'div div:only-of-type': /:only-of-type/ }, selector, d = div.cloneNode(true), d2 = div.cloneNode(true), p = para.cloneNode(true), p2 = para.cloneNode(true); d.appendChild( p ); d.appendChild( p2 ); d.appendChild( d2 ); for ( selector in selectors ) { (function( selector, lookup ){ e.register( { fingerprint: EASY + lookup.toString().replace(/[\/:]/g,''), selector: lookup, test: function(){ return ! supported( SELECTOR, selector, d, p ); } }, EVERYTHING, inline ); })( selector, selectors[selector] ); } })(); // :empty/:enabled/:disabled (function(){ var selectors = { 'div input:empty': /:empty/, 'div input:disabled': /:disabled/, 'div input:enabled': /:enabled/ }, selector, inputs, i=0, d = div.cloneNode(true); d.innerHTML = '<input type="text" disabled="disabled"/><input type="text"/>'; inputs = d.getElementsByTagName('input'); for ( selector in selectors ) { (function( selector, lookup ){ var target = inputs[i]; e.register( { fingerprint: EASY + lookup.toString().replace(/[\/:]/g,''), selector: lookup, test: function(){ return ! supported( SELECTOR, selector, d, target ); } }, EVERYTHING, inline ); })( selector, selectors[selector] ); i = i == 1 ? 1 : i + 1; } })(); // :target //(function(){ // var // last_tgt = false, // curr_tgt = false, // curr_el = false, // the_class = e.makeUniqueClass(), // toggle = e.toggleClass; // function target() // { // if ( curr_tgt != last_tgt ){ // if ( curr_el ) // { // toggle( curr_el, the_class ); // } // last_tgt = curr_tgt; // curr_el = document.getElementById( curr_tgt ); // if ( curr_el ) // { // toggle( curr_el, the_class ); // } // } // } // eCSStender.register( // { fingerprint: EASY + 'target', // selector: /:target/, // test: function(){ // // the markup // var // d = div.cloneNode(true), // p = para.cloneNode(true); // d.appendChild( p ); // document.expando = false; // // the test // return ( ! supported( SELECTOR, 'div p, div p:target', d, p ) ); // } // }, // EVERYTHING, // function(){ // curr_tgt = window.location.hash; // target(); // addEvent( document.body, CLICK, function( event ){ // var // el = event.target, // re = /^#(\w+)$/; // if ( el.nodeName.toLowerCase() == 'a' && // el.href && // el.href.match( re ) ) // { // curr_tgt = el.href.replace( re, '$1' ); // target(); // } // }); // function func( selector, properties, medium ) // { // var re = /:target/; // selector = selector.replace( re, the_class ); // embed( selector, properties, medium ); // }; // func( selector, properties, medium ); // return func; // }); //})(); // :lang() e.register( { fingerprint: EASY + 'lang', selector: /:lang\(.*\)/, test: function(){ // the markup var d = div.cloneNode(true), p = para.cloneNode(true); p.setAttribute('lang','en'); d.appendChild( p ); // the test return ( ! supported( 'selector', 'div p:lang(en)', d, p ) ); } }, EVERYTHING, function( selector, properties, medium, specificity ) { var func = inline, $els; // fix for selector engines that don't implement lang() try { $els = $(selector); } catch( e ) { func = function( selector, properties, medium, specificity ) { selector = selector.replace( /:lang\(([^)]*)\)/, '[lang=$1]' ); inline( selector, properties, medium, specificity ); }; } func( selector, properties, medium, specificity ); return func; } ); // :checked (function(){ var the_class = e.makeUniqueClass(), the_regex = /:checked/, classify = function() { var inputs = document.getElementsByTagName('input'), i = inputs.length; while ( i-- ) { if ( inputs[i].checked ) { e.addClass( inputs[i], the_class ); } else { e.removeClass( inputs[i], the_class ); } } }; e.register( { fingerprint: EASY + 'checked', selector: the_regex, test: function(){ var d = div.cloneNode(true), i; d.innerHTML = '<input type="checkbox" checked="checked" />'; i = d.getElementsByTagName('input')[0]; return ! supported( SELECTOR, 'div input:checked', d, i ); } }, EVERYTHING, function( selector, properties, medium, specificity ){ // initialize classify(); // only add the event once addEvent( document.body, CLICK, function( e ){ var el = e.target; if ( el.nodeName.toLowerCase() == 'input' && ( el.getAttribute('type') == 'radio' || el.getAttribute('type') == 'checkbox' ) ) { classify(); } }); // then switch to embed a modified selector function modify( selector, properties, medium, specificity ) { selector = selector.replace( the_regex, DOT + the_class ); embed( selector, properties, medium ); } modify( selector, properties, medium, specificity ); return modify; }); })(); // :first-line/:first-letter/::first-line/::first-letter // how do we handle these? // :before/:after/::before/::after // need a clean element // use element height to determine support // var // d = document.createElement('div'), // p = document.createElement('p'), // s = document.createElement('style'); // d.appendChild(p); // document.body.appendChild(d); // console.log(window.getComputedStyle(d,null).getPropertyValue('height')); // s.appendChild(document.createTextNode('p:after{display:block;content:".";height:10px;}')); // document.getElementsByTagName('head')[0].appendChild(s); // console.log(window.getComputedStyle(d,null).getPropertyValue('height')); // :not e.register( { selector: /:not\([^)]*\)/, test: function(){ // the markup var d = div.cloneNode(true), p = para.cloneNode(true), p2 = para.cloneNode(true); p.setAttribute('id','no'); d.appendChild( p ); d.appendChild( p2 ); // the test return ( ! supported( SELECTOR, 'div p:not(#no)', d, p2 ) ); } }, EVERYTHING, inline ); // adjacent siblings e.register( { selector: function(){ return ( this.match(/\+/) && ! this.match( /:nth-(?:last-)?(?:child|of-type)\(\s*(?:even|odd|[+-]?\d*?|[+-]?\d*?n(?:\s*[+-]\s*\d*?)?)\s*\)/ ) ); }, test: function(){ // the markup var d = div.cloneNode(true), p = para.cloneNode(true), p2 = para.cloneNode(true); d.appendChild( p ); d.appendChild( p2 ); // the test return ( ! supported( SELECTOR, 'div p + p', d, p2 ) ); } }, EVERYTHING, inline ); // general sibling e.register( { selector: /~[^=]/, test: function(){ // the markup var d = div.cloneNode(true), p = para.cloneNode(true), p2 = para.cloneNode(true), p3 = para.cloneNode(true); d.appendChild( p ); d.appendChild( p2 ); d.appendChild( p3 ); // the test return ( ! supported( SELECTOR, 'div p ~ p', d, p3 ) ); } }, EVERYTHING, inline ); })(eCSStender);
import { VIEW, DISPLACEMENT, CATCH, DROP, factory as makeEvent, typeIs } from './events'; import { CARRY, GOTO, factory as makeGoal } from './goals'; import * as actions from './actions'; import { positionString, randomNumber } from './utils'; import Agent from './Agent.js'; import Leaf from './Leaf.js'; import Hole from './Hole.js'; import Rock from './Rock.js'; const containsSome = (square, ...classes) => square.objects.some(obj => classes.some(objClass => obj instanceof objClass)); const distance = (from, to) => Math.sqrt(from.reduce((sum, value, index) => sum + Math.pow(value - to[index], 2), 0)); export default class Ant extends Agent { _getInitialState(){ return { environment: null, position: null, world: {}, carries: null } } _beforeReasoning(){ if(this.state.environment === null) return; const action = actions.factory(actions.OBSERVE); this.state.environment.executeAgentPassiveAction(this, action); } _getStateReducers(){ return [ this._updateEnvironment, this._updatePosition, this._updateWorld, this._updateCarriedObject, this._updateDroppedObject ]; } _updateEnvironment(state, event){ if(typeIs(event, DISPLACEMENT) && state.environment === null) return Object.assign({}, state, { environment: event.sender }); return state; } _updatePosition(state, event){ if(typeIs(event, DISPLACEMENT)){ const { position } = event.data; return Object.assign({}, state, { position }); } return state; } _updateWorld(state, event){ if(typeIs(event, VIEW)){ const view = event.data; const timestamp = Date.now(); const index = view.reduce((carry, square) => { carry[square.key] = Object.assign({ timestamp }, square); return carry; }, {}); const world = Object.assign({}, state.world, index); return Object.assign({}, state, { world }); } return state; } _updateCarriedObject(state, event){ if(typeIs(event, CATCH)) return Object.assign({}, state, { carries: event.data.object }); return state; } _updateDroppedObject(state, event){ if(typeIs(event, DROP) && event.data.object === state.carries) return Object.assign({}, state, { carries: null }); return state; } _getGoalEvaluationChain(){ return [ this._shouldDrop, this._shouldCatch, this._shouldMoveTowardsHole, this._shouldMoveTowardsLeaf, this._shouldExploreWorld, this._shouldVisitOldSquares ]; } _shouldDrop(state){ if(!state.carries) return; const square = state.world[positionString(...state.position)]; if(square && containsSome(square, Hole)) return makeGoal(CARRY, { carry: false }); } _shouldCatch(state){ if(state.carries) return; const square = state.world[positionString(...state.position)]; if(square && containsSome(square, Leaf)) return makeGoal(CARRY, { carry: true }); } _shouldMoveTowardsHole(state){ if(!state.carries) return; const squares = this._squaresContaining(state.world, Hole); const closest = this._closestSquare(state.position, squares); if(closest) return makeGoal(GOTO, { position: closest.value }); } _shouldMoveTowardsLeaf(state){ if(state.carries) return; const squares = this._squaresContaining(state.world, Leaf) .filter(square => !containsSome(square, Ant)); const closest = this._closestSquare(state.position, squares); if(closest) return makeGoal(GOTO, { position: closest.value }); } _squaresContaining(world, objectClass){ return Object.values(world).filter(square => containsSome(square, objectClass)); } _closestSquare(position, squares){ const sortedSquares = squares.map(square => ({ square, distance: distance(position, square.value) })) .sort((a, b) => a.distance - b.distance) .map(obj => obj.square); return sortedSquares.length ? sortedSquares[0] : null; } _shouldExploreWorld(state){ const squares = this._squaresWithUnknowNeighbours(state.world); const closest = this._closestSquare(state.position, squares); if(closest) return makeGoal(GOTO, { position: closest.value }); } _squaresWithUnknowNeighbours(world){ const values = Object.values(world); const knowNeighboursIndex = values.reduce((carry, square) => { if(!carry[square.key]) carry[square.key] = 0; carry[square.key] += square.blockedSides; const { UP, DOWN, LEFT, RIGHT, applyActionToPosition } = actions; [UP, DOWN, LEFT, RIGHT].forEach(action => { const position = applyActionToPosition(action, square.value); const key = positionString(...position); if(world[key]){ if(!carry[key]) carry[key] = 0; carry[key]++; } }); return carry; }, {}); return Object.keys(knowNeighboursIndex) .map(key => ({ cmp: knowNeighboursIndex[key], square: world[key] })) .filter(obj => obj.cmp < 4) .sort((a, b) => a.cmp - b.cmp) .map(obj => obj.square); } _shouldVisitOldSquares(state){ const squares = Object.values(state.world) .sort((a, b) => a.timestamp - b.timestamp) .slice(0, 10); if(squares.length){ const index = randomNumber(squares.length); return makeGoal(GOTO, { position: squares[index].value }); } } _formulateProblem(state, goal){ switch(goal.type){ case CARRY: return this._generateCarryProblem(state, goal.carry); case GOTO: return this._generateGotoProblem(state, goal.position); default: return null; } } _generateCarryProblem(state, carry){ const { CATCH, DROP, cost } = actions; const result = (bool, action) => { switch(action){ case CATCH: return true; case DROP: return false; } }; const initialState = !!state.carries; const problemActions = bool => [bool ? DROP : CATCH]; const goalTest = bool => bool === carry; const pathCost = (from, action, to) => cost(action); const heuristic = bool => bool === carry ? 0 : 1; return { initialState, actions: problemActions, result, goalTest, pathCost, heuristic }; } _generateGotoProblem(state, position){ const { UP, DOWN, LEFT, RIGHT, cost, applyActionToPosition } = actions; const problemActions = pos => { return [UP, DOWN, LEFT, RIGHT].filter(action => { const position = result(pos, action); const square = state.world[canonical(position)]; return !!(square && !containsSome(square, Ant, Rock)); }); }; const result = (pos, action) => applyActionToPosition(action, pos); const initialState = state.position; const goalTest = pos => pos.every((num, index) => num === position[index]); const pathCost = (from, action, to) => cost(action); const heuristic = pos => distance(pos, position); const canonical = pos => positionString(...pos); return { initialState, actions: problemActions, result, goalTest, pathCost, heuristic, canonical }; } }
import webpack from "webpack"; import ExtractTextPlugin from "extract-text-webpack-plugin"; import baseConfig from "./webpack.config.base"; const config = { ...baseConfig, devtool: "source-map", entry: "./app/index", output: { ...baseConfig.output, publicPath: "../dist/" }, module: { ...baseConfig.module, loaders: [ ...baseConfig.module.loaders, { test: /\.global\.css$/, loader: ExtractTextPlugin.extract( "style-loader", "css-loader" ) }, { test: /^((?!\.global).)*\.css$/, loader: ExtractTextPlugin.extract( "style-loader", "css-loader?modules&importLoaders=1" + "&localIdentName=[name]__[local]___[hash:base64:5]" ) } ] }, plugins: [ ...baseConfig.plugins, new webpack.optimize.OccurrenceOrderPlugin(), new webpack.DefinePlugin({ "process.env.NODE_ENV": JSON.stringify("production") }), new webpack.optimize.UglifyJsPlugin({ compressor: { screw_ie8: true, warnings: false } }), new ExtractTextPlugin("style.css", { allChunks: true }) ], target: "electron-renderer" }; export default config;
import { ADDRESS_CLAMP_TO_EDGE, PIXELFORMAT_R8_G8_B8, PIXELFORMAT_R8_G8_B8_A8, TEXTURETYPE_DEFAULT, TEXTURETYPE_RGBM } from '../graphics/constants.js'; import { Asset } from '../asset/asset.js'; import { Texture } from '../graphics/texture.js'; /** @typedef {import('../asset/asset-registry.js').AssetRegistry} AssetRegistry */ /** @typedef {import('../graphics/graphics-device.js').GraphicsDevice} GraphicsDevice */ /** @typedef {import('./handler.js').ResourceHandler} ResourceHandler */ /** @typedef {import('./loader.js').ResourceLoader} ResourceLoader */ /** * Resource handler used for loading cubemap {@link Texture} resources. * * @implements {ResourceHandler} */ class CubemapHandler { /** * Create a new CubemapHandler instance. * * @param {GraphicsDevice} device - The graphics device. * @param {AssetRegistry} assets - The asset registry. * @param {ResourceLoader} loader - The resource loader. */ constructor(device, assets, loader) { this._device = device; this._registry = assets; this._loader = loader; } load(url, callback, asset) { this.loadAssets(asset, callback); } open(url, data, asset) { // caller will set our return value to asset.resources[0]. We've already set resources[0], // but we must return it again here so it doesn't get overwritten. return asset ? asset.resource : null; } patch(asset, registry) { this.loadAssets(asset, function (err, result) { if (err) { // fire error event if patch failed registry.fire('error', asset); registry.fire('error:' + asset.id, err, asset); asset.fire('error', asset); } // nothing to do since asset:change would have been raised if // resources were changed. }); } // get the list of dependent asset ids for the cubemap getAssetIds(cubemapAsset) { const result = []; // prefiltered cubemap is stored at index 0 result[0] = cubemapAsset.file; // faces are stored at index 1..6 if ((cubemapAsset.loadFaces || !cubemapAsset.file) && cubemapAsset.data && cubemapAsset.data.textures) { for (let i = 0; i < 6; ++i) { result[i + 1] = cubemapAsset.data.textures[i]; } } else { result[1] = result[2] = result[3] = result[4] = result[5] = result[6] = null; } return result; } // test whether two assets ids are the same compareAssetIds(assetIdA, assetIdB) { if (assetIdA && assetIdB) { if (parseInt(assetIdA, 10) === assetIdA || typeof assetIdA === "string") { return assetIdA === assetIdB; // id or url } // else { return assetIdA.url === assetIdB.url; // file/url structure with url and filename } // else { return (assetIdA !== null) === (assetIdB !== null); } // update the cubemap resources given a newly loaded set of assets with their corresponding ids update(cubemapAsset, assetIds, assets) { const assetData = cubemapAsset.data || {}; const oldAssets = cubemapAsset._handlerState.assets; const oldResources = cubemapAsset._resources; let tex, mip, i; // faces, prelit cubemap 128, 64, 32, 16, 8, 4 const resources = [null, null, null, null, null, null, null]; // texture type used for faces and prelit cubemaps are both taken from // cubemap.data.rgbm const getType = function () { if (assetData.hasOwnProperty('type')) { return assetData.type; } if (assetData.hasOwnProperty('rgbm')) { return assetData.rgbm ? TEXTURETYPE_RGBM : TEXTURETYPE_DEFAULT; } return null; }; // handle the prelit data if (!cubemapAsset.loaded || assets[0] !== oldAssets[0]) { // prelit asset changed if (assets[0]) { tex = assets[0].resource; for (i = 0; i < 6; ++i) { resources[i + 1] = new Texture(this._device, { name: cubemapAsset.name + '_prelitCubemap' + (tex.width >> i), cubemap: true, type: getType() || tex.type, width: tex.width >> i, height: tex.height >> i, format: tex.format, levels: [tex._levels[i]], fixCubemapSeams: true, addressU: ADDRESS_CLAMP_TO_EDGE, addressV: ADDRESS_CLAMP_TO_EDGE, // generate cubemaps on the top level only mipmaps: i === 0 }); } } } else { // prelit asset didn't change so keep the existing cubemap resources resources[1] = oldResources[1] || null; resources[2] = oldResources[2] || null; resources[3] = oldResources[3] || null; resources[4] = oldResources[4] || null; resources[5] = oldResources[5] || null; resources[6] = oldResources[6] || null; } const faceAssets = assets.slice(1); if (!cubemapAsset.loaded || !this.cmpArrays(faceAssets, oldAssets.slice(1))) { // face assets have changed if (faceAssets.indexOf(null) === -1) { // extract cubemap level data from face textures const faceTextures = faceAssets.map(function (asset) { return asset.resource; }); const faceLevels = []; for (mip = 0; mip < faceTextures[0]._levels.length; ++mip) { faceLevels.push(faceTextures.map(function (faceTexture) { // eslint-disable-line no-loop-func return faceTexture._levels[mip]; })); } // Force RGBA8 if we are loading a RGB8 texture due to a bug on M1 Macs Monterey and Chrome not // rendering the face on right of the cubemap (`faceAssets[0]` and `resources[1]`). // Using a RGBA8 texture works around the issue https://github.com/playcanvas/engine/issues/4091 const format = faceTextures[0].format; const faces = new Texture(this._device, { name: cubemapAsset.name + '_faces', cubemap: true, type: getType() || faceTextures[0].type, width: faceTextures[0].width, height: faceTextures[0].height, format: format === PIXELFORMAT_R8_G8_B8 ? PIXELFORMAT_R8_G8_B8_A8 : format, levels: faceLevels, minFilter: assetData.hasOwnProperty('minFilter') ? assetData.minFilter : faceTextures[0].minFilter, magFilter: assetData.hasOwnProperty('magFilter') ? assetData.magFilter : faceTextures[0].magFilter, anisotropy: assetData.hasOwnProperty('anisotropy') ? assetData.anisotropy : 1, addressU: ADDRESS_CLAMP_TO_EDGE, addressV: ADDRESS_CLAMP_TO_EDGE, fixCubemapSeams: !!assets[0] }); resources[0] = faces; } } else { // no faces changed so keep existing faces cubemap resources[0] = oldResources[0] || null; } // check if any resource changed if (!this.cmpArrays(resources, oldResources)) { // set the new resources, change events will fire cubemapAsset.resources = resources; cubemapAsset._handlerState.assetIds = assetIds; cubemapAsset._handlerState.assets = assets; // destroy the old cubemap resources that are not longer needed for (i = 0; i < oldResources.length; ++i) { if (oldResources[i] !== null && resources.indexOf(oldResources[i]) === -1) { oldResources[i].destroy(); } } } // destroy old assets which have been replaced for (i = 0; i < oldAssets.length; ++i) { if (oldAssets[i] !== null && assets.indexOf(oldAssets[i]) === -1) { oldAssets[i].unload(); } } } cmpArrays(arr1, arr2) { if (arr1.length !== arr2.length) { return false; } for (let i = 0; i < arr1.length; ++i) { if (arr1[i] !== arr2[i]) { return false; } } return true; } // convert string id to int resolveId(value) { const valueInt = parseInt(value, 10); return ((valueInt === value) || (valueInt.toString() === value)) ? valueInt : value; } loadAssets(cubemapAsset, callback) { // initialize asset structures for tracking load requests if (!cubemapAsset.hasOwnProperty('_handlerState')) { cubemapAsset._handlerState = { // the list of requested asset ids in order of [prelit cubemap, 6 faces] assetIds: [null, null, null, null, null, null, null], // the dependent (loaded, active) texture assets assets: [null, null, null, null, null, null, null] }; } const self = this; const assetIds = self.getAssetIds(cubemapAsset); const assets = [null, null, null, null, null, null, null]; const loadedAssetIds = cubemapAsset._handlerState.assetIds; const loadedAssets = cubemapAsset._handlerState.assets; const registry = self._registry; // one of the dependent assets has finished loading let awaiting = 7; const onLoad = function (index, asset) { assets[index] = asset; awaiting--; if (awaiting === 0) { // all dependent assets are finished loading, set them as the active resources self.update(cubemapAsset, assetIds, assets); callback(null, cubemapAsset.resources); } }; // handle an asset load failure const onError = function (index, err, asset) { callback(err); }; // process the texture asset const processTexAsset = function (index, texAsset) { if (texAsset.loaded) { // asset already exists onLoad(index, texAsset); } else { // asset is not loaded, register for load and error events registry.once('load:' + texAsset.id, onLoad.bind(self, index)); registry.once('error:' + texAsset.id, onError.bind(self, index)); if (!texAsset.loading) { // kick off load if it's not already registry.load(texAsset); } } }; let texAsset; for (let i = 0; i < 7; ++i) { const assetId = this.resolveId(assetIds[i]); if (!assetId) { // no asset onLoad(i, null); } else if (self.compareAssetIds(assetId, loadedAssetIds[i])) { // asset id hasn't changed from what is currently set onLoad(i, loadedAssets[i]); } else if (parseInt(assetId, 10) === assetId) { // assetId is an asset id texAsset = registry.get(assetId); if (texAsset) { processTexAsset(i, texAsset); } else { // if we are unable to find the dependent asset, then we introduce here an // asynchronous step. this gives the caller (for example the scene loader) // a chance to add the dependent scene texture to registry before we attempt // to get the asset again. setTimeout(function (index, assetId_) { const texAsset = registry.get(assetId_); if (texAsset) { processTexAsset(index, texAsset); } else { onError(index, "failed to find dependent cubemap asset=" + assetId_); } }.bind(null, i, assetId)); } } else { // assetId is a url or file object and we're responsible for creating it const file = (typeof assetId === "string") ? { url: assetId, filename: assetId } : assetId; texAsset = new Asset(cubemapAsset.name + "_part_" + i, "texture", file); registry.add(texAsset); registry.once('load:' + texAsset.id, onLoad.bind(self, i)); registry.once('error:' + texAsset.id, onError.bind(self, i)); registry.load(texAsset); } } } } export { CubemapHandler };
import _ from 'lodash'; import Bluebird from 'bluebird'; import fs from 'fs'; import _path from 'path'; /** * @class JSONStorage */ module.exports = class JSONStorage { /** * Constructs JSON file storage. * * @param {Object} [options] * @param {String} [options.path='./umzug.json'] - Path to JSON file where * the log is stored. Defaults './umzug.json' relative to process' cwd. */ constructor({ path = _path.resolve(process.cwd(), 'umzug.json') } = {}) { this.path = path; } /** * Logs migration to be considered as executed. * * @param {String} migrationName - Name of the migration to be logged. * @returns {Promise} */ logMigration(migrationName) { var filePath = this.path; var readfile = Bluebird.promisify(fs.readFile); var writefile = Bluebird.promisify(fs.writeFile); return readfile(filePath) .catch(function () { return '[]'; }) .then(function (content) { return JSON.parse(content); }) .then(function (content) { content.push(migrationName); return writefile(filePath, JSON.stringify(content, null, ' ')); }); } /** * Unlogs migration to be considered as pending. * * @param {String} migrationName - Name of the migration to be unlogged. * @returns {Promise} */ unlogMigration(migrationName) { var filePath = this.path; var readfile = Bluebird.promisify(fs.readFile); var writefile = Bluebird.promisify(fs.writeFile); return readfile(filePath) .catch(function () { return '[]'; }) .then(function (content) { return JSON.parse(content); }) .then(function (content) { content = _.without(content, migrationName); return writefile(filePath, JSON.stringify(content, null, ' ')); }); } /** * Gets list of executed migrations. * * @returns {Promise.<String[]>} */ executed() { var filePath = this.path; var readfile = Bluebird.promisify(fs.readFile); return readfile(filePath) .catch(function () { return '[]'; }) .then(function (content) { return JSON.parse(content); }); } }
Template.registerHelper('areFriends', function (friendId) { if (validations.hasFriend(Meteor.userId(), friendId)) { return validations.validateUserRelations({ userId: Meteor.userId(), status: STATUSES.friend }, { userId: friendId, status: STATUSES.friend }); } else { return false; } }); Template.registerHelper('friendRequest', function (friendId) { if (validations.hasFriend(Meteor.userId(), friendId)) { return validations.validateUserRelations({ userId: Meteor.userId(), status: STATUSES.request }, { userId: friendId, status: STATUSES.pending }); } else { return false; } }); Template.registerHelper('friendPending', function (friendId) { if (validations.hasFriend(Meteor.userId(), friendId)) { return validations.validateUserRelations({ userId: Meteor.userId(), status: STATUSES.pending }, { userId: friendId, status: STATUSES.request }); } else { return false; } }); Template.registerHelper('wereFriends', function (friendId) { if (validations.hasFriend(Meteor.userId(), friendId)) { return validations.validateUserRelations({ userId: Meteor.userId(), status: STATUSES.request }, { userId: friendId, status: STATUSES.pending }); } else { return false; } });
import { mount } from 'riot'; export default function renderCompiledButUnmounted(component) { mount('root', component.tagName, component.opts || {}); }
exports.init = function(plugins, bot){ bot.addCommand('wolfram', '<question>', 'Answer question using wolfram alpha', USER_LEVEL_GLOBAL); if(this.config.client){ var wolfram = require('wolfram').createClient(this.config.client); }else{ throw new Error('No application id specified!'); } plugins.listen(this, 'command', function(args){ switch(args.command){ case 'wolfram': if(args && args.arguments){ var query = args.arguments.join(' '); wolfram.query(query, function(err, result){ if(result && result.length > 0){ //for(a in result){ // b = result[a]; // for(c in b){ // console.log(b[c]); // } //} IRC.message(args.channel, result[1]['subpods'][0]['value']); }else{ IRC.message(args.channel, 'Wolfram error.'); } }); }else{ IRC.message(args.channel, 'Not enough arguments!'); } break; } }); };
/** * `this` refers to the EventHandler object of the WebdriverIO instance * `that` refers to the Browserevent instance */ var addEventListener = module.exports = function(that) { return function(eventName,elem,callback,useCapture) { if(!that.socket) { // try again after 100ms return setTimeout(that.removeEventListener.bind(this,eventName,elem,callback,useCapture), 100); } else if(!that.browserEvents[eventName + '-' + elem] || !that.browserEvents[eventName + '-' + elem].length) { return this; } // get stored event listener that.browserEvents[eventName + '-' + elem].forEach(function(listener, i) { if(listener === callback.toString()) { // remove listener in event list that.browserEvents[eventName + '-' + elem].splice(i,1); // remove listener on server side that.socket.removeListener(eventName + '-' + elem,callback); // break loop return false; } }); // remove event listener on client side if there is no listener anymore if(that.browserEvents[eventName + '-' + elem].length === 0) { that.socket.emit('removeEventListener', { eventName: eventName, elem: elem, useCapture: useCapture || false }); } }; };
'use strict'; // An object describing a push notification. function Notification(kind, message, userIds, objectId) { this.kind = kind; this.message = message; this.userIds = userIds; this.objectId = objectId; }; // Parses and returns a configured Notification object. // - blob: { meta: JSON, data: JSON } // - returns: Notification function createNotification(json) { if (!json) { return null; } var meta = json.meta; if (!meta) { return null; } if (meta.is_deleted === true || !meta.type) { return null; } var note; switch (meta.type) { case 'bookmark': note = createBookmarkNotification(json.data); break; case 'post': note = createPostNotification(json.post); break; case 'follow': note = createFollowNotification(json.data); break; default: break; } return note; }; // Creates a Notification object with kind of "repost" or "mention" // - post: JSON (Post object) // - returns: Notification function createPostNotification(post) { if (!post) { return null; } if (post.repost_of) { var original = post.repost_of; var message = '@' + post.user.username + ' reposted: ' + original.content.text; return new Notification('repost', message, [original.user.id], post.id); } else { var mentions = post.content.entities.mentions; if (!mentions || (mentions !== null && mentions.length == 0)) { return null; } var ids = []; for (var index in mentions) { ids.push(mentions[index].id); } if (ids.length == 0) { return null; } var message = '@' + post.user.username + ' mentioned you: ' + post.content.text; return new Notification('mention', message, ids, post.id); } }; // Creates a Notification object with a kind of "bookmark" // - data: { user: JSON, post: JSON } // - returns: Notification function createBookmarkNotification(data) { var user = data.user, post = data.post; if (!user || !post) { return null; } var message = '@' + user.username + ' favorited: ' + post.content.text; return new Notification('bookmark', message, [post.user.id], user.id); }; // Creates a Notification object with kind of "follow" // - data: { user: JSON, followed_user: JSON } // - returns: Notification function createFollowNotification(data) { var user = data.user, followed = data.followed_user; if (!user || !followed) { return null; } var name; if (user.name && user.name !== ' ') { name = user.name + ' (@' + user.username + ')'; } else { name = '@' + user.username; } var message = name + ' started following you' return new Notification('follow', message, [followed.id], user.id); } // Creates a Notification object from App Stream json payload. // - payload: { meta: JSON, data: JSON } // - returns: Notification Notification.createNotificationFromAppStreamPayload = function(payload) { return createNotification(payload); }; module.exports = Notification;
(function () { var config, options, dictionary; config = { DEFAULT_SCALE_FACTOR: 1.1, TAB_EVENTS: 0, TAB_COURSES: 1, TAB_RESULTS: 2, TAB_DRAW: 3, TAB_LOGIN: 4, TAB_CREATE: 5, TAB_EDIT: 6, TAB_MAP: 7, TAB_DELETE_MAP: 8, INVALID_MAP_ID: 9999, // translated when output so leave as English here DEFAULT_NEW_COMMENT: "Type your comment", DEFAULT_EVENT_COMMENT: "Comments (optional)", // added to resultid when saving a GPS track GPS_RESULT_OFFSET: 50000, MASS_START_REPLAY: 1, REAL_TIME_REPLAY: 2, // dropdown selection value MASS_START_BY_CONTROL: 99999, VERY_HIGH_TIME_IN_SECS: 99999, // screen sizes for different layouts BIG_SCREEN_BREAK_POINT: 800, SMALL_SCREEN_BREAK_POINT: 500, PURPLE: '#b300ff', RED: '#ff0000', GREEN: '#00ff00', GREY: '#e0e0e0', RED_30: 'rgba(255,0,0,0.3)', GREEN_30: 'rgba(0,255,0,0.3)', WHITE: '#ffffff', BLACK: '#000000', RUNNER_DOT_RADIUS: 6, HANDLE_DOT_RADIUS: 7, HANDLE_COLOUR: '#ff0000', // parameters for call to draw courses DIM: 0.75, FULL_INTENSITY: 1.0, // version gets set automatically by grunt file during build process RG2VERSION: '1.8.0', TIME_NOT_FOUND: 9999, // values for evt.which RIGHT_CLICK: 3, DO_NOT_SAVE_COURSE: 9999, // values of event format FORMAT_NORMAL: 1, FORMAT_NORMAL_NO_RESULTS: 2, FORMAT_SCORE_EVENT: 3, FORMAT_SCORE_EVENT_NO_RESULTS: 4, DISPLAY_ALL_COURSES: 99999, //number of drawn routes that can be saved for possible later deletion MAX_DRAWN_ROUTES: 10, // array of available languages: not great to do it like this but it helps for routegadget.co.uk set-up languages: [ { language: "Deutsch", code: "de" }, { language: "Suomi", code: "fi" }, { language: "Franรงais", code: "fr" }, { language: "Italiano", code: "it" }, { language: "ๆ—ฅๆœฌ่ชž", code: "ja" }, { language: "Norsk", code: "no" }, { language: "Portuguรชs - Brasil", code: "pt" }, { language: "ะ ัƒััะบะธะน", code: "ru" } ], // Size of map upload in MB that triggers the warning dialog FILE_SIZE_WARNING: 2 }; options = { // initialised to default values: overwritten from storage later mapIntensity: 1, routeIntensity: 1, replayFontSize: 12, courseWidth: 3, routeWidth: 4, circleSize: 20, snap: true, showThreeSeconds: false, showGPSSpeed: false, // align map with next control at top when drawing route alignMap: false, // speeds in min/km maxSpeed: 4, minSpeed: 15, // array of up to MAX_DRAWN_ROUTES entries with details to allow deletion // stored in order they are added, so first entry is most recent and gets deleted if necessary drawnRoutes: [] }; // translation function function t(str) { // eslint-disable-next-line no-prototype-builtins if (dictionary.hasOwnProperty(str)) { return dictionary[str]; } return str; } function translateTextFields() { var i, selector, text; selector = ["#rg2-events-tab a", "#rg2-courses-tab a", "#rg2-results-tab a", "#rg2-draw-tab a", '#rg2-draw-title', '#draw-text-1', '#draw-text-2', '#draw-text-3', '#draw-text-4', '#draw-text-5', '#rg2-load-gps-title', '.rg2-options-dialog .ui-dialog-title']; text = ['Events', 'Courses', 'Results', 'Draw', 'Draw route', 'Left click to add/lock/unlock a handle', 'Green - draggable', 'Red - locked', 'Right click to delete a handle', 'Drag a handle to adjust track around locked point(s)', 'Load GPS file (GPX or TCX)', 'Configuration options']; for (i = 0; i < selector.length; i += 1) { $(selector[i]).text(t(text[i])); } } function translateTitleProperties() { var i, selector, text; selector = ["rg2-replay-start-control", "#rg2-hide-info-panel-icon", '#btn-about', '#btn-options', '#btn-zoom-out', '#btn-zoom-in', '#btn-reset', '#btn-show-splits', '#rg2-splits-table', '#btn-slower', '#btn-faster', '#btn-rotate-right', '#btn-rotate-left', '#btn-stats', '#btn-measure']; text = ["Start at", "Hide info panel", 'Help', 'Options', 'Zoom out', 'Zoom in', 'Reset', 'Splits', 'Splits table', 'Slower', 'Faster', 'Rotate right', 'Rotate left', 'Statistics', 'Measure']; for (i = 0; i < selector.length; i += 1) { $(selector[i]).prop('title', t(text[i])); } } function translateTextContentProperties() { var i, selector, text; selector = ['label[for=btn-full-tails]', 'label[for=spn-tail-length]', 'label[for=rg2-select-language]', 'label[for=spn-map-intensity]', 'label[for=spn-route-intensity]', 'label[for=spn-route-width]', 'label[for=spn-name-font-size]', 'label[for=spn-course-width]', 'label[for=spn-control-circle]', 'label[for=chk-snap-toggle]', 'label[for=chk-show-three-seconds]', 'label[for=chk-show-GPS-speed]', 'label[for=rg2-course-select]', 'label[for=rg2-name-select]', 'label[for=btn-move-all]', 'label[for=btn-align-map]']; text = ['Full tails', 'Length', 'Language', 'Map intensity %', 'Route intensity %', 'Route width', 'Replay label font size', 'Course overprint width', 'Control circle size', 'Snap to control when drawing', 'Show +3 time loss for GPS routes', 'Show GPS speed colours', 'Select course', 'Select name', 'Move track and map together (or right click-drag)', 'Align map to next control']; for (i = 0; i < selector.length; i += 1) { $(selector[i]).prop('textContent', t(text[i])); } } function translateButtons() { var i, selector, text; selector = ['#btn-undo', '#btn-undo-gps-adjust', '#btn-save-route', '#btn-reset-drawing', '#btn-three-seconds', '#btn-save-gps-route', '#btn-autofit-gps']; text = ['Undo', 'Undo', 'Save', 'Reset', '+3 sec', 'Save GPS route', 'Autofit']; for (i = 0; i < selector.length; i += 1) { $(selector[i]).button('option', 'label', t(text[i])); } } function translateFixedText() { translateTextFields(); translateTitleProperties(); translateTextContentProperties(); translateButtons(); // #316 missing translation on language change // animation controls are done in resetAnimation fora new language so don't need to do them here if ($('#btn-toggle-controls').hasClass('fa-circle-o')) { $('#btn-toggle-controls').prop('title', t('Show controls')); } else { $('#btn-toggle-controls').prop('title', t('Hide controls')); } } function createLanguageDropdown(languages) { var i, selected, dropdown; $("#rg2-select-language").empty(); dropdown = document.getElementById("rg2-select-language"); selected = (dictionary.code === "en"); dropdown.options.add(rg2.utils.generateOption('en', 'en: English', selected)); for (i = 0; i < languages.length; i = i + 1) { selected = (dictionary.code === languages[i].code); dropdown.options.add(rg2.utils.generateOption(languages[i].code, languages[i].code + ": " + languages[i].language, selected)); } } function getDictionaryCode() { return dictionary.code; } function setDictionary(newDictionary) { dictionary = newDictionary; translateFixedText(); } function setLanguageOptions() { // use English until we load something else dictionary = {}; dictionary.code = 'en'; // set available languages and set start language if requested rg2.createLanguageDropdown(rg2.config.languages); if (rg2Config.start_language !== "en") { rg2.getNewLanguage(rg2Config.start_language); } } function setConfigOption(option, value) { this.options[option] = value; } function saveDrawnRouteDetails(route) { // this allows for deletion later var routes; routes = this.options.drawnRoutes; if (routes.length >= rg2.config.MAX_DRAWN_ROUTES) { // array is full so delete oldest (=first) entry routes.shift(); } routes.push(route); this.options.drawnRoutes = routes; this.saveConfigOptions(); } function removeDrawnRouteDetails(route) { var routes, i; routes = []; for (i = 0; i < this.options.drawnRoutes.length; i += 1) { if ((this.options.drawnRoutes[i].id !== route.id) || (this.options.drawnRoutes[i].eventid !== route.eventid)) { routes.push(this.options.drawnRoutes[i]); } } this.options.drawnRoutes = routes; this.saveConfigOptions(); } function saveConfigOptions() { try { // eslint-disable-next-line no-prototype-builtins if ((window.hasOwnProperty('localStorage')) && (window.localStorage !== null)) { localStorage.setItem('rg2-options', JSON.stringify(this.options)); } } catch (e) { // storage not supported so just return return; } } function loadConfigOptions() { try { var prop, storedOptions; // eslint-disable-next-line no-prototype-builtins if ((window.hasOwnProperty('localStorage')) && (window.localStorage !== null)) { if (localStorage.getItem('rg2-options') !== null) { storedOptions = JSON.parse(localStorage.getItem('rg2-options')); // overwrite the options array with saved options from local storage // need to do this to allow for new options that people don't yet have for (prop in storedOptions) { // probably a redundant check but it prevents lint from complaining // eslint-disable-next-line no-prototype-builtins if (storedOptions.hasOwnProperty(prop)) { this.options[prop] = storedOptions[prop]; } } // best to keep these at default? this.options.circleSize = 20; if (this.options.mapIntensity === 0) { rg2.utils.showWarningDialog("Warning", "Your saved settings have 0% map intensity so the map is invisible. You can adjust this on the configuration menu"); } } } } catch (e) { // storage not supported so just continue console.log('Local storage not supported'); } } function getOverprintDetails() { var opt, size, scaleFact, circleSize; opt = {}; // attempt to scale overprint depending on map image size // this avoids very small/large circles, or at least makes things a bit more sensible size = rg2.getMapSize(); // Empirically derived so open to suggestions. This is based on a nominal 20px circle // as default. The square root stops things getting too big too quickly. // 1500px is a typical map image maximum size. scaleFact = Math.pow(Math.min(size.height, size.width) / 1500, 0.5); // don't get too carried away, although these would be strange map files scaleFact = Math.min(scaleFact, 5); scaleFact = Math.max(scaleFact, 0.5); circleSize = Math.round(rg2.options.circleSize * scaleFact); // ratios based on IOF ISOM overprint specification opt.controlRadius = circleSize; opt.finishInnerRadius = circleSize * (5 / 6); opt.finishOuterRadius = circleSize * (7 / 6); opt.startTriangleLength = circleSize * (7 / 6); opt.overprintWidth = this.options.courseWidth; opt.font = circleSize + 'pt Arial'; return opt; } rg2.t = t; rg2.options = options; rg2.config = config; rg2.saveConfigOptions = saveConfigOptions; rg2.saveDrawnRouteDetails = saveDrawnRouteDetails; rg2.removeDrawnRouteDetails = removeDrawnRouteDetails; rg2.setConfigOption = setConfigOption; rg2.loadConfigOptions = loadConfigOptions; rg2.getOverprintDetails = getOverprintDetails; rg2.setDictionary = setDictionary; rg2.getDictionaryCode = getDictionaryCode; rg2.setLanguageOptions = setLanguageOptions; rg2.createLanguageDropdown = createLanguageDropdown; }());
export const rupiah = n => new Intl.NumberFormat('id-ID', { style: 'currency', currency: 'IDR' }).format(n) export const readFile = file => new Promise((res, rej) => { const reader = new FileReader() reader.onload = e => { const src = e.target.result res(src) } reader.readAsDataURL(file) })
// parse command line options var minimist = require('minimist'); var mopts = { string: [ 'node', 'runner', 'server', 'suite', 'task', 'version' ] }; var options = minimist(process.argv, mopts); // remove well-known parameters from argv before loading make, // otherwise each arg will be interpreted as a make target process.argv = options._; // modules var make = require('shelljs/make'); var fs = require('fs'); var os = require('os'); var path = require('path'); var semver = require('semver'); var util = require('./make-util'); var admzip = require('adm-zip'); // util functions var cd = util.cd; var cp = util.cp; var mkdir = util.mkdir; var rm = util.rm; var test = util.test; var run = util.run; var banner = util.banner; var rp = util.rp; var fail = util.fail; var ensureExists = util.ensureExists; var pathExists = util.pathExists; var buildNodeTask = util.buildNodeTask; var addPath = util.addPath; var copyTaskResources = util.copyTaskResources; var matchFind = util.matchFind; var matchCopy = util.matchCopy; var ensureTool = util.ensureTool; var assert = util.assert; var getExternals = util.getExternals; var createResjson = util.createResjson; var createTaskLocJson = util.createTaskLocJson; var validateTask = util.validateTask; var fileToJson = util.fileToJson; var createYamlSnippetFile = util.createYamlSnippetFile; var createMarkdownDocFile = util.createMarkdownDocFile; // global paths var buildPath = path.join(__dirname, '_build', 'Tasks'); var buildTestsPath = path.join(__dirname, '_build', 'Tests'); var commonPath = path.join(__dirname, '_build', 'Tasks', 'Common'); var packagePath = path.join(__dirname, '_package'); var legacyTestPath = path.join(__dirname, '_test', 'Tests-Legacy'); var legacyTestTasksPath = path.join(__dirname, '_test', 'Tasks'); // node min version var minNodeVer = '6.10.3'; if (semver.lt(process.versions.node, minNodeVer)) { fail('requires node >= ' + minNodeVer + '. installed: ' + process.versions.node); } // add node modules .bin to the path so we can dictate version of tsc etc... var binPath = path.join(__dirname, 'node_modules', '.bin'); if (!test('-d', binPath)) { fail('node modules bin not found. ensure npm install has been run.'); } addPath(binPath); // resolve list of tasks var taskList; if (options.task) { // find using --task parameter taskList = matchFind(options.task, path.join(__dirname, 'Tasks'), { noRecurse: true, matchBase: true }) .map(function (item) { return path.basename(item); }); if (!taskList.length) { fail('Unable to find any tasks matching pattern ' + options.task); } } else { // load the default list taskList = fileToJson(path.join(__dirname, 'make-options.json')).tasks; } // set the runner options. should either be empty or a comma delimited list of test runners. // for example: ts OR ts,ps // // note, currently the ts runner igores this setting and will always run. process.env['TASK_TEST_RUNNER'] = options.runner || ''; target.clean = function () { rm('-Rf', path.join(__dirname, '_build')); mkdir('-p', buildPath); rm('-Rf', path.join(__dirname, '_test')); }; // // Generate documentation (currently only YAML snippets) // ex: node make.js gendocs // ex: node make.js gendocs --task ShellScript // target.gendocs = function() { var docsDir = path.join(__dirname, '_gendocs'); rm('-Rf', docsDir); mkdir('-p', docsDir); console.log(); console.log('> generating docs'); taskList.forEach(function(taskName) { var taskPath = path.join(__dirname, 'Tasks', taskName); ensureExists(taskPath); // load the task.json var taskJsonPath = path.join(taskPath, 'task.json'); if (test('-f', taskJsonPath)) { var taskDef = fileToJson(taskJsonPath); validateTask(taskDef); // create YAML snippet Markdown var yamlOutputFilename = taskName + '.md'; createYamlSnippetFile(taskDef, docsDir, yamlOutputFilename); // create Markdown documentation file var mdDocOutputFilename = taskName + '.md'; createMarkdownDocFile(taskDef, taskJsonPath, docsDir, mdDocOutputFilename); } }); banner('Generating docs successful', true); } // // ex: node make.js build // ex: node make.js build --task ShellScript // target.build = function() { target.clean(); ensureTool('tsc', '--version', 'Version 2.3.4'); ensureTool('npm', '--version', function (output) { if (semver.lt(output, '5.6.0')) { fail('Expected 5.6.0 or higher. To fix, run: npm install -g npm'); } }); taskList.forEach(function(taskName) { banner('Building: ' + taskName); var taskPath = path.join(__dirname, 'Tasks', taskName); ensureExists(taskPath); // load the task.json var outDir; var shouldBuildNode = test('-f', path.join(taskPath, 'tsconfig.json')); var taskJsonPath = path.join(taskPath, 'task.json'); if (test('-f', taskJsonPath)) { var taskDef = fileToJson(taskJsonPath); validateTask(taskDef); // fixup the outDir (required for relative pathing in legacy L0 tests) outDir = path.join(buildPath, taskName); // create loc files createTaskLocJson(taskPath); createResjson(taskDef, taskPath); // determine the type of task shouldBuildNode = shouldBuildNode || taskDef.execution.hasOwnProperty('Node') || taskDef.execution.hasOwnProperty('Node10'); } else { outDir = path.join(buildPath, path.basename(taskPath)); } mkdir('-p', outDir); // get externals var taskMakePath = path.join(taskPath, 'make.json'); var taskMake = test('-f', taskMakePath) ? fileToJson(taskMakePath) : {}; if (taskMake.hasOwnProperty('externals')) { console.log(''); console.log('> getting task externals'); getExternals(taskMake.externals, outDir); } //-------------------------------- // Common: build, copy, install //-------------------------------- var commonPacks = []; if (taskMake.hasOwnProperty('common')) { var common = taskMake['common']; common.forEach(function(mod) { var modPath = path.join(taskPath, mod['module']); var modName = path.basename(modPath); var modOutDir = path.join(commonPath, modName); if (!test('-d', modOutDir)) { banner('Building module ' + modPath, true); mkdir('-p', modOutDir); // create loc files var modJsonPath = path.join(modPath, 'module.json'); if (test('-f', modJsonPath)) { createResjson(fileToJson(modJsonPath), modPath); } // npm install and compile if ((mod.type === 'node' && mod.compile == true) || test('-f', path.join(modPath, 'tsconfig.json'))) { buildNodeTask(modPath, modOutDir); } // copy default resources and any additional resources defined in the module's make.json console.log(); console.log('> copying module resources'); var modMakePath = path.join(modPath, 'make.json'); var modMake = test('-f', modMakePath) ? fileToJson(modMakePath) : {}; copyTaskResources(modMake, modPath, modOutDir); // get externals if (modMake.hasOwnProperty('externals')) { console.log(''); console.log('> getting module externals'); getExternals(modMake.externals, modOutDir); } if (mod.type === 'node' && mod.compile == true || test('-f', path.join(modPath, 'package.json'))) { var commonPack = util.getCommonPackInfo(modOutDir); // assert the pack file does not already exist (name should be unique) if (test('-f', commonPack.packFilePath)) { fail(`Pack file already exists: ${commonPack.packFilePath}`); } // pack the Node module. a pack file is required for dedupe. // installing from a folder creates a symlink, and does not dedupe. cd(path.dirname(modOutDir)); run(`npm pack ./${path.basename(modOutDir)}`); } } // store the npm pack file info if (mod.type === 'node' && mod.compile == true) { commonPacks.push(util.getCommonPackInfo(modOutDir)); } // copy ps module resources to the task output dir else if (mod.type === 'ps') { console.log(); console.log('> copying ps module to task'); var dest; if (mod.hasOwnProperty('dest')) { dest = path.join(outDir, mod.dest, modName); } else { dest = path.join(outDir, 'ps_modules', modName); } matchCopy('!Tests', modOutDir, dest, { noRecurse: true, matchBase: true }); } }); // npm install the common modules to the task dir if (commonPacks.length) { cd(taskPath); var installPaths = commonPacks.map(function (commonPack) { return `file:${path.relative(taskPath, commonPack.packFilePath)}`; }); run(`npm install --save-exact ${installPaths.join(' ')}`); } } // build Node task if (shouldBuildNode) { buildNodeTask(taskPath, outDir); } // remove the hashes for the common packages, they change every build if (commonPacks.length) { var lockFilePath = path.join(taskPath, 'package-lock.json'); if (!test('-f', lockFilePath)) { lockFilePath = path.join(taskPath, 'npm-shrinkwrap.json'); } var packageLock = fileToJson(lockFilePath); Object.keys(packageLock.dependencies).forEach(function (dependencyName) { commonPacks.forEach(function (commonPack) { if (dependencyName == commonPack.packageName) { delete packageLock.dependencies[dependencyName].integrity; } }); }); fs.writeFileSync(lockFilePath, JSON.stringify(packageLock, null, ' ')); } // copy default resources and any additional resources defined in the task's make.json console.log(); console.log('> copying task resources'); copyTaskResources(taskMake, taskPath, outDir); }); banner('Build successful', true); } // // will run tests for the scope of tasks being built // npm test // node make.js test // node make.js test --task ShellScript --suite L0 // target.test = function() { ensureTool('tsc', '--version', 'Version 2.3.4'); ensureTool('mocha', '--version', '2.3.3'); // build the general tests and ps test infra rm('-Rf', buildTestsPath); mkdir('-p', path.join(buildTestsPath)); cd(path.join(__dirname, 'Tests')); run(`tsc --rootDir ${path.join(__dirname, 'Tests')} --outDir ${buildTestsPath}`); console.log(); console.log('> copying ps test lib resources'); mkdir('-p', path.join(buildTestsPath, 'lib')); matchCopy(path.join('**', '@(*.ps1|*.psm1)'), path.join(__dirname, 'Tests', 'lib'), path.join(buildTestsPath, 'lib')); // find the tests var suiteType = options.suite || 'L0'; var taskType = options.task || '*'; var pattern1 = buildPath + '/' + taskType + '/Tests/' + suiteType + '.js'; var pattern2 = buildPath + '/Common/' + taskType + '/Tests/' + suiteType + '.js'; var pattern3 = buildTestsPath + '/' + suiteType + '.js'; var testsSpec = []; if (matchFind(pattern1, buildPath).length > 0) { testsSpec.push(pattern1); } if (matchFind(pattern2, buildPath).length > 0) { testsSpec.push(pattern2); } testsSpec.concat(matchFind(pattern3, buildTestsPath, { noRecurse: true })); if (!testsSpec.length && !process.env.TF_BUILD) { fail(`Unable to find tests using the following patterns: ${JSON.stringify([pattern1, pattern2, pattern3])}`); } // setup the version of node to run the tests util.installNode(options.node); run('mocha ' + testsSpec.join(' ') /*+ ' --reporter mocha-junit-reporter --reporter-options mochaFile=../testresults/test-results.xml'*/, /*inheritStreams:*/true); } // // node make.js testLegacy // node make.js testLegacy --suite L0/XCode // target.testLegacy = function() { ensureTool('tsc', '--version', 'Version 2.3.4'); ensureTool('mocha', '--version', '2.3.3'); if (options.suite) { fail('The "suite" parameter has been deprecated. Use the "task" parameter instead.'); } // clean console.log('removing _test'); rm('-Rf', path.join(__dirname, '_test')); // copy the L0 source files for each task; copy the layout for each task console.log(); console.log('> copying tasks'); taskList.forEach(function (taskName) { var testCopySource = path.join(__dirname, 'Tests-Legacy', 'L0', taskName); // copy the L0 source files if exist if (test('-e', testCopySource)) { console.log('copying ' + taskName); var testCopyDest = path.join(legacyTestPath, 'L0', taskName); matchCopy('*', testCopySource, testCopyDest, { noRecurse: true, matchBase: true }); // copy the task layout var taskCopySource = path.join(buildPath, taskName); var taskCopyDest = path.join(legacyTestTasksPath, taskName); matchCopy('*', taskCopySource, taskCopyDest, { noRecurse: true, matchBase: true }); } // copy each common-module L0 source files if exist var taskMakePath = path.join(__dirname, 'Tasks', taskName, 'make.json'); var taskMake = test('-f', taskMakePath) ? fileToJson(taskMakePath) : {}; if (taskMake.hasOwnProperty('common')) { var common = taskMake['common']; common.forEach(function(mod) { // copy the common-module L0 source files if exist and not already copied var modName = path.basename(mod['module']); console.log('copying ' + modName); var modTestCopySource = path.join(__dirname, 'Tests-Legacy', 'L0', `Common-${modName}`); var modTestCopyDest = path.join(legacyTestPath, 'L0', `Common-${modName}`); if (test('-e', modTestCopySource) && !test('-e', modTestCopyDest)) { matchCopy('*', modTestCopySource, modTestCopyDest, { noRecurse: true, matchBase: true }); } var modCopySource = path.join(commonPath, modName); var modCopyDest = path.join(legacyTestTasksPath, 'Common', modName); if (test('-e', modCopySource) && !test('-e', modCopyDest)) { // copy the common module layout matchCopy('*', modCopySource, modCopyDest, { noRecurse: true, matchBase: true }); } }); } }); // short-circuit if no tests if (!test('-e', legacyTestPath)) { banner('no legacy tests found', true); return; } // copy the legacy test infra console.log(); console.log('> copying legacy test infra'); matchCopy('@(definitions|lib|tsconfig.json)', path.join(__dirname, 'Tests-Legacy'), legacyTestPath, { noRecurse: true, matchBase: true }); // copy the lib tests when running all legacy tests if (!options.task) { matchCopy('*', path.join(__dirname, 'Tests-Legacy', 'L0', 'lib'), path.join(legacyTestPath, 'L0', 'lib'), { noRecurse: true, matchBase: true }); } // compile legacy L0 and lib var testSource = path.join(__dirname, 'Tests-Legacy'); cd(legacyTestPath); run('tsc --rootDir ' + legacyTestPath); // create a test temp dir - used by the task runner to copy each task to an isolated dir var tempDir = path.join(legacyTestPath, 'Temp'); process.env['TASK_TEST_TEMP'] = tempDir; mkdir('-p', tempDir); // suite paths var testsSpec = matchFind(path.join('**', '_suite.js'), path.join(legacyTestPath, 'L0')); if (!testsSpec.length) { fail(`Unable to find tests using the pattern: ${path.join('**', '_suite.js')}`); } // setup the version of node to run the tests util.installNode(options.node); // mocha doesn't always return a non-zero exit code on test failure. when only // a single suite fails during a run that contains multiple suites, mocha does // not appear to always return non-zero. as a workaround, the following code // creates a wrapper suite with an "after" hook. in the after hook, the state // of the runnable context is analyzed to determine whether any tests failed. // if any tests failed, log a ##vso command to fail the build. var testsSpecPath = '' var testsSpecPath = path.join(legacyTestPath, 'testsSpec.js'); var contents = 'var __suite_to_run;' + os.EOL; contents += 'describe(\'Legacy L0\', function (__outer_done) {' + os.EOL; contents += ' after(function (done) {' + os.EOL; contents += ' var failedCount = 0;' + os.EOL; contents += ' var suites = [ this._runnable.parent ];' + os.EOL; contents += ' while (suites.length) {' + os.EOL; contents += ' var s = suites.pop();' + os.EOL; contents += ' suites = suites.concat(s.suites); // push nested suites' + os.EOL; contents += ' failedCount += s.tests.filter(function (test) { return test.state != "passed" }).length;' + os.EOL; contents += ' }' + os.EOL; contents += '' + os.EOL; contents += ' if (failedCount && process.env.TF_BUILD) {' + os.EOL; contents += ' console.log("##vso[task.logissue type=error]" + failedCount + " test(s) failed");' + os.EOL; contents += ' console.log("##vso[task.complete result=Failed]" + failedCount + " test(s) failed");' + os.EOL; contents += ' }' + os.EOL; contents += '' + os.EOL; contents += ' done();' + os.EOL; contents += ' });' + os.EOL; testsSpec.forEach(function (itemPath) { contents += ` __suite_to_run = require(${JSON.stringify(itemPath)});` + os.EOL; }); contents += '});' + os.EOL; fs.writeFileSync(testsSpecPath, contents); run('mocha ' + testsSpecPath /*+ ' --reporter mocha-junit-reporter --reporter-options mochaFile=../testresults/test-legacy-results.xml' */, /*inheritStreams:*/true); } // // node make.js package // This will take the built tasks and create the files we need to publish them. // target.package = function() { banner('Starting package process...') // START LOCAL CONFIG // console.log('> Cleaning packge path'); // rm('-Rf', packagePath); // TODO: Only need this when we run locally //var layoutPath = util.createNonAggregatedZip(buildPath, packagePath); // END LOCAL CONFIG // Note: The local section above is needed when running layout locally due to discrepancies between local build and // slicing in CI. This will get cleaned up after we fully roll out and go to build only changed. var layoutPath = path.join(packagePath, 'milestone-layout'); util.createNugetPackagePerTask(packagePath, layoutPath); } // used by CI that does official publish target.publish = function() { var server = options.server; assert(server, 'server'); // if task specified, skip if (options.task) { banner('Task parameter specified. Skipping publish.'); return; } // get the branch/commit info var refs = util.getRefs(); // test whether to publish the non-aggregated tasks zip // skip if not the tip of a release branch var release = refs.head.release; var commit = refs.head.commit; if (!release || !refs.releases[release] || commit != refs.releases[release].commit) { // warn not publishing the non-aggregated console.log(`##vso[task.logissue type=warning]Skipping publish for non-aggregated tasks zip. HEAD is not the tip of a release branch.`); } else { // store the non-aggregated tasks zip var nonAggregatedZipPath = path.join(packagePath, 'non-aggregated-tasks.zip'); util.storeNonAggregatedZip(nonAggregatedZipPath, release, commit); } // resolve the nupkg path var nupkgFile; var nupkgDir = path.join(packagePath, 'pack-target'); if (!test('-d', nupkgDir)) { fail('nupkg directory does not exist'); } var fileNames = fs.readdirSync(nupkgDir); if (fileNames.length != 1) { fail('Expected exactly one file under ' + nupkgDir); } nupkgFile = path.join(nupkgDir, fileNames[0]); // publish the package ensureTool('nuget3.exe'); run(`nuget3.exe push ${nupkgFile} -Source ${server} -apikey Skyrise`); } var agentPluginTasks = ['DownloadPipelineArtifact', 'PublishPipelineArtifact']; // used to bump the patch version in task.json files target.bump = function() { taskList.forEach(function (taskName) { // load files var taskJsonPath = path.join(__dirname, 'Tasks', taskName, 'task.json'); var taskJson = JSON.parse(fs.readFileSync(taskJsonPath)); var taskLocJsonPath = path.join(__dirname, 'Tasks', taskName, 'task.loc.json'); var taskLocJson = JSON.parse(fs.readFileSync(taskLocJsonPath)); // skip agent plugin tasks if(agentPluginTasks.indexOf(taskJson.name) > -1) { return; } if (typeof taskJson.version.Patch != 'number') { fail(`Error processing '${taskName}'. version.Patch should be a number.`); } taskJson.version.Patch = taskJson.version.Patch + 1; taskLocJson.version.Patch = taskLocJson.version.Patch + 1; fs.writeFileSync(taskJsonPath, JSON.stringify(taskJson, null, 4)); fs.writeFileSync(taskLocJsonPath, JSON.stringify(taskLocJson, null, 2)); // Check that task.loc and task.loc.json versions match if ((taskJson.version.Major !== taskLocJson.version.Major) || (taskJson.version.Minor !== taskLocJson.version.Minor) || (taskJson.version.Patch !== taskLocJson.version.Patch)) { console.log(`versions dont match for task '${taskName}', task json: ${JSON.stringify(taskJson.version)} task loc json: ${JSON.stringify(taskLocJson.version)}`); } }); } // Generate sprintly zip // This methods generate a zip file that contains the tip of all task major versions for the last sprint // Use: // node make.js gensprintlyzip --sprint=m153 --outputdir=E:\testing\ --depxmlpath=C:\Users\stfrance\Desktop\tempdeps.xml // // Result: // azure-pipelines.firstpartytasks.m153.zip // // The generated zip can be uploaded to an account using tfx cli and it will install all of the tasks contained in the zip. // The zip should be uploaded to the azure-pipelines-tasks repository // // Process: // // We create a workspace folder to do all of our work in. This is created in the output directory. output-dir/workspace-GUID // Inside here, we first create a package file based on the packages we want to download. // Then nuget restore, then get zips, then create zip. target.gensprintlyzip = function() { var sprint = options.sprint; var outputDirectory = options.outputdir; var dependenciesXmlFilePath = options.depxmlpath; var taskFeedUrl = 'https://mseng.pkgs.visualstudio.com/_packaging/Codex-Deps/nuget/v3/index.json'; console.log('# Creating sprintly zip.'); console.log('\n# Loading tasks from dependencies file.'); var dependencies = fs.readFileSync(dependenciesXmlFilePath, 'utf8'); var dependenciesArr = dependencies.split('\n'); console.log(`Found ${dependenciesArr.length} dependencies.`); var taskDependencies = []; var taskStringArr = []; dependenciesArr.forEach(function (currentDep) { if (currentDep.indexOf('Mseng.MS.TF.DistributedTask.Tasks.') === -1) { return; } taskStringArr.push(currentDep); var depDetails = currentDep.split("\""); var name = depDetails[1]; var version = depDetails[3]; taskDependencies.push({ 'name': name, 'version': version }); }); console.log(`Found ${taskDependencies.length} task dependencies.`); console.log('\n# Downloading task nuget packages.'); var tempWorkspaceDirectory = `${outputDirectory}\\workspace-${Math.floor(Math.random() * 1000000000)}`; console.log(`Creating temporary workspace directory ${tempWorkspaceDirectory}`); fs.mkdirSync(tempWorkspaceDirectory); console.log('Writing packages.config file'); var packagesConfigPath = `${tempWorkspaceDirectory}\\packages.config`; var packagesConfigContent = '<?xml version="1.0" encoding="utf-8"?>\n'; packagesConfigContent += '<packages>\n'; taskStringArr.forEach(function (taskString) { packagesConfigContent += taskString; }); packagesConfigContent += '</packages>'; fs.writeFileSync(packagesConfigPath, packagesConfigContent); console.log(`Completed writing packages.json file. ${packagesConfigPath}`); console.log('\n# Restoring NuGet packages.'); run(`nuget restore ${tempWorkspaceDirectory} -source "${taskFeedUrl}" -packagesdirectory ${tempWorkspaceDirectory}\\packages`); console.log('Restoring NuGet packages complete.'); console.log(`\n# Creating sprintly zip.`); var sprintlyZipContentsPath = `${tempWorkspaceDirectory}\\sprintly-zip`; fs.mkdirSync(sprintlyZipContentsPath); console.log('Sprintly zip folder created.'); console.log('Copying task zip files to sprintly zip folder.'); taskDependencies.forEach(function (taskDependency) { var nameAndVersion = `${taskDependency.name}.${taskDependency.version}`; var src = `${tempWorkspaceDirectory}\\packages\\${nameAndVersion}\\content\\task.zip`; // workspace-735475103\packages\Mseng.MS.TF.DistributedTask.Tasks.AndroidBuildV1.1.0.16\content\task.zip var dest = `${sprintlyZipContentsPath}\\${nameAndVersion}.zip`; // workspace-735475103\sprintly-zip\ fs.copyFileSync(src, dest); }); console.log('Copying task zip files to sprintly zip folder complete.'); console.log('Creating sprintly zip file from folder.'); var sprintlyZipPath = `${outputDirectory}azure-pipelines.firstpartytasks.${sprint}.zip`; var zip = new admzip(); zip.addLocalFolder(sprintlyZipContentsPath); zip.writeZip(sprintlyZipPath); console.log('Creating sprintly zip file from folder complete.'); console.log('\n# Cleaning up folders'); console.log(`Deleting temporary workspace directory ${tempWorkspaceDirectory}`); rm('-Rf', tempWorkspaceDirectory); console.log('\n# Completed creating sprintly zip.'); }
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import HistoriqueCommandesUtilisateur from 'components/HistoriqueCommandesUtilisateur'; export default class HistoriqueCommandes extends Component { static propTypes = { utilisateurId: PropTypes.string.isRequired, }; state = { commandeId: null, }; handleSelect = (event, value) => this.setState({ commandeId: value }); render() { const { utilisateurId } = this.props; const { commandeId } = this.state; return ( <HistoriqueCommandesUtilisateur utilisateurId={utilisateurId} commandeId={commandeId} onSelectCommande={this.handleSelect} /> ); } }
// All symbols in the Hiragana block as per Unicode v5.0.0: [ '\u3040', '\u3041', '\u3042', '\u3043', '\u3044', '\u3045', '\u3046', '\u3047', '\u3048', '\u3049', '\u304A', '\u304B', '\u304C', '\u304D', '\u304E', '\u304F', '\u3050', '\u3051', '\u3052', '\u3053', '\u3054', '\u3055', '\u3056', '\u3057', '\u3058', '\u3059', '\u305A', '\u305B', '\u305C', '\u305D', '\u305E', '\u305F', '\u3060', '\u3061', '\u3062', '\u3063', '\u3064', '\u3065', '\u3066', '\u3067', '\u3068', '\u3069', '\u306A', '\u306B', '\u306C', '\u306D', '\u306E', '\u306F', '\u3070', '\u3071', '\u3072', '\u3073', '\u3074', '\u3075', '\u3076', '\u3077', '\u3078', '\u3079', '\u307A', '\u307B', '\u307C', '\u307D', '\u307E', '\u307F', '\u3080', '\u3081', '\u3082', '\u3083', '\u3084', '\u3085', '\u3086', '\u3087', '\u3088', '\u3089', '\u308A', '\u308B', '\u308C', '\u308D', '\u308E', '\u308F', '\u3090', '\u3091', '\u3092', '\u3093', '\u3094', '\u3095', '\u3096', '\u3097', '\u3098', '\u3099', '\u309A', '\u309B', '\u309C', '\u309D', '\u309E', '\u309F' ];
module.exports = { Bitmap: require('./lib/bitmap') };
/** * QUnit - A JavaScript Unit Testing Framework * * http://docs.jquery.com/QUnit * * Copyright (c) 2011 John Resig, Jรถrn Zaefferer * Dual licensed under the MIT (MIT-LICENSE.txt) * or GPL (GPL-LICENSE.txt) licenses. * Pulled Live from Git Wed Sep 14 11:20:01 UTC 2011 * Last Commit: 96e42601cadcba989f80bd4c294b7e0ee4ff1d29 */ (function(window) { var defined = { setTimeout: typeof window.setTimeout !== "undefined", sessionStorage: (function() { try { return !!sessionStorage.getItem; } catch(e) { return false; } })() }; var testId = 0; var Test = function(name, testName, expected, testEnvironmentArg, async, callback) { this.name = name; this.testName = testName; this.expected = expected; this.testEnvironmentArg = testEnvironmentArg; this.async = async; this.callback = callback; this.assertions = []; }; Test.prototype = { init: function() { var tests = id("qunit-tests"); if (tests) { var b = document.createElement("strong"); b.innerHTML = "Running " + this.name; var li = document.createElement("li"); li.appendChild(b); li.className = "running"; li.id = this.id = "test-output" + testId++; tests.appendChild(li); } }, setup: function() { if (this.module != config.previousModule) { if (config.previousModule) { runLoggingCallbacks('moduleDone', QUnit, { name: config.previousModule, failed: config.moduleStats.bad, passed: config.moduleStats.all - config.moduleStats.bad, total: config.moduleStats.all }); } config.previousModule = this.module; config.moduleStats = { all: 0, bad: 0 }; runLoggingCallbacks('moduleStart', QUnit, { name: this.module }); } config.current = this; this.testEnvironment = extend({ setup: function() { }, teardown: function() { } }, this.moduleTestEnvironment); if (this.testEnvironmentArg) { extend(this.testEnvironment, this.testEnvironmentArg); } runLoggingCallbacks('testStart', QUnit, { name: this.testName }); // allow utility functions to access the current test environment // TODO why?? QUnit.current_testEnvironment = this.testEnvironment; try { if (!config.pollution) { saveGlobal(); } this.testEnvironment.setup.call(this.testEnvironment); } catch(e) { QUnit.ok(false, "Setup failed on " + this.testName + ": " + e.message); } }, run: function() { if (this.async) { QUnit.stop(); } if (config.notrycatch) { this.callback.call(this.testEnvironment); return; } try { this.callback.call(this.testEnvironment); } catch(e) { fail("Test " + this.testName + " died, exception and test follows", e, this.callback); QUnit.ok(false, "Died on test #" + (this.assertions.length + 1) + ": " + e.message + " - " + QUnit.jsDump.parse(e)); // else next test will carry the responsibility saveGlobal(); // Restart the tests if they're blocking if (config.blocking) { start(); } } }, teardown: function() { try { this.testEnvironment.teardown.call(this.testEnvironment); checkPollution(); } catch(e) { QUnit.ok(false, "Teardown failed on " + this.testName + ": " + e.message); } }, finish: function() { if (this.expected && this.expected != this.assertions.length) { QUnit.ok(false, "Expected " + this.expected + " assertions, but " + this.assertions.length + " were run"); } var good = 0, bad = 0, tests = id("qunit-tests"); config.stats.all += this.assertions.length; config.moduleStats.all += this.assertions.length; if (tests) { var ol = document.createElement("ol"); for (var i = 0; i < this.assertions.length; i++) { var assertion = this.assertions[i]; var li = document.createElement("li"); li.className = assertion.result ? "pass" : "fail"; li.innerHTML = assertion.message || (assertion.result ? "okay" : "failed"); ol.appendChild(li); if (assertion.result) { good++; } else { bad++; config.stats.bad++; config.moduleStats.bad++; } } // store result when possible if (QUnit.config.reorder && defined.sessionStorage) { if (bad) { sessionStorage.setItem("qunit-" + this.module + "-" + this.testName, bad); } else { sessionStorage.removeItem("qunit-" + this.module + "-" + this.testName); } } if (bad == 0) { ol.style.display = "none"; } var b = document.createElement("strong"); b.innerHTML = this.name + " <strong class='counts'>(<strong class='failed'>" + bad + "</strong>, <strong class='passed'>" + good + "</strong>, " + this.assertions.length + ")</strong>"; var a = document.createElement("a"); a.innerHTML = "Rerun"; a.href = QUnit.url({ filter: getText([b]).replace(/\([^)]+\)$/, "").replace(/(^\s*|\s*$)/g, "") }); addEvent(b, "click", function() { var next = b.nextSibling.nextSibling, display = next.style.display; next.style.display = display === "none" ? "block" : "none"; }); addEvent(b, "dblclick", function(e) { var target = e && e.target ? e.target : window.event.srcElement; if (target.nodeName.toLowerCase() == "span" || target.nodeName.toLowerCase() == "b") { target = target.parentNode; } if (window.location && target.nodeName.toLowerCase() === "strong") { window.location = QUnit.url({ filter: getText([target]).replace(/\([^)]+\)$/, "").replace(/(^\s*|\s*$)/g, "") }); } }); var li = id(this.id); li.className = bad ? "fail" : "pass"; li.removeChild(li.firstChild); li.appendChild(b); li.appendChild(a); li.appendChild(ol); } else { for (var i = 0; i < this.assertions.length; i++) { if (!this.assertions[i].result) { bad++; config.stats.bad++; config.moduleStats.bad++; } } } try { QUnit.reset(); } catch(e) { fail("reset() failed, following Test " + this.testName + ", exception and reset fn follows", e, QUnit.reset); } runLoggingCallbacks('testDone', QUnit, { name: this.testName, failed: bad, passed: this.assertions.length - bad, total: this.assertions.length }); }, queue: function() { var test = this; synchronize(function() { test.init(); }); function run() { // each of these can by async synchronize(function() { test.setup(); }); synchronize(function() { test.run(); }); synchronize(function() { test.teardown(); }); synchronize(function() { test.finish(); }); } // defer when previous test run passed, if storage is available var bad = QUnit.config.reorder && defined.sessionStorage && +sessionStorage.getItem("qunit-" + this.module + "-" + this.testName); if (bad) { run(); } else { synchronize(run); } ; } }; var QUnit = { // call on start of module test to prepend name to all tests module: function(name, testEnvironment) { config.currentModule = name; config.currentModuleTestEnviroment = testEnvironment; }, asyncTest: function(testName, expected, callback) { if (arguments.length === 2) { callback = expected; expected = 0; } QUnit.test(testName, expected, callback, true); }, test: function(testName, expected, callback, async) { var name = '<span class="test-name">' + testName + '</span>', testEnvironmentArg; if (arguments.length === 2) { callback = expected; expected = null; } // is 2nd argument a testEnvironment? if (expected && typeof expected === 'object') { testEnvironmentArg = expected; expected = null; } if (config.currentModule) { name = '<span class="module-name">' + config.currentModule + "</span>: " + name; } if (!validTest(config.currentModule + ": " + testName)) { return; } var test = new Test(name, testName, expected, testEnvironmentArg, async, callback); test.module = config.currentModule; test.moduleTestEnvironment = config.currentModuleTestEnviroment; test.queue(); }, /** * Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through. */ expect: function(asserts) { config.current.expected = asserts; }, /** * Asserts true. * @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" ); */ ok: function(a, msg) { a = !!a; var details = { result: a, message: msg }; msg = escapeHtml(msg); runLoggingCallbacks('log', QUnit, details); config.current.assertions.push({ result: a, message: msg }); }, /** * Checks that the first two arguments are equal, with an optional message. * Prints out both actual and expected values. * * Prefered to ok( actual == expected, message ) * * @example equal( format("Received {0} bytes.", 2), "Received 2 bytes." ); * * @param Object actual * @param Object expected * @param String message (optional) */ equal: function(actual, expected, message) { QUnit.push(expected == actual, actual, expected, message); }, notEqual: function(actual, expected, message) { QUnit.push(expected != actual, actual, expected, message); }, deepEqual: function(actual, expected, message) { QUnit.push(QUnit.equiv(actual, expected), actual, expected, message); }, notDeepEqual: function(actual, expected, message) { QUnit.push(!QUnit.equiv(actual, expected), actual, expected, message); }, strictEqual: function(actual, expected, message) { QUnit.push(expected === actual, actual, expected, message); }, notStrictEqual: function(actual, expected, message) { QUnit.push(expected !== actual, actual, expected, message); }, raises: function(block, expected, message) { var actual, ok = false; if (typeof expected === 'string') { message = expected; expected = null; } try { block(); } catch (e) { actual = e; } if (actual) { // we don't want to validate thrown error if (!expected) { ok = true; // expected is a regexp } else if (QUnit.objectType(expected) === "regexp") { ok = expected.test(actual); // expected is a constructor } else if (actual instanceof expected) { ok = true; // expected is a validation function which returns true is validation passed } else if (expected.call({}, actual) === true) { ok = true; } } QUnit.ok(ok, message); }, start: function() { config.semaphore--; if (config.semaphore > 0) { // don't start until equal number of stop-calls return; } if (config.semaphore < 0) { // ignore if start is called more often then stop config.semaphore = 0; } // A slight delay, to avoid any current callbacks if (defined.setTimeout) { window.setTimeout(function() { if (config.semaphore > 0) { return; } if (config.timeout) { clearTimeout(config.timeout); } config.blocking = false; process(); }, 13); } else { config.blocking = false; process(); } }, stop: function(timeout) { config.semaphore++; config.blocking = true; if (timeout && defined.setTimeout) { clearTimeout(config.timeout); config.timeout = window.setTimeout(function() { QUnit.ok(false, "Test timed out"); QUnit.start(); }, timeout); } } }; //We want access to the constructor's prototype (function() { function F() { } ; F.prototype = QUnit; QUnit = new F(); //Make F QUnit's constructor so that we can add to the prototype later QUnit.constructor = F; })(); // Backwards compatibility, deprecated QUnit.equals = QUnit.equal; QUnit.same = QUnit.deepEqual; // Maintain internal state var config = { // The queue of tests to run queue: [], // block until document ready blocking: true, // when enabled, show only failing tests // gets persisted through sessionStorage and can be changed in UI via checkbox hidepassed: false, // by default, run previously failed tests first // very useful in combination with "Hide passed tests" checked reorder: true, // by default, modify document.title when suite is done altertitle: true, urlConfig: ['noglobals', 'notrycatch'], //logging callback queues begin: [], done: [], log: [], testStart: [], testDone: [], moduleStart: [], moduleDone: [] }; // Load paramaters (function() { var location = window.location || { search: "", protocol: "file:" }, params = location.search.slice(1).split("&"), length = params.length, urlParams = {}, current; if (params[ 0 ]) { for (var i = 0; i < length; i++) { current = params[ i ].split("="); current[ 0 ] = decodeURIComponent(current[ 0 ]); // allow just a key to turn on a flag, e.g., test.html?noglobals current[ 1 ] = current[ 1 ] ? decodeURIComponent(current[ 1 ]) : true; urlParams[ current[ 0 ] ] = current[ 1 ]; } } QUnit.urlParams = urlParams; config.filter = urlParams.filter; // Figure out if we're running the tests from a server or not QUnit.isLocal = !!(location.protocol === 'file:'); })(); // Expose the API as global variables, unless an 'exports' // object exists, in that case we assume we're in CommonJS if (typeof exports === "undefined" || typeof require === "undefined") { extend(window, QUnit); window.QUnit = QUnit; } else { extend(exports, QUnit); exports.QUnit = QUnit; } // define these after exposing globals to keep them in these QUnit namespace only extend(QUnit, { config: config, // Initialize the configuration options init: function() { extend(config, { stats: { all: 0, bad: 0 }, moduleStats: { all: 0, bad: 0 }, started: +new Date, updateRate: 1000, blocking: false, autostart: true, autorun: false, filter: "", queue: [], semaphore: 0 }); var tests = id("qunit-tests"), banner = id("qunit-banner"), result = id("qunit-testresult"); if (tests) { tests.innerHTML = ""; } if (banner) { banner.className = ""; } if (result) { result.parentNode.removeChild(result); } if (tests) { result = document.createElement("p"); result.id = "qunit-testresult"; result.className = "result"; tests.parentNode.insertBefore(result, tests); result.innerHTML = 'Running...<br/>&nbsp;'; } }, /** * Resets the test setup. Useful for tests that modify the DOM. * * If jQuery is available, uses jQuery's html(), otherwise just innerHTML. */ reset: function() { if (window.jQuery) { jQuery("#qunit-fixture").html(config.fixture); } else { var main = id('qunit-fixture'); if (main) { main.innerHTML = config.fixture; } } }, /** * Trigger an event on an element. * * @example triggerEvent( document.body, "click" ); * * @param DOMElement elem * @param String type */ triggerEvent: function(elem, type, event) { if (document.createEvent) { event = document.createEvent("MouseEvents"); event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView, 0, 0, 0, 0, 0, false, false, false, false, 0, null); elem.dispatchEvent(event); } else if (elem.fireEvent) { elem.fireEvent("on" + type); } }, // Safe object type checking is: function(type, obj) { return QUnit.objectType(obj) == type; }, objectType: function(obj) { if (typeof obj === "undefined") { return "undefined"; // consider: typeof null === object } if (obj === null) { return "null"; } var type = Object.prototype.toString.call(obj) .match(/^\[object\s(.*)\]$/)[1] || ''; switch (type) { case 'Number': if (isNaN(obj)) { return "nan"; } else { return "number"; } case 'String': case 'Boolean': case 'Array': case 'Date': case 'RegExp': case 'Function': return type.toLowerCase(); } if (typeof obj === "object") { return "object"; } return undefined; }, push: function(result, actual, expected, message) { var details = { result: result, message: message, actual: actual, expected: expected }; message = escapeHtml(message) || (result ? "okay" : "failed"); message = '<span class="test-message">' + message + "</span>"; expected = escapeHtml(QUnit.jsDump.parse(expected)); actual = escapeHtml(QUnit.jsDump.parse(actual)); var output = message + '<table><tr class="test-expected"><th>Expected: </th><td><pre>' + expected + '</pre></td></tr>'; if (actual != expected) { output += '<tr class="test-actual"><th>Result: </th><td><pre>' + actual + '</pre></td></tr>'; output += '<tr class="test-diff"><th>Diff: </th><td><pre>' + QUnit.diff(expected, actual) + '</pre></td></tr>'; } if (!result) { var source = sourceFromStacktrace(); if (source) { details.source = source; output += '<tr class="test-source"><th>Source: </th><td><pre>' + escapeHtml(source) + '</pre></td></tr>'; } } output += "</table>"; runLoggingCallbacks('log', QUnit, details); config.current.assertions.push({ result: !!result, message: output }); }, url: function(params) { params = extend(extend({}, QUnit.urlParams), params); var querystring = "?", key; for (key in params) { querystring += encodeURIComponent(key) + "=" + encodeURIComponent(params[ key ]) + "&"; } return window.location.pathname + querystring.slice(0, -1); }, extend: extend, id: id, addEvent: addEvent, }); //QUnit.constructor is set to the empty F() above so that we can add to it's prototype later //Doing this allows us to tell if the following methods have been overwritten on the actual //QUnit object, which is a deprecated way of using the callbacks. extend(QUnit.constructor.prototype, { // Logging callbacks; all receive a single argument with the listed properties // run test/logs.html for any related changes begin: registerLoggingCallback('begin'), // done: { failed, passed, total, runtime } done: registerLoggingCallback('done'), // log: { result, actual, expected, message } log: registerLoggingCallback('log'), // testStart: { name } testStart: registerLoggingCallback('testStart'), // testDone: { name, failed, passed, total } testDone: registerLoggingCallback('testDone'), // moduleStart: { name } moduleStart: registerLoggingCallback('moduleStart'), // moduleDone: { name, failed, passed, total } moduleDone: registerLoggingCallback('moduleDone'), }); if (typeof document === "undefined" || document.readyState === "complete") { config.autorun = true; } QUnit.load = function() { runLoggingCallbacks('begin', QUnit, {}); // Initialize the config, saving the execution queue var oldconfig = extend({}, config); QUnit.init(); extend(config, oldconfig); config.blocking = false; var urlConfigHtml = '', len = config.urlConfig.length; for (var i = 0, val; i < len,val = config.urlConfig[i]; i++) { config[val] = QUnit.urlParams[val]; urlConfigHtml += '<label><input name="' + val + '" type="checkbox"' + ( config[val] ? ' checked="checked"' : '' ) + '>' + val + '</label>'; } var userAgent = id("qunit-userAgent"); if (userAgent) { userAgent.innerHTML = navigator.userAgent; } var banner = id("qunit-header"); if (banner) { banner.innerHTML = '<a href="' + QUnit.url({ filter: undefined }) + '"> ' + banner.innerHTML + '</a> ' + urlConfigHtml; addEvent(banner, "change", function(event) { var params = {}; params[ event.target.name ] = event.target.checked ? true : undefined; window.location = QUnit.url(params); }); } var toolbar = id("qunit-testrunner-toolbar"); if (toolbar) { var filter = document.createElement("input"); filter.type = "checkbox"; filter.id = "qunit-filter-pass"; addEvent(filter, "click", function() { var ol = document.getElementById("qunit-tests"); if (filter.checked) { ol.className = ol.className + " hidepass"; } else { var tmp = " " + ol.className.replace(/[\n\t\r]/g, " ") + " "; ol.className = tmp.replace(/ hidepass /, " "); } if (defined.sessionStorage) { if (filter.checked) { sessionStorage.setItem("qunit-filter-passed-tests", "true"); } else { sessionStorage.removeItem("qunit-filter-passed-tests"); } } }); if (config.hidepassed || defined.sessionStorage && sessionStorage.getItem("qunit-filter-passed-tests")) { filter.checked = true; var ol = document.getElementById("qunit-tests"); ol.className = ol.className + " hidepass"; } toolbar.appendChild(filter); var label = document.createElement("label"); label.setAttribute("for", "qunit-filter-pass"); label.innerHTML = "Hide passed tests"; toolbar.appendChild(label); } var main = id('qunit-fixture'); if (main) { config.fixture = main.innerHTML; } if (config.autostart) { QUnit.start(); } }; addEvent(window, "load", QUnit.load); function done() { config.autorun = true; // Log the last module results if (config.currentModule) { runLoggingCallbacks('moduleDone', QUnit, { name: config.currentModule, failed: config.moduleStats.bad, passed: config.moduleStats.all - config.moduleStats.bad, total: config.moduleStats.all }); } var banner = id("qunit-banner"), tests = id("qunit-tests"), runtime = +new Date - config.started, passed = config.stats.all - config.stats.bad, html = [ 'Tests completed in ', runtime, ' milliseconds.<br/>', '<span class="passed">', passed, '</span> tests of <span class="total">', config.stats.all, '</span> passed, <span class="failed">', config.stats.bad, '</span> failed.' ].join(''); if (banner) { banner.className = (config.stats.bad ? "qunit-fail" : "qunit-pass"); } if (tests) { id("qunit-testresult").innerHTML = html; } if (config.altertitle && typeof document !== "undefined" && document.title) { // show โœ– for good, โœ” for bad suite result in title // use escape sequences in case file gets loaded with non-utf-8-charset document.title = [ (config.stats.bad ? "\u2716" : "\u2714"), document.title.replace(/^[\u2714\u2716] /i, "") ].join(" "); } runLoggingCallbacks('done', QUnit, { failed: config.stats.bad, passed: passed, total: config.stats.all, runtime: runtime }); } function validTest(name) { var filter = config.filter, run = false; if (!filter) { return true; } var not = filter.charAt(0) === "!"; if (not) { filter = filter.slice(1); } if (name.indexOf(filter) !== -1) { return !not; } if (not) { run = true; } return run; } // so far supports only Firefox, Chrome and Opera (buggy) // could be extended in the future to use something like https://github.com/csnover/TraceKit function sourceFromStacktrace() { try { throw new Error(); } catch (e) { if (e.stacktrace) { // Opera return e.stacktrace.split("\n")[6]; } else if (e.stack) { // Firefox, Chrome return e.stack.split("\n")[4]; } else if (e.sourceURL) { // Safari, PhantomJS // TODO sourceURL points at the 'throw new Error' line above, useless //return e.sourceURL + ":" + e.line; } } } function escapeHtml(s) { if (!s) { return ""; } s = s + ""; return s.replace(/[\&"<>\\]/g, function(s) { switch (s) { case "&": return "&amp;"; case "\\": return "\\\\"; case '"': return '\"'; case "<": return "&lt;"; case ">": return "&gt;"; default: return s; } }); } function synchronize(callback) { config.queue.push(callback); if (config.autorun && !config.blocking) { process(); } } function process() { var start = (new Date()).getTime(); while (config.queue.length && !config.blocking) { if (config.updateRate <= 0 || (((new Date()).getTime() - start) < config.updateRate)) { config.queue.shift()(); } else { window.setTimeout(process, 13); break; } } if (!config.blocking && !config.queue.length) { done(); } } function saveGlobal() { config.pollution = []; if (config.noglobals) { for (var key in window) { config.pollution.push(key); } } } function checkPollution(name) { var old = config.pollution; saveGlobal(); var newGlobals = diff(config.pollution, old); if (newGlobals.length > 0) { ok(false, "Introduced global variable(s): " + newGlobals.join(", ")); } var deletedGlobals = diff(old, config.pollution); if (deletedGlobals.length > 0) { ok(false, "Deleted global variable(s): " + deletedGlobals.join(", ")); } } // returns a new Array with the elements that are in a but not in b function diff(a, b) { var result = a.slice(); for (var i = 0; i < result.length; i++) { for (var j = 0; j < b.length; j++) { if (result[i] === b[j]) { result.splice(i, 1); i--; break; } } } return result; } function fail(message, exception, callback) { if (typeof console !== "undefined" && console.error && console.warn) { console.error(message); console.error(exception); console.warn(callback.toString()); } else if (window.opera && opera.postError) { opera.postError(message, exception, callback.toString); } } function extend(a, b) { for (var prop in b) { if (b[prop] === undefined) { delete a[prop]; } else { a[prop] = b[prop]; } } return a; } function addEvent(elem, type, fn) { if (elem.addEventListener) { elem.addEventListener(type, fn, false); } else if (elem.attachEvent) { elem.attachEvent("on" + type, fn); } else { fn(); } } function id(name) { return !!(typeof document !== "undefined" && document && document.getElementById) && document.getElementById(name); } function registerLoggingCallback(key) { return function(callback) { config[key].push(callback); }; } // Supports deprecated method of completely overwriting logging callbacks function runLoggingCallbacks(key, scope, args) { //debugger; var callbacks; if (QUnit.hasOwnProperty(key)) { QUnit[key].call(scope, args); } else { callbacks = config[key]; for (var i = 0; i < callbacks.length; i++) { callbacks[i].call(scope, args); } } } // Test for equality any JavaScript type. // Author: Philippe Rathรฉ <[email protected]> QUnit.equiv = function () { var innerEquiv; // the real equiv function var callers = []; // stack to decide between skip/abort functions var parents = []; // stack to avoiding loops from circular referencing // Call the o related callback with the given arguments. function bindCallbacks(o, callbacks, args) { var prop = QUnit.objectType(o); if (prop) { if (QUnit.objectType(callbacks[prop]) === "function") { return callbacks[prop].apply(callbacks, args); } else { return callbacks[prop]; // or undefined } } } var callbacks = function () { // for string, boolean, number and null function useStrictEquality(b, a) { if (b instanceof a.constructor || a instanceof b.constructor) { // to catch short annotaion VS 'new' annotation of a // declaration // e.g. var i = 1; // var j = new Number(1); return a == b; } else { return a === b; } } return { "string" : useStrictEquality, "boolean" : useStrictEquality, "number" : useStrictEquality, "null" : useStrictEquality, "undefined" : useStrictEquality, "nan" : function(b) { return isNaN(b); }, "date" : function(b, a) { return QUnit.objectType(b) === "date" && a.valueOf() === b.valueOf(); }, "regexp" : function(b, a) { return QUnit.objectType(b) === "regexp" && a.source === b.source && // the regex itself a.global === b.global && // and its modifers // (gmi) ... a.ignoreCase === b.ignoreCase && a.multiline === b.multiline; }, // - skip when the property is a method of an instance (OOP) // - abort otherwise, // initial === would have catch identical references anyway "function" : function() { var caller = callers[callers.length - 1]; return caller !== Object && typeof caller !== "undefined"; }, "array" : function(b, a) { var i, j, loop; var len; // b could be an object literal here if (!(QUnit.objectType(b) === "array")) { return false; } len = a.length; if (len !== b.length) { // safe and faster return false; } // track reference to avoid circular references parents.push(a); for (i = 0; i < len; i++) { loop = false; for (j = 0; j < parents.length; j++) { if (parents[j] === a[i]) { loop = true;// dont rewalk array } } if (!loop && !innerEquiv(a[i], b[i])) { parents.pop(); return false; } } parents.pop(); return true; }, "object" : function(b, a) { var i, j, loop; var eq = true; // unless we can proove it var aProperties = [], bProperties = []; // collection of // strings // comparing constructors is more strict than using // instanceof if (a.constructor !== b.constructor) { return false; } // stack constructor before traversing properties callers.push(a.constructor); // track reference to avoid circular references parents.push(a); for (i in a) { // be strict: don't ensures hasOwnProperty // and go deep loop = false; for (j = 0; j < parents.length; j++) { if (parents[j] === a[i]) loop = true; // don't go down the same path // twice } aProperties.push(i); // collect a's properties if (!loop && !innerEquiv(a[i], b[i])) { eq = false; break; } } callers.pop(); // unstack, we are done parents.pop(); for (i in b) { bProperties.push(i); // collect b's properties } // Ensures identical properties name return eq && innerEquiv(aProperties.sort(), bProperties .sort()); } }; }(); innerEquiv = function() { // can take multiple arguments var args = Array.prototype.slice.apply(arguments); if (args.length < 2) { return true; // end transition } return (function(a, b) { if (a === b) { return true; // catch the most you can } else if (a === null || b === null || typeof a === "undefined" || typeof b === "undefined" || QUnit.objectType(a) !== QUnit.objectType(b)) { return false; // don't lose time with error prone cases } else { return bindCallbacks(a, callbacks, [ b, a ]); } // apply transition with (1..n) arguments })(args[0], args[1]) && arguments.callee.apply(this, args.splice(1, args.length - 1)); }; return innerEquiv; }(); /** * jsDump Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | * http://flesler.blogspot.com Licensed under BSD * (http://www.opensource.org/licenses/bsd-license.php) Date: 5/15/2008 * * @projectDescription Advanced and extensible data dumping for Javascript. * @version 1.0.0 * @author Ariel Flesler * @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html} */ QUnit.jsDump = (function() { function quote(str) { return '"' + str.toString().replace(/"/g, '\\"') + '"'; } ; function literal(o) { return o + ''; } ; function join(pre, arr, post) { var s = jsDump.separator(), base = jsDump.indent(), inner = jsDump.indent(1); if (arr.join) arr = arr.join(',' + s + inner); if (!arr) return pre + post; return [ pre, inner + arr, base + post ].join(s); } ; function array(arr, stack) { var i = arr.length, ret = Array(i); this.up(); while (i--) ret[i] = this.parse(arr[i], undefined, stack); this.down(); return join('[', ret, ']'); } ; var reName = /^function (\w+)/; var jsDump = { parse:function(obj, type, stack) { //type is used mostly internally, you can fix a (custom)type in advance stack = stack || [ ]; var parser = this.parsers[ type || this.typeOf(obj) ]; type = typeof parser; var inStack = inArray(obj, stack); if (inStack != -1) { return 'recursion(' + (inStack - stack.length) + ')'; } //else if (type == 'function') { stack.push(obj); var res = parser.call(this, obj, stack); stack.pop(); return res; } // else return (type == 'string') ? parser : this.parsers.error; }, typeOf:function(obj) { var type; if (obj === null) { type = "null"; } else if (typeof obj === "undefined") { type = "undefined"; } else if (QUnit.is("RegExp", obj)) { type = "regexp"; } else if (QUnit.is("Date", obj)) { type = "date"; } else if (QUnit.is("Function", obj)) { type = "function"; } else if (typeof obj.setInterval !== undefined && typeof obj.document !== "undefined" && typeof obj.nodeType === "undefined") { type = "window"; } else if (obj.nodeType === 9) { type = "document"; } else if (obj.nodeType) { type = "node"; } else if (typeof obj === "object" && typeof obj.length === "number" && obj.length >= 0) { type = "array"; } else { type = typeof obj; } return type; }, separator:function() { return this.multiline ? this.HTML ? '<br />' : '\n' : this.HTML ? '&nbsp;' : ' '; }, indent:function(extra) {// extra can be a number, shortcut for increasing-calling-decreasing if (!this.multiline) return ''; var chr = this.indentChar; if (this.HTML) chr = chr.replace(/\t/g, ' ').replace(/ /g, '&nbsp;'); return Array(this._depth_ + (extra || 0)).join(chr); }, up:function(a) { this._depth_ += a || 1; }, down:function(a) { this._depth_ -= a || 1; }, setParser:function(name, parser) { this.parsers[name] = parser; }, // The next 3 are exposed so you can use them quote:quote, literal:literal, join:join, // _depth_: 1, // This is the list of parsers, to modify them, use jsDump.setParser parsers:{ window: '[Window]', document: '[Document]', error:'[ERROR]', //when no parser is found, shouldn't happen unknown: '[Unknown]', 'null':'null', 'undefined':'undefined', 'function':function(fn) { var ret = 'function', name = 'name' in fn ? fn.name : (reName.exec(fn) || [])[1];//functions never have name in IE if (name) ret += ' ' + name; ret += '('; ret = [ ret, QUnit.jsDump.parse(fn, 'functionArgs'), '){'].join(''); return join(ret, QUnit.jsDump.parse(fn, 'functionCode'), '}'); }, array: array, nodelist: array, arguments: array, object:function(map, stack) { var ret = [ ]; QUnit.jsDump.up(); for (var key in map) { var val = map[key]; ret.push(QUnit.jsDump.parse(key, 'key') + ': ' + QUnit.jsDump.parse(val, undefined, stack)); } QUnit.jsDump.down(); return join('{', ret, '}'); }, node:function(node) { var open = QUnit.jsDump.HTML ? '&lt;' : '<', close = QUnit.jsDump.HTML ? '&gt;' : '>'; var tag = node.nodeName.toLowerCase(), ret = open + tag; for (var a in QUnit.jsDump.DOMAttrs) { var val = node[QUnit.jsDump.DOMAttrs[a]]; if (val) ret += ' ' + a + '=' + QUnit.jsDump.parse(val, 'attribute'); } return ret + close + open + '/' + tag + close; }, functionArgs:function(fn) {//function calls it internally, it's the arguments part of the function var l = fn.length; if (!l) return ''; var args = Array(l); while (l--) args[l] = String.fromCharCode(97 + l);//97 is 'a' return ' ' + args.join(', ') + ' '; }, key:quote, //object calls it internally, the key part of an item in a map functionCode:'[code]', //function calls it internally, it's the content of the function attribute:quote, //node calls it internally, it's an html attribute value string:quote, date:quote, regexp:literal, //regex number:literal, 'boolean':literal }, DOMAttrs:{//attributes to dump from nodes, name=>realName id:'id', name:'name', 'class':'className' }, HTML:false,//if true, entities are escaped ( <, >, \t, space and \n ) indentChar:' ',//indentation unit multiline:true //if true, items in a collection, are separated by a \n, else just a space. }; return jsDump; })(); // from Sizzle.js function getText(elems) { var ret = "", elem; for (var i = 0; elems[i]; i++) { elem = elems[i]; // Get the text from text nodes and CDATA nodes if (elem.nodeType === 3 || elem.nodeType === 4) { ret += elem.nodeValue; // Traverse everything else, except comment nodes } else if (elem.nodeType !== 8) { ret += getText(elem.childNodes); } } return ret; } ; //from jquery.js function inArray(elem, array) { if (array.indexOf) { return array.indexOf(elem); } for (var i = 0, length = array.length; i < length; i++) { if (array[ i ] === elem) { return i; } } return -1; } /* * Javascript Diff Algorithm * By John Resig (http://ejohn.org/) * Modified by Chu Alan "sprite" * * Released under the MIT license. * * More Info: * http://ejohn.org/projects/javascript-diff-algorithm/ * * Usage: QUnit.diff(expected, actual) * * QUnit.diff("the quick brown fox jumped over", "the quick fox jumps over") == "the quick <del>brown </del> fox <del>jumped </del><ins>jumps </ins> over" */ QUnit.diff = (function() { function diff(o, n) { var ns = {}; var os = {}; for (var i = 0; i < n.length; i++) { if (ns[n[i]] == null) ns[n[i]] = { rows: [], o: null }; ns[n[i]].rows.push(i); } for (var i = 0; i < o.length; i++) { if (os[o[i]] == null) os[o[i]] = { rows: [], n: null }; os[o[i]].rows.push(i); } for (var i in ns) { if (ns[i].rows.length == 1 && typeof(os[i]) != "undefined" && os[i].rows.length == 1) { n[ns[i].rows[0]] = { text: n[ns[i].rows[0]], row: os[i].rows[0] }; o[os[i].rows[0]] = { text: o[os[i].rows[0]], row: ns[i].rows[0] }; } } for (var i = 0; i < n.length - 1; i++) { if (n[i].text != null && n[i + 1].text == null && n[i].row + 1 < o.length && o[n[i].row + 1].text == null && n[i + 1] == o[n[i].row + 1]) { n[i + 1] = { text: n[i + 1], row: n[i].row + 1 }; o[n[i].row + 1] = { text: o[n[i].row + 1], row: i + 1 }; } } for (var i = n.length - 1; i > 0; i--) { if (n[i].text != null && n[i - 1].text == null && n[i].row > 0 && o[n[i].row - 1].text == null && n[i - 1] == o[n[i].row - 1]) { n[i - 1] = { text: n[i - 1], row: n[i].row - 1 }; o[n[i].row - 1] = { text: o[n[i].row - 1], row: i - 1 }; } } return { o: o, n: n }; } return function(o, n) { o = o.replace(/\s+$/, ''); n = n.replace(/\s+$/, ''); var out = diff(o == "" ? [] : o.split(/\s+/), n == "" ? [] : n.split(/\s+/)); var str = ""; var oSpace = o.match(/\s+/g); if (oSpace == null) { oSpace = [" "]; } else { oSpace.push(" "); } var nSpace = n.match(/\s+/g); if (nSpace == null) { nSpace = [" "]; } else { nSpace.push(" "); } if (out.n.length == 0) { for (var i = 0; i < out.o.length; i++) { str += '<del>' + out.o[i] + oSpace[i] + "</del>"; } } else { if (out.n[0].text == null) { for (n = 0; n < out.o.length && out.o[n].text == null; n++) { str += '<del>' + out.o[n] + oSpace[n] + "</del>"; } } for (var i = 0; i < out.n.length; i++) { if (out.n[i].text == null) { str += '<ins>' + out.n[i] + nSpace[i] + "</ins>"; } else { var pre = ""; for (n = out.n[i].row + 1; n < out.o.length && out.o[n].text == null; n++) { pre += '<del>' + out.o[n] + oSpace[n] + "</del>"; } str += " " + out.n[i].text + nSpace[i] + pre; } } } return str; }; })(); })(this);
import { h, Component } from 'preact'; import { bind } from 'decko'; export default class TodoItem extends Component { shouldComponentUpdate({ todo, onRemove }) { return todo!==this.props.todo || onRemove!==this.props.onRemove; } @bind remove() { let { onRemove, todo } = this.props; onRemove(todo); } render({ todo }) { return ( <li> <button onClick={this.remove}>&times;</button> { ' ' + todo.text } </li> ); } }
module.exports = { extends: 'airbnb', env: { 'mocha': true }, rules: { 'arrow-body-style': ['error', 'always'] } };
version https://git-lfs.github.com/spec/v1 oid sha256:a6403d8d6ac6a60c0935fd3e3251d7e2f30be098f94483b89a8720349710e3b0 size 2166
import { Configurator } from 'substance' import SaveHandlerStub from './SaveHandlerStub' import FileClientStub from './FileClientStub' class TextureConfigurator extends Configurator { constructor(...args) { super(...args) this.config.saveHandler = new SaveHandlerStub() this.config.fileClient = new FileClientStub() this.config.xmlStore = null this.config.InterfaceComponentClass = null } setInterfaceComponentClass(Class) { if (this.config.InterfaceComponentClass) { throw new Error("InterfaceComponetClass can't be set twice") } this.config.InterfaceComponentClass = Class } getInterfaceComponentClass() { return this.config.InterfaceComponentClass } setSaveHandler(saveHandler) { this.config.saveHandler = saveHandler } setFileClient(fileClient) { this.config.fileClient = fileClient } getFileClient() { return this.config.fileClient } getSaveHandler() { return this.config.saveHandler } setXMLStore(XMLStoreClass, params) { this.config.xmlStore = { Class: XMLStoreClass, params: params } return this } getXMLStore() { let xmlStore = this.config.xmlStore let XMLStoreClass = this.config.xmlStore.Class return new XMLStoreClass(this.config.xmlStore.params) } } export default TextureConfigurator
/*! * Kratos * Seaton Jiang <[email protected]> */ ;(function () { 'use strict' var KRATOS_VERSION = '4.0.1' var navbarConfig = function () { $('#navbutton').on('click', function () { $('.navbar-toggler').toggleClass('nav-close') }) } var tooltipConfig = function () { $(function () { $('[data-toggle="tooltip"]').tooltip() }) } var gotopConfig = function () { $(window).on('load', function () { var $win = $(window) var setShowOrHide = function () { if ($win.scrollTop() > 200) { $('.gotop').addClass('active') } else { $('.gotop').removeClass('active') } } setShowOrHide() $win.scroll(setShowOrHide) }) $('.gotop').on('click', function (event) { event.preventDefault() $('html, body').animate( { scrollTop: $('html').offset().top }, 500 ) return false }) } var searchConfig = function () { $('.search').on('click', function (e) { $('.search-form').animate( { width: '200px' }, 200 ), $('.search-form input').css('display', 'block') $(document).one('click', function () { $('.search-form').animate( { width: '0' }, 100 ), $('.search-form input').hide() }) e.stopPropagation() }) $('.search-form').on('click', function (e) { e.stopPropagation() }) } var wechatConfig = function () { $('.wechat').mouseout(function () { $('.wechat-pic')[0].style.display = 'none' }) $('.wechat').mouseover(function () { $('.wechat-pic')[0].style.display = 'block' }) } var smiliesConfig = function () { $('#addsmile').on('click', function (e) { $('.smile').toggleClass('open') $(document).one('click', function () { $('.smile').toggleClass('open') }) e.stopPropagation() return false }) } var postlikeConfig = function () { $.fn.postLike = function () { if ($(this).hasClass('done')) { layer.msg(kratos.repeat, function () {}) return false } else { $(this).addClass('done') layer.msg(kratos.thanks) var id = $(this).data('id'), action = $(this).data('action') var ajax_data = { action: 'love', um_id: id, um_action: action } $.post(kratos.site + '/wp-admin/admin-ajax.php', ajax_data, function (data) {}) return false } } $(document).on('click', '.btn-thumbs', function () { $(this).postLike() }) } var donateConfig = function () { $('#donate').on('click', function () { layer.open({ type: 1, area: ['300px', '370px'], title: kratos.donate, resize: false, scrollbar: false, content: '<div class="donate-box"><div class="meta-pay text-center my-2"><strong>' + kratos.scan + '</strong></div><div class="qr-pay text-center"><img class="pay-img" id="alipay_qr" src="' + kratos.alipay + '"><img class="pay-img d-none" id="wechat_qr" src="' + kratos.wechat + '"></div><div class="choose-pay text-center mt-2"><input id="alipay" type="radio" name="pay-method" checked><label for="alipay" class="pay-button"><img src="' + kratos.directory + '/assets/img/payment/alipay.png"></label><input id="wechatpay" type="radio" name="pay-method"><label for="wechatpay" class="pay-button"><img src="' + kratos.directory + '/assets/img/payment/wechat.png"></label></div></div>' }) $(".choose-pay input[type='radio']").click(function () { var id = $(this).attr('id') if (id == 'alipay') { $('.qr-pay #alipay_qr').removeClass('d-none') $('.qr-pay #wechat_qr').addClass('d-none') } if (id == 'wechatpay') { $('.qr-pay #alipay_qr').addClass('d-none') $('.qr-pay #wechat_qr').removeClass('d-none') } }) }) } var accordionConfig = function () { $(document).on('click', '.acheader', function (event) { var $this = $(this) $this.closest('.accordion').find('.contents').slideToggle(300) if ($this.closest('.accordion').hasClass('active')) { $this.closest('.accordion').removeClass('active') } else { $this.closest('.accordion').addClass('active') } event.preventDefault() }) } var consoleConfig = function () { console.log('\n Kratos v' + KRATOS_VERSION + '\n\n https://github.com/vtrois/kratos \n\n') } var lightGalleryConfig = function () { lightGallery(document.getElementById('lightgallery'), { selector: 'a[href$=".jpg"], a[href$=".jpeg"], a[href$=".png"], a[href$=".gif"], a[href$=".bmp"], a[href$=".webp"]' }) } $(function () { accordionConfig() navbarConfig() tooltipConfig() gotopConfig() searchConfig() wechatConfig() smiliesConfig() postlikeConfig() donateConfig() consoleConfig() lightGalleryConfig() }) })() function grin(tag) { var myField tag = ' ' + tag + ' ' if (document.getElementById('comment') && document.getElementById('comment').type == 'textarea') { myField = document.getElementById('comment') } else { return false } if (document.selection) { myField.focus() sel = document.selection.createRange() sel.text = tag myField.focus() } else if (myField.selectionStart || myField.selectionStart == '0') { var startPos = myField.selectionStart var endPos = myField.selectionEnd var cursorPos = endPos myField.value = myField.value.substring(0, startPos) + tag + myField.value.substring(endPos, myField.value.length) cursorPos += tag.length myField.focus() myField.selectionStart = cursorPos myField.selectionEnd = cursorPos } else { myField.value += tag myField.focus() } }
var classJson_1_1StreamWriterBuilder = [ [ "StreamWriterBuilder", "classJson_1_1StreamWriterBuilder.html#ab95b76179c152673ad14abc639a46ee4", null ], [ "~StreamWriterBuilder", "classJson_1_1StreamWriterBuilder.html#a93263f8ef1e2d22593907075d8f0aaef", null ], [ "newStreamWriter", "classJson_1_1StreamWriterBuilder.html#ab9ee278609f88ae04a7c1a84e1f559e6", null ], [ "operator[]", "classJson_1_1StreamWriterBuilder.html#af68f6b59cb20b074052ed12bb3d336a3", null ], [ "validate", "classJson_1_1StreamWriterBuilder.html#a12353b97766841db7d049da84658da09", null ], [ "settings_", "classJson_1_1StreamWriterBuilder.html#a79bdf2e639a52f4e758c0b95bd1d3423", null ] ];
/*! * Bootstrap-select v1.7.3 (http://silviomoreto.github.io/bootstrap-select) * * Copyright 2013-2015 bootstrap-select * Licensed under MIT (https://github.com/silviomoreto/bootstrap-select/blob/master/LICENSE) */ (function (root, factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module unless amdModuleId is set define(["jquery"], function (a0) { return (factory(a0)); }); } else if (typeof exports === 'object') { // Node. Does not work with strict CommonJS, but // only CommonJS-like environments that support module.exports, // like Node. module.exports = factory(require("jquery")); } else { factory(jQuery); } }(this, function (jQuery) { (function ($) { $.fn.selectpicker.defaults = { noneSelectedText: 'Nic nenรญ vybrรกno', noneResultsText: 'ลฝรกdnรฉ vรฝsledky {0}', countSelectedText: 'Oznaฤeno {0} z {1}', maxOptionsText: ['Limit pล™ekroฤen ({n} {var} max)', 'Limit skupiny pล™ekroฤen ({n} {var} max)', ['poloลพek', 'poloลพka']], multipleSeparator: ', ' }; })(jQuery); }));
const isNumber = require("../object/isNumber.js"); /** * Evaluate if a value is a port. * @param {Number} value The value to evaluate * @returns {Boolean} True if value is a port, false otherwise */ function isPort(value) { value = parseInt(value, 10); if (!isNumber(value)) return false; return value >= 0 && value <= 65535; } module.exports = isPort;
import React from 'react-native'; import stacktraceParser from 'stacktrace-parser'; // import _ from 'underscore'; const NativeBugsnag = React.NativeModules.RNBugsnag; /* * The instance of our singleton * Setting up block level variable to store class state * , set's to null by default. */ let instance = null; let exceptionID = 0; //exception report timeout const timeoutPromise = new Promise((resolve) => { setTimeout(() => { resolve(); }, 1000); }); const parseErrorStack = (error)=>{ if (!error || !error.stack) { return []; } return Array.isArray(error.stack) ? error.stack : stacktraceParser.parse(error.stack); } export default class RNBugsnag { /** * ## Constructor */ constructor( props ) { //Singleton pattern, see here(http://amanvirk.me/singleton-classes-in-es6/) if(!instance){ //Initializing singleton instance instance = this; //intercept react-native error handling if (NativeBugsnag && ErrorUtils._globalHandler) { this.defaultHandler = ErrorUtils.getGlobalHandler && ErrorUtils.getGlobalHandler() || ErrorUtils._globalHandler; ErrorUtils.setGlobalHandler(this.wrapGlobalHandler.bind(this)); //feed errors directly to our wrapGlobalHandler function } if(!!props && !!props.identifier){ this.setIdentifier(props.identifier.userId, props.identifier.userEmail, props.identifier.userFullname); } if(!!props && props.suppressDevErrors!=null) { //if the user has specified wether to suppress or not this.setSuppressDebugOnDev(!!props.suppressDevErrors); //do what the user wishes to do }else{ //otherwise this.setSuppressDebugOnDev(__DEV__===true); // if on DEV suppress all the errors, otherwise don't } } return instance; } async setSuppressDebugOnDev(suppress){ return await NativeBugsnag.setSuppressDebug(suppress); } async wrapGlobalHandler(error, isFatal){ let currentExceptionID = ++exceptionID; const stack = parseErrorStack(error); const reportExceptionPromise = NativeBugsnag.reportException(error.message, stack, currentExceptionID, {}, isFatal); //submit the exception to our native part return Promise.race([reportExceptionPromise, timeoutPromise]) //whatever finishes first .then(() => { //afterwards call the default error handler this.defaultHandler(error, isFatal); }); } async notify(exceptionTitle, exceptionReason, severity, otherData){ return await NativeBugsnag.notify(exceptionTitle, exceptionReason, severity, otherData); } async leaveBreadcrumb(message){ return await NativeBugsnag.leaveBreadcrumb(message); } async setContext(context){ return await NativeBugsnag.setContext(context); } async setReleaseStage(releaseStage){ return await NativeBugsnag.setReleaseStage(releaseStage); } async setAppVersion(appVersion){ return await NativeBugsnag.setAppVersion(appVersion); } async setIdentifier(userId, userEmail, userFullname){ return await NativeBugsnag.setIdentifier(userId, userEmail, userFullname); } };
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var BaseHandler = function () { function BaseHandler() { _classCallCheck(this, BaseHandler); } _createClass(BaseHandler, [{ key: 'filterParams', value: function filterParams(params, whitelist) { var filtered = {}; for (var key in params) { if (whitelist.indexOf(key) > -1) { filtered[key] = params[key]; } } return filtered; } }, { key: 'formatApiError', value: function formatApiError(err) { if (!err) { // eslint-disable-next-line no-console return console.error('Provide an error'); } var formatted = { message: err.message }; if (err.errors) { formatted.errors = {}; var errors = err.errors; for (var type in errors) { formatted.errors[type] = errors[type].message; } } return formatted; } }]); return BaseHandler; }(); exports.default = BaseHandler;
import { module, test } from 'qunit'; import { setupTest } from 'ember-qunit'; module('Unit | Route | session/index', function (hooks) { setupTest(hooks); test('it exists', function (assert) { const route = this.owner.lookup('route:session/index'); assert.ok(route); }); });
import React, {PropTypes, Component} from 'react'; import reactElementToJSXString from 'react-element-to-jsx-string'; import AutoCompleteComposite from '../../src/AutoCompleteComposite'; import AutoComplete from '../../src/AutoComplete'; import Label from '../../src/Label'; export default class Form extends Component { static propTypes = { onChange: PropTypes.func.isRequired, withLabel: PropTypes.bool, label: PropTypes.object, autoComplete: PropTypes.object }; componentDidUpdate(props) { props.onChange(reactElementToJSXString(this.getComponent())); } componentDidMount() { this.props.onChange(reactElementToJSXString(this.getComponent())); } getComponent() { return ( <AutoCompleteComposite> {this.props.withLabel ? <Label for="firstName" {...this.props.label}/> : null} <AutoComplete id="firstName" {...this.props.autoComplete}/> </AutoCompleteComposite> ); } render() { return this.getComponent(); } }
(function () { /* Imports */ var Meteor = Package.meteor.Meteor; var _ = Package.underscore._; var Accounts = Package['accounts-base'].Accounts; var Twitter = Package.twitter.Twitter; var HTTP = Package.http.HTTP; (function () { ///////////////////////////////////////////////////////////////////////////////////////////////////////// // // // packages/accounts-twitter/twitter.js // // // ///////////////////////////////////////////////////////////////////////////////////////////////////////// // Accounts.oauth.registerService('twitter'); // 1 // 2 if (Meteor.isClient) { // 3 Meteor.loginWithTwitter = function(options, callback) { // 4 // support a callback without options // 5 if (! callback && typeof options === "function") { // 6 callback = options; // 7 options = null; // 8 } // 9 // 10 var credentialRequestCompleteCallback = Accounts.oauth.credentialRequestCompleteHandler(callback); // 11 Twitter.requestCredential(options, credentialRequestCompleteCallback); // 12 }; // 13 } else { // 14 var autopublishedFields = _.map( // 15 // don't send access token. https://dev.twitter.com/discussions/5025 // 16 Twitter.whitelistedFields.concat(['id', 'screenName']), // 17 function (subfield) { return 'services.twitter.' + subfield; }); // 18 // 19 Accounts.addAutopublishFields({ // 20 forLoggedInUser: autopublishedFields, // 21 forOtherUsers: autopublishedFields // 22 }); // 23 } // 24 // 25 ///////////////////////////////////////////////////////////////////////////////////////////////////////// }).call(this); /* Exports */ if (typeof Package === 'undefined') Package = {}; Package['accounts-twitter'] = {}; })(); //# sourceMappingURL=accounts-twitter.js.map
const _ = require('lodash') const mongoose = require('mongoose') const request = require('supertest') const should = require('should') const nassert = require('n-assert') const app = require('../../src/app') const User = mongoose.model('user') describe('users / controller', () => { describe('getUsers', () => { let initialUsers = [ { _id: nassert.getObjectId(), name: 'user1', email: '[email protected]' }, { _id: nassert.getObjectId(), name: 'user2', email: '[email protected]' }, { _id: nassert.getObjectId(), name: 'user3', email: '[email protected]' } ] async function test({ expectedStatus, expectedBody }) { await User.create(initialUsers) return request(app) .get('/api/users/') .expect(expectedStatus) .expect('Content-Type', /json/) .expect(res => nassert.assert(_.sortBy(res.body, 'userId'), _.sortBy(expectedBody, 'userId'))) } it('should return status 200 and list of users', () => { let expectedStatus = 200 let expectedBody = _.map(initialUsers, user => { let userCopy = _.cloneDeep(user) userCopy.userId = user._id // rewrite id after clone delete userCopy._id return userCopy }) return test({ expectedStatus, expectedBody }) }) }) describe('getUserById', () => { let initialUsers = [ { _id: nassert.getObjectId(), name: 'user1', email: '[email protected]' }, { _id: nassert.getObjectId(), name: 'user2', email: '[email protected]' }, { _id: nassert.getObjectId(), name: 'user3', email: '[email protected]' } ] async function test({ userId, expectedStatus, expectedBody }) { await User.create(initialUsers) return request(app) .get('/api/users/' + userId) .expect(expectedStatus) .expect('Content-Type', /json/) .expect(res => nassert.assert(res.body, expectedBody)) } it('should return status 422 when req.params.userId is invalid', () => { let userId = 'Invalid Id' let expectedStatus = 422 let expectedBody = { message: 'userId must be a valid ObjectId' } return test({ userId, expectedStatus, expectedBody }) }) it('should return status 404 when user is not found by req.params.userId', () => { let userId = nassert.getObjectId() let expectedStatus = 404 let expectedBody = { message: 'user is not found' } return test({ userId, expectedStatus, expectedBody }) }) it('should return status 200 and user', () => { let userId = initialUsers[0]._id let expectedStatus = 200 let expectedBody = _.cloneDeep(initialUsers[0]) expectedBody.userId = userId delete expectedBody._id return test({ userId, expectedStatus, expectedBody }) }) }) describe('createUser', () => { let initialUsers = [ { _id: nassert.getObjectId(), name: 'user1', email: '[email protected]' }, { _id: nassert.getObjectId(), name: 'user2', email: '[email protected]' }, { _id: nassert.getObjectId(), name: 'user3', email: '[email protected]' } ] async function test({ userData, expectedStatus, expectedBody }) { await User.create(initialUsers) return request(app) .post('/api/users') .send(userData) .expect(expectedStatus) .expect('Content-Type', /application\/json/) .expect(res => nassert.assert(res.body, expectedBody)) } it('should return status 422 when req.body is empty', () => { let userData let expectedStatus = 422 let expectedBody = { message: 'name is required' } return test({ userData, expectedStatus, expectedBody }) }) it('should return status 422 when req.body.name is undefined', () => { let userData = { email: '[email protected]' } let expectedStatus = 422 let expectedBody = { message: 'name is required' } return test({ userData, expectedStatus, expectedBody }) }) it('should return status 422 when req.body.email is undefined', () => { let userData = { name: 'new-user' } let expectedStatus = 422 let expectedBody = { message: 'email is required' } return test({ userData, expectedStatus, expectedBody }) }) it('should return status 422 when req.body.email is not valid email', () => { let userData = { name: 'new-user', email: 'invalidEmail' } let expectedStatus = 422 let expectedBody = { message: 'email must be a valid email address' } return test({ userData, expectedStatus, expectedBody }) }) it('should return status 200 and create a new user when req.body is valid', () => { let userData = { name: 'new-user', email: '[email protected]' } let expectedStatus = 201 let expectedBody = { userId: '_mock_', name: 'new-user', email: '[email protected]' } return test({ userData, expectedStatus, expectedBody }) }) }) describe('updateUser', () => { let initialUsers = [ { _id: nassert.getObjectId(), name: 'user1', email: '[email protected]' }, { _id: nassert.getObjectId(), name: 'user2', email: '[email protected]' }, { _id: nassert.getObjectId(), name: 'user3', email: '[email protected]' } ] async function test({ userId, userData, expectedStatus, expectedBody }) { await User.create(initialUsers) return request(app) .put('/api/users/' + userId) .send(userData) .expect(expectedStatus) .expect(res => { if (expectedStatus === 204) { should(res.headers['content-type']).is.undefined } else { should(res.headers['content-type']).match(/application\/json/) } nassert.assert(res.body, expectedBody, true) }) } it('should return status 422 when req.params.userId is invalid', () => { let userId = 'InvalidId' let userData = { name: 'user1-new', email: '[email protected]' } let expectedStatus = 422 let expectedBody = { message: 'userId must be a valid ObjectId' } return test({ userId, userData, expectedStatus, expectedBody }) }) it('should return status 422 when req.body is empty', () => { let userId = initialUsers[0]._id let userData let expectedStatus = 422 let expectedBody = { message: 'name is required' } return test({ userId, userData, expectedStatus, expectedBody }) }) it('should return status 422 when req.body.name is undefined', () => { let userId = initialUsers[0]._id let userData = { email: '[email protected]' } let expectedStatus = 422 let expectedBody = { message: 'name is required' } return test({ userId, userData, expectedStatus, expectedBody }) }) it('should return status 422 when req.body.email is undefined', () => { let userId = initialUsers[0]._id let userData = { name: 'user1-new' } let expectedStatus = 422 let expectedBody = { message: 'email is required' } return test({ userId, userData, expectedStatus, expectedBody }) }) it('should return status 422 when req.body.email is not valid email', () => { let userId = initialUsers[0]._id let userData = { name: 'user1-new', email: 'invalidEmail' } let expectedStatus = 422 let expectedBody = { message: 'email must be a valid email address' } return test({ userId, userData, expectedStatus, expectedBody }) }) it('should return status 404 when user is not found by req.params.userId', () => { let userId = nassert.getObjectId() let userData = { name: 'user1-new', email: '[email protected]' } let expectedStatus = 404 let expectedBody = { message: 'user is not found' } return test({ userId, userData, expectedStatus, expectedBody }) }) it('should return status 200 and update an user when req.body is valid', () => { let userId = initialUsers[0]._id let userData = { name: 'user1-new', email: '[email protected]' } let expectedStatus = 204 let expectedBody = {} return test({ userId, userData, expectedStatus, expectedBody }) }) }) describe('deleteUser', () => { let initialUsers = [ { _id: nassert.getObjectId(), name: 'user1', email: '[email protected]' }, { _id: nassert.getObjectId(), name: 'user2', email: '[email protected]' }, { _id: nassert.getObjectId(), name: 'user3', email: '[email protected]' } ] async function test({ userId, expectedStatus, expectedBody }) { await User.create(initialUsers) return request(app) .delete('/api/users/' + userId) .expect(expectedStatus) .expect(res => { if (expectedStatus === 204) { should(res.headers['content-type']).is.undefined } else { should(res.headers['content-type']).match(/application\/json/) } nassert.assert(res.body, expectedBody, true) }) } it('should return status 422 when req.params.userId is invalid', () => { let userId = 'Invalid Id' let expectedStatus = 422 let expectedBody = { message: 'userId must be a valid ObjectId' } return test({ userId, expectedStatus, expectedBody }) }) it('should return status 404 when user is not found by req.params.userId', () => { let userId = nassert.getObjectId() let expectedStatus = 404 let expectedBody = { message: 'user is not found' } return test({ userId, expectedStatus, expectedBody }) }) it('should return status 204 and delete user', () => { let userId = initialUsers[0]._id let expectedStatus = 204 let expectedBody = {} return test({ userId, expectedStatus, expectedBody }) }) }) })
var Icon = require('../icon'); var element = require('magic-virtual-element'); var clone = require('../clone'); exports.render = function render(component) { var props = clone(component.props); delete props.children; return element( Icon, props, element('path', { d: 'M16.05 16.29l2.86-3.07c.38-.39.72-.79 1.04-1.18.32-.39.59-.78.82-1.17.23-.39.41-.78.54-1.17.13-.39.19-.79.19-1.18 0-.53-.09-1.02-.27-1.46-.18-.44-.44-.81-.78-1.11-.34-.31-.77-.54-1.26-.71-.51-.16-1.08-.24-1.72-.24-.69 0-1.31.11-1.85.32-.54.21-1 .51-1.36.88-.37.37-.65.8-.84 1.3-.18.47-.27.97-.28 1.5h2.14c.01-.31.05-.6.13-.87.09-.29.23-.54.4-.75.18-.21.41-.37.68-.49.27-.12.6-.18.96-.18.31 0 .58.05.81.15.23.1.43.25.59.43.16.18.28.4.37.65.08.25.13.52.13.81 0 .22-.03.43-.08.65-.06.22-.15.45-.29.7-.14.25-.32.53-.56.83-.23.3-.52.65-.88 1.03l-4.17 4.55V18H22v-1.71h-5.95zM8 7H6v4H2v2h4v4h2v-4h4v-2H8V7z' }) ); };
/** * ์‹œํ€€์Šค ์ด๋ฏธ์ง€์— ๋Œ€ํ•œ ํ•˜๋‚˜์˜ ์ธ์Šคํ„ด์Šค๋ฅผ ์ƒ์„ฑํ•œ๋‹ค. * @class * @param {Int} width ํ•œ ์ปท์˜ ์ด๋ฏธ์ง€ ๋„“์ด * @param {Int} height ํ•œ ์ปท์˜ ์ด๋ฏธ์ง€ ๋†’์ด * @param {Int} scene ์ปท ๊ฐฏ์ˆ˜ * @param {Int} speed ms ๋‹จ์œ„์˜ ์ปท ๋‹น ๋ณ€ํ™” ์‹œ๊ฐ„ * @param {DOM} selector background-image ๋กœ ์ง€์ •๋˜์–ด ์žˆ๋Š” DOM * @param {Boolean} isReplay ๋ฐ˜๋ณต์žฌ์ƒ ์—ฌ๋ถ€ * @example * // Installation * <script src="js/sequence.js"></script> * @auchor: ์ •๋ช…ํ•™ * @version 0.1 * @copyright 2016 Jeong Myoung Hak * @license http://opensource.org/licenses/MIT MIT */ function Sequence(width, height, scene, speed, selector, isReplay) { this.width = width; this.height = height; this.scene = scene; this.speed = speed; this.selector = selector; this.count = 0; this.object = ''; this.isReplay = isReplay; }; /** * ์ด๋ฏธ์ง€ ์ •๋ฉด ์ „ํ™˜์— ๋Œ€ํ•œ ์ฒ˜๋ฆฌ ํ•จ์ˆ˜ * @function * @memberOf Sequence * @private */ Sequence.prototype.procedure = function() { var position = -1 * (this.count * this.width); this.selector.style.backgroundPosition = position + 'px 0px'; this.count++; if (this.count === this.scene) { position = -1 * (this.count * this.width); this.count = 0; } }; /** * ์ƒ์„ฑ๋œ ์ธ์Šคํ„ด์Šค์— ๋Œ€ํ•ด ์ˆœ์ฐจ์ ์œผ๋กœ ์ด๋ฏธ์ง€ ์žฅ๋ฉด ์ „ํ™˜์„ ์‹คํ–‰ํ•œ๋‹ค. * @function * @param {String} type ํ•œ๋ฒˆ ์žฌ์ƒ ์‹œ "once" / ์—†์„ ์‹œ ๋นˆ๊ฐ’ * @param {Function} callback ํ•œ๋ฒˆ๋งŒ ์žฌ์ƒ ์‹œ ์žฌ์ƒ ์ข…๋ฃŒ ํ›„ ์‹คํ–‰ ๋  callback * @public */ Sequence.prototype.play = function(type, callback) { // @์„ค๋ช…: setInterval ์—๋„ this๋ฅผ ์ฃผ๊ธฐ ์œ„ํ•˜์—ฌ ํ˜„์žฌ์˜ this ๋ฅผ ์ €์žฅ var _this = this; this.object = setInterval(function() { // @์„ค๋ช…: ํ•œ๋ฒˆ๋งŒ ์žฌ์ƒ if (type === "once" && _this.count === _this.scene - 1) { _this.stop('pause'); // @์„ค๋ช…: ์ฝœ๋ฐฑํ•จ์ˆ˜ ์‹คํ–‰ if (typeof callback === "function") { callback(); return true; } } _this.procedure(); }, this.speed); }; /** * ์ƒ์„ฑ๋œ ์ธ์Šคํ„ด์Šค์— ์‹คํ–‰๋˜๊ณ  ์žˆ๋Š” ์žฅ๋ฉด ์ „ํ™˜์— ๋Œ€ํ•˜์—ฌ ์ค‘์ง€ํ•œ๋‹ค. * @function * @param {String} type ํ•œ๋ฒˆ ์žฌ์ƒ ์‹œ "once" / ์—†์„ ์‹œ ๋นˆ๊ฐ’ * @param {Function} callback ํ•œ๋ฒˆ๋งŒ ์žฌ์ƒ ์‹œ ์žฌ์ƒ ์ข…๋ฃŒ ํ›„ ์‹คํ–‰ ๋  callback * @public */ Sequence.prototype.stop = function(type, callback) { clearInterval(this.object); // @์„ค๋ช…: ์ผ์‹œ ์ค‘์ง€์ธ ๊ฒฝ์šฐ clearInterval ๋งŒ ์ง„ํ–‰ if (type === "pause") return true; this.count = 0; this.procedure(); if (typeof callback === "function") { callback(); return true; } };
var Vt00 = { // CELLS // Public to allow access to /*verilator_public*/ items; // otherwise the application code can consider these internals. // PORTS // The application code writes and reads these signals to // propagate new values into/out from the Verilated model. clk : verilated.VL_IN8 (0,0), c : verilated.VL_OUT32 (17,0), a : verilated.VL_IN32 (17,0), b : verilated.VL_IN32 (17,0), // LOCAL SIGNALS // Internals; generally not touched by application code v__DOT__aa : verilated.VL_SIG32(17,0), v__DOT__bb : verilated.VL_SIG32(17,0), //char __VpadToAlign10[2]; // LOCAL VARIABLES // Internals; generally not touched by application code __Vclklast__TOP__clk : verilated.VL_SIG32(0,0), //char __VpadToAlign17[3]; // INTERNAL VARIABLES // Internals; generally not touched by application code __VlSymsp : {} // Symbol table // PARAMETERS // Parameters marked /*verilator public*/ for use by application code // CONSTRUCTORS // Vt00& operator= (const Vt00&); ///< Copying not allowed // Vt00(const Vt00&); ///< Copying not allowed // public: /// Construct the model; called by application code /// The special name may be used to make a wrapper with a /// single model invisible WRT DPI scope names. //Vt00(const char* name="TOP"); /// Destroy the model; called (often implicitly) by application code //~Vt00(); // USER METHODS // API METHODS /// Evaluate the model. Application must call when inputs change. // eval(); /// Simulation complete, run final blocks. Application must call on completion. //void final(); // INTERNAL METHODS //private: //static void _eval_initial_loop(Vt00__Syms* __restrict vlSymsp); //public: //void __Vconfigure(Vt00__Syms* symsp, bool first); //private: //static IData _change_request(Vt00__Syms* __restrict vlSymsp); //public: //static void _eval(Vt00__Syms* __restrict vlSymsp); //static void _eval_initial(Vt00__Syms* __restrict vlSymsp); //static void _eval_settle(Vt00__Syms* __restrict vlSymsp); //static void _sequent__TOP__1(Vt00__Syms* __restrict vlSymsp); }; Vt00.constructor = function () { 'use strict' var vlSymsp = {}, vlTOPp = vlSymsp.TOPp; // Reset internal values // Reset structure values this.c = verilated.VL_RAND_RESET_I(18); this.a = verilated.VL_RAND_RESET_I(18); this.b = verilated.VL_RAND_RESET_I(18); this.clk = verilated.VL_RAND_RESET_I(1); this.v__DOT__aa = verilated.VL_RAND_RESET_I(18); this.v__DOT__bb = verilated.VL_RAND_RESET_I(18); this.__Vclklast__TOP__clk = verilated.VL_RAND_RESET_I(1); }; Vt00._eval_initial_loop = function (vlSymsp) { return "Hello!"; }; Vt00.__Vconfigure = function (symsp, first) {}; Vt00._change_request = function (vlSymsp) {}; Vt00._eval_initial = function (vlSymsp) {}; Vt00._eval_settle = function (vlSymsp) {}; Vt00._sequent__TOP__1 = function (vlSymsp) { "use asm" //Vt00* __restrict vlTOPp VL_ATTR_UNUSED = vlSymsp->TOPp; var vlTOPp = this; /*VL_DEBUG_IF(VL_PRINTF*/ //console.log(" Vt00._sequent__TOP__1"); // Body // ALWAYS at t00.sv:26 vlTOPp.c = (0x3ffff & (vlTOPp.v__DOT__aa) + (vlTOPp.v__DOT__bb))|0; // ALWAYS at t00.sv:24 vlTOPp.v__DOT__aa = vlTOPp.a|0; // ALWAYS at t00.sv:25 vlTOPp.v__DOT__bb = vlTOPp.b|0; }; Vt00._eval = function (vlSymsp) { var vlTOPp = this; // vlSymsp.TOPp; // console.log(" Vt00._eval\n"); // Body if ((vlTOPp.clk) & (~(vlTOPp.__Vclklast__TOP__clk))) { vlTOPp._sequent__TOP__1(vlSymsp); } // Final vlTOPp.__Vclklast__TOP__clk = vlTOPp.clk; }; Vt00.eval = function () { var //__VclockLoop = 0, vlSymsp; // = this.__VlSymsp, // Setup global symbol table // __Vchange, // vlTOPp = vlSymsp.TOPp; // Initialize // if (/*VL_UNLIKELY*/(!vlSymsp.__Vm_didInit)) { this._eval_initial_loop(vlSymsp) }; // Evaluate till stable // console.log("----TOP Evaluate Vt00.eval"); // __VclockLoop = 0; // __Vchange = 0; // while (/*VL_LIKELY*/(__Vchange)) { { // console.log(" Clock loop"); // vlSymsp.__Vm_activity = true; this._eval(vlSymsp); // __Vchange = this._change_request(vlSymsp); // if (++__VclockLoop > 100) { // vl_fatal // console.log("Verilated model didn't converge"); // __Vchange = 0; // } } };
import ApplicationSerializer from 'appkit/serializers/application'; export default ApplicationSerializer.extend({ normalizeHash: { events: function(hash) { hash.id = [hash.world_id, hash.map_id, hash.event_id].join('.'); hash.eventName = hash.event_id; hash.eventDetail = hash.event_id; hash.worldName = hash.world_id; hash.mapName = hash.map; delete hash.event_id; delete hash.world_id; return hash; } } });
import React from 'react'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon( <path d="M18 4l-4 4h3v7c0 1.1-.9 2-2 2s-2-.9-2-2V8c0-2.21-1.79-4-4-4S5 5.79 5 8v7H2l4 4 4-4H7V8c0-1.1.9-2 2-2s2 .9 2 2v7c0 2.21 1.79 4 4 4s4-1.79 4-4V8h3l-4-4z" /> , 'SwapCallsSharp');
define("view/modal/setting-tabs/personal/password", ["require", "exports", "module", "view/modal/setting-tabs/personal/formBase", "lang/index", "service/userProfile", "utils/server"], function(e, t) { var i = e("view/modal/setting-tabs/personal/formBase").View, n = e("lang/index"), s = e("service/userProfile"), a = e("utils/server"); t.View = i.extend({ className: "row settings-password", messages: function() { this.listenTo(s, "change:filledPassword", this.changeFilledPassword) }, initialize: function(e) { return this.constructor.__super__.initialize.apply(this, [e]), this.messages(), this }, changeFilledPassword: function() { this.$controlName.text("โ—โ—โ—โ—โ—โ—"), this.$controlEdit.text(n.get("change")) }, getRenderData: function() { var e = { label: n.get("password"), type1: "password" }; return s.get("filledPassword") ? _.extend(e, { name: "โ—โ—โ—โ—โ—โ—", editName: n.get("change_password"), ph1: n.get("current_password"), type2: "password", ph2: n.get("new_password") }) : _.extend(e, { editName: n.get("set_password"), ph1: n.get("new_password") }), e }, checkValue1: function(e) { return e ? e && e.length >= 6 && e.length <= 20 ? !0 : (this.showErrorMsg(n.get("password_length_error_info")), !1) : (this.showErrorMsg(n.get("password_empty")), !1) }, checkValue2: function(e) { return s.get("filledPassword") ? this.checkValue1(e) : !0 }, saveValue: function(e) { var t = a.changePassword, i = this; if (s.get("filledPassword")) var r = JSON.stringify({ password: e[1], newPassword1: e[2], newPassword2: e[2] }); else var r = JSON.stringify({ newPassword1: e[1], newPassword2: e[1] }); t(r, function(e) { e && e.error ? "password_incorrect" == e.error.code && i.afterSaveFail(n.get("password_incorrect")) : (s.get("filledPassword") || s.set("filledPassword", !0), i.afterSaveSuccess("โ—โ—โ—โ—โ—โ—")) }) } }) })
// src/app-client.js import React from 'react'; import ReactDOM from 'react-dom'; import AppRoutes from './components/AppRoutes'; window.onload = () => { ReactDOM.render(<AppRoutes/>, document.getElementById('main')); };
var person = { name : "Mosh", walk : function(){ this.trigger("walking", { speed : 1, startTime: "8:00" }); } }; _.extend(person , Backbone.Events); //person.on("walking", function(e){ // console.log("Person is walking"); // console.log("Event:" + e); //}); //person.off("walking"); person.once("walking", function(e){ console.log("Person is walking"); console.log("Event:" + e); }); person.walk(); person.walk();
import * as is from '../stringConstants/stringConstants'; const triangularOrNot = (inputNum) => { if (/[a-z]/i.test(inputNum)) { return inputNum; } let triangularNumber = 0; let nextAddition = 1; while (triangularNumber < inputNum) { triangularNumber += nextAddition; nextAddition += 1; } return (inputNum === triangularNumber) ? `${inputNum}${is.TRI}` : `${inputNum}${is.NOT_TRI}`; }; export default triangularOrNot;
/// <reference path="../typings/node/node.d.ts"/> /* var xmlhttp = new XMLHttpRequest(); var apply = 'title=00111101211u0122i40&content=222&recipient_id={"userId":"5672592b202517dedb"},{"userId":"2517dedb"},{"userId":"5670f202517dedb"}'; xmlhttp.open('POST','http://localhost:3000/api/v1.0/apply/add',true); xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xmlhttp.send(apply); */ // query={elete_flag:'false'}ๅœจๆœๅŠก็ซฏ็ญ›้€‰ๅฅฝๆ•ฐๆฎ exports.tome = function(req, res, next) { var applyModel = global.dbConn.getModel('apply'); var recipient_id = req.session.user._id; // ๆŸฅ่ฏขๅญๆ–‡ๆกฃ applyModel.find({'recipient_id.userId':recipient_id, delete_flag:'false'},function(err, data){ if(err){ // ๆŽฅๅฃ่ฟ”ๅ›žๅฏน่ฑก res.send(); res.send({ "code":"0", "msg":err, "data":"" }); console.log(err); }else if(!data){ req.session.error = '้€š็Ÿฅไธๅญ˜ๅœจ'; res.send({ "code":"-2", "msg":"Not Found", "data":"" }); }else{ res.send({ "code":"1", "msg":"success", "data":data }); } }); }; // query={elete_flag:'false'}ๅœจๆœๅŠก็ซฏ็ญ›้€‰ๅฅฝๆ•ฐๆฎ exports.fromme = function(req, res, next) { var applyModel = global.dbConn.getModel('apply'); var applicant_id = req.session.user._id; // ๆŸฅ่ฏขๅญๆ–‡ๆกฃ applyModel.find({'applicant_id':applicant_id, delete_flag:'false'},function(err, data){ if(err){ // ๆŽฅๅฃ่ฟ”ๅ›žๅฏน่ฑก res.send(); res.send({ "code":"0", "msg":err, "data":"" }); console.log(err); }else if(!data){ req.session.error = '้€š็Ÿฅไธๅญ˜ๅœจ'; res.send({ "code":"-2", "msg":"Not Found", "data":"" }); }else{ res.send({ "code":"1", "msg":"success", "data":data }); } }); }; exports.add = function(req, res, next) { var applyModel = global.dbConn.getModel('apply'); var title = req.body.title; var content = req.body.content; var applicant_id = req.session.user._id; var recipient_id = req.body.recipient_id; var delete_flag = 'false'; console.log('apply' + req.body); // ๆ ผๅผๅŒ–ๆไบคๅ‚ๆ•ฐ var recipient = []; for(var i=0; i<recipient_id.length; i++) { recipient[i] = new Object(); recipient[i].userId = recipient_id[i]._id; recipient[i].read = "false"; console.log(recipient_id[i]._id); } console.log('all' + recipient); // ๆŸฅ่ฏขโ€”โ€”ๅˆ›ๅปบโ€”โ€”ๅˆ›ๅปบๅญๆ–‡ๆกฃ applyModel.findOne({title: title},function(err, data){ if(err){ // ๆŽฅๅฃ่ฟ”ๅ›žๅฏน่ฑก res.send(); res.send({ "code":"0", "msg":err, "data":"" }); console.log(err); }else if(data){ // ๅฏนๅบ”titleๅทฒ็ปๆœ‰ๆ•ฐๆฎ req.session.error = '้€š็Ÿฅๅทฒๅญ˜ๅœจ'; // ๆŽฅๅฃ่ฟ”ๅ›žๅฏน่ฑก res.send(); res.send({ "code":"2", "msg":"exist", "data":"" }); }else{ applyModel.create({ 'title' : title, 'content' : content, 'applicant_id' : applicant_id, 'delete_flag' : delete_flag },function(err,data){ if (err) { // ๆŽฅๅฃ่ฟ”ๅ›žๅฏน่ฑก res.send(); res.send({ "code":"0", "msg":err, "data":"" }); console.log(err); } else { // mongooseModel.update(conditions, update, options, callback) applyModel.update( {'_id':data._id}, {'$push':{'recipient_id':{'$each': recipient}}}, {upsert : true}, function(err){ if (err) { // ไธ่ƒฝๆ›ดๆ–ฐๅญๆ–‡ๆกฃ applyModel.remove( {'_id':data._id}, function(err, data){ if(err){ // ๆ›ดๆ–ฐไธไบ†ๅญๆ–‡ๆกฃไธ”ๅˆ ้™คๅคฑ่ดฅ res.send({ "code":"3", "msg":err, "data":"" }); console.log(err); } else { // ๆ›ดๆ–ฐไธไบ†ๅญๆ–‡ๆกฃไฝ†ๅˆ ้™คๆˆๅŠŸ res.send({ "code":"3", "msg":data, "data":"" }); console.log(data); } }); } else { res.send({ "code":"1", "msg":"success", "data":data }); } } ); } }); } }); }; exports.detail = function(req, res, next) { var applyModel = global.dbConn.getModel('apply'); var id = req.params.id; applyModel.findOne({"_id": id},function(err, data){ if(err){ // ๆŽฅๅฃ่ฟ”ๅ›žๅฏน่ฑก res.send(); res.send({ "code":"0", "msg":err, "data":"" }); console.log(err); }else if(!data){ req.session.error = '้€š็Ÿฅไธๅญ˜ๅœจ'; res.send({ "code":"-2", "msg":"Not Found", "data":"" }); }else{ res.send({ "code":"1", "msg":"success", "data":data }); } }); }; exports.edit = function(req, res, next) { var applyModel = global.dbConn.getModel('apply'); // console.log(req.params.id); // console.log(req.body); var id = req.params.id; var params = req.body; var delete_flag = 'true'; applyModel.findOneAndUpdate({"_id": id}, params, {new: false}, function(err, data){ if(err){ // ๆŽฅๅฃ่ฟ”ๅ›žๅฏน่ฑก res.send(); res.send({ "code":"0", "msg":err, "data":"" }); console.log(err); }else if(!data){ req.session.error = '้€š็Ÿฅไธๅญ˜ๅœจ'; res.send({ "code":"-2", "msg":"Not Found", "data":"" }); }else{ res.send({ "code":"1", "msg":"success", "data":data }); } }); }; exports.delete = function(req, res, next) { var applyModel = global.dbConn.getModel('apply'); // console.log(req.params.id); var id = req.params.id; var delete_flag = 'true'; applyModel.findOneAndUpdate({"_id": id}, {"delete_flag": delete_flag}, {new: false}, function(err, data){ if(err){ // ๆŽฅๅฃ่ฟ”ๅ›žๅฏน่ฑก res.send(); res.send({ "code":"0", "msg":err, "data":"" }); console.log(err); }else if(!data){ req.session.error = '้€š็Ÿฅไธๅญ˜ๅœจ'; res.send({ "code":"-2", "msg":"Not Found", "data":"" }); }else{ res.send({ "code":"1", "msg":"success", "data":data }); } }); }; exports.read = function(req, res, next) { var applyModel = global.dbConn.getModel('apply'); var recipient_id = req.session.user._id; //var recipient_id = "5672592b4c970f202517dedb"; var id = req.params.id; var delete_flag = 'true'; applyModel.findOneAndUpdate({"_id": id,"recipient_id.userId":recipient_id}, {$set: { "recipient_id.$.read" : delete_flag }}, {new: false}, function(err, data){ if(err){ // ๆŽฅๅฃ่ฟ”ๅ›žๅฏน่ฑก res.send(); res.send({ "code":"0", "msg":err, "data":"" }); console.log(err); }else if(!data){ req.session.error = '้€š็Ÿฅไธๅญ˜ๅœจ'; res.send({ "code":"-2", "msg":"Not Found", "data":"" }); }else{ res.send({ "code":"1", "msg":"success", "data":data }); } }); };
exports.name = "sotd.status"; exports.check = function (sr, done) { if (!sr.config.sotdStatus) return done(); var $sotd = sr.getSotDSection(); if (!$sotd || !$sotd.length) { sr.error(exports.name, "no-sotd"); return done(); } if (!sr.norm($sotd.text()).match(new RegExp(sr.config.longStatus))) sr.error(exports.name, "no-mention", { status: sr.config.longStatus }); done(); };
import cssRules from './cssRules'; import $ from 'jquery'; import loaders from './loadHTML'; cssRules.importStyle(); let state = 'dinamicly loaded'; console.log(`main loaded loaded ${state}`); loaders.table(); // loaders.list();
define(["require", "exports"], function (require, exports) { "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.items = [ (_a = { key: 'newItem', name: 'New', icon: 'Add', ariaLabel: 'New. Use left and right arrow keys to navigate' }, _a['data-automation-id'] = 'newItemMenu', _a.subMenuProps = { items: [ (_b = { key: 'emailMessage', name: 'Email message', icon: 'Mail' }, _b['data-automation-id'] = 'newEmailButton', _b), { key: 'calendarEvent', name: 'Calendar event', icon: 'Calendar' } ], }, _a), (_c = { key: 'upload', name: 'Upload', icon: 'Upload', href: 'https://mytenenat.sharepoint.com/teams/IT/BPU/' }, _c['data-automation-id'] = 'uploadButton', _c), { key: 'share', name: 'Share', icon: 'Share', onClick: function () { return; } }, { key: 'download', name: 'Download', icon: 'Download', onClick: function () { return; } }, { key: 'move', name: 'Move to...', icon: 'MoveToFolder', onClick: function () { return; } }, { key: 'copy', name: 'Copy to...', icon: 'Copy', onClick: function () { return; } }, { key: 'rename', name: 'Rename...', icon: 'Edit', onClick: function () { return; } }, { key: 'disabled', name: 'Disabled...', icon: 'Cancel', disabled: true, onClick: function () { return; } } ]; exports.textOnlyItems = [ { key: 'upload', name: 'Upload', onClick: function () { return; } }, { key: 'share', name: 'Share', onClick: function () { return; } }, { key: 'download', name: 'Download', onClick: function () { return; } }, { key: 'move', name: 'Move to...', onClick: function () { return; } }, { key: 'copy', name: 'Copy to...', onClick: function () { return; } }, { key: 'rename', name: 'Rename...', onClick: function () { return; } }, { key: 'disabled', name: 'Disabled...', disabled: true, onClick: function () { return; } } ]; exports.iconOnlyItems = [ { key: 'upload', name: '', icon: 'Upload', onClick: function () { return; } }, { key: 'share', name: '', icon: 'Share', onClick: function () { return; } }, { key: 'download', name: '', icon: 'Download', onClick: function () { return; } }, { key: 'move', name: '', icon: 'MoveToFolder', onClick: function () { return; } }, { key: 'copy', name: '', icon: 'Copy', onClick: function () { return; } }, { key: 'rename', name: '', icon: 'Edit', onClick: function () { return; } }, { key: 'disabled', icon: 'Cancel', disabled: true, onClick: function () { return; } } ]; exports.overflowItems = [ { key: 'move', name: 'Move to...', icon: 'MoveToFolder' }, { key: 'copy', name: 'Copy to...', icon: 'Copy' }, { key: 'rename', name: 'Rename...', icon: 'Edit' } ]; exports.farItems = [ { key: 'sort', name: 'Sort', icon: 'SortLines', onClick: function () { return; } }, { key: 'tile', name: 'Grid view', icon: 'Tiles', onClick: function () { return; } }, { key: 'info', name: 'Info', icon: 'Info', onClick: function () { return; } } ]; var _a, _b, _c; }); //# sourceMappingURL=data.js.map
import React from 'react'; import { mount } from 'enzyme'; import SimpleSlider from '../SimpleSlider'; import { repeatClicks } from '../../test-helpers'; describe('Simple Slider', function () { it('should have 8 slides (6 actual and 2 clone slides)', function () { const wrapper = mount(<SimpleSlider />); expect(wrapper.find('.slick-slide').length).toEqual(8); }); it('should have 2 clone slides', function () { const wrapper = mount(<SimpleSlider />); expect(wrapper.find('.slick-cloned').length).toEqual(2); }); it('should have 1 active slide', function () { const wrapper = mount(<SimpleSlider />); expect(wrapper.find('.slick-slide.slick-active').length).toEqual(1); }); it('should have 6 dots', function () { const wrapper = mount(<SimpleSlider />); expect(wrapper.find('.slick-dots').children().length).toEqual(6); }); it('should have 1 active dot', function () { const wrapper = mount(<SimpleSlider />); expect(wrapper.find('.slick-dots .slick-active').length).toEqual(1); }); it('should have a prev arrow', function () { const wrapper = mount(<SimpleSlider />); expect(wrapper.find('.slick-prev').length).toEqual(1); }); it('should have a next arrow', function () { const wrapper = mount(<SimpleSlider />); expect(wrapper.find('.slick-next').length).toEqual(1); }); it('should got to second slide when next button is clicked', function () { const wrapper = mount(<SimpleSlider />); wrapper.find('.slick-next').simulate('click') expect(wrapper.find('.slick-slide.slick-active').first().text()).toEqual('2'); expect(wrapper.find('.slick-dots .slick-active').length).toEqual(1); expect(wrapper.find('.slick-dots').childAt(1).hasClass('slick-active')).toEqual(true) }); it('should goto last slide when prev button is clicked', function () { const wrapper = mount(<SimpleSlider />); wrapper.find('.slick-prev').simulate('click') expect(wrapper.find('.slick-slide.slick-active').first().text()).toEqual('6'); expect(wrapper.find('.slick-dots .slick-active').length).toEqual(1); expect(wrapper.find('.slick-dots').childAt(5).hasClass('slick-active')).toEqual(true) }) it('should goto 4th slide when 4th dot is clicked', function () { const wrapper = mount(<SimpleSlider />); wrapper.find('.slick-dots button').at(3).simulate('click') expect(wrapper.find('.slick-slide.slick-active').first().text()).toEqual('4'); expect(wrapper.find('.slick-dots .slick-active').length).toEqual(1); expect(wrapper.find('.slick-dots').childAt(3).hasClass('slick-active')).toEqual(true) }) // it('should come back to 1st slide after 6 clicks on next button', function () { // // waitForAnimate option is causing problem for this test // const wrapper = mount(<SimpleSlider />); // wrapper.find('.slick-next').first().simulate('click').simulate('click') // // wrapper.find('.slick-prev').first().simulate('click') // // wrapper.find('.slick-next').first().simulate('click') // // console.log(nextButton) // // nextButton.simulate('click').simulate('click') // // nextButton.simulate('click') // // repeatClicks(wrapper.find('.slick-next'), 1) // expect(wrapper.find('.slick-slide.slick-active').first().text()).toEqual('1'); // expect(wrapper.find('.slick-dots .slick-active').length).toEqual(1); // expect(wrapper.find('.slick-dots').childAt(0).hasClass('slick-active')).toEqual(true) // }) }); describe("Simple Slider Snapshots", function () { it("slider initial state", function () { const wrapper = mount(<SimpleSlider />); expect(wrapper.html()).toMatchSnapshot() }); it("click on next button", function () { const wrapper = mount(<SimpleSlider />); wrapper.find('.slick-next').simulate('click') expect(wrapper.html()).toMatchSnapshot() }); it("click on prev button", function () { const wrapper = mount(<SimpleSlider />); wrapper.find('.slick-prev').simulate('click') expect(wrapper.html()).toMatchSnapshot() }); it("click on 3rd dot", function () { const wrapper = mount(<SimpleSlider />); wrapper.find('.slick-dots button').at(2).simulate('click') expect(wrapper.html()).toMatchSnapshot() }) });
module.exports = { __test_name: 'delegated/disabled' };
import { shallowRender } from '../src'; import { h, Fragment } from 'preact'; import { expect } from 'chai'; import { spy } from 'sinon'; describe('shallowRender()', () => { it('should not render nested components', () => { let Test = spy(({ foo, children }) => ( <div bar={foo}> <b>test child</b> {children} </div> )); Test.displayName = 'Test'; let rendered = shallowRender( <section> <Test foo={1}> <span>asdf</span> </Test> </section> ); expect(rendered).to.equal( `<section><Test foo="1"><span>asdf</span></Test></section>` ); expect(Test).not.to.have.been.called; }); it('should always render root component', () => { let Test = spy(({ foo, children }) => ( <div bar={foo}> <b>test child</b> {children} </div> )); Test.displayName = 'Test'; let rendered = shallowRender( <Test foo={1}> <span>asdf</span> </Test> ); expect(rendered).to.equal( `<div bar="1"><b>test child</b><span>asdf</span></div>` ); expect(Test).to.have.been.calledOnce; }); it('should ignore Fragments', () => { let rendered = shallowRender( <Fragment> <div>foo</div> </Fragment> ); expect(rendered).to.equal(`<div>foo</div>`); }); });
if (!Array.prototype.filter) { Array.prototype.filter = function(fun/*, thisArg*/) { 'use strict'; if (this === void 0 || this === null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; if (typeof fun !== 'function') { throw new TypeError(); } var res = []; var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { if (i in t) { var val = t[i]; // NOTE: Technically this should Object.defineProperty at // the next index, as push can be affected by // properties on Object.prototype and Array.prototype. // But that method's new, and collisions should be // rare, so use the more-compatible alternative. if (fun.call(thisArg, val, i, t)) { res.push(val); } } } return res; }; } String.prototype.capitalize = function() { return this.charAt(0).toUpperCase() + this.slice(1); } $(function () { var $select_tool = $('#area-select-tool'); var $input_area = $('#input-area'); var $input_weight = $('#input-weight'); var $btn_query = $('#btn-query'); var $group_header = $('#group-header'); var $group_body = $('#group-body'); var $price_result = $('#price-result'); // var $btn_close = $('#btn-close'); $btn_query.on('click', function(event) { event.preventDefault(); var url = $('#query-form').attr('action'); var area = $input_area.val(); var weight = $input_weight.val(); if(!(area && weight)){ alert('ๆŸฅ่ฏขๆกไปถไธๅฎŒๆ•ด๏ผŒ่ฏท่พ“ๅ…ฅๅ›ฝๅฎถๆˆ–้‡้‡๏ผ'); return false; } var state= $input_area.attr('data-state') || area; var state_en= $input_area.attr('data-en'); var company_id = $('#choose-company').val(); if(!company_id && $('#choose-company').length){ alert('่ฏท้€‰ๆ‹ฉๆŸฅ่ฏขๅ…ฌๅธ'); return; } $price_result.find('#price-tbody').empty(); /* Act on the event */ $.ajax({ url: url, type: 'POST', dataType: 'json', data: { 'state':state, 'state_en':state_en, 'weight': weight, 'company_id': company_id } }) .done(function(response) { if(response.ok){ var data = response.data; data.sort(function (a,b) { return a.price - b.price; }); var state = response.state + '(' + response['state_en'] + ')'; var w = response.weight; w = math_round(w); var trs = ''; for (var i = 0; i < data.length; i++) { var _d = data[i]; var single = _d.price; var sum = (single * w).toFixed(2); if(w<=20.5){ single = ''; sum = _d.price; } var tr = "<tr><td>"+ _d.cname+"</td><td>"+ state + '</td><td>'+ w +'KG </td><td>' + single + '</td><td>'+ sum +'</td></tr>'; trs += tr; } $price_result.find('#price-tbody').empty().append(trs); } }) .fail(function() { console.log("error"); }) .always(function() { console.log("complete"); }); }); function math_round(w) { if(w<21){ var w_floor = Math.floor(w); if(w_floor<w){ if(w> w_floor+ 0.5){ return Math.ceil(w); }else{ return w_floor+0.5; } }else{ return w; } }else{ return Math.ceil(w); } } $input_area.on('click', function(event) { event.preventDefault(); event.stopPropagation(); var url = $(this).attr('action'); var offset = $(this).offset(); $select_tool.css({ 'top' : offset.top + $(this).outerHeight() + 'px', 'left': offset.left + 'px' }).slideDown(); }); $input_area.keydown(false); $group_body.on('click','span',function(event) { event.preventDefault(); var state = $(this).attr('data-state'); var state_en = $(this).attr('data-en'); var $input = $('#input-area'); $input.attr('data-state',state); $input.attr('data-en',state_en); $input.val($(this).text()); $(this).addClass('selected').siblings().removeClass('selected'); $select_tool.hide(); }); $group_header.on('click', 'b', function(event) { event.preventDefault(); var key = $(this).text(); $(this).addClass('current').siblings().removeClass('current'); var filter_result = []; if(key == 'ๅธธ็”จๅ›ฝๅฎถ'){ filter_result = window.common_counties; }else{ var area_json = window.areajson; filter_result = area_json.filter(function (area) { var state_en = area['state_en']; if(state_en.capitalize().charAt(0)==this){ return true; } },key); } var group = ""; var group_title = "<h3>" + key + '</h3>'; for (var i = filter_result.length - 1; i >= 0; i--) { var area = filter_result[i]; var area_id = area['area_id']; var state = area['state']; var state_en = area['state_en']; group += '<span data-state="'+state+'" data-en="'+state_en+'">' + state + '(' + state_en + ')' + '</span>'; } $("#group-body").empty().append(group_title,group); }); $select_tool.on('click', function(event) { event.preventDefault(); event.stopPropagation(); /* Act on the event */ }); $(document).on('click', function(event) { $select_tool.hide(); /* Act on the event */ }); // $btn_close.on('click', function(event) { // event.preventDefault(); // $select_tool.hide(); // }); $group_header.find('b:first').trigger('click'); });
"use strict"; (function (ImAddressKey) { ImAddressKey[ImAddressKey["ImAddress1"] = 0] = "ImAddress1"; ImAddressKey[ImAddressKey["ImAddress2"] = 1] = "ImAddress2"; ImAddressKey[ImAddressKey["ImAddress3"] = 2] = "ImAddress3"; })(exports.ImAddressKey || (exports.ImAddressKey = {})); var ImAddressKey = exports.ImAddressKey;
version https://git-lfs.github.com/spec/v1 oid sha256:99519206345dbda635b50e44e1604eb10fa2b8f5d2487bdeb55d58d92279f01b size 1617
/** * @module typedarray-polyfill */ var methods = ['values', 'sort', 'some', 'slice', 'reverse', 'reduceRight', 'reduce', 'map', 'keys', 'lastIndexOf', 'join', 'indexOf', 'includes', 'forEach', 'find', 'findIndex', 'copyWithin', 'filter', 'entries', 'every', 'fill']; if (typeof Int8Array !== 'undefined') { for (var i = methods.length; i--;) { var method = methods[i]; if (!Int8Array.prototype[method]) Int8Array.prototype[method] = Array.prototype[method]; } } if (typeof Uint8Array !== 'undefined') { for (var i = methods.length; i--;) { var method = methods[i]; if (!Uint8Array.prototype[method]) Uint8Array.prototype[method] = Array.prototype[method]; } } if (typeof Uint8ClampedArray !== 'undefined') { for (var i = methods.length; i--;) { var method = methods[i]; if (!Uint8ClampedArray.prototype[method]) Uint8ClampedArray.prototype[method] = Array.prototype[method]; } } if (typeof Int16Array !== 'undefined') { for (var i = methods.length; i--;) { var method = methods[i]; if (!Int16Array.prototype[method]) Int16Array.prototype[method] = Array.prototype[method]; } } if (typeof Uint16Array !== 'undefined') { for (var i = methods.length; i--;) { var method = methods[i]; if (!Uint16Array.prototype[method]) Uint16Array.prototype[method] = Array.prototype[method]; } } if (typeof Int32Array !== 'undefined') { for (var i = methods.length; i--;) { var method = methods[i]; if (!Int32Array.prototype[method]) Int32Array.prototype[method] = Array.prototype[method]; } } if (typeof Uint32Array !== 'undefined') { for (var i = methods.length; i--;) { var method = methods[i]; if (!Uint32Array.prototype[method]) Uint32Array.prototype[method] = Array.prototype[method]; } } if (typeof Float32Array !== 'undefined') { for (var i = methods.length; i--;) { var method = methods[i]; if (!Float32Array.prototype[method]) Float32Array.prototype[method] = Array.prototype[method]; } } if (typeof Float64Array !== 'undefined') { for (var i = methods.length; i--;) { var method = methods[i]; if (!Float64Array.prototype[method]) Float64Array.prototype[method] = Array.prototype[method]; } } if (typeof TypedArray !== 'undefined') { for (var i = methods.length; i--;) { var method = methods[i]; if (!TypedArray.prototype[method]) TypedArray.prototype[method] = Array.prototype[method]; } }
/*! jQuery nCookie - v0.1.0 - 2012-08-08 * https://github.com/nak0yui/jquery.ncookie.js * Copyright (c) 2012 nak0yui; Licensed MIT, GPL */ (function(a,b){"use strict";var c={expires:1,path:"/"},d=function(d,e,f){var g={},h=[];a.inflate(g,c,f);if(d===null||typeof d=="undefined")return;if(e===null||typeof e=="undefined")e="",g.expires=-1;if(typeof g.expires=="number"){var i=g.expires;g.expires=new Date,g.expires.setTime(g.expires.getTime()+i*24*60*60*1e3)}h.push(encodeURIComponent(d)+"="+e),h.push("expires="+g.expires.toUTCString()),h.push("path="+g.path),b.cookie=h.join("; ")},e=function(a){var c=b.cookie.split("; ");for(var d=0;d<c.length;d++){var e=c[d].split("=");if(decodeURIComponent(e[0])===a)return e[1]}return null},f=function(a){d(a)},g={set:d,get:e,destory:f};a.ncookie=g})(window.jQuery,document),function(a){"use strict";var b=function(a){var b=a[0]||{},c=a.length,d=a,e,f,g,h,i;typeof b!="object"&&(b={});for(e=1;e<c;e++)for(g in d[e])f=b[g],h=d[e][g],b[g]=h;return b};a.inflate=function(){return b(arguments)}}(window.jQuery);
"use strict"; const csv2gexf = require('../lib/index'); // ------------------------------------------------------------------------------------------------- var config = { graphParams: { defaultEdgeType: 'directed', meta: { description: 'An example graph.', creator: 'csv2gexf by Wouter Van den Broeck' } }, nodes: { file: 'csv/nodes.csv', schema: [ 'id', 'label', { target: 'attributes', id: 'attrib_1', type: 'float' }, { target: 'attributes', type: 'string' } ], parseOptions: { columns: true, skip_empty_lines: true, trim: true } }, edges: { file: 'csv/edges.csv', schema: [ 'source', 'target', { target: 'attributes', type: 'string' }, { target: 'viz', id: 'thickness' } ], parseOptions: { columns: true, skip_empty_lines: true, trim: true } }, saveAs: 'result.gexf' }; csv2gexf.convert(config) .then(function () { console.log("The Gexf file is written."); });
// annyang // version : 0.2.0 // author : Tal Ater @TalAter // license : MIT // https://www.TalAter.com/annyang/ (function(a){ "use strict"; var b=a.webkitSpeechRecognition||a.mozSpeechRecognition||a.msSpeechRecognition||a.oSpeechRecognition||a.SpeechRecognition; if(!b) return a.annyang=null,null; var c, d, e, f, g={ start:[], error:[], end:[], result:[], resultMatch:[], resultNoMatch:[] }, h=0, i=!1, j="font-weight: bold; color: #00f;", k=/\s*\((.*?)\)\s*/g, l=/(\(\?:[^)]+\))\?/g, m=/(\(\?)?:\w+/g, n=/\*\w+/g, o=/[\-{}\[\]+?.,\\\^$|#]/g, p=function(a){ return a=a.replace(o,"\\$&") .replace(k,"(?:$1)?") .replace(m,function(a,b){return b?a:"([^\\s]+)"}) .replace(n,"(.*?)") .replace(l,"\\s*$1?\\s*"), new RegExp("^"+a+"$","i") }, q=function(a){ for(var b=0,c=a.length;c>b;b++) a[b].apply(this) }; a.annyang={ init:function(k){ d&&d.abort&&d.abort(),d=new b, d.maxAlternatives=5, d.continuous=!0, d.lang="en-US", d.onstart=function(a){q(g.start)}, d.onerror=function(a){ //improve this console.log(a.error); q(g.error) }, d.onend=function(a){ //improve this }, d.onresult=function(b){ q(g.result); for(var d,e=b.results[b.resultIndex],f=0;f<e.length;f++){ d=e[f].transcript.trim(),i&&a.console.log("Speech recognized: %c"+d,j); for(var h=0,k=c.length;k>h;h++){ var l=c[h].command.exec(d); if(l){ var m=l.slice(1); return i&&(a.console.log("command matched: %c"+c[h].originalPhrase,j),m.length&&a.console.log("with parameters",m)),c[h].callback.apply(this,m),q(g.resultMatch),!0 } } console.log('walang command n nagmatch : '); console.log(d); } return q(g.resultNoMatch),!1 }, c=[] }, start:function(a){ a=a||{}, e="undefined"!=typeof a.autoRestart?!!a.autoRestart:!0, d.start() }, abort:function(){ e=!1, d.abort() }, debug:function(a){ i=arguments.length>0?!!a:!0 }, setLanguage:function(a){ f=a, d&&d.abort&&(d.lang=a) }, addCallback:function(b,c){ if(void 0!==g[b]){ var d=a[c]||c; "function"==typeof d&&g[b].push(d) } } } }).call(this);
angular.module('nbaRoutes').controller('teamCtrl', function($scope, $stateParams, teamService, teamData) { $scope.teamData = teamData; $scope.newGame = {}; $scope.showNewGameForm = false; $scope.toggleNewGameForm = function() { $scope.showNewGameForm = !$scope.showNewGameForm; }; $scope.submitGame = function() { $scope.newGame.homeTeam = $scope.teamData.homeTeam.split(' ').join('').toLowerCase(); teamService.addNewGame($scope.newGame).then(function(res) { return teamService.getTeamData($stateParams.team); }).then(function(res) { $scope.teamData = res; $scope.newGame = {}; $scope.showNewGameForm = false; }).catch(function(err) { console.log(err); }); }; });
var util = require('util'); var songHistory = []; /** * That is this and this is that * @type {Room} */ var that = null; var User = function(data) { this.avatarID = data.avatarID ? data.avatarID : ''; this.badge = data.badge ? data.badge : 0; this.blurb = data.blurb ? data.blurb : undefined; this.ep = data.ep ? data.ep : undefined; this.gRole = data.gRole !== null ? data.gRole : 0; this.grab = grabs[data.id] === 1; this.id = data.id ? data.id : -1; this.ignores = data.ignores ? data.ignores : undefined; this.joined = data.joined ? data.joined : ''; this.language = data.language ? data.language : ''; this.level = data.level ? data.level : 0; this.notifications = data.notifications ? data.notifications : undefined; this.pVibes = data.pVibes ? data.pVibes : undefined; this.pw = data.pw ? data.pw : undefined; this.role = data.role ? data.role : 0; this.slug = data.slug ? data.slug : undefined; this.status = data.status ? data.status : 0; this.username = data.username ? data.username : ''; this.vote = votes[data.id] !== undefined ? votes[data.id] === -1 ? -1 : 1 : 0; this.xp = data.xp ? data.xp : 0; this.guest = data.guest ? data.guest : false; }; User.prototype.toString = function() { return this.username; }; var cacheUsers = {}; /** * @type {{currentDJ: number, isLocked: boolean, shouldCycle: boolean, waitingDJs: Array}} */ var booth = { currentDJ: -1, isLocked: false, shouldCycle: true, waitingDJs: [] }; /** * @type {Array} */ var fx = []; /** * @type {{}} */ var grabs = {}; /** * @type {{description: string, favorite: boolean, hostID: number, hostName: string, id: number, name: string, population: number, slug: string, welcome: string}} */ var meta = { description: '', favorite: false, hostID: -1, hostName: '', id: -1, name: '', population: 0, slug: '', welcome: '' }; /** * @type {{}} */ var mutes = {}; /** * @type {{historyID: string, media: {author: string, cid: string, duration: number, format: number, id: number, image: string, title: string}, playlistID: number, startTime: string}} */ var playback = { historyID: '', media: { author: '', cid: '', duration: -1, format: -1, id: -1, image: '', title: '' }, playlistID: -1, startTime: '' }; /** * @type {{}} */ var mySelf = {}; /** * @type {number} */ var role = 0; /** * @type {Array} */ var users = []; /** * @type {{}} */ var votes = {}; setInterval(function() { for (var i in mutes) { if (!mutes.hasOwnProperty(i)) continue; if (mutes[i] > 0) mutes[i]--; } }, 1e3); /** * Room data container * SHOULD NOT BE USED/ACCESSED DIRECTLY * @constructor */ var Room = function() { that = this; }; /** * Make an array of userIDs to an array of user objects * @param {Number[]} ids * @return {User[]} */ Room.prototype.usersToArray = function(ids) { var user, users; users = []; for (var i in ids) { if (!ids.hasOwnProperty(i)) continue; user = this.getUser(ids[i]); if (user != null) users.push(user); } return users; }; /** * Implementation of plug.dj methods * Gets the permissions over another user by user object * @param {User} other * @return {{canModChat: boolean, canModMute: boolean, canModBan: boolean, canModStaff: boolean}} */ Room.prototype.getPermissions = function(other) { var me = this.getSelf(); var permissions = { canModChat: false, canModMute: false, canModBan: false, canModStaff: false }; if (other.gRole === 0) { if (me.gRole === 5) { permissions.canModChat = true; permissions.canModBan = true; } else { permissions.canModChat = me.role > 1 && Math.max(me.role, me.gRole) > other.role; permissions.canModBan = me.role > other.role; } } if (me.gRole === 5) { permissions.canModStaff = true; } else if (other.gRole !== 5) { permissions.canModStaff = Math.max(me.role, me.gRole) > Math.max(other.role, other.gRole); } permissions.canModMute = !(other.role > 0 || other.gRole > 0); return permissions; }; /** * Extend the User object * @param {PlugAPI} instance Instance of PlugAPI client */ Room.prototype.registerUserExtensions = function(instance) { //noinspection JSUnusedGlobalSymbols /** * Add the user to the waitlist */ User.prototype.addToWaitList = function() { instance.moderateAddDJ(this.id); }; //noinspection JSUnusedGlobalSymbols /** * Remove the user from the waitlist */ User.prototype.removeFromWaitList = function() { instance.moderateRemoveDJ(this.id); }; //noinspection JSUnusedGlobalSymbols /** * Move the user to a new position in the waitlist * @param {Number} pos New position */ User.prototype.moveInWaitList = function(pos) { instance.moderateMoveDJ(this.id, pos); }; }; //noinspection JSUnusedGlobalSymbols /** * Implementation of plug.dj methods * Gets the permissions over another user by userID * @param {Number} [uid] Other userID * @return {{canModChat: boolean, canModMute: boolean, canModBan: boolean, canModStaff: boolean}} */ Room.prototype.getPermissionsID = function(uid) { return this.getPermissions(this.getUser(uid)); }; /** * Check if a user have a certain permission in the room staff * @param {Number|undefined} uid User ID * @param {Number} permission * @returns {boolean} */ Room.prototype.haveRoomPermission = function(uid, permission) { var user = this.getUser(uid); return !(user == null || user.role < permission); }; /** * Check if a user have a certain permission in the global staff (admins, ambassadors) * @param {Number|undefined} uid User ID * @param {Number} permission * @returns {boolean} */ Room.prototype.haveGlobalPermission = function(uid, permission) { var user = this.getUser(uid); return !(user == null || user.gRole < permission); }; //noinspection JSUnusedGlobalSymbols /** * Is user an ambassador? * Can only check users in the room * @param {Number} [uid] * @returns {Boolean} */ Room.prototype.isAmbassador = function(uid) { if (!uid) uid = mySelf.id; return this.haveGlobalPermission(uid, 2) && !this.isAdmin(uid); }; /** * Is user an admin? * Can only check users in the room * @param {Number} [uid] * @returns {Boolean} */ Room.prototype.isAdmin = function(uid) { if (!uid) uid = mySelf.id; return this.haveGlobalPermission(uid, 5); }; //noinspection JSUnusedGlobalSymbols /** * Is user staff? * Does not include global staff * Can only check users in the room * @param {Number} [uid] * @returns {Boolean} */ Room.prototype.isStaff = function(uid) { if (!uid) uid = mySelf.id; return this.haveRoomPermission(uid, 1); }; /** * Is user current DJ? * @param {Number} [uid] * @return {boolean} */ Room.prototype.isDJ = function(uid) { if (!uid) uid = mySelf.id; return booth.currentDJ === uid; }; /** * Is user in waitlist? * @param {Number} [uid] * @return {boolean} */ Room.prototype.isInWaitList = function(uid) { if (!uid) uid = mySelf.id; return this.getWaitListPosition(uid) > 0; }; /** * Reset all room variables */ Room.prototype.reset = function() { booth = { currentDJ: -1, isLocked: false, shouldCycle: true, waitingDJs: [] }; fx = []; grabs = {}; meta = { description: '', favorite: false, hostID: -1, hostName: '', id: -1, name: '', population: 0, guests: 0, slug: '', welcome: '' }; mutes = {}; playback = { historyID: '', media: { author: '', cid: '', duration: -1, format: -1, id: -1, image: '', title: '' }, playlistID: -1, startTime: '' }; role = 0; users = []; votes = {}; }; /** * Add a new user * @param {Object} user User data */ Room.prototype.addUser = function(user) { // Don't add yourself if (user.id === mySelf.id) return; // Handle guests if (user.guest == true) { meta.guests ++; return; } // Only add if the user doesn't exist if (this.getUser(user.id) === null) users.push(user); meta.population ++; // Remove user from cache delete cacheUsers[booth.currentDJ]; }; /** * Remove an user * @param {Number} uid UserID */ Room.prototype.removeUser = function(uid) { // Don't remove yourself if (uid === mySelf.id) return; // User is guest if (uid == 0) { meta.guests --; return; } for (var i in users) { if (!users.hasOwnProperty(i)) continue; if (users[i].id == uid) { // User found cacheUsers[uid] = users.splice(i, 1); meta.population --; return; } } }; /** * Update an user * @param {Object} data User data changes */ Room.prototype.updateUser = function(data) { for (var i in users) { if (!users.hasOwnProperty(i)) continue; if (users[i].id === data.i) { for (var j in data) { if (!data.hasOwnProperty(j)) continue; if (j != 'i') { users[i][j] = data[j]; } } return; } } }; Room.prototype.isMuted = function(uid) { return mutes[uid] != null && mutes[uid] > 0; }; /** * Set mySelf object * @param {Object} data Self data */ Room.prototype.setSelf = function(data) { mySelf = data; }; /** * Set room data * @param {Object} data Room data */ Room.prototype.setRoomData = function(data) { //noinspection JSUnresolvedVariable booth = data.booth; //noinspection JSUnresolvedVariable fx = data.fx; grabs = data.grabs; meta = data.meta; //noinspection JSUnresolvedVariable mutes = data.mutes; //noinspection JSUnresolvedVariable playback = data.playback; mySelf.role = data.role; //noinspection JSUnresolvedVariable users = data.users; //noinspection JSUnresolvedVariable votes = data.votes; }; Room.prototype.setBoothLocked = function(data){ booth.isLocked = data; }; Room.prototype.setDJs = function(djs) { booth.waitingDJs = djs; }; /** * Set the media object. * @param mediaInfo * @param mediaStartTime */ Room.prototype.setMedia = function(mediaInfo, mediaStartTime) { votes = {}; grabs = {}; playback.media = mediaInfo; playback.startTime = mediaStartTime; }; /** * @param {AdvanceEventObject} data */ Room.prototype.advance = function(data) { if (songHistory.length < 1) { setImmediate(this.advance, data); return; } songHistory[0].room = this.getRoomScore(); this.setMedia(data.media, data.startTime); this.setDJs(data.djs); booth.currentDJ = data.currentDJ; playback.historyID = data.historyID; playback.playlistID = data.playlistID; var historyObj = { id: data.historyID, media: data.media, room: { name: meta.name, slug: meta.slug }, score: { positive: 0, listeners: null, grabs: 0, negative: 0, skipped: 0 }, timestamp: data.startTime, user: { id: data.currentDJ, username: this.getUser(data.currentDJ) === null ? '' : this.getUser(data.currentDJ).username } }; if (songHistory.unshift(historyObj) > 50) { songHistory.splice(50, songHistory.length - 50); } // Clear cache of users cacheUsers = {}; }; Room.prototype.muteUser = function(data) { //noinspection JSUnresolvedVariable switch (data.d) { // Unmute case 'o': mutes[data.i] = 0; break; // Short (15 minutes) case 's': mutes[data.i] = 900; break; // Medium (30 minutes) case 'm': mutes[data.i] = 1800; break; // Long (45 minutes) case 'l': mutes[data.i] = 2700; break; } }; Room.prototype.setGrab = function(uid) { grabs[uid] = 1; }; Room.prototype.setVote = function(uid, vote) { votes[uid] = vote; }; Room.prototype.setEarn = function(data) { mySelf.xp = data.xp; mySelf.ep = data.ep; mySelf.level = data.level; }; /** * Get the user object for yourself * @returns {User} */ Room.prototype.getSelf = function() { return mySelf != null ? new User(mySelf) : null; }; /** * Get specific user in the community * @param {Number} [uid] * @returns {User|null} */ Room.prototype.getUser = function(uid) { if (!uid || uid === mySelf.id) return this.getSelf(); for (var i in users) { if (!users.hasOwnProperty(i)) continue; if (users[i].id === uid) return new User(users[i]); } return null; }; /** * Get all users in the community * @returns {User[]} */ Room.prototype.getUsers = function() { return this.usersToArray([mySelf.id].concat((function() { var ids = []; for (var i in users) { if (!users.hasOwnProperty(i)) continue; ids.push(users[i].id); } return ids; })())); }; /** * Get the current DJ * @returns {User|null} Current DJ or {null} if no one is currently DJing */ Room.prototype.getDJ = function() { if (booth.currentDJ > 0) { var user = this.getUser(booth.currentDJ); if (user !== null) return user; if (cacheUsers[booth.currentDJ] !== undefined) return new User(cacheUsers[booth.currentDJ]); } return null; }; /** * Get all DJs (including current DJ) * @returns {User[]} */ Room.prototype.getDJs = function() { return this.usersToArray([booth.currentDJ].concat(booth.waitingDJs)); }; /** * Get all DJs in waitlist * @returns {User[]} */ Room.prototype.getWaitList = function() { return this.usersToArray(booth.waitingDJs); }; /** * Get a user's position in waitlist * @param {Number} uid User ID * @returns {Number} * Position in waitlist. * If current DJ, it returns 0. * If not in waitlist, it returns -1 */ Room.prototype.getWaitListPosition = function(uid) { if (booth.currentDJ === uid) { return 0; } var pos = booth.waitingDJs == null ? -1 : booth.waitingDJs.indexOf(uid); return pos < 0 ? -1 : pos + 1; }; /** * Get admins in the room * @returns {Array} */ Room.prototype.getAdmins = function() { var admins = [], _ref; _ref = [mySelf].concat(users); for (var i in _ref) { if (!_ref.hasOwnProperty(i)) continue; var user = _ref[i]; if (user.gRole == 5) { admins.push(user.id); } } return this.usersToArray(admins); }; /** * Get all ambassadors in the community * @returns {Array} */ Room.prototype.getAmbassadors = function() { var ambassadors = [], _ref; _ref = [mySelf].concat(users); for (var i in _ref) { if (!_ref.hasOwnProperty(i)) continue; var user = _ref[i]; if (user.gRole < 5 && user.gRole > 1) { ambassadors.push(user.id); } } return this.usersToArray(ambassadors); }; /** * Get users in the community that aren't DJing nor in the waitlist * @return {Array} */ Room.prototype.getAudience = function() { var audience = [], _ref; _ref = [mySelf].concat(users); for (var i in _ref) { if (!_ref.hasOwnProperty(i)) continue; var uid = _ref[i].id; if (this.getWaitListPosition(uid) < 0) { audience.push(uid); } } return this.usersToArray(audience); }; Room.prototype.getStaff = function() { var staff = [], _ref; _ref = [mySelf].concat(users); for (var i in _ref) { if (!_ref.hasOwnProperty(i)) continue; var user = _ref[i]; if (user.role > 0) { staff.push(user.id); } } return this.usersToArray(staff); }; /** * Host if in community, otherwise null * @returns {User|null} */ Room.prototype.getHost = function() { return this.getUser(meta.hostID); }; Room.prototype.getMedia = function() { return playback.media; }; Room.prototype.getStartTime = function() { return playback.startTime; }; Room.prototype.getHistoryID = function() { return playback.historyID; }; Room.prototype.getHistory = function() { return songHistory; }; Room.prototype.setHistory = function(err, data) { if (!err) songHistory = data; }; Room.prototype.setCycle = function(cycle) { booth.shouldCycle = cycle; }; /** * Get the booth meta * @return {booth} */ Room.prototype.getBoothMeta = function() { return util._extend({}, booth); }; /** * Get the room meta * @return {meta} */ Room.prototype.getRoomMeta = function() { return util._extend({}, meta); }; /** * Get the room score * @return {{positive: number, listeners: number, grabs: number, negative: number, skipped: number}} */ Room.prototype.getRoomScore = function() { var result = { positive: 0, listeners: Math.max(this.getUsers().length - 1, 0), grabs: 0, negative: 0, skipped: 0 }, i; var _ref = votes; for (i in _ref) { if (!_ref.hasOwnProperty(i)) continue; var vote = _ref[i]; if (vote > 0) { result.positive++; } else if (vote < 0) { result.negative++; } } var _ref1 = grabs; for (i in _ref1) { if (!_ref1.hasOwnProperty(i)) continue; if (_ref1[i] > 0) { result.grabs++; } } return result; }; module.exports = Room;
sample.controller('sampleIndexController', ['$scope', function($scope){ }]);
'use strict'; exports.init = function(req, res){ if (req.isAuthenticated()) { res.redirect(req.user.defaultReturnUrl()); } else { res.render('login/reset/index'); } }; exports.set = function(req, res){ var workflow = req.app.utility.workflow(req, res); workflow.on('validate', function() { if (!req.body.password) { workflow.outcome.errfor.password = 'required'; } if (!req.body.confirm) { workflow.outcome.errfor.confirm = 'required'; } if (req.body.password !== req.body.confirm) { workflow.outcome.errors.push('Passwords do not match.'); } if (workflow.hasErrors()) { return workflow.emit('response'); } workflow.emit('findUser'); }); workflow.on('findUser', function() { var conditions = { email: req.params.email, resetPasswordExpires: { $gt: Date.now() } }; req.app.db.models.User.findOne(conditions, function(err, user) { if (err) { return workflow.emit('exception', err); } if (!user) { workflow.outcome.errors.push('Invalid request - not a user.'); return workflow.emit('response'); } req.app.db.models.User.validatePassword(req.params.token, user.resetPasswordToken, function(err, isValid) { if (err) { return workflow.emit('exception', err); } if (!isValid) { workflow.outcome.errors.push('Invalid request - not valid.'); return workflow.emit('response'); } workflow.emit('patchUser', user); }); }); }); workflow.on('patchUser', function(user) { req.app.db.models.User.encryptPassword(req.body.password, function(err, hash) { if (err) { return workflow.emit('exception', err); } var fieldsToSet = { password: hash, resetPasswordToken: '' }; req.app.db.models.User.findByIdAndUpdate(user._id, fieldsToSet, function(err, user) { if (err) { return workflow.emit('exception', err); } workflow.emit('response'); }); }); }); workflow.emit('validate'); };
'use strict'; /*global SVG, mill */ /* Features: - image preloading - stepping - zoom - animation paths */ function SVGjsAnim(id) { this.draw = SVG(id) .fixSubPixelOffset(); this.scene = this.draw.group() .attr({ id: 'scene' }); this.positionAndScale(); this.resize(); this.zooms = this.draw.set(); } SVGjsAnim.prototype.layers = {}; SVGjsAnim.prototype.activeVideo = ''; SVGjsAnim.prototype.zoomed = false; SVGjsAnim.prototype.stepObjs = []; SVGjsAnim.prototype.bullets = {}; SVGjsAnim.prototype.headings = {}; SVGjsAnim.prototype.animations = []; SVGjsAnim.prototype.steps = []; SVGjsAnim.prototype.stepCurrent = 'overview'; SVGjsAnim.prototype.init = function() { var svgjsAnim = mill; if (svgjsAnim.preloadedImages) { var loadingImage = document.getElementById('anim-loading'); loadingImage.parentNode.removeChild(loadingImage); svgjsAnim.build(); svgjsAnim.start(); } else { setTimeout(svgjsAnim.init, 100); } }; SVGjsAnim.prototype.build = function() { this.transform.defaultX = this.scene.x(); this.transform.defaultY = this.scene.y(); this.resetCamera(); this.setupLayers(); // Ore Circuit var grindingSlurry = this.draw.grindingSlurry('grinding-slurry').go(); var circuitOre = this.draw.image('images/circuit-ore-equipment.svg') .size(this.origSceneW, this.origSceneH); var conveyors = this.setupConveyors(); var receiving = this.setupReceiving(); var crushing = this.setupCrushing(); var storage = this.setupStorage(); var grinding = this.setupGrinding(); var oreToCrusher = this.setupOreToCrusher(); var oreToStorage = this.setupOreToStorageDome(); var oreToGrinding = this.setupOreToSAGMill(); // left var tree = this.draw.tree(700, 385, 0.7); var t0001 = this.draw.tree(95, 320, 0.95); var t0002 = this.draw.tree(200, 600, 1); var t0003 = this.draw.tree(400, 390, 1.5); // middle var t0004 = this.draw.tree(1000, 400, 1.5); // right /* var t0004 = tree.clone().move(2493, 500).scale(0.78); var t0005 = tree.clone().move(1830, 540).scale(0.8); var t0006 = tree.clone().move(2030, 500); var t0007 = tree.clone().move(3030, 420).scale(0.7); var t0008 = tree.clone().move(3080, 460); var t0009 = tree.clone().move(3130, 490).scale(0.8); var t0010 = tree.clone().move(3270, 800).scale(1.3); var t0011 = tree.clone().move(1400, 530).scale(0.9); var t0012 = tree.clone().move(1530, 650).scale(0.95); var t0013 = tree.clone().move(3530, 650).scale(1.2); var t0014 = tree.clone().move(3530, 650).scale(1.2); var t0015 = tree.clone().move(3530, 650).scale(1.3); var t0016 = tree.clone().move(3530, 650).scale(1.3); var t0017 = tree.clone().move(3530, 650).scale(1.5); var t0018 = tree.clone().move(3530, 650).scale(1.5);*/ var trees = this.draw.group() .add(tree) .add(t0002) .add(t0003) .add(t0004); /* .add(t0004) .add(t0005) .addToInner(t0006) .addToInner(t0007) .addToInner(t0008) .addToInner(t0009) .addToInner(t0010) .addToInner(t0011) .addToInner(t0012) .addToInner(t0013) .add(t0014) .add(t0015) .add(t0016) .add(t0017) .add(t0018)*/ this.layers.circuitOre .addToInner(grindingSlurry) .addToInner(circuitOre) .addToInner(trees) .addToInner(conveyors) .addToInner(receiving) .addToInner(t0001) .addToInner(crushing) .addToInner(storage) .addToInner(grinding) .addToInner(oreToCrusher) .addToInner(oreToStorage) .addToInner(oreToGrinding); // Slurry Circuit var slurry = this.draw.slurry('slurrry').go(); var circuitSlurry = this.draw.image('images/circuit-slurry-equipment.svg') .size(this.origSceneW, this.origSceneH); var refining = this.setupRefining(); var electrowinning = this.setupElectrowinning(); var extraction = this.setupExtraction(); /* var t1000 = tree.clone().move(150, 410).scale(2); var t1001 = tree.clone().move(650, 910).scale(2.5); var t1002 = tree.clone().move(3550, 1083).scale(2.3); var t1003 = tree.clone().move(3570, 950).scale(2.3);*/ this.layers.circuitSlurry .addToInner(slurry) .addToInner(circuitSlurry) // .addToInner(t1000) // .addToInner(t1001) // .addToInner(t1002) // .addToInner(t1003) .addToInner(refining) .addToInner(electrowinning) .addToInner(extraction); }; SVGjsAnim.prototype.setupLayers = function() { var w = this.origSceneW; var h = this.origSceneH; var cloudsBack = this.draw.image('images/clouds.svg', w, h) .transform({ scaleX: -1 }); var treescape = this.draw.image('images/treescape.svg', w, h); var cloudsOnce = this.draw.image('images/clouds.svg', w, h); var clouds = this.draw.image('images/clouds.svg', w, h); var circuitOre = this.draw.image('images/circuit-ore.svg', w, h); var circuitSlurry = this.draw.image('images/circuit-slurry.svg', w, h); this.layers.cloudsBack = this.draw.layer({ 'clouds-back': cloudsBack }, w, h) .move(-w, 0); this.layers.cloudsBackClone = this.draw.layer({ 'clouds-back-clone': cloudsBack.clone() }, w, h) .move(-w*2, 0); this.layers.treescape = this.draw.layer({ 'treescape': treescape }, w, h); this.layers.cloudsOnce = this.draw.layer({ 'clouds-once': cloudsOnce }, w, h); this.layers.clouds = this.draw.layer({ 'clouds': clouds }, w, h) .move(-w, 0); this.layers.cloudsClone = this.draw.layer({ 'clouds-clone': clouds.clone() }, w, h) .move(-w*2, 0); // Circuit Ore this.layers.circuitOre = this.draw.layer( { 'circuit-ore': circuitOre }, w, h ); // Circuit Slurry var groundExtension = this.draw.group() .move(0, 1060) .add( this.draw.rect(this.origSceneW, 4000) .attr({ fill: '#4e6a47', id: 'ground' }) ); this.layers.circuitSlurry = this.draw.layer({ 'circuit-slurry-ground': groundExtension, 'circuit-slurry': circuitSlurry }, w, h + 4000 ) .move(0, 585) .moveInner(0, -485); this.scene .add(this.layers.cloudsBack) .add(this.layers.cloudsBackClone) .add(this.layers.treescape) .add(this.layers.cloudsOnce) .add(this.layers.clouds) .add(this.layers.cloudsClone) .add(this.layers.circuitOre) .add(this.layers.circuitSlurry); // var d = 350000; // var d2 = 550000; // this.layers.cloudsBack.animate(d, '-', 0).move(w, 0).loop(); // this.layers.cloudsBackClone.animate(d*2, '-', 0).move(w, 0).loop(); // this.layers.clouds.animate(d2, '-', 0).move(w, 0).loop(); // this.layers.cloudsClone.animate(d2*2, '-', 0).move(w, 0).loop(); // this.layers.cloudsOnce.animate(d, '-', 0) // .move(w, 0) // .after(function(){ this.remove(); }); return this; }; SVGjsAnim.prototype.start = function() { this.showBullets(); this.conveyorGo(); this.cycloneGo(); this.dumpTruck.go(); this.rockBreaker.go(); this.jawCrusher.go(); // Ore for (var i=0; i<this.animations.length; i++) { this.animations[i].animate(); } }; SVGjsAnim.prototype.scale = function(n) { n = n || false; return (n) ? this.scene.scale(n) : this.scene.attr('scale'); }; SVGjsAnim.prototype.move = function(x, y) { this.scene.move(x, y); }; SVGjsAnim.prototype.x = function(x) { this.scene.x(x); }; SVGjsAnim.prototype.y = function(y) { this.scene.y(y); };
/** * Created by socialmoneydev on 8/30/2014. */ var AccountIdOnly = function(){ var self = this; self.accountId = null; }; module.exports = AccountIdOnly;
'use strict'; module.exports = { sms: { url: 'http://sslsms.cafe24.com/sms_sender.php', userId: 'bitpr', secure: 'a8178aeb09e085a76dc64909397f4805 ', source: { phone1: '02', phone2: '598', phone3: '1234' } } }
'use strict'; var util = require('util'); var events = require('events'); function Worker(name, handler, options) { events.EventEmitter.call(this); options = options || {}; this.name = name; this.options = options.queue || {}; this.handler = handler; this.handlerOptions = options.consumer || {}; this.prefetchCount = options.count || 0; this.requeue = (typeof options.requeue !== 'undefined') ? options.requeue : true; this.channel = null; this.status = {}; this.consumer = {}; } util.inherits(Worker, events.EventEmitter); Worker.prototype.start = function(conn, callback) { var that = this; var work = function(msg) { that.handler(msg, function(err, result) { if (!that.handlerOptions.noAck) { if (err) { that.channel.nack(msg, false, that.requeue); } else { that.channel.ack(msg); } } that.emit('complete', { err: err, result: result, msg: msg }); }); }; conn.createChannel().then(function(chan) { that.channel = chan; that.channel.prefetch(that.prefetchCount); return that.channel.assertQueue(that.name, that.options); }).then(function(status) { that.status = status; return that.channel.consume(that.name, work, that.handlerOptions); }).then(function() { callback(); }).catch(function(err) { callback(err); }); }; module.exports = Worker;
/* @flow */ var moment = require('moment'); var rest = require('restler'); var util = require('./util'); var config = require('./../private/config.json'); var neaAuthKey = config.NEA.key; var nowcastURL = 'http://api.nea.gov.sg/api/WebAPI?dataset=2hr_nowcast&keyref=' + neaAuthKey; var psiURL = 'http://api.nea.gov.sg/api/WebAPI/?dataset=psi_update&keyref=' + neaAuthKey; var pm2_5URL = 'http://api.nea.gov.sg/api/WebAPI/?dataset=pm2.5_update&keyref=' + neaAuthKey; function getWeather(callback) { function onFailureCB() { return callback('Something went wrong. Please try again later.'); } function onErrorCB() { return callback('There was an error while retrieving the data. Please try again later.'); } function onTimeoutCB() { return callback('NEA is taking too long to respond. Please try again later.'); } rest.get(nowcastURL, {timeout: 10000}) .on('fail', onFailureCB) .on('timeout', onTimeoutCB) .on('error', onErrorCB) .on('success', function(data) { var nowCastJSON = data.channel.item[0]; var clementiNowcastCode = nowCastJSON.weatherForecast[0].area[9].$.forecast.trim(); // area[9] is Clementi rest.get(psiURL, {timeout: 10000}) .on('fail', onFailureCB) .on('timeout', onTimeoutCB) .on('error', onErrorCB) .on('success', function(data) { var time = moment(data.channel.item[0].region[4].record[0].$.timestamp, 'YYYYMMDDHHmmss').toDate(); var westPSI_24HR = data.channel.item[0].region[4].record[0].reading[0].$.value; var westPSI_3HR = data.channel.item[0].region[4].record[0].reading[1].$.value; rest.get(pm2_5URL, {timeout:10000}) .on('fail', onFailureCB) .on('timeout', onTimeoutCB) .on('error', onErrorCB) .on('success', function(data) { var westPM2_5_1HR = data.channel.item[0].region[3].record[0].reading[0].$.value; var msg = '*Cinnabot Weather Service*\n'; msg += 'Good ' + util.currentTimeGreeting() + ', the weather in *Clementi* at ' + util.formatTime(time) + ' is: _' + getWeatherDesc(clementiNowcastCode) + '_ ' + getWeatherEmoji(clementiNowcastCode) + ' ' + '\n\nHere are the PSI readings:\n*24 Hour PSI:* ' + westPSI_24HR + '\n*3 Hour PSI*: ' + westPSI_3HR + '\n*1 Hour PM 2.5*: ' + westPM2_5_1HR + '.'; callback(msg); }); }); }); } function getWeatherEmoji(weatherCode) { return weatherEmojiMap[weatherCode]; } function getWeatherDesc(weatherCode) { return weatherDescMap[weatherCode]; } var weatherEmojiMap = { 'BR':'๐ŸŒซ', 'CL':'โ˜๏ธ', 'DR':'๐ŸŒง', 'FA':'โ˜€๏ธ', 'FG':'๐ŸŒซ', 'FN':'๐ŸŒ™', 'FW':'โ˜€๏ธ', 'HG':'โ›ˆ๐Ÿƒ', 'HR':'๐ŸŒง๐ŸŒง', 'HS':'๐ŸŒง๐ŸŒง', 'HT':'โ›ˆโ›ˆ', 'HZ':'๐ŸŒซ', 'LH':'๐Ÿ˜ท', 'LR':'๐ŸŒง', 'LS':'๐ŸŒง', 'OC':'โ˜๏ธ', 'PC':'โ›…', 'PN':'โ˜๏ธ', 'PS':'๐Ÿƒ๐ŸŒง', 'RA':'๐ŸŒง', 'SH':'๐ŸŒง', 'SK':'๐Ÿƒ๐ŸŒง', 'SN':'โ›„', 'SR':'๐Ÿƒ๐ŸŒง', 'SS':'๐ŸŒจ', 'SU':'โ˜€๏ธ', 'SW':'๐Ÿƒ๐Ÿƒ', 'TL':'โ›ˆ', 'WC':'๐Ÿƒโ˜๏ธ', 'WD':'๐Ÿƒ', 'WF':'๐Ÿƒ', 'WR':'๐Ÿƒ๐ŸŒง', 'WS':'๐Ÿƒ๐ŸŒง', }; var weatherDescMap = { 'BR':'Mist', 'CL':'Cloudy', 'DR':'Drizzle', 'FA':'Fair (Day)', 'FG':'Fog', 'FN':'Fair (Night)', 'FW':'Fair & Warm', 'HG':'Heavy Thundery Showers with Gusty Winds', 'HR':'Heavy Rain', 'HS':'Heavy Showers', 'HT':'Heavy Thundery Showers', 'HZ':'Hazy', 'LH':'Slightly Hazy', 'LR':'Light Rain', 'LS':'Light Showers', 'OC':'Overcast', 'PC':'Partly Cloudy (Day)', 'PN':'Partly Cloudy (Night)', 'PS':'Passing Showers', 'RA':'Moderate Rain', 'SH':'Showers', 'SK':'Strong Winds, Showers', 'SN':'Snow', 'SR':'Strong Winds, Rain', 'SS':'Snow Showers', 'SU':'Sunny', 'SW':'Strong Winds', 'TL':'Thundery Showers', 'WC':'Windy, Cloudy', 'WD':'Windy', 'WF':'Windy, Fair', 'WR':'Windy, Rain', 'WS':'Windy, Showers', }; module.exports = { getWeather };
/* @echo header */ var // dictonary _dict = { fr: { search: 'Recherche de votre positionnement', position: 'Votre position', unavailable: 'Service de localisation non-disponible', deactivated: 'Service de localisation dรฉsactivรฉ', notFound: 'Position indisponible', timeout: 'Dรฉlai expirรฉ', error: 'Il y a eu un problรจme' }, en: { search: 'Searching your location', position: 'Your position', unavailable: 'Location service unavailable', deactivated: 'Location service deactivated', notFound: 'Position not found', timeout: 'Timeout', error: 'There has been a problem' } }, // get a valid lang _lang = function(lang) { return kafe.fn.lang(_dict,lang); } ; /** * ### Version <!-- @echo VERSION --> * Methods to access geolocalization information about the client. * * @module <!-- @echo MODULE --> * @class <!-- @echo NAME_FULL --> */ var geolocation = {}; /** * Get the current geolocalization information of the client. * * @method locate * @param {Object} parameters Parameters for the current request. * @param {String|jQueryObject|DOMElement} [parameters.selector] Element used to show status messages. * @param {String} [parameters.lang=CURRENT_ENV_LANG] A two character language code. * @param {Function} [parameters.success] Callback triggered when geolocalization informations have been successful retrieved. An object containing the informations is passed as the first argument. * @param {Function} [parameters.error] Callback triggered on geolocalization errors. The error message is passed as the first argument. * @param {Object} [parameters.options] Options given to optimize getCurrentPosition. * @example * <!-- @echo NAME_FULL -->.locate({ * selector: '#GeoLocStatus', lang: 'en', * success: function(coords) { * console.log('latitude: ' + coords.latitude); * console.log('longitude: ' + coords.longitude); * } * error: function(msg) { * console.log('Cannot geoloc: ' + msg); * }, * options: { * enableHighAccuracy: false, * timeout: 5000, * maximumAge: 0 * } * }); * @example * $('#GeoLocStatus').<!-- @echo PACKAGE -->('<!-- @echo NAME -->.locate', {}); */ geolocation.locate = function(parameters) { var d = _dict[_lang(parameters.lang)], $msg = $(parameters.selector), options = (parameters.options) ? parameters.options : {}, errorCallback = parameters.error, successCallback = parameters.success ; // if service available if (Modernizr.geolocation) { $msg.html('... '+d.search+' ...'); // try to get coords navigator.geolocation.getCurrentPosition( // success function(position) { $msg.html(d.position + ': ' + position.coords.latitude + ', ' + position.coords.longitude); if (!!successCallback) { successCallback({coords:position.coords}); } }, // failure function(error) { var msg = ''; switch (error.code) { case 1: msg = d.deactivated; break; case 2: msg = d.notFound; break; case 3: msg = d.timeout; break; } $msg.html(msg); if (!!errorCallback) { errorCallback({message:msg}); } }, // Options to use options ); // if service unavailable } else { var msg = d.unavailable; $msg.html(msg); if (!!errorCallback) { errorCallback({message:msg}); } } }; // Add as jQuery plugin kafe.fn.plugIntojQuery('', { '<!-- @echo NAME -->.locate': function(obj, parameters) { geolocation.locate($.extend({}, parameters[0], {selector:obj})); } }); return geolocation; /* @echo footer */
//= require ./model (function () { 'use strict'; var node = typeof window === 'undefined'; var app = node ? {} : window.app; var Model = node ? require('./model') : app.Model; var Endpoint = Model.extend({}); Endpoint.Collection = Model.Collection.extend({ model: Endpoint }); node ? module.exports = Endpoint : app.Endpoint = Endpoint; })();
var Analyzer = (function() { function Analyzer(options) { var defaults = {}; this.opt = _.extend({}, defaults, options); this.init(); } Analyzer.prototype.init = function(){ this.ctx = this.opt.ctx; this.paths = []; // init canvas this.onUpdate(); // this.loadNodes(); this.loadListeners(); }; Analyzer.prototype.activate = function(path, isNew){ var distances = this.analyzePath(path, isNew); var len = distances.length; // var minD = _.min(distances); // var maxD = _.max(distances); // distances = _.map(distances, function(d, i){ return {index: i, value: UTIL.norm(d, minD, maxD)}; }); distances = _.map(distances, function(d, i){ return {index: i, value: d}; }); distances = _.sortBy(distances, function(d){ return d.value; }); var weights = new Array(len); this.activationDate = new Date(); _.each(distances, function(d, i){ weights[d.index] = (1-d.value) / Math.pow(1.5, i); }); _.each(this.nodes, function(node, i){ node.activate(weights[i]); }); }; Analyzer.prototype.analyze = function(paths){ var _this = this; var nPaths = _.map(paths, function(path){ return _this.getValue(path); }); var clusters = clusterfck.kmeans(nPaths, this.opt.nodeCount); this.loadNodes(clusters); // save the cluster values var path_clusters = _.map(paths, function(p, i){ return -1; }); nPaths = _.map(nPaths, function(p, i){ return {index: i, value: p}; }); _.each(clusters, function(cluster, i){ _.each(cluster, function(path, j){ var match = _.find(nPaths, function(p){ return p.value[0]==path[0] && p.value[1]==path[1] && p.value[2]==path[2]; }); if (match) { path_clusters[match.index] = i; } }); }); localStorage.setItem('node.loaded', JSON.stringify({d: new Date(), data: path_clusters})); }; Analyzer.prototype.analyzePath = function(path, isNew){ var nodes = this.nodes; var value = this.getValue(path); var minDistance = 1; var minNode = 0; var distances = []; // find the closest node _.each(nodes, function(node, i){ var d = node.distance(value); if (d < minDistance) { minDistance = d; minNode = i; } distances.push(d); }); if (isNew) { // add value to closest node nodes[minNode].addValue(value); localStorage.setItem('node.activate', JSON.stringify({d: new Date(), value: minNode})); } return distances; }; Analyzer.prototype.getValue = function(path){ var value = [0, 0, 0]; var precision = 100; var len = path.length; _.each(path, function(point){ var x = point.x * precision; var y = point.y * precision; var xy = y * precision + x; var p = xy / (precision*precision); value[0] += p; value[1] += point.a; value[2] += point.v; }); return [value[0]/len, value[1]/len, value[2]/len]; }; Analyzer.prototype.isActive = function(){ var nodeActive = false; for (var i=0; i<this.nodes.length; i++) { var n = this.nodes[i]; if (n.isActive()) { nodeActive = true; break; } } return nodeActive; }; Analyzer.prototype.loadListeners = function(){ var _this = this; $.subscribe('training.loaded', function(e, d){ _this.analyze(d.data); }); $.subscribe('user.create.points', function(e, d){ _this.activate(d.points, true); }); $.subscribe('machine.create.points', function(e, d){ _this.activate(d.points); }); $(window).on('storage', function(e){ var event = e.originalEvent; if (event.key == 'user.create.points') { _this.activate(JSON.parse(localStorage.getItem('user.create.points')), true); } else if (event.key == 'machine.create.points') { _this.activate(JSON.parse(localStorage.getItem('machine.create.points'))); } }); }; Analyzer.prototype.loadNodes = function(clusters){ var _this = this; var nodeCount = this.opt.nodeCount; var perRow = this.opt.perRow; var nodeOpt = this.opt.node; var position = _.clone(this.pos); var ctx = this.ctx; // console.log(clusters) this.nodes = []; _(nodeCount).times(function(i){ var values = []; if (clusters[i]) values = clusters[i].slice(0); _this.nodes.push(new Node(_.extend({index: i, ctx: ctx, perRow: perRow, parent: position, values: values}, nodeOpt))); }); }; Analyzer.prototype.onUpdate = function(){ this.canvasWidth = this.ctx.canvas.width; this.canvasHeight = this.ctx.canvas.height; var pos = {x: 0, y: 0}; var perRow = this.opt.perRow; // determine width and height pos.width = this.opt.width * this.canvasWidth; var nodeW = pos.width / perRow; var rows = Math.ceil(this.opt.nodeCount / perRow); pos.height = nodeW * rows; // determine x and y pos.x = this.opt.position[0] * this.canvasWidth; pos.y = this.opt.position[1] * this.canvasHeight; pos.x = _.max([0, pos.x - pos.width]); pos.y = _.max([0, pos.y - pos.height]); this.pos = pos; }; Analyzer.prototype.render = function(){ var rest = false; if (this.activationDate) { var t = new Date(); if ((t - this.activationDate) > this.opt.restAfter) { rest = true; this.activationDate = false; } } _.each(this.nodes, function(n){ if (rest) n.rest(); n.render(); }); }; Analyzer.prototype.resize = function(){ var _this = this; this.onUpdate(); _.each(this.nodes, function(n){ n.resize(_.clone(_this.pos)); }); }; return Analyzer; })();
import { mount } from '@vue/test-utils' import useI18nGlobally from '../../../__utils__/i18n' import { PluginInstallModal } from '@/components/PluginManager/PluginManagerModals' jest.mock('electron', () => ({ ipcRenderer: { on: jest.fn(), send: jest.fn(), removeListener: jest.fn() } })) const i18n = useI18nGlobally() let wrapper const plugin = { id: 'test', source: 'source' } const availablePlugin = { config: { id: 'test', source: 'store-source' } } const mocks = { $store: { getters: { 'plugin/availableById': jest.fn(() => availablePlugin) } }, formatter_bytes: jest.fn(bytes => bytes), formatter_percentage: jest.fn() } beforeEach(() => { wrapper = mount(PluginInstallModal, { i18n, mocks, propsData: { plugin }, stubs: { Portal: '<div><slot /></div>' } }) wrapper.setData({ progress: { percent: 0.5, transferredBytes: 50, totalBytes: 100 } }) }) afterEach(() => { wrapper.destroy() }) describe('PluginInstallModal', () => { it('should render', () => { expect(wrapper.isVueInstance()).toBeTrue() }) describe('Methods', () => { it('should emit install event', () => { wrapper.vm.emitInstall() expect(wrapper.emitted('install')).toBeTruthy() }) describe('emitDownload', () => { it('should emit download event with plugin source', () => { wrapper.vm.emitDownload() expect(wrapper.emitted('download', plugin.source)).toBeTruthy() }) it('should emit download event with available plugin source if update', () => { wrapper.setProps({ isUpdate: true }) wrapper.vm.emitDownload() expect(wrapper.emitted('download', availablePlugin.config.source)).toBeTruthy() }) }) describe('emitClose', () => { it('should emit close event', () => { wrapper.vm.emitClose() expect(wrapper.emitted('close')).toBeTruthy() }) it('should call cancel()', () => { jest.spyOn(wrapper.vm, 'cancel') wrapper.vm.emitClose() expect(wrapper.vm.cancel).toHaveBeenCalled() }) it('should call cleanup() if download failed', () => { wrapper.setData({ isDownloadFailed: true }) jest.spyOn(wrapper.vm, 'cleanup') wrapper.vm.emitClose() expect(wrapper.vm.cleanup).toHaveBeenCalled() }) }) }) })
angular .module('app.directives') .directive('wager', wager) ; /* @ngInject */ function wager(TemplateUrls) { return { scope: { wager: '=' }, templateUrl: TemplateUrls.WAGER, replace: true, restrict: 'E' }; }
export { default, initialize } from 'ember-m3/initializers/m3-store';
'use strict'; var express = require('express'); var socketio = require('socket.io'); var app = express(); app.use(express.static('client')); var server = app.listen(3000, function(){ console.log('server listening on port 3000'); }); var io = socketio(server); io.on('connection', function(socket){ console.log('Client connected:', socket.id); socket.on('disconnect', function(){ console.log('Client disconnected:', socket.id); }); socket.on('chatMessage', function(msg){ console.log('Chat Message recieved', msg); // to one socket // socket.emit('chatMessage', {toOne : msg}); // to everyone except the sender // socket.broadcast.emit('chatMessage', {toOthers : msg}); //to everyone io.emit('chatMessage', msg); }); });
// path: test/fixtures/barView.js // filename: barView.js define(['test/fixtures/barView'], function(BarView) { 'use strict'; describe('test/fixtures/barView', function() { var barView; beforeEach(function() { barView = new BarView(); }); describe('constructor', function() { }); }); });
import Model, { attr } from "@ember-data/model"; export default class UserModel extends Model { @attr firstName; @attr lastName; @attr aboutMe; @attr country; @attr gender; @attr terms; @attr color; }
'use strict'; // B.2.3.12 String.prototype.strike() require('./_string-html')('strike', function (createHTML) { return function strike() { return createHTML(this, 'strike', '', ''); }; }); //# sourceMappingURL=es6.string.strike.js.map
define({ root: ({ methodNotConfigured: 'Function ${method} is not configured for controller ${controller}.', noDefaultMethod: 'Controller ${controller} has no default method defined', noConfig: 'Controller name ${controller} could not be found in the di config.', noMethod: 'Function ${method} could not found be in the controller instance created from the ${controller} controller config.' }) });
/** * Created by AntecPC on 4/11/2015. */ (function (){ 'use strict'; //var app = angular.module('blogApp'); //get data from json app.factory('basicService', function ($http, $q){ return { savePair: function (pair) { var defer = $q.defer(); $http.post('http://168.63.96.84:1978/savePair', { pair: pair }).success(function (data, status) { defer.resolve(data); }); return defer.promise; }, labelText: 'allPosts', typeOfSearch: 'filterAll', quantity: 0 }; //return $http.get('data/posts.json'); }); }());
/** * MENU3 - ์žฌ๋ฌดํšŒ๊ณ„ ํŽ˜์ด์ง€ ํ•จ์ˆ˜ ๋ชจ์Œ */ // ๊ตฌ๋ถ„ ๋ชฉ๋ก์ƒ์ž ์„ ํƒ1 (capital2.php // capital_edit.php // capital3.php) function inoutSel(form, no, pj){ // ==capital2.php ์™€ capital_edit.php => form // capital3.php => no // ํ˜„์žฅ์ „๋„๊ธˆ์ผ๋•Œ pj ์ธ์žํ™œ์šฉ var class1_str = "class1_"; var class1 = class1_str+no; // ๊ตฌ๋ถ„1 var class2_str = "class2_"; var class2 = class2_str+no; // ๊ตฌ๋ถ„2 var pj_seq_str = "pj_seq_"; var pj_seq = pj_seq_str+no; // ํ˜„์žฅ์ฝ”๋“œ var jh_loan_str = "jh_loan_"; var jh_loan = jh_loan_str+no; // ์กฐํ•ฉ๋Œ€์—ฌ ์—ฌ๋ถ€ var d1_1_str = "d1_1_"; var d1_1 = d1_1_str+no; // ์ž์‚ฐ๊ณ„์ • td var d1_2_str = "d1_2_"; var d1_2 = d1_2_str+no; // ๋ถ€์ฑ„๊ณ„์ • td var d1_3_str = "d1_3_"; var d1_3 = d1_3_str+no; // ์ž๋ณธ๊ณ„์ • td var d1_4_str = "d1_4_"; var d1_4 = d1_4_str+no; // ์ˆ˜์ต๊ณ„์ • td var d1_5_str = "d1_5_"; var d1_5 = d1_5_str+no; // ๋น„์šฉ๊ณ„์ • td var d1_acc1_str = "d1_acc1_"; var d1_acc1 = d1_acc1_str+no; // ์ž์‚ฐ ๊ณ„์ •๊ณผ๋ชฉ var d1_acc2_str = "d1_acc2_"; var d1_acc2 = d1_acc2_str+no; // ๋ถ€์ฑ„ ๊ณ„์ •๊ณผ๋ชฉ var d1_acc3_str = "d1_acc3_"; var d1_acc3 = d1_acc3_str+no; // ์ž๋ณธ ๊ณ„์ •๊ณผ๋ชฉ var d1_acc4_str = "d1_acc4_"; var d1_acc4 = d1_acc4_str+no; // ์ˆ˜์ต ๊ณ„์ •๊ณผ๋ชฉ var d1_acc5_str = "d1_acc5_"; var d1_acc5 = d1_acc5_str+no; // ๋น„์šฉ ๊ณ„์ •๊ณผ๋ชฉ var in_str = "in_"; var iin = in_str+no; // ์ž…๊ธˆ์ฒ˜ var inc_str = "inc_"; var inc = inc_str+no; // ์ž…๊ธˆ์•ก var out_str = "out_"; var out = out_str+no; // ์ถœ๊ธˆ์ฒ˜ var exp_str = "exp_"; var exp = exp_str+no; // ์ถœ๊ธˆ์•ก var class1_id = document.getElementById(class1); if( !no) var class1_id = form.class1; var class2_id = document.getElementById(class2); if( !no) var class2_id = form.class2; var pj_seq_id = document.getElementById(pj_seq); if( !no) var pj_seq_id = form.any_jh; var jh_loan_id = document.getElementById(jh_loan); if( !no) var jh_loan_id = form.is_jh; var d1_1_id = document.getElementById(d1_1); var d1_2_id = document.getElementById(d1_2); var d1_3_id = document.getElementById(d1_3); var d1_4_id = document.getElementById(d1_4); var d1_5_id = document.getElementById(d1_5); var d1_acc1_id = document.getElementById(d1_acc1); if( !no) var d1_acc1_id = document.getElementById('d1_1'); var d1_acc2_id = document.getElementById(d1_acc2); if( !no) var d1_acc2_id = document.getElementById('d1_2'); var d1_acc3_id = document.getElementById(d1_acc3); if( !no) var d1_acc3_id = document.getElementById('d1_3'); var d1_acc4_id = document.getElementById(d1_acc4); if( !no) var d1_acc4_id = document.getElementById('d1_4'); var d1_acc5_id = document.getElementById(d1_acc5); if( !no) var d1_acc5_id = document.getElementById('d1_5'); var in_id = document.getElementById(iin); if(!no) var in_id = form.ina; var inc_id = document.getElementById(inc); if(!no) var inc_id = form.inc; var out_id = document.getElementById(out); if(!no) var out_id = form.out; var exp_id = document.getElementById(exp); if(!no) var exp_id = form.exp; class2_id.disabled=0; if(class1_id.value==1){ //1๋ฒˆ์งธ ์…€๋ ‰ํŠธ๋ฐ” ์ž…๊ธˆ์ด๋ฉด class2_id.length=5; //2๋ฒˆ์งธ ์…€๋ ‰ํŠธ๋ฐ” ๋ชฉ๋ก 5๊ฐœ class2_id.options[0].text = '์„  ํƒ';//2-1๋ฒˆ์งธ ์…€๋ ‰ํŠธ๋ฐ” ํ…์ŠคํŠธ ์ •์˜ class2_id.options[0].value = '0';//2-1๋ฒˆ์งธ ์…€๋ ‰ํŠธ๋ฐ” ๊ฐ’ ์ •์˜ class2_id.options[1].text = '์ž ์‚ฐ';//2-1๋ฒˆ์งธ ์…€๋ ‰ํŠธ๋ฐ” ํ…์ŠคํŠธ ์ •์˜ class2_id.options[1].value = '1';//2-1๋ฒˆ์งธ ์…€๋ ‰ํŠธ๋ฐ” ๊ฐ’ ์ •์˜ class2_id.options[2].text = '๋ถ€ ์ฑ„';//2-2๋ฒˆ์งธ ์…€๋ ‰ํŠธ๋ฐ” ํ…์ŠคํŠธ ์ •์˜ class2_id.options[2].value = '2';//2-2๋ฒˆ์งธ ์…€๋ ‰ํŠธ๋ฐ” ๊ฐ’ ์ •์˜ class2_id.options[3].text = '์ž ๋ณธ';//2-3๋ฒˆ์งธ ์…€๋ ‰ํŠธ๋ฐ” ํ…์ŠคํŠธ ์ •์˜ class2_id.options[3].value = '3';//2-3๋ฒˆ์งธ ์…€๋ ‰ํŠธ๋ฐ” ๊ฐ’ ์ •์˜ class2_id.options[4].text = '์ˆ˜ ์ต';//2-4๋ฒˆ์งธ ์…€๋ ‰ํŠธ๋ฐ” ํ…์ŠคํŠธ ์ •์˜ class2_id.options[4].value = '4';//2-4๋ฒˆ์งธ ์…€๋ ‰ํŠธ๋ฐ” ๊ฐ’ ์ •์˜ if( !jh_loan_id || jh_loan_id.checked==0){ class2_id.options[4].selected =1; // ์ˆ˜์ต์„ ์„ ํƒํ•˜๊ณ  /////// if(d1_1_id)d1_1_id.style.display='none'; //์ž์‚ฐ๊ณ„์ • ๋น„ํ™œ์„ฑ if(d1_2_id)d1_2_id.style.display='none'; //๋ถ€์ฑ„๊ณ„์ • ๋น„ํ™œ์„ฑ if(d1_3_id)d1_3_id.style.display='none'; //์ž๋ณธ๊ณ„์ • ๋น„ํ™œ์„ฑ if(d1_4_id)d1_4_id.style.display=''; //์ˆ˜์ต๊ณ„์ • ํ™œ์„ฑํ™” if(d1_5_id)d1_5_id.style.display='none'; //๋น„์šฉ๊ณ„์ • ๋น„ํ™œ์„ฑ d1_acc1_id.disabled=1; d1_acc1_id.style.display='none'; d1_acc2_id.disabled=1; d1_acc2_id.style.display='none'; d1_acc3_id.disabled=1; d1_acc3_id.style.display='none'; d1_acc4_id.disabled=0; d1_acc4_id.style.display=''; /// ์ˆ˜์ต๊ณ„์ • ํ™œ์„ฑํ™” d1_acc5_id.disabled=1; d1_acc5_id.style.display='none'; }else{ class2_id.options[1].selected =1; // ์ž์‚ฐ์„ ์„ ํƒํ•˜๊ณ  /////// if(d1_1_id)d1_1_id.style.display=''; //์ž์‚ฐ๊ณ„์ • ํ™œ์„ฑ if(d1_2_id)d1_2_id.style.display='none'; //๋ถ€์ฑ„๊ณ„์ • ๋น„ํ™œ์„ฑ if(d1_3_id)d1_3_id.style.display='none'; //์ž๋ณธ๊ณ„์ • ๋น„ํ™œ์„ฑ if(d1_4_id)d1_4_id.style.display='none'; //์ˆ˜์ต๊ณ„์ • ๋น„ํ™œ์„ฑ if(d1_5_id)d1_5_id.style.display='none'; //๋น„์šฉ๊ณ„์ • ๋น„ํ™œ์„ฑ d1_acc1_id.disabled=0; d1_acc1_id.style.display=''; d1_acc2_id.disabled=1; d1_acc2_id.style.display='none'; d1_acc3_id.disabled=1; d1_acc3_id.style.display='none'; d1_acc4_id.disabled=1; d1_acc4_id.style.display='none'; /// ์ˆ˜์ต๊ณ„์ • ํ™œ์„ฑํ™” d1_acc5_id.disabled=1; d1_acc5_id.style.display='none'; } in_id.disabled=0; inc_id.disabled=0; out_id.disabled=1; out_id.options[0].selected =1; exp_id.disabled=1; exp_id.value=null; }else if(class1_id.value==2){ //1๋ฒˆ์งธ ์…€๋ ‰ํŠธ๋ฐ” ์ถœ๊ธˆ์ด๋ฉด class2_id.length=5; class2_id.options[0].text = '์„  ํƒ'; class2_id.options[0].value = '0'; class2_id.options[1].text = '์ž ์‚ฐ'; class2_id.options[1].value = '1'; class2_id.options[2].text = '๋ถ€ ์ฑ„'; class2_id.options[2].value = '2'; class2_id.options[3].text = '์ž ๋ณธ'; class2_id.options[3].value = '3'; class2_id.options[4].text = '๋น„ ์šฉ'; class2_id.options[4].value = '5'; if(!jh_loan_id||jh_loan_id.checked==0){ class2_id.options[4].selected =1; // ๋น„์šฉ์„ ์„ ํƒํ•˜๊ณ  /////// if(d1_1_id)d1_1_id.style.display='none'; //์ž์‚ฐ๊ณ„์ • ๋น„ํ™œ์„ฑ if(d1_2_id)d1_2_id.style.display='none'; //๋ถ€์ฑ„๊ณ„์ • ๋น„ํ™œ์„ฑ if(d1_3_id)d1_3_id.style.display='none'; //์ž๋ณธ๊ณ„์ • ๋น„ํ™œ์„ฑ if(d1_4_id)d1_4_id.style.display='none'; //์ˆ˜์ต๊ณ„์ • ๋น„ํ™œ์„ฑ if(d1_5_id)d1_5_id.style.display=''; //๋น„์šฉ๊ณ„์ • ํ™œ์„ฑํ™” d1_acc1_id.disabled=1; d1_acc1_id.style.display='none'; d1_acc2_id.disabled=1; d1_acc2_id.style.display='none'; d1_acc3_id.disabled=1; d1_acc3_id.style.display='none'; d1_acc4_id.disabled=1; d1_acc4_id.style.display='none'; d1_acc5_id.disabled=0; d1_acc5_id.style.display=''; /// ๋น„์šฉ๊ณ„์ • ํ™œ์„ฑํ™” }else{ class2_id.options[1].selected =1; // ์ž์‚ฐ์„ ์„ ํƒํ•˜๊ณ  /////// if(d1_1_id)d1_1_id.style.display=''; //์ž์‚ฐ๊ณ„์ • ํ™œ์„ฑํ™” if(d1_2_id)d1_2_id.style.display='none'; //๋ถ€์ฑ„๊ณ„์ • ๋น„ํ™œ์„ฑ if(d1_3_id)d1_3_id.style.display='none'; //์ž๋ณธ๊ณ„์ • ๋น„ํ™œ์„ฑ if(d1_4_id)d1_4_id.style.display='none'; //์ˆ˜์ต๊ณ„์ • ๋น„ํ™œ์„ฑ if(d1_5_id)d1_5_id.style.display='none'; //๋น„์šฉ๊ณ„์ • ๋น„ํ™œ์„ฑ d1_acc1_id.disabled=0; d1_acc1_id.style.display=''; //์ž์‚ฐ๊ณ„์ • ํ™œ์„ฑํ™” d1_acc2_id.disabled=1; d1_acc2_id.style.display='none'; d1_acc3_id.disabled=1; d1_acc3_id.style.display='none'; d1_acc4_id.disabled=1; d1_acc4_id.style.display='none'; d1_acc5_id.disabled=1; d1_acc5_id.style.display='none'; } in_id.disabled=1; in_id.options[0].selected =1; inc_id.disabled=1; inc_id.value=null; out_id.disabled=0; exp_id.disabled=0; }else if(class1_id.value==3){ class2_id.length=3; if(pj=='pj'){ class2_id.options[0].text = '์„  ํƒ'; class2_id.options[0].value = '0'; class2_id.options[1].text = 'ํ˜„ ์žฅ'; class2_id.options[1].value = '7'; class2_id.options[1].selected =1; // ํ˜„์žฅ์„ ์„ ํƒํ•˜๊ณ  class2_id.options[2].text = '๋ณธ ์‚ฌ'; class2_id.options[2].value = '6'; }else{ class2_id.options[0].text = '์„  ํƒ'; class2_id.options[0].value = '0'; class2_id.options[1].text = '๋ณธ ์‚ฌ'; class2_id.options[1].value = '6'; class2_id.options[1].selected =1; // ๋ณธ์‚ฌ๋ฅผ ์„ ํƒํ•˜๊ณ  class2_id.options[2].text = 'ํ˜„ ์žฅ'; class2_id.options[2].value = '7'; } ////////////////////////////// pj_seq_id.options[0].selected =1; pj_seq_id.disabled=1; jh_loan_id.checked=0; jh_loan_id.disabled=1; if(d1_1_id)d1_1_id.style.display=''; //์ฒซ๋ฒˆ์งธ ํ™œ์„ฑํ™” if(d1_2_id)d1_2_id.style.display='none'; //๋ถ€์ฑ„๊ณ„์ • ๋น„ํ™œ์„ฑํ™” if(d1_3_id)d1_3_id.style.display='none'; //์ž๋ณธ๊ณ„์ • ๋น„ํ™œ์„ฑํ™” if(d1_4_id)d1_4_id.style.display='none'; //์ˆ˜์ต๊ณ„์ • ๋น„ํ™œ์„ฑํ™” if(d1_5_id)d1_5_id.style.display='none'; //๋น„์šฉ๊ณ„์ • ๋น„ํ™œ์„ฑํ™” d1_acc1_id.options[0].selected =1; // ์„ ํƒ์„ ์„ ํƒํ•˜๊ณ  d1_acc1_id.disabled=1; d1_acc1_id.style.display=''; //์ž์‚ฐ๊ณ„์ • ํ™œ์„ฑํ™” d1_acc2_id.disabled=1; d1_acc2_id.style.display='none'; d1_acc3_id.disabled=1; d1_acc3_id.style.display='none'; d1_acc4_id.disabled=1; d1_acc4_id.style.display='none'; d1_acc5_id.disabled=1; d1_acc5_id.style.display='none'; in_id.disabled=0; inc_id.disabled=0; out_id.disabled=0; exp_id.disabled=0; }else{ // ์„ ํƒ(๊ฐ’์ด '0')์„ ์„ ํƒํ•˜๋ฉด class2_id.disabled=1; class2_id.length=1; class2_id.options[0].text = '์„  ํƒ'; class2_id.options[0].value = ''; class2_id.options[0].selected =1; // ์„ ํƒ์„ ์„ ํƒํ•˜๊ณ  pj_seq_id.options[0].selected=1; pj_seq_id.disabled=1; jh_loan_id.checked=0; jh_loan_id.disabled=1; ////////////////////////////// if(d1_1_id)d1_1_id.style.display=''; //์ˆ˜์ต๊ณ„์ • ํ™œ์„ฑํ™” if(d1_2_id)d1_2_id.style.display='none'; //๋ถ€์ฑ„๊ณ„์ • ๋น„ํ™œ์„ฑํ™” if(d1_3_id)d1_3_id.style.display='none'; //์ž๋ณธ๊ณ„์ • ๋น„ํ™œ์„ฑํ™” if(d1_4_id)d1_4_id.style.display='none'; //์ˆ˜์ต๊ณ„์ • ๋น„ํ™œ์„ฑํ™” if(d1_5_id)d1_5_id.style.display='none'; //๋น„์šฉ๊ณ„์ • ๋น„ํ™œ์„ฑํ™” d1_acc1_id.disabled=1; d1_acc1_id.style.display=''; //์ž์‚ฐ๊ณ„์ • ํ™œ์„ฑํ™” d1_acc2_id.disabled=1; d1_acc2_id.style.display='none'; d1_acc3_id.disabled=1; d1_acc3_id.style.display='none'; d1_acc4_id.disabled=1; d1_acc4_id.style.display='none'; d1_acc5_id.disabled=1; d1_acc5_id.style.display='none'; in_id.disabled=1; // ์ž…๊ธˆ๊ณ„์ • inc_id.disabled=0; // ์ž…๊ธˆ๊ธˆ์•ก out_id.disabled=1; // ์ถœ๊ธˆ๊ณ„์ • exp_id.disabled=0; // ์ถœ๊ธˆ๊ธˆ์•ก } } // ๊ตฌ๋ถ„๋ชฉ๋ก ์ƒ์ž์„ ํƒ2 (capital2.php // capital_edit.php // capital3.php) function inoutSel2(form, no){ // ==capital2.php ์™€ capital_edit.php => form // capital3.php => no ์ธ์ž var class1_str = "class1_"; var class1 = class1_str+no; // ๊ตฌ๋ถ„1 var class2_str = "class2_"; var class2 = class2_str+no; // ๊ตฌ๋ถ„2 var pj_seq_str = "pj_seq_"; var pj_seq = pj_seq_str+no; // ํ˜„์žฅ์ฝ”๋“œ var jh_loan_str = "jh_loan_"; var jh_loan = jh_loan_str+no; // ์กฐํ•ฉ๋Œ€์—ฌ ์—ฌ๋ถ€ var d1_1_str = "d1_1_"; var d1_1 = d1_1_str+no; // ์ž์‚ฐ๊ณ„์ • td var d1_2_str = "d1_2_"; var d1_2 = d1_2_str+no; // ๋ถ€์ฑ„๊ณ„์ • td var d1_3_str = "d1_3_"; var d1_3 = d1_3_str+no; // ์ž๋ณธ๊ณ„์ • td var d1_4_str = "d1_4_"; var d1_4 = d1_4_str+no; // ์ˆ˜์ต๊ณ„์ • td var d1_5_str = "d1_5_"; var d1_5 = d1_5_str+no; // ๋น„์šฉ๊ณ„์ • td var d1_acc1_str = "d1_acc1_"; var d1_acc1 = d1_acc1_str+no; // ์ž์‚ฐ ๊ณ„์ •๊ณผ๋ชฉ var d1_acc2_str = "d1_acc2_"; var d1_acc2 = d1_acc2_str+no; // ๋ถ€์ฑ„ ๊ณ„์ •๊ณผ๋ชฉ var d1_acc3_str = "d1_acc3_"; var d1_acc3 = d1_acc3_str+no; // ์ž๋ณธ ๊ณ„์ •๊ณผ๋ชฉ var d1_acc4_str = "d1_acc4_"; var d1_acc4 = d1_acc4_str+no; // ์ˆ˜์ต ๊ณ„์ •๊ณผ๋ชฉ var d1_acc5_str = "d1_acc5_"; var d1_acc5 = d1_acc5_str+no; // ๋น„์šฉ ๊ณ„์ •๊ณผ๋ชฉ var in_str = "in_"; var iin = in_str+no; // ์ž…๊ธˆ์ฒ˜ var inc_str = "inc_"; var inc = inc_str+no; // ์ž…๊ธˆ์•ก var out_str = "out_"; var out = out_str+no; // ์ถœ๊ธˆ์ฒ˜ var exp_str = "exp_"; var exp = exp_str+no; // ์ถœ๊ธˆ์•ก var class1_id = document.getElementById(class1); if(!no) var class1_id = form.class1; var class2_id = document.getElementById(class2); if(!no) var class2_id = form.class2; var pj_seq_id = document.getElementById(pj_seq); if(!no) var pj_seq_id = form.any_jh; var jh_loan_id = document.getElementById(jh_loan); if(!no) var jh_loan_id = form.is_jh; var d1_1_id = document.getElementById(d1_1);//////////// ์ž์‚ฐ๊ณ„์ • TD var d1_2_id = document.getElementById(d1_2); // ๋ถ€์ฑ„๊ณ„์ • TD var d1_3_id = document.getElementById(d1_3); // ์ž๋ณธ๊ณ„์ • TD var d1_4_id = document.getElementById(d1_4); // ์ˆ˜์ต๊ณ„์ • TD var d1_5_id = document.getElementById(d1_5);//////////// ๋น„์šฉ๊ณ„์ • TD var d1_acc1_id = document.getElementById(d1_acc1); if(!no) var d1_acc1_id = document.getElementById('d1_1');////// ์ž์‚ฐ๊ณ„์ • FORM var d1_acc2_id = document.getElementById(d1_acc2); if(!no) var d1_acc2_id = document.getElementById('d1_2'); // ๋ถ€์ฑ„๊ณ„์ • FORM var d1_acc3_id = document.getElementById(d1_acc3); if(!no) var d1_acc3_id = document.getElementById('d1_3'); // ์ž๋ณธ๊ณ„์ • FORM var d1_acc4_id = document.getElementById(d1_acc4); if(!no) var d1_acc4_id = document.getElementById('d1_4'); // ์ˆ˜์ต๊ณ„์ • FORM var d1_acc5_id = document.getElementById(d1_acc5); if(!no) var d1_acc5_id = document.getElementById('d1_5');////// ๋น„์šฉ๊ณ„์ • FORM var in_id = document.getElementById(iin); if(!no) var in_id = form.ina; var inc_id = document.getElementById(inc); if(!no) var inc_id = form.inc; var out_id = document.getElementById(out); if(!no) var out_id = form.out; var exp_id = document.getElementById(exp); if(!no) var exp_id = form.exp; if(class2_id.value>0&&class2_id.value<=3) { // ์ž์‚ฐ, ๋ถ€์ฑ„, ์ž๋ณธ ํ•ญ๋ชฉ๋“ค ์„ ํƒ ์‹œ //if(class1_id.value==3) class1_id.options[0].selected=1; if(class2_id.value==1){ // ์ž์‚ฐ์„ ์„ ํƒํ•˜๋ฉด if(d1_1_id) d1_1_id.style.display=''; // ์ž์‚ฐ๊ณ„์ •๊ณผ๋ชฉ ๋ณด์ด๊ธฐ if(d1_2_id)d1_2_id.style.display='none'; if(d1_3_id)d1_3_id.style.display='none'; if(d1_4_id)d1_4_id.style.display='none'; if(d1_5_id)d1_5_id.style.display='none'; d1_acc1_id.disabled=0; d1_acc1_id.style.display=''; // ์ž์‚ฐ๊ณ„์ •๊ณผ๋ชฉ ๋ณด์ด๊ธฐ d1_acc2_id.disabled=1; d1_acc2_id.style.display='none'; d1_acc3_id.disabled=1; d1_acc3_id.style.display='none'; d1_acc4_id.disabled=1; d1_acc4_id.style.display='none'; d1_acc5_id.disabled=1; d1_acc5_id.style.display='none'; }else if(class2_id.value==2){ // ๋ถ€์ฑ„ ์„ ํƒํ•˜๋ฉด if(d1_1_id) d1_1_id.style.display='none'; if(d1_2_id)d1_2_id.style.display=''; // ๋ถ€์ฑ„๊ณ„์ •๊ณผ๋ชฉ ๋ณด์ด๊ณ  if(d1_3_id)d1_3_id.style.display='none'; if(d1_4_id)d1_4_id.style.display='none'; if(d1_5_id)d1_5_id.style.display='none'; d1_acc1_id.disabled=1; d1_acc1_id.style.display='none'; d1_acc2_id.disabled=0; d1_acc2_id.style.display=''; // ๋ถ€์ฑ„๊ณ„์ •๊ณผ๋ชฉ ๋ณด์ด๊ธฐ d1_acc3_id.disabled=1; d1_acc3_id.style.display='none'; d1_acc4_id.disabled=1; d1_acc4_id.style.display='none'; d1_acc5_id.disabled=1; d1_acc5_id.style.display='none'; }else if(class2_id.value==3){ // ์ž๋ณธ ์„ ํƒํ•˜๋ฉด if(d1_1_id) d1_1_id.style.display='none'; if(d1_2_id)d1_2_id.style.display='none'; if(d1_3_id)d1_3_id.style.display=''; // ์ž๋ณธ๊ณ„์ •๊ณผ๋ชฉ ๋ณด์ด๊ณ  if(d1_4_id)d1_4_id.style.display='none'; if(d1_5_id)d1_5_id.style.display='none'; d1_acc1_id.disabled=1; d1_acc1_id.style.display='none'; d1_acc2_id.disabled=1; d1_acc2_id.style.display='none'; d1_acc3_id.disabled=0; d1_acc3_id.style.display=''; // ์ž๋ณธ๊ณ„์ •๊ณผ๋ชฉ ๋ณด์ด๊ณ  d1_acc4_id.disabled=1; d1_acc4_id.style.display='none'; d1_acc5_id.disabled=1; d1_acc5_id.style.display='none'; } }else if(class2_id.value==4) { // ์ˆ˜์ต ํ•ญ๋ชฉ์„ ์„ ํƒํ•˜๋ฉด class1_id.options[1].selected=1; // 1๋ฒˆ์งธ ์…€๋ ‰ํŠธ๋„ ์ž…๊ธˆ์„ ์„ ํƒ in_id.disabled=0; // ์ž…๊ธˆ์ฒ˜ ์—ด๊ณ  inc_id.disabled=0; // ์ž…๊ธˆ์•ก ์—ด๊ณ  out_id.disabled=1; // ์ถœ๊ธˆ์ฒ˜ ๋‹ซ๊ณ  exp_id.disabled=1; // ์ถœ๊ธˆ์•ก ๋‹ซ๊ณ  if(d1_1_id) d1_1_id.style.display='none'; if(d1_2_id)d1_2_id.style.display='none'; if(d1_3_id)d1_3_id.style.display='none'; if(d1_4_id)d1_4_id.style.display=''; // ์ˆ˜์ต๊ณ„์ •๊ณผ๋ชฉ ๋ณด์ด๊ณ  if(d1_5_id)d1_5_id.style.display='none'; d1_acc1_id.disabled=1; d1_acc1_id.style.display='none'; d1_acc2_id.disabled=1; d1_acc2_id.style.display='none'; d1_acc3_id.disabled=1; d1_acc3_id.style.display='none'; d1_acc4_id.disabled=0; d1_acc4_id.style.display=''; // ์ˆ˜์ต๊ณ„์ •๊ณผ๋ชฉ ๋ณด์ด๊ณ  d1_acc5_id.disabled=1; d1_acc5_id.style.display='none'; }else if(class2_id.value==5){ // ๋น„์šฉ ํ•ญ๋ชฉ์„ ์„ ํƒํ•˜๋ฉด class1_id.options[2].selected=1; // 1๋ฒˆ์งธ ์…€๋ ‰ํŠธ๋„ ์ถœ๊ธˆ์„ ์„ ํƒ in_id.disabled=1; // ์ž…๊ธˆ์ฒ˜ ๋‹ซ๊ณ  inc_id.disabled=1; // ์ž…๊ธˆ์•ก ๋‹ซ๊ณ  out_id.disabled=0; // ์ถœ๊ธˆ์ฒ˜ ์—ด๊ณ  exp_id.disabled=0; // ์ถœ๊ธˆ์•ก ์—ด๊ณ  if(d1_1_id) d1_1_id.style.display='none'; if(d1_2_id)d1_2_id.style.display='none'; if(d1_3_id)d1_3_id.style.display='none'; if(d1_4_id)d1_4_id.style.display='none'; if(d1_5_id)d1_5_id.style.display=''; // ๋น„์šฉ๊ณ„์ •๊ณผ๋ชฉ ๋ณด์ด๊ณ  d1_acc1_id.disabled=1; d1_acc1_id.style.display='none'; d1_acc2_id.disabled=1; d1_acc2_id.style.display='none'; d1_acc3_id.disabled=1; d1_acc3_id.style.display='none'; d1_acc4_id.disabled=1; d1_acc4_id.style.display='none'; d1_acc5_id.disabled=0; d1_acc5_id.style.display=''; // ๋น„์šฉ๊ณ„์ •๊ณผ๋ชฉ ๋ณด์ด๊ณ  }else if(class2_id.value>5){ ///////////////////// ๋Œ€์ฒด๊ด€๋ จ ํ•ญ๋ชฉ์ด๋ฉด class1_id.options[3].selected=1; // 1๋ฒˆ์งธ ์…€๋ ‰ํŠธ๋„ ๋Œ€์ฒด๋ฅผ ์„ ํƒ in_id.disabled=0; // ์ž…๊ธˆ์ฒ˜ ์—ด๊ณ  inc_id.disabled=0; // ์ž…๊ธˆ์•ก ์—ด๊ณ  out_id.disabled=0; // ์ถœ๊ธˆ์ฒ˜ ์—ด๊ณ  exp_id.disabled=0; // ์ถœ๊ธˆ์•ก ์—ด๊ณ  if(d1_1_id) d1_1_id.style.display=''; if(d1_2_id)d1_2_id.style.display='none'; if(d1_3_id)d1_3_id.style.display='none'; if(d1_4_id)d1_4_id.style.display='none'; if(d1_5_id)d1_5_id.style.display='none'; d1_acc1_id.style.disabled=1; d1_acc2_id.style.disabled=1; d1_acc3_id.style.disabled=1; d1_acc4_id.style.disabled=1; d1_acc5_id.style.disabled=1; } if(class2_id.value==1){ if(jh_loan_id)jh_loan_id.disabled=0; }else{ if(jh_loan_id)jh_loan_id.disabled=1;// ๋Œ€์—ฌ ์„ ํƒ ์‹œ ์กฐํ•ฉ๋Œ€์—ฌ๊ธˆ ์ฒดํฌ๋ฐ•์Šค ์—ด๊ธฐ if(jh_loan_id)jh_loan_id.checked=0; } if(class2_id.value==7) if(pj_seq_id)pj_seq_id.disabled=false; else if(pj_seq_id)pj_seq_id.disabled=true; // ํ˜„์žฅ ๋Œ€์ฒด ์„ ํƒ ์‹œ ํ˜„์žฅ ์„ ํƒ ์—ด๊ธฐ } /** * // ์กฐํ•ฉ๋Œ€์—ฌ๊ธˆ ์—ฌ๋ถ€ ์ฒดํฌ๋ฐ•์Šค ์ฒดํฌ ์‹œ * @param {[type]} no [description] * @return {[type]} [description] */ function jh_chk(no){ var pj_seq_str = "pj_seq_"; // ํ˜„์žฅ์ฝ”๋“œ var pj_seq = pj_seq_str+no; var jh_loan_str = "jh_loan_"; // ์กฐํ•ฉ๋Œ€์—ฌ ์—ฌ๋ถ€ var jh_loan = jh_loan_str+no; var pj_seq_id = document.getElementById(pj_seq); var jh_loan_id = document.getElementById(jh_loan); if(jh_loan_id.checked===true){ pj_seq_id.disabled=0; }else{ pj_seq_id.disabled=1; pj_seq_id.options[0].selected=1; } } // Edit ํŒŒ์ผ ์กฐํ•ฉ ์ฒดํฌ๋ฐ•์Šค ์ฒดํฌ ์‹œ function edit_jh_chk(){ var any_jh = document.getElementById('any_jh'); var is_jh = document.getElementById('is_jh'); // if(is_jh.checked===true){ any_jh.disabled=0; }else{ any_jh.disabled=1; any_jh.options[0].selected=1; } } // ์„œ๋ธŒ๋ฐ‹ ์ฒดํฌ function inout_frm_chk(com){ var form=document.inout_frm; if(!form.deal_date.value){ alert('๊ฑฐ๋ž˜์ผ์ž๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”!'); form.deal_date.focus(); return; } if(!form.class1_1.value&&!form.class1_2.value&&!form.class1_3.value&&!form.class1_4.value&&!form.class1_5.value&&!form.class1_6.value&&!form.class1_7.value&&!form.class1_8.value&&!form.class1_9.value&&!form.class1_10.value){ alert('ํ•˜๋‚˜ ์ด์ƒ์˜ ๊ฑฐ๋ž˜๋ฅผ ์ž…๋ ฅํ•˜์„ธ์š”!'); form.class1_1.focus(); return; } for(i=1; i<=10; i++){ // ์ด 10ํ–‰ ํ–‰์ˆ˜๋งŒํผ ๋ฐ˜๋ณต var d1_acc1 = "d1_acc1_"+i; // ์ž์‚ฐ ๊ณ„์ •๊ณผ๋ชฉ var d1_acc2 = "d1_acc2_"+i; // ๋ถ€์ฑ„ ๊ณ„์ •๊ณผ๋ชฉ var d1_acc3 = "d1_acc3_"+i; // ์ž๋ณธ ๊ณ„์ •๊ณผ๋ชฉ var d1_acc4 = "d1_acc4_"+i; // ์ˆ˜์ต ๊ณ„์ •๊ณผ๋ชฉ var d1_acc5 = "d1_acc5_"+i; // ๋น„์šฉ ๊ณ„์ •๊ณผ๋ชฉ var d1_acc1_id = document.getElementById(d1_acc1);////// ์ž์‚ฐ๊ณ„์ • FORM var d1_acc2_id = document.getElementById(d1_acc2); // ๋ถ€์ฑ„๊ณ„์ • FORM var d1_acc3_id = document.getElementById(d1_acc3); // ์ž๋ณธ๊ณ„์ • FORM var d1_acc4_id = document.getElementById(d1_acc4); // ์ˆ˜์ต๊ณ„์ • FORM var d1_acc5_id = document.getElementById(d1_acc5);////// ๋น„์šฉ๊ณ„์ • FORM if(eval('form.class1_'+i).value){ if(eval('form.class2_'+i).value=='7'){ if(!eval('form.pj_seq_'+i).value){ alert('์ „๋„๊ธˆ์„ ๋Œ€์ฒด(์ด์ฒด)ํ•  ํ˜„์žฅ์„ ์„ ํƒํ•˜์—ฌ ์ฃผ์‹ญ์‹œ์š”!'); eval('form.pj_seq_'+i).focus(); return; } } if(eval('form.jh_loan_'+i).checked===true){ // ์กฐํ•ฉ์—ฌ๋ถ€ ์ฒดํฌ๋ฐ•์Šค if(!eval('form.pj_seq_'+i).value){ // ์กฐํ•ฉํ˜„์žฅ ์„ ํƒ๋ชฉ๋ก alert('๋Œ€์—ฌ๊ธˆ์„ ์ง€๊ธ‰ํ•˜๋Š” ํ˜„์žฅ์„ ์„ ํƒํ•˜์„ธ์š”!'); eval('form.pj_seq_'+i).focus(); return; } } if(eval('form.class2_'+i).value<6){ if(!d1_acc1_id.value&&!d1_acc2_id.value&&!d1_acc3_id.value&&!d1_acc4_id.value&&!d1_acc5_id.value){ alert('๊ณ„์ •๊ณผ๋ชฉ์„ ์„ ํƒํ•˜์—ฌ ์ฃผ์‹ญ์‹œ์š”!'); return; } } if(!eval('form.cont_'+i).value){ alert('์ ์š” ํ•ญ๋ชฉ์„ ์ž…๋ ฅํ•˜์„ธ์š”!'); eval('form.cont_'+i).focus(); return; } if(eval('form.class1_'+i).value==1){ if(!eval('form.in_'+i).value){ alert('์ž…๊ธˆ ๊ณ„์ • ํ•ญ๋ชฉ์„ ์„ ํƒํ•˜์„ธ์š”!'); eval('form.in_'+i).focus(); return; } if(!eval('form.inc_'+i).value){ alert('์ž…๊ธˆ ๊ธˆ์•ก์„ ์ž…๋ ฅํ•˜์„ธ์š”!'); eval('form.inc_'+i).focus(); return; } } if(eval('form.class1_'+i).value==2){ if(!eval('form.out_'+i).value){ alert('์ถœ๊ธˆ ๊ณ„์ • ํ•ญ๋ชฉ์„ ์„ ํƒํ•˜์„ธ์š”!'); eval('form.out_'+i).focus(); return; } if(!eval('form.exp_'+i).value){ alert('์ถœ๊ธˆ ๊ธˆ์•ก์„ ์ž…๋ ฅํ•˜์„ธ์š”!'); eval('form.exp_'+i).focus(); return; } } if(eval('form.class1_'+i).value==3){ // ๋Œ€์ฒด๊ฑฐ๋ž˜์ธ ๊ฒฝ์šฐ if(!eval('form.in_'+i).value){ alert('์ž…๊ธˆ ๊ณ„์ • ํ•ญ๋ชฉ์„ ์„ ํƒํ•˜์„ธ์š”!'); eval('form.in_'+i).focus(); return; } if(!eval('form.inc_'+i).value){ alert('์ž…๊ธˆ ๊ธˆ์•ก์„ ์ž…๋ ฅํ•˜์„ธ์š”!'); eval('form.inc_'+i).focus(); return; } if(!eval('form.out_'+i).value){ alert('์ถœ๊ธˆ ๊ณ„์ • ํ•ญ๋ชฉ์„ ์„ ํƒํ•˜์„ธ์š”!'); eval('form.out_'+i).focus(); return; } var out_val = eval('form.out_'+i).value.split("-"); if(eval('form.in_'+i).value==out_val[0]){ alert('๋Œ€์ฒด ๊ฑฐ๋ž˜์ธ ๊ฒฝ์šฐ ์ž…๊ธˆ๊ณ„์ •๊ณผ ์ถœ๊ธˆ๊ณ„์ •์„ ๋‹ค๋ฅด๊ฒŒ ์„ ํƒํ•˜์—ฌ ์ฃผ์‹ญ์‹œ์š”!'); eval('form.out_'+i).focus(); return; } if(!eval('form.exp_'+i).value){ alert('์ถœ๊ธˆ ๊ธˆ์•ก์„ ์ž…๋ ฅํ•˜์„ธ์š”!'); eval('form.exp_'+i).focus(); return; } } } } var aaa=confirm('๊ฑฐ๋ž˜๋‚ด์šฉ์„ ๋“ฑ๋กํ•˜์‹œ๊ฒ ์Šต๋‹ˆ๊นŒ???'); if(aaa==true){ form.submit(); } } //// ํ˜„์žฅ ์„œ๋ธŒ๋ฐ‹ function pj_inout_frm_chk(){ var form=document.form1; if(!form.pj_list.value){ alert('ํ”„๋กœ์ ํŠธ๋ฅผ ์„ ํƒํ•˜์—ฌ ์ฃผ์‹ญ์‹œ์š”!'); form.pj_list.focus(); return; } inout_frm_chk(); } // ๋Œ€์ฒด์‹œ ์ฒดํฌ function transfer(frm1,frm2,frm3){ if(frm1.value==3) frm3.value=frm2.value; } // ์นดํ…Œ์ฒต ์œˆ๋„์˜คํ”ˆ function cate_chk(ref,name) { var window_left = (screen.width-640)/2; var window_top = (screen.height-480)/2; window.open(ref,name,'width=420,height=460,scrollbars=no,status=no,top=' + window_top + ',left=' + window_left + ''); } //์ˆ˜์ˆ˜๋ฃŒ ๊ด€๋ จ ์ฒดํฌ๋ฐ•์Šค ํ™œ์„ฑํ™” function charge(no,obj){ var form=document.inout_frm; var nobj = obj.split("-"); if(no==1){ if(nobj[0]<=1 || !obj){ form.char1_1.disabled=1; form.char2_1.disabled=1; form.char1_1.checked=0; form.char2_1.value=''; }else{ form.char1_1.disabled=0; } } if(no==2){ if(nobj[0]==1 || !obj){ form.char1_2.disabled=1; form.char2_2.disabled=1; form.char1_2.checked=0; form.char2_2.value=''; }else{ form.char1_2.disabled=0; } } if(no==3){ if(nobj[0]==1 || !obj){ form.char1_3.disabled=1; form.char2_3.disabled=1; form.char1_3.checked=0; form.char2_3.value=''; }else{ form.char1_3.disabled=0; } } if(no==4){ if(nobj[0]==1 || !obj){ form.char1_4.disabled=1; form.char2_4.disabled=1; form.char1_4.checked=0; form.char2_4.value=''; }else{ form.char1_4.disabled=0; } } if(no==5){ if(nobj[0]==1 || !obj){ form.char1_5.disabled=1; form.char2_5.disabled=1; form.char1_5.checked=0; form.char2_5.value=''; }else{ form.char1_5.disabled=0; } } if(no==6){ if(nobj[0]==1 || !obj){ form.char1_6.disabled=1; form.char2_6.disabled=1; form.char1_6.checked=0; form.char2_6.value=''; }else{ form.char1_6.disabled=0; } } if(no==7){ if(nobj[0]==1 || !obj){ form.char1_7.disabled=1; form.char2_7.disabled=1; form.char1_7.checked=0; form.char2_7.value=''; }else{ form.char1_7.disabled=0; } } if(no==8){ if(nobj[0]==1 || !obj){ form.char1_8.disabled=1; form.char2_8.disabled=1; form.char1_8.checked=0; form.char2_8.value=''; }else{ form.char1_8.disabled=0; } } if(no==9){ if(nobj[0]==1 || !obj){ form.char1_9.disabled=1; form.char2_9.disabled=1; form.char1_9.checked=0; form.char2_9.value=''; }else{ form.char1_9.disabled=0; } } if(no==10){ if(nobj[0]==1 || !obj){ form.char1_10.disabled=1; form.char2_10.disabled=1; form.char1_10.checked=0; form.char2_10.value=''; }else{ form.char1_10.disabled=0; } } } // ์ˆ˜์ˆ˜๋ฃŒ ์ฒดํฌ๋ฐ•์Šค function char2_chk(frm, no){ var form=document.inout_frm; if(frm.disabled==true) {frm.disabled=false; frm.value=500;}else{frm.disabled=true; frm.value="";} if(no==1){form.cont_1_h.value=form.cont_1.value;} if(no==2){form.cont_2_h.value=form.cont_2.value;} if(no==3){form.cont_3_h.value=form.cont_3.value;} if(no==4){form.cont_4_h.value=form.cont_4.value;} if(no==5){form.cont_5_h.value=form.cont_5.value;} if(no==6){form.cont_6_h.value=form.cont_6.value;} if(no==7){form.cont_7_h.value=form.cont_7.value;} if(no==8){form.cont_8_h.value=form.cont_8.value;} if(no==9){form.cont_9_h.value=form.cont_9.value;} if(no==10){form.cont_10_h.value=form.cont_10.value;} }
module.exports = ` <html> <head> <title>Show Me A Dog</title> <style>{{{css}}}</style> </head> <body> <h1>Here is your {{breed}}!</h1> <div><img src="{{image}}"></div> <div class="links"> <div class="link"><a href="javascript:window.location.reload(false);">Another?</a></div> <div class="link"><a href=".">Change breed?</a></div> </div> <div class="about"> <div>Coded by <a href="http://mattholland.info/">Matt Holland</a></div> <div>Powered by <a href="https://dog.ceo/">Dog CEO's</a> <a href="https://dog.ceo/dog-api/">Dog API</a> and the <a href="http://vision.stanford.edu/aditya86/ImageNetDogs/">Stanford Dogs Dataset</a></div> <div><a href="https://github.com/hollandmatt/show-me-a-dog">Source Code</a></div> </div> </body> </html> `;
import{a as e}from"./chunk-S4JGXK5I.js";function i(t,r){e(t,"beforebegin",r)}export{i as a}; //# sourceMappingURL=chunk-JNJ2L7JL.js.map