code stringlengths 2 1.05M |
|---|
var expect = require('expect.js'),
options = require('../lib/options');
describe("options", function() {
describe("#firstNumberTest", function() {
it("should be true when divisble by 3", function() {
expect(options.firstNumberTest(3,3)).to.be(true);
});
it("should be false when divisble by 3", function() {
expect(options.firstNumberTest(8,3)).to.be(false);
});
});
describe("#secondNumberTest", function() {
it("should be true when divisble by 5", function() {
expect(options.secondNumberTest(5,5)).to.be(true);
});
it("should be false when divisble by 5", function() {
expect(options.secondNumberTest(8,5)).to.be(false);
});
});
describe("#noSuccess", function() {
it("should return a string of the number given", function() {
expect(options.noSuccess(4)).to.equal("4");
});
});
}); |
'use strict';
/**
* @module
* @copyright paywell Team at byteskode <www.byteskode.com>
* @description redis client factories
* @since 0.1.0
* @author lally elias<lallyelias87@gmail.com, lally.elias@byteskode.com>
* @singleton
* @public
*/
//dependencies
const path = require('path');
const redis = require('redis');
const _ = require('lodash');
const uuid = require('uuid');
const noop = function () {};
//reference to all created redis clients
//mainly used for safe shutdown and resource cleanups
exports._clients = [];
//import and extend redis with hash utilities
const hash = require(path.join(__dirname, 'hash'));
hash.redis = exports;
exports.hash = hash;
//defaults settings
const defaults = {
prefix: 'paywell',
separator: ':',
redis: {
port: 6379,
host: '127.0.0.1'
}
};
/**
* @name defaults
* @description default redis client connection options
* @type {Object}
* @since 0.1.0
* @public
*/
exports.defaults = _.merge({}, defaults);
/**
* @function
* @name createClient
* @description instantiate new redis client if not exists
* @return {Object} an instance of redis client
* @since 0.1.0
* @public
*/
exports.createClient = function (options) {
//merge options
options = _.merge({}, exports.defaults, options);
//instantiate a redis client
const socket = options.redis.socket;
const port = !socket ? (options.redis.port || 6379) : null;
const host = !socket ? (options.redis.host || '127.0.0.1') : null;
const client =
redis.createClient(socket || port, host, options.redis.options);
//authenticate
if (options.redis.auth) {
client.auth(options.redis.auth);
}
//select database
if (options.redis.db) {
client.select(options.redis.db);
}
//remember created client(s) for later safe shutdown
exports._clients = _.compact([].concat(exports._clients).concat(client));
return client;
};
/**
* @function
* @name init
* @description initialize redis client and pubsub
* @return {Object} redis client
* @since 0.1.0
* @public
*/
exports.init = exports.client = function () {
//initialize normal client
if (!exports._client) {
exports._client = exports.createClient();
exports._client._id = Date.now();
}
//initialize publisher and subscriber clients
exports.pubsub();
//return a normal redis client
return exports._client;
};
/**
* @function
* @name pubsub
* @description instantiate redis pub-sub clients pair if not exists
* @since 0.1.0
* @public
*/
exports.pubsub = function () {
//create publisher if not exists
if (!exports.publisher) {
exports.publisher = exports.createClient();
exports.publisher._id = Date.now();
}
//create subscriber if not exist
if (!exports.subscriber) {
exports.subscriber = exports.createClient();
exports.subscriber._id = Date.now();
}
//exports pub/sub clients
return { publisher: exports.publisher, subscriber: exports.subscriber };
};
/**
* @function
* @name multi
* @description initialize redis multi command object
* @return {Object} redis multi command object
* @since 0.3.0
* @see {@link https://github.com/NodeRedis/node_redis#clientmulticommands}
* @public
*/
exports.multi = function () {
//ensure clients
const client = exports.init();
//obtain client
const multi = client.multi();
return multi;
};
/**
* @function
* @name info
* @description collect redis server health information
* @param {Function} done a callback to invoke on success or failure
* @return {Object} server details
* @since 0.1.0
* @public
*/
exports.info = function (done) {
//ensure connection
exports.init();
exports.client().info(function (error /*, info*/ ) {
// jshint camelcase:false
done(error, exports._client.server_info);
// jshint camelcase:true
});
};
/**
* @function
* @name key
* @description prepare data storage key
* @param {String|String[]} key valid data store key
* @since 0.1.0
* @public
*/
exports.key = function (...args) {
//concatenate key is varargs
let key = [].concat(...args);
//ensure key
if (key.length === 0) {
key = key.concat(uuid.v1());
}
key = [exports.defaults.prefix].concat(key);
//join key using separator
key = key.join(exports.defaults.separator);
return key;
};
/**
* @function
* @name reset
* @description quit and reset redis clients states
* @since 0.1.0
* @public
*/
exports.reset = exports.quit = function () {
//clear subscriptions and listeners
if (exports.subscriber) {
exports.subscriber.unsubscribe();
exports.subscriber.removeAllListeners();
}
//quit all clients
_.forEach(exports._clients, function (_client) {
//TODO do they shutdown immediately
//TODO check kue how they handle this
_client.quit();
});
//reset clients
exports._client = null;
exports.publisher = null;
exports.subscriber = null;
//reset settings
exports.defaults = _.merge({}, defaults);
//reset clients
exports._clients = [];
};
/**
* @function
* @name clear
* @description clear all data saved and their key
* @param {String} [pattern] pattern of keys to be removed
* @param {Function} done a callback to invoke on success or failure
* @since 0.1.0
* @public
*/
exports.clear = function (pattern, done) {
//TODO clear hash search index
//normalize arguments
if (pattern && _.isFunction(pattern)) {
done = pattern;
pattern = undefined;
}
//ensure callback
if (!done) {
done = noop;
}
//prepare clear all key regex
pattern = _.compact([exports.defaults.prefix, pattern]);
if (pattern.length > 1) {
pattern = pattern.join(exports.defaults.separator);
}
pattern = [pattern].concat(['*']).join('');
//ensure client
exports.init();
//clear data
exports.client().keys(pattern, function (error, keys) {
//back-off in case there is error
if (error) {
done(error);
} else {
//initiate multi to run all commands atomically
var _client = exports.multi();
//queue commands
_.forEach(keys, function (key) {
_client.del(key);
});
//execute commands
_client.exec(done);
}
});
}; |
"use strict";
exports.__esModule = true;
exports.default = createTemplateBuilder;
var _options = require("./options");
var _string = _interopRequireDefault(require("./string"));
var _literal = _interopRequireDefault(require("./literal"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var NO_PLACEHOLDER = (0, _options.validate)({
placeholderPattern: false
});
function createTemplateBuilder(formatter, defaultOpts) {
var templateFnCache = new WeakMap();
var templateAstCache = new WeakMap();
var cachedOpts = defaultOpts || (0, _options.validate)(null);
return Object.assign(function (tpl) {
for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
if (typeof tpl === "string") {
if (args.length > 1) throw new Error("Unexpected extra params.");
return extendedTrace((0, _string.default)(formatter, tpl, (0, _options.merge)(cachedOpts, (0, _options.validate)(args[0]))));
} else if (Array.isArray(tpl)) {
var builder = templateFnCache.get(tpl);
if (!builder) {
builder = (0, _literal.default)(formatter, tpl, cachedOpts);
templateFnCache.set(tpl, builder);
}
return extendedTrace(builder(args));
} else if (typeof tpl === "object" && tpl) {
if (args.length > 0) throw new Error("Unexpected extra params.");
return createTemplateBuilder(formatter, (0, _options.merge)(cachedOpts, (0, _options.validate)(tpl)));
}
throw new Error("Unexpected template param " + typeof tpl);
}, {
ast: function ast(tpl) {
for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {
args[_key2 - 1] = arguments[_key2];
}
if (typeof tpl === "string") {
if (args.length > 1) throw new Error("Unexpected extra params.");
return (0, _string.default)(formatter, tpl, (0, _options.merge)((0, _options.merge)(cachedOpts, (0, _options.validate)(args[0])), NO_PLACEHOLDER))();
} else if (Array.isArray(tpl)) {
var builder = templateAstCache.get(tpl);
if (!builder) {
builder = (0, _literal.default)(formatter, tpl, (0, _options.merge)(cachedOpts, NO_PLACEHOLDER));
templateAstCache.set(tpl, builder);
}
return builder(args)();
}
throw new Error("Unexpected template param " + typeof tpl);
}
});
}
function extendedTrace(fn) {
var rootStack = "";
try {
throw new Error();
} catch (error) {
if (error.stack) {
rootStack = error.stack.split("\n").slice(3).join("\n");
}
}
return function (arg) {
try {
return fn(arg);
} catch (err) {
err.stack += "\n =============\n" + rootStack;
throw err;
}
};
} |
var passport = require('passport'),
jwt = require('jsonwebtoken'),
extend = require('json-extend'),
common = require('./common'),
Client = require('./client');
function Strategy(identifier, config) {
if(typeof(identifier) === 'object') {
config = identifier;
identifier = 'identity3-oidc';
}
if(!config || !config.client_id || !config.client_secret || !config.callback_url) {
throw new Error('The required config settings are not present [client_id, client_secret, callback_url]');
}
if(!config.jwt) {
config.jwt = {
audience: config.audience || config.client_id,
issuer: config.issuer,
ignoreNotBefore: config.ignoreNotBefore || false,
ignoreExpiration: config.ignoreExpiration || false
};
}
passport.Strategy.call(this);
this.name = identifier;
this.config = config;
this.client = new Client(config);
if(config.configuration_endpoint) {
this.discover(config);
}
}
require('util').inherits(Strategy, passport.Strategy);
/*********** Passport Strategy Impl ***********/
Strategy.prototype.authenticate = function(req, options) {
if(req.query.error) {
return this.error(new Error(req.query.error));
} else if(req.query.code) {
if(!req.session.tokens || req.query.state !== req.session.tokens.state) {
return this.error(new Error('State does not match session.'));
}
var self = this,
config = self.config;
this.client.getTokens(req, function(err, data) {
var user;
if(err) {
self.error(err);
} else if(user = self.validateToken(data.id_token)) {
if(config.transformIdentity) {
if(config.transformIdentity.length === 1) {
user = config.transformIdentity(user);
self.success(user);
} else {
config.transformIdentity(user, self.success, self.error);
}
} else {
self.success(user);
}
} else {
req.session.tokens = null;
}
});
} else {
var state = common.randomHex(16);
req.session.tokens = {
state: state
};
this.redirect(this.client.authorizationUrl(req, state));
}
};
/*********** End Passport Strategy Impl ***********/
// 5.3. UserInfo Endpoint [http://openid.net/specs/openid-connect-core-1_0.html#UserInfo]
Strategy.prototype.profile = function(req, scopes, claims, callback) {
this.client.getProfile(req, scopes, claims, callback);
};
// 5. RP-Initiated Logout [http://openid.net/specs/openid-connect-session-1_0.html#RPLogout]
Strategy.prototype.endSession = function(req, res) {
var endSessionUrl = this.client.getEndSessionUrl(req);
// Clean up session for passport just in case express session is not being used.
req.logout();
req.session.tokens = null;
// Destroy express session if possible
if(req.session && req.session.destroy) {
req.session.destroy();
}
// Allow app to do some cleanup if needed
if(this.config.onEndSession) {
this.config.onEndSession(req, res);
}
res.redirect(endSessionUrl);
};
// 3.1.3.7. ID Token Validation [http://openid.net/specs/openid-connect-core-1_0.html#IDTokenValidation]
Strategy.prototype.validateToken = function(token) {
try {
var cert;
if(!this.config.keys || !this.config.keys.length) {
this.error(new Error('No keys configured for verifying tokens'));
return false;
}
cert = common.formatCert(this.config.keys[0].x5c[0]);
return jwt.verify(token, cert, this.config.jwt);
} catch (e) {
this.error(e);
}
};
// 4. Obtaining OpenID Provider Configuration Information [http://openid.net/specs/openid-connect-discovery-1_0.html#ProviderConfig]
Strategy.prototype.discover = function(config) {
var self = this,
origAuth = self.authenticate,
pendingAuth = [];
// overwrite authentication to pause the auth requests while we are discovering.
self.authenticate = function(req, options) {
pendingAuth.push([this, req, options]);
};
common.json('GET', config.configuration_endpoint, null, null, function(err, data) {
if(err) { throw err; }
extend(config, data);
if(config.jwt) {
config.jwt.issuer = config.issuer;
}
common.json('GET', data.jwks_uri, null, null, function(err, data) {
if(err) { throw err; }
extend(config, data);
self.authenticate = origAuth;
pendingAuth.forEach(function(pending) {
var self = pending.shift();
origAuth.apply(self, pending);
});
// Remove refs to allow gc.
pendingAuth = null;
});
});
};
module.exports = Strategy;
|
import http from 'http' // HTTP Server
import express from 'express' // HTTP improvements
import bodyParser from 'body-parser' // Parse JSON
import cors from 'cors' // Cross-origin resource sharing
import blocked from 'blocked' // detect if a node event loop is blocked
import api from '~/api'
import config from '~/config'
import logger from '~/logger'
import { toBoolean } from '~/utils'
blocked(ms => logger.warn(`node blocked for ${ms}ms`))
// define web server
const app = express()
app.server = http.createServer(app)
app.disable('x-powered-by') // https://github.com/helmetjs/hide-powered-by
app.use(bodyParser.json())
// bodyParser error handling
app.use((err, req, res, next) => {
if (err instanceof SyntaxError && err.statusCode === 400) {
logger.error('likely a bodyParser error', err.message, err.stack)
res.status(400).json({ errors: ['invalid json'] })
} else {
next(err)
}
})
if (toBoolean(config.cors)) {
app.use(cors()) // https://github.com/expressjs/cors#simple-usage-enable-all-cors-requests
app.options('*', cors()) // https://github.com/expressjs/cors#enabling-cors-pre-flight
}
// logging middleware
app.use((req, res, next) => {
logger.verbose(`${new Date().toISOString()} ${req.method} ${req.path}`)
next()
})
// define routes here, before catch-all functions, after cors setup and logging middlware
app.use('/api/v1', api())
// 404
app.use((req, res) => {
res.status(404).json({ errors: [`cannot ${req.method} ${req.path}`] })
})
// 500
app.use((err, req, res, next) => {
logger.error('catch-all error', err.message, err.stack)
res.status(500).json({ errors: ['catch-all server error, check the logs'] })
})
// validate config
const requiredProviderInfo = ['type', 'priority', 'limit', 'path']
const requiredHttpProviderInfo = ['key', 'url', 'timeout']
const requiredPgProviderInfo = ['host', 'port', 'database', 'user', 'password', 'sql']
Object.keys(config.providers).forEach(provider => {
requiredProviderInfo.forEach(info => {
if (config.providers[provider][info] === undefined) {
throw new Error(`Provider ${provider} is missing ${info} information`)
}
})
requiredHttpProviderInfo.forEach(info => {
if (config.providers[provider][info] === undefined && config.providers[provider].type === 'http') {
throw new Error(`Provider ${provider} is missing ${info} information`)
}
})
requiredPgProviderInfo.forEach(info => {
if (config.providers[provider][info] === undefined && config.providers[provider].type === 'pg') {
throw new Error(`Provider ${provider} is missing ${info} information`)
}
})
})
export default app
|
// Description of supported double byte encodings and aliases.
// Tables are not require()-d until they are needed to speed up library load.
// require()-s are direct to support Browserify.
module.exports = {
// == Japanese/ShiftJIS ====================================================
// All japanese encodings are based on JIS X set of standards:
// JIS X 0201 - Single-byte encoding of ASCII + ¥ + Kana chars at 0xA1-0xDF.
// JIS X 0208 - Main set of 6879 characters, placed in 94x94 plane, to be encoded by 2 bytes.
// Has several variations in 1978, 1983, 1990 and 1997.
// JIS X 0212 - Supplementary plane of 6067 chars in 94x94 plane. 1990. Effectively dead.
// JIS X 0213 - Extension and modern replacement of 0208 and 0212. Total chars: 11233.
// 2 planes, first is superset of 0208, second - revised 0212.
// Introduced in 2000, revised 2004. Some characters are in Unicode Plane 2 (0x2xxxx)
// Byte encodings are:
// * Shift_JIS: Compatible with 0201, uses not defined chars in top half as lead bytes for double-byte
// encoding of 0208. Lead byte ranges: 0x81-0x9F, 0xE0-0xEF; Trail byte ranges: 0x40-0x7E, 0x80-0x9E, 0x9F-0xFC.
// Windows CP932 is a superset of Shift_JIS. Some companies added more chars, notably KDDI.
// * EUC-JP: Up to 3 bytes per character. Used mostly on *nixes.
// 0x00-0x7F - lower part of 0201
// 0x8E, 0xA1-0xDF - upper part of 0201
// (0xA1-0xFE)x2 - 0208 plane (94x94).
// 0x8F, (0xA1-0xFE)x2 - 0212 plane (94x94).
// * JIS X 208: 7-bit, direct encoding of 0208. Byte ranges: 0x21-0x7E (94 values). Uncommon.
// Used as-is in ISO2022 family.
// * ISO2022-JP: Stateful encoding, with escape sequences to switch between ASCII,
// 0201-1976 Roman, 0208-1978, 0208-1983.
// * ISO2022-JP-1: Adds esc seq for 0212-1990.
// * ISO2022-JP-2: Adds esc seq for GB2313-1980, KSX1001-1992, ISO8859-1, ISO8859-7.
// * ISO2022-JP-3: Adds esc seq for 0201-1976 Kana set, 0213-2000 Planes 1, 2.
// * ISO2022-JP-2004: Adds 0213-2004 Plane 1.
//
// After JIS X 0213 appeared, Shift_JIS-2004, EUC-JISX0213 and ISO2022-JP-2004 followed, with just changing the planes.
//
// Overall, it seems that it's a mess :( http://www8.plala.or.jp/tkubota1/unicode-symbols-map2.html
'shiftjis': {
type: '_dbcs',
table: function() { return require('./tables/shiftjis.json') },
encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E},
encodeSkipVals: [{from: 0xED40, to: 0xF940}],
},
'csshiftjis': 'shiftjis',
'mskanji': 'shiftjis',
'sjis': 'shiftjis',
'windows31j': 'shiftjis',
'xsjis': 'shiftjis',
'windows932': 'shiftjis',
'932': 'shiftjis',
'cp932': 'shiftjis',
'eucjp': {
type: '_dbcs',
table: function() { return require('./tables/eucjp.json') },
encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E},
},
// TODO: KDDI extension to Shift_JIS
// TODO: IBM CCSID 942 = CP932, but F0-F9 custom chars and other char changes.
// TODO: IBM CCSID 943 = Shift_JIS = CP932 with original Shift_JIS lower 128 chars.
// == Chinese/GBK ==========================================================
// http://en.wikipedia.org/wiki/GBK
// Oldest GB2312 (1981, ~7600 chars) is a subset of CP936
'gb2312': 'cp936',
'gb231280': 'cp936',
'gb23121980': 'cp936',
'csgb2312': 'cp936',
'csiso58gb231280': 'cp936',
'euccn': 'cp936',
'isoir58': 'gbk',
// Microsoft's CP936 is a subset and approximation of GBK.
// TODO: Euro = 0x80 in cp936, but not in GBK (where it's valid but undefined)
'windows936': 'cp936',
'936': 'cp936',
'cp936': {
type: '_dbcs',
table: function() { return require('./tables/cp936.json') },
},
// GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other.
'gbk': {
type: '_dbcs',
table: function() { return require('./tables/cp936.json').concat(require('./tables/gbk-added.json')) },
},
'xgbk': 'gbk',
// GB18030 is an algorithmic extension of GBK.
'gb18030': {
type: '_dbcs',
table: function() { return require('./tables/cp936.json').concat(require('./tables/gbk-added.json')) },
gb18030: function() { return require('./tables/gb18030-ranges.json') },
},
'chinese': 'gb18030',
// TODO: Support GB18030 (~27000 chars + whole unicode mapping, cp54936)
// http://icu-project.org/docs/papers/gb18030.html
// http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml
// http://www.khngai.com/chinese/charmap/tblgbk.php?page=0
// == Korean ===============================================================
// EUC-KR, KS_C_5601 and KS X 1001 are exactly the same.
'windows949': 'cp949',
'949': 'cp949',
'cp949': {
type: '_dbcs',
table: function() { return require('./tables/cp949.json') },
},
'cseuckr': 'cp949',
'csksc56011987': 'cp949',
'euckr': 'cp949',
'isoir149': 'cp949',
'korean': 'cp949',
'ksc56011987': 'cp949',
'ksc56011989': 'cp949',
'ksc5601': 'cp949',
// == Big5/Taiwan/Hong Kong ================================================
// There are lots of tables for Big5 and cp950. Please see the following links for history:
// http://moztw.org/docs/big5/ http://www.haible.de/bruno/charsets/conversion-tables/Big5.html
// Variations, in roughly number of defined chars:
// * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT
// * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/
// * Big5-2003 (Taiwan standard) almost superset of cp950.
// * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported |
/*
--> carouselit jQuery Plugin <--
author : Horacio Herrera
website : hherrerag.com
twitter : @hhg2288
email: : me@hherrerag.com
description : plugin to made a simple carousel of list objects
SYNTAX:
$("yourSelector").carouselit({
step ---> how many blocks it move ,
visible ---> how many block are visible ,
speed ---> in miliseconds ,
liSize ---> width of every li object in pixels ,
prevBtn ---> selector of previews anchor object ,
nextBtn ---> selector of next anchor object
});
*/
(function($) {
$.fn.carouselit = function( options ){
var settings = {
'step' : 1, // How many objects will move when next/prev button is pressed
'visible' : 1, // How many objects are visible
'speed' : 1000, // How fast will be the animation
'liSize' : 0, // width of every object, should be the same to all (for now)
'prevBtn' : '#prev', // object id that will be the 'previews' anchor
'nextBtn' : '#next', // object id that will be the 'next' anchor
'hasPagination' : false,
'_current' : '',
'_maximun' : '',
'threshold' : {
x: 10,
y: 10
},
'preventDefaultEvents': true
};
return this.each(function(){
if ( options ) { // If options exist, lets merge them
$.extend( settings, options ); // with our default settings
}
var $this = $(this);
var container = $this.children();
var maximum = $(container).find('li').size();
var carousel_height = $this.height()+20;
var current = 0;
var ulSize = settings.liSize * maximum;
var divSize = settings.liSize * settings.visible;
var pagination = ((maximum - settings.visible) / settings.step) + 1;
var pager = 1;
// Private variables for each element
var originalCoord = { x: 0, y: 0 };
var finalCoord = { x: 0, y: 0 };
// adding some css to the container object (ul)
$(container).css({"width" : ulSize+"px", // setting the total width of the container object to the total widht of all 'li' childs
"left" : current * settings.liSize, // starting position for the container
"position" : "absolute" // setting it to absolute to get control of it for future positioning changes
});
// adding some css to the wrapper object (the one you call) ; this element works as a mask for the container, is the visible area of your carousel
$this.css({ "width" : divSize+"px", // setting the width of the mask or wrapper
"height" : carousel_height+"px", // setting the height of the element
"visibility" : "visible",
"overflow" : "hidden",
"position" : "relative" // this is to set the absolute position of the container relative to this element,
// and not relative to the whole HTML
});
if (current == 0){
$(settings.prevBtn).addClass('disable'); // conditional to hide
if (settings.hasPagination) { $(settings._maximun).append(pagination); }
}
function moveLeft(){
if(current + settings.step < 0 || current + settings.step > maximum - settings.visible) {return; }
else {
current = current + settings.step;
pager++;
$(container).animate({left: -(settings.liSize * current)}, settings.speed, null);
$(settings.prevBtn).removeClass('disable');
if (settings.hasPagination) { $(settings._current).empty().append(pager); }
if (current + settings.step == maximum) { $(settings.nextBtn).addClass('disable'); }
}
}
function moveRight(){
if(current - settings.step < 0 || current - settings.step > maximum - settings.visible) {
$(this).addClass('disable');
return;
} else {
current = current - settings.step;
pager--;
$(container).animate({left: -(settings.liSize * current)}, settings.speed, null);
$(settings.nextBtn).removeClass('disable');
if (settings.hasPagination) { $(settings._current).empty().append(pager); }
if (current == 0) { $(settings.prevBtn).addClass('disable'); }
}
}
$(settings.nextBtn).click(function(e) {
e.preventDefault();
moveLeft();
return false;
});
$(settings.prevBtn).click(function(e) {
e.preventDefault();
moveRight();
return false;
});
// Screen touched, store the original coordinate
function touchStart(event) {
console.log('Starting swipe gesture...')
originalCoord.x = event.targetTouches[0].pageX
originalCoord.y = event.targetTouches[0].pageY
}
// Store coordinates as finger is swiping
function touchMove(event) {
if (settings.preventDefaultEvents)
event.preventDefault();
finalCoord.x = event.targetTouches[0].pageX // Updated X,Y coordinates
finalCoord.y = event.targetTouches[0].pageY
}
// Done Swiping
// Swipe should only be on X axis, ignore if swipe on Y axis
// Calculate if the swipe was left or right
function touchEnd(event) {
//console.log('Ending swipe gesture...')
var changeX = originalCoord.x - finalCoord.x;
if(changeX > settings.threshold.x) {
moveLeft();
//console.log('entro a condicional izq');
}
if(changeX < (settings.threshold.x*-1)) {
moveRight();
//console.log('entro a condicional derecha');
}
}
// Swipe was canceled
function touchCancel(event) {
//console.log('Canceling swipe gesture...')
}
// Add gestures to all swipable areas
this.addEventListener("touchstart", touchStart, false);
this.addEventListener("touchmove", touchMove, false);
this.addEventListener("touchend", touchEnd, false);
this.addEventListener("touchcancel", touchCancel, false);
});
}
})(jQuery);
|
var models = require('../database');
var config = require('../config/config');
var Boom = require('boom');
var Joi = require('joi');
// private internal functions
var internals = {};
exports.login = {
tags: ['auth', 'login'],
description: "App login endpoint with cookie session init",
auth: {
mode: 'try',
strategy: 'session'
},
plugins: {
'hapi-auth-cookie': {
redirectTo: false
}
},
validate: {
payload: {
network: Joi.string().valid(config.login.validNetworks).required(),
email: Joi.string().email().max(60),
password: Joi.string().min(6).max(60)
}
},
pre: [{
assign: 'isLoggedin',
method: function(request, reply){
if (request.auth.isAuthenticated) {
//return reply.redirect('/');
}
reply();
}
},{
assign: 'isLoginAbuse',
method: function(request, reply){
var emailAddress = request.payload.email.toLowerCase();
var ipAddress = (request.info.remoteAddress) ? request.info.remoteAddress : ' ';
models.Authattempt.findAll({email:emailAddress, ip:ipAddress}).then(function(collection){
if(!collection){
return reply();
}
if(collection.length >= config.login.maxAllowedAttempts){
return reply(Boom.badRequest('Maximum number of attempts reached.'));
}
return reply();
}).catch(function(error){
if(error){
return reply(Boom.badRequest(error));
}
});
}
},{
assign: 'user',
method: function(request, reply){
var emailAddress = request.payload.email.toLowerCase();
var password = request.payload.password;
models.User.findByCredentials({email: emailAddress, password:password}).then(function (userRecord) {
if(userRecord){
return reply (userRecord.toJSON());
}
return reply();
}).catch(function(error){
if(error){
//@TODO: log db error ?
}
return reply();
});
}
},{
assign: 'logAttempt',
method: function(request, reply){
// credentials are valid, and a user object was returned, so let's create a session.
if (request.pre.user){
return reply();
}
// credentials are NOT valid, log user attempt.
var emailAddress = request.payload.email.toLowerCase();
var ipAddress = (request.info.remoteAddress) ? request.info.remoteAddress : ' ';
return models.Authattempt.add({email:emailAddress, ip:ipAddress}).then(function(result){
//@TODO: check for account status.
return reply(Boom.badRequest('Email and password combination do not match.'));
}).catch(function (error) {
if(error){
//@TODO: log db error ?
}
return reply(Boom.badRequest(error));
});
}
}],
handler: function (request, reply) {
request.server.app.cache.set( String(request.pre.user.id), { user: request.pre.user }, 0, (err) => {
if (err) {
reply(err);
}
request.cookieAuth.set({id: request.pre.user.id });
return reply([]);
});
}
};
exports.logout = {
tags: ['auth', 'logout'],
description: "App logut and remove session",
auth: 'session',
handler: function (request, reply) {
request.cookieAuth.clear();
return reply();
}
};
exports.facebook = {
tags: ['auth', 'social login', 'facebook'],
description: "App login via facebook",
auth: 'facebook',
pre: [
{
assign: 'isLoggedin',
method: function(request, reply){
//check to see if a session exists or if they approved social login.
if (request.auth.isAuthenticated) {
return reply.redirect('/');
}
reply();
}
},
{
assign: 'user',
method: function(request, reply){
var payload = {
network:request.auth.credentials.provider,
token:request.auth.credentials.profile.raw.id
};
return models.findOne(payload).then(function (userRecord) {
if(userRecord){
return reply ({user: [userRecord.toJSON()]});
}
return reply(Boom.badRequest(error));
});
}
},
],
handler: function (request, reply) {
if (request.pre.user){
return reply.redirect('/');
}else{
return reply(Boom.badRequest('Please register.'));
}
// console.log('request method: ' + request.method);
// console.log('request.auth');
// console.log(request.auth);
// console.log('request.auth.credentials.profile.raw');
// console.log(request.auth.credentials.profile.raw.id);
}
}; |
'use strict';
exports.redis = {
client: {
host: '127.0.0.1',
port: 6379,
password: '',
db: '0',
},
agent: true,
};
exports.keys = 'keys';
|
export { default } from './DeviceChanger';
|
'use strict';
const R = require('ramda');
const Bluebird = require('bluebird');
const OtomatkError = require('./error');
class Expressify {
constructor(model) {
this.model = model;
}
nextErr(next) {
return (err) => next(new OtomatkError(err));
}
query() {
var _model = this.model;
var _error = this.nextErr;
return (req, res, next) => {
let q = req.query.q;
let options = req.query.options;
let fields = req.query.fields;
Bluebird
.try(() => {
let Cursor = _model.find(q, fields || {});
if (options && options.skip) {
Cursor = Cursor.skip(options.skip);
}
if (options && options.sort) {
Cursor = Cursor.sort(options.sort);
}
if (options && options.limit) {
Cursor = Cursor.limit(options.limit);
}
return Cursor.toArray();
})
.then((data) => {
if (!data) {
return next(new OtomatkError('Error in evaluating cursor data'));
}
res.json(R.map(x => x.toJSON(), data));
})
.catch(_error(next));
};
}
detail() {
var _model = this.model;
var _error = this.nextErr;
return (req, res, next) => {
let id = req.params.id || null;
_model.findOne(id).then((data) => {
res.json(data.toJSON());
}).catch(_error(next));
};
}
save() {
var _model = this.model;
var _error = this.nextErr;
return (req, res, next) => {
var data = req.body || null;
var id = req.params.id || null;
if (!R.isArrayLike(data) && (data._id || data.id) && id) {
var changes = R.pickBy((v, k) => ['_id', 'id'].indexOf(k), data);
_model.get(data._id || data.id)
.then((m) => m.save(changes))
.then((updated) => res.json(updated.toJSON()))
.catch(_error(next));
} else {
_model.create(data, { upsert: true })
.then((data) => res.json(data.length ? R.map(x => x.toJSON()) : data.toJSON()))
.catch(_error(next));
}
}
}
remove() {
var _model = this.model;
var _error = this.nextErr;
return (req, res, next) => {
var id = req.params.id || null;
_model.remove(id).then((removed) => {
res.json({ removed: removed });
}).catch(_error(next));
};
}
}
module.exports = Expressify; |
module.exports = {
entry: './example/index.js',
output: {
filename: 'bundle.js'
},
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel-loader',
options: {
forceEnv: 'browser'
}
},
{
test: /\.css/,
use: ['style-loader', 'css-loader']
}
]
},
resolve: {
alias: {
crossfilter: 'crossfilter2'
}
}
};
|
/**
* Created by Pencroff on 05.01.2015.
*/
module.exports = {
primaryKey:'id',
identity: 'pet',
datastore: 'flat',
attributes: {
id: { type: 'number', autoMigrations: { autoIncrement: true, columnType:'integer' } },
name: {type: 'string',autoMigrations: { columnType:'text' } },
breed: {type: 'string',autoMigrations: { columnType:'text' } }
}
}; |
var _ = require('underscore'),
nconf = require('nconf'),
fs = require('fs'),
path = require('path'),
utils = require('./lib/utility');
// Default nconf
nconf.use('memory');
_.each({
debug: false
}, function(v, k) {
nconf.set(k, v);
});
// New stuff!
var Manager = require('./lib/manager'),
main = new Manager();
/**
* Load up main
*/
// Find and register Types
var type_folder = path.join(__dirname, "lib/types");
_.each(fs.readdirSync(type_folder), function(file) {
if (path.extname(file) === ".js") {
require(path.join(type_folder, file))(main);
}
});
// Find and register Load functions
var load_folder = path.join(__dirname, "lib/loads");
_.each(fs.readdirSync(load_folder), function(file) {
if (path.extname(file) === ".js") {
var res = require(path.join(load_folder, file))();
if (_.isArray(res)) main.register_load.apply(main, res)
}
});
// Default storage engine
main.register_storage("memory");
module.exports = function(options) {
// Set up app-wide options
if (_.isObject(options))
_.each(options, function(v, k) { nconf.set(k, v); });
// Return manager object
return main;
} |
// borrow from universal-redux-boilerplate
// https://github.com/savemysmartphone/universal-redux-boilerplate
export default class ReduxResolver {
constructor () {
this.pending = []
this.firstRendering = true
}
resolve (action) {
const [, ...args] = arguments
if (process.env.BROWSER && !this.firstRendering) {
return action(...args)
} else {
this.pending = [
...this.pending,
{ action, args }
]
}
}
async dispatch () {
await Promise.all(
this.pending.map(({ action, args }) => {
return action(...args)
}
))
}
clear () {
this.pending = []
this.firstRendering = false
}
}
|
module.exports = exports = {
lang: 'zh-cn',
newglyph: '新字形',
undo: '撤销',
redo: '重做',
import: '导入',
import_svg: '导入svg',
import_svg_title: '导入svg格式字体文件',
import_pic: '导入图片',
import_pic_title: '导入包含字形的图片',
import_font: '导入字体文件',
import_font_title: '导入ttf,woff,eot,otf格式字体文件',
export_ttf: '导出ttf',
export_woff: '导出woff',
export_zip: '导出zip,包含ttf,woff,eot,svg等格式字体和icon示例',
save_proj: '保存项目',
onlinefont: '线上字体',
fonturl: '字体URL',
tool: '工具',
gen_glyph_name: '生成字形名称',
clear_glyph_name: '清除字形名称',
optimize_glyph: '优化字体',
compound2simple: '复合字形转简单字形',
preview: '预览',
preview_ttf: 'ttf字体',
preview_woff: 'woff字体',
preview_svg: 'svg字体(仅safari)',
preview_eot: 'eot字体(仅IE)',
new_font: '新建',
new_font_title: '新建ttf字体文件',
open_font: '打开',
open_font_title: '打开ttf,woff,eot,otf格式字体文件',
project_list: '项目列表',
close_editor: '点击或者按`F2`键关闭编辑器',
metrics: '字体度量',
editor_setting: '编辑器设置',
import_and_export: '导入和导出',
setting: '设置',
help: '帮助',
confirm: '确定',
cancel: '取消',
fontinfo: '字体信息'
};
|
'use strict';
var gulp = require('gulp');
var del = require('del');
var concat = require('gulp-concat');
var stripDebug = require('gulp-strip-debug');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var gutil = require('gulp-util');
var runSequence = require('run-sequence');
gulp.task('clean', function (cb) {
del([
'build/**'
], cb);
});
gulp.task('build', function(callback) {
runSequence('clean', 'build-js', callback);
});
gulp.task('build-js', function() {
return gulp.src([
'app.js',
'services/*.js',
'data/providers.js'
])
.pipe(concat('angularjs-maillinker.debug.js'))
.pipe(gulp.dest('build/scripts'))
.pipe(stripDebug())
.pipe(concat('angularjs-maillinker.js'))
.pipe(gulp.dest('build/scripts'))
.pipe(uglify())
.pipe(rename('angularjs-maillinker.min.js'))
.pipe(gulp.dest('build/scripts'))
.on('error', gutil.log);
}); |
/**
* @ngdoc module
* @name material.components.buttons
* @description
*
* Button
*/
angular.module('material.components.button', [
'material.animations',
])
.directive('materialButton', [
MaterialButtonDirective
]);
/**
* @ngdoc directive
* @name materialButton
* @order 0
*
* @restrict E
*
* @description
* `<material-button type="" disabled noink>` is a button directive with optional ink ripples (default enabled).
*
* @param {boolean=} noink Flag indicates use of ripple ink effects
* @param {boolean=} disabled Flag indicates if the tab is disabled: not selectable with no ink effects
* @param {string=} type Optional attribute to specific button types (useful for forms); such as 'submit', etc.
*
* @usage
* <hljs lang="html">
* <material-button>Button</material-button>
* <br/>
* <material-button noink class="material-button-colored">
* Button (noInk)
* </material-button>
* <br/>
* <material-button disabled class="material-button-colored">
* Colored (disabled)
* </material-button>
* </hljs>
*/
function MaterialButtonDirective() {
return {
restrict: 'E',
transclude: true,
template: '<material-ripple start="center" initial-opacity="0.25" opacity-decay-velocity="0.75"></material-ripple>',
link: function(scope, element, attr, ctrl, transclude) {
// Put the content of the <material-button> inside after the ripple
transclude(scope, function(clone) {
element.append(clone);
});
//
configureInk(attr.noink);
configureButton(attr.type);
/**
* If the inkRipple is disabled, then remove the ripple area....
* NOTE: <material-ripple/> directive replaces itself with `<canvas.material-ink-ripple />` element
* @param isDisabled
*/
function configureInk(noInk) {
if ( noInk ) {
element.find('canvas').remove();
}
}
/**
* If a type attribute is specified, dynamically insert a <button> element.
* This is vital to allow <material-button> to be used as form buttons
* @param type
*/
function configureButton(type) {
var hasButton = !!element.find('button');
if (type && !hasButton) {
var innerButton = angular.element('<button>')
.attr('type', type)
.addClass('material-inner-button');
element.append(innerButton);
}
}
}
};
}
|
"use strict";
var __extends = (this && this.__extends) || (function () {
var extendStatics = Object.setPrototypeOf ||
({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
return function (d, b) {
extendStatics(d, b);
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
})();
Object.defineProperty(exports, "__esModule", { value: true });
var Lint = require("tslint");
var sprintf_js_1 = require("sprintf-js");
var walkerFactory_1 = require("./walkerFactory/walkerFactory");
var walkerFn_1 = require("./walkerFactory/walkerFn");
var function_1 = require("./util/function");
var Rule = (function (_super) {
__extends(Rule, _super);
function Rule() {
return _super !== null && _super.apply(this, arguments) || this;
}
Rule.validate = function (className, suffixList) {
return suffixList.some(function (suffix) { return className.endsWith(suffix); });
};
Rule.prototype.apply = function (sourceFile) {
return this.applyWithWalker(Rule.walkerBuilder(sourceFile, this.getOptions()));
};
return Rule;
}(Lint.Rules.AbstractRule));
Rule.metadata = {
ruleName: 'component-class-suffix',
type: 'style',
description: "Classes decorated with @Component must have suffix \"Component\" (or custom) in their name.",
descriptionDetails: "See more at https://angular.io/styleguide#!#02-03.",
rationale: "Consistent conventions make it easy to quickly identify and reference assets of different types.",
options: {
type: 'array',
items: {
type: 'string',
}
},
optionExamples: [
"true",
"[true, \"Component\", \"View\"]"
],
optionsDescription: "Supply a list of allowed component suffixes. Defaults to \"Component\".",
typescriptOnly: true,
};
Rule.FAILURE = 'The name of the class %s should end with the suffix %s ($$02-03$$)';
Rule.walkerBuilder = walkerFn_1.all(walkerFn_1.validateComponent(function (meta, suffixList) {
return function_1.Maybe.lift(meta.controller)
.fmap(function (controller) { return controller.name; })
.fmap(function (name) {
var className = name.text;
if (suffixList.length === 0) {
suffixList = ['Component'];
}
if (!Rule.validate(className, suffixList)) {
return [new walkerFactory_1.Failure(name, sprintf_js_1.sprintf(Rule.FAILURE, className, suffixList))];
}
});
}));
exports.Rule = Rule;
|
pageName=location.pathname.split('/').pop().split('.')[0]||'index';
siteTpl={};
$.when(
resload('css/style.css'),
resload('js/siteapi.js'),
resload('js/sitecontroller.js'),
resload('js/pages/'+pageName+'.js'),
resload('templates/header.html', siteTpl, 'header'),
resload('templates/'+pageName+'.html', siteTpl, pageName),
resload('templates/footer.html', siteTpl, 'footer')
).then(function(){
siteApi = new SiteApi();
siteCtl = new SiteController(siteApi,siteTpl);
siteCtl.renderPage(pageName);
});
|
var path = require('path');
var fakeson = require('./fakeson');
module.exports = function(folder, update) {
var cache = {};
return function(req, res) {
var url = req.url;
var fullpath = path.join(folder, req.url+'.fakeson');
try {
var jsonString;
if (!update && cache[fullpath]) {
jsonString = cache[fullpath];
} else {
jsonString = fakeson(fullpath);
cache[fullpath] = jsonString;
}
res.writeHead(200, {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
});
res.end(jsonString);
} catch(e) {
res.writeHead(500);
res.end(e.message);
}
}
}
|
import Layout from '../components/layout'
export default function Home() {
return (
<Layout>
<div>Hello World.</div>
</Layout>
)
}
|
module.exports = function(grunt) {
var os = require('os');
var ifaces = os.networkInterfaces();
var lookupIpAddress = null;
for (var dev in ifaces) {
if (dev !== "en1" && dev !== "en0") {
continue;
}
ifaces[dev].forEach(function(details) {
if (details.family === 'IPv4') {
lookupIpAddress = details.address;
}
});
}
//If an IP Address is passed
//we're going to use the ip/host from the param
//passed over the command line
//over the ip addressed that was looked up
var ipAddress = grunt.option('host') || lookupIpAddress;
// Project configuration.
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
// Task configuration.
shell: {
wraith: { // Visual Regression Testing
command: [
"cd tests/wraith",
"wraith capture config",
"../../"
].join('&&')
},
scssGlob: {
command: [
"sass -r sass-globbing source/sass/styles.scss:source/css/style.css",
"cd ./"
].join('&&')
}
},
clean: {
options: {
force: true
},
files: ['./public/patterns']
},
concat: {
options: {
stripBanners: true,
banner: '/* \n * <%= pkg.name %> - v<%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %> \n * \n * <%= pkg.author %>, and the web community.\n * Licensed under the <%= pkg.license %> license. \n * \n * Many thanks to Brad Frost and Dave Olsen for inspiration, encouragement, and advice. \n *\n */\n\n',
},
patternlab: {
src: './builder/patternlab.js',
dest: './builder/patternlab.js'
},
object_factory: {
src: './builder/object_factory.js',
dest: './builder/object_factory.js'
}
},
copy: {
main: {
files: [
{
expand: true,
cwd: './source/js/',
src: '*',
dest: './public/js/'
},
{
expand: true,
cwd: './source/css/',
src: 'style.css',
dest: './public/css/'
},
{
expand: true,
cwd: './source/images/',
src: ['*.png', '*.jpg', '*.gif', '*.jpeg'],
dest: './public/images/'
},
{
expand: true,
cwd: './source/images/sample/',
src: ['*.png', '*.jpg', '*.gif', '*.jpeg'],
dest: './public/images/sample/'
},
{
expand: true,
cwd: './source/fonts/',
src: '*',
dest: './public/fonts/'
},
{
expand: true,
cwd: './source/_data/',
src: 'annotations.js',
dest: './public/data/'
}
]
}
},
/*
CSS
*/
sass: {
dist: {
options: { // Target options
sourcemap: true
},
files: {
'public/css/style.css': 'source/css/style.scss'
}
}
},
cssmin: {
minify: {
expand: true,
cwd: 'public/css/',
src: ['style.css'],
dest: 'public/css/',
ext: '.min.css'
}
},
uncss: { // Removes unused css
dist: {
options: {
stylesheets: ['/css/style.css'],
htmlroot: 'public'
},
files: {
'public/css/style.css': ['public/patterns/**/*.html']
}
}
},
/*
Images
*/
svgmin: { // Task
options: { // Configuration that will be passed directly to SVGO
plugins: [{
removeViewBox: false
}, {
removeUselessStrokeAndFill: false
}, {
convertPathData: {
straightCurves: false // advanced SVGO plugin option
}
}]
},
dist: { // Target
files: [{ // Dictionary of files
expand: true, // Enable dynamic expansion.
cwd: 'source/images/', // Src matches are relative to this path.
src: ['**/*.svg'], // Actual pattern(s) to match.
dest: 'public/images/', // Destination path prefix.
ext: '.svg' // Dest filepaths will have this extension.
// ie: optimise img/src/branding/logo.svg and store it in img/branding/logo.min.svg
}]
}
},
"svg-sprites": {
"svg-sprite": {
options: {
spriteElementPath: "public/images/",
spritePath: "public/images/",
cssPath: "public/css/",
cssSuffix: "scss",
cssPrefix: "_",
sizes: {
std: 18
},
refSize: 17,
unit: 20
}
}
},
imagemin: { // Task
dynamic: {
files: [{
expand: true, // Enable dynamic expansion
cwd: 'source/images', // Src matches are relative to this path
src: ['**/*.{png,jpg,gif}'], // Actual patterns to match
dest: 'public/images' // Destination path prefix
}]
}
},
responsive_images: {
myTask: {
options: {
files: [{
expand: true,
src: ['source/images/**/*.{jpg,gif,png}'],
dest: 'source/images/responsive'
}]
}
}
},
/*
Performance & Testing
*/
'html-inspector': {
all: {
src: ['public/patterns/**/*.html', '!public/patterns/**/*escaped.html']
}
},
csscss: {
dist: {
src: ['source/css/style.scss']
}
},
cssmetrics: {
dev: {
src: [
'public/css/style.css'
]
},
prod: {
src: [
'public/css/style.min.css'
]
}
},
/*
Server Related
*/
watch: {
html: {
files: [
'source/_patterns/**/*.mustache',
'source/_patterns/**/*.hbs',
'source/_patterns/**/*.json',
'source/_data/*.json',
],
tasks: ['patternlab', 'copy'],
options: {
spawn: false,
livereload: true
}
},
styles: {
files: ['source/sass/**/*.scss'],
tasks: ['shell:scssGlob', 'copy'],
options: {
spawn: false
}
},
svgs: {
files: ['source/images/**/*.svg'],
tasks: ['shell:patternlab', 'svgmin', "svg-sprites"],
options: {
spawn: false,
livereload: true
}
},
imgs: {
files: ['source/images/**/*.{png,jpg,gif}'],
tasks: ['responsive_images', 'imagemin'],
options: {
spawn: false,
livereload: true
}
},
gruntfile: {
files: ['Gruntfile.js']
},
livereload: {
options: {
livereload: '<%= connect.options.livereload %>'
},
files: [
'public/*.html',
'{.tmp,public}/css/{,*/}*.css',
'{.tmp,public}/js/{,*/}*.js',
'public/images/{,*/}*.{png,jpg,jpeg,gif,webp,svg}'
]
}
},
connect: {
options: {
port: 9000,
// change this to '0.0.0.0' to access the server from outsideres
hostname: '0.0.0.0',
livereload: 35729
},
livereload: {
options: {
open: true,
base: [
'.tmp',
'public'
]
}
},
test: {
options: {
port: 9001,
base: [
'.tmp',
'test',
'public'
]
}
},
dist: {
options: {
base: 'source'
}
}
},
browserSync: {
bsFiles: {
src: 'public/css/style.css'
},
options: {
host: ipAddress,
watchTask: true
}
},
/*
Misc
*/
replace: {
ip: {
src: ['public/**/*.html'], // source files array (supports minimatch)
overwrite: true, // destination directory or file
replacements: [{
from: '0.0.0.0', // string replacement
to: ipAddress
}]
}
},
/*
JS
*/
jshint: {
options: {
"curly": true,
"eqnull": true,
"eqeqeq": true,
"undef": true,
"forin": true,
//"unused": true,
"node": true
},
patternlab: ['Gruntfile.js', './builder/lib/patternlab.js']
},
nodeunit: {
all: ['test/*_tests.js']
}
});
// load all grunt tasks
require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
grunt.registerTask('serve', function(target) {
if (target === 'dist') {
return grunt.task.run(['build', 'connect:dist:keepalive']);
}
grunt.task.run([
'sass',
'replace',
'connect:livereload',
//'browserSync',
'watch'
]);
});
//load the patternlab task
grunt.task.loadTasks('./builder/');
//if you choose to use scss, or any preprocessor, you can add it here
grunt.registerTask('default', ['clean', 'concat', 'patternlab', 'shell:scssGlob', 'copy', 'uncss', 'cssmin', 'cssmetrics:prod']);
grunt.registerTask('webapp', ['clean', 'concat', 'patternlab:web', 'shell:scssGlob', 'copy', 'uncss', 'cssmin', 'cssmetrics:prod']);
grunt.registerTask('wraith', ['shell:wraith']);
grunt.registerTask('test', ['csscss', 'cssmetrics:dev']);
//travis CI task
grunt.registerTask('travis', ['clean', 'concat', 'patternlab', /*'sass',*/ 'copy', 'nodeunit']);
};
|
var db = require('./db')
var prop = process.argv[2]
var value = process.argv[3]
db.sublevel('index')
.createQueryStream(prop, value)
.on('data', function (value) {
console.log(value)
})
|
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
// import {Map, InfoWindow, Marker, Polygon, GoogleApiWrapper} from 'google-maps-react';
import history from '../history';
import { poiClusters } from '../Config/sampleMapClusters';
import appConfig from '../Config/params';
import MapComponent from '../Components/MapComponent';
const map_key = appConfig.googlemaps.key;
const POIClustersData = poiClusters;
const DEFAULT_PADDING = { top: 40, right: 40, bottom: 40, left: 40 };
export default class MapScreen extends React.Component {
constructor(props) {
super(props);
// const window_google_instance = this.props.google;
this.state = { width: '0', height: '0' };
this.updateWindowDimensions = this.updateWindowDimensions.bind(this);
this.mapMarkers = this.parseMarkers();
this.state.mapDataLoaded = false;
this.state.mapMarkersData = [];
this.state.mapClustersData = [];
this.state.selectedCluster = 0;
this.polygons = poiClusters;
this.initialRegion = {
lat: 39.135452,
//lng: -94.577164
lng: -94.577350
};
}
componentWillMount() {
fetch(appConfig.app.API_BASE_URL+'clusters')
.then(response => response.json(true))
.then((responseData) => {
// console.log(JSON.parse(responseData.body));
// venue.showInMap = "Yes"
let apiResponseData = JSON.parse(responseData.body);
let allMarkersData = apiResponseData.markers;
let allClustersData = apiResponseData.clusters;
let tempMarkersData= [];
let tempClustersData = [];
for (var i = 0; i < allMarkersData.length; i++) {
if(allMarkersData[i].showInMap == "Yes")
{
allMarkersData[i].latlng = {
lat: allMarkersData[i].latlng.latitude,
lng: allMarkersData[i].latlng.longitude
};
tempMarkersData.push(allMarkersData[i]);
}
}
for (var i = 0; i < allClustersData.length; i++) {
let tmpData = allClustersData[i];
tmpData.coordinates = this.transformClusterCoordinates(allClustersData[i].coordinates);
// tmpData.coordinates = allClustersData[i].coordinates;
tempClustersData.push(tmpData);
}
console.log("allMarkersData - ");
console.log(allMarkersData.length);
console.log("markers to show on map Data - ");
console.log(tempMarkersData);
console.log("all clusters Data - ");
console.log(tempClustersData);
this.setState({ mapMarkersData: tempMarkersData });
this.setState({ mapClustersData: tempClustersData });
this.setState({ mapDataLoaded: true });
});
}
transformClusterCoordinates(inputCoordinates)
{
let tmpData = [];
for (let j = 0; j < inputCoordinates.length; j++) {
tmpData.push({
lat: inputCoordinates[j].latitude,
lng: inputCoordinates[j].longitude
});
}
return tmpData;
}
val2key(val,array){
for (var key in array) {
let this_val = array[key];
if(this_val.key == val){
return key;
break;
}
}
}
parseMarkers()
{
let markers = [];
for (var i = POIClustersData.length - 1; i >= 0; i--) {
for (var j = POIClustersData[i].pois.length - 1; j >= 0; j--) {
markers.push(POIClustersData[i].pois[j]);
}
}
return markers;
}
/**
* check if input latlong is inside any of the polygons
* if yes return that polygon
* else return false
*/
pointInPloygons(point)
{
var tmpFlag = false;
for (var i = POIClustersData.length - 1; i >= 0; i--) {
tmpFlag = this.pointInPoly(point, POIClustersData[i].polygonOverlay.coordinates);
if(tmpFlag)
{
break;
}
}
if(tmpFlag)
{
return POIClustersData[i];
}
else
{
return tmpFlag;
}
}
/**
* Check if point(latlong object) is inside polygon
* Returns boolean true or false
*/
pointInPoly(point, polygon) {
// ray-casting algorithm based on
// http://www.ecse.rpi.edu/Homepages/wrf/Research/Short_Notes/pnpoly.html
var x = point.latitude, y = point.longitude;
var inside = false;
for (var i = 0, j = polygon.length - 1; i < polygon.length; j = i++) {
var xi = polygon[i].latitude, yi = polygon[i].longitude;
var xj = polygon[j].latitude, yj = polygon[j].longitude;
var intersect = ((yi > y) != (yj > y))
&& (x < (xj - xi) * (y - yi) / (yj - yi) + xi);
if (intersect) inside = !inside;
}
return inside;
};
componentDidMount() {
// this.state.markerPoint = new window.google.maps.Point(32,32);
// this.state.markerSize = new window.google.maps.Size(64,64);
this.updateWindowDimensions();
window.addEventListener('resize', this.updateWindowDimensions);
}
componentWillUnmount() {
window.removeEventListener('resize', this.updateWindowDimensions);
}
updateWindowDimensions() {
this.setState({ width: window.innerWidth, height: window.innerHeight });
}
onPolygonClick(e, polygon_key)
{
// alert(polygon_key);
console.log("Polygon key - ");
console.log(polygon_key);
let selected_polygon = null;
for (var i = POIClustersData.length - 1; i >= 0; i--) {
if(POIClustersData[i].polygon.key==polygon_key)
{
selected_polygon = POIClustersData[i];
}
}
if(selected_polygon)
{
this.fitPolygonToScreen(selected_polygon);
}
else
{
console.log("No selected polygon found.");
}
}
onMarkerClick(e, venue_key)
{
// alert(venue_key);
console.log(this.props);
// this.props.params = {currentVenueId: venue_key};
history.replace('/venue',{venue_key:venue_key});
}
/**
* Fit map to polygon coordinates
*/
fitPolygonToScreen(polygon)
{
this.map.fitToCoordinates(polygon.polygonOverlay.coordinates, {
edgePadding: DEFAULT_PADDING,
animated: true,
});
}
onMapClicked(e)
{
console.log(e);
// alert("Map clicked");
}
render() {
// markerPoint = new this.props.google.maps.Point(32,32)
// markerSize = new this.props.google.maps.Size(64,64)
//<MapComponent initialRegion={this.initialRegion} mapMarkers={this.state.mapMarkersData} mapClusters={this.state.mapClustersData} />
return (
<div>
{
this.state.mapDataLoaded ?
<span>
<MapComponent initialRegion={this.initialRegion} mapMarkers={this.state.mapMarkersData} mapClusters={this.state.mapClustersData} />
</span>
:
<span> Loading maps data, please wait.</span>
}
</div>
);
}
}
const style = {
width: '100%',
height: '100%'
} |
var searchData=
[
['protocol_5ftype_5ft',['protocol_type_t',['../_i_s_comm_8h.html#a932bee6e7c2e702a8cce14cfd728ba92',1,'ISComm.h']]]
];
|
$('#signIn').on('click', (e) => {
e.preventDefault();
const email = $('#email').val();
const password = $('#password').val();
const payload = {
email: email,
password: password
};
$.ajax({
url: '/signIn',
method: 'POST',
data: payload
}).done((data) => {
if (data.message) {
if (document.referrer.includes('newuser')) {
window.location.href = '/';
} else {
window.location.href = document.referrer;
}
} else {
$('#password').val('');
$('#error').html(`<div>${data.error}</div>`);
}
});
});
|
var stage = 0;
var delimiter = ',';
function removeTemplateData() {
$('#fileUploadTemplate').hide();
$('#fileUploadTemplateInput').val(null);
}
function removeDataSourceData() {
$('#fileUploadDataSource').hide();
$('#fileUploadDataSourceInput').val(null);
$("#TableIndex").hide();
$("#TableDelimiter").hide();
}
function setDelimiter(newDelimiter, buttontext = null) {
delimiter = newDelimiter;
if (buttontext === null)
buttontext = delimiter;
$('#delimiter')[0].innerText = buttontext;
};
$(document).ready(function () {
var stageLabel = $("#StageLabel");
var helpTemplateButton = $("#TemplateHelpButton");
var templateFiledrop = $("#TemplateFileDrop");
var helpDataSourceButton = $("#DataSourceHelpButton");
var dataSourceFiledrop = $("#DataSourceFileDrop");
var dataSourceForms = $("#DataSourceForms");
var nextButton = $("#NextButton");
var backButton = $("#BackButton");
var assembleAnotherFileButton = $("#AnotherFileButton");
var assembleButton = $("#AssembleButton");
var tableIndexDiv = $("#TableIndex");
var tableDelimiterDiv = $("#TableDelimiter");
tableIndexDiv.hide();
tableDelimiterDiv.hide();
$('#fileUploadTemplate').hide();
$('#fileUploadTemplateInput').change(function () {
var file = $('#fileUploadTemplateInput')[0].files[0].name;
$('#fileUploadTemplate label').text(file);
$('#fileUploadTemplate').show();
});
$('#fileUploadDataSource').hide();
$('#fileUploadDataSourceInput').change(function () {
var file = $('#fileUploadDataSourceInput')[0].files[0].name;
var re = /(?:\.([^.]+))?$/;
var extension = re.exec(file)[1].toLowerCase();
switch (extension) {
case "xml":
case "json":
tableIndexDiv.hide();
tableDelimiterDiv.hide();
break;
case "csv":
tableIndexDiv.hide();
tableDelimiterDiv.show();
break;
default:
tableIndexDiv.show();
tableDelimiterDiv.hide();
break;
}
$('#fileUploadDataSource label').text(file);
$('#fileUploadDataSource').show();
});
function toNextStage() {
ToStage(stage+1);
}
function toBackStage() {
ToStage(stage-1);
}
function reset() {
ToStage(0);
removeDataSourceData();
removeTemplateData();
tableIndexDiv.val(null);
tableDelimiterDiv.val(null);
}
nextButton.click(function (event) {
event.preventDefault();
toNextStage();
});
backButton.click(function (event) {
event.preventDefault();
toBackStage();
});
assembleAnotherFileButton.click(function (event) {
event.preventDefault();
reset();
});
function ToStage(newStage, animated = true) {
var stageContent = $("#StageContent");
if (animated) {
stageContent.fadeOut(300, function () {
ToggleStageViews(newStage);
stageContent.fadeIn();
});
}
else {
ToggleStageViews(newStage);
}
}
function ToggleStageViews(newStage) {
stage = newStage;
switch (newStage) {
case 0:
{
stageLabel.text("STAGE 1/3");
helpTemplateButton.show();
templateFiledrop.show();
helpDataSourceButton.hide();
dataSourceFiledrop.hide();
dataSourceForms.hide();
nextButton.show();
backButton.hide();
assembleAnotherFileButton.hide();
assembleButton.hide();
break;
}
case 1:
{
stageLabel.text("STAGE 2/3");
helpTemplateButton.hide();
templateFiledrop.hide();
helpDataSourceButton.show();
dataSourceFiledrop.show();
dataSourceForms.show();
nextButton.show();
backButton.show();
assembleAnotherFileButton.hide();
assembleButton.hide();
break;
}
case 2:
{
stageLabel.text("STAGE 3/3");
helpTemplateButton.hide();
templateFiledrop.hide();
helpDataSourceButton.hide();
dataSourceFiledrop.hide();
dataSourceForms.hide();
nextButton.hide();
backButton.show();
assembleAnotherFileButton.show();
assembleButton.show();
break;
}
default: break;
}
}
ToStage(0, false);
assembleButton.click(function (event) {
event.preventDefault();
let templateFiles = $('#fileUploadTemplateInput')[0].files;
if (templateFiles.length === 0) {
showAlert(o.FileSelectMessage);
return;
}
let dataSourceFiles = $('#fileUploadDataSourceInput')[0].files;
if (dataSourceFiles.length === 0) {
showAlert(o.FileSelectMessage);
return;
}
let data = new FormData();
let template = templateFiles[0];
let dataSource = dataSourceFiles[0];
data.append('template', template, template.name);
data.append('dataSource', dataSource, dataSource.name);
var sourceName = $('#DataSourceName').val();
var tableIndex = $('#datasourceTableIndex').val();
if (tableIndex === '')
tableIndex = 0;
let url = o.UIBasePath + 'api/AsposeEmailAssembly/Assemble?delimiter=' + delimiter + '&sourceName=' + sourceName + '&tableIndex=' + tableIndex;
request(url, data);
});
}); |
function supportNewKeyboardEvent(){
var newElement = document.createElement('input');
try{
var charA = 65;
e = new KeyboardEvent('keypress', {
key: 'A',
code: 'KeyA',
});
newElement.focus();
newElement.dispatchEvent(e);
return newElement.value === 'A'
}catch(err){
return false;
}
}
|
import React from 'react';
import IngredientsField from './IngredientsField';
import { Section } from 'components/common';
function IngredientsSection(props) {
const { inputProps, ...rest } = props;
const caption = 'Tip: You can paste multiple ingredients at once.';
const isError = !!inputProps.error;
return (
<Section caption={caption} title={'Ingredients'} error={isError} {...rest}>
<IngredientsField {...inputProps} />
</Section>
);
}
export default IngredientsSection;
|
function foo() {
if (a) {
y();
return;
}
}
function bar() {
y();
return;
}
function baz() {
if (a) {
y();
if (b) {
return;
}
return;
}
return;
}
// keep non-redundant returns
function foo1() {
if (a) {
y();
return;
}
x();
}
|
/**
* Courses services
*/
"use strict";
angular.module("k2pServices")
.factory("Courses", ["$resource", function($resource) {
return $resource("/api/courses/:courseId/:sub", {}, {
getStudents: {
method: "GET",
params: {
sub: "students"
},
isArray: true
}
});
}]); |
var config = require('traveling_salesman/config'),
utils = require('traveling_salesman/utils');
/*
* TravelingSalesmanMap
*
* Description: Generate virtual map to run traveling salesman experiment on
*
* Parameters:
* sender - who is calling this
* callback - callback called when initialization is complete
*/
var TravelingSalesmanMap = function (points, map_size, sender, callback) {
if("function" !== typeof callback) callback = function() {}; // callback should always be a function
var self = {};
var __range = {
x: map_size,
y: map_size,
z: map_size
};
var __points_to_generate = points;
var __map;
var __map_flat;
var __points;
function _initialize() {
var error;
_buildMap();
_generatePoints();
callback(error, self);
}
function _buildMap() {
__map = [];
for (var x = 0; x < __range.x; x++) {
__map[x] = [];
for (var y = 0; y < __range.y; y++) {
__map[x][y] = [];
for (var z = 0; z < __range.z; z++) {
__map[x][y][z] = 0;
}
}
}
}
function _generatePoints() {
var num_points_generated = 0;
__points = [];
while (num_points_generated < __points_to_generate) {
var x = _getRandomInt(0, __range.x);
var y = _getRandomInt(0, __range.y);
var z = _getRandomInt(0, __range.z);
if (! _isValidPoint(x,y,z)) {
continue;
}
var point = num_points_generated + 1;
__map[x][y][z] = point;
__points.push({
"x": x,
"y": y,
"z": z,
"point": point
});
num_points_generated++;
}
}
function _getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function _isValidPoint(x,y,z) {
if (__map[x][y][z] === 1) {
return false;
}
// points have to be a certain distance apart
for (var p = 0; p < __points.length; p++) {
if (utils.distance(x,y,z,__points[p].x,__points[p].y,__points[p].z) < Math.ceil(config.minimum_map_size / 2) + 1) {
return false;
}
}
return true;
}
// accessors for generated data
self.getMap = function () { return __map; };
self.getFlatMap = function () {
if ("undefined" !== typeof __map_flat)
return __map_flat;
__map_flat = [];
for (var x = 0; x < __range.x; x++) {
for (var y = 0; y < __range.y; y++) {
for (var z = 0; z < __range.z; z++) {
__map_flat.push({
"x": x,
"y": y,
"z": z,
"point": __map[x][y][z]
});
}
}
}
return __map_flat;
}
self.getPoints = function () { return __points; };
self.getNumPointsGenerated = function () { return __points_to_generate; };
self.getRange = function () { return __range; };
// call constructor
_initialize();
return self;
};
module.exports = TravelingSalesmanMap; |
'use strict'
module.exports = {
branches: require('./branches'),
milestones: require('./milestones'),
project: require('./project'),
projectEvents: require('./project_events'),
}
|
define(
[
'knockout',
'../control-base',
'text!./control-radio-view.html'
],
function (ko, ComponentBase, template) {
ko.components.register('control-radio',
{
viewModel: ComponentBase,
template: template
}
);
}
); |
import {Store} from 'flux/utils';
import AppDispatcher from '../dispatcher/AppDispatcher';
import LogReaderConstants from '../actions/ActionTypes';
import Immutable from 'immutable';
class LogStore extends Store {
constructor(dispatcher){
super(dispatcher);
this.logdata = Immutable.List();
this.envurl = "";
this.itemCount = 0;
this.totalCount = 0;
this.pageSize = 0;
this.lastPageAdded = 0;
this.logcountdata = Immutable.List();
this.startDate = {};
this.endDate = {};
}
setLogData(logdata, totalcount, pagesize, lastpageadded, startdate, enddate, envurl) {
this.logdata = Immutable.List(logdata);
this.itemCount = this.logdata.size;
this.totalCount = totalcount;
this.pageSize = pagesize;
this.lastPageAdded = lastpageadded;
this.startDate = startdate;
this.endDate = enddate;
this.envurl = envurl;
}
mergeLogData(logdata, totalcount, pagesize, lastpageadded, startdate, enddate) {
this.logdata = this.logdata.concat(logdata);
this.itemCount = this.logdata.size;
this.totalCount = totalcount;
this.pageSize = pagesize;
this.lastPageAdded = lastpageadded;
this.startDate = startdate;
this.endDate = enddate;
}
setHourlyCountData(logcountdata){
this.logcountdata = Immutable.List(logcountdata);
}
getLogData() {
return this.logdata.toJS();
}
getHourlyLogData() {
var countItems = this.logcountdata.toJS();
countItems = countItems.map(function(v) {
var countItem = {
time: new Date(v.Year,v.Month-1,v.Day, v.Hour, v.Minute, 0).getTime(),
Year: v.Year,
Month: v.Month,
Day: v.Day,
Hour: v.Hour,
Minute: v.Minute,
TraceCount: v.TraceCount,
DebugCount: v.DebugCount,
InfoCount: v.InfoCount,
WarnCount: v.WarnCount,
ErrorCount: v.ErrorCount,
FatalCount: v.FatalCount
};
return countItem;
});
return countItems;
}
getItemCount() {
return this.itemCount;
}
getTotalCount() {
return this.totalCount;
}
getNextPageNumber() {
return this.lastPageAdded + 1;
}
getPageSize() {
return this.pageSize;
}
getMoreUrl() {
return this.envurl;
}
getStartDate() {
return this.startDate;
}
getEndDate() {
return this.endDate;
}
__onDispatch(action) {
switch(action.actionType) {
case LogReaderConstants.RECEIVE_RAW_LOG_ITEMS:
this.setLogData(action.logData, action.totalCount, action.pagesize, action.pagenumber, action.startdate, action.enddate, action.envurl);
this.__emitChange();
break;
case LogReaderConstants.MERGE_RAW_LOG_ITEMS:
this.mergeLogData(action.logData, action.totalCount, action.pagesize, action.pagenumber, action.startdate, action.enddate);
this.__emitChange();
break;
case LogReaderConstants.RECEIVE_RAW_HOURLY_LOG_COUNTS:
this.setHourlyCountData(action.logCountData);
this.__emitChange();
break;
default:
// no op
}
}
}
export default new LogStore(AppDispatcher); |
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
var Cookie = exports.Cookie = {
createCookie: function createCookie(name, value, expireTime) {
expireTime = !!expireTime ? expireTime : 15 * 60 * 1000; // Default 15 min
var date = new Date();
date.setTime(date.getTime() + expireTime);
var expires = "; expires=" + date.toGMTString();
document.cookie = name + "=" + value + expires + "; path=/";
},
getCookie: function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) {
return parts.pop().split(";").shift();
}
},
deleteCookie: function deleteCookie(name) {
document.cookie = name + '=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}
}; |
// https://pedrohs.github.io/criando-banco-de-dados-com-nedb/
var nedb = require('nedb');
var db = new nedb( { filename: 'banco.nedb',
autoload: true,
timestampData: true,
flushDataOnCompaction: true });
// Original {"name":"Update da Silva Neto","age":16,"email":"updateneto@update.com","password":"senhadoupdateneto"}
db.update({ email: 'updateneto@update.com'},
{ $set: { name: 'Updated da Silva Neto', email: 'updatedneto@update.com', state: 'AM' }},
{ multi: true, upsert: false },
function (err, numRepl) {
if (err) {
return console.log(err);
}
db.persistence.compactDatafile();
console.log("User updated...");
});
|
import $ from 'jquery';
import Component from '@ember/component';
import DataTablesHelpers from 'api-umbrella-admin-ui/utils/data-tables-helpers';
import I18n from 'npm:i18n-js';
import { computed } from '@ember/object';
import { inject } from '@ember/service';
export default Component.extend({
session: inject('session'),
didInsertElement() {
let dataTable = this.$().find('table').DataTable({
serverSide: true,
ajax: '/api-umbrella/v1/admins.json',
pageLength: 50,
order: [[0, 'asc']],
columns: [
{
data: 'username',
name: 'Username',
title: I18n.t('mongoid.attributes.admin.username'),
defaultContent: '-',
render: _.bind(function(username, type, data) {
if(type === 'display' && username && username !== '-') {
let link = '#/admins/' + data.id + '/edit';
return '<a href="' + link + '">' + _.escape(username) + '</a>';
}
return username;
}, this),
},
{
data: 'group_names',
name: 'Groups',
title: 'Groups',
orderable: false,
render: DataTablesHelpers.renderListEscaped,
},
{
data: 'current_sign_in_at',
type: 'date',
name: 'Last Signed In',
title: 'Last Signed In',
defaultContent: '-',
render: DataTablesHelpers.renderTime,
},
{
data: 'created_at',
type: 'date',
name: 'Created',
title: 'Created',
defaultContent: '-',
render: DataTablesHelpers.renderTime,
},
],
});
dataTable.on('draw.dt', function() {
let params = dataTable.ajax.params();
delete params.start;
delete params.length;
this.set('queryParams', params);
}.bind(this));
},
downloadUrl: computed('queryParams', function() {
let params = this.get('queryParams');
if(params) {
params = $.param(params);
}
return '/api-umbrella/v1/admins.csv?api_key=' + this.get('session.data.authenticated.api_key') + '&' + params;
}),
});
|
$(document).ready(function () {
$("nav li a.custom").click(function (event) {
event.preventDefault();
var menuItemId = $(this).attr("data-item");
showModalEditor("Edit Menu Item: " + $(this).attr("data-itemname"), "/Admin/MenuItem/Edit?menuItemId=" + menuItemId);
});
}); |
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
'use strict';
const strictUriEncode = require('strict-uri-encode');
const decodeComponent = require('decode-uri-component');
function encoderForArrayFormat(options) {
switch (options.arrayFormat) {
case 'index':
return (key, value, index) => {
return value === null ? [
encode(key, options),
'[',
index,
']'
].join('') : [
encode(key, options),
'[',
encode(index, options),
']=',
encode(value, options)
].join('');
};
case 'bracket':
return (key, value) => {
return value === null ? [encode(key, options), '[]'].join('') : [
encode(key, options),
'[]=',
encode(value, options)
].join('');
};
default:
return (key, value) => {
return value === null ? encode(key, options) : [
encode(key, options),
'=',
encode(value, options)
].join('');
};
}
}
function parserForArrayFormat(options) {
let result;
switch (options.arrayFormat) {
case 'index':
return (key, value, accumulator) => {
result = /\[(\d*)\]$/.exec(key);
key = key.replace(/\[\d*\]$/, '');
if (!result) {
accumulator[key] = value;
return;
}
if (accumulator[key] === undefined) {
accumulator[key] = {};
}
accumulator[key][result[1]] = value;
};
case 'bracket':
return (key, value, accumulator) => {
result = /(\[\])$/.exec(key);
key = key.replace(/\[\]$/, '');
if (!result) {
accumulator[key] = value;
return;
}
if (accumulator[key] === undefined) {
accumulator[key] = [value];
return;
}
accumulator[key] = [].concat(accumulator[key], value);
};
default:
return (key, value, accumulator) => {
if (accumulator[key] === undefined) {
accumulator[key] = value;
return;
}
accumulator[key] = [].concat(accumulator[key], value);
};
}
}
function encode(value, options) {
if (options.encode) {
return options.strict ? strictUriEncode(value) : encodeURIComponent(value);
}
return value;
}
function decode(value, options) {
if (options.decode) {
return decodeComponent(value);
}
return value;
}
function keysSorter(input) {
if (Array.isArray(input)) {
return input.sort();
}
if (typeof input === 'object') {
return keysSorter(Object.keys(input))
.sort((a, b) => Number(a) - Number(b))
.map(key => input[key]);
}
return input;
}
function extract(input) {
const queryStart = input.indexOf('?');
if (queryStart === -1) {
return '';
}
return input.slice(queryStart + 1);
}
function parse(input, options) {
options = Object.assign({decode: true, arrayFormat: 'none'}, options);
const formatter = parserForArrayFormat(options);
// Create an object with no prototype
const ret = Object.create(null);
if (typeof input !== 'string') {
return ret;
}
input = input.trim().replace(/^[?#&]/, '');
if (!input) {
return ret;
}
for (const param of input.split('&')) {
let [key, value] = param.replace(/\+/g, ' ').split('=');
// Missing `=` should be `null`:
// http://w3.org/TR/2012/WD-url-20120524/#collect-url-parameters
value = value === undefined ? null : decode(value, options);
formatter(decode(key, options), value, ret);
}
return Object.keys(ret).sort().reduce((result, key) => {
const value = ret[key];
if (Boolean(value) && typeof value === 'object' && !Array.isArray(value)) {
// Sort object keys, not values
result[key] = keysSorter(value);
} else {
result[key] = value;
}
return result;
}, Object.create(null));
}
exports.extract = extract;
exports.parse = parse;
exports.stringify = (obj, options) => {
const defaults = {
encode: true,
strict: true,
arrayFormat: 'none'
};
options = Object.assign(defaults, options);
if (options.sort === false) {
options.sort = () => {};
}
const formatter = encoderForArrayFormat(options);
return obj ? Object.keys(obj).sort(options.sort).map(key => {
const value = obj[key];
if (value === undefined) {
return '';
}
if (value === null) {
return encode(key, options);
}
if (Array.isArray(value)) {
const result = [];
for (const value2 of value.slice()) {
if (value2 === undefined) {
continue;
}
result.push(formatter(key, value2, result.length));
}
return result.join('&');
}
return encode(key, options) + '=' + encode(value, options);
}).filter(x => x.length > 0).join('&') : '';
};
exports.parseUrl = (input, options) => {
return {
url: input.split('?')[0] || '',
query: parse(extract(input), options)
};
};
},{"decode-uri-component":2,"strict-uri-encode":3}],2:[function(require,module,exports){
'use strict';
var token = '%[a-f0-9]{2}';
var singleMatcher = new RegExp(token, 'gi');
var multiMatcher = new RegExp('(' + token + ')+', 'gi');
function decodeComponents(components, split) {
try {
// Try to decode the entire string first
return decodeURIComponent(components.join(''));
} catch (err) {
// Do nothing
}
if (components.length === 1) {
return components;
}
split = split || 1;
// Split the array in 2 parts
var left = components.slice(0, split);
var right = components.slice(split);
return Array.prototype.concat.call([], decodeComponents(left), decodeComponents(right));
}
function decode(input) {
try {
return decodeURIComponent(input);
} catch (err) {
var tokens = input.match(singleMatcher);
for (var i = 1; i < tokens.length; i++) {
input = decodeComponents(tokens, i).join('');
tokens = input.match(singleMatcher);
}
return input;
}
}
function customDecodeURIComponent(input) {
// Keep track of all the replacements and prefill the map with the `BOM`
var replaceMap = {
'%FE%FF': '\uFFFD\uFFFD',
'%FF%FE': '\uFFFD\uFFFD'
};
var match = multiMatcher.exec(input);
while (match) {
try {
// Decode as big chunks as possible
replaceMap[match[0]] = decodeURIComponent(match[0]);
} catch (err) {
var result = decode(match[0]);
if (result !== match[0]) {
replaceMap[match[0]] = result;
}
}
match = multiMatcher.exec(input);
}
// Add `%C2` at the end of the map to make sure it does not replace the combinator before everything else
replaceMap['%C2'] = '\uFFFD';
var entries = Object.keys(replaceMap);
for (var i = 0; i < entries.length; i++) {
// Replace all decoded components
var key = entries[i];
input = input.replace(new RegExp(key, 'g'), replaceMap[key]);
}
return input;
}
module.exports = function (encodedURI) {
if (typeof encodedURI !== 'string') {
throw new TypeError('Expected `encodedURI` to be of type `string`, got `' + typeof encodedURI + '`');
}
try {
encodedURI = encodedURI.replace(/\+/g, ' ');
// Try the built in decoder first
return decodeURIComponent(encodedURI);
} catch (err) {
// Fallback to a more advanced decoder
return customDecodeURIComponent(encodedURI);
}
};
},{}],3:[function(require,module,exports){
'use strict';
module.exports = str => encodeURIComponent(str).replace(/[!'()*]/g, x => `%${x.charCodeAt(0).toString(16).toUpperCase()}`);
},{}],4:[function(require,module,exports){
'use strict';
var _require = require('./tilda.js'),
Tilda = _require.Tilda,
CanvasRenderer = _require.CanvasRenderer;
var queryString = require('query-string');
window.addEventListener('load', function () {
var canvasRenderer = new CanvasRenderer(document.querySelector('canvas'));
var game = new Tilda(canvasRenderer);
var path = window.location.pathname.substr(1).split(/\//g);
var parsed = queryString.parse(window.location.search);
var location = { x: 0, y: 0 };
if (parsed.x) location.x = parseFloat(parsed.x);
if (parsed.y) location.y = parseFloat(parsed.y);
var level = 'overworld';
console.log(path);
if (path.length > 1) {
level = path[1];
}
var dockManager = new dockspawn.DockManager(document.querySelector("body"));
dockManager.initialize();
var canvas = new dockspawn.PanelContainer(document.querySelector("#canvas"), dockManager);
var scriptEditor = new dockspawn.PanelContainer(document.querySelector("#scriptWindow"), dockManager);
var propertiesEditor = new dockspawn.PanelContainer(document.querySelector("#properties"), dockManager);
var toolbox = new dockspawn.PanelContainer(document.querySelector("#toolbar"), dockManager);
var documentNode = dockManager.context.model.documentManagerNode;
dockManager.dockRight(documentNode, propertiesEditor, 0.1);
dockManager.dockFill(documentNode, canvas);
dockManager.dockUp(documentNode, toolbox, 0.2);
dockManager.dockDown(documentNode, scriptEditor, 0.2);
window.onresize = function (event) {
dockManager.resize(window.innerWidth, window.innerHeight);
};
window.onresize();
//var editor = ace.edit('script');
//editor.getSession().setMode('ace/mode/javascript');
//editor.setTheme('ace/theme/monokai');
game.loadLevel(level, location).then(function (level) {
game.start();
var iframe = document.createElement('iframe');
iframe.style.height = 1200;
game.propertiesWindow = document.querySelector('iframe#properties');
$('#script').val(game.level.script);
});
document.querySelector('#toolbar').addEventListener('mousedown', function (event) {
var x = event.pageX;
var y = event.pageY - $('#toolbar').offset().top;
var TILE_SIZE = 16;
var tileX = Math.floor((x + 1) / TILE_SIZE);
var tileY = Math.floor((y + 1) / TILE_SIZE);
var selection = document.querySelector('#selection');
selection.style.width = TILE_SIZE + 'px';
selection.style.height = TILE_SIZE + 'px';
selection.style.left = tileX * TILE_SIZE + 'px';
selection.style.top = tileY * TILE_SIZE + 'px';
var type = null;
var tool = 0;
for (var i in game.blockTypes) {
var blockType = game.blockTypes[i];
if (tileX == blockType.tileX && tileY == blockType.tileY) {
type = blockType.id;
}
}
if (tileX == 0 && tileY == 0) {
tool = 0;
} else {
tool = 1;
}
console.log(type);
game.editor.activeBlockType = type;
game.editor.tool = tool;
});
window.addEventListener('message', function (event) {});
game.addEventListener('selectedblock', function (event) {
var block = event.data.block;
if (!block) {
return;
}
if (!block.teleport) {
block.teleport = {
x: 0,
y: 0,
level: null
};
}
$('#teleport_x').val(block.teleport.x);
$('#teleport_y').val(block.teleport.y);
$('#yin').val(block.yin);
$('#yang').val(block.yang);
$('#teleport_level').val(block.teleport.level);
$('#object_script').val(block.script);
});
window.save = function () {
try {
var block = game.editor.selectedBlock;
block.script = $('#object_script').val();
block.yin = parseInt($('#yin').val());
block.yang = parseInt($('#yang').val());
block.teleport = {
x: $('#teleport_x').val(),
y: $('#teleport_y').val(),
level: $('#teleport_level').val()
};
game.setBlock(block);
debugger;
} catch (e) {}
game.level.script = $('#script').val();
game.level.save();
};
game.addEventListener('move', function (event) {
history.replaceState({
level: {
id: event.data.level.id,
player: {
x: event.data.level.player.x,
y: event.data.level.player.y
}
}
}, 'Level', '/level/' + event.data.level.id + '?x=' + event.data.level.player.x + '&y=' + event.data.level.player.y);
});
game.addEventListener('levelchanged', function (event) {
history.pushState({
level: {
id: event.data.level.id,
player: {
x: event.data.level.player.x,
y: event.data.level.player.y
}
},
position: event.data.position
}, 'Level', '/level/' + event.data.level.id + '?x=' + event.data.level.player.x + '&y=' + event.data.level.player.y);
$('#script').val(game.level.script);
});
});
},{"./tilda.js":5,"query-string":1}],5:[function(require,module,exports){
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
var FLAG_SIDE_SCROLLING = 0x1;
var TILE_SIZE = 16;
var NUM_SCREEN_TILES_X = 124;
var NUM_SCREEN_TILES_Y = 128;
var TILE_SOLID = 1;
var TILE_FLAG_JUMP_LEFT = 2;
var TILE_FLAG_JUMP_TOP = 4;
var TILE_FLAG_JUMP_RIGHT = 8;
var TILE_FLAG_JUMP_BOTTOM = 16;
var GAME_READY = 0;
var GAME_RUNNING = 1;
var TOOL_POINTER = 0;
var TOOL_DRAW = 1;
var TOOL_PROPERTIES = 2;
var MODE_PLAYING = 0;
var MODE_EDITING = 1;
var TILESET = '';
var Renderer = function () {
function Renderer() {
_classCallCheck(this, Renderer);
}
_createClass(Renderer, [{
key: 'loadImage',
value: function loadImage(url) {}
}, {
key: 'translate',
value: function translate(x, y) {}
}, {
key: 'renderImageChunk',
value: function renderImageChunk(image, destX, destY, destWidth, destHeight, srcX, srcY, srcWidth, srcHeight) {}
}, {
key: 'clear',
value: function clear() {}
}]);
return Renderer;
}();
var Setence = function Setence(setence) {
_classCallCheck(this, Setence);
var parts = setence.split(' ');
this.subject = parts[0];
this.predicate = parts[1];
this.object = parts[2];
this.duration = parts[3];
};
function sleep(seconds) {
return new Promise(function (resolve, fail) {
setTimeout(function () {
resolve();
}, seconds);
});
}
var CanvasRenderer = exports.CanvasRenderer = function (_Renderer) {
_inherits(CanvasRenderer, _Renderer);
function CanvasRenderer(canvas) {
_classCallCheck(this, CanvasRenderer);
var _this = _possibleConstructorReturn(this, (CanvasRenderer.__proto__ || Object.getPrototypeOf(CanvasRenderer)).call(this));
_this.canvas = canvas;
_this.context = canvas.getContext('2d');
return _this;
}
_createClass(CanvasRenderer, [{
key: 'clear',
value: function clear() {
this.context.fillStyle = 'white';
this.context.fillRect(0, 0, this.canvas.width, this.canvas.height);
}
}, {
key: 'translate',
value: function translate(x, y) {
this.context.translate(x, y);
}
}, {
key: 'loadImage',
value: function loadImage(url) {
var image = new Image();
image.src = 'img/tileset.png';
return image;
}
}, {
key: 'renderImageChunk',
value: function renderImageChunk(image, destX, destY, destWidth, destHeight, srcX, srcY, srcWidth, srcHeight) {
this.context.drawImage(image, srcX, srcY, srcWidth, srcHeight, destX, destY, destWidth, destHeight);
}
}]);
return CanvasRenderer;
}(Renderer);
var Tilda = function () {
_createClass(Tilda, [{
key: 'dispatchEvent',
value: function dispatchEvent(event) {
if (this.hasOwnProperty('on' + event.type) && this['on' + event.type] instanceof Function) {
this['on' + event.type].call(this, event);
}
}
}, {
key: 'addEventListener',
value: function addEventListener(eventId, callback) {
this['on' + eventId] = callback;
}
}, {
key: 'seq',
value: function seq() {
this.sequence = arguments[0];
if (!this.sequence) {}
this.next();
}
/**
* Returns the cluster the player is in
**/
}, {
key: 'getCluster',
value: function getCluster() {
var clusterX = Math.floor((this.level.player.x + 1) / this.gameWidth);
var clusterY = Math.floor((this.level.player.y + 1) / this.gameHeight);
return {
x: clusterX,
y: clusterY
};
}
}, {
key: 'addEntity',
value: function addEntity(id, type, x, y) {
var cluster = this.getCluster();
return this.level.addEntity(id, type, x + cluster.x * this.gameWidth, cluster.y * this.gameHeight);
}
}, {
key: 'getEntity',
value: function getEntity(obj) {
return this.level.entities[obj];
}
}, {
key: 'lock',
value: function lock() {
this.status.locked = true;
}
}, {
key: 'unlock',
value: function unlock() {
this.status.locked = false;
}
}, {
key: 'next',
value: function next() {
this.text = '';
if (this.sequence == null) {
return;
}
if (this.sequence.length < 1) {
return;
}
var nextOperation = this.sequence.pop();
nextOperation.call(this);
}
}, {
key: 'getPostionFromCursor',
value: function getPostionFromCursor() {
var width = this.renderer.canvas.width;
var height = this.renderer.canvas.height;
var pageWidth = this.renderer.canvas.getBoundingClientRect().width;
var pageHeight = this.renderer.canvas.getBoundingClientRect().height;
var bounds = this.renderer.canvas.getBoundingClientRect();
var cx = width;
var cy = height;
var x = (event.pageX - bounds.left) / pageWidth * cx;
var y = (event.pageY - bounds.top) / pageHeight * cy;
var selectedX = Math.floor((x + 1) / TILE_SIZE);
var selectedY = Math.floor((y + 1) / TILE_SIZE);
return {
x: selectedX,
y: selectedY
};
}
/**
* Tells us if a certain flag is meet
* */
}, {
key: 'hasFlag',
value: function hasFlag(flag) {
return this.status.flags.indexOf(flag) != -1;
}
}, {
key: 'getSetting',
value: function getSetting(setting, defaultValue) {
if (!setting in this.status.settings) {
return defaultValue;
}
return this.status.settings[setting];
}
}]);
function Tilda(renderer) {
var _this2 = this;
_classCallCheck(this, Tilda);
this.timers = {};
this.gameWidth = 192;
this.gameUrl = '';
this.gameHeight = 192;
renderer.canvas.width = this.gameWidth;
renderer.canvas.height = this.gameHeight;
this.sequences = {};
this.renderer = renderer;
this.zoom = {
x: 1,
y: 1
};
this.entityTypes = {
'CharacterEntity': CharacterEntity,
'PlayerEntity': PlayerEntity
};
this.level = null;
this.blockTypes = {};
this.editor = {
selectedX: 0,
tool: TOOL_POINTER,
selectedY: 0,
activeBlockType: 15
};
this.cameraX = 0;
this.activeTile = {
x: 1, y: 2
};
this.keysPressed = [];
this.cameraY = 0;
this.activeTool = 0;
this.isJumpingOver = false;
this.mode = MODE_EDITING;
this.tileset = this.renderer.loadImage('img/tileset.png');
this.loadTiles(TILESET);
this.state = GAME_READY;
this.activeBlock = null;
this.aKeyPressed = false;
this.status = {
yin: 0,
locked: false,
yang: 0,
points: 0,
exp: 0,
settings: {},
flags: [],
level: null
};
this.text = '';
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
var lines = xmlHttp.responseText.split('\n');
for (var i in lines) {
var block = new Block(lines[i]);
_this2.blockTypes[block.id] = block;
}
} else {}
}
};
xmlHttp.open('GET', this.gameUrl + '/t.tileset', true);
xmlHttp.send(null);
this.renderer.canvas.addEventListener('mousedown', function (event) {
if (_this2.mode != MODE_EDITING) {
return;
}
var pos = _this2.getPostionFromCursor();
if (event.which == 1) {
switch (_this2.editor.tool) {
case TOOL_DRAW:
_this2.level.setBlock(pos.x + _this2.cameraX / TILE_SIZE, pos.y + _this2.cameraY / TILE_SIZE, {
x: pos.x + _this2.cameraX / TILE_SIZE,
y: pos.y + _this2.cameraY / TILE_SIZE,
type: _this2.editor.activeBlockType
});
break;
case TOOL_POINTER:
if (event.shiftKey) {
_this2.level.removeBlock(pos.x + _this2.cameraX / TILE_SIZE, pos.y + _this2.cameraY / TILE_SIZE);
_this2.level.save();
return;
}
_this2.editor.selectedX = pos.x;
_this2.editor.selectedY = pos.y;
_this2.editor.selectedBlock = _this2.level.blocks[_this2.editor.selectedX + _this2.cameraX][_this2.editor.selectedY + _this2.cameraY];
var evt = new CustomEvent('selectedblock');
evt.data = {
block: _this2.editor.selectedBlock
};
_this2.dispatchEvent(evt);
break;
}
_this2.level.save();
}
});
}
_createClass(Tilda, [{
key: 'setBlock',
value: function setBlock(block) {
this.level.blocks[block.x][block.y] = block;
}
}, {
key: 'setBlockType',
value: function setBlockType(blockType) {
if (blockType != null) {
this.activeTool = TOOL_DRAW;
this.editor.activeBlockType = event.data.blockType;
} else {
this.activeTool = TOOL_POINTER;
}
}
}, {
key: 'setTool',
value: function setTool(tool) {
this.activeTool = tool;
}
}, {
key: 'getBlockType',
value: function getBlockType(blockType) {
for (var b in this.blockTypes) {
var bt = this.blockTypes[b];
if (bt.tileX == blockType.tileX && bt.tileY == blockType.tileY && bt.flags == blockType.flags) {
return b;
}
}
}
}, {
key: 'setTimer',
value: function setTimer(id, time, callback) {
this.timers[id] = {
frame: 0,
time: time,
callback: callback
};
}
}, {
key: 'playSequence',
value: async function playSequence(sequence) {
var _this3 = this;
await Promise.all(sequence.map(function (action) {
return new Promise(async function (resolve, fail) {
await sleep(action.time);
action.callback(_this3);
});
}));
}
}, {
key: 'start',
value: function start() {
var _this4 = this;
this.gameInterval = setInterval(this.tick.bind(this), 5);
this.renderInterval = setInterval(this.render.bind(this), 5);
this.state = GAME_RUNNING;
this.ic = setInterval(function () {
var event = new CustomEvent('move');
event.data = {
level: _this4.level
};
_this4.dispatchEvent(event);
}, 1000);
}
}, {
key: 'stop',
value: function stop() {
clearInterval(this.ic);
clearInterval(this.gameInterval);
clearInterval(this.renderInterval);
this.state = GAME_READY;
}
}, {
key: 'loadTiles',
value: function loadTiles(tiles) {
var tiles = tiles.split('\n');
for (var i = 1; i < tiles.length; i++) {
var tile = tiles[i];
var blockType = new Block(tile);
this.blockTypes[i] = blockType;
}
}
}, {
key: 'loadLevel',
value: function loadLevel(id) {
var _this5 = this;
var position = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { x: 0, y: 0 };
return new Promise(function (resolve, reject) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
var level = JSON.parse(xmlHttp.responseText);
level = new Level(_this5, level);
level.player.x = position.x;
level.player.y = position.y;
level.id = id;
_this5.setLevel(level, position);
resolve(level);
} else {
reject();
}
}
};
xmlHttp.open('GET', _this5.gameUrl + '/api/levels/' + id, true);
xmlHttp.send(null);
});
}
}, {
key: 'setLevel',
value: function setLevel(level) {
var position = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : { x: 0, y: 0 };
this.level = level;
var evt = new CustomEvent('levelchanged');
evt.data = {
level: level
};
if ('script' in level) {
try {
var func = new Function(level.script);
func.call(this);
} catch (e) {
console.log(e.stack);
}
}
this.dispatchEvent(evt);
}
}, {
key: 'message',
value: function message(_message, cb) {
this.text = _message;
}
}, {
key: 'tick',
value: function tick() {
var _this6 = this;
for (var i in this.timers) {
this.timers[i].frame += 1;
if (this.timers[i].frame == this.timers.time) {
debugger;
this.timers[i].callback.call(this);
}
}
for (var i in this.level.objects) {
var obj = this.level.objects[i];
obj.tick();
}
for (var x in this.level.blocks) {
for (var y in this.level.blocks[x]) {
for (var i in this.level.objects) {
var collidied = false;
var left = x * TILE_SIZE;
var top = y * TILE_SIZE;
var block = this.level.blocks[x][y];
if (!block) {
return;
}
var blockType = this.blockTypes[block.type];
if (!blockType) {
continue;
}
if (this.isJumpingOver) {
return;
}
var is_solid = (blockType.flags & TILE_SOLID) == TILE_SOLID;
var obj = this.level.objects[i];
if (obj.x > left - TILE_SIZE && obj.x < left + TILE_SIZE && obj.y > top - TILE_SIZE * 0.8 && obj.y < top + TILE_SIZE / 2 - 1 && obj.moveX > 0 && is_solid) {
if ((blockType.flags & TILE_FLAG_JUMP_RIGHT) == TILE_FLAG_JUMP_RIGHT) {
this.isJumpingOver = true;
obj.moveX = .2;
obj.moveZ = 1;
} else {
obj.moveX = 0;
}
}
if (obj.y > top - TILE_SIZE && obj.y < top + TILE_SIZE / 2 - 1 && obj.x < left + TILE_SIZE && obj.x > left - TILE_SIZE && obj.moveX < 0 && is_solid) {
if ((blockType.flags & TILE_FLAG_JUMP_LEFT) == TILE_FLAG_JUMP_LEFT) {
this.isJumpingOver = true;
obj.moveX = -.2;
obj.moveZ = 1;
} else {
obj.moveX = 0;
}
}
if (obj.x > left - TILE_SIZE / 2 && obj.x < left + TILE_SIZE * 0.7 && obj.y > top - TILE_SIZE && obj.y < top + TILE_SIZE / 2 - 2 && obj.moveY > 0 && is_solid) {
if (block.teleport) {
if (block.teleport.level) {
this.loadLevel(block.teleport.level);
}
}
if ((blockType.flags & TILE_FLAG_JUMP_BOTTOM) == TILE_FLAG_JUMP_BOTTOM) {
this.isJumpingOver = true;
obj.moveY = 1;
obj.moveZ = 1;
} else {
obj.moveY = 0;
}
}
if (obj.x > left - TILE_SIZE && obj.x < left + TILE_SIZE - 1 && obj.y < top + TILE_SIZE / 2 && obj.y > top - TILE_SIZE && is_solid) {
if (block.script && block.script.length > 0 && this.aKeyPressed) {
// #QINOTE #AQUAJOGGING@R@CT
if (block.script.indexOf('res://') == 0) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
try {
var func = new Function(xmlHttp.responseText);
func = func.bind(_this6);
func();
} catch (e) {
console.log(e.stack);
}
}
}
};
xmlHttp.open('GET', this.gameUrl + block.script.substr('res://'.length));
xmlHttp.send(null);
} else {
try {
var func = new Function(block.script);
func.apply(this);
} catch (e) {
console.log(e.stack);
}
}
}
if (obj.moveY < 0) {
if (block.teleport) {
if (block.teleport.level) {
this.loadLevel(block.teleport.level);
}
}
if ((blockType.flags & TILE_FLAG_JUMP_TOP) == TILE_FLAG_JUMP_TOP) {
this.isJumpingOver = true;
obj.moveY = -0.6;
obj.moveZ = 1;
} else {
obj.moveY = -0;
}
this.activeBlock = block;
collidied = true;
}
}
if (!collidied) {
this.activeBlock = null;
}
}
}
}
}
}, {
key: 'render',
value: function render() {
this.renderer.clear();
if (this.level) {
for (var x in this.level.blocks) {
for (var y in this.level.blocks[x]) {
var left = (TILE_SIZE * x - this.cameraX) * this.zoom.x;
var top = (TILE_SIZE * y - this.cameraY) * this.zoom.y;
var width = TILE_SIZE * this.zoom.x;
var height = TILE_SIZE * this.zoom.y;
var block = this.level.blocks[x][y];
if (!block) {
return;
}
var type = this.blockTypes[block.type];
if (!type) {
continue;
}
var tileX = type.tileX * TILE_SIZE;
var tileY = type.tileY * TILE_SIZE;
this.renderer.renderImageChunk(this.tileset, left, top, width, height, tileX, tileY, width, height);
}
}
for (var i in this.level.objects) {
var object = this.level.objects[i];
var left = (object.x - this.cameraX) * this.zoom.x;
var top = (object.y - this.cameraY) * this.zoom.y;
var zeta = object.z * this.zoom.y;
var width = TILE_SIZE * this.zoom.x;
var height = TILE_SIZE * this.zoom.y;
var tileX = object.tileX * TILE_SIZE;
var tileY = object.tileY * TILE_SIZE;
if (zeta > 0) {}
this.renderer.renderImageChunk(this.tileset, left, top, width, height, 0, TILE_SIZE * 1, width, height);
this.renderer.renderImageChunk(this.tileset, left, top - zeta, width, height, tileX, tileY, width, height); // Render shadow
}
for (var i in this.blockTypes) {
var block = this.blockTypes[i];
var width = TILE_SIZE * this.zoom.x;
var height = TILE_SIZE * this.zoom.y;
var left = i * TILE_SIZE * this.zoom.x;
var top = this.renderer.canvas.height - TILE_SIZE * 2;
//this.renderer.renderImageChunk(this.tile, left, top, width, height, block.tileX * TILE_SIZE, block.tileY * TILE_SIZE, width, height);
}
}
// set camera
var clusterX = Math.floor((this.level.player.x + 1) / this.gameWidth);
var clusterY = Math.floor((this.level.player.y + 1) / this.gameHeight);
this.cameraX = clusterX * this.gameWidth;
this.cameraY = clusterY * this.gameHeight;
var width = TILE_SIZE * this.zoom.x;
var height = TILE_SIZE * this.zoom.y;
this.renderer.renderImageChunk(this.tileset, 0, this.renderer.canvas.height - TILE_SIZE * 2, TILE_SIZE, TILE_SIZE, this.activeTile.x * TILE_SIZE, this.activeTile.x * TILE_SIZE, TILE_SIZE, TILE_SIZE);
this.renderer.context.beginPath();
this.renderer.context.strokeStyle = 'blue';
this.renderer.context.strokeWidth = '1px';
this.renderer.context.rect(this.editor.selectedX * TILE_SIZE, this.editor.selectedY * TILE_SIZE, TILE_SIZE, TILE_SIZE);
this.renderer.context.stroke();
this.renderer.context.font = "11px Courier";
this.renderer.context.fillStyle = 'black';
this.renderer.context.fillText('points ' + this.status.points, 2, 12);
if (this.text && this.text.length > 0) {
this.renderer.context.fillStyle = 'rgba(0, 0, 0, .8)';
this.renderer.context.fillRect(10, 22, 180, 60);
this.renderer.context.fillStyle = 'white';
wrapText(this.renderer.context, this.text, 22, 32, 180, 9);
}
}
}]);
return Tilda;
}();
// From http://stackoverflow.com/questions/2936112/text-wrap-in-a-canvas-element
exports.Tilda = Tilda;
function wrapText(context, text, x, y, line_width, line_height) {
var line = '';
var paragraphs = text.split('\n');
for (var i = 0; i < paragraphs.length; i++) {
var words = paragraphs[i].split(' ');
for (var n = 0; n < words.length; n++) {
var testLine = line + words[n] + ' ';
var metrics = context.measureText(testLine);
var testWidth = metrics.width;
if (testWidth > line_width && n > 0) {
context.fillText(line, x, y);
line = words[n] + ' ';
y += line_height;
} else {
line = testLine;
}
}
context.fillText(line, x, y);
y += line_height;
line = '';
}
}
var Entity = function () {
function Entity(game, level) {
_classCallCheck(this, Entity);
this.level = level;
this.game = game;
this.moveX = 0;
this.moveY = 0;
this.moveZ = 0;
this.x = 0;
this.y = 0;
this.z = 0;
this.tileX = 0;
this.tileY = 0;
}
_createClass(Entity, [{
key: 'tick',
value: function tick() {
this.x += this.moveX;
this.y += this.moveY;
this.z += this.moveZ;
if (this.z > 0) {
this.moveZ -= 0.03;
}
if (this.z < 0) {
this.moveZ = 0;
if (this.game.isJumpingOver) {
this.game.isJumpingOver = false;
this.moveX = 0;
this.moveY = 0;
}
this.z = 0;
}
}
}, {
key: 'render',
value: function render() {}
}]);
return Entity;
}();
var SupplementEntity = function (_Entity) {
_inherits(SupplementEntity, _Entity);
function SupplementEntity(game, level) {
_classCallCheck(this, SupplementEntity);
var _this7 = _possibleConstructorReturn(this, (SupplementEntity.__proto__ || Object.getPrototypeOf(SupplementEntity)).call(this, game, level));
_this7.level = level;
_this7.tileX = 2;
_this7.tileY = 1;
return _this7;
}
return SupplementEntity;
}(Entity);
var CharacterEntity = function (_Entity2) {
_inherits(CharacterEntity, _Entity2);
function CharacterEntity(game, level) {
_classCallCheck(this, CharacterEntity);
var _this8 = _possibleConstructorReturn(this, (CharacterEntity.__proto__ || Object.getPrototypeOf(CharacterEntity)).call(this, game, level));
_this8.level = level;
_this8.tileX = 2;
_this8.tileY = 1;
return _this8;
}
_createClass(CharacterEntity, [{
key: 'turnRight',
value: function turnRight() {
this.tileX = 4;
}
}, {
key: 'turnLeft',
value: function turnLeft() {
this.tileX = 5;
}
}, {
key: 'turnUp',
value: function turnUp() {
this.tileX = 2;
}
}, {
key: 'turnDown',
value: function turnDown() {
this.tileX = 3;
}
}, {
key: 'walkLeft',
value: function walkLeft() {
this.turnLeft();
this.moveX = -.3;
}
}, {
key: 'walkRight',
value: function walkRight() {
this.turnRight();
this.moveX = .3;
}
}, {
key: 'walkUp',
value: function walkUp() {
this.moveY = -.3;
this.turnUp();
}
}, {
key: 'walkDown',
value: function walkDown() {
this.moveY = .3;
this.turnDown();
}
}, {
key: 'stop',
value: function stop() {
this.moveX = 0;
this.moveY = 0;
}
}, {
key: 'jump',
value: function jump() {
this.moveZ = 1;
}
}, {
key: 'render',
value: function render() {}
}]);
return CharacterEntity;
}(Entity);
var PlayerEntity = function (_CharacterEntity) {
_inherits(PlayerEntity, _CharacterEntity);
function PlayerEntity(game, level) {
_classCallCheck(this, PlayerEntity);
var _this9 = _possibleConstructorReturn(this, (PlayerEntity.__proto__ || Object.getPrototypeOf(PlayerEntity)).call(this, game, level));
_this9.x = _this9.level.player.x;
_this9.y = _this9.level.player.y;
_this9.game.renderer.canvas.tabIndex = 1000;
_this9.game.renderer.canvas.onkeydown = function (event) {
_this9.game.keysPressed.push(event.code);
if (_this9.game.status.locked) {
return;
}
if (_this9.game.isJumpingOver) {
return;
}
if (event.code == 'ArrowUp') {
_this9.walkUp();
}
if (event.code == 'ArrowDown') {
_this9.walkDown();
}
if (event.code == 'ArrowLeft') {
_this9.walkLeft();
}
if (event.code == 'ArrowRight') {
_this9.walkRight();
}
if (event.code == 'KeyA') {
_this9.game.aKeyPressed = true;
console.log(_this9.aKeyPressed);
_this9.game.next();
if (_this9.game.activeBlock) {
if (_this9.game.activeBlock.script.length > 0) {
try {
var func = new Function(_this9.game.activeBlock.script);
func.apply(_this9.game);
} catch (e) {
console.log(e.stack);
}
}
_this9.game.text = '';
_this9.game.activeBlock = null;
return;
}
_this9.jump();
}
};
_this9.game.renderer.canvas.onkeyup = function (event) {
_this9.game.keysPressed = array_remove(_this9.game.keysPressed, event.code);
if (_this9.game.isJumpingOver) {
return;
}
if (event.code == 'ArrowUp') {
if (_this9.moveY < 0) _this9.moveY = -0;
}
if (event.code == 'ArrowDown') {
if (_this9.moveY > 0) _this9.moveY = 0;
}
if (event.code == 'ArrowLeft') {
if (_this9.moveX < 0) _this9.moveX = -0;
}
if (event.code == 'ArrowRight') {
if (_this9.moveX > 0) _this9.moveX = 0;
}
if (event.code == 'KeyA') {
_this9.game.aKeyPressed = false;
_this9.moveZ = 0;
}
};
return _this9;
}
return PlayerEntity;
}(CharacterEntity);
// http://stackoverflow.com/questions/9792927/javascript-array-search-and-remove-string
function array_remove(array, elem, all) {
for (var i = array.length - 1; i >= 0; i--) {
if (array[i] === elem) {
array.splice(i, 1);
if (!all) break;
}
}
return array;
};
var Block = function Block(tile) {
_classCallCheck(this, Block);
var parts = tile.split(' ');
this.id = parts[0];
this.tileX = parseInt(parts[1]);
this.tileY = parseInt(parts[2]);
this.flags = parseInt(parts[3]);
};
var Level = function () {
_createClass(Level, [{
key: 'setBlock',
value: function setBlock(x, y, block) {
if (!(x in this.blocks)) {
this.blocks[x] = {};
}
if (!block) {
return;
}
this.blocks[x][y] = block;
}
}, {
key: 'removeBlock',
value: function removeBlock(x, y) {
delete this.blocks[x][y];
}
}, {
key: 'save',
value: function save() {
var jsonData = {
blocks: [],
script: this.script,
player: {
x: this.player.x,
y: this.player.y
}
};
for (var x in this.blocks) {
for (var y in this.blocks[x]) {
var block = this.blocks[x][y];
if (!block && block == null) {
return;
}
jsonData.blocks.push(block);
}
}
var json_upload = JSON.stringify(jsonData, null, 2);
var xmlHttp = new XMLHttpRequest(); // new HttpRequest instance
xmlHttp.onreadystatechange = function () {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
var json = JSON.parse(xmlHttp.responseText);
} else {}
}
};
xmlHttp.open("PUT", this.game.gameUrl + "/api/levels/" + this.id + '', true);
xmlHttp.setRequestHeader("Content-Type", "application/json");
xmlHttp.send(json_upload);
}
}, {
key: 'addEntity',
value: function addEntity(id, type, x, y) {
var t = new this.game.entityTypes[type](this.game, this);
t.x = x * TILE_SIZE;
t.y = y * TILE_SIZE;
this.level.entities[id] = t;
return t;
}
}]);
function Level(game, level) {
_classCallCheck(this, Level);
this.game = game;
this.name = level.name;
this.entities = {};
this.blocks = {};
this.player = level.player;
this.flags = level.flags;
this.script = level.script;
this.objects = [];
for (var i in level.blocks) {
var block = level.blocks[i];
if (block != null) this.setBlock(block.x, block.y, block);
}
this.player = new PlayerEntity(game, level);
if ('entities' in level) {
for (var e in level.entities) {
var _entity = level.entities[e];
var type = _entity.type;
var entity = new this[type](_entity);
this.objects.push(entity);
this.entities[_entity.id] = entity;
}
}
this.objects.push(this.player);
}
_createClass(Level, [{
key: 'render',
value: function render() {}
}]);
return Level;
}();
},{}]},{},[4]);
|
'use strict';
const path = require('path');
const staticPath = path.resolve(__dirname, 'lib', 'static');
module.exports = {
entry: './main.js',
context: staticPath,
output: {
path: staticPath,
filename: 'bundle.min.js'
},
module: {
rules: [
{
test: /\.jsx?$/,
loader: 'babel-loader',
query: {
presets: ['react', 'es2015', 'env', 'stage-2']
}
},
{
test: /\.css$/,
loader: 'style-loader!css-loader'
}
]
}
};
|
import React from "react";
const label = {
display: "inline-block",
fontWeight: 700,
marginBottom: 0.25
};
const input = {
border: "1px solid",
borderColor: "blue",
marginBottom: 0.25,
resize: "none",
width: "100%"
};
const button = {
fontSize: "1em",
margin: "1em",
padding: "0.25em 1em",
border: "2px solid #78BE20",
borderRadius: "3px",
color: "white",
cursor: "pointer",
background: "#78BE20"
};
class Profile extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
title: "Mr",
firstName: "Budi",
lastName: "Mulyawan",
email: "Budi.Mulyawan@mann.travel",
notepad: 'Cost centre code XYZ123',
};
}
upload() {
if (webBrowser) {
// webBrowser.sendTerminalCommand('N.' + this.state.lastName + '/' + this.state.firstName + this.state.title);
// webBrowser.sendTerminalCommand('MT.' + this.state.email);
// webBrowser.sendTerminalCommand('NP.' + this.state.notepad);
var name = webBrowser.getPassengerNames();
alert(name);
}
}
render() {
return (
<div>
<h1>Profile</h1>
<div>
<label style={label}>Title</label>
<input style={input} type="text" value={this.state.title} />
<label style={label}>First name</label>
<input style={input} type="text" value={this.state.firstName} />
<label style={label}>Last name</label>
<input style={input} type="text" value={this.state.lastName} />
<label style={label}>Email</label>
<input style={input} type="email" value={this.state.email} />
<label style={label}>Notepad</label>
<input style={input} type="text" value={this.state.notepad} />
<button style={button} onClick={this.upload.bind(this)}>
Upload
</button>
</div>
<p>Travelport Pacific 2017</p>
</div>
);
}
}
export default Profile;
|
"use strict"
Meteor.startup(function () {
Meteor.subscribe('users')
})
Template.userList.events({
'click .name a': manageRolesClicked,
'click .roles': manageRolesClicked
})
Template.userList.helpers({
users: function () {
return Meteor.users.find()
},
mobile: function () {
var profile = this.profile,
mobile = ''
if (profile)
mobile = profile.mobile
if ("null" === mobile || !mobile)
mobile = ''
return mobile
},
emailAddress: function () {
var emails = this.emails
if (emails && emails.length > 0) {
return emails[0].address
}
return ""
}
})
function manageRolesClicked (evt) {
var $person,
userId
evt.preventDefault()
$person = $(evt.target).closest('.person')
userId = $person.attr('data-id')
Session.set('selectedUserId', userId)
$('#user-roles').modal()
}
|
'use strict';
/**
* Module dependencies.
*/
var should = require('should'),
mongoose = require('mongoose'),
Grid = require('gridfs-stream');
/**
* Globals
*/
var connected = mongoose.Connection.STATES.connected;
var db = mongoose.connection.db;
var mongo = mongoose.mongo;
/**
* Unit tests
*/
describe('MongoDB Test:', function() {
beforeEach(function(done) {
setTimeout(function() {
var gfs = new Grid(db, mongo);
done();
}, 500);
});
describe('Connection Availability', function() {
it('should be able to have an active mongoose connection', function(done) {
done();
});
});
});
|
/**
* the-wall-of-quotes
*
* Copyright 2016-2017, Andrea Sonny, All rights reserved.
*
* @author: Andrea Sonny <andreasonny83@gmail.com>
*/
// look in ./config for protractor.conf.js
exports.config = require('./config/protractor.conf.js').config;
|
var sisr__smooth_8h =
[
[ "SISRSmoother", "classSISRSmoother.html", "classSISRSmoother" ],
[ "Mat", "sisr__smooth_8h.html#ae601f56a556993079f730483c574356f", null ],
[ "Vec", "sisr__smooth_8h.html#a4c7df05c6f5e8a0d15ae14bcdbc07152", null ],
[ "SISRResampStyle", "sisr__smooth_8h.html#a2486051fd2028dedca520d3e0f8fd92f", [
[ "everytime_multinomial", "sisr__smooth_8h.html#a2486051fd2028dedca520d3e0f8fd92faefd13eec9fdcde04f037a4bd3dd594aa", null ],
[ "never", "sisr__smooth_8h.html#a2486051fd2028dedca520d3e0f8fd92fac7561db7a418dd39b2201dfe110ab4a4", null ],
[ "ess_multinomial", "sisr__smooth_8h.html#a2486051fd2028dedca520d3e0f8fd92fa9c6a482b0d50f2734e0da9f99d168098", null ],
[ "everytime_multinomial", "sisr__smooth_8h.html#a2486051fd2028dedca520d3e0f8fd92faefd13eec9fdcde04f037a4bd3dd594aa", null ],
[ "never", "sisr__smooth_8h.html#a2486051fd2028dedca520d3e0f8fd92fac7561db7a418dd39b2201dfe110ab4a4", null ],
[ "ess_multinomial", "sisr__smooth_8h.html#a2486051fd2028dedca520d3e0f8fd92fa9c6a482b0d50f2734e0da9f99d168098", null ]
] ]
]; |
'use strict';
var chai = require('chai'),
expect = chai.expect,
sinon = require('sinon'),
sinonChai = require("sinon-chai"),
expectSinonChai = chai.use(sinonChai),
util = require('util'),
lodash = require('lodash'),
errors = require('../../lib/errors'),
DirectiveContext = require('trbl-evergreen/lib/directive-context.js'),
TestUtils = require('trbl-evergreen/test/utils.js'),
StateManager = require('../../lib/state-manager'),
ConsulDirective = require('../../lib/directive');
describe('Consul Source Directive', function() {
describe('Configuration', function(){
it('should configure itself from environment variable.', function(){
var directive = new ConsulDirective(null, {
EV_CONSUL_URI: 'https://consul.the-trbl.com:18500?dc=us-east-1&consistent=true&token=abc123'
});
expect(directive.config.host).to.eq('consul.the-trbl.com');
expect(directive.config.port).to.eq(18500);
expect(directive.config.secure).to.be.true;
expect(directive.config.dc).to.eq('us-east-1');
expect(directive.config.consistent).to.be.true;
expect(directive.config.token).to.eq('abc123');
});
it('should configure itself from a configuration object', function(){
var directive = new ConsulDirective({
host: 'consul2.the-trbl.com',
port: 18600,
secure: false,
dc: 'us-west-2',
consistent: false,
token: '123abc'
});
expect(directive.config.host).to.eq('consul2.the-trbl.com');
expect(directive.config.port).to.eq(18600);
expect(directive.config.secure).to.be.false;
expect(directive.config.dc).to.eq('us-west-2');
expect(directive.config.consistent).to.be.false;
expect(directive.config.token).to.eq('123abc');
});
it('should provide a sensible default configuration', function(){
var directive = new ConsulDirective();
expect(directive.config.host).to.eq('localhost');
expect(directive.config.port).to.eq(8500);
expect(directive.config.secure).to.be.false;
});
});
describe('Expression Parsing', function(){
var consulDirective = new ConsulDirective();
it('should throw an error if the entity/method is invalid', function(){
expect(function(){ consulDirective.parseExpression('acl.list'); }).to.not.throw(Error);
expect(function(){
consulDirective.parseExpression('acl.get?id=abc123');
}).to.not.throw(Error);
expect(function(){ consulDirective.parseExpression('blah'); }).to.throw(Error);
expect(function(){ consulDirective.parseExpression('blah.blah'); }).to.throw(Error);
expect(function(){ consulDirective.parseExpression('blah?foo=bar'); }).to.throw(Error);
expect(function(){ consulDirective.parseExpression('blah.blah?foo=bar'); }).to.throw(Error);
});
it('should return a method and parsed options', function(){
var context = consulDirective.parseExpression('acl.get?id=abc123');
expect(context.method).to.eq('acl.get');
expect(context.options.id).to.eq('abc123');
});
it('should allow no options to be passed', function(){
var context = consulDirective.parseExpression('acl.list');
expect(context.method).to.eq('acl.list');
expect(context.options).to.not.be.undefined;
expect(context.options).to.not.be.null;
});
it('should throw an error if method requirements aren\'t satisfied.', function(){
expect(function(){ consulDirective.parseExpression('acl.get'); }).to.throw(Error);
});
it('should return defaults if they are not specified', function(){
var context = consulDirective.parseExpression('acl.list');
expect(context.method).to.eq('acl.list');
expect(context.options.ignoreStartupNodata).to.eq(false);
expect(context.options.mode).to.eq('once');
});
});
describe('Context Handling', function(){
var methodMock, consul, context, consulDirective;
// This is a real response (from the node-consul documentation);
var kvResponse = { db: 'mysql://localhost:3306' };
beforeEach(function(){
methodMock = sinon.stub();
consul = {
kv: {
get: methodMock,
},
};
context = {
method: 'kv.get',
options: {
mode: 'once',
},
};
consulDirective = new ConsulDirective(null, null, consul);
});
it('should return an error if the expression cannot be parsed', function(){
var context = new DirectiveContext(
'consul',
'nonexistent.function',
[{ field: 'foo' }]
);
var callback = sinon.spy();
consulDirective.handle(context, {}, {}, callback);
expect(callback).to.be.calledWith(sinon.match(Error));
});
it('should return an error if the config item cannot be retrieved', function(){
var context = new DirectiveContext(
'consul',
'kv.get?key=/database',
[{ field: 'db' }]
);
methodMock.callsArgWith(1, new Error('Whoops!'));
var callback = sinon.spy();
consulDirective.handle(context, {}, {}, callback);
expect(callback).to.be.calledWith(sinon.match(Error));
});
it('should allow clients to ignore startup failure', function(){
var context = new DirectiveContext(
'consul',
'kv.get?key=/database&ignoreStartupNodata=true',
[{ field: 'db' }]
);
methodMock.callsArgWith(1, new Error('Whoops!'));
var callback = sinon.spy();
consulDirective.handle(context, {}, {}, callback);
expect(callback).to.be.calledWith(null, sinon.match.instanceOf(DirectiveContext));
var spyArgs = callback.getCall(0).args;
expect(spyArgs[1].value).to.be.an.instanceOf(StateManager);
});
it('should retrieve the config item on startup', function(){
var context = new DirectiveContext(
'consul',
'kv.get?key=/database&ignoreStartupNodata=true',
[{ field: 'db' }]
);
methodMock.callsArgWith(1, null, kvResponse);
var callback = sinon.spy();
consulDirective.handle(context, {}, {}, callback);
expect(callback).to.be.calledWith(null, sinon.match.instanceOf(DirectiveContext));
var spyArgs = callback.getCall(0).args;
expect(spyArgs[1].value).to.be.an.instanceOf(StateManager);
var stateManager = spyArgs[1].value;
expect(stateManager.value).to.eq(kvResponse);
});
});
});
|
const fs = require('fs');
const { resolve } = require('path');
const merge = require('lodash.merge');
const environment = process.env.NODE_ENV || 'development';
const debug = environment === 'development' && !process.argv.includes('build');
const sandbox = process.env.SANDBOX === 'true' || debug;
const overrideProp = process.env.CONFIG_OVERRIDE_KEY || 'sandboxOverrides';
const configDir = process.env.CONFIG_DIR || 'config';
const getConfigs = (paths) => paths.map((path) => {
if (fs.existsSync(path)) return require(path);
return null;
});
const getPath = (name) => resolve(`${__dirname}/../../${configDir}/${name}`);
const overrides = getConfigs([
getPath('default.js'),
getPath(`${environment}.js`),
getPath('local.js'),
]);
const base = { environment, debug, sandbox };
let config = merge(base, ...overrides);
if (sandbox) config = merge(config, config[overrideProp]);
delete config[overrideProp];
module.exports = config;
|
/*
The MIT License (MIT)
Copyright (c) 2016 Narendra Sisodiya https://github.com/nsisodiya
*/
module.exports = function (Main, Rest) {
Rest.map((v) => {
return Object.getOwnPropertyNames(v.prototype);
}).reduce(function (a, b) {
return a.concat(b);
}, []).filter(function (item, pos, arr) {
return arr.indexOf(item) === pos && item !== 'constructor';
}).map((method) => {
var backup = Main.prototype[method];
Main.prototype[method] = function () {
Rest.map((v) => {
if (typeof v.prototype[method] === "function") {
v.prototype[method].apply(this, arguments);
}
});
if (typeof backup === 'function') {
backup.apply(this, arguments);
}
}
})
}; |
function Clouds() {
function webGlSupport() {
try {
return !!window.WebGLRenderingContext && !!document.createElement('canvas').getContext('experimental-webgl');
} catch(e) {
return false;
}
}
this.start = function() {
container = document.createElement('div');
$('body').prepend(container);
// Bg gradient
var canvas = document.createElement('canvas');
canvas.width = 32;
canvas.height = (window.innerHeight + 3);
var context = canvas.getContext('2d');
var gradient = context.createLinearGradient(0, 0, 0, canvas.height);
// gradient.addColorStop(0, "#04142E");
// gradient.addColorStop(0.35, "#1D508F");
// gradient.addColorStop(0.5, "#5299D1");
// gradient.addColorStop(1, "#1D508F");
gradient.addColorStop(0, "#1C1F21");
gradient.addColorStop(0.35, "#1C1F21");
gradient.addColorStop(0.5, "#1C1F21");
gradient.addColorStop(1, "#1D508F");
context.fillStyle = gradient;
context.fillRect(0, 0, canvas.width, canvas.height);
container.id = 'clouds';
container.style.background = 'url(' + canvas.toDataURL('image/png') + ')';
container.style.backgroundSize = '32px 100%';
container.style.position = 'absolute';
container.style.top = '0px';
container.style.left = '0px';
container.style.zIndex = '0';
container.style.width = window.innerWidth + 'px';
container.style.height = window.innerHeight + 'px';
container.style.overflow = 'hidden';
$(container).css({
opacity: 0
});
if (webGlSupport()) {
var container;
var camera, scene, renderer;
var mesh, geometry, material;
var mouseX = 0, mouseY = 0;
var start_time = Date.now();
var windowHalfX = window.innerWidth / 2;
var windowHalfY = (window.innerHeight + 3) / 2;
function init() {
camera = new THREE.PerspectiveCamera(30, window.innerWidth / (window.innerHeight + 3), 1, 3000);
camera.position.z = 6000;
scene = new THREE.Scene();
geometry = new THREE.Geometry();
var texture = THREE.ImageUtils.loadTexture('/img/cloud10.png', null, animate);
texture.magFilter = THREE.LinearMipMapLinearFilter;
texture.minFilter = THREE.LinearMipMapLinearFilter;
var fog = new THREE.Fog(0x4584b4, -100, 3000);
material = new THREE.ShaderMaterial({
uniforms: {
"map": {
type: "t",
value: texture
},
"fogColor": {
type: "c",
value: fog.color
},
"fogNear": {
type: "f",
value: fog.near
},
"fogFar": {
type: "f",
value: fog.far
},
},
vertexShader: 'varying vec2 vUv; void main() {vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);}',
fragmentShader: 'uniform sampler2D map; uniform vec3 fogColor; uniform float fogNear; uniform float fogFar; varying vec2 vUv; void main(){ float depth = gl_FragCoord.z / gl_FragCoord.w; float fogFactor = smoothstep(fogNear, fogFar, depth); gl_FragColor = texture2D(map, vUv); gl_FragColor.w *= pow(gl_FragCoord.z, 20.0); gl_FragColor = mix(gl_FragColor, vec4(fogColor, gl_FragColor.w), fogFactor); }',
depthWrite: false,
depthTest: false,
transparent: true
});
var plane = new THREE.Mesh(new THREE.PlaneGeometry(64, 64));
for (var i = 0; i < 8000; i++) {
plane.position.x = Math.random() * 1000 - 500;
plane.position.y = -Math.random() * Math.random() * 200 - 15;
plane.position.z = i;
plane.rotation.z = Math.random() * Math.PI;
plane.scale.x = plane.scale.y = Math.random() * Math.random() * 1.5 + 0.5;
THREE.GeometryUtils.merge(geometry, plane);
}
mesh = new THREE.Mesh(geometry, material);
scene.add(mesh);
mesh = new THREE.Mesh(geometry, material);
mesh.position.z = -8000;
scene.add(mesh);
renderer = new THREE.WebGLRenderer({
antialias: false
});
renderer.setSize(window.innerWidth, (window.innerHeight + 3));
container.appendChild(renderer.domElement);
document.addEventListener('mousemove', onDocumentMouseMove, false);
window.addEventListener('resize', onWindowResize, false);
}
function onDocumentMouseMove(event) {
mouseX = (event.clientX - windowHalfX) * 0.03;
mouseY = (event.clientY - windowHalfY) * 0.03;
}
function onWindowResize(event) {
container.style.width = window.innerWidth + 'px';
container.style.height = window.innerHeight + 'px';
camera.aspect = window.innerWidth / (window.innerHeight + 3);
camera.updateProjectionMatrix();
renderer.setSize(window.innerWidth, (window.innerHeight + 3));
}
function animate() {
requestAnimationFrame(animate);
position = ((Date.now() - start_time) * 0.005) % 8000;
camera.position.x += (mouseX - camera.position.x) * 0.005;
camera.position.y += (-mouseY - camera.position.y) * 0.005;
camera.position.z = -position + 8000;
renderer.render(scene, camera);
}
init();
}
$(container).animate({
opacity: 1
}, 2000);
};
this.stop = function() {
$('#clouds').remove();
};
}
Clouds = new Clouds(); |
export const logError = message => {
console.error(message);
};
|
module.exports = {
"extends": ["eslint:recommended", "google"],
"env": {
// For more environments, see here: http://eslint.org/docs/user-guide/configuring.html#specifying-environments
"browser": true,
// "es6": true
},
"rules": {
// Insert custom rules here
"no-var": "off",
},
}
|
var key = 'rabbit__compressed';
var data = {data: [{age: 1}, {age: '2'}]};
var rabbit_c = new SecureLS({encodingType: 'rabbit'});
ae = rabbit_c.RABBIT.encrypt(JSON.stringify(data), 's3cr3t@123');
bde = rabbit_c.RABBIT.decrypt(ae.toString(), 's3cr3t@123');
de = bde.toString(rabbit_c.enc._Utf8);
rabbit_c.set(key, data);
console.log('RABBIT Compressed');
console.log(localStorage.getItem(key));
console.log(rabbit_c.get(key));
console.log('____________________________________') |
"use strict";
exports.__esModule = true;
exports.RecaptchaV2 = exports.RecaptchaExpired = exports.RecaptchaError = exports.RecaptchaVerified = void 0;
var _aureliaFramework = require("aurelia-framework");
var _recaptchaBase = require("./recaptcha-base");
var _dec, _class, _class2, _descriptor, _descriptor2, _descriptor3, _descriptor4, _descriptor5, _descriptor6, _temp;
function _initializerDefineProperty(target, property, descriptor, context) { if (!descriptor) return; Object.defineProperty(target, property, { enumerable: descriptor.enumerable, configurable: descriptor.configurable, writable: descriptor.writable, value: descriptor.initializer ? descriptor.initializer.call(context) : void 0 }); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
function _applyDecoratedDescriptor(target, property, decorators, descriptor, context) { var desc = {}; Object.keys(descriptor).forEach(function (key) { desc[key] = descriptor[key]; }); desc.enumerable = !!desc.enumerable; desc.configurable = !!desc.configurable; if ('value' in desc || desc.initializer) { desc.writable = true; } desc = decorators.slice().reverse().reduce(function (desc, decorator) { return decorator(target, property, desc) || desc; }, desc); if (context && desc.initializer !== void 0) { desc.value = desc.initializer ? desc.initializer.call(context) : void 0; desc.initializer = undefined; } if (desc.initializer === void 0) { Object.defineProperty(target, property, desc); desc = null; } return desc; }
function _initializerWarningHelper(descriptor, context) { throw new Error('Decorating class property failed. Please ensure that ' + 'proposal-class-properties is enabled and set to use loose mode. ' + 'To use proposal-class-properties in spec mode with decorators, wait for ' + 'the next major version of decorators in stage 2.'); }
var scriptReady = false;
var callbackName = "__recaptcha_callback_" + (0, _recaptchaBase.getHash)() + "__";
var callbackPromise = new Promise(function (resolve) {
return window[callbackName] = function () {
scriptReady = true;
resolve();
};
});
var RecaptchaVerified = function RecaptchaVerified(component, token, widgetId) {
this.component = component;
this.grecaptcha = grecaptcha;
this.token = token;
this.widgetId = widgetId;
};
exports.RecaptchaVerified = RecaptchaVerified;
var RecaptchaError = function RecaptchaError(component, widgetId) {
this.component = component;
this.grecaptcha = grecaptcha;
this.widgetId = widgetId;
};
exports.RecaptchaError = RecaptchaError;
var RecaptchaExpired = function RecaptchaExpired(component, widgetId) {
this.component = component;
this.grecaptcha = grecaptcha;
this.widgetId = widgetId;
};
exports.RecaptchaExpired = RecaptchaExpired;
var RecaptchaV2 = (_dec = (0, _aureliaFramework.customElement)('recaptcha-v2'), _dec(_class = (_class2 = (_temp = function (_RecaptchaBase) {
_inheritsLoose(RecaptchaV2, _RecaptchaBase);
function RecaptchaV2() {
var _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
_this = _RecaptchaBase.call.apply(_RecaptchaBase, [this].concat(args)) || this;
_initializerDefineProperty(_this, "callback", _descriptor, _assertThisInitialized(_this));
_initializerDefineProperty(_this, "errorCallback", _descriptor2, _assertThisInitialized(_this));
_initializerDefineProperty(_this, "expiredCallback", _descriptor3, _assertThisInitialized(_this));
_initializerDefineProperty(_this, "size", _descriptor4, _assertThisInitialized(_this));
_initializerDefineProperty(_this, "tabindex", _descriptor5, _assertThisInitialized(_this));
_initializerDefineProperty(_this, "theme", _descriptor6, _assertThisInitialized(_this));
_this.widgetId = null;
return _this;
}
var _proto = RecaptchaV2.prototype;
_proto.bind = function bind() {
_RecaptchaBase.prototype.bind && _RecaptchaBase.prototype.bind.call(this);
if (!this.sitekey) {
this.sitekey = this.config.get('siteKeys.v2');
}
var lang = document.getElementsByTagName('html')[0].getAttribute('lang') || this.config.get('lang');
var script = "https://www.google.com/recaptcha/api.js?onload=" + callbackName + "&render=explicit&hl=" + lang;
this.loadScript(this.getScriptId(), script);
this.registerResetEvent();
};
_proto.attached = function attached() {
_RecaptchaBase.prototype.attached && _RecaptchaBase.prototype.attached.call(this);
this.render();
};
_proto.registerResetEvent = function registerResetEvent() {
var _this2 = this;
var eventName = "grecaptcha:reset:" + this.id;
this.__auevents__[eventName] = this.events.subscribe(eventName, function () {
_this2.logger.debug("Triggered " + eventName);
grecaptcha && grecaptcha.reset && grecaptcha.reset(_this2.widgetId);
_this2.value = null;
});
};
_proto.render = function render() {
var _this3 = this;
if (!scriptReady) {
return callbackPromise.then(function () {
return _this3.render();
});
}
this.widgetId = grecaptcha.render(this.element, this.renderOptions());
};
_proto.renderOptions = function renderOptions() {
var _this4 = this;
var callback = function callback() {
if (_this4.widgetId !== null) {
_this4.value = grecaptcha.getResponse(_this4.widgetId);
_this4.logger.debug('reCAPTCHA callback', _this4.widgetId, _this4.value);
}
if (_this4.callback) {
if (typeof _this4.callback === 'function') {
return _this4.callback(new RecaptchaVerified(_this4, _this4.value, _this4.widgetId));
}
if (window[_this4.callback]) {
return window[_this4.callback].call(null, new RecaptchaVerified(_this4, _this4.value, _this4.widgetId));
}
}
};
var errorCallback = function errorCallback() {
_this4.value = undefined;
_this4.logger.debug('reCAPTCHA error-callback', _this4.widgetId);
if (_this4.errorCallback) {
if (typeof _this4.errorCallback === 'function') {
return _this4.callback(new RecaptchaError(_this4, _this4.widgetId));
}
if (window[_this4.errorCallback]) {
return window[_this4.errorCallback].call(null, new RecaptchaError(_this4, _this4.widgetId));
}
}
};
var expiredCallback = function expiredCallback() {
_this4.value = undefined;
_this4.logger.debug('reCAPTCHA expired-callback', _this4.widgetId);
if (_this4.expiredCallback) {
if (typeof _this4.expiredCallback === 'function') {
return _this4.expiredCallback(new RecaptchaExpired(_this4, _this4.widgetId));
}
if (window[_this4.expiredCallback]) {
return window[_this4.expiredCallback].call(null, new RecaptchaExpired(_this4, _this4.widgetId));
}
}
};
return {
callback: callback,
'error-callback': errorCallback,
'expired-callback': expiredCallback,
sitekey: this.sitekey,
size: this.size,
tabindex: this.tabindex,
theme: this.theme,
type: this.type
};
};
return RecaptchaV2;
}(_recaptchaBase.RecaptchaBase), _temp), (_descriptor = _applyDecoratedDescriptor(_class2.prototype, "callback", [_aureliaFramework.bindable], {
configurable: true,
enumerable: true,
writable: true,
initializer: null
}), _descriptor2 = _applyDecoratedDescriptor(_class2.prototype, "errorCallback", [_aureliaFramework.bindable], {
configurable: true,
enumerable: true,
writable: true,
initializer: null
}), _descriptor3 = _applyDecoratedDescriptor(_class2.prototype, "expiredCallback", [_aureliaFramework.bindable], {
configurable: true,
enumerable: true,
writable: true,
initializer: null
}), _descriptor4 = _applyDecoratedDescriptor(_class2.prototype, "size", [_aureliaFramework.bindable], {
configurable: true,
enumerable: true,
writable: true,
initializer: function initializer() {
return 'normal';
}
}), _descriptor5 = _applyDecoratedDescriptor(_class2.prototype, "tabindex", [_aureliaFramework.bindable], {
configurable: true,
enumerable: true,
writable: true,
initializer: function initializer() {
return 0;
}
}), _descriptor6 = _applyDecoratedDescriptor(_class2.prototype, "theme", [_aureliaFramework.bindable], {
configurable: true,
enumerable: true,
writable: true,
initializer: function initializer() {
return 'light';
}
})), _class2)) || _class);
exports.RecaptchaV2 = RecaptchaV2; |
var app = app || {};
(function(){
app.TestButton = React.createClass({displayName: "TestButton",
handleClick: function() {
this.props.submitTestTask(this.props.btnType);
},
render: function() {
return ( React.createElement("button", {onClick: this.handleClick,
className: "btn btn-test"}, " ", React.createElement("span", {className: "btn-test-text"}, " ", this.props.btn_name, " ")) );
}
});
app.CodeEditor = React.createClass({displayName: "CodeEditor",
handleType:function(){
this.props.updateCode(this.editor.session.getValue());
},
componentDidMount:function(){
this.editor = ace.edit("codeeditor");
this.editor.setTheme("ace/theme/clouds");
this.editor.setOptions({
fontSize: "1.2em"
});
this.editor.session.setMode("ace/mode/"+this.props.language);
},
render:function(){
return (
React.createElement("div", {id: "codeeditor", onKeyUp: this.handleType})
);
}
});
app.TokenEditor = React.createClass({displayName: "TokenEditor",
handleChange:function(){
var new_token = this.refs.tokenInput.value;
this.props.updateToken(new_token);
},
render: function(){
return (
React.createElement("input", {className: "input-url", onChange: this.handleChange, ref: "tokenInput", placeholder: "Input Server Access Token"})
);
}
});
app.UrlEditor = React.createClass({displayName: "UrlEditor",
getInitialState: function(){
return {
url_vaild:true
}
},
handleChange:function(){
//if url valid, update state, if not, warn
var url_str = this.refs.urlInput.value;
if (app.isUrl(url_str)){
this.setState({url_vaild:true});
//this.probs.updateUrl(url_str)
}else{
this.setState({url_vaild:false});
}
this.props.updateUrl(url_str);
},
classNames:function(){
return 'input-url ' + ((this.state.url_vaild) ? 'input-right':'input-error');
},
render: function(){
return (
React.createElement("input", {className: this.classNames(), onChange: this.handleChange, ref: "urlInput", placeholder: "Type Server or App URL"})
);
}
});
var ServerList = app.ServerList = React.createClass({displayName: "ServerList",
getInitialState:function(){
return {chosedServer:-1, currentDisplay:"Servers"};
},
onServerClick:function(event){
console.log(this.refs.menu_display);
},
render:function(){
return (
React.createElement("div", {className: "dropdown"},
React.createElement("button", {ref: "menu_display", className: "btn btn-default dropdown-toggle", type: "button", id: "dropdownMenu1", "data-toggle": "dropdown"},
this.state.currentDisplay,
React.createElement("span", {className: "caret"})
),
React.createElement("ul", {className: "dropdown-menu", role: "menu", "aria-labelledby": "dropdownMenu1"},
React.createElement("li", {role: "presentation"}, React.createElement("a", {onClick: this.onServerClick, role: "menuitem", tabindex: "-1", href: "#"}, "SMART")),
React.createElement("li", {role: "presentation"}, React.createElement("a", {onClick: this.onServerClick, role: "menuitem", tabindex: "-1", href: "#"}, "HAPI FHIR")),
React.createElement("li", {role: "presentation"}, React.createElement("a", {onClick: this.onServerClick, role: "menuitem", tabindex: "-1", href: "#"}, "FHIR Genomics"))
)
)
);
}
})
var ResultDisplay = app.ResultDisplay = React.createClass({displayName: "ResultDisplay",
getInitialState:function(){
return {'level':-1, test_type:0, 'steps':[]}
},
displayResult:function(res_dict){
console.log(res_dict);
var test_type = res_dict.test_type
this.setState({'test_type':test_type})
if (test_type == 0){
this.setState({'level':res_dict.level});
}
this.setState({'steps':res_dict['steps']});
},
render: function(){
return (
React.createElement("div", {className: "result-container"},
React.createElement("div", {className: "result-head"}, React.createElement("span", {className: "area-title area-title-black"}, "Test Type: "), " ", React.createElement("span", null, this.props.testType)),
React.createElement("div", {className: "detail-result"},
React.createElement("div", {className: "result-sum"},
this.state.test_type == 0 ? React.createElement("h3", null, "Level: ", this.state.level) : null
),
this.state.steps.map(function(step){
return React.createElement(StepDisplay, {stepInfo: step})
})
)
)
)
}
});
var StepDisplay = app.StepDisplay = React.createClass({displayName: "StepDisplay",
getInitialState: function(){
return {
is_img_hide:true,
is_modal_show:false,
is_has_image:false
}
},
componentDidMount:function(){
if(this.props.stepInfo.addi){
this.setState({is_has_image:true});
}
},
handleTextClick:function(){
if (this.state.is_has_image){
this.setState({is_img_hide:!this.state.is_img_hide});
}
},
handleShowFullImage:function(event){
event.stopPropagation();
this.setState({is_modal_show:true});
},
handleHideModal(){
this.setState({is_modal_show:false});
},
handleShowModal(){
this.setState({is_modal_show: true});
},
render:function(){
return (
React.createElement("div", {className: "step-brief step-brief-success", onClick: this.handleTextClick},
React.createElement("div", null, React.createElement("span", {className: "step-brief-text"}, this.props.stepInfo.desc)),
React.createElement("div", {hidden: this.state.is_img_hide && !this.state.is_has_image, className: "step-img-block"},
React.createElement("button", {onClick: this.handleShowFullImage, className: "btn btn-primary"}, "Full Image"),
React.createElement("img", {className: "img-responsive img-rounded step-img", src: this.props.stepInfo.addi})
),
this.state.is_modal_show && this.state.is_has_image ? React.createElement(Modal, {handleHideModal: this.handleHideModal, title: "Step Image", content: React.createElement(FullImageArea, {img_src: this.props.stepInfo.addi})}) : null
)
);
}
});
app.UserBtnArea = React.createClass({displayName: "UserBtnArea",
handleLogout:function(){
app.showMsg("Logout");
},
render:function(){
return (
React.createElement("div", {className: "user-op"},
React.createElement("button", {className: "btn btn-user", onClick: this.props.history_action}, "History"),
React.createElement("button", {className: "btn btn-user"}, "Search Task"),
React.createElement("button", {className: "btn btn-user"}, "Change Password"),
React.createElement("button", {className: "btn btn-user", onClick: this.handleLogout}, React.createElement("span", {className: "glyphicon glyphicon-off"}))
)
);
}
});
var FullImageArea = app.FullImageArea = React.createClass({displayName: "FullImageArea",
render:function(){
return(
React.createElement("img", {src: this.props.img_src, className: "img-responsive"})
);
}
});
var TaskItem = app.TaskItem = React.createClass({displayName: "TaskItem",
handleClick:function(){
this.props.itemClicked(this.props.task_id);
},
render:function(){
return (
React.createElement("div", {className: "list-item", onClick: this.handleClick},
React.createElement("span", null, "Task ID:"), this.props.task_id
)
);
}
});
var TaskList = app.TaskList = React.createClass({displayName: "TaskList",
render:function(){
return (
React.createElement("div", {className: "task-list"},
React.createElement("h2", null, "History Tasks"),
React.createElement("div", {className: "list-content"},
this.props.tasks.map(function(task_id){
return React.createElement(TaskItem, {itemClicked: this.props.fetchTaskDetail, task_id: task_id})
},this)
)
)
);
}
});
var HistoryViewer = app.HistoryViewer = React.createClass({displayName: "HistoryViewer",
getInitialState:function(){
return {tasks:[]};
},
updateTestResult:function(res){
this.refs.res_area.displayResult(res);
},
componentDidMount:function(){
window.hist = this;
var postData = {
token:$.cookie('fhir_token')
};
var self = this;
console.log(postData);
$.ajax({
url:'http://localhost:8000/home/history',
type:'POST',
data:JSON.stringify(postData),
dataType:'json',
cache:false,
success:function(data){
if( data.isSuccessful ){
self.setState({tasks:data.tasks});
}
}
});
},
getTaskDetail:function(task_id){
console.log(task_id);
app.setup_websocket(task_id,2)
},
render:function(){
return (
React.createElement("div", {className: "history-area"},
React.createElement(TaskList, {fetchTaskDetail: this.getTaskDetail, tasks: this.state.tasks}),
React.createElement(ResultDisplay, {ref: "res_area"})
)
);
}
});
var Modal = app.Modal = React.createClass({displayName: "Modal",
componentDidMount(){
$(ReactDOM.findDOMNode(this)).modal('show');
$(ReactDOM.findDOMNode(this)).on('hidden.bs.modal', this.props.handleHideModal);
},
render:function(){
return (
React.createElement("div", {className: "modal modal-wide fade"},
React.createElement("div", {className: "modal-dialog"},
React.createElement("div", {className: "modal-content"},
React.createElement("div", {className: "modal-header"},
React.createElement("button", {type: "button", className: "close", "data-dismiss": "modal", "aria-label": "Close"}, React.createElement("span", {"aria-hidden": "true"}, "×")),
React.createElement("h4", {className: "modal-title"}, this.props.title)
),
React.createElement("div", {className: "modal-body"},
this.props.content
),
React.createElement("div", {className: "modal-footer text-center"},
React.createElement("button", {className: "btn btn-primary center-block", "data-dismiss": "modal"}, "Close")
)
)
)
)
);
}
});
})();
|
/**
* Logger
* ======
*/
var colors = require('./ui/colorize'),
inherit = require('inherit');
/**
* Логгер. В данной реализации — обертка над console.log.
* Выводит в консоль процесс сборки проекта.
* @name Logger
*/
var Logger = module.exports = inherit( /** @lends Logger.prototype */ {
/**
* Конструктор.
* На основе одного логгера можно создать вложенный логгер с помощью аргумента scope.
* Если указан scope, то scope будет выводиться при логгировании.
* @param {String} scope
* @private
*/
__constructor: function(scope) {
this._scope = scope || '';
this._enabled = true;
},
/**
* Базовый метод для логгирования.
* @param {String} msg
* @param {String} [scope]
* @param {String} [action]
*/
log: function(msg, scope, action) {
scope = scope || this._scope;
action = action || '';
var dt = new Date();
if (this._enabled) {
console.log(
colors.grey(
zeros(dt.getHours(), 2) + ':' +
zeros(dt.getMinutes(), 2) + ':' +
zeros(dt.getSeconds(), 2) + '.' +
zeros(dt.getMilliseconds(), 3) + ' - '
) +
(action && action + ' ') +
(scope && ('[' +
colors.blue(
scope.replace(/(:.+)$/, function(s, g) {
return colors.magenta(g.substr(1));
})
) +
'] ')
) +
msg
);
}
},
/**
* Оформляет запись в лог, как действие.
* @param {String} action
* @param {String} target
* @param {String} [additionalInfo]
*/
logAction: function(action, target, additionalInfo) {
this.log(
(additionalInfo ? colors.grey(additionalInfo) : ''),
(this._scope && (this._scope + '/')) + target,
'[' + colors.green(action) + ']'
);
},
/**
* Выводит варнинг.
* @param {String} action
* @param {String} msg
*/
logWarningAction: function(action, msg) {
this.log('[' + colors.yellow(action) + '] ' + msg);
},
/**
* Выводит ошибку.
* @param {String} action
* @param {String} target
* @param {String} [additionalInfo]
*/
logErrorAction: function(action, target, additionalInfo) {
this.log(
(additionalInfo ? colors.grey(additionalInfo) : ''),
(this._scope && (this._scope + '/')) + target,
'[' + colors.red(action) + ']'
);
},
/**
* Выводит сообщение isValid
* (используется технологиями для показа сообщения о том, что таргет не нужно пересобирать).
* @param {String} target
* @param {String} [tech]
*/
isValid: function(target, tech) {
this.logAction('isValid', target, tech);
},
/**
* Выводит сообщение clean (используется технологиями для показа сообщения о том, что таргет удален).
* @param {String} target
*/
logClean: function(target) {
this.logAction('clean', target);
},
/**
* Активирует/деактивирует логгер.
* С помощью этого метода можно отключить логгирование.
* @param {Boolean} enabled
*/
setEnabled: function(enabled) {
this._enabled = enabled;
},
/**
* Возвращает активность логгера.
* @returns {Boolean}
*/
isEnabled: function() {
return this._enabled;
},
/**
* Возвращает новый логгер на основе scope текущего (складывая scope'ы).
* @param {String} scope
* @returns {Logger}
*/
subLogger: function(scope) {
var res = new Logger(this._scope + (scope.charAt(0) === ':' ? scope : (this._scope && '/') + scope));
res.setEnabled(this._enabled);
return res;
}
});
/**
* Добавляет ведущие нули.
* @param {String} s
* @param {Number} l
* @returns {String}
* @private
*/
function zeros(s, l) {
s = '' + s;
while (s.length < l) {
s = '0' + s;
}
return s;
}
|
/*
* Kendo UI v2014.2.1008 (http://www.telerik.com/kendo-ui)
* Copyright 2014 Telerik AD. All rights reserved.
*
* Kendo UI commercial licenses may be obtained at
* http://www.telerik.com/purchase/license-agreement/kendo-ui-complete
* If you do not own a commercial license, this file shall be governed by the trial license terms.
*/
(function(f, define){
define([], f);
})(function(){
(function( window, undefined ) {
var kendo = window.kendo || (window.kendo = { cultures: {} });
kendo.cultures["lo-LA"] = {
name: "lo-LA",
numberFormat: {
pattern: ["(n)"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3,0],
percent: {
pattern: ["-n %","n %"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3,0],
symbol: "%"
},
currency: {
pattern: ["(n$)","n$"],
decimals: 2,
",": ",",
".": ".",
groupSize: [3,0],
symbol: "₭"
}
},
calendars: {
standard: {
days: {
names: ["ວັນອາທິດ","ວັນຈັນ","ວັນອັງຄານ","ວັນພຸດ","ວັນພະຫັດ","ວັນສຸກ","ວັນເສົາ"],
namesAbbr: ["ອາທິດ","ຈັນ","ອັງຄານ","ພຸດ","ພະຫັດ","ສຸກ","ເສົາ"],
namesShort: ["ອ","ຈ","ອ","ພ","ພ","ສ","ເ"]
},
months: {
names: ["ມັງກອນ","ກຸມພາ","ມີນາ","ເມສາ","ພຶດສະພາ","ມິຖຸນາ","ກໍລະກົດ","ສິງຫາ","ກັນຍາ","ຕຸລາ","ພະຈິກ","ທັນວາ",""],
namesAbbr: ["ມັງກອນ","ກຸມພາ","ມີນາ","ເມສາ","ພຶດສະພາ","ມິຖຸນາ","ກໍລະກົດ","ສິງຫາ","ກັນຍາ","ຕຸລາ","ພະຈິກ","ທັນວາ",""]
},
AM: ["ເຊົ້າ","ເຊົ້າ","ເຊົ້າ"],
PM: ["ແລງ","ແລງ","ແລງ"],
patterns: {
d: "dd/MM/yyyy",
D: "dd MMMM yyyy",
F: "dd MMMM yyyy HH:mm:ss",
g: "dd/MM/yyyy H:mm tt",
G: "dd/MM/yyyy HH:mm:ss",
m: "dd MMMM",
M: "dd MMMM",
s: "yyyy'-'MM'-'dd'T'HH':'mm':'ss",
t: "H:mm tt",
T: "HH:mm:ss",
u: "yyyy'-'MM'-'dd HH':'mm':'ss'Z'",
y: "MMMM yyyy",
Y: "MMMM yyyy"
},
"/": "/",
":": ":",
firstDay: 0
}
}
}
})(this);
return window.kendo;
}, typeof define == 'function' && define.amd ? define : function(_, f){ f(); }); |
module.exports = function(SerMcglobalRequests) {
};
|
/**
* ng-openweathermap
*
* A simple & configurable provider for openweathermap.org
*
* @link https://github.com/OpenServices/ng-weathermap
* @author Michael Fladischer <michael@openservices.at>
* @license MIT License, http://www.opensource.org/licenses/MIT
*/
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
define(function () {
return factory(root.angular);
});
} else if (typeof exports === 'object') {
module.exports = factory(root.angular || (window && window.angular));
} else {
factory(root.angular);
}
})(this, function (angular) {
'use strict';
angular.module('ngOpenWeatherMap', [])
.provider('owm', function() {
var apiKey;
var units = 'metric';
var language = 'en';
var mappings = [
{
ids: [200,201,230,231],
neutral: 'storm-showers',
day: 'day-storm-showers',
night: 'night-storm-showers'
},
{
ids: [202,232],
neutral: 'thunderstorm',
day: 'day-thunderstorm',
night: 'night-thunderstorm'
},
{
ids: [210,211,212,221],
neutral: 'lightning',
day: 'day-lightning',
night: 'night-lightning'
},
{
ids: [300,301,302],
neutral: 'sprinkle',
day: 'day-sprinkle',
night: 'night-sprinkle'
},
{
ids: [310,311,312,500,],
neutral: 'rain-mix',
day: 'day-rain-mix',
night: 'night-rain-mix'
},
{
ids: [313,314,321,520,521,522,531],
neutral: 'showers',
day: 'day-showers',
night: 'night-showers'
},
{
ids: [500,501,502,503,504],
neutral: 'rain',
day: 'day-rain',
night: 'night-rain'
},
{
ids: [511,611,612,615,616,620,621,622],
neutral: 'sleet',
day: 'day-sleet',
night: 'night-sleet'
},
{
ids: [600,601,602],
neutral: 'snow',
day: 'day-snow',
night: 'night-snow'
},
{
ids: [701,741],
neutral: 'fog',
day: 'day-fog',
night: 'night-fog'
},
{
ids: [711],
neutral: 'smoke'
},
{
ids: [721],
neutral: 'day-haze'
},
{
ids: [781],
neutral: 'tornado'
},
{
ids: [771],
neutral: 'strong-wind',
day: 'day-windy'
},
{
ids: [731,751,761,762],
neutral: 'dust'
},
{
ids: [800],
neutral: 'day-sunny',
night: 'night-clear'
},
{
ids: [801,802,803,804],
neutral: 'cloudy',
day: 'day-cloudy',
night: 'night-cloudy'
},
{
ids: [900,901,902],
neutral: 'tornado'
},
{
ids: [903],
neutral: 'snowflake-cold'
},
{
ids: [904],
neutral: 'hot'
},
{
ids: [905],
neutral: 'windy'
},
{
ids: [906],
neutral: 'hail',
day: 'day-hail',
night: 'night-hail'
},
{
ids: [951],
neutral: 'beafort-0'
},
{
ids: [952],
neutral: 'beafort-1'
},
{
ids: [953],
neutral: 'beafort-2'
},
{
ids: [954],
neutral: 'beafort-3'
},
{
ids: [955],
neutral: 'beafort-4'
},
{
ids: [956],
neutral: 'beafort-5'
},
{
ids: [957],
neutral: 'beafort-6'
},
{
ids: [958],
neutral: 'beafort-7'
},
{
ids: [959],
neutral: 'beafort-8'
},
{
ids: [960],
neutral: 'beafort-9'
},
{
ids: [961],
neutral: 'beafort-10'
},
{
ids: [962],
neutral: 'beafort-11'
}
];
this.setApiKey = function(value) {
apiKey = value;
return this;
};
this.useMetric = function() {
units = 'metric';
return this;
};
this.useImperial = function() {
units = 'imperial';
return this;
};
this.setLanguage = function(value) {
language = value;
return this;
};
this.$get = ['$http', '$q', function($http, $q) {
if (!apiKey) {
console.warn('No OpenWeatherMap API key set.');
}
var fetch = function(base, query) {
var url = base + "?APPID=" + apiKey + "&lang=" + language + '&units=' + units + '&' + query;
var deferred = $q.defer();
$http
.get(url)
.then(function(data, status, headers, config) {
if (parseInt(data.data.cod) === 200) {
deferred.resolve(data.data);
} else {
deferred.reject(data.data);
}
})
.catch(function(data, status, headers, config) {
deferred.reject(status);
});
return deferred.promise;
};
var api = function(base) {
return {
find: function(city) {
return fetch(base, 'q=' + city + '&type=like');
},
name: function(city) {
return fetch(base, 'q=' + city + '&type=accurate');
},
id: function(id) {
return fetch(base, 'id=' + id);
},
coordinates: function(lat, lon) {
return fetch(base, 'lat=' + lat + '&lon=' + lon);
},
zip: function(zip) {
return fetch(base, 'zip=' + zip);
}
};
};
var icon = function(type) {
return function(id) {
var iid = parseInt(id);
var mapping = mappings.filter(function(m) {
return (m.ids.indexOf(iid) >= 0);
});
if (mapping.length !== 1) {
return 'umbrella'; // Better safe than sorry
}
if (!mapping[0].hasOwnProperty(type)) {
return mapping[0].neutral;
}
return mapping[0][type];
};
};
return {
icons: {
neutral: icon('neutral'),
day: icon('day'),
night: icon('night')
},
current: api('http://api.openweathermap.org/data/2.5/weather'),
forecast5: api('http://api.openweathermap.org/data/2.5/forecast'),
forecast16: api('http://api.openweathermap.org/data/2.5/forecast/daily')
};
}];
})
.directive('owmIcon', function() {
return {
restrict: 'E',
scope: {
id: '@',
type: '@'
},
template: '<i class="wi wi-{{ name }}"></i>',
controller: ['$scope', 'owm', function($scope, owm) {
$scope.$watchGroup(['id', 'type'], function() {
if (owm.icons.hasOwnProperty($scope.type)) {
$scope.name = owm.icons[$scope.type]($scope.id);
} else {
$scope.name = owm.icons.neutral($scope.id);
}
});
}]
};
});
}); |
angular.module('elements')
.config(function ($routeProvider) {
$routeProvider.when('/login', {
templateUrl: '/elements/page-login/page-login.html',
controller: 'PageLoginCtrl'
})
})
.controller('PageLoginCtrl', function($scope, $alert, $location, $auth, BaseUser, LoopBackAuth) {
$scope.authenticate = function (provider) {
$auth
.authenticate(provider)
.then(function (response) {
var accessToken = response.data;
LoopBackAuth.setUser(accessToken.id, accessToken.userId, accessToken.user);
LoopBackAuth.rememberMe = true;
LoopBackAuth.save();
return response.resource;
});
};
$scope.login = function () {
var credentials = {
email: $scope.email,
password: $scope.password
};
BaseUser
.login(credentials)
.$promise
.then(function (res) {
$location.path('/profile');
});
};
}); |
'use strict';
var job = require('../index.js'),
File = require('vinyl');
describe('gulp-job', sandbox(function () {
describe('pre', function () {
var buffer;
beforeEach(function () {
buffer = job.prototype.pre();
});
it('returns a buffer', function () {
buffer.should.be.an.instanceof(Buffer);
});
});
describe('post', function () {
var buffer;
beforeEach(function () {
buffer = job.prototype.post();
});
it('returns a buffer', function () {
buffer.should.be.an.instanceof(Buffer);
});
});
describe('capitalise', function () {
it('capitalises a word', function () {
job.prototype.capitalise('foo').should.equal('Foo');
});
});
describe('camel', function () {
it('converts seperated words to camelcase', function () {
job.prototype.camel('foo-bar-baz').should.equal('fooBarBaz');
});
});
describe('getFileName', function () {
it('returns a file name from a path', function () {
job.prototype.getFileName('/foo/bar/myfile.js').should.equal('myfile');
});
it('strips and dots from the file name', function () {
job.prototype.getFileName('/foo/bar/myfile.test.js').should.equal('myfiletest');
});
});
describe('wrap', function () {
var file;
beforeEach(function () {
sandbox.stub(job.prototype, 'pre').returns(new Buffer('foo'));
sandbox.stub(job.prototype, 'post').returns(new Buffer('bar'));
file = new File({
path: '/test/file.js',
contents: new Buffer('-middle-')
});
job.prototype.wrap(file);
});
it('wraps the file', function () {
file.contents.toString().should.equal('foo-middle-bar');
});
});
describe('funnel', function () {
var callback,
file = {};
beforeEach(function () {
callback = sandbox.stub();
file.isNull = sandbox.stub().returns(false);
file.isStream = sandbox.stub().returns(false);
file.isBuffer = sandbox.stub().returns(true);
job.prototype.push = sandbox.stub();
job.prototype.wrap = sandbox.stub();
job.prototype.funnel(file, 'utf8', callback);
});
it('checks if file isNull', function () {
file.isNull.should.have.been.calledOnce;
});
it('checks if file isStream', function () {
file.isStream.should.have.been.calledOnce;
});
it('checks if file isBuffer', function () {
file.isStream.should.have.been.calledOnce;
});
it('wraps the file', function () {
job.prototype.wrap.should.have.been.calledWithExactly(file);
});
it('pushes the file into scope', function () {
job.prototype.push.should.have.been.calledWithExactly(file);
});
it('finishes up with the callback', function () {
callback.should.have.been.calledOnce;
});
});
}));
|
'use strict';
module.exports = function(name) {
name = name.toLowerCase();
if (['test', 'mern', 'mern-cli', 'vendor', 'app'].indexOf(name) > -1) { return false; }
if (name.indexOf('.') > -1) { return false; }
if (!isNaN(parseInt(name.charAt(0), 10))) { return false; }
return true;
};
|
var FS = require('fs');
var Path = require('path');
var io = module.exports = function () {
// https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#32-leaking-arguments
var $_len = arguments.length;var args = new Array($_len); for(var $_i = 0; $_i < $_len; ++$_i) {args[$_i] = arguments[$_i];}
// arguments can be mix from io objects and strings
var lastArg = args[args.length - 1];
if (args.length > 1 && !(typeof lastArg === "string" || lastArg instanceof String)) {
this.options = args.pop ();
} else {
this.options = {};
}
// console.log (process.cwd (), Path.resolve (process.cwd ()));
this.options.anchorDir = this.options.anchorDir || Path.resolve (process.cwd ());
this.setAnchorDir (this.options.anchorDir);
this.path = Path.join.apply (Path, args.map (function (arg) {
return arg.path ? arg.path : arg
}));
// console.log (path);
// TODO: define setter for path
this.name = Path.basename (this.path);
this.extname = Path.extname (this.path);
this.extension = this.extname.substr (1);
this.onlyName = Path.basename (this.name, this.extname);
};
// this function is needed when you want to get io object or undefined
io.safe = (function() {
function F(args) {
try {
return io.apply (this, args);
} catch (e) {
return {error: true};
}
}
F.prototype = io.prototype;
return function () {
var o = new F (arguments);
if ('error' in o) {
return;
} else {
return o;
}
}
})();
io.prototype.inspect = function (depth, opts) {
if (opts && opts.showHidden)
return this
else
return "{path: "+this.path+"}";
}
io.prototype.relative = function (relPath) {
return Path.relative (this.path, relPath instanceof io ? relPath.path : relPath);
};
io.prototype.setAnchorDir = function (relPath) {
this.shortPath = function () {
var relative = Path.relative (relPath instanceof io ? relPath.path : relPath, this.path);
var absolute = Path.resolve (this.path);
if (relative.length < absolute.length && !relative.match (/^\.\./)) {
return relative;
} else {
return absolute;
}
}
};
io.prototype.shortPath = function (relPath) {
return Path.relative (this.path, relPath instanceof io ? relPath.path : relPath);
};
io.prototype.unlink = function (cb) {
fs.unlink(relPath.path | relPath, cb);
}
io.prototype.isFile = function () {
return this.stats ? this.stats.isFile () : null;
};
io.prototype.isDirectory = function () {
return this.stats ? this.stats.isDirectory () : null;
};
io.prototype.fileIO = io.prototype.file_io = function () {
var path = Path.join.apply(Path, arguments);
return new io(Path.resolve(this.path, path));
};
io.prototype.chmod = function (mode, cb) {
var p = this.path;
FS.chmod (p, mode, function (err) {
cb (err);
});
};
io.prototype.mkdir = function (mode, callback) {
if ("function" === typeof mode && callback === undefined) {
callback = mode;
mode = 0777; // node defaults
}
return FS.mkdir (this.path, mode, callback);
};
io.prototype.mkpath = function (path, mode, callback) {
if ("function" === typeof mode && callback === undefined) {
callback = mode;
mode = 0777; // node defaults
}
if (!path) {
if (callback) callback ();
return;
}
var self = this;
var pathChunks = path.split (Path.sep);
var currentPathChunk = pathChunks.shift ();
FS.mkdir (Path.join (this.path, currentPathChunk), mode, function (err) {
if (err && err.code !== 'EEXIST') {
if (callback) callback (err);
return;
}
if (pathChunks.length === 0) {
if (callback) callback ();
return;
}
var children = self.fileIO (currentPathChunk);
children.mkpath (Path.join.apply (Path, pathChunks), mode, callback);
});
};
io.prototype.writeStream = function (options) {
return FS.createWriteStream (this.path, options);
};
io.prototype.readStream = function (options, cb) {
if (arguments.length == 1)
cb = arguments[0];
var self = this;
this.stat (function (err, stats) {
var readStream = null;
if (!err && stats.isFile()) {
readStream = FS.createReadStream (self.path, options);
readStream.pause();
}
cb (readStream, stats);
});
};
io.prototype.scanTree = function (cb) {
var self = this;
FS.readdir (this.path, function (err, files) {
// console.log (err, files);
for (var i = 0; i < files.length; i++) {
var f = files[i] = new io (Path.join (self.path, files[i]));
f.stat (self.scanSubTree, cb);
}
});
};
io.prototype.findUp = function (fileNames, cb) {
var self = this;
if (!cb || cb.constructor != Function)
return;
if (!Array.isArray (fileNames)) {
fileNames = [fileNames]
}
FS.readdir (this.path, function (err, dirListing) {
var foundFileName;
if (fileNames.some (function (fileName) {
if (dirListing.indexOf (fileName) >= 0) {
foundFileName = fileName;
return true;
}
})) {
FS.stat (Path.join (this.path, foundFileName), function (err, stats) {
cb (null, self, stats, foundFileName);
});
} else {
// no go if we have volume root
if (this.parent().path === this.path) {
return cb (true, this);
}
// no files found with requested names, go up
this.parent().findUp(fileNames, cb);
}
}.bind (this));
};
io.prototype.scanSubTree = function (err, stats, cb) {
var scanFurther = 0;
if (cb)
scanFurther = cb (this);
// console.log (scanFurther, this.isDirectory ());
if (scanFurther && this.isDirectory ())
this.scanTree (cb);
};
io.prototype.stat = function (cb) {
var self = this;
var a = arguments;
FS.stat (this.path, function (err, stats) {
self.stats = stats;
// console.log (self.path);
if (cb)
cb (err, stats, a[1]);
});
};
io.prototype.parent = function () {
return new io (Path.dirname (this.path));
};
io.prototype.readFile = function (cb) {
var self = this;
FS.readFile(this.path, function (err, data) {
cb (err, data);
});
};
io.prototype.writeFile = function (data, cb) {
var self = this;
FS.writeFile (this.path + '.tmp', data, (function (err) {
if (err) {
// console.log ('CANNOT WRITE FILE', err);
if (cb)
cb (err);
return;
}
FS.rename(this.path + '.tmp', this.path, function (err) {
// if (err) console.log ('CANNOT RENAME FILE', err);
if (cb)
cb (err);
});
}).bind (this));
};
|
import storage from '../utils/storageModule'
export default {
saveClass (c) {
storage.session.set('class', c)
},
getClass () {
return storage.session.get('class')
},
saveClassId (id) {
storage.session.set('classId', id)
},
getClassId () {
return storage.session.get('classId')
},
saveEditingClass (c) {
storage.session.set('editingClass', c)
},
getEditingClass () {
return storage.session.get('editingClass')
}
}
|
import { configLoaderCreator } from '@storybook/core/server';
import { logger } from '@storybook/node-logger';
import defaultConfig from './config/babel';
import loadTsConfig from './ts_config';
import {
getAngularCliWebpackConfigOptions,
applyAngularCliWebpackConfig,
} from './angular-cli_config';
const cliWebpackConfigOptions = getAngularCliWebpackConfigOptions(process.cwd());
if (cliWebpackConfigOptions) {
logger.info('=> Loading angular-cli config.');
}
const configLoader = configLoaderCreator({
defaultConfigName: 'angular-cli',
defaultBabelConfig: defaultConfig,
wrapInitialConfig: (config, configDir) => {
const tsRule = config.module.rules[1];
tsRule.loaders[0].options = loadTsConfig(configDir);
return config;
},
wrapDefaultConfig: config => applyAngularCliWebpackConfig(config, cliWebpackConfigOptions),
wrapBasicConfig: config => applyAngularCliWebpackConfig(config, cliWebpackConfigOptions),
});
export default configLoader;
|
module.exports = function(config){
config.set({
basePath : './',
files : [
'app/bower_components/angular/angular.js',
'app/bower_components/angular-route/angular-route.js',
'app/bower_components/angular-mocks/angular-mocks.js',
'app/bower_components/lodash/lodash.js',
'app/models/*.js',
'app/components/**/*.js',
'app/seatingPlan/**/*.js',
'unit-tests/**/*.js'
],
autoWatch : true,
frameworks: ['jasmine'],
browsers : ['Chrome'],
plugins : [
'karma-chrome-launcher',
'karma-firefox-launcher',
'karma-jasmine',
'karma-junit-reporter'
],
junitReporter : {
outputFile: 'test_out/unit.xml',
suite: 'unit'
}
});
};
|
var previous
module.exports = error
module.exports.clear = clear
function error(message) {
var element = document.createElement('div')
clear()
element.classList.add('error-message')
element.innerHTML = message
document.body.appendChild(element)
previous = hide
function hide() {
if (element.parentNode) {
element.parentNode.removeChild(element)
}
}
}
function clear() {
if (!previous) return
previous()
previous = null
}
|
'use strict';
/**
* Module dependencies.
*/
var fs = require('fs'),
http = require('http'),
socketio = require('socket.io'),
https = require('https'),
express = require('express'),
morgan = require('morgan'),
bodyParser = require('body-parser'),
session = require('express-session'),
compress = require('compression'),
methodOverride = require('method-override'),
cookieParser = require('cookie-parser'),
helmet = require('helmet'),
passport = require('passport'),
mongoStore = require('connect-mongo')({
session: session
}),
flash = require('connect-flash'),
config = require('./config'),
consolidate = require('consolidate'),
path = require('path');
module.exports = function(db) {
// Initialize express app
var app = express();
// Globbing model files
config.getGlobbedFiles('./app/models/**/*.js').forEach(function(modelPath) {
require(path.resolve(modelPath));
});
// Setting application local variables
app.locals.title = config.app.title;
app.locals.description = config.app.description;
app.locals.keywords = config.app.keywords;
app.locals.facebookAppId = config.facebook.clientID;
app.locals.jsFiles = config.getJavaScriptAssets();
app.locals.cssFiles = config.getCSSAssets();
// Passing the request url to environment locals
app.use(function(req, res, next) {
res.locals.url = req.protocol + '://' + req.headers.host + req.url;
next();
});
// Should be placed before express.static
app.use(compress({
filter: function(req, res) {
return (/json|text|javascript|css/).test(res.getHeader('Content-Type'));
},
level: 9
}));
// Showing stack errors
app.set('showStackError', true);
// Set swig as the template engine
app.engine('server.view.html', consolidate[config.templateEngine]);
// Set views path and view engine
app.set('view engine', 'server.view.html');
app.set('views', './app/views');
// Environment dependent middleware
if (process.env.NODE_ENV === 'development') {
// Enable logger (morgan)
app.use(morgan('dev'));
// Disable views cache
app.set('view cache', false);
} else if (process.env.NODE_ENV === 'production') {
app.locals.cache = 'memory';
}
// Request body parsing middleware should be above methodOverride
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.use(methodOverride());
// CookieParser should be above session
app.use(cookieParser());
// Express MongoDB session storage
app.use(session({
saveUninitialized: true,
resave: true,
secret: config.sessionSecret,
store: new mongoStore({
db: db.connection.db,
collection: config.sessionCollection
})
}));
// use passport session
app.use(passport.initialize());
app.use(passport.session());
// connect flash for flash messages
app.use(flash());
// Use helmet to secure Express headers
app.use(helmet.xframe());
app.use(helmet.xssFilter());
app.use(helmet.nosniff());
app.use(helmet.ienoopen());
app.disable('x-powered-by');
// Setting the app router and static folder
app.use(express.static(path.resolve('./public')));
// Globbing routing files
config.getGlobbedFiles('./app/routes/**/*.js').forEach(function(routePath) {
require(path.resolve(routePath))(app);
});
// Assume 'not found' in the error msgs is a 404. this is somewhat silly, but valid, you can do whatever you like, set properties, use instanceof etc.
app.use(function(err, req, res, next) {
// If the error object doesn't exists
if (!err) return next();
// Log it
console.error(err.stack);
// Error page
res.status(500).render('500', {
error: err.stack
});
});
// Assume 404 since no middleware responded
app.use(function(req, res) {
res.status(404).render('404', {
url: req.originalUrl,
error: 'Not Found'
});
});
if (process.env.NODE_ENV === 'secure') {
// Log SSL usage
console.log('Securely using https protocol');
// Load SSL key and certificate
var privateKey = fs.readFileSync('./config/sslcerts/key.pem', 'utf8');
var certificate = fs.readFileSync('./config/sslcerts/cert.pem', 'utf8');
// Create HTTPS Server
var httpsServer = https.createServer({
key: privateKey,
cert: certificate
}, app);
// Return HTTPS server instance
return httpsServer;
}
// Return Express server instance
var server = http.createServer(app);
var io = socketio.listen(server);
app.set('socketio', io);
app.set('server', server);
var mongoose = require('mongoose'),
Verse = mongoose.model('Verse');
io.sockets.on('connection', function(socket){
socket.on('sound bites', function(data, cb){
//console.log(Verse);
/*console.log(data.verseId);
console.log(data.line_index);
console.log(data.sound_bites);*/
var arr = [];
var arr_from_client = data.sound_bites ;
for(var i in arr_from_client){
arr.push(arr_from_client[i]);
}
/*for(var i = 0; i < 20000; i++){
arr.push(500);
}*/
Verse.update({_id: data.verseId, 'poem.line_index' : data.line_index}, {$set: {'poem.$.line_sound_buffer' : arr}}, function(error, result){
if(error){
cb('Error while loading line');
}else{
cb('Success');
}
});
});
});
return app;
};
|
(function($) {
var digestQueued = false;
var digestRunning = false;
var queueDigest = function() {
if (!digestQueued) {
digestQueued = true;
if (!digestRunning) {
setTimeout(function() {
var maxIters = 10;
digestRunning = true;
while (digestQueued && (maxIters-- > 0)) {
digestQueued = false;
$(".--treena-watched-element").triggerHandler('treena:data-change');
}
if (digestQueued) {
console.log('maxIters exceeded!');
digestQueued = false;
}
digestRunning = false;
}, 0);
}
}
};
var addWatcher = function($e, ifF, thenF) {
var oldValue = undefined;
$e.on("treena:data-change", function() {
var v = ifF.__watcher__ ? ifF.__watcher__() : ifF();
var newValue = (typeof(v) === 'number') ? v : JSON.stringify(v);
if (oldValue !== newValue) {
oldValue = newValue;
thenF && thenF(ifF(), $e);
queueDigest();
}
});
$e.addClass("--treena-watched-element");
queueDigest();
return $e;
};
var isWatcher = $.isFunction;
var setCss = function($e, css) {
if (isWatcher(css)) {
addWatcher($e, css, function(c) {
$e.css(c);
} );
} else if (typeof(css) === 'object') {
$.each(css, function(k, val) {
if (isWatcher(val)) {
addWatcher($e, val, function(c) { $e.css(k, c); } );
} else {
$e.css(k, val);
}
});
} else {
$e.css(css);
}
};
var setClass = function($e, val) {
if (typeof(val) == 'string') {
val = val.split(' ');
} else if (!$.isArray(val)) {
val = [ val ];
}
$.each(val, function(i, clas) {
if (isWatcher(clas)) {
var oldClass = null;
addWatcher($e, clas, function(newClass) {
if (oldClass) {
$e.removeClass(oldClass);
}
if (newClass) {
$e.addClass(newClass);
}
oldClass = newClass;
});
} else {
$e.addClass(clas);
}
});
};
/* fix some stupid IE capitalization bugs */
var IEcaps = {
"rowspan" : "rowSpan",
"colspan" : "colSpan",
"frameborder" : "frameBorder"
};
var setAttr = function($e, attr, val, initial) {
attr = attr.toLowerCase();
if ((attr === 'class') || (attr === 'clas') || (attr === 'clazz')) {
if (val) setClass($e, val);
} else if (attr === 'style') {
if (val) setCss($e, val);
} else {
attr = IEcaps[attr] || attr;
if (isWatcher(val)) {
if (initial) {
addWatcher($e, val, function(v) { $e.attr(attr, v); } );
} else {
$e.attr(attr, val());
}
} else {
$e.attr(attr, val);
}
}
};
var setAttrs = function($e, attrs, initial) {
if (isWatcher(attrs)) {
if (initial) {
addWatcher($e, attrs, function(a) { setAttrs($e, a, false); } );
} else {
attrs = attrs();
}
} else if ($.isPlainObject(attrs)) {
$.each(attrs, function(k, v) {
setAttr($e, k, v, initial);
});
}
};
var clickables = {
'a' : true,
'form' : true,
'button' : true
};
var createNode = function(node_name, node_args) {
var callback = (clickables[node_name] && node_args.length && $.isFunction(node_args[0])) ?
node_args.shift() : null;
var attrs = (node_args.length && ($.isPlainObject(node_args[0]) || isWatcher(node_args[0]))) ?
node_args.shift() : {};
var e = ($.browser && $.browser.msie && (node_name === "input") && attrs.name) ? ('<input name="' + attrs.name + '"/>') : node_name;
var $e = $(document.createElement(e));
setAttrs($e, attrs, true);
var processChild = function($parent, arg) {
if ((arg === null) || (arg === undefined)) {
// skip it
} else if ($.isArray(arg)) {
$.each(arg, function(i, c) {
processChild($parent, c);
});
} else {
if ((typeof(arg) === 'string') || (typeof(arg) === 'number')) {
arg = document.createTextNode(arg);
} else if (isWatcher(arg)) {
addWatcher($parent, arg,
function(v) {
$(arg).empty();
processChild($(arg), v);
});
arg = document.createElement('span');
}
$parent.append(arg);
}
};
processChild($e, node_args);
if ((node_name === "a") && !attrs.href) {
$e.attr("href", "#");
callback = callback || function() {};
};
if (callback) {
var f = function(ev) {
ev.preventDefault();
callback.apply(this);
queueDigest();
};
if (node_name === "form") {
$e.submit(f);
} else {
$e.click(f);
}
}
return $e;
};
var nodeNames = [ 'table', 'tbody','thead', 'tr', 'th', 'td', 'a', 'strong', 'div', 'img',
'br', 'b', 'span', 'li', 'ul', 'ol', 'iframe', 'form', 'h1',
'input', 'h2', 'h3', 'h4','h5','h6', 'p', 'br', 'select', 'option', 'optgroup',
'script', 'label', 'textarea', 'em', 'button', 'b', 'hr', 'fieldset', 'nobr',
'object', 'embed', 'param', 'style', 'tt', 'header', 'footer', 'section', 'i', 'small'];
var treena = {};
$.each(nodeNames, function(i, node_name) {
treena[node_name.toUpperCase()] = function() {
return createNode(node_name, $.map(arguments, function(x) { return x; }));
};
});
treena.NBSP = '\u00a0';
treena.px = function(n) {
return n + "px";
};
treena.url = function(n) {
return 'url("' + n + '")';
};
treena.setTimeout = function(f, tm) {
return window.setTimeout(function(a) {
f(a);
queueDigest();
}, tm || 0);
};
treena.setInterval = function(f, tm) {
return window.setInterval(function(a) {
f(a);
queueDigest();
}, tm);
};
treena.digest = function(cb) {
if (cb) {
return function(a,b,c) {
// cb.apply(this, Array.prototype.slice.apply(arguments));
cb(a,b,c);
queueDigest();
};
} else {
queueDigest();
}
};
treena.watcher = function(source, transformOut, transformIn) {
if (transformOut) {
var st = function(n) {
if (arguments.length) {
source(transformIn ? transformIn(n) : n);
} else {
return transformOut(source());
}
};
st.__watcher__ = function() {
return source.__watcher__ ? source.__watcher__() : source();
};
return st;
} else {
return source;
}
};
treena.watch = addWatcher;
treena.watchField = function(source, field) {
return treena.watcher(source,
function(s) {
return s && s[field];
},
function(n) {
var d = $.extend({}, source())
d[field] = n;
return d;
});
};
treena.settable = function(name, onchange) {
var statev = undefined;
return function (n) {
if (arguments.length === 0) {
return statev;
} else if (statev !== n) {
statev = n;
onchange && onchange();
treena.digest();
}
};
};
treena.setter = function(settable, $e) {
$e.change(function() {
settable($e.val());
});
return $e;
};
$.t = treena;
})(window.jQuery || window.Zeptos); |
import Ember from 'ember';
import layout from '../templates/components/smd-form-control';
const {
computed,
Component
} = Ember;
export default Component.extend({
layout,
tagName: 'div',
classNames: [
'smd-form__control',
'mdl-textfield',
'mdl-js-textfield',
],
classNameBindings: [
'inputTypeModifier',
'floatingClass',
'invalidClass',
'validClass',
'inlineClass',
],
// Attributes
name: null,
disabled: false,
label: null,
model: null,
type: 'text',
icon: null,
tip: null,
isFloating: true,
isInline: false,
max: null,
min: null,
step: null,
cols: null,
rows: 3,
format: 'DD/MM/YYYY',
placeholder: null,
// Select Attributes
nullOption: null,
options: [],
modelOptions: null,
modelLabel: null,
// Computed
hasNullOption: computed.bool('nullOption'),
/**
* The options attribute maybe in one of 3 formats:
* - flat
* - objects
* - models
* This method will convert them all to a usable format for the hbs template
*/
computedOptions: computed('options', 'modelOptions', 'modelLabel', 'value', function() {
var options = this.get('options'),
modelOptions = this.get('modelOptions'),
modelLabel = this.get('modelLabel'),
value = this.get('value'),
name = this.get('name');
var array = [];
// Check options is an array
if (!options && typeof options.forEach !== 'function') {
Ember.Logger.error('Options attribute must be instance of array: ' + this.get('name'));
Ember.Logger.log(options);
}
if (modelOptions) {
modelOptions.forEach(
function(obj) {
var option = {};
if (modelLabel) {
option.label = obj.get(modelLabel);
} else {
Ember.Logger.warn('Define modelLabel for: ' + name);
option.label = obj;
}
option.value = obj;
if(value !== null && typeof(value) === 'object' && value.get) {
if (obj.id === value.get('id')) {
option.selected = true;
}
}
array.push(option);
}
);
} else {
options.forEach(
function(obj) {
var option = {};
if (obj !== null && typeof obj !== 'object') {
// option is a flat value
option.label = obj;
option.value = obj;
// check if selected
if (obj === value) {
option.selected = true;
}
} else {
option = obj;
// check if selected
if (obj.value === value) {
option.selected = true;
}
}
array.push(option);
}
);
}
return array;
}),
hasLabel: computed('label', 'type', function() {
let label = this.get('label'),
type = this.get('type');
var noLabel = ['switch', 'checkbox'];
if (noLabel.indexOf(type) !== -1) {
return false;
}
return !!label;
}),
notValidating: computed.not('validation.isValidating'),
didValidate: false,
hasContent: computed.notEmpty('value'),
isValid: computed.and('hasContent', 'validation.isValid', 'notValidating'),
isInvalid: computed.oneWay('validation.isInvalid'),
isTextarea: computed.equal('type', 'textarea'),
isSwitch: computed.equal('type', 'switch'),
isCheckbox: computed.equal('type', 'checkbox'),
isRadio: computed.equal('type', 'radio'),
isIcon: computed.equal('type', 'icon'),
isSelect: computed.equal('type', 'select'),
isDate: computed.equal('type', 'date'),
showErrorClass: computed.and('notValidating', 'showErrorMessage', 'hasContent', 'validation'),
showErrorMessage: computed('validation.isDirty', 'isInvalid', 'didValidate', function() {
return (this.get('validation.isDirty') || this.get('didValidate')) && this.get('isInvalid');
}),
showWarningMessage: computed('validation.isDirty', 'validation.warnings.[]', 'isValid', 'didValidate', function() {
return (this.get('validation.isDirty') || this.get('didValidate')) && this.get('isValid') && !Ember.isEmpty(this.get('validation.warnings'));
}),
showTip: computed('tip', function() {
return (this.get('tip'));
}),
// Classes
inputTypeModifier: computed('type', function() {
return 'smd-form__control--' + this.get('type');
}),
floatingClass: computed('isFloating', function() {
if (this.get('isFloating')) {
return 'mdl-textfield--floating-label';
}
}),
invalidClass: computed('isInvalid', function() {
if ((this.get('validation.isDirty') || this.get('didValidate')) && this.get('isInvalid')) {
return 'is-invalid';
}
}),
validClass: computed('isValid', function() {
if (this.get('isValid')) {
return 'is-valid';
}
}),
inlineClass: computed('isInline', 'type', function() {
if (this.get('type') === 'radio') {
if (this.get('isInline')) {
return 'smd-form__control--inline-radio';
}
}
}),
inputClasses: computed('type', function() {
var classNames = [];
let type = this.get('type');
if (type === 'range') {
classNames.push('mdl-slider');
classNames.push('mdl-js-slider');
} else {
classNames.push('mdl-textfield__input');
}
classNames.push('smd-form__input');
classNames.push('smd-form__input--' + type);
return classNames.join(' ');
}),
labelClasses: computed('type', function() {
var classNames = [];
classNames.push('mdl-textfield__label');
classNames.push('smd-form__label');
let type = this.get('type');
let types = ['select', 'radio', 'icon', 'date', 'month', 'week', 'time', 'datetime', 'datetime-local', 'range'];
if (types.indexOf(type) !== -1) {
classNames.push('smd-form__label--fixed');
}
return classNames.join(' ');
}),
// Methods
init() {
this._super(...arguments);
var propName = this.get('name');
if (this.get("model")) {
Ember.defineProperty(this, 'validation', computed.oneWay(`model.validations.attrs.${propName}`));
Ember.defineProperty(this, 'value', computed.alias(`model.${propName}`));
}
},
didInsertElement() {
this._super(...arguments);
componentHandler.upgradeElement(this.element);
},
actions: {
selectedOption(option) {
this.set('value', option);
},
checkOption(option) {
this.set('value', option.value);
},
selectedDate(date) {
this.set('value', date);
},
},
});
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.compileSituation = exports.current = exports.get = undefined;
var _requests = require('../../requests');
function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }
const get = exports.get = (() => {
var _ref = _asyncToGenerator(function* () {
var raw = yield (0, _requests.meteolux)();
var lines = raw.trim().split('\r\n');
var result = {};
for (var i = 0; i < lines.length; i++) {
var lineParts = lines[i].split(';');
result[lineParts[0]] = lineParts[1];
}
return result;
});
return function get() {
return _ref.apply(this, arguments);
};
})();
const current = exports.current = (() => {
var _ref2 = _asyncToGenerator(function* () {
var situation = yield get();
return compileSituation(situation);
});
return function current() {
return _ref2.apply(this, arguments);
};
})();
const compileSituation = exports.compileSituation = situation => {
var windDirection = '';
switch (situation.wind_direction_text.toUpperCase()) {
case 'NORD':
windDirection = 360;
break;
case 'NE':
windDirection = 45;
break;
case 'EST':
windDirection = 90;
break;
case 'SE':
windDirection = 135;
break;
case 'SUD':
windDirection = 180;
break;
case 'SO':
windDirection = 225;
break;
case 'OUEST':
windDirection = 270;
break;
case 'NO':
windDirection = 315;
break;
default:
windDirection = 360;
break;
}
var visibility = parseInt(situation.visibility);
if (situation.visibility.indexOf('km') !== -1) {
visibility = visibility * 1000;
}
return {
coord: {
lat: 49.627688,
lon: 6.223234
},
weather: [{
id: null,
main: null,
description: situation.weather,
icon: null
}],
base: null,
main: {
temp: parseInt(situation.temp),
pressure: parseInt(situation.pressure),
humidity: parseInt(situation.humidity),
temp_min: null,
temp_max: null
},
visibility: visibility,
wind: {
speed: parseInt(situation.wind_force),
deg: windDirection
},
clouds: {
all: null
},
dt: Math.round(new Date().getTime() / 1000),
sys: {
type: null,
id: null,
message: null,
country: null,
sunrise: null,
sunset: null
},
id: null,
name: 'Findel',
cod: 200
};
}; |
/** PROMISIFY CALLBACK-STYLE FUNCTIONS TO ES6 PROMISES
*
* EXAMPLE:
* const fn = promisify( (callback) => callback(null, "Hello world!") );
* fn((err, str) => console.log(str));
* fn().then((str) => console.log(str));
* //Both functions, will log 'Hello world!'
*
* Note: The function you pass, may have any arguments you want, but the latest
* have to be the callback, which you will call with: next(err, value)
*
* @param method: Function/Array/Map = The function(s) to promisify
* @param options: Map =
* "context" (default is function): The context which to apply the called function
* "replace" (default is falsy): When passed an array/map, if to replace the original object
*
* @return: A promise if passed a function, otherwise the object with the promises
*
* @license: MIT
* @version: 1.0.3
* @author: Manuel Di Iorio
**/
var createCallback = function (method, context) {
return function () {
var args = Array.prototype.slice.call(arguments);
var lastIndex = args.length - 1;
var lastArg = args && args.length > 0 ? args[lastIndex] : null;
var cb = typeof lastArg === 'function' ? lastArg : null;
if (cb) {
return method.apply(context, args);
}
return new Promise(function (resolve, reject) {
args.push(function (err, val) {
if (err) return reject(err);
resolve(val);
});
method.apply(context, args);
});
};
};
if (typeof module === "undefined") module = {}; // Browserify this module
module.exports = function (methods, options) {
options = options || {};
var type = Object.prototype.toString.call(methods);
if (type === "[object Object]" || type === "[object Array]") {
var obj = options.replace ? methods : {};
for (var key in methods) {
if (methods.hasOwnProperty(key)) obj[key] = createCallback(methods[key]);
}return obj;
}
return createCallback(methods, options.context || methods);
};
// Browserify this module
if (typeof exports === "undefined") {
this["promisify"] = module.exports;
}
|
var Notification = require('./Notification');
var AndroidNotification = Notification.extend({
// the array for payload, please see API doc for more information
_androidPayload: {
'display_type': 'notification',
'body': {
'ticker': '',
'title': '',
'text': '',
// 'icon': '',
// 'largeIcon': '',
'play_vibrate': 'true',
'play_lights': 'true',
'play_sound': 'true',
'after_open': '',
// 'url': '',
// 'activity': '',
// 'custom': ''
},
// 'extra': {
// 'foo': 'bar'
// }
},
initialize: function() {
AndroidNotification.superclass.initialize.call(this);
this._data['payload'] = this._androidPayload;
}
});
module.exports = AndroidNotification; |
import test from 'ava';
import modifyValues from './index.js';
test('main', t => {
t.is(modifyValues({foo: 'UNICORN'}, value => value.toLowerCase()).foo, 'unicorn');
});
|
'use strict';
angular.module('core').controller('HomeController', ['$scope', 'Authentication','Voitures',
function ($scope, Authentication,Voitures) {
// This provides Authentication context.
$scope.authentication = Authentication;
// Find a list of Voitures
$scope.trouver = function () {
$scope.voitures = Voitures.query();
};
}
]);
|
import test from 'ava';
import assert from '../helpers/assertions.js';
import File from '../../src/File.js';
import { mix, Mix } from '../helpers/mix.js';
import webpack from '../helpers/webpack.js';
test('mix.ts()', t => {
let response = mix.ts('src/app.ts', 'dist');
t.deepEqual(mix, response);
t.deepEqual(
[
{
entry: [new File('src/app.ts')],
output: new File('dist')
}
],
Mix.components.get('ts').toCompile
);
// There's also a mix.typeScript() alias.
t.deepEqual(mix, mix.typeScript('src/app.ts', 'dist'));
});
test('it applies the correct extensions and aliases to the webpack config', async t => {
mix.ts(`test/fixtures/app/src/js/app.js`, 'dist');
let { config } = await webpack.compile();
t.true(config.resolve.extensions.includes('.ts'));
t.true(config.resolve.extensions.includes('.tsx'));
});
test('it applies Babel transformation', async t => {
mix.ts('js/app.js', 'dist');
t.true(
(await webpack.buildConfig()).module.rules
.find(rule => {
return rule.test.test('foo.tsx');
})
.use.some(loader => loader.loader === 'babel-loader')
);
});
test('it is able to apply options to ts-loader', async t => {
mix.ts('js/app.js', 'dist', { transpileOnly: true });
t.truthy(
(await webpack.buildConfig()).module.rules.find(
rule => rule.loader === 'ts-loader'
).options.transpileOnly
);
});
test.only('it compiles TypeScript with dynamic import', async t => {
mix.ts(`test/fixtures/app/src/dynamic-ts/dynamic.ts`, 'js', {
transpileOnly: true,
// These would normally be in tsconfig.json but are here because
// we'll eventually have one and the options won't match these
compilerOptions: {
target: 'esnext',
module: 'esnext',
moduleResolution: 'node',
noEmit: false
}
});
await webpack.compile();
t.true(File.exists(`test/fixtures/app/dist/js/dynamic.js`));
assert.manifestEquals(
{
'/js/absolute.js': '/js/absolute.js',
'/js/dynamic.js': '/js/dynamic.js',
'/js/named.js': '/js/named.js'
},
t
);
});
|
var SystemNotifier = require("../../webgl/system/system-notifier.js");
var RenderNode = require("./rendernode.js");
var DrawableClosure= require("./drawableclosure.js");
var C = require("./constants.js");
var Scene= require("./scene.js");
var ComputeRequest = require("../../../xflow/interface/request.js").ComputeRequest;
/**
* @interface
*/
var IRenderObject = function () {
};
IRenderObject.prototype.getModelViewMatrix = function () {
};
IRenderObject.prototype.getModelViewProjectionMatrix = function () {
};
IRenderObject.prototype.getModelMatrixN = function () {
};
IRenderObject.prototype.getModelViewMatrixN = function () {
};
IRenderObject.prototype.getObjectSpaceBoundingBox = function () {
};
IRenderObject.prototype.getWorldSpaceBoundingBox = function () {
};
IRenderObject.prototype.updateWorldSpaceMatrices = function () {
};
IRenderObject.prototype.isVisible = function () {
};
IRenderObject.prototype.setTransformDirty = function () {
};
IRenderObject.prototype.setMaterial = function () {
};
IRenderObject.prototype.hasTransparency = function () {
};
// Entry:
/** @const */
var WORLD_MATRIX_OFFSET = 0;
/** @const */
var LOCAL_MATRIX_OFFSET = WORLD_MATRIX_OFFSET + 16;
/** @const */
var OBJECT_BB_OFFSET = LOCAL_MATRIX_OFFSET + 16;
/** @const */
var WORLD_BB_OFFSET = OBJECT_BB_OFFSET + 6;
/** @const */
var MODELVIEW_MATRIX_OFFSET = WORLD_BB_OFFSET + 6;
/** @const */
var MODELVIEWPROJECTION_MATRIX_OFFSET = MODELVIEW_MATRIX_OFFSET + 16;
/** @const */
var MODEL_MATRIX_N_OFFSET = MODELVIEWPROJECTION_MATRIX_OFFSET + 16;
/** @const */
var MODELVIEW_MATRIX_N_OFFSET = MODEL_MATRIX_N_OFFSET + 16;
/** @const */
var ENTRY_SIZE = MODELVIEW_MATRIX_N_OFFSET + 16;
//noinspection JSClosureCompilerSyntax,JSClosureCompilerSyntax
/**
* Represents a renderable object in the scene.
* The RenderObject has these responsibilities:
* 1. Keep track of the transformation hierarchy and bounding boxes
* 2. Connect the DrawableClosure with the ShaderClosure
*
* The {@link DrawableClosure} is a DrawableObject plus it's data
* The {@link ShaderClosure} is a ProgramObject plus it's data
* The concrete ShaderClosure can vary per DrawableObject and change
* due to scene or object changes. Thus we have to keep track of the
* related {@link IShaderComposer}.
*
* @constructor
* @implements {IRenderObject}
* @param {Scene} scene
* @param {Object} pageEntry
* @param {Object} opt
*/
var RenderObject = function (scene, pageEntry, opt) {
RenderNode.call(this, C.NODE_TYPE.OBJECT, scene, pageEntry, opt);
opt = opt || {};
/**
* Keep reference to DOM Element need e.g. for picking
* @type {Element}
*/
this.node = opt.node;
/**
* Object related data
* @type {{data: DataNode|null, type: string}}
*/
this.object = opt.object || {data: null, type: "triangles"};
/**
* Can we rely on current WorldMatrix?
* @type {boolean}
*/
this.transformDirty = true;
/**
* Can we rely on current Bounding Boxes?
* @type {boolean}
*/
this.boundingBoxDirty = true;
this.transformDataRequest = this.createTransformRequest();
/**
* The drawable closure transforms object data and type into
* a drawable entity
* @type {DrawableClosure}
*/
this.drawable = this.createDrawable();
this._material = opt.material || null;
this._actualMaterial = null;
this.initMaterial();
/** {Object?} **/
this.override = null;
};
RenderObject.ENTRY_SIZE = ENTRY_SIZE;
RenderObject.IDENTITY_MATRIX = XML3D.math.mat4.create();
XML3D.createClass(RenderObject, RenderNode, {
createTransformRequest: function () {
if (!this.object.data)
return null;
var request = new ComputeRequest(this.object.data, ["meshTransform"], this.onTransformDataChange.bind(this));
return request;
},
createDrawable: function () {
var result = this.scene.createDrawable(this);
if (result) {
var that = this;
result.on(C.EVENT_TYPE.DRAWABLE_STATE_CHANGED, function (newState, oldState) {
if (newState === DrawableClosure.READY_STATE.COMPLETE) {
that.scene.moveFromQueueToReady(that);
} else if (newState === DrawableClosure.READY_STATE.INCOMPLETE && oldState === DrawableClosure.READY_STATE.COMPLETE) {
that.scene.moveFromReadyToQueue(that);
}
});
result.updateTypeRequest();
result.calculateBoundingBox();
result.on(C.EVENT_TYPE.SCENE_SHAPE_CHANGED, function (evt) {
that.scene.emit(C.EVENT_TYPE.SCENE_SHAPE_CHANGED)
})
}
return result;
},
setType: function (type) {
this.object.type = type;
// TODO: this.typeChangedEvent
},
getType: function () {
return this.object.type;
},
getDataNode: function () {
return this.object ? this.object.data : null;
},
getLocalMatrix: function (dest) {
var o = this.offset + LOCAL_MATRIX_OFFSET;
for (var i = 0; i < 16; i++, o++) {
dest[i] = this.page[o];
}
},
setLocalMatrix: function (source) {
var o = this.offset + LOCAL_MATRIX_OFFSET;
for (var i = 0; i < 16; i++, o++) {
this.page[o] = source[i];
}
this.setTransformDirty();
this.setBoundingBoxDirty();
},
dispose: function () {
this.transformDataRequest && this.transformDataRequest.clear();
this.scene.remove(this);
}, onTransformDataChange: function () {
this.setTransformDirty();
},
getModelViewMatrix: function (target) {
var o = this.offset + MODELVIEW_MATRIX_OFFSET;
for (var i = 0; i < 16; i++, o++) {
target[i] = this.page[o];
}
},
getModelMatrixN: function (target) {
var o = this.offset + MODEL_MATRIX_N_OFFSET;
target[0] = this.page[o];
target[1] = this.page[o + 1];
target[2] = this.page[o + 2];
target[3] = this.page[o + 4];
target[4] = this.page[o + 5];
target[5] = this.page[o + 6];
target[6] = this.page[o + 8];
target[7] = this.page[o + 9];
target[8] = this.page[o + 10];
},
getModelViewMatrixN: function (target) {
var o = this.offset + MODELVIEW_MATRIX_N_OFFSET;
target[0] = this.page[o];
target[1] = this.page[o + 1];
target[2] = this.page[o + 2];
target[3] = this.page[o + 4];
target[4] = this.page[o + 5];
target[5] = this.page[o + 6];
target[6] = this.page[o + 8];
target[7] = this.page[o + 9];
target[8] = this.page[o + 10];
},
getModelViewProjectionMatrix: function (dest) {
var o = this.offset + MODELVIEWPROJECTION_MATRIX_OFFSET;
for (var i = 0; i < 16; i++, o++) {
dest[i] = this.page[o];
}
},
updateWorldSpaceMatrices: function (view, projection) {
if (this.transformDirty) {
this.updateWorldMatrix();
}
this.updateModelViewMatrix(view);
this.updateModelMatrixN();
this.updateModelViewMatrixN();
this.updateModelViewProjectionMatrix(projection);
},
updateWorldMatrix: (function () {
var tmp_mat = XML3D.math.mat4.create();
return function () {
this.parent.getWorldMatrix(tmp_mat);
var page = this.page;
var offset = this.offset;
XML3D.math.mat4.multiplyOffset(tmp_mat, 0, page, offset + LOCAL_MATRIX_OFFSET, tmp_mat, 0);
if (this.transformDataRequest) {
var result = this.transformDataRequest.getResult();
var transformData = result.getOutputData("meshTransform");
if (transformData && transformData.getValue()) {
XML3D.math.mat4.multiply(tmp_mat, tmp_mat, transformData.getValue());
}
}
this.setWorldMatrix(tmp_mat);
this.boundingBoxDirty = true;
this.transformDirty = false;
}
})(),
/** Relies on an up-to-date transform matrix **/
updateModelViewMatrix: function (view) {
if (this.transformDirty) {
this.updateWorldMatrix();
}
var page = this.page;
var offset = this.offset;
XML3D.math.mat4.multiplyOffset(page, offset + MODELVIEW_MATRIX_OFFSET, page, offset + WORLD_MATRIX_OFFSET, view, 0);
},
updateModelMatrixN: (function () {
var c_tmpMatrix = XML3D.math.mat4.create();
return function () {
this.getWorldMatrix(c_tmpMatrix);
var normalMatrix = XML3D.math.mat4.invert(c_tmpMatrix, c_tmpMatrix);
normalMatrix = normalMatrix ? XML3D.math.mat4.transpose(normalMatrix, normalMatrix) : RenderObject.IDENTITY_MATRIX;
var o = this.offset + MODEL_MATRIX_N_OFFSET;
for (var i = 0; i < 16; i++, o++) {
this.page[o] = normalMatrix[i];
}
}
})(),
/** Relies on an up-to-date view matrix **/
updateModelViewMatrixN: (function () {
var c_tmpMatrix = XML3D.math.mat4.create();
return function () {
this.getModelViewMatrix(c_tmpMatrix);
var normalMatrix = XML3D.math.mat4.invert(c_tmpMatrix, c_tmpMatrix);
normalMatrix = normalMatrix ? XML3D.math.mat4.transpose(normalMatrix, normalMatrix) : RenderObject.IDENTITY_MATRIX;
var o = this.offset + MODELVIEW_MATRIX_N_OFFSET;
for (var i = 0; i < 16; i++, o++) {
this.page[o] = normalMatrix[i];
}
}
})(),
/** Relies on an up-to-date view matrix **/
updateModelViewProjectionMatrix: function (projection) {
var page = this.page;
var offset = this.offset;
XML3D.math.mat4.multiplyOffset(page, offset + MODELVIEWPROJECTION_MATRIX_OFFSET, page, offset + MODELVIEW_MATRIX_OFFSET, projection, 0);
},
setTransformDirty: function () {
this.transformDirty = true;
this.setBoundingBoxDirty();
this.scene.emit(C.EVENT_TYPE.SCENE_SHAPE_CHANGED);
this.scene.requestRedraw("Transformation changed");
},
setObjectSpaceBoundingBox: function (box) {
var o = this.offset + OBJECT_BB_OFFSET;
this.page[o] = box[0];
this.page[o + 1] = box[1];
this.page[o + 2] = box[2];
this.page[o + 3] = box[3];
this.page[o + 4] = box[4];
this.page[o + 5] = box[5];
this.setBoundingBoxDirty();
},
getObjectSpaceBoundingBox: function (box) {
var o = this.offset + OBJECT_BB_OFFSET;
box[0] = this.page[o];
box[1] = this.page[o + 1];
box[2] = this.page[o + 2];
box[3] = this.page[o + 3];
box[4] = this.page[o + 4];
box[5] = this.page[o + 5];
},
setBoundingBoxDirty: function () {
this.boundingBoxDirty = true;
this.parent.setBoundingBoxDirty();
},
setWorldSpaceBoundingBox: function (bbox) {
var o = this.offset + WORLD_BB_OFFSET;
this.page[o] = bbox[0];
this.page[o + 1] = bbox[1];
this.page[o + 2] = bbox[2];
this.page[o + 3] = bbox[3];
this.page[o + 4] = bbox[4];
this.page[o + 5] = bbox[5];
},
getWorldSpaceBoundingBox: function (bbox) {
if (this.boundingBoxDirty) {
this.updateWorldSpaceBoundingBox();
}
var o = this.offset + WORLD_BB_OFFSET;
bbox[0] = this.page[o];
bbox[1] = this.page[o + 1];
bbox[2] = this.page[o + 2];
bbox[3] = this.page[o + 3];
bbox[4] = this.page[o + 4];
bbox[5] = this.page[o + 5];
},
updateWorldSpaceBoundingBox: (function () {
var c_box = new XML3D.math.bbox.create();
var c_trans = new XML3D.math.mat4.create();
return function () {
this.getObjectSpaceBoundingBox(c_box);
this.getWorldMatrix(c_trans);
XML3D.math.bbox.transform(c_box, c_trans, c_box);
this.setWorldSpaceBoundingBox(c_box);
this.boundingBoxDirty = false;
}
})(),
setLocalVisible: function (newVal) {
this.localVisible = newVal;
this.setVisible(this.parent && this.parent.isVisible() && newVal);
this.setBoundingBoxDirty();
},
getProgram: function () {
return this.drawable.getProgram();
},
hasTransparency: function () {
var program = this.getProgram();
return program ? program.hasTransparency() : false;
},
updateForRendering: function () {
SystemNotifier.setNode(this.node);
try {
this.drawable && this.drawable.update(this.scene);
} catch (e) {
XML3D.debug.logError("Mesh Error: " + e.message, this.node);
}
SystemNotifier.setNode(null);
},
findRayIntersections: (function () {
var bbox = XML3D.math.bbox.create();
var opt = {dist: 0};
return function (ray, intersections) {
this.getWorldSpaceBoundingBox(bbox);
if (XML3D.math.bbox.intersects(bbox, ray, opt)) {
intersections.push(this);
}
}
})(),
/**
* @param {MaterialConfiguration|null} material
*/
setMaterial: function (material) {
if(this._material === material) {
return;
}
this._material = material;
if (material) {
this._actualMaterial = material;
} else {
this._actualMaterial = this.parent.getMaterial();
}
this.materialChanged();
},
parentMaterialChanged: function () {
if (this._material) {
// Local material overrides the change from above
return;
}
this.initMaterial();
},
initMaterial: function () {
if (this._material) {
this._actualMaterial = this._material;
} else {
this._actualMaterial = this.parent.getMaterial();
}
this.materialChanged();
},
materialChanged: function() {
XML3D.debug.logDebug("material changed", this._actualMaterial);
if (this.drawable) {
var composer = this.scene.shaderFactory.createComposerFromMaterialConfiguration(this._actualMaterial);
this.drawable.setShaderComposer(composer);
}
}
});
// Export
module.exports = RenderObject;
|
(function () {
'use strict';
angular.module('simple-chat.app')
.factory('Messages', Messages);
Messages.$inject = ['$resource'];
function Messages($resource) {
return $resource('/api/messages/:id');
}
})();
|
'use strict';
module.exports = function(environment) {
let ENV = {
modulePrefix: 'dummy',
environment,
rootURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
},
EXTEND_PROTOTYPES: {
// Prevent Ember Data from overriding Date.parse.
Date: false
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
},
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
ENV.APP.autoboot = false;
}
if (environment === 'production') {
// put production settings here
}
return ENV;
};
|
var api_key = 'de882c8150f854766bbeb4388c25881d';
var lat = '51.2';
var lon = '-0.1';
var map = L.map('map').setView([lat,lon],17);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
function loadPhotos(){
$.getJSON(
[
'https://api.flickr.com/services/rest/?',
'method=flickr.photos.search',
'&format=json',
'&api_key=', api_key,
'&lat=', lat,
'&lon=', lon,
'&extras=geo,url_t,url_m,url_sq',
'&radius=0.3',
'&per_page=20',
'&jsoncallback=?'
].join(""), function(data){
if(data && data.stat == "ok" && data.photos && data.photos.photo.length){
displayPhotos(data.photos.photo);
}
});
}
function displayPhotos(photos){
var photo;
console.log(photos);
for(var i = 0; i < photos.length; i++){
photo = photos[i];
html = [
'<a href="',
'https://www.flickr.com/photos/', photo.owner, '/', photo.id,
'" target = "_blank">',
'<img src="'+photo.url_sq+'" alt="'+photo.title+'" width="',photo.width_sq,'" height="',photo.height_sq,'"/>',
'</a>'
].join("");
L.marker([photo.latitude, photo.longitude]).addTo(map)
.bindPopup(html);
}
}
loadPhotos();
map.on('moveend',function(){
var center = map.getCenter();
lat = center.lat;
lon = center.lng;
loadPhotos();
})
|
function render_module(name, args) {
$('#' + name).load('modules/' + name + '.module.php?' + args);
}
function activate_module(name, seconds, args) {
render_module(name, args);
if (seconds > 0) {
setInterval("render_module('"+name+"', '"+args+"')", (seconds * 1000));
}
}
$(document).ready(function() {
$('.middle').each(function(id, val) {
var outer_height = $(val).height();
var inner_height = $(val).children().first().height();
var buffer = (outer_height - inner_height) / 2;
var SEL = '#' + $(val).attr('id') + '>div';
$(SEL).css('marginTop', buffer);
$(SEL).css('marginBottom', buffer);
});
}); |
angular.module('ui.bootstrap.modal', ['ui.bootstrap.stackedMap'])
/**
* A helper, internal data structure that stores all references attached to key
*/
.factory('$$multiMap', function() {
return {
createNew: function() {
var map = {};
return {
entries: function() {
return Object.keys(map).map(function(key) {
return {
key: key,
value: map[key]
};
});
},
get: function(key) {
return map[key];
},
hasKey: function(key) {
return !!map[key];
},
keys: function() {
return Object.keys(map);
},
put: function(key, value) {
if (!map[key]) {
map[key] = [];
}
map[key].push(value);
},
remove: function(key, value) {
var values = map[key];
if (!values) {
return;
}
var idx = values.indexOf(value);
if (idx !== -1) {
values.splice(idx, 1);
}
if (!values.length) {
delete map[key];
}
}
};
}
};
})
/**
* A helper directive for the $modal service. It creates a backdrop element.
*/
.directive('uibModalBackdrop', ['$animateCss', '$injector', '$uibModalStack',
function($animateCss, $injector, $modalStack) {
return {
replace: true,
templateUrl: 'uib/template/modal/backdrop.html',
compile: function(tElement, tAttrs) {
tElement.addClass(tAttrs.backdropClass);
return linkFn;
}
};
function linkFn(scope, element, attrs) {
if (attrs.modalInClass) {
$animateCss(element, {
addClass: attrs.modalInClass
}).start();
scope.$on($modalStack.NOW_CLOSING_EVENT, function(e, setIsAsync) {
var done = setIsAsync();
if (scope.modalOptions.animation) {
$animateCss(element, {
removeClass: attrs.modalInClass
}).start().then(done);
} else {
done();
}
});
}
}
}])
.directive('uibModalWindow', ['$uibModalStack', '$q', '$animate', '$animateCss', '$document',
function($modalStack, $q, $animate, $animateCss, $document) {
return {
scope: {
index: '@'
},
replace: true,
transclude: true,
templateUrl: function(tElement, tAttrs) {
return tAttrs.templateUrl || 'uib/template/modal/window.html';
},
link: function(scope, element, attrs) {
element.addClass(attrs.windowClass || '');
element.addClass(attrs.windowTopClass || '');
scope.size = attrs.size;
scope.close = function(evt) {
var modal = $modalStack.getTop();
if (modal && modal.value.backdrop &&
modal.value.backdrop !== 'static' &&
evt.target === evt.currentTarget) {
evt.preventDefault();
evt.stopPropagation();
$modalStack.dismiss(modal.key, 'backdrop click');
}
};
// moved from template to fix issue #2280
element.on('click', scope.close);
// This property is only added to the scope for the purpose of detecting when this directive is rendered.
// We can detect that by using this property in the template associated with this directive and then use
// {@link Attribute#$observe} on it. For more details please see {@link TableColumnResize}.
scope.$isRendered = true;
// Deferred object that will be resolved when this modal is render.
var modalRenderDeferObj = $q.defer();
// Observe function will be called on next digest cycle after compilation, ensuring that the DOM is ready.
// In order to use this way of finding whether DOM is ready, we need to observe a scope property used in modal's template.
attrs.$observe('modalRender', function(value) {
if (value === 'true') {
modalRenderDeferObj.resolve();
}
});
modalRenderDeferObj.promise.then(function() {
var animationPromise = null;
if (attrs.modalInClass) {
animationPromise = $animateCss(element, {
addClass: attrs.modalInClass
}).start();
scope.$on($modalStack.NOW_CLOSING_EVENT, function(e, setIsAsync) {
var done = setIsAsync();
if ($animateCss) {
$animateCss(element, {
removeClass: attrs.modalInClass
}).start().then(done);
} else {
$animate.removeClass(element, attrs.modalInClass).then(done);
}
});
}
$q.when(animationPromise).then(function() {
/**
* If something within the freshly-opened modal already has focus (perhaps via a
* directive that causes focus). then no need to try and focus anything.
*/
if (!($document[0].activeElement && element[0].contains($document[0].activeElement))) {
var inputWithAutofocus = element[0].querySelector('[autofocus]');
/**
* Auto-focusing of a freshly-opened modal element causes any child elements
* with the autofocus attribute to lose focus. This is an issue on touch
* based devices which will show and then hide the onscreen keyboard.
* Attempts to refocus the autofocus element via JavaScript will not reopen
* the onscreen keyboard. Fixed by updated the focusing logic to only autofocus
* the modal element if the modal does not contain an autofocus element.
*/
if (inputWithAutofocus) {
inputWithAutofocus.focus();
} else {
element[0].focus();
}
}
});
// Notify {@link $modalStack} that modal is rendered.
var modal = $modalStack.getTop();
if (modal) {
$modalStack.modalRendered(modal.key);
}
});
}
};
}])
.directive('uibModalAnimationClass', function() {
return {
compile: function(tElement, tAttrs) {
if (tAttrs.modalAnimation) {
tElement.addClass(tAttrs.uibModalAnimationClass);
}
}
};
})
.directive('uibModalTransclude', function() {
return {
link: function(scope, element, attrs, controller, transclude) {
transclude(scope.$parent, function(clone) {
element.empty();
element.append(clone);
});
}
};
})
.factory('$uibModalStack', ['$animate', '$animateCss', '$document',
'$compile', '$rootScope', '$q', '$$multiMap', '$$stackedMap',
function($animate, $animateCss, $document, $compile, $rootScope, $q, $$multiMap, $$stackedMap) {
var OPENED_MODAL_CLASS = 'modal-open';
var backdropDomEl, backdropScope;
var openedWindows = $$stackedMap.createNew();
var openedClasses = $$multiMap.createNew();
var $modalStack = {
NOW_CLOSING_EVENT: 'modal.stack.now-closing'
};
//Modal focus behavior
var focusableElementList;
var focusIndex = 0;
var tababbleSelector = 'a[href], area[href], input:not([disabled]), ' +
'button:not([disabled]),select:not([disabled]), textarea:not([disabled]), ' +
'iframe, object, embed, *[tabindex], *[contenteditable=true]';
function backdropIndex() {
var topBackdropIndex = -1;
var opened = openedWindows.keys();
for (var i = 0; i < opened.length; i++) {
if (openedWindows.get(opened[i]).value.backdrop) {
topBackdropIndex = i;
}
}
return topBackdropIndex;
}
$rootScope.$watch(backdropIndex, function(newBackdropIndex) {
if (backdropScope) {
backdropScope.index = newBackdropIndex;
}
});
function removeModalWindow(modalInstance, elementToReceiveFocus) {
var modalWindow = openedWindows.get(modalInstance).value;
var appendToElement = modalWindow.appendTo;
//clean up the stack
openedWindows.remove(modalInstance);
removeAfterAnimate(modalWindow.modalDomEl, modalWindow.modalScope, function() {
var modalBodyClass = modalWindow.openedClass || OPENED_MODAL_CLASS;
openedClasses.remove(modalBodyClass, modalInstance);
appendToElement.toggleClass(modalBodyClass, openedClasses.hasKey(modalBodyClass));
toggleTopWindowClass(true);
});
checkRemoveBackdrop();
//move focus to specified element if available, or else to body
if (elementToReceiveFocus && elementToReceiveFocus.focus) {
elementToReceiveFocus.focus();
} else {
appendToElement.focus();
}
}
// Add or remove "windowTopClass" from the top window in the stack
function toggleTopWindowClass(toggleSwitch) {
var modalWindow;
if (openedWindows.length() > 0) {
modalWindow = openedWindows.top().value;
modalWindow.modalDomEl.toggleClass(modalWindow.windowTopClass || '', toggleSwitch);
}
}
function checkRemoveBackdrop() {
//remove backdrop if no longer needed
if (backdropDomEl && backdropIndex() === -1) {
var backdropScopeRef = backdropScope;
removeAfterAnimate(backdropDomEl, backdropScope, function() {
backdropScopeRef = null;
});
backdropDomEl = undefined;
backdropScope = undefined;
}
}
function removeAfterAnimate(domEl, scope, done, closedDeferred) {
var asyncDeferred;
var asyncPromise = null;
var setIsAsync = function() {
if (!asyncDeferred) {
asyncDeferred = $q.defer();
asyncPromise = asyncDeferred.promise;
}
return function asyncDone() {
asyncDeferred.resolve();
};
};
scope.$broadcast($modalStack.NOW_CLOSING_EVENT, setIsAsync);
// Note that it's intentional that asyncPromise might be null.
// That's when setIsAsync has not been called during the
// NOW_CLOSING_EVENT broadcast.
return $q.when(asyncPromise).then(afterAnimating);
function afterAnimating() {
if (afterAnimating.done) {
return;
}
afterAnimating.done = true;
$animateCss(domEl, {
event: 'leave'
}).start().then(function() {
domEl.remove();
if (closedDeferred) {
closedDeferred.resolve();
}
});
scope.$destroy();
if (done) {
done();
}
}
}
$document.on('keydown', keydownListener);
$rootScope.$on('$destroy', function() {
$document.off('keydown', keydownListener);
});
function keydownListener(evt) {
if (evt.isDefaultPrevented()) {
return evt;
}
var modal = openedWindows.top();
if (modal) {
switch (evt.which) {
case 27: {
if (modal.value.keyboard) {
evt.preventDefault();
$rootScope.$apply(function() {
$modalStack.dismiss(modal.key, 'escape key press');
});
}
break;
}
case 9: {
$modalStack.loadFocusElementList(modal);
var focusChanged = false;
if (evt.shiftKey) {
if ($modalStack.isFocusInFirstItem(evt)) {
focusChanged = $modalStack.focusLastFocusableElement();
}
} else {
if ($modalStack.isFocusInLastItem(evt)) {
focusChanged = $modalStack.focusFirstFocusableElement();
}
}
if (focusChanged) {
evt.preventDefault();
evt.stopPropagation();
}
break;
}
}
}
}
$modalStack.open = function(modalInstance, modal) {
var modalOpener = $document[0].activeElement,
modalBodyClass = modal.openedClass || OPENED_MODAL_CLASS;
toggleTopWindowClass(false);
openedWindows.add(modalInstance, {
deferred: modal.deferred,
renderDeferred: modal.renderDeferred,
closedDeferred: modal.closedDeferred,
modalScope: modal.scope,
backdrop: modal.backdrop,
keyboard: modal.keyboard,
openedClass: modal.openedClass,
windowTopClass: modal.windowTopClass,
animation: modal.animation,
appendTo: modal.appendTo
});
openedClasses.put(modalBodyClass, modalInstance);
var appendToElement = modal.appendTo,
currBackdropIndex = backdropIndex();
if (!appendToElement.length) {
throw new Error('appendTo element not found. Make sure that the element passed is in DOM.');
}
if (currBackdropIndex >= 0 && !backdropDomEl) {
backdropScope = $rootScope.$new(true);
backdropScope.modalOptions = modal;
backdropScope.index = currBackdropIndex;
backdropDomEl = angular.element('<div uib-modal-backdrop="modal-backdrop"></div>');
backdropDomEl.attr('backdrop-class', modal.backdropClass);
if (modal.animation) {
backdropDomEl.attr('modal-animation', 'true');
}
$compile(backdropDomEl)(backdropScope);
$animate.enter(backdropDomEl, appendToElement);
}
var angularDomEl = angular.element('<div uib-modal-window="modal-window"></div>');
angularDomEl.attr({
'template-url': modal.windowTemplateUrl,
'window-class': modal.windowClass,
'window-top-class': modal.windowTopClass,
'size': modal.size,
'index': openedWindows.length() - 1,
'animate': 'animate'
}).html(modal.content);
if (modal.animation) {
angularDomEl.attr('modal-animation', 'true');
}
$animate.enter(angularDomEl, appendToElement)
.then(function() {
$compile(angularDomEl)(modal.scope);
$animate.addClass(appendToElement, modalBodyClass);
});
openedWindows.top().value.modalDomEl = angularDomEl;
openedWindows.top().value.modalOpener = modalOpener;
$modalStack.clearFocusListCache();
};
function broadcastClosing(modalWindow, resultOrReason, closing) {
return !modalWindow.value.modalScope.$broadcast('modal.closing', resultOrReason, closing).defaultPrevented;
}
$modalStack.close = function(modalInstance, result) {
var modalWindow = openedWindows.get(modalInstance);
if (modalWindow && broadcastClosing(modalWindow, result, true)) {
modalWindow.value.modalScope.$$uibDestructionScheduled = true;
modalWindow.value.deferred.resolve(result);
removeModalWindow(modalInstance, modalWindow.value.modalOpener);
return true;
}
return !modalWindow;
};
$modalStack.dismiss = function(modalInstance, reason) {
var modalWindow = openedWindows.get(modalInstance);
if (modalWindow && broadcastClosing(modalWindow, reason, false)) {
modalWindow.value.modalScope.$$uibDestructionScheduled = true;
modalWindow.value.deferred.reject(reason);
removeModalWindow(modalInstance, modalWindow.value.modalOpener);
return true;
}
return !modalWindow;
};
$modalStack.dismissAll = function(reason) {
var topModal = this.getTop();
while (topModal && this.dismiss(topModal.key, reason)) {
topModal = this.getTop();
}
};
$modalStack.getTop = function() {
return openedWindows.top();
};
$modalStack.modalRendered = function(modalInstance) {
var modalWindow = openedWindows.get(modalInstance);
if (modalWindow) {
modalWindow.value.renderDeferred.resolve();
}
};
$modalStack.focusFirstFocusableElement = function() {
if (focusableElementList.length > 0) {
focusableElementList[0].focus();
return true;
}
return false;
};
$modalStack.focusLastFocusableElement = function() {
if (focusableElementList.length > 0) {
focusableElementList[focusableElementList.length - 1].focus();
return true;
}
return false;
};
$modalStack.isFocusInFirstItem = function(evt) {
if (focusableElementList.length > 0) {
return (evt.target || evt.srcElement) === focusableElementList[0];
}
return false;
};
$modalStack.isFocusInLastItem = function(evt) {
if (focusableElementList.length > 0) {
return (evt.target || evt.srcElement) === focusableElementList[focusableElementList.length - 1];
}
return false;
};
$modalStack.clearFocusListCache = function() {
focusableElementList = [];
focusIndex = 0;
};
$modalStack.loadFocusElementList = function(modalWindow) {
if (focusableElementList === undefined || !focusableElementList.length) {
if (modalWindow) {
var modalDomE1 = modalWindow.value.modalDomEl;
if (modalDomE1 && modalDomE1.length) {
focusableElementList = modalDomE1[0].querySelectorAll(tababbleSelector);
}
}
}
};
return $modalStack;
}])
.provider('$uibModal', function() {
var $modalProvider = {
options: {
animation: true,
backdrop: true, //can also be false or 'static'
keyboard: true
},
$get: ['$injector', '$rootScope', '$q', '$document', '$templateRequest', '$controller', '$uibModalStack',
function ($injector, $rootScope, $q, $document, $templateRequest, $controller, $modalStack) {
var $modal = {};
function getTemplatePromise(options) {
return options.template ? $q.when(options.template) :
$templateRequest(angular.isFunction(options.templateUrl) ?
options.templateUrl() : options.templateUrl);
}
function getResolvePromises(resolves) {
var promisesArr = [];
angular.forEach(resolves, function(value) {
if (angular.isFunction(value) || angular.isArray(value)) {
promisesArr.push($q.when($injector.invoke(value)));
} else if (angular.isString(value)) {
promisesArr.push($q.when($injector.get(value)));
} else {
promisesArr.push($q.when(value));
}
});
return promisesArr;
}
var promiseChain = null;
$modal.getPromiseChain = function() {
return promiseChain;
};
$modal.open = function(modalOptions) {
var modalResultDeferred = $q.defer();
var modalOpenedDeferred = $q.defer();
var modalClosedDeferred = $q.defer();
var modalRenderDeferred = $q.defer();
//prepare an instance of a modal to be injected into controllers and returned to a caller
var modalInstance = {
result: modalResultDeferred.promise,
opened: modalOpenedDeferred.promise,
closed: modalClosedDeferred.promise,
rendered: modalRenderDeferred.promise,
close: function (result) {
return $modalStack.close(modalInstance, result);
},
dismiss: function (reason) {
return $modalStack.dismiss(modalInstance, reason);
}
};
//merge and clean up options
modalOptions = angular.extend({}, $modalProvider.options, modalOptions);
modalOptions.resolve = modalOptions.resolve || {};
modalOptions.appendTo = modalOptions.appendTo || $document.find('body').eq(0);
//verify options
if (!modalOptions.template && !modalOptions.templateUrl) {
throw new Error('One of template or templateUrl options is required.');
}
var templateAndResolvePromise =
$q.all([getTemplatePromise(modalOptions)].concat(getResolvePromises(modalOptions.resolve)));
function resolveWithTemplate() {
return templateAndResolvePromise;
}
// Wait for the resolution of the existing promise chain.
// Then switch to our own combined promise dependency (regardless of how the previous modal fared).
// Then add to $modalStack and resolve opened.
// Finally clean up the chain variable if no subsequent modal has overwritten it.
var samePromise;
samePromise = promiseChain = $q.all([promiseChain])
.then(resolveWithTemplate, resolveWithTemplate)
.then(function resolveSuccess(tplAndVars) {
var modalScope = (modalOptions.scope || $rootScope).$new();
modalScope.$close = modalInstance.close;
modalScope.$dismiss = modalInstance.dismiss;
modalScope.$on('$destroy', function() {
if (!modalScope.$$uibDestructionScheduled) {
modalScope.$dismiss('$uibUnscheduledDestruction');
}
});
var ctrlInstance, ctrlLocals = {};
var resolveIter = 1;
//controllers
if (modalOptions.controller) {
ctrlLocals.$scope = modalScope;
ctrlLocals.$uibModalInstance = modalInstance;
angular.forEach(modalOptions.resolve, function(value, key) {
ctrlLocals[key] = tplAndVars[resolveIter++];
});
ctrlInstance = $controller(modalOptions.controller, ctrlLocals);
if (modalOptions.controllerAs) {
if (modalOptions.bindToController) {
angular.extend(ctrlInstance, modalScope);
}
modalScope[modalOptions.controllerAs] = ctrlInstance;
}
}
$modalStack.open(modalInstance, {
scope: modalScope,
deferred: modalResultDeferred,
renderDeferred: modalRenderDeferred,
closedDeferred: modalClosedDeferred,
content: tplAndVars[0],
animation: modalOptions.animation,
backdrop: modalOptions.backdrop,
keyboard: modalOptions.keyboard,
backdropClass: modalOptions.backdropClass,
windowTopClass: modalOptions.windowTopClass,
windowClass: modalOptions.windowClass,
windowTemplateUrl: modalOptions.windowTemplateUrl,
size: modalOptions.size,
openedClass: modalOptions.openedClass,
appendTo: modalOptions.appendTo
});
modalOpenedDeferred.resolve(true);
}, function resolveError(reason) {
modalOpenedDeferred.reject(reason);
modalResultDeferred.reject(reason);
})['finally'](function() {
if (promiseChain === samePromise) {
promiseChain = null;
}
});
return modalInstance;
};
return $modal;
}
]
};
return $modalProvider;
});
|
import React, { Component } from 'react'
import './App.css'
// 组件
import Message from './message'
import Timer from './timer'
import TodoApp from './todo'
import MarkdownEditor from './editor'
import Logo from './logo'
class App extends Component {
// constructor 是类被初始化后自动调用的函数
constructor(props) {
super(props)
this.state = {
showTimer: true,
}
}
// jsx 语法
render() {
// 用一个变量决定是否显示 timer 组件
// 组件就是说呢 我们不写页面了
// 我们写一个个组件 最后把小组件拼成一个 html
// ? 三元表达式
// button 绑定事件
var timer = this.state.showTimer ? <Timer /> : null
return (
<div className="App">
<Logo />
<Message name="Young" />
<Message name="洋" />
<button onClick={this.handleToggleTimer}>开关 timer</button>
{timer}
<TodoApp />
<MarkdownEditor />
</div>
)
}
// e 用了箭头函数指向 handleToggleTimer 这个函数 再指向 this
// this 就是外面这个 class App
handleToggleTimer = (e) => {
var showTimer = !this.state.showTimer
// 使用 setState 改变 this.state
// 程序自动重新调用 render
// 框架提供的 setState
this.setState({showTimer})
}
}
export default App
|
import withMediaControl from 'EditorWidgets/withMedia/withMediaControl';
const FileControl = withMediaControl();
export default FileControl;
|
var fs = require('fs');
var fmt = require('util').format;
var uniq = require('lodash.uniq');
var path = require('path');
var Plugin = require('broccoli-plugin');
function FastBootConfig(inputNode, options) {
Plugin.call(this, [inputNode], {
annotation: "Generate: FastBoot package.json"
});
this.project = options.project;
this.name = options.name;
this.ui = options.ui;
this.fastbootAppConfig = options.fastbootAppConfig;
this.outputPaths = options.outputPaths;
this.appConfig = options.appConfig;
}
FastBootConfig.prototype = Object.create(Plugin.prototype);
FastBootConfig.prototype.constructor = FastBootConfig;
/**
* The main hook called by Broccoli Plugin. Used to build or
* rebuild the tree. In this case, we generate the configuration
* and write it to `package.json`.
*/
FastBootConfig.prototype.build = function() {
this.buildDependencies();
this.buildManifest();
this.buildHostWhitelist();
var outputPath = path.join(this.outputPath, 'package.json');
fs.writeFileSync(outputPath, this.toJSONString());
};
FastBootConfig.prototype.buildDependencies = function() {
var dependencies = {};
var moduleWhitelist = [];
var ui = this.ui;
eachAddonPackage(this.project, function(pkg) {
var deps = getFastBootDependencies(pkg);
if (deps) {
deps.forEach(function(dep) {
var version = getDependencyVersion(pkg, dep);
if (dep in dependencies) {
version = dependencies[dep];
ui.writeLine(fmt("Duplicate FastBoot dependency %s. Versions may mismatch. Using range %s.", dep, version), ui.WARNING);
return;
}
moduleWhitelist.push(dep);
if (version) {
dependencies[dep] = version;
}
});
}
});
var pkg = this.project.pkg;
var projectDeps = pkg.fastbootDependencies;
if (projectDeps) {
projectDeps.forEach(function(dep) {
moduleWhitelist.push(dep);
var version = pkg.dependencies && pkg.dependencies[dep];
if (version) {
dependencies[dep] = version;
}
});
}
this.dependencies = dependencies;
this.moduleWhitelist = uniq(moduleWhitelist);
};
FastBootConfig.prototype.readAssetManifest = function() {
var assetMapPath = path.join(this.inputPaths[0], 'fastbootAssetMap.json');
try {
var assetMap = JSON.parse(fs.readFileSync(assetMapPath));
return assetMap;
} catch (e) {
// No asset map was found, proceed as usual
}
};
FastBootConfig.prototype.buildManifest = function() {
var appFileName = path.basename(this.outputPaths.app.js).split('.')[0];
var appFile = 'fastboot/' + appFileName + '.js';
var vendorFileName = path.basename(this.outputPaths.vendor.js).split('.')[0];
var vendorFile = 'fastboot/' + vendorFileName + '.js';
var manifest = {
appFile: appFile,
vendorFile: vendorFile,
htmlFile: 'index.html'
};
var rewrittenAssets = this.readAssetManifest();
if (rewrittenAssets) {
var assets = {};
// Because the assetMap was written before the files in the
// `asset` folder were moved to the `fastboot` folder,
// we have to rewrite them here.
for (var key in rewrittenAssets.assets) {
var rewrittenKey = assetToFastboot(key);
assets[rewrittenKey] = assetToFastboot(rewrittenAssets.assets[key]);
}
['appFile', 'vendorFile'].forEach(function(file) {
// Update package.json with the fingerprinted file.
manifest[file] = assets[manifest[file]];
});
}
this.manifest = manifest;
};
FastBootConfig.prototype.buildHostWhitelist = function() {
if (!!this.fastbootAppConfig) {
this.hostWhitelist = this.fastbootAppConfig.hostWhitelist;
}
};
FastBootConfig.prototype.toJSONString = function() {
return JSON.stringify({
dependencies: this.dependencies,
fastboot: {
moduleWhitelist: this.moduleWhitelist,
manifest: this.manifest,
hostWhitelist: this.normalizeHostWhitelist(),
appConfig: this.appConfig
}
}, null, 2);
};
FastBootConfig.prototype.normalizeHostWhitelist = function() {
if (!this.hostWhitelist) {
return;
}
return this.hostWhitelist.map(function(entry) {
// Is a regex
if (entry.source) {
return '/' + entry.source + '/';
} else {
return entry;
}
});
};
function eachAddonPackage(project, cb) {
project.addons.map(function(addon) {
cb(addon.pkg);
});
}
function getFastBootDependencies(pkg) {
return pkg['ember-addon'] && pkg['ember-addon'].fastBootDependencies;
}
function getDependencyVersion(pkg, dep) {
if (!pkg.dependencies) {
throw new Error(fmt("Could not find FastBoot dependency '%s' in %s/package.json dependencies.", dep, pkg.name));
}
return pkg.dependencies[dep];
}
module.exports = FastBootConfig;
function assetToFastboot(key) {
var parts = key.split('/');
var dir = parts[0];
if (dir === 'assets') {
parts[0] = 'fastboot';
}
return parts.join('/');
}
|
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
export { withContext } from './withContext';
export { withStyles } from './withStyles';
export { withViewport } from './withViewport';
|
//NB Very important: there needs to be a reducer for each piece of state
// as defined in the store.js file cf. const defaulState
//NB all reducers are fired by an action dispatch, we must
// therefore check the actions to be handled (pertinent to the reducer) here
// and just return state if no action is handled
function gameCommand(state=[], action) {
switch(action.type) {
case 'START_GAME' :
var {start,clear,pattern,requestId,pause} = action.payload
return {
...state,
start,
clear,
pattern,
requestId,
pause
}
case 'BIG_BOARD' :
var { start, clear, big } = action.payload
return {
...state,
big,
clear,
start
}
case 'PAUSE_GAME' :
var {clear,start,pause} = action.payload
return {
...state,
pause,
clear,
start
}
case 'DRAW' :
var {clear,pattern,requestId,draw} = action.payload
return {
...state,
draw,
clear,
pattern,
requestId
}
case 'CLEAR_BOARD' :
var {clear, pattern, requestId, pause, start} = action.payload
return {
...state,
clear,
pattern,
requestId,
pause,
start
}
case 'CHANGE_SPEED' :
var {fps, clear, start} = action.payload
return {
...state,
fps,
clear,
start
}
case 'BUILT-IN_PATTERN' :
var {start,clear,pattern,requestId} = action.payload
return {
...state,
pattern,
start,
clear,
requestId,
}
default:
return state
}
return state
}
export default gameCommand; |
'use strict';
var gulp = require('gulp');
var eslint = require('gulp-eslint');
var htmlExtract = require('gulp-html-extract');
var sourcemaps = require('gulp-sourcemaps');
var stylelint = require('gulp-stylelint');
var ts = require('gulp-typescript');
var typings = require('gulp-typings');
gulp.task('lint', ['lint:js', 'lint:html', 'lint:css']);
gulp.task('lint:js', function() {
return gulp.src([
'*.js',
'test/*.js'
])
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failAfterError());
});
gulp.task('lint:html', function() {
return gulp.src([
'*.html',
'demo/*.html',
'test/*.html'
])
.pipe(htmlExtract({
sel: 'script, code-example code',
strip: true
}))
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failAfterError());
});
gulp.task('lint:css', function() {
return gulp.src([
'*.html',
'demo/*.html',
'test/*.html'
])
.pipe(htmlExtract({
sel: 'style'
}))
.pipe(stylelint({
reporters: [
{formatter: 'string', console: true}
]
}));
});
gulp.task('typings', function() {
return gulp.src('test/angular2/typings.json')
.pipe(typings());
});
gulp.task('ng2', ['typings'], function() {
['test/angular2'].forEach(function(dir) {
gulp.src([dir + '/*.ts', 'test/angular2/typings/main/**/*.d.ts'])
.pipe(sourcemaps.init())
.pipe(ts(ts.createProject('test/angular2/tsconfig.json')))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(dir));
});
});
gulp.task('ng2:watch', function() {
gulp.watch('test/angular2/*.ts', ['ng2']);
});
|
'use strict';
var gulp = require('gulp');
var del = require('del');
var outputDir = 'static';
gulp.task('clean:static', function() {
return del([`${outputDir}/**/*`]);
});
gulp.task('copy:js', ['clean:static'], function() {
var files = [
'node_modules/firebase/firebase-app.js',
'node_modules/firebase/firebase-auth.js',
'node_modules/bootstrap/dist/js/bootstrap.min.js',
'node_modules/jquery/dist/jquery.min.js',
'node_modules/owl.carousel/dist/owl.carousel.min.js'
];
return gulp.src(files)
.pipe(gulp.dest(`${outputDir}/js`))
});
gulp.task('copy:css-font-awesome', ['clean:static'], function() {
return gulp.src('node_modules/font-awesome/**/*')
.pipe(gulp.dest(`${outputDir}/css/font-awesome`))
});
gulp.task('copy:css', ['clean:static', 'copy:css-font-awesome'], function() {
var files = [
'node_modules/bootstrap/dist/css/bootstrap.min.css',
'node_modules/owl.carousel/dist/assets/owl.carousel.min.css',
'node_modules/owl.carousel/dist/assets/owl.theme.default.min.css',
];
return gulp.src(files)
.pipe(gulp.dest(`${outputDir}/css`))
});
gulp.task('copy:src', ['clean:static'], function() {
return gulp.src('src-static/**/*')
.pipe(gulp.dest(outputDir));
})
gulp.task('copy', ['copy:src', 'copy:js', 'copy:css']);
gulp.task('default', ['copy']);
|
import Ember from 'ember';
var Session = Ember.Object.extend({
user: {
isAdmin: false
}
});
export function initialize(container, application) {
application.register('service:session', Session.create(), { instantiate: false });
application.inject('route', 'session', 'service:session');
}
export default {
name: 'inject-session',
initialize: initialize
};
|
const electron = require('electron');
const app = electron.app; // Module to control application life.
const BrowserWindow = electron.BrowserWindow; // Module to create native browser window.
const Menu = electron.Menu;
const autoUpdater = electron.autoUpdater;
const dialog = electron.dialog;
// Report crashes to our server.
// electron.crashReporter.start();
// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.
var mainWindow = null;
const APP_NAME = app.getName();
const DARWIN_ALL_CLOSED_MENU = [
{
label: APP_NAME,
submenu: [
{
label: 'About ' + APP_NAME,
role: 'about'
},
{
type: 'separator'
},
{
label: 'Services',
role: 'services',
submenu: []
},
{
type: 'separator'
},
{
label: 'Hide ' + APP_NAME,
accelerator: 'Command+H',
role: 'hide'
},
{
label: 'Hide Others',
accelerator: 'Command+Shift+H',
role: 'hideothers'
},
{
label: 'Show All',
role: 'unhide'
},
{
type: 'separator'
},
{
label: 'Quit ' + APP_NAME,
accelerator: 'Command+Q',
click: function () {
app.quit();
}
}
]
},
{
label: 'File',
submenu: [
{
label: 'New ' + APP_NAME +' Window',
click: makeWindow
}
]
}
];
// Quit when all windows are closed.
app.on('window-all-closed', function() {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform != 'darwin') {
app.quit();
} else {
Menu.setApplicationMenu(Menu.buildFromTemplate(DARWIN_ALL_CLOSED_MENU));
}
});
function makeWindow() {
// Create the browser window.
var conf = {
width: 1024, height: 768,
minWidth: 270, minHeight: 437,
titleBarStyle: 'hidden'
};
if (process.platform == 'linux') {
conf['icon'] = __dirname + '/icon.png';
}
mainWindow = new BrowserWindow(conf);
// Set ApplicationMenu bar
// and load the index.html of the app.
mainWindow.loadURL('file://' + __dirname + '/index.html');
// Open the DevTools.
// mainWindow.webContents.openDevTools();
// Emitted when the window is closed.
mainWindow.on('closed', function() {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null;
});
}
function applyUpdater() {
var feedUrl = 'https://zwkuawed8b.execute-api.ap-northeast-1.amazonaws.com/prod?version=' + app.getVersion();
autoUpdater.on('update-downloaded', function (event, releaseNotes, releaseName, releaseDate, updateUrl, quitAndUpdate) {
var index = dialog.showMessageBox(mainWindow, {
type: 'info',
buttons: ['Restart', 'Later'],
title: "PileMd",
message: 'The new version has been downloaded. Please restart the application to apply the updates.',
detail: releaseName + "\n\n" + releaseNotes
});
if (index === 1) {
return;
}
quitAndUpdate();
});
autoUpdater.on("error", (error) => {});
autoUpdater.setFeedURL(feedUrl);
autoUpdater.checkForUpdates();
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', function() {
makeWindow();
applyUpdater();
});
app.on('activate', function() {
if(!mainWindow){
makeWindow();
autoUpdater.checkForUpdates();
}
});
|
import {
moduleFor,
test
} from 'ember-qunit';
moduleFor('controller:quiz/q3-1', 'QuizQ31Controller', {
// Specify the other units that are required for this test.
// needs: ['controller:foo']
});
// Replace this with your real tests.
test('it exists', function() {
var controller = this.subject();
ok(controller);
});
|
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2015 Photon Storm Ltd.
* @license {@link https://github.com/photonstorm/phaser/blob/master/license.txt|MIT License}
*/
/**
* An Animation instance contains a single animation and the controls to play it.
*
* It is created by the AnimationManager, consists of Animation.Frame objects and belongs to a single Game Object such as a Sprite.
*
* @class Phaser.Animation
* @constructor
* @param {Phaser.Game} game - A reference to the currently running game.
* @param {Phaser.Sprite} parent - A reference to the owner of this Animation.
* @param {string} name - The unique name for this animation, used in playback commands.
* @param {Phaser.FrameData} frameData - The FrameData object that contains all frames used by this Animation.
* @param {number[]|string[]} frames - An array of numbers or strings indicating which frames to play in which order.
* @param {number} [frameRate=60] - The speed at which the animation should play. The speed is given in frames per second.
* @param {boolean} [loop=false] - Whether or not the animation is looped or just plays once.
* @param {boolean} loop - Should this animation loop when it reaches the end or play through once.
*/
Phaser.Animation = function (game, parent, name, frameData, frames, frameRate, loop) {
if (typeof loop === 'undefined') { loop = false; }
/**
* @property {Phaser.Game} game - A reference to the currently running Game.
*/
this.game = game;
/**
* @property {Phaser.Sprite} _parent - A reference to the parent Sprite that owns this Animation.
* @private
*/
this._parent = parent;
/**
* @property {Phaser.FrameData} _frameData - The FrameData the Animation uses.
* @private
*/
this._frameData = frameData;
/**
* @property {string} name - The user defined name given to this Animation.
*/
this.name = name;
/**
* @property {array} _frames
* @private
*/
this._frames = [];
this._frames = this._frames.concat(frames);
/**
* @property {number} delay - The delay in ms between each frame of the Animation, based on the given frameRate.
*/
this.delay = 1000 / frameRate;
/**
* @property {boolean} loop - The loop state of the Animation.
*/
this.loop = loop;
/**
* @property {number} loopCount - The number of times the animation has looped since it was last started.
*/
this.loopCount = 0;
/**
* @property {boolean} killOnComplete - Should the parent of this Animation be killed when the animation completes?
* @default
*/
this.killOnComplete = false;
/**
* @property {boolean} isFinished - The finished state of the Animation. Set to true once playback completes, false during playback.
* @default
*/
this.isFinished = false;
/**
* @property {boolean} isPlaying - The playing state of the Animation. Set to false once playback completes, true during playback.
* @default
*/
this.isPlaying = false;
/**
* @property {boolean} isPaused - The paused state of the Animation.
* @default
*/
this.isPaused = false;
/**
* @property {boolean} _pauseStartTime - The time the animation paused.
* @private
* @default
*/
this._pauseStartTime = 0;
/**
* @property {number} _frameIndex
* @private
* @default
*/
this._frameIndex = 0;
/**
* @property {number} _frameDiff
* @private
* @default
*/
this._frameDiff = 0;
/**
* @property {number} _frameSkip
* @private
* @default
*/
this._frameSkip = 1;
/**
* @property {Phaser.Frame} currentFrame - The currently displayed frame of the Animation.
*/
this.currentFrame = this._frameData ? this._frameData.getFrame(this._frames[this._frameIndex]) : this._frameIndex;
/**
* @property {Phaser.Signal} onStart - This event is dispatched when this Animation starts playback.
*/
this.onStart = new Phaser.Signal();
/**
* @property {Phaser.Signal|null} onUpdate - This event is dispatched when the Animation changes frame. By default this event is disabled due to its intensive nature. Enable it with: `Animation.enableUpdate = true`.
* @default
*/
this.onUpdate = null;
/**
* @property {Phaser.Signal} onComplete - This event is dispatched when this Animation completes playback. If the animation is set to loop this is never fired, listen for onAnimationLoop instead.
*/
this.onComplete = new Phaser.Signal();
/**
* @property {Phaser.Signal} onLoop - This event is dispatched when this Animation loops.
*/
this.onLoop = new Phaser.Signal();
// Set-up some event listeners
this.game.onPause.add(this.onPause, this);
this.game.onResume.add(this.onResume, this);
};
Phaser.Animation.prototype = {
/**
* Plays this animation.
*
* @method Phaser.Animation#play
* @param {number} [frameRate=null] - The framerate to play the animation at. The speed is given in frames per second. If not provided the previously set frameRate of the Animation is used.
* @param {boolean} [loop=false] - Should the animation be looped after playback. If not provided the previously set loop value of the Animation is used.
* @param {boolean} [killOnComplete=false] - If set to true when the animation completes (only happens if loop=false) the parent Sprite will be killed.
* @return {Phaser.Animation} - A reference to this Animation instance.
*/
play: function (frameRate, loop, killOnComplete) {
if (typeof frameRate === 'number')
{
// If they set a new frame rate then use it, otherwise use the one set on creation
this.delay = 1000 / frameRate;
}
if (typeof loop === 'boolean')
{
// If they set a new loop value then use it, otherwise use the one set on creation
this.loop = loop;
}
if (typeof killOnComplete !== 'undefined')
{
// Remove the parent sprite once the animation has finished?
this.killOnComplete = killOnComplete;
}
this.isPlaying = true;
this.isFinished = false;
this.paused = false;
this.loopCount = 0;
this._timeLastFrame = this.game.time.time;
this._timeNextFrame = this.game.time.time + this.delay;
this._frameIndex = 0;
this.updateCurrentFrame(false);
this._parent.events.onAnimationStart$dispatch(this._parent, this);
this.onStart.dispatch(this._parent, this);
this._parent.animations.currentAnim = this;
this._parent.animations.currentFrame = this.currentFrame;
return this;
},
/**
* Sets this animation back to the first frame and restarts the animation.
*
* @method Phaser.Animation#restart
*/
restart: function () {
this.isPlaying = true;
this.isFinished = false;
this.paused = false;
this.loopCount = 0;
this._timeLastFrame = this.game.time.time;
this._timeNextFrame = this.game.time.time + this.delay;
this._frameIndex = 0;
this.currentFrame = this._frameData ? this._frameData.getFrame(this._frames[this._frameIndex]) : this._frameIndex;
this._parent.setFrame(this.currentFrame);
this._parent.animations.currentAnim = this;
this._parent.animations.currentFrame = this.currentFrame;
this.onStart.dispatch(this._parent, this);
},
/**
* Sets this animations playback to a given frame with the given ID.
*
* @method Phaser.Animation#setFrame
* @param {string|number} [frameId] - The identifier of the frame to set. Can be the name of the frame, the sprite index of the frame, or the animation-local frame index.
* @param {boolean} [useLocalFrameIndex=false] - If you provide a number for frameId, should it use the numeric indexes of the frameData, or the 0-indexed frame index local to the animation.
*/
setFrame: function(frameId, useLocalFrameIndex) {
var frameIndex;
if (typeof useLocalFrameIndex === 'undefined')
{
useLocalFrameIndex = false;
}
// Find the index to the desired frame.
if (typeof frameId === "string")
{
for (var i = 0; i < this._frames.length; i++)
{
if (this._frameData && this._frameData.getFrame(this._frames[i]).name === frameId)
{
frameIndex = i;
}
}
}
else if (typeof frameId === "number")
{
if (useLocalFrameIndex)
{
frameIndex = frameId;
}
else
{
for (var i = 0; i < this._frames.length; i++)
{
if (this._frames[i] === frameIndex)
{
frameIndex = i;
}
}
}
}
if (frameIndex)
{
// Set the current frame index to the found index. Subtract 1 so that it animates to the desired frame on update.
this._frameIndex = frameIndex - 1;
// Make the animation update at next update
this._timeNextFrame = this.game.time.time;
this.update();
}
},
/**
* Stops playback of this animation and set it to a finished state. If a resetFrame is provided it will stop playback and set frame to the first in the animation.
* If `dispatchComplete` is true it will dispatch the complete events, otherwise they'll be ignored.
*
* @method Phaser.Animation#stop
* @param {boolean} [resetFrame=false] - If true after the animation stops the currentFrame value will be set to the first frame in this animation.
* @param {boolean} [dispatchComplete=false] - Dispatch the Animation.onComplete and parent.onAnimationComplete events?
*/
stop: function (resetFrame, dispatchComplete) {
if (typeof resetFrame === 'undefined') { resetFrame = false; }
if (typeof dispatchComplete === 'undefined') { dispatchComplete = false; }
this.isPlaying = false;
this.isFinished = true;
this.paused = false;
if (resetFrame)
{
this.currentFrame = this._frameData ? this._frameData.getFrame(this._frames[0]) : 0;
this._parent.setFrame(this.currentFrame);
}
if (dispatchComplete)
{
this._parent.events.onAnimationComplete$dispatch(this._parent, this);
this.onComplete.dispatch(this._parent, this);
}
},
/**
* Called when the Game enters a paused state.
*
* @method Phaser.Animation#onPause
*/
onPause: function () {
if (this.isPlaying)
{
this._frameDiff = this._timeNextFrame - this.game.time.time;
}
},
/**
* Called when the Game resumes from a paused state.
*
* @method Phaser.Animation#onResume
*/
onResume: function () {
if (this.isPlaying)
{
this._timeNextFrame = this.game.time.time + this._frameDiff;
}
},
/**
* Updates this animation. Called automatically by the AnimationManager.
*
* @method Phaser.Animation#update
*/
update: function () {
if (this.isPaused)
{
return false;
}
if (this.isPlaying && this.game.time.time >= this._timeNextFrame)
{
this._frameSkip = 1;
// Lagging?
this._frameDiff = this.game.time.time - this._timeNextFrame;
this._timeLastFrame = this.game.time.time;
if (this._frameDiff > this.delay)
{
// We need to skip a frame, work out how many
this._frameSkip = Math.floor(this._frameDiff / this.delay);
this._frameDiff -= (this._frameSkip * this.delay);
this._frameSkip += 1;
}
// And what's left now?
this._timeNextFrame = this.game.time.time + (this.delay - this._frameDiff);
this._frameIndex += this._frameSkip;
if (this._frameIndex >= this._frames.length)
{
if (this.loop)
{
// Update current state before event callback
this._frameIndex %= this._frames.length;
this.currentFrame = this._frameData ? this._frameData.getFrame(this._frames[this._frameIndex]) : this._frameIndex;
this.loopCount++;
this._parent.events.onAnimationLoop$dispatch(this._parent, this);
this.onLoop.dispatch(this._parent, this);
return this.updateCurrentFrame(true);
}
else
{
this.complete();
return false;
}
}
else
{
return this.updateCurrentFrame(true);
}
}
return false;
},
/**
* Changes the currentFrame per the _frameIndex, updates the display state,
* and triggers the update signal.
*
* Returns true if the current frame update was 'successful', false otherwise.
*
* @method Phaser.Animation#updateCurrentFrame
* @param {bool} signalUpdate - If true th onUpdate signal will be triggered.
* @private
*/
updateCurrentFrame: function (signalUpdate) {
if (!this._frameData)
{
// The animation is already destroyed, probably from a callback
return false;
}
this.currentFrame = this._frameData.getFrame(this._frames[this._frameIndex]);
if (this.currentFrame)
{
this._parent.setFrame(this.currentFrame);
if (this._parent.__tilePattern)
{
this._parent.__tilePattern = false;
this._parent.tilingTexture = false;
}
}
if (this.onUpdate && signalUpdate)
{
this.onUpdate.dispatch(this, this.currentFrame);
// False if the animation was destroyed from within a callback
return !!this._frameData;
}
else
{
return true;
}
},
/**
* Advances by the given number of frames in the Animation, taking the loop value into consideration.
*
* @method Phaser.Animation#next
* @param {number} [quantity=1] - The number of frames to advance.
*/
next: function (quantity) {
if (typeof quantity === 'undefined') { quantity = 1; }
var frame = this._frameIndex + quantity;
if (frame >= this._frames.length)
{
if (this.loop)
{
frame %= this._frames.length;
}
else
{
frame = this._frames.length - 1;
}
}
if (frame !== this._frameIndex)
{
this._frameIndex = frame;
this.updateCurrentFrame(true);
}
},
/**
* Moves backwards the given number of frames in the Animation, taking the loop value into consideration.
*
* @method Phaser.Animation#previous
* @param {number} [quantity=1] - The number of frames to move back.
*/
previous: function (quantity) {
if (typeof quantity === 'undefined') { quantity = 1; }
var frame = this._frameIndex - quantity;
if (frame < 0)
{
if (this.loop)
{
frame = this._frames.length + frame;
}
else
{
frame++;
}
}
if (frame !== this._frameIndex)
{
this._frameIndex = frame;
this.updateCurrentFrame(true);
}
},
/**
* Changes the FrameData object this Animation is using.
*
* @method Phaser.Animation#updateFrameData
* @param {Phaser.FrameData} frameData - The FrameData object that contains all frames used by this Animation.
*/
updateFrameData: function (frameData) {
this._frameData = frameData;
this.currentFrame = this._frameData ? this._frameData.getFrame(this._frames[this._frameIndex % this._frames.length]) : this._frameIndex % this._frames.length;
},
/**
* Cleans up this animation ready for deletion. Nulls all values and references.
*
* @method Phaser.Animation#destroy
*/
destroy: function () {
if (!this.game)
{
// Already destroyed
return;
}
this.game.onPause.remove(this.onPause, this);
this.game.onResume.remove(this.onResume, this);
this.game = null;
this._parent = null;
this._frames = null;
this._frameData = null;
this.currentFrame = null;
this.isPlaying = false;
this.onStart.dispose();
this.onLoop.dispose();
this.onComplete.dispose();
if (this.onUpdate)
{
this.onUpdate.dispose();
}
},
/**
* Called internally when the animation finishes playback.
* Sets the isPlaying and isFinished states and dispatches the onAnimationComplete event if it exists on the parent and local onComplete event.
*
* @method Phaser.Animation#complete
*/
complete: function () {
this._frameIndex = this._frames.length - 1;
this.currentFrame = this._frameData ? this._frameData.getFrame(this._frames[this._frameIndex]) : this._frameIndex;
this.isPlaying = false;
this.isFinished = true;
this.paused = false;
this._parent.events.onAnimationComplete$dispatch(this._parent, this);
this.onComplete.dispatch(this._parent, this);
if (this.killOnComplete)
{
this._parent.kill();
}
}
};
Phaser.Animation.prototype.constructor = Phaser.Animation;
/**
* @name Phaser.Animation#paused
* @property {boolean} paused - Gets and sets the paused state of this Animation.
*/
Object.defineProperty(Phaser.Animation.prototype, 'paused', {
get: function () {
return this.isPaused;
},
set: function (value) {
this.isPaused = value;
if (value)
{
// Paused
this._pauseStartTime = this.game.time.time;
}
else
{
// Un-paused
if (this.isPlaying)
{
this._timeNextFrame = this.game.time.time + this.delay;
}
}
}
});
/**
* @name Phaser.Animation#frameTotal
* @property {number} frameTotal - The total number of frames in the currently loaded FrameData, or -1 if no FrameData is loaded.
* @readonly
*/
Object.defineProperty(Phaser.Animation.prototype, 'frameTotal', {
get: function () {
return this._frames.length;
}
});
/**
* @name Phaser.Animation#frame
* @property {number} frame - Gets or sets the current frame index and updates the Texture Cache for display.
*/
Object.defineProperty(Phaser.Animation.prototype, 'frame', {
get: function () {
if (this.currentFrame !== null)
{
return this.currentFrame.index;
}
else
{
return this._frameIndex;
}
},
set: function (value) {
this.currentFrame = this._frameData ? this._frameData.getFrame(this._frames[value]) : value;
if (this.currentFrame !== null)
{
this._frameIndex = value;
this._parent.setFrame(this.currentFrame);
if (this.onUpdate)
{
this.onUpdate.dispatch(this, this.currentFrame);
}
}
}
});
/**
* @name Phaser.Animation#speed
* @property {number} speed - Gets or sets the current speed of the animation in frames per second. Changing this in a playing animation will take effect from the next frame. Minimum value is 1.
*/
Object.defineProperty(Phaser.Animation.prototype, 'speed', {
get: function () {
return Math.round(1000 / this.delay);
},
set: function (value) {
if (value >= 1)
{
this.delay = 1000 / value;
}
}
});
/**
* @name Phaser.Animation#enableUpdate
* @property {boolean} enableUpdate - Gets or sets if this animation will dispatch the onUpdate events upon changing frame.
*/
Object.defineProperty(Phaser.Animation.prototype, 'enableUpdate', {
get: function () {
return (this.onUpdate !== null);
},
set: function (value) {
if (value && this.onUpdate === null)
{
this.onUpdate = new Phaser.Signal();
}
else if (!value && this.onUpdate !== null)
{
this.onUpdate.dispose();
this.onUpdate = null;
}
}
});
/**
* Really handy function for when you are creating arrays of animation data but it's using frame names and not numbers.
* For example imagine you've got 30 frames named: 'explosion_0001-large' to 'explosion_0030-large'
* You could use this function to generate those by doing: Phaser.Animation.generateFrameNames('explosion_', 1, 30, '-large', 4);
*
* @method Phaser.Animation.generateFrameNames
* @static
* @param {string} prefix - The start of the filename. If the filename was 'explosion_0001-large' the prefix would be 'explosion_'.
* @param {number} start - The number to start sequentially counting from. If your frames are named 'explosion_0001' to 'explosion_0034' the start is 1.
* @param {number} stop - The number to count to. If your frames are named 'explosion_0001' to 'explosion_0034' the stop value is 34.
* @param {string} [suffix=''] - The end of the filename. If the filename was 'explosion_0001-large' the prefix would be '-large'.
* @param {number} [zeroPad=0] - The number of zeroes to pad the min and max values with. If your frames are named 'explosion_0001' to 'explosion_0034' then the zeroPad is 4.
* @return {string[]} An array of framenames.
*/
Phaser.Animation.generateFrameNames = function (prefix, start, stop, suffix, zeroPad) {
if (typeof suffix === 'undefined') { suffix = ''; }
var output = [];
var frame = '';
if (start < stop)
{
for (var i = start; i <= stop; i++)
{
if (typeof zeroPad === 'number')
{
// str, len, pad, dir
frame = Phaser.Utils.pad(i.toString(), zeroPad, '0', 1);
}
else
{
frame = i.toString();
}
frame = prefix + frame + suffix;
output.push(frame);
}
}
else
{
for (var i = start; i >= stop; i--)
{
if (typeof zeroPad === 'number')
{
// str, len, pad, dir
frame = Phaser.Utils.pad(i.toString(), zeroPad, '0', 1);
}
else
{
frame = i.toString();
}
frame = prefix + frame + suffix;
output.push(frame);
}
}
return output;
};
|
'use strict';
module.exports = {
set: function (v) {
this.setProperty('border-spacing', v);
},
get: function () {
return this.getPropertyValue('border-spacing');
},
enumerable: true
};
|
Meteor.startup(function () {
if (Parties.find().count() === 0) {
var parties = [
{
'name': 'Dubstep-Free Zone',
'description': 'Fast just got faster with Nexus S.'
},
{
'name': 'All dubstep all the time',
'description': 'Get it on!'
},
{
'name': 'Savage lounging',
'description': 'Leisure suit required. And only fiercest manners.'
}
];
for (var i = 0; i < parties.length; i++) {
Parties.insert(parties[i]);
}
}
});
Meteor.methods({
'postParseInstallation': function(token) {
var data = {};
if (token.gcm) {
// data['deviceType'] = 'android';
// data['pushType'] = 'gcm';
// data['GCMSenderId'] = '961358389228';
// data['deviceToken'] = 'APA91bFCZUBYtcmJtKMiydHqe9VWOVZCEla2O0mFQ9Ig9hPCqtRrpQl24tAWcBEKkUbGvfS-qBp_AtwNHyBAacZroG0Bv3zz3bbwIeG_SIkTrU3UfCvqJ610HnaMABoOzq3SfkLzhWRr';
HTTP.call( 'POST', 'https://api.parse.com/1/installations', {
headers: {
'Content-Type': 'application/json',
'X-Parse-Application-Id': 'USE-YOUR-OWN', //Meteor.settings.parse_aplicationId,
'X-Parse-REST-API-Key': 'USE-YOUR-OWN'//Meteor.settings.parse_apiKey
},
data: {
'deviceType':'android',
'pushType':'gcm',
'deviceToken':token.gcm,
'GCMSenderId':'USE-YOUR-OWN'
}
}, function( error, response ) {
if ( error ) {
console.log( error );
} else {
console.log( response );
}
});
}
else {
HTTP.call( 'POST', 'https://api.parse.com/1/installations', {
headers: {
'Content-Type': 'application/json',
'X-Parse-Application-Id': 'USE-YOUR-OWN', //Meteor.settings.parse_aplicationId,
'X-Parse-REST-API-Key': 'USE-YOUR-OWN'//Meteor.settings.parse_apiKey
},
data: {
'deviceType':'ios',
'deviceToken':token.apn,
}
}, function( error, response ) {
if ( error ) {
console.log( error );
} else {
console.log( response );
}
});
};
console.log(data);
}
});
|
import 'docs/src/modules/components/bootstrap';
// --- Post bootstrap -----
import React from 'react';
import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs';
const req = require.context('docs/src/pages/utils/popover', false, /\.md|\.js$/);
const reqSource = require.context('!raw-loader!../../docs/src/pages/utils/popover', false, /\.js$/);
const reqPrefix = 'pages/utils/popover';
function Page() {
return <MarkdownDocs req={req} reqSource={reqSource} reqPrefix={reqPrefix} />;
}
export default Page;
|
var should = require('should');
var helper = require('../support/spec_helper');
var ORM = require('../../');
describe("Event", function() {
var db = null;
var Person = null;
var triggeredHooks = {};
var checkHook = function (hook) {
triggeredHooks[hook] = false;
return function () {
triggeredHooks[hook] = Date.now();
};
};
var setup = function (hooks) {
return function (done) {
Person = db.define("person", {
name : { type: "text", required: true }
});
return helper.dropSync(Person, done);
};
};
before(function (done) {
helper.connect(function (connection) {
db = connection;
return done();
});
});
after(function () {
return db.close();
});
describe("save", function () {
before(setup());
it("should trigger when saving an instance", function (done) {
var triggered = false;
var John = new Person({
name : "John Doe"
});
John.on("save", function () {
triggered = true;
});
triggered.should.be.false;
John.save(function () {
triggered.should.be.true;
return done();
});
});
it("should trigger when saving an instance even if it fails", function (done) {
var triggered = false;
var John = new Person();
John.on("save", function (err) {
triggered = true;
err.should.be.a.Object();
err.should.have.property("msg", "required");
});
triggered.should.be.false;
John.save(function () {
triggered.should.be.true;
return done();
});
});
it("should be writable for mocking", function (done) {
var triggered = false;
var John = new Person();
John.on = function(event, cb) {
triggered = true;
};
triggered.should.be.false;
John.on("mocked", function (err) {} );
triggered.should.be.true;
done();
});
});
});
|
var net = require('net');
var chatServer = net.createServer();
clientList = [];
chatServer.on("connection", function(client) {
client.write('Hi!\n');
client.name = client.remoteAddress + ":" + client.remotePort;
client.write('Hi' + client.name + '\n');
clientList.push(client);
client.on('data', function(data) {
broadcast(data, client);
});
//客户端退出
client.on('end', function() {
console.log(client.name + " quit");
clientList.splice(clientList.indexOf(client), 1);
});
//记录错误日志
client.on('error', function(e) {
console.log(e);
})
});
function broadcast(msg, client) {
var cleanup = [];
for (var i = 0, clen = clientList.length; i < clen; i++) {
if (client !== clientList[i]) {
//检查socket是否可写
if (clientList[i].writable) {
clientList[i].write(client.name + " says " + msg + "\n");
} else {
cleanup.push(clientList[i]);
clientList[i].destroy(); //对断开连接的socket进行销毁
}
}
}
//在写入循环中删除死节点,消除垃圾索引
for (var i = 0, clenuplen = cleanup.length; i < clenuplen; i++) {
clientList.splice(clientList.indexOf(cleanup[i]), 1);
}
}
chatServer.listen(9000); |
const { readFileToArray } = require('./utils');
day1b();
async function day1b(frequencyMap = {}, currentFrequency = 0) {
const frequencies = await readFileToArray('./day1-input.txt', function (line) {
return Number(line);
})
frequencies.reduce((acc, item) => {
currentFrequency += item;
if (!acc[currentFrequency]) {
acc[currentFrequency] = 1
return acc;
}
console.log(currentFrequency);
process.exit(0);
}, frequencyMap);
day1b(frequencyMap, currentFrequency);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.