code
stringlengths
2
1.05M
version https://git-lfs.github.com/spec/v1 oid sha256:fd0bc3773d4b49f811a360c65d809d09019c1916da1346bd89c49c71b225193f size 62450
version https://git-lfs.github.com/spec/v1 oid sha256:70e41128e3047c752ac90e54ed4b12155d8358f9f452ce17145a44c930c22d03 size 158903
version https://git-lfs.github.com/spec/v1 oid sha256:05ef65f7c2f572a3134108e9091e69b4a3bffdf20a5f05e9f9d0e5333564a7b0 size 107584
/* * AboutPage Messages * * This contains all the text for the AboutPage component. */ import { defineMessages } from 'react-intl'; export default defineMessages({ header: { id: 'app.containers.AboutPage.header', defaultMessage: 'This is AboutPage container !', }, });
/** @jsx React.DOM */ var React = require('react/addons'); var cx = require('classnames'); var Label = React.createClass({ propTypes: { id: React.PropTypes.string.isRequired, fixed: React.PropTypes.bool.isRequired, large: React.PropTypes.bool.isRequired, text: React.PropTypes.string.isRequired }, render: function() { var labelClass = cx({ 'Label': true, 'Label--fixed': this.props.fixed, 'Label--regular': !this.props.large, 'Label--large': this.props.large }); return ( <div className={labelClass} id={this.props.id}> <h3> {this.props.text} </h3> </div> ); } }); module.exports = Label;
import TwitchSerializer from "data/models/twitch/serializer"; export default TwitchSerializer.extend({ primaryKey: "regex", modelNameFromPayloadKey() { return "twitchProductEmoticon"; } });
/** * @fileoverview Enforce component methods order * @author Yannick Croissant */ 'use strict'; var util = require('util'); var Components = require('../util/Components'); /** * Get the methods order from the default config and the user config * @param {Object} defaultConfig The default configuration. * @param {Object} userConfig The user configuration. * @returns {Array} Methods order */ function getMethodsOrder(defaultConfig, userConfig) { userConfig = userConfig || {}; var groups = util._extend(defaultConfig.groups, userConfig.groups); var order = userConfig.order || defaultConfig.order; var config = []; var entry; for (var i = 0, j = order.length; i < j; i++) { entry = order[i]; if (groups.hasOwnProperty(entry)) { config = config.concat(groups[entry]); } else { config.push(entry); } } return config; } // ------------------------------------------------------------------------------ // Rule Definition // ------------------------------------------------------------------------------ module.exports = Components.detect(function(context, components) { var errors = {}; var MISPOSITION_MESSAGE = '{{propA}} must be placed {{position}} {{propB}}'; var methodsOrder = getMethodsOrder({ order: [ 'lifecycle', 'everything-else', 'render' ], groups: { lifecycle: [ 'displayName', 'propTypes', 'contextTypes', 'childContextTypes', 'mixins', 'statics', 'defaultProps', 'constructor', 'getDefaultProps', 'state', 'getInitialState', 'getChildContext', 'componentWillMount', 'componentDidMount', 'componentWillReceiveProps', 'shouldComponentUpdate', 'componentWillUpdate', 'componentDidUpdate', 'componentWillUnmount' ] } }, context.options[0]); /** * Checks if the component must be validated * @param {Object} component The component to process * @returns {Boolean} True if the component must be validated, false if not. */ function mustBeValidated(component) { return ( component && !component.hasDisplayName ); } // -------------------------------------------------------------------------- // Public // -------------------------------------------------------------------------- var regExpRegExp = /\/(.*)\/([g|y|i|m]*)/; /** * Get indexes of the matching patterns in methods order configuration * @param {String} method - Method name. * @returns {Array} The matching patterns indexes. Return [Infinity] if there is no match. */ function getRefPropIndexes(method) { var isRegExp; var matching; var i; var j; var indexes = []; for (i = 0, j = methodsOrder.length; i < j; i++) { isRegExp = methodsOrder[i].match(regExpRegExp); if (isRegExp) { matching = new RegExp(isRegExp[1], isRegExp[2]).test(method); } else { matching = methodsOrder[i] === method; } if (matching) { indexes.push(i); } } // No matching pattern, return 'everything-else' index if (indexes.length === 0) { for (i = 0, j = methodsOrder.length; i < j; i++) { if (methodsOrder[i] === 'everything-else') { indexes.push(i); } } } // No matching pattern and no 'everything-else' group if (indexes.length === 0) { indexes.push(Infinity); } return indexes; } /** * Get properties name * @param {Object} node - Property. * @returns {String} Property name. */ function getPropertyName(node) { // Special case for class properties // (babel-eslint does not expose property name so we have to rely on tokens) if (node.type === 'ClassProperty') { var tokens = context.getFirstTokens(node, 2); return tokens[1].type === 'Identifier' ? tokens[1].value : tokens[0].value; } return node.key.name; } /** * Store a new error in the error list * @param {Object} propA - Mispositioned property. * @param {Object} propB - Reference property. */ function storeError(propA, propB) { // Initialize the error object if needed if (!errors[propA.index]) { errors[propA.index] = { node: propA.node, score: 0, closest: { distance: Infinity, ref: { node: null, index: 0 } } }; } // Increment the prop score errors[propA.index].score++; // Stop here if we already have a closer reference if (Math.abs(propA.index - propB.index) > errors[propA.index].closest.distance) { return; } // Update the closest reference errors[propA.index].closest.distance = Math.abs(propA.index - propB.index); errors[propA.index].closest.ref.node = propB.node; errors[propA.index].closest.ref.index = propB.index; } /** * Dedupe errors, only keep the ones with the highest score and delete the others */ function dedupeErrors() { for (var i in errors) { if (!errors.hasOwnProperty(i)) { continue; } var index = errors[i].closest.ref.index; if (!errors[index]) { continue; } if (errors[i].score > errors[index].score) { delete errors[index]; } else { delete errors[i]; } } } /** * Report errors */ function reportErrors() { dedupeErrors(); var nodeA; var nodeB; var indexA; var indexB; for (var i in errors) { if (!errors.hasOwnProperty(i)) { continue; } nodeA = errors[i].node; nodeB = errors[i].closest.ref.node; indexA = i; indexB = errors[i].closest.ref.index; context.report(nodeA, MISPOSITION_MESSAGE, { propA: getPropertyName(nodeA), propB: getPropertyName(nodeB), position: indexA < indexB ? 'before' : 'after' }); } } /** * Get properties for a given AST node * @param {ASTNode} node The AST node being checked. * @returns {Array} Properties array. */ function getComponentProperties(node) { if (node.type === 'ClassDeclaration') { return node.body.body; } return node.properties; } /** * Compare two properties and find out if they are in the right order * @param {Array} propertiesNames Array containing all the properties names. * @param {String} propA First property name. * @param {String} propB Second property name. * @returns {Object} Object containing a correct true/false flag and the correct indexes for the two properties. */ function comparePropsOrder(propertiesNames, propA, propB) { var i; var j; var k; var l; var refIndexA; var refIndexB; // Get references indexes (the correct position) for given properties var refIndexesA = getRefPropIndexes(propA); var refIndexesB = getRefPropIndexes(propB); // Get current indexes for given properties var classIndexA = propertiesNames.indexOf(propA); var classIndexB = propertiesNames.indexOf(propB); // Loop around the references indexes for the 1st property for (i = 0, j = refIndexesA.length; i < j; i++) { refIndexA = refIndexesA[i]; // Loop around the properties for the 2nd property (for comparison) for (k = 0, l = refIndexesB.length; k < l; k++) { refIndexB = refIndexesB[k]; if ( // Comparing the same properties refIndexA === refIndexB || // 1st property is placed before the 2nd one in reference and in current component refIndexA < refIndexB && classIndexA < classIndexB || // 1st property is placed after the 2nd one in reference and in current component refIndexA > refIndexB && classIndexA > classIndexB ) { return { correct: true, indexA: classIndexA, indexB: classIndexB }; } } } // We did not find any correct match between reference and current component return { correct: false, indexA: refIndexA, indexB: refIndexB }; } /** * Check properties order from a properties list and store the eventual errors * @param {Array} properties Array containing all the properties. */ function checkPropsOrder(properties) { var propertiesNames = properties.map(getPropertyName); var i; var j; var k; var l; var propA; var propB; var order; // Loop around the properties for (i = 0, j = propertiesNames.length; i < j; i++) { propA = propertiesNames[i]; // Loop around the properties a second time (for comparison) for (k = 0, l = propertiesNames.length; k < l; k++) { propB = propertiesNames[k]; // Compare the properties order order = comparePropsOrder(propertiesNames, propA, propB); // Continue to next comparison is order is correct if (order.correct === true) { continue; } // Store an error if the order is incorrect storeError({ node: properties[i], index: order.indexA }, { node: properties[k], index: order.indexB }); } } } return { 'Program:exit': function() { var list = components.list(); for (var component in list) { if (!list.hasOwnProperty(component) || !mustBeValidated(list[component])) { continue; } var properties = getComponentProperties(list[component].node); checkPropsOrder(properties); } reportErrors(); } }; }); module.exports.schema = [{ type: 'object', properties: { order: { type: 'array', items: { type: 'string' } }, groups: { type: 'object', patternProperties: { '^.*$': { type: 'array', items: { type: 'string' } } } } }, additionalProperties: false }];
'use strict'; import angular from 'angular'; class ArticlesService { constructor($http, settings) { this.http = $http; this.settings = settings; } getAll(query) { return this.http .get(this.settings.apiUrl + '/articles', {params: query}) .then((response) => { return response.data; }); } } angular.module('lmd.app') .service('ArticlesService', ArticlesService);
'use strict'; var test = require('tap').test; var DrSax = require('../index'); test('should never be four newlines in a row', function(t){ var drsax = new DrSax(); var output = drsax.write('<p>this is a test<p>of newline issues'); t.equal(output.match(/\n\n\n\n/), null, 'block level elements generate correct line spacing'); t.end(); });
'use strict'; // Keeps track of wallet status results var wallet = {}; // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Lock Icon ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Helper function for the lock-icon to make sure its classes are cleared function setLockIcon(lockStatus, lockAction, iconClass) { $('#status span').text(lockStatus); $('#lock.button span').text(lockAction); $('#lock.button .fa').get(0).className = 'fa ' + iconClass; } // Markup changes to reflect state function setLocked() { setLockIcon('Locked', 'Unlock Wallet', 'fa-lock'); } function setUnlocked() { setLockIcon('Unlocked', 'Lock Wallet', 'fa-unlock'); } function setUnlocking() { setLockIcon('Unlocking', 'Unlocking', 'fa-cog fa-spin'); } function setUnencrypted() { setLockIcon('New Wallet', 'Create Wallet', 'fa-plus'); } // Update wallet summary in header capsule function updateStatus(result) { wallet = result; // Show correct lock status. if (!wallet.encrypted) { setUnencrypted(); } else if (!wallet.unlocked) { setLocked(); } else if (wallet.unlocked) { setUnlocked(); } // Update balance confirmed and uncomfirmed var bal = convertSiacoin(wallet.confirmedsiacoinbalance); var pend = convertSiacoin(wallet.unconfirmedincomingsiacoins).sub(convertSiacoin(wallet.unconfirmedoutgoingsiacoins)); if (wallet.unlocked && wallet.encrypted) { // TODO: Janky fix for graphical difficulty where a 2px border line appears when 1px is expected $('#status.pod').css('border-left', '1px solid #00CBA0'); $('#confirmed').show(); $('#unconfirmed').show(); $('#confirmed').html('Balance: ' + bal + ' S'); $('#unconfirmed').html('Pending: ' + pend + ' S'); } else { // TODO: Janky fix for graphical difficulty where a 2px border line appears when 1px is expected $('#status.pod').css('border-left', 'none'); $('#confirmed').hide(); $('#unconfirmed').hide(); } } // Make wallet api call function getStatus() { Siad.apiCall('/wallet', updateStatus); } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Locking ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Lock the wallet function lock() { Siad.apiCall({ url: '/wallet/lock', method: 'POST', }, function(result) { notify('Wallet locked', 'locked'); update(); }); } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Unlocking ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Unlock the wallet function unlock(password) { // Password attempted, show responsive processing icon setUnlocking(); Siad.call({ url: '/wallet/unlock', method: 'POST', qs: { encryptionpassword : password, }, }, function(err, result) { if (err) { notify('Wrong password', 'error'); $('#request-password').show(); } else { notify('Wallet unlocked', 'unlocked'); } update(); }); } // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Encrypting ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Encrypt the wallet (only applies to first time opening) function encrypt() { Siad.apiCall({ url: '/wallet/init', method: 'POST', qs: { dictionary: 'english', }, }, function(result) { setLocked(); var popup = $('#show-password'); popup.show(); // Clear old password in config if there is one var settings = IPCRenderer.sendSync('config', 'wallet'); if (settings) { settings.password = null; } else { settings = {password: null}; } IPCRenderer.sendSync('config', 'wallet', settings); // Show password in the popup $('#generated-password').text(result.primaryseed); update(); }); }
var testConsumer = { i : function (raw, date, collection, object) { insertTestResult = { raw : raw, date : date, collection : collection, object : object }; }, u : function (raw, date, collection, objectId, update) { updateTestResult = { raw : raw, date : date, collection : collection, objectId : objectId, update : update }; }, d : function (raw, date, collection, objectId, success) { deleteTestResult = { raw : raw, date : date, collection : collection, objectId : objectId, success : success }; }, c : function (raw, date, collection) { commandTestResult = { raw : raw, date : date, collection : collection }; } }; module.exports = testConsumer;
var app = angular.module( 'TagConverter', [] ); app.controller( 'TagConverterController', function ( $scope ) { $scope.Number = window.Number; $scope.digits = [ 1, 0, 0, 0, 0, 0, 1, 1, 0, 1, 0, 0 ]; $scope.flipDigit = function ( index ) { $scope.digits[ index ] = $scope.digits[ index ] ^ 1; }; $scope.showGrid = false; $scope.toggleShowGrid = function () { $scope.showGrid = !$scope.showGrid; }; $scope.mode = 0; $scope.setMode = function ( mode ) { $scope.mode = mode; }; $scope.modeDefs = [ { significance: [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ], read: { dir: -1, rot: -75 }, sig: { dir: 1, rot: 15 } }, { significance: [ 7, 6, 5, 4, 3, 2, 1, 0, 'parity', 10, 9, 8 ], read: { dir: 1, rot: -75 }, sig: { dir: -1, rot: 165 } } ]; var toInt = function ( mode ) { var sum = 0; $scope.digits.forEach( function ( v, i ) { var s = $scope.modeDefs[ mode ].significance[ i ]; if ( Number.isInteger( s ) ) { sum += v * Math.pow( 2, s ); } } ); return sum; }; var toArray = function ( int, mode ) { var result = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]; var i = 0; while ( int > 0 ) { result[ i ] = ( int & 1 ); int >>= 1; i++; } $scope.modeDefs[ mode ].significance.forEach( function ( s, i ) { if ( Number.isInteger( s ) ) { $scope.digits[ i ] = result[ s ]; } } ); }; $scope.decoderId = 705; $scope.$watchCollection( 'digits', function () { $scope.decoderId = toInt( 0 ); } ); $scope.$watch( 'decoderId', function () { toArray( $scope.decoderId, 0 ); } ); $scope.preparationId = 1155; $scope.$watchCollection( 'digits', function () { $scope.preparationId = toInt( 1 ); } ); $scope.$watch( 'preparationId', function () { var p = $scope.parity(); toArray( $scope.preparationId, 1 ); if ( $scope.parity() !== p ) { $scope.digits[ 8 ] = $scope.digits[ 8 ] ^ 1; } } ); $scope.parity = function () { var sum = $scope.digits.reduce( function ( a, b, i ) { return a + ( i !== 8 ? b : 0 ); } ); return $scope.digits[ 8 ] === ( sum & 1 ); }; });
'use strict'; const path = require('path'); const serveStatic = require('feathers').static; const favicon = require('serve-favicon'); const compress = require('compression'); const cors = require('cors'); const feathers = require('feathers'); const configuration = require('feathers-configuration'); const hooks = require('feathers-hooks'); const rest = require('feathers-rest'); const bodyParser = require('body-parser'); const socketio = require('feathers-socketio'); const middleware = require('./middleware'); const services = require('./services'); const models = require('./models'); const relateModels = require('./relate-models'); const app = feathers(); app.configure(configuration(path.join(__dirname, '..'))); app.use(compress()) .options('*', cors()) .use(cors()) .use(favicon( path.join(app.get('public'), 'favicon.ico') )) .use('/', serveStatic( app.get('public') )) .use(bodyParser.json()) .use(bodyParser.urlencoded({ extended: true })) .configure(hooks()) .configure(rest()) .configure(socketio()) .configure(models) .configure(services) .configure(middleware); // I don't know why this works, but it does...or rather, it did. It's broken // now for some obscure reason I can't put my finger on. // Meh. relateModels(app); module.exports = app;
'use strict'; exports.find = function(req, res, next){ req.query.username = req.query.username ? req.query.username : ''; req.query.limit = req.query.limit ? parseInt(req.query.limit, null) : 20; req.query.page = req.query.page ? parseInt(req.query.page, null) : 1; req.query.sort = req.query.sort ? req.query.sort : '_id'; var filters = {}; if (req.query.username) { filters.username = new RegExp('^.*?'+ req.query.username +'.*$', 'i'); } if (req.query.isActive) { filters.isActive = req.query.isActive; } if (req.query.isTutor) { filters.isTutor = req.query.isTutor; } if (req.query.roles && req.query.roles === 'admin') { filters['roles.admin'] = { $exists: true }; } if (req.query.roles && req.query.roles === 'account') { filters['roles.account'] = { $exists: true }; } req.app.db.models.User.pagedFind({ filters: filters, keys: 'username email isActive isTutor', limit: req.query.limit, page: req.query.page, sort: req.query.sort }, function(err, results) { if (err) { return next(err); } if (req.xhr) { res.header("Cache-Control", "no-cache, no-store, must-revalidate"); results.filters = req.query; res.send(results); } else { results.filters = req.query; res.render('admin/users/index', { data: { results: JSON.stringify(results) } }); } }); }; exports.read = function(req, res, next){ req.app.db.models.User.findById(req.params.id).populate('roles.admin', 'name.full').populate('roles.account', 'name.full').exec(function(err, user) { if (err) { return next(err); } if (req.xhr) { res.send(user); } else { res.render('admin/users/details', { data: { record: escape(JSON.stringify(user)) } }); } }); }; exports.create = function(req, res, next){ var workflow = req.app.utility.workflow(req, res); workflow.on('validate', function() { if (!req.body.username) { workflow.outcome.errors.push('Please enter a username.'); return workflow.emit('response'); } if (!/^[a-zA-Z0-9\-\_]+$/.test(req.body.username)) { workflow.outcome.errors.push('only use letters, numbers, -, _'); return workflow.emit('response'); } workflow.emit('duplicateUsernameCheck'); }); workflow.on('duplicateUsernameCheck', function() { req.app.db.models.User.findOne({ username: req.body.username }, function(err, user) { if (err) { return workflow.emit('exception', err); } if (user) { workflow.outcome.errors.push('That username is already taken.'); return workflow.emit('response'); } workflow.emit('createUser'); }); }); workflow.on('createUser', function() { var fieldsToSet = { username: req.body.username, search: [ req.body.username ] }; req.app.db.models.User.create(fieldsToSet, function(err, user) { if (err) { return workflow.emit('exception', err); } workflow.outcome.record = user; return workflow.emit('response'); }); }); workflow.emit('validate'); }; exports.update = function(req, res, next){ var workflow = req.app.utility.workflow(req, res); workflow.on('validate', function() { if (!req.body.isActive) { req.body.isActive = 'no'; } if (!req.body.isTutor) { req.body.isTutor = 'no'; } if (!req.body.username) { workflow.outcome.errfor.username = 'required'; } else if (!/^[a-zA-Z0-9\-\_]+$/.test(req.body.username)) { workflow.outcome.errfor.username = 'only use letters, numbers, \'-\', \'_\''; } if (!req.body.email) { workflow.outcome.errfor.email = 'required'; } else if (!/^[a-zA-Z0-9\-\_\.\+]+@[a-zA-Z0-9\-\_\.]+\.[a-zA-Z0-9\-\_]+$/.test(req.body.email)) { workflow.outcome.errfor.email = 'invalid email format'; } if (workflow.hasErrors()) { return workflow.emit('response'); } workflow.emit('duplicateUsernameCheck'); }); workflow.on('duplicateUsernameCheck', function() { req.app.db.models.User.findOne({ username: req.body.username, _id: { $ne: req.params.id } }, function(err, user) { if (err) { return workflow.emit('exception', err); } if (user) { workflow.outcome.errfor.username = 'username already taken'; return workflow.emit('response'); } workflow.emit('duplicateEmailCheck'); }); }); workflow.on('duplicateEmailCheck', function() { req.app.db.models.User.findOne({ email: req.body.email.toLowerCase(), _id: { $ne: req.params.id } }, function(err, user) { if (err) { return workflow.emit('exception', err); } if (user) { workflow.outcome.errfor.email = 'email already taken'; return workflow.emit('response'); } workflow.emit('patchUser'); }); }); workflow.on('patchUser', function() { var fieldsToSet = { isActive: req.body.isActive, isTutor: req.body.isTutor, username: req.body.username, email: req.body.email.toLowerCase(), search: [ req.body.username, req.body.email ] }; req.app.db.models.User.findByIdAndUpdate(req.params.id, fieldsToSet, function(err, user) { if (err) { return workflow.emit('exception', err); } workflow.emit('patchAdmin', user); }); }); workflow.on('patchAdmin', function(user) { if (user.roles.admin) { var fieldsToSet = { user: { id: req.params.id, name: user.username } }; req.app.db.models.Admin.findByIdAndUpdate(user.roles.admin, fieldsToSet, function(err, admin) { if (err) { return workflow.emit('exception', err); } workflow.emit('patchAccount', user); }); } else { workflow.emit('patchAccount', user); } }); workflow.on('patchAccount', function(user) { if (user.roles.account) { var fieldsToSet = { user: { id: req.params.id, name: user.username } }; req.app.db.models.Account.findByIdAndUpdate(user.roles.account, fieldsToSet, function(err, account) { if (err) { return workflow.emit('exception', err); } workflow.emit('populateRoles', user); }); } else { workflow.emit('populateRoles', user); } }); workflow.on('populateRoles', function(user) { user.populate('roles.admin roles.account', 'name.full', function(err, populatedUser) { if (err) { return workflow.emit('exception', err); } workflow.outcome.user = populatedUser; workflow.emit('response'); }); }); workflow.emit('validate'); }; exports.password = function(req, res, next){ var workflow = req.app.utility.workflow(req, res); workflow.on('validate', function() { if (!req.body.newPassword) { workflow.outcome.errfor.newPassword = 'required'; } if (!req.body.confirm) { workflow.outcome.errfor.confirm = 'required'; } if (req.body.newPassword !== req.body.confirm) { workflow.outcome.errors.push('Passwords do not match.'); } if (workflow.hasErrors()) { return workflow.emit('response'); } workflow.emit('patchUser'); }); workflow.on('patchUser', function() { req.app.db.models.User.encryptPassword(req.body.newPassword, function(err, hash) { if (err) { return workflow.emit('exception', err); } var fieldsToSet = { password: hash }; req.app.db.models.User.findByIdAndUpdate(req.params.id, fieldsToSet, function(err, user) { if (err) { return workflow.emit('exception', err); } user.populate('roles.admin roles.account', 'name.full', function(err, user) { if (err) { return workflow.emit('exception', err); } workflow.outcome.user = user; workflow.outcome.newPassword = ''; workflow.outcome.confirm = ''; workflow.emit('response'); }); }); }); }); workflow.emit('validate'); }; exports.linkAdmin = function(req, res, next){ var workflow = req.app.utility.workflow(req, res); workflow.on('validate', function() { if (!req.user.roles.admin.isMemberOf('root')) { workflow.outcome.errors.push('You may not link users to admins.'); return workflow.emit('response'); } if (!req.body.newAdminId) { workflow.outcome.errfor.newAdminId = 'required'; return workflow.emit('response'); } workflow.emit('verifyAdmin'); }); workflow.on('verifyAdmin', function(callback) { req.app.db.models.Admin.findById(req.body.newAdminId).exec(function(err, admin) { if (err) { return workflow.emit('exception', err); } if (!admin) { workflow.outcome.errors.push('Admin not found.'); return workflow.emit('response'); } if (admin.user.id && admin.user.id !== req.params.id) { workflow.outcome.errors.push('Admin is already linked to a different user.'); return workflow.emit('response'); } workflow.admin = admin; workflow.emit('duplicateLinkCheck'); }); }); workflow.on('duplicateLinkCheck', function(callback) { req.app.db.models.User.findOne({ 'roles.admin': req.body.newAdminId, _id: {$ne: req.params.id} }).exec(function(err, user) { if (err) { return workflow.emit('exception', err); } if (user) { workflow.outcome.errors.push('Another user is already linked to that admin.'); return workflow.emit('response'); } workflow.emit('patchUser'); }); }); workflow.on('patchUser', function(callback) { req.app.db.models.User.findById(req.params.id).exec(function(err, user) { if (err) { return workflow.emit('exception', err); } user.roles.admin = req.body.newAdminId; user.save(function(err, user) { if (err) { return workflow.emit('exception', err); } user.populate('roles.admin roles.account', 'name.full', function(err, user) { if (err) { return workflow.emit('exception', err); } workflow.outcome.user = user; workflow.emit('patchAdmin'); }); }); }); }); workflow.on('patchAdmin', function() { workflow.admin.user = { id: req.params.id, name: workflow.outcome.user.username }; workflow.admin.save(function(err, admin) { if (err) { return workflow.emit('exception', err); } workflow.emit('response'); }); }); workflow.emit('validate'); }; exports.unlinkAdmin = function(req, res, next){ var workflow = req.app.utility.workflow(req, res); workflow.on('validate', function() { if (!req.user.roles.admin.isMemberOf('root')) { workflow.outcome.errors.push('You may not unlink users from admins.'); return workflow.emit('response'); } if (req.user._id === req.params.id) { workflow.outcome.errors.push('You may not unlink yourself from admin.'); return workflow.emit('response'); } workflow.emit('patchUser'); }); workflow.on('patchUser', function() { req.app.db.models.User.findById(req.params.id).exec(function(err, user) { if (err) { return workflow.emit('exception', err); } if (!user) { workflow.outcome.errors.push('User was not found.'); return workflow.emit('response'); } var adminId = user.roles.admin; user.roles.admin = null; user.save(function(err, user) { if (err) { return workflow.emit('exception', err); } user.populate('roles.admin roles.account', 'name.full', function(err, user) { if (err) { return workflow.emit('exception', err); } workflow.outcome.user = user; workflow.emit('patchAdmin', adminId); }); }); }); }); workflow.on('patchAdmin', function(id) { req.app.db.models.Admin.findById(id).exec(function(err, admin) { if (err) { return workflow.emit('exception', err); } if (!admin) { workflow.outcome.errors.push('Admin was not found.'); return workflow.emit('response'); } admin.user = undefined; admin.save(function(err, admin) { if (err) { return workflow.emit('exception', err); } workflow.emit('response'); }); }); }); workflow.emit('validate'); }; exports.linkAccount = function(req, res, next){ var workflow = req.app.utility.workflow(req, res); workflow.on('validate', function() { if (!req.user.roles.admin.isMemberOf('root')) { workflow.outcome.errors.push('You may not link users to accounts.'); return workflow.emit('response'); } if (!req.body.newAccountId) { workflow.outcome.errfor.newAccountId = 'required'; return workflow.emit('response'); } workflow.emit('verifyAccount'); }); workflow.on('verifyAccount', function(callback) { req.app.db.models.Account.findById(req.body.newAccountId).exec(function(err, account) { if (err) { return workflow.emit('exception', err); } if (!account) { workflow.outcome.errors.push('Account not found.'); return workflow.emit('response'); } if (account.user.id && account.user.id !== req.params.id) { workflow.outcome.errors.push('Account is already linked to a different user.'); return workflow.emit('response'); } workflow.account = account; workflow.emit('duplicateLinkCheck'); }); }); workflow.on('duplicateLinkCheck', function(callback) { req.app.db.models.User.findOne({ 'roles.account': req.body.newAccountId, _id: {$ne: req.params.id} }).exec(function(err, user) { if (err) { return workflow.emit('exception', err); } if (user) { workflow.outcome.errors.push('Another user is already linked to that account.'); return workflow.emit('response'); } workflow.emit('patchUser'); }); }); workflow.on('patchUser', function(callback) { req.app.db.models.User.findById(req.params.id).exec(function(err, user) { if (err) { return workflow.emit('exception', err); } user.roles.account = req.body.newAccountId; user.save(function(err, user) { if (err) { return workflow.emit('exception', err); } user.populate('roles.admin roles.account', 'name.full', function(err, user) { if (err) { return workflow.emit('exception', err); } workflow.outcome.user = user; workflow.emit('patchAccount'); }); }); }); }); workflow.on('patchAccount', function() { workflow.account.user = { id: req.params.id, name: workflow.outcome.user.username }; workflow.account.save(function(err, account) { if (err) { return workflow.emit('exception', err); } workflow.emit('response'); }); }); workflow.emit('validate'); }; exports.unlinkAccount = function(req, res, next){ var workflow = req.app.utility.workflow(req, res); workflow.on('validate', function() { if (!req.user.roles.admin.isMemberOf('root')) { workflow.outcome.errors.push('You may not unlink users from accounts.'); return workflow.emit('response'); } workflow.emit('patchUser'); }); workflow.on('patchUser', function() { req.app.db.models.User.findById(req.params.id).exec(function(err, user) { if (err) { return workflow.emit('exception', err); } if (!user) { workflow.outcome.errors.push('User was not found.'); return workflow.emit('response'); } var accountId = user.roles.account; user.roles.account = null; user.save(function(err, user) { if (err) { return workflow.emit('exception', err); } user.populate('roles.admin roles.account', 'name.full', function(err, user) { if (err) { return workflow.emit('exception', err); } workflow.outcome.user = user; workflow.emit('patchAccount', accountId); }); }); }); }); workflow.on('patchAccount', function(id) { req.app.db.models.Account.findById(id).exec(function(err, account) { if (err) { return workflow.emit('exception', err); } if (!account) { workflow.outcome.errors.push('Account was not found.'); return workflow.emit('response'); } account.user = undefined; account.save(function(err, account) { if (err) { return workflow.emit('exception', err); } workflow.emit('response'); }); }); }); workflow.emit('validate'); }; exports.delete = function(req, res, next){ var workflow = req.app.utility.workflow(req, res); workflow.on('validate', function() { if (!req.user.roles.admin.isMemberOf('root')) { workflow.outcome.errors.push('You may not delete users.'); return workflow.emit('response'); } if (req.user._id === req.params.id) { workflow.outcome.errors.push('You may not delete yourself from user.'); return workflow.emit('response'); } workflow.emit('deleteUser'); }); workflow.on('deleteUser', function(err) { req.app.db.models.User.findByIdAndRemove(req.params.id, function(err, user) { if (err) { return workflow.emit('exception', err); } workflow.emit('response'); }); }); workflow.emit('validate'); };
#!/usr/bin/env node 'use strict'; /** * KoshekhBot launcher script. */ var KoshekhBot = require('../lib/koshekh'); /** * Environment variables used to configure the bot: * * BOT_API_KEY : the authentication token to allow the bot to connect to your slack organization. You can get your * token at the following url: https://<yourorganization>.slack.com/services/new/bot (Mandatory) * BOT_DB_PATH: the path of the SQLite database used by the bot * BOT_NAME: the username you want to give to the bot within your organisation. */ var token = process.env.BOT_API_KEY || require('../token'); var dbPath = process.env.BOT_DB_PATH; var name = process.env.BOT_NAME; var koshekhbot = new KoshekhBot({ token: token, dbPath: dbPath, name: name }); koshekhbot.run();
const test = require('ava'); const { constants, createClient } = require('./helpers/createClient'); test('can init and close more than one client', async (t) => { const client = createClient(); const secondClient = createClient(); await new Promise((resolve) => { client.on('connect', () => { secondClient.init({}); }); secondClient.on('connect', () => { t.is(client.state, constants.ZOO_CONNECTED_STATE); t.is(secondClient.state, constants.ZOO_CONNECTED_STATE); t.not(client.client_id, secondClient.client_id); client.close(); }); client.on('close', () => secondClient.close()); secondClient.on('close', () => resolve()); client.init({}); }); }); test('two connected clients can create and fetch nodes', async (t) => { const pathOne = '/first'; const pathTwo = '/second'; const client = createClient(); const secondClient = createClient(); await new Promise((resolve) => { client.on('connect', () => { secondClient.init({}); }); secondClient.on('connect', async () => { const first = await client.create(pathOne, 'one', constants.ZOO_EPHEMERAL); const second = await secondClient.create(pathTwo, 'two', constants.ZOO_EPHEMERAL); t.is(first, pathOne); t.is(second, pathTwo); t.true(await client.pathExists(pathOne, false)); t.true(await client.pathExists(pathTwo, false)); t.true(await secondClient.pathExists(pathOne, false)); t.true(await secondClient.pathExists(pathTwo, false)); client.close(); }); client.on('close', () => secondClient.close()); secondClient.on('close', () => resolve()); client.init({}); }); }); test('closed client cannot create node', async (t) => { const pathOne = '/first'; const firstClient = createClient(); const secondClient = createClient(firstClient.client_id, firstClient.client_password); await new Promise((resolve) => { firstClient.on('connect', () => { secondClient.init({}); firstClient.close(); }); secondClient.on('connect', async () => { try { await firstClient.create(pathOne, 'should not be possible, because client is closed', constants.ZOO_EPHEMERAL); t.fail('closed client should not be able to create a node'); } catch (e) { t.pass(e); } secondClient.close(); }); secondClient.on('close', () => resolve()); firstClient.init({}); }); });
class SoundManager { constructor () { this.sound = $('#speaker') } play () { $(this.sound).trigger('play') } stop () { $(this.sound).trigger('pause') } } export {SoundManager}
Ext.namespace('BB'); var pageSize = BB.pageSize; Ext.create('Ext.data.Store', { storeId: 'bbContactsStore', model: 'Contact', pageSize: pageSize, proxy: { idProperty : '_id', type: 'rest', url: 'data/contacts/', autoload: true, noCache: false, sortParam: undefined, autoSync: true, reader: { root: 'data', totalProperty: 'total' }, autoLoad: { params: { start: 0, } }, actionMethods: { create : 'PUT', read : 'GET', update : 'POST', destroy: 'DELETE' }, reader: { type: 'json', root: 'data' }, listeners: { exception: function(proxy, response, operation) { Ext.gritter.add({ title: 'update',//BB.text['action.' + operation.action] || operation.action, text: (operation.error ? operation.error.statusText : null) || BB.text.exception }); // Ext JS 4.0 does not handle this exception! switch (operation.action) { case 'create': Ext.each(operation.records, function(record) { record.store.remove(record); }); break; case 'destroy': Ext.each(operation.records, function(record) { if (record.removeStore) { record.removeStore.insert(record.removeIndex, record); } }); break; } } } }// close proxy } );
import fs from "fs"; import JSZip from "jszip"; import { scenarioDB} from '/imports/DBs/scenarioDB.js'; import { computeScenario } from '/imports/server/startup/scenarioDef.js' //let path = process.env['METEOR_SHELL_DIR'] + '/../../../public/cities/'; //let path = Assets.absoluteFilePath('cities/') var meteorRoot = fs.realpathSync( process.cwd() + '/../' ); var publicPath = meteorRoot + '/web.browser/app/'; let path = publicPath + '/cities/'; export let citiesData = {}; export let listCities = []; export let addDataFromZip = function(nameFile){ console.log("reading", nameFile, Meteor.settings.public) fs.readFile(nameFile, function(err, data) { if (err) throw err; JSZip.loadAsync(data).then(function (zip) { zip.file("cityData.txt").async("string").then(function (data2){ let cityData = JSON.parse(data2) let city = cityData['city'] citiesData[city] = {} citiesData[city]['city'] = city citiesData[city]['nameFile'] = nameFile.split("/").pop(); citiesData[city]['oneHex'] = cityData['hex']; citiesData[city]['areaHex'] = cityData['areaHex']; citiesData[city]['newScenario'] = cityData['newScenario']; citiesData[city]['budget'] = cityData['budget']; citiesData[city]['metroLines'] = cityData['metroLines']; citiesData[city]['serverOSRM'] = Meteor.settings.public.OSRM_SERVER || cityData['serverOSRM'] + "/" ; console.log(citiesData[city]['serverOSRM']) citiesData[city]['centerCity'] = cityData['centerCity']; citiesData[city]['arrayN'] = {}; citiesData[city]['arrayPop'] = []; //console.log(citiesData[city], nameFile, nameFile.split("/").pop()) zip.file("connections.txt").async("string").then(function (data3){ console.log(city, 'parsing, arrayC') citiesData[city]['arrayC'] = JSON.parse(data3);//data3.split(",").map(Number); //JSON.parse(data3); console.log(city, 'arrayC') zip.file("listPoints.txt").async("string").then(function (data3){ citiesData[city]['listPoints'] = JSON.parse(data3); citiesData[city]['listPoints'].forEach((p)=>{ citiesData[city]['arrayPop'].push(p.pop) }) zip.file("listStops.txt").async("string").then(function (data3){ citiesData[city]['stops'] = JSON.parse(data3); zip.file("P2PPos.txt").async("string").then(function (data3){ citiesData[city]['arrayN']['P2PPos'] = JSON.parse(data3); zip.file("P2PTime.txt").async("string").then(function (data3){ citiesData[city]['arrayN']['P2PTime'] = JSON.parse(data3); zip.file("P2SPos.txt").async("string").then(function (data3){ citiesData[city]['arrayN']['P2SPos'] = JSON.parse(data3); zip.file("P2STime.txt").async("string").then(function (data3){ citiesData[city]['arrayN']['P2STime'] = JSON.parse(data3); zip.file("S2SPos.txt").async("string").then(function (data3){ citiesData[city]['arrayN']['S2SPos'] = JSON.parse(data3); zip.file("S2STime.txt").async("string").then(function (data3){ citiesData[city]['arrayN']['S2STime'] = JSON.parse(data3); let latlng = citiesData[city]['centerCity']; let newScenario = citiesData[city]['newScenario'] listCities.push({'city':city, 'latlng': latlng.reverse(), 'newScenario':newScenario}); console.log('readed', nameFile) //console.log("loaded", city+".zip", 'scenario def',scenarioDB.find({'city':city, 'default':true}).count(), ' newScenario', newScenario, citiesData[city]['centerCity']) if(scenarioDB.find({'city':city, 'default':true}).count()==0){ computeScenario(city, citiesData[city]); console.log("computeScenario", city) } }); }); }); }); }); }); }); }); }); }); }); }); }; export let loadCity = function(){ fs.readdirSync(path).forEach(nameFile => { //console.log(file.slice(-3)); if(nameFile.slice(-3) =="zip"){ //console.log(file.slice(0,-4)) addDataFromZip(path + nameFile); } }); }
import * as React from 'react'; import TopLayoutBlog from 'docs/src/modules/components/TopLayoutBlog'; import { docs } from './april-2019-update.md?@mui/markdown'; export default function Page() { return <TopLayoutBlog docs={docs} />; }
/* MIT License http://www.opensource.org/licenses/mit-license.php Author Jason Anderson @diurnalist */ "use strict"; const REGEXP_HASH = /\[hash(?::(\d+))?\]/gi, REGEXP_CHUNKHASH = /\[chunkhash(?::(\d+))?\]/gi, REGEXP_MODULEHASH = /\[modulehash(?::(\d+))?\]/gi, REGEXP_NAME = /\[name\]/gi, REGEXP_ID = /\[id\]/gi, REGEXP_MODULEID = /\[moduleid\]/gi, REGEXP_FILE = /\[file\]/gi, REGEXP_QUERY = /\[query\]/gi, REGEXP_FILEBASE = /\[filebase\]/gi; // Using global RegExp for .test is dangerous // We use a normal RegExp instead of .test const REGEXP_HASH_FOR_TEST = new RegExp(REGEXP_HASH.source, "i"), REGEXP_CHUNKHASH_FOR_TEST = new RegExp(REGEXP_CHUNKHASH.source, "i"), REGEXP_NAME_FOR_TEST = new RegExp(REGEXP_NAME.source, "i"); const withHashLength = (replacer, handlerFn) => { const fn = (match, hashLength, ...args) => { const length = hashLength && parseInt(hashLength, 10); if (length && handlerFn) { return handlerFn(length); } const hash = replacer(match, hashLength, ...args); return length ? hash.slice(0, length) : hash; }; return fn; }; const getReplacer = (value, allowEmpty) => { const fn = (match, ...args) => { // last argument in replacer is the entire input string const input = args[args.length - 1]; if (value === null || value === undefined) { if (!allowEmpty) throw new Error( `Path variable ${match} not implemented in this context: ${input}` ); return ""; } else { return `${value}`; } }; return fn; }; const replacePathVariables = (path, data) => { const chunk = data.chunk; const chunkId = chunk && chunk.id; const chunkName = chunk && (chunk.name || chunk.id); const chunkHash = chunk && (chunk.renderedHash || chunk.hash); const chunkHashWithLength = chunk && chunk.hashWithLength; const module = data.module; const moduleId = module && module.id; const moduleHash = module && (module.renderedHash || module.hash); const moduleHashWithLength = module && module.hashWithLength; if (typeof path === "function") { path = path(data); } if (data.noChunkHash && REGEXP_CHUNKHASH_FOR_TEST.test(path)) { throw new Error( `Cannot use [chunkhash] for chunk in '${path}' (use [hash] instead)` ); } return ( path .replace( REGEXP_HASH, withHashLength(getReplacer(data.hash), data.hashWithLength) ) .replace( REGEXP_CHUNKHASH, withHashLength(getReplacer(chunkHash), chunkHashWithLength) ) .replace( REGEXP_MODULEHASH, withHashLength(getReplacer(moduleHash), moduleHashWithLength) ) .replace(REGEXP_ID, getReplacer(chunkId)) .replace(REGEXP_MODULEID, getReplacer(moduleId)) .replace(REGEXP_NAME, getReplacer(chunkName)) .replace(REGEXP_FILE, getReplacer(data.filename)) .replace(REGEXP_FILEBASE, getReplacer(data.basename)) // query is optional, it's OK if it's in a path but there's nothing to replace it with .replace(REGEXP_QUERY, getReplacer(data.query, true)) ); }; class TemplatedPathPlugin { apply(compiler) { compiler.hooks.compilation.tap("TemplatedPathPlugin", compilation => { const mainTemplate = compilation.mainTemplate; mainTemplate.hooks.assetPath.tap( "TemplatedPathPlugin", replacePathVariables ); mainTemplate.hooks.globalHash.tap( "TemplatedPathPlugin", (chunk, paths) => { const outputOptions = mainTemplate.outputOptions; const publicPath = outputOptions.publicPath || ""; const filename = outputOptions.filename || ""; const chunkFilename = outputOptions.chunkFilename || outputOptions.filename; if ( REGEXP_HASH_FOR_TEST.test(publicPath) || REGEXP_CHUNKHASH_FOR_TEST.test(publicPath) || REGEXP_NAME_FOR_TEST.test(publicPath) ) return true; if (REGEXP_HASH_FOR_TEST.test(filename)) return true; if (REGEXP_HASH_FOR_TEST.test(chunkFilename)) return true; if (REGEXP_HASH_FOR_TEST.test(paths.join("|"))) return true; } ); mainTemplate.hooks.hashForChunk.tap( "TemplatedPathPlugin", (hash, chunk) => { const outputOptions = mainTemplate.outputOptions; const chunkFilename = outputOptions.chunkFilename || outputOptions.filename; if (REGEXP_CHUNKHASH_FOR_TEST.test(chunkFilename)) hash.update(JSON.stringify(chunk.getChunkMaps(true).hash)); if (REGEXP_NAME_FOR_TEST.test(chunkFilename)) hash.update(JSON.stringify(chunk.getChunkMaps(true).name)); } ); }); } } module.exports = TemplatedPathPlugin;
enabled(){ this.ENABLE_CUSTOM_KEYBOARD = false; this.selectedSkinTone = ""; this.currentKeywords = []; this.skinToneList = [ "", "1F3FB", "1F3FC", "1F3FD", "1F3FE", "1F3FF" ]; this.skinToneNonDefaultList = [ "1F3FB", "1F3FC", "1F3FD", "1F3FE", "1F3FF" ]; this.skinToneData = [ [ "", "#ffdd67" ], [ "1F3FB", "#ffe1bd" ], [ "1F3FC", "#fed0ac" ], [ "1F3FD", "#d6a57c" ], [ "1F3FE", "#b47d56" ], [ "1F3FF", "#8a6859" ], ]; this.emojiData1 = []; // no skin tones, prepended this.emojiData2 = {}; // contains emojis with skin tones this.emojiData3 = []; // no skin tones, appended this.emojiNames = []; const me = this; // styles this.css = window.TDPF_createCustomStyle(this); this.css.insert(".emoji-keyboard { position: absolute; width: 15.35em; background-color: white; border-radius: 1px; font-size: 24px; z-index: 9999 }"); this.css.insert(".emoji-keyboard-popup-btn { height: 36px !important }"); this.css.insert(".emoji-keyboard-popup-btn .icon { vertical-align: -4px !important }"); this.css.insert(".emoji-keyboard-list { height: 10.14em; padding: 0.1em; box-sizing: border-box; overflow-y: auto }"); this.css.insert(".emoji-keyboard-list .separator { height: 26px }"); this.css.insert(".emoji-keyboard-list img { padding: 0.1em !important; width: 1em; height: 1em; vertical-align: -0.1em; cursor: pointer }"); this.css.insert(".emoji-keyboard-search { height: auto; padding: 4px 10px 8px; background-color: #292f33; border-radius: 1px 1px 0 0 }"); this.css.insert(".emoji-keyboard-search input { width: 100%; border-radius: 1px; }"); this.css.insert(".emoji-keyboard-skintones { height: 1.3em; text-align: center; background-color: #292f33; border-radius: 0 0 1px 1px }"); this.css.insert(".emoji-keyboard-skintones div { width: 0.8em; height: 0.8em; margin: 0.25em 0.1em; border-radius: 50%; display: inline-block; box-sizing: border-box; cursor: pointer }"); this.css.insert(".emoji-keyboard-skintones .sel { border: 2px solid rgba(0, 0, 0, 0.35); box-shadow: 0 0 2px 0 rgba(255, 255, 255, 0.65), 0 0 1px 0 rgba(255, 255, 255, 0.4) inset }"); this.css.insert(".emoji-keyboard-skintones :hover { border: 2px solid rgba(0, 0, 0, 0.25); box-shadow: 0 0 1px 0 rgba(255, 255, 255, 0.65), 0 0 1px 0 rgba(255, 255, 255, 0.25) inset }"); this.css.insert(".js-compose-text { font-family: \"Twitter Color Emoji\", Helvetica, Arial, Verdana, sans-serif; }"); // layout let buttonHTML = "<button class=\"needsclick btn btn-on-blue txt-left padding-v--6 padding-h--8 emoji-keyboard-popup-btn\"><i class=\"icon icon-heart\"></i></button>"; this.prevComposeMustache = TD.mustaches["compose/docked_compose.mustache"]; window.TDPF_injectMustache("compose/docked_compose.mustache", "append", "<div class=\"cf margin-t--12 margin-b--30\">", buttonHTML); this.getDrawerInput = () => { return $(".js-compose-text", me.composeDrawer); }; this.getDrawerScroller = () => { return $(".js-compose-scroller > .scroll-v", me.composeDrawer); }; // keyboard generation this.currentKeyboard = null; this.currentSpanner = null; let wasSearchFocused = false; let lastEmojiKeyword, lastEmojiPosition, lastEmojiLength; const hideKeyboard = (refocus) => { $(this.currentKeyboard).remove(); this.currentKeyboard = null; $(this.currentSpanner).remove(); this.currentSpanner = null; this.currentKeywords = []; this.getDrawerScroller().trigger("scroll"); $(".emoji-keyboard-popup-btn").removeClass("is-selected"); if (refocus) { this.getDrawerInput().focus(); if (lastEmojiKeyword && lastEmojiPosition === 0) { document.execCommand("insertText", false, lastEmojiKeyword); } } lastEmojiKeyword = null; }; const generateEmojiHTML = skinTone => { let index = 0; let html = [ "<p style='font-size:13px;color:#444;margin:4px;text-align:center'>Please, note that some emoji may not show up correctly in the text box above, but they will display in the tweet.</p>" ]; for (let array of [ this.emojiData1, this.emojiData2[skinTone], this.emojiData3 ]) { for (let emoji of array) { if (emoji === "___") { html.push("<div class='separator'></div>"); } else { html.push(TD.util.cleanWithEmoji(emoji).replace(" class=\"emoji\" draggable=\"false\"", "")); index++; } } } return html.join(""); }; const updateFilters = () => { let keywords = this.currentKeywords; let container = $(this.currentKeyboard.children[1]); let emoji = container.children("img"); let info = container.children("p:first"); let separators = container.children("div"); if (keywords.length === 0) { info.css("display", "block"); separators.css("display", "block"); emoji.css("display", "inline"); } else { info.css("display", "none"); separators.css("display", "none"); emoji.css("display", "none"); emoji.filter(index => keywords.every(kw => me.emojiNames[index].includes(kw))).css("display", "inline"); } }; const selectSkinTone = skinTone => { let selectedEle = this.currentKeyboard.children[2].querySelector("[data-tone='" + this.selectedSkinTone + "']"); selectedEle && selectedEle.classList.remove("sel"); this.selectedSkinTone = skinTone; this.currentKeyboard.children[1].innerHTML = generateEmojiHTML(skinTone); this.currentKeyboard.children[2].querySelector("[data-tone='" + this.selectedSkinTone + "']").classList.add("sel"); updateFilters(); }; this.generateKeyboard = (left, top) => { let outer = document.createElement("div"); outer.classList.add("emoji-keyboard"); outer.style.left = left + "px"; outer.style.top = top + "px"; let keyboard = document.createElement("div"); keyboard.classList.add("emoji-keyboard-list"); keyboard.addEventListener("click", function(e) { let ele = e.target; if (ele.tagName === "IMG") { insertEmoji(ele.getAttribute("src"), ele.getAttribute("alt")); } e.stopPropagation(); }); let search = document.createElement("div"); search.innerHTML = "<input type='text' placeholder='Search...'>"; search.classList.add("emoji-keyboard-search"); let skintones = document.createElement("div"); skintones.innerHTML = me.skinToneData.map(entry => "<div data-tone='" + entry[0] + "' style='background-color:" + entry[1] + "'></div>").join(""); skintones.classList.add("emoji-keyboard-skintones"); outer.appendChild(search); outer.appendChild(keyboard); outer.appendChild(skintones); $(".js-app").append(outer); skintones.addEventListener("click", function(e) { if (e.target.hasAttribute("data-tone")) { selectSkinTone(e.target.getAttribute("data-tone") || ""); } e.stopPropagation(); }); search.addEventListener("click", function(e) { e.stopPropagation(); }); let searchInput = search.children[0]; searchInput.focus(); wasSearchFocused = false; searchInput.addEventListener("input", function(e) { me.currentKeywords = e.target.value.split(" ").filter(kw => kw.length > 0).map(kw => kw.toLowerCase()); updateFilters(); wasSearchFocused = $(this).val().length > 0; e.stopPropagation(); }); searchInput.addEventListener("keydown", function(e) { if (e.keyCode === 13 && $(this).val().length) { // enter let ele = $(".emoji-keyboard-list").children("img").filter(":visible").first(); if (ele.length > 0) { insertEmoji(ele[0].getAttribute("src"), ele[0].getAttribute("alt")); } e.preventDefault(); } }); searchInput.addEventListener("click", function() { $(this).select(); }); searchInput.addEventListener("focus", function() { wasSearchFocused = true; }); this.currentKeyboard = outer; selectSkinTone(this.selectedSkinTone); this.currentSpanner = document.createElement("div"); this.currentSpanner.style.height = ($(this.currentKeyboard).height() - 10) + "px"; $(".emoji-keyboard-popup-btn").parent().after(this.currentSpanner); this.getDrawerScroller().trigger("scroll"); }; const getKeyboardTop = () => { let button = $(".emoji-keyboard-popup-btn"); return button.offset().top + button.outerHeight() + me.getDrawerScroller().scrollTop() + 8; }; const insertEmoji = (src, alt) => { let input = this.getDrawerInput(); let val = input.val(); let posStart = input[0].selectionStart; let posEnd = input[0].selectionEnd; input.val(val.slice(0, posStart) + alt + val.slice(posEnd)); input.trigger("change"); input[0].selectionStart = posStart + alt.length; input[0].selectionEnd = posStart + alt.length; lastEmojiKeyword = null; if (wasSearchFocused) { $(".emoji-keyboard-search").children("input").focus(); } else { input.focus(); } }; // general event handlers this.emojiKeyboardButtonClickEvent = function(e) { if (me.currentKeyboard) { $(this).blur(); hideKeyboard(true); } else { me.generateKeyboard($(this).offset().left, getKeyboardTop()); $(this).addClass("is-selected"); } e.stopPropagation(); }; this.composerScrollEvent = function(e) { if (me.currentKeyboard) { me.currentKeyboard.style.marginTop = (-$(this).scrollTop()) + "px"; } }; this.composeInputKeyDownEvent = function(e) { if (lastEmojiKeyword && (e.keyCode === 8 || e.keyCode === 27)) { // backspace, escape let ele = $(this)[0]; if (ele.selectionStart === lastEmojiPosition) { ele.selectionStart -= lastEmojiLength; // selects the emoji document.execCommand("insertText", false, lastEmojiKeyword); e.preventDefault(); e.stopPropagation(); } lastEmojiKeyword = null; } }; this.composeInputKeyPressEvent = function(e) { if (String.fromCharCode(e.which) === ":") { let ele = $(this); let val = ele.val(); let firstColon = val.lastIndexOf(":", ele[0].selectionStart); if (firstColon === -1) { return; } let search = val.substring(firstColon + 1, ele[0].selectionStart).toLowerCase(); if (!/^[a-z_]+$/.test(search)) { return; } let keywords = search.split("_").filter(kw => kw.length > 0).map(kw => kw.toLowerCase()); if (keywords.length === 0) { return; } let foundNames = me.emojiNames.filter(name => keywords.every(kw => name.includes(kw))); if (foundNames.length === 0) { return; } else if (foundNames.length > 1 && foundNames.includes(search)) { foundNames = [ search ]; } lastEmojiKeyword = `:${search}:`; lastEmojiPosition = lastEmojiLength = 0; if (foundNames.length === 1) { let foundIndex = me.emojiNames.indexOf(foundNames[0]); let foundEmoji; for (let array of [ me.emojiData1, me.emojiData2[me.selectedSkinTone], me.emojiData3 ]) { let realArray = array.filter(ele => ele !== "___"); if (foundIndex >= realArray.length) { foundIndex -= realArray.length; } else { foundEmoji = realArray[foundIndex]; break; } } if (foundEmoji) { e.preventDefault(); ele.val(val.substring(0, firstColon) + foundEmoji + val.substring(ele[0].selectionStart)); ele[0].selectionEnd = ele[0].selectionStart = firstColon + foundEmoji.length; ele.trigger("change"); ele.focus(); lastEmojiPosition = firstColon + foundEmoji.length; lastEmojiLength = foundEmoji.length; } } else if (foundNames.length > 1 && $(".js-app-content").is(".is-open")) { e.preventDefault(); ele.val(val.substring(0, firstColon) + val.substring(ele[0].selectionStart)); ele[0].selectionEnd = ele[0].selectionStart = firstColon; ele.trigger("change"); if (!me.currentKeyboard) { $(".emoji-keyboard-popup-btn").click(); } $(".emoji-keyboard-search").children("input").focus().val(""); document.execCommand("insertText", false, keywords.join(" ")); } } else { lastEmojiKeyword = null; } }; this.composeInputFocusEvent = function(e) { wasSearchFocused = false; }; this.composerSendingEvent = function(e) { hideKeyboard(); }; this.composerActiveEvent = function(e) { $(".emoji-keyboard-popup-btn", me.composeDrawer).on("click", me.emojiKeyboardButtonClickEvent); $(".js-docked-compose .js-compose-scroller > .scroll-v", me.composeDrawer).on("scroll", me.composerScrollEvent); }; this.documentClickEvent = function(e) { if (me.currentKeyboard && $(e.target).closest(".compose-text-container").length === 0) { hideKeyboard(); } }; this.documentKeyEvent = function(e) { if (me.currentKeyboard && e.keyCode === 27) { // escape hideKeyboard(true); e.stopPropagation(); } }; this.uploadFilesEvent = function(e) { if (me.currentKeyboard) { me.currentKeyboard.style.top = getKeyboardTop() + "px"; } }; // re-enabling let maybeDockedComposePanel = $(".js-docked-compose"); if (maybeDockedComposePanel.length) { maybeDockedComposePanel.find(".cf.margin-t--12.margin-b--30").first().append(buttonHTML); this.composerActiveEvent(); } } ready(){ this.composeDrawer = $(".js-drawer[data-drawer='compose']"); this.composeSelector = ".js-compose-text,.js-reply-tweetbox"; $(document).on("click", this.documentClickEvent); $(document).on("keydown", this.documentKeyEvent); $(document).on("tduckOldComposerActive", this.composerActiveEvent); $(document).on("uiComposeImageAdded", this.uploadFilesEvent); this.composeDrawer.on("uiComposeTweetSending", this.composerSendingEvent); $(document).on("keydown", this.composeSelector, this.composeInputKeyDownEvent); $(document).on("keypress", this.composeSelector, this.composeInputKeyPressEvent); $(document).on("focus", this.composeSelector, this.composeInputFocusEvent); // HTML generation const convUnicode = function(codePt) { if (codePt > 0xFFFF) { codePt -= 0x10000; return String.fromCharCode(0xD800 + (codePt >> 10), 0xDC00 + (codePt & 0x3FF)); } else { return String.fromCharCode(codePt); } }; $TDP.readFileRoot(this.$token, "emoji-ordering.txt").then(contents => { for (let skinTone of this.skinToneList) { this.emojiData2[skinTone] = []; } // declaration inserters let mapUnicode = pt => convUnicode(parseInt(pt, 16)); let addDeclaration1 = decl => { this.emojiData1.push(decl.split(" ").map(mapUnicode).join("")); }; let addDeclaration2 = (tone, decl) => { let gen = decl.split(" ").map(mapUnicode).join(""); if (tone === null) { for (let skinTone of this.skinToneList) { this.emojiData2[skinTone].push(gen); } } else { this.emojiData2[tone].push(gen); } }; let addDeclaration3 = decl => { this.emojiData3.push(decl.split(" ").map(mapUnicode).join("")); }; // line reading let skinToneState = 0; for (let line of contents.split("\n")) { if (line[0] === "@") { switch (skinToneState) { case 0: this.emojiData1.push("___"); break; case 1: this.skinToneList.forEach(skinTone => this.emojiData2[skinTone].push("___")); break; case 2: this.emojiData3.push("___"); break; } continue; } else if (line[0] === "#") { if (line[1] === "1") { skinToneState = 1; } else if (line[1] === "2") { skinToneState = 2; } continue; } let semicolon = line.indexOf(";"); let decl = line.slice(0, semicolon); let desc = line.slice(semicolon + 1).toLowerCase(); if (skinToneState === 1) { let skinIndex = decl.indexOf("$"); if (skinIndex !== -1) { let declPre = decl.slice(0, skinIndex); let declPost = decl.slice(skinIndex + 1); for (let skinTone of this.skinToneNonDefaultList) { this.emojiData2[skinTone].pop(); addDeclaration2(skinTone, declPre + skinTone + declPost); } } else { addDeclaration2(null, decl); this.emojiNames.push(desc); } } else if (skinToneState === 2) { addDeclaration3(decl); this.emojiNames.push(desc); } else if (skinToneState === 0) { addDeclaration1(decl); this.emojiNames.push(desc); } } }).catch(err => { $TD.alert("error", "Problem loading emoji keyboard: " + err.message); }); } disabled(){ this.css.remove(); if (this.currentKeyboard) { $(this.currentKeyboard).remove(); } if (this.currentSpanner) { $(this.currentSpanner).remove(); } $(".emoji-keyboard-popup-btn").remove(); $(document).off("click", this.documentClickEvent); $(document).off("keydown", this.documentKeyEvent); $(document).off("tduckOldComposerActive", this.composerActiveEvent); $(document).off("uiComposeImageAdded", this.uploadFilesEvent); this.composeDrawer.off("uiComposeTweetSending", this.composerSendingEvent); $(document).off("keydown", this.composeSelector, this.composeInputKeyDownEvent); $(document).off("keypress", this.composeSelector, this.composeInputKeyPressEvent); $(document).off("focus", this.composeSelector, this.composeInputFocusEvent); TD.mustaches["compose/docked_compose.mustache"] = this.prevComposeMustache; }
// @flow import 'test-utils/legacy-env' import { injectGlobal, sheet, flush, css } from '@emotion/css' describe('injectGlobal', () => { afterEach(() => { flush() }) test('basic', () => { injectGlobal` html { background: pink; } html.active { background: red; } ` expect(sheet).toMatchSnapshot() }) test('interpolated value', () => { const color = 'yellow' injectGlobal` body { color: ${color}; margin: 0; padding: 0; } ` expect(sheet).toMatchSnapshot() }) test('nested interpolated media query', () => { injectGlobal` body { ${'@media (max-width: 600px)'} { display: flex; } } ` expect(sheet).toMatchSnapshot() }) test('random interpolation', () => { const cls = css` display: flex; ` injectGlobal` body { ${cls}; } ` expect(sheet).toMatchSnapshot() }) test('with @font-face', () => { injectGlobal` @font-face { font-family: 'Patrick Hand SC'; font-style: normal; font-weight: 400; src: local('Patrick Hand SC'), local('PatrickHandSC-Regular'), url(https://fonts.gstatic.com/s/patrickhandsc/v4/OYFWCgfCR-7uHIovjUZXsZ71Uis0Qeb9Gqo8IZV7ckE.woff2) format('woff2'); unicode-range: U+0100-024f, U+1-1eff, U+20a0-20ab, U+20ad-20cf, U+2c60-2c7f, U+A720-A7FF; } ` expect(sheet).toMatchSnapshot() }) test('pseudo in @media', () => { injectGlobal` @media (min-width: 300px) { .header:after { content: ''; } } ` expect(sheet).toMatchSnapshot() }) })
/* eslint-disable class-methods-use-this */ import Job from '../../../../../../packages/oors-scheduler/build/libs/Job'; class DoNothing extends Job { config = { interval: '25 minutes', }; run = () => { console.log(this.module.get('takeABreak')()); }; } export default DoNothing;
import WPAPI from 'wpapi' const wp = new WPAPI({ endpoint: window.five_recent_api.root, nonce: window.five_recent_api.nonce }) export default wp
var chatter = (function(){ // OAuth Configuration var login_url = 'https://login.salesforce.com/'; var client_id = '3MVG9A2kN3Bn17hsXCLd3JHayKA_4lVHkqfvD.R4Ut3k4Haw7idK3YGmkX7XrxAKlNqqS0svqtIgT0uG3qThc'; var redirect_uri = 'https://login.salesforce.com/services/oauth2/success'; var state = "Chrome_Chatter_Share"; var version = "v30.0"; var api_prefix = "/" + version; var max_page_size = 250; // public methods function openAuthorizePage(){ chrome.tabs.create({ url: getAuthorizeUrl(login_url, client_id, redirect_uri) }); } function getCurrentUserInfo(callback){ var client = createClient(); client.ajax(api_prefix + "/chatter/users/me", callback); } function getCurrentUserGroups(callback){ var client = createClient(); client.ajax(api_prefix + "/chatter/users/me/groups?pageSize=" + max_page_size, callback); } function postLink(args){ args.successCallback = args.successCallback || function(){}; args.errorCallback = args.errorCallback || function(){}; var payload = { attachment: { attachmentType: "Link", url: args.url, urlName: args.title }, body: { messageSegments: [ { type: "Text", text: args.comment } ] } }; var client = createClient(); client.ajax( api_prefix + "/chatter/feeds/record/"+ args.group_id + "/feed-items", args.successCallback, args.errorCallback, "POST", JSON.stringify(payload) ); } function isLoggedIn(){ return config.getAccessToken().length > 0 && config.getInstanceUrl().length > 0; } return { openAuthorizePage: openAuthorizePage, getCurrentUserInfo: getCurrentUserInfo, getCurrentUserGroups: getCurrentUserGroups, postLink: postLink, isLoggedIn: isLoggedIn }; // private methods function getAuthorizeUrl(login_url, client_id, redirect_uri){ return login_url+'services/oauth2/authorize?'+ 'display=page'+ '&response_type=token' + '&client_id=' + encodeURIComponent(client_id) + '&redirect_uri='+encodeURIComponent(redirect_uri) + '&state=' + state; } function createClient(){ var client = new forcetk.Client(client_id, login_url); client.proxyUrl = null; client.setSessionToken(config.getAccessToken(), version, config.getInstanceUrl()); client.setRefreshToken(config.getRefreshToken()); return client; } }());
let express = require('express') let path = require('path') let cookieParser = require('cookie-parser') let bodyParser = require('body-parser') let session = require('express-session') let FileStore = require('session-file-store')(session) let history = require('connect-history-api-fallback') let controller = require('./controller') let app = express() app.set('views', path.join(__dirname, 'views')) app.use(bodyParser.json()) app.use(bodyParser.urlencoded({ extended: false })) app.use(cookieParser()) app.use(session({ store: new FileStore(), secret: 'hongchh', resave: false, saveUninitialized: false })); app.use(history()) app.use('/static', express.static(path.join(__dirname, './static'))) app.use('/', controller) module.exports = app
$(document).ready(function() { 'use strict'; var socket = io.connect('http://localhost:3000'); var minion_list = document.getElementById('minions_list'); // Request initial minion list socket.emit('get_minion_list'); // Handle receiving minion list socket.on('minion_list', function(data) { if (data.minions.length > 0) { var minions = data.minions; var html = "<ul class='list-group'>"; for (var i = 0; i < minions.length; i++) { html += '<a href="/minions/' + minions[i]['_id'] + '" class="list-group-item"><h4>' + minions[i].name + '</h4></a>'; } html += '</ul>'; minion_list.innerHTML = html; $('#refresh').button('reset'); } else { // If we didn't get what we wanted the first time, // ask for it again. socket.emit('get_minion_list'); } }); // Handle Clicking Refresh $('#refresh').click(function() { $(this).button('loading'); $(this).prop('disabled', true); socket.emit('refresh_minion_list'); }); });
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.ValidationRule = undefined; exports.cleanResult = cleanResult; var _validate2 = require('validate.js'); var _validate3 = _interopRequireDefault(_validate2); var _aureliaValidation = require('aurelia-validation'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var ValidationRule = exports.ValidationRule = function () { function ValidationRule(name, config) { _classCallCheck(this, ValidationRule); this.name = ''; this.name = name; this.config = config; } ValidationRule.prototype.validate = function validate(target, propName) { if (target && propName) { var _propName, _validator; var validator = (_validator = {}, _validator[propName] = (_propName = {}, _propName[this.name] = this.config, _propName), _validator); var result = (0, _validate3.default)(target, validator); if (result) { var error = cleanResult(result); result = new _aureliaValidation.ValidationError(error); } return result; } throw new Error('Invalid target or property name.'); }; ValidationRule.date = function date() { var config = arguments.length <= 0 || arguments[0] === undefined ? true : arguments[0]; return new ValidationRule('date', config); }; ValidationRule.datetime = function datetime() { var config = arguments.length <= 0 || arguments[0] === undefined ? true : arguments[0]; return new ValidationRule('datetime', config); }; ValidationRule.email = function email() { var config = arguments.length <= 0 || arguments[0] === undefined ? true : arguments[0]; return new ValidationRule('email', config); }; ValidationRule.equality = function equality(config) { return new ValidationRule('equality', config); }; ValidationRule.exclusion = function exclusion(config) { return new ValidationRule('exclusion', config); }; ValidationRule.format = function format(config) { return new ValidationRule('format', config); }; ValidationRule.inclusion = function inclusion(config) { return new ValidationRule('inclusion', config); }; ValidationRule.lengthRule = function lengthRule(config) { return new ValidationRule('length', config); }; ValidationRule.numericality = function numericality() { var config = arguments.length <= 0 || arguments[0] === undefined ? true : arguments[0]; return new ValidationRule('numericality', config); }; ValidationRule.presence = function presence() { var config = arguments.length <= 0 || arguments[0] === undefined ? true : arguments[0]; return new ValidationRule('presence', config); }; ValidationRule.url = function url() { var config = arguments.length <= 0 || arguments[0] === undefined ? true : arguments[0]; return new ValidationRule('url', config); }; return ValidationRule; }(); function cleanResult(data) { var result = {}; for (var prop in data) { if (data.hasOwnProperty(prop)) { result = { propertyName: prop, message: data[prop][0] }; } } return result; }
'use strict'; class LogController { constructor($state) { this.$state = $state; this.entry = { date: new Date(2015, 1, 12), exercises: [ { name: 'Squat', sets: [{reps: 0, weight: 0}] }, { name: 'Bench', sets: [{reps: 0, weight: 0}] }, { name: 'Deadlift', sets: [{reps: 0, weight: 0}] } ] }; this.isSaving = false; } save() { this.$state.go('home'); } addSet(exercise) { exercise.sets.push({reps: 0, weight: 0}); } cloneSet(exercise, set) { exercise.sets.push(angular.extend({}, set)); } calculateVolume(sets) { return sets.reduce(function (total, set) { return total + (set.reps * set.weight); }, 0); } } LogController.$inject = ['$state']; export {LogController};
//Autogenerated by ../../build_app.js import questionnaire_response_question_component from 'ember-fhir-adapter/models/questionnaire-response-question-component'; export default questionnaire_response_question_component;
const ScrollTo = require('../scroll-to'); class FeaturesNavBarItem { /** * @param {HTMLElement} element * @param {number} scrollOffset */ constructor (element, scrollOffset) { this.element = element; this.scrollOffset = scrollOffset; let anchor = this.element.getElementsByTagName('a')[0]; let href = anchor.getAttribute('href'); this.targetId = href.replace('#', ''); this.element.addEventListener('click', this.handleClick.bind(this)); }; handleClick (event) { event.stopPropagation(); event.preventDefault(); let eventTargetValue = event.target.dataset.target; let target = this.getTarget(); if (eventTargetValue) { target = document.getElementById(eventTargetValue.replace('#', '')); } ScrollTo.scrollTo(target, this.scrollOffset); } getTarget () { return document.getElementById(this.targetId); } isForTarget (targetId) { return this.targetId === targetId; } setActive () { this.element.classList.add('active'); } setInactive () { this.element.classList.remove('active'); } setScrollOffset (scrollOffset) { this.scrollOffset = scrollOffset; } } module.exports = FeaturesNavBarItem;
Package.describe({ name: 'mengkeys:orion-lang-zh-cn', version: '1.5.0', summary: 'Orion简体中文语言包', git: 'https://github.com/mengkeys/orion-lang-zh-cn', documentation: 'README.md' }); Package.onUse(function(api) { api.versionsFrom('1.0'); api.use('ecmascript@0.1.6'); api.use('anti:i18n@0.4.3'); api.use('softwarerero:accounts-t9n@1.1.4'); api.imply('anti:i18n'); api.imply('softwarerero:accounts-t9n'); api.addFiles('init.js'); api.addFiles('zh-cn.js'); api.addFiles('lib/datatables.js'); });
module.exports = { devHost: 'http://localhost:8081/', serverHost: '/', rootPath: '/', title: '宇宸的博客', subTitle: '我不是一个伟大的前端工程师,我只是一个具有良好习惯的前端工程师', myselfInfo: { name: '宇宸' }, adminLeftNavList: [{ value: '发布文章', url: '/admin/publish' }, { value: '文章管理', url: '/admin/manage' }, { value: '分类管理', url: '/admin/sort' }, { value: '退出' } ], leftNavList: [{ value: '主页', url:'/' },{ value: '分类', url: '/sort' },{ value: '归档', url: '/archives' }], otherPlatform:[{ name: 'github', url: 'https://github.com/YuChenLi923', target: '_blank' }], shareType: ['JavaScript','CSS','HTML','Node','其他'] }
var zmq = require('..') , should = require('should') , semver = require('semver'); describe('socket.monitor', function() { if (!zmq.ZMQ_CAN_MONITOR) { console.log("monitoring not enabled skipping test"); return; } it('should be able to monitor the socket', function(done) { var rep = zmq.socket('rep') , req = zmq.socket('req'); rep.on('message', function(msg){ msg.should.be.an.instanceof(Buffer); msg.toString().should.equal('hello'); rep.send('world'); }); var testedEvents = ['listen', 'accept', 'disconnect']; testedEvents.forEach(function(e) { rep.on(e, function(event_value, event_endpoint_addr) { // Test the endpoint addr arg event_endpoint_addr.toString().should.equal('tcp://127.0.0.1:5423'); testedEvents.pop(); if (testedEvents.length === 0) { rep.unmonitor(); rep.close(); done(); } }); }); // enable monitoring for this socket rep.monitor(); rep.bind('tcp://127.0.0.1:5423', function (error) { if (error) throw error; }); rep.on('bind', function(){ req.connect('tcp://127.0.0.1:5423'); req.send('hello'); req.on('message', function(msg){ msg.should.be.an.instanceof(Buffer); msg.toString().should.equal('world'); req.close(); }); }); }); it('should use default interval and numOfEvents', function(done) { var req = zmq.socket('req'); req.setsockopt(zmq.ZMQ_RECONNECT_IVL, 5); // We want a quick connect retry from zmq // We will try to connect to a non-existing server, zmq will issue events: "connect_retry", "close", "connect_retry" // The connect_retry will be issued immediately after the close event, so we will measure the time between the close // event and connect_retry event, those should >= 9 (this will tell us that we are reading 1 event at a time from // the monitor socket). var closeTime; req.on('close', function() { closeTime = Date.now(); }); req.on('connect_retry', function() { var diff = Date.now() - closeTime; req.unmonitor(); req.close(); diff.should.be.within(9, 20); done(); }); req.monitor(); req.connect('tcp://127.0.0.1:5423'); }); it('should read multiple events on monitor interval', function(done) { var req = zmq.socket('req'); req.setsockopt(zmq.ZMQ_RECONNECT_IVL, 5); var closeTime; req.on('close', function() { closeTime = Date.now(); }); req.on('connect_retry', function() { var diff = Date.now() - closeTime; req.unmonitor(); req.close(); diff.should.be.within(0, 5); done(); }); // This should read all available messages from the queue, and we expect that "close" and "connect_retry" will be // read on the same interval (for further details see the comment in the previous test) req.monitor(10, 0); req.connect('tcp://127.0.0.1:5423'); }); });
// This service monitors all other services var zonar = require('zonar'); var clc = require('cli-color'); var z = zonar.create({ net : 'cammes', name: 'service-monitor'}); var list = {}; z.listen(function(){ z.on('found', function(service) { list[service.name] = service; render(list); }); z.on('dropped', function(service) { delete list[service.name]; render(list); }); }); function render(list) { console.log(clc.reset); process.stdout.write(clc.moveTo(0, 0)); console.log(""); console.log(clc.yellow(" Active services:")); console.log(" ----------------"); var counter = 0; for(var s in list) { console.log(" %s. %s", ++counter, s); } if (counter == 0) { console.log(" No services found"); } console.log(""); } render(list); // Greacefully quit process.on('SIGINT', function() { z.stop(function() { process.exit( ); }); })
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router'; import { reduxForm, Field } from 'redux-form'; import renderField from '../helpers/renderField'; import { validate } from '../helpers/form'; import { validateAndSignInUser, resetUser } from './actions'; import { connect } from 'react-redux' //import '../form.css' class SignInFormComponent extends Component { static contextTypes = { router: PropTypes.object }; componentWillMount() { //Important! If your component is navigating based on some global state(from say componentWillReceiveProps) //always reset that global state back to null when you REMOUNT this.props.resetUser(); } componentWillReceiveProps(nextProps) { if (nextProps.user.isAuthenticated === 'yes' && nextProps.user.user && !nextProps.user.error) { this.context.router.push('/'); } //error //Throw error if it was not already thrown (check this.props.user.error to see if alert was already shown) //If u dont check this.props.user.error, u may throw error multiple times due to redux-form's validation errors if (nextProps.user.isAuthenticated === 'no' && !nextProps.user.user && nextProps.user.error && !this.props.user.error) { alert(nextProps.user.error.message); } } render() { const { handleSubmit, submitting } = this.props; return ( <div className="container"> <h2 className="centered-text">Rejection App Sign In</h2> <form className="form" onSubmit={ handleSubmit(validateAndSignInUser) }> <Field name="email" type="text" component={ renderField } label="Email Address" /> <Field name="password" type="password" component={ renderField } label="Password" /> <div> <div className="button-styles"> <button> <a type="submit" className="btn btn-primary" disabled={ submitting }> Submit </a> </button> <button> <Link to="/" className="btn btn-error">Back to Home </Link> </button> <button> <Link to="/register" className="btn btn-error">New User Signup </Link> </button> </div> </div> </form> </div> ) } } SignInFormComponent = reduxForm({ form: 'SignInFormComponent', // a unique identifier for this form validate // <--- validation function given to redux-form })(SignInFormComponent) const mapStateToProps = (state, ownProps) => { return { user: state.userState }; } SignInFormComponent = connect( mapStateToProps, { resetUser } )(SignInFormComponent) export default SignInFormComponent;
'use strict'; angular.module('zApp.templates', []); angular.module('zApp.animations', []); angular.module('zApp.filters', []); angular.module('zApp.services', []); angular.module('zApp.controllers', []); angular.module('zApp.directives', []); angular.module('zApp.controllers') .controller('root', ['$scope', function ($scope) { console.log('root controller'); } ]) angular.module('zApp.controllers') .controller('users', ['$scope', function ($scope) { console.log('users controller'); $scope.list = [{ id: 1, name: "User 1" }, { id: 2, name: "User 2" }, { id: 3, name: "User 3" }, { id: 4, name: "User 4" }, { id: 5, name: "User 5" }]; } ]) angular.module('zApp.controllers') .controller('pages', ['$scope', function ($scope) { console.log('pages controller'); } ]); /** * angular-z sample application */ angular.module('zApp', [ 'ngRoute', 'ngAnimate', 'z', 'zApp.controllers', ]).config(['$routeProvider', '$locationProvider', 'zProvider', function ($routeProvider, $locationProvider, zProvider) { zProvider.config({ 'paneRootPath': 'html' }); $routeProvider.when('/', { controller: 'root', templateUrl: '/html/stacks/default.html', resolve: { z: function () { return zProvider.setStack({ defaultLayer: 'content', defaultPhase: 'yield' }); } } }).when('/users/:uuid?', { controller: 'users', templateUrl: '/html/stacks/default.html', resolve: { z: function () { return zProvider.setStack({ defaultLayer: 'navigation', defaultPhase: 'list', paneFills: ['list:users'] }); } } }).when('/pages', { controller: 'pages', templateUrl: '/html/stacks/default.html', resolve: { z: function () { return zProvider.setStack({ defaultLayer: 'navigation', defaultPhase: 'list', paneFills: ['list:pages'] }); } } }); $locationProvider.html5Mode(true); } ]);
initSidebarItems({"fn":[["abs","计算绝对值 #例子 ``` let a = abs(-20); ```"]]});
events_type={ "PushEvent": "is more of a pusher", "CreateEvent": "spends most of their time creating new repositories and branches", "CommitCommentEvent": "is far more likely to comment on your commits", "FollowEvent": "is more of a follower", "ForkEvent": "is a more serious forker", "IssueCommentEvent": "spends more of their time commenting on issues", "PublicEvent": "is most likely to open source a new project", "PullRequestEvent":"submits pull requests more frequently" }
$( document ).ready(function () { var fishInit = function () { // Menu trigger $( '.nav-trigger' ).click(function () { $( '.header__menu' ).slideToggle(); }); var bgRand = Math.floor((Math.random() * 8) + 1); var bgImg = 'url(http://fishingonorfu.hu/wp-content/themes/fishing/assets/img/bg_0' + bgRand + '.jpg)'; $('body').css( 'background-image', bgImg ); }; fishInit(); });
import React from 'react' import { TableCell } from 'material-ui/Table' import returnSpeakerPosition from '../returnSpeakerPosition' export default ( debater, round, debaterStandings, roomsById ) => { const debaterResults = debaterStandings[round._id][debater._id].roomResults if ( debaterResults.constructive === 0 && debaterResults.reply === 0 ) { return ( <TableCell key={round._id} width={50} style={{ maxWidth: '50px', padding: 0 }} children={''} /> ) } const speakerPosition = returnSpeakerPosition( debater, roomsById[debaterStandings[round._id][debater._id].room] ) return ( <TableCell key={round._id} className={'grow hide-child'} width={50} style={{ maxWidth: '50px', padding: 0 }} children={ <span className={ debaterResults.reply > 0 ? 'flex justify-center fw9 underline i' : 'flex justify-center' } > {debaterResults.constructive.toFixed(2)} <span style={{ position: 'absolute', top: 0, left: 0, textAlign: 'center', background: 'white', width: '100%', opacity: '100%', height: '100%' }} className={'child black fw9 i flex flex-column justify-center'}> { debaterResults.reply > 0 ? <div>{speakerPosition}<br />{`Reply: ${debaterResults.reply.toFixed(2)}`}</div> : <div>{speakerPosition}</div> } </span> </span> } /> ) }
/** * @fileoverview Tests for no-func-assign. * @author Ian Christian Myers */ "use strict"; //------------------------------------------------------------------------------ // Requirements //------------------------------------------------------------------------------ const rule = require("../../../lib/rules/no-func-assign"), RuleTester = require("../../../lib/testers/rule-tester"); //------------------------------------------------------------------------------ // Tests //------------------------------------------------------------------------------ const ruleTester = new RuleTester(); ruleTester.run("no-func-assign", rule, { valid: [ "function foo() { var foo = bar; }", "function foo(foo) { foo = bar; }", "function foo() { var foo; foo = bar; }", { code: "var foo = () => {}; foo = bar;", parserOptions: { ecmaVersion: 6 } }, "var foo = function() {}; foo = bar;", "var foo = function() { foo = bar; };", { code: "import bar from 'bar'; function foo() { var foo = bar; }", parserOptions: { ecmaVersion: 6, sourceType: "module" } } ], invalid: [ { code: "function foo() {}; foo = bar;", errors: [{ message: "'foo' is a function.", type: "Identifier" }] }, { code: "function foo() { foo = bar; }", errors: [{ message: "'foo' is a function.", type: "Identifier" }] }, { code: "foo = bar; function foo() { };", errors: [{ message: "'foo' is a function.", type: "Identifier" }] }, { code: "[foo] = bar; function foo() { };", parserOptions: { ecmaVersion: 6 }, errors: [{ message: "'foo' is a function.", type: "Identifier" }] }, { code: "({x: foo = 0} = bar); function foo() { };", parserOptions: { ecmaVersion: 6 }, errors: [{ message: "'foo' is a function.", type: "Identifier" }] }, { code: "function foo() { [foo] = bar; }", parserOptions: { ecmaVersion: 6 }, errors: [{ message: "'foo' is a function.", type: "Identifier" }] }, { code: "(function() { ({x: foo = 0} = bar); function foo() { }; })();", parserOptions: { ecmaVersion: 6 }, errors: [{ message: "'foo' is a function.", type: "Identifier" }] } ] });
'use strict'; const _ = require('lodash'); const Stats = require('../../models/stats'); const setupMatches = require('../support/setupMatches'); describe('Stats', function() { beforeEach(function(done) { setupMatches.call(this).then(done); }); describe('getSummary', function() { let stats; beforeEach(function() { stats = Stats.getSummary(); }); it('returns overall stats', function(done) { stats.then(({ overall }) => { expect(overall.matchesPlayed).toEqual(12); expect(overall.bestWinRate.rate).toEqual(1); expect(overall.bestWinRate.name).toEqual(this.teamPele.get('name')); done(); }); }); it('returns 2v2 stats', function(done) { stats.then(({ twovtwo }) => { expect(twovtwo.matchesPlayed).toEqual(5); expect(twovtwo.bestWinRate.rate).toEqual(1); expect(twovtwo.bestWinRate.name).toEqual(this.germany.get('name')); done(); }); }); it('returns 1v1 stats', function(done) { stats.then(({ onevone }) => { expect(onevone.matchesPlayed).toEqual(7); expect(onevone.bestWinRate.rate).toEqual(1); expect(onevone.bestWinRate.name).toEqual(this.teamPele.get('name')); done(); }); }); }); describe('getAll', function() { let stats; beforeEach(function() { stats = Stats.getAll(); }); it('returns 2v2 stats', function(done) { stats.then(({ twovtwo }) => { let france = _.find(twovtwo, { id: this.france.id }); expect(france.goals_for).toEqual(13); expect(france.goals_against).toEqual(31); expect(france.goals_difference).toEqual(-18); expect(france.clean_sheets).toEqual(0); expect(france.failed_to_score).toEqual(1); let brazil = _.find(twovtwo, { id: this.brazil.id }); expect(brazil.goals_for).toEqual(15); expect(brazil.goals_against).toEqual(10); expect(brazil.goals_difference).toEqual(5); expect(brazil.clean_sheets).toEqual(1); expect(brazil.failed_to_score).toEqual(0); done(); }); }); it('returns 1v1 stats', function(done) { stats.then(({ onevone }) => { let platini = _.find(onevone, { id: this.teamPlatini.id }); expect(platini.goals_for).toEqual(20); expect(platini.goals_against).toEqual(5); expect(platini.goals_difference).toEqual(15); expect(platini.clean_sheets).toEqual(0); expect(platini.failed_to_score).toEqual(0); let maldini = _.find(onevone, { id: this.teamMaldini.id }); expect(maldini.goals_for).toEqual(10); expect(maldini.goals_against).toEqual(10); expect(maldini.goals_difference).toEqual(0); expect(maldini.clean_sheets).toEqual(1); expect(maldini.failed_to_score).toEqual(1); done(); }); }); }); describe('getForTeam', function() { let stats; beforeEach(function() { stats = Stats.getForTeam(this.france.id); }); it('returns the team', function(done) { stats.then(({ team }) => { expect(team.get('name')).toEqual(this.france.get('name')); done(); }); }); it('returns the recent matches', function(done) { stats.then(({ scores }) => { let json = scores.toJSON(); expect(json.length).toEqual(4); json.forEach((j) => { expect([j.team1_id, j.team2_id]).toContain(this.france.id); }); done(); }); }); it('returns the team\'s stats', function(done) { stats.then(({ stats }) => { expect(stats.goals_for).toEqual(13); expect(stats.goals_against).toEqual(31); expect(stats.goals_difference).toEqual(-18); expect(stats.name).toEqual(this.france.get('name')); expect(stats.id).toEqual(this.france.id); expect(stats.clean_sheets).toEqual(0); expect(stats.failed_to_score).toEqual(1); done(); }); }); }); describe('getPlayersStats', function() { let stats; beforeEach(function() { stats = Stats.getPlayersStats(); }); it('returns stats ordered by win rate', function(done) { stats.then((s) => { expect(s[0]).toEqual(jasmine.objectContaining({ name: 'Pele', played: 5, won: 4, lost: 1, win_rate: '0.8000' })); done(); }); }); it('includes players with no matches played', function(done) { stats.then((s) => { let noMatches = _.find(s, { win_rate: 'n/a' }); expect(noMatches).toEqual(jasmine.objectContaining({ name: 'No Matches', played: 0, won: 0, lost: 0, win_rate: 'n/a' })); done(); }); }); }); });
// Increases testrpc time by the passed duration (a moment.js instance) export default function increaseTime(duration) { const id = Date.now() return new Promise((resolve, reject) => { web3.currentProvider.sendAsync({ jsonrpc: '2.0', method: 'evm_increaseTime', params: [duration.asSeconds()], id: id, }, err1 => { if (err1) return reject(err1) web3.currentProvider.sendAsync({ jsonrpc: '2.0', method: 'evm_mine', id: id+1, }, (err2, res) => { return err2 ? reject(err2) : resolve(res) }) }) }) }
module.exports = { "inputs": { "data": { "id": "223064b3-2e66-42ed-92a7-1f11b781e81c", "friendlyName": "data", "description": "", "example": {}, "defaultsTo": {}, "addedManually": true } }, "exits": { "error": { "example": undefined }, "success": { "void": true, "friendlyName": "then", "variableName": "result", "description": "Normal outcome." } }, "sync": false, "cacheable": false, "defaultExit": "success", "fn": function(inputs, exits, env) { return exits.success(JSON.stringify(inputs.data)); }, "identity": "json" };
'use strict'; var Q = require('q'); var debug = require('debug')('dynamodel:table'); var util = require('util'); function Table(name, schema, options, base) { debug('new Table (%s)', name, schema); this.name = name; this.schema = schema; this.options = options || {}; this.base = base; if(this.options.create === undefined || this.options.create === null) { this.options.create = true; } } Table.prototype.init = function(next) { debug('initializing table, %s, %j', this.name, this.options); var deferred = Q.defer(); var table = this; if (this.options.create) { this.describe() .then(function (data) { debug('table exist -- initialization done'); // TODO verify table keys and index's match table.active = data.Table.TableStatus === 'ACTIVE'; table.initialized = true; return deferred.resolve(); }, function (err) { if(err && err.code === 'ResourceNotFoundException') { debug('table does not exist -- creating'); return deferred.resolve( table.create() .then(function () { table.initialized = true; }) // .then(function() { // if(table.options.waitForActive) { // return table.waitForActive(); // } // }) ); } if(err) { debug('error initializing', err); return deferred.reject(err); } }); } else { table.initialized = true; return deferred.resolve(); } return deferred.promise.nodeify(next); }; Table.prototype.waitForActive = function(timeout, next) { debug('Waiting for Active table, %s, %j', this.name, this.options); var deferred = Q.defer(); if(typeof timeout === 'function') { next = timeout; timeout = null; } if(!timeout) { timeout = this.options.waitForActiveTimeout; } var table = this; var timeoutAt = Date.now() + timeout; function waitForActive() { if(table.active) { debug('Table is Active - %s', table.name); return deferred.resolve(); } if(Date.now() > timeoutAt) { return deferred.reject( new Error('Wait for Active timed out after ' + timeout + ' ms.') ); } if(!table.initialized) { return setTimeout(waitForActive, 10); } table.describe() .then(function (data) { if(data.Table.TableStatus !== 'ACTIVE'){ debug('Waiting for Active - %s', table.name); setTimeout(waitForActive, 1000); } else { // TODO verify table keys and index's match table.active = true; deferred.resolve(); } }, function (err) { return deferred.reject(err); }); } waitForActive(); return deferred.promise.nodeify(next); }; Table.prototype.describe = function(next) { var describeTableReq = { TableName: this.name }; debug('ddb.describeTable request: %j', describeTableReq); var deferred = Q.defer(); var ddb = this.base.ddb(); ddb.describeTable(describeTableReq, function(err, data) { if(err) { debug('error describing table', err); return deferred.reject(err); } debug('got table description: %j', data); deferred.resolve(data); }); return deferred.promise.nodeify(next); }; Table.prototype.create = function(next) { var ddb = this.base.ddb(); var schema = this.schema; var attrDefs = []; var keyAttr = {}; function addKeyAttr (attr) { if(attr) { keyAttr[attr.name] = attr; } } addKeyAttr(schema.hashKey); addKeyAttr(schema.rangeKey); for(var globalIndexName in schema.indexes.global) { addKeyAttr(schema.indexes.global[globalIndexName]); // add the range key to the attribute definitions if specified var rangeKeyName = schema.indexes.global[globalIndexName].indexes[globalIndexName].rangeKey; addKeyAttr(schema.attributes[rangeKeyName]); } for(var indexName in schema.indexes.local) { addKeyAttr(schema.indexes.local[indexName]); } for(var keyAttrName in keyAttr) { attrDefs.push({ AttributeName: keyAttrName, AttributeType: keyAttr[keyAttrName].type.dynamo }); } var keySchema = [{ AttributeName: schema.hashKey.name, KeyType: 'HASH' }]; if(schema.rangeKey) { keySchema.push({ AttributeName: schema.rangeKey.name, KeyType: 'RANGE' }); } var provThroughput = { ReadCapacityUnits: schema.throughput.read, WriteCapacityUnits: schema.throughput.write }; var createTableReq = { AttributeDefinitions: attrDefs, TableName: this.name, KeySchema: keySchema, ProvisionedThroughput: provThroughput }; debug('Creating table local indexes', schema.indexes.local); var localSecIndexes, index; for(var localSecIndexName in schema.indexes.local) { localSecIndexes = localSecIndexes || []; var indexAttr = schema.indexes.local[localSecIndexName]; index = indexAttr.indexes[localSecIndexName]; var localSecIndex = { IndexName: localSecIndexName, KeySchema: [{ AttributeName: schema.hashKey.name, KeyType: 'HASH' }, { AttributeName: indexAttr.name, KeyType: 'RANGE' }] }; if(index.project) { if(util.isArray(index.project)){ localSecIndex.Projection = { ProjectionType: 'INCLUDE', NonKeyAttributes: index.project }; } else { localSecIndex.Projection = { ProjectionType: 'ALL' }; } } else { localSecIndex.Projection = { ProjectionType: 'KEYS_ONLY' }; } localSecIndexes.push(localSecIndex); } var globalSecIndexes; for(var globalSecIndexName in schema.indexes.global) { globalSecIndexes = globalSecIndexes || []; var globalIndexAttr = schema.indexes.global[globalSecIndexName]; index = globalIndexAttr.indexes[globalSecIndexName]; var globalSecIndex = { IndexName: globalSecIndexName, KeySchema: [{ AttributeName: globalIndexAttr.name, KeyType: 'HASH' }], ProvisionedThroughput: { ReadCapacityUnits: index.throughput.read, WriteCapacityUnits: index.throughput.write } }; if(index.rangeKey) { globalSecIndex.KeySchema.push({ AttributeName: index.rangeKey, KeyType: 'RANGE' }); } if(index.project) { if(util.isArray(index.project)){ globalSecIndex.Projection = { ProjectionType: 'INCLUDE', NonKeyAttributes: index.project }; } else { globalSecIndex.Projection = { ProjectionType: 'ALL' }; } } else { globalSecIndex.Projection = { ProjectionType: 'KEYS_ONLY' }; } globalSecIndexes.push(globalSecIndex); } if(localSecIndexes) { createTableReq.LocalSecondaryIndexes = localSecIndexes; } if(globalSecIndexes) { createTableReq.GlobalSecondaryIndexes = globalSecIndexes; } debug('ddb.createTable request:', createTableReq); var deferred = Q.defer(); ddb.createTable(createTableReq, function(err, data) { if(err) { debug('error creating table', err); return deferred.reject(err); } debug('table created', data); deferred.resolve(data); }); return deferred.promise.nodeify(next); }; Table.prototype.delete = function(next) { var deleteTableReq = { TableName: this.name }; debug('ddb.deleteTable request:', deleteTableReq); var ddb = this.base.ddb(); var deferred = Q.defer(); ddb.deleteTable(deleteTableReq, function(err, data) { if(err) { debug('error deleting table', err); return deferred.reject(err); } debug('deleted table', data); deferred.resolve(data); }); return deferred.promise.nodeify(next); }; Table.prototype.update = function(next) { // var ddb = this.base.ddb(); // ddb.updateTable(); var deferred = Q.defer(); deferred.reject(new Error('TODO')); return deferred.promise.nodeify(next); }; module.exports = Table;
var Heap = require('heap'); var ndarray = require('ndarray'); var vec3 = require('gl-vec3'); var vec4 = require('gl-vec4'); var normals = require('normals').faceNormals; var ops = require('ndarray-ops'); var solve = require('ndarray-linear-solve'); var removeOrphans = require('remove-orphan-vertices'); var removeDegenerates = require('remove-degenerate-cells'); function vertexError(vertex, quadratic) { var xformed = new Array(4); vec4.transformMat4(xformed, vertex, quadratic); return vec4.dot(vertex, xformed); }; function optimalPosition(v1, v2) { var q1 = v1.error; var q2 = v2.error; var costMatrix = ndarray(new Float32Array(4 * 4), [4, 4]); ops.add(costMatrix, q1, q2); var mat4Cost = Array.from(costMatrix.data); var optimal = ndarray(new Float32Array(4)); var toInvert = costMatrix; toInvert.set(0, 3, 0); toInvert.set(1, 3, 0); toInvert.set(2, 3, 0); toInvert.set(3, 3, 1); var solved = solve(optimal, toInvert, ndarray([0, 0, 0, 1])); if (!solved) { var v1Homogenous = Array.from(v1.position); v1Homogenous.push(1); var v2Homogenous = Array.from(v2.position); v2Homogenous.push(1); var midpoint = vec3.add(new Array(3), v1.position, v2.position); vec3.scale(midpoint, midpoint, 0.5); midpoint.push(1); var v1Error = vertexError(v1Homogenous, mat4Cost); var v2Error = vertexError(v2Homogenous, mat4Cost); var midpointError = vertexError(midpoint, mat4Cost); var minimum = Math.min([v1Error, v2Error, midpointError]); if (v1Error == minimum) { optimal = v1Homogenous; } else if (v2Error == minimum) { optimal = v2Homogenous; } else { optimal = midpoint; } } else { optimal = optimal.data; } var error = vertexError(optimal, mat4Cost); return {vertex: optimal.slice(0, 3), error: error}; }; module.exports = function(cells, positions, faceNormals, threshold = 0) { cells = removeDegenerates(cells); if (!faceNormals) { faceNormals = normals(cells, positions); } var n = positions.length; var vertices = positions.map(function(p, i) { return { position: p, index: i, pairs: [], error: ndarray(new Float32Array(4 * 4).fill(0), [4, 4]) } }); cells.map(function(cell) { for (var i = 0; i < 2; i++) { var j = (i + 1) % 3; var v1 = cell[i]; var v2 = cell[j]; // consistent ordering to prevent double entries if (v1 < v2) { vertices[v1].pairs.push(v2); } else { vertices[v2].pairs.push(v1); } } }); if (threshold > 0) { for (var i = 0; i < n; i++) { for (var j = i - 1; j >= 0; j--) { if (vec3.distance(cells[i], cells[j]) < threshold) { if (i < j) { vertices[i].pairs.push(vertices[j]); } else { vertices[j].pairs.push(vertices[i]); } } } } } cells.map(function(cell, cellId) { var normal = faceNormals[cellId]; // [a, b, c, d] where plane is defined by a*x+by+cz+d=0 // choose the first vertex WLOG var pointOnTri = positions[cell[0]]; var plane = [normal[0], normal[1], normal[2], -vec3.dot(normal, pointOnTri)]; cell.map(function(vertexId) { var errorQuadric = ndarray(new Float32Array(4 * 4), [4, 4]); for (var i = 0; i < 4; i++) { for (var j = i; j >= 0; j--) { var value = plane[i] * plane[j]; errorQuadric.set(i, j, value); if (i != j) { errorQuadric.set(j, i, value); } } } var existingQuadric = vertices[vertexId].error; ops.add(existingQuadric, existingQuadric, errorQuadric); }) }); var costs = new Heap(function(a, b) { return a.cost - b.cost; }); var edges = [] vertices.map(function(v1) { v1.pairs.map(function(v2Index) { var v2 = vertices[v2Index]; var optimal = optimalPosition(v1, v2); var edge = { pair: [v1.index, v2Index], cost: optimal.error, optimalPosition: optimal.vertex }; costs.push(edge); // to update costs edges.push(edge); }); }); var n = positions.length; return function(targetCount) { // deep-copy trick: https://stackoverflow.com/questions/597588/how-do-you-clone-an-array-of-objects-in-javascript var newCells = JSON.parse(JSON.stringify(cells)); var deletedCount = 0; while (n - deletedCount > targetCount) { var leastCost = costs.pop(); var i1 = leastCost.pair[0]; var i2 = leastCost.pair[1]; if (i1 == i2) { // edge has already been collapsed continue; } vertices[i1].position = leastCost.optimalPosition; for (var i = newCells.length - 1; i >= 0; i--) { var cell = newCells[i]; var cellIndex2 = cell.indexOf(i2); if (cellIndex2 != -1) { if (cell.indexOf(i1) != -1) { // Delete cells with zero area, as v1 == v2 now newCells.splice(i, 1); } cell[cellIndex2] = i1; } } var v1 = vertices[i1]; edges.map(function(edge, i) { var edgeIndex1 = edge.pair.indexOf(i1); var edgeIndex2 = edge.pair.indexOf(i2); if (edgeIndex1 != -1 && edgeIndex2 != -1) { edge.pair[edgeIndex2] = i1; return; } if (edge.pair.indexOf(i1) != -1) { var optimal = optimalPosition(v1, vertices[edge.pair[(edgeIndex1 + 1) % 2]]); edge.optimalPosition = optimal.vertex; edge.cost = optimal.error; } if (edge.pair.indexOf(i2) != -1) { // use v1 as that is the new position of v2 var optimal = optimalPosition(v1, vertices[edge.pair[(edgeIndex2 + 1) % 2]]); edge.pair[edgeIndex2] = i1; edge.optimalPosition = optimal.vertex; edge.cost = optimal.error; } }); costs.heapify(); deletedCount++; } return removeOrphans(newCells, vertices.map(function(p) { return p.position })); }; }
define('JSComposer/Instance', ['JSComposer/Utils', 'JSComposer/Schema'], function(Utils, Schema) { // Constructor function Instance(context, parent, type_desc, value) { this.context = context; this.parent = parent; this.elements = { ctr: Utils.makeElement("div", {"className":"panel panel-default"}) }; schema = Utils.ldef(type_desc, {'type':'null'}); for (var k in schema) { if (!schema.hasOwnProperty(k)) continue; this[k] = schema[k]; } } Instance.Objects = {}; Instance.Schema = {}; // Resolve Schema: incorporate references and valid // types from multiple layers into a single schema, // identifying potential constructors along the way Instance.ResolveSchema = function(schema, current, type_merge) { if (typeof current === 'undefined') { current = {}; // Create non-enumerable constructors property // for tracking discovered constructors Object.defineProperty(current, 'constructors', { configurable: true, enumerable: false, value: {} }); Object.defineProperty(current, 'cons_order', { configurable: true, enumerable: false, value: [] }); } // Enclosed function for repeated operation function add_constructor(uri, cons, front) { front = Utils.ldef(front, false); if (current.constructors.hasOwnProperty(uri)) return; current.constructors[uri] = cons; if (front) { current.cons_order.unshift(uri); } else { current.cons_order.push(uri); } } // Incorporate identified constructors from // lower levels if (typeof schema.constructors !== 'undefined') { for (var k in schema.constructors) { if (!schema.constructors.hasOwnProperty) continue; add_constructor(k, schema.constructors[k]); } } type_merge = Utils.ldef(type_merge, true); // Parse keys in this schema and incorporate into current // TODO: break up this logic just a wee bit (mmm, s'ghetti) for (var key in schema) { switch (key) { case "$ref": var uri = schema[key], schema2 = Schema.Fetch(uri), cons = Instance.Objects[uri]; if (cons !== undefined) add_constructor(uri, cons); Instance.ResolveSchema(schema2, current); break; case "enum": add_constructor('enum', Instance.Objects['enum']); current[key] = Utils.clone(schema[key]); break; case "oneOf": if (typeof current.oneOf === 'undefined') { current.oneOf = []; } if (schema[key].length === 1) { var resolved = Instance.ResolveSchema(schema[key][0]); current.oneOf.push(resolved); Instance.ResolveSchema(schema[key][0], current); } else { for (var i = 0, l = schema[key].length; i < l; ++i) { current.oneOf.push(Instance.ResolveSchema(schema[key][i])); } var cons = Instance.Objects['oneOf']; add_constructor('oneOf', cons, true); } break; case "allOf": case "anyOf": if (typeof current[key] === 'undefined') { current[key] = []; } var type_merge = key === 'allOf' ? false : true; for (var i = 0, l = schema[key].length; i < l; ++i) { var resolved = Instance.ResolveSchema(schema[key][i], undefined, type_merge); current[key].push(resolved); Instance.ResolveSchema(resolved, current); } break; case "additionalProperties": current[key] = schema[key]; break; case "properties": case "patternProperties": if (typeof current[key] === 'undefined') { current[key] = {}; } for (var k in schema[key]) { current[key][k] = Utils.clone(schema[key][k]); } break; case "type": switch (typeof current[key]) { case 'undefined': current[key] = typeof schema[key] === 'string' ? schema[key] : Utils.clone(schema[key]); break; case 'string': if (type_merge) { current[key] = [current[key]]; } else if (current[key] !== schema[key]) { throw "invalid_type_merger"; } if (schema[key] === current[key]) { // No need to do anything; types are the same } else if (typeof schema[key] === 'string') { if (current[key].indexOf(schema[key]) < 0) current[key].push(schema[key]); } else { for (var i = 0, l = schema[key].length; i < l; ++i) { if (current[key].indexOf(schema[key][i]) < 0) current[key].push(schema[key][i]); } } break; case 'object': default: if (type_merge) { for (var i = 0, l = schema[key].length; i < l; ++i) { if (current[key].indexOf(schema[key][i]) < 0) current[key].push(schema[key][i]); } } else { throw "invalid_type_merger"; } break; } break; default: if (typeof current[key] === 'undefined') { current[key] = schema[key]; } break; } } if (typeof current.oneOf !== 'undefined') { var anyOf = typeof current.anyOf === 'undefined' ? [] : current.anyOf, allOf = typeof current.allOf === 'undefined' ? [] : current.allOf, of = anyOf.concat(allOf); for (var i = 0, l = current.oneOf.length; i < l; ++i) { for (var index = 0, length = of.length; index < length; ++index) { current.oneOf[i] = Instance.ResolveSchema(of[index], current.oneOf[i], false); } } } if (typeof current.type === 'object' && current.type.length === 1) { current.type = current.type[0]; } if (typeof current.type === 'string') { add_constructor(current.type, Instance.Objects[current.type]); } else if (typeof current.type === 'undefined') { var uri = Schema.URI("#/definitions/label"), cons = Instance.Objects[uri]; add_constructor(uri, cons); } else { //throw "disallowed_multitype_field"; } return current; }; Instance.RegisterInstance = function(type, constructor) { if (Instance.Objects[type] !== undefined) throw "Object already defined: " + type; Instance.Objects[type] = constructor; }; Instance.prototype.CreateInstance = function (schema, value) { return Instance.CreateInstance(this.context, this, schema, value); } Instance.CreateInstance = function(context, parent, schema, value) { var key = undefined; // 1. Check to make sure we got a schema if (schema === undefined || typeof schema !== "object") { throw("invalid schema"); } schema = Instance.ResolveSchema(schema); if (schema.cons_order.length > 0) { var uri = schema.cons_order[0], cons = schema.constructors[uri]; return new cons(context, parent, schema, value); } return Instance.CreateInstance(context, parent, Schema.Ref('#/definitions/label'), value); }; // Instance Methods Instance.prototype.Render = function (target) { target.appendChild(this.elements.ctr); }; Instance.prototype.GetValue = function () { return null; }; Instance.prototype.Destroy = function() { var parent_node = this.elements.ctr.parentElement; parent_node.removeChild(this.elements.ctr); }; Instance.prototype.OnChange = function() { }; Instance.RegisterInstance('null', Instance); return Instance; });
#!/usr/bin/env node /* @flow */ // Need that because of regenerator runtime require("babel-polyfill"); // $FlowFixMe process.noDeprecation = true; // Suppress webpack deprecation warnings const meow = require("meow"); const chalk = require("chalk"); const aik = require("./lib"); const cli = meow({ help: [ chalk.green("Usage"), " $ aik filename.js", "", chalk.green("Options"), ` ${chalk.yellow("-b, --build")} Build production version for given entry point. [Default output: dist]`, ` ${chalk.yellow("-u, --base")} Base path with which URLs in build begins`, ` ${chalk.yellow("-p, --port")} Web server port. ${chalk.dim("[Default: 4444]")}`, ` ${chalk.yellow("-h, --host")} Web server host. ${chalk.dim("[Default: localhost]")}`, ` ${chalk.yellow("-n, --ngrok")} Exposes server to the real world by ngrok.`, ` ${chalk.yellow("-o, --open")} Opens web server URL in the default browser.`, ` ${chalk.yellow("-v, --version")} Shows version.`, ` ${chalk.yellow("--help")} Shows help.`, "", chalk.green("Examples"), " $ aik filename.js --port 3000 -n", chalk.dim(" Runs aik web server on 3000 port with ngrok."), "", " $ aik filename.js --build", chalk.dim(" Builds filename.js for production use and saves the output to dist folder.") ].join("\n"), flags: { build: { alias: "b" }, base: { type: "string", alias: "u" }, port: { type: "string", alias: "p" }, host: { type: "string", alias: "h" }, ngrok: { type: "boolean", alias: "n" }, open: { type: "boolean", alias: "o" }, version: { type: "boolean", alias: "v" } } }); const input = cli.input || []; const flags = cli.flags || {}; const errorHandler = err => { if (err.formattedMessage) { aik.print(err.formattedMessage, /* clear */ true); } else { // eslint-disable-next-line console.log(chalk.red(err.stack || err)); } process.exit(1); }; aik.deprecation.flagDeprecationWarnings(flags, () => { if (!input.length) { console.log(cli.help); // eslint-disable-line } else if (flags.build) { aik.build(input, flags).catch(errorHandler); } else { aik.devServer(input, flags).catch(errorHandler); } });
'use strict'; /* 컨트롤러 단위 테스트 */ describe('controllers 단위 테스트', function(){ beforeEach(module('myApp.controllers')); var scope; it('MyCtrl1 컨트롤러 test1값', inject(function($rootScope, $controller) { scope = $rootScope.$new(); var ctrl = $controller('MyCtrl1', { $scope : scope }); expect(scope.test1).toBe('EFG'); })); it('MyCtrl2 컨트롤러 test2값', inject(function($rootScope, $controller) { scope = $rootScope.$new(); var ctrl = $controller('MyCtrl2', { $scope : scope }); expect(scope.test2()).toBe('안녕히계세요!!'); })); });
import React from 'react'; import {FontIcon, Styles} from 'material-ui'; import Radium from 'radium'; let ThemeManager = new Styles.ThemeManager(); let styles = { page: {}, editView: { padding: '10px 10px 100px 10px' }, }; @Radium export default class PageLayout extends React.Component { render() { let [ editView, commandLine, messages ] = this.props.children; return <div style={styles.page}> <div style={styles.editView}>{editView}</div> <div>{commandLine}</div> <div>{messages}</div> </div>; } }
/** * Created by suman on 08/05/16. */ var core = require('chanakya'); var _ = require('lodash'); var Q = require('q'), http = require('http'); var rp = require('request-promise'); core.response('fail', function (to) { return { text: `I am sorry ${to.first_name}, I am unable to understand what you meant. Please rephrase and send back.` }; }, 'statement'); core.response('balance', function (to) { console.log(to); var deferred = Q.defer(); var options = { uri: `https://polar-atoll-33216.herokuapp.com/users/1`, headers: { 'Authorization': 'Bearer LUPCP5OOAFQXURYOH7I7YVU4FGBGVAG3', 'Accept': 'application/vnd.wit.20141022+json' }, json: true // Automatically parses the JSON string in the response }; rp(options) .then(function (res) { deferred.resolve({ text: `Your balance is =${res.currency}${res.balance}` }); }) .catch(function (err) { console.error(err); }); return deferred.promise; }, 'statement'); core.response('creditcard', function (to) { return { "attachment":{ "type":"template", "payload":{ "template_type":"generic", "elements":[ { "title":"NBA American Express Card", "image_url":"https://s3.amazonaws.com/facebookbot/NBA+American+Express+Card.png", "subtitle":"9.49% to 29.49% variable APR based on your creditworthiness", "buttons":[ { "type":"web_url", "url":"https://www.efirstbank.com/customer-service/find-location.htm", "title":"Apply for this card" }, { "type":"web_url", "url":"https://www.efirstbank.com/products/credit-loan/credit-cards/credit-cards-visa.htm", "title":"View Details", }, { "title":"View APR, Terms & Fees", "type":"web_url", "url":"https://www.efirstbank.com/products/credit-loan/credit-cards/credit-card-agreement.htm", } ] }, { "title":"Clearpoints Credit Card", "image_url":"https://s3.amazonaws.com/facebookbot/Clearpoints+Credit+Card.png", "subtitle":"9.49% to 23.49% variable APR based on your creditworthiness", "buttons":[ { "type":"web_url", "url":"https://www.efirstbank.com/customer-service/find-location.htm", "title":"Apply for this card" }, { "type":"web_url", "url":"https://www.efirstbank.com/products/credit-loan/credit-cards/credit-cards-visa.htm", "title":"View Details", }, { "title":"View APR, Terms & Fees", "type":"web_url", "url":"https://www.efirstbank.com/products/credit-loan/credit-cards/credit-card-agreement.htm", } ] }, { "title":"Select Credit Card", "image_url":"https://s3.amazonaws.com/facebookbot/Select+Credit+Card.png", "subtitle":"1.49% to 17.49% variable APR based on your creditworthiness", "buttons":[ { "type":"web_url", "url":"https://www.efirstbank.com/customer-service/find-location.htm", "title":"Apply for this card" }, { "type":"web_url", "url":"https://www.efirstbank.com/products/credit-loan/credit-cards/credit-cards-visa.htm", "title":"View Details", }, { "title":"View APR, Terms & Fees", "type":"web_url", "url":"https://www.efirstbank.com/products/credit-loan/credit-cards/credit-card-agreement.htm", } ] } ] } } }; request({ url: 'https://graph.facebook.com/v2.6/me/messages', qs: {access_token:token}, method: 'POST', json: { recipient: {id:sender}, message: messageData, } }, function(error, response, body) { if (error) { console.log('Error sending message: ', error); } else if (response.body.error) { console.log('Error: ', response.body.error); } }); }, 'statement'); core.response('payment', function (to) { return { "attachment":{ "type":"template", "payload":{ "template_type":"generic", "elements":[ { "title":`${to.first_name}, please see your credit card statement below.`, "image_url": "https://s3.amazonaws.com/facebookbot/creditcard.png", "buttons":[ { "type":"web_url", "url":"https://www.billdesk.com/pgidsk/pgmerc/amexcard/amex_card.jsp", "title":"Pay minimum payment due" }, { "type":"web_url", "url":"https://www.billdesk.com/pgidsk/pgmerc/amexcard/amex_card.jsp", "title":"Pay $2000" }, { "title":"Increase credit limit", "type":"web_url", "url":"https://www.americanexpress.com/in/content/credit-know-how/credit-card-limits/" } ] } ] } } }; }, 'statement');
var searchData= [ ['update_2eh',['update.h',['../update_8h.html',1,'']]] ];
import { moduleForComponent, test } from 'ember-qunit'; import hbs from 'htmlbars-inline-precompile'; moduleForComponent('scroll-indicator', 'Integration | Component | scroll indicator', { integration: true }); test('it renders', function(assert) { // Set any properties with this.set('myProperty', 'value'); // Handle any actions with this.on('myAction', function(val) { ... }); this.render(hbs`{{scroll-indicator}}`); assert.equal(this.$().text().trim(), ''); // Template block usage: this.render(hbs` {{#scroll-indicator}} template block text {{/scroll-indicator}} `); assert.equal(this.$().text().trim(), 'template block text'); });
// module for ng-app var app = angular.module("memorin",["ngSanitize"]); app.controller("editorCtrl",["$scope","$sanitize","$filter","$sce", function($scope,$sanitize,$filter,$sce){ $scope.items = [ {"content":"test1<br>1111"}, {"content":"test2<br>2222"}, {"content":"aaa<br>aa<br>aaa"}, {"content":"test4"} ]; // $scope.items = angular.fromJson(localStorage.getItem("items")); // $scope.htmlFilter = function(text){ // // console.log(text); // text = text.replace(/\<br\>/g,"\n"); // var linky_text = $filter("linky")(text,"_blank"); // // ここでエスケープされたHTMLタグを戻したい // var html = linky_text.replace(/&lt;/g,"<").replace(/&gt;/g, ">").replace(/&#10;/g,"<br>").replace(/&amp;nbsp;/g," "); // return html; // } $scope.onSubmit = function(){ var text = $scope.testmodel; text = text.replace(/\<br\>/g,"\n"); var linky_text = $filter("linky")(text,"_blank"); var html = linky_text.replace(/&lt;/g,"<").replace(/&gt;/g, ">").replace(/&#10;/g,"<br>").replace(/&amp;nbsp;/g," "); var item = {"content":html}; $scope.items.push(item); localStorage.setItem("items",angular.toJson($scope.items)); } }]); app.directive("memorinEditor", function(){ return { restrict: "A", require: "?ngModel", // template: "<strong>this is directive test</strong>" link: function(scope, element, attrs, ngModel){ ngModel.$render = function(){ element.html(ngModel.$viewValue || ""); }; // console.log(ngModel); element.on("blur keyup change",function(){ scope.$apply(read); }); read(); function read(){ var html = element.html(); ngModel.$setViewValue(html); } } } }); // angular.module('customControl', []). // directive('contenteditable', function() { // return { // restrict: 'A', // only activate on element attribute // require: '?ngModel', // get a hold of NgModelController // link: function(scope, element, attrs, ngModel) { // if(!ngModel) return; // do nothing if no ng-model // // Specify how UI should be updated // ngModel.$render = function() { // element.html(ngModel.$viewValue || ''); // }; // // Listen for change events to enable binding // element.on('blur keyup change', function() { // scope.$apply(read); // }); // read(); // initialize // // Write data to the model // function read() { // var html = element.html(); // // When we clear the content editable the browser leaves a <br> behind // // If strip-br attribute is provided then we strip this out // if( attrs.stripBr && html == '<br>' ) { // html = ''; // } // ngModel.$setViewValue(html); // } // } // }; // });
(function() { function require(path, parent, orig) { var resolved = require.resolve(path); if (null == resolved) { orig = orig || path; parent = parent || "root"; var err = new Error('Failed to require "' + orig + '" from "' + parent + '"'); err.path = orig; err.parent = parent; err.require = true; throw err; } var module = require.modules[resolved]; if (!module.exports) { module.exports = {}; module.client = module.component = true; module.call(this, module.exports, require.relative(resolved), module); } return module.exports; } require.modules = {}; require.aliases = {}; require.resolve = function(path) { if (path.charAt(0) === "/") path = path.slice(1); var index = path + "/index.js"; var paths = [ path, path + ".js", path + ".json", path + "/index.js", path + "/index.json" ]; for (var i = 0; i < paths.length; i++) { var path = paths[i]; if (require.modules.hasOwnProperty(path)) return path; } if (require.aliases.hasOwnProperty(index)) { return require.aliases[index]; } }; require.normalize = function(curr, path) { var segs = []; if ("." != path.charAt(0)) return path; curr = curr.split("/"); path = path.split("/"); for (var i = 0; i < path.length; ++i) { if (".." == path[i]) { curr.pop(); } else if ("." != path[i] && "" != path[i]) { segs.push(path[i]); } } return curr.concat(segs).join("/"); }; require.register = function(path, definition) { require.modules[path] = definition; }; require.alias = function(from, to) { if (!require.modules.hasOwnProperty(from)) { throw new Error('Failed to alias "' + from + '", it does not exist'); } require.aliases[to] = from; }; require.relative = function(parent) { var p = require.normalize(parent, ".."); function lastIndexOf(arr, obj) { var i = arr.length; while (i--) { if (arr[i] === obj) return i; } return -1; } function localRequire(path) { var resolved = localRequire.resolve(path); return require(resolved, parent, path); } localRequire.resolve = function(path) { var c = path.charAt(0); if ("/" == c) return path.slice(1); if ("." == c) return require.normalize(p, path); var segs = parent.split("/"); var i = lastIndexOf(segs, "deps") + 1; if (!i) i = 0; path = segs.slice(0, i + 1).join("/") + "/deps/" + path; return path; }; localRequire.exists = function(path) { return require.modules.hasOwnProperty(localRequire.resolve(path)); }; return localRequire; }; require.register("visionmedia-configurable.js/index.js", function(exports, require, module) { module.exports = function(obj) { obj.settings = {}; obj.set = function(name, val) { if (1 == arguments.length) { for (var key in name) { this.set(key, name[key]); } } else { this.settings[name] = val; } return this; }; obj.get = function(name) { return this.settings[name]; }; obj.enable = function(name) { return this.set(name, true); }; obj.disable = function(name) { return this.set(name, false); }; obj.enabled = function(name) { return !!this.get(name); }; obj.disabled = function(name) { return !this.get(name); }; return obj; }; }); require.register("codeactual-extend/index.js", function(exports, require, module) { module.exports = function extend(object) { var args = Array.prototype.slice.call(arguments, 1); for (var i = 0, source; source = args[i]; i++) { if (!source) continue; for (var property in source) { object[property] = source[property]; } } return object; }; }); require.register("qualiancy-tea-properties/lib/properties.js", function(exports, require, module) { var exports = module.exports = {}; exports.get = function(obj, path) { var parsed = parsePath(path); return getPathValue(parsed, obj); }; exports.set = function(obj, path, val) { var parsed = parsePath(path); setPathValue(parsed, val, obj); }; function defined(val) { return "undefined" === typeof val; } function parsePath(path) { var str = path.replace(/\[/g, ".["), parts = str.match(/(\\\.|[^.]+?)+/g); return parts.map(function(value) { var re = /\[(\d+)\]$/, mArr = re.exec(value); if (mArr) return { i: parseFloat(mArr[1]) }; else return { p: value }; }); } function getPathValue(parsed, obj) { var tmp = obj, res; for (var i = 0, l = parsed.length; i < l; i++) { var part = parsed[i]; if (tmp) { if (!defined(part.p)) tmp = tmp[part.p]; else if (!defined(part.i)) tmp = tmp[part.i]; if (i == l - 1) res = tmp; } else { res = undefined; } } return res; } function setPathValue(parsed, val, obj) { var tmp = obj; for (var i = 0, l = parsed.length; i < l; i++) { var part = parsed[i]; if (!defined(tmp)) { if (i == l - 1) { if (!defined(part.p)) tmp[part.p] = val; else if (!defined(part.i)) tmp[part.i] = val; } else { if (!defined(part.p) && tmp[part.p]) tmp = tmp[part.p]; else if (!defined(part.i) && tmp[part.i]) tmp = tmp[part.i]; else { var next = parsed[i + 1]; if (!defined(part.p)) { tmp[part.p] = {}; tmp = tmp[part.p]; } else if (!defined(part.i)) { tmp[part.i] = []; tmp = tmp[part.i]; } } } } else { if (i == l - 1) tmp = val; else if (!defined(part.p)) tmp = {}; else if (!defined(part.i)) tmp = []; } } } }); require.register("manuelstofer-each/index.js", function(exports, require, module) { "use strict"; var nativeForEach = [].forEach; module.exports = function(obj, iterator, context) { if (obj == null) return; if (nativeForEach && obj.forEach === nativeForEach) { obj.forEach(iterator, context); } else if (obj.length === +obj.length) { for (var i = 0, l = obj.length; i < l; i++) { if (iterator.call(context, obj[i], i, obj) === {}) return; } } else { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { if (iterator.call(context, obj[key], key, obj) === {}) return; } } } }; }); require.register("codeactual-is/index.js", function(exports, require, module) { "use strict"; var each = require("each"); var types = [ "Arguments", "Function", "String", "Number", "Date", "RegExp", "Array" ]; each(types, function(type) { var method = type === "Function" ? type : type.toLowerCase(); module.exports[method] = function(obj) { return Object.prototype.toString.call(obj) === "[object " + type + "]"; }; }); if (Array.isArray) { module.exports.array = Array.isArray; } module.exports.object = function(obj) { return obj === Object(obj); }; }); require.register("long-con/lib/component/main.js", function(exports, require, module) { module.exports = { requireComponent: require }; }); require.alias("visionmedia-configurable.js/index.js", "long-con/deps/configurable.js/index.js"); require.alias("visionmedia-configurable.js/index.js", "configurable.js/index.js"); require.alias("codeactual-extend/index.js", "long-con/deps/extend/index.js"); require.alias("codeactual-extend/index.js", "extend/index.js"); require.alias("qualiancy-tea-properties/lib/properties.js", "long-con/deps/tea-properties/lib/properties.js"); require.alias("qualiancy-tea-properties/lib/properties.js", "long-con/deps/tea-properties/index.js"); require.alias("qualiancy-tea-properties/lib/properties.js", "tea-properties/index.js"); require.alias("qualiancy-tea-properties/lib/properties.js", "qualiancy-tea-properties/index.js"); require.alias("codeactual-is/index.js", "long-con/deps/is/index.js"); require.alias("codeactual-is/index.js", "is/index.js"); require.alias("manuelstofer-each/index.js", "codeactual-is/deps/each/index.js"); require.alias("long-con/lib/component/main.js", "long-con/index.js"); if (typeof exports == "object") { module.exports = require("long-con"); } else if (typeof define == "function" && define.amd) { define(function() { return require("long-con"); }); } else { this["longCon"] = require("long-con"); } })();
let crypto = require('crypto') let Buffer = crypto.Buffer module.exports = { generateSalt: function () { return crypto.randomBytes(128).toString('base64') }, generatePasswordHash: function (salt, password) { return crypto.createHash('sha256').update(password).digest("hex"); } }
'use strict'; // Use applicaion configuration module to register a new module ApplicationConfiguration.registerModule('google-agenda');
import SongManager from '../songs.js'; class Boot extends Phaser.State { constructor() { super(); } preload() { this.load.image('preloader', 'assets/preloader.gif'); } create() { this.game.input.maxPointers = 1; //setup device scaling if (this.game.device.desktop) { this.game.scale.pageAlignHorizontally = true; } else { this.game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL; this.game.scale.minWidth = 480; this.game.scale.minHeight = 260; this.game.scale.maxWidth = 640; this.game.scale.maxHeight = 480; this.game.scale.forceOrientation(true); this.game.scale.pageAlignHorizontally = true; this.game.scale.setScreenSize(true); } this.initGlobalVariables(); this.game.state.start('preloader'); } initGlobalVariables(){ this.game.global = { room: 'Bed', songManager: new SongManager(this.game) }; } } export default Boot;
'use strict'; /* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */ const mongo = require('@turbasen/db-mongo'); const redis = require('@turbasen/db-redis'); const users = require('@turbasen/test-data').api.users; before(done => { if (mongo.db) { return done(); } return mongo.on('ready', done); }); beforeEach(done => redis.flushall(done)); beforeEach(done => mongo.db.dropDatabase(done)); beforeEach(done => mongo.api.users.insert(users, done));
/* */ "format global"; var resolveRc = require("../../lib/babel/api/register/resolve-rc"); var readdir = require("fs-readdir-recursive"); var index = require("./index"); var babel = require("../../lib/babel/api/node"); var util = require("../../lib/babel/util"); var path = require("path"); var fs = require("fs"); var _ = require("lodash"); exports.readdirFilter = function (filename) { return readdir(filename).filter(function (filename) { return util.canCompile(filename); }); }; exports.readdir = readdir; exports.canCompile = util.canCompile; exports.addSourceMappingUrl = function (code, loc) { return code + "\n//# sourceMappingURL=" + path.basename(loc); }; exports.transform = function (filename, code, opts) { opts = _.defaults(opts || {}, index.opts); opts.filename = filename; resolveRc(filename, opts); var result = babel.transform(code, opts); result.filename = filename; result.actual = code; return result; }; exports.compile = function (filename, opts) { var code = fs.readFileSync(filename, "utf8"); return exports.transform(filename, code, opts); };
// 用於事件處理 // 一種事件通道 var EventEmitter = require('events') var eventEmitter = new EventEmitter() eventEmitter.setMaxListeners(0) module.exports = eventEmitter
import * as THREE from '../../build/three.module.js'; import { Config } from './Config.js'; import { Loader } from './Loader.js'; import { History as _History } from './History.js'; import { Strings } from './Strings.js'; import { Storage as _Storage } from './Storage.js'; var _DEFAULT_CAMERA = new THREE.PerspectiveCamera( 50, 1, 0.01, 1000 ); _DEFAULT_CAMERA.name = 'Camera'; _DEFAULT_CAMERA.position.set( 0, 5, 10 ); _DEFAULT_CAMERA.lookAt( new THREE.Vector3() ); function Editor() { var Signal = signals.Signal; this.signals = { // script editScript: new Signal(), // player startPlayer: new Signal(), stopPlayer: new Signal(), // vr toggleVR: new Signal(), exitedVR: new Signal(), // notifications editorCleared: new Signal(), savingStarted: new Signal(), savingFinished: new Signal(), transformModeChanged: new Signal(), snapChanged: new Signal(), spaceChanged: new Signal(), rendererCreated: new Signal(), rendererUpdated: new Signal(), sceneBackgroundChanged: new Signal(), sceneEnvironmentChanged: new Signal(), sceneFogChanged: new Signal(), sceneFogSettingsChanged: new Signal(), sceneGraphChanged: new Signal(), sceneRendered: new Signal(), cameraChanged: new Signal(), cameraResetted: new Signal(), geometryChanged: new Signal(), objectSelected: new Signal(), objectFocused: new Signal(), objectAdded: new Signal(), objectChanged: new Signal(), objectRemoved: new Signal(), cameraAdded: new Signal(), cameraRemoved: new Signal(), helperAdded: new Signal(), helperRemoved: new Signal(), materialAdded: new Signal(), materialChanged: new Signal(), materialRemoved: new Signal(), scriptAdded: new Signal(), scriptChanged: new Signal(), scriptRemoved: new Signal(), windowResize: new Signal(), showGridChanged: new Signal(), showHelpersChanged: new Signal(), refreshSidebarObject3D: new Signal(), historyChanged: new Signal(), viewportCameraChanged: new Signal(), animationStopped: new Signal() }; this.config = new Config(); this.history = new _History( this ); this.storage = new _Storage(); this.strings = new Strings( this.config ); this.loader = new Loader( this ); this.camera = _DEFAULT_CAMERA.clone(); this.scene = new THREE.Scene(); this.scene.name = 'Scene'; this.sceneHelpers = new THREE.Scene(); this.object = {}; this.geometries = {}; this.materials = {}; this.textures = {}; this.scripts = {}; this.materialsRefCounter = new Map(); // tracks how often is a material used by a 3D object this.mixer = new THREE.AnimationMixer( this.scene ); this.selected = null; this.helpers = {}; this.cameras = {}; this.viewportCamera = this.camera; this.addCamera( this.camera ); } Editor.prototype = { setScene: function ( scene ) { this.scene.uuid = scene.uuid; this.scene.name = scene.name; this.scene.background = ( scene.background !== null ) ? scene.background.clone() : null; if ( scene.fog !== null ) this.scene.fog = scene.fog.clone(); this.scene.userData = JSON.parse( JSON.stringify( scene.userData ) ); // avoid render per object this.signals.sceneGraphChanged.active = false; while ( scene.children.length > 0 ) { this.addObject( scene.children[ 0 ] ); } this.signals.sceneGraphChanged.active = true; this.signals.sceneGraphChanged.dispatch(); }, // addObject: function ( object, parent, index ) { var scope = this; object.traverse( function ( child ) { if ( child.geometry !== undefined ) scope.addGeometry( child.geometry ); if ( child.material !== undefined ) scope.addMaterial( child.material ); scope.addCamera( child ); scope.addHelper( child ); } ); if ( parent === undefined ) { this.scene.add( object ); } else { parent.children.splice( index, 0, object ); object.parent = parent; } this.signals.objectAdded.dispatch( object ); this.signals.sceneGraphChanged.dispatch(); }, moveObject: function ( object, parent, before ) { if ( parent === undefined ) { parent = this.scene; } parent.add( object ); // sort children array if ( before !== undefined ) { var index = parent.children.indexOf( before ); parent.children.splice( index, 0, object ); parent.children.pop(); } this.signals.sceneGraphChanged.dispatch(); }, nameObject: function ( object, name ) { object.name = name; this.signals.sceneGraphChanged.dispatch(); }, removeObject: function ( object ) { if ( object.parent === null ) return; // avoid deleting the camera or scene var scope = this; object.traverse( function ( child ) { scope.removeCamera( child ); scope.removeHelper( child ); if ( child.material !== undefined ) scope.removeMaterial( child.material ); } ); object.parent.remove( object ); this.signals.objectRemoved.dispatch( object ); this.signals.sceneGraphChanged.dispatch(); }, addGeometry: function ( geometry ) { this.geometries[ geometry.uuid ] = geometry; }, setGeometryName: function ( geometry, name ) { geometry.name = name; this.signals.sceneGraphChanged.dispatch(); }, addMaterial: function ( material ) { if ( Array.isArray( material ) ) { for ( var i = 0, l = material.length; i < l; i ++ ) { this.addMaterialToRefCounter( material[ i ] ); } } else { this.addMaterialToRefCounter( material ); } this.signals.materialAdded.dispatch(); }, addMaterialToRefCounter: function ( material ) { var materialsRefCounter = this.materialsRefCounter; var count = materialsRefCounter.get( material ); if ( count === undefined ) { materialsRefCounter.set( material, 1 ); this.materials[ material.uuid ] = material; } else { count ++; materialsRefCounter.set( material, count ); } }, removeMaterial: function ( material ) { if ( Array.isArray( material ) ) { for ( var i = 0, l = material.length; i < l; i ++ ) { this.removeMaterialFromRefCounter( material[ i ] ); } } else { this.removeMaterialFromRefCounter( material ); } this.signals.materialRemoved.dispatch(); }, removeMaterialFromRefCounter: function ( material ) { var materialsRefCounter = this.materialsRefCounter; var count = materialsRefCounter.get( material ); count --; if ( count === 0 ) { materialsRefCounter.delete( material ); delete this.materials[ material.uuid ]; } else { materialsRefCounter.set( material, count ); } }, getMaterialById: function ( id ) { var material; var materials = Object.values( this.materials ); for ( var i = 0; i < materials.length; i ++ ) { if ( materials[ i ].id === id ) { material = materials[ i ]; break; } } return material; }, setMaterialName: function ( material, name ) { material.name = name; this.signals.sceneGraphChanged.dispatch(); }, addTexture: function ( texture ) { this.textures[ texture.uuid ] = texture; }, // addCamera: function ( camera ) { if ( camera.isCamera ) { this.cameras[ camera.uuid ] = camera; this.signals.cameraAdded.dispatch( camera ); } }, removeCamera: function ( camera ) { if ( this.cameras[ camera.uuid ] !== undefined ) { delete this.cameras[ camera.uuid ]; this.signals.cameraRemoved.dispatch( camera ); } }, // addHelper: function () { var geometry = new THREE.SphereGeometry( 2, 4, 2 ); var material = new THREE.MeshBasicMaterial( { color: 0xff0000, visible: false } ); return function ( object, helper ) { if ( helper === undefined ) { if ( object.isCamera ) { helper = new THREE.CameraHelper( object ); } else if ( object.isPointLight ) { helper = new THREE.PointLightHelper( object, 1 ); } else if ( object.isDirectionalLight ) { helper = new THREE.DirectionalLightHelper( object, 1 ); } else if ( object.isSpotLight ) { helper = new THREE.SpotLightHelper( object ); } else if ( object.isHemisphereLight ) { helper = new THREE.HemisphereLightHelper( object, 1 ); } else if ( object.isSkinnedMesh ) { helper = new THREE.SkeletonHelper( object.skeleton.bones[ 0 ] ); } else { // no helper for this object type return; } var picker = new THREE.Mesh( geometry, material ); picker.name = 'picker'; picker.userData.object = object; helper.add( picker ); } this.sceneHelpers.add( helper ); this.helpers[ object.id ] = helper; this.signals.helperAdded.dispatch( helper ); }; }(), removeHelper: function ( object ) { if ( this.helpers[ object.id ] !== undefined ) { var helper = this.helpers[ object.id ]; helper.parent.remove( helper ); delete this.helpers[ object.id ]; this.signals.helperRemoved.dispatch( helper ); } }, // addScript: function ( object, script ) { if ( this.scripts[ object.uuid ] === undefined ) { this.scripts[ object.uuid ] = []; } this.scripts[ object.uuid ].push( script ); this.signals.scriptAdded.dispatch( script ); }, removeScript: function ( object, script ) { if ( this.scripts[ object.uuid ] === undefined ) return; var index = this.scripts[ object.uuid ].indexOf( script ); if ( index !== - 1 ) { this.scripts[ object.uuid ].splice( index, 1 ); } this.signals.scriptRemoved.dispatch( script ); }, getObjectMaterial: function ( object, slot ) { var material = object.material; if ( Array.isArray( material ) && slot !== undefined ) { material = material[ slot ]; } return material; }, setObjectMaterial: function ( object, slot, newMaterial ) { if ( Array.isArray( object.material ) && slot !== undefined ) { object.material[ slot ] = newMaterial; } else { object.material = newMaterial; } }, setViewportCamera: function ( uuid ) { this.viewportCamera = this.cameras[ uuid ]; this.signals.viewportCameraChanged.dispatch(); }, // select: function ( object ) { if ( this.selected === object ) return; var uuid = null; if ( object !== null ) { uuid = object.uuid; } this.selected = object; this.config.setKey( 'selected', uuid ); this.signals.objectSelected.dispatch( object ); }, selectById: function ( id ) { if ( id === this.camera.id ) { this.select( this.camera ); return; } this.select( this.scene.getObjectById( id ) ); }, selectByUuid: function ( uuid ) { var scope = this; this.scene.traverse( function ( child ) { if ( child.uuid === uuid ) { scope.select( child ); } } ); }, deselect: function () { this.select( null ); }, focus: function ( object ) { if ( object !== undefined ) { this.signals.objectFocused.dispatch( object ); } }, focusById: function ( id ) { this.focus( this.scene.getObjectById( id ) ); }, clear: function () { this.history.clear(); this.storage.clear(); this.camera.copy( _DEFAULT_CAMERA ); this.signals.cameraResetted.dispatch(); this.scene.name = 'Scene'; this.scene.userData = {}; this.scene.background = null; this.scene.environment = null; this.scene.fog = null; var objects = this.scene.children; while ( objects.length > 0 ) { this.removeObject( objects[ 0 ] ); } this.geometries = {}; this.materials = {}; this.textures = {}; this.scripts = {}; this.materialsRefCounter.clear(); this.animations = {}; this.mixer.stopAllAction(); this.deselect(); this.signals.editorCleared.dispatch(); }, // fromJSON: function ( json ) { var scope = this; var loader = new THREE.ObjectLoader(); var camera = loader.parse( json.camera ); this.camera.copy( camera ); this.signals.cameraResetted.dispatch(); this.history.fromJSON( json.history ); this.scripts = json.scripts; loader.parse( json.scene, function ( scene ) { scope.setScene( scene ); } ); }, toJSON: function () { // scripts clean up var scene = this.scene; var scripts = this.scripts; for ( var key in scripts ) { var script = scripts[ key ]; if ( script.length === 0 || scene.getObjectByProperty( 'uuid', key ) === undefined ) { delete scripts[ key ]; } } // return { metadata: {}, project: { shadows: this.config.getKey( 'project/renderer/shadows' ), shadowType: this.config.getKey( 'project/renderer/shadowType' ), vr: this.config.getKey( 'project/vr' ), physicallyCorrectLights: this.config.getKey( 'project/renderer/physicallyCorrectLights' ), toneMapping: this.config.getKey( 'project/renderer/toneMapping' ), toneMappingExposure: this.config.getKey( 'project/renderer/toneMappingExposure' ) }, camera: this.camera.toJSON(), scene: this.scene.toJSON(), scripts: this.scripts, history: this.history.toJSON() }; }, objectByUuid: function ( uuid ) { return this.scene.getObjectByProperty( 'uuid', uuid, true ); }, execute: function ( cmd, optionalName ) { this.history.execute( cmd, optionalName ); }, undo: function () { this.history.undo(); }, redo: function () { this.history.redo(); } }; export { Editor };
/** * @venus-library jasmine * @venus-include ../../src/functions.js * @venus-include ../../src/EventDispatcher/EventDispatcherInterface.js * @venus-include ../../src/EventDispatcher/EventDispatcher.js * @venus-include ../../src/EventDispatcher/Event.js * @venus-code ../../src/EventDispatcher/GenericEvent.js */ describe('event dispatcher generic event', function () { var e; beforeEach(function () { e = new Sy.EventDispatcher.GenericEvent(); }) it('should extend base event', function () { expect(e instanceof Sy.EventDispatcher.Event).toBe(true); }); it('should throw if setting invalid args object', function () { expect(function () { new Sy.EventDispatcher.GenericEvent('foo', ''); }).toThrow('Event arguments must be an object'); expect(function () { e.setArguments(''); }).toThrow('Event arguments must be an object'); }); it('should return the subject', function () { var e = new Sy.EventDispatcher.GenericEvent('foo'); expect(e.getSubject()).toEqual('foo'); }); it('should return an argument', function () { var e = new Sy.EventDispatcher.GenericEvent('foo', {foo: 'bar'}) expect(e.getArgument('foo')).toEqual('bar'); }); it('should set an argument', function () { expect(e.setArgument('foo', 'bar')).toBe(e); expect(e.getArgument('foo')).toEqual('bar'); }); it('should get arguments', function () { var data = {foo: 'bar'}; expect(e.setArguments(data)).toBe(e); expect(e.getArguments()).toBe(data); }); });
/** * Credit to @faceleg for some of the typedefs seen here: * https://github.com/solnet-aquarium/flow-interfaces-angular/blob/master/interfaces/angular.js */ declare module angular { // NOTE: if you don't use named scope bindings, remove string type in the end // for stricter types declare type ScopeBindings = "<" | "=" | "&" | "<?" | "=?" | "&?" | string; declare type Scope = { [key: string]: ScopeBindings }; declare type ControllerFunction = (...a: Array<*>) => void; // I'm not sure how represent this properly: Angular DI declarations are a // list of strings with a single function at the end. The function can vary, // so it is a type param. // // NOTE: if you use compile step to mangle array, replace below with // declare type $npm$angular$DependencyInjection<T> = T declare type $npm$angular$DependencyInjection<T> = Array<string | T>; // Extending Array<Element> allows us to do the `jq[0]` expression and friends // to get the actual underlying Element. // TODO: This is supposed to be interchangeable with JQuery. Can we possibly // check to see if JQuery's types are already defined? declare interface JqliteElement extends Array<Element> { remove: () => JqliteElement; contents: () => JqliteElement; injector: Function; } declare type AngularLinkFunction = ( scope: $Scope<*>, element: JqliteElement, attrs: mixed, controller: mixed ) => void; declare type AngularCompileLink = { post?: AngularLinkFunction, pre?: AngularLinkFunction }; // TODO: Attrs and controller should be properly typed. declare function CompileFunction( element: JqliteElement, attrs: mixed, controller: ControllerFunction ): AngularLinkFunction; // TODO: Expand to cover the whole matrix of AECM, in any order. Probably // should write something to handle it. declare type DirectiveRestrict = "A" | "E" | "AE" | "EA"; declare type Directive = {| restrict?: DirectiveRestrict, template?: string, templateUrl?: string, scope?: Scope, controller?: ControllerFunction, link?: AngularLinkFunction, controllerAs?: string, bindToController?: boolean, // TODO: flesh out this definition compile?: (...a: any) => AngularCompileLink |}; declare type DirectiveDeclaration = ( name: string, di: $npm$angular$DependencyInjection<(...a: Array<*>) => Directive> ) => AngularModule; declare type Component = {| bindings?: Scope, template?: string, templateUrl?: string, controllerAs?: string, controller?: $npm$angular$DependencyInjection< Class<*> | ControllerFunction >, transclude?: boolean |}; declare type ComponentDeclaration = ( name: string, component: Component ) => AngularModule; declare type ControllerDeclaration = ( name: string, di: $npm$angular$DependencyInjection<ControllerFunction> ) => AngularModule; declare type ConfigDeclaration = ( di: $npm$angular$DependencyInjection<(...a: Array<*>) => void> ) => AngularModule; declare type FactoryDeclaration = ( name: string, di: $npm$angular$DependencyInjection<(...a: Array<*>) => Object> ) => AngularModule; declare type FilterDeclaration = ( name: string, di: $npm$angular$DependencyInjection<(...a: Array<*>) => Function> ) => AngularModule; declare type ServiceDeclaration = ( name: string, di: $npm$angular$DependencyInjection<(...a: Array<*>) => Function | Object> ) => AngularModule; declare type RunDeclaration = ( fn: $npm$angular$DependencyInjection<(...a: Array<*>) => void> ) => AngularModule; declare type ValueDeclaration = (name: string, value: mixed) => AngularModule; declare type ConstantDeclaration = ( name: string, value: mixed ) => AngularModule; declare type AngularModule = {| controller: ControllerDeclaration, component: ComponentDeclaration, directive: DirectiveDeclaration, run: RunDeclaration, config: ConfigDeclaration, factory: FactoryDeclaration, filter: FilterDeclaration, service: ServiceDeclaration, value: ValueDeclaration, constant: ConstantDeclaration, name: string |}; declare type Dependency = AngularModule | string; declare function module( name: string, deps?: ?Array<Dependency> ): AngularModule; declare function element(html: string | Element | Document): JqliteElement; declare function copy<T>(object: T): T; declare function extend<A, B>(a: A, b: B): A & B; declare function extend<A, B, C>(a: A, b: B, c: C): A & B & C; declare function extend<A, B, C, D>(a: A, b: B, c: C, d: D): A & B & C & D; declare function extend<A, B, C, D, E>( a: A, b: B, c: C, d: D, e: E ): A & B & C & D & E; declare function forEach<T>( obj: Object, iterator: (value: T, key: string) => void ): void; declare function forEach<T>( obj: Array<T>, iterator: (value: T, key: number) => void ): void; declare function fromJson(json: string): Object | Array<*> | string | number; declare function toJson( obj: Object | Array<any> | string | Date | number | boolean, pretty?: boolean | number ): string; declare function isDefined(val: any): boolean; declare function isArray(value: Array<any>): true; declare function isArray(value: any): false; declare function noop(): void; declare type AngularQ = { when: <T>(value: T) => AngularPromise<T> }; declare type AngularPromise<T> = { then: <U>(a: (resolve: U) => T) => AngularPromise<*>, catch: <U>(a: (e: Error) => U) => AngularPromise<*>, finally: <U>(a: (result: U | typeof Error) => T) => AngularPromise<*> }; //**************************************************************************** // Angular testing tools //**************************************************************************** declare type AngularMock = { inject: (...a: Array<*>) => Function, module: (...a: Array<string | Function | Object>) => () => void }; declare var mock: AngularMock; declare type StateProviderParams = { url?: string, abstract?: boolean, params?: Object, views?: Object, data?: Object, templateUrl?: string, template?: string, controller?: string | ControllerFunction, resolve?: Object }; declare type $StateProvider = { state: (name: string, conf: StateProviderParams) => $StateProvider }; //---------------------------------------------------------------------------- // Service specific stuff //---------------------------------------------------------------------------- declare type AngularHttpService = { post: AngularHttpPost<*> }; declare type AngularHttpPost<T> = ( url: string, data: mixed ) => AngularPromise<T>; declare type AngularResourceResult<T> = { $promise: AngularPromise<T> }; declare type AngularResource = { get: <T>(options?: Object, callback?: Function) => AngularResourceResult<T> }; declare function AngularResourceFactory( url: string, defaultParams?: Object, actions?: Object, options?: Object ): AngularResource; declare function AngularCompileService(a: JqliteElement): JqliteElement; declare type WatchExpression<T> = string | ((scope: $Scope<T>) => any); declare type EvalExpression = string | (() => void); declare type ApplyExpression = string | (() => void); declare type Listener<T> = ( newValue: *, oldValue: *, $scope: $Scope<T> ) => any; declare type _Watch1<T> = ( expression: WatchExpression<T>, listener: Listener<T>, objectEquality?: boolean ) => () => void; declare type _Watch2<T> = ( listener: Listener<T>, objectEquality?: boolean ) => () => void; declare type $Scope<T: Object> = {| $new(isolate: boolean, parent: $Scope<T>): $Scope<T>, $watch: _Watch1<T> & _Watch2<T>, $watchGroup( expressions: Array<WatchExpression<T>>, listener: Listener<T> ): () => void, $watchCollection( expression: WatchExpression<T>, listener: Listener<T> ): () => void, $digest(): void, $destroy(): void, $eval(expression: EvalExpression, locals?: Object): void, $evalAsync(expression: EvalExpression, locals?: Object): void, $apply(expression?: ApplyExpression): void, $applyAsync(expression?: ApplyExpression): void, $on(name: string, listener: (event: *, ...Array<*>) => void): () => void, $emit(name: string, ...Array<*>): void, $broadcast(name: string, ...Array<*>): void, $$postDigest(cb: () => void): void, $id: string, $parent: $Scope<*>, $root: $Scope<*> |} & T; declare type $Timeout = ( fn?: Function, delay?: number, invokeApply?: boolean, additionalParams?: * ) => AngularPromise<*>; }
/* MENU */ $("#menu-main .menu-item").hover(function() { $("#menu-main > .menu-item > a").addClass('sfocato'); $(this).find("a").removeClass('sfocato'); $("menu-main").css("z-index", "50"); /* visualizzazione submenu */ $(".is-active > .is-dropdown-submenu").css("opacity", 1); //$(this).removeClass('sfocato'); }); $("#menu-main > .menu-item").mouseout(function() { $("#menu-main > .menu-item > a").removeClass('sfocato'); //$(".submenu").css("top", "5px"); }); $("#menu-main").find(".menu-item").click(function() { $("#menu-main").find(".active").removeClass('active'); $(this).addClass("active"); var sect_id = $(this).find("a").eq(0).attr("href"); if(sect_id != "#") { console.log(sect_id); goto_section($(sect_id)); } }); $(window).scroll(function() { /* animazione top menu */ if($(this).scrollTop()>50){ $(".is-stuck").removeClass("bigger"); $(".is-stuck").addClass("smaller"); $("#backtotop").css("opacity"," 1"); } else { $(".is-stuck").removeClass("smaller"); $(".is-stuck").addClass("bigger"); $("#backtotop").css("opacity", "0"); } /* fade in sezioni */ var ST = new Number($("#backtotop").offset().top); var idx = 0; $(".container section").each( function() { var sect_ST = parseInt($(".container section").eq(idx).offset().top); var IDS = $(this).attr("id"); if(IDS != "hp") { if(ST>sect_ST) { console.log("fade in "+$(this).attr("id")); //console.log("Page "+ST+" section "+sect_ST); $(this).css("opacity",1); } } idx++; }); }); function goto_section(sect) { $('html, body').animate({ scrollTop: sect.offset().top + 60 },2000); } function goto_top() { $('html, body').animate({ scrollTop: 0 },1500); } /* SLIDER */ $(document).ready( function() { $(".claim img").animate({ opacity: 1 },200); var $animation = $(".claim img").data("animation"); //MotionUI.animateIn($(".claim img"), "slide-in-right"); $(".submenu").removeClass("vertical"); //$(".submenu").css("top", "5px"); }); /* BACK TO TOP */ $("#backtotop a").click( function() { //console.log("back to top"); goto_top(); });
var React = require('react'); var ReactDOM = require('react-dom'); var MyFeedList = require('./MyFeedList') var MyProfileBox = require('./MyProfileBox') var MyGroupsBox = require('./MyGroupsBox') module.exports = (props) => ( <div className="container"> <div className="row"> <div className="aside"> <MyProfileBox user={props.user}/> <MyGroupsBox groups={props.groups}/> </div> <div className="content"> <MyFeedList user={props.user}/> </div> </div> </div> )
/** * cheap.js - C-like memory layout for javascript * version 0.1.1 * Copyright 2014 Robert Nix * MIT License */ (function() { var C, addressMax, addressMin, block, makeAccessors, makeStructMember, pointerShift, pointerSize, ptr, __slice = [].slice; C = {}; makeStructMember = function(typeName, pointerDepth, memberName, arrayLength, offset) { return { typeName: typeName, pointerDepth: pointerDepth, memberName: memberName, offset: offset, arrayLength: arrayLength, isArray: arrayLength != null }; }; C._typedefs = {}; C.typedef = function(typeName, structDef) { if (typeName in C) { throw new Error('name collides'); } C._typedefs[typeName] = structDef; return C[typeName] = function(memberName, arrayLength) { if (typeof memberName === 'string') { return makeStructMember(typeName, 0, memberName, arrayLength); } else { return makeStructMember(typeName, 0, void 0, arrayLength, memberName); } }; }; C.ptr = function(typeName, memberName, pointerDepth) { if (pointerDepth == null) { pointerDepth = 1; } return makeStructMember(typeName, pointerDepth, memberName); }; C.typedef('uint'); C.typedef('int'); C.typedef('ushort'); C.typedef('short'); C.typedef('uchar'); C.typedef('char'); C.typedef('float'); C.typedef('double'); C.typedef('void'); pointerSize = 4; pointerShift = 2; C.set64Bit = function(is64Bit) { if (is64Bit) { pointerSize = 8; return pointerShift = 3; } else { pointerSize = 4; return pointerShift = 2; } }; C._typeNameToId = function(n) { switch (n) { case 'uint': return 0; case 'int': return 1; case 'ushort': return 2; case 'short': return 3; case 'uchar': return 4; case 'char': return 5; case 'float': return 6; case 'double': return 7; default: return -1; } }; C._arrayName = function(t) { switch (t) { case 0: case 'uint': return 'ui32'; case 1: case 'int': return 'i32'; case 2: case 'ushort': return 'ui16'; case 3: case 'short': return 'i16'; case 4: case 'uchar': return 'ui8'; case 5: case 'char': return 'i8'; case 6: case 'float': return 'f32'; case 7: case 'double': return 'f64'; default: return 'ui32'; } }; C._arrayElSize = function(t) { switch (t) { case 0: case 'uint': case 1: case 'int': return 4; case 2: case 'ushort': case 3: case 'short': return 2; case 4: case 'uchar': case 5: case 'char': return 1; case 6: case 'float': return 4; case 7: case 'double': return 8; default: return pointerSize; } }; C._arrayElShift = function(t) { switch (t) { case 0: case 'uint': case 1: case 'int': case 6: case 'float': return 2; case 2: case 'ushort': case 3: case 'short': return 1; case 4: case 'uchar': case 5: case 'char': return 0; case 7: case 'double': return 3; default: return pointerShift; } }; C.sizeof = function(type) { if (typeof type === 'string') { switch (type) { case 'char': case 'uchar': return 1; case 'short': case 'ushort': return 2; case 'int': case 'uint': case 'float': return 4; case 'double': return 8; case 'void*': return pointerSize; default: return 1; } } else { return type.__size; } }; C.strideof = function(type) { if (typeof type === 'string') { return C.sizeof(type); } else { return (type.__size + type.__align - 1) & -type.__align; } }; C.alignof = function(type) { if (typeof type === 'string') { return C.sizeof(type); } else { return type.__align; } }; C.offsetof = function(type, member) { return type[member].offset; }; makeAccessors = function(def) { var T, align, arr, basic, cName, elShift, member, offset, pd, size, stride, type, typeId; offset = def.offset, member = def.member, type = def.type, stride = def.stride, align = def.align, size = def.size; basic = typeof type === 'string'; typeId = C._typeNameToId(type); arr = C._arrayName(type); elShift = C._arrayElShift(type); if (member.pointerDepth === 0 && !member.isArray) { if (basic) { return { get: function() { return this.__b[arr][(this.__a + offset) >> elShift]; }, set: function(x) { return this.__b[arr][(this.__a + offset) >> elShift] = x; } }; } else { cName = '__c_' + member.memberName; return { get: function() { var res; if (this[cName] != null) { return this[cName]; } else { res = new type.__ctor(this.__b, this.__a + offset); this[cName] = res; return res; } }, set: function(x) { return C.memcpy(this.__b, this.__a + offset, x.__b, x.__a, size); } }; } } else if (member.pointerDepth === 0) { if (basic) { return { get: function() { var bIdx, __b; bIdx = (this.__a + offset) >> elShift; __b = this.__b; return function(idx, val) { if (val == null) { return __b[arr][bIdx + idx]; } else { return __b[arr][bIdx + idx] = val; } }; } }; } else { return { get: function() { var bOff, __b; bOff = this.__a + offset; __b = this.__b; return function(idx, val) { if (val == null) { return new type.__ctor(__b, bOff + idx * stride); } else { return C.memcpy(__b, bOff + idx * stride, val.__b, val.__a, size); } }; } }; } } else { T = typeId; if (T < 0) { T = type; } pd = member.pointerDepth; return { get: function() { var addr; addr = this.__b.ui32[(this.__a + offset) / 4]; return new ptr(addr, T, pd); }, set: function(x) { return this.__b.ui32[(this.__a + offset) / 4] = x.a; } }; } }; C.struct = function(def) { var align, end, member, name, offset, size, stride, struct, type, _i, _len, _type; struct = function() { return struct.__ctor.apply(this, arguments); }; struct.__size = 0; struct.__align = 1; if (Array.isArray(def)) { for (_i = 0, _len = def.length; _i < _len; _i++) { member = def[_i]; type = C._typedefs[member.typeName] || member.typeName; _type = type; if (member.pointerDepth > 0) { _type = 'void*'; } size = C.sizeof(_type); align = C.alignof(_type); stride = (size + align - 1) & -align; if (member.isArray) { size += stride * (member.arrayLength - 1); } struct.__size = (struct.__size + align - 1) & -align; offset = struct.__size; struct.__size += size; if (align > struct.__align) { struct.__align = align; } struct[member.memberName] = { offset: offset, member: member, type: type, stride: stride, align: align, size: size }; } } else { for (name in def) { member = def[name]; type = C._typedefs[member.typeName] || member.typeName; _type = type; if (member.pointerDepth > 0) { _type = 'void*'; } member.memberName = name; size = C.sizeof(_type); align = C.alignof(_type); stride = (size + align - 1) & -align; if (member.isArray) { size += stride * (member.arrayLength - 1); } offset = member.offset; end = offset + size; if (end > struct.__size) { struct.__size = end; } if (align > struct.__align) { struct.__align = align; } struct[member.memberName] = { offset: offset, member: member, type: type, stride: stride, align: align, size: size }; } } struct.__ctor = function(buffer, address) { this.__b = buffer; this.__a = address; return this; }; struct.__ctor.prototype = (function() { var k, result, v; result = { __t: struct }; for (k in struct) { v = struct[k]; if (k.substr(0, 2) !== '__') { Object.defineProperty(result, k, makeAccessors(v)); } } return result; })(); struct.prototype = struct.__ctor.prototype; return struct; }; C._heapLast = null; block = function(addr, size, prev, next) { var buf; this.a = addr; this.l = size; this.e = addr + size; this.prev = prev; if (prev != null) { prev.next = this; } this.next = next; if (next != null) { next.prev = this; } this.buf = buf = new ArrayBuffer(size); this.ui32 = new Uint32Array(buf); this.i32 = new Int32Array(buf); this.ui16 = new Uint16Array(buf); this.i16 = new Int16Array(buf); this.ui8 = new Uint8Array(buf); this.i8 = new Int8Array(buf); this.f32 = new Float32Array(buf); this.f64 = new Float64Array(buf); return this; }; block.prototype.free = function() { if (this === C._heapLast) { C._heapLast = this.prev; } if (this.prev != null) { this.prev.next = this.next; } if (this.next != null) { this.next.prev = this.prev; } }; addressMin = 0x00010000; addressMax = 0x7fff0000; C.malloc = function(size) { var addr, b, curr, min, room, _ref; if (size < 0) { throw new Error('invalid allocation size'); } size = (size + 0xf) & -0x10; if (C._heapLast === null) { if (size + addressMin > addressMax) { throw new Error('invalid allocation size'); } return C._heapLast = new block(addressMin, size, null, null); } else { curr = C._heapLast; if (size + curr.e <= addressMax) { addr = curr.e; return C._heapLast = new block(addr, size, curr, null); } else { b = null; while (true) { min = ((_ref = curr.prev) != null ? _ref.e : void 0) || addressMin; room = curr.a - min; if (room >= size) { addr = curr.a - size; b = new block(addr, size, curr.prev, curr); break; } curr = curr.prev; if (curr == null) { throw new Error('heap space not available'); } } return b; } } }; C.free = function(addr) { var curr; if (typeof addr === 'object') { return addr.free(); } if (addr < addressMin) { return; } if (addr >= addressMax) { return; } curr = C._heapLast; while (true) { if (curr == null) { break; } if (curr.a === addr) { return curr.free(); } curr = curr.prev; } }; C.getBufferAddress = function(addr) { var curr; if (typeof addr === 'object') { addr = addr.a; } curr = C._heapLast; while (true) { if (curr == null) { break; } if (curr.e > addr && curr.a <= addr) { return [curr, addr - curr.a]; } curr = curr.prev; } return [null, 0]; }; C._getHeapValue = function(addr, t) { var buf, rva, _ref; _ref = C.getBufferAddress(addr), buf = _ref[0], rva = _ref[1]; switch (t) { case 0: return buf.ui32[0 | rva / 4]; case 1: return buf.i32[0 | rva / 4]; case 2: return buf.ui16[0 | rva / 2]; case 3: return buf.i16[0 | rva / 2]; case 4: return buf.ui8[0 | rva]; case 5: return buf.i8[0 | rva]; case 6: return buf.f32[0 | rva / 4]; case 7: return buf.f64[0 | rva / 8]; default: return buf.ui32[0 | rva / 4]; } }; C._setHeapValue = function(addr, t, v) { var buf, rva, _ref; _ref = C.getBufferAddress(addr), buf = _ref[0], rva = _ref[1]; switch (t) { case 0: return buf.ui32[0 | rva / 4] = v; case 1: return buf.i32[0 | rva / 4] = v; case 2: return buf.ui16[0 | rva / 2] = v; case 3: return buf.i16[0 | rva / 2] = v; case 4: return buf.ui8[0 | rva] = v; case 5: return buf.i8[0 | rva] = v; case 6: return buf.f32[0 | rva / 4] = v; case 7: return buf.f64[0 | rva / 8] = v; default: return buf.ui32[0 | rva / 4] = v; } }; C.memcpy = function(dstBuf, dstRva, srcBuf, srcRva, size) { var dstAddr, srcAddr, _ref, _ref1; if (size == null) { dstAddr = dstBuf; srcAddr = dstRva; size = srcBuf; _ref = C.getBufferAddress(dstAddr), dstBuf = _ref[0], dstRva = _ref[1]; _ref1 = C.getBufferAddress(srcAddr), srcBuf = _ref1[0], srcRva = _ref1[1]; } return dstBuf.ui8.set(srcBuf.ui8.subarray(srcRva, srcRva + size), dstRva); }; C.copyBuffer = function(buf) { var res; res = C.malloc(buf.byteLength); res.ui8.set(new Uint8Array(buf), 0); return res; }; ptr = function(a, t, p) { this.a = a; this.t = t; this.p = p; return this; }; ptr.prototype.deref = function() { var buf, currAddr, head, nextDepth, nextObj, nextPtr, rva, tail, _ref; head = arguments[0], tail = 2 <= arguments.length ? __slice.call(arguments, 1) : []; nextDepth = this.p - 1; currAddr = this.a; head || (head = 0); if (nextDepth === 0) { if (typeof this.t === 'number') { return C._getHeapValue(currAddr + head * C._arrayElSize(this.t), this.t); } else { _ref = C.getBufferAddress(currAddr + head * C.sizeof(this.t)), buf = _ref[0], rva = _ref[1]; return new this.t(buf, rva); } } else { nextPtr = C._getHeapValue(currAddr + head * pointerSize, 0); nextObj = new ptr(nextPtr, this.t, nextDepth); if (tail.length > 0) { return this.deref.apply(nextObj, tail); } else { return nextObj; } } }; ptr.prototype.set = function(idx, val) { var currAddr, dstBuf, dstRva, nextDepth, _ref; nextDepth = this.p - 1; currAddr = this.a; if (nextDepth < 0) { throw new Error('bad pointer'); } if (nextDepth === 0) { if (typeof this.t === 'number') { return C._setHeapValue(currAddr + idx * C._arrayElSize(this.t), this.t, val); } else { _ref = C.getBufferAddress(currAddr + idx * C.sizeof(this.t)), dstBuf = _ref[0], dstRva = _ref[1]; return C.memcpy(dstBuf, dstRva, val.__b, val.__a, C.sizeof(this.t)); } } else { return C._setHeapValue(currAddr + idx * pointerSize, 0, val.a); } }; ptr.prototype.cast = function(type) { var p, tId; if (typeof type === 'string') { type = type.split('*'); p = type.length - 1; if (p === 0) { p = this.p; } tId = C._typeNameToId(type[0]); if (tId < 0) { tId = C._typedefs[type[0]]; } return new ptr(this.a, tId, p); } else { return new ptr(this.a, type, this.p); } }; C.ref = function(locatable, memberName) { var a, p, t; if (locatable.__t != null) { t = locatable.__t; a = locatable.__a + locatable.__b.a; p = 1; if (memberName != null) { a += t[memberName].offset; p += t[memberName].pointerDepth; t = t[memberName].type; } return new ptr(a, t, p); } else { return new ptr(locatable.a, 'void*', 1); } }; ptr.prototype.add = function(offset) { return new ptr(this.a + offset, this.t, this.p); }; if (typeof module === 'object' && typeof module.exports === 'object') { module.exports = C; } else if (typeof define === 'function' && define.amd) { define(['cheap'], function() { return this.cheap = C; }); } else { this.cheap = C; } }).call(this);
var UserPage = function UserPage() { var page = this; page.users = element.all(by.tagName('user-list-item')); page.get = get; page.selectRandomUser = selectRandomUser; page.mainContent = { startupText: element(by.id('content')).getText(), userLoaded: element(by.css('md-avatar face')).isPresent() }; function get() { browser.get("/e2e-index.html"); } function selectRandomUser() { console.log(page.users); page.users[0].click(); } }; module.exports = UserPage;
/* eslint key-spacing:0 spaced-comment:0 */ const path = require('path') const debug = require('debug')('app:config:project') const argv = require('yargs').argv const ip = require('ip') debug('Creating default configuration.') // ======================================================== // Default Configuration // ======================================================== const config = { env : process.env.NODE_ENV || 'development', // ---------------------------------- // Project Structure // ---------------------------------- path_base : path.resolve(__dirname, '..'), dir_client : 'src', dir_dist : 'dist', dir_public : 'public', dir_server : 'server', dir_test : 'tests', // ---------------------------------- // Server Configuration // ---------------------------------- server_host : ip.address(), // use string 'localhost' to prevent exposure on local network server_port : process.env.PORT || 3000, // ---------------------------------- // Compiler Configuration // ---------------------------------- compiler_babel : { cacheDirectory : true, plugins : ['transform-runtime', 'recharts'], presets : ['es2015', 'react', 'stage-0'] }, compiler_devtool : 'source-map', compiler_hash_type : 'hash', compiler_fail_on_warning : false, compiler_quiet : false, compiler_public_path : '/', compiler_stats : { chunks : false, chunkModules : false, colors : true }, compiler_vendors : [ 'react', 'react-redux', 'react-router', 'redux' ], // ---------------------------------- // Test Configuration // ---------------------------------- coverage_reporters : [ { type : 'text-summary' }, { type : 'lcov', dir : 'coverage' } ] } /************************************************ ------------------------------------------------- All Internal Configuration Below Edit at Your Own Risk ------------------------------------------------- ************************************************/ // ------------------------------------ // Environment // ------------------------------------ // N.B.: globals added here must _also_ be added to .eslintrc config.globals = { 'process.env' : { 'NODE_ENV' : JSON.stringify(config.env) }, 'NODE_ENV' : config.env, '__DEV__' : config.env === 'development', '__PROD__' : config.env === 'production', '__TEST__' : config.env === 'test', '__COVERAGE__' : !argv.watch && config.env === 'test', '__BASENAME__' : JSON.stringify(process.env.BASENAME || '') } // ------------------------------------ // Validate Vendor Dependencies // ------------------------------------ const pkg = require('../package.json') config.compiler_vendors = config.compiler_vendors .filter((dep) => { if (pkg.dependencies[dep]) return true debug( `Package "${dep}" was not found as an npm dependency in package.json; ` + `it won't be included in the webpack vendor bundle. Consider removing it from \`compiler_vendors\` in ~/config/index.js` ) }) // ------------------------------------ // Utilities // ------------------------------------ function base () { const args = [config.path_base].concat([].slice.call(arguments)) return path.resolve.apply(path, args) } config.paths = { base : base, client : base.bind(null, config.dir_client), public : base.bind(null, config.dir_public), dist : base.bind(null, config.dir_dist) } // ======================================================== // Environment Configuration // ======================================================== debug(`Looking for environment overrides for NODE_ENV "${config.env}".`) const environments = require('./environments.config') const overrides = environments[config.env] if (overrides) { debug('Found overrides, applying to default configuration.') Object.assign(config, overrides(config)) } else { debug('No environment overrides found, defaults will be used.') } module.exports = config
var fs = require('fs'); var execSync = require('child_process').execSync; var deployDir = __dirname + '/deploy'; // Helper to get rid of directories for us deleteFolderRecursive = function(path) { var files = []; if (fs.existsSync(path)) { files = fs.readdirSync(path); files.forEach(function(file,index){ var curPath = path + "/" + file; if (fs.lstatSync(curPath).isDirectory()) { deleteFolderRecursive(curPath); } else { fs.unlinkSync(curPath); } }); fs.rmdirSync(path); } }; // Ensure we start fresh for every deploy deleteFolderRecursive(deployDir); // Parse the current repositories origin URL var remoteUrl = execSync('git config --get remote.origin.url').toString().trim(); // Do a shallow clone of the repository's gh-pages branch into a "deploy" directory and remove everything. execSync('git clone --depth 1 --branch gh-pages --single-branch ' + remoteUrl + ' "' + deployDir + '"'); execSync('git -C "' + deployDir + '" rm -r "*"'); // Run the deploy task using Gulp to build the site into the deploy directory. execSync('node_modules/.bin/gulp deploy'); execSync('git -C "' + deployDir + '" add .'); // Get the current commit of the branch to use in our commit message var hash = execSync("git log --pretty=format:'%h' -n 1").toString().trim(); execSync('git -C "' + deployDir + '" commit -am "Deploying commit ' + hash + '."'); // Push the deploy directory execSync('git -C "' + deployDir + '" push');
//models/Points var mongoose = require('mongoose'); var Schema = mongoose.Schema; var PointsSchema = new Schema({ lineupID: String, leagueID: String, score: Number, referenceID: String, referenceType: String, referenceName: String, referenceUser: String, confirmationuserID: String, datecreated: { type: Date, default: Date.now() } }); module.exports = mongoose.model('Points', PointsSchema);
// All material copyright ESRI, All Rights Reserved, unless otherwise specified. // See https://js.arcgis.com/4.16/esri/copyright.txt for details. //>>built define("require exports ../../core/tsSupport/assignHelper ../../Color ../../request ../../core/ItemCache ../../core/promiseUtils ../../core/screenUtils".split(" "),function(l,d,w,m,n,p,q,e){function k(a){if(!a)return null;var b;switch(a.type){case "simple-fill":case "picture-fill":case "simple-marker":b=k(a.outline);break;case "simple-line":var c=e.pt2px(a.width);"none"!==a.style&&0!==c&&(b={color:a.color,style:r(a.style),width:c,cap:a.cap,join:"miter"===a.join?e.pt2px(a.miterLimit):a.join});break; default:b=null}return b}Object.defineProperty(d,"__esModule",{value:!0});var t=l.toUrl("../../symbols/patterns/"),u={left:"start",center:"middle",right:"end",justify:"start"},v={top:"text-before-edge",middle:"central",baseline:"alphabetic",bottom:"text-after-edge"},h=new p(1E3);d.getSVGAlign=function(a){return a=(a=a.horizontalAlignment)&&u[a.toLowerCase()]||"middle"};d.getSVGBaseline=function(a){return(a=a.verticalAlignment)&&v[a.toLowerCase()]||"alphabetic"};d.getSVGBaselineShift=function(a){return"bottom"=== a.verticalAlignment?"super":null};d.getFill=function(a){var b=a.style,c=null;if(a)switch(a.type){case "simple-marker":"cross"!==b&&"x"!==b&&(c=a.color);break;case "simple-fill":"solid"===b?c=a.color:"none"!==b&&(c={type:"pattern",x:0,y:0,src:t+b+".png",width:8,height:8});break;case "picture-fill":c={type:"pattern",src:a.url,width:e.pt2px(a.width)*a.xscale,height:e.pt2px(a.height)*a.yscale,x:e.pt2px(a.xoffset),y:e.pt2px(a.yoffset)};break;case "text":c=a.color}return c};d.getPatternUrlWithColor=function(a, b){var c=a+"-"+b;return void 0!==h.get(c)?q.resolve(h.get(c)):n(a,{responseType:"image"}).then(function(a){a=a.data;var d=a.naturalWidth,e=a.naturalHeight,f=document.createElement("canvas");f.width=d;f.height=e;var g=f.getContext("2d");g.fillStyle=b;g.fillRect(0,0,d,e);g.globalCompositeOperation="destination-in";g.drawImage(a,0,0);a=f.toDataURL();h.put(c,a);return a})};d.getStroke=k;var r=function(){var a={};return function(b){if(a[b])return a[b];var c=b.replace(/-/g,"");return a[b]=c}}();d.defaultThematicColor= new m([128,128,128])});
'use babel'; var _ = require('underscore'); var fs = require('fs'); var path = require('path'); var BufferedProcess = require("atom").BufferedProcess; var hiddenEditor; module.exports = { getFileEditor: function(path){ var targetEditor = _.find(atom.workspace.getTextEditors(), (editor) => { return editor.getPath() === path; }); // if targetFile not opened or tokenized yet, use new buffer if(!targetEditor || (targetEditor && !targetEditor.tokenizedBuffer.fullyTokenized)){ hiddenEditor = hiddenEditor || atom.workspace.buildTextEditor(); //https://discuss.atom.io/t/best-way-to-create-new-texteditor/18995/5 hiddenEditor.buffer.setPath(path); hiddenEditor.buffer.loadSync(path); targetEditor = hiddenEditor } return targetEditor; }, completionSortFun : function (a,b) { if(a.priority==0 ^ b.priority==0){ return b.priority - a.priority; } // if(a.priority == 'deprecated' && b.rightLabel !== 'deprecated'){ // return 1; // }else if(a.rightLabel !== 'deprecated' && b.rightLabel == 'deprecated'){ // return -1; // } aStr = a.text || a.displayText || a.snippet || ''; bStr = b.text || b.displayText || b.snippet || ''; return aStr.length - bStr.length; }, getTiProjectRootPath : function () { var activeEditor = atom.workspace.getActiveTextEditor(); if(activeEditor && atom.project.rootDirectories.length){ return atom.project.relativizePath(activeEditor.getPath())[0] || ''; } return ''; }, isTitaniumProject : function(){ if( this.isExistAsFile(path.join(this.getTiProjectRootPath(),'tiapp.xml')) ){ return true } }, sortCompletions : function (completes) { }, getAlloyRootPath : function () { let customPath = atom.config.get('titanium-alloy.alloyAppPath'); return path.join(this.getTiProjectRootPath(), customPath || 'app'); }, isAlloyProject : function () { return this.isExistAsDirectory(this.getAlloyRootPath()); }, isAlloy18Later : function () { return atom.config.get('titanium-alloy.isAlloy1_8later'); }, getI18nPath : function () { if(this.isAlloyProject() && this.isAlloy18Later() ){ return path.join(this.getAlloyRootPath(),'i18n'); }else{ return path.join(this.getTiProjectRootPath(),'i18n'); } }, isExistAsFile : function (path) { try { var stat = fs.statSync(path); return stat.isFile(); } catch(err) { return !(err && err.code === 'ENOENT'); } }, isExistAsDirectory : function (path) { try { var stat = fs.statSync(path); return stats.isDirectory(); } catch(err) { return !(err && err.code === 'ENOENT'); } }, getCustomPrefix : (function () { var regex = /^[ ]*$|[^\s\\\(\)"':,;<>~!@\$%\^&\*\|\+=\[\]\{\}`\?\…]+$/; return function (request) { var editor = request.editor; var bufferPosition = request.bufferPosition; // Get the text for the line up to the triggered buffer position var line = editor.getTextInRange([[bufferPosition.row, 0], bufferPosition]); // Match the regex to the line, and return the match var matchResult = line.match(regex) return matchResult?matchResult[0]:''; } })(), getLine : function(arg) { var bufferPosition, editor, line; editor = arg.editor, bufferPosition = arg.bufferPosition; return line = editor.getTextInRange([[bufferPosition.row, 0], bufferPosition]); }, toUnixPath : function(p) { //https://github.com/anodynos/upath var double; p = p.replace(/\\/g, '/'); double = /\/\//; while (p.match(double)) { p = p.replace(double, '/'); } return p; }, getAllKeys : function functionName(obj) { if(!_.isObject(obj)) return []; var result = []; _.each(obj, function (value,key) { result.push(key); _.each(module.exports.getAllKeys(value), function (value) { result.push(key+'.'+value) }); }); return result; } }
var loader = Components.classes["@mozilla.org/moz/jssubscript-loader;1"].getService(Components.interfaces.mozIJSSubScriptLoader); loader.loadSubScript("chrome://socialsidebar/content/socket.js"); function SslImapClient() { this.clearState(); } /** * @interface */ function ImapCommandHandler() {} /** * @param {Array.<String>} reply */ ImapCommandHandler.prototype.onUntagged = function(reply) {}; /** * @param {Array.<String>} reply */ ImapCommandHandler.prototype.onResponse = function(reply) {}; SslImapClient.prototype.clearState = function() { this.server = undefined; this.email = undefined; this.username = undefined; this.password = undefined; this.socket = undefined; this.on_login = undefined; this.on_bad_password = undefined; this.on_disconnect = undefined; this.commands = undefined; this.pending_commands = undefined; this.response_data = undefined; this.next_command_id = undefined; this.current_reply = undefined; this.data_bytes_needed = undefined; this.current_folder = undefined; this.idling = undefined; this.uid_next = undefined; this.fully_connected = undefined; this.logging = undefined; this.capabilities = undefined; }; SslImapClient.prototype.hasCapability = function(cap) { return this.capabilities[cap] == true; } SslImapClient.prototype.connect = function(server, email, password, on_login, on_bad_password, on_error, on_disconnect, logging) { if(this.socket) throw "already connected"; this.clearState(); this.server = server; this.username = email.split('@', 1)[0]; this.email = email; this.password = password; this.logging = logging; this.capabilities = {} this.socket = new Socket(); try { this.socket.open(server, 993, "ssl", bind(this.onConnect, this)); var client = this; window.setTimeout(function() { if(!client.fully_connected) { client.on_disconnect = undefined; client.disconnect(); on_error("Unable to contact server! Check you server settings."); } }, 15000); } catch(err) { on_error(err) } this.on_login = on_login; this.on_bad_password = on_bad_password; this.on_disconnect = on_disconnect; this.commands = []; this.next_command_id = 1; this.pending_commands = {}; this.response_data = ""; this.current_reply = [""]; this.data_bytes_needed = undefined; this.current_folder = undefined; this.idling = false; this.uid_next = {}; this.pending_commands["*"] = {"handler":bind(this.onAckConnect, this), "untagged":function(){}}; }; SslImapClient.prototype.onAckConnect = function(reply) { this.fully_connected = true; // alert("Initial Hello\n" + response + "\n" + extra); var client = this; var u = encode_utf8(this.username.replace("\\", "\\\\").replace("\"", "\\\"")); var p = encode_utf8(this.password); //this.sendCommand('LOGIN \"' + u + '\" \"' + p + "\"", bind(this.onLogin, this), function() {}); // var auth = btoa("\0" + u + "\0" + p); // this.sendCommand('AUTHENTICATE PLAIN',bind(this.onLogin, this), function() {}, true, // function() { // if(client.logging) // Cu.reportError("IMAP OUT @ " + new Date() + ":\n" + auth); // client.socket.write(auth + "\r\n"); // } // ); this.sendCommand('LOGIN \"' + u + '\" {' + p.length + '}',bind(this.onLogin, this), function() {}, true, function() { if(client.logging) Cu.reportError("IMAP OUT @ " + new Date() + ":\n" + p); client.socket.write(p + "\r\n"); } ); }; SslImapClient.prototype.onLogin = function(reply) { var reply = reply[0].split(" ", 1); var client = this; if(reply == "OK") { this.sendCommand("CAPABILITY", function() { client.on_login(); }, function(reply) { var parts = reply[0].split(" "); if(parts[0] == "CAPABILITY") { parts.shift(); for(var i = 0; i < parts.length; ++i) { client.capabilities[parts[i]] = true; } } } ); } else { this.on_disconnect = undefined; this.on_bad_password(); this.disconnect(); } }; /* * @constructor */ function ImapListHandler(since_uid, next_uid, on_success, on_error) { this.results = []; this.since_uid = since_uid; this.next_uid = next_uid; this.on_success = on_success; this.on_error = on_error; }; /** * @param {Array.<String>} reply */ ImapListHandler.prototype.onUntagged = function(reply) { if(reply[0].split(" ")[0] != "SEARCH") return; this.results = reply[0].split(" "); this.results.shift(); if(this.results[this.results.length - 1] == "") this.results.pop(); for(var i = 0; i < this.results.length; ++i) { this.results[i] = parseInt(this.results[i]); } }; /** * @param {Array.<String>} reply */ ImapListHandler.prototype.onResponse = function(reply) { if(reply[0].split(" ", 1) != "OK") { this.on_error(reply[0]); } else { if(!this.next_uid) { for(var i = 0; i < this.results.length; ++i) { if(!this.next_uid || this.results[i] > this.next_uid) this.next_uid = this.results[i] + 1; if(this.results[i] < this.since_uid) { this.results.splice(i, 1); } } } this.on_success(this.results, this.next_uid); } }; // var month_short_names = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"]; /** * @param {string} folder * @param {string} tag * @param {number} after_uid * @param {Date} since_date * @param {function(Array.<number>, number)} on_success * @param {function(string)} on_error */ SslImapClient.prototype.listMessages = function(folder, tag, since_uid, mrp, on_success, on_error) { if(tag == undefined) tag = "[Mr.Privacy]["; else tag = "[Mr.Privacy][" + tag + "]"; var client = this; var next_uid = undefined; //you have to issue a select before search or the IMAP server may return a cached set of results (atleast GMAIL does) this.sendCommand("SELECT \"" + folder + "\"", function(reply) { //alert("got select"); if(reply[0].split(" ", 1) != "OK") { on_error(reply[0]); } else { client.current_folder = folder; if(next_uid && since_uid && since_uid >= next_uid) { on_success([], next_uid); return; } var handler = new ImapListHandler(since_uid, next_uid, on_success, on_error); // if(since_date) { // since_date = " SENTSINCE " + since_date.getDate() + "-" + month_short_names[since_date.getMonth()] + "-" + since_date.getFullYear(); // } else { // since_date = ""; // } if(since_uid) { since_uid = " UID " + since_uid + ":*"; } else { since_uid = ""; } if(mrp) mrp = " SUBJECT \"" + tag + "\" HEADER \"X-MR-PRIVACY\" \"\""; else mrp = ""; client.sendCommand("UID SEARCH" + since_uid + " NOT DELETED" + mrp, bind(handler.onResponse, handler), bind(handler.onUntagged, handler), true); } }, function(reply) { if(reply[0].indexOf("UIDNEXT") != -1) { next_uid = parseInt(reply[0].split("UIDNEXT ", 2)[1].split("]")[0]); } }); }; /* * @constructor */ function ImapOpenOrCreateHandler(client, folder, on_success, on_error) { this.on_success = on_success; this.on_error = on_error; this.folder = folder; this.client = client; }; /** * @param {Array.<String>} reply */ ImapOpenOrCreateHandler.prototype.onUntagged = function(reply) { }; /** * @param {Array.<String>} reply */ ImapOpenOrCreateHandler.prototype.onCreateResponse = function(reply) { this.client.sendCommand("SELECT \"" + this.folder + "\"", bind(this.onSelectResponse, this), bind(this.onUntagged, this), true); }; /** * @param {Array.<String>} reply */ ImapOpenOrCreateHandler.prototype.onSelectResponse = function(reply) { if(reply[0].split(" ", 1) != "OK") { this.on_error(reply[0]); } else { this.client.current_folder = this.folder; this.on_success(); } }; SslImapClient.prototype.openOrCreateFolder = function(folder, on_success, on_error) { var handler = new ImapOpenOrCreateHandler(this, folder, on_success, on_error); this.sendCommand("CREATE " + folder, bind(handler.onCreateResponse, handler), bind(handler.onUntagged, handler), false); }; /* * @constructor */ function ImapCreateHandler(on_success, on_error) { this.on_success = on_success; this.on_error = on_error; }; /** * @param {Array.<String>} reply */ ImapCreateHandler.prototype.onUntagged = function(reply) { }; /** * @param {Array.<String>} reply */ ImapCreateHandler.prototype.onResponse = function(reply) { if(reply[0].split(" ", 1) != "OK") { this.on_error(reply[0]); } else { this.on_success(this.messages); } }; /** * @param {string} folder * @param {function()} on_success * @param {function(string)} on_error */ SslImapClient.prototype.createFolder = function(folder, on_success, on_error) { var handler = new ImapCreateHandler(on_success, on_error); this.sendCommand("CREATE " + folder, bind(handler.onResponse, handler), bind(handler.onUntagged, handler), false); } /* * @constructor */ function ImapCopyHandler(on_success, on_error) { this.on_success = on_success; this.on_error = on_error; }; /** * @param {Array.<String>} reply */ ImapCopyHandler.prototype.onUntagged = function(reply) { }; /** * @param {Array.<String>} reply */ ImapCopyHandler.prototype.onResponse = function(reply) { if(reply[0].split(" ", 1) != "OK") { this.on_error(reply[0]); } else { this.on_success(this.messages); } }; /** * @param {string} to * @param {string} from * @param {number} uid * @param {function()} on_success * @param {function(string)} on_error */ SslImapClient.prototype.copyMessage = function(to, from, uid, on_success, on_error) { if(typeof(uid) == "Array") uid = uid.join(","); var client = this; if(this.current_folder != from) { this.sendCommand("SELECT \"" + folder + "\"", function(reply) { //alert("got select"); if(reply[0].split(" ", 1) != "OK") { on_error(reply[0]); } else { client.current_folder = from; var handler = new ImapCopyHandler(on_success, on_error); client.sendCommand("UID COPY " + uid + " " + to, bind(handler.onResponse, handler), bind(handler.onUntagged, handler), true); } }, function() {}); } else { var handler = new ImapCopyHandler(on_success, on_error); client.sendCommand("UID COPY " + uid + " " + to, bind(handler.onResponse, handler), bind(handler.onUntagged, handler), false); } } /* * @constructor */ function ImapDeleteHandler(client, uid, on_success, on_error) { this.client = client; this.on_success = on_success; this.on_error = on_error; this.uid = uid; }; /** * @param {Array.<String>} reply */ ImapDeleteHandler.prototype.onUntagged = function(reply) { }; /** * @param {Array.<String>} reply */ ImapDeleteHandler.prototype.onResponse = function(reply) { if(reply[0].split(" ", 1) != "OK") { this.on_error(reply[0]); } else { //we don't need to wait for the expunge if(!this.client.hasCapability("UIDPLUS")) { this.client.sendCommand("EXPUNGE", function() {}, function() {}, true); } else { this.client.sendCommand("UID EXPUNGE " + this.uid, function() {}, function() {}, true); } this.on_success(this.messages); } }; /** * @param {string} to * @param {string} from * @param {number} uid * @param {function()} on_success * @param {function(string)} on_error */ SslImapClient.prototype.deleteMessage = function(folder, uid, on_success, on_error) { if(typeof(uid) == "Array") uid = uid.join(","); var client = this; if(this.current_folder != folder) { this.sendCommand("SELECT \"" + folder + "\"", function(reply) { //alert("got select"); if(reply[0].split(" ", 1) != "OK") { on_error(reply[0]); } else { client.current_folder = folder; var handler = new ImapDeleteHandler(client, uid, on_success, on_error); client.sendCommand("UID STORE " + uid + " +FLAGS (\\Deleted)", bind(handler.onResponse, handler), bind(handler.onUntagged, handler), true); } }, function() {}); } else { var handler = new ImapDeleteHandler(client, uid, on_success, on_error); client.sendCommand("UID STORE " + uid + " +FLAGS (\\Deleted)", bind(handler.onResponse, handler), bind(handler.onUntagged, handler), false); } } //TODO: is this according to the RFC function extractMailAddressRFC(raw) { var lt = raw.indexOf('<'); if(lt != -1) { var gt = raw.indexOf('>'); raw = raw.slice(lt + 1, gt); } return raw.trim(); } var message_tokenizer = /\(|\)|\\?[\w\d]+(?:\[[^\]]*\])?|\s+|(?:"(?:[^"\\]|\\.)*")|\{\d*\}/g; function tokenizeMessage(msg) { var match; var tokens = []; var levels = [tokens]; message_tokenizer.lastIndex = 0; do { // Cu.reportError(JSON.stringify(levels)); var last_index = message_tokenizer.lastIndex; match = message_tokenizer.exec(msg); //invalid message if(!match || last_index + match[0].length != message_tokenizer.lastIndex) { // Cu.reportError("skipped @\n" + msg.slice(last_index)); return undefined; } if(match[0] == "(") { levels.push([]); levels[levels.length - 2].push(levels[levels.length - 1]); } else if(match[0] == ")") { levels.pop(); if(levels.length == 0) { // Cu.reportError("too many )"); return undefined; } } else if(!(/^\s+$/.test(match[0]))) { levels[levels.length - 1].push(match[0]); } } while(message_tokenizer.lastIndex != msg.length); if(message_tokenizer.lastIndex != msg.length) { // Cu.reportError("missed end"); return undefined; } return tokens; } function mimeBodyStructure(parts) { var mime = []; if((typeof parts[0]) == "object") { for(var i = 0; i < parts.length; ++i) { if((typeof parts[i]) == "object") mime.push(mimeBodyStructure(parts[i])); else break; } return mime; } return (parts[0].slice(1, parts[0].length - 1) + "/" + parts[1].slice(1, parts[1].length - 1)).toLowerCase(); } function partsOfType(parts, type) { var jsons = []; for(var i = 0; i < parts.length; ++i) { if(parts[i] == type) { jsons.push("" + (i + 1)) continue; } if(typeof parts[i] != "object") continue; var p = partsOfType(parts[i], type); if(!p) continue; for(var j = 0; j < p.length; ++j) jsons.push("" + (i + 1) + "." + p[j]); } if(jsons.length == 0) return undefined; return jsons; } /* * @constructor */ function MrPrivacyMessage() { this.id = undefined; this.uid = undefined; this.tag = undefined; this.date = undefined; this.from = undefined; this.to = undefined; this.objs = undefined; this.structure = undefined; } /* * @constructor */ function ImapFetchMrpHandler(client, on_success, on_error) { this.structures = {}; this.messages = {}; this.finished_messages = []; this.finished_message_ids = []; this.client = client; this.on_success = on_success; this.on_error = on_error; }; var whitespace_start_regex = /^\s+/; /** * @param {Array.<String>} reply */ ImapFetchMrpHandler.prototype.onUntagged = function(reply) { if(reply.length < 2) { //this means a header was not returned return; } //TODO: other checks like split(" ")[1] == "FETCH"? //TODO: does imap always return them in our requested order? var msg = new MrPrivacyMessage(); msg.uid = parseInt(reply[0].split("UID ", 2)[1].split(" ", 1)[0]); var headers = reply[1].split("\r\n"); for(var i = 0; i < headers.length; ++i) { var header = headers[i]; while(i + 1 < headers.length && whitespace_start_regex.test(headers[i + 1])) { var whitespace = whitespace_start_regex.exec(headers[i + 1]); header += " " + headers[i + 1].slice(whitespace.length); ++i; } var colon = header.indexOf(":"); var key = header.slice(0, colon); key = key.toLowerCase(); // name will only be lower case var value = header.slice(colon + 2); //skip ": " switch(key) { case "message-id": msg.id = value; break; case "subject": var tag_part = /\[Mr\.Privacy\]\[[^\]]+\]/.exec(value); if(tag_part) { msg.tag = tag_part[0].slice(13); msg.tag = msg.tag.slice(0, msg.tag.length - 1); } else { Cu.reportError("Bad subject for Mr. P:\n" + value + "\n" + JSON.stringify(headers)); } break; case "date": msg.date = new Date(value); break; case "from": msg.from = extractMailAddressRFC(value); break; case "to": msg.to = value.split(","); for(var j = 0; j < msg.to.length; ++j) { msg.to[j] = extractMailAddressRFC(msg.to[j]); } break; } } if(!msg.uid || !msg.tag || !msg.date || !msg.from || !msg.to) { return; } var parts = tokenizeMessage(reply[0]); if(!parts) { Cu.reportError("failed to parse " + msg.uid + "\n" + reply[0]); return; } parts = parts[2]; for(var i = 0; i < parts.length - 1; ++i) { if(parts[i] == "BODYSTRUCTURE") { msg.structure = mimeBodyStructure(parts[i + 1]); var s = JSON.stringify(msg.structure); if(!(s in this.structures)) { this.structures[s] = []; } this.structures[s].push(msg.uid); this.messages[msg.uid] = msg; return; } } }; ImapFetchMrpHandler.prototype.onUntaggedBody = function(reply) { var uid = parseInt(reply[0].split("UID ", 2)[1].split(" ", 1)[0]); var msg = this.messages[uid]; if(msg == undefined) { Cu.reportError("unknown uid returned " + uid); return; } if(reply.length < 2) { Cu.reportError("missing body for uid " + uid); //this means a body was not returned delete this.messages[uid]; return; } try { msg.objs = []; for(var i = 1; i < reply.length; ++i) { msg.objs.push(objify(decode_utf8(atob(reply[i].replace(/[\r\n]/g, ""))))); } this.finished_messages.push(msg); this.finished_message_ids.push(msg.uid); } catch (err) { delete this.messages[uid]; } } /** * @param {Array.<String>} reply */ ImapFetchMrpHandler.prototype.onResponse = function(reply) { if(reply[0].split(" ", 1) != "OK") { this.on_error(reply[0]); } else { for(var s in this.structures) { // Cu.reportError("" + this.structures[s].length + " messages of type\n" + s); var example_msg_uid = this.structures[s][0]; var st = this.messages[example_msg_uid].structure; var uid = "" + this.structures[s].join(","); var part = partsOfType(st, "application/json"); if(!part) continue; this.client.sendCommand("UID FETCH " + uid + " (BODY.PEEK[" + part.join("] BODY.PEEK[") + "])", bind(this.onResponse, this), bind(this.onUntaggedBody, this), true); delete this.structures[s]; return; } this.on_success(this.finished_messages, this.finished_message_ids); } }; /** * @param {string} folder * @param {number} uid * @param {function(Array.<MrPrivacyMessage>)} on_success * msgid, tag, date, from, to, obj * @param {function(string)} on_error */ SslImapClient.prototype.getMrpMessage = function(folder, uid, on_success, on_error) { if(typeof(uid) == "Array") uid = uid.join(","); var client = this; //TODO: can we assume that a mime forwarding mailing list will always make our message MIME part one. //This code assumes the JSON is either part 2 or 1.2 and relies on the server to return an inline nil for the missing part if(this.current_folder != folder) { this.sendCommand("SELECT \"" + folder + "\"", function(reply) { //alert("got select"); if(reply[0].split(" ", 1) != "OK") { on_error(reply[0]); } else { client.current_folder = folder; var handler = new ImapFetchMrpHandler(client, on_success, on_error); client.sendCommand("UID FETCH " + uid + " (BODY.PEEK[HEADER.FIELDS (MESSAGE-ID IN-REPLY-TO DATE FROM TO SUBJECT)] BODYSTRUCTURE)", bind(handler.onResponse, handler), bind(handler.onUntagged, handler), true); } }, function() {}); } else { var handler = new ImapFetchMrpHandler(client, on_success, on_error); client.sendCommand("UID FETCH " + uid + " (BODY.PEEK[HEADER.FIELDS (MESSAGE-ID IN-REPLY-TO DATE FROM TO SUBJECT)] BODYSTRUCTURE)", bind(handler.onResponse, handler), bind(handler.onUntagged, handler), false); } }; /* * @constructor */ function PlainMessage() { this.id = undefined; this.uid = undefined; this.date = undefined; this.from = undefined; this.to = undefined; this.subject = undefined; this.body = undefined; this.structure = undefined; } /* * @constructor */ function ImapFetchPlainHandler(client, on_success, on_error) { this.structures = {}; this.messages = {}; this.finished_messages = []; this.finished_message_ids = []; this.client = client; this.on_success = on_success; this.on_error = on_error; }; var whitespace_start_regex = /^\s+/; /** * @param {Array.<String>} reply */ ImapFetchPlainHandler.prototype.onUntagged = function(reply) { if(reply.length < 2) { //this means a header was not returned return; } //TODO: other checks like split(" ")[1] == "FETCH"? //TODO: does imap always return them in our requested order? var msg = new PlainMessage(); msg.uid = parseInt(reply[0].split("UID ", 2)[1].split(" ", 1)[0]); var headers = reply[1].split("\r\n"); for(var i = 0; i < headers.length; ++i) { var header = headers[i]; while(i + 1 < headers.length && whitespace_start_regex.test(headers[i + 1])) { var whitespace = whitespace_start_regex.exec(headers[i + 1]); header += " " + headers[i + 1].slice(whitespace.length); ++i; } var colon = header.indexOf(":"); var key = header.slice(0, colon); key = key.toLowerCase(); // name will only be lower case var value = header.slice(colon + 2); //skip ": " switch(key) { case "message-id": msg.id = value; break; case "subject": msg.subject = value; break; case "date": msg.date = new Date(value); break; case "from": msg.from = extractMailAddressRFC(value); break; case "to": msg.to = value.split(","); for(var j = 0; j < msg.to.length; ++j) { msg.to[j] = extractMailAddressRFC(msg.to[j]); } break; } } if(!msg.uid || !msg.date || !msg.from || !msg.to) { return; } var parts = tokenizeMessage(reply[0]); if(!parts) { Cu.reportError("failed to parse " + msg.uid + "\n" + reply[0]); return; } parts = parts[2]; for(var i = 0; i < parts.length - 1; ++i) { if(parts[i] == "BODYSTRUCTURE") { msg.structure = mimeBodyStructure(parts[i + 1]); var s = JSON.stringify(msg.structure); if(!(s in this.structures)) { this.structures[s] = []; } this.structures[s].push(msg.uid); this.messages[msg.uid] = msg; return; } } }; ImapFetchPlainHandler.prototype.onUntaggedBody = function(reply) { var uid = parseInt(reply[0].split("UID ", 2)[1].split(" ", 1)[0]); var msg = this.messages[uid]; if(msg == undefined) { Cu.reportError("unknown uid returned " + uid); return; } if(reply.length < 2) { Cu.reportError("missing body for uid " + uid); //this means a body was not returned delete this.messages[uid]; return; } try { msg.body = []; for(var i = 1; i < reply.length; ++i) { msg.body.push(decode_utf8(reply[i])); } this.finished_messages.push(msg); this.finished_message_ids.push(msg.uid); } catch (err) { delete this.messages[uid]; } } /** * @param {Array.<String>} reply */ ImapFetchPlainHandler.prototype.onResponse = function(reply) { if(reply[0].split(" ", 1) != "OK") { this.on_error(reply[0]); } else { for(var s in this.structures) { // Cu.reportError("" + this.structures[s].length + " messages of type\n" + s); var example_msg_uid = this.structures[s][0]; var st = this.messages[example_msg_uid].structure; var uid = "" + this.structures[s].join(","); var part = partsOfType(st, "text/plain"); if(!part) continue; this.client.sendCommand("UID FETCH " + uid + " (BODY.PEEK[" + part.join("] BODY.PEEK[") + "])", bind(this.onResponse, this), bind(this.onUntaggedBody, this), true); delete this.structures[s]; return; } this.on_success(this.finished_messages, this.finished_message_ids); } }; /** * @param {string} folder * @param {number} uid * @param {function(Array.<PlainMessage>)} on_success * msgid, tag, date, from, to, obj * @param {function(string)} on_error */ SslImapClient.prototype.getPlainMessage = function(folder, uid, on_success, on_error) { if(typeof(uid) == "Array") uid = uid.join(","); var client = this; //TODO: can we assume that a mime forwarding mailing list will always make our message MIME part one. //This code assumes the JSON is either part 2 or 1.2 and relies on the server to return an inline nil for the missing part if(this.current_folder != folder) { this.sendCommand("SELECT \"" + folder + "\"", function(reply) { //alert("got select"); if(reply[0].split(" ", 1) != "OK") { on_error(reply[0]); } else { client.current_folder = folder; var handler = new ImapFetchPlainHandler(client, on_success, on_error); client.sendCommand("UID FETCH " + uid + " (BODY.PEEK[HEADER.FIELDS (MESSAGE-ID IN-REPLY-TO DATE FROM TO SUBJECT)] BODYSTRUCTURE)", bind(handler.onResponse, handler), bind(handler.onUntagged, handler), true); } }, function() {}); } else { var handler = new ImapFetchPlainHandler(client, on_success, on_error); client.sendCommand("UID FETCH " + uid + " (BODY.PEEK[HEADER.FIELDS (MESSAGE-ID IN-REPLY-TO DATE FROM TO SUBJECT)] BODYSTRUCTURE)", bind(handler.onResponse, handler), bind(handler.onUntagged, handler), false); } }; /** * @param {string} folder */ SslImapClient.prototype.waitMessages = function(folder, expected_next_uid, on_success, on_error) { var client = this; var cancel_idle = false; var exists = undefined; this.sendCommand("SELECT \"" + folder + "\"", function(reply) { //alert("got select"); if(reply[0].split(" ", 1) != "OK") { on_error(reply[0]); } else { client.current_folder = folder; if(cancel_idle) { on_success(); return; } client.sendCommand("IDLE", function(reply) { client.idling = false; if(reply[0].split(" ", 1) != "OK") { on_error(reply[0]); } else { on_success(); } }, function(reply) { if(reply[0].indexOf("EXISTS") != -1) { var new_exists = parseInt(reply[0].split(" ", 1)[0]); if(exists != new_exists) { // alert("exists changed, idle satisfied"); cancel_idle = true; } if(client.idling) { this.idling = false; if(this.logging) Cu.reportError("IMAP OUT @ " + new Date() + ":\nDONE\nReason: cancel after continuation response"); client.socket.write("DONE\r\n"); } } }, true, function() { if(!cancel_idle) client.idling = true; else { this.idling = false; if(this.logging) Cu.reportError("IMAP OUT @ " + new Date() + ":\nDONE\nReason: cancel idle on continuation response"); client.socket.write("DONE\r\n"); } } ); } }, function(reply) { if(reply[0].indexOf("UIDNEXT") != -1) { var next_uid = parseInt(reply[0].split("UIDNEXT ", 2)[1].split("]")[0]); if(expected_next_uid == undefined) { expected_next_uid = next_uid; alert("assuming wait for any new message could lose data" + expected_next_uid); } else { if(next_uid > expected_next_uid) cancel_idle = true; } } if(reply[0].indexOf("EXISTS") != -1) { exists = parseInt(reply[0].split(" ", 1)[0]); } } ); }; SslImapClient.prototype.sendCommand = function(command, on_response, on_untagged, continuation, on_continue) { if(on_untagged == undefined) on_untagged = function(reply) { alert("untagged\n" + reply); }; if(on_continue == undefined) on_continue = function(reply) { alert("continue\n" + reply); }; if(!continuation) this.commands.push({"command":command, "handler":on_response, "untagged": on_untagged, "continue": on_continue}); else this.commands.unshift({"command":command, "handler":on_response, "untagged": on_untagged, "continue": on_continue}); this.internalNextCommand(); }; SslImapClient.prototype.internalNextCommand = function() { if(!this.idling) { for(var id in this.pending_commands) { //bail out if there are pending commands return; } } if(this.commands.length == 0) return; if(this.idling && this.commands[0]["command"] != "DONE") { //cancel the idle this.idling = false; if(this.logging) Cu.reportError("IMAP OUT @ " + new Date() + ":\nDONE\nReason: cancel because new command was issued: " + JSON.stringify(this.commands[0])); this.socket.write("DONE\r\n"); return; } var cmd = this.commands.shift(); var id = "Ax" + this.next_command_id++; cmd["id"] = id; var data_bit = id + " " + cmd["command"] + "\r\n"; if(this.logging) Cu.reportError("IMAP OUT @ " + new Date() + ":\n" + data_bit); this.socket.write(data_bit); this.pending_commands[id] = cmd; }; SslImapClient.prototype.disconnect = function() { if(this.socket == undefined) return; this.socket.close(); this.socket = undefined; }; SslImapClient.prototype.onConnect = function() { // alert('connected'); var client = this; var socket_cbs = { "streamStarted": function (socketContext){ //do nothing, this just means data came in... we'll //get it via the receiveData callback }, "streamStopped": function (socketContext, status){ client.onDisconnect(); }, "receiveData": function (data){ client.onData(data); } }; this.socket.async(socket_cbs); this.internalNextCommand(); }; SslImapClient.prototype.onDisconnect = function() { if(this.socket) { this.socket.close(); this.socket = undefined; } if(this.on_disconnect) this.on_disconnect(); }; SslImapClient.prototype.onData = function(data) { if(this.logging) Cu.reportError("IMAP IN @ " + new Date() + ":\n" + data); this.response_data += data; for(;;) { if(this.data_bytes_needed) { if(this.response_data.length < this.data_bytes_needed) return; this.current_reply.push(this.response_data.slice(0, this.data_bytes_needed)); this.response_data = this.response_data.slice(this.data_bytes_needed); this.data_bytes_needed = undefined; //ok, now we wait for the actual command to complete continue; } var ofs = this.response_data.indexOf('\n'); //not complete if(ofs == -1) return; var partial = this.response_data.slice(0, ofs - 1); var literal_end = partial.lastIndexOf('}'); if(literal_end == ofs - 2) { var literal_start = partial.lastIndexOf('{'); this.data_bytes_needed = parseInt(partial.slice(literal_start + 1, literal_end)); this.current_reply[0] += partial.slice(0, literal_start) + "{}"; this.response_data = this.response_data.slice(ofs + 1); //ok now we need the literal continue; } else { this.current_reply[0] += partial; this.response_data = this.response_data.slice(ofs + 1); } var cmd = this.current_reply[0].split(" ", 1)[0]; this.current_reply[0] = this.current_reply[0].slice(cmd.length + 1); if(!(cmd in this.pending_commands)) { if(cmd == "*") { for(var i in this.pending_commands) { this.pending_commands[i]["untagged"](this.current_reply); } } else if(cmd == "+") { for(var i in this.pending_commands) { this.pending_commands[i]["continue"](this.current_reply); } } else { alert("unknown cmd " + cmd + " " + this.current_reply); } } else { this.pending_commands[cmd]["handler"](this.current_reply); delete this.pending_commands[cmd]; } this.current_reply = [""]; this.internalNextCommand(); } }; function SslSmtpClient() { this.clearState(); }; SslSmtpClient.prototype.clearState = function() { this.server = undefined; this.username = undefined; this.email = undefined; this.password = undefined; this.socket = undefined; this.on_login = undefined; this.on_bad_password = undefined; this.on_disconnect = undefined; this.commands = undefined; this.pending_command = undefined; this.response_data = undefined; this.current_reply = undefined; this.fully_connected = undefined; this.logging = undefined; }; SslSmtpClient.prototype.connect = function(server, email, password, on_login, on_bad_password, on_error, on_disconnect, logging) { if(this.socket) throw "already connected"; this.clearState(); this.server = server; this.username = email.split('@', 1)[0]; this.email = email; this.password = password; this.logging = logging; this.socket = new Socket(); try { this.socket.open(server, 465, "ssl", bind(this.onConnect, this)); var client = this; window.setTimeout(function() { if(!client.fully_connected) { client.on_disconnect = undefined; client.disconnect(); on_error("Unable to contact server! Check you server settings."); } }, 15000); } catch(err) { on_error(err); return; } this.on_login = on_login; this.on_bad_password = on_bad_password; this.on_disconnect = on_disconnect; this.commands = [] this.response_data = ""; this.current_reply = []; this.pending_command = bind(this.onAckConnect, this); }; SslSmtpClient.prototype.onAckConnect = function(reply) { this.fully_connected = true; this.sendCommand('EHLO somehost', bind(this.onShake, this)); }; SslSmtpClient.prototype.onShake = function(reply) { // alert("on shake"); var u = encode_utf8(this.username); var p = encode_utf8(this.password); var auth = btoa("\0" + u + "\0" + p); this.sendCommand("AUTH PLAIN " + auth, bind(this.onLogin, this)); }; SslSmtpClient.prototype.sendMessage = function(tag, to, subject, related, html, txt, obj, on_success, on_error) { if(!this.fully_connected) { on_error("SMTP is not fully connected"); return; } if(to.length < 1) throw "at least one destination email is required"; var data = ""; data += "X-Mr-Privacy: " + tag + "\r\n"; if(related) data += "In-Reply-To: " + related + "\r\n"; data += "MIME-Version: 1.0\r\n"; data += "To:"; for(var i = 0; i < to.length - 1; ++i) { data += " " + encode_utf8(to[i]) + ","; } data += " " + to[to.length - 1] + "\r\n"; data += "From: " + encode_utf8(this.email) + "\r\n"; data += "Subject: " + encode_utf8(subject) + " [Mr.Privacy][" + tag + "]\r\n"; var divider = "------------xxxxxxxxxxxxxxxxxxxxxxxx".replace(/x/g, function(c) { return (Math.random()*16|0).toString(10); }); data += "Content-Type: multipart/alternative; boundary=\"" + divider + "\"\r\n"; data += "\r\n"; data += "This is a multi-part message in MIME format.\r\n"; data += "--" + divider + "\r\n"; /////////// data += "Content-Type: text/plain; charset=\"utf-8\"\r\n" data += "Content-Transfer-Encoding: 8bit\r\n"; data += "\r\n"; data += encode_utf8(txt.replace(/(^|[^\r])(?=\n)/g, function(c) { return c + "\r"; })); data += "\r\n"; /////////// data += "--" + divider + "\r\n"; /////////// data += "Content-Type: application/json; charset=\"us-ascii\"\r\n" data += "Content-Transfer-Encoding: base64\r\n"; data += "\r\n"; var encoded = btoa(encode_utf8(jsonify(obj))); for(var i = 0; i < encoded.length; i += 74) { data += encoded.slice(i, i + 74) + "\r\n"; } /////////// data += "--" + divider + "\r\n"; /////////// data += "Content-Type: text/html; charset=\"utf-8\"\r\n" data += "Content-Transfer-Encoding: 8bit\r\n"; data += "\r\n"; data += encode_utf8(html.replace(/(^|[^\r])(?=\n)/g, function(c) { return c + "\r"; })); data += "\r\n"; /////////// data += "--" + divider + "--\r\n"; data += "."; var send_cmd = {"to":to.slice(0), "data":data, "success":on_success, "error":on_error}; var client = this; client.sendCommand("MAIL FROM: <" + this.email + "> BODY=8BITMIME", function(reply) { var code = reply[0].split(" ", 1); if(code != "250" && code != "354") { send_cmd["error"](reply.join("\n")); return; } if("to" in send_cmd && send_cmd["to"].length > 0) { //send recipients 1 by 1 client.sendCommand("RCPT TO: <" + send_cmd.to.pop() + ">", arguments.callee, true); } else if("to" in send_cmd) { //then send the data message delete send_cmd["to"]; client.sendCommand("DATA", arguments.callee, true); } else if("data" in send_cmd){ //then send actual data var data = send_cmd["data"]; delete send_cmd["data"]; client.sendCommand(data, arguments.callee, true) } else { send_cmd["success"](); } }); }; SslSmtpClient.prototype.onLogin = function(reply) { var code = reply[0].split(" ", 1); if(code == "235") { this.on_login(); } else { this.on_disconnect = undefined; this.on_bad_password(); this.disconnect(); } }; SslSmtpClient.prototype.sendCommand = function(command, on_response, continuation) { if(!continuation) this.commands.push({"command":command, "handler":on_response}); else this.commands.unshift({"command":command, "handler":on_response}); this.internalNextCommand(); }; SslSmtpClient.prototype.internalNextCommand = function() { if(this.pending_command) return; if(this.commands.length == 0) return; var cmd = this.commands.shift(); var data_bit = cmd["command"] + "\r\n"; if(this.logging) Cu.reportError("SMTP OUT @ " + new Date() + ":\n" + data_bit); this.socket.write(data_bit); this.pending_command = cmd["handler"]; }; SslSmtpClient.prototype.disconnect = function() { if(this.socket == undefined) return; this.socket.close(); this.socket = undefined; }; SslSmtpClient.prototype.onConnect = function() { // alert('connected'); var client = this; var socket_cbs = { "streamStarted": function (socketContext){ //do nothing, this just means data came in... we'll //get it via the receiveData callback }, "streamStopped": function (socketContext, status){ client.onDisconnect(); }, "receiveData": function (data){ client.onData(data); } }; this.socket.async(socket_cbs); this.internalNextCommand(); }; SslSmtpClient.prototype.onDisconnect = function() { if(this.socket) { this.socket.close(); this.socket = undefined; } if(this.on_disconnect) this.on_disconnect(); }; SslSmtpClient.prototype.onData = function(data) { if(this.logging) Cu.reportError("SMTP IN @ " + new Date() + ":\n" + data); this.response_data += data; for(;;) { var ofs = this.response_data.indexOf('\n'); //not complete if(ofs == -1) { // alert("bailing\n" + this.response_data); return; } //TODO: handle gibbrish respone (not a 3 dig number with a space or - after it) var reply = this.response_data.slice(0, ofs - 1); this.response_data = this.response_data.slice(ofs + 1); this.current_reply.push(reply); // alert("adding\n" + reply); if(reply[3] == "-") continue; // alert("issuing\n" + this.current_reply); if(this.pending_command) this.pending_command(this.current_reply); else { var code = this.current_reply[0].split(" ", 1)[0]; if(code == "451" || code == "421") { this.disconnect(); //SMTP timeout, just pass on the disconnect message } else { alert("unexpected reply: " + this.current_reply); } } this.current_reply = [] this.pending_command = undefined; this.internalNextCommand(); } }; /** * @param {Array.<string>} emails */ function elimateDuplicateAddreses(emails, skip) { var mushed = {}; for(var i = 0; i < emails.length; ++i) { mushed[emails[i]] = true; } if(skip) { for(var i = 0; i < skip.length; ++i) { delete mushed[skip[i]]; } } var remaining = []; for(var i in mushed) { i = i.trim(); if(i.length == 0) continue; remaining.push(i); } return remaining; } function MrPrivacyObject() { this.tag = undefined; this.date = undefined; this.from = undefined; this.to = undefined; this.obj = undefined; } function MrPrivacyClient() { this.inbox = undefined; this.mrprivacy = undefined; this.sender = undefined; this.options = undefined; this.idle = undefined; this.phases_left = undefined; this.connect_errors = undefined; this.db = undefined; this.next_inbox_uid = undefined; this.next_mrprivacy_uid = undefined; this.mrprivacy_folder_id = undefined; this.inbox_folder_id = undefined; this.offline_toggles = []; this.waiters = {}; } MrPrivacyClient.prototype.onConnectFailed = function(on_error) { this.disconnect(); on_error("Check your account and server settings. Also make sure you are connected.\n\n" + this.connect_errors.join("\n")); } MrPrivacyClient.prototype.onConnectPhaseSuccess = function(phase, on_success, on_error, on_offline_toggle) { this.phases_left--; if(this.phases_left > 0) return; if(this.connect_errors.length > 0) { this.onConnectFailed(on_error); return; } this.idle = this.inbox.hasCapability("IDLE"); var mrp = this; mrp.mrprivacy.openOrCreateFolder("MrPrivacy", function() { Cu.reportError("mrp client mrprivacy all connected"); try { mrp.openDatabase(); mrp.startInboxProcessing(); mrp.startObjectImport(); } catch(err) { mrp.disconnect(); on_error("Opening database failed: " + err) return; } mrp.offline_toggles.push(on_offline_toggle); on_success(); }, function(e) { mrp.disconnect(); on_error(e); } ); } MrPrivacyClient.prototype.onConnectPhaseError = function(phase, on_error, error) { var err_msg = "" + error; if(err_msg.indexOf('OFFLINE') != -1) { err_msg = "Offline, cannot connect"; } this.connect_errors.push(phase + " says " + err_msg + "."); this.phases_left--; if(this.phases_left > 0) return; this.onConnectFailed(on_error); } MrPrivacyClient.prototype.isOnline = function() { return this.inbox && this.inbox.socket && this.mrprivacy && this.mrprivacy.socket && this.inbox.fully_connected && this.mrprivacy.fully_connected; } MrPrivacyClient.prototype.openDatabase = function() { var file = Components.classes["@mozilla.org/file/directory_service;1"] .getService(Components.interfaces.nsIProperties) .get("ProfD", Components.interfaces.nsIFile); var db_name = this.options['email'].replace(/[^\w\d\.]/g, function(c) { return "" + c.charCodeAt(0); }); file.append(db_name + ".sqlite"); var storageService = Components.classes["@mozilla.org/storage/service;1"] .getService(Components.interfaces.mozIStorageService); this.db = storageService.openDatabase(file); // Will also create the file if it does not exist var version = 1; var db_version = 0; //if the table doesn't exist then we should update try { var st_version = this.db.createStatement("SELECT version FROM versions"); while(st_version.step()) { db_version = st_version.row.version; } st_version.finalize(); } catch(e) {} if(this.options["clear_cache"] || db_version != version) { this.db.beginTransaction(); var st_table = this.db.createStatement("SELECT name FROM sqlite_master WHERE type='table'"); var tables = []; while(st_table.step()) { tables.push(st_table.row.name); } for(var i = 0; i < tables.length; ++i) { try { this.db.executeSimpleSQL("DROP TABLE " + tables[i]); } catch(e) {} } this.db.commitTransaction(); this.db.executeSimpleSQL("VACUUM"); } this.db.beginTransaction(); try { if(!this.db.tableExists("versions")) { var fields = [ "version INTEGER UNIQUE" ]; this.db.createTable("versions", fields.join(", ")); this.db.executeSimpleSQL("INSERT INTO versions (version) VALUES (" + version + ") "); } if(!this.db.tableExists("objects")) { var fields = [ "object_id INTEGER PRIMARY KEY", "message_id INTEGER", //tells what message the object came from, for finding attachments, etc ]; this.db.createTable("objects", fields.join(", ")); this.db.executeSimpleSQL("CREATE UNIQUE INDEX objects_by_object_id ON objects (object_id)"); this.db.executeSimpleSQL("CREATE INDEX objects_by_message_id ON objects (message_id)"); } if(!this.db.tableExists("people")) { var fields = [ "person_id INTEGER PRIMARY KEY", "name TEXT", //the name of the person "email TEXT UNIQUE", //the email of the person ]; this.db.createTable("people", fields.join(", ")); this.db.executeSimpleSQL("CREATE UNIQUE INDEX people_by_person_id ON people (person_id)"); } if(!this.db.tableExists("groups")) { var fields = [ "group_id INTEGER PRIMARY KEY", "name TEXT", //the name for a group if this is a user defined group "flattened TEXT", //flattened array of people ids e.g. 1:2:5:10 in sorted order ]; this.db.createTable("groups", fields.join(", ")); this.db.executeSimpleSQL("CREATE UNIQUE INDEX groups_by_group_id ON groups (group_id)"); this.db.executeSimpleSQL("CREATE INDEX groups_by_flattened ON groups (flattened)"); } if(!this.db.tableExists("members")) { var fields = [ "group_id INTEGER", //a group that contains "person_id INTEGER", //this member ]; this.db.createTable("members", fields.join(", ")); this.db.executeSimpleSQL("CREATE INDEX members_by_group_id ON members (group_id)"); } this.db.executeSimpleSQL("CREATE TRIGGER IF NOT EXISTS group_add_member AFTER INSERT ON members BEGIN UPDATE groups SET flattened = (SELECT GROUP_CONCAT(pid, ':') FROM(SELECT members.person_id AS pid FROM members WHERE members.group_id = new.group_id ORDER BY members.person_id)) WHERE new.group_id = groups.group_id; END;"); this.db.executeSimpleSQL("CREATE TRIGGER IF NOT EXISTS group_delete_member AFTER DELETE ON members BEGIN UPDATE groups SET flattened = (SELECT GROUP_CONCAT(pid, ':') FROM(SELECT members.person_id AS pid FROM members WHERE members.group_id = old.group_id ORDER BY members.person_id)) WHERE old.group_id = groups.group_id; END;"); if(!this.db.tableExists("folders")) { var fields = [ "folder_id INTEGER PRIMARY KEY", "name TEXT UNIQUE", //name of an imap folder (INBOX, MrPrivacy, Sent) "next_uid INTEGER", //next id to consider when scanning ]; this.db.createTable("folders", fields.join(", ")); this.db.executeSimpleSQL("CREATE UNIQUE INDEX folders_by_folder_id ON folders (folder_id)"); this.db.executeSimpleSQL("CREATE UNIQUE INDEX folders_by_name ON folders (name)"); } this.db.executeSimpleSQL("INSERT OR IGNORE INTO folders (name, next_uid) VALUES ('INBOX', 1)"); this.db.executeSimpleSQL("INSERT OR IGNORE INTO folders (name, next_uid) VALUES ('MrPrivacy', 1)"); var qfs = this.db.createStatement("SELECT folder_id FROM folders WHERE name = :folder"); qfs.params.folder = "INBOX"; while(qfs.step()) { this.inbox_folder_id = qfs.row.folder_id; } qfs.params.folder = "MrPrivacy"; while(qfs.executeStep()) { this.mrprivacy_folder_id = qfs.row.folder_id; } qfs.finalize(); if(!this.db.tableExists("messages")) { var fields = [ "message_id INTEGER PRIMARY KEY", "folder_id INTEGER", "message_unique TEXT", "date INTEGER", "imap_uid INTEGER", "from_id INTEGER", "to_id INTEGER", "type TEXT", //mr privacy tag ]; this.db.createTable("messages", fields.join(", ")); this.db.executeSimpleSQL("CREATE UNIQUE INDEX messages_by_message_id ON messages (folder_id, message_id)"); this.db.executeSimpleSQL("CREATE UNIQUE INDEX messages_by_type_and_imap_uid ON messages (folder_id, type, imap_uid)"); this.db.executeSimpleSQL("CREATE UNIQUE INDEX messages_by_unique ON messages (folder_id, message_unique)"); this.db.executeSimpleSQL("CREATE INDEX messages_by_type_and_date ON messages (folder_id, type, date)"); } if(!this.db.tableExists("properties")) { var fields = [ "object_id INTEGER", "property TEXT", "value", ]; this.db.createTable("properties", fields.join(", ")); this.db.executeSimpleSQL("CREATE INDEX properties_by_object_id ON properties (object_id)"); this.db.executeSimpleSQL("CREATE INDEX properties_by_object_id_and_property ON properties (object_id, property)"); this.db.executeSimpleSQL("CREATE INDEX properties_by_object_id_and_property_and_value ON properties (object_id, property, value)"); } if(!this.db.tableExists("attachments")) { var fields = [ "message_id INTEGER", "part TEXT", "content_type TEXT", "cache_path TEXT", ]; this.db.createTable("attachments", fields.join(", ")); this.db.executeSimpleSQL("CREATE INDEX attachments_by_message_id ON attachments (message_id)"); } this.db.commitTransaction(); } catch(e) { this.db.rollbackTransaction(); throw e; } this.st_folder_has_uid = this.db.createStatement("SELECT 1 FROM messages WHERE messages.folder_id = :folder AND messages.imap_uid = :uid"); this.st_get_person_by_email = this.db.createStatement("SELECT person_id FROM people WHERE email = :email"); this.st_insert_person = this.db.createStatement("INSERT INTO people (email) VALUES (:email);"); this.st_get_group_by_flattened = this.db.createStatement("SELECT group_id FROM groups WHERE flattened = :flattened"); this.st_create_generic_group = this.db.createStatement("INSERT INTO groups (flattened) VALUES ('');"); this.st_insert_group_member = this.db.createStatement("INSERT INTO members (group_id, person_id) VALUES (:group, :person)"); this.st_insert_message = this.db.createStatement("INSERT INTO messages (folder_id, message_unique, date, imap_uid, from_id, to_id, type) " + "VALUES (" + this.mrprivacy_folder_id + ", :unique, :date, :uid, :from, :to, :type);"); this.st_insert_object = this.db.createStatement("INSERT INTO objects (message_id) VALUES (:message);"); this.st_insert_property = this.db.createStatement("INSERT INTO properties (object_id, property, value) VALUES (:object, :property, :value)"); this.st_get_object = this.db.createStatement("SELECT properties.property, properties.value FROM objects LEFT OUTER JOIN properties ON properties.object_id = objects.object_id WHERE objects.object_id = :object"); this.st_get_object_meta = this.db.createStatement("SELECT messages.message_id, messages.date, messages.type, people.email FROM objects JOIN messages ON messages.message_id = objects.message_id, people ON messages.from_id = people.person_id WHERE objects.object_id = :object"); this.st_get_object_to = this.db.createStatement("SELECT people.email FROM objects JOIN messages ON messages.message_id = objects.message_id JOIN members ON messages.to_id = members.group_id JOIN people ON people.person_id = members.person_id WHERE objects.object_id = :object"); //TODO: needs to pick mrp folder... this.st_list_objects = this.db.createStatement("SELECT objects.object_id FROM messages JOIN objects ON messages.message_id = objects.message_id WHERE messages.type = :type AND messages.folder_id = :folder ORDER BY messages.date"); this.st_list_objects_starting_at = this.db.createStatement("SELECT objects.object_id FROM messages JOIN objects ON messages.message_id = objects.message_id WHERE messages.type = :type AND objects.object_id >= :start AND messages.folder_id = :folder ORDER BY messages.date"); this.st_set_next_uid = this.db.createStatement("UPDATE folders SET next_uid = :next WHERE name = :folder"); this.st_get_next_uid = this.db.createStatement("SELECT next_uid FROM folders WHERE name = :folder"); } MrPrivacyClient.prototype.startInboxProcessing = function() { this.st_get_next_uid.params.folder = "INBOX"; while(this.st_get_next_uid.step()) { this.next_inbox_uid = this.st_get_next_uid.row.next_uid; } // alert("next inbox: " + this.next_inbox_uid); this.onNewInbox(); } MrPrivacyClient.prototype.onNewInbox = function() { var mrp = this; mrp.inbox.listMessages("INBOX", undefined, this.next_inbox_uid, true, function(ids, next_uid) { if(ids.length == 0) { mrp.next_inbox_uid = next_uid; if(!mrp.idle) { window.setTimeout(bind(mrp.onNewInbox, mrp), 30000); return; } else { mrp.inbox.waitMessages("INBOX", mrp.next_inbox_uid, bind(mrp.onNewInbox, mrp), function(error) { Cu.reportError("failed to wait for inbox messages, reconnect needed..." + error); } ) return; } } mrp.next_inbox_uid = next_uid; mrp.inbox.copyMessage("MrPrivacy", "INBOX", ids, function() { mrp.inbox.deleteMessage("INBOX", ids, function() { mrp.st_set_next_uid.params.folder = "INBOX"; mrp.st_set_next_uid.params.next = next_uid; while(mrp.st_set_next_uid.step()) {}; //if there is no idle, we won't wake up so do it this way if(!mrp.idle) mrp.onNewMrPrivacy(); }, function(error) { //hmm...this is BAD Cu.reportError("failed to delete messages, mailbox will be getting wastefully full" + error); } ); //TODO: if no idle then do the alternative if(!mrp.idle) { window.setTimeout(bind(mrp.onNewInbox, mrp), 30000); } else { mrp.inbox.waitMessages("INBOX", mrp.next_inbox_uid, bind(mrp.onNewInbox, mrp), function(error) { Cu.reportError("failed to wait for message messages, reconnect needed..." + error); } ); } }, function(e) { Cu.reportError("failed to copy messages, items will be temporarily lost" + error); } ); }, function(e) { alert("Listing inbox failed!\n" + e); } ); } MrPrivacyClient.prototype.startObjectImport = function() { this.st_get_next_uid.params.folder = "MrPrivacy"; while(this.st_get_next_uid.step()) { this.next_mrprivacy_uid = this.st_get_next_uid.row.next_uid; } // alert("next mrp: " + this.next_mrprivacy_uid); this.onNewMrPrivacy(); } MrPrivacyClient.prototype.getOrInsertPerson = function(email) { var person_id = undefined; this.st_get_person_by_email.params.email = email; while(this.st_get_person_by_email.step()) { person_id = this.st_get_person_by_email.row.person_id; } if(person_id != undefined) return person_id; this.st_insert_person.params.email = email; while(this.st_insert_person.step()) {}; return this.db.lastInsertRowID; } MrPrivacyClient.prototype.getOrInsertGroup = function(emails) { var pid_map = {}; for(var i = 0; i < emails.length; ++i) { pid_map[this.getOrInsertPerson(emails[i])] = emails[i]; } var pids = []; for(var i in pid_map) { pids.push(i); } pids.sort(); var group_id = undefined; this.st_get_group_by_flattened.params.flattened = pids.join(":"); while(this.st_get_group_by_flattened.step()) { group_id = this.st_get_group_by_flattened.row.group_id; } if(group_id != undefined) return group_id; while(this.st_create_generic_group.step()) {}; group_id = this.db.lastInsertRowID; for(var i = 0; i < pids.length; ++i) { this.st_insert_group_member.params.group = group_id; this.st_insert_group_member.params.person = pids[i]; while(this.st_insert_group_member.step()) {}; } return group_id; } MrPrivacyClient.prototype.onNewMrPrivacy = function() { var mrp = this; if(mrp.mrprivacy_timeout) { window.clearTimeout(mrp.mrprivacy_timeout); mrp.mrprivacy_timeout = undefined; } mrp.mrprivacy.listMessages("MrPrivacy", undefined, this.next_mrprivacy_uid, true, function(ids, next_uid) { if(ids.length == 0) { mrp.next_mrprivacy_uid = next_uid; if(!mrp.idle) { mrp.mrprivacy_timeout = window.setTimeout(bind(mrp.onNewMrPrivacy, mrp), 30000); return; } else { mrp.mrprivacy.waitMessages("MrPrivacy", mrp.next_mrprivacy_uid, bind(mrp.onNewMrPrivacy, mrp), function(error) { Cu.reportError("failed to wait for mrp messages, reconnect needed..." + error); } ) return; } } mrp.next_mrprivacy_uid = next_uid; //TODO: if there are a bunch of bad messages at the head of the inbox, then they get redownloaded and scanned each //start until a valid one comes in mrp.mrprivacy.getMrpMessage("MrPrivacy", ids, function(hits) { if(hits.length == 0) { Cu.reportError("no new messages parsed successfully..."); return; } var tags = {}; //need to sort by uid to ensure that the "first message wins" dedupe strategy works hits.sort(function(a, b) { return a.uid < b.uid; }); mrp.db.beginTransaction(); try { for(var i = 0; i < hits.length; ++i) { var msg = hits[i]; // Cu.reportError(JSON.stringify(msg)); mrp.st_insert_message.params.unique = msg.id; mrp.st_insert_message.params.date = msg.date.getTime(); mrp.st_insert_message.params.uid = msg.uid; mrp.st_insert_message.params.from = mrp.getOrInsertPerson(msg.from); mrp.st_insert_message.params.to = mrp.getOrInsertGroup(msg.to); mrp.st_insert_message.params.type = msg.tag; try { while(mrp.st_insert_message.step()) {}; } catch(e) { if(mrp.db.lastError == 19) { mrp.st_insert_message.reset(); mrp.st_folder_has_uid.params.folder = mrp.mrprivacy_folder_id; mrp.st_folder_has_uid.params.uid = msg.uid; var duplicate_by_uid = false; while(mrp.st_folder_has_uid.step()) { duplicate_by_uid = true; //if it is duplicated by UID then we still want to wake up because //some other mrp client inserted it into the db (another ffx window) tags[msg.tag] = true; } if(!duplicate_by_uid) { mrp.mrprivacy.deleteMessage("MrPrivacy", msg.uid, function() {}, function() {}); } continue; } else { throw e; } } tags[msg.tag] = true; var message_id = mrp.db.lastInsertRowID; mrp.st_insert_object.params.message = message_id; for(var j = 0; j < msg.objs.length; ++j) { while(mrp.st_insert_object.step()) {}; var object_id = mrp.db.lastInsertRowID; var obj = msg.objs[j]; for(var prop in obj) { var v = obj[prop]; if(v instanceof Array && v.unordered) { for(var k = 0; k < v.length; ++k) { mrp.st_insert_property.params.object = object_id; mrp.st_insert_property.params.property = prop; mrp.st_insert_property.params.value = JSON.stringify(v[k]); while(mrp.st_insert_property.step()) {}; } } else { mrp.st_insert_property.params.object = object_id; mrp.st_insert_property.params.property = prop; mrp.st_insert_property.params.value = JSON.stringify(v); while(mrp.st_insert_property.step()) {}; } } } } mrp.db.commitTransaction(); } catch(e) { alert("failed inserting objects:\n" + e + "\n" + mrp.db.lastErrorString); mrp.db.rollbackTransaction(); } var cbs = []; for(var t in tags) { if(t in mrp.waiters) { cbs.push.apply(cbs, mrp.waiters[t]); delete mrp.waiters[t]; } } mrp.st_set_next_uid.params.folder = "MrPrivacy"; mrp.st_set_next_uid.params.next = next_uid; while(mrp.st_set_next_uid.step()) {}; for(var i = 0; i < cbs.length; ++i) { cbs[i](); } //TODO: if no idle then do the alternative if(!mrp.idle) { mrp.mrprivacy_timeout = window.setTimeout(bind(mrp.onNewMrPrivacy, mrp), 30000); } else { mrp.mrprivacy.waitMessages("MrPrivacy", mrp.next_mrprivacy_uid, bind(mrp.onNewMrPrivacy, mrp), function(error) { Cu.reportError("failed to wait for mrp messages, reconnect needed..." + error); } ); } }, function(msg) { on_error("Fetching messages failed", msg); } ); }, function(e) { alert("Listing mrprivacy failed!\n" + e); } ); } MrPrivacyClient.prototype.handlePartialReconnect = function() { if(this.isOnline()) { for(var i in this.offline_toggles) { this.offline_toggles[i](); } } } MrPrivacyClient.prototype.onInboxDisconnect = function() { Cu.reportError("mrp client inbox disconnect"); this.inbox = undefined; for(var i in this.offline_toggles) { this.offline_toggles[i](); } if(!this.reconnect_inbox_timeout) this.reconnect_inbox_timeout = window.setTimeout(bind(this.tryInboxAgain, this), 30000); } MrPrivacyClient.prototype.tryInboxAgain = function() { if(this.inbox) { alert("inbox already connected"); return; } var mrp = this; mrp.reconnect_inbox_timeout = undefined; this.inbox = new SslImapClient(); this.inbox.connect(this.options["imap_server"], this.options['email'], this.options['password'], function() { Cu.reportError("mrp client inbox reconnected"); mrp.handlePartialReconnect(); mrp.startInboxProcessing(); }, function() { mrp.inbox = undefined; alert("Email password rejected, Mr Privacy will be disabled!"); }, function(e) { mrp.inbox = undefined; mrp.reconnect_inbox_timeout = window.setTimeout(bind(mrp.tryInboxAgain, mrp), 30000); }, bind(this.onInboxDisconnect, this), this.options['logging'] ); } MrPrivacyClient.prototype.onMrPrivacyDisconnect = function() { Cu.reportError("mrp client mrprivacy disconnect"); this.mrprivacy = undefined; for(var i in this.offline_toggles) { this.offline_toggles[i](); } if(!this.reconnect_mrprivacy_timeout) this.reconnect_mrprivacy_timeout = window.setTimeout(bind(this.tryMrPrivacyAgain, this), 30000); } MrPrivacyClient.prototype.tryMrPrivacyAgain = function() { if(this.mrprivacy) { alert("mrp already connected"); return; } var mrp = this; mrp.reconnect_mrprivacy_timeout = undefined; this.mrprivacy = new SslImapClient(); this.mrprivacy.connect(this.options["imap_server"], this.options['email'], this.options['password'], function() { Cu.reportError("mrp client mrp reconnected"); mrp.handlePartialReconnect(); mrp.startObjectImport(); }, function() { mrp.mrprivacy = undefined; alert("Email password rejected, Mr Privacy will be disabled!"); }, function(e) { mrp.mrprivacy = undefined; mrp.reconnect_mrprivacy_timeout = window.setTimeout(bind(mrp.tryMrPrivacyAgain, mrp), 30000); }, bind(this.onMrPrivacyDisconnect, this), this.options['logging'] ); } MrPrivacyClient.prototype.onSenderDisconnect = function() { Cu.reportError("mrp client sender disconnect"); this.sender = undefined; } MrPrivacyClient.prototype.connect = function(options, on_success, on_error, on_offline_toggle) { if(this.connected) on_error("You are already connected"); if(options['email'] == undefined || options['email'].length == 0) return on_error("Missing email!"); if(options['email'].indexOf('@') == -1) return on_error("Email address invalid."); if(options['password'] == undefined || options['password'].length == 0) return on_error("Missing password!"); if(options['imap_server'] == undefined || options['imap_server'].length == 0) return on_error("Missing IMAP server!"); if(options['smtp_server'] == undefined || options['smtp_server'].length == 0) return on_error("Missing SMTP server!"); if(options['email'].indexOf('@') == -1) return on_error("Email address invalid."); var validated = options['validated']; this.options = deep_copy(options); this.connect_errors = []; if(!validated) { this.phases_left = 2; this.inbox = new SslImapClient(); this.inbox.connect(options["imap_server"], options['email'], options['password'], bind(this.onConnectPhaseSuccess, this, "IMAP inbox", on_success, on_error, on_offline_toggle), bind(this.onConnectPhaseError, this, "IMAP inbox", on_error, "bad username or password"), bind(this.onConnectPhaseError, this, "IMAP inbox", on_error), bind(this.onInboxDisconnect, this), options['logging'] ); this.mrprivacy = new SslImapClient(); this.mrprivacy.connect(options["imap_server"], options['email'], options['password'], bind(this.onConnectPhaseSuccess, this, "IMAP aux", on_success, on_error, on_offline_toggle), bind(this.onConnectPhaseError, this, "IMAP aux", on_error, "bad username or password"), bind(this.onConnectPhaseError, this, "IMAP aux", on_error), bind(this.onMrPrivacyDisconnect, this), options['logging'] ); } this.phases_left++; this.sender = new SslSmtpClient(); this.sender.connect(options["smtp_server"], options['email'], options['password'], bind(this.onConnectPhaseSuccess, this, "SMTP sender", on_success, on_error, on_offline_toggle), bind(this.onConnectPhaseError, this, "SMTP sender", on_error, "bad username or password"), bind(this.onConnectPhaseError, this, "SMTP sender", on_error), bind(this.onSenderDisconnect, this), options['logging'] ); } MrPrivacyClient.prototype.disconnect = function() { if(this.inbox) { this.inbox.disconnect(); this.inbox = undefined; } if(this.mrprivacy) { this.mrprivacy.disconnect(); this.mrprivacy = undefined; } if(this.sender) { this.sender.disconnect() this.sender = undefined; } if(this.db) { try { this.db.close(); } catch (e) {} this.db = undefined; } } MrPrivacyClient.prototype.getData = function(id) { this.st_get_object.params.object = id; var obj = undefined; while(this.st_get_object.step()) { if(!obj) { obj = {}; } var val; try { val = JSON.parse(this.st_get_object.row.value); } catch(e) { Cu.reportError("failed to parse property data: \n" + this.st_get_object.row.value); this.st_get_object.reset(); return undefined; } if(this.st_get_object.row.property in obj) { if(obj[this.st_get_object.row.property].unordered) { obj[this.st_get_object.row.property].push(val); } else { var s = []; s.push(obj[this.st_get_object.row.property]); s.push(val); s.unordered = true; obj[this.st_get_object.row.property] = s; } } else { obj[this.st_get_object.row.property] = val; } } return obj; } MrPrivacyClient.prototype.get = function(id) { var obj = new MrPrivacyObject(); obj.obj = this.getData(id); if(obj.obj == undefined) return undefined; this.st_get_object_meta.params.object = id; while(this.st_get_object_meta.step()) { obj.tag = this.st_get_object_meta.row.type; obj.date = new Date(this.st_get_object_meta.row.date); obj.from = this.st_get_object_meta.row.email; } this.st_get_object_to.params.object = id; obj.to = []; while(this.st_get_object_to.step()) { obj.to.push(this.st_get_object_to.row.email); } return obj; } MrPrivacyClient.prototype.list = function(start_id, tag) { var st; if(start_id != undefined) { st = this.st_list_objects_starting_at; st.params.start = start_id; } else { st = this.st_list_objects; } st.params.folder = this.mrprivacy_folder_id; st.params.type = tag; var objects = []; while(st.step()) { objects.push(st.row.object_id); } return objects; } MrPrivacyClient.prototype.wait = function(start_id, tag, on_success) { //we do the list inside because if there was any async handling in between the callers //last call to list, we want to catch it... not really necessary right now though if(this.list(start_id, tag).length > 0) { on_success(); return; } if(!(tag in this.waiters)) this.waiters[tag] = []; this.waiters[tag].push(on_success); } MrPrivacyClient.prototype.send = function(tag, to, subject, related, html, txt, obj, on_success, on_error) { if(this.sender) { this.sender.sendMessage(tag, to, subject, related, html, txt, obj, on_success, on_error); return; } var mrp = this; mrp.sender = new SslSmtpClient(); mrp.sender.connect(mrp.options["smtp_server"], mrp.options['email'], mrp.options['password'], function() { Cu.reportError("sender connected"); mrp.sender.sendMessage(tag, to, subject, related, html, txt, obj, on_success, on_error); }, function() { mrp.sender = undefined; on_error("SMTP says bad username/password"); }, function(err) { mrp.sender = undefined; var err_msg = "" + err; if(err_msg.indexOf('OFFLINE') != -1) { on_error("Offline, cannot connect to " + mrp.options["smtp_server"], err_msg); return; } on_error("Failed to connect to " + mrp.options["smtp_server"], err_msg); }, bind(this.onSenderDisconnect, this), mrp.options['logging'] ); }
$(window).load(function() { game.init(); }); var game = { // Start preloading assets init: function(){ loader.init(); mouse.init(); $('.gamelayer').hide(); $('#gamestartscreen').show(); game.backgroundCanvas = document.getElementById('gamebackgroundcanvas'); game.backgroundContext = game.backgroundCanvas.getContext('2d'); game.foregroundCanvas = document.getElementById('gameforegroundcanvas'); game.foregroundContext = game.foregroundCanvas.getContext('2d'); game.canvasWidth = game.backgroundCanvas.width; game.canvasHeight = game.backgroundCanvas.height; }, start:function(){ $('.gamelayer').hide(); $('#gameinterfacescreen').show(); game.running = true; game.refreshBackground = true; game.drawingLoop(); }, // The map is broken into square tiles of this size (20 pixels x 20 pixels) gridSize:20, // Store whether or not the background moved and needs to be redrawn refreshBackground:true, // A control loop that runs at a fixed period of time animationTimeout:100, // 100 milliseconds or 10 times a second offsetX:0, // X & Y panning offsets for the map offsetY:0, panningThreshold:60, // Distance from edge of canvas at which panning starts panningSpeed:10, // Pixels to pan every drawing loop handlePanning:function(){ // do not pan if mouse leaves the canvas if (!mouse.insideCanvas){ return; } if(mouse.x<=game.panningThreshold){ if (game.offsetX>=game.panningSpeed){ game.refreshBackground = true; game.offsetX -= game.panningSpeed; } } else if (mouse.x>= game.canvasWidth - game.panningThreshold){ if (game.offsetX + game.canvasWidth + game.panningSpeed <= game.currentMapImage.width){ game.refreshBackground = true; game.offsetX += game.panningSpeed; } } if(mouse.y<=game.panningThreshold){ if (game.offsetY>=game.panningSpeed){ game.refreshBackground = true; game.offsetY -= game.panningSpeed; } } else if (mouse.y>= game.canvasHeight - game.panningThreshold){ if (game.offsetY + game.canvasHeight + game.panningSpeed <= game.currentMapImage.height){ game.refreshBackground = true; game.offsetY += game.panningSpeed; } } if (game.refreshBackground){ // Update mouse game coordinates based on game offsets mouse.calculateGameCoordinates(); } }, animationLoop:function(){ // Process orders for any item that handles it for (var i = game.items.length - 1; i >= 0; i--){ if(game.items[i].processOrders){ game.items[i].processOrders(); } }; // Animate each of the elements within the game for (var i = game.items.length - 1; i >= 0; i--){ game.items[i].animate(); }; // Sort game items into a sortedItems array based on their x,y coordinates game.sortedItems = $.extend([],game.items); game.sortedItems.sort(function(a,b){ return b.y-a.y + ((b.y==a.y)?(a.x-b.x):0); }); game.lastAnimationTime = (new Date()).getTime(); }, drawingLoop:function(){ // Handle Panning the Map game.handlePanning(); // Check the time since the game was animated and calculate a linear interpolation factor (-1 to 0) // since drawing will happen more often than animation game.lastDrawTime = (new Date()).getTime(); if (game.lastAnimationTime){ game.drawingInterpolationFactor = (game.lastDrawTime-game.lastAnimationTime)/game.animationTimeout - 1; if (game.drawingInterpolationFactor>0){ // No point interpolating beyond the next animation loop... game.drawingInterpolationFactor = 0; } } else { game.drawingInterpolationFactor = -1; } // Since drawing the background map is a fairly large operation, // we only redraw the background if it changes (due to panning) if (game.refreshBackground){ game.backgroundContext.drawImage(game.currentMapImage,game.offsetX,game.offsetY,game.canvasWidth,game.canvasHeight, 0,0,game.canvasWidth,game.canvasHeight); game.refreshBackground = false; } // fast way to clear the foreground canvas game.foregroundCanvas.width = game.foregroundCanvas.width; // Start drawing the foreground elements for (var i = game.sortedItems.length - 1; i >= 0; i--){ game.sortedItems[i].draw(); }; // Draw the mouse mouse.draw() // Call the drawing loop for the next frame using request animation frame if (game.running){ requestAnimationFrame(game.drawingLoop); } }, resetArrays:function(){ game.counter = 0; game.items = []; game.sortedItems = []; game.buildings = []; game.vehicles = []; game.aircraft = []; game.terrain = []; game.triggeredEvents = []; game.selectedItems = []; game.sortedItems = []; }, add:function(itemDetails) { // Set a unique id for the item if (!itemDetails.uid){ itemDetails.uid = game.counter++; } var item = window[itemDetails.type].add(itemDetails); // Add the item to the items array game.items.push(item); // Add the item to the type specific array game[item.type].push(item); if(item.type == "buildings" || item.type == "terrain"){ game.currentMapPassableGrid = undefined; } return item; }, remove:function(item){ // Unselect item if it is selected item.selected = false; for (var i = game.selectedItems.length - 1; i >= 0; i--){ if(game.selectedItems[i].uid == item.uid){ game.selectedItems.splice(i,1); break; } }; // Remove item from the items array for (var i = game.items.length - 1; i >= 0; i--){ if(game.items[i].uid == item.uid){ game.items.splice(i,1); break; } }; // Remove items from the type specific array for (var i = game[item.type].length - 1; i >= 0; i--){ if(game[item.type][i].uid == item.uid){ game[item.type].splice(i,1); break; } }; if(item.type == "buildings" || item.type == "terrain"){ game.currentMapPassableGrid = undefined; } }, /* Selection Related Code */ selectionBorderColor:"rgba(255,255,0,0.5)", selectionFillColor:"rgba(255,215,0,0.2)", healthBarBorderColor:"rgba(0,0,0,0.8)", healthBarHealthyFillColor:"rgba(0,255,0,0.5)", healthBarDamagedFillColor:"rgba(255,0,0,0.5)", lifeBarHeight:5, clearSelection:function(){ while(game.selectedItems.length>0){ game.selectedItems.pop().selected = false; } }, selectItem:function(item,shiftPressed){ // Pressing shift and clicking on a selected item will deselect it if (shiftPressed && item.selected){ // deselect item item.selected = false; for (var i = game.selectedItems.length - 1; i >= 0; i--){ if(game.selectedItems[i].uid == item.uid){ game.selectedItems.splice(i,1); break; } }; return; } if (item.selectable && !item.selected){ item.selected = true; game.selectedItems.push(item); } }, // Send command to either single player or multi player object sendCommand:function(uids,details){ switch (game.type){ case "singleplayer": singleplayer.sendCommand(uids,details); break; case "multiplayer": multiplayer.sendCommand(uids,details); break; } }, getItemByUid:function(uid){ for (var i = game.items.length - 1; i >= 0; i--){ if(game.items[i].uid == uid){ return game.items[i]; } }; }, // Receive command from single player or multi player object and send it to units processCommand:function(uids,details){ // In case the target "to" object is in terms of uid, fetch the target object if (details.toUid){ details.to = game.getItemByUid(details.toUid); if(!details.to || details.to.lifeCode=="dead"){ // To object no longer exists. Invalid command return; } } for (var i in uids){ var uid = uids[i]; var item = game.getItemByUid(uid); //if uid is a valid item, set the order for the item if(item){ item.orders = $.extend([],details); } } }, //Movement related properties speedAdjustmentFactor:1/64, turnSpeedAdjustmentFactor:1/8, rebuildPassableGrid:function(){ game.currentMapPassableGrid = $.extend([],game.currentMapTerrainGrid); for (var i = game.items.length - 1; i >= 0; i--){ var item = game.items[i]; if(item.type == "buildings" || item.type == "terrain"){ for (var y = item.passableGrid.length - 1; y >= 0; y--){ for (var x = item.passableGrid[y].length - 1; x >= 0; x--){ if(item.passableGrid[y][x]){ game.currentMapPassableGrid[item.y+y][item.x+x] = 1; } }; }; } }; }, }
var url = require('url'); var util = require('util'); var path = require('path'); var webdriver = require('selenium-webdriver'); var clientSideScripts = require('./clientsidescripts.js'); var ProtractorBy = require('./locators.js').ProtractorBy; var DEFER_LABEL = 'NG_DEFER_BOOTSTRAP!'; var WEB_ELEMENT_FUNCTIONS = [ 'click', 'sendKeys', 'getTagName', 'getCssValue', 'getAttribute', 'getText', 'getSize', 'getLocation', 'isEnabled', 'isSelected', 'submit', 'clear', 'isDisplayed', 'getOuterHtml', 'getInnerHtml']; /** * Mix in other webdriver functionality to be accessible via protractor. */ for (var foo in webdriver) { exports[foo] = webdriver[foo]; } /** * @type {ProtractorBy} */ exports.By = new ProtractorBy(); /** * Mix a function from one object onto another. The function will still be * called in the context of the original object. * * @private * @param {Object} to * @param {Object} from * @param {string} fnName * @param {function=} setupFn */ var mixin = function(to, from, fnName, setupFn) { to[fnName] = function() { if (setupFn) { setupFn(); } return from[fnName].apply(from, arguments); }; }; /** * Build the helper 'element' function for a given instance of Protractor. * * @private * @param {Protractor} ptor * @param {=Array.<webdriver.Locator>} opt_usingChain * @return {function(webdriver.Locator): ElementFinder} */ var buildElementHelper = function(ptor, opt_usingChain) { var usingChain = opt_usingChain || []; var using = function() { var base = ptor; for (var i = 0; i < usingChain.length; ++i) { base = base.findElement(usingChain[i]); } return base; }; /** * The element function returns an Element Finder. Element Finders do * not actually attempt to find the element until a method is called on them, * which means they can be set up in helper files before the page is * available. * * Example: * var nameInput = element(by.model('name')); * browser.get('myurl'); * nameInput.sendKeys('Jane Doe'); * * @param {webdriver.Locator} locator * @return {ElementFinder} */ var element = function(locator) { var elementFinder = {}; var webElementFns = WEB_ELEMENT_FUNCTIONS.concat( ['findElements', 'isElementPresent', 'evaluate', '$$']); webElementFns.forEach(function(fnName) { elementFinder[fnName] = function() { var args = arguments; return using().findElement(locator).then(function(element) { return element[fnName].apply(element, args); }, function(error) { throw error; }); }; }); // This is a special case since it doesn't return a promise, instead it // returns a WebElement. elementFinder.findElement = function(subLocator) { return using().findElement(locator).findElement(subLocator); }; /** * Return the actual WebElement. * * @return {webdriver.WebElement} */ elementFinder.find = function() { return using().findElement(locator); }; /** * @return {boolean} whether the element is present on the page. */ elementFinder.isPresent = function() { return using().isElementPresent(locator); }; /** * Calls to element may be chained to find elements within a parent. * Example: * var name = element(by.id('container')).element(by.model('name')); * browser.get('myurl'); * name.sendKeys('John Smith'); * * @param {Protractor} ptor * @param {=Array.<webdriver.Locator>} opt_usingChain * @return {function(webdriver.Locator): ElementFinder} */ elementFinder.element = buildElementHelper(ptor, usingChain.concat(locator)); /** * Shortcut for chaining css element finders. * Example: * var name = element(by.id('container')).$('input.myclass'); * browser.get('myurl'); * name.sendKeys('John Smith'); * * @param {string} cssSelector * @return {ElementFinder} */ elementFinder.$ = function(cssSelector) { return buildElementHelper(ptor, usingChain.concat(locator))( webdriver.By.css(cssSelector)); }; return elementFinder; }; /** * element.all is used for operations on an array of elements (as opposed * to a single element). * * Example: * var lis = element.all(by.css('li')); * browser.get('myurl'); * expect(lis.count()).toEqual(4); * * @param {webdriver.Locator} locator * @return {ElementArrayFinder} */ element.all = function(locator) { var elementArrayFinder = {}; /** * @return {number} the number of elements matching the locator. */ elementArrayFinder.count = function() { return using().findElements(locator).then(function(arr) { return arr.length; }); }; /** * @param {number} index * @return {webdriver.WebElement} the element at the given index */ elementArrayFinder.get = function(index) { var id = using().findElements(locator).then(function(arr) { return arr[index]; }); return ptor.wrapWebElement(new webdriver.WebElement(ptor.driver, id)); }; /** * @return {webdriver.WebElement} the first matching element */ elementArrayFinder.first = function() { var id = using().findElements(locator).then(function(arr) { if (!arr.length) { throw new Error('No element found using locator: ' + locator.message); } return arr[0]; }); return ptor.wrapWebElement(new webdriver.WebElement(ptor.driver, id)); }; /** * @return {webdriver.WebElement} the last matching element */ elementArrayFinder.last = function() { var id = using().findElements(locator).then(function(arr) { return arr[arr.length - 1]; }); return ptor.wrapWebElement(new webdriver.WebElement(ptor.driver, id)); }; /** * @type {webdriver.promise.Promise} a promise which will resolve to * an array of WebElements matching the locator. */ elementArrayFinder.then = function(fn) { return using().findElements(locator).then(fn); }; /** * Calls the input function on each WebElement found by the locator. * * @param {function(webdriver.WebElement)} */ elementArrayFinder.each = function(fn) { using().findElements(locator).then(function(arr) { arr.forEach(function(webElem) { fn(webElem); }); }); }; /** * Apply a map function to each element found using the locator. The * callback receives the web element as the first argument and the index as * a second arg. * * Usage: * <ul class="menu"> * <li class="one">1</li> * <li class="two">2</li> * </ul> * * var items = element.all(by.css('.menu li')).map(function(elm, index) { * return { * index: index, * text: elm.getText(), * class: elm.getAttribute('class') * }; * }); * expect(items).toEqual([ * {index: 0, text: '1', class: 'one'}, * {index: 0, text: '1', class: 'one'}, * ]); * * @param {function(webdriver.WebElement, number)} mapFn Map function that * will be applied to each element. * @return {!webdriver.promise.Promise} A promise that resolves to an array * of values returned by the map function. */ elementArrayFinder.map = function(mapFn) { return using().findElements(locator).then(function(arr) { var list = []; arr.forEach(function(webElem, index) { var mapResult = mapFn(webElem, index); // All nested arrays and objects will also be fully resolved. webdriver.promise.fullyResolved(mapResult).then(function(resolved) { list.push(resolved); }); }); return list; }); }; return elementArrayFinder; }; return element; }; /** * Build the helper '$' function for a given instance of Protractor. * * @private * @param {Protractor} ptor * @return {function(string): ElementFinder} */ var buildCssHelper = function(ptor) { return function(cssSelector) { return buildElementHelper(ptor)(webdriver.By.css(cssSelector)); }; }; /** * Build the helper '$$' function for a given instance of Protractor. * * @private * @param {Protractor} ptor * @return {function(string): ElementArrayFinder} */ var buildMultiCssHelper = function(ptor) { return function(cssSelector) { return buildElementHelper(ptor).all(webdriver.By.css(cssSelector)); }; }; /** * @param {webdriver.WebDriver} webdriver * @param {string=} opt_baseUrl A base URL to run get requests against. * @param {string=body} opt_rootElement Selector element that has an ng-app in * scope. * @constructor */ var Protractor = function(webdriver, opt_baseUrl, opt_rootElement) { // These functions should delegate to the webdriver instance, but should // wait for Angular to sync up before performing the action. This does not // include functions which are overridden by protractor below. var methodsToSync = ['getCurrentUrl', 'getPageSource', 'getTitle']; // Mix all other driver functionality into Protractor. for (var method in webdriver) { if(!this[method] && typeof webdriver[method] == 'function') { if (methodsToSync.indexOf(method) !== -1) { mixin(this, webdriver, method, this.waitForAngular.bind(this)); } else { mixin(this, webdriver, method); } } } /** * The wrapped webdriver instance. Use this to interact with pages that do * not contain Angular (such as a log-in screen). * * @type {webdriver.WebDriver} */ this.driver = webdriver; /** * Helper function for finding elements. * * @type {function(webdriver.Locator): ElementFinder} */ this.element = buildElementHelper(this); /** * Helper function for finding elements by css. * * @type {function(string): ElementFinder} */ this.$ = buildCssHelper(this); /** * Helper function for finding arrays of elements by css. * * @type {function(string): ElementArrayFinder} */ this.$$ = buildMultiCssHelper(this); /** * All get methods will be resolved against this base URL. Relative URLs are = * resolved the way anchor tags resolve. * * @type {string} */ this.baseUrl = opt_baseUrl || ''; /** * The css selector for an element on which to find Angular. This is usually * 'body' but if your ng-app is on a subsection of the page it may be * a subelement. * * @type {string} */ this.rootEl = opt_rootElement || 'body'; /** * If true, Protractor will not attempt to synchronize with the page before * performing actions. This can be harmful because Protractor will not wait * until $timeouts and $http calls have been processed, which can cause * tests to become flaky. This should be used only when necessary, such as * when a page continuously polls an API using $timeout. * * @type {boolean} */ this.ignoreSynchronization = false; /** * An object that holds custom test parameters. * * @type {Object} */ this.params = {}; this.moduleNames_ = []; this.moduleScripts_ = []; }; /** * Instruct webdriver to wait until Angular has finished rendering and has * no outstanding $http calls before continuing. * * @return {!webdriver.promise.Promise} A promise that will resolve to the * scripts return value. */ Protractor.prototype.waitForAngular = function() { if (this.ignoreSynchronization) { return webdriver.promise.fulfilled(); } return this.driver.executeAsyncScript( clientSideScripts.waitForAngular, this.rootEl).then(function(browserErr) { if (browserErr) { throw 'Error while waiting for Protractor to ' + 'sync with the page: ' + JSON.stringify(browserErr); } }).then(null, function(err) { var timeout; if (/asynchronous script timeout/.test(err.message)) { // Timeout on Chrome timeout = /[\d\.]*\ seconds/.exec(err.message); } else if (/Timed out waiting for async script/.test(err.message)) { // Timeout on Firefox timeout = /[\d\.]*ms/.exec(err.message); } else if (/Timed out waiting for an asynchronous script/.test(err.message)) { // Timeout on Safari timeout = /[\d\.]*\ ms/.exec(err.message); } if (timeout) { throw 'Timed out waiting for Protractor to synchronize with ' + 'the page after ' + timeout + '. Please see ' + 'https://github.com/angular/protractor/blob/master/docs/faq.md'; } else { throw err; } }); }; // TODO: activeelement also returns a WebElement. /** * Wrap a webdriver.WebElement with protractor specific functionality. * * @param {webdriver.WebElement} element * @return {webdriver.WebElement} the wrapped web element. */ Protractor.prototype.wrapWebElement = function(element) { var thisPtor = this; // Before any of the WebElement functions, Protractor will wait to make sure // Angular is synched up. var originalFns = {}; WEB_ELEMENT_FUNCTIONS.forEach(function(name) { originalFns[name] = element[name]; element[name] = function() { thisPtor.waitForAngular(); return originalFns[name].apply(element, arguments); }; }); var originalFindElement = element.findElement; var originalFindElements = element.findElements; var originalIsElementPresent = element.isElementPresent; /** * Shortcut for querying the document directly with css. * * @param {string} selector a css selector * @see webdriver.WebElement.findElement * @return {!webdriver.WebElement} */ element.$ = function(selector) { var locator = protractor.By.css(selector); return this.findElement(locator); }; /** * @see webdriver.WebElement.findElement * @return {!webdriver.WebElement} */ element.findElement = function(locator, varArgs) { thisPtor.waitForAngular(); var found; if (locator.findElementsOverride) { found = thisPtor.findElementsOverrideHelper_(element, locator); } else { found = originalFindElement.apply(element, arguments); } return thisPtor.wrapWebElement(found); }; /** * Shortcut for querying the document directly with css. * * @param {string} selector a css selector * @see webdriver.WebElement.findElements * @return {!webdriver.promise.Promise} A promise that will be resolved to an * array of the located {@link webdriver.WebElement}s. */ element.$$ = function(selector) { var locator = protractor.By.css(selector); return this.findElements(locator); }; /** * @see webdriver.WebElement.findElements * @return {!webdriver.promise.Promise} A promise that will be resolved to an * array of the located {@link webdriver.WebElement}s. */ element.findElements = function(locator, varArgs) { thisPtor.waitForAngular(); var found; if (locator.findElementsOverride) { found = locator.findElementsOverride(element.getDriver(), element); } else { found = originalFindElements.apply(element, arguments); } return found.then(function(elems) { for (var i = 0; i < elems.length; ++i) { thisPtor.wrapWebElement(elems[i]); } return elems; }); }; /** * @see webdriver.WebElement.isElementPresent * @return {!webdriver.promise.Promise} A promise that will be resolved with * whether an element could be located on the page. */ element.isElementPresent = function(locator, varArgs) { thisPtor.waitForAngular(); if (locator.findElementsOverride) { return locator.findElementsOverride(element.getDriver(), element). then(function (arr) { return !!arr.length; }); } return originalIsElementPresent.apply(element, arguments); }; /** * Evalates the input as if it were on the scope of the current element. * @param {string} expression * * @return {!webdriver.promise.Promise} A promise that will resolve to the * evaluated expression. The result will be resolved as in * {@link webdriver.WebDriver.executeScript}. In summary - primitives will * be resolved as is, functions will be converted to string, and elements * will be returned as a WebElement. */ element.evaluate = function(expression) { thisPtor.waitForAngular(); return element.getDriver().executeScript(clientSideScripts.evaluate, element, expression); }; return element; }; /** * Waits for Angular to finish rendering before searching for elements. * @see webdriver.WebDriver.findElement * @return {!webdriver.WebElement} */ Protractor.prototype.findElement = function(locator, varArgs) { var found; this.waitForAngular(); if (locator.findElementsOverride) { found = this.findElementsOverrideHelper_(null, locator); } else { found = this.driver.findElement(locator, varArgs); } return this.wrapWebElement(found); }; /** * Waits for Angular to finish rendering before searching for elements. * @see webdriver.WebDriver.findElements * @return {!webdriver.promise.Promise} A promise that will be resolved to an * array of the located {@link webdriver.WebElement}s. */ Protractor.prototype.findElements = function(locator, varArgs) { var self = this, found; this.waitForAngular(); if (locator.findElementsOverride) { found = locator.findElementsOverride(this.driver); } else { found = this.driver.findElements(locator, varArgs); } return found.then(function(elems) { for (var i = 0; i < elems.length; ++i) { self.wrapWebElement(elems[i]); } return elems; }); }; /** * Tests if an element is present on the page. * @see webdriver.WebDriver.isElementPresent * @return {!webdriver.promise.Promise} A promise that will resolve to whether * the element is present on the page. */ Protractor.prototype.isElementPresent = function(locatorOrElement, varArgs) { this.waitForAngular(); if (locatorOrElement.findElementsOverride) { return locatorOrElement.findElementsOverride(this.driver).then(function(arr) { return !!arr.length; }); } return this.driver.isElementPresent(locatorOrElement, varArgs); }; /** * Add a module to load before Angular whenever Protractor.get is called. * Modules will be registered after existing modules already on the page, * so any module registered here will override preexisting modules with the same * name. * * @param {!string} name The name of the module to load or override. * @param {!string|Function} script The JavaScript to load the module. */ Protractor.prototype.addMockModule = function(name, script) { this.moduleNames_.push(name); this.moduleScripts_.push(script); }; /** * Clear the list of registered mock modules. */ Protractor.prototype.clearMockModules = function() { this.moduleNames_ = []; this.moduleScripts_ = []; }; /** * Remove a registered mock module. * @param {!string} name The name of the module to remove. */ Protractor.prototype.removeMockModule = function (name) { var index = this.moduleNames_.indexOf(name); this.moduleNames_.splice(index, 1); this.moduleScripts_.splice(index, 1); }; /** * See webdriver.WebDriver.get * * Navigate to the given destination and loads mock modules before * Angular. Assumes that the page being loaded uses Angular. * If you need to access a page which does have Angular on load, use * the wrapped webdriver directly. * * @param {string} destination Destination URL. * @param {=number} opt_timeout Number of seconds to wait for Angular to start. */ Protractor.prototype.get = function(destination, opt_timeout) { var timeout = opt_timeout || 10; var self = this; destination = url.resolve(this.baseUrl, destination); if (this.ignoreSynchronization) { return this.driver.get(destination); } this.driver.get('about:blank'); this.driver.executeScript( 'window.name = "' + DEFER_LABEL + '" + window.name;' + 'window.location.assign("' + destination + '");'); // At this point, we need to make sure the new url has loaded before // we try to execute any asynchronous scripts. this.driver.wait(function() { return self.driver.getCurrentUrl().then(function(url) { return url !== 'about:blank'; }); }, timeout * 1000, 'Timed out waiting for page to load'); var assertAngularOnPage = function(arr) { var hasAngular = arr[0]; if (!hasAngular) { var message = arr[1]; throw new Error('Angular could not be found on the page ' + destination + " : " + message); } }; // Make sure the page is an Angular page. self.driver.executeAsyncScript(clientSideScripts.testForAngular, timeout). then(assertAngularOnPage, function(err) { throw 'Error while running testForAngular: ' + err.message; }); // At this point, Angular will pause for us, until angular.resumeBootstrap // is called. for (var i = 0; i < this.moduleScripts_.length; ++i) { name = this.moduleNames_[i]; this.driver.executeScript(this.moduleScripts_[i]). then(null, function(err) { throw 'Error wile running module script ' + name + ': ' + err.message; }); } return this.driver.executeScript(function() { // Continue to bootstrap Angular. angular.resumeBootstrap(arguments[0]); }, this.moduleNames_); }; /** * Returns the current absolute url from AngularJS. */ Protractor.prototype.getLocationAbsUrl = function() { this.waitForAngular(); return this.driver.executeScript(clientSideScripts.getLocationAbsUrl, this.rootEl); }; /** * Pauses the test and injects some helper functions into the browser, so that * debugging may be done in the browser console. * * This should be used under node in debug mode, i.e. with * protractor debug <configuration.js> * * While in the debugger, commands can be scheduled through webdriver by * entering the repl: * debug> repl * Press Ctrl + C to leave rdebug repl * > ptor.findElement(protractor.By.input('user').sendKeys('Laura')); * > ptor.debugger(); * debug> c * * This will run the sendKeys command as the next task, then re-enter the * debugger. */ Protractor.prototype.debugger = function() { var clientSideScriptsList = []; for (var script in clientSideScripts) { clientSideScriptsList.push( script + ': ' + clientSideScripts[script].toString()); } this.driver.executeScript( 'window.clientSideScripts = {' + clientSideScriptsList.join(', ') + '}'); var flow = webdriver.promise.controlFlow(); flow.execute(function() { debugger; }); }; /** * Builds a single web element from a locator with a findElementsOverride. * Throws an error if an element is not found, and issues a warning * if more than one element is described by the selector. * * @private * @param {webdriver.WebElement} using A WebElement to scope the find, * or null. * @param {webdriver.Locator} locator * @return {webdriver.WebElement} */ Protractor.prototype.findElementsOverrideHelper_ = function(using, locator) { // We need to return a WebElement, so we construct one using a promise // which will resolve to a WebElement. return new webdriver.WebElement( this.driver, locator.findElementsOverride(this.driver, using).then(function(arr) { if (!arr.length) { throw new Error('No element found using locator: ' + locator.message); } if (arr.length > 1) { util.puts('warning: more than one element found for locator ' + locator.message + '- you may need to be more specific'); } return arr[0]; })); }; /** * Create a new instance of Protractor by wrapping a webdriver instance. * * @param {webdriver.WebDriver} webdriver The configured webdriver instance. * @param {string=} opt_baseUrl A URL to prepend to relative gets. * @return {Protractor} */ exports.wrapDriver = function(webdriver, opt_baseUrl, opt_rootElement) { return new Protractor(webdriver, opt_baseUrl, opt_rootElement); }; /** * @type {Protractor} */ var instance; /** * Set a singleton instance of protractor. * @param {Protractor} ptor */ exports.setInstance = function(ptor) { instance = ptor; }; /** * Get the singleton instance. * @return {Protractor} */ exports.getInstance = function() { return instance; }; /** * Utility function that filters a stack trace to be more readable. It removes * Jasmine test frames and webdriver promise resolution. * @param {string} text Original stack trace. * @return {string} */ exports.filterStackTrace = function(text) { if (!text) { return text; } var jasmineFilename = 'node_modules/minijasminenode/lib/jasmine-1.3.1.js'; var seleniumFilename = 'node_modules/selenium-webdriver'; var lines = []; text.split(/\n/).forEach(function(line){ if (line.indexOf(jasmineFilename) == -1 && line.indexOf(seleniumFilename) == -1) { lines.push(line); } }); return lines.join('\n'); };
'use strict'; angular.module('security.login.toolbar', []) // The loginToolbar directive is a reusable widget that can show login or logout buttons // and information the current authenticated user .directive('loginToolbar', ['security', '$state', function (security, $state) { var directive = { templateUrl: 'scripts/common/security/login/assets/templates/toolbar.tpl.html', restrict: 'E', replace: true, scope: true, // link: function ($scope, $element, $attrs, $controller) { link: function ($scope) { $scope.isAuthenticated = security.isAuthenticated; $scope.login = security.showLogin; $scope.register = function() { $state.transitionTo('register.show'); }; $scope.logout = security.logout; $scope.$watch(function () { return security.currentUser; }, function (currentUser) { $scope.currentUser = currentUser; }); } }; return directive; }]);
/*! * AngularJS Material Design * https://github.com/angular/material * @license MIT * v1.1.7 */ (function( window, angular, undefined ){ "use strict"; /** * @ngdoc module * @name material.components.input */ mdInputContainerDirective['$inject'] = ["$mdTheming", "$parse"]; inputTextareaDirective['$inject'] = ["$mdUtil", "$window", "$mdAria", "$timeout", "$mdGesture"]; mdMaxlengthDirective['$inject'] = ["$animate", "$mdUtil"]; placeholderDirective['$inject'] = ["$compile"]; ngMessageDirective['$inject'] = ["$mdUtil"]; mdSelectOnFocusDirective['$inject'] = ["$timeout"]; mdInputInvalidMessagesAnimation['$inject'] = ["$$AnimateRunner", "$animateCss", "$mdUtil", "$log"]; ngMessagesAnimation['$inject'] = ["$$AnimateRunner", "$animateCss", "$mdUtil", "$log"]; ngMessageAnimation['$inject'] = ["$$AnimateRunner", "$animateCss", "$mdUtil", "$log"]; var inputModule = angular.module('material.components.input', [ 'material.core' ]) .directive('mdInputContainer', mdInputContainerDirective) .directive('label', labelDirective) .directive('input', inputTextareaDirective) .directive('textarea', inputTextareaDirective) .directive('mdMaxlength', mdMaxlengthDirective) .directive('placeholder', placeholderDirective) .directive('ngMessages', ngMessagesDirective) .directive('ngMessage', ngMessageDirective) .directive('ngMessageExp', ngMessageDirective) .directive('mdSelectOnFocus', mdSelectOnFocusDirective) .animation('.md-input-invalid', mdInputInvalidMessagesAnimation) .animation('.md-input-messages-animation', ngMessagesAnimation) .animation('.md-input-message-animation', ngMessageAnimation); // If we are running inside of tests; expose some extra services so that we can test them if (window._mdMocksIncluded) { inputModule.service('$$mdInput', function() { return { // special accessor to internals... useful for testing messages: { show : showInputMessages, hide : hideInputMessages, getElement : getMessagesElement } } }) // Register a service for each animation so that we can easily inject them into unit tests .service('mdInputInvalidAnimation', mdInputInvalidMessagesAnimation) .service('mdInputMessagesAnimation', ngMessagesAnimation) .service('mdInputMessageAnimation', ngMessageAnimation); } /** * @ngdoc directive * @name mdInputContainer * @module material.components.input * * @restrict E * * @description * `<md-input-container>` is the parent of any input or textarea element. * * Input and textarea elements will not behave properly unless the md-input-container * parent is provided. * * A single `<md-input-container>` should contain only one `<input>` element, otherwise it will throw an error. * * <b>Exception:</b> Hidden inputs (`<input type="hidden" />`) are ignored and will not throw an error, so * you may combine these with other inputs. * * <b>Note:</b> When using `ngMessages` with your input element, make sure the message and container elements * are *block* elements, otherwise animations applied to the messages will not look as intended. Either use a `div` and * apply the `ng-message` and `ng-messages` classes respectively, or use the `md-block` class on your element. * * @param md-is-error {expression=} When the given expression evaluates to true, the input container * will go into error state. Defaults to erroring if the input has been touched and is invalid. * @param md-no-float {boolean=} When present, `placeholder` attributes on the input will not be converted to floating * labels. * * @usage * <hljs lang="html"> * * <md-input-container> * <label>Username</label> * <input type="text" ng-model="user.name"> * </md-input-container> * * <md-input-container> * <label>Description</label> * <textarea ng-model="user.description"></textarea> * </md-input-container> * * </hljs> * * <h3>When disabling floating labels</h3> * <hljs lang="html"> * * <md-input-container md-no-float> * <input type="text" placeholder="Non-Floating Label"> * </md-input-container> * * </hljs> */ function mdInputContainerDirective($mdTheming, $parse) { ContainerCtrl['$inject'] = ["$scope", "$element", "$attrs", "$animate"]; var INPUT_TAGS = ['INPUT', 'TEXTAREA', 'SELECT', 'MD-SELECT']; var LEFT_SELECTORS = INPUT_TAGS.reduce(function(selectors, isel) { return selectors.concat(['md-icon ~ ' + isel, '.md-icon ~ ' + isel]); }, []).join(","); var RIGHT_SELECTORS = INPUT_TAGS.reduce(function(selectors, isel) { return selectors.concat([isel + ' ~ md-icon', isel + ' ~ .md-icon']); }, []).join(","); return { restrict: 'E', compile: compile, controller: ContainerCtrl }; function compile(tElement) { // Check for both a left & right icon var leftIcon = tElement[0].querySelector(LEFT_SELECTORS); var rightIcon = tElement[0].querySelector(RIGHT_SELECTORS); if (leftIcon) { tElement.addClass('md-icon-left'); } if (rightIcon) { tElement.addClass('md-icon-right'); } return function postLink(scope, element) { $mdTheming(element); }; } function ContainerCtrl($scope, $element, $attrs, $animate) { var self = this; self.isErrorGetter = $attrs.mdIsError && $parse($attrs.mdIsError); self.delegateClick = function() { self.input.focus(); }; self.element = $element; self.setFocused = function(isFocused) { $element.toggleClass('md-input-focused', !!isFocused); }; self.setHasValue = function(hasValue) { $element.toggleClass('md-input-has-value', !!hasValue); }; self.setHasPlaceholder = function(hasPlaceholder) { $element.toggleClass('md-input-has-placeholder', !!hasPlaceholder); }; self.setInvalid = function(isInvalid) { if (isInvalid) { $animate.addClass($element, 'md-input-invalid'); } else { $animate.removeClass($element, 'md-input-invalid'); } }; $scope.$watch(function() { return self.label && self.input; }, function(hasLabelAndInput) { if (hasLabelAndInput && !self.label.attr('for')) { self.label.attr('for', self.input.attr('id')); } }); } } function labelDirective() { return { restrict: 'E', require: '^?mdInputContainer', link: function(scope, element, attr, containerCtrl) { if (!containerCtrl || attr.mdNoFloat || element.hasClass('md-container-ignore')) return; containerCtrl.label = element; scope.$on('$destroy', function() { containerCtrl.label = null; }); } }; } /** * @ngdoc directive * @name mdInput * @restrict E * @module material.components.input * * @description * You can use any `<input>` or `<textarea>` element as a child of an `<md-input-container>`. This * allows you to build complex forms for data entry. * * When the input is required and uses a floating label, then the label will automatically contain * an asterisk (`*`).<br/> * This behavior can be disabled by using the `md-no-asterisk` attribute. * * @param {number=} md-maxlength The maximum number of characters allowed in this input. If this is * specified, a character counter will be shown underneath the input.<br/><br/> * The purpose of **`md-maxlength`** is exactly to show the max length counter text. If you don't * want the counter text and only need "plain" validation, you can use the "simple" `ng-maxlength` * or maxlength attributes.<br/><br/> * **Note:** Only valid for text/string inputs (not numeric). * * @param {string=} aria-label Aria-label is required when no label is present. A warning message * will be logged in the console if not present. * @param {string=} placeholder An alternative approach to using aria-label when the label is not * PRESENT. The placeholder text is copied to the aria-label attribute. * @param md-no-autogrow {boolean=} When present, textareas will not grow automatically. * @param md-no-asterisk {boolean=} When present, an asterisk will not be appended to the inputs floating label * @param md-no-resize {boolean=} Disables the textarea resize handle. * @param {number=} max-rows The maximum amount of rows for a textarea. * @param md-detect-hidden {boolean=} When present, textareas will be sized properly when they are * revealed after being hidden. This is off by default for performance reasons because it * guarantees a reflow every digest cycle. * * @usage * <hljs lang="html"> * <md-input-container> * <label>Color</label> * <input type="text" ng-model="color" required md-maxlength="10"> * </md-input-container> * </hljs> * * <h3>With Errors</h3> * * `md-input-container` also supports errors using the standard `ng-messages` directives and * animates the messages when they become visible using from the `ngEnter`/`ngLeave` events or * the `ngShow`/`ngHide` events. * * By default, the messages will be hidden until the input is in an error state. This is based off * of the `md-is-error` expression of the `md-input-container`. This gives the user a chance to * fill out the form before the errors become visible. * * <hljs lang="html"> * <form name="colorForm"> * <md-input-container> * <label>Favorite Color</label> * <input name="favoriteColor" ng-model="favoriteColor" required> * <div ng-messages="colorForm.favoriteColor.$error"> * <div ng-message="required">This is required!</div> * </div> * </md-input-container> * </form> * </hljs> * * We automatically disable this auto-hiding functionality if you provide any of the following * visibility directives on the `ng-messages` container: * * - `ng-if` * - `ng-show`/`ng-hide` * - `ng-switch-when`/`ng-switch-default` * * You can also disable this functionality manually by adding the `md-auto-hide="false"` expression * to the `ng-messages` container. This may be helpful if you always want to see the error messages * or if you are building your own visibilty directive. * * _<b>Note:</b> The `md-auto-hide` attribute is a static string that is only checked upon * initialization of the `ng-messages` directive to see if it equals the string `false`._ * * <hljs lang="html"> * <form name="userForm"> * <md-input-container> * <label>Last Name</label> * <input name="lastName" ng-model="lastName" required md-maxlength="10" minlength="4"> * <div ng-messages="userForm.lastName.$error" ng-show="userForm.lastName.$dirty"> * <div ng-message="required">This is required!</div> * <div ng-message="md-maxlength">That's too long!</div> * <div ng-message="minlength">That's too short!</div> * </div> * </md-input-container> * <md-input-container> * <label>Biography</label> * <textarea name="bio" ng-model="biography" required md-maxlength="150"></textarea> * <div ng-messages="userForm.bio.$error" ng-show="userForm.bio.$dirty"> * <div ng-message="required">This is required!</div> * <div ng-message="md-maxlength">That's too long!</div> * </div> * </md-input-container> * <md-input-container> * <input aria-label='title' ng-model='title'> * </md-input-container> * <md-input-container> * <input placeholder='title' ng-model='title'> * </md-input-container> * </form> * </hljs> * * <h3>Notes</h3> * * - Requires [ngMessages](https://docs.angularjs.org/api/ngMessages). * - Behaves like the [AngularJS input directive](https://docs.angularjs.org/api/ng/directive/input). * * The `md-input` and `md-input-container` directives use very specific positioning to achieve the * error animation effects. Therefore, it is *not* advised to use the Layout system inside of the * `<md-input-container>` tags. Instead, use relative or absolute positioning. * * * <h3>Textarea directive</h3> * The `textarea` element within a `md-input-container` has the following specific behavior: * - By default the `textarea` grows as the user types. This can be disabled via the `md-no-autogrow` * attribute. * - If a `textarea` has the `rows` attribute, it will treat the `rows` as the minimum height and will * continue growing as the user types. For example a textarea with `rows="3"` will be 3 lines of text * high initially. If no rows are specified, the directive defaults to 1. * - The textarea's height gets set on initialization, as well as while the user is typing. In certain situations * (e.g. while animating) the directive might have been initialized, before the element got it's final height. In * those cases, you can trigger a resize manually by broadcasting a `md-resize-textarea` event on the scope. * - If you want a `textarea` to stop growing at a certain point, you can specify the `max-rows` attribute. * - The textarea's bottom border acts as a handle which users can drag, in order to resize the element vertically. * Once the user has resized a `textarea`, the autogrowing functionality becomes disabled. If you don't want a * `textarea` to be resizeable by the user, you can add the `md-no-resize` attribute. */ function inputTextareaDirective($mdUtil, $window, $mdAria, $timeout, $mdGesture) { return { restrict: 'E', require: ['^?mdInputContainer', '?ngModel', '?^form'], link: postLink }; function postLink(scope, element, attr, ctrls) { var containerCtrl = ctrls[0]; var hasNgModel = !!ctrls[1]; var ngModelCtrl = ctrls[1] || $mdUtil.fakeNgModel(); var parentForm = ctrls[2]; var isReadonly = angular.isDefined(attr.readonly); var mdNoAsterisk = $mdUtil.parseAttributeBoolean(attr.mdNoAsterisk); var tagName = element[0].tagName.toLowerCase(); if (!containerCtrl) return; if (attr.type === 'hidden') { element.attr('aria-hidden', 'true'); return; } else if (containerCtrl.input) { if (containerCtrl.input[0].contains(element[0])) { return; } else { throw new Error("<md-input-container> can only have *one* <input>, <textarea> or <md-select> child element!"); } } containerCtrl.input = element; setupAttributeWatchers(); // Add an error spacer div after our input to provide space for the char counter and any ng-messages var errorsSpacer = angular.element('<div class="md-errors-spacer">'); element.after(errorsSpacer); var placeholderText = angular.isString(attr.placeholder) ? attr.placeholder.trim() : ''; if (!containerCtrl.label && !placeholderText.length) { $mdAria.expect(element, 'aria-label'); } element.addClass('md-input'); if (!element.attr('id')) { element.attr('id', 'input_' + $mdUtil.nextUid()); } // This works around a Webkit issue where number inputs, placed in a flexbox, that have // a `min` and `max` will collapse to about 1/3 of their proper width. Please check #7349 // for more info. Also note that we don't override the `step` if the user has specified it, // in order to prevent some unexpected behaviour. if (tagName === 'input' && attr.type === 'number' && attr.min && attr.max && !attr.step) { element.attr('step', 'any'); } else if (tagName === 'textarea') { setupTextarea(); } // If the input doesn't have an ngModel, it may have a static value. For that case, // we have to do one initial check to determine if the container should be in the // "has a value" state. if (!hasNgModel) { inputCheckValue(); } var isErrorGetter = containerCtrl.isErrorGetter || function() { return ngModelCtrl.$invalid && (ngModelCtrl.$touched || (parentForm && parentForm.$submitted)); }; scope.$watch(isErrorGetter, containerCtrl.setInvalid); // When the developer uses the ngValue directive for the input, we have to observe the attribute, because // AngularJS's ngValue directive is just setting the `value` attribute. if (attr.ngValue) { attr.$observe('value', inputCheckValue); } ngModelCtrl.$parsers.push(ngModelPipelineCheckValue); ngModelCtrl.$formatters.push(ngModelPipelineCheckValue); element.on('input', inputCheckValue); if (!isReadonly) { element .on('focus', function(ev) { $mdUtil.nextTick(function() { containerCtrl.setFocused(true); }); }) .on('blur', function(ev) { $mdUtil.nextTick(function() { containerCtrl.setFocused(false); inputCheckValue(); }); }); } scope.$on('$destroy', function() { containerCtrl.setFocused(false); containerCtrl.setHasValue(false); containerCtrl.input = null; }); /** Gets run through ngModel's pipeline and set the `has-value` class on the container. */ function ngModelPipelineCheckValue(arg) { containerCtrl.setHasValue(!ngModelCtrl.$isEmpty(arg)); return arg; } function setupAttributeWatchers() { if (containerCtrl.label) { attr.$observe('required', function (value) { // We don't need to parse the required value, it's always a boolean because of angular's // required directive. containerCtrl.label.toggleClass('md-required', value && !mdNoAsterisk); }); } } function inputCheckValue() { // An input's value counts if its length > 0, // or if the input's validity state says it has bad input (eg string in a number input) containerCtrl.setHasValue(element.val().length > 0 || (element[0].validity || {}).badInput); } function setupTextarea() { var isAutogrowing = !attr.hasOwnProperty('mdNoAutogrow'); attachResizeHandle(); if (!isAutogrowing) return; // Can't check if height was or not explicity set, // so rows attribute will take precedence if present var minRows = attr.hasOwnProperty('rows') ? parseInt(attr.rows) : NaN; var maxRows = attr.hasOwnProperty('maxRows') ? parseInt(attr.maxRows) : NaN; var scopeResizeListener = scope.$on('md-resize-textarea', growTextarea); var lineHeight = null; var node = element[0]; // This timeout is necessary, because the browser needs a little bit // of time to calculate the `clientHeight` and `scrollHeight`. $timeout(function() { $mdUtil.nextTick(growTextarea); }, 10, false); // We could leverage ngModel's $parsers here, however it // isn't reliable, because AngularJS trims the input by default, // which means that growTextarea won't fire when newlines and // spaces are added. element.on('input', growTextarea); // We should still use the $formatters, because they fire when // the value was changed from outside the textarea. if (hasNgModel) { ngModelCtrl.$formatters.push(formattersListener); } if (!minRows) { element.attr('rows', 1); } angular.element($window).on('resize', growTextarea); scope.$on('$destroy', disableAutogrow); function growTextarea() { // temporarily disables element's flex so its height 'runs free' element .attr('rows', 1) .css('height', 'auto') .addClass('md-no-flex'); var height = getHeight(); if (!lineHeight) { // offsetHeight includes padding which can throw off our value var originalPadding = element[0].style.padding || ''; lineHeight = element.css('padding', 0).prop('offsetHeight'); element[0].style.padding = originalPadding; } if (minRows && lineHeight) { height = Math.max(height, lineHeight * minRows); } if (maxRows && lineHeight) { var maxHeight = lineHeight * maxRows; if (maxHeight < height) { element.attr('md-no-autogrow', ''); height = maxHeight; } else { element.removeAttr('md-no-autogrow'); } } if (lineHeight) { element.attr('rows', Math.round(height / lineHeight)); } element .css('height', height + 'px') .removeClass('md-no-flex'); } function getHeight() { var offsetHeight = node.offsetHeight; var line = node.scrollHeight - offsetHeight; return offsetHeight + Math.max(line, 0); } function formattersListener(value) { $mdUtil.nextTick(growTextarea); return value; } function disableAutogrow() { if (!isAutogrowing) return; isAutogrowing = false; angular.element($window).off('resize', growTextarea); scopeResizeListener && scopeResizeListener(); element .attr('md-no-autogrow', '') .off('input', growTextarea); if (hasNgModel) { var listenerIndex = ngModelCtrl.$formatters.indexOf(formattersListener); if (listenerIndex > -1) { ngModelCtrl.$formatters.splice(listenerIndex, 1); } } } function attachResizeHandle() { if (attr.hasOwnProperty('mdNoResize')) return; var handle = angular.element('<div class="md-resize-handle"></div>'); var isDragging = false; var dragStart = null; var startHeight = 0; var container = containerCtrl.element; var dragGestureHandler = $mdGesture.register(handle, 'drag', { horizontal: false }); element.wrap('<div class="md-resize-wrapper">').after(handle); handle.on('mousedown', onMouseDown); container .on('$md.dragstart', onDragStart) .on('$md.drag', onDrag) .on('$md.dragend', onDragEnd); scope.$on('$destroy', function() { handle .off('mousedown', onMouseDown) .remove(); container .off('$md.dragstart', onDragStart) .off('$md.drag', onDrag) .off('$md.dragend', onDragEnd); dragGestureHandler(); handle = null; container = null; dragGestureHandler = null; }); function onMouseDown(ev) { ev.preventDefault(); isDragging = true; dragStart = ev.clientY; startHeight = parseFloat(element.css('height')) || element.prop('offsetHeight'); } function onDragStart(ev) { if (!isDragging) return; ev.preventDefault(); disableAutogrow(); container.addClass('md-input-resized'); } function onDrag(ev) { if (!isDragging) return; element.css('height', (startHeight + ev.pointer.distanceY) + 'px'); } function onDragEnd(ev) { if (!isDragging) return; isDragging = false; container.removeClass('md-input-resized'); } } // Attach a watcher to detect when the textarea gets shown. if (attr.hasOwnProperty('mdDetectHidden')) { var handleHiddenChange = function() { var wasHidden = false; return function() { var isHidden = node.offsetHeight === 0; if (isHidden === false && wasHidden === true) { growTextarea(); } wasHidden = isHidden; }; }(); // Check every digest cycle whether the visibility of the textarea has changed. // Queue up to run after the digest cycle is complete. scope.$watch(function() { $mdUtil.nextTick(handleHiddenChange, false); return true; }); } } } } function mdMaxlengthDirective($animate, $mdUtil) { return { restrict: 'A', require: ['ngModel', '^mdInputContainer'], link: postLink }; function postLink(scope, element, attr, ctrls) { var maxlength; var ngModelCtrl = ctrls[0]; var containerCtrl = ctrls[1]; var charCountEl, errorsSpacer; // Wait until the next tick to ensure that the input has setup the errors spacer where we will // append our counter $mdUtil.nextTick(function() { errorsSpacer = angular.element(containerCtrl.element[0].querySelector('.md-errors-spacer')); charCountEl = angular.element('<div class="md-char-counter">'); // Append our character counter inside the errors spacer errorsSpacer.append(charCountEl); // Stop model from trimming. This makes it so whitespace // over the maxlength still counts as invalid. attr.$set('ngTrim', 'false'); scope.$watch(attr.mdMaxlength, function(value) { maxlength = value; if (angular.isNumber(value) && value > 0) { if (!charCountEl.parent().length) { $animate.enter(charCountEl, errorsSpacer); } renderCharCount(); } else { $animate.leave(charCountEl); } }); ngModelCtrl.$validators['md-maxlength'] = function(modelValue, viewValue) { if (!angular.isNumber(maxlength) || maxlength < 0) { return true; } // We always update the char count, when the modelValue has changed. // Using the $validators for triggering the update works very well. renderCharCount(); return ( modelValue || element.val() || viewValue || '' ).length <= maxlength; }; }); function renderCharCount(value) { // If we have not been appended to the body yet; do not render if (!charCountEl.parent) { return value; } // Force the value into a string since it may be a number, // which does not have a length property. charCountEl.text(String(element.val() || value || '').length + ' / ' + maxlength); return value; } } } function placeholderDirective($compile) { return { restrict: 'A', require: '^^?mdInputContainer', priority: 200, link: { // Note that we need to do this in the pre-link, as opposed to the post link, if we want to // support data bindings in the placeholder. This is necessary, because we have a case where // we transfer the placeholder value to the `<label>` and we remove it from the original `<input>`. // If we did this in the post-link, AngularJS would have set up the observers already and would be // re-adding the attribute, even though we removed it from the element. pre: preLink } }; function preLink(scope, element, attr, inputContainer) { // If there is no input container, just return if (!inputContainer) return; var label = inputContainer.element.find('label'); var noFloat = inputContainer.element.attr('md-no-float'); // If we have a label, or they specify the md-no-float attribute, just return if ((label && label.length) || noFloat === '' || scope.$eval(noFloat)) { // Add a placeholder class so we can target it in the CSS inputContainer.setHasPlaceholder(true); return; } // md-select handles placeholders on it's own if (element[0].nodeName != 'MD-SELECT') { // Move the placeholder expression to the label var newLabel = angular.element('<label ng-click="delegateClick()" tabindex="-1">' + attr.placeholder + '</label>'); // Note that we unset it via `attr`, in order to get AngularJS // to remove any observers that it might have set up. Otherwise // the attribute will be added on the next digest. attr.$set('placeholder', null); // We need to compile the label manually in case it has any bindings. // A gotcha here is that we first add the element to the DOM and we compile // it later. This is necessary, because if we compile the element beforehand, // it won't be able to find the `mdInputContainer` controller. inputContainer.element .addClass('md-icon-float') .prepend(newLabel); $compile(newLabel)(scope); } } } /** * @ngdoc directive * @name mdSelectOnFocus * @module material.components.input * * @restrict A * * @description * The `md-select-on-focus` directive allows you to automatically select the element's input text on focus. * * <h3>Notes</h3> * - The use of `md-select-on-focus` is restricted to `<input>` and `<textarea>` elements. * * @usage * <h3>Using with an Input</h3> * <hljs lang="html"> * * <md-input-container> * <label>Auto Select</label> * <input type="text" md-select-on-focus> * </md-input-container> * </hljs> * * <h3>Using with a Textarea</h3> * <hljs lang="html"> * * <md-input-container> * <label>Auto Select</label> * <textarea md-select-on-focus>This text will be selected on focus.</textarea> * </md-input-container> * * </hljs> */ function mdSelectOnFocusDirective($timeout) { return { restrict: 'A', link: postLink }; function postLink(scope, element, attr) { if (element[0].nodeName !== 'INPUT' && element[0].nodeName !== "TEXTAREA") return; var preventMouseUp = false; element .on('focus', onFocus) .on('mouseup', onMouseUp); scope.$on('$destroy', function() { element .off('focus', onFocus) .off('mouseup', onMouseUp); }); function onFocus() { preventMouseUp = true; $timeout(function() { // Use HTMLInputElement#select to fix firefox select issues. // The debounce is here for Edge's sake, otherwise the selection doesn't work. element[0].select(); // This should be reset from inside the `focus`, because the event might // have originated from something different than a click, e.g. a keyboard event. preventMouseUp = false; }, 1, false); } // Prevents the default action of the first `mouseup` after a focus. // This is necessary, because browsers fire a `mouseup` right after the element // has been focused. In some browsers (Firefox in particular) this can clear the // selection. There are examples of the problem in issue #7487. function onMouseUp(event) { if (preventMouseUp) { event.preventDefault(); } } } } var visibilityDirectives = ['ngIf', 'ngShow', 'ngHide', 'ngSwitchWhen', 'ngSwitchDefault']; function ngMessagesDirective() { return { restrict: 'EA', link: postLink, // This is optional because we don't want target *all* ngMessage instances, just those inside of // mdInputContainer. require: '^^?mdInputContainer' }; function postLink(scope, element, attrs, inputContainer) { // If we are not a child of an input container, don't do anything if (!inputContainer) return; // Add our animation class element.toggleClass('md-input-messages-animation', true); // Add our md-auto-hide class to automatically hide/show messages when container is invalid element.toggleClass('md-auto-hide', true); // If we see some known visibility directives, remove the md-auto-hide class if (attrs.mdAutoHide == 'false' || hasVisibiltyDirective(attrs)) { element.toggleClass('md-auto-hide', false); } } function hasVisibiltyDirective(attrs) { return visibilityDirectives.some(function(attr) { return attrs[attr]; }); } } function ngMessageDirective($mdUtil) { return { restrict: 'EA', compile: compile, priority: 100 }; function compile(tElement) { if (!isInsideInputContainer(tElement)) { // When the current element is inside of a document fragment, then we need to check for an input-container // in the postLink, because the element will be later added to the DOM and is currently just in a temporary // fragment, which causes the input-container check to fail. if (isInsideFragment()) { return function (scope, element) { if (isInsideInputContainer(element)) { // Inside of the postLink function, a ngMessage directive will be a comment element, because it's // currently hidden. To access the shown element, we need to use the element from the compile function. initMessageElement(tElement); } }; } } else { initMessageElement(tElement); } function isInsideFragment() { var nextNode = tElement[0]; while (nextNode = nextNode.parentNode) { if (nextNode.nodeType === Node.DOCUMENT_FRAGMENT_NODE) { return true; } } return false; } function isInsideInputContainer(element) { return !!$mdUtil.getClosest(element, "md-input-container"); } function initMessageElement(element) { // Add our animation class element.toggleClass('md-input-message-animation', true); } } } var $$AnimateRunner, $animateCss, $mdUtil, $log; function mdInputInvalidMessagesAnimation($$AnimateRunner, $animateCss, $mdUtil, $log) { saveSharedServices($$AnimateRunner, $animateCss, $mdUtil, $log); return { addClass: function(element, className, done) { showInputMessages(element, done); } // NOTE: We do not need the removeClass method, because the message ng-leave animation will fire }; } function ngMessagesAnimation($$AnimateRunner, $animateCss, $mdUtil, $log) { saveSharedServices($$AnimateRunner, $animateCss, $mdUtil, $log); return { enter: function(element, done) { showInputMessages(element, done); }, leave: function(element, done) { hideInputMessages(element, done); }, addClass: function(element, className, done) { if (className == "ng-hide") { hideInputMessages(element, done); } else { done(); } }, removeClass: function(element, className, done) { if (className == "ng-hide") { showInputMessages(element, done); } else { done(); } } }; } function ngMessageAnimation($$AnimateRunner, $animateCss, $mdUtil, $log) { saveSharedServices($$AnimateRunner, $animateCss, $mdUtil, $log); return { enter: function(element, done) { var animator = showMessage(element); animator.start().done(done); }, leave: function(element, done) { var animator = hideMessage(element); animator.start().done(done); } }; } function showInputMessages(element, done) { var animators = [], animator; var messages = getMessagesElement(element); var children = messages.children(); if (messages.length == 0 || children.length == 0) { $log.warn('mdInput messages show animation called on invalid messages element: ', element); done(); return; } angular.forEach(children, function(child) { animator = showMessage(angular.element(child)); animators.push(animator.start()); }); $$AnimateRunner.all(animators, done); } function hideInputMessages(element, done) { var animators = [], animator; var messages = getMessagesElement(element); var children = messages.children(); if (messages.length == 0 || children.length == 0) { $log.warn('mdInput messages hide animation called on invalid messages element: ', element); done(); return; } angular.forEach(children, function(child) { animator = hideMessage(angular.element(child)); animators.push(animator.start()); }); $$AnimateRunner.all(animators, done); } function showMessage(element) { var height = parseInt(window.getComputedStyle(element[0]).height); var topMargin = parseInt(window.getComputedStyle(element[0]).marginTop); var messages = getMessagesElement(element); var container = getInputElement(element); // Check to see if the message is already visible so we can skip var alreadyVisible = (topMargin > -height); // If we have the md-auto-hide class, the md-input-invalid animation will fire, so we can skip if (alreadyVisible || (messages.hasClass('md-auto-hide') && !container.hasClass('md-input-invalid'))) { return $animateCss(element, {}); } return $animateCss(element, { event: 'enter', structural: true, from: {"opacity": 0, "margin-top": -height + "px"}, to: {"opacity": 1, "margin-top": "0"}, duration: 0.3 }); } function hideMessage(element) { var height = element[0].offsetHeight; var styles = window.getComputedStyle(element[0]); // If we are already hidden, just return an empty animation if (parseInt(styles.opacity) === 0) { return $animateCss(element, {}); } // Otherwise, animate return $animateCss(element, { event: 'leave', structural: true, from: {"opacity": 1, "margin-top": 0}, to: {"opacity": 0, "margin-top": -height + "px"}, duration: 0.3 }); } function getInputElement(element) { var inputContainer = element.controller('mdInputContainer'); return inputContainer.element; } function getMessagesElement(element) { // If we ARE the messages element, just return ourself if (element.hasClass('md-input-messages-animation')) { return element; } // If we are a ng-message element, we need to traverse up the DOM tree if (element.hasClass('md-input-message-animation')) { return angular.element($mdUtil.getClosest(element, function(node) { return node.classList.contains('md-input-messages-animation'); })); } // Otherwise, we can traverse down return angular.element(element[0].querySelector('.md-input-messages-animation')); } function saveSharedServices(_$$AnimateRunner_, _$animateCss_, _$mdUtil_, _$log_) { $$AnimateRunner = _$$AnimateRunner_; $animateCss = _$animateCss_; $mdUtil = _$mdUtil_; $log = _$log_; } })(window, window.angular);
//! moment.js locale configuration //! locale : French [fr] //! author : John Fischer : https://github.com/jfroffice ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../moment')) : typeof define === 'function' && define.amd ? define(['../moment'], factory) : factory(global.Px.moment) }(this, (function (moment) { 'use strict'; var fr = moment.defineLocale('fr', { months : 'janvier_février_mars_avril_mai_juin_juillet_août_septembre_octobre_novembre_décembre'.split('_'), monthsShort : 'janv._févr._mars_avr._mai_juin_juil._août_sept._oct._nov._déc.'.split('_'), monthsParseExact : true, weekdays : 'dimanche_lundi_mardi_mercredi_jeudi_vendredi_samedi'.split('_'), weekdaysShort : 'dim._lun._mar._mer._jeu._ven._sam.'.split('_'), weekdaysMin : 'Di_Lu_Ma_Me_Je_Ve_Sa'.split('_'), weekdaysParseExact : true, longDateFormat : { LT : 'HH:mm', LTS : 'HH:mm:ss', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY HH:mm', LLLL : 'dddd D MMMM YYYY HH:mm' }, calendar : { sameDay : '[Aujourd’hui à] LT', nextDay : '[Demain à] LT', nextWeek : 'dddd [à] LT', lastDay : '[Hier à] LT', lastWeek : 'dddd [dernier à] LT', sameElse : 'L' }, relativeTime : { future : 'dans %s', past : 'il y a %s', s : 'quelques secondes', m : 'une minute', mm : '%d minutes', h : 'une heure', hh : '%d heures', d : 'un jour', dd : '%d jours', M : 'un mois', MM : '%d mois', y : 'un an', yy : '%d ans' }, dayOfMonthOrdinalParse: /\d{1,2}(er|)/, ordinal : function (number, period) { switch (period) { // TODO: Return 'e' when day of month > 1. Move this case inside // block for masculine words below. // See https://github.com/moment/moment/issues/3375 case 'D': return number + (number === 1 ? 'er' : ''); // Words with masculine grammatical gender: mois, trimestre, jour default: case 'M': case 'Q': case 'DDD': case 'd': return number + (number === 1 ? 'er' : 'e'); // Words with feminine grammatical gender: semaine case 'w': case 'W': return number + (number === 1 ? 're' : 'e'); } }, week : { dow : 1, // Monday is the first day of the week. doy : 4 // The week that contains Jan 4th is the first week of the year. } }); return fr; })));
import React, {PureComponent} from 'react'; import PropTypes from 'prop-types'; import autobind from 'autobind-decorator'; import Button from './button'; const STATE_DEFAULT = 'default'; const STATE_ASK = 'ask'; const STATE_DONE = 'done'; @autobind class PromptButton extends PureComponent { constructor (props) { super(props); this.state = { state: STATE_DEFAULT }; } _confirm (...args) { // Clear existing timeouts clearTimeout(this._triggerTimeout); // Fire the click handler this.props.onClick(...args); // Set the state to done (but delay a bit to not alarm user) this._doneTimeout = setTimeout(() => { this.setState({state: STATE_DONE}); }, 100); // Set a timeout to hide the confirmation this._triggerTimeout = setTimeout(() => { this.setState({state: STATE_DEFAULT}); }, 2000); } _ask (...args) { const e = args[args.length - 1]; // Prevent events (ex. won't close dropdown if it's in one) e.preventDefault(); e.stopPropagation(); // Toggle the confirmation notice this.setState({state: STATE_ASK}); // Set a timeout to hide the confirmation this._triggerTimeout = setTimeout(() => { this.setState({state: STATE_DEFAULT}); }, 2000); } _handleClick (...args) { const {state} = this.state; if (state === STATE_ASK) { this._confirm(...args); } else if (state === STATE_DEFAULT) { this._ask(...args); } else { // Do nothing } } componentWillUnmount () { clearTimeout(this._triggerTimeout); clearTimeout(this._doneTimeout); } render () { const { onClick, // eslint-disable-line no-unused-vars children, addIcon, disabled, confirmMessage, doneMessage, tabIndex, ...other } = this.props; const {state} = this.state; const finalConfirmMessage = (confirmMessage || 'Click to confirm').trim(); const finalDoneMessage = doneMessage || 'Done'; let innerMsg; if (state === STATE_ASK && addIcon) { innerMsg = ( <span className="warning" title="Click again to confirm"> <i className="fa fa-exclamation-circle"/> {finalConfirmMessage ? <span className="space-left">{finalConfirmMessage}</span> : '' } </span> ); } else if (state === STATE_ASK) { innerMsg = ( <span className="warning" title="Click again to confirm"> {finalConfirmMessage} </span> ); } else if (state === STATE_DONE) { innerMsg = finalDoneMessage; } else { innerMsg = children; } return ( <Button onClick={this._handleClick} disabled={disabled} tabIndex={tabIndex} {...other}> {innerMsg} </Button> ); } } PromptButton.propTypes = { onClick: PropTypes.func, addIcon: PropTypes.bool, children: PropTypes.node, disabled: PropTypes.bool, confirmMessage: PropTypes.string, doneMessage: PropTypes.string, value: PropTypes.any, tabIndex: PropTypes.number }; export default PromptButton;
import Ember from 'ember'; const { RSVP } = Ember; let _useNativeImpl = (window && typeof window.FontFace !== 'undefined'); let _loadedFonts = {}; let _failedFonts = {}; const kFontLoadTimeout = 3000; export default class FontFace { constructor(family, url, attributes = {}) { attributes.style = attributes.style || 'normal'; attributes.weight = attributes.weight || 400; let fontId = getCacheKey(family, url, attributes); this.id = fontId; this.family = family; this.url = url; this.attributes = attributes; } isLoaded() { // For remote URLs, check the cache. System fonts (sans url) assume loaded. return _loadedFonts[this.id] !== undefined || !this.url; } loadFont() { // See if we've previously loaded it. if (_loadedFonts[this.id]) { return RSVP.resolve(null); } // See if we've previously failed to load it. if (_failedFonts[this.id]) { return RSVP.resolve(_failedFonts[this.id]); } // System font: assume it's installed. if (!this.url) { return RSVP.resolve(null); } // Use font loader API return new Promise((resolve, reject) => { let theFontFace = new window.FontFace(this.family, 'url(' + this.url + ')', this.attributes); theFontFace.load().then(function () { _loadedFonts[this.id] = true; resolve(null); }, function (err) { _failedFonts[this.id] = err; reject(err); }); }); } } /** * Helper for retrieving the default family by weight. * * @param {Number} fontWeight * @return {FontFace} */ export function defaultFontFace(fontWeight) { return new FontFace('sans-serif', null, { weight: fontWeight }); }; /** * @internal */ function getCacheKey(family, url, attributes) { return family + url + Object.keys(attributes).sort().map((key) => attributes[key]); }
define([ 'streamhub-sdk/auth', 'event-emitter'], function (Auth, EventEmitter) { 'use strict'; describe('streamhub-sdk/auth', function () { afterEach(function () { Auth.setToken(); }); it('is an object', function () { expect(Auth).toEqual(jasmine.any(Object)); }); it('is an EventEmitter', function () { expect(Auth instanceof EventEmitter).toBe(true); }); describe('.setToken(token)', function () { it('stores the token', function () { var token = '123'; Auth.setToken(token); expect(Auth._token).toBe(token); }); it('emits a token event', function () { var token = 'token', onToken = jasmine.createSpy('onToken'); Auth.on('token', onToken); Auth.setToken(token); expect(onToken).toHaveBeenCalledWith(token); }); }); describe('.getToken()', function () { it('returns undefined if no token has been set', function () { expect(Auth.getToken()).toBe(undefined); }); it('returns a token if one has been set', function () { var token1 = '12345', token2 = 'abcdef'; Auth.setToken(token1); expect(Auth.getToken()).toBe(token1); Auth.setToken(token2); expect(Auth.getToken()).toBe(token2); }); }); describe('UnauthorizedError', function () { it('can be constructed with new', function () { var err = new Auth.UnauthorizedError(); expect(err instanceof Error).toBe(true); expect(err instanceof Auth.UnauthorizedError).toBe(true); }); it('can be passed a message', function () { var err = new Auth.UnauthorizedError('no auth!'); expect(err.toString()).toBe("UnauthorizedError: no auth!"); }); }); }); });
// http://requirejs.org/docs/api.html#packages // Packages are not quite as ez as they appear, review the above require.config( { waitSeconds: 15, packages: [ { name: 'editPackage', location: '../../editor/modules', // default 'packagename' main: 'service-edit' // default 'main' } ] } ); require( ["editPackage", "service-os-panel", "service-app-panel", "./service-graph"], function ( serviceEdit, osPanel, appPanel, serviceGraph ) { console.log( "\n\n ************** _main: loaded *** \n\n" ); // Shared variables need to be visible prior to scope var _deploySuccess = false; var _resultsDialog = null; var $resultsPre = $( "#resultPre" ) ; var $serviceParameters ; $( document ).ready( function () { initialize(); } ); this.initialize = initialize; function initialize() { CsapCommon.configureCsapAlertify(); console.log( "ServiceAdmin::initialize" ); $serviceParameters=$("#serviceParameters") ; register_lifeCycleEvents(); register_Buttons(); register_ToolTips(); register_ReportActions(); initialize_ServiceSettings() serviceInstancesGet( false ); addServiceContext( '#instanceTable', getLast ); } function getLast() { return lastInstanceRollOver; } /** @memberOf ServiceAdmin */ function register_lifeCycleEvents() { $( '#lcSelect' ).change( function () { var lcSelected = $( this ).val(); if ( lcSelected == "none" ) return false; $( '#instanceTable tbody tr.selected input' ).prop( 'checked', false ); $( "#instanceTable tbody tr" ).removeClass( "selected" ); $( currentInstance ).addClass( "selected" ); $( "#instanceTable tbody tr" ).each( function () { var rowLc = $( this ).column( 1 ).text(); // alert( "lcSelected: " + lcSelected + " rowLc: " + // rowLc ) ; if ( lcSelected == rowLc ) { $( this ).addClass( "selected" ); } } ); $( '#instanceTable tbody tr.selected input' ).prop( 'checked', true ); // reset the select drop down $( "option:eq(0)", this ).attr( "selected", "selected" ); return false; // prevents link } ); $( '.selectAllHosts' ).click( function () { // $( "#meters" ).hide(); //$( "#toggleMeters" ).trigger( "click" ); $( "#instanceTable tbody tr" ).addClass( "selected" ); $( '#instanceTable tbody tr.selected input' ).prop( 'checked', true ); // alert( $("#instanceTable *.selected").length ) ; serviceGraph.updateHosts(); getLatestServiceStats(); return false; } ); $( '#deselectAllHosts' ).click( function () { $( '#instanceTable tbody tr.selected input' ).prop( 'checked', false ); $( "#instanceTable tbody tr" ).removeClass( "selected" ); $( currentInstance ).addClass( "selected" ); $( '#instanceTable tbody tr.selected input' ).prop( 'checked', true ); serviceGraph.updateHosts(); getLatestServiceStats(); return false; } ); $( '#isGarbageLogs' ).click( function () { if ( $( "#isGarbageLogs" ).is( ':checked' ) ) alertify.notify( "Adding params to start: " + gcParams ); else alertify.notify( "GC params will not be added" ); return true; } ); $( '#isInlineGarbageLogs' ).click( function () { if ( $( "#isInlineGarbageLogs" ).is( ':checked' ) ) alertify.notify( "Adding params to start: " + gcInlineParams ); else alertify.notify( "GC params will not be added" ); return true; } ); } /** @memberOf ServiceAdmin */ function register_Buttons() { var message = "Use checkbox to select service instances to be included in start/stop/deploy operations." + "\n\nRight mouse click to run commands on individual instances. " + "\n\nThe checkbox that is disabled is the primary instance for deployments and builds. Click other a different host name to change.\n\n"; $( '#instanceHelpButton' ).attr( "title", message ); $( '#instanceHelpButton' ).click( function () { alertify.alert( message, function ( result ) { // do nothing } ); $( ".alertify-inner" ).css( "text-align", "left" ); $( ".alertify-inner" ).css( "white-space", "pre-wrap" ); return false; } ); $( "#showFilteredMetersButton" ).click( function () { $( ".hiddenMeter" ).toggle( "slow" ); } ); $( '.uncheckAll' ).click( function () { $( 'input', $( this ).parent().parent() ).prop( "checked", false ).trigger( "change" ); return false; // prevents link } ); $( '.checkAll' ).click( function () { $( 'input', $( this ).parent().parent() ).prop( "checked", true ); return false; // prevents link } ); $( '.multipleServicesButton' ).click( function () { console.log( "Adding: " + $( this ).data( "target" ) + " services: " + servicesOnHostForward.length ); var operation = $( this ).data( "target" ); var $servicesContainer = $( "#" + operation ); $servicesContainer.toggle(); var $serviceCheckboxes = $( ".serviceCheckboxes", $servicesContainer ); $serviceCheckboxes.empty(); var serviceOrder = servicesOnHostForward; if ( operation == "killServerServices" ) serviceOrder = servicesOnHostReverse; for ( var i = 0; i < serviceOrder.length; i++ ) { var label = serviceOrder[i]; if ( label.contains( "_" ) ) label = label.substring( 0, label.indexOf( "_" ) ); var serviceLabel = jQuery( '<label/>', { class: "serviceLabels", text: label } ).appendTo( $serviceCheckboxes ); var optionItem = jQuery( '<input/>', { name: serviceOrder[i], type: "checkbox" } ).prependTo( serviceLabel ); if ( serviceOrder[i] == serviceName ) { optionItem.prop( 'checked', true ); } } } ); $( '#editServiceButton' ).click( function () { serviceEdit.setSpecificHost( hostName ); $.get( serviceEditUrl, serviceEdit.showServiceDialog, 'html' ); return false; } ); $( '#deployOptionsButton' ).click( showDeployDialog ); // Do start bindings $( '#startOptionsButton' ).click( showStartDialog ); $( '#killOptionsButton' ).click( showKillDialog ); $( '#jobsButton' ).click( showJobsDialog ); // Do event bindings $( '#launchService' ).click( launchServiceDialog ); $( '#runtimeSelect' ).change( showRuntimeConfirmDialog ); $( '#jdkSelect' ).change( showJdkConfirmDialog ); $( '#motdButton' ).click( showHostMessageDialog ); $( '#undeploySelect' ).change( function () { unDeployService( true ); return false; // prevents link } ); $( '#showFiles' ).click( function () { launchFiles( $( "#instanceTable *.selected" ) ); return false; // prevents link } ); $( '#showLogs' ).click( function () { launchLogs( $( "#instanceTable *.selected" ) ); return false; // prevents link } ); $( '#searchLogs' ).click( function () { var urlAction = agentHostUrlPattern.replace( /CSAP_HOST/g, hostName ); urlAction += commandScreen + "?command=logSearch&fromFolder=defaultLog&serviceName=" + serviceName + "&hostName=" + hostName + "&"; openWindowSafely( urlAction, "_blank" ); return false; } ); $( '#hostDashboardButton' ).click( function () { launchHostDash( $( "#instanceTable *.selected" ) ); return false; // prevents link } ); $( '#jmxDashboardButton' ).click( function () { launchJmxDash( $( "#instanceTable *.selected" ) ); return false; // prevents link } ); $( '#jmxCustomDashboardButton, #httpCollectionButton' ).click( function () { launchCustomJmxDash( $( "#instanceTable *.selected" ) ); return false; // prevents link } ); $( '#historyButton' ).click( function () { launchHistory( $( "#instanceTable *.selected" ), null ); return false; // prevents link } ); $( '#jmcButton' ).click( function () { launchProfiler( $( "#instanceTable *.selected" ), false ); return false; // prevents link } ); $( '#jmeterButton' ).click( function () { launchJMeter( false ); return false; // prevents link } ); $( '#jvisualvmButton' ).click( function () { launchProfiler( $( "#instanceTable *.selected" ), true ); return false; // prevents link } ); $( '#hostCompareButton, #jmxCompareButton, #appCompareButton, #osCompareButton' ).click( function () { // launchPerfCompare( $("#instanceTable *.selected"), true); // alert (" Num: " +jqueryRows.length) ; var jqueryRows = $( "#instanceTable *.selected" ) var hosts = ""; jqueryRows.each( function ( index ) { var host = $( this ).data( "host" ); if ( hosts != "" ) hosts += ","; hosts += host; } ); var urlAction = analyticsUrl + "&report=" + $( this ).data( "report" ) + "&project=" + selectedProject + "&host=" + hosts + "&service=" + serviceShortName + "&appId=" + appId + "&"; if ( $( this ).attr( "id" ) == "appCompareButton" ) { urlAction += "appGraph=appGraph"; } openWindowSafely( urlAction, "_blank" ); return false; // prevents link } ); $( '#serviceHelpButton' ).click( function () { launchHelp( $( this ) ); return false; // prevents link } ); $( '#hostHelpButton' ).click( function () { var urlAction = agentHostUrlPattern.replace( /CSAP_HOST/g, hostName ); urlAction += "/csap/health?pattern=" + serviceShortName + "&u=1"; // console.log("hostHelp: " + urlAction) ; openWindowSafely( urlAction, "_blank" ); return false; // prevents link } ); $( '#launchOptions a' ).each( function ( index ) { // alert(index + ': ' + $(this).text()); $( this ).click( function () { launchService( $( this ) ); return false; // prevents link } ); } ); } /** @memberOf ServiceAdmin */ function initialize_ServiceSettings() { if ( serviceName == "CsAgent_8011" || serviceName.indexOf( "admin" ) == 0 ) { $( "#deployStart" ).prop( 'checked', false ); $( "#isScmUpload" ).prop( 'checked', true ); $( "#stopButton" ).hide(); } // jvmSelection for ( var i = 0; i < jvms.available.length; i++ ) { var optionItem = jQuery( '<option/>', { text: jvms.available[i] } ); $( "#jdkSelect" ).append( optionItem ); } $( "#jdkSelect" ).val( jvms.serviceSelected ); // Update load // serviceDataGet() ; if ( isSkipJmx ) { $( ".jmxClassifier" ).hide(); } } /** @memberOf ServiceAdmin */ function register_ReportActions() { var triggerReports = function () { if ( $( this ).attr( "id" ) == "compareStartInput" ) return; getLatestServiceStats(); } $( '#filterThreshold' ).selectmenu( { width: "6em", change: triggerReports } ); $( '#numAppSamples' ).selectmenu( { width: "6em", change: triggerReports } ); $( '#rateSelect' ).selectmenu( { width: "10em", change: triggerReports } ); $( '#jmxAnalyticsLaunch' ).click( function () { var urlAction = analyticsUrl + "&project=" + selectedProject + "&report=jmx/detail" + "&service=" + serviceShortName + "&appId=" + appId + "&"; openWindowSafely( urlAction, "_blank" ); return false; } ); $( '#applicationLaunch' ).click( function () { var urlAction = analyticsUrl + "&project=" + selectedProject + "&report=jmxCustom/detail" + "&service=" + serviceShortName + "&appId=" + appId + "&"; openWindowSafely( urlAction, "_blank" ); return false; } ); $( "#compareStartInput" ).datepicker( { maxDate: '-1' } ); $( "#compareStartInput" ).change( function () { var days = calculateUsCentralDays( $( this ).datepicker( "getDate" ).getTime() ); // $("#dayOffset", resourceRootContainer).val(days) ; console.log( "Num days offset: " + days + " id " + $( this ).attr( "id" ) ); if ( days == 0 ) { days = 1; } osPanel.updateOffset( days ); appPanel.updateOffset( days ); getLatestServiceStats(); } ); $( "#refreshStats" ).click( function () { getLatestServiceStats(); $( 'body , a' ).css( 'cursor', 'wait' ); refreshServiceData(); return false; // prevents link } ); $.jqplot.config.enablePlugins = true; if ( isScript ) { $( "#meters" ).hide(); $( "#osChart" ).hide(); } else { getLatestServiceStats(); } } /** @memberOf ServiceAdmin */ function register_ToolTips() { // return; // $( '[data-qtipLeft!=""]' ).qtip( { // content: { // attr: 'data-qtipLeft', // button: true // }, // style: { // classes: 'qtip-bootstrap' // }, // position: { // my: 'top left', // at: 'bottom left' // } // } ); // $( '[data-qtipRight!=""]' ).qtip( { // content: { // attr: 'data-qtipRight', // button: true // }, // style: { // classes: 'qtip-bootstrap' // }, // position: { // my: 'top right', // at: 'bottom right', // adjust: { x: 0, y: 10 } // } // } ); // // $( '[title != ""]' ).qtip( { // content: { // attr: 'title', // button: true // }, // style: { // classes: 'qtip-bootstrap' // }, // position: { // my: 'top left', // Position my top left... // at: 'bottom left', // adjust: { x: 5, y: 10 } // } // } ); } /** @memberOf ServiceAdmin */ function getLatestServiceStats() { var hostNameArray = new Array(); $( "#instanceTable *.selected" ).each( function () { var serviceNamePort = $( this ).data( "instance" ); var serviceHost = $( this ).data( "host" ); hostNameArray.push( serviceHost ); } ); if ( hostNameArray.length == 0 ) hostNameArray.push( hostName ); if ( $( "#serviceStats" ).is( ":visible" ) ) { osPanel.show( hostNameArray ); } appPanel.show( hostNameArray ); } /** @memberOf ServiceAdmin */ function launchServiceDialog() { if ( isOsOrWrapper ) { launchDefaultService( $( "#instanceTable *.selected" ) ); } else { // Lazy create if ( !alertify.launch ) { var launchDialogFactory = function factory() { return{ build: function () { // Move content from template this.setContent( $( "#launchOptions" ).show()[0] ); }, setup: function () { return { buttons: [{ text: "Close", className: alertify.defaults.theme.cancel, key: 27/* Esc */ }], options: { title: "Service Launch :", resizable: false, movable: false, maximizable: false } }; } }; }; alertify.dialog( 'launch', launchDialogFactory, false, 'alert' ); } var alertsDialog = alertify.launch().show(); } return; } /** @memberOf ServiceAdmin */ function showJdkConfirmDialog() { var message = "<div style='margin: 2em'>Review the logs to verify JDK selection."; message += " Use the edit configuration button to make the change permanent on all instances</div>"; var applyDialog = alertify.confirm( message ); applyDialog.setting( { title: "Caution Advised", 'labels': { ok: 'Proceed Anyway', cancel: 'Cancel request' }, 'onok': function () { var javaOpts = $serviceParameters.val(); javaOpts = javaOpts.replace( "-DcsapJava9", " " ); javaOpts = javaOpts.replace( "-DcsapJava8", " " ); javaOpts = javaOpts.replace( "-DcsapJava7", " " ); var csapJdkParam = "-DcsapJava7"; if ( $( '#jdkSelect' ).val().indexOf( "8" ) != -1 ) { csapJdkParam = "-DcsapJava8"; } else if ( $( '#jdkSelect' ).val().indexOf( "9" ) != -1 ) { csapJdkParam = "-DcsapJava9"; } $serviceParameters.val( csapJdkParam + " " + javaOpts ); }, 'oncancel': function () { alertify.warning( "Reverting java to version in Definition" ); $( "#jdkSelect" ).val( jvms.serviceSelected ); } } ); } /** @memberOf ServiceAdmin */ function showRuntimeConfirmDialog() { var message = "<div style='margin: 2em'>Changing the application runtime can cause the application to fail to start.<br><br> Review the logs to verify."; message += '<br><br><span class="selected">' + 'Use the edit configuration button to make the change permanent on all instances</span></div>'; var applyDialog = alertify.confirm( message ); applyDialog.setting( { title: "Caution Advised", 'labels': { ok: 'Proceed Anyway', cancel: 'Cancel request' }, 'onok': function () { // alertify.notify("Made the change") ; }, 'oncancel': function () { alertify.warning( "Operation Cancelled" ); $( '#runtimeSelect' ).val( serverType ) } } ); } function showJobsDialog() { // Lazy create if ( !alertify.jobs ) { var jobsDialogFactory = function factory() { return{ build: function () { // Move content from template if ( serviceJobDefinition != null ) { $( "#jobDetails" ).text( JSON.stringify( serviceJobDefinition, null, "\t" ) ); } $( "#jobSelect" ).empty(); jQuery( '<option/>', { text: "Log Rotation" } ).appendTo( $( "#jobSelect" ) ); for ( var i = 0; i < serviceJobs.length; i++ ) { jQuery( '<option/>', { text: serviceJobs[i].description } ).appendTo( $( "#jobSelect" ) ); } this.setContent( $( "#jobOptions" ).show()[0] ); }, setup: function () { return { buttons: [{ text: "Cancel", className: alertify.defaults.theme.cancel, key: 27/* Esc */ }], options: { title: "Dummy :", resizable: false, movable: false, maximizable: false } }; } }; }; alertify.dialog( 'jobs', jobsDialogFactory, false, 'alert' ); $( '#doJobsButton' ).click( function () { alertify.closeAll(); //runServiceJobs(); var paramObject = { jobToRun: $( "#jobSelect" ).val() } executeOnSelectedHosts( "runServiceJob", paramObject ); } ); } setAlertifyTitle( "Run Jobs for ", alertify.jobs().show() ); } function showKillDialog() { // Lazy create if ( !alertify.kill ) { var killDialogFactory = function factory() { return{ build: function () { // Move content from template this.setContent( $( "#killOptions" ).show()[0] ); }, setup: function () { return { buttons: [{ text: "Cancel", className: alertify.defaults.theme.cancel, key: 27/* Esc */ }], options: { title: "Service Stop :", resizable: false, movable: false, maximizable: false } }; } }; }; alertify.dialog( 'kill', killDialogFactory, false, 'alert' ); $( '#killButton' ).click( function () { alertify.closeAll(); killService(); } ); $( '#stopButton' ).click( function () { alertify.closeAll(); if ( isOsOrWrapper || serverType == "SpringBoot" ) { stopService(); return; } var message = "Warning: JEE service stops can take a while, and may never terminate the OS process.<br><br>" + "Use the CSAP Host Dashboard and log viewer to monitor progress; use kill if needed.<br><br>" + 'Unless specifically requested by service owner: <br>' + '<div class="news"><span class="stopWarn">kill option is preferred as it is an immediate termination</span></div>'; var applyDialog = alertify.confirm( message ); applyDialog.setting( { title: "Caution Advised", 'labels': { ok: 'Proceed Anyway', cancel: 'Cancel request' }, 'onok': function () { stopService(); }, 'oncancel': function () { alertify.warning( "Operation Cancelled" ); } } ); } ); } setAlertifyTitle( "Stopping", alertify.kill().show() ); } /** @memberOf ServiceAdmin */ function showStartDialog() { // Lazy create if ( !alertify.start ) { var startDialogFactory = function factory() { return{ build: function () { // Move content from template this.setContent( $( "#startOptions" ).show()[0] ); this.setting( { 'onok': startService, 'oncancel': function () { alertify.warning( "Cancelled Request" ); } } ); }, setup: function () { return { buttons: [{ text: "Start Service", className: alertify.defaults.theme.ok }, { text: "Cancel", className: alertify.defaults.theme.cancel, key: 27/* Esc */ } ], options: { title: "Service Start :", resizable: false, movable: false, maximizable: true, } }; } }; }; alertify.dialog( 'start', startDialogFactory, false, 'confirm' ); } if ( serverType == "docker" ) { $serviceParameters.val( JSON.stringify( __dockerConfiguration, "\n", "\t" )) ; $serviceParameters.css("min-height", "25em") ; } var startDialog = alertify.start().show() ; setAlertifyTitle( "Starting", startDialog); if ( serviceName.indexOf( "CsAgent" ) != -1 ) { var message = "Warning - CsAgent should be killed which will trigger auto restart.<br> Do not issue start on CsAgent unless you have confirmed with CSAP team."; alertify.alert( message ); } } var _lastOperation = ""; /** @memberOf ServiceAdmin */ function setAlertifyTitle( operation, dialog ) { var target = $( "#instanceTable *.selected" ).length; if ( target === 1 ) target = hostName; else target += " hosts"; _lastOperation = operation + " Service: " + serviceShortName + " on " + target; dialog.setting( { title: _lastOperation } ); } /** @memberOf ServiceAdmin */ function showDeployDialog() { // Lazy create if ( !alertify.deploy ) { createDeployDialog(); } setAlertifyTitle( "Deploying", alertify.deploy().show() ); // $("#sourceOptions").fadeTo( "slow" , 0.5) ; if ( serviceName.indexOf( "CsAgent" ) != -1 ) { var message = "Please confirm deployment of CsAgent, including update of CS-AP application runtimes and scripts in STAGING/bin"; alertify.confirm( message, function () { alertify.notify( "CsAgent will be updated" ); }, function () { alertify.closeAll() } ); } } /** @memberOf ServiceAdmin */ function createDeployDialog() { console.log( "\n\n Creating dialog" ); var deployTitle = 'Service Deploy: <span title="After build/maven deploy on build host, artifact is deployed to other selected instances">' + hostName + "</span>" var okFunction = function () { var deployChoice = $( 'input[name=deployRadio]:checked' ).val(); // alertify.success("Deployment using: " // + // deployChoice); alertify.closeAll(); _resultsDialog=null ; showResultsDialog( "Deploy" ); $resultsPre.html( "Deploy Request is being processed\n" ); $( 'body' ).css( 'cursor', 'wait' ); displayResults( "Initiating build" ); switch ( deployChoice ) { case "maven": if ( $( "#deployServerServices input:checked" ).length == 0 ) { deployService( true, serviceName ); } else { $( "#deployServerServices input:checked" ).each( function () { var curName = $( this ).attr( "name" ); deployService( true, curName ); } ); // var msg = "Multiple Services selected for deployment, only the status of the final build will be shown" // + " Once the final deployment has completed, then the start can be issued." // alertify.csapWarning( msg ); } break; case "source": deployService( false, serviceName ); break; case "upload": uploadWar( ); break; } } var deployDialogFactory = function factory() { return{ build: function () { // Move content from template this.setContent( $( "#deployDialog" ).show()[0] ); this.setting( { 'onok': okFunction, 'oncancel': function () { alertify.warning( "Cancelled Request" ); } } ); }, setup: function () { return { buttons: [{ text: "Deploy Service", className: alertify.defaults.theme.ok }, { text: "Cancel", className: alertify.defaults.theme.cancel, key: 27/* Esc */ } ], options: { title: deployTitle, resizable: false, movable: false, maximizable: false } }; } }; }; alertify.dialog( 'deploy', deployDialogFactory, false, 'confirm' ); if ( serverType == "docker" ) { $("#dockerImageVersion").val( __dockerConfiguration.image ) ; $("#osDeployOptions").hide() ; } else { $("#dockerDeployOptions").hide() ; } $( 'input[name=deployRadio]' ).change( function () { $( "#osDeployOptions >div" ).hide(); var $selectedDiv = $( "#" + $( this ).val() + "Options" ); $selectedDiv.show(); } ); $( 'input[name=deployRadio]:checked' ).trigger( "change" ); $( '#scmPass' ).keypress( function ( e ) { if ( e.which == 13 ) { $( '.ajs-buttons button:first', $( "#deployDialog" ).parent().parent().parent() ) .trigger( "click" ); } } ); $( '#cleanServiceBuild' ).click( function () { cleanServiceBuild( false ); return false; // prevents link } ); $( '#cleanGlobalBuild' ).click( function () { cleanServiceBuild( true ); return false; // prevents link } ); } /** @memberOf ServiceAdmin */ function displayResults( resultsJson, append ) { //console.log("results", resultsJson, append) ; var results = JSON.stringify( resultsJson, null, "\t" ); results = results.replace( /\\n/g, "<br />" ); if ( !append ) { $resultsPre.html( "" ); $( 'body' ).css( 'cursor', 'default' ); refreshServiceData(); } $resultsPre.append( results ); // needed when results is small showResultsDialog( "Updating" ); } /** @memberOf ServiceAdmin */ function displayHostResults( host, serviceInstance, command, resultsJson, currentCount, totalCount ) { var results = JSON.stringify( resultsJson, null, "\t" ); results = results.replace( /\\n/g, "<br />" ); results = results.replace( /\\t/g, '&#9;' ); var isDetailsShown = false; if ( results.indexOf( "__ERROR" ) != -1 || results.indexOf( "__WARN" ) != -1 ) { isDetailsShown = true; } var resultProgressMessage = ""; if ( currentCount != 0 ) resultProgressMessage = currentCount + " of " + totalCount; if ( command == "startServer" || command == "killServer" ) { var $console = $resultsPre; if ( isDetailsShown ) { var $commandOutput = jQuery( '<div/>', { id: serviceInstance + "Output", class: "note", html: results } ).css( "font-size", "0.9em" ).appendTo( $console ); $commandOutput.css( "display", "block" ); } var progress = '\n' + resultProgressMessage + " : " + host + ' : ' + command + " on " + serviceInstance + ' has been queued.'; $console.append( progress ); //var launchResponse="Start" var $scriptLink = jQuery( '<a/>', { href: "#scriptOutput", class: "simple ", text: "Command Output" } ).appendTo( $console ); $scriptLink.click( function () { var urlAction = agentHostUrlPattern.replace( /CSAP_HOST/g, host ); var logname = serviceInstance + "_start.log&"; if ( command == "killServer" ) { logname = serviceInstance + "_kill.log&" } urlAction += "/file/FileMonitor?serviceName=" + serviceInstance + "&hostName=" + host + "&ts=1&fileName=//" + logname + "isLogFile=false&"; openWindowSafely( urlAction, "_blank" ); return false; } ); var $serviceTail = jQuery( '<a/>', { href: "#tailLogs", class: "simple", text: "Service Logs" } ).appendTo( $console ); $serviceTail.click( function () { var urlAction = agentHostUrlPattern.replace( /CSAP_HOST/g, host ); urlAction += "/file/FileMonitor?serviceName=" + serviceInstance + "&hostName=" + host + "&isLogFile=true&"; openWindowSafely( urlAction, "_blank" ); return false; } ); } else { var $console = $resultsPre; var progress = '\n' + resultProgressMessage + " : " + host + ' : ' + command + " on " + serviceInstance + ' has completed.'; $console.append( progress ); var $commandLink = jQuery( '<a/>', { href: "#scriptOutput", class: "simple ", text: "Results" } ).appendTo( $console ); var $commandOutput = jQuery( '<div/>', { id: serviceInstance + "Output", class: "note", html: results } ).css( "font-size", "0.9em" ).appendTo( $console ); if ( isDetailsShown ) { $commandOutput.css( "display", "block" ); } else { $commandOutput.css( "display", "none" ); } $commandLink.click( function () { if ( $commandOutput.is( ":visible" ) ) { $commandOutput.hide(); restoreResultsDialog(); } else { $commandOutput.css( "display", "block" ); maximizeResultsDialog(); } return false; // prevents link } ); } showResultsDialog( command ); if ( !isDetailsShown && currentCount == totalCount ) { restoreResultsDialog(); showResultsDialog( command ); } } /** @memberOf ServiceAdmin */ function maximizeResultsDialog() { var targetWidth = $( window ).outerWidth( true ) - 100; var targetHeight = $( window ).outerHeight( true ) - 100; _resultsDialog.resizeTo( targetWidth, targetHeight ) } /** @memberOf ServiceAdmin */ function restoreResultsDialog() { _resultsDialog.show(); } /** @memberOf ServiceAdmin */ function showResultsDialog( commandName ) { console.log("commandName: ", commandName) ; // if dialog is active, just updated scroll and return if ( _resultsDialog != null ) { var heightToScroll = $resultsPre[0].scrollHeight; // console.log("Scrolling to bottom: " + heightToScroll) ; $( ".ajs-content" ).scrollTop( heightToScroll ); return; } console.log("building results dialog: ", commandName) ; if ( !alertify.results ) { alertify.dialog( 'results', function factory() { return{ build: function () { this.setContent( $( "#resultsSection pre" ).show()[0] ); } }; }, false, 'alert' ); } _resultsDialog = alertify.results().show(); var targetWidth = $( window ).outerWidth( true ) - 100; var targetHeight = $( window ).outerHeight( true ) - 100; var dialogTitle = commandName; if ( _lastOperation != "" ) { dialogTitle = _lastOperation; _lastOperation = ""; } _resultsDialog.setting( { title: "Results: " + dialogTitle, resizable: true, movable: false, 'label': "Close after reviewing output", 'onok': function () { //$( "#resultsSection" ).append( $resultsPre ); //_resultsDialog = null; } } ); // resultsDialog.resizeTo(targetWidth, targetHeight) } /** @memberOf ServiceAdmin */ function deployService( isMavenDeploy, deployServiceName ) { var targetScpHosts = new Array(); // $("#instanceTable tbody tr").addClass("selected") ; $( "#instanceTable *.selected" ).each( function () { // alert( Checking ) if ( $( this ).data( "host" ) != hostName ) targetScpHosts.push( $( this ).data( "host" ) ); } ); var paramObject = { scmUserid: $( "#scmUserid" ).val(), scmPass: $( "#scmPass" ).val(), scmBranch: $( "#scmBranch" ).val(), commandArguments: $serviceParameters.val(), runtime: $( "#runtimeSelect" ).val(), targetScpHosts: targetScpHosts, serviceName: deployServiceName, hostName: hostName }; if ( serverType == "docker" ) { $.extend( paramObject, { dockerImage: $("#dockerImageVersion").val(), mavenDeployArtifact: $("#dockerImageVersion").val() } ); } else if ( isMavenDeploy ) { // paramObject.push({noDeploy: "noDeploy"}) ; var artifact = $( "#mavenArtifact" ).val(); $.extend( paramObject, { mavenDeployArtifact: artifact } ); console.log( "Number of ':' in artifact", artifact.split( ":" ).length ); if ( artifact.split( ":" ).length != 4 ) { $( "#mavenArtifact" ).css( "background-color", "#f5bfbf" ); alertify.csapWarning( "Unexpected format of artifact. Typical is a:b:c:d eg. org.csap:BootEnterprise:1.0.27:jar" ); //return ; } else { $( "#mavenArtifact" ).css( "background-color", "#CCFFE0" ); } } else { var scmCommand = $( "#scmCommand" ).val(); if ( scmCommand.indexOf( "deploy" ) == -1 && $( "#isScmUpload" ).is( ':checked' ) ) { scmCommand += " deploy"; } $.extend( paramObject, { scmCommand: scmCommand } ); } if ( $( "#deployServerServices input:checked" ).length > 0 ) { $( "#deployStart" ).prop( 'checked', false ); // default params are used when multistarts delete paramObject.commandArguments; delete paramObject.runtime; delete paramObject.scmCommand; delete paramObject.mavenDeployArtifact; $.extend( paramObject, { mavenDeployArtifact: "default" } ); } if ( $( "#isHotDeploy" ).is( ':checked' ) ) { $.extend( paramObject, { hotDeploy: "hotDeploy" } ); } var buildUrl = serviceBaseUrl + "/rebuildServer"; // buildUrl = "http://yourlb.yourcompany.com/admin/services" + // "/rebuildServer" ; $.post( buildUrl, paramObject ) .done( function ( results ) { displayHostResults( hostName, deployServiceName, "Build Started", results, 0, 0 ); // $("#resultPre div").first().show() ; $( "#resultPre div" ).first().css( "display", "block" ); fileOffset = "-1"; _deploySuccess = false; getUpdatedBuildOutput( deployServiceName ); } ) .fail( function ( jqXHR, textStatus, errorThrown ) { if ( deployServiceName.indexOf( "CsAgent" ) != -1 ) { alert( "CsAgent can get into race conditions...." ); var numHosts = $( "#instanceTable *.selected" ).length; if ( numHosts > 1 && results.indexOf( "BUILD__SUCCESS" ) != -1 ) { isBuild = true; // rebuild autostarts startService(); } else { $( 'body' ).css( 'cursor', 'default' ); } } else { handleConnectionError( hostName + ":" + rebuild, errorThrown ); } } ); } var fileOffset = "-1"; /** @memberOf ServiceAdmin */ function getUpdatedBuildOutput( nameOfService ) { clearTimeout( checkForChangesTimer[nameOfService] ); // $('#serviceOps').css("display", "inline-block") ; // console.log("Hitting Offset: " + fileOffset) ; var requestParms = { serviceName: nameOfService, hostName: hostName, logFileOffset: fileOffset }; $.getJSON( deployProgressUrl, requestParms ) .done( function ( hostJson ) { buildOutputSuccess( hostJson, nameOfService ); } ) .fail( function ( jqXHR, textStatus, errorThrown ) { handleConnectionError( "Retrieving changes for file " + $( "#logFileSelect" ).val(), errorThrown ); } ); } var checkForChangesTimer = new Object(); var warnRe = new RegExp( "warning", 'gi' ); var errorRe = new RegExp( "error", 'gi' ); var infoRe = new RegExp( "info", 'gi' ); var debugRe = new RegExp( "debug", 'gi' ); var winHackRegEx = new RegExp( "\r", 'g' ); var newLineRegEx = new RegExp( "\n", 'g' ); var refreshTimer = 2 * 1000; /** @memberOf ServiceAdmin */ function buildOutputSuccess( changesJson, nameOfService ) { //$resultsPre.parent().append( $("#resultsLoading") ) ; $("#resultsLoading").show() if ( changesJson.error || changesJson.contents == undefined ) { console.log( "No results found, rescheduling" ); checkForChangesTimer[nameOfService] = setTimeout( function () { getUpdatedBuildOutput( nameOfService ); }, refreshTimer ); return; } // $("#"+ hostName + "Result").append("<br>peter") ; // console.log( JSON.stringify( changesJson ) ) ; // console.log("Number of changes :" + changesJson.contents.length); for ( var i = 0; i < changesJson.contents.length; i++ ) { var fileChanges = changesJson.contents[i]; var htmlFormated = fileChanges.replace( warnRe, '<span class="warn">WARNING</span>' ); htmlFormated = htmlFormated.replace( errorRe, '<span class="error">ERROR</span>' ); htmlFormated = htmlFormated.replace( debugRe, '<span class="debug">DEBUG</span>' ); htmlFormated = htmlFormated.replace( infoRe, '<span class="info">INFO</span>' ); htmlFormated = htmlFormated.replace( /\\n/g, "<br />" ); // htmlFormated = htmlFormated.replace(winHackRegEx, '') ; // htmlFormated = htmlFormated.replace(newLineRegEx, '<br>') ; // displayResults( '<span class="chunk">' + htmlFormated + // "</span>", true); var $consoleOutput = $( "#" + nameOfService + "Output" ); $consoleOutput.append( '<span class="chunk">' + htmlFormated + "</span>" ); // TOKEN may get split in lines, so check text results for success and complete tokens var resultsSofar = $consoleOutput.text(); if ( resultsSofar.length > 100 ) { resultsSofar = resultsSofar.substring( resultsSofar.length - 100 ); } if ( fileChanges.contains( "BUILD__SUCCESS" ) || resultsSofar.contains( "BUILD__SUCCESS" ) ) { _deploySuccess = true; } if ( fileChanges.contains( "__COMPLETED__" ) || resultsSofar.contains( "__COMPLETED__" ) ) { $("#resultsLoading").hide() ; if ( _deploySuccess ) { isBuild = true; // only going to restart the other // VMs $consoleOutput.hide(); if ( $( "#deployStart" ).is( ':checked' ) ) { startService(); } else { $resultsPre.append( '\n<img class="but" height="14" src="images/16x16/note.png">' + nameOfService + " Deploy autostart is not selected. Service may now be started from console\n" ); } } else { $resultsPre.append( '\n<img class="but" height="14" src="images/16x16/warning.png">' + nameOfService + " Warning - did not find BUILD__SUCCESS in output\n" ); // displayResults( "\n\n", true) ; // alertify.alert("Warning - did not find // BUILD__SUCCESS in // output") ; } showResultsDialog( "Updating" ); return; } } showResultsDialog( "Updating" ); maximizeResultsDialog(); fileOffset = changesJson.newOffset; // $("#fileSize").html("File Size:" + changesJson.currLength) ; checkForChangesTimer[nameOfService] = setTimeout( function () { getUpdatedBuildOutput( nameOfService ); }, refreshTimer ); } /** * * Ajax call to kill service * */ /** @memberOf ServiceAdmin */ function killService() { var paramObject = new Object(); if ( $( "#isSuperClean" ).is( ':checked' ) ) { // paramObject.push({noDeploy: "noDeploy"}) ; $.extend( paramObject, { clean: "super" } ); } else { if ( $( "#isClean" ).is( ':checked' ) ) { // paramObject.push({noDeploy: "noDeploy"}) ; $.extend( paramObject, { clean: "clean" } ); } if ( $( "#isSaveLogs" ).is( ':checked' ) ) { // paramObject.push({noDeploy: "noDeploy"}) ; $.extend( paramObject, { keepLogs: "keepLogs" } ); } } var message = '<div class="myAlerts">' + serviceName + " is configured with warnings to prevent corruption caused by sending:\n\t kill -9"; message += "<br><br>It is strongly recommended to issue a stop rather then a kill in order for graceful shutdown to occur."; message += "<br><br> Failing to stop the service gracefully may lead to corruption."; message += "<br><br> Click OK to proceed anyway, or cancel to use the stop button.</div>"; if ( isShowWarning ) { var applyDialog = alertify.confirm( message ); applyDialog.setting( { title: "Caution Advised", 'labels': { ok: 'Proceed Anyway', cancel: 'Cancel request' }, 'onok': function () { executeOnSelectedHosts( "killServer", paramObject ); }, 'oncancel': function () { alertify.warning( "Operation Cancelled" ); } } ); } else { executeOnSelectedHosts( "killServer", paramObject ); } } var isBuild = false; /** @memberOf ServiceAdmin */ function executeOnSelectedHosts( command, paramObject ) { // alert("numSelected: " + numHosts) ; // nothing to do on a single node build if ( !isBuild ) $resultsPre.html( "" ); $resultsPre.append( command + " Request initiated\n" ); $( 'body' ).css( 'cursor', 'wait' ); var numResults = 0; // Now run through the additional hosts selected var postCommandToServerFunction = function ( serviceInstance, serviceHost ) { var hostParamObject = new Object(); if ( $( "#isHotDeploy" ).is( ':checked' ) ) { $.extend( paramObject, { hotDeploy: "hotDeploy" } ); } $.extend( hostParamObject, paramObject, { hostName: serviceHost, serviceName: serviceInstance } ); $.post( serviceBaseUrl + "/" + command, hostParamObject, totalCommandsToRun ) .done( function ( results ) { // displayResults(results); numResults++; displayHostResults( serviceHost, serviceInstance, command, results, numResults, totalCommandsToRun ); isBuild = false; // console.log("numResults: " + // numResults + " // numHosts:" + numHosts) ; if ( numResults >= totalCommandsToRun ) { $( 'body' ).css( 'cursor', 'default' ); refreshServiceData(); } } ) .fail( function ( jqXHR, textStatus, errorThrown ) { //console.log( JSON.stringify( jqXHR, null, "\t" )); //console.log( JSON.stringify( errorThrown, null, "\t" )); handleConnectionError( serviceHost + ":" + command, errorThrown ); } ); } // var $multiServiceContainer = $( "#" + command + "Services" ); var numServices = $( "input:checked", $multiServiceContainer ).length; if ( numServices == 0 ) { var totalCommandsToRun = $( "#instanceTable *.selected" ).length; $( "#instanceTable *.selected" ).each( function () { var serviceNamePort = $( this ).data( "instance" ); var serviceHost = $( this ).data( "host" ); postCommandToServerFunction( serviceNamePort, serviceHost, totalCommandsToRun ); } ); } else { var totalCommandsToRun = $( "#instanceTable *.selected" ).length * numServices; $( "#instanceTable *.selected" ).each( function () { var serviceHost = $( this ).data( "host" ); $( "input:checked", $multiServiceContainer ).each( function () { var serviceMulti = $( this ).attr( "name" ); // default params are used when multistarts delete paramObject.runtime; delete paramObject.commandArguments; postCommandToServerFunction( serviceMulti, serviceHost, totalCommandsToRun ); } ); } ); } } var t1 = null, t2 = null, t3 = null, t4 = null; /** @memberOf ServiceAdmin */ function refreshServiceData() { // alertify.notify("Refreshing Data - Note that Sockets and Disk are // only // checked every few minutes due to OS cost. Use CSAP dashboard for // direct // access") ; clearTimeout( t1 ); clearTimeout( t2 ); clearTimeout( t3 ); clearTimeout( t4 ); t1 = setTimeout( function () { serviceInstancesGet( true ); }, 1 * 1000 ); t2 = setTimeout( function () { serviceInstancesGet( true ); }, 10 * 1000 ); t3 = setTimeout( function () { serviceInstancesGet( true ); }, 20 * 1000 ); t4 = setTimeout( function () { serviceInstancesGet( true ); }, 30 * 1000 ); } /** * * Ajax call to stop service * */ /** @memberOf ServiceAdmin */ function stopService() { var paramObject = { serviceName: serviceName }; executeOnSelectedHosts( "stopServer", paramObject ); } /** * * Ajax call to stop service * */ /** @memberOf ServiceAdmin */ function showHostMessageDialog() { var message = "<div style='margin: 2em'>Enter the updated message of the day:<div>"; var motdDialog = alertify.prompt( message, $( "#motd" ).text() ); motdDialog.setting( { title: "Message Of the Day", 'labels': { ok: 'Change Message', cancel: 'Cancel' }, 'onok': function ( evt, value ) { var paramObject = { motd: value, hostName: hostName }; $.post( serviceBaseUrl + "/updateMotd", paramObject, function ( results ) { displayResults( results ); } ); }, 'oncancel': function () { alertify.warning( "Update cancelled" ); } } ); } /** * * Ajax call to stop service * */ /** @memberOf ServiceAdmin */ function unDeployService() { $resultsPre.html( "Request is being processed\n" ); $( 'body' ).css( 'cursor', 'wait' ); var paramObject = { serviceName: serviceName, warSelect: $( "#undeploySelect" ).val() }; executeOnSelectedHosts( "undeploy", paramObject ); $( '#undeploySelect' ).val( "select" ); // $.post( serviceBaseUrl + "/undeploy", paramObject, // function (results) { // // displayResults( results ); // // } ); } /** @memberOf ServiceAdmin */ function launchHelp( helpButtonObj ) { var url = helpButtonObj.attr( "href" ); if ( url == "" ) { alertMessage = "No help url configured for service. Request service team contact cluster admin with help url."; alertify.alert( alertMessage ); return; } openWindowSafely( url, serviceName + "Help" ); } /** * Context menu also launches urls - but only the default LB. This * function enables user to select different LBs. Eg. the embedded http * in tomcat, or via different httpd apache configurations. * * @param buttonObject */ /** @memberOf ServiceAdmin */ function launchService( buttonObject ) { var buttonUrl = buttonObject.attr( 'href' ); console.log( " buttonUrl: " + buttonUrl ) if ( buttonUrl == "default" ) { // use default launch code launchDefaultService( $( "#instanceTable *.selected" ) ); return } var jqueryRows = $( "#instanceTable *.selected" ); if ( !confirmMaxItem( jqueryRows ) ) return; jqueryRows.each( function ( index ) { var host = $( this ).data( "host" ); var port = $( this ).data( "port" ); var context = $( this ).data( "context" ); var urlAction = buttonUrl + "/" + context; if ( context.charAt( serviceContext.length - 1 ) != "/" ) urlAction += "/"; openWindowSafely( urlAction, context + host + "Launch" ); } ); } /** * * Ajax call to trigger jmeter * */ /** @memberOf ServiceAdmin */ function launchJMeter() { _resultsDialog=null ; showResultsDialog( "Jmeter launch" ); var message = "\nRequest is being processed\n"; displayResults( message, false ); $( 'body' ).css( 'cursor', 'wait' ); var paramObject = { serviceName: serviceName, hostName: hostName }; $.post( serviceBaseUrl + "/jmeter", paramObject, function ( results ) { displayResults( results ); showResultsDialog(); } ); } /** * * Ajax call to clean build and maven caches * */ /** @memberOf ServiceAdmin */ function cleanServiceBuild( isGlobal ) { _resultsDialog=null ; displayResults( "Cleaning service sources files" ); $( 'body' ).css( 'cursor', 'wait' ); var paramObject = { serviceName: serviceName, hostName: hostName }; if ( isGlobal ) { $.extend( paramObject, { global: "GLOBAL" } ); } $.post( serviceBaseUrl + "/purgeDeployCache", paramObject, function ( results ) { displayResults( results, false ); } ); } /** * * This sends an ajax http get to server to start the service * */ /** @memberOf ServiceAdmin */ function startService() { var paramObject = new Object(); if ( $( "#noDeploy" ).is( ':checked' ) ) { // paramObject.push({noDeploy: "noDeploy"}) ; $.extend( paramObject, { noDeploy: "noDeploy" } ); } if ( $( "#isDebug" ).is( ':checked' ) && $serviceParameters.val().indexOf( "agentlib" ) == -1 ) { // paramObject.push({noDeploy: "noDeploy"}) ; $serviceParameters.val( $serviceParameters.val() + " -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=" + debugPort ); } if ( $( "#isJmc" ).is( ':checked' ) && $serviceParameters.val().indexOf( "FlightRecorder" ) == -1 ) { // paramObject.push({noDeploy: "noDeploy"}) ; $serviceParameters.val( $serviceParameters.val() + " -XX:+UnlockCommercialFeatures -XX:+FlightRecorder -XX:+UnlockDiagnosticVMOptions -XX:+DebugNonSafepoints" ); } if ( $( "#isGarbageLogs" ).is( ':checked' ) && $serviceParameters.val().indexOf( "PrintGCDetails" ) == -1 ) { // paramObject.push({noDeploy: "noDeploy"}) ; $serviceParameters.val( $serviceParameters.val() + gcParams ); } if ( $( "#isInlineGarbageLogs" ).is( ':checked' ) && $serviceParameters.val().indexOf( "PrintGCDetails" ) == -1 ) { // paramObject.push({noDeploy: "noDeploy"}) ; $serviceParameters.val( $serviceParameters.val() + gcInlineParams ); } $.extend( paramObject, { commandArguments: $serviceParameters.val(), runtime: $( "#runtimeSelect" ).val() } ); if ( $serviceParameters.val().indexOf( "agentlib" ) != -1 ) { alertify.alert( 'Service started in debug mode, configure your ide with host: <div class="note">' + hostName + '</div> debug port: <div class="note">' + debugPort + '</div><br><br> Jvm started using options: <br><div class="note">' + $serviceParameters.val() + '</div>' ); $( ".alertify-inner" ).css( "text-align", "left" ); $( ".alertify" ).css( "width", "800px" ); $( ".alertify" ).css( "margin-left", "-400px" ); } executeOnSelectedHosts( "startServer", paramObject ); } var gcParams = " -XX:+PrintGCDetails -XX:+PrintGCDateStamps -Xloggc:logs/garbageCollect.log -XX:+UseGCLogFileRotation -XX:NumberOfGCLogFiles=2 -XX:GCLogFileSize=5M "; var gcInlineParams = " -XX:+PrintGCDetails -XX:+PrintGCDateStamps"; /** @memberOf ServiceAdmin */ function uploadWar() { _resultsDialog=null ; showResultsDialog( "Uploading artifact: " + $( "#uploadOptions :file" ).val() ); displayResults( "" ); $resultsPre.append( '<div class="progress"><div class="bar"></div ><div class="percent">0%</div ></div>' ); $( "#upService" ).val( serviceName ); // <input type="hidden " name="hostName" value="" /> $( "#upHosts" ).empty(); $( "#instanceTable *.selected" ).each( function () { var reqHost = $( this ).data( "host" ); // (this).data("host") $( "#upHosts" ).append( '<input type="hidden" name="hostName" value="' + reqHost + '" />' ); // $.extend(formParams, { // hostName : reqHost // }); } ); var bar = $( '.bar' ); var percent = $( '.percent' ); var status = $( '#status' ); var formOptions = { beforeSend: function () { $( 'body' ).css( 'cursor', 'wait' ); status.empty(); var percentVal = '0%'; bar.width( percentVal ); percent.html( "Upload Progress: " + percentVal ); }, uploadProgress: function ( event, position, total, percentComplete ) { var percentVal = percentComplete + '%'; bar.width( percentVal ); percent.html( "Upload Progress: " + percentVal ); }, success: function () { var percentVal = '100%'; bar.width( percentVal ); percent.html( "Upload Progress: " + percentVal ); $( ".progress" ).hide(); }, complete: function ( xhr ) { var percentVal = '100%'; bar.width( percentVal ); percent.html( "Upload Progress: " + percentVal ); $( ".progress" ).hide(); // status.html(xhr.responseText); // $("#resultPre").html( xhr.responseText ) ; displayResults( xhr.responseText ); } }; $( '#uploadOptions form' ).ajaxSubmit( formOptions ); } /** @memberOf ServiceAdmin */ function toggleResultsButton( toggleButton ) { // $("#resultPre").css('height', 'auto'); alertify.success( "toggleResults" ); } var serviceTimer = 0; /** @memberOf ServiceAdmin */ function serviceInstancesGet( blocking ) { clearTimeout( serviceTimer ); var serviceNameStrippedOfPort = serviceName.substr( 0, serviceName .indexOf( "_" ) ); $.getJSON( serviceBaseUrl + "/getServiceInstances", { "serviceName": serviceNameStrippedOfPort, "blocking": blocking, "releasePackage": releasePackage } ) .done( function ( loadJson ) { serviceInstanceSuccess( loadJson ); if ( blocking ) { setTimeout( function () { $( 'body, a' ).css( 'cursor', 'default' ); getLatestServiceStats(); }, 2000 ); } serviceTimer = setTimeout( function () { serviceInstancesGet( false ); }, 60000 ); } ) .fail( function ( jqXHR, textStatus, errorThrown ) { handleConnectionError( "Retrieving service instances", errorThrown ); } ); } var hostInit = false; // hostSelect is stateful, only inited once /** @memberOf ServiceAdmin */ function serviceInstanceSuccess( serviceInstancesJson ) { var tableHtml = ""; // for (var serviceInstance in loadJson.instances ) { // alert( loadJson.instances.length ) ; $( "#primaryHost" ).html( hostName ); // $( "#primaryInstance" ).html( serviceShortName ); $( "#instanceTableDiv" ).show(); serviceInstancesJson.serviceStatus.sort( function ( a, b ) { if ( a.host < b.host ) return -1; else return 1; } ); var $instanceTableBody = $( "#instanceTable tbody" ); $( 'tr input', $instanceTableBody ).unbind( 'click' ); $( 'tr input', $instanceTableBody ).unbind( 'hover' ); $( "#undeploySelect" ).empty(); var optionItem = jQuery( '<option/>', { value: "select", text: "Select Version to remove" } ); $( "#undeploySelect" ).append( optionItem ); for ( var i = 0; i < serviceInstancesJson.serviceStatus.length; i++ ) { var serviceOnHost = serviceInstancesJson.serviceStatus[i]; $instanceTableBody.append( buildServiceInstanceRow( serviceOnHost ) ); } checkForServiceWarnings( serviceInstancesJson ); hostInit = true; // $('#instanceTable tbody tr').each( function( index ) { // registerRowEvents( $(this)); }) ; $( '#instanceTable tbody tr input' ).click( function () { if ( $( this ).prop( 'checked' ) == true ) { $( this ).parent().parent().addClass( "selected" ); } else { $( this ).parent().parent().removeClass( "selected" ); } } ); // alert("setting selected"); $( currentInstance ).addClass( "selected" ); $( '#instanceTable tbody tr.selected input' ).prop( 'checked', true ); $( '#instanceTable tbody tr' ).hover( function () { lastInstanceRollOver = $( this ); } ); $( 'input', currentInstance ).each( function ( index ) { $( this ).prop( 'disabled', true ); $( this ).prop( 'title', "Click another service to make it the master" ); } ); $( '#instanceTable .simple' ).click( function () { var rowObject = $( this ).parent().parent(); var host = rowObject.data( 'host' ); var serviceName = rowObject.data( 'instance' ); var url = "admin?serviceName=" + serviceName + "&hostName=" + host + "&releasePackage=" + releasePackage; document.location.href = url; return false; // prevents link } ); } var _isShowServiceWarningOnce = true; /** @memberOf ServiceAdmin */ function checkForServiceWarnings( serviceInstancesJson ) { if ( isScript ) { $( "#serviceCpu" ).hide(); $( "#osChart" ).hide(); $( "#osLearnMore" ).show(); } else if ( isOs ) { $( "#opsButtons" ).html( '<div class="note">Server type is OS, operations may be executed via the VM Admin.</div>' ); $( "#meters" ).hide(); } else if ( _isShowServiceWarningOnce ) { _isShowServiceWarningOnce = false; showTechnologyScore( serviceInstancesJson ); var limitsExceeded = ""; var maxDiskInMb = resourceLimits[ "diskUtil" ]; for ( var i = 0; i < serviceInstancesJson.serviceStatus.length; i++ ) { var serviceInstance = serviceInstancesJson.serviceStatus[i]; if ( parseInt( serviceInstance.diskUtil ) > maxDiskInMb ) { limitsExceeded += " " + serviceInstance.host + ": " + serviceInstance.diskUtil + " MB"; } } if ( limitsExceeded != "" ) { // console.log("serviceInstance.diskUtil: " + // serviceInstance.diskUtil + // " maxDisk " + maxDisk) ; var $warnContainer = jQuery( '<div/>', { } ); var $warning = jQuery( '<div/>', { } ) .css( "font-size", "0.8em" ) .appendTo( $warnContainer ); $warning.append( '<img style="vertical-align: middle" src="images/error.gif">' ); $warning.append( 'One or more of the ' + serviceShortName + ' instances exceeds disk limit of: ' + maxDiskInMb + " MB<br>" ); if ( svcUser == "null" ) { $warning.append( '<div class="error" style="text-align: left"> Run away disk usage may ' + 'trigger a cascading failure of other services. Auto shutdown will be initiated' + ' once breach threshold is exceeded on the following:<br>' + limitsExceeded + ' </div>' ); } else { $warning.append( '<div class="error" style="text-align: left"> This could case VM disk to fill causing service interruption: <br>' + limitsExceeded + ' </div>' ); } $warning.append( '<br>Verify application is working, log rotations configured, etc. If neededed, update the limits, or kill/clean the service. ' ); $warning.append( jQuery( '<a/>', { class: "simple", title: "Click to learn more about monitoring configuration", target: "_blank", href: "https://github.com/csap-platform/csap-core/wiki#updateRefCS-AP+Monitoring", text: "Visit CS-AP Monitoring" } ).css( "display", "inline" ) ); alertify.csapWarning( $warnContainer.html() ); } } } function addTechnologyError( description ) { console.log( "Adding: " + description ); $( ".eolItems" ).append( jQuery( '<div/>', { class: "noteHighlight", text: description } ) ); } function showTechnologyScore( serviceInstancesJson ) { var numEol = 0; if ( customMetrics == null ) { numEol += 2; addTechnologyError( "Performance Metrics Not Configured" ); } if ( (!isSkipJmx) && jvms.serviceSelected.indexOf( "7" ) != -1 ) { numEol += 2; addTechnologyError( "Java 7" ); } if ( serverType.contains( "cssp-" ) ) { numEol += 3; } //if ( serverType.contains( "cssp-" ) || serverType == "tomcat7.x"|| serverType == "tomcat8.x" ) { if ( isTomcatEol ) { numEol += 2; addTechnologyError( serverType ); } for ( var i = 0; i < serviceInstancesJson.serviceStatus.length; i++ ) { var serviceInstance = serviceInstancesJson.serviceStatus[i]; if ( serviceInstance.host == hostName && serviceInstance.port == httpPort ) { if ( serviceInstance.eolJars && serviceInstance.eolJars.length > 0 ) { numEol += serviceInstance.eolJars.length; addTechnologyError( JSON.stringify( serviceInstance.eolJars, null, "\t" ) ); } break; } } var $statusButton = $( "#eolWarningButton" ); var $statusImages = $( "span", $statusButton ); if ( numEol >= 4 ) { $statusButton.show().click( function () { alertify.csapWarning( $( "#eolWarningsMessage" ).html() ); } ); $statusButton.removeClass( "ok" ).addClass( "warning" ); $( "span", $statusButton ).text( "Warnings" ); jQuery( '<img/>', { src: baseUrl + "images/16x16/warning.png" } ).appendTo( $( "span", $statusButton ) ); $( "span", $statusButton ).addClass( "attention" ); } else if ( numEol > 0 ) { var maxStars = $( "img", $statusImages ).size(); console.log( "maxStars: " + maxStars ); if ( numEol > maxStars ) numEol = maxStars; for ( var i = 0; i < numEol; i++ ) { console.log( "updating: " + i ); $( ":nth-child(" + (maxStars - i) + ")", $statusImages ).attr( "src", baseUrl + "images/starBlack.png" ); } //$statusImages.empty() ; // $( "#eolSoftware" ).show(); $statusButton.show().click( function () { alertify.csapWarning( $( "#eolWarningsMessage" ).html() ); } ); $statusButton.removeClass( "ok" ).addClass( "warning" ); // var } else { $statusButton.show(); $statusButton.removeClass( "warning" ).addClass( "ok" ); } } /** @memberOf ServiceAdmin */ function buildServiceInstanceRow( serviceInstance ) { var instancePort = serviceInstance.serviceName + "_" + serviceInstance.port; var rowClass = ""; var currentId = serviceInstance.host + "_" + instancePort; if ( $( "#" + currentId ).first().hasClass( "selected" ) ) { rowClass = "selected"; } $( "#" + currentId ).remove(); // get rid of previous if ( instancePort == serviceName && serviceInstance.host == hostName ) { updateUIForInstance( serviceInstance ); } var $instanceRow = jQuery( '<tr/>', { id: currentId, class: rowClass, title: serviceInstance.scmVersion, "data-host": serviceInstance.host, "data-instance": instancePort, "data-context": serviceInstance.context, "data-launchurl": serviceInstance.launchUrl, "data-jmx": serviceInstance.jmx, "data-jmxrmi": serviceInstance.jmxrmi, "data-port": serviceInstance.port } ); // $instanceRow.qtip( { // content: { // attr: 'title', // title: serviceInstance.serviceName + " Deployment Status", // button: 'Close' // }, // style: { // classes: 'qtip-bootstrap versionTip' // }, // position: { // my: 'bottom left', // Position my top left... // at: 'bottom right', // adjust: { // x: +5 // } // } // } ); // .qtip( { // content: { // attr: 'title', // button: true // }, // style: { // classes: 'qtip-bootstrap' // }, // position: { // my: 'bottom left', // at: 'bottom right' // } // } ); var $checkCol = jQuery( '<td/>', { } ); $instanceRow.append( $checkCol ); var $instanceCheck = jQuery( '<input/>', { class: "instanceCheck", type: "checkbox", title: "Select to include in operations" } ); $instanceCheck.change( function () { serviceGraph.updateHosts(); getLatestServiceStats(); // seems to be a race } ); $instanceCheck.css( "margin-right", "0.5em" ); $checkCol.append( $instanceCheck ); $checkCol.append( jQuery( '<a/>', { class: "simple", title: "Click to switch primary host", href: "#switchPrimary", text: serviceInstance.host } ).css( "display", "inline" ) ); // + ":" + serviceInstance.port if ( serviceInstance.port != 0 ) { $checkCol.append( jQuery( '<span/>', { text: serviceInstance.port } ) ); } var lc = serviceInstance.lc; if ( lc && lc.indexOf( "-" ) != -1 ) lc = lc.substr( lc.indexOf( "-" ) + 1 ); $instanceRow.append( jQuery( '<td/>', { text: lc } ) ); if ( !hostInit ) { var found = false; $( "#lcSelect option" ).each( function () { if ( $( this ).text() == lc ) found = true; } ); if ( !found ) { $( "#lcSelect" ).append( '<option value="' + lc + '">' + lc + '</option>' ); } } var regex = new RegExp( ".*##", "g" ); var ver = serviceInstance.deployedArtifacts; // alert(ver) ; if ( serviceInstance.deployedArtifacts ) { ver = ""; var verArray = serviceInstance.deployedArtifacts .split( ',' ); for ( var j = 0; j < verArray.length; j++ ) { if ( serviceInstance.host == hostName ) { //console.log("Adding: " + verArray[j]) ; optionItem = jQuery( '<option/>', { value: verArray[j], text: verArray[j] } ); $( "#undeploySelect" ).append( optionItem ); } if ( ver != "" ) ver += ", "; ver += verArray[j].replace( regex, "" ); // ver += verArray[j] + " "; } if ( serviceInstance.scmVersion.indexOf( "Custom artifact uploaded" ) != -1 ) ver += "upload"; } $instanceRow.append( jQuery( '<td/>', { text: ver } ) ); if ( serviceInstance.cpuUtil ) { $instanceRow.append( jQuery( '<td/>', { text: serviceInstance.cpuLoad + ' / ' + serviceInstance.cpuCount } ) ); var $cpuCol = jQuery( '<td/>', { } ); $instanceRow.append( $cpuCol ); if ( serviceInstance.cpuUtil == "-" ) { if ( serviceInstance.serverType == "script" ) { $cpuCol.append( jQuery( '<span/>', { text: 'script' } ) ).css( "font-size", "0.8em" ); } else { $cpuCol.append( jQuery( '<img/>', { src: "images/16x16/process-stop.png" } ).css( "height", "12px" ) ); } } else { var cpu = serviceInstance.cpuUtil; if ( cpu == "AUTO" ) { $cpuCol.append( jQuery( '<img/>', { src: "images/32x32/appointment-new.png" } ).css( "height", "12px" ) ); } else if ( cpu == "CLEAN" ) { $cpuCol.append( jQuery( '<img/>', { src: "images/16x16/clean.png" } ).css( "height", "12px" ) ); } else { if ( cpu.length > 4 ) cpu = cpu.substr( 0, 4 ); $cpuCol.text( cpu ); } } var disk = serviceInstance.diskUtil; if ( disk > 1000 ) { disk = (disk / 1000).toFixed( 1 ) + " Gb" } else { disk += " Mb" } $instanceRow.append( jQuery( '<td/>', { text: disk } ) ); } else { // Service is not active - use placeholders $instanceRow.append( jQuery( '<td/>', { text: "-" } ) ); $instanceRow.append( jQuery( '<td/>', { text: "-" } ) ); $instanceRow.append( jQuery( '<td/>', { text: "-" } ) ); } return $instanceRow; } var _isServiceActive = false; /** @memberOf ServiceAdmin */ function updateUIForInstance( serviceInstance ) { $( "#motd" ).html( serviceInstance.motd ); $( "#lastOp" ).html( serviceInstance.lastOp ); $( "#users" ).html( "Users: " + serviceInstance.users ); // alert( Number(serviceInstance.cpuCount) + 1) ; // var cpuCountInt = Number( serviceInstance.cpuCount ); // $( "#cpuCount" ).html( // Number( serviceInstance.cpuCount ) ); // // var cpuLoadFloat = parseFloat( Number( serviceInstance.cpuLoad ) ); // $( "#cpuLoad" ).html( cpuLoadFloat ); // if ( cpuLoadFloat >= cpuCountInt ) { // $( "#cpuLoad" ) // .html( // cpuLoadFloat // + '<img class="but" height="14" src="images/16x16/warning.png">' ); // } // // $( "#du" ).html( serviceInstance.du ); // if ( serviceInstance.du >= 80 ) { // $( "#du" ).html( // '<img class="but" height="14" src="images/16x16/warning.png">' + // serviceInstance.du ); // } // // // if ( serviceInstance.diskUtil != null ) { // $( "#serviceDisk" ).html( // '<span style="font-weight:bold">disk: </span>' // + serviceInstance.diskUtil // + "M" ); // if ( serviceInstance.diskUtil == "-1" ) { // $( "#serviceDisk" ) // .html( // '<span style="font-weight:bold">disk: </span>...' ); // ; // } // } // _isServiceActive = serviceInstance.cpuUtil != null && serviceInstance.cpuUtil != "-"; if ( !_isServiceActive ) { $( "#serviceCpu" ) .html( '<img src="images/16x16/process-stop.png">' + '<span style="font-weight:bold">Stopped </span>' ); } else { $( "#serviceCpu" ) .html( '<img src="images/16x16/ok.png">' + '<span style="font-weight:bold">Relative Cpu: </span>' + serviceInstance.topCpu + "%" ); } $( "#serviceVersion" ).html( serviceInstance.scmVersion ); $( "#serviceDate" ).html( '<span style="font-weight:bold">Date: </span>' + serviceInstance.warDate ); } } );
var app = angular.module('uwCourseAlerter', [], function($httpProvider) { // Use x-www-form-urlencoded Content-Type // Credits to http://stackoverflow.com/questions/19254029/angularjs-http-post-does-not-send-data $httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=utf-8'; /** * The workhorse; converts an object to x-www-form-urlencoded serialization. * @param {Object} obj * @return {String} */ var param = function(obj) { var query = '', name, value, fullSubName, subName, subValue, innerObj, i; for(name in obj) { value = obj[name]; if(value instanceof Array) { for(i=0; i<value.length; ++i) { subValue = value[i]; fullSubName = name + '[' + i + ']'; innerObj = {}; innerObj[fullSubName] = subValue; query += param(innerObj) + '&'; } } else if(value instanceof Object) { for(subName in value) { subValue = value[subName]; fullSubName = name + '[' + subName + ']'; innerObj = {}; innerObj[fullSubName] = subValue; query += param(innerObj) + '&'; } } else if(value !== undefined && value !== null) query += encodeURIComponent(name) + '=' + encodeURIComponent(value) + '&'; } return query.length ? query.substr(0, query.length - 1) : query; }; // Override $http service's default transformRequest $httpProvider.defaults.transformRequest = [function(data) { return angular.isObject(data) && String(data) !== '[object File]' ? param(data) : data; }]; }); app.controller('MainCtrl', function($scope, $http) { });
/** * @author Mat Groves http://matgroves.com/ @Doormat23 */ /** * A set of functions used to handle masking. * * @class PIXI.CanvasMaskManager * @constructor */ PIXI.CanvasMaskManager = function () { }; PIXI.CanvasMaskManager.prototype.constructor = PIXI.CanvasMaskManager; /** * This method adds it to the current stack of masks. * * @method PIXI.CanvasMaskManager#pushMask * @param maskData {Object} the maskData that will be pushed * @param renderSession {Object} The renderSession whose context will be used for this mask manager. */ PIXI.CanvasMaskManager.prototype.pushMask = function (maskData, renderSession) { var context = renderSession.context; context.save(); var cacheAlpha = maskData.alpha; var transform = maskData.worldTransform; var resolution = renderSession.resolution; context.setTransform(transform.a * resolution, transform.b * resolution, transform.c * resolution, transform.d * resolution, transform.tx * resolution, transform.ty * resolution); PIXI.CanvasGraphics.renderGraphicsMask(maskData, context); context.clip(); maskData.worldAlpha = cacheAlpha; }; /** * Restores the current drawing context to the state it was before the mask was applied. * * @method PIXI.CanvasMaskManager#popMask * @param renderSession {Object} The renderSession whose context will be used for this mask manager. */ PIXI.CanvasMaskManager.prototype.popMask = function (renderSession) { renderSession.context.restore(); };
/* global describe, it, expect, LinkedList*/ describe('Linked list', function () { 'use strict'; /** * Helper functions to ease in setting up test cases * * */ function insertFirst(list, element) { list.insertFirst(element); } function insertLast(list, element) { list.insertLast(element); } function insertList(list, listTwo) { list.insertLast(listTwo); } function helper(fn, list) { var args = [].slice.call(arguments); args.shift(); args.shift(); args.forEach(function (element) { fn(list, element); }); } function batcher(fn, list, element, count) { for (var i = 0; i < count; i++) { fn(list, element); } } describe('Getting size of list', function () { it('should have zero size if empty', function () { var list = new LinkedList(); expect(list.size()).to.equal(0); }); it('should have size one if one item added', function () { var list = new LinkedList(); list.insertFirst(1); expect(list.size()).to.equal(1); }); it('should have size 10 if 10 items added', function () { var list = new LinkedList(); helper(insertFirst, list, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10); expect(list.size()).to.equal(10); }); it('should have size 2048 if 2048 items inserted first', function () { var list = new LinkedList(); batcher(insertFirst, list, 'foo', 2048); expect(list.size()).to.equal(2048); }); it('should have size 2048 if 2048 items inserted last', function () { var list = new LinkedList(); batcher(insertLast, list, 'foo', 2048); expect(list.size()).to.equal(2048); }); it('should have size 112 if 122 items inserted at index zero', function () { var list = new LinkedList(); batcher(function (list, value) { list.insertAt(0, value); }, list, 'foo', 2048); expect(list.size()).to.equal(2048); }); }); describe('Finding element at position', function () { it('should return correct element at position 0', function () { var list = new LinkedList(); list.insertFirst('one'); expect(list.elementAt(0)).to.equal('one'); }); it('should return correct element at position 3', function () { var list = new LinkedList(); helper(insertFirst, list, '10', '9', '8', '7', '6', '5', '4', '3', '2', '1'); expect(list.elementAt(3)).to.equal('4'); }); }); describe('Inserting elements', function () { describe('Insert first', function () { it('should insert in correct order', function () { var list = new LinkedList(); helper(insertFirst, list, '1', '2', '3', '4', '5', '6', '7', '8', '9', '10'); expect(list.elementAt(0)).to.equal('10'); expect(list.elementAt(1)).to.equal('9'); expect(list.elementAt(2)).to.equal('8'); expect(list.elementAt(3)).to.equal('7'); expect(list.elementAt(4)).to.equal('6'); expect(list.elementAt(5)).to.equal('5'); expect(list.elementAt(6)).to.equal('4'); expect(list.elementAt(7)).to.equal('3'); expect(list.elementAt(8)).to.equal('2'); expect(list.elementAt(9)).to.equal('1'); }); }); describe('Insert last', function () { it('should insert in correct order', function () { var list = new LinkedList(); helper(insertLast, list, '1', '2', '3', '4', '5', '6', '7', '8', '9', '10'); expect(list.elementAt(9)).to.equal('10'); expect(list.elementAt(8)).to.equal('9'); expect(list.elementAt(7)).to.equal('8'); expect(list.elementAt(6)).to.equal('7'); expect(list.elementAt(5)).to.equal('6'); expect(list.elementAt(4)).to.equal('5'); expect(list.elementAt(3)).to.equal('4'); expect(list.elementAt(2)).to.equal('3'); expect(list.elementAt(1)).to.equal('2'); expect(list.elementAt(0)).to.equal('1'); }); }); describe('Inserting at', function () { it('should insert node at correct position', function () { var list = new LinkedList(); batcher(insertFirst, list, 'element', 12); list.insertAt(5, 'five'); expect(list.size()).to.equal(13); expect(list.elementAt(5)).to.equal('five'); }); }); describe('Inserting list', function () { it('should add all elements from list', function () { var listOne = new LinkedList(); helper(insertList, listOne, '1', '2', '3'); var listTwo = new LinkedList(); helper(insertList, listTwo, '4', '5', '6'); var list = new LinkedList(); list.insertList(listOne); list.insertList(listTwo); expect(list.elementAt(0)).to.equal('1'); expect(list.elementAt(1)).to.equal('2'); expect(list.elementAt(2)).to.equal('3'); expect(list.elementAt(3)).to.equal('4'); expect(list.elementAt(4)).to.equal('5'); expect(list.elementAt(5)).to.equal('6'); }); }); }); describe('Removing elements', function () { describe('Remove first ', function () { it('it should remove first element', function () { var list = new LinkedList(); helper(insertFirst, list, '1', '2', '3', '4', '5'); list.removeFirst(); expect(list.elementAt(0)).to.equal('4'); }); }); describe('Remove last ', function () { it('it should remove last element', function () { var list = new LinkedList(); helper(insertLast, list, '1', '2', '3', '4', '5'); list.removeLast(); expect(list.elementAt(list.size() - 1)).to.equal('4'); }); }); describe('Remove at ', function () { it('it should remove item from correct position element', function () { var list = new LinkedList(); helper(insertLast, list, '1', '2', '3', '4', '5'); list.removeAt(2); expect(list.elementAt(2)).to.equal('4'); }); }); describe('Empty', function () { it('should return true on newly created list', function () { var list = new LinkedList(); expect(list.isEmpty()).to.equal(true); }); it('should return false on list with items', function () { var list = new LinkedList(); list.insertFirst('value'); expect(list.isEmpty()).to.equal(false); }); it('should return true on list that has been cleared', function () { var list = new LinkedList(); list.insertFirst('value'); list.clear(); expect(list.isEmpty()).to.equal(true); }); }); }); describe('Error handling', function () { describe('Out of bounds', function () { it('should throw OutOfBoundException when inserting outsize of higher bound ', function () { var list = new LinkedList(); expect(function () { list.insertAt(1); }).to.throw("OutOfBoundException"); }); it('should throw OutOfBoundException when inserting outsize of lower bound ', function () { var list = new LinkedList(); expect(function () { list.insertAt(-1); }).to.throw("OutOfBoundException"); }); it('should throw OutOfBoundException when retrieving outsize of higher bound ', function () { var list = new LinkedList(); expect(function () { list.elementAt(1); }).to.throw("OutOfBoundException"); }); it('should throw OutOfBoundException when retrieving outsize of lower bound ', function () { var list = new LinkedList(); expect(function () { list.elementAt(-1); }).to.throw("OutOfBoundException"); }); it('should throw OutOfBoundException when removing outsize of higher bound ', function () { var list = new LinkedList(); expect(function () { list.removeAt(1); }).to.throw("OutOfBoundException"); }); it('should throw OutOfBoundException when removing outsize of lower bound ', function () { var list = new LinkedList(); expect(function () { list.removeAt(-1); }).to.throw("OutOfBoundException"); }); }); describe('Working with arrays', function () { describe('Creating from array', function () { it('should add all elements from array', function () { var arr = ["1", "2", "3", "4"]; var list = new LinkedList(arr); expect(list.elementAt(0)).to.equal('1'); expect(list.elementAt(1)).to.equal('2'); expect(list.elementAt(2)).to.equal('3'); expect(list.elementAt(3)).to.equal('4'); }); }); describe('Adding array', function () { it('should add all elements from array', function () { var arr = ["1", "2", "3", "4"]; var list = new LinkedList(); list.insertArray(arr); expect(list.elementAt(0)).to.equal('1'); expect(list.elementAt(1)).to.equal('2'); expect(list.elementAt(2)).to.equal('3'); expect(list.elementAt(3)).to.equal('4'); }); }); describe('To array', function () { it('should return empty array on empty list', function () { var list = new LinkedList(); var arr = list.toArray(); expect(arr).to.be.an('array'); expect(arr.length).to.equal(0); }); it('should return array with correct element', function () { var list = new LinkedList(); helper(insertLast, list, '1', '2', '3', '4', '5'); var arr = list.toArray(); expect(arr[0]).to.equal('1'); expect(arr[1]).to.equal('2'); expect(arr[2]).to.equal('3'); expect(arr[3]).to.equal('4'); expect(arr[4]).to.equal('5'); }); }); }); describe('Iterating over elements', function () { it('should run callback for each element', function () { var list = new LinkedList([0, 1, 2]); list.forEach(function (element, index) { expect(element).to.equal(index); }); }); it('should iterate correctly with for loop', function () { var list = new LinkedList([0, 1, 2]); for (var i = 0, size = list.size(); i < size; i++) { expect(list.elementAt(i)).to.equal(i); } }); it('should iterate correctly with iterator', function () { var list = new LinkedList([0, 1, 2]); var iterator = list.iterator(); var i = 0; while (iterator.hasNext()) { expect(iterator.next()).to.equal(i); i++; } }); }); describe('Finding elements', function () { it('should return index of existing item', function () { var list = new LinkedList(['one', 'two', 'three']); var result = list.indexOf('two'); expect(result).to.equal(1); }); it('should return -1 if item does not exist', function () { var list = new LinkedList(['one', 'two', 'three']); expect(list.indexOf('unknown')).to.equal(-1); }); it('should return -1 when trying to find item on empty list', function () { var list = new LinkedList(); expect(list.indexOf('unknown')).to.equal(-1); }); }); describe('Compound tests', function () { var list = new LinkedList(); //Inserting and retrieving list.insertFirst('b'); list.insertFirst('a'); list.insertLast('d'); list.insertAt(2, 'c'); expect(list.elementAt(0)).to.equal('a'); expect(list.elementAt(1)).to.equal('b'); expect(list.elementAt(2)).to.equal('c'); expect(list.elementAt(3)).to.equal('d'); expect(list.size()).to.equal(4); list.clear(); // removing list.insertLast('a'); list.insertLast('b'); list.insertLast('c'); list.insertLast('d'); list.insertLast('e'); expect(list.size()).to.equal(5); list.removeAt(2); expect(list.size()).to.equal(4); expect(list.elementAt(2)).to.equal('d'); list.removeFirst(); expect(list.size()).to.equal(3); expect(list.elementAt(0)).to.equal('b'); list.removeLast(); expect(list.size()).to.equal(2); expect(list.elementAt(1)).to.equal('d'); list.clear(); // working with arrays arr = ["1", "2", "3", "4"]; list = new LinkedList(arr); expect(list.elementAt(0)).to.equal('1'); expect(list.elementAt(1)).to.equal('2'); expect(list.elementAt(2)).to.equal('3'); expect(list.elementAt(3)).to.equal('4'); list.clear(); list.insertArray(arr); expect(list.elementAt(0)).to.equal('1'); expect(list.elementAt(1)).to.equal('2'); expect(list.elementAt(2)).to.equal('3'); expect(list.elementAt(3)).to.equal('4'); var arr = list.toArray(); expect(arr[0]).to.equal('1'); expect(arr[1]).to.equal('2'); expect(arr[2]).to.equal('3'); expect(arr[3]).to.equal('4'); list = new LinkedList(); try { list.elementAt(-1); } catch (err) { expect(err.message).to.equal('OutOfBoundException'); } }); }); });
version https://git-lfs.github.com/spec/v1 oid sha256:9c0056aa2edf0d4c0f91a634f4bf5f98cf872ad17910f57fb7d25a667c6e5cfd size 32988
const async = require('async') const { BN, privateToAddress, isValidPrivate, stripHexPrefix, toChecksumAddress } = require('ethereumjs-util') const crypto = require('crypto') const { EventEmitter } = require('events') const TxRunner = require('./execution/txRunner') const txHelper = require('./execution/txHelper') const EventManager = require('./eventManager') const defaultExecutionContext = require('./execution/execution-context') const { resultToRemixTx } = require('./helpers/txResultHelper') module.exports = class UniversalDApp { constructor (config, executionContext) { this.events = new EventEmitter() this.event = new EventManager() // has a default for now for backwards compatability this.executionContext = executionContext || defaultExecutionContext this.config = config this.txRunner = new TxRunner({}, { config: config, detectNetwork: (cb) => { this.executionContext.detectNetwork(cb) }, personalMode: () => { return this.executionContext.getProvider() === 'web3' ? this.config.get('settings/personal-mode') : false } }, this.executionContext) this.accounts = {} this.executionContext.event.register('contextChanged', this.resetEnvironment.bind(this)) } // TODO : event should be triggered by Udapp instead of TxListener /** Listen on New Transaction. (Cannot be done inside constructor because txlistener doesn't exist yet) */ startListening (txlistener) { txlistener.event.register('newTransaction', (tx) => { this.events.emit('newTransaction', tx) }) } resetEnvironment () { this.accounts = {} if (this.executionContext.isVM()) { this._addAccount('3cd7232cd6f3fc66a57a6bedc1a8ed6c228fff0a327e169c2bcc5e869ed49511', '0x56BC75E2D63100000') this._addAccount('2ac6c190b09897cd8987869cc7b918cfea07ee82038d492abce033c75c1b1d0c', '0x56BC75E2D63100000') this._addAccount('dae9801649ba2d95a21e688b56f77905e5667c44ce868ec83f82e838712a2c7a', '0x56BC75E2D63100000') this._addAccount('d74aa6d18aa79a05f3473dd030a97d3305737cbc8337d940344345c1f6b72eea', '0x56BC75E2D63100000') this._addAccount('71975fbf7fe448e004ac7ae54cad0a383c3906055a65468714156a07385e96ce', '0x56BC75E2D63100000') } // TODO: most params here can be refactored away in txRunner this.txRunner = new TxRunner(this.accounts, { // TODO: only used to check value of doNotShowTransactionConfirmationAgain property config: this.config, // TODO: to refactor, TxRunner already has access to executionContext detectNetwork: (cb) => { this.executionContext.detectNetwork(cb) }, personalMode: () => { return this.executionContext.getProvider() === 'web3' ? this.config.get('settings/personal-mode') : false } }, this.executionContext) this.txRunner.event.register('transactionBroadcasted', (txhash) => { this.executionContext.detectNetwork((error, network) => { if (error || !network) return this.event.trigger('transactionBroadcasted', [txhash, network.name]) }) }) } resetAPI (transactionContextAPI) { this.transactionContextAPI = transactionContextAPI } /** * Create a VM Account * @param {{privateKey: string, balance: string}} newAccount The new account to create */ createVMAccount (newAccount) { const { privateKey, balance } = newAccount if (this.executionContext.getProvider() !== 'vm') { throw new Error('plugin API does not allow creating a new account through web3 connection. Only vm mode is allowed') } this._addAccount(privateKey, balance) const privKey = Buffer.from(privateKey, 'hex') return '0x' + privateToAddress(privKey).toString('hex') } newAccount (password, passwordPromptCb, cb) { if (!this.executionContext.isVM()) { if (!this.config.get('settings/personal-mode')) { return cb('Not running in personal mode') } passwordPromptCb((passphrase) => { this.executionContext.web3().personal.newAccount(passphrase, cb) }) } else { let privateKey do { privateKey = crypto.randomBytes(32) } while (!isValidPrivate(privateKey)) this._addAccount(privateKey, '0x56BC75E2D63100000') cb(null, '0x' + privateToAddress(privateKey).toString('hex')) } } /** Add an account to the list of account (only for Javascript VM) */ _addAccount (privateKey, balance) { if (!this.executionContext.isVM()) { throw new Error('_addAccount() cannot be called in non-VM mode') } if (this.accounts) { privateKey = Buffer.from(privateKey, 'hex') const address = privateToAddress(privateKey) // FIXME: we don't care about the callback, but we should still make this proper let stateManager = this.executionContext.vm().stateManager stateManager.getAccount(address, (error, account) => { if (error) return console.log(error) account.balance = balance || '0xf00000000000000001' stateManager.putAccount(address, account, function cb (error) { if (error) console.log(error) }) }) this.accounts[toChecksumAddress('0x' + address.toString('hex'))] = { privateKey, nonce: 0 } } } /** Return the list of accounts */ getAccounts (cb) { return new Promise((resolve, reject) => { const provider = this.executionContext.getProvider() switch (provider) { case 'vm': { if (!this.accounts) { if (cb) cb('No accounts?') reject('No accounts?') return } if (cb) cb(null, Object.keys(this.accounts)) resolve(Object.keys(this.accounts)) } break case 'web3': { if (this.config.get('settings/personal-mode')) { return this.executionContext.web3().personal.getListAccounts((error, accounts) => { if (cb) cb(error, accounts) if (error) return reject(error) resolve(accounts) }) } else { this.executionContext.web3().eth.getAccounts((error, accounts) => { if (cb) cb(error, accounts) if (error) return reject(error) resolve(accounts) }) } } break case 'injected': { this.executionContext.web3().eth.getAccounts((error, accounts) => { if (cb) cb(error, accounts) if (error) return reject(error) resolve(accounts) }) } } }) } /** Get the balance of an address */ getBalance (address, cb) { address = stripHexPrefix(address) if (!this.executionContext.isVM()) { this.executionContext.web3().eth.getBalance(address, (err, res) => { if (err) { cb(err) } else { cb(null, res.toString(10)) } }) } else { if (!this.accounts) { return cb('No accounts?') } this.executionContext.vm().stateManager.getAccount(Buffer.from(address, 'hex'), (err, res) => { if (err) { cb('Account not found') } else { cb(null, new BN(res.balance).toString(10)) } }) } } /** Get the balance of an address, and convert wei to ether */ getBalanceInEther (address, callback) { this.getBalance(address, (error, balance) => { if (error) { callback(error) } else { callback(null, this.executionContext.web3().utils.fromWei(balance, 'ether')) } }) } pendingTransactionsCount () { return Object.keys(this.txRunner.pendingTxs).length } /** * deploy the given contract * * @param {String} data - data to send with the transaction ( return of txFormat.buildData(...) ). * @param {Function} callback - callback. */ createContract (data, confirmationCb, continueCb, promptCb, callback) { this.runTx({data: data, useCall: false}, confirmationCb, continueCb, promptCb, (error, txResult) => { // see universaldapp.js line 660 => 700 to check possible values of txResult (error case) callback(error, txResult) }) } /** * call the current given contract * * @param {String} to - address of the contract to call. * @param {String} data - data to send with the transaction ( return of txFormat.buildData(...) ). * @param {Object} funAbi - abi definition of the function to call. * @param {Function} callback - callback. */ callFunction (to, data, funAbi, confirmationCb, continueCb, promptCb, callback) { const useCall = funAbi.stateMutability === 'view' || funAbi.stateMutability === 'pure' this.runTx({to, data, useCall}, confirmationCb, continueCb, promptCb, (error, txResult) => { // see universaldapp.js line 660 => 700 to check possible values of txResult (error case) callback(error, txResult) }) } /** * call the current given contract * * @param {String} to - address of the contract to call. * @param {String} data - data to send with the transaction ( return of txFormat.buildData(...) ). * @param {Function} callback - callback. */ sendRawTransaction (to, data, confirmationCb, continueCb, promptCb, callback) { this.runTx({to, data, useCall: false}, confirmationCb, continueCb, promptCb, (error, txResult) => { // see universaldapp.js line 660 => 700 to check possible values of txResult (error case) callback(error, txResult) }) } context () { return (this.executionContext.isVM() ? 'memory' : 'blockchain') } getABI (contract) { return txHelper.sortAbiFunction(contract.abi) } getFallbackInterface (contractABI) { return txHelper.getFallbackInterface(contractABI) } getReceiveInterface (contractABI) { return txHelper.getReceiveInterface(contractABI) } getInputs (funABI) { if (!funABI.inputs) { return '' } return txHelper.inputParametersDeclarationToString(funABI.inputs) } /** * This function send a tx only to javascript VM or testnet, will return an error for the mainnet * SHOULD BE TAKEN CAREFULLY! * * @param {Object} tx - transaction. */ sendTransaction (tx) { return new Promise((resolve, reject) => { this.executionContext.detectNetwork((error, network) => { if (error) return reject(error) if (network.name === 'Main' && network.id === '1') { return reject(new Error('It is not allowed to make this action against mainnet')) } this.silentRunTx(tx, (error, result) => { if (error) return reject(error) try { resolve(resultToRemixTx(result)) } catch (e) { reject(e) } }) }) }) } /** * This function send a tx without alerting the user (if mainnet or if gas estimation too high). * SHOULD BE TAKEN CAREFULLY! * * @param {Object} tx - transaction. * @param {Function} callback - callback. */ silentRunTx (tx, cb) { this.txRunner.rawRun( tx, (network, tx, gasEstimation, continueTxExecution, cancelCb) => { continueTxExecution() }, (error, continueTxExecution, cancelCb) => { if (error) { cb(error) } else { continueTxExecution() } }, (okCb, cancelCb) => { okCb() }, cb ) } runTx (args, confirmationCb, continueCb, promptCb, cb) { const self = this async.waterfall([ function getGasLimit (next) { if (self.transactionContextAPI.getGasLimit) { return self.transactionContextAPI.getGasLimit(next) } next(null, 3000000) }, function queryValue (gasLimit, next) { if (args.value) { return next(null, args.value, gasLimit) } if (args.useCall || !self.transactionContextAPI.getValue) { return next(null, 0, gasLimit) } self.transactionContextAPI.getValue(function (err, value) { next(err, value, gasLimit) }) }, function getAccount (value, gasLimit, next) { if (args.from) { return next(null, args.from, value, gasLimit) } if (self.transactionContextAPI.getAddress) { return self.transactionContextAPI.getAddress(function (err, address) { next(err, address, value, gasLimit) }) } self.getAccounts(function (err, accounts) { let address = accounts[0] if (err) return next(err) if (!address) return next('No accounts available') if (self.executionContext.isVM() && !self.accounts[address]) { return next('Invalid account selected') } next(null, address, value, gasLimit) }) }, function runTransaction (fromAddress, value, gasLimit, next) { const tx = { to: args.to, data: args.data.dataHex, useCall: args.useCall, from: fromAddress, value: value, gasLimit: gasLimit, timestamp: args.data.timestamp } const payLoad = { funAbi: args.data.funAbi, funArgs: args.data.funArgs, contractBytecode: args.data.contractBytecode, contractName: args.data.contractName, contractABI: args.data.contractABI, linkReferences: args.data.linkReferences } let timestamp = Date.now() if (tx.timestamp) { timestamp = tx.timestamp } self.event.trigger('initiatingTransaction', [timestamp, tx, payLoad]) self.txRunner.rawRun(tx, confirmationCb, continueCb, promptCb, function (error, result) { let eventName = (tx.useCall ? 'callExecuted' : 'transactionExecuted') self.event.trigger(eventName, [error, tx.from, tx.to, tx.data, tx.useCall, result, timestamp, payLoad]) if (error && (typeof (error) !== 'string')) { if (error.message) error = error.message else { try { error = 'error: ' + JSON.stringify(error) } catch (e) {} } } next(error, result) } ) } ], cb) } }
// the following is for the generic search on the top right corner of the screen sr.fn.search_generic.setup = function() { $('#generic_search_input').keyup(function(e) { if (e.keyCode == 13) { sr.fn.search_generic.go('#generic_search_input'); } }); $('#generic_search_wide_input').keyup(function(e) { if (e.keyCode == 13) { sr.fn.search_generic.go('#generic_search_wide_input'); } }) } sr.fn.search_generic.go = function(caller) { var encoded_search_string = encodeURIComponent($(caller).val()); window.location = '?keywords=' + encoded_search_string; } sr.fn.search_pos.showPopup = function() { sr.data.search_pos.current_page = 1; $('#search').show(); $('#search').css({'z-index':'1010'}); $('#search_keywords').val(""); sr.fn.focus.set($('#search_keywords')); var inp = $('<input type="text" id="search_keywords" name="keywords" class="keyboardable" value="" />'); inp.keyup(function(e) { if (e.keyCode == 13) { sr.fn.search_pos.go('#search_keywords'); inp.select(); } }) $('.search-div-input-constrainer').html(inp); sr.fn.onscreen_keyboard.make(inp); $('#search').height($(window).height() * 0.75); $('#search').width($(window).width() * 0.75); $('.search-results').height($('#search').height() - 136); inp.select(); shared.helpers.center($('#search')); } sr.fn.search_pos.hidePopup = function() { $('#search').hide(); $('#search_results').html(''); setTimeout(function () { sr.fn.focus.set($('#keyboard_input')); },120); } sr.fn.search_pos.go = function(caller) { sr.fn.debug.echo('search', caller); var query = '/items/search?keywords=' + $('#search_keywords').val() + '&klass=' + $('#search_models').val() + '&page=' + sr.data.search_pos.current_page; get(query, '_search.html.erb'); } sr.fn.search_pos.displayNextPage = function() { sr.data.search_pos.current_page = sr.data.search_pos.current_page + 1; sr.fn.search_pos.go('search_get_next_page'); } sr.fn.search_pos.displayPreviousPage = function() { sr.data.search_pos.current_page = sr.data.search_pos.current_page - 1; sr.fn.search_pos.go('search_get_prev_page'); } ;
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { UploadComponent } from './upload.component'; import { DropZoneDirective } from './dropzone.directive'; import { FileListComponent } from './file-list.component'; import { FileListItemDirective } from './file-list-item'; import { FileListSingleItemComponent } from './file-list-single-item.component'; import { FileListMultipleItemsComponent } from './file-list-multiple-items.component'; import { FileListItemActionButtonComponent } from './file-list-item-action-button.component'; import { FileTemplateDirective } from './templates/file-template.directive'; import { FileSelectDirective } from './file-select.directive'; import { UploadActionButtonsComponent } from './upload-action-buttons.component'; import { UploadStatusTotalComponent } from './upload-status-total.component'; import { TemplateContextDirective } from './templates/template-context.directive'; import { LocalizedMessagesDirective } from './localization/localized-messages.directive'; import { CustomMessagesComponent } from './localization/custom-messages.component'; var declarations = [ CustomMessagesComponent, DropZoneDirective, FileListComponent, FileListItemDirective, FileListItemActionButtonComponent, FileListMultipleItemsComponent, FileListSingleItemComponent, FileSelectDirective, FileTemplateDirective, LocalizedMessagesDirective, TemplateContextDirective, UploadComponent, UploadActionButtonsComponent, UploadStatusTotalComponent ]; /** * Represents the [NgModule](https://angular.io/docs/ts/latest/guide/ngmodule.html) definition for the Upload component. */ var UploadModule = (function () { function UploadModule() { } return UploadModule; }()); export { UploadModule }; UploadModule.decorators = [ { type: NgModule, args: [{ declarations: [declarations], exports: [UploadComponent, FileTemplateDirective, CustomMessagesComponent], imports: [CommonModule, FormsModule] },] }, ]; /** @nocollapse */ UploadModule.ctorParameters = function () { return []; };
var util = require("util"), Stream = require("stream").Stream; function MiddleStream(from, to) { var self = this; Stream.call(this); this.writable = true; this.readable = true; this.__from = from; this.__to = to; this.__piped = true; ['drain', 'error', 'close', 'pipe'].forEach(function(eventType) { self.__from.on(eventType, function() { var args = Array.prototype.slice.call(arguments); args.unshift(eventType); self.emit.apply(self, args); }); }); ['data', 'end', 'error', 'close'].forEach(function(eventType) { self.__to.on(eventType, function() { var args = Array.prototype.slice.call(arguments); args.unshift(eventType); self.emit.apply(self, args); }); }); from.pipe(to); } util.inherits(MiddleStream, Stream); MiddleStream.prototype.setEncoding = function setEncoding(encoding) { this.__from.setEncoding(encoding); this.__to.setEncoding && this.__to.setEncoding(encoding); } /** * Prevents this stream from emitting `data` events until `resume` is called. * This does not prevent writes to this stream. */ MiddleStream.prototype.pause = function pause() { this.__to.pause(); } /** * Resumes emitting `data` events. */ MiddleStream.prototype.resume = function resume() { this.__to.resume(); } /** * Writes the given `chunk` of data to this stream. Returns `false` if this * stream is full and should not be written to further until drained, `true` * otherwise. */ MiddleStream.prototype.write = function write(chunk, encoding) { if (! this.__piped) { this.__piped = true; this.__from.pipe(this.__to); } return this.__from.write(chunk, encoding); } MiddleStream.prototype.end = function end(chunk, encoding) { this.__from.end(); } /** * Destroys this stream immediately. It is no longer readable or writable. This * method should rarely ever be called directly by users as it will be called * automatically when using BufferedStream#end. */ MiddleStream.prototype.destroy = function destroy() { this.__writeStream.destroy && this.__writeStream.destroy(); this.__readStream.destroy && this.__readStream.destroy(); } module.exports = MiddleStream;
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import 'babel-polyfill'; import ReactDOM from 'react-dom'; import FastClick from 'fastclick'; import { match } from 'universal-router'; import routes from './routes'; import history from './core/history'; import configureStore from './store/configureStore'; import { addEventListener, removeEventListener } from './core/DOMUtils'; const context = { store: null, insertCss: styles => styles._insertCss(), // eslint-disable-line no-underscore-dangle setTitle: value => (document.title = value), setMeta: (name, content) => { // Remove and create a new <meta /> tag in order to make it work // with bookmarks in Safari const elements = document.getElementsByTagName('meta'); Array.from(elements).forEach((element) => { if (element.getAttribute('name') === name) { element.parentNode.removeChild(element); } }); const meta = document.createElement('meta'); meta.setAttribute('name', name); meta.setAttribute('content', content); document .getElementsByTagName('head')[0] .appendChild(meta); }, }; // Restore the scroll position if it was saved into the state function restoreScrollPosition(state) { if (state && state.scrollY !== undefined) { window.scrollTo(state.scrollX, state.scrollY); } else { window.scrollTo(0, 0); } } let renderComplete = (state, callback) => { const elem = document.getElementById('css'); if (elem) elem.parentNode.removeChild(elem); callback(true); renderComplete = (s) => { restoreScrollPosition(s); // Google Analytics tracking. Don't send 'pageview' event after // the initial rendering, as it was already sent window.ga('send', 'pageview'); callback(true); }; }; function render(container, state, component) { return new Promise((resolve, reject) => { try { ReactDOM.render( component, container, renderComplete.bind(undefined, state, resolve) ); } catch (err) { reject(err); } }); } function run() { let currentLocation = null; const container = document.getElementById('app'); const initialState = JSON.parse( document. getElementById('source'). getAttribute('data-initial-state') ); // Make taps on links and buttons work fast on mobiles FastClick.attach(document.body); context.store = configureStore(initialState, {}); // Re-render the app when window.location changes const removeHistoryListener = history.listen(location => { currentLocation = location; match(routes, { path: location.pathname, query: location.query, state: location.state, context, render: render.bind(undefined, container, location.state), }).catch(err => console.error(err)); // eslint-disable-line no-console }); // Save the page scroll position into the current location's state const supportPageOffset = window.pageXOffset !== undefined; const isCSS1Compat = ((document.compatMode || '') === 'CSS1Compat'); const setPageOffset = () => { currentLocation.state = currentLocation.state || Object.create(null); if (supportPageOffset) { currentLocation.state.scrollX = window.pageXOffset; currentLocation.state.scrollY = window.pageYOffset; } else { currentLocation.state.scrollX = isCSS1Compat ? document.documentElement.scrollLeft : document.body.scrollLeft; currentLocation.state.scrollY = isCSS1Compat ? document.documentElement.scrollTop : document.body.scrollTop; } }; addEventListener(window, 'scroll', setPageOffset); addEventListener(window, 'pagehide', () => { removeEventListener(window, 'scroll', setPageOffset); removeHistoryListener(); }); } // Run the application when both DOM is ready and page content is loaded if (['complete', 'loaded', 'interactive'].includes(document.readyState) && document.body) { run(); } else { document.addEventListener('DOMContentLoaded', run, false); }
import React from 'react'; import Section from 'component/Section'; import './style.css'; const rangeStyle = { textAlign: 'right', }; const SkillPanel = ({data: {name}}) => ( <h3 style={rangeStyle}> {name} </h3> ); const recordStyle = { flex: 1, margin: 0, paddingTop: 3, paddingRight: 30, paddingLeft: 58, }; const SkillContent = ({data: {description, descriptors = []}}) => ( <ul style={recordStyle}> {descriptors.map((d, i) => <li key={i}>{d}</li>)} </ul> ); const SkillTitle = () => <h2>Technical Skills</h2>; const spacerStyle = { height: 30, }; const SkillSpacer = () => <div className="SkillSpacer" style={spacerStyle} />; const SkillSection = ({data}) => { if (!data) return null; const {skills} = data; if (skills.length === 0) return null; return ( <div> {skills && skills.map((d, i) => [ (!i && <div className="title" key={i}> <Section content={SkillTitle} /> <Section sub={true} data={d} panel={SkillPanel} content={SkillContent} /> </div>) || null, (i && <Section sub={true} data={d} panel={SkillPanel} content={SkillContent} />) || null, (i !== skills.length - 1 && <SkillSpacer key={100 + i} />) || null, ])} <Section.Footer /> </div> ); }; export default SkillSection;
{ appDir: '../js', baseUrl: './', paths: { 'angular': 'libs/angular-1.3.0', 'uirouter': 'libs/angular-ui-router', 'jquery': 'libs/jquery/dist/jquery', 'bootstrapjs': '../bootstrap/js/bootstrap', 'marked': 'libs/marked', 'fileupload': 'libs/angular-file-upload', 'bmob': 'libs/bmob-min', 'highlight': 'libs/highlight/highlight.pack', 'app': './app', 'rome-timepicker': 'libs/rome-datetimepicker/dist/rome.min' }, dir: '../www-built', modules: [ //First set up the common build layer. { //module names are relative to baseUrl name: './main', //List common dependencies here. Only need to list //top level dependencies, "include" will find //nested dependencies. include: ['angular', 'app', 'router' ] }, //Now set up a build layer for each page, but exclude //the common one. "exclude" will exclude //the nested, built dependencies from "common". Any //"exclude" that includes built modules should be //listed before the build layer that wants to exclude it. //"include" the appropriate "app/main*" module since by default //it will not get added to the build since it is loaded by a nested //require in the page*.js files. { //module names are relative to baseUrl/paths config name: 'app', include: ['angular', 'controller', 'directive', 'service', 'filter'], exclude: ['./main'] }, { //module names are relative to baseUrl name: 'controller', include: ['angular', 'controllers/homeCtr', 'controllers/writepageCtr', 'controllers/menubarCtr', "controllers/articleCtr", "controllers/hupunewsCtr", "controllers/trendsCtr" ] } ] }
/*********************/ /** SYMBOL POLYFILL **/ /*********************/ var symbolDetection; try { symbolDetection = Symbol('foo'); } catch (ignored) {} // eslint-disable-line no-empty if (!symbolDetection) { Symbol = function (name) { return '' + name + Math.floor(Math.random() * 99999); }; }
import { assign } from './utils' const camelize = str => { return str.toLowerCase().replace(/[^a-zA-Z0-9]+(.)/g, (_, c) => c.toUpperCase()) } export default (name, width, height, path, keywords) => { const attributes = opts => { const options = assign({ scale: 1, label: null, class: null }, opts || {}) return elementAttributes({ version: '1.1', width, height, viewBox: `0 0 ${width} ${height}` }, options) } const elementAttributes = (attrs, options) => { if (options.label) { attrs['aria-label'] = options.label } else { attrs['aria-hidden'] = true } if (options.class) { attrs.class = `octicon octicon-${name} ${options.class}` } else { attrs.class = `octicon octicon-${name}` } const actualScale = options.scale === 0 ? 0 : parseFloat(options.scale) || 1 const actualWidth = actualScale * parseInt(attrs.width) const actualHeight = actualScale * parseInt(attrs.height) attrs.width = Number(actualWidth.toFixed(2)) attrs.height = Number(actualHeight.toFixed(2)) return attrs } const elementAttributesString = attrs => { return Object.keys(attrs).map(name => { return `${name}="${attrs[name]}"` }).join(' ').trim() } return { name, path (camel = false) { const frozen = assign({}, path) if (!camel) { return frozen } const normalizedPath = {} Object.keys(frozen).forEach(key => { normalizedPath[camelize(key)] = frozen[key] }) return normalizedPath }, keywords () { return keywords }, attrs (options) { return attributes(options) }, html (options) { const attrs = elementAttributesString(this.attrs(options)) const pathAttrs = elementAttributesString(this.path()) return `<svg ${attrs}><path ${pathAttrs}/></svg>` } } }
import { moduleFor, test } from 'ember-qunit'; moduleFor('route:my-communities/manage/embed-registration', 'Unit | Route | my communities/manage/embed registration', { // Specify the other units that are required for this test. // needs: ['controller:foo'] needs: [ 'service:router-scroll', 'service:scheduler' ] }); test('it exists', function(assert) { let route = this.subject(); assert.ok(route); });
Template[getTemplate('postMeta')].helpers({ pointsUnitDisplayText: function(){ return this.upvotes == 1 ? i18n.t('point') : i18n.t('points'); }, can_edit: function(){ return canEdit(Meteor.user(), this); }, authorName: function(){ return getAuthorName(this); }, ago: function(){ // if post is approved show submission time, else show creation time. time = this.status == STATUS_APPROVED ? this.postedAt : this.createdAt; return moment(time).fromNow(); }, profileUrl: function(){ // note: we don't want the post to be re-rendered every time user properties change var user = Meteor.users.findOne(this.userId, {reactive: false}); if(user) return getProfileUrl(user); }, domain: function(){ var a = document.createElement('a'); a.href = this.url; return a.hostname; } });