code
stringlengths
2
1.05M
/** * config is the configuration wrapper object of the app */ var config = { site : 'http://www.some.com', domains : { some : 'some.com' }, el : { productList : $('#product_list'), productTemplate : $('#productTemplate'), loader : $('#loader'), err : $("#err") }, imgPaths : { logo : '../../img/logo.png' }, urls : { favouriteProducts : 'http://127.0.0.1/ajax/favorite_products', fireabase : 'https://product-api.firebaseio.com' }, errors : { 400 : '400', 500 : '500', timeout : 'timeout' }, errorMessages : { serverConnectionFailed : 'Sunucuya bağlanılamıyor...',/*400*/ internalServerError : 'Sunucu taraflı bir hata oluştu...',/*500*/ timeout : 'Sayfa zaman aşımına uğradı. Lütfen tekrar deneyiniz...', unidentifiedError : 'Beklenmeyen bir hata oluştu. Lütfen tekrar deneyiniz.' }, stringBoundry : 16, stringExtension : '...', json : { shortDesc : 'short_description', name : 'name' } };
/*! * Usher * Copyright(c) 2014 meltmedia <mike@meltmedia.com> */ 'use strict'; var async = require('async'), winston = require('winston'), STATUS = require('./tasks/status'); module.exports = WorkflowExecution; function WorkflowExecution(tasks) { if (!(this instanceof WorkflowExecution)) { return new WorkflowExecution(tasks); } this.tasks = tasks; } WorkflowExecution.prototype.execute = function execute(context, done) { done = done || function () {}; async.eachSeries(this.tasks, function (task, next) { // Check to see if the task's dependencies have been resolved first if (!context.isResolved(task)) { var mask = STATUS.mask('pending'); context.setTaskStatus(task, mask); return next(null, { name: task.name, mask: mask }); } // Execute this task, updating the context for future tasks to utilize task.execute(context, function (mask) { winston.log('debug', 'Task %s completed with status: ', task.name, mask._value); // Update the status context.setTaskStatus(task, mask); next(null, { name: task.name, mask: mask }); }); }, function (err, results) { done(err, results); }); };
// Generated by CoffeeScript 1.6.3 var BackoffTimer, ConnectionRdy, ConnectionRdyState, EventEmitter, NSQDConnection, NodeState, READER_COUNT, ReaderRdy, RoundRobinList, StateChangeLogger, _, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; _ = require('underscore'); EventEmitter = require('events').EventEmitter; BackoffTimer = require('./backofftimer'); NodeState = require('node-state'); NSQDConnection = require('./nsqdconnection').NSQDConnection; RoundRobinList = require('./roundrobinlist'); StateChangeLogger = require('./logging'); /* Maintains the RDY and in-flight counts for a nsqd connection. ConnectionRdy ensures that the RDY count will not exceed the max set for this connection. The max for the connection can be adjusted at any time. Usage: connRdy = ConnectionRdy conn connRdy.setConnectionRdyMax 10 conn.on 'message', -> # On a successful message, bump up the RDY count for this connection. connRdy.raise 'bump' conn.on 'requeue', -> # We're backing off when we encounter a requeue. Wait 5 seconds to try # again. connRdy.raise 'backoff' setTimeout (-> connRdy.raise 'bump'), 5000 */ ConnectionRdy = (function(_super) { __extends(ConnectionRdy, _super); ConnectionRdy.READY = 'ready'; ConnectionRdy.STATE_CHANGE = 'statechange'; function ConnectionRdy(conn) { var _this = this; this.conn = conn; this.maxConnRdy = 0; this.inFlight = 0; this.lastRdySent = 0; this.availableRdy = 0; this.statemachine = new ConnectionRdyState(this); this.conn.on(NSQDConnection.ERROR, function(err) { return _this.log(err); }); this.conn.on(NSQDConnection.MESSAGE, function() { if (_this.idleId != null) { clearTimeout(_this.idleId); } _this.idleId = null; _this.inFlight += 1; return _this.availableRdy -= 1; }); this.conn.on(NSQDConnection.FINISHED, function() { return _this.inFlight -= 1; }); this.conn.on(NSQDConnection.REQUEUED, function() { return _this.inFlight -= 1; }); this.conn.on(NSQDConnection.READY, function() { return _this.start(); }); } ConnectionRdy.prototype.name = function() { return String(this.conn.conn.localPort); }; ConnectionRdy.prototype.start = function() { this.statemachine.start(); return this.emit(ConnectionRdy.READY); }; ConnectionRdy.prototype.setConnectionRdyMax = function(maxConnRdy) { this.log("setConnectionRdyMax " + maxConnRdy); this.maxConnRdy = Math.min(maxConnRdy, this.conn.maxRdyCount); return this.statemachine.raise('adjustMax'); }; ConnectionRdy.prototype.bump = function() { return this.statemachine.raise('bump'); }; ConnectionRdy.prototype.backoff = function() { return this.statemachine.raise('backoff'); }; ConnectionRdy.prototype.isStarved = function() { if (!(this.inFlight <= this.maxConnRdy)) { throw new Error('isStarved check is failing'); } return this.inFlight === this.lastRdySent; }; ConnectionRdy.prototype.setRdy = function(rdyCount) { this.log("RDY " + rdyCount); if (rdyCount < 0 || rdyCount > this.maxConnRdy) { return; } this.conn.setRdy(rdyCount); return this.availableRdy = this.lastRdySent = rdyCount; }; ConnectionRdy.prototype.log = function(message) { return StateChangeLogger.log('ConnectionRdy', this.statemachine.current_state_name, this.name(), message); }; return ConnectionRdy; })(EventEmitter); ConnectionRdyState = (function(_super) { __extends(ConnectionRdyState, _super); function ConnectionRdyState(connRdy) { this.connRdy = connRdy; ConnectionRdyState.__super__.constructor.call(this, { autostart: false, initial_state: 'INIT', sync_goto: true }); } ConnectionRdyState.prototype.log = function(message) { return this.connRdy.log(message); }; ConnectionRdyState.prototype.states = { INIT: { bump: function() { if (this.connRdy.maxConnRdy > 0) { return this.goto('MAX'); } }, backoff: function() {}, adjustMax: function() {} }, BACKOFF: { Enter: function() { return this.connRdy.setRdy(0); }, bump: function() { if (this.connRdy.maxConnRdy > 0) { return this.goto('ONE'); } }, backoff: function() {}, adjustMax: function() {} }, ONE: { Enter: function() { return this.connRdy.setRdy(1); }, bump: function() { return this.goto('MAX'); }, backoff: function() { return this.goto('BACKOFF'); }, adjustMax: function() {} }, MAX: { Enter: function() { return this.raise('bump'); }, bump: function() { if (this.connRdy.availableRdy <= this.connRdy.lastRdySent * 0.25) { return this.connRdy.setRdy(this.connRdy.maxConnRdy); } }, backoff: function() { return this.goto('BACKOFF'); }, adjustMax: function() { this.log("adjustMax RDY " + this.connRdy.maxConnRdy); return this.connRdy.setRdy(this.connRdy.maxConnRdy); } } }; ConnectionRdyState.prototype.transitions = { '*': { '*': function(data, callback) { this.log(''); callback(data); return this.connRdy.emit(ConnectionRdy.STATE_CHANGE); } } }; return ConnectionRdyState; })(NodeState); /* Usage: backoffTime = 90 heartbeat = 30 [topic, channel] = ['sample', 'default'] [host1, port1] = ['127.0.0.1', '4150'] c1 = new NSQDConnection host1, port1, topic, channel, backoffTime, heartbeat readerRdy = new ReaderRdy 1, 128 readerRdy.addConnection c1 message = (msg) -> console.log "Callback [message]: #{msg.attempts}, #{msg.body.toString()}" if msg.attempts >= 5 msg.finish() return if msg.body.toString() is 'requeue' msg.requeue() else msg.finish() discard = (msg) -> console.log "Giving up on this message: #{msg.id}" msg.finish() c1.on NSQDConnection.MESSAGE, message c1.connect() */ READER_COUNT = 0; ReaderRdy = (function(_super) { __extends(ReaderRdy, _super); ReaderRdy.getId = function() { READER_COUNT += 1; return READER_COUNT - 1; }; /* Parameters: - maxInFlight : Maximum number of messages in-flight across all connections. - maxBackoffDuration : The longest amount of time (secs) for a backoff event. - lowRdyTimeout : Time (secs) to rebalance RDY count among connections during low RDY conditions. */ function ReaderRdy(maxInFlight, maxBackoffDuration, lowRdyTimeout) { this.maxInFlight = maxInFlight; this.maxBackoffDuration = maxBackoffDuration; this.lowRdyTimeout = lowRdyTimeout != null ? lowRdyTimeout : 1.5; ReaderRdy.__super__.constructor.call(this, { autostart: true, initial_state: 'ZERO', sync_goto: true }); this.id = ReaderRdy.getId(); this.backoffTimer = new BackoffTimer(0, this.maxBackoffDuration); this.backoffId = null; this.balanceId = null; this.connections = []; this.roundRobinConnections = new RoundRobinList([]); } ReaderRdy.prototype.close = function() { clearTimeout(this.backoffId); return clearTimeout(this.balanceId); }; ReaderRdy.prototype.log = function(message) { return StateChangeLogger.log('ReaderRdy', this.current_state_name, this.id, message); }; ReaderRdy.prototype.isStarved = function() { var c; if (_.isEmpty(this.connections)) { return false; } return !_.isEmpty(((function() { var _i, _len, _ref, _results; if (c.isStarved()) { _ref = this.connections; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { c = _ref[_i]; _results.push(c); } return _results; } }).call(this))); }; ReaderRdy.prototype.createConnectionRdy = function(conn) { return new ConnectionRdy(conn); }; ReaderRdy.prototype.isLowRdy = function() { return this.maxInFlight < this.connections.length; }; ReaderRdy.prototype.addConnection = function(conn) { var connectionRdy, _this = this; connectionRdy = this.createConnectionRdy(conn); conn.on(NSQDConnection.CLOSED, function() { _this.removeConnection(connectionRdy); return _this.balance(); }); conn.on(NSQDConnection.FINISHED, function() { _this.backoffTimer.success(); if (_this.isLowRdy()) { _this.balance(); } else { connectionRdy.bump(); } return _this.raise('success'); }); conn.on(NSQDConnection.REQUEUED, function() { if (_this.current_state_name !== 'BACKOFF') { return connectionRdy.bump(); } }); conn.on(NSQDConnection.BACKOFF, function() { return _this.raise('backoff'); }); return connectionRdy.on(ConnectionRdy.READY, function() { var _ref; _this.connections.push(connectionRdy); _this.roundRobinConnections.add(connectionRdy); _this.balance(); if (_this.current_state_name === 'ZERO') { return _this.goto('MAX'); } else if ((_ref = _this.current_state_name) === 'TRY_ONE' || _ref === 'MAX') { return connectionRdy.bump(); } }); }; ReaderRdy.prototype.removeConnection = function(conn) { this.connections.splice(this.connections.indexOf(conn), 1); this.roundRobinConnections.remove(conn); if (this.connections.length === 0) { return this.goto('ZERO'); } }; ReaderRdy.prototype.bump = function() { var conn, _i, _len, _ref, _results; _ref = this.connections; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { conn = _ref[_i]; _results.push(conn.bump()); } return _results; }; ReaderRdy.prototype["try"] = function() { return this.balance(); }; ReaderRdy.prototype.backoff = function() { var conn, delay, onTimeout, _i, _len, _ref, _this = this; this.backoffTimer.failure(); _ref = this.connections; for (_i = 0, _len = _ref.length; _i < _len; _i++) { conn = _ref[_i]; conn.backoff(); } if (this.backoffId) { clearTimeout(this.backoffId); } onTimeout = function() { return _this.raise('try'); }; delay = new Number(this.backoffTimer.getInterval().valueOf()) * 1000; return this.backoffId = setTimeout(onTimeout, delay); }; ReaderRdy.prototype.inFlight = function() { var add; add = function(previous, conn) { return previous + conn.inFlight; }; return this.connections.reduce(add, 0); }; /* Evenly or fairly distributes RDY count based on the maxInFlight across all nsqd connections. */ ReaderRdy.prototype.balance = function() { /* In the perverse situation where there are more connections than max in flight, we do the following: There is a sliding window where each of the connections gets a RDY count of 1. When the connection has processed it's single message, then the RDY count is distributed to the next waiting connection. If the connection does nothing with it's RDY count, then it should timeout and give it's RDY count to another connection. */ var c, connMax, i, max, perConnectionMax, rdyRemainder, _i, _j, _k, _len, _len1, _ref, _ref1, _ref2, _results; StateChangeLogger.log('ReaderRdy', this.current_state_name, this.id, 'balance'); if (this.balanceId != null) { clearTimeout(this.balanceId); this.balanceId = null; } max = this.current_state_name === 'TRY_ONE' ? 1 : this.maxInFlight; perConnectionMax = Math.floor(max / this.connections.length); if (perConnectionMax === 0) { _ref = this.connections; for (_i = 0, _len = _ref.length; _i < _len; _i++) { c = _ref[_i]; c.backoff(); } _ref1 = this.roundRobinConnections.next(max - this.inFlight()); for (_j = 0, _len1 = _ref1.length; _j < _len1; _j++) { c = _ref1[_j]; c.setConnectionRdyMax(1); c.bump(); } return this.balanceId = setTimeout(this.balance.bind(this), this.lowRdyTimeout * 1000); } else { rdyRemainder = this.maxInFlight % this.connectionsLength; _results = []; for (i = _k = 0, _ref2 = this.connections.length; 0 <= _ref2 ? _k < _ref2 : _k > _ref2; i = 0 <= _ref2 ? ++_k : --_k) { connMax = perConnectionMax; if (rdyRemainder > 0) { connMax += 1; rdyRemainder -= 1; } this.connections[i].setConnectionRdyMax(connMax); _results.push(this.connections[i].bump()); } return _results; } }; /* The following events results in transitions in the ReaderRdy state machine: 1. Adding the first connection 2. Remove the last connections 3. Finish event from message handling 4. Backoff event from message handling 5. Backoff timeout */ ReaderRdy.prototype.states = { ZERO: { Enter: function() { if (this.backoffId) { return clearTimeout(this.backoffId); } }, backoff: function() {}, success: function() {}, "try": function() {} }, TRY_ONE: { Enter: function() { return this["try"](); }, backoff: function() { return this.goto('BACKOFF'); }, success: function() { return this.goto('MAX'); }, "try": function() {} }, MAX: { Enter: function() { return this.bump(); }, backoff: function() { return this.goto('BACKOFF'); }, success: function() {}, "try": function() {} }, BACKOFF: { Enter: function() { return this.backoff(); }, backoff: function() { return this.backoff(); }, success: function() {}, "try": function() { return this.goto('TRY_ONE'); } } }; ReaderRdy.prototype.transitions = { '*': { '*': function(data, callback) { this.log(''); return callback(data); } } }; return ReaderRdy; })(NodeState); module.exports = { ReaderRdy: ReaderRdy, ConnectionRdy: ConnectionRdy };
(function() { 'use strict'; b3e.nodes.RestartBehaviorTree = b3e.node.create('RestartBehaviorTree', b3e.MODULATOR, { group: 'behaviorTrees', properties: [ ['treeName', b3e.properties.String, {title: 'Tree name'}], ], }); })();
/** * Created by Wayne on 15/7/9. */ 'use strict'; zhuzhuqs.directive('zzplacehold', function() { return { restrict: 'A', require: 'ngModel', link: function(scope, element, attr, ctrl) { var value; var placehold = function () { element.val(attr.zzplacehold) }; var unplacehold = function () { element.val(''); }; scope.$watch(attr.ngModel, function (val) { value = val || ''; }); element.bind('focus', function () { if(value == '') unplacehold(); }); element.bind('blur', function () { if (element.val() == '') placehold(); }); ctrl.$formatters.unshift(function (val) { if (!val) { placehold(); value = ''; return attr.zzplacehold; } return val; }); } }; });
// Karma configuration // Generated on Wed May 13 2015 17:38:34 GMT-0400 (EDT) module.exports = function(config) { config.set({ basePath: '', browsers: ['Firefox', 'PhantomJS'], frameworks: ['mocha', 'requirejs'], files: [ 'node_modules/mocha/mocha.js', 'node_modules/mocha/mocha.css', 'node_modules/chai/chai.js', {pattern: 'bower_components/**/*.js', included: false}, {pattern: 'bower_components/**/*.css', included: false}, {pattern: 'lib/**/*.js', included: false}, {pattern: 'lib/**/*.spec.js', included: false}, 'test-main.js', 'test/app.js' ], exclude: [], preprocessors: {}, reporters: ['progress'], client: { mocha: { reporter: 'html' } }, port: 9876, colors: true, logLevel: config.LOG_INFO, autoWatch: true, singleRun: true }); };
worldlyPosition = { config: { topLongitude: 10000 , leftLatitude: 20000 , bottomLongitude: 14000 , rightLatitude: 26000 } , field: {} , calcVars: function () { var self = this // Measured from left to right self.field.width = self.config.rightLatitude - self.config.leftLatitude self.field.latitudeConversionRate = self.field.width / 100 // Measured from top to bottom self.field.height = self.config.bottomLongitude - self.config.topLongitude self.field.longitudeConversionRate = self.field.height / 100 } , longitudeToPercent: function (longitude) { var self = this self.calcVars() , relativeLongitude = longitude - self.config.topLongitude return relativeLongitude / self.field.longitudeConversionRate } , latitudeToPercent: function (latitude) { var self = this self.calcVars() , relativeLatitude = latitude - self.config.leftLatitude return relativeLatitude / self.field.latitudeConversionRate } } Template.registerHelper('longitudeToPercent', function (longitude) { return worldlyPosition.longitudeToPercent(longitude) }) Template.registerHelper('latitudeToPercent', function (latitude) { return worldlyPosition.latitudeToPercent(latitude) })
'use strict' const config = require('../config') const pkg = require('../../package.json') const winston = require('winston') require('winston-papertrail').Papertrail // eslint-disable-line no-unused-expressions function getPapertrail () { return process.env.NODE_ENV !== 'production' ? {} : new winston.transports.Papertrail({ host: config.papertrailHost, port: config.papertrailPort, hostname: config.papertrailHostName, logFormat: (level, message) => `${level.toUpperCase()} - ${message || ''}` }) } const winstonPapertrail = getPapertrail() const winstonConsole = new winston.transports.Console({ formatter: options => `${new Date().toUTCString()} - ${options.level.toUpperCase()} - ${(options.message ? options.message : '')}` }) const winstonTransports = process.env.NODE_ENV !== 'production' ? [winstonConsole] : [winstonConsole, winstonPapertrail] const logger = new (winston.Logger)({ transports: winstonTransports }) module.exports = (level, message) => { const data = Array.isArray(message) ? message : [message] const logMessage = `${pkg.name} - ${pkg.version}: ${data.join(' - ')}` return logger.log(level, logMessage) }
#!/usr/bin/env babel-node --harmony // import firequeue from 'firequeue' import firequeue from './src' import { concat, throughSync } from 'stream-util' import parallel from 'concurrent-transform' const queue = firequeue.init('https://firequeue-test.firebaseio.com') const logger = (fn) => throughSync(function(data) { console.log(fn(data)) this.push(data) }) // create some jobs // in a real application you might want to use push to generate random job id instead queue.incoming.child('job1').set({ task: 'task1', data: { name: 'job1' } }) queue.incoming.child('job2').set({ task: 'task1', data: { name: 'job2' } }) queue.incoming.child('job3').set({ task: 'task1', data: { name: 'job3' }, delayed: '20s' }) queue.incoming.child('job4').set({ task: 'task2', data: { name: 'job4' } }) queue.incoming.child('job5').set({ task: 'task3', data: { name: 'job5' } }) // listen to job updates queue.jobs .child('job1/state') .on('value', (s) => console.log(`job1 changed state to ${s.val()}`)) // log 'queued' // log 'activated' // log 'completed' // start queue engine queue .start() .pipe(logger(({ task, key, state }) => `task: ${task}, job: ${key}, state: ${state}`)) // log task: task1, job: job1, state: queued // log task: task1, job: job2, state: queued // log task: task1, job: job3, state: delayed // ... // process task1 const task1 = queue .read('task1') .pipe(queue.process((job) => { // do some work with job.key(), job.val() return Promise.resolve() })) .pipe(logger(({ task, key, state }) => `task: ${task}, job: ${key}, state: ${state}`)) // log task: task1, job: job1, state: completed // log task: task1, job: job2, state: completed // ... // process task2 with maxAttempts and backoff const task2 = queue .read('task2') .pipe(queue.maxAttempts(2)) .pipe(queue.backoff('2s')) // wait 2s before retrying .pipe(queue.process((job) => { console.log('do some work with', job.key(), job.val()) const attempts = job.child('attempts').val() || 0 return attempts < 2 ? Promise.reject() : Promise.resolve() })) // process task3 with a concurrency of 10 const task3 = queue .read('task3') .pipe(parallel(queue.process((job) => { console.log('do some work with', job.key(), job.val()) return Promise.resolve() }), 10)) // remove completed jobs concat(task1, task2, task3) .pipe(queue.clean('completed')) .pipe(logger(({ task, key, state }) => `task: ${task}, job: ${key}, state: ${state}`)) // log task: task1, job: job1, state: cleaned // log task: task1, job: job2, state: cleaned // ... // 30sec later... setTimeout(() => { queue.stop().then(() => { console.log('queue was stopped successfuly') }) }, 30000)
exports = module.exports; const request = require('request'); exports.answerJoke = function(sender, token) { let messageData = { "text":"Oh ho ho. My street name is \"the bot with the jokes\", FYI. Check out a few of them below." + " I love to share and make hoomans laugh!", "quick_replies":[ { "content_type":"text", "title":"joke1", "payload":"joke1" }, { "content_type":"text", "title":"joke2", "payload":"joke2" }, { "content_type":"text", "title":"joke3", "payload":"joke3" }, { "content_type":"text", "title":"joke4", "payload":"joke4" }, { "content_type":"text", "title":"back", "payload":"back" } ] } request({ url: 'https://graph.facebook.com/v2.6/me/messages', qs: {access_token:token}, method: 'POST', json: { messaging_type: "RESPONSE", recipient: {id:sender}, message: messageData, } }) } exports.answerJoke1 = function(sender, token) { let messageData = { "text":"What's Beethoven's favorite fruit?\nBA-NA-NA-NAAAAA!", "quick_replies":[ { "content_type":"text", "title":"joke2", "payload":"joke2" }, { "content_type":"text", "title":"joke3", "payload":"joke3" }, { "content_type":"text", "title":"joke4", "payload":"joke4" }, { "content_type":"text", "title":"back", "payload":"back" } ] } request({ url: 'https://graph.facebook.com/v2.6/me/messages', qs: {access_token:token}, method: 'POST', json: { messaging_type: "RESPONSE", recipient: {id:sender}, message: messageData, } }) } exports.answerJoke2 = function(sender, token) { let messageData = { "text":"Why was the musician arrested?\nHe was in TREBLE!", "quick_replies":[ { "content_type":"text", "title":"joke1", "payload":"joke1" }, { "content_type":"text", "title":"joke3", "payload":"joke3" }, { "content_type":"text", "title":"joke4", "payload":"joke4" }, { "content_type":"text", "title":"back", "payload":"back" } ] } request({ url: 'https://graph.facebook.com/v2.6/me/messages', qs: {access_token:token}, method: 'POST', json: { messaging_type: "RESPONSE", recipient: {id:sender}, message: messageData, } }) } exports.answerJoke3 = function(sender, token) { let messageData = { "text":"Why did Mozart kill his chickens?\nBecause they went BACH BACH BACH!", "quick_replies":[ { "content_type":"text", "title":"joke1", "payload":"joke1" }, { "content_type":"text", "title":"joke2", "payload":"joke2" }, { "content_type":"text", "title":"joke4", "payload":"joke4" }, { "content_type":"text", "title":"back", "payload":"back" } ] } request({ url: 'https://graph.facebook.com/v2.6/me/messages', qs: {access_token:token}, method: 'POST', json: { messaging_type: "RESPONSE", recipient: {id:sender}, message: messageData, } }) } exports.answerJoke4 = function(sender, token) { let messageData = { "text":"Why shouldn't you let your kids watch symphonies on the television?\nBecause there's too much VIOLINS and SAX on TV!", "quick_replies":[ { "content_type":"text", "title":"joke1", "payload":"joke1" }, { "content_type":"text", "title":"joke2", "payload":"joke2" }, { "content_type":"text", "title":"joke3", "payload":"joke3" }, { "content_type":"text", "title":"back", "payload":"back" } ] } request({ url: 'https://graph.facebook.com/v2.6/me/messages', qs: {access_token:token}, method: 'POST', json: { messaging_type: "RESPONSE", recipient: {id:sender}, message: messageData, } }) }
const nconf = require('nconf'); nconf.argv() .env() .file({ file: './config.json' }); const task = require('./task'); const context = { data: { DOMAINS: nconf.get('DOMAINS'), DAYS_THRESHOLD: nconf.get('DAYS_THRESHOLD'), SLACK_INCOMING_WEBHOOK_URL: nconf.get('SLACK_INCOMING_WEBHOOK_URL') } }; task(context, (err) => { if (err) { console.log(JSON.stringify(err, null, 2)); return process.exit(1); } });
'use strict' let models class BlocksController { constructor (projectModels) { models = projectModels } async create (req, res) { models.Blocks.create({ block: req.body.block }) .then((block) => { res.json({ error: false, id: block.id }) }) .catch((err) => { res.json({ error: true, message: err }) }) } get (req, res) { models.Blocks.findById(req.params.id) .then((block) => { if (block === null) { res.json({ error: true, message: `Block ${req.params.id} not found`, }) } else { res.json({ error: false, block, }) } }) .catch((err) => { res.json({ error: true, message: err, }) }) } listAll (req, res) { models.Blocks.findAll({}) .then((blocks) => { if(blocks.length === 0) { res.json({ error: true, message: "No blocks were found" }) }else { res.json({ error: false, blocks }) } }) .catch((err) => { res.json({ error: true, message: err }) }) } update (req, res) { models.Blocks.findById(req.params.id) .then((block) => { if (block === null) { res.json({ error: true, message: `Block ${req.params.id} not found`, }) } else { const block = req.body.block block.block = block !== undefined ? block : block.block block.save() .then((block) => { res.json({ error: false, block, }) }) } }) .catch((err) => { res.json({ error: true, message: err, }) }) } } module.exports = BlocksController
export { default } from './poop'
'use strict'; var EventDispatcher = createjs.EventDispatcher , EaselEvent = createjs.Event; var controls = { 37: 'moveleft', 39: 'moveright', 38: 'moveup', 40: 'movedown', 32: 'fire1' }; var currentActions = {}; var actionService = module.exports = { init: actions_init, get: actions_get } var stage; function actions_init(win, stage2) { stage = stage2; EventDispatcher.initialize(actionService); win.addEventListener('keydown', onKeyDown); win.addEventListener('keyup', onKeyUp); win.addEventListener('mousemove', onMouseMove); } function actions_get() { return currentActions; } function onKeyDown(event) { var keyEvent = processEvent(event, 'down'); if (keyEvent) currentActions[keyEvent.type] = keyEvent.data; } function onKeyUp(event) { var keyEvent = processEvent(event, 'up'); if (keyEvent) delete currentActions[keyEvent.type]; } function onMouseMove(event) { var canvasEl = stage && stage.canvas; if (!canvasEl) return; // May need to be more complex depending var canvasXPos = canvasEl.offsetLeft; var canvasYPos = canvasEl.offsetTop; currentActions.mouse = { winX: event.clientX, winY: event.clientY, stageX: event.clientX - canvasXPos, stageY: event.clientY - canvasYPos, target: event.target }; } function processEvent(event, phase) { var generalEvent = prepareEvent(event, phase, 'key'); if (!generalEvent) return; var specificEvent = prepareEvent(event, phase); actionService.dispatchEvent(generalEvent); actionService.dispatchEvent(specificEvent); return specificEvent; } function prepareEvent(event, phase, type) { var actionName = controls[event.keyCode]; if (!actionName) return; type = type || actionName; var eventData = { name: actionName, shiftKey: event.shiftKey, metaKey: event.metaKey, altKey: event.altKey, ctrlKey: event.ctrlKey, phase: phase }; var keyEvent = new EaselEvent(type); keyEvent.data = eventData; keyEvent.nativeEvent = event; return keyEvent; }
/** * Represents a student's response */ var StudentResponse = function (question, answeredCorrectly, abilityLevel) { 'use strict'; // TODO: Add some checking and error handling here. // TODO: Possibly add a few more methods. //console.log(question); //console.log(answeredCorrectly); //console.log(abilityLevel); // The question that was asked. this.question = question; // Was the question properly answered? this.answeredCorrectly = answeredCorrectly; // The student's ability at the time it was answered. this.abilityLevel = abilityLevel; }; module.exports = StudentResponse;
var ebayTradingAPI = require('../index'); console.log(ebayTradingAPI.getUserToken()); ebayTradingAPI.setUserToken("adfsafdsaf"); console.log(ebayTradingAPI.getUserToken()); var config = require('./config.json'); ebayTradingAPI.setUserToken(config.eBayAuthToken); console.log(ebayTradingAPI.getUserToken()); ebayTradingAPI.call( "GetItem", { "ItemID" : 251636383648 }, function(result){ console.log(result); } );
import axios from 'axios'; import {Pet, PetList} from '../types/Pet'; /** * @class PetService */ class PetService { /** * Get all pets the user has access to * @return {Promise<Array<Pet>>} A promise that unwraps to an array of pets */ getAll() { return axios.get('/pets') .then(({data}) => new PetList(data)) .catch(e => { console.error(e); throw e; }); } /** * [createPet description] * @param {[type]} pet [description] * @return {[type]} [description] */ createPet(pet) { return axios.post('/pets', pet) .then(({data}) => new Pet(data)); } getPet(id) { return axios.get(`/pets/${id}`) .then(({data}) => new Pet(data)); } deletePet(id) { return axios.delete(`/pets/${id}`); } } export default new PetService();
var underscore = require('./underscore.js'); var _executeBound = require('./_executeBound.js'); var restArguments = require('./restArguments.js'); // Partially apply a function by creating a version that has had some of its // arguments pre-filled, without changing its dynamic `this` context. `_` acts // as a placeholder by default, allowing any combination of arguments to be // pre-filled. Set `_.partial.placeholder` for a custom placeholder argument. var partial = restArguments(function(func, boundArgs) { var placeholder = partial.placeholder; var bound = function() { var position = 0, length = boundArgs.length; var args = Array(length); for (var i = 0; i < length; i++) { args[i] = boundArgs[i] === placeholder ? arguments[position++] : boundArgs[i]; } while (position < arguments.length) args.push(arguments[position++]); return _executeBound(func, bound, this, this, args); }; return bound; }); partial.placeholder = underscore; module.exports = partial;
/** * Renders graph with text symbols. Even though name says ASCII it supports * unicode as well. * * @example * var asciiGraphics = require('ngraph.ascii').graphics(graph); * asciiGraphics.run(); // this will render graph with '*' symbols * * @param {ngraph.graph} graph - graph object to be rendered */ module.exports.graphics = require('./lib/graphics'); /** * This primary serves as a mock for terminal, to test this package. But * You can also use it if you want to graph as a text to somewhere else * See `./lib/arrayScreen` for detailed information */ module.exports.arrayScreen = require('./lib/arrayScreen');
/* * ToNumber() (E5 Section 9.3). * * Postfix increment changes its LHS, put returns ToNumber(oldValue) as the * expression value. Use this get ToNumber() indirectly. */ function tonumber(x) { var tmp = x; return tmp++; } function zeroSign(x) { if (x !== 0) { return 'nz'; } if (1 / x > 0) { return 'pos'; } else { return 'neg'; } } function test(x) { var num = tonumber(x); print(num, zeroSign(num)); } /*=== NaN nz 0 pos 1 nz 0 pos -1 nz 0 neg 0 pos 1 nz NaN nz Infinity nz -Infinity nz ===*/ test(undefined); test(null); test(true); test(false); test(-1); test(-0); test(+0); test(1); test(NaN); test(Number.POSITIVE_INFINITY); test(Number.NEGATIVE_INFINITY); /*=== -1 nz -1 nz 0 neg 0 pos 0 pos 1 nz 17 nz 19 nz -Infinity nz Infinity nz Infinity nz 3735928559 nz 3735928559 nz 3735928559 nz NaN nz ===*/ /* String to number */ test('-1'); test(' -1 '); // whitespace is trimmed test('-0'); test('+0'); test('0'); test('1'); test('000017'); // lead zeroes allowed, not interpreted as octal! test('000019'); test(' -Infinity'); test(' +Infinity'); test(' Infinity'); test('0xdeadbeef'); test('0Xdeadbeef'); test(' \n0xdeadbeef\n'); test(' \n0xdeadbeefg\n'); // trailing garbage not allowed -> NaN /*=== 83 nz 83 nz 83 nz 83 nz NaN nz 17 nz 17 nz 17 nz 17 nz NaN nz ===*/ /* In ES6 0o123, and 0b10001 are recognized. Whitespace is also allowed. * Note that whitespace is trimmed so these forms cannot be recognized * by just peeking at the first few characters. */ test('0o123'); test('0O123'); test('\n0o123 \t'); test('\n0o000000123 \t'); test('\n0o000000123 x\t'); test('0b10001'); test('0B10001'); test('\t0b10001 \r\n'); test('\t0b0000010001 \r\n'); test('\t0b00000000000100012 \r\n'); // '2' is garbage to binary /* XXX: object coercion */
module.exports = function (string) { return string.charAt(0).toUpperCase() + string.slice(1); }
/* eslint no-unused-expressions:0 */ import { createElement } from 'react'; import ReactDOM from 'react-dom'; import CheckboxGroup from './index'; import { $, $$, conformanceChecker } from '../boundless-utils-test-helpers/index'; import sinon from 'sinon'; describe('CheckboxGroup component', () => { const mountNode = document.body.appendChild(document.createElement('div')); const render = (vdom) => ReactDOM.render(vdom, mountNode); const sandbox = sinon.sandbox.create(); const items = [ { inputProps: { name: 'gender-male', checked: false, }, label: 'Male', }, { inputProps: { name: 'gender-female', checked: false, }, label: 'Female', }, { inputProps: { name: 'gender-other', checked: false, }, label: 'Other', } ]; const checkedItems = items.map((item) => { return { ...item, inputProps: { ...item.inputProps, checked: true } }; }); const mixedItems = items.map((item, index) => { return { ...item, inputProps: { ...item.inputProps, checked: !!(index % 2) } }; }); afterEach(() => { ReactDOM.unmountComponentAtNode(mountNode); sandbox.restore(); }); it('conforms to the Boundless prop interface standards', () => conformanceChecker(render, CheckboxGroup)); it('accepts an alternate wrapper HTML element type', () => { render(<CheckboxGroup component='section' items={items} />); expect($('section.b-checkbox-group')).not.toBeNull(); }); it('accepts an array of properly structured items', () => { render(<CheckboxGroup items={items} />); expect($$('.b-checkbox-wrapper:not(.b-checkbox-group-all) .b-checkbox').length).toBe(items.length); }); it('accepts arbitrary React-supported HTML attributes via prop.selectAllProps', () => { render(<CheckboxGroup selectAllProps={{ 'data-id': 'foo' }} />); expect($('.b-checkbox-group-all[data-id="foo"]')).not.toBeNull(); }); describe('"select all" checkbox', () => { it('will not render if `selectAll` is `CheckboxGroup.selectAll.NONE`', () => { render(<CheckboxGroup items={items} selectAll={CheckboxGroup.selectAll.NONE} />); expect($('.b-checkbox-group-all')).toBeNull(); }); it('renders as the first child if `selectAll` is `CheckboxGroup.selectAll.BEFORE`', () => { render(<CheckboxGroup items={items} selectAll={CheckboxGroup.selectAll.BEFORE} />); expect($('.b-checkbox-group > *:first-child')).toBe($('.b-checkbox-group-all')); }); it('renders in the last position if `selectAll` is `CheckboxGroup.selectAll.AFTER`', () => { render(<CheckboxGroup items={items} selectAll={CheckboxGroup.selectAll.AFTER} />); expect($('.b-checkbox-group > *:last-child')).toBe($('.b-checkbox-group-all')); }); it('accepts a name passed by `selectAllProps.className`', () => { render(<CheckboxGroup items={items} selectAllProps={{ className: 'foo' }} />); expect($('.b-checkbox-group-all.foo')).not.toBeNull(); }); it('accepts a name passed by `selectAllProps.inputProps.name`', () => { render(<CheckboxGroup items={items} selectAllProps={{ inputProps: { name: 'foo' } }} />); expect($('.b-checkbox-group-all .b-checkbox[name="foo"]')).not.toBeNull(); }); it('checks all children', () => { const stub = sandbox.stub(); render(<CheckboxGroup items={items} onAllChecked={stub} />); $('.b-checkbox-group-all .b-checkbox-unchecked').click(); expect(stub.calledOnce).toBe(true); }); it('unchecks all children', () => { const stub = sandbox.stub(); render(<CheckboxGroup items={checkedItems} onAllUnchecked={stub} />); $('.b-checkbox-group-all .b-checkbox-checked').click(); expect(stub.calledOnce).toBe(true); }); it('is indeterminate if children are in different checked states', () => { render(<CheckboxGroup items={mixedItems} />); expect($('.b-checkbox-group-all .b-checkbox-mixed')).not.toBeNull(); }); it('makes all children checked if clicked in indeterminate state', () => { const stub = sandbox.stub(); render(<CheckboxGroup items={mixedItems} onAllChecked={stub} />); $('.b-checkbox-group-all .b-checkbox-mixed').click(); expect(stub.calledOnce).toBe(true); }); it('renders a custom label if given', () => { render(<CheckboxGroup items={mixedItems} selectAllProps={{ label: 'foo' }} />); expect($('.b-checkbox-group-all .b-checkbox-label')).not.toBeNull(); expect($('.b-checkbox-group-all .b-checkbox-label').textContent).toBe('foo'); }); }); });
// ==UserScript== // @name RPH Tools // @namespace https://openuserjs.org/scripts/shuffyiosys/RPH_Tools // @version 2.3.4e // @description Adds extended settings to RPH // @match http://chat.rphaven.com/ // @copyright (c)2014 shuffyiosys@github // @grant none // @license MIT license (https://en.wikipedia.org/wiki/MIT_License) // ==/UserScript== /*jshint multistr: true */ /*jshint bitwise: false*/ /*global $:false */ var RPHT_AUTO_JOIN = 1; var RPHT_PING_BOLD = 2; var RPHT_PING_ITALICS = 4; var RPHT_PING_EXACT_MATCH = 8; var RPHT_PING_CASE_SENSE = 16; var RPHT_NO_PM_ICONS = 32; var RPHT_SHOW_NAMES = 64; var RPHT_NO_ROOM_ICONS = 128; var RPHT_CLEANUP_RECONNECT = 256; var RPHT_DIE_MIN = 1; var RPHT_DIE_MAX = 10; var RPHT_DIE_SIDE_MIN = 2; var RPHT_DIE_SIDE_MAX = 100; var RPHT_RNG_NUM_MIN = -4294967296; var RPHT_RNG_NUM_MAX = 4294967296; /***************************************************************************** * Variables for persistent storage /***************************************************************************/ /**************************************************************************** Array that holds all of the user name settings. The settings itself are stored in a JSON object. "pings": Names/Words/etc. to use for pinging "ping_url": URL to the audio source for pinging "color": Text color to use when a match is found "highlight": background color to use when a match is found "flags": Bitmask of option flags. 0 - Settings have been modified 1 - Bold text 2 - Italicize text 3 - Use exact matching 4 - Case sensitive matching 5 - Remove room links in chat. 6 - Show names in chat tabs and textbox 7 - Remove icons in chat *****************************************************************************/ var scriptSettings = { "pings" : "", "ping_url" : "http://chat.rphaven.com/sounds/boop.mp3", "color" : "#000", "highlight" : "#FFA", "flags" : 0, "pmPingUrl" : "http://chat.rphaven.com/sounds/imsound.mp3", "favRooms" : [], }; var blockedUsers = []; /* Object for dialog box */ var settingsDialog = {}; var validSettings = true; var settingsChanged = false; var pingSound = null; var awayMessages = {}; var roomNamePairs = {}; var startupTimer = null; var versString = 'RPH Tools 2.3.4e'; var html = '<style>' + '.rpht_headers{cursor: pointer; padding-left: 5px; background: #43698D; width: 99%; border-radius: 3px; color:#FFF;}' + '.rpht_textarea{background: rgb(255, 255, 255); height: 80px; width: 403px;}' + '.rpht-block {text-align: right; margin-top: 10px;}' + '.rpht-block label { display: inline-block; font-size: 1em; margin-right: 10px; }' + '.rpht-block input[type=checkbox] { width: 14px; margin-right: 286px;}' + '</style>' + '<div id="settingsBox" style="display: none; position: absolute; top: 35px; z-index: 9999999; height: 500px; width: 450px; border-radius: 10px; box-shadow: 0px 2px 5px rgba(0, 0, 0, 0.7); right: 85px; background: url(&quot;http://www.rphaven.com/css/img/aero-bg.png&quot;) repeat scroll 0px 0px transparent; padding: 5px;" left="">' + '<h3 style="text-align: center; color:#000;">RPH Tools</h3>' + '<div id="settingsContainer" style="height: 470px; width: 100%; overflow: auto; background: rgb(51, 51, 51); padding: 10px; border-radius: 5px; font-size: 0.8em;">' + '<h3 class="rpht_headers" id="chatSettingsHeader">Chat room</h3>' + /* Chat Settings */ '<div id="chatSettingsForm" style="display:none;">' + '<p style="border-bottom: 2px solid #EEE;">' + '<span style="background: #333; position: relative; top: 0.7em;"><strong>User text color</strong>&nbsp;</span>' + '</p>' + '<div class="rpht-block"><label>Username:</label><select style="width: 300px;" id="userColorDroplist"></select></div>'+ '<div class="rpht-block"><label>Text color:</label><input style="width: 300px;" type="text" id="userNameTextColor" name="userNameTextColor" value="#111"></div>' + '<div class="rpht-block"><button type="button" id="userNameTextColorButton">Set color</button></div>' + '<p style="border-bottom: 2px solid #EEE;">' + '<span style="background: #333; position: relative; top: 0.7em;"><strong>Pings</strong>&nbsp;</span>' + '</p><br />' + '<p>Names to be pinged (comma separated)</p>' + '<textarea id="pingNames" class="rpht_textarea" name="pingNames"> </textarea>' + '<br /><br />' + '<div class="rpht-block"><label>Ping URL: </label><input style="width: 370px;" type="text" id="pingURL" name="pingURL"></div>' + '<div class="rpht-block"><label>Text Color: </label><input style="width: 370px;" type="text" id="pingTextColor" name="pingTextColor" value="#000"></div>' + '<div class="rpht-block"><label>Highlight: </label><input style="width: 370px;" type="text" id="pingHighlightColor" name="pingHighlightColor" value="#FFA"></div>' + '<br>' + '<p>Matching options</p> <br/>' + '<input style="width: 40px;" type="checkbox" id="pingBoldEnable" name="pingBoldEnable"><strong>Bold</strong>' + '<input style="width: 40px;" type="checkbox" id="pingItalicsEnable" name="pingItalicsEnable"><em>Italics</em>' + '<input style="width: 40px;" type="checkbox" id="pingExactMatch" name="pingExactMatch">Exact match' + '<input style="width: 40px;" type="checkbox" id="pingCaseSense" name="pingCaseSense">Case sensitive' + '<br /><br />' + '<p style="border-bottom: 2px solid #EEE;">' + '<span style="background: #333; position: relative; top: 0.7em;"><strong>Auto Join Favorite Rooms</strong>&nbsp; </span>' + '</p>' + '<div class="rpht-block"><label>Enable Auto Join: </label><input type="checkbox" id="favEnable" name="favEnable"></div>' + '<div class="rpht-block"><label>Username: </label><select style="width: 300px;" id="favUserList"></select></div>'+ '<div class="rpht-block"><label>Room: </label><input style="width: 370px;" type="text" id="favRoom" name="favRoom"></div>' + '<div class="rpht-block"><label>Password: </label><input style="width: 370px;" type="text" id="favRoomPw" name="favRoomPw"></div>' + '<div class="rpht-block"><button type="button" id="favAdd">Add</button></div>'+ '<p>Favorite rooms</p>' + '<select style="width: 403px;" id="favRoomsList" size="5"></select><br><br>' + '<div class="rpht-block"><button type="button" id="favRemove">Remove</button></div>'+ '<br>' + '<p style="border-bottom: 2px solid #EEE;">' + '<span style="background: #333; position: relative; top: 0.7em;"><strong>Other Settings</strong>&nbsp; </span>' + '</p><br />' + '<div class="rpht-block"><label>Chat history: </label><input style="width: 300px;" type="number" id="chatHistory" name="chatHistory" max="65535" min="10" value="300"><br /><br /></div>' + '<div class="rpht-block"><label>No image icons in chat</label><input style="margin-right: 10px;" type="checkbox" id="imgIconDisable" name="imgIconDisable"></div>' + '<div class="rpht-block"><label>Show username in tabs & textbox (requires rejoin)</label><input style="margin-right: 10px;" type="checkbox" id="showUsername" name="showUsername"></div>' + /*'<div class="rpht-block"><label>Cleanup on reconnect</label><input style="margin-right: 10px;" type="checkbox" id="cleanupOnReconnect" name="cleanupOnReconnect"></div>' +*/ '</div>' + '<br />' + /* PM Settings */ '<h3 class="rpht_headers" id="pmSettingsHeader">PM</h3>' + '<div id="pmSettingsForm" style="display:none;">'+ '<p style="border-bottom: 2px solid #EEE;">' + '<span style="background: #333; position: relative; top: 0.7em;"><strong>PM Away System</strong>&nbsp; </span>' + '</p><br />' + '<p>Username</p>' + '<select style="width: 403px;" id="pmNamesDroplist" size="5"></select><br><br>' + '<div class="rpht-block"><label>Away Message: </label><input style="width: 300px;" type="text" id="awayMessageTextbox" name="awayMessageTextbox" maxlength="300" placeholder="Away message..."></div>' + '<div class="rpht-block"><button type="button" id="setAwayButton">Enable</button> <button type="button" id="removeAwayButton">Disable</button></div>' + '<br /><br />' + '<p style="border-bottom: 2px solid #EEE;">' + '<span style="background: #333; position: relative; top: 0.7em;"><strong>Other Settings</strong>&nbsp; </span>' + '</p><br />' + '<div class="rpht-block"><label>PM Sound: </label><input style="width: 300px;" type="text" id="pmPingURL" name="pmPingURL"></div><br />' + '<div class="rpht-block"><label>Mute PMs: </label><input type="checkbox" id="pmMute" name="pmMute"></div><br />' + '<div class="rpht-block"><label>No Image Icons: </label><input type="checkbox" id="pmIconsDisable" name="pmIconsDisable"></div>' + '</div>' + '<br />' + /* RNG */ '<h3 class="rpht_headers" id="rngHeader">Random Number Generators</h3>' + '<div id="rngForm" style="display:none;">' + '<p style="border-bottom: 2px solid #EEE;">' + '<span style="background: #333; position: relative; top: 0.7em;"><strong>Type</strong>&nbsp;</span>' + '</p> <br />' + '<form>' + '<input style="width: 50px;" type="radio" name="rng" value="coin" id="coinRadio"> Coin tosser' + '<input style="width: 50px;" type="radio" name="rng" value="dice" id="diceRadio" checked> Dice roller' + '<input style="width: 50px;" type="radio" name="rng" value="rng" id="rngRadio"> General RNG' + '</form>' + '<p style="border-bottom: 2px solid #EEE;">' + '<span style="background: #333; position: relative; top: 0.7em;"><strong>Options</strong>&nbsp;</span>' + '</p> <br />' + '<div id="diceOptions">' + '<div class="rpht-block"><label>Number of die </label><input style="width: 300px;" type="number" id="diceNum" name="diceNum" max="10" min="1" value="2"></div>'+ '<div class="rpht-block"><label>Sides </label><input style="width: 300px;" type="number" id="diceSides" name="diceSides" max="100" min="2" value="6"></div>'+ '<div class="rpht-block"><label>Show Totals:</label><input type="checkbox" id="showRollTotals" name="showRollTotals"></div>' + '</div>' + '<div id="rngOptions" style="display: none;">' + '<div class="rpht-block"><label>Minimum: </label><input style="width: 300px;" type="number" id="rngMinNumber" name="rngMinNumber" max="4294967295" min="-4294967296" value="0"></div>' + '<div class="rpht-block"><label>Maximum: </label><input style="width: 300px;" type="number" id="rngMaxNumber" name="rngMaxNumber" max="4294967295" min="-4294967296" value="10"></div>' + '</div>' + '<div class="rpht-block"><button type="button" id="rngButton">Let\'s roll!</button></div>' + '</div>' + '<br />' + '<h3 class="rpht_headers" id="blockHeader">Blocking</h3>' + '<div id="blockForm" style="display:none;">' + '<p style="border-bottom: 2px solid #EEE;">' + '<span style="background: #333; position: relative; top: 0.7em;"><strong>Block</strong>&nbsp;</span>' + '</p>' + '<div class="rpht-block"><label>User:</label><input style="width: 400px;" type="text" id="nameCheckTextbox" name="nameCheckTextbox" placeholder="User to block"></div>' + '<div class="rpht-block"><button style="margin-left: 357px;" type="button" id="blockButton">Block</button></div></ br>' + '<br />' + '<p>Blocked users</p>' + '<select style="width: 100%;" size="5" id="blockedDropList"></select>' + '<div class="rpht-block"><button style="margin-left: 341px;" type="button" id="unblockButton">Unblock</button></div>' + '</div>' + '<br />' + /* Modding */ '<h3 class="rpht_headers" id="moddingHeader">Modding</h3>' + '<div id="moddingForm" style="display:none;">' + '<p style="border-bottom: 2px solid #EEE;">' + '<span style="background: #333; position: relative; top: 0.7em;"><strong>Mod Commands</strong>&nbsp;</span>' + '</p><br />' + '<p>This will only work if you\'re actually a mod and you own the user name.</p>' + '<br />' + '<div class="rpht-block"><label>Room-Name pair</label> <select style="width: 300px;" id="roomModSelect">' + '<option value=""></option>' + '</select></div>' + '<div class="rpht-block"><label>Room:</label><input style="width: 300px;" type="text" id="modRoomTextInput" placeholder="Room"></div>' + '<div class="rpht-block"><label>Mod name:</label><input style="width: 300px;" type="text" id="modFromTextInput" placeholder="Your mod name"></div>' + '<div class="rpht-block"><label>Message:</label><input style="width: 300px;" type="text" id="modMessageTextInput" placeholder="Message"></div>' + '<br/><br/>' + '<p>Perform action on these users (semicolon separated with no space between): </p>' + '<textarea name="modTargetTextInput" id="modTargetTextInput" class="rpht_textarea"></textarea>' + '<br />' + '<div class="rpht-block">' + '<button type="button" id="resetPassword">Reset PW</button>' + '<button style="margin-left: 30px;" type="button" id="kickButton">Kick</button>' + '<button style="margin-left: 30px;" type="button" id="banButton">Ban</button>' + '<button style="margin-left: 6px;" type="button" id="unbanButton">Unban</button>' + '<button style="margin-left: 30px;" type="button" id="modButton">Mod</button>' + '<button style="margin-left: 6px;" type="button" id="unmodButton">Unmod</button></div>' + '</div>' + '<br />' + /* Script settings */ '<h3 class="rpht_headers" id="importExportHeader">Script Settings</h3>' + '<div id="importExportForm" style="display:none;">' + '<br />' + '<p>Press "Export" to export savable settings.</p>' + '<p>To import settings, paste them into the text box and press "Import".</p><br />' + '<textarea name="importExportText" id="importExportTextarea" class="rpht_textarea" ></textarea>' + '<div class="rpht-block">' + '<button style="float: left;" type="button" id="exportButton">Export</button>' + '<button style="float: right;"type="button" id="importButton">Import</button>' + '</div>' + '<br />' + '<p style="border-bottom: 2px solid #EEE;">' + '<span style="background: #333; position: relative; top: 0.7em;"></span>' + '</p><br />' + /*'<button type="button" id="printSettingsButton">Print settings</button> (open console to see settings) <br /><br />' +*/ '<button type="button" id="deleteSettingsButton">Delete settings</button>' + '<br /><br/>' + '</div>' + '<br />' + /* About */ '<h3 class="rpht_headers" id="aboutHeader">About</h3>' + '<div id="aboutHelpForm" style="display:none;">' + '<br><p>Click on the "Settings" button again to save your settings!</p>' + '<p>You may need to refresh the chat for the settings to take effect.</p>' + '<br><p><a href="http://www.rphaven.com/topics.php?id=1#topic=1883&page=1" target="_blank">Report a problem</a> |' + '<a href="https://openuserjs.org/scripts/shuffyiosys/RPH_Tools#troubleshooting" target=_blank">Troubleshooting Tips</a> | '+ versString +'</p><br>' + '<br>' + '</div>' + '<br />' + '</div>' + '</div>'; var rpht_css = '<style>' + '.rpht_chat_tab {' + 'position: absolute;' + 'bottom: 40px;' + 'height: 40px;' + 'overflow-x: auto;' + 'overflow-y: hidden;' + 'white-space: nowrap;' + '}' + '.rpht_chat_tab_scroll {' + 'height: 60px;' + '}' + '</style>' ; /* If this doesn't print, something happened with the global vars */ console.log('RPH Tools start'); /**************************************************************************** * MAIN FUNCTIONS ****************************************************************************/ /*************************************************************************** * @brief: Called when connection to chat is established. If it is, it will * inject the ping settings form to the chat and restore any saved * settings ***************************************************************************/ $(function() { scriptSettings.flags = RPHT_SHOW_NAMES; _on('accounts', function() { ProcessAccountEvt(account); }); _on('ignores', function(data) { ProcessIngoresEvt(data); }); chatSocket.on('confirm-room-join', function(data) { RoomJoinSetup(data); }); _on('pm', function(data) { HandleIncomingPm(data); }); _on('outgoing-pm', function(data) { HandleOutgoingPm(data); }); chatSocket.on('user-kicked', function(data){ for(var i=0; i < account.users.length; i++){ if (data.targetid == account.users[i]){ $('<div class="inner"><p>You were kicked from '+data.room+'.<br />'+ ' Reason: '+ data.msg + '.</p></div>').dialog().dialog('open'); } } }); chatSocket.on('user-banned', function(data){ for(var i=0; i < account.users.length; i++){ if (data.targetid == account.users[i]){ $('<div class="inner"><p>You were banned from '+data.room+'.<br />'+ ' Reason: '+ data.msg + '.</p></div>').dialog().dialog('open'); } } }); InitRphTools(); }); /***************************************************************************** * @brief: Further initialize the script after receiving an account data blob. ***************************************************************************/ function InitRphTools(){ /* Set up HTML injection. */ $('#random-quote').hide(); $('a.settings').hide(); $('#top p.right').prepend('<a class="pings settings">Settings</a>'); $('body').append(html); $('head').append(rpht_css); InitSettingsDialog(); LoadSettings(); console.log('RPH Tools[InitRphTools]: Init complete, setting up dialog box'); SetUpToolsDialog(); } /**************************************************************************** * 2. GUI SETUP FUNCTION ****************************************************************************/ /**************************************************************************** * @brief: Sets up all the ping dialog box GUI handling. ****************************************************************************/ function SetUpToolsDialog() { ChatSettingsSetup(); PmSettingsSetup(); DiceRollSetup(); BlockingSetup(); ModdingSetup(); ImportExportSetup(); AboutFormSetup(); PopulateSettingsDialog(); setTimeout(ReblockList, 60*1000); startupTimer = setInterval(DoDelayedSetup, 5*1000); console.log('RPH Tools[SetUpToolsDialog]: Dialog box setup complete. RPH Tools is now ready.'); } /**************************************************************************** * @brief Sets up the chat settings group. * * @note Anything that deals with flags is listed by bit order for sanity's * sake ****************************************************************************/ function ChatSettingsSetup() { settingsDialog.chat.button.click(function() { if (settingsDialog.chat.state === true) { settingsDialog.chat.form.hide(); settingsDialog.chat.state = false; } else{ settingsDialog.chat.form.show(); settingsDialog.chat.state = true; } }); $('#pingNames').blur(function() { scriptSettings.pings = $('#pingNames').val().replace('\n','').replace('\r',''); settingsChanged = true; }); $('#pingURL').blur(function() { UpdateChatPmSetting('pingURL', 'ping_url'); }); $('#pingTextColor').blur(function() { UpdateChatPmSetting('pingTextColor', 'color'); }); $('#pingHighlightColor').blur(function() { UpdateChatPmSetting('pingHighlightColor', 'highlight'); }); $('#pingBoldEnable').change(function() { ToggleFlag(RPHT_PING_BOLD); }); $('#pingItalicsEnable').change(function() { ToggleFlag(RPHT_PING_ITALICS); }); $('#pingExactMatch').change(function() { ToggleFlag(RPHT_PING_EXACT_MATCH); }); $('#pingCaseSense').change(function() { ToggleFlag(RPHT_PING_CASE_SENSE); }); $('#showUsername').change(function() { ToggleFlag(RPHT_SHOW_NAMES); }); $('#imgIconDisable').change(function() { ToggleFlag(RPHT_NO_ROOM_ICONS); }); $('#favEnable').click(function(){ ToggleFlag(RPHT_AUTO_JOIN); SaveChatSettings(); }); $('#favAdd').click(function(){ AddFavoriteRoom(); }); $('#favRemove').click(function(){ RemoveFavoriteRoom(); }); $('#userNameTextColorButton').click(function() { ChangeTextColor(); }); $('#chatHistory').change(function() { rph.setSetting('maxHistory', parseInt($(this).val()) ); }); } /**************************************************************************** * @brief Sets up PM settings dialog * * @note Anything that deals with flags is listed by bit order for sanity's * sake ****************************************************************************/ function PmSettingsSetup() { settingsDialog.pm.button.click(function() { if (settingsDialog.pm.state === true) { settingsDialog.pm.form.hide(); settingsDialog.pm.state = false; } else{ settingsDialog.pm.form.show(); settingsDialog.pm.state = true; } }); $('#pmPingURL').change(function(){ UpdateChatPmSetting('pmPingURL', 'pmPingUrl'); }); $('#pmMute').change(function(){ if ($('#pmMute').is(":checked")){ $('#im-sound').children("audio").attr('src', ''); } else { $('#im-sound').children("audio").attr('src', scriptSettings.pmPingUrl); } }); $('#pmIconsDisable').change(function() { ToggleFlag(RPHT_NO_PM_ICONS); }); $('#pmNamesDroplist').change(function() { var userId = $('#pmNamesDroplist option:selected').val(); var message = ''; if (awayMessages[userId] !== undefined) { message = awayMessages[userId].message; } $('input#awayMessageTextbox').val(message); }); $('#setAwayButton').click(function() { SetPmAway(); }); $('#removeAwayButton').click(function() { RemovePmAway(); }); } /**************************************************************************** * @brief: Sets up the GUI callbacks and behavior for the RNGs. ****************************************************************************/ function DiceRollSetup() { settingsDialog.rng.button.click(function() { if (settingsDialog.rng.state === true) { settingsDialog.rng.form.hide(); settingsDialog.rng.state = false; } else{ settingsDialog.rng.form.show(); settingsDialog.rng.state = true; } }); $('#diceNum').blur(function() { var dieNum = parseInt($('#diceNum').val()); if (dieNum < RPHT_DIE_MIN) { $('#diceNum').val(RPHT_DIE_MIN); } else if (RPHT_DIE_MAX < dieNum) { $('#diceNum').val(RPHT_DIE_MAX); } }); $('#diceSides').blur(function() { var dieSides = parseInt($('#diceSides').val()); if (dieSides < RPHT_DIE_SIDE_MIN) { $('#diceSides').val(RPHT_DIE_SIDE_MIN); } else if (RPHT_DIE_SIDE_MAX < dieSides) { $('#diceSides').val(RPHT_DIE_SIDE_MAX); } }); $('#rngMinNumber').blur(function() { var minNum = parseInt($('#rngMinNumber').val()); if (minNum < RPHT_RNG_NUM_MIN) { $('#rngMinNumber').val(RPHT_RNG_NUM_MIN); } else if (RPHT_RNG_NUM_MAX < minNum) { $('#rngMinNumber').val(RPHT_RNG_NUM_MAX); } }); $('#rngMaxNumber').blur(function() { var maxNum = parseInt($('#rngMaxNumber').val()); if (maxNum < RPHT_RNG_NUM_MIN) { $('#rngMaxNumber').val(RPHT_RNG_NUM_MIN); } else if (RPHT_RNG_NUM_MAX < maxNum) { $('#rngMaxNumber').val(RPHT_RNG_NUM_MAX); } }); $('#rngButton').click(function() { if ($('#coinRadio')[0].checked) { RunRNG('coin'); } else if ($('#diceRadio')[0].checked) { RunRNG('dice'); } else if ($('#rngRadio')[0].checked) { RunRNG('rng'); } }); $('#coinRadio').change(function() { ChangeRngDisplay('coin'); }); $('#diceRadio').change(function() { ChangeRngDisplay('dice'); }); $('#rngRadio').change(function() { ChangeRngDisplay('rng'); }); } /**************************************************************************** * @brief: Sets up the GUI callbacks and behavior for blocking ****************************************************************************/ function BlockingSetup() { settingsDialog.blocking.button.click(function() { if (settingsDialog.blocking.state === true) { settingsDialog.blocking.form.hide(); settingsDialog.blocking.state = false; } else{ settingsDialog.blocking.form.show(); settingsDialog.blocking.state = true; } }); $('#blockButton').click(function() { var userName = $('#nameCheckTextbox').val(); BlockUserByName(userName); }); $('#unblockButton').click(function() { RemoveFromBlockList(); }); } /**************************************************************************** * @brief: Sets up the GUI callbacks and behavior for modding functions ****************************************************************************/ function ModdingSetup() { settingsDialog.modding.button.click(function() { if (settingsDialog.modding.state === true) { settingsDialog.modding.form.hide(); settingsDialog.modding.state = false; } else{ settingsDialog.modding.form.show(); settingsDialog.modding.state = true; } }); $('#roomModSelect').change(function() { var roomModPair_sel = document.getElementById("roomModSelect"); var roomModVal = roomModPair_sel.options[roomModPair_sel.selectedIndex].value; if (roomNamePairs[roomModVal] !== undefined) { $('input#modRoomTextInput').val(roomNamePairs[roomModVal].room); $('input#modFromTextInput').val(roomNamePairs[roomModVal].modName); } else{ $('input#modRoomTextInput').val(""); $('input#modFromTextInput').val(""); } }); $('#resetPassword').click(function(){ var room = $('input#modRoomTextInput').val(); var user = $('input#modFromTextInput').val(); getUserByName($('input#modFromTextInput').val(), function(User) { var userId = User.props.id; chatSocket.emit('modify', {room:room, userid:userId, props:{pw:false}}); }); }); $('#kickButton').click(function() { ModAction('kick'); }); $('#banButton').click(function() { ModAction('ban'); }); $('#unbanButton').click(function() { ModAction('unban'); }); $('#modButton').click(function() { ModAction('add-mod'); }); $('#unmodButton').click(function() { ModAction('remove-mod'); }); } /**************************************************************************** * @brief: Sets up callback functions for importing/exporting settings ****************************************************************************/ function ImportExportSetup() { settingsDialog.importExport.button.click(function() { if (settingsDialog.importExport.state === true) { settingsDialog.importExport.form.hide(); settingsDialog.importExport.state = false; } else{ settingsDialog.importExport.form.show(); settingsDialog.importExport.state = true; } }); $('#importButton').click(function() { ImportSettings(); }); $('#exportButton').click(function() { ExportSettings(); }); $('#printSettingsButton').click(function() { PrintSettings(); }); $('#deleteSettingsButton').click(function(){ DeleteSettings(); }); } /**************************************************************************** * @brief: Sets up callback functions for the about area ****************************************************************************/ function AboutFormSetup(){ settingsDialog.about.button.click(function() { if (settingsDialog.about.state === true) { settingsDialog.about.form.hide(); settingsDialog.about.state = false; } else{ settingsDialog.about.form.show(); settingsDialog.about.state = true; } }); } /**************************************************************************** * @brief Populates the dialog with settings from the gathered settings. * * @param user_id - ID of username ****************************************************************************/ function PopulateSettingsDialog() { $('#pingNames').val(scriptSettings.pings); $('#pingURL').val(scriptSettings.ping_url); $('#pingTextColor').val(scriptSettings.color); $('#pingHighlightColor').val(scriptSettings.highlight); $('#pmPingURL').val(scriptSettings.pmPingUrl); $('input#favEnable').prop("checked", GetFlagState(RPHT_AUTO_JOIN)); $('input#pingBoldEnable').prop("checked", GetFlagState(RPHT_PING_BOLD)); $('input#pingItalicsEnable').prop("checked", GetFlagState(RPHT_PING_ITALICS)); $('input#pingExactMatch').prop("checked", GetFlagState(RPHT_PING_EXACT_MATCH)); $('input#pingCaseSense').prop("checked", GetFlagState(RPHT_PING_CASE_SENSE)); $('input#pmIconsDisable').prop("checked", GetFlagState(RPHT_NO_PM_ICONS)); $('input#showUsername').prop("checked", GetFlagState(RPHT_SHOW_NAMES)); $('inputimgIconDisable').prop("checked", GetFlagState(RPHT_NO_ROOM_ICONS)); for(var i = 0; i < scriptSettings.favRooms.length; i++){ var favRoomObj = scriptSettings.favRooms[i]; $('#favRoomsList').append( '<option value="' + favRoomObj._id + '">' + favRoomObj.user + ": " + favRoomObj.room + '</option>' ); } if (scriptSettings.favRooms.length >= 10){ $('#favAdd').text("Favorites Full"); $('#favAdd')[0].disabled = true; } // Prevents populating the dialogue from counting as a change. settingsChanged = false; } /**************************************************************************** * @brief Changes the character's text color. * ****************************************************************************/ function ChangeTextColor(){ var text_color = $('input#userNameTextColor').val(); if (ValidateColor(text_color) === false || ValidateColorRange(text_color) === false) { MarkProblem('userNameTextColor', true); } else{ var userId = $('#userColorDroplist option:selected').val(); text_color = text_color.substring(1,text_color.length); getUserById(userId, function(User) { MarkProblem('userNameTextColor', false); sendToSocket('modify', {userid:User.props.id, color:text_color}); }); } } /**************************************************************************** * @brief Adds a room and user to the favorite's list * ****************************************************************************/ function AddFavoriteRoom(){ var room = getRoom($('#favRoom').val()); if (room === undefined){ MarkProblem('favRoom', true); return; } if (scriptSettings.favRooms.length < 10){ var favExists = false; var hashStr = $('#favRoom').val() + $('#favUserList option:selected').html(); var favRoomObj = { _id: hashStr.hashCode(), user : $('#favUserList option:selected').html(), userId: parseInt($('#favUserList option:selected').val()), room : $('#favRoom').val(), roomPw : $('#favRoomPw').val() }; MarkProblem('favRoom', false); if (ArrayObjectIndexOf(scriptSettings.favRooms, "_id", favRoomObj._id) === -1){ $('#favRoomsList').append( '<option value="' + favRoomObj._id + '">' + favRoomObj.user + ": " + favRoomObj.room + '</option>' ); scriptSettings.favRooms.push(favRoomObj); console.log('RPH Tools[AddFavoriteRoom]: Added favorite room', favRoomObj); } if (scriptSettings.favRooms.length >= 10){ $('#favAdd').text("Favorites Full"); $('#favAdd')[0].disabled = true; } } SaveChatSettings(); } /**************************************************************************** * @brief Removes a room and user to the favorite's list * ****************************************************************************/ function RemoveFavoriteRoom(){ var favItem = document.getElementById("favRoomsList"); var favItemId = $('#favRoomsList option:selected').val(); favItem.remove(favItem.selectedIndex); for(var favs_i = 0; favs_i < scriptSettings.favRooms.length; favs_i++){ if (scriptSettings.favRooms[favs_i]._id == favItemId){ scriptSettings.favRooms.splice(favs_i, 1); break; } } if (scriptSettings.favRooms.length < 10){ $('#favAdd').text("Add"); $('#favAdd')[0].disabled = false; } SaveChatSettings(); } /**************************************************************************** * @brief Automatically joins rooms in the saved list. * ****************************************************************************/ function JoinFavoriteRooms(){ if (roomnames.length > 10){ for(var i = 0; i < scriptSettings.favRooms.length; i++){ var favRoom = scriptSettings.favRooms[i]; chatSocket.emit('join', {name:favRoom.room, userid:favRoom.userId, pw:favRoom.roomPw}); } clearTimeout(startupTimer); } } /**************************************************************************** PM functions ****************************************************************************/ /**************************************************************************** * @brief: Sets up PM Away Messages ****************************************************************************/ function SetPmAway(){ var userId = $('#pmNamesDroplist option:selected').val(); var name = $("#pmNamesDroplist option:selected").html(); if (awayMessages[userId] !== undefined) { if (awayMessages[userId].enabled === false){ $("#pmNamesDroplist option:selected").html("[Away]" + name); } awayMessages[userId].enabled = true; awayMessages[userId].message = $('input#awayMessageTextbox').val(); $("#pmNamesDroplist option:selected").css("background-color", "#FFD800"); $("#pmNamesDroplist option:selected").prop("selected", false); console.log('RPH Tools[ChatSettingsSetup]: Setting away message for', name, 'with message', awayMessages[userId].message); } else{ var awayMsgObj = { "usedPmAwayMsg" : false, "message" : "", "enabled" : true }; awayMsgObj.message = $('input#awayMessageTextbox').val(); awayMessages[userId] = awayMsgObj; $("#pmNamesDroplist option:selected").html("[Away]" + name); $("#pmNamesDroplist option:selected").css("background-color", "#FFD800"); $("#pmNamesDroplist option:selected").prop("selected", false); } } /**************************************************************************** * @brief: Removes PM away message ****************************************************************************/ function RemovePmAway(){ var userId = $('#pmNamesDroplist option:selected').val(); if (awayMessages[userId] !== undefined) { if (awayMessages[userId].enabled === true) { var name = $("#pmNamesDroplist option:selected").html(); awayMessages[userId].enabled = false; $("#pmNamesDroplist option:selected").html(name.substring(6,name.length)); $("#pmNamesDroplist option:selected").css("background-color", ""); $('input#awayMessageTextbox').val(""); console.log('RPH Tools[ChatSettingsSetup]: Remove away message for', name); } } } /**************************************************************************** RNG functions ****************************************************************************/ /**************************************************************************** * @brief: Changes the RNG options being displayed * @param: "option", option to be displayed ("coin", "dice", "rng") ****************************************************************************/ function ChangeRngDisplay(option) { if (option === 'coin') { $('#diceOptions').hide(); $('#rngOptions').hide(); $('#rngButton').text('Flip it!'); } else if (option === 'dice') { $('#diceOptions').show(); $('#rngOptions').hide(); $('#rngButton').text('Let\'s roll!'); } else if (option === 'rng') { $('#diceOptions').hide(); $('#rngOptions').show(); $('#rngButton').text('Randomize!'); } } /**************************************************************************** * @brief: Performs an RNG action * @param: "action", Which RNG action to perform ('coin', 'dice', 'rng') ****************************************************************************/ function RunRNG(action) { var class_name = $('li.active')[0].className.split(" "); var room_name = ""; var this_room = null; var userID = parseInt(class_name[2].substring(0,6)); var outcomeMsg = ''; /* Populate room name based on if showing usernames is checked. */ if (GetFlagState(RPHT_SHOW_NAMES)) { room_name = $('li.active').find("span:first").text(); } else { room_name = $('li.active')[0].textContent.slice(0,-1); } this_room = getRoom(room_name); if (action == "coin") { outcomeMsg = Rng_flipCoin(); } else if (action == "dice") { outcomeMsg = Rng_rollDice(); } else if (action == "rng") { outcomeMsg = Rng_randomNumber(); } outcomeMsg += '\u200b'; this_room.sendMessage(outcomeMsg, userID); DisableRngButtons(action); } /**************************************************************************** * @brief: Generates a coin toss ****************************************************************************/ function Rng_flipCoin(){ var coinMsg = '(( Coin toss: '; if (Math.ceil(Math.random() * 2) == 2) { coinMsg += '**heads!**))'; } else{ coinMsg += '**tails!**))'; } return coinMsg; } /**************************************************************************** * @brief: Generates a dice roll. ****************************************************************************/ function Rng_rollDice(){ var totals = 0; var dieNum = parseInt($('#diceNum').val()); var dieSides = parseInt($('#diceSides').val()); var dieMsg = '/me rolled ' + dieNum + 'd' + dieSides + ':'; for(i = 0; i < dieNum; i++) { var result = Math.ceil(Math.random() * dieSides); if ($('#showRollTotals')[0].checked) { totals += result; } dieMsg += ' '; dieMsg += result; } if ($('#showRollTotals')[0].checked) { dieMsg += " (Total amount: " + totals + ")"; } return dieMsg; } /**************************************************************************** * @brief: Generates a random number ****************************************************************************/ function Rng_randomNumber(){ var minNum = parseInt($('#rngMinNumber').val()); var maxNum = parseInt($('#rngMaxNumber').val()); var ranNumMsg = '(( Random number generated (' + minNum + ' to ' + maxNum + '): **'; ranNumMsg += Math.floor((Math.random() * (maxNum - minNum) + minNum)) + '** ))'; return ranNumMsg; } /**************************************************************************** * @brief: Disables the RNG buttons for three seconds. ****************************************************************************/ function DisableRngButtons(action) { $('#rngButton').text('Wait...'); $('#rngRadio')[0].disabled = true; $('#diceRadio')[0].disabled = true; $('#coinRadio')[0].disabled = true; $('#rngButton')[0].disabled = true; setTimeout(function() { $('#rngRadio')[0].disabled = false; $('#diceRadio')[0].disabled = false; $('#coinRadio')[0].disabled = false; $('#rngButton')[0].disabled = false; ChangeRngDisplay(action); }, 3000); } /**************************************************************************** Blocking Functions ****************************************************************************/ /**************************************************************************** * @brief: Adds a user to the internal and dialog block list. * @param: User - User object for the username being blocked ****************************************************************************/ function AddToBlockList(User) { /* Check if this user is already in the list. */ var inList = false; for (var i=0; i < blockedUsers.length; i++) { if (User.props.id == blockedUsers[i].id) { inList = true; } } if (inList === false) { blockedUsers.push({id:User.props.id, name:User.props.name}); $('#blockedDropList').append('<option value="' + User.props.id + '">' + User.props.name + '</option>'); } console.log('RPH Tools[BlockUser]: Blocking user', User.props.name); User.blocked = true; } /**************************************************************************** * @brief: Removes a user from the internal and dialog block list. ****************************************************************************/ function RemoveFromBlockList(){ var names = document.getElementById("blockedDropList"); var userId = $('#blockedDropList option:selected').val(); UnblockUser(userId); names.remove(names.selectedIndex); blockedUsers.splice(blockedUsers.indexOf(userId),1); SaveBlockSettings(); } /**************************************************************************** * @brief: Blocks everyone on the list. Used to refresh blocking. ****************************************************************************/ function ReblockList(){ console.log('RPH Tools[ReblockList]: reblocking everyone'); for(var i = 0; i < blockedUsers.length; i++){ BlockUser(blockedUsers[i].id); } } /**************************************************************************** * @brief: Sets the blocked flag to true for a user. * @param: UserId - ID of the user whose ignore settings are being changed ****************************************************************************/ function BlockUser(UserId) { getUserById(UserId, function(User) { User.blocked = true; }); } /**************************************************************************** * @brief: Sets the blocked flag to false for a user. * @param: UserId - ID of the user whose ignore settings are being changed ****************************************************************************/ function UnblockUser(UserId){ getUserById(UserId, function(User) { User.blocked = false; }); } /**************************************************************************** * @brief: Blocks a user by their ID * @param: userID - ID of the using being blocked ****************************************************************************/ function BlockUserById(userID) { if (userID !== undefined){ getUserById(userID, function(User) { AddToBlockList(User); SaveBlockSettings(); }); } } /**************************************************************************** * @brief: Blocks a user by their name * @param: username - username of the using being blocked ****************************************************************************/ function BlockUserByName(username){ if (username !== undefined){ getUserByName(username, function(user){ AddToBlockList(user); SaveBlockSettings(); }); } } /**************************************************************************** Modding Functions ****************************************************************************/ /**************************************************************************** * @brief: Performs a modding action * @param: action - string command that has the action. ****************************************************************************/ function ModAction(action) { var targets = $('#modTargetTextInput').val().replace('\n','').replace('\r',''); targets = targets.split(';'); console.log('RPH Tools[ModAction]: Performing', action, 'on', targets); for(var i = 0; i < targets.length; i++) { EmitModAction(action, targets[i]); } } /**************************************************************************** * @brief: Sends off the mod action * @param: action - string command that has the action. * @param: targetName - user name that the action is meant for. ****************************************************************************/ function EmitModAction(action, targetName) { var room = $('input#modRoomTextInput').val(); var user = $('input#modFromTextInput').val(); var userId = 0; var targetId = 0; var target = ''; var modMessage = ' '; getUserByName(targetName, function(Target) { targetId = Target.props.id; target = Target.props.name; }); getUserByName($('input#modFromTextInput').val(), function(User) { userId = User.props.id; modMessage += $("input#modMessageTextInput").val(); if (action === 'add-mod' || action === 'remove-mod') { modMessage = ''; } chatSocket.emit(action, {room:room, userid:userId, targetid:targetId, msg:modMessage}); if (action === 'ban') { modMessage = "Banning: " + target + " by: " + user + " In room: " + room; } else if (action === 'unban') { modMessage = "Unbanning: " + target + " by: " + user + " In room: " + room; } else if (action === 'add-mod') { modMessage = "Modding: " + target + " by: " + user + " In room: " + room; } else if (action === 'remove-mod') { modMessage = "Unmodding: " + target + " by: " + user + " In room: " + room; } else if (action === 'kick') { modMessage = "Kicking: " + target + " by: " + user + " In room: " + room; } console.log('RPH Tools[EmitModAction]:', modMessage); }); } /**************************************************************************** Script settings functions ****************************************************************************/ /**************************************************************************** * @brief: Imports settings from the textarea. ****************************************************************************/ function ImportSettings() { var settings_str = $('textarea#importExportTextarea').val(); var chatSettings_str = ''; var blockedUsers_str = ''; var temp_scriptSettings; var temp_blockedUsers; var delimiter = settings_str.indexOf("|"); try{ chatSettings_str = settings_str.substring(0, delimiter); blockedUsers_str = settings_str.substring(delimiter+1, settings_str.length); temp_scriptSettings = JSON.parse(chatSettings_str); temp_blockedUsers = JSON.parse(blockedUsers_str); /* Time to do a lot of checking here. */ if ( chatSettings_str === '' || blockedUsers_str === '' || temp_scriptSettings === undefined || temp_blockedUsers === undefined ) { MarkProblem("importExportTextarea", true); } else{ ExtractChatPmSettings(temp_scriptSettings); ExtractBlockSettings(temp_blockedUsers); SaveChatSettings(scriptSettings); console.log("RPH Tools[ImportSettings]: Importing blocked list", blockedUsers); MarkProblem("importExportTextarea", false); PopulateSettingsDialog(); } } catch (err) { console.log('RPH Tools[ImportSettings]: Error importing settings'); MarkProblem("importExportTextarea", true); } } /**************************************************************************** * @brief: Prints out the settings into the main textbox for exporting. ****************************************************************************/ function ExportSettings(){ var chatSettings_str = JSON.stringify(scriptSettings); var blockedUsers_str = JSON.stringify(blockedUsers); $('textarea#importExportTextarea').val(chatSettings_str + "|" + blockedUsers_str); MarkProblem("importExportTextarea", false); } /**************************************************************************** * @brief: Prints out settings in the console. ****************************************************************************/ function PrintSettings(){ console.log('RPH Tools[SetUpToolsDialog]: Chat settings', scriptSettings); console.log('RPH Tools[SetUpToolsDialog]: Blocked users', blockedUsers); } /**************************************************************************** * @brief: Deletes settings. * @note: The user has to press the button twice to delete. ****************************************************************************/ function DeleteSettings(){ if (settingsDialog.importExport.deleteConfirm === false){ $('#deleteSettingsButton').text('Press again to delete'); settingsDialog.importExport.deleteConfirm = true; } else if (settingsDialog.importExport.deleteConfirm === true){ $('#deleteSettingsButton').text('Delete Settings'); settingsDialog.importExport.deleteConfirm = false; localStorage.removeItem("chatSettings"); localStorage.removeItem("blockedUsers"); scriptSettings = { "pings" : "", "ping_url" : "http://chat.rphaven.com/sounds/boop.mp3", "color" : "#000", "highlight" : "#FFA", "flags" : 0, "pmPingUrl" : "http://chat.rphaven.com/sounds/imsound.mp3", "favRooms" : [] }; PopulateSettingsDialog(); } } /**************************************************************************** PM processing functions ****************************************************************************/ /**************************************************************************** * @brief Handles incoming PMs. * * @param data - Data containing the PM. ****************************************************************************/ function HandleIncomingPm(data){ getUserById(data.to, function(fromUser) { /* Send away message. */ if (awayMessages[data.from] !== undefined) { if (awayMessages[data.from].enabled === true) { var awayMsg = awayMessages[data.from].message; awayMessages[data.from].usedPmAwayMsg = true; sendToSocket('pm', {'from':data.from, 'to':data.to, 'msg':awayMsg, 'target':'all'}); } } }); } /**************************************************************************** * @brief Handles outgoing PMs. * * @param data - Data containing the PM. ****************************************************************************/ function HandleOutgoingPm(data){ getUserById(data.from, function(fromUser) { if (awayMessages[data.from] !== undefined) { if (awayMessages[data.from].usedPmAwayMsg === false) { awayMessages[data.from].enabled = false; $('#pmNamesDroplist option').filter(function() { return this.value == data.from; }).css("background-color", ""); } awayMessages[data.from].usedPmAwayMsg = false; } }); } /**************************************************************************** Chat message processing functions ****************************************************************************/ /**************************************************************************** * @brief: When user joins a room, do the following: * - Set up the .onMessage function for pinging * - Add the user's name to the chat tab and textarea * - Create a room-pair name for the Modding section * @param: room - Room that the user has joined ****************************************************************************/ function RoomJoinSetup(room) { var thisRoom = getRoom(room.room); var userId = GetIdFromChatTab(thisRoom); thisRoom.onMessage = function (data) { var thisRoom = this; if ( account.ignores.indexOf(data.userid) !== -1 ) { return; } PostMessage(thisRoom, data); }; if (GetFlagState(RPHT_SHOW_NAMES)) { AddNameToUI(thisRoom, userId); } AddModFeatures(thisRoom, userId); ResizeChatTabs(); if (jQuery._data(window, "events").resize === undefined){ $( window ).resize(ResizeChatTabs); } } /**************************************************************************** * @brief: Takes a message received in the chat and modifies it if it has * a match for pinging * @param: thisRoom - The room that the message is for. * @param: data - The message for the room ****************************************************************************/ function PostMessage(thisRoom, data) { getUserById(data.userid, function(User) { var timestamp = makeTimestamp(data.time); var msg = parseMsg(data.msg); var classes = ''; var $el = ''; var msgHtml = ''; if ( User.blocked ) { return; } classes = GetClasses(User, thisRoom); /* Check if this is a valid RNG */ if (msg[msg.length-1] === '\u200b'){ msg += '&nbsp;<span style="background:#4A4; color: #000;">☑</span>'; } /* Add pinging higlights */ try{ var testRegex = null; testRegex = MatchPing(msg); if (testRegex !== null) { msg = HighlightPing(msg, testRegex); HighlightRoom(thisRoom); if (pingSound !== null) { pingSound.play(); } } } catch (err) { console.log('RPH Tools[PostMessage]: I tried pinging D:', err); msg = parseMsg(data.msg); } if ( msg.charAt(0) === '/' && msg.slice(1,3) === 'me') { classes += 'action '; msg = msg.slice(3); msgHtml = '<span class="first">[' + timestamp + ']</span>\n<span style="color:#' + User.props.color + '"><a class="name" title="[' + timestamp + ']" style="color:#' + User.props.color + '">'+ User.props.name + '</a>' + msg + '</span>'; } else { msgHtml = '<span class="first">[' + timestamp + ']<a class="name" title="[' + timestamp + ']" style="color:#' + User.props.color + '">' + User.props.name + '<span class="colon">:</span></a></span>\n<span style="color:#' + User.props.color+'">' + msg +'</span>'; } if (GetFlagState(RPHT_NO_ROOM_ICONS)) { $el = AppendMessageTextOnly(msgHtml, thisRoom).addClass(classes); } else{ $el = thisRoom.appendMessage(msgHtml).addClass(classes); } $el.find('br:gt(7)').remove(); }); } /**************************************************************************** * @brief: Gets the user name's classes that are applicable to it * @param: User - User of the message * @param: thisRoom - Room that the message is being sent to ****************************************************************************/ function GetClasses(User, thisRoom) { var classes = ''; if ( User.friendOf ) { classes += 'friend '; } if ( isOwnUser(User) ) { classes += 'self '; } if ( isOwnerOf(thisRoom, User) ) { classes += 'owner '; } else if ( isModOf(thisRoom, User) ) { classes += 'mod '; } if ( isInGroup(thisRoom, User) ) { classes += 'group-member '; } return classes; } /**************************************************************************** * @brief: Checks if the message has any ping terms * @param: msg - The message for the chat as a string. * * @return: Returns the match or null ****************************************************************************/ function MatchPing(msg) { var pingNames = scriptSettings.pings.split(','); var pingFlags = scriptSettings.flags; var regexParam = "m"; if ((pingFlags & 16) === 0) { regexParam = 'im'; } for(i = 0; i < pingNames.length; i++) { if (pingNames[i] !== "") { var regexPattern = pingNames[i].trim(); if ((pingFlags & 8) > 0) { regexPattern = "\\b" + pingNames[i].trim() + "\\b"; } /* Check if search term is not in a link. */ if (IsInLink(pingNames[i], msg) === false) { var testRegex = new RegExp(regexPattern, regexParam); if (msg.match(testRegex)) { return testRegex; } } } } return null; } /**************************************************************************** * @brief: Adds highlights to the ping term * @param: msg - Message to be sent to the chat. * @param: testRegex - Regular expression to use to match the term. * * @param: Modified msg. ****************************************************************************/ function HighlightPing(msg, testRegex) { var pingFlags = scriptSettings.flags; var pingColor = scriptSettings.color; var pingHighlight = scriptSettings.highlight; var boldEnabled = ""; var italicsEnabled = ""; if ((pingFlags & 2) > 0) { boldEnabled = "font-weight: bold; "; } if ((pingFlags & 4) > 0) { italicsEnabled = "font-style:italic; "; } msg = msg.replace(testRegex, '<span style="color: ' + pingColor + '; background: ' + pingHighlight +'; ' + boldEnabled + italicsEnabled + '">' + msg.match(testRegex) + '</span>'); return msg; } /**************************************************************************** * @brief: Adds a highlight to the room's tab * @param: thisRoom - Room where the ping happened. ****************************************************************************/ function HighlightRoom(thisRoom) { //Don't highlight chat tab if the chat is marked as active. var testRegex = new RegExp('active', 'im'); var className = thisRoom.$tabs[0][0].className; var pingColor = scriptSettings.color; var pingHighlight = scriptSettings.highlight; if (className.search(testRegex) == -1) { thisRoom.$tabs[0].css('background-color', pingHighlight); thisRoom.$tabs[0].css('color', pingColor); thisRoom.$tabs[0].click(function() { thisRoom.$tabs[0].css('background-color', '#333'); thisRoom.$tabs[0].css('color', '#6F9FB9'); thisRoom.$tabs[0].hover( function() { thisRoom.$tabs[0].css('background-color', '#6F9FB9'); thisRoom.$tabs[0].css('color', '#333'); }, function() { thisRoom.$tabs[0].css('background-color', '#333'); thisRoom.$tabs[0].css('color', '#6F9FB9'); }); }); } } /**************************************************************************** * @brief: Adds user name to chat tab and chat textarea * @param: thisRoom - Room that was entered * @param: userId - ID of the user that entered ****************************************************************************/ function AddNameToUI(thisRoom, userId) { getUserById(userId, function(User) { var tabsLen = thisRoom.$tabs.length; var idRoomName = thisRoom.$tabs[tabsLen-1][0].className.split(' ')[2]; var newTabHtml = '<span>' + thisRoom.props.name + '</span><p style="font-size: x-small; position: absolute; top: 12px;">' + User.props.name + '</p>'; thisRoom.$tabs[tabsLen-1].html(newTabHtml); $('<a class="close ui-corner-all">x</a>').on('click', function(ev) { ev.stopPropagation(); chatSocket.emit('leave', {userid:User.props.id, name:thisRoom.props.name}); }).appendTo( thisRoom.$tabs[tabsLen-1] ); $('textarea.' + idRoomName).prop('placeholder', 'Post as ' + User.props.name); $('textarea.' + idRoomName).css('color', "#" + User.props.color); userId = User.props.id; userName = User.props.name; classes = GetClasses(User, thisRoom); console.log('RPH Tools[AddNameToUI]: User class:,', User.props.name, classes); }); } /**************************************************************************** * @brief: Initializes extra features if user is a mod of the room. * @param: thisRoom - Room that was entered * @param: userId - ID of the user that entered ****************************************************************************/ function AddModFeatures(thisRoom, userId) { getUserById(userId, function(User) { var classes = GetClasses(User, thisRoom); if (classes.indexOf("mod") > -1 || classes.indexOf("owner") > -1 ) { var roomNamePair = thisRoom.props.name + ': ' + userName; var roomNameValue = thisRoom.props.name + '.' + userId; var roomNameObj = { 'room': thisRoom.props.name, 'modName': userName, 'modId': userId }; if (roomNamePairs[roomNameValue] === undefined) { roomNamePairs[roomNameValue] = roomNameObj; $('#roomModSelect').append('<option value="' + roomNameValue + '">' + roomNamePair + '</option>'); console.log("RPH Tools[AddModFeatures]: Added room mod pair", roomNamePairs); } } }); } /**************************************************************************** * UTILITY FUNCTIONS ****************************************************************************/ /**************************************************************************** * @brief Initializes the data structures and initial event handlers for the * main dialog. ****************************************************************************/ function InitSettingsDialog(){ settingsDialog.dialog = { button: $('#top a.pings'), form: $('#settingsBox'), state: false }; settingsDialog.chat = { button: $('#chatSettingsHeader'), form: $('#chatSettingsForm'), state: false }; settingsDialog.pm = { button: $('#pmSettingsHeader'), form: $('#pmSettingsForm'), state: false }; settingsDialog.rng = { button: $('#rngHeader'), form: $('#rngForm'), state: false }; settingsDialog.blocking = { button: $('#blockHeader'), form: $('#blockForm'), state: false }; settingsDialog.modding = { button: $('#moddingHeader'), form: $('#moddingForm'), state: false }; settingsDialog.importExport = { button: $('#importExportHeader'), form: $('#importExportForm'), state: false, deleteConfirm: false }; settingsDialog.about = { button: $('#aboutHeader'), form: $('#aboutHelpForm'), state: false }; settingsDialog.dialog.button.click(function() { if (settingsDialog.dialog.state === false) { settingsDialog.dialog.form.show(); settingsDialog.dialog.state = true; ReblockList(); } else { if (settingsChanged === true) { console.log('RPH Tools[SetUpToolsDialog]: Chat settings were changed', scriptSettings); settingsChanged = false; if (validSettings === true) { SaveChatSettings(scriptSettings); } } else{ console.log('RPH Tools[SetUpToolsDialog]: No chat settings were changed'); } settingsDialog.dialog.form.hide(); settingsDialog.dialog.state = false; $('#deleteSettingsButton').text('Delete Settings'); settingsDialog.importExport.deleteConfirm = false; } }); } /**************************************************************************** * @brief Processes account events. * * @param account - Data blob countaining the user's account. ****************************************************************************/ function ProcessAccountEvt(account){ var users = account.users; ClearUsersDropLists(); for(i = 0; i < users.length; i++) { AddUserToDroplist(users[i]); } console.log('RPH Tools[_on.accounts]: Account data blob received, adding users', users); } /**************************************************************************** * @brief Processes ignores events. * * @param data - Data containing the user being ignored. ****************************************************************************/ function ProcessIngoresEvt(data){ console.log("RPH Tools[_on.ignores]: Blocking user from ignore button", data.ids[0]); if (data.ids[0] !== undefined){ BlockUserById(data.ids[0]); } } /**************************************************************************** * @brief Toggles one of the settings flags. * * @param flag - Flag mask to toggle. ****************************************************************************/ function ToggleFlag(flag){ scriptSettings.flags ^= flag; settingsChanged = true; } /**************************************************************************** * @brief Get the state of the flag * * @param flag - Flag mask to check. ****************************************************************************/ function GetFlagState(flag){ return ((scriptSettings.flags & flag) > 0); } /**************************************************************************** * @brief Tests the ping URL to make sure it ends in .wav, otherwise use * the default ping URL (not sure if .mp3 and the like are supported) * * @param PingURL - URL to test ****************************************************************************/ function ValidateUrl(PingURL) { var match = false; var regexp = /(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/; var pingExt = PingURL.slice( (PingURL.length-4), (PingURL.length)); if (PingURL === '') { match = true; } else if (regexp.test(PingURL) === true) { if (pingExt == ".wav" || pingExt == ".ogg" || pingExt == ".mp3") { match = true; } } return match; } /**************************************************************************** * @brief: Tests the highlight color to make sure it's valid * @param: HighlightColor - String representation of the color. * * @return: Returns boolean if the color matches the regex pattern. ****************************************************************************/ function ValidateColor(HighlightColor) { var pattern = new RegExp(/(^#[0-9A-Fa-f]{6}$)|(^#[0-9A-Fa-f]{3}$)/i); return pattern.test(HighlightColor); } /**************************************************************************** * @brief: Tests the color range of the color to ensure its valid * @param: TextColor - String representation of the color. * * @return: True if the color is within range, false otherwise. ****************************************************************************/ function ValidateColorRange(TextColor) { var rawHex = TextColor.substring(1,TextColor.length); var red = 255; var green = 255; var blue = 255; /* If the color text is 3 characters, limit it to #DDD */ if (rawHex.length == 3) { red = parseInt(rawHex.substring(0,1), 16); green = parseInt(rawHex.substring(1,2), 16); blue = parseInt(rawHex.substring(2,3), 16); if ((red <= 13) && (green <= 13) && (blue <= 13)) { return true; } } /* If the color text is 6 characters, limit it to #D2D2D2 */ else if (rawHex.length == 6) { red = parseInt(rawHex.substring(0,2), 16); green = parseInt(rawHex.substring(2,4), 16); blue = parseInt(rawHex.substring(4,6), 16); if ((red <= 210) && (green <= 210) && (blue <= 210)) { return true; } } console.log('RPH Tools[ValidateColorRange]: Color check failed', rawHex, red, green, blue); return false; } /**************************************************************************** * @brief Adds usernames to droplists. * @param user_id - ID of username ****************************************************************************/ function AddUserToDroplist(user_id) { getUserById(user_id, function(User) { $('#pmNamesDroplist').append('<option value="' + user_id + '">' + User.props.name + '</option>'); $('#userColorDroplist').append('<option value="' + user_id + '">' + User.props.name + '</option>'); $('#favUserList').append('<option value="' + user_id + '">' + User.props.name + '</option>'); }); } /**************************************************************************** * @brief Clears droplists. ****************************************************************************/ function ClearUsersDropLists(){ $('#pmNamesDroplist').empty(); $('#userColorDroplist').empty(); $('#favUserList').empty(); } /**************************************************************************** * @brief: Marks if there's a problem or not. * @param: element - element ID that has the problem * @param: mark - true or false if it has a problem ****************************************************************************/ function MarkProblem(element, mark) { if (mark === true) { $("#"+element).css('background', '#FF7F7F'); } else{ $("#"+element).css('background', '#FFF'); } } /**************************************************************************** * @brief: Checks if a search term is in an <a href=...> tag. * @param: searchTerm - String to look for * @param: msg - msg being searched. * * @return: True or false if there's a match. ****************************************************************************/ function IsInLink(searchTerm, msg) { var regexp = new RegExp('href=".*?' + searchTerm + '.*?"', ''); return regexp.test(msg); } /**************************************************************************** * @brief: Gets the user's ID from the chat tab (it's in the class) * @param: thisRoom - Room to get the ID from ****************************************************************************/ function GetIdFromChatTab(thisRoom) { var tabsLen = thisRoom.$tabs.length; var className = thisRoom.$tabs[tabsLen-1][0].className; var charID = className.match(new RegExp(' [0-9]+', ''))[0]; charID = charID.substring(1,charID.length); return parseInt(charID); } /**************************************************************************** * @brief Appends message to a room without adding an image icon * @param html - HTML to add to the room. * @param thisRoom - Object to the room receiving the message. * * @note This was modified from RPH's original code, which is not covered * by this license. ****************************************************************************/ function AppendMessageTextOnly(html, thisRoom) { var $el = $('<div>\n'+html+'\n</div>').appendTo( thisRoom.$el ); var extra = 5; //add more if near the bottom if ( thisRoom.$el[0].scrollHeight - thisRoom.$el.scrollTop() < 50 ) { extra = 60; } thisRoom.$el.animate({scrollTop: '+='+($el.outerHeight()+extra)}, 180); if ( thisRoom.$el.children('div').length > account.settings.maxHistory ) { thisRoom.$el.children('div:not(.sys):lt(3)').remove(); } return $el; } /**************************************************************************** * @brief In an array of object, return the first instance where a key * matches a value. * * @param objArray - Array of objects * @param key - Key to look for * @param value - Value of the key to match * @return Index of the first instance where the key matches the value, -1 * otherwise. ****************************************************************************/ function ArrayObjectIndexOf (objArray, key, value) { for(var i = 0; i < objArray.length; i++){ if (objArray[i][key] === value){ return i; } } return -1; } /**************************************************************************** Chat room and PM settings functions ****************************************************************************/ /**************************************************************************** * @brief: Updates a chat or PM setting. * @param: settingId - ID of which setting this * @param: pingSetting - Name of setting in scriptSettings to update. ****************************************************************************/ function UpdateChatPmSetting(settingId, pingSetting){ var validInput = false; var input = $('#'+settingId).val(); switch(pingSetting){ case "ping_url": case "pmPingUrl": validInput = ValidateUrl(input); break; case "color": case "highlight": validInput = ValidateColor(input); break; } if (validInput === true){ scriptSettings[pingSetting] = input; switch (pingSetting){ case "ping_url": pingSound = new Audio(scriptSettings.ping_url); break; case "pmPingUrl": $('#im-sound').children("audio").attr('src', input); break; } MarkProblem(settingId, false); settingsChanged = true; validSettings = true; } else { MarkProblem(settingId, true); validSettings = false; } } /**************************************************************************** * @brief: Extracts the data from locally stored settings. * @param: settingsObj - Object that holds the stored settings. ****************************************************************************/ function ExtractChatPmSettings(settingsObj){ for(var setting in scriptSettings){ if (settingsObj[setting] !== undefined){ scriptSettings[setting] = settingsObj[setting]; } } pingSound = new Audio(scriptSettings.ping_url); $('#im-sound').children("audio").attr('src', scriptSettings.pmPingUrl); console.log("RPH Tools[InitRphTools]: Loaded chat settings: ", scriptSettings); } /**************************************************************************** * @brief: Extracts the data from locally stored block users list. * @param: blockedUsersStorage - Object that holds the stored list. ****************************************************************************/ function ExtractBlockSettings(blockedUsersStorage){ console.log("RPH Tools[InitRphTools]: Loaded blocked users: ", blockedUsersStorage); for (var i = 0; i < blockedUsersStorage.length; i++) { console.log("RPH Tools[InitRphTools]: Blocking user ", blockedUsersStorage[i]); if (blockedUsersStorage[i] !== "") { var user = blockedUsersStorage[i]; blockUserDontSave(user.id); } } } function blockUserDontSave(userId){ getUserById(userId, function(User) { console.log('Blocking from stored list'); AddToBlockList(User); }); } /**************************************************************************** * @brief: Saves the chat and PM settings into local storage ****************************************************************************/ function SaveChatSettings() { localStorage.setItem("chatSettings", JSON.stringify(scriptSettings)); console.log("RPH Tools[SaveChatSettings]: Saving chat settings... ", localStorage.getItem("chatSettings")); } /**************************************************************************** * @brief: Loads the settings from local storage. ****************************************************************************/ function LoadSettings(){ if (typeof(storage) != "undefined") { if (localStorage.getItem("chatSettings") !== null) { var storedSettings = JSON.parse(localStorage.getItem("chatSettings")); ExtractChatPmSettings(storedSettings); } if (localStorage.getItem("blockedUsers") !== null) { var blockedUsers = JSON.parse(localStorage.getItem("blockedUsers")); ExtractBlockSettings(blockedUsers); } } } /**************************************************************************** * @brief: Saves the blocked users list into local storage. ****************************************************************************/ function SaveBlockSettings() { localStorage.setItem("blockedUsers", JSON.stringify(blockedUsers)); console.log("RPH Tools[SaveBlockSettings]: Saving blocked users (storage, session)", localStorage.getItem("blockedUsers"), blockedUsers); } /**************************************************************************** * @brief Generates a hash value for a string * * @note This was modified from https://stackoverflow.com/questions/7616461/generate-a-hash-from-string-in-javascript-jquery ****************************************************************************/ String.prototype.hashCode = function() { var hash = 0, i, chr, len; if (this.length === 0) return hash; for (i = 0, len = this.length; i < len; i++) { chr = this.charCodeAt(i); hash = ((hash << 31) - hash) + chr; hash |= 0; // Convert to 32bit integer } return hash; }; /**************************************************************************** * @brief: Creating a new prototype for PM messaging, to make image icons * not show up if desired. ****************************************************************************/ Pm.prototype.appendMsg = function(html){ var $el = $(html); this.$msgs.append($el); if( this.$typing ){ $el.insertBefore( this.$typing ); } this.$msgs.animate({scrollTop: '+='+($el.outerHeight()+18)}, 250); if (GetFlagState(RPHT_NO_PM_ICONS) === false){ $el.find('.img-wrapper').each(function(){ var $this = $(this); var url = $this.attr('href'); var $checker = $('<img src="'+url+'"/>').hide().appendTo('body'); $checker.load(function(){ if( $checker.height() <= 90 && $checker.width() <= 120 ){ $this.replaceWith('<img src="'+url+'" class="smily" />'); } else { $this.before($('<a href="#" />').text('Open in dialog box').bind('click', function(ev){ ev.preventDefault(); var matched = html.match(/([http|https]+:\/\/\S*\.(jpg|jpeg|png|gif))/i)[0]; $('<div class="innerbg smallBorders" style="padding:0 2px;height:100%;"><img src="'+matched+'" /></div>').dialog({ bgiframe: true, title: 'Image', width: $checker.width() }); }).add( $('<span />').text(' - ') ) ); } }); }); } }; /**************************************************************************** * @brief: Performs actions that are delayed so the script can do things when * actually in chat. ****************************************************************************/ function DoDelayedSetup(){ if (GetFlagState(RPHT_AUTO_JOIN) === true){ JoinFavoriteRooms(); } } /**************************************************************************** * @brief: Resizes chat tabs accordingly ****************************************************************************/ function ResizeChatTabs(){ $('#chat-tabs').addClass('rpht_chat_tab'); if ($('#chat-tabs')[0].clientWidth < $('#chat-tabs')[0].scrollWidth || $('#chat-tabs')[0].clientWidth + 200 > $('#chat-bottom')[0].clientWidth ){ $('#chat-top .inner').css('height', 'calc(100% - 20px)'); $('#chat-bottom').css({ 'margin-top': '-160px', 'height' : '120px' }); $('#chat-tabs').addClass('rpht_chat_tab_scroll'); $('#chat-tabs').css('width', $('#chat-bottom')[0].clientWidth - 200); } else { $('#chat-top .inner').removeAttr('style'); $('#chat-bottom').css({ 'margin-top': '-140px', }); $('#chat-tabs').removeClass('rpht_chat_tab_scroll'); $('#chat-tabs').css('width', 'auto'); } }
// Config params for the Angular App var contentLoaded = false, template_ext = '.html', host = (function () { return '//' + location.host + '/'; })(), firstLoad = true; jQuery(window).scroll(function (event) { if (jQuery(this).scrollTop() > 200) { jQuery('.static-share-header').css({ transform: 'translateX(0px) translateY(0px)', transition: 'transform 500ms' }); } else { jQuery('.static-share-header').css({ transform: 'translateX(0px) translateY(-71px)', transition: 'transform 500ms' }); } }); function isMobile() { return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) } function refreshAdsense() { (adsbygoogle = window.adsbygoogle || []).push({}); } function addUnits() { (adsbygoogle = window.adsbygoogle || []).push({ google_ad_client: "ca-pub-3833845702235676", enable_page_level_ads: true }); console.log('units added'); } $(document).on('click', 'a.google_vignette_inst', function (e) { console.log(this); e.preventDefault(); return false; });
var sh = require('../'); sh.log.on('message', function (level, message) { console.log(level, message); }) sh.log.mode = 'event'; sh.config.setAlias('lsHidden', 'ls', ['-a']); sh.config.setAlias('lsFull', sh.cmd('ls', ['-l'])); sh('lsHidden').on('success', function (output) { console.assert(output.indexOf('..') !== -1); }); sh('lsHidden', ['-l']).on('success', function (output) { console.assert(output.indexOf('..') !== -1); }); sh('lsFull').on('success', function (output) { console.assert(output.indexOf('LICENSE.md') !== -1); });
import { h } from 'omi'; import createSvgIcon from './utils/createSvgIcon'; export default createSvgIcon(h("path", { d: "M3 2l2.21 20H18.8L21 2H3zm9 17c-1.66 0-3-1.34-3-3 0-2 3-5.4 3-5.4s3 3.4 3 5.4c0 1.66-1.34 3-3 3zm6.33-11H5.67l-.44-4h13.53l-.43 4z" }), 'LocalDrinkSharp');
/* * JSLists v0.4.5 * © 2016 George Duff * * Release date: 01/06/2016 * The MIT License (MIT) * Copyright (c) 2016 George Duff * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // TO DO LIST - Will get round to most of them at some point! // Add folder & file icons dynamically from param // Collapse All & Open All are ropey at best! // Add a search function // Make the margins user definable // Add support for UL & OL var blackCircle = '&#9679; '; var openCircle = '&#9678; '; (function() { "use strict"; function define_JSLists() { var JSLists = {}; var JSLists_Error = function(error, alertType) { console.log(error); } var getUl = function(){ return document.getElementsByTagName("UL"); }; var getOl = function(){ return document.getElementsByTagName("OL"); }; var getAllLists = function(){ var olLists = Array.prototype.slice.call(document.getElementsByTagName("UL")), ulLists = Array.prototype.slice.call(document.getElementsByTagName("OL")) var gLists = olLists.concat(ulLists); return gLists; } JSLists.searchList = function(listId, searchTerm) { var i, j, lilNodes, liItems = document.getElementsByTagName("LI"); for(i=0; i<liItems.length; i++) { if(liItems[i].hasChildNodes()) { for(j=0; j<liItems[i].childNodes.length; j++) { if(liItems[i].childNodes[j].innerHTML == searchTerm) { //????? } } } } } JSLists.collapseAll = function(listId) { var i, ulLists = document.getElementsByTagName("UL"); for(i=0; i<ulLists.length; i++) { if(ulLists[i].className == "jsl-collapsed") { console.log(ulLists[i].className + '\n' + '@'); } }; }; JSLists.openAll = function(listId){ var i, olLists = Array.prototype.slice.call(document.getElementsByTagName("UL")), ulLists = Array.prototype.slice.call(document.getElementsByTagName("OL")) var gLists = olLists.concat(ulLists); for(i=1; i<gLists.length; i++) { gLists[i].setAttribute('class', 'jsl-open'); }; }; JSLists.padUnorderedLists = function(listId) { var i, listItems = document.getElementById(listId).getElementsByTagName("UL"); for(i=0; i<listItems.length; i++) { listItems[i].classList.add('jslist-ul'); } }; JSLists.padOrderedLists = function(listId) { var i, listItems = document.getElementById(listId).getElementsByTagName("UL"); for(i=0; i<listItems.length; i++) { listItems[i].classList.add('jslist-ol'); } }; JSLists.padLists = function(listId) { var i, listItems = document.getElementById(listId).getElementsByTagName("LI"); for(i=0; i<listItems.length; i++) { if(listItems[i].childNodes[0].className != "jsl-collapsed-arrow") { listItems[i].classList.add('jslist-li'); } } for(i=1; i<listItems.length; i++) { // console.log(listItems[i].childNodes.length); if(listItems[i].classList = "jslist-li" && listItems[i].childNodes.length < 2) { listItems[i].innerHTML = blackCircle + listItems[i].innerHTML } } this.padUnorderedLists(listId); this.padOrderedLists(listId); }; JSLists.createTree = function(listId, bulletPoint) { document.getElementById(listId).style.display = "none;" var i, j, curElem, ulCount, olCount, listItems = document.getElementById(listId).getElementsByTagName('LI'); //this should be the main parent for(i=0; i<listItems.length; i++) { if(listItems[i].id.length > 0) { curElem = document.getElementById(listItems[i].id); ulCount = document.getElementById(listItems[i].id).getElementsByTagName("UL"); if(ulCount.length > 0){ for(j=0; j<ulCount.length; j++) { if(ulCount[j].nodeName == "UL") { break; } } ulCount[j].setAttribute('class', 'jsl-collapsed'); var tglDiv = document.createElement("div"); tglDiv.setAttribute('class', 'jsl-list-closed'); tglDiv.setAttribute("id", listItems[i].id + i +'_tgl'); curElem.insertBefore(tglDiv, curElem.childNodes[0]); document.getElementById(listItems[i].id + i +'_tgl').addEventListener('click', function(e) { document.getElementById(e.target.id).classList.toggle('jsl-list-open'); document.getElementById(e.target.id).parentElement.lastElementChild.classList.toggle('jsl-open'); e.stopPropagation(); },true); } } else { listItems[i].setAttribute("id", listId+"tmp"+i); curElem = document.getElementById(listId+"tmp"+i); ulCount = document.getElementById(listItems[i].id).getElementsByTagName("UL"); if(ulCount.length > 0) { //There is a nested UL in this LI element, now find the position of the UL for(j=0; j<ulCount.length; j++) { if(ulCount[j].nodeName == "UL") { break; //Multiple UL's? //Set class collapseAll here } } ulCount[j].setAttribute('class', 'jsl-collapsed'); var tglDiv = document.createElement("div"); tglDiv.setAttribute('class', 'jsl-list-closed'); tglDiv.setAttribute("id", listItems[i].id + i +'_tgl'); curElem.insertBefore(tglDiv, curElem.childNodes[0]); document.getElementById(listItems[i].id + i +'_tgl').addEventListener('click', function(e){ document.getElementById(e.target.id).classList.toggle('jsl-list-open'); document.getElementById(e.target.id).parentElement.lastElementChild.classList.toggle('jsl-open'); e.stopPropagation(); },true); } listItems[i].removeAttribute("id"); } } setTimeout(function() { document.getElementById(listId).style.display = "block;" }, 50); // stops FOUC! this.padLists(listId); }; // JSLists.applyToList = function(listId, listType, applyIcons, applyTheme, themeNumber){ //Check the params here // does the id exist? JSLists.applyToList = function(listId, bulletPoint) { this.createTree(listId, "UL"); }; return JSLists; } //define the JSLists library in the global namespace if it doesn't already exist if(typeof(JSLists) === 'undefined') { window.JSLists = define_JSLists(); }else{ console.log("JSLists already defined."); } })();
function parseAngular(arr) { let modules = new Map(); let elements = new Map(); let appPattern = /^\$app='([^']+)'$/; let controllerPattern = /^\$controller='([^']+)'&app='([^']+)'$/; let modelPattern = /^\$model='([^']+)'&app='([^']+)'$/; let viewPattern = /^\$view='([^']+)'&app='([^']+)'$/; arr = arr.filter(e => e !== ''); function newMapEntry(map, match) { map.set(match, new Map()); map.get(match).set('controllers', new Set()); map.get(match).set('models', new Set()); map.get(match).set('views', new Set()); } function addToMaps(match, type) { if (modules.has(match[2])) { modules.get(match[2]).get(type).add(match[1]); } else { if (elements.has(match[2])) { elements.get(match[2]).get(type).add(match[1]); } else { newMapEntry(elements, match[2]); elements.get(match[2]).get(type).add(match[1]); } } } for (let str of arr) { if (str.startsWith('$app')) { let match = appPattern.exec(str); newMapEntry(modules, match[1]); if (elements.has(match[1])) { modules.get(match[1]).set('controllers', elements.get(match[1]).get('controllers')); modules.get(match[1]).set('models', elements.get(match[1]).get('models')); modules.get(match[1]).set('views', elements.get(match[1]).get('views')); elements.delete(match[1]); } appPattern.lastIndex = 0; } if (str.startsWith('$controller')) { let match = controllerPattern.exec(str); addToMaps(match, 'controllers'); controllerPattern.lastIndex = 0; } if (str.startsWith('$model')) { let match = modelPattern.exec(str); addToMaps(match, 'models'); modelPattern.lastIndex = 0; } if (str.startsWith('$view')) { let match = viewPattern.exec(str); addToMaps(match, 'views'); viewPattern.lastIndex = 0; } } let sortedModules = Array.from(modules.keys()).sort((a, b) => { if (modules.get(b).get('controllers').size !== modules.get(a).get('controllers').size) { return modules.get(b).get('controllers').size - modules.get(a).get('controllers').size; } if (modules.get(a).get('models').size !== modules.get(b).get('models').size) { return modules.get(a).get('models').size - modules.get(b).get('models').size; } return 0; }); let output = '{'; for (let module of sortedModules) { output += `"${module}":{"controllers":`; output += JSON.stringify(Array.from(modules.get(module).get('controllers').keys()).sort((a, b) => a.localeCompare(b))); output += ',"models":'; output += JSON.stringify(Array.from(modules.get(module).get('models').keys()).sort((a, b) => a.localeCompare(b))); output += ',"views":'; output += JSON.stringify(Array.from(modules.get(module).get('views').keys()).sort((a, b) => a.localeCompare(b))); output += '},'; } output = output.substr(0, output.length - 1); output += '}'; console.log(output); } parseAngular(['$app=\'MyApp\'', '$controller=\'My Controller\'&app=\'MyApp\'', '$model=\'My Model\'&app=\'MyApp\'', '$view=\'My View\'&app=\'MyApp\'']); parseAngular(['$controller=\'PHPController\'&app=\'Language Parser\'', '$controller=\'JavaController\'&app=\'Language Parser\'', '$controller=\'C#Controller\'&app=\'Language Parser\'', '$controller=\'C++Controller\'&app=\'Language Parser\'', '$app=\'Garbage Collector\'', '$controller=\'GarbageController\'&app=\'Garbage Collector\'', '$controller=\'SpamController\'&app=\'Garbage Collector\'', '$app=\'Language Parser\'']);
"use strict"; const utils = require('../utils/utils'); const ruleRegexp = /^S?([0-9]*)\/B?([0-9]*)\/C?([1-9][0-9]*)([MV]?)([0-9]*)$/i; function getNeighbourMethod (methodId) { if (methodId === 'V' || methodId === 'v' || methodId === 'von-neumann') { return 'von-neumann'; } else { return 'moore'; } } function generationsFunction (currentValue, neighbours) { let sum = 0; let result = 0; for (let index = 0; index < neighbours.length; index++) { sum = sum + (neighbours[index] === 1 ? 1 : 0); } if (currentValue === 0 && this.birth.indexOf(sum) > -1) { result = 1; } else if (currentValue === 1 && this.survival.indexOf(sum) > -1) { result = 1; } else if (currentValue > 0) { result = (currentValue + 1) % this.stateCount; } return result; } module.exports = function parseRuleString (ruleString) { const extractedRule = ruleRegexp.exec(utils.stripWhitespaces(ruleString)); return extractedRule ? { process: generationsFunction, ruleFormat: 'generations', ruleString: ruleString, survival: utils.splitStringInNumberArray(extractedRule[1]), birth: utils.splitStringInNumberArray(extractedRule[2]), stateCount: parseInt(extractedRule[3], 10) || 1, neighbourhoodType: getNeighbourMethod(extractedRule[4]), neighbourhoodRange: parseInt(extractedRule[5], 10) || 1 } : null; };
function expandLeft() { document.getElementById("sectionLeft").style.left = "0"; document.getElementById("sectionMiddle").style.left = "80%"; document.getElementById("sectionRight").style.left = "90%"; document.getElementById("titleLeft").style.left = "40%"; document.getElementById("titleMiddle").style.left = "0"; document.getElementById("titleRight").style.left = "0"; } function expandMiddle() { document.getElementById("sectionLeft").style.left = "0"; document.getElementById("sectionMiddle").style.left = "10%"; document.getElementById("sectionRight").style.left = "90%"; document.getElementById("titleLeft").style.left = "0"; document.getElementById("titleMiddle").style.left = "40%"; document.getElementById("titleRight").style.left = "0"; } function expandRight() { document.getElementById("sectionLeft").style.left = "0"; document.getElementById("sectionMiddle").style.left = "10%"; document.getElementById("sectionRight").style.left = "20%"; document.getElementById("titleLeft").style.left = "0"; document.getElementById("titleMiddle").style.left = "0"; document.getElementById("titleRight").style.left = "40%"; }
$(function() { var toc = $('.toc-link'), sidebar = $('#sidebar'), main = $('#main'), menu = $('#menu'), x1, y1; // run this function after pjax load. var afterPjax = function() { // open links in new tab. $('#main').find('a').filter(function() { return this.hostname != window.location.hostname; }).attr('target', '_blank'); // discus comment. (function() { var dsq = document.createElement('script'); dsq.type = 'text/javascript'; dsq.async = true; dsq.src = '//devwayne' + '.disqus.com/embed.js'; (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(dsq); })(); // your scripts }; afterPjax(); // NProgress NProgress.configure({ showSpinner: false }); // Pjax $(document).pjax('#sidebar-avatar, .toc-link', '#main', { fragment: '#main', timeout: 3000 }); $(document).on({ 'pjax:click': function() { NProgress.start(); main.removeClass('fadeIn'); }, 'pjax:end': function() { afterPjax(); NProgress.done(); main.scrollTop(0).addClass('fadeIn'); menu.add(sidebar).removeClass('open'); } }); // Tags Filter $('#sidebar-tags').on('click', '.sidebar-tag', function() { var filter = $(this).data('filter'); if (filter === 'all') { toc.fadeIn(350); } else { toc.hide(); $('.toc-link[data-tags~=' + filter + ']').fadeIn(350); } $(this).addClass('active').siblings().removeClass('active'); }); // Menu menu.on('click', function() { $(this).add(sidebar).toggleClass('open'); }); });
// @flow import SRStudyTaskEditor from '../js/components/screens/SRStudyTaskEditor' test('input title label visibility', () => { // hidden at launch when not readonly // hidden when place text input placeholder is still visible }) test('Added SRSpacedRepetition properties', () => { // expect(.easinessFactor).toBeCloseTo(2.5) // expect(.interval).toBe(1) // expect(.repetition).toBe(0) }) test('Check default edit UI elements properties', () => { // when editable: default selected date, intesity // when readonly: not editable, edit button, delete button, visible rating history }) test('Custom selected date', () => { }) test('', () => { })
this.NesDb = this.NesDb || {}; NesDb[ '7974126FFE8C5C064D6A0BDDA14646F874FA7109' ] = { "$": { "name": "Dokuganryuu Masamune", "altname": "独眼竜政宗", "class": "Licensed", "subclass": "3rd-Party", "catalog": "NAM-DG-5500", "publisher": "Namco", "developer": "Namco", "region": "Japan", "players": "1", "date": "1988-04-05" }, "cartridge": [ { "$": { "system": "Famicom", "crc": "10C8F2FA", "sha1": "7974126FFE8C5C064D6A0BDDA14646F874FA7109", "dump": "ok", "dumper": "bootgod", "datedumped": "2007-05-20" }, "board": [ { "$": { "type": "NAMCOT-163", "pcb": "60-12", "mapper": "19" }, "prg": [ { "$": { "size": "128k", "crc": "96533999", "sha1": "1FA339A59832562A3ACD1B524F6E41ED125486BF" } } ], "chr": [ { "$": { "size": "128k", "crc": "C73DD1AA", "sha1": "6A841634C15AD5EA3562572224F662D1C910CF88" } } ], "wram": [ { "$": { "size": "8k", "battery": "1" } } ], "chip": [ { "$": { "type": "<163>" } } ] } ] } ] };
'use strict'; /* * Module dependencies */ export default class Index{ //Constructor de la clase constructor(){ } }
'use strict'; const _ = require('lodash'); const Bluebird = require('bluebird'); const request = Bluebird.promisifyAll(require('request')); const BASE_URL = 'https://api.test.rb.is/v1/'; function createClaim(token, phoneNumber) { return request.getAsync({ url: `${BASE_URL}/accounts/identifier?identifierId=${phoneNumber}`, json: true, headers: { Authorization: `Bearer ${token}` } }) .then(res => { if (res.statusCode === 404) { return null; } return res.body; }); } module.exports = { createClaim };
"use strict"; var flatMap = function (arr, fn) { return Array.prototype.concat.apply([], arr.map(fn)); }; var xmlQuery = function (ast) { var nodes = Array.isArray(ast) ? ast : (ast ? [ast] : []); var length = nodes.length; var get = function (index) { return nodes[index]; }; var children = function () { return xmlQuery(flatMap(nodes, function (node) { return node.children; })); }; var findInNode = function (node, sel) { var res = (node.name === sel) ? [node] : []; return res.concat(flatMap(node.children, function (node) { return findInNode(node, sel); })); }; var find = function (sel) { return xmlQuery(flatMap(nodes, function (node) { return findInNode(node, sel); })); }; var has = function (sel) { if (nodes.length === 0) { return false; } if (nodes.some(function (node) { return node.name === sel; })) { return true; } return children().has(sel); }; var attr = function (name) { if (length) { var attrs = nodes[0].attributes; return name ? attrs[name] : attrs; } }; var eq = function (index) { return xmlQuery(nodes[index]); }; var first = function () { return eq(0); }; var last = function () { return eq(length - 1); }; var map = function (fn) { return nodes.map(fn); }; var each = function (fn) { return nodes.forEach(fn); }; var size = function () { return length; }; var prop = function (name) { var node = get(0); if (node) { return node[name]; } }; var text = function () { var res = ''; each(function (node) { if (node.type === 'text') { res += node.value; } else { res += xmlQuery(node).children().text(); } }); return res; }; return { attr: attr, children: children, each: each, eq: eq, find: find, has: has, first: first, get: get, last: last, length: length, map: map, prop: prop, size: size, text: text, ast: ast, }; }; module.exports = xmlQuery;
define({ "module-appland": { "projectName": 'Project Name' } });
/* | Ast minus assignment ( -= ) */ /* | The jion definition. */ if( JION ) { throw{ id : 'jion$ast_minusAssign', attributes : { left : { comment : 'left-hand side', type : require( '../typemaps/astExpression' ) }, right : { comment : 'right-hand side', type : require( '../typemaps/astExpression' ) } } }; } /* | Capsule */ (function() { 'use strict'; var ast_minusAssign, prototype; ast_minusAssign = require( '../this' )( module, 'ouroboros' ); prototype = ast_minusAssign.prototype; /**/if( CHECK ) /**/{ /**/ var /**/ util; /**/ /**/ util = require( 'util' ); /**/ /*** / **** | Custom inspect **** / ***/ prototype.inspect = /**/ function( /**/ depth, /**/ opts /**/ ) /**/ { /**/ var /**/ postfix, /**/ result; /**/ /**/ if( !opts.ast ) /**/ { /**/ result = 'ast{ '; /**/ /**/ postfix = ' }'; /**/ } /**/ else /**/ { /**/ result = postfix = ''; /**/ } /**/ /**/ opts.ast = true; /**/ /**/ result += '( ' + util.inspect( this.left, opts ) + ' )'; /**/ /**/ result += ' -= '; /**/ /**/ result += '( ' + util.inspect( this.right, opts ) + ' )'; /**/ /**/ return result + postfix; /**/ }; /**/} } )( );
/* * poeditor_htmid * * This is an adaptation of a plugin found https://github.com/Philoozushi/grunt-poeditor-pz . This plugin will download the localizations for a particular project ID and then get all of the string associated with the project. This plugin is to be used in combination with the other htmid plugins. * * Copyright (c) 2016 Codin Pangell * Licensed under the MIT license. */ 'use strict'; module.exports = function(grunt) { // Project configuration. grunt.initConfig({ jshint: { all: [ 'Gruntfile.js', 'tasks/*.js', '<%= nodeunit.tests %>' ], options: { jshintrc: '.jshintrc' } }, // Before generating any new files, remove any previously-created files. clean: { tests: ['tmp'] }, // Configuration to be run (and then tested). poeditor_htmid: { }, // Unit tests. nodeunit: { tests: ['test/*_test.js'] } }); // Actually load this plugin's task(s). grunt.loadTasks('tasks'); // These plugins provide necessary tasks. grunt.loadNpmTasks('grunt-contrib-jshint'); grunt.loadNpmTasks('grunt-contrib-clean'); grunt.loadNpmTasks('grunt-contrib-nodeunit'); // Whenever the "test" task is run, first clean the "tmp" dir, then run this // plugin's task(s), then test the result. grunt.registerTask('test', ['clean', poeditor_htmid, 'nodeunit']); // By default, lint and run all tests. grunt.registerTask('default', ['jshint', 'test']); };
var assign = require('object-assign'); var number = require('as-number'); module.exports = function (THREE) { return function (opt) { opt = opt || {}; var ret = assign({ transparent: true, uniforms: { thickness: { type: 'f', value: number(opt.thickness, 0.1) }, opacity: { type: 'f', value: number(opt.opacity, 1.0) }, diffuse: { type: 'c', value: new THREE.Color(opt.diffuse) }, time: { type: 'f', value: 0 } }, vertexShader: [ 'uniform float thickness;', 'attribute float lineMiter;', 'attribute vec2 lineNormal;', 'attribute float lineDistance;', 'varying float edge;', 'varying float lineU;', 'uniform float time;', 'void main() {', 'edge = sign(lineMiter);', 'lineU = lineDistance;', 'vec3 pointPos = position.xyz + vec3(lineNormal * thickness/2.0 * lineMiter, 0.0);', 'gl_Position = projectionMatrix * modelViewMatrix * vec4( pointPos, 1.0 );', '}' ].join('\n'), fragmentShader: [ 'varying float edge;', 'varying float lineU;', 'uniform float opacity;', 'uniform float time;', 'uniform vec3 diffuse;', 'void main() {', 'float lineV = 1.0 - abs(edge);', 'lineV = smoothstep(0.0, 0.8, lineV);', 'float radial = lineU * sin(time + lineU*2.0);', 'gl_FragColor = vec4(vec3(lineV), 1.0);', 'gl_FragColor.a *= opacity * radial * lineV;', '}' ].join('\n') }, opt); // remove to satisfy r73 delete ret.thickness; delete ret.opacity; delete ret.diffuse; var threeVers = (parseInt(THREE.REVISION, 10) || 0) | 0; if (threeVers < 72) { // Old versions need to specify shader attributes ret.attributes = { lineMiter: { type: 'f', value: 0 }, lineDistance: { type: 'f', value: 0 }, lineNormal: { type: 'v2', value: new THREE.Vector2() } }; } return ret; }; };
var through = require('through2'), falafel = require('falafel'), fs = require('fs') module.exports = lintroller function lintroller(_checks) { var count = 0, files = [], stream = through(add_files, noop), checks = _checks || [] checks.forEach(resolve_check) checks = checks.filter(Boolean) return stream function add_files(chunk, enc, next) { files.push(chunk.toString()) if (!count) { count++ read_file(files.shift()) } next() } function read_file(filename) { fs.readFile(filename, 'utf8', process_file) function process_file(err, data) { if (err) process.stdout.write('whoopsie goldberg') && process.exit(1) falafel('' + data, check_node) if (!files.length) return finish() count++ read_file(files.shift()) } } function check_node(node) { checks.forEach(run_check) function run_check(check) { if (check.selectors.some(match_selector)) { check.rules.forEach(compare_and_count) } function match_selector(selector) { return selector(node) } function compare_and_count(rule) { if (rule.test(node)) rule.count++ } } } function finish() { process.stdout.write('processed ' + count + ' files\n') console.dir(checks) } } function resolve_check(check) { if (typeof check === 'string') { try { check = require(check) } catch(e) { check = false return } } if (!check.rules || !check.rules.length) { check = false return } check.rules.forEach(validate_rules) check.rules = check.rules.filter(Boolean) function validate_rules(rule) { if (!rule.name || !rule.test || typeof rule.test !== 'function') { rule = false return } rule.description = rule.description || rule.name rule.count = rule.count || 0 } } function noop() {}
const _ = require("lodash"); const logger = require("../util/logger"); const MANDATORY_ENV_VARS = [ "PORT", "FB_PAGE_ACCESS_TOKEN", "FB_VERIFICATION_TOKEN", "VIRTUAL_ASSISTANT_NAME", "SOCIALMINER_HOST", "SOCIALMINER_CHAT_FEED_ID", "CCX_QUEUE_ID", ]; module.exports = { /** * Validates the deployed environment to ensure * all required variables are defined. If not, it * aborts the entire application. */ validateEnvironment: () => { _.each(MANDATORY_ENV_VARS, (variable) => { if (_.isUndefined(process.env[variable]) || _.isEmpty(_.trim(process.env[variable]))) { throw new ReferenceError(`SEVERE ERROR: MISSING/INVALID environment variable value: ${variable}`); } }); }, /** * Logs an error with its stack trace * * @param {*} err * @param {String} msg */ logErrorWithStackTrace: (err, msg) => { logger.error("Something went wrong.", err, new Error(msg).stack); }, /** * Properly decode a URLEncoded string * * @param {String} str */ decodeString: (str) => { let decodedStr = decodeURIComponent(str.replace(/\+/g, " ")); decodedStr = decodedStr.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;") .replace(/'/g, "&#x27;") .replace(/\//g, "&#x2f;"); return decodedStr; }, };
import Inflector from 'ember-inflector'; const { inflector } = Inflector; inflector.uncountable('knowledge'); inflector.uncountable('account-access'); export default { };
'use strict'; var build = "build"; // ビルド結果が出力されるディレクトリ var tmp = ".tmp"; // Sassコンパイルで作成されるcssのテンポラリーファイルの場所 var src = 'src'; // ソースコードの場所 module.exports = { build: build, tmp: tmp, src: src, sf: { //Salesforceのビルド結果が出力されるディレクトリ sfbuild: build + "/sf", // デプロイする静的リソースの名前 resourceName: "vfResource", // apex:pageタグの属性値 apexPageOption: { // デフォルト値、すべてのページに適用されます 'default': { "docType": "html-5.0", "showHeader": false, "standardStyleSheets": false }, // ページごとの設定、デフォルト値より優先されます 'topPage': { controller: 'RemoteActionTestController' } }, // 開発環境の認証情報 development: { user: '<Your salesforce email address>', pass: '<Your salesforce password>', token: '<Your salesforce access token>', apiVersion: '30.0' }, // SandBox環境の認証情報 sandbox: { user: '<Your salesforce email address>', pass: '<Your salesforce password>', token: '<Your salesforce access token>', apiVersion: '30.0' }, // Visualforceページと静的リソースの取得先 retrieve: { user: '<Your salesforce email address>', pass: '<Your salesforce password>', token: '<Your salesforce access token>', apiVersion: '30.0' } }, script: { // JavaScriptの結合順序を指定します src: [ src + '/js/main.js', src + '/js/chart/*.js', src + '/js/controller/*.js' ] }, css: { // CSSの結合順序を指定します Sassはコンパイル後のcssを指定します src: [ src + "/css/normalize.css", tmp + "/css/main.css" ] } }
/** * Created by 文琪 on 2015/3/3. * 用于读取云大主页上的通知,并在数据库中保存发送标识。 */ var MongoClient = require('mongodb').MongoClient, ObjectID = require('mongodb').ObjectID; var array = require('array'); var uuid = require('node-uuid'); var date = require('date-extended'); var sa = require('superagent'); var cheer = require('cheerio'); module.exports = function(connString){ return { /** * 从数据库中读取尚未发送的通知 * @param options * @param callback */ getNotSendNotices: function (options, callback) { MongoClient.connect(connString, function (err, db) { var notice = db.collection('ynu_notices'); at.find({ 'sended': false }).toArray(function (err, notices) { db.close(); callback(err, notices); }); }); }, /** * 从网页抓取通知,并标记为未发送 * @param callback */ catchNotices: function (callback) { sa.get('http://www.ynu.edu.cn/xwzx/xygg/index.html').end(function(res2){ if(res2.ok){ var $ = cheer.load(res2.text); var articles = []; $('dl.right ul li').each(function(i, li){ if(i > 5) return; var a = $(li).find('a'); articles.push({ title: a.text().trim(), picurl: '', 'sended': false, url: a.attr('href') }); }); MongoClient.connect(connString, function (err, db) { var notices = db.collection('ynu_notices'); var count = 0; array(articles).each(function(article){ notices.update({ url: article }, article, {upsert: true}, function (err, doc) { if(++count === articles.length){ db.close(); callback(err, articles); } }); }); }); } }); } }; }
const { ALCore } = require('./lib/AurelionCore'); ALCore.startApp();
define([ "dojo/_base/declare", // declare "dojo/dom-construct", // domConstruct.create "dojo/has", "dojo/_base/lang", // lang.hitch "dojo/on", "dojo/_base/window", // win.body "../Viewport" ], function(declare, domConstruct, has, lang, on, win, Viewport){ // module: // dijit/form/_ExpandingTextAreaMixin // feature detection, true for mozilla and webkit has.add("textarea-needs-help-shrinking", function(){ var body = win.body(), // note: if multiple documents exist, doesn't matter which one we use te = domConstruct.create('textarea', { rows:"5", cols:"20", value: ' ', style: {zoom:1, fontSize:"12px", height:"96px", overflow:'hidden', visibility:'hidden', position:'absolute', border:"5px solid white", margin:"0", padding:"0", boxSizing: 'border-box', MsBoxSizing: 'border-box', WebkitBoxSizing: 'border-box', MozBoxSizing: 'border-box' } }, body, "last"); var needsHelpShrinking = te.scrollHeight >= te.clientHeight; body.removeChild(te); return needsHelpShrinking; }); return declare("dijit.form._ExpandingTextAreaMixin", null, { // summary: // Mixin for textarea widgets to add auto-expanding capability _setValueAttr: function(){ this.inherited(arguments); this.resize(); }, postCreate: function(){ this.inherited(arguments); var textarea = this.textbox; textarea.style.overflowY = "hidden"; this.own(on(textarea, "focus, resize", lang.hitch(this, "_resizeLater"))); }, startup: function(){ this.inherited(arguments); this.own(Viewport.on("resize", lang.hitch(this, "_resizeLater"))); this._resizeLater(); }, _onInput: function(e){ this.inherited(arguments); this.resize(); }, _estimateHeight: function(){ // summary: // Approximate the height when the textarea is invisible with the number of lines in the text. // Fails when someone calls setValue with a long wrapping line, but the layout fixes itself when the user clicks inside so . . . // In IE, the resize event is supposed to fire when the textarea becomes visible again and that will correct the size automatically. // var textarea = this.textbox; // #rows = #newlines+1 textarea.rows = (textarea.value.match(/\n/g) || []).length + 1; }, _resizeLater: function(){ this.defer("resize"); }, resize: function(){ // summary: // Resizes the textarea vertically (should be called after a style/value change) var textarea = this.textbox; function textareaScrollHeight(){ var empty = false; if(textarea.value === ''){ textarea.value = ' '; empty = true; } var sh = textarea.scrollHeight; if(empty){ textarea.value = ''; } return sh; } if(textarea.style.overflowY == "hidden"){ textarea.scrollTop = 0; } if(this.busyResizing){ return; } this.busyResizing = true; if(textareaScrollHeight() || textarea.offsetHeight){ var newH = textareaScrollHeight() + Math.max(textarea.offsetHeight - textarea.clientHeight, 0); var newHpx = newH + "px"; if(newHpx != textarea.style.height){ textarea.style.height = newHpx; textarea.rows = 1; // rows can act like a minHeight if not cleared } if(has("textarea-needs-help-shrinking")){ var origScrollHeight = textareaScrollHeight(), newScrollHeight = origScrollHeight, origMinHeight = textarea.style.minHeight, decrement = 4, // not too fast, not too slow thisScrollHeight, origScrollTop = textarea.scrollTop; textarea.style.minHeight = newHpx; // maintain current height textarea.style.height = "auto"; // allow scrollHeight to change while(newH > 0){ textarea.style.minHeight = Math.max(newH - decrement, 4) + "px"; thisScrollHeight = textareaScrollHeight(); var change = newScrollHeight - thisScrollHeight; newH -= change; if(change < decrement){ break; // scrollHeight didn't shrink } newScrollHeight = thisScrollHeight; decrement <<= 1; } textarea.style.height = newH + "px"; textarea.style.minHeight = origMinHeight; textarea.scrollTop = origScrollTop; } textarea.style.overflowY = textareaScrollHeight() > textarea.clientHeight ? "auto" : "hidden"; if(textarea.style.overflowY == "hidden"){ textarea.scrollTop = 0; } }else{ // hidden content of unknown size this._estimateHeight(); } this.busyResizing = false; } }); });
describe('Reinforced Plate', function() { integration(function() { describe('Reinforced Plate\'s constant ability', function() { beforeEach(function() { this.setupTest({ phase: 'conflict', player1: { inPlay: ['brash-samurai', 'doji-whisperer'], hand: ['reinforced-plate', 'way-of-the-scorpion'] }, player2: { inPlay: ['doomed-shugenja'], hand: ['kirei-ko', 'way-of-the-scorpion', 'assassination'] } }); this.brash = this.player1.findCardByName('brash-samurai'); this.whisperer = this.player1.findCardByName('doji-whisperer'); this.p1scorpion = this.player1.findCardByName('way-of-the-scorpion'); this.p2scorpion = this.player2.findCardByName('way-of-the-scorpion'); this.kireiko = this.player2.findCardByName('kirei-ko'); this.reinforcedPlate = this.player1.playAttachment('reinforced-plate', this.brash); this.assassination = this.player2.findCardByName('assassination'); this.noMoreActions(); }); it('should make its wearer immune to opponent events during a military conflict', function() { this.initiateConflict({ type: 'military', attackers: [this.brash], defenders: [] }); expect(this.player2).toHavePrompt('Conflict Action Window'); this.player2.clickCard(this.p2scorpion); expect(this.player2).toHavePrompt('Conflict Action Window'); this.player2.pass(); this.player1.clickCard(this.brash); expect(this.player2).not.toBeAbleToSelect(this.kireiko); }); it('should not make its wearer immune to own events during a military conflict', function() { this.initiateConflict({ type: 'military', attackers: [this.brash], defenders: [] }); this.player2.pass(); this.player1.clickCard(this.p1scorpion); expect(this.player1).toBeAbleToSelect(this.brash); this.player1.clickCard(this.brash); expect(this.brash.isDishonored).toBe(true); }); it('should not make its wearer immune to opponent events during a political conflict', function() { this.initiateConflict({ type: 'political', attackers: [this.brash], defenders: [] }); expect(this.player2).toHavePrompt('Conflict Action Window'); this.player2.clickCard(this.p2scorpion); expect(this.player2).toBeAbleToSelect(this.brash); this.player2.clickCard(this.brash); expect(this.brash.isDishonored).toBe(true); this.player1.clickCard(this.brash); expect(this.player2).toBeAbleToSelect(this.kireiko); this.player2.clickCard(this.kireiko); expect(this.brash.bowed).toBe(true); }); it('should not make its wearer immune to opponent events if not participating', function() { this.initiateConflict({ type: 'military', attackers: [this.whisperer], defenders: [] }); expect(this.player2).toHavePrompt('Conflict Action Window'); this.player2.clickCard(this.assassination); expect(this.player2).toBeAbleToSelect(this.brash); this.player2.clickCard(this.brash); expect(this.brash.location).toBe('dynasty discard pile'); }); }); }); });
'use strict' const path = require('path') const execa = require('execa') const merge = require('merge-options') const { pkg } = require('./utils') /** * @typedef {import("execa").Options} ExecaOptions * @typedef {import("./types").GlobalOptions} GlobalOptions * @typedef {import("./types").DependencyCheckOptions} DependencyCheckOptions */ /** * @param {any} arr1 * @param {any} arr2 */ const isDefaultInput = (arr1, arr2) => JSON.stringify(arr1) === JSON.stringify(arr2) /** * Check dependencies * * @param {GlobalOptions & DependencyCheckOptions} argv - Command line arguments passed to the process. * @param {ExecaOptions} [execaOptions] - execa options. */ const check = (argv, execaOptions) => { const forwardOptions = argv['--'] ? argv['--'] : [] const input = argv.productionOnly && isDefaultInput(argv.fileConfig.dependencyCheck.input, argv.input) ? argv.fileConfig.dependencyCheck.productionInput : argv.input const noDev = argv.productionOnly ? ['--no-dev'] : [] const ignore = argv.ignore .concat(argv.fileConfig.dependencyCheck.ignore) .reduce((acc, i) => acc.concat('-i', i), /** @type {string[]} */ ([])) const args = [...input, '--missing', ...noDev, ...ignore] if (pkg.type === 'module') { // use detective-es6 for js, regular detective for cjs args.push( '--extensions', 'cjs:detective', '--extensions', 'js:detective-es6' ) } return execa( 'dependency-check', [...args, ...forwardOptions], merge( { localDir: path.join(__dirname, '..'), preferLocal: true }, execaOptions ) ) } module.exports = { check }
import { SimpleSchema } from 'meteor/aldeed:simple-schema'; import organSiteCategories from './organSiteCategories'; import riskEstimateSchema from './riskEstimateSchema'; import { isNumericishString } from '/imports/api/validators'; export default { organSiteCategory: { label: 'Organ site', type: String, popoverText: 'Organ site (controlled vocabulary - select one from list)', allowedValues: organSiteCategories.options, forceRequiredSymbol: true, typeaheadMethod: 'searchOrganSiteCategories', }, organSite: { label: 'Organ site details', type: String, optional: true, popoverText: 'Optional to further specify details, e.g ICD code, subtype', typeaheadMethod: 'searchOrganSite', }, effectMeasure: { label: 'Measure of effect', type: String, min: 1, popoverText: 'Risk metric used to display results (SMR, RR, etc.)', typeaheadMethod: 'searchEffectMeasure', }, effectUnits: { label: 'Units of effect measurement', type: String, optional: true, popoverText: 'Units, if relevant (e.g., risk per 10 μg/m3)', typeaheadMethod: 'searchEffectUnits', }, stratum: { label: 'Stratum (if relevant)', type: String, optional: true, popoverText: 'e.g.: men only, women only', typeaheadMethod: 'searchStratum', }, trendTest: { label: 'Trend p-value', type: String, optional: true, custom: isNumericishString, popoverText: 'Provide p-value for trend-test when reported', }, riskEstimates: { type: [riskEstimateSchema], minCount: 1, }, covariates: { label: 'Covariates controlled', type: [String], minCount: 1, popoverText: 'List all covariates which were controlled by matching or adjustment in the analysis reported. Enter each covariate individually, and then press <enter> to add it to the list. If no covariates were specified, add \'not-specified\'', typeaheadMethod: 'searchCovariates', }, covariatesControlledText: { label: 'Covariates controlled notes', type: String, optional: true, popoverText: 'Further describe how covariates were controlled, if needed, such as details on matching methodology or adjustments made', textAreaRows: 4, }, notes: { label: 'General notes', type: String, optional: true, popoverText: 'Note issues related to appropriateness of comparison groups, potential for uncontrolled confounding, etc. (e.g. matching criteria for case-control studies)', textAreaRows: 4, }, parent_id: { type: SimpleSchema.RegEx.Id, denyUpdate: true, }, };
var Util = { addClass: function(cl, el){ if( el.className.trim() == '' || el.className.indexOf(cl) == -1 ){ el.className += ' '+ cl; } }, hasClass: function(cl, el){ return el.className.split(' ').indexOf( cl.replace('.', '') ) > -1; }, removeClass: function(cl, el){ if( el.className.trim() != '' && el.className.indexOf(cl) > -1 ){ el.className = el.className.replace( new RegExp('\\s?'+ cl), '' ); } }, closest: function(cl, el){ cl = cl.replace('.', ''); while( el.parentNode ){ el = el.parentNode; if( Util.hasClass(cl, el) ){ return el; break; } } return false; }, newDomElement: function(str){ var wrapper = document.createElement('div'); wrapper.innerHTML = str; return wrapper.childNodes; }, replaceElement: function(oldEl, newEl){ if( newEl && newEl.length && newEl.length === 1 ) newEl = newEl[0]; if( newEl && newEl.length ){ for( var i=0; i<newEl.length; i++ ){ oldEl.parentNode.insertBefore(newEl[i], oldEl.nextSibling); } }else{ oldEl.parentNode.insertBefore(newEl, oldEl.nextSibling); } oldEl.parentNode.removeChild(oldEl); return newEl; }, ajax: function(opts){ var req = new XMLHttpRequest(); var reqType = (opts.type || opts.form.method).toUpperCase(); var reqURL = opts.url || opts.form.action; var reqData = buildFormData(); if( reqType == 'GET' ){ reqURL += (( reqURL.indexOf('?') > -1 ) ? '&' : '?') + reqData; } function addObjectData(data, formData){ var buildStr = !formData; if( buildStr ) formData = []; for( var key in data ){ if( data.hasOwnProperty(key) ){ var dat = data[key]; if( dat instanceof Array ){ for( var i=0; i<dat.length; i++ ){ var item = ( dat[i] instanceof Object || dat[i] instanceof Array ) ? JSON.stringify(dat[i]) : dat[i]; if( buildStr ) formData.push( key +'[]='+ item ); else formData.append( key+'[]', item ); } }else if( dat instanceof Object ){ if( buildStr ) formData.push( key +'='+ JSON.stringify(dat) ); else formData.append( key, JSON.stringify(dat) ); }else{ if( buildStr ) formData.push( key +'='+ dat ); else formData.append( key, dat ); } } } if( buildStr ){ return formData.join('&'); } } function buildFormData(){ var formData; if( reqType == 'GET' ){ formData = ''; }else{ if( opts.form && !opts.formData ){ formData = new FormData( opts.form ); }else if( opts.formData ){ formData = opts.formData; }else{ formData = new FormData(); } } if( opts.data ){ if( typeof formData == 'string' ) formData = addObjectData(opts.data); else addObjectData(opts.data, formData); } return formData; } var promise = new Promise(function(resolve, reject){ req.open( reqType, reqURL, true ); if( opts.onProgress ){ req.upload.addEventListener('progress', function(ev){ var uploadProgress = (ev.loaded / ev.total) * 100; opts.onProgress( uploadProgress ); if( uploadProgress == 100 ){ if( opts.onProgressComplete ) opts.onProgressComplete(); } }, false); } req.onreadystatechange = function(){ if( req.readyState == 4 ){ var resp; if( req.status == 200 ){ try{ resp = JSON.parse(req.responseText); }catch( error ){ resp = req.responseText; } resolve( resp ); if( opts.onSuccess ) opts.onSuccess( resp ); }else{ try{ resp = JSON.parse(req.responseText); }catch( error ){ resp = req.responseText; } reject( resp ); if( opts.onError ) opts.onError( resp, req.status, req.statusText ); } } }; if( reqType == 'GET' ) req.send(); else req.send( reqData ); }); return promise; } };
/* Copyright (c) 2006-2013 by OpenLayers Contributors (see authors.txt for * full list of contributors). Published under the 2-clause BSD license. * See license.txt in the OpenLayers distribution or repository for the * full text of the license. */ /** * @requires OpenLayers/Control.js * @requires OpenLayers/Handler/Drag.js * @requires OpenLayers/Handler/Feature.js */ /** * Class: OpenLayers.Control.DragFeature * The DragFeature control moves a feature with a drag of the mouse. Create a * new control with the <OpenLayers.Control.DragFeature> constructor. * * Inherits From: * - <OpenLayers.Control> */ OpenLayers.Control.DragFeature = OpenLayers.Class(OpenLayers.Control, { /** * APIProperty: geometryTypes * {Array(String)} To restrict dragging to a limited set of geometry types, * send a list of strings corresponding to the geometry class names. */ geometryTypes: null, /** * APIProperty: onStart * {Function} Define this function if you want to know when a drag starts. * The function should expect to receive two arguments: the feature * that is about to be dragged and the pixel location of the mouse. * * Parameters: * feature - {<OpenLayers.Feature.Vector>} The feature that is about to be * dragged. * pixel - {<OpenLayers.Pixel>} The pixel location of the mouse. */ onStart: function(feature, pixel) {}, /** * APIProperty: onDrag * {Function} Define this function if you want to know about each move of a * feature. The function should expect to receive two arguments: the * feature that is being dragged and the pixel location of the mouse. * * Parameters: * feature - {<OpenLayers.Feature.Vector>} The feature that was dragged. * pixel - {<OpenLayers.Pixel>} The pixel location of the mouse. */ onDrag: function(feature, pixel) {}, /** * APIProperty: onComplete * {Function} Define this function if you want to know when a feature is * done dragging. The function should expect to receive two arguments: * the feature that is being dragged and the pixel location of the * mouse. * * Parameters: * feature - {<OpenLayers.Feature.Vector>} The feature that was dragged. * pixel - {<OpenLayers.Pixel>} The pixel location of the mouse. */ onComplete: function(feature, pixel) {}, /** * APIProperty: onEnter * {Function} Define this function if you want to know when the mouse * goes over a feature and thereby makes this feature a candidate * for dragging. * * Parameters: * feature - {<OpenLayers.Feature.Vector>} The feature that is ready * to be dragged. */ onEnter: function(feature) {}, /** * APIProperty: onLeave * {Function} Define this function if you want to know when the mouse * goes out of the feature that was dragged. * * Parameters: * feature - {<OpenLayers.Feature.Vector>} The feature that was dragged. */ onLeave: function(feature) {}, /** * APIProperty: documentDrag * {Boolean} If set to true, mouse dragging will continue even if the * mouse cursor leaves the map viewport. Default is false. */ documentDrag: false, /** * Property: layer * {<OpenLayers.Layer.Vector>} */ layer: null, /** * Property: feature * {<OpenLayers.Feature.Vector>} */ feature: null, /** * Property: dragCallbacks * {Object} The functions that are sent to the drag handler for callback. */ dragCallbacks: {}, /** * Property: featureCallbacks * {Object} The functions that are sent to the feature handler for callback. */ featureCallbacks: {}, /** * Property: lastPixel * {<OpenLayers.Pixel>} */ lastPixel: null, /** * Constructor: OpenLayers.Control.DragFeature * Create a new control to drag features. * * Parameters: * layer - {<OpenLayers.Layer.Vector>} The layer containing features to be * dragged. * options - {Object} Optional object whose properties will be set on the * control. */ initialize: function(layer, options) { OpenLayers.Control.prototype.initialize.apply(this, [options]); this.layer = layer; this.handlers = { drag: new OpenLayers.Handler.Drag( this, OpenLayers.Util.extend({ down: this.downFeature, move: this.moveFeature, up: this.upFeature, out: this.cancel, done: this.doneDragging }, this.dragCallbacks), { documentDrag: this.documentDrag } ), feature: new OpenLayers.Handler.Feature( this, this.layer, OpenLayers.Util.extend({ // 'click' and 'clickout' callback are for the mobile // support: no 'over' or 'out' in touch based browsers. click: this.clickFeature, clickout: this.clickoutFeature, over: this.overFeature, out: this.outFeature }, this.featureCallbacks), {geometryTypes: this.geometryTypes} ) }; }, /** * Method: clickFeature * Called when the feature handler detects a click-in on a feature. * * Parameters: * feature - {<OpenLayers.Feature.Vector>} */ clickFeature: function(feature) { if (this.handlers.feature.touch && !this.over && this.overFeature(feature)) { this.handlers.drag.dragstart(this.handlers.feature.evt); // to let the events propagate to the feature handler (click callback) this.handlers.drag.stopDown = false; } }, /** * Method: clickoutFeature * Called when the feature handler detects a click-out on a feature. * * Parameters: * feature - {<OpenLayers.Feature.Vector>} */ clickoutFeature: function(feature) { if (this.handlers.feature.touch && this.over) { this.outFeature(feature); this.handlers.drag.stopDown = true; } }, /** * APIMethod: destroy * Take care of things that are not handled in superclass */ destroy: function() { this.layer = null; OpenLayers.Control.prototype.destroy.apply(this, []); }, /** * APIMethod: activate * Activate the control and the feature handler. * * Returns: * {Boolean} Successfully activated the control and feature handler. */ activate: function() { return (this.handlers.feature.activate() && OpenLayers.Control.prototype.activate.apply(this, arguments)); }, /** * APIMethod: deactivate * Deactivate the control and all handlers. * * Returns: * {Boolean} Successfully deactivated the control. */ deactivate: function() { // the return from the handlers is unimportant in this case this.handlers.drag.deactivate(); this.handlers.feature.deactivate(); this.feature = null; this.dragging = false; this.lastPixel = null; OpenLayers.Element.removeClass( this.map.viewPortDiv, this.displayClass + "Over" ); return OpenLayers.Control.prototype.deactivate.apply(this, arguments); }, /** * Method: overFeature * Called when the feature handler detects a mouse-over on a feature. * This activates the drag handler. * * Parameters: * feature - {<OpenLayers.Feature.Vector>} The selected feature. * * Returns: * {Boolean} Successfully activated the drag handler. */ overFeature: function(feature) { var activated = false; if(!this.handlers.drag.dragging) { this.feature = feature; this.handlers.drag.activate(); activated = true; this.over = true; OpenLayers.Element.addClass(this.map.viewPortDiv, this.displayClass + "Over"); this.onEnter(feature); } else { if(this.feature.id == feature.id) { this.over = true; } else { this.over = false; } } return activated; }, /** * Method: downFeature * Called when the drag handler detects a mouse-down. * * Parameters: * pixel - {<OpenLayers.Pixel>} Location of the mouse event. */ downFeature: function(pixel) { this.lastPixel = pixel; this.onStart(this.feature, pixel); }, /** * Method: moveFeature * Called when the drag handler detects a mouse-move. Also calls the * optional onDrag method. * * Parameters: * pixel - {<OpenLayers.Pixel>} Location of the mouse event. */ moveFeature: function(pixel) { var res = this.map.getResolution(); this.feature.geometry.move(res * (pixel.x - this.lastPixel.x), res * (this.lastPixel.y - pixel.y)); this.layer.drawFeature(this.feature); this.lastPixel = pixel; this.onDrag(this.feature, pixel); }, /** * Method: upFeature * Called when the drag handler detects a mouse-up. * * Parameters: * pixel - {<OpenLayers.Pixel>} Location of the mouse event. */ upFeature: function(pixel) { if(!this.over) { this.handlers.drag.deactivate(); } }, /** * Method: doneDragging * Called when the drag handler is done dragging. * * Parameters: * pixel - {<OpenLayers.Pixel>} The last event pixel location. If this event * came from a mouseout, this may not be in the map viewport. */ doneDragging: function(pixel) { this.onComplete(this.feature, pixel); }, /** * Method: outFeature * Called when the feature handler detects a mouse-out on a feature. * * Parameters: * feature - {<OpenLayers.Feature.Vector>} The feature that the mouse left. */ outFeature: function(feature) { if(!this.handlers.drag.dragging) { this.over = false; this.handlers.drag.deactivate(); OpenLayers.Element.removeClass( this.map.viewPortDiv, this.displayClass + "Over" ); this.onLeave(feature); this.feature = null; } else { if(this.feature.id == feature.id) { this.over = false; } } }, /** * Method: cancel * Called when the drag handler detects a mouse-out (from the map viewport). */ cancel: function() { this.handlers.drag.deactivate(); this.over = false; }, /** * Method: setMap * Set the map property for the control and all handlers. * * Parameters: * map - {<OpenLayers.Map>} The control's map. */ setMap: function(map) { this.handlers.drag.setMap(map); this.handlers.feature.setMap(map); OpenLayers.Control.prototype.setMap.apply(this, arguments); }, CLASS_NAME: "OpenLayers.Control.DragFeature" });
// Pluralize export function pluralize(length, singular, plural) { if (length == 1) { return singular } else { return plural } } // Get a single dom node by selector export function getDOMNode(selector) { const node = document.querySelectorAll(selector)[0] return node } // Create array from DOM elements list export function createDOMArray(list) { const arr = []; for (let i = 0; i < list.length; i++) { arr.push(list[i]); } return arr } // Look for parent with id export function hasParentId(target, id) { let node = target while (node !== null) { if (node.id === id) { return true } node = node.parentNode; } return false } // Pluralize export function calculateSidebarDimensions() { const sidebar = document.getElementById('sidebar') const filters = document.getElementById('filters') if (filters !== undefined) { const viewportHeight = window.innerHeight - (2 * 48) const filtersHeight = filters.scrollHeight if (filtersHeight > viewportHeight) { sidebar.classList.add('scroll-overflow') } else { sidebar.classList.remove('scroll-overflow') } } } // Visually focus element (via className) export function visuallyFocusElem(elem) { elem.classList.add('focus') } // Visually blur element (via className) export function visuallyBlurElem(elem) { elem.classList.remove('focus') } // Create fieldset id export function createFieldSetId(...args) { const id = `fieldset_${args.join('_')}` return id } // Create inlines-item id export function createInlinesItemId(...args) { const id = `inlines_item_${args.join('_')}` return id } // Get the [data-field-display-values] of a dom node with [data-field-display-name="fieldDisplayName"] export function getFieldDisplayValues(fieldDisplayName) { const node = getDOMNode(`[data-field-display-name="${fieldDisplayName}"]`) if (node !== undefined) { const fieldDisplayValues = node.getAttribute('data-field-display-values') return fieldDisplayValues } return undefined } // Toggle expanded export function toggleExpanded(id) { const handler = getDOMNode(`[aria-controls="${id}"]`) const region = document.getElementById(id) const display = handler.getAttribute('aria-expanded') === 'false' handler.setAttribute('aria-expanded', display) region.setAttribute('aria-hidden', !display) } // Close expanded export function closeExpanded(id) { const handler = getDOMNode(`[aria-controls="${id}"]`) const region = document.getElementById(id) handler.setAttribute('aria-expanded', false) region.setAttribute('aria-hidden', true) } // Show expanded export function showExpanded(id) { const handler = getDOMNode(`[aria-controls="${id}"]`) const region = document.getElementById(id) handler.setAttribute('aria-expanded', true) region.setAttribute('aria-hidden', false) } // Close all expanded export function closeAllExpanded(container) { const expandables = container.querySelectorAll('[aria-expanded]') expandables.forEach((element) => { element.setAttribute('aria-expanded', false) const region = document.getElementById(element.getAttribute('aria-controls')) region.setAttribute('aria-hidden', true) }) } // Show all expanded export function showAllExpanded(container) { const expandables = container.querySelectorAll('[aria-expanded]') expandables.forEach((element) => { element.setAttribute('aria-expanded', true) const region = document.getElementById(element.getAttribute('aria-controls')) region.setAttribute('aria-hidden', false) }) } // Format date YYYY-MM-DD export function formatDate(date) { return date.toJSON().slice(0, 10) } // Format time HH:MM:SS export function formatTime(date) { return date.toJSON().slice(11, 19) } export function formatDateTime(date) { const d = formatDate(date) const t = formatTime(date) return `${d}, ${t}` }
'use strict'; var MongoBox = require('mongobox').MongoBox, mongobox = new MongoBox(); before(function (done) { mongobox.start(function (error) { if (error) { return done(error); } global.MONGOBIRD_TEST_PORT = mongobox.options.port; done(); }); }); after(function (done) { mongobox.stop(done); });
version https://git-lfs.github.com/spec/v1 oid sha256:577cc71f3d670e7c7a12e65b775a4e4e1c92a3552bb6b5ad94a69c4bec582b61 size 67957
version https://git-lfs.github.com/spec/v1 oid sha256:344627044ea2b88e1bc840b18e4a63a9eea81e6dc19bfd280e321a47f8a9c78a size 412114
// 引入 node 的 fms 模块 var fms = require('fms') fms.run({ // Server 启动在 3000 端口 port: 3100, read: ['/demo/'] }) fms.ajax({ type: 'POST', title: '获取颜值节目列表', url: '/get_face/', request: { cid: 1 }, res: { ok: { list:[ { url: "test.html", _url: "该节目跳转链接", image: "ex/head1.jpg", _image: "节目头像", author: "桐桐宝宝", _author: "主播妮称", number: "16.7万", _number: "在线人数", webname: "虎牙", _webname: "直播平台名称拼音" }, { url: "http://www.qq.com", _url: "该节目跳转链接", image: "ex/head2.jpg", _image: "节目头像", author: "萱儿", _author: "主播妮称", number: "5633", _number: "在线人数", webname: "美拍", _webname: "直播平台名称拼音" }, { url: "http://www.baidu.com", _url: "该节目跳转链接", image: "ex/head1.jpg", _image: "节目头像", author: "桐桐宝宝", _author: "主播妮称", number: "16.7万", _number: "在线人数", webname: "虎牙", _webname: "直播平台名称拼音" }, { url: "http://www.qq.com", _url: "该节目跳转链接", image: "ex/head2.jpg", _image: "节目头像", author: "萱儿", _author: "主播妮称", number: "5633", _number: "在线人数", webname: "美拍", _webname: "直播平台名称拼音" }, { url: "http://www.baidu.com", _url: "该节目跳转链接", image: "ex/head1.jpg", _image: "节目头像", author: "桐桐宝宝", _author: "主播妮称", number: "16.7万", _number: "在线人数", webname: "虎牙", _webname: "直播平台名称拼音" }, { url: "http://www.qq.com", _url: "该节目跳转链接", image: "ex/head2.jpg", _image: "节目头像", author: "萱儿", _author: "主播妮称", number: "5633", _number: "在线人数", webname: "美拍", _webname: "直播平台名称拼音" } ], status: 1, page: 1, pagetotal: 5 }, err: { status: "error", msg: "请先登录" } } }) fms.ajax({ type: 'POST', title: '获取游戏节目列表', url: '/get_game/', request: { cid: 2 }, res: { ok: { list:[ { url: "http://www.baidu.com", _url: "该节目跳转链接", image: "ex/head1.jpg", _image: "节目头像", author: "桐桐宝宝", _author: "主播妮称", number: "16.7万", _number: "在线人数", title: "Sli群星联赛NB.Y vs EHOME", _title: "节目名称", webname: "zhanqi", _webname: "直播平台名称拼音" } ], status: 1, _status: "请求状态,1成功,0失败", page: 1, _page: "当前页码", pagetotal: 1, _pagetotal: "总页码数" }, err: { status: "error", msg: "请先登录" } }, timeout: 1000 })
/** * @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'filetools', 'nl', { loadError: 'Fout tijdens lezen van bestand.', networkError: 'Netwerkfout tijdens uploaden van bestand.', httpError404: 'HTTP fout tijdens uploaden van bestand (404: Bestand niet gevonden).', httpError403: 'HTTP fout tijdens uploaden van bestand (403: Verboden).', httpError: 'HTTP fout tijdens uploaden van bestand (fout status: %1).', noUrlError: 'Upload URL is niet gedefinieerd.', responseError: 'Ongeldig antwoord van server.' } );
"use strict"; var Sequence = require('../models/sequence.model'); // Create a sequence exports.sequenceGenerator = function(name){ return { next: function(callback){ Sequence.find({"name":name},function(err, data){ if(err){ throw(err); } if(data.length < 1){ // create if doesn't exist create and return first Sequence.create({name:name,nextSeqNumber:1}, function(err, seq){ if(err) { throw(err); } callback(seq.nextSeqNumber); }); } else { // update sequence and return next Sequence.findOneAndUpdate({"name": name}, { $inc: { nextSeqNumber: 1 } }, {new: true}, function(err, seq){ if(err) { throw(err); } callback(seq.nextSeqNumber); }); } }); } }; }
var Mongoose = require('mongoose'); var personSchema = Mongoose.Schema({ family:String, gen1:String, gen2:String, firstName:String, maidenName:String, familyName:String, birtDate:Date, weddingDate:Date, phone:Array, street:String, city:String, zip:String, email:Array, social:Array }); var person = Mongoose.model('Person', personSchema); module.exports = { Person: person };
(function() { var template = Handlebars.template, templates = Handlebars.templates = Handlebars.templates || {}; templates['items-stored'] = template({"1":function(container,depth0,helpers,partials,data) { var helper, alias1=depth0 != null ? depth0 : {}, alias2=helpers.helperMissing, alias3="function", alias4=container.escapeExpression; return "<tr>\n <td><i class=\"icon-" + alias4(((helper = (helper = helpers.smiling || (depth0 != null ? depth0.smiling : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"smiling","hash":{},"data":data}) : helper))) + "\"></i></td>\n <td>\n <div class=\"table-results-imc\">" + alias4(((helper = (helper = helpers.imc || (depth0 != null ? depth0.imc : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"imc","hash":{},"data":data}) : helper))) + "</div>\n </td>\n <td>\n <div class=\"table-results-info\">\n <div class=\"table-results-name\">" + alias4(((helper = (helper = helpers.name || (depth0 != null ? depth0.name : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"name","hash":{},"data":data}) : helper))) + "</div>\n <div class=\"table-results-data\">" + alias4(((helper = (helper = helpers.date || (depth0 != null ? depth0.date : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"date","hash":{},"data":data}) : helper))) + "</div>\n <div class=\"table-results-time\">" + alias4(((helper = (helper = helpers.hours || (depth0 != null ? depth0.hours : depth0)) != null ? helper : alias2),(typeof helper === alias3 ? helper.call(alias1,{"name":"hours","hash":{},"data":data}) : helper))) + "</div>\n </div>\n </td>\n</tr>\n"; },"compiler":[7,">= 4.0.0"],"main":function(container,depth0,helpers,partials,data) { var stack1; return ((stack1 = helpers.each.call(depth0 != null ? depth0 : {},depth0,{"name":"each","hash":{},"fn":container.program(1, data, 0),"inverse":container.noop,"data":data})) != null ? stack1 : ""); },"useData":true}); })();
// Karma configuration // Generated on Thu Jul 03 2014 13:23:26 GMT+0530 (India Standard Time) module.exports = function(config) { config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) basePath: '', // frameworks to use // available frameworks: https://npmjs.org/browse/keyword/karma-adapter frameworks: ['jasmine'], // list of files / patterns to load in the browser files: [ 'dist/gainda.js', 'test/spec/*.js' ], // list of files to exclude exclude: [ ], // preprocess matching files before serving them to the browser // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor preprocessors: { }, // test results reporter to use // possible values: 'dots', 'progress' // available reporters: https://npmjs.org/browse/keyword/karma-reporter reporters: ['progress'], // web server port port: 9876, // enable / disable colors in the output (reporters and logs) colors: true, // level of logging // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG logLevel: config.LOG_INFO, // enable / disable watching file and executing tests whenever any file changes autoWatch: true, // start these browsers // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher browsers: ['Chrome'], // Continuous Integration mode // if true, Karma captures browsers, runs the tests and exits singleRun: false }); };
export default { SHOW_WEB3_CONFIRM_MODAL: 'showWeb3Wallet', SHOW_TX_CONFIRM_MODAL: 'showTxConfirmModal', SHOW_MSG_CONFIRM_MODAL: 'showMessageConfirmModal', SHOW_TX_SIGN_MODAL: 'showTxSignModal', CONFIRMED_TX: 'confirmedTx', SHOW_BATCH_TX_MODAL: 'showTxCollectionConfirmModal', SHOW_SWAP_TX_MODAL: 'showSwapTxConfirmModal' };
angular.module('septicaApp', []). // services factory('socket', function ($rootScope) { var socket = {}; return { connect: function (url, opts) { socket = io.connect(url, opts); }, on: function (eventName, callback) { socket.on && socket.on(eventName, function () { var args = arguments; $rootScope.$apply(function () { callback.apply(socket, args); }); }); }, emit: function (eventName) { socket.emit && socket.emit.apply(socket, arguments); }, disconnect: function () { socket.disconnect && socket.disconnect(); } }; }). factory('gameService', ['socket', function(socket) { return { connecting: false, connect: function(username) { if (!this.connecting) { this.connecting = true; socket.connect(gconst.WSADDRESS, {'reconnect': false, 'force new connection': true, 'query': "username=" + username}); this.handle_exposed(); this.handle_global(); } }, handle_exposed: function() { var self = this; socket.on('error', function(err) { this.connecting = false; if (err === 'handshake unauthorized') self.onError('Server did not authorize your login. Check FAQ. '); else self.onError('An unexpected error occured: ' + err); }); socket.on('connect', function() { self.onConnect(); }); socket.on('disconnect', function() { self.onDisconnect(); }); }, setOnConnect: function(fn) { var self = this; var oldFn = this.onConnect; this.onConnect = function() { if (oldFn) oldFn.apply(self, arguments); fn.apply(self, arguments); }; }, setOnDisconnect: function(fn) { var self = this; var oldFn = this.onDisconnect; this.onDisconnect = function() { if (oldFn) oldFn.apply(self, arguments); fn.apply(self, arguments); }; }, setOnError: function(fn) { var self = this; var oldFn = this.onError; this.onError = function() { if (oldFn) oldFn.apply(self, arguments); fn.apply(self, arguments); }; }, setOnUpdateStatus: function(fn) { var self = this; var oldFn = this.onUpdateStatus; this.onUpdateStatus = function() { oldFn.apply(self, arguments); fn.apply(self, arguments); }; }, setOnUpdateRoom: function(fn) { var self = this; var oldFn = this.onUpdateRoom; this.onUpdateRoom = function() { oldFn.apply(self, arguments); fn.apply(self, arguments); }; }, setOnUpdateUsername: function(fn) { var self = this; var oldFn = this.onUpdateUsername; this.onUpdateUsername = function() { oldFn.apply(self, arguments); fn.apply(self, arguments); }; }, setOnUpdateChat: function(fn) { var self = this; var oldFn = this.onUpdateChat; this.onUpdateChat = function() { oldFn.apply(self, arguments); fn.apply(self, arguments); }; }, setOnUpdateList: function(fn) { var self = this; var oldFn = this.onUpdateList; this.onUpdateList = function() { oldFn.apply(self, arguments); fn.apply(self, arguments); }; }, setOnUpdateStack: function(fn) { var self = this; var oldFn = this.onUpdateStack; this.onUpdateStack = function() { oldFn.apply(self, arguments); fn.apply(self, arguments); }; }, setOnUpdatePoints: function(fn) { var self = this; var oldFn = this.onUpdatePoints; this.onUpdatePoints = function() { oldFn.apply(self, arguments); fn.apply(self, arguments); }; }, setOnUpdatePlayers: function(fn) { var self = this; var oldFn = this.onUpdatePlayers; this.onUpdatePlayers = function() { oldFn.apply(self, arguments); fn.apply(self, arguments); }; }, setOnUpdateTurn: function(fn) { var self = this; var oldFn = this.onUpdateTurn; this.onUpdateTurn = function() { oldFn.apply(self, arguments); fn.apply(self, arguments); }; }, setOnUpdateCut: function(fn) { var self = this; var oldFn = this.onUpdateCut; this.onUpdateCut = function() { oldFn.apply(self, arguments); fn.apply(self, arguments); }; }, setOnUpdateStarter: function(fn) { var self = this; var oldFn = this.onUpdateStarter; this.onUpdateStarter = function() { oldFn.apply(self, arguments); fn.apply(self, arguments); }; }, setOnUpdateCards: function(fn) { var self = this; var oldFn = this.onUpdateCards; this.onUpdateCards = function() { oldFn.apply(self, arguments); fn.apply(self, arguments); }; }, onConnect: function(){}, onDisconnect: function(){}, onError: function(){}, onUpdateStatus: function(){}, onUpdateRoom: function(){}, onUpdateUsername: function(){}, onUpdateChat: function(){}, onUpdateList: function(){}, onUpdateStack: function(){}, onUpdatePoints: function(){}, onUpdatePlayers: function(){}, onUpdateTurn: function(){}, onUpdateCut: function(){}, onUpdateStarter: function(){}, onUpdateCards: function(){}, handle_global: function() { var self = this; socket.on(gconst.S_ERROR, function() { self.onError.apply(self, arguments); }); socket.on(gconst.S_UPDATE_STATUS, function() { self.onUpdateStatus.apply(self, arguments); }); socket.on(gconst.S_UPDATE_ROOM , function() { self.onUpdateRoom.apply(self, arguments); }); socket.on(gconst.S_UPDATE_USERNAME, function() { self.onUpdateUsername.apply(self, arguments); }); socket.on(gconst.S_UPDATE_CHAT , function() { self.onUpdateChat.apply(self, arguments); }); socket.on(gconst.S_UPDATE_LIST , function() { self.onUpdateList.apply(self, arguments); }); socket.on(gconst.S_UPDATE_STACK , function() { self.onUpdateStack.apply(self, arguments); }); socket.on(gconst.S_UPDATE_POINTS, function() { self.onUpdatePoints.apply(self, arguments); }); socket.on(gconst.S_UPDATE_PLAYERS , function() { self.onUpdatePlayers.apply(self, arguments); }); socket.on(gconst.S_UPDATE_TURN , function() { self.onUpdateTurn.apply(self, arguments); }); socket.on(gconst.S_UPDATE_CUT , function() { self.onUpdateCut.apply(self, arguments); }); socket.on(gconst.S_UPDATE_STARTER , function() { self.onUpdateStarter.apply(self, arguments); }); socket.on(gconst.S_UPDATE_CARDS , function() { self.onUpdateCards.apply(self, arguments); }); }, create: function(name, players) { socket.emit(gconst.C_GAME_CREATE, name, players); }, join: function(gameId) { socket.emit(gconst.C_GAME_JOIN, gameId); }, leave: function() { socket.emit(gconst.C_GAME_LEAVE); }, add: function() { socket.emit(gconst.C_GAME_ADD); }, kick: function(playerIdx) { socket.emit(gconst.C_GAME_KICK, playerIdx); }, start: function() { socket.emit(gconst.C_GAME_START); }, restart: function() { socket.emit(gconst.C_GAME_RESTART); }, dropCard: function(cardId) { socket.emit(gconst.C_GAME_CARD, cardId); }, passTurn: function() { socket.emit(gconst.C_GAME_PASS); }, orderPlayers: function(perm) { socket.emit(gconst.C_GAME_ORDER, perm); }, sendChat: function(message) { socket.emit(gconst.C_CHAT_SEND, message); }, 'socket': socket }; }]). factory('localStorageService', function($rootScope) { var obj = {}; obj.get = function(){}; obj.set = function(){}; if (!Modernizr.localstorage) { $rootScope.localStorageEnabled = false; // fallback to cookies? is it worth it? } else { $rootScope.localStorageEnabled = true; obj.get = function(key, success, error) { var value = localStorage[key]; if (!value) { error(); return; } try { var valObj = JSON.parse(value); success(valObj); } catch (err) { console.log("Couldn't parse localStorage JSON."); error(); } }; obj.set = function(key, object) { localStorage[key] = JSON.stringify(object); }; } return obj; }). factory('audioService', function($rootScope) { var obj = {}; obj.play = function() {}; obj.repeat = function() {}; obj.stop = function() {}; if (!Modernizr.audio) { $rootScope.audioEnabled = false; } else { $rootScope.audioEnabled = true; var Sound = function(name) { this.stop = false; this.audio = document.getElementById(name + '-audio'); var self = this; this.audio.addEventListener('ended', function() { if (!self.stop) { self.audio.currentTime = 0; setTimeout(function() { self.audio.play(); }, 500); }; }); }; var sounds = { notify: new Sound('notify'), card: new Sound('card'), tick: new Sound('tick'), }; obj.play = function(name) { sounds[name] && (sounds[name].stop = true) && sounds[name].audio.play(); }; obj.repeat = function(name) { if (sounds[name]) { sounds[name].stop = false; sounds[name].audio.play(); } }; obj.stop = function(name) { sounds[name] && (sounds[name].stop = true); }; } return obj; }). factory('windowActiveService', function() { var active = true; angular.element(window).on('focus', function() { active = true; }); angular.element(window).on('blur', function() { active = false; }); return { isActive: function() { return active; } }; }). // directives directive('player', function() { return { restrict: 'E', scope: { ngModel: '=', // two way binding kick: '&', // one way binding moveUp: '&', // one way binding moveDown: '&', // one way binding index: '@', // text binding type: '@', // text binding hostNick: '=', // two way binding userName: '=', // two way binding settingsObject: '=', // two way binding playerTurn: '@', // text binding playerStarter: '@', playerCutter: '@', teams: '@', }, require: ['^ngModel'], templateUrl: 'templates/player.html' }; }). directive('cardList', function() { return { restrict: 'E', scope: { ngModel: '=', // two way random: '@', // text [ yes or no ] clickable: '@', // text [ yes or no ] hover: '@', // text [ highlight or disperse ] action: '&', // one way binding [ function on click ] }, require: ['^ngModel'], templateUrl: 'templates/cardList.html', } }). directive('card', function() { return { restrict: 'E', scope: { ngModel: '=', // two way action: '&', // [ function with parameter, given an index ] hover: '@', // text clickable: '@', // text random: '@', // text index: '@', // text }, require: ['^ngModel'], link: function (scope, element, attrs) { if (scope.action && scope.clickable == 'yes') { var actionHandler = scope.action(); $(element).click(function() { actionHandler(scope.index); }); } }, templateUrl: 'templates/card.html', } }). // autoscroll directive('scrollableContainer', function() { return { restrict: 'A', // attr link: function (scope, element, attrs) { var scrollToTop = false; scope.$on("scrollableRendered", function() { var $el = angular.element(element); $el.stop(); if (scrollToTop) $el.scrollTop(0); $el.animate({'scrollTop': $el[0].scrollHeight}, 400); scrollToTop = false; }); scope.$on('scrollableCleared', function() { scrollToTop = true; }); } } }). directive('scrollableItem', function() { return { restrict: 'A', // attr link: function (scope, element, attrs) { if (scope.$last) scope.$emit("scrollableRendered"); } } }). // scrollbar directive('perfectScroll', function($parse) { return { restrict: 'E', transclude: true, template: '<div><div ng-transclude></div></div>', replace: true, link: function($scope, $elem, $attr) { $elem.perfectScrollbar({ wheelSpeed: $parse($attr.wheelSpeed)() || 50, wheelPropagation: $parse($attr.wheelPropagation)() || false, minScrollbarLength: $parse($attr.minScrollbarLength)() || false, }); if ($attr.refreshOnChange) { $scope.$watchCollection($attr.refreshOnChange, function(newNames, oldNames) { // I'm not crazy about setting timeouts but it sounds like thie is unavoidable per // http://stackoverflow.com/questions/11125078/is-there-a-post-render-callback-for-angular-js-directive setTimeout(function() { $elem.perfectScrollbar('update'); }, 10); }); } } }; }). // controllers controller('MainCtrl', function($scope, $timeout, $animate, gameService, localStorageService, audioService, windowActiveService) { var defaultSettings = { // default settings general: { theme: 0, // default }, audio: { isEnabled: $scope.audioEnabled, isChatEnabled: true, isTurnEnabled: true, isCountdownEnabled: false, isGameFXEnabled: false, }, gameplay: { showLastCutter: true, showTurnStarter: true, highlightTurn: true, highlightPlayer: true }, chat: { showTimestamp: true, showServerMessages: true, clearInterval: 0, // never }, }; $scope.settings = defaultSettings; // if localstorage isn't enabled. // try loading anything from localStorage localStorageService.get('settings', function(settings) { $scope.settings = settings; }, function() { localStorageService.set('settings', defaultSettings); $scope.settings = defaultSettings; }); // watch settings for changes $scope.$watch('settings', function(newValue) { localStorageService.set('settings', newValue); }, true); $scope.main = { unload: function(e) { var msg = "Leaving this page will result in you losing your session."; (e || window.event).returnValue = msg; return msg; }, utility: { fadeOut: function(element, callback) { $animate.removeClass(element, 'in', function() { $timeout(function() { $animate.removeClass(element, 'active', function() { callback && callback(); }); }, 150); }); }, fadeIn: function(element, callback) { $animate.addClass(element, 'active', function() { $animate.addClass(element, 'in', function() { callback && callback(); }); }); }, }, tabs: { // valid: ['login', 'list', 'create', 'room', 'zone'] previous: null, current: 'login', set: function(tab) { this.previous = this.current; this.current = tab; if (this.previous) var $prev = angular.element("#game-" + this.previous); else var $prev = null; var $current = angular.element("#game-" + this.current); if ($prev) { $scope.main.utility.fadeOut($prev, function() { $scope.main.utility.fadeIn($current); }); } else { $scope.main.utility.fadeIn($current); } }, }, error: { $container: angular.element("#error-container"), message: '', hideTimeout: null, shown: false, show: function(msg) { var self = this; self.message = msg; $scope.main.utility.fadeIn(self.$container, function() { self.shown = true; if (self.hideTimeout) $timeout.cancel(self.hideTimeout); self.hideTimeout = $timeout(function() { self.hide(); }, 2500); }); }, hide: function() { var self = this; if (self.hideTimeout) $timeout.cancel(self.hideTimeout); $scope.main.utility.fadeOut(self.$container, function() { self.shown = false; }); } }, data: {}, }; // handle exposed socket events gameService.setOnError(function(msg) { $scope.main.error.show(msg); }); gameService.setOnConnect(function() { $scope.main.tabs.set('list'); window.addEventListener('beforeunload', $scope.main.unload); }); gameService.setOnDisconnect(function() { $scope.main.data.username = ''; $scope.main.error.show('You have been disconnected.'); $scope.main.tabs.set('login'); window.removeEventListener('beforeunload', $scope.main.unload); }); // handle game specific events gameService.setOnUpdateUsername(function(data) { if (data.username) $scope.main.data.username = data.username; }); gameService.setOnUpdateRoom(function(data) { if (data.room == -1) { $scope.main.tabs.set('list'); } }); gameService.setOnUpdateStatus(function(data) { if (data.status == "started") { $scope.main.tabs.set('zone'); } else if (data.status == "created") { $scope.main.tabs.set('room'); } else if (data.status == "stopped") { $scope.main.tabs.set('list'); } else if (data.status == "over") { $scope.main.tabs.set('stats'); } }); }). controller('GameLoginCtrl', function($scope, gameService) { var $submit = angular.element('#gameLoginSubmit'); $scope.nickname = ''; $scope.login = function(form) { if (form.$valid) { $submit.button('loading'); gameService.connect($scope.nickname); } }; gameService.setOnDisconnect(function() { $submit.button('reset'); }); gameService.setOnError(function() { $submit.button('reset'); }); }). controller('RoomListCtrl', function($scope, gameService) { $scope.rooms = []; $scope.isEmpty = function() { if ($scope.rooms.length === 0) return true; return false; }; $scope.goCreate = function() { $scope.main.tabs.set('create'); }; $scope.joinRoom = function(idx) { gameService.join($scope.rooms[idx].id); }; gameService.setOnUpdateList(function(data) { $scope.rooms = data.list; }); }). controller('GameCreateCtrl', function($scope, gameService) { var $submit = angular.element("#gameCreateSubmit"); $scope.roomName = ''; $scope.roomLimit = 4; gameService.setOnUpdateUsername(function(data) { $scope.roomName = data.username; }); $scope.doCreate = function(form) { if (form.$valid) { var name = $scope.roomName; var limit = $scope.roomLimit; $submit.button('loading'); gameService.create(name, limit); } } $scope.cancelCreate = function() { $scope.main.tabs.set('list'); }; gameService.setOnError(function() { $submit.button('reset'); }) gameService.setOnDisconnect(function() { $submit.button('reset'); }) }). controller('GameRoomCtrl', function($scope, gameService) { // add game service update username on scope // will two-way bind these to the directive. $scope.userName = ''; $scope.hostName = ''; $scope.roomName = ''; $scope.players = []; var $start = angular.element('#gameRoomStart'); gameService.setOnUpdateUsername(function(data) { $scope.userName = data.username; }); gameService.setOnUpdateRoom(function(data) { if (data.room != -1) { $scope.hostName = data.room_host; $scope.roomName = data.room_name; } }); gameService.setOnUpdatePlayers(function(data) { $scope.players = []; for (var i = 0, len = data.players.length; i < len; i++) { $scope.players.push({'name': data.players[i], 'points': 0}); } }); $scope.kickPlayer = function(index) { // call game service kick gameService.kick(index); }; $scope.move = function(index, offset) { var perm = []; for ( var i = 0, len = $scope.players.length; i < len; i++ ) perm.push(i); // swap if (index + offset < $scope.players.length && index + offset >= 0) { var tmp = perm[index + offset]; perm[index + offset] = perm[index]; perm[index] = tmp; gameService.orderPlayers(perm); } }; $scope.leave = function() { gameService.leave(); }; $scope.addBot = function() { gameService.add(); }; $scope.start = function() { $start.button('loading'); gameService.start(); }; gameService.setOnDisconnect(function() { $start.button('reset'); }); gameService.setOnError(function() { $start.button('reset'); }); gameService.setOnUpdateRoom(function(data) { if (data.room != -1) { $start.button('reset'); } }); }). controller('GameZoneCtrl', function($scope, $interval, gameService, audioService, windowActiveService) { $scope.timer = { seconds_left: -1, interval: null, start: function(s) { $interval.cancel(this.interval); var self = this; this.seconds_left = s; this.interval = $interval(function() { self.seconds_left--; if (self.seconds_left == 10 && $scope.settings.audio.isEnabled && $scope.settings.audio.isCountdownEnabled) audioService.repeat('tick'); if (self.seconds_left <= 0) self.stop(); }, 1000); }, stop: function() { $interval.cancel(this.interval); this.seconds_left = -1; audioService.stop('tick'); }, }; $scope.roomName = ''; $scope.player_idx = -1; $scope.players = []; $scope.cards = []; $scope.stack = []; $scope.cut = -1; $scope.starter = -1; $scope.turn = -1; /* required UI things */ $scope.getPassTurnLabel = function() { if ($scope.turn == $scope.cut) return 'Take'; else return 'Pass'; }; $scope.isPassTurnHidden = function() { return !(($scope.player_idx == $scope.turn) && ($scope.turn == $scope.starter) && ($scope.stack.length != -1) && ($scope.player_idx != -1) && ($scope.turn != -1)); }; // player_idx === turn && stack.length !== 0 $scope.dropCard = function(index) { gameService.dropCard(index); }; $scope.passTurn = function() { gameService.passTurn(); }; /* game service register events */ gameService.setOnUpdateRoom(function(data) { if (data.room != -1) $scope.roomName = data.room_name; }); gameService.setOnUpdatePlayers(function(data) { $scope.players = []; for (var i = 0, len = data.players.length; i < len; i++) { if (data.players[i] == $scope.main.data.username) { $scope.player_idx = i; } $scope.players.push({'name': data.players[i], 'points': 0}); } }); gameService.setOnUpdatePoints(function(data) { for (var i = 0, len = data.points.length; i < len; i++) { $scope.players[i].points = data.points[i]; } }); gameService.setOnUpdateCards(function(data) { $scope.cards = data.cards; }); gameService.setOnUpdateStarter(function(data){ $scope.starter = data.starter; }); gameService.setOnUpdateTurn(function(data){ $scope.turn = data.turn; if ($scope.turn == $scope.player_idx) { if ($scope.settings.audio.isEnabled && $scope.settings.audio.isTurnEnabled && (!windowActiveService.isActive() || $scope.main.tabs.current != 'zone')) audioService.play('notify'); $scope.timer.start(gconst.TURN_TIME_LIMIT); } else { $scope.timer.stop(); } }); gameService.setOnUpdateStack(function(data){ $scope.stack = data.stack; if ($scope.settings.audio.isEnabled && $scope.settings.audio.isGameFXEnabled && windowActiveService.isActive() && $scope.main.tabs.current == 'zone') { audioService.play('card'); } }); gameService.setOnUpdateCut(function(data){ $scope.cut = data.cut; }); gameService.setOnUpdateStatus(function(data) { if (data.status == 'over') { $scope.timer.stop(); } }); }). controller('GameStatsCtrl', function($scope, $interval, gameService) { $scope.userName = ''; $scope.hostName = ''; $scope.roomName = ''; $scope.players = []; $scope.preventUpdates = false; var $restart = angular.element('#gameStatsRestart'), $disband = angular.element('#gameStatsDisband'), $leave = angular.element('#gameStatsLeave'); /* disband timer */ $scope.timer = { seconds_left: -1, interval: null, start: function(s) { $interval.cancel(this.interval); var self = this; this.seconds_left = s; this.interval = $interval(function() { self.seconds_left--; if (self.seconds_left <= 0) self.stop(); }, 1000); }, stop: function() { $interval.cancel(this.interval); this.seconds_left = -1; }, }; gameService.setOnUpdateUsername(function(data) { $scope.userName = data.username; }); gameService.setOnUpdateRoom(function(data) { console.log('HERE1'); if (data.room != -1) { $scope.hostName = data.room_host; $scope.roomName = data.room_name; } }); gameService.setOnUpdatePlayers(function(data) { if (!$scope.preventUpdates) { $scope.players = []; for (var i = 0, len = data.players.length; i < len; i++) { $scope.players.push({'name': data.players[i], 'points': 0}); } } }); gameService.setOnUpdatePoints(function(data) { if (!$scope.preventUpdates) { for (var i = 0, len = data.points.length; i < len; i++) { $scope.players[i].points = data.points[i]; } } }); gameService.setOnUpdateStatus(function(data) { console.log('HERE2'); if (data.status == 'over') { $scope.timer.start(30); $scope.preventUpdates = true; } else $scope.preventUpdates = false; }); // restart / disband $scope.restart = function() { $restart.button('loading'); gameService.restart(); }; $scope.leave = function() { gameService.leave(); }; var resetButtons = function() { $restart.button('reset'); }; gameService.setOnDisconnect(function() { resetButtons(); }); gameService.setOnError(function() { resetButtons(); }); gameService.setOnUpdateStatus(function(data) { console.log('here2'); if (data.status == 'created') { resetButtons(); } }); gameService.setOnUpdateRoom(function(data) { console.log("here1"); if (data.room == -1) { resetButtons(); } }); }). controller('ChatCtrl', function($scope, $interval, gameService, audioService, windowActiveService, dateFilter) { $scope.messages = []; $scope.inputMessage = ''; $scope.chatShown = false; $scope.chatActive = false; $scope.newMessagesCount = 0; $scope.hideChat = function() { $scope.chatShown = false; }; $scope.showChat = function() { $scope.$emit('scrollableCleared'); $scope.chatShown = true; $scope.newMessagesCount = 0; $scope.$emit('scrollableRendered'); }; $scope.sendMessage = function() { gameService.sendChat($scope.inputMessage); $scope.inputMessage = ''; }; var clearMessagesInterval; var clearMessages = function() { $scope.$emit('scrollableCleared'); $scope.messages = []; $scope.messages.push({ timestamp: dateFilter(new Date(), 'h:mm:ss a'), sender: 'SERVER', content: 'Cleared your chat history.' }); }; $scope.$watch('settings.chat.clearInterval', function(newVal) { if (newVal == 0) $interval.cancel(clearMessagesInterval); else { var timeInterval = 5 * newVal; if (newVal == 4) timeInterval = 30; timeInterval *= 60 * 1000; // 60 seconds * 1000 ms clearMessagesInterval = $interval(function() { clearMessages(); }, timeInterval); } }); gameService.setOnUpdateChat(function(data) { $scope.messages.push({ timestamp: dateFilter(new Date(), 'h:mm:ss a'), sender: data.chat.sender, content: data.chat.message }); if (!$scope.chatShown) { $scope.newMessagesCount++; } }); gameService.setOnUpdateRoom(function(data) { if (data.room == -1) { clearMessages(); $scope.chatActive = false; } else { $scope.chatActive = true; } }); }). controller('SettingsCtrl', function($scope) { $scope.themes = [ {label: "Default", value: 0} ]; $scope.clearChatOptions = [ {label: 'never', value: 0}, {label: 'every 5 minutes', value: 1}, {label: 'every 10 minutes', value: 2}, {label: 'every 15 minutes', value: 3}, {label: 'every 30 minutes', value: 4} ]; $scope.$watch('theme', function(newVal){ $scope.settings.general.theme = newVal.value; }); $scope.$watch('clearChatOption', function(newVal){ $scope.settings.chat.clearInterval = newVal.value; }); $scope.theme = $scope.themes[$scope.settings.general.theme]; $scope.clearChatOption = $scope.clearChatOptions[$scope.settings.chat.clearInterval]; }). controller('FAQCtrl', function($scope) { $scope.questions = []; var addQuestion = function (q, a) { $scope.questions.push({question: q, answer: a}); }; // initialize questions addQuestion('"Server did not authorize your login" message shows up every time I try to connect.', 'Make sure you have cookies enabled and try refreshing the page.'); addQuestion('"An unexpected error occured" message shows up every time I try to connect.', 'Our game servers are experiencing technical problems or are under maintenance.'); addQuestion('I cannot access Settings page. Help!', 'Your browser does not support HTML5 Local Storage, which we use to store your preferences for future visits. Please upgrade your browser.'); }). controller('RulesCtrl', function($scope) { }). controller('AboutCtrl', function($scope) { var age; var today = new Date(); var dob = new Date(1996, 2, 3); age = today.getYear() - dob.getYear(); if ( today.getMonth() < dob.getMonth() || (today.getMonth() == dob.getMonth() && today.getDate() < dob.getDate() ) ) age--; $scope.age = age; });
"use strict"; angular.module("homeuiApp") .factory("getTime", function () { return function getTime () { return new Date().getTime(); }; });
/* Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'blockquote', 'ku', { toolbar: 'بەربەستکردنی ووتەی وەرگیراو' } );
$(document).ready(function() { $.validator.setDefaults({ highlight: function (element) { $(element) .closest('.input-group') .addClass('has-danger') .removeClass('has-success') }, unhighlight: function (element) { $(element) .closest('.input-group') .removeClass('has-danger') .addClass('has-success') }, errorElement: 'div', errorClass: 'form-text', errorPlacement: function(error, element) { error.insertAfter(element.parent('div')); } }); $("#add-driver-form").validate({ rules: { "email": { required: true, email: true }, "password": { required: true, minlength: 6 }, "full-name": { required: true, pattern: "^[A-ZА-Я][a-zа-я]+ [A-ZА-Я][a-zа-я]+$" }, "passport-serial-numbers": { required: true, pattern: "^([А-Я]{2} \\d{6})|(\\d{10})$" }, "phone-number": { required: true, pattern: "^(\\+?\\d{12})|(\\d{10})$" }, "age": { required: true, pattern: "^(1[89]|[2-9][0-9])$" } }, messages: { "email": { required: "Please, enter an email address.", email: "Please, enter a valid email address." }, "password": { required: "Please, enter your password.", minlength: "Password must contain at least 6 characters." }, "full-name": { pattern: "Please, enter a valid full name(ex. John Smith)." }, "passport-serial-numbers": { pattern: "Please, enter valid passport serial numbers(ex. ВТ 123456)." }, "phone-number": { required: "Please, enter a phone number.", pattern: "Please, enter a valid phone number(ex. +380664039952)." }, "age": { required: "Please, enter driver's age.", pattern: "Please, enter a valid age(>18 & <99)." } } }); });
/*let calculator = (function () { let result = 0; function add(x) { result += x; return this; } function subtract(x) { result -= x; return this; } function getResult() { return result; } return{ add, subtract, getResult } })();*/ // our lasted obj starts as empty let calculator = {}; // private iffe with every private functionality (function (module) { let result = 0; function add(x) { result += x; return this; } function subtract(x) { result -= x; return this; } function getResult() { return result; } module.add = add; module.subtract = subtract; module.getResult = getResult; }(calculator)); // calling it with our obj (function (module) { module.add42 = function () { this.add(42); }; }(calculator)); calculator.add42(); console.log(calculator.add(5).getResult());
"use strict"; const {toPromise} = require("./promise"); const {interceptNode, registerGlobalInterceptor} = require("./interceptor"); // pipeline interceptor registerGlobalInterceptor(node => node instanceof Pipeline ? (payload => node.dispatch(payload)) : null); class Pipeline { constructor() { this.firstNode = null; this.lastNode = null; this.eagerNodes = []; this.innerNodes = []; this.deferedNodes = []; this.errorHandler = null; this.interceptors = []; // Soon to be deprecated functions (renamed) // Polyfill for backwards compatibility with 0.1 this.pipe = this.through; this.capture = this.to; } from(node) { if (arguments.length === 0) { return this.firstNode; } this.firstNode = node; return this; } to(node) { if (arguments.length === 0) { return this.lastNode; } this.lastNode = node; return this; } through(...nodes) { if (arguments.length === 0) { return [].concat(this.innerNodes); } this.innerNodes = this.innerNodes.concat(nodes); return this; } eager(...nodes) { if (arguments.length === 0) { return [].concat(this.eagerNodes); } this.eagerNodes = this.eagerNodes.concat(nodes); return this; } defer(...nodes) { if (arguments.length === 0) { return [].concat(this.deferedNodes); } this.deferedNodes = this.deferedNodes.concat(nodes); return this; } intercept(...interceptors) { this.interceptors = this.interceptors.concat(interceptors); return this; } get nodes() { const nodes = [].concat(this.eagerNodes, this.innerNodes, this.deferedNodes); if (this.firstNode != undefined) { nodes.unshift(this.firstNode); } if (this.lastNode != undefined) { nodes.push(this.lastNode); } return nodes; } report(errorHandler) { this.errorHandler = errorHandler; return this; } dispatch(payload = {}) { let response = toPromise(payload); this.nodes.forEach(node => { const callback = interceptNode(node, [].concat(this.interceptors)); if (typeof callback === "function") { response = response.then( currentPayload => toPromise(currentPayload != undefined ? currentPayload : payload).then(callback) ); } }); if (this.errorHandler) { const callback = interceptNode(this.errorHandler, [].concat(this.interceptors)); if (typeof callback === "function") { response = response.catch(callback); } } return response; } } // generator const createPipeline = () => new Pipeline(); module.exports = { Pipeline, createPipeline };
import {connect } from 'react-redux' import React,{Component} from 'react' import {Nav, Navbar, NavItem} from 'react-bootstrap' import {pushState} from 'redux-router' import Alert from '../components/alert' import Loader from 'react-loader-advanced'; @connect((state) => ( {loading: state.common.loading})) export default class App extends Component { constructor(props){ super(props); } render () { let topRoutes = this.props.route.childRoutes; let activeRoute = topRoutes.filter(route => this.props.history.isActive(route.path))[0] return (<div> <Navbar> <Navbar.Header> <Navbar.Brand><a href="#">ToolboxSite</a></Navbar.Brand> </Navbar.Header> <Nav pullRight> {topRoutes.map(route =><NavItem key={route.path} href={'#'+ route.path}>{route.name}</NavItem>)} <NavItem href="https://github.com/Jishun/ToolboxSite" target="_blank">GitHub</NavItem> </Nav> </Navbar> <div id="content_area" className="container"> <Nav bsStyle="tabs"> {activeRoute && activeRoute.childRoutes? activeRoute.childRoutes.map((route, i) => <NavItem key={i} active={this.props.history.isActive(route.path)} href={'#' +route.path}>{route.name}</NavItem>) : null} </Nav> <Alert></Alert> <div>{this.props.children}</div> </div> </div>); } }
'use strict'; //Emails service used to communicate Emails REST endpoints angular.module('emails').factory('Emails', ['$resource', function($resource) { return $resource('api/emails/:emailId', { emailId: '@_id' }, { update: { method: 'PUT' } }); } ]);
var assert = require('assert'); var util = require('util'); var auth0OidcStrategy = require('../lib/passport-auth0-openidconnect'); describe('passport-auth0-openidconnect', function(){ it('should report a version', function () { assert.ok(auth0OidcStrategy.version); assert.equal(typeof(auth0OidcStrategy.version),'string'); assert.ok(auth0OidcStrategy.version.length > 0); }); });
var Omegle = require('omegle').Omegle; var omegleSessions = []; function init() { if(Omegle) { this.on('command', function(context, command) { if(command == 'omegle') { if(command.arguments.length == 0) { context.reply('Omegle Plugin commands: pair, stop'); }else { if(command.arguments[0] == 'pair') { var session = {} session.sideA = new Omegle(); session.sideB = new Omegle(); session.sideA.on('error', function(err) { console.log(err); console.log(err.stack); context.reply('Error occured on Side A. Disconnecting'); session.sideA.disconnect(); session.sideB.disconnect(); }); session.sideB.on('error', function(err) { console.log(err); console.log(err.stack); context.reply('Error occured on Side B. Disconnecting'); session.sideA.disconnect(); session.sideB.disconnect(); }); session.sideA.start(function(err) { if(err) { context.reply('Failed to create first side. Terminating connection'); session.sideA.disconnect(); session.sideB.disconnect(); return; }else{ context.reply('Person 1 connected'); /* Start side B */ session.sideB.start(function(err) { if(err) { context.reply('Failed to create second side. Terminating connection'); session.sideA.disconnect(); session.sideB.disconnect(); return; }else{ context.reply('Person 2 connected'); session.sideA.on('strangerDisconnected', function() { context.reply('First person disconnected. Closing connection'); session.sideA.disconnect(); session.sideB.disconnect(); }); session.sideB.on('strangerDisconnected', function() { context.reply('Second person disconnected. Closing connection'); session.sideA.disconnect(); session.sideB.disconnect(); }); session.sideA.on('typing', function() { console.log('Omegle SideA Typing'); session.sideB.startTyping(); }); session.sideA.on('stoppedTyping', function() { console.log('Omegle SideA Stop Typing'); session.sideB.stopTyping(); }); session.sideB.on('typing', function() { console.log('Omegle SideB Typing'); session.sideA.startTyping(); }); session.sideB.on('stoppedTyping', function() { console.log('Omegle SideB Stop Typing'); session.sideA.stopTyping(); }); session.sideA.on('gotMessage', function(msg) { session.sideB.send(msg, function(err) { if(err) { context.reply('Error sending to sideB, abandoning!'); session.sideA.disconnect(); session.sideB.disconnect(); }else{ context.reply('P1 > P2: ' + msg); } }); }); session.sideB.on('gotMessage', function(msg) { session.sideA.send(msg, function(err) { if(err) { context.reply('Error sending to sideA, abandoning'); session.sideA.disconnect(); session.sideB.disconnect(); }else{ context.reply('P2 > P1: ' + msg); } }); }); session.sideA.on('recaptchaRequired', function(key) { context.reply('Side A requested a captcha. Bugging out! Woop!'); session.sideA.disconnect(); session.sideB.disconnect(); }); session.sideB.on('recaptchaRequired', function(key) { context.reply('Side B requested a captcha. No thankies!'); session.sideA.disconnect(); session.sideB.disconnect(); }); } }); } }); } } } }); } else { console.log('Omegle API unavailable. Not attaching plugin'); } } function unload() { } module.exports = { 'init': init, 'unload': unload };
var temp; var weather; function setTemp(tempKelvin) { temp = tempKelvin - 273.15; $("#temp").html(Math.floor(temp)); } function getWeather(geolocation) { $("#city").html(geolocation.city + ", " + geolocation.regionName); $.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=" + geolocation.lat + "&lon=" + geolocation.lon + "&APPID=3d46ddc5857d31d05cb855f315723e84", function(openApiJson) { $("#neighborhood").html(openApiJson.name + " Neighborhood"); weather = openApiJson.weather[0].main; setIcon(); $("#weather").html(weather); $("#humidity").html("Humidity: " + openApiJson.main.humidity + "%"); $("#wind").html("Wind speed: " + openApiJson.wind.speed + "m/s"); setTemp(openApiJson.main.temp); }); } function getLocation() { $.getJSON("http://ip-api.com/json", getWeather); } function setIcon() { var weatherIcon = "ion-home"; console.log(weather); switch (weather) { case "Thunderstorm": weatherIcon = "ion-ios-thunderstorm"; break; case "Drizzle": case "Rain": weatherIcon = "ion-ios-rainy"; break; case "Snow": weatherIcon = "ion-ios-snowy"; break; case "Atmosphere": weatherIcon = "ion-ios-partlysunny"; break; case "Clear": weatherIcon = "ion-ios-sunny"; break; case "Clouds": weatherIcon = "ion-ios-cloudy"; break; case "Extreme": weatherIcon = "ion-ios-thunderstorm"; break; case "Additional": weatherIcon = "ion-ios-cloudy-night"; break; default: weatherIcon = "ion-ios-moon"; break; } $("#weatherIcon").addClass(weatherIcon); } $(document).ready(function() { var today = new Date(); $("#date").html(today.toDateString()); getLocation(); $(".unit").click(function() { if (!$(this).is(".active")) { $(".unit.active").removeClass("active"); $(this).addClass("active"); if ($(this).is("#far")) { temp = temp * 9 / 5 + 32; } else { temp = (temp - 32) * 5 / 9; } $("#temp").html(Math.floor(temp)); } }); });
Ext.define('OppUI.view.loadTestDashboard.loadtestreport.loadtestchart.LoadTestChart',{ extend: 'Ext.chart.CartesianChart', alias: 'widget.loadtestchart', requires: [ 'OppUI.view.loadTestDashboard.loadtestreport.loadtestchart.LoadTestChartController', 'OppUI.view.loadTestDashboard.loadtestreport.loadtestchart.LoadTestChartModel', 'Ext.chart.series.Line', 'Ext.chart.axis.Numeric', 'Ext.chart.axis.Time', 'Ext.chart.axis.Category', 'Ext.chart.plugin.ItemEvents' ], controller: 'loadtestchart', viewModel: { type: 'loadtestchart' }, config: { seriesStyle: { lineWidth: 4 }, seriesMarker: { radius: 4 }, seriesHighlight: { fillStyle: '#000', radius: 5, lineWidth: 2, strokeStyle: '#fff' }, seriesTooltip: { trackMouse: true, renderer: function (tooltip, record, item) { var startTime; if(item && record) { // determine if the tooltip is for a timeseries chart // or aggregation chart. startTime = record.data.start_time; if(!startTime) { startTime = window.parseInt(record.data.xaxis); } tooltip.setHtml(item.field + ' on ' + new Date(startTime * 1000) + ': ' + record.get(item.series.getYField()) + ' (ms)'); } } }, tools: [{ type:'gear', handler: function(event, element, view){ var chart = this.up('loadtestchart'); var type = chart.getItemId().split('-'); var loadTestId = chart.up('loadtestreport').getLoadTestId(); var yAxis = type[0].indexOf('timeseries') >= 0 ? chart.getDockedItems()[1].items.items[1].getValue() : // get the combobox's selected value type[1]; // just get the item id's yAxis type. if(chart.getStore().getData().items.length > 0) { var window = Ext.create('Ext.window.Window', { layout: 'fit', height: Ext.getBody().getViewSize().height - 100, width: Ext.getBody().getViewSize().width - 100, maximizable: true, title: chart.title, items: [{ xtype: 'chartdatagrid', loadTestId: loadTestId, yAxis: yAxis }], tools: [ { type:'print', listeners: { afterrender: function(me) { // Ext.tip.QuickTipManager.register({ // target: me.getId(), // title: 'View as Wiki', // text: 'View Wiki Markup for this table' // }); } }, handler: function(event, element, view){ var grid = this.up('window').down('grid'); var wiki = grid.getWikiFormat(); Ext.Msg.alert('Wiki Markup', wiki); } }, { type: 'save', listeners: { afterrender: function(me) { // Ext.tip.QuickTipManager.register({ // target: me.getId(), // title: 'Save Data', // text: 'Save Data as CSV' // }); } }, handler: function(a,b,c) { var grid = this.up('window').down('grid'); var csv = grid.getCsv(); var link = document.createElement("a"); link.download = loadTestId + "_" + yAxis + "_data.csv"; link.href='data:text/plain;charset=utf-8,' + encodeURIComponent(csv); link.click(); } }] }); window.show(); // Ext.tip.QuickTipManager.register({ // target: window.tools[2].id, // title: 'Toggle Maximize', // text: 'Toggle size of this window' // }); // Ext.tip.QuickTipManager.register({ // target: window.tools[3].id, // title: 'Close', // text: 'Close this window' // }); } else { Ext.Msg.alert('Error', 'This chart has no raw data'); } } }, { type:'print', listeners: { afterrender: function(me) { // Ext.tip.QuickTipManager.register({ // target: me.getId(), // title: 'Print', // text: 'Print this graph' // }); } }, handler: function(event, element, view){ view.up('loadtestchart').download(); } }, { type:'maximize', handler: function(event, element, view){ var parentContainer = this.up().up().up(); // header --> chart --> container var chart = view.up('loadtestchart'); chart.getHeader().hide(); var window = Ext.create('Ext.window.Window', { layout: 'fit', parentContainer: parentContainer, height: Ext.getBody().getViewSize().height - 100, width: Ext.getBody().getViewSize().width - 100, maximizable: true, title: view.up('loadtestchart').getTitle(), hideCollapseTool: true, items: chart, tools: [{ type:'print', handler: function(event, element, view){ view.up('window').down('loadtestchart').download(); } }], listeners: { beforeclose: function(chart, options) { var child = this.items.items[0]; child.getHeader().show(); this.parentContainer.add(child); } } }); window.show(); //window.center(); } }] }, plugins: { ptype: 'chartitemevents' // moveEvents: true }, listeners: { itemdblclick: function(series, item, event, eOpts ) { // only create a tab if the user is dblclicking // on aggregation load test chart. if(this.getItemId().indexOf('trend-') >= 0) { this.up('loadtest') .getController() .updateUrlTabState(item.record.id, true) } } }, legend: { docked: 'right' }, axes: [ { type: 'numeric', minimum: 0, position: 'left', title: 'Response Time (msec)', // gets overridden with yaxisTitle grid: true }, { type: 'category', position: 'bottom', title: 'Run Date', // gets overridden with xaxisTitle renderer: function (o, value) { if (value.length > 20) { this.font = "10px Arial, Helvetica, sans-serif"; } //return parseInt(value) * 1000; return Ext.Date.format(new Date(parseInt(value) * 1000), 'm/d/y'); } } ] });
var Login = function() {}; Login.prototype = { preload: function() { console.log('STATE : Login - Preload'); }, create: function() { console.log('STATE : Login - Create'); this.state.start('Setup'); } }; module.exports = Login;
const loadAll = true const defaultLanguage = 'en' const otherLang = [ 'vi'] const supportLanguage = [defaultLanguage, ...otherLang] const defaultAndActive = [defaultLanguage, 'active'] module.exports = { supportLanguage, defaultLanguage, loadAll, defaultAndActive, otherLang }
$( document ).ready( function( ) { setTimeout( function( ) { $( ".alert.alert-overhead" ).css({ "opacity": 0 }); }, 1500 ) });
const path = require('path'); const { resolve, join } = path; const OfflinePlugin = require(process.env.OFFLINE_PLUGIN_ROOT); const CopyWebpackPlugin = require('copy-webpack-plugin'); const DefinePlugin = require('webpack').DefinePlugin; module.exports = { entry: { main: join(__dirname, 'src/main.js'), }, output: { path: join(__dirname, 'www'), filename: '[name].js', chunkFilename: '[name].js', publicPath: '/' }, plugins: [ new CopyWebpackPlugin([ { from: join(__dirname, 'src/index.html') }, { from: join(__dirname, 'src/app-shell.html') } ]), new DefinePlugin({ 'process.env.OFFLINE_PLUGIN_ROOT': JSON.stringify(process.env.OFFLINE_PLUGIN_ROOT) }), new OfflinePlugin({ appShell: '/app-shell.html', ServiceWorker: { navigationPreload: { map: (url) => { if (url.pathname === '/') { return '/api/index.json'; } if (url.pathname === '/not-found') { return '/api/not-found.json'; } }, test: (url) => { if (url.pathname.indexOf('/api/') === 0) { return true; } } }, }, AppCache: false, }) ] };
'use strict'; var path = require('path'); var gulp = require('gulp'); var gutil = require('gulp-util'); var _ = require('lodash'); var notify = require('gulp-notify'); var plumber = require('gulp-plumber'); var livereload = require('gulp-livereload'); var config = require('./config'); var loaded = []; var ns = function (name) { return ['luminous-gulp', name].join(':'); }; /** * Get the task name with the namespace after loading. * * @param {string} name * @return {string} */ var LuminousGulp = function (name) { var file = name.split(':')[0]; if (!_.includes(loaded, file)) { loaded.push(file); require(path.join(__dirname, 'tasks', file))(LuminousGulp); } return ns(name); }; /** * Get configuration. * * @param {string} path * @return {Object} */ LuminousGulp.config = function (path) { var paths = _.isString(path) ? path.split('.') : _.toArray(arguments), value = config; while (paths.length > 0) { value = value[paths.shift()]; } return value; }; /** * The wrapper for "gulp.task()". * * @param {string} name * @param {array} deps * @param {function} fn * @return {undefined} */ LuminousGulp.task = function (name, deps, fn) { if (!fn && typeof deps === 'function') { fn = deps; deps = []; } gulp.task(ns(name), deps.map(LuminousGulp), fn); }; // Report file paths in the stream pipeline. LuminousGulp.report = require('./report'); // https://www.npmjs.com/package/gulp-notify LuminousGulp.notify = function (message) { return notify({title: 'luminous-gulp', message: message}); }; LuminousGulp.onError = function () { return notify.onError({title: 'luminous-gulp', message: "Error: <%= error.message %>"}); }; // https://www.npmjs.com/package/gulp-plumber LuminousGulp.plumber = function () { return plumber({ errorHandler: LuminousGulp.onError() }); }; // https://www.npmjs.com/package/gulp-livereload LuminousGulp.listen = function (options) { livereload.listen(options); }; LuminousGulp.reload = function (file) { if (file && file.path) { gutil.log(gutil.colors.magenta('./' + path.relative(process.cwd(), file.path)) + ' is changed.'); } livereload.reload('/'); }; module.exports = LuminousGulp;
import { someValue } from './index.js'; assert.equal( someValue, 10 );
// var pheader = '<tr class="header"> <td><a href="javascript:sort(&quot;name&quot;, arr)">Name</a></td> <td><a href="javascript:sort(&quot;data[i]&quot;, arr)">Team</a></td> <td><a href="javascript:sort(&quot;POS&quot;, arr)">Position</a></td> <td><a href="javascript:sort(&quot;gp&quot;, arr)">Games Played</a></td> <td><a href="javascript:sort(&quot;recs&quot;, arr)">Receptions</a></td> <td><a href="javascript:sort(&quot;yards&quot;, arr)">Yards</a></td> <td><a href="javascript:sort(&quot;rectuddies&quot;, arr)">Reception TDs</a></td> <td><a href="javascript:sort(&quot;rushtuddies&quot;, arr)">Rush TDs</a></td> </tr>' var theader = '<tr class="header"> <td><a href="javascript:Tsort(&quot;name&quot;, arr)">Name</a></td> <td><a href="javascript:Tsort(&quot;div&quot;, arr)">Division</a></td></tr>'; var currpos = 'all'; var header = '<thead class="header"> <td><a href="javascript:sort(&quot;lastname&quot;, arr)">Name</a></td> <td><a href="javascript:sort(&quot;team&quot;, arr)">Team</a></td> <td><a href="javascript:sort(&quot;pos&quot;, arr)">Position</a></td> <td><a href="javascript:sort(&quot;yards&quot;, arr)">Yards</a></td> <td><a href="javascript:sort(&quot;passing_tds&quot;, arr)">Passing TDs</a></td> <td><a href="javascript:sort(&quot;passing_int&quot;, arr)">INTs</a></td> <td><a href="javascript:sort(&quot;rectuddies&quot;, arr)">Reception TDs</a></td> <td><a href="javascript:sort(&quot;rushtuddies&quot;, arr)">Rush TDs</a></td></thead>'; function updateTable(pos, data){ function updateCell(i) { var tr = document.createElement('tr'); var tstring = '<td>' + data[i].firstname + " " + data[i].lastname + '</td> <td>' + data[i].team + '</td> <td>' + data[i].pos + '</td>'; if (data[i].pos == 'QB') { tstring = tstring + '<td>' + data[i].passing_yds + '</td>'; } else if (data[i].pos == 'WR') { tstring = tstring + '<td>' + data[i].receiving_yds + '</td>'; } else if (data[i].pos == 'RB') { tstring = tstring + '<td>' + data[i].rushing_yds + '</td>'; } else { tstring = tstring + '<td>0</td>'; } tstring = tstring + '<td>' + data[i].passing_tds + '</td> <td>' + data[i].passing_int + '</td> <td>' + data[i].receiving_tds + '</td> <td>' + data[i].rushing_tds + '</td>'; // tr.innerHTML = "<tr> <td>" + data[i].name + "</td> <td>" + data[i].team + "</td> <td>" + data[i].POS + "</td> <td>" + data[i].gp + "</td> <td>" + data[i].recs + "</td> <td>" + data[i].pyards + "</td> <td>" + data[i].rectuddies + "</td> <td>" + data[i].rushtuddies + "</td> </tr>"; tr.innerHTML = tstring; table.appendChild(tr); return { tr, tstring }; } var table = document.getElementById('table'); table.innerHTML = header; currpos = pos; if(pos == 'all'){ for(var i = 0; i < data.length; i++){ var { tr, tstring } = updateCell(i); } }else if(pos == 'FLEX'){ for(var i = 0; i < data.length; i++){ if(data[i].pos == 'WR' || data[i].pos == 'RB'){ var { tr, tstring } = updateCell(i); } } }else{ for(i = 0; i < data.length; i++){ if(data[i].pos == pos){ var { tr, tstring } = updateCell(i); } } } } function updateTTable(data){ var table = document.getElementById('table'); table.innerHTML = theader; for(i = 0; i < data.length, i < 10; i++){ if(data[i].name != 'name'){ var tr = document.createElement('tr'); tr.innerHTML = '<tr> <td>' + data[i].name + '</td> <td>' + data[i].div + '</td>'; table.appendChild(tr); } } } function searchPlayer(data){ var name = document.getElementById('playerSearch').value; var table = document.getElementById('table'); // table.innerHTML = '<tr class="header"> <td>Name</td> <td>data[i]</td> <td>Position</td> <td>Games Played</td> <td>Receptions</td> <td>Reception TDs</td> <td>Rush TDs</td> </tr>'; table.innerHTML = header; data.forEach(function(Player) { if(Player.name == name){ var tr = document.createElement('tr'); tr.innerHTML = '<tr> <td>' + Player.name + '</td> <td>' + Player.team + '</td> <td>' + Player.POS + '</td> <td>' + Player.gp + '</td> <td>' + Player.recs + '</td> <td>' + (Player.rushyards + Player.recyards) + '</td> <td>' + Player.rectuddies + '</td> <td>' + Player.rushtuddies + '</td> </tr>'; table.appendChild(tr); } }); } function searchTeam(data){ var name = document.getElementById('teamSearch').value; var table = document.getElementById('table'); table.innerHTML = header; data.forEach(function(Team) { if(Team.name == name){ var tr = document.createElement('tr'); tr.innerHTML = '<tr> <td>' + Team.name + '</td> <td>' + Team.team + '</td> <td>' + Team.POS + '</td> <td>' + Team.gp + '</td> <td>' + Team.recs + '</td> <td>' + (Team.rushyards + Team.recyards) + '</td> <td>' + Team.rectuddies + '</td> <td>' + Team.rushtuddies + '</td> </tr>'; table.appendChild(tr); } }); } function sort(param, data){ //sort by name if(param == 'lastname'){ data.sort(function (a, b) { if (a.lastname > b.lastname) { return 1; } if (a.lastname < b.lastname) { return -1; } // a must be equal to b return 0; }); } //sort by team if(param == 'team'){ data.sort(function (a, b) { if (a.team > b.team) { return 1; } if (a.team < b.team) { return -1; } // a must be equal to b return 0; }); } //sort by POS if(param == 'pos'){ data.sort(function (a, b) { if (a.pos > b.pos) { return 1; } if (a.pos < b.pos) { return -1; } // a must be equal to b return 0; }); } // sort by games played if(param == 'yards'){ data.sort(function (a, b) { if ((a.passing_yds + a.rushing_yds + a.receiving_yds) > (b.passing_yds + b.rushing_yds + b.receiving_yds)) { return 1; } if ((a.passing_yds + a.rushing_yds + a.receiving_yds) < (b.passing_yds + b.rushing_yds + b.receiving_yds)) { return -1; } // a must be equal to b return 0; }); } // sort by receptions if(param == 'passing_tds'){ data.sort(function (a, b) { if (a.passing_tds > b.passing_tds) { return 1; } if (a.passing_tds < b.passing_tds) { return -1; } // a must be equal to b return 0; }); } // sort by rectuddies if(param == 'passing_int'){ data.sort(function (a, b) { if (a.passing_int > b.passing_int) { return 1; } if (a.passing_int < b.passing_int) { return -1; } // a must be equal to b return 0; }); } // sort by rushtuddies if(param == 'rushtuddies'){ data.sort(function (a, b) { if (a.rushtuddies > b.rushtuddies) { return 1; } if (a.rushtuddies < b.rushtuddies) { return -1; } // a must be equal to b return 0; }); } updateTable(currpos, data); } function Tsort(param, data){ //sort by name if(param == 'name'){ data.sort(function (a, b) { if (a.name > b.name) { return 1; } if (a.name < b.name) { return -1; } // a must be equal to b return 0; }); } //sort by div if(param == 'div'){ data.sort(function (a, b) { if (a.div > b.div) { return 1; } if (a.div < b.div) { return -1; } // a must be equal to b return 0; }); } updateTTable(data); }
'use strict'; var should = require('chai').should(); var sinon = require('sinon'); var proxyquire = require('proxyquire'); var fs = require('fs'); var sinon = require('sinon'); var readFileSync = sinon.stub().returns(fs.readFileSync(__dirname + '/../data/bitcoin.conf')); var BitcoinService = proxyquire('../../lib/services/bitcoind', { fs: { readFileSync: readFileSync } }); describe('Bitcoin Service', function() { var baseConfig = { node: { datadir: 'testdir', network: { name: 'regtest' } } }; describe('@constructor', function() { it('will create an instance', function() { var bitcoind = new BitcoinService(baseConfig); should.exist(bitcoind); }); it('will create an instance without `new`', function() { var bitcoind = BitcoinService(baseConfig); should.exist(bitcoind); }); }); describe('@dependencies', function() { it('will have no dependencies', function() { BitcoinService.dependencies.should.deep.equal([]); }); }); describe('#_loadConfiguration', function() { it('will parse a bitcoin.conf file', function() { var TestBitcoin = proxyquire('../../lib/services/bitcoind', { fs: { readFileSync: readFileSync, existsSync: sinon.stub().returns(true) }, mkdirp: { sync: sinon.stub() } }); var bitcoind = new TestBitcoin(baseConfig); bitcoind._loadConfiguration({datadir: process.env.HOME + '/.bitcoin'}); should.exist(bitcoind.configuration); bitcoind.configuration.should.deep.equal({ server: 1, whitelist: '127.0.0.1', txindex: 1, port: 20000, rpcallowip: '127.0.0.1', rpcuser: 'bitcoin', rpcpassword: 'local321' }); }); it('should throw an exception if txindex isn\'t enabled in the configuration', function() { var TestBitcoin = proxyquire('../../lib/services/bitcoind', { fs: { readFileSync: sinon.stub().returns(fs.readFileSync(__dirname + '/../data/badbitcoin.conf')), existsSync: sinon.stub().returns(true), }, mkdirp: { sync: sinon.stub() } }); var bitcoind = new TestBitcoin(baseConfig); (function() { bitcoind._loadConfiguration({datadir: './test'}); }).should.throw('Txindex option'); }); it('should set https options if node https options are set', function() { var writeFileSync = function(path, config) { config.should.equal('whitelist=127.0.0.1\ntxindex=1\nrpcssl=1\nrpcsslprivatekeyfile=key.pem\nrpcsslcertificatechainfile=cert.pem\n'); }; var TestBitcoin = proxyquire('../../lib/services/bitcoind', { fs: { writeFileSync: writeFileSync, readFileSync: readFileSync, existsSync: sinon.stub().returns(false) }, mkdirp: { sync: sinon.stub() } }); var config = { node: { datadir: 'testdir', network: { name: 'regtest' }, https: true, httpsOptions: { key: 'key.pem', cert: 'cert.pem' } } }; var bitcoind = new TestBitcoin(config); bitcoind._loadConfiguration({datadir: process.env.HOME + '/.bitcoin'}); }); describe('reindex', function() { var log = require('../../lib/').log; var stub; beforeEach(function() { stub = sinon.stub(log, 'warn'); }); after(function() { stub.restore(); }); it('should warn the user if reindex is set to 1 in the bitcoin.conf file', function() { var readFileSync = function() { return "txindex=1\nreindex=1"; }; var testbitcoin = proxyquire('../../lib/services/bitcoind', { fs: { readFileSync: readFileSync, existsSync: sinon.stub().returns(true) }, mkdirp: { sync: sinon.stub() }, }); var bitcoind = new testbitcoin(baseConfig); bitcoind._loadConfiguration(); stub.callCount.should.equal(1); }); }); }); describe('#_registerEventHandlers', function() { it('will emit tx with transactions from bindings', function(done) { var transaction = {}; var TestBitcoin = proxyquire('../../lib/services/bitcoind', { fs: { readFileSync: readFileSync }, bindings: function(name) { name.should.equal('bitcoind.node'); return { onTipUpdate: sinon.stub(), startTxMon: sinon.stub().callsArgWith(0, [transaction]) }; } }); var bitcoind = new TestBitcoin(baseConfig); bitcoind.on('tx', function(tx) { tx.should.equal(transaction); done(); }); bitcoind._registerEventHandlers(); }); it('will emit tip from bindings', function(done) { var height = 1; var TestBitcoin = proxyquire('../../lib/services/bitcoind', { fs: { readFileSync: readFileSync }, bindings: function(name) { name.should.equal('bitcoind.node'); return { syncPercentage: function() { return height * 10; }, onTipUpdate: function(callback) { if (height >= 10) { return callback(undefined); } setImmediate(function() { callback(height++); }); }, startTxMon: sinon.stub() }; } }); var bitcoind = new TestBitcoin(baseConfig); var tipCallCount = 0; bitcoind.on('tip', function(height) { should.exist(height); tipCallCount++; if (height === 9) { tipCallCount.should.equal(9); done(); } }); bitcoind._registerEventHandlers(); }); }); describe('#_onReady', function(done) { var genesisBuffer = new Buffer('0100000043497fd7f826957108f4a30fd9cec3aeba79972084e90ead01ea330900000000bac8b0fa927c0ac8234287e33c5f74d38d354820e24756ad709d7038fc5f31f020e7494dffff001d03e4b6720101000000010000000000000000000000000000000000000000000000000000000000000000ffffffff0e0420e7494d017f062f503253482fffffffff0100f2052a010000002321021aeaf2f8638a129a3156fbe7e5ef635226b0bafd495ff03afe2c843d7e3a4b51ac00000000', 'hex'); it('will emit ready and set the height and genesisBuffer', function(done) { var TestBitcoin = proxyquire('../../lib/services/bitcoind', { fs: { readFileSync: readFileSync }, bindings: function(name) { name.should.equal('bitcoind.node'); return { onTipUpdate: sinon.stub(), startTxMon: sinon.stub(), getInfo: sinon.stub().returns({ blocks: 101 }), getBlock: sinon.stub().callsArgWith(1, null, genesisBuffer) }; } }); var bitcoind = new TestBitcoin(baseConfig); bitcoind._registerEventHandlers = sinon.stub(); var result = {}; var readyCallCount = 0; bitcoind.on('ready', function() { readyCallCount++; }); bitcoind._onReady(result, function(err) { if (err) { throw err; } bitcoind._registerEventHandlers.callCount.should.equal(1); readyCallCount.should.equal(1); bitcoind.genesisBuffer.should.equal(genesisBuffer); bitcoind.height.should.equal(101); done(); }); }); }); describe('#start', function() { it('call bindings start with the correct arguments', function(done) { var startCallCount = 0; var start = function(obj, cb) { startCallCount++; obj.datadir.should.equal('testdir'); obj.network.should.equal('regtest'); cb(); }; var onBlocksReady = sinon.stub().callsArg(0); var TestBitcoin = proxyquire('../../lib/services/bitcoind', { fs: { readFileSync: readFileSync }, bindings: function(name) { name.should.equal('bitcoind.node'); return { start: start, onBlocksReady: onBlocksReady }; } }); var bitcoind = new TestBitcoin(baseConfig); bitcoind._loadConfiguration = sinon.stub(); bitcoind._onReady = sinon.stub().callsArg(1); bitcoind.start(function(err) { should.not.exist(err); bitcoind._loadConfiguration.callCount.should.equal(1); startCallCount.should.equal(1); onBlocksReady.callCount.should.equal(1); bitcoind._onReady.callCount.should.equal(1); done(); }); }); it('will give an error from bindings.start', function(done) { var start = sinon.stub().callsArgWith(1, new Error('test')); var TestBitcoin = proxyquire('../../lib/services/bitcoind', { fs: { readFileSync: readFileSync }, bindings: function(name) { name.should.equal('bitcoind.node'); return { start: start }; } }); var bitcoind = new TestBitcoin(baseConfig); bitcoind._loadConfiguration = sinon.stub(); bitcoind.start(function(err) { should.exist(err); err.message.should.equal('test'); done(); }); }); it('will give an error from bindings.onBlocksReady', function(done) { var start = sinon.stub().callsArgWith(1, null); var onBlocksReady = sinon.stub().callsArgWith(0, new Error('test')); var TestBitcoin = proxyquire('../../lib/services/bitcoind', { fs: { readFileSync: readFileSync }, bindings: function(name) { name.should.equal('bitcoind.node'); return { start: start, onBlocksReady: onBlocksReady }; } }); var bitcoind = new TestBitcoin(baseConfig); bitcoind._onReady = sinon.stub().callsArg(1); bitcoind._loadConfiguration = sinon.stub(); bitcoind.start(function(err) { should.exist(err); err.message.should.equal('test'); done(); }); }); describe('reindex', function() { var log = require('../../lib/').log; var info; beforeEach(function() { info = sinon.stub(log, 'info'); }); afterEach(function() { info.restore(); }); it('will wait for a reindex to complete before calling the callback.', function(done) { var start = sinon.stub().callsArgWith(1, null); var onBlocksReady = sinon.stub().callsArg(0); var percentage = 98; var TestBitcoin = proxyquire('../../lib/services/bitcoind', { fs: { readFileSync: readFileSync }, bindings: function(name) { return { start: start, onBlocksReady: onBlocksReady, syncPercentage: function() { return percentage; } }; } }); var bitcoind = new TestBitcoin(baseConfig); bitcoind._reindex = true; bitcoind._reindexWait = 1; bitcoind._onReady = sinon.stub().callsArg(1); bitcoind._loadConfiguration = sinon.stub(); bitcoind.start(function() { info.callCount.should.be.within(2,3); bitcoind._reindex.should.be.false; done(); }); setTimeout(function() { percentage = 100; }, 2); }); }); }); describe('#stop', function() { it('will call bindings stop', function() { var stop = sinon.stub().callsArgWith(0, null, 'status'); var TestBitcoin = proxyquire('../../lib/services/bitcoind', { fs: { readFileSync: readFileSync }, bindings: function(name) { name.should.equal('bitcoind.node'); return { stop: stop }; } }); var bitcoind = new TestBitcoin(baseConfig); bitcoind.stop(function(err, status) { stop.callCount.should.equal(1); should.not.exist(err); }); }); it('will give an error from bindings stop', function() { var stop = sinon.stub().callsArgWith(0, new Error('test')); var TestBitcoin = proxyquire('../../lib/services/bitcoind', { fs: { readFileSync: readFileSync }, bindings: function(name) { name.should.equal('bitcoind.node'); return { stop: stop }; } }); var bitcoind = new TestBitcoin(baseConfig); bitcoind.stop(function(err) { stop.callCount.should.equal(1); should.exist(err); err.message.should.equal('test'); }); }); }); describe('proxy methods', function() { var proxyMethods = [ ['isSynced', 0], ['syncPercentage', 0], ['getBlock', 2], ['isSpent', 2], ['getBlockIndex', 1], ['isMainChain', 1], ['estimateFee', 1], ['sendTransaction', 2], ['getTransaction', 3], ['getTransactionWithBlockInfo', 3], ['getMempoolOutputs', 1], ['addMempoolUncheckedTransaction', 1], ['getInfo', 0] ]; proxyMethods.forEach(function(x) { it('pass ' + x[1] + ' argument(s) to ' + x[0], function() { var stub = sinon.stub(); var TestBitcoin = proxyquire('../../lib/services/bitcoind', { fs: { readFileSync: readFileSync }, bindings: function(name) { name.should.equal('bitcoind.node'); var methods = {}; methods[x[0]] = stub; return methods; } }); var bitcoind = new TestBitcoin(baseConfig); var args = []; for (var i = 0; i < x[1]; i++) { args.push(i); } bitcoind[x[0]].apply(bitcoind, args); stub.callCount.should.equal(1); stub.args[0].length.should.equal(x[1]); }); }); }); });
Options.set('collectionsDefaultUpdateTemplate', 'orionHeartbeatCollectionsUpdate'); ReactiveTemplates.set('pages.update', 'orionHeartbeatPagesUpdate');
// COPYRIGHT © 2017 Esri // // All rights reserved under the copyright laws of the United States // and applicable international laws, treaties, and conventions. // // This material is licensed for use under the Esri Master License // Agreement (MLA), and is bound by the terms of that agreement. // You may redistribute and use this code without modification, // provided you adhere to the terms of the MLA and include this // copyright notice. // // See use restrictions at http://www.esri.com/legal/pdfs/mla_e204_e300/english // // For additional information, contact: // Environmental Systems Research Institute, Inc. // Attn: Contracts and Legal Services Department // 380 New York Street // Redlands, California, USA 92373 // USA // // email: contracts@esri.com // // See http://js.arcgis.com/4.4/esri/copyright.txt for details. define(["require","exports","./decorators","./jsxFactory","./widgetUtils"],function(e,r,o,t,i){function n(e){for(var o in e)r.hasOwnProperty(o)||(r[o]=e[o])}Object.defineProperty(r,"__esModule",{value:!0}),n(o),n(t),n(i)});
'use strict'; (function() { // Employer profile view Controller Spec describe('Employer profile view Controller Tests', function() { // Initialize global variables var EmployerProfileViewController, scope, $httpBackend, $stateParams, $location; // The $resource service augments the response object with methods for updating and deleting the resource. // If we were to use the standard toEqual matcher, our tests would fail because the test values would not match // the responses exactly. To solve the problem, we define a new toEqualData Jasmine matcher. // When the toEqualData matcher compares two objects, it takes only object properties into // account and ignores methods. beforeEach(function() { jasmine.addMatchers({ toEqualData: function(util, customEqualityTesters) { return { compare: function(actual, expected) { return { pass: angular.equals(actual, expected) }; } }; } }); }); // Then we can start by loading the main application module beforeEach(module(ApplicationConfiguration.applicationModuleName)); // The injector ignores leading and trailing underscores here (i.e. _$httpBackend_). // This allows us to inject a service but then attach it to a variable // with the same name as the service. beforeEach(inject(function($controller, $rootScope, _$location_, _$stateParams_, _$httpBackend_) { // Set a new global scope scope = $rootScope.$new(); // Point global variables to injected services $stateParams = _$stateParams_; $httpBackend = _$httpBackend_; $location = _$location_; // Initialize the Employer profile view controller. EmployerProfileViewController = $controller('EmployerProfileViewController', { $scope: scope }); })); it('Should do some controller test', inject(function() { // The test logic // ... })); }); }());
version https://git-lfs.github.com/spec/v1 oid sha256:8935846d723ae549df268eb54eaa120003319b3e26aca089dfd2fc3b0f146a7e size 14667
(function($, $$) { var _ = Mavo.UI.Popup = $.Class({ constructor: function(primitive) { this.primitive = primitive; // Need to be defined here so that this is what expected this.position = evt => { var bounds = this.primitive.element.getBoundingClientRect(); var x = bounds.left; var y = bounds.bottom; var pointDown = false; if (this.element.offsetHeight) { // Is in the DOM, check if it fits this.height = this.element.getBoundingClientRect().height || this.height; } if (this.height + y + 20 > innerHeight) { // Normal positioning means the popup would be cut off or too close to the edge, adjust // Perhaps placing it above is better if (bounds.top - this.height > 20) { var pointDown = true; y = bounds.top - this.height - 20; } else { // Nah, just raise it a bit y = innerHeight - this.height - 20; } } this.element.classList.toggle("mv-point-down", pointDown); $.style(this.element, { top: `${y}px`, left: `${x}px` }); }; this.element = $.create("div", { className: "mv-popup", hidden: true, contents: { tag: "fieldset", contents: [ { tag: "legend", textContent: this.primitive.label + ":" }, this.editor ] }, events: { keyup: evt => { if (evt.keyCode == 13 || evt.keyCode == 27) { if (this.element.contains(document.activeElement)) { this.primitive.element.focus(); } evt.stopPropagation(); this.hide(); } }, transitionend: this.position } }); // No point in having a dropdown in a popup if (this.editor.matches("select")) { this.editor.size = Math.min(10, this.editor.children.length); } this.hideCallback = evt => { if (!this.element.contains(evt.target) && !this.primitive.element.contains(evt.target)) { this.hide(); } }; }, show: function() { $.unbind([this.primitive.element, this.element], ".mavo:showpopup"); this.shown = true; this.element.style.transition = "none"; this.element.removeAttribute("hidden"); this.position(); this.element.setAttribute("hidden", ""); this.element.style.transition = ""; document.body.appendChild(this.element); setTimeout(() => { this.element.removeAttribute("hidden"); }, 100); // trigger transition. rAF or timeouts < 100 don't seem to, oddly. $.bind(document, "focus click", this.hideCallback, true); window.addEventListener("scroll", this.position, {passive: true}); }, hide: function() { $.unbind(document, "focus click", this.hideCallback, true); window.removeEventListener("scroll", this.position, {passive: true}); this.element.setAttribute("hidden", ""); // trigger transition this.shown = false; setTimeout(() => { $.remove(this.element); }, parseFloat(getComputedStyle(this.element).transitionDuration) * 1000 || 400); // TODO transition-duration could override this }, prepare: function() { $.bind(this.primitive.element, { "click.mavo:edit": evt => { this.show(); }, "keyup.mavo:edit": evt => { if ([13, 113].indexOf(evt.keyCode) > -1) { // Enter or F2 this.show(); this.editor.focus(); } } }); if (!this.element.contains(this.editor)) { // This can happen if edit type changes from popup to inline this.element.append(this.editor); } }, close: function() { this.hide(); $.unbind(this.primitive.element, ".mavo:edit .mavo:preedit .mavo:showpopup"); }, proxy: { "editor": "primitive" } }); })(Bliss, Bliss.$);
module.exports = isLabelIdentifier; function isLabelIdentifier(path) { const { node } = path; return ( path.parentPath.isLabeledStatement({ label: node }) || path.parentPath.isBreakStatement({ label: node }) || path.parentPath.isContinueStatement({ label: node }) ); }
import gulp from 'gulp'; import es from 'event-stream'; import nugetRestore from 'gulp-nuget-restore'; export default { /** * Task name * @type {String} */ name: 'sitecore:nuget-restore', /** * Task description * @type {String} */ description: 'Restore all nuget packages for solution.', /** * Task default configuration * @type {Object} */ config: { deps: [], }, /** * Task help options * @type {Object} */ help: { 'solution, -s': 'Solution file path', }, /** * Task function * @param {object} config * @param {Function} end * @param {Function} error */ fn(config, end, error) { if (!config.solution) { error('A solution file path was not set.'); return; } gulp.src(config.solution) .pipe(nugetRestore()) .pipe(es.through(() => {})) .on('end', end); }, };
$(document).ready(function () { var $sliderSlick = $('.latest-posts__list'); var $destroyed = true; var $documentSize = $(document).innerWidth(); var $sliderOptions = { arrows: false, dots: true, dotsClass: 'latest-posts__dots', infinite: true, vertical: true, verticalSwiping: true }; if ($documentSize > 600) { $sliderSlick.slick($sliderOptions); $sliderSlick.slick('init', function () { $(this).equalize({ target: '.latest-post__item', property: 'height' }); }); $destroyed = !$destroyed; } $(window).on('resize', function (e) { var documentSize = $(document).innerWidth(); if (documentSize < 600 && !$destroyed) { $sliderSlick.slick('unslick'); $destroyed = !$destroyed; } else if (documentSize >= 600 && $destroyed) { $sliderSlick.slick($sliderOptions); $destroyed = !$destroyed; } }); });
import QItem from './QItem' import QItemMain from './QItemMain' import QItemSide from './QItemSide' function push (child, h, name, slot, replace, conf) { const defaultProps = { props: { right: conf.right } } if (slot && replace) { child.push(h(name, defaultProps, slot)) return } let props, v = false if (!slot) { for (let p in conf) { if (conf.hasOwnProperty(p)) { v = conf[p] if (v !== void 0 && v !== true) { props = true break } } } } if (props || slot) { child.push(h(name, props ? {props: conf} : defaultProps, slot)) } } export default { name: 'q-item-wrapper', functional: true, props: { cfg: { type: Object, default: () => ({}) }, slotReplace: Boolean }, render (h, ctx) { const cfg = ctx.props.cfg, replace = ctx.props.slotReplace, slot = ctx.slots(), child = [] push(child, h, QItemSide, slot.left, replace, { icon: cfg.icon, color: cfg.leftColor, avatar: cfg.avatar, letter: cfg.letter, image: cfg.image }) push(child, h, QItemMain, slot.main, replace, { label: cfg.label, sublabel: cfg.sublabel, labelLines: cfg.labelLines, sublabelLines: cfg.sublabelLines, inset: cfg.inset }) push(child, h, QItemSide, slot.right, replace, { right: true, icon: cfg.rightIcon, color: cfg.rightColor, avatar: cfg.rightAvatar, letter: cfg.rightLetter, image: cfg.rightImage, stamp: cfg.stamp }) if (slot.default) { child.push(slot.default) } ctx.data.props = cfg return h(QItem, ctx.data, child) } }
// Component: QuestionsPage import React from 'react'; import { Redirect } from 'react-router-dom'; import { Header, SubTitle } from 'styles/Layout'; import { QuestionCard, UnansweredList } from 'Questions/ui/dynamicRoutes'; const QuestionListCard = question => <QuestionCard {...question} />; const QuestionsPage = ({ list, questionnaire, ...props }) => { const unanswered = list.filter(o => !o.answered); const completed = list.length > 0 && unanswered.length === 0; if (completed) { return <Redirect to="/results" />; } return ( <> <Header> <h1> Paitent Health Questionnaire <small>(PHQ-9)</small> </h1> </Header> {!completed && <UnansweredList unanswered={unanswered} />} <SubTitle className="subtitle">{questionnaire.subtitle}</SubTitle> <ul className="questions-list"> {list.map(question => ( <QuestionListCard key={question.id} {...question} /> ))} </ul> </> ); }; export default QuestionsPage;
$(document).ready(function() { clickReg(); clickCancel(); logOut(); scheduleThings(); makeAppointments(); });
'use strict'; var pi = require( './../lib' ); console.log( pi );
/* * Object to hold iTunes search query results. * The result from apple is JSON format. This class will support pulling out * specific attributes. */ var Album = require('./album').Album; var Artist = require('./artist').Artist; var Track = require('./track').Track; var iError = require('./ierror').iError; //Track total and completed instances of the class for debugging purposes. var total = 0; var complete = 0; function iResults() { this.glob = ''; this.numGlobs = 0; this.data = ''; this.rawJSON = ''; total++; }; exports.iResults = iResults; //Debugging function. iResults.prototype.stats = function () { return {"complete":complete, "total":total} }; //Builds the intermediary string of results returned by the iTunes web service in pieces. iResults.prototype.capture = function (data) { this.numGlobs++; this.glob += data; }; /* iTunes returns a JSON that contains two elements: a count of the results a single element array containing a JSON of the result set. This function sets the self.data to the actual itunes data set and returns 1 if parsing was successful, 0 otherwise. In this way, the function can be used in an if statement. e.g. if (self.parse) { //analyze & process the data } else { //raise a warning } */ iResults.prototype.parse = function () { var self = this; complete++; // self.stats(); var success = 1; try { self.rawJSON= JSON.parse(self.glob); self.data = self.rawJSON.results; self.hits= self.rawJSON.resultCount; } catch (err) { success = 0; } if (self.data == 'undefined') { console.log('undefined data'); } return success; }; /* Removes an initial 'The' from strings during search. In most cases 'The' should not prevent a match. */ noThe = function(title) { title = title.toLowerCase(); var artArray = title.split(' '); var normal = title; if (artArray[0] == 'the') { artArray.reverse(); artArray.pop(); artArray.reverse(); } normal = artArray.join(' '); return normal } /* Extracts a few items from the iTunes results for an artist search and returns them in an object. */ iResults.prototype.getArtist = function(target,callback) { var artist = null; var error = null; var i = 0; var found = 0; normTargetArtist = noThe(target.artist); var userd = {input: {artist:normTargetArtist}}; //console.log(userd); while (this.data.length > i && found == 0) { var item = this.data[i]; if (item.wrapperType == 'artist') { normItemArtist = noThe(item.artistName); var resultSet = {reply: {artist:normItemArtist}}; //console.log(resultSet); if (item.artistName == target.artist || normItemArtist == normTargetArtist) { var artist = new Artist(item.artistLinkUrl, item.amgArtistId, item.artistId, item.artistName); found = 1; }; }; i++; }; if (found == 0) { error = new iError(11); } callback(error,artist); }; /* Extracts a few items from the iTunes results for an album search and returns them in an object. */ iResults.prototype.getTrack = function(target,callback) { var track = null; var error = null; var i = 0; var found = 0; var resultSet = ''; normTargetArtist = noThe(target.artist); normTargetTrack = noThe(target.track); var userd = {input: {Track:normTargetTrack, Artist:normTargetArtist}}; //console.log(userd); while (this.data.length > i && found == 0) { var item = this.data[i]; if (item.wrapperType == 'track' && item.kind == 'song' ) { normItemArtist = noThe(item.artistName); normItemTrack = noThe(item.trackName); resultSet = {reply: {Track:normItemTrack, Artist:normItemArtist}}; // console.log(resultSet); /* console.log( normTargetArtist + ' ' + normItemArtist + ' ' + normTargetTrack + ' ' + normItemTrack + ' ' );*/ if ((item.artistName == target.artist || normTargetArtist == normItemArtist) && (item.trackName == target.track || normTargetTrack == normItemTrack )) { var track = new Track(item.trackName, item.trackId, item.trackViewUrl, item.artistId, item.artworkUrl60, item.artworkUrl100, item.artistName); found = 1; }; }; i++; }; if (found == 0) { error = new iError(9); }; callback(error,track); }; /* Extracts a few items from the iTunes results for an album search and returns them in an object. */ iResults.prototype.getAlbum = function(target,callback) { var album = null; var error = null; var i = 0; var found = 0; normTargetAlbum = noThe(target.album ); normTargetArtist = noThe(target.artist); var userd = {input: {Track:normTargetAlbum, Artist:normTargetAlbum}}; //console.log(userd); while (this.data.length > i && found == 0) { var item = this.data[i]; if (item.wrapperType == 'collection' && item.collectionType == 'Album') { normItemAlbum = noThe(item.collectionName); normItemArtist = noThe(item.artistName); resultSet = {reply: {Track:normItemAlbum, Artist:normItemArtist}}; //console.log(resultSet); if ((item.artistName == target.artist || normTargetArtist == normItemArtist) && (item.collectionName == target.album || normTargetAlbum == normItemAlbum )) { album = new Album(item.collectionViewUrl, item.amgArtistId, item.artistId, item.collectionName, item.artistName, item.artworkUrl60, item.artworkUrl100); found = 1; } }; i++; }; if (found == 0) { error = new iError(10); }; callback(error,album); };
'use strict'; const autoprefixer = require('autoprefixer'); const path = require('path'); const webpack = require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const ExtractTextPlugin = require('extract-text-webpack-plugin'); const ManifestPlugin = require('webpack-manifest-plugin'); const InterpolateHtmlPlugin = require('react-dev-utils/InterpolateHtmlPlugin'); const SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin'); const eslintFormatter = require('react-dev-utils/eslintFormatter'); const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin'); const paths = require('./paths'); const getClientEnvironment = require('./env'); // Webpack uses `publicPath` to determine where the app is being served from. // It requires a trailing slash, or the file assets will get an incorrect path. const publicPath = paths.servedPath; // Some apps do not use client-side routing with pushState. // For these, "homepage" can be set to "." to enable relative asset paths. const shouldUseRelativeAssetPaths = publicPath === './'; // `publicUrl` is just like `publicPath`, but we will provide it to our app // as %PUBLIC_URL% in `index.html` and `process.env.PUBLIC_URL` in JavaScript. // Omit trailing slash as %PUBLIC_URL%/xyz looks better than %PUBLIC_URL%xyz. const publicUrl = publicPath.slice(0, -1); // Get environment variables to inject into our app. const env = getClientEnvironment(publicUrl); // Assert this just to be safe. // Development builds of React are slow and not intended for production. if (env.stringified['process.env'].NODE_ENV !== '"production"') { throw new Error('Production builds must have NODE_ENV=production.'); } // Note: defined here because it will be used more than once. const cssFilename = 'static/css/[name].[contenthash:8].css'; // ExtractTextPlugin expects the build output to be flat. // (See https://github.com/webpack-contrib/extract-text-webpack-plugin/issues/27) // However, our output is structured with css, js and media folders. // To have this structure working with relative paths, we have to use custom options. const extractTextPluginOptions = shouldUseRelativeAssetPaths ? // Making sure that the publicPath goes back to to build folder. { publicPath: Array(cssFilename.split('/').length).join('../') } : {}; // This is the production configuration. // It compiles slowly and is focused on producing a fast and minimal bundle. // The development configuration is different and lives in a separate file. module.exports = { // Don't attempt to continue if there are any errors. bail: true, // We generate sourcemaps in production. This is slow but gives good results. // You can exclude the *.map files from the build during deployment. devtool: 'source-map', // In production, we only want to load the polyfills and the app code. entry: [require.resolve('./polyfills'), paths.appIndexJs], output: { // The build folder. path: paths.appBuild, // Generated JS file names (with nested folders). // There will be one main bundle, and one file per asynchronous chunk. // We don't currently advertise code splitting but Webpack supports it. filename: 'static/js/[name].[chunkhash:8].js', chunkFilename: 'static/js/[name].[chunkhash:8].chunk.js', // We inferred the "public path" (such as / or /my-project) from homepage. publicPath: publicPath, // Point sourcemap entries to original disk location (format as URL on Windows) devtoolModuleFilenameTemplate: info => path .relative(paths.appSrc, info.absoluteResourcePath) .replace(/\\/g, '/'), }, resolve: { // This allows you to set a fallback for where Webpack should look for modules. // We placed these paths second because we want `node_modules` to "win" // if there are any conflicts. This matches Node resolution mechanism. // https://github.com/facebookincubator/create-react-app/issues/253 modules: ['node_modules', paths.appNodeModules].concat( // It is guaranteed to exist because we tweak it in `env.js` process.env.NODE_PATH.split(path.delimiter).filter(Boolean) ), // These are the reasonable defaults supported by the Node ecosystem. // We also include JSX as a common component filename extension to support // some tools, although we do not recommend using it, see: // https://github.com/facebookincubator/create-react-app/issues/290 // `web` extension prefixes have been added for better support // for React Native Web. extensions: ['.web.js', '.js', '.json', '.web.jsx', '.jsx'], alias: { "react": "preact-compat", "react-dom": "preact-compat", // Support React Native Web // https://www.smashingmagazine.com/2016/08/a-glimpse-into-the-future-with-react-native-for-web/ 'react-native': 'react-native-web', }, plugins: [ // Prevents users from importing files from outside of src/ (or node_modules/). // This often causes confusion because we only process files within src/ with babel. // To fix this, we prevent you from importing files out of src/ -- if you'd like to, // please link the files into your node_modules/ and let module-resolution kick in. // Make sure your source files are compiled, as they will not be processed in any way. new ModuleScopePlugin(paths.appSrc), ], }, module: { strictExportPresence: true, rules: [ // TODO: Disable require.ensure as it's not a standard language feature. // We are waiting for https://github.com/facebookincubator/create-react-app/issues/2176. // { parser: { requireEnsure: false } }, // First, run the linter. // It's important to do this before Babel processes the JS. { test: /\.(js|jsx)$/, enforce: 'pre', use: [ { options: { formatter: eslintFormatter, }, loader: require.resolve('eslint-loader'), }, ], include: paths.appSrc, }, // ** ADDING/UPDATING LOADERS ** // The "file" loader handles all assets unless explicitly excluded. // The `exclude` list *must* be updated with every change to loader extensions. // When adding a new loader, you must add its `test` // as a new entry in the `exclude` list in the "file" loader. // "file" loader makes sure those assets end up in the `build` folder. // When you `import` an asset, you get its filename. { exclude: [ /\.html$/, /\.(js|jsx)$/, /\.css$/, /\.json$/, /\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/, ], loader: require.resolve('file-loader'), options: { name: 'static/media/[name].[hash:8].[ext]', }, }, // "url" loader works just like "file" loader but it also embeds // assets smaller than specified size as data URLs to avoid requests. { test: [/\.bmp$/, /\.gif$/, /\.jpe?g$/, /\.png$/], loader: require.resolve('url-loader'), options: { limit: 10000, name: 'static/media/[name].[hash:8].[ext]', }, }, // Process JS with Babel. { test: /\.(js|jsx)$/, include: paths.appSrc, loader: require.resolve('babel-loader'), options: { compact: true, }, }, // The notation here is somewhat confusing. // "postcss" loader applies autoprefixer to our CSS. // "css" loader resolves paths in CSS and adds assets as dependencies. // "style" loader normally turns CSS into JS modules injecting <style>, // but unlike in development configuration, we do something different. // `ExtractTextPlugin` first applies the "postcss" and "css" loaders // (second argument), then grabs the result CSS and puts it into a // separate file in our build process. This way we actually ship // a single CSS file in production instead of JS code injecting <style> // tags. If you use code splitting, however, any async bundles will still // use the "style" loader inside the async code so CSS from them won't be // in the main CSS file. { test: /\.css$/, loader: ExtractTextPlugin.extract( Object.assign( { fallback: require.resolve('style-loader'), use: [ { loader: require.resolve('css-loader'), options: { importLoaders: 1, minimize: true, sourceMap: true, }, }, { loader: require.resolve('postcss-loader'), options: { // Necessary for external CSS imports to work // https://github.com/facebookincubator/create-react-app/issues/2677 ident: 'postcss', plugins: () => [ require('postcss-flexbugs-fixes'), autoprefixer({ browsers: [ '>1%', 'last 4 versions', 'Firefox ESR', 'not ie < 9', // React doesn't support IE8 anyway ], flexbox: 'no-2009', }), ], }, }, ], }, extractTextPluginOptions ) ), // Note: this won't work without `new ExtractTextPlugin()` in `plugins`. }, // ** STOP ** Are you adding a new loader? // Remember to add the new extension(s) to the "file" loader exclusion list. ], }, plugins: [ // Makes some environment variables available in index.html. // The public URL is available as %PUBLIC_URL% in index.html, e.g.: // <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"> // In production, it will be an empty string unless you specify "homepage" // in `package.json`, in which case it will be the pathname of that URL. new InterpolateHtmlPlugin(env.raw), // Generates an `index.html` file with the <script> injected. new HtmlWebpackPlugin({ inject: true, template: paths.appHtml, minify: { removeComments: true, collapseWhitespace: true, removeRedundantAttributes: true, useShortDoctype: true, removeEmptyAttributes: true, removeStyleLinkTypeAttributes: true, keepClosingSlash: true, minifyJS: true, minifyCSS: true, minifyURLs: true, }, }), // Makes some environment variables available to the JS code, for example: // if (process.env.NODE_ENV === 'production') { ... }. See `./env.js`. // It is absolutely essential that NODE_ENV was set to production here. // Otherwise React will be compiled in the very slow development mode. new webpack.DefinePlugin(env.stringified), // Minify the code. new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false, // Disabled because of an issue with Uglify breaking seemingly valid code: // https://github.com/facebookincubator/create-react-app/issues/2376 // Pending further investigation: // https://github.com/mishoo/UglifyJS2/issues/2011 comparisons: false, }, output: { comments: false, // Turned on because emoji and regex is not minified properly using default // https://github.com/facebookincubator/create-react-app/issues/2488 ascii_only: true, }, sourceMap: true, }), // Note: this won't work without ExtractTextPlugin.extract(..) in `loaders`. new ExtractTextPlugin({ filename: cssFilename, }), // Generate a manifest file which contains a mapping of all asset filenames // to their corresponding output file so that tools can pick it up without // having to parse `index.html`. new ManifestPlugin({ fileName: 'asset-manifest.json', }), // Generate a service worker script that will precache, and keep up to date, // the HTML & assets that are part of the Webpack build. new SWPrecacheWebpackPlugin({ // By default, a cache-busting query parameter is appended to requests // used to populate the caches, to ensure the responses are fresh. // If a URL is already hashed by Webpack, then there is no concern // about it being stale, and the cache-busting can be skipped. dontCacheBustUrlsMatching: /\.\w{8}\./, filename: 'service-worker.js', logger(message) { if (message.indexOf('Total precache size is') === 0) { // This message occurs for every build and is a bit too noisy. return; } if (message.indexOf('Skipping static resource') === 0) { // This message obscures real errors so we ignore it. // https://github.com/facebookincubator/create-react-app/issues/2612 return; } console.log(message); }, minify: true, // For unknown URLs, fallback to the index page navigateFallback: publicUrl + '/index.html', // Ignores URLs starting from /__ (useful for Firebase): // https://github.com/facebookincubator/create-react-app/issues/2237#issuecomment-302693219 navigateFallbackWhitelist: [/^(?!\/__).*/], // Don't precache sourcemaps (they're large) and build asset manifest: staticFileGlobsIgnorePatterns: [/\.map$/, /asset-manifest\.json$/], }), // Moment.js is an extremely popular library that bundles large locale files // by default due to how Webpack interprets its code. This is a practical // solution that requires the user to opt into importing specific locales. // https://github.com/jmblog/how-to-optimize-momentjs-with-webpack // You can remove this if you don't use Moment.js: new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/), ], // Some libraries import Node modules but don't use them in the browser. // Tell Webpack to provide empty mocks for them so importing them works. node: { dgram: 'empty', fs: 'empty', net: 'empty', tls: 'empty', }, };
// Generated on 2014-12-14 using generator-chrome-extension 0.2.11 'use strict'; // # Globbing // for performance reasons we're only matching one level down: // 'test/spec/{,*/}*.js' // use this if you want to recursively match all subfolders: // 'test/spec/**/*.js' module.exports = function (grunt) { // Load grunt tasks automatically require('load-grunt-tasks')(grunt); // Time how long tasks take. Can help when optimizing build times require('time-grunt')(grunt); // Configurable paths var config = { app: 'app', dist: 'dist' }; grunt.initConfig({ // Project settings config: config, // Watches files for changes and runs tasks based on the changed files watch: { bower: { files: ['bower.json'], tasks: ['bowerInstall'] }, js: { files: ['<%= config.app %>/scripts/{,*/}*.js'], tasks: ['jshint'], options: { livereload: true } }, gruntfile: { files: ['Gruntfile.js'] }, styles: { files: ['<%= config.app %>/styles/{,*/}*.css'], tasks: [], options: { livereload: true } }, livereload: { options: { livereload: '<%= connect.options.livereload %>' }, files: [ '<%= config.app %>/*.html', '<%= config.app %>/public/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}', '<%= config.app %>/manifest.json', '<%= config.app %>/_locales/{,*/}*.json' ] } }, // Grunt server and debug server setting connect: { options: { port: 9000, livereload: 35729, // change this to '0.0.0.0' to access the server from outside hostname: 'localhost' }, chrome: { options: { open: false, base: [ '<%= config.app %>' ] } }, test: { options: { open: false, base: [ 'test', '<%= config.app %>' ] } } }, // Empties folders to start fresh clean: { chrome: { }, dist: { files: [{ dot: true, src: [ '<%= config.dist %>/*', '!<%= config.dist %>/.git*' ] }] } }, // Make sure code styles are up to par and there are no obvious mistakes jshint: { options: { jshintrc: '.jshintrc', reporter: require('jshint-stylish') }, all: [ 'Gruntfile.js', '<%= config.app %>/scripts/{,*/}*.js', '!<%= config.app %>/scripts/vendor/*', 'test/spec/{,*/}*.js' ] }, mocha: { all: { options: { run: true, urls: ['http://localhost:<%= connect.options.port %>/index.html'] } } }, // Automatically inject Bower components into the HTML file bowerInstall: { app: { src: [ '<%= config.app %>/*.html' ] } }, // Reads HTML for usemin blocks to enable smart builds that automatically // concat, minify and revision files. Creates configurations in memory so // additional tasks can operate on them useminPrepare: { options: { dest: '<%= config.dist %>' }, html: [ '<%= config.app %>/popup.html', '<%= config.app %>/options.html' ] }, // Performs rewrites based on rev and the useminPrepare configuration usemin: { options: { assetsDirs: ['<%= config.dist %>', '<%= config.dist %>/images'] }, html: ['<%= config.dist %>/{,*/}*.html'], css: ['<%= config.dist %>/styles/{,*/}*.css'] }, // The following *-min tasks produce minifies files in the dist folder imagemin: { dist: { files: [{ expand: true, cwd: '<%= config.app %>/public/images', src: '{,*/}*.{gif,jpeg,jpg,png}', dest: '<%= config.dist %>/public/images' }] } }, svgmin: { dist: { files: [{ expand: true, cwd: '<%= config.app %>/public/images', src: '{,*/}*.svg', dest: '<%= config.dist %>/public/images' }] } }, htmlmin: { dist: { options: { // removeCommentsFromCDATA: true, // collapseWhitespace: true, // collapseBooleanAttributes: true, // removeAttributeQuotes: true, // removeRedundantAttributes: true, // useShortDoctype: true, // removeEmptyAttributes: true, // removeOptionalTags: true }, files: [{ expand: true, cwd: '<%= config.app %>', src: '*.html', dest: '<%= config.dist %>' }] } }, // By default, your `index.html`'s <!-- Usemin block --> will take care of // minification. These next options are pre-configured if you do not wish // to use the Usemin blocks. cssmin: { dist: { files: { '<%= config.dist %>/styles/main.css': [ '<%= config.app %>/styles/{,*/}*.css' ] } } }, uglify: { dist: { files: { '<%= config.dist %>/scripts/scripts.js': [ '<%= config.dist %>/scripts/scripts.js' ] } } }, concat: { dist: {} }, // Copies remaining files to places other tasks can use copy: { dist: { files: [{ expand: true, dot: true, cwd: '<%= config.app %>', dest: '<%= config.dist %>', src: [ '*.{ico,png,txt}', 'public/images/{,*/}*.{webp,gif}', '{,*/}*.html', 'public/styles/{,*/}*.css', 'public/components/bootstrap/dist/css/bootstrap.min.css', 'public/components/bootstrap/dist/fonts/glyphicons-halflings-regular.woff', 'public/styles/fonts/{,*/}*.*', '_locales/{,*/}*.json', 'public/scripts/{,*/}*.js', 'public/components/jquery/dist/jquery.min.js', 'public/components/angular/angular.min.js', 'public/components/angular-route/angular-route.min.js', 'public/components/bootstrap/dist/js/bootstrap.min.js' ] }] } }, // Run some tasks in parallel to speed up build process concurrent: { chrome: [ ], dist: [ 'imagemin', 'svgmin' ], test: [ ] }, // Auto buildnumber, exclude debug files. smart builds that event pages chromeManifest: { dist: { options: { buildnumber: true, background: { target: 'scripts/background.js', exclude: [ 'scripts/chromereload.js' ] } }, src: '<%= config.app %>', dest: '<%= config.dist %>' } }, // Compres dist files to package compress: { dist: { options: { archive: function() { var manifest = grunt.file.readJSON('app/manifest.json'); return 'package/nextdatavizevents-' + manifest.version + '.zip'; } }, files: [{ expand: true, cwd: 'dist/', src: ['**'], dest: '' }] } } }); grunt.registerTask('debug', function () { grunt.task.run([ 'jshint', 'concurrent:chrome', 'connect:chrome', 'watch' ]); }); grunt.registerTask('test', [ 'connect:test', 'mocha' ]); grunt.registerTask('build', [ 'clean:dist', 'chromeManifest:dist', 'useminPrepare', 'concurrent:dist', // No UI feature selected, cssmin task will be commented // 'cssmin', 'concat', 'uglify', 'copy', 'usemin', 'compress' ]); grunt.registerTask('default', [ 'jshint', 'test', 'build' ]); };
import React from 'react'; import { compose, mapProps } from 'recompose'; import { withRouter } from '@ui/NativeWebRouter'; import BackgroundView from '@ui/BackgroundView'; import SavedPaymentReviewForm from '@ui/forms/SavedPaymentReviewForm'; import PaddedView from '@ui/PaddedView'; import { Title, Row, TinyButton, TinyButtonText } from '../styles'; const enhance = compose( withRouter, mapProps(props => ({ onPressEdit() { props.history.push('address'); }, })), ); const PaymentMethodConfirmation = enhance(({ onPressEdit }) => ( <BackgroundView> <PaddedView> <Row> <Title>Review</Title> <TinyButton onPress={onPressEdit}> <TinyButtonText>Edit</TinyButtonText> </TinyButton> </Row> </PaddedView> <SavedPaymentReviewForm navigateToOnComplete="done" /> </BackgroundView> )); export default PaymentMethodConfirmation;
import { combineReducers } from 'redux'; import todoReducer from './todoReducer'; import userReducer from './userReducer'; const rootReducer = combineReducers({ todos: todoReducer, user: userReducer }); export default rootReducer;