code stringlengths 2 1.05M |
|---|
module.exports = {
// Function to test if device is iOS 7 or later
isiOS7Plus : function() {
// iOS-specific test
if (Titanium.Platform.name == 'iPhone OS') {
var version = Titanium.Platform.version.split(".");
var major = parseInt(version[0], 10);
// Can only test this support on a 3.2+ device
if (major >= 7) {
return true;
}
}
return false;
}
};
|
/**
* Creates a Max Heap Data Structure and provide push and pop methods
* @param {Array} list List of elements to initialize the heap with
*/
const MaxHeap = function(list) {
const heap = [];
/**
* Swap the two elements at the given positions
* @param {Number} x Position of first element
* @param {Number} y Position of second element
*/
const swap = function(x, y) {
const item = heap[x];
heap[x] = heap[y];
heap[y] = item;
}
/**
* Inserts an element in the heap at the proper place
* @param {Any} item Item to be inserted to the heap
*/
this.push = function(item) {
heap.push(item);
let pos = heap.length;
/**
* Swap the element with its parent until it is greater than its parent
*/
while(parseInt(pos/2 -1) >= 0 && heap[parseInt(pos/2 -1)] < heap[parseInt(pos-1)]) {
swap(parseInt(pos/2 -1), parseInt(pos-1));
pos = parseInt(pos/2);
}
}
/**
* Removes the top element from the heap (returns the largest element from the heap)
*/
this.pop = function() {
if(this.empty())
throw "No Such Element Found Exception.";
/**
* Replace the top element with the last element in the heap
*/
const item = heap[0];
heap[0] = heap[heap.length-1];
heap.pop();
const pos = 1;
/**
* Replace the element with largest of its two children until it is smaller than any of its children
*/
while(pos*2-1 < heap.length) {
if(pos*2 < heap.length) {
if(heap[pos*2] < heap[pos*2-1]) {
if(heap[pos-1] >= heap[pos*2-1]) break;
swap(pos-1, pos*2-1);
pos = pos*2;
} else {
if(heap[pos-1] >= heap[pos*2]) break;
swap(pos-1, pos*2);
pos = pos*2+1;
}
} else {
if(heap[pos-1] >= heap[pos*2-1]) break;
swap(pos-1, pos*2-1);
pos = pos*2;
}
}
return item;
}
/**
* Returns true if the heap is empty otherwise false
*/
this.empty = function() {
return heap.length == 0;
}
/**
* Initialize the head with given array
*/
if(typeof list == "object") {
for(const item of list)
this.push(item);
}
} |
/**
* Very simple in-browser unit-test library, with zero deps.
*
* Background turns green if all tests pass, otherwise red.
* View the JavaScript console to see failure reasons.
*
* Example:
*
* adder.js (code under test)
*
* function add(a, b) {
* return a + b;
* }
*
* adder-test.html (tests - just open a browser to see results)
*
* <script src="tinytest.js"></script>
* <script src="adder.js"></script>
* <script>
*
* tests({
*
* 'adds numbers': function() {
* eq(6, add(2, 4));
* eq(6.6, add(2.6, 4));
* },
*
* 'subtracts numbers': function() {
* eq(-2, add(2, -4));
* },
*
* });
* </script>
*
* That's it. Stop using over complicated frameworks that get in your way.
*
* -Joe Walnes
* MIT License. See https://github.com/joewalnes/jstinytest/
*/
var TinyTestHelper = {
renderStats: function (tests,failures) {
var numberOfTests = Object.keys(tests).length;
var successes = numberOfTests - failures;
var summaryString = 'Ran' + numberOfTests
+ ', Successes: '
+ successes
+ ', failures: '
+ failures;
var summaryElement = document.createElement('h1');
summaryElement.textContent = summaryString;
document.body.appendChild(summaryElement);
}
}
var TinyTest = {
run: function(tests) {
var failures = 0;
for (var testName in tests) {
var testAction = tests[testName];
try {
testAction.apply(this);
console.log('%cTest:' + testName + 'OK' , "color:#22FF09; background-color:#16300E;" );
} catch (e) {
failures++;
console.groupCollapsed('%c'+ testName, "color:red;");
console.error(e.stack);
console.groupEnd();
}
}
setTimeout(function() { // Give document a chance to complete
if (window.document && document.body) {
document.body.style.backgroundColor = (failures == 0 ? '#99ff99' : '#ff9999');
}
TinyTestHelper.renderStats(tests,failures);
}, 0);
},
fail: function(msg) {
throw new Error('fail(): ' + msg);
},
assert: function(value, msg) {
if (!value) {
throw new Error('assert(): ' + msg);
}
},
assertEquals: function(expected, actual) {
if (expected != actual) {
throw new Error('assertEquals() "' + expected + '" != "' + actual + '"');
}
},
assertStrictEquals: function(expected, actual) {
if (expected !== actual) {
throw new Error('assertStrictEquals() "' + expected + '" !== "' + actual + '"');
}
},
};
var fail = TinyTest.fail.bind(TinyTest),
assert = TinyTest.assert.bind(TinyTest),
assertEquals = TinyTest.assertEquals.bind(TinyTest),
eq = TinyTest.assertEquals.bind(TinyTest), // alias for assertEquals
assertStrictEquals = TinyTest.assertStrictEquals.bind(TinyTest),
tests = TinyTest.run.bind(TinyTest);
|
'use strict';
/* Services */
// Demonstrate how to register services
// In this case it is a simple value service.
angular.module('myApp.services', []).
value('version', '0.1');
angular.module('myApp2.services', []).
value('version', '0.1');
|
//jQuery to collapse the navbar on scroll
$(window).scroll(function() {
if ($(".use-header").offset().top > 50) {
$(".navbar-fixed-top").addClass("top-nav-collapse");
} else {
$(".navbar-fixed-top").removeClass("top-nav-collapse");
}
});
//jQuery for page scrolling feature - requires jQuery Easing plugin
$(function() {
$('a.page-scroll').bind('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: $($anchor.attr('href')).offset().top
}, 1500, 'easeInOutExpo');
event.preventDefault();
});
});
|
var bootstrap__filter_8h =
[
[ "BSFilter", "classBSFilter.html", "classBSFilter" ],
[ "Mat", "bootstrap__filter_8h.html#ae601f56a556993079f730483c574356f", null ],
[ "Vec", "bootstrap__filter_8h.html#a4c7df05c6f5e8a0d15ae14bcdbc07152", null ],
[ "BSResampStyle", "bootstrap__filter_8h.html#a476b3b5754056a34ac843629c9570b49", [
[ "everytime_multinomial", "bootstrap__filter_8h.html#a476b3b5754056a34ac843629c9570b49aefd13eec9fdcde04f037a4bd3dd594aa", null ],
[ "never", "bootstrap__filter_8h.html#a476b3b5754056a34ac843629c9570b49ac7561db7a418dd39b2201dfe110ab4a4", null ],
[ "ess_multinomial", "bootstrap__filter_8h.html#a476b3b5754056a34ac843629c9570b49a9c6a482b0d50f2734e0da9f99d168098", null ]
] ]
]; |
/*
* This file defines the base webpack configuration that is shared across both
* build and testing environments. If you need to add anything to the general
* webpack config, like adding loaders for different asset types, different
* preLoaders or Plugins - they should be done here. If you are looking to add
* dev specific features, please do so in webpack.config.dev.js - if you wish
* to add test specific features, these can be done in the karma.conf.js.
*
* Note:
* This file is not called directly by webpack.
* It copied once for each plugin by parse_bundle_plugin.js
* and used as a template, with additional plugin-specific
* modifications made on top.
*/
var path = require('path');
/*
* This is a filthy hack. Do as I say, not as I do.
* Taken from: https://gist.github.com/branneman/8048520#6-the-hack
* This forces the NODE_PATH environment variable to include the main
* kolibri node_modules folder, so that even plugins being built outside
* of the kolibri folder will have access to all installed loaders, etc.
* Doing it here, rather than at command invocation, allows us to do this
* in a cross platform way, and also to avoid having to prepend it to all
* our commands that end up invoking webpack.
*/
process.env.NODE_PATH = path.resolve(path.join(__dirname, '..', '..', 'node_modules'));
require('module').Module._initPaths();
var fs = require('fs');
var path = require('path');
var webpack = require('webpack');
var merge = require('webpack-merge');
var production = process.env.NODE_ENV === 'production';
var lint = (process.env.LINT || production);
// helps convert to older string syntax for vue-loader
var combineLoaders = require('webpack-combine-loaders');
var postCSSLoader = {
loader: 'postcss-loader',
options: { config: path.resolve(__dirname, '../../postcss.config.js') }
};
var cssLoader = {
loader: 'css-loader',
options: { minimize: production, sourceMap: !production }
};
// for stylus blocks in vue files.
// note: vue-style-loader includes postcss processing
var vueStylusLoaders = [ 'vue-style-loader', cssLoader, 'stylus-loader' ];
if (lint) {
vueStylusLoaders.push('stylint-loader')
}
// for scss blocks in vue files (e.g. Keen-UI files)
var vueSassLoaders = [
'vue-style-loader', // includes postcss processing
cssLoader,
{
loader: 'sass-loader',
// prepends these variable override values to every parsed vue SASS block
options: { data: '@import "~kolibri.styles.keenVars";' }
}
];
// primary webpack config
var config = {
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: {
loaders: {
js: 'buble-loader',
stylus: combineLoaders(vueStylusLoaders),
scss: combineLoaders(vueSassLoaders),
},
// handles <mat-svg/>, <ion-svg/>, <iconic-svg/>, and <file-svg/> svg inlining
preLoaders: { html: 'svg-icon-inline-loader' }
}
},
{
test: /\.js$/,
loader: 'buble-loader',
exclude: /node_modules\/(?!(keen-ui)\/).*/
},
{
test: /\.css$/,
use: [ 'style-loader', cssLoader, postCSSLoader ]
},
{
test: /\.styl$/,
use: [ 'style-loader', cssLoader, postCSSLoader, 'stylus-loader' ]
},
{
test: /\.s[a|c]ss$/,
use: [ 'style-loader', cssLoader, postCSSLoader, 'sass-loader' ]
},
{
test: /\.(png|jpe?g|gif|svg)$/,
use: {
loader: 'url-loader',
options: { limit: 10000, name: '[name].[ext]?[hash]' }
}
},
// Use file loader to load font files.
{
test: /\.(eot|woff|ttf|woff2)$/,
use: {
loader: 'file-loader',
options: { name: '[name].[ext]?[hash]' }
}
},
// Hack to make the onloadCSS node module properly export-able.
// Not currently used - we may be able to delete this if we
// deprecate our custom KolibriModule async css loading functionality.
{
test: /fg-loadcss\/src\/onloadCSS/,
use: 'exports-loader?onloadCSS'
}
]
},
plugins: [],
resolve: {
extensions: [ ".js", ".vue", ".styl" ],
},
node: {
__filename: true
}
};
// Only lint in dev mode if LINT env is set. Always lint in production.
if (lint) {
// adds custom rules
require('./htmlhint_custom');
var lintConfig = {
module: {
rules: [
{
test: /\.(vue|js)$/,
enforce: 'pre',
use: {
loader: 'eslint-loader',
options: { failOnError: true }
},
exclude: /node_modules/
},
{
test: /\.(vue|html)/,
enforce: 'pre',
use: {
loader: 'htmlhint-loader',
options: { failOnError: true, emitAs: "error" }
},
exclude: /node_modules/
},
{
test: /\.styl$/,
enforce: 'pre',
loader: 'stylint-loader'
}
]
}
};
config = merge.smart(config, lintConfig);
}
module.exports = config;
|
var fs = require('fs');
var http = require('http');
var path = require('path');
var DocumentTitle = require('react-document-title');
var Hapi = require('hapi');
var React = require('react');
var Router = require('react-router');
var routes = require('./lib/routes');
var server = new Hapi.Server();
server.connection({
host: process.env.TARO_HOST || process.env.HOST || '0.0.0.0',
port: process.env.TARO_PORT || process.env.PORT || 5000,
routes: {
cors: 'CORS' in process.env ? !!process.env.CORS : true,
validate: {
options: {
abortEarly: false
}
}
}
});
server.route({
method: 'GET',
path: '/src/{path*}',
handler: {
directory: {
path: './src',
listing: false,
index: true
}
}
});
server.route({
method: 'GET',
path: '/static/{path*}',
handler: {
directory: {
path: './static',
listing: false,
index: true
}
}
});
var hapiReactRouter = {
register: function (server, options, next) {
server.ext('onPreResponse', function (request, reply) {
if (request.response.source) {
// Bail if this response was served from the `static/` directory.
return reply.continue();
}
// Pass in `request.path` and the router will immediately match.
Router.run(routes, request.path, function (Handler, state) {
var content = React.renderToString(React.createElement(Handler, null));
var body = template.replace('{{{content}}}', content)
.replace('{{{title}}}', DocumentTitle.rewind());
reply(body);
});
});
next();
}
};
hapiReactRouter.register.attributes = {
name: 'hapi-react-router',
version: '0.0.1'
};
server.register({
register: hapiReactRouter
}, function (err) {
if (err) {
console.error('Failed to load "hapiReactRouter" plugin: %s', err);
throw err;
}
});
var template = '';
fs.readFile('templates/index.html', function (err, templateData) {
if (err) {
return console.error(err);
}
template = templateData.toString();
server.start(function () {
console.log('Server is listening: %s', server.info.uri);
});
});
|
/**
* @author Diego Alberto Molina Vera
* @copyright 2016 - 2017
*/
/* --------------------------------- Functions --------------------------------- */
function makeThumBar(win, imgs = {}) {
const play = {
icon: imgs.play,
tooltip: 'Play',
click: () => {
win.setThumbarButtons(pauseMomment);
win.webContents.send('thumbar-controls', 'play-pause');
}
};
const prev = {
icon: imgs.prev,
tooltip: 'Prev',
click: () => win.webContents.send('thumbar-controls', 'prev')
};
const next = {
icon: imgs.next,
tooltip: 'Next',
click: () => win.webContents.send('thumbar-controls', 'next')
};
const pause = {
icon: imgs.pause,
tooltip: 'Pause',
click: () => {
win.setThumbarButtons(playMomment);
win.webContents.send('thumbar-controls', 'play-pause');
}
}
const playMomment = [prev, play, next];
const pauseMomment = [prev, pause, next];
return {
playMomment,
pauseMomment
};
}
module.exports = Object.freeze({
makeThumBar
}); |
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports._wireObjectInstance = void 0;
const _injectPropertiesAndLookUpMethods_1 = require("../properties/_injectPropertiesAndLookUpMethods");
const _injectAliasFactory_1 = require("../alias/_injectAliasFactory");
const inject_1 = require("../../inject/inject");
const _injectFactoryObject_1 = require("../factories/_injectFactoryObject");
const _invokeBootStrapMethod_1 = require("../methods/_invokeBootStrapMethod");
const _invokeInitMethod_1 = require("../methods/_invokeInitMethod");
const _injectAlias_1 = require("../alias/_injectAlias");
function _wireObjectInstance(instance, definition, objectId) {
if (instance[inject_1.IsWiredSymbol]) {
return;
}
//inject properties and look up methods
_injectPropertiesAndLookUpMethods_1._injectPropertiesAndLookUpMethods.call(this, instance, definition, objectId);
_injectFactoryObject_1._injectFactoryObject.call(this, instance, objectId);
_injectAlias_1._injectAlias.call(this, definition, instance);
_injectAliasFactory_1._injectAliasFactory.call(this, definition, instance);
_invokeInitMethod_1._invokeInitMethod.call(this, instance, definition);
_invokeBootStrapMethod_1._invokeBootStrapMethod.call(this, instance, definition);
instance[inject_1.IsWiredSymbol] = true;
}
exports._wireObjectInstance = _wireObjectInstance;
//# sourceMappingURL=_wireObjectInstance.js.map |
app.controller('index', ['$scope','indexlist', function($scope,indexlist){
//类别
$scope.type = ["首页","企业简介","产品中心","新闻中心","在线留言","联系我们"];
$scope.states = ["关闭","开启"];
indexlist.load('seo',$scope);
}]); |
var keystone = require('keystone'),
async = require('async'),
sanitizer=require("sanitizer"),
wally=false,
snowcoins = require('wallets'),
snowlist = snowcoins.get('lists'),
moduleDir = snowcoins.get('moduleDir'),
ledger = require(moduleDir + '/lib/snowcoins/d3c/ledger.js'),
tx = require(moduleDir + '/lib/snowcoins/d3c/tx.js'),
status = require(moduleDir + '/lib/snowcoins/d3c/status.js'),
fetch = require(moduleDir + '/lib/snowcoins/d3c/fetch.js'),
snowauth = require(moduleDir + '/lib/snowcoins/d3c/snowauth.js'),
_ = require('lodash'),
moment = require('moment');
var commands = {
ledger: {
create:ledger.create,
cancel:ledger.cancel,
modify:ledger.modify,
additem:ledger.additem,
deleteitem:ledger.deleteitem,
find:fetch.ledger
},
transaction: {
create:tx.create,
cancel:tx.cancel,
modify:tx.modify,
additem:ledger.additem,
addaddress:tx.addaddress,
deleteitem:ledger.deleteitem,
find:ledger.find
},
status: ['system','ledger','transaction'],
find: {
ledger:fetch.ledger,
wallets:fetch.receivers,
clients:fetch.clients,
currencyrates:fetch.rates,
accounts:fetch.attendedaccounts,
addresses:fetch.attendedaddresses
},
}
exports = module.exports = function(req, res) {
var gettime = new Date(),
time = moment(gettime).format('MMM Do YYYY h:mm:ss a zz'),
unixtime=gettime.getTime();
var user='';
var Wallet = snowlist.wallets;
var ClientConnect = snowlist.clients;
var CurrentWallets = snowlist.attended;
var Offline = snowlist.offline;
async.series([
function(next) {
if(req.params.apikey) {
var options = {
ip:req.ip,
key:req.params.apikey
}
snowauth.init(options);
snowauth.auth(function(err,resp){
if(err)
return res.apiResponse({ success: false, error:err});
else {
ledger.init();
fetch.init();
tx.init();
next();
}
});
} else {
return res.apiResponse({ success: false, error:'API key required'});
}
},
function(next) {
/**
* check for a valid command and execute
* */
//console.log('sc command.req',req)
if(req.query.command) {
if(!req.query.action)return res.apiResponse({ success: false,time:time, unixtime:unixtime, err:'I received a command without an action.',command:req.query.command+'.null'});
if(commands[req.query.command][req.query.action]) {
//run the command
req.query.apikey=req.params.apikey;
var fn = commands[req.query.command][req.query.action];
fn(req.query,function(err,resp) {
if(err) {
return res.apiResponse({ success: false, error:err,time:time, unixtime:unixtime, command:req.query.command+'.'+req.query.action+''});
} else {
//if( req.query.action=='currencyrates')console.log(resp,'rates api return');
var ll = resp ? resp.length : 0
return res.apiResponse({ success: true, time:time, results:ll, data: resp, unixtime:unixtime, command:req.query.command+'.'+req.query.action+'',query:req.query});
}
});
} else {
return res.apiResponse({ success: false,time:time, unixtime:unixtime, error:'Bad command & action pair. commands.'+req.query.command+'.'+req.query.action,command:req.query.command+'.'+req.query.action+''});
}
} else {
// no command. pass through and send a welcome message
next();
}
}],
function(err) {
return res.apiResponse({ success: true,time:time, unixtime:unixtime, message:'Welcome. You passed a successful nonce. Next time try a command.'});
});
}
|
"use strict";
var arrays = require("../../utils/arrays"),
asts = require("../asts"),
op = require("../opcodes"),
js = require("../javascript");
/* Generates parser JavaScript code. */
function generateJavascript(ast, options) {
/* These only indent non-empty lines to avoid trailing whitespace. */
function indent2(code) { return code.replace(/^(.+)$/gm, ' $1'); }
function indent4(code) { return code.replace(/^(.+)$/gm, ' $1'); }
function indent8(code) { return code.replace(/^(.+)$/gm, ' $1'); }
function indent10(code) { return code.replace(/^(.+)$/gm, ' $1'); }
function generateTables() {
if (options.optimize === "size") {
return [
'peg$consts = [',
indent2(ast.consts.join(',\n')),
'],',
'',
'peg$bytecode = [',
indent2(arrays.map(ast.rules, function(rule) {
return 'peg$decode("'
+ js.stringEscape(arrays.map(
rule.bytecode,
function(b) { return String.fromCharCode(b + 32); }
).join(''))
+ '")';
}).join(',\n')),
'],'
].join('\n');
} else {
return arrays.map(
ast.consts,
function(c, i) { return 'peg$c' + i + ' = ' + c + ','; }
).join('\n');
}
}
function generateRuleHeader(ruleNameCode, ruleIndexCode) {
var parts = [];
parts.push('');
if (options.trace) {
parts.push([
'peg$tracer.trace({',
' type: "rule.enter",',
' rule: ' + ruleNameCode + ',',
' location: peg$computeLocation(startPos, startPos)',
'});',
''
].join('\n'));
}
if (options.cache) {
parts.push([
'var key = peg$currPos * ' + ast.rules.length + ' + ' + ruleIndexCode + ',',
' cached = peg$resultsCache[key];',
'',
'if (cached) {',
' peg$currPos = cached.nextPos;',
'',
].join('\n'));
if (options.trace) {
parts.push([
'if (cached.result !== peg$FAILED) {',
' peg$tracer.trace({',
' type: "rule.match",',
' rule: ' + ruleNameCode + ',',
' result: cached.result,',
' location: peg$computeLocation(startPos, peg$currPos)',
' });',
'} else {',
' peg$tracer.trace({',
' type: "rule.fail",',
' rule: ' + ruleNameCode + ',',
' location: peg$computeLocation(startPos, startPos)',
' });',
'}',
''
].join('\n'));
}
parts.push([
' return cached.result;',
'}',
''
].join('\n'));
}
return parts.join('\n');
}
function generateRuleFooter(ruleNameCode, resultCode) {
var parts = [];
if (options.cache) {
parts.push([
'',
'peg$resultsCache[key] = { nextPos: peg$currPos, result: ' + resultCode + ' };'
].join('\n'));
}
if (options.trace) {
parts.push([
'',
'if (' + resultCode + ' !== peg$FAILED) {',
' peg$tracer.trace({',
' type: "rule.match",',
' rule: ' + ruleNameCode + ',',
' result: ' + resultCode + ',',
' location: peg$computeLocation(startPos, peg$currPos)',
' });',
'} else {',
' peg$tracer.trace({',
' type: "rule.fail",',
' rule: ' + ruleNameCode + ',',
' location: peg$computeLocation(startPos, startPos)',
' });',
'}'
].join('\n'));
}
parts.push([
'',
'return ' + resultCode + ';'
].join('\n'));
return parts.join('\n');
}
function generateInterpreter() {
var parts = [];
function generateCondition(cond, argsLength) {
var baseLength = argsLength + 3,
thenLengthCode = 'bc[ip + ' + (baseLength - 2) + ']',
elseLengthCode = 'bc[ip + ' + (baseLength - 1) + ']';
return [
'ends.push(end);',
'ips.push(ip + ' + baseLength + ' + ' + thenLengthCode + ' + ' + elseLengthCode + ');',
'',
'if (' + cond + ') {',
' end = ip + ' + baseLength + ' + ' + thenLengthCode + ';',
' ip += ' + baseLength + ';',
'} else {',
' end = ip + ' + baseLength + ' + ' + thenLengthCode + ' + ' + elseLengthCode + ';',
' ip += ' + baseLength + ' + ' + thenLengthCode + ';',
'}',
'',
'break;'
].join('\n');
}
function generateLoop(cond) {
var baseLength = 2,
bodyLengthCode = 'bc[ip + ' + (baseLength - 1) + ']';
return [
'if (' + cond + ') {',
' ends.push(end);',
' ips.push(ip);',
'',
' end = ip + ' + baseLength + ' + ' + bodyLengthCode + ';',
' ip += ' + baseLength + ';',
'} else {',
' ip += ' + baseLength + ' + ' + bodyLengthCode + ';',
'}',
'',
'break;'
].join('\n');
}
function generateCall() {
var baseLength = 4,
paramsLengthCode = 'bc[ip + ' + (baseLength - 1) + ']';
return [
'params = bc.slice(ip + ' + baseLength + ', ip + ' + baseLength + ' + ' + paramsLengthCode + ');',
'for (i = 0; i < ' + paramsLengthCode + '; i++) {',
' params[i] = stack[stack.length - 1 - params[i]];',
'}',
'',
'stack.splice(',
' stack.length - bc[ip + 2],',
' bc[ip + 2],',
' peg$consts[bc[ip + 1]].apply(null, params)',
');',
'',
'ip += ' + baseLength + ' + ' + paramsLengthCode + ';',
'break;'
].join('\n');
}
parts.push([
'function peg$decode(s) {',
' var bc = new Array(s.length), i;',
'',
' for (i = 0; i < s.length; i++) {',
' bc[i] = s.charCodeAt(i) - 32;',
' }',
'',
' return bc;',
'}',
'',
'function peg$parseRule(index) {',
].join('\n'));
if (options.trace) {
parts.push([
' var bc = peg$bytecode[index],',
' ip = 0,',
' ips = [],',
' end = bc.length,',
' ends = [],',
' stack = [],',
' startPos = peg$currPos,',
' params, i;',
].join('\n'));
} else {
parts.push([
' var bc = peg$bytecode[index],',
' ip = 0,',
' ips = [],',
' end = bc.length,',
' ends = [],',
' stack = [],',
' params, i;',
].join('\n'));
}
parts.push(indent2(generateRuleHeader('peg$ruleNames[index]', 'index')));
parts.push([
/*
* The point of the outer loop and the |ips| & |ends| stacks is to avoid
* recursive calls for interpreting parts of bytecode. In other words, we
* implement the |interpret| operation of the abstract machine without
* function calls. Such calls would likely slow the parser down and more
* importantly cause stack overflows for complex grammars.
*/
' while (true) {',
' while (ip < end) {',
' switch (bc[ip]) {',
' case ' + op.PUSH + ':', // PUSH c
' stack.push(peg$consts[bc[ip + 1]]);',
' ip += 2;',
' break;',
'',
' case ' + op.PUSH_UNDEFINED + ':', // PUSH_UNDEFINED
' stack.push(void 0);',
' ip++;',
' break;',
'',
' case ' + op.PUSH_NULL + ':', // PUSH_NULL
' stack.push(null);',
' ip++;',
' break;',
'',
' case ' + op.PUSH_FAILED + ':', // PUSH_FAILED
' stack.push(peg$FAILED);',
' ip++;',
' break;',
'',
' case ' + op.PUSH_EMPTY_ARRAY + ':', // PUSH_EMPTY_ARRAY
' stack.push([]);',
' ip++;',
' break;',
'',
' case ' + op.PUSH_CURR_POS + ':', // PUSH_CURR_POS
' stack.push(peg$currPos);',
' ip++;',
' break;',
'',
' case ' + op.POP + ':', // POP
' stack.pop();',
' ip++;',
' break;',
'',
' case ' + op.POP_CURR_POS + ':', // POP_CURR_POS
' peg$currPos = stack.pop();',
' ip++;',
' break;',
'',
' case ' + op.POP_N + ':', // POP_N n
' stack.length -= bc[ip + 1];',
' ip += 2;',
' break;',
'',
' case ' + op.NIP + ':', // NIP
' stack.splice(-2, 1);',
' ip++;',
' break;',
'',
' case ' + op.APPEND + ':', // APPEND
' stack[stack.length - 2].push(stack.pop());',
' ip++;',
' break;',
'',
' case ' + op.WRAP + ':', // WRAP n
' stack.push(stack.splice(stack.length - bc[ip + 1], bc[ip + 1]));',
' ip += 2;',
' break;',
'',
' case ' + op.TEXT + ':', // TEXT
' stack.push(input.substring(stack.pop(), peg$currPos));',
' ip++;',
' break;',
'',
' case ' + op.IF + ':', // IF t, f
indent10(generateCondition('stack[stack.length - 1]', 0)),
'',
' case ' + op.IF_ERROR + ':', // IF_ERROR t, f
indent10(generateCondition(
'stack[stack.length - 1] === peg$FAILED',
0
)),
'',
' case ' + op.IF_NOT_ERROR + ':', // IF_NOT_ERROR t, f
indent10(
generateCondition('stack[stack.length - 1] !== peg$FAILED',
0
)),
'',
' case ' + op.WHILE_NOT_ERROR + ':', // WHILE_NOT_ERROR b
indent10(generateLoop('stack[stack.length - 1] !== peg$FAILED')),
'',
' case ' + op.MATCH_ANY + ':', // MATCH_ANY a, f, ...
indent10(generateCondition('input.length > peg$currPos', 0)),
'',
' case ' + op.MATCH_STRING + ':', // MATCH_STRING s, a, f, ...
indent10(generateCondition(
'input.substr(peg$currPos, peg$consts[bc[ip + 1]].length) === peg$consts[bc[ip + 1]]',
1
)),
'',
' case ' + op.MATCH_STRING_IC + ':', // MATCH_STRING_IC s, a, f, ...
indent10(generateCondition(
'input.substr(peg$currPos, peg$consts[bc[ip + 1]].length).toLowerCase() === peg$consts[bc[ip + 1]]',
1
)),
'',
' case ' + op.MATCH_REGEXP + ':', // MATCH_REGEXP r, a, f, ...
indent10(generateCondition(
'peg$consts[bc[ip + 1]].test(input.charAt(peg$currPos))',
1
)),
'',
' case ' + op.ACCEPT_N + ':', // ACCEPT_N n
' stack.push(input.substr(peg$currPos, bc[ip + 1]));',
' peg$currPos += bc[ip + 1];',
' ip += 2;',
' break;',
'',
' case ' + op.ACCEPT_STRING + ':', // ACCEPT_STRING s
' stack.push(peg$consts[bc[ip + 1]]);',
' peg$currPos += peg$consts[bc[ip + 1]].length;',
' ip += 2;',
' break;',
'',
' case ' + op.FAIL + ':', // FAIL e
' stack.push(peg$FAILED);',
' if (peg$silentFails === 0) {',
' peg$fail(peg$consts[bc[ip + 1]]);',
' }',
' ip += 2;',
' break;',
'',
' case ' + op.LOAD_SAVED_POS + ':', // LOAD_SAVED_POS p
' peg$savedPos = stack[stack.length - 1 - bc[ip + 1]];',
' ip += 2;',
' break;',
'',
' case ' + op.UPDATE_SAVED_POS + ':', // UPDATE_SAVED_POS
' peg$savedPos = peg$currPos;',
' ip++;',
' break;',
'',
' case ' + op.CALL + ':', // CALL f, n, pc, p1, p2, ..., pN
indent10(generateCall()),
'',
' case ' + op.RULE + ':', // RULE r
' stack.push(peg$parseRule(bc[ip + 1]));',
' ip += 2;',
' break;',
'',
' case ' + op.SILENT_FAILS_ON + ':', // SILENT_FAILS_ON
' peg$silentFails++;',
' ip++;',
' break;',
'',
' case ' + op.SILENT_FAILS_OFF + ':', // SILENT_FAILS_OFF
' peg$silentFails--;',
' ip++;',
' break;',
'',
' default:',
' throw new Error("Invalid opcode: " + bc[ip] + ".");',
' }',
' }',
'',
' if (ends.length > 0) {',
' end = ends.pop();',
' ip = ips.pop();',
' } else {',
' break;',
' }',
' }'
].join('\n'));
parts.push(indent2(generateRuleFooter('peg$ruleNames[index]', 'stack[0]')));
parts.push('}');
return parts.join('\n');
}
function generateRuleFunction(rule) {
var parts = [], code;
function c(i) { return "peg$c" + i; } // |consts[i]| of the abstract machine
function s(i) { return "s" + i; } // |stack[i]| of the abstract machine
var stack = {
sp: -1,
maxSp: -1,
push: function(exprCode) {
var code = s(++this.sp) + ' = ' + exprCode + ';';
if (this.sp > this.maxSp) { this.maxSp = this.sp; }
return code;
},
pop: function() {
var n, values;
if (arguments.length === 0) {
return s(this.sp--);
} else {
n = arguments[0];
values = arrays.map(arrays.range(this.sp - n + 1, this.sp + 1), s);
this.sp -= n;
return values;
}
},
top: function() {
return s(this.sp);
},
index: function(i) {
return s(this.sp - i);
}
};
function compile(bc) {
var ip = 0,
end = bc.length,
parts = [],
value;
function compileCondition(cond, argCount) {
var baseLength = argCount + 3,
thenLength = bc[ip + baseLength - 2],
elseLength = bc[ip + baseLength - 1],
baseSp = stack.sp,
thenCode, elseCode, thenSp, elseSp;
ip += baseLength;
thenCode = compile(bc.slice(ip, ip + thenLength));
thenSp = stack.sp;
ip += thenLength;
if (elseLength > 0) {
stack.sp = baseSp;
elseCode = compile(bc.slice(ip, ip + elseLength));
elseSp = stack.sp;
ip += elseLength;
if (thenSp !== elseSp) {
throw new Error(
"Branches of a condition must move the stack pointer in the same way."
);
}
}
parts.push('if (' + cond + ') {');
parts.push(indent2(thenCode));
if (elseLength > 0) {
parts.push('} else {');
parts.push(indent2(elseCode));
}
parts.push('}');
}
function compileLoop(cond) {
var baseLength = 2,
bodyLength = bc[ip + baseLength - 1],
baseSp = stack.sp,
bodyCode, bodySp;
ip += baseLength;
bodyCode = compile(bc.slice(ip, ip + bodyLength));
bodySp = stack.sp;
ip += bodyLength;
if (bodySp !== baseSp) {
throw new Error("Body of a loop can't move the stack pointer.");
}
parts.push('while (' + cond + ') {');
parts.push(indent2(bodyCode));
parts.push('}');
}
function compileCall() {
var baseLength = 4,
paramsLength = bc[ip + baseLength - 1];
var value = c(bc[ip + 1]) + '('
+ arrays.map(
bc.slice(ip + baseLength, ip + baseLength + paramsLength),
function(p) { return stack.index(p); }
).join(', ')
+ ')';
stack.pop(bc[ip + 2]);
parts.push(stack.push(value));
ip += baseLength + paramsLength;
}
while (ip < end) {
switch (bc[ip]) {
case op.PUSH: // PUSH c
parts.push(stack.push(c(bc[ip + 1])));
ip += 2;
break;
case op.PUSH_CURR_POS: // PUSH_CURR_POS
parts.push(stack.push('peg$currPos'));
ip++;
break;
case op.PUSH_UNDEFINED: // PUSH_UNDEFINED
parts.push(stack.push('void 0'));
ip++;
break;
case op.PUSH_NULL: // PUSH_NULL
parts.push(stack.push('null'));
ip++;
break;
case op.PUSH_FAILED: // PUSH_FAILED
parts.push(stack.push('peg$FAILED'));
ip++;
break;
case op.PUSH_EMPTY_ARRAY: // PUSH_EMPTY_ARRAY
parts.push(stack.push('[]'));
ip++;
break;
case op.POP: // POP
stack.pop();
ip++;
break;
case op.POP_CURR_POS: // POP_CURR_POS
parts.push('peg$currPos = ' + stack.pop() + ';');
ip++;
break;
case op.POP_N: // POP_N n
stack.pop(bc[ip + 1]);
ip += 2;
break;
case op.NIP: // NIP
value = stack.pop();
stack.pop();
parts.push(stack.push(value));
ip++;
break;
case op.APPEND: // APPEND
value = stack.pop();
parts.push(stack.top() + '.push(' + value + ');');
ip++;
break;
case op.WRAP: // WRAP n
parts.push(
stack.push('[' + stack.pop(bc[ip + 1]).join(', ') + ']')
);
ip += 2;
break;
case op.TEXT: // TEXT
parts.push(
stack.push('input.substring(' + stack.pop() + ', peg$currPos)')
);
ip++;
break;
case op.IF: // IF t, f
compileCondition(stack.top(), 0);
break;
case op.IF_ERROR: // IF_ERROR t, f
compileCondition(stack.top() + ' === peg$FAILED', 0);
break;
case op.IF_NOT_ERROR: // IF_NOT_ERROR t, f
compileCondition(stack.top() + ' !== peg$FAILED', 0);
break;
case op.WHILE_NOT_ERROR: // WHILE_NOT_ERROR b
compileLoop(stack.top() + ' !== peg$FAILED', 0);
break;
case op.MATCH_ANY: // MATCH_ANY a, f, ...
compileCondition('input.length > peg$currPos', 0);
break;
case op.MATCH_STRING: // MATCH_STRING s, a, f, ...
compileCondition(
eval(ast.consts[bc[ip + 1]]).length > 1
? 'input.substr(peg$currPos, '
+ eval(ast.consts[bc[ip + 1]]).length
+ ') === '
+ c(bc[ip + 1])
: 'input.charCodeAt(peg$currPos) === '
+ eval(ast.consts[bc[ip + 1]]).charCodeAt(0),
1
);
break;
case op.MATCH_STRING_IC: // MATCH_STRING_IC s, a, f, ...
compileCondition(
'input.substr(peg$currPos, '
+ eval(ast.consts[bc[ip + 1]]).length
+ ').toLowerCase() === '
+ c(bc[ip + 1]),
1
);
break;
case op.MATCH_REGEXP: // MATCH_REGEXP r, a, f, ...
compileCondition(
c(bc[ip + 1]) + '.test(input.charAt(peg$currPos))',
1
);
break;
case op.ACCEPT_N: // ACCEPT_N n
parts.push(stack.push(
bc[ip + 1] > 1
? 'input.substr(peg$currPos, ' + bc[ip + 1] + ')'
: 'input.charAt(peg$currPos)'
));
parts.push(
bc[ip + 1] > 1
? 'peg$currPos += ' + bc[ip + 1] + ';'
: 'peg$currPos++;'
);
ip += 2;
break;
case op.ACCEPT_STRING: // ACCEPT_STRING s
parts.push(stack.push(c(bc[ip + 1])));
parts.push(
eval(ast.consts[bc[ip + 1]]).length > 1
? 'peg$currPos += ' + eval(ast.consts[bc[ip + 1]]).length + ';'
: 'peg$currPos++;'
);
ip += 2;
break;
case op.FAIL: // FAIL e
parts.push(stack.push('peg$FAILED'));
parts.push('if (peg$silentFails === 0) { peg$fail(' + c(bc[ip + 1]) + '); }');
ip += 2;
break;
case op.LOAD_SAVED_POS: // LOAD_SAVED_POS p
parts.push('peg$savedPos = ' + stack.index(bc[ip + 1]) + ';');
ip += 2;
break;
case op.UPDATE_SAVED_POS: // UPDATE_SAVED_POS
parts.push('peg$savedPos = peg$currPos;');
ip++;
break;
case op.CALL: // CALL f, n, pc, p1, p2, ..., pN
compileCall();
break;
case op.RULE: // RULE r
parts.push(stack.push("peg$parse" + ast.rules[bc[ip + 1]].name + "()"));
ip += 2;
break;
case op.SILENT_FAILS_ON: // SILENT_FAILS_ON
parts.push('peg$silentFails++;');
ip++;
break;
case op.SILENT_FAILS_OFF: // SILENT_FAILS_OFF
parts.push('peg$silentFails--;');
ip++;
break;
default:
throw new Error("Invalid opcode: " + bc[ip] + ".");
}
}
return parts.join('\n');
}
code = compile(rule.bytecode);
parts.push('function peg$parse' + rule.name + '() {');
if (options.trace) {
parts.push([
' var ' + arrays.map(arrays.range(0, stack.maxSp + 1), s).join(', ') + ',',
' startPos = peg$currPos;'
].join('\n'));
} else {
parts.push(
' var ' + arrays.map(arrays.range(0, stack.maxSp + 1), s).join(', ') + ';'
);
}
parts.push(indent2(generateRuleHeader(
'"' + js.stringEscape(rule.name) + '"',
asts.indexOfRule(ast, rule.name)
)));
parts.push(indent2(code));
parts.push(indent2(generateRuleFooter(
'"' + js.stringEscape(rule.name) + '"',
s(0)
)));
parts.push('}');
return parts.join('\n');
}
var parts = [],
startRuleIndices, startRuleIndex,
startRuleFunctions, startRuleFunction,
ruleNames;
parts.push([
'(function() {',
' "use strict";',
'',
' /*',
' * Generated by PEG.js 0.8.0.',
' *',
' * http://pegjs.org/',
' */',
'',
' function peg$subclass(child, parent) {',
' function ctor() { this.constructor = child; }',
' ctor.prototype = parent.prototype;',
' child.prototype = new ctor();',
' }',
'',
' function peg$SyntaxError(message, expected, found, location) {',
' this.message = message;',
' this.expected = expected;',
' this.found = found;',
' this.location = location;',
'',
' this.name = "SyntaxError";',
' }',
'',
' peg$subclass(peg$SyntaxError, Error);',
''
].join('\n'));
if (options.trace) {
parts.push([
' function peg$DefaultTracer() {',
' this.indentLevel = 0;',
' }',
'',
' peg$DefaultTracer.prototype.trace = function(event) {',
' var that = this;',
'',
' function log(event) {',
' function repeat(string, n) {',
' var result = "", i;',
'',
' for (i = 0; i < n; i++) {',
' result += string;',
' }',
'',
' return result;',
' }',
'',
' function pad(string, length) {',
' return string + repeat(" ", length - string.length);',
' }',
'',
' console.log(',
' event.location.start.line + ":" + event.location.start.column + "-"',
' + event.location.end.line + ":" + event.location.end.column + " "',
' + pad(event.type, 10) + " "',
' + repeat(" ", that.indentLevel) + event.rule',
' );',
' }',
'',
' switch (event.type) {',
' case "rule.enter":',
' log(event);',
' this.indentLevel++;',
' break;',
'',
' case "rule.match":',
' this.indentLevel--;',
' log(event);',
' break;',
'',
' case "rule.fail":',
' this.indentLevel--;',
' log(event);',
' break;',
'',
' default:',
' throw new Error("Invalid event type: " + event.type + ".");',
' }',
' };',
''
].join('\n'));
}
parts.push([
' function peg$parse(input) {',
' var options = arguments.length > 1 ? arguments[1] : {},',
' parser = this,',
'',
' peg$FAILED = {},',
''
].join('\n'));
if (options.optimize === "size") {
startRuleIndices = '{ '
+ arrays.map(
options.allowedStartRules,
function(r) { return r + ': ' + asts.indexOfRule(ast, r); }
).join(', ')
+ ' }';
startRuleIndex = asts.indexOfRule(ast, options.allowedStartRules[0]);
parts.push([
' peg$startRuleIndices = ' + startRuleIndices + ',',
' peg$startRuleIndex = ' + startRuleIndex + ','
].join('\n'));
} else {
startRuleFunctions = '{ '
+ arrays.map(
options.allowedStartRules,
function(r) { return r + ': peg$parse' + r; }
).join(', ')
+ ' }';
startRuleFunction = 'peg$parse' + options.allowedStartRules[0];
parts.push([
' peg$startRuleFunctions = ' + startRuleFunctions + ',',
' peg$startRuleFunction = ' + startRuleFunction + ','
].join('\n'));
}
parts.push('');
parts.push(indent8(generateTables()));
parts.push([
'',
' peg$currPos = 0,',
' peg$savedPos = 0,',
' peg$posDetailsCache = [{ line: 1, column: 1, seenCR: false }],',
' peg$maxFailPos = 0,',
' peg$maxFailExpected = [],',
' peg$silentFails = 0,', // 0 = report failures, > 0 = silence failures
''
].join('\n'));
if (options.cache) {
parts.push([
' peg$resultsCache = {},',
''
].join('\n'));
}
if (options.trace) {
if (options.optimize === "size") {
ruleNames = '['
+ arrays.map(
ast.rules,
function(r) { return '"' + js.stringEscape(r.name) + '"'; }
).join(', ')
+ ']';
parts.push([
' peg$ruleNames = ' + ruleNames + ',',
''
].join('\n'));
}
parts.push([
' peg$tracer = "tracer" in options ? options.tracer : new peg$DefaultTracer(),',
''
].join('\n'));
}
parts.push([
' peg$result;',
''
].join('\n'));
if (options.optimize === "size") {
parts.push([
' if ("startRule" in options) {',
' if (!(options.startRule in peg$startRuleIndices)) {',
' throw new Error("Can\'t start parsing from rule \\"" + options.startRule + "\\".");',
' }',
'',
' peg$startRuleIndex = peg$startRuleIndices[options.startRule];',
' }'
].join('\n'));
} else {
parts.push([
' if ("startRule" in options) {',
' if (!(options.startRule in peg$startRuleFunctions)) {',
' throw new Error("Can\'t start parsing from rule \\"" + options.startRule + "\\".");',
' }',
'',
' peg$startRuleFunction = peg$startRuleFunctions[options.startRule];',
' }'
].join('\n'));
}
parts.push([
'',
' function text() {',
' return input.substring(peg$savedPos, peg$currPos);',
' }',
'',
' function location() {',
' return peg$computeLocation(peg$savedPos, peg$currPos);',
' }',
'',
' function expected(description) {',
' throw peg$buildException(',
' null,',
' [{ type: "other", description: description }],',
' input.substring(peg$savedPos, peg$currPos),',
' peg$computeLocation(peg$savedPos, peg$currPos)',
' );',
' }',
'',
' function error(message) {',
' throw peg$buildException(',
' message,',
' null,',
' input.substring(peg$savedPos, peg$currPos),',
' peg$computeLocation(peg$savedPos, peg$currPos)',
' );',
' }',
'',
' function peg$computePosDetails(pos) {',
' var details = peg$posDetailsCache[pos],',
' p, ch;',
'',
' if (details) {',
' return details;',
' } else {',
' p = pos - 1;',
' while (!peg$posDetailsCache[p]) {',
' p--;',
' }',
'',
' details = peg$posDetailsCache[p];',
' details = {',
' line: details.line,',
' column: details.column,',
' seenCR: details.seenCR',
' };',
'',
' while (p < pos) {',
' ch = input.charAt(p);',
' if (ch === "\\n") {',
' if (!details.seenCR) { details.line++; }',
' details.column = 1;',
' details.seenCR = false;',
' } else if (ch === "\\r" || ch === "\\u2028" || ch === "\\u2029") {',
' details.line++;',
' details.column = 1;',
' details.seenCR = true;',
' } else {',
' details.column++;',
' details.seenCR = false;',
' }',
'',
' p++;',
' }',
'',
' peg$posDetailsCache[pos] = details;',
' return details;',
' }',
' }',
'',
' function peg$computeLocation(startPos, endPos) {',
' var startPosDetails = peg$computePosDetails(startPos),',
' endPosDetails = peg$computePosDetails(endPos);',
'',
' return {',
' start: {',
' offset: startPos,',
' line: startPosDetails.line,',
' column: startPosDetails.column',
' },',
' end: {',
' offset: endPos,',
' line: endPosDetails.line,',
' column: endPosDetails.column',
' }',
' };',
' }',
'',
' function peg$fail(expected) {',
' if (peg$currPos < peg$maxFailPos) { return; }',
'',
' if (peg$currPos > peg$maxFailPos) {',
' peg$maxFailPos = peg$currPos;',
' peg$maxFailExpected = [];',
' }',
'',
' peg$maxFailExpected.push(expected);',
' }',
'',
' function peg$buildException(message, expected, found, location) {',
' function cleanupExpected(expected) {',
' var i = 1;',
'',
' expected.sort(function(a, b) {',
' if (a.description < b.description) {',
' return -1;',
' } else if (a.description > b.description) {',
' return 1;',
' } else {',
' return 0;',
' }',
' });',
'',
/*
* This works because the bytecode generator guarantees that every
* expectation object exists only once, so it's enough to use |===| instead
* of deeper structural comparison.
*/
' while (i < expected.length) {',
' if (expected[i - 1] === expected[i]) {',
' expected.splice(i, 1);',
' } else {',
' i++;',
' }',
' }',
' }',
'',
' function buildMessage(expected, found) {',
' function stringEscape(s) {',
' function hex(ch) { return ch.charCodeAt(0).toString(16).toUpperCase(); }',
'',
/*
* ECMA-262, 5th ed., 7.8.4: All characters may appear literally in a string
* literal except for the closing quote character, backslash, carriage
* return, line separator, paragraph separator, and line feed. Any character
* may appear in the form of an escape sequence.
*
* For portability, we also escape all control and non-ASCII characters.
* Note that "\0" and "\v" escape sequences are not used because JSHint does
* not like the first and IE the second.
*/
' return s',
' .replace(/\\\\/g, \'\\\\\\\\\')', // backslash
' .replace(/"/g, \'\\\\"\')', // closing double quote
' .replace(/\\x08/g, \'\\\\b\')', // backspace
' .replace(/\\t/g, \'\\\\t\')', // horizontal tab
' .replace(/\\n/g, \'\\\\n\')', // line feed
' .replace(/\\f/g, \'\\\\f\')', // form feed
' .replace(/\\r/g, \'\\\\r\')', // carriage return
' .replace(/[\\x00-\\x07\\x0B\\x0E\\x0F]/g, function(ch) { return \'\\\\x0\' + hex(ch); })',
' .replace(/[\\x10-\\x1F\\x80-\\xFF]/g, function(ch) { return \'\\\\x\' + hex(ch); })',
' .replace(/[\\u0100-\\u0FFF]/g, function(ch) { return \'\\\\u0\' + hex(ch); })',
' .replace(/[\\u1000-\\uFFFF]/g, function(ch) { return \'\\\\u\' + hex(ch); });',
' }',
'',
' var expectedDescs = new Array(expected.length),',
' expectedDesc, foundDesc, i;',
'',
' for (i = 0; i < expected.length; i++) {',
' expectedDescs[i] = expected[i].description;',
' }',
'',
' expectedDesc = expected.length > 1',
' ? expectedDescs.slice(0, -1).join(", ")',
' + " or "',
' + expectedDescs[expected.length - 1]',
' : expectedDescs[0];',
'',
' foundDesc = found ? "\\"" + stringEscape(found) + "\\"" : "end of input";',
'',
' return "Expected " + expectedDesc + " but " + foundDesc + " found.";',
' }',
'',
' if (expected !== null) {',
' cleanupExpected(expected);',
' }',
'',
' return new peg$SyntaxError(',
' message !== null ? message : buildMessage(expected, found),',
' expected,',
' found,',
' location',
' );',
' }',
''
].join('\n'));
if (options.optimize === "size") {
parts.push(indent4(generateInterpreter()));
parts.push('');
} else {
arrays.each(ast.rules, function(rule) {
parts.push(indent4(generateRuleFunction(rule)));
parts.push('');
});
}
if (ast.initializer) {
parts.push(indent4(ast.initializer.code));
parts.push('');
}
if (options.optimize === "size") {
parts.push(' peg$result = peg$parseRule(peg$startRuleIndex);');
} else {
parts.push(' peg$result = peg$startRuleFunction();');
}
parts.push([
'',
' if (peg$result !== peg$FAILED && peg$currPos === input.length) {',
' return peg$result;',
' } else {',
' if (peg$result !== peg$FAILED && peg$currPos < input.length) {',
' peg$fail({ type: "end", description: "end of input" });',
' }',
'',
' throw peg$buildException(',
' null,',
' peg$maxFailExpected,',
' peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null,',
' peg$maxFailPos < input.length',
' ? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1)',
' : peg$computeLocation(peg$maxFailPos, peg$maxFailPos)',
' );',
' }',
' }',
'',
' return {',
].join('\n'));
if (options.trace) {
parts.push([
' SyntaxError: peg$SyntaxError,',
' DefaultTracer: peg$DefaultTracer,',
' parse: peg$parse'
].join('\n'));
} else {
parts.push([
' SyntaxError: peg$SyntaxError,',
' parse: peg$parse'
].join('\n'));
}
parts.push([
' };',
'})()'
].join('\n'));
ast.code = parts.join('\n');
}
module.exports = generateJavascript;
|
frappe.provide('frappe.ui.misc');
frappe.ui.misc.about = function() {
if(!frappe.ui.misc.about_dialog) {
var d = new frappe.ui.Dialog({title: __('Revalue Framework')})
$(d.body).html(repl("<div>\
<p>"+__("ERP System On Cloud & On Premises")+"</p> \
<p><i class='fa fa-globe fa-fw'></i>\
Website: <a href='http://revaluesoft.com' target='_blank'>http://revaluesoft.com</a></p>\
<hr>\
<p class='text-muted'>© 2016 Revalue Soft SAE.</p> \
</div>", frappe.app));
frappe.ui.misc.about_dialog = d;
frappe.ui.misc.about_dialog.on_page_show = function() {
if(!frappe.versions) {
frappe.call({
method: "frappe.utils.change_log.get_versions",
callback: function(r) {
show_versions(r.message);
}
})
}
};
var show_versions = function(versions) {
var $wrap = $("#about-app-versions").empty();
$.each(keys(versions).sort(), function(i, key) {
var v = versions[key];
$($.format('<p><b>{0}:</b> v{1}<br></p>',
[v.title, v.version])).appendTo($wrap);
});
frappe.versions = versions;
}
}
frappe.ui.misc.about_dialog.show();
}
|
/*
rest.js
mongodb-rest
Created by Tom de Grunt on 2010-10-03.
Copyright (c) 2010 Tom de Grunt.
This file is part of mongodb-rest.
*/
var mongo = require("mongodb"),
app = module.parent.exports.app,
config = module.parent.exports.config,
util = require("./util"),
BSON = mongo.BSONPure;
/**
* Query
*/
app.get('/:db/:collection/:id?', function(req, res) {
var query = req.query.query ? JSON.parse(req.query.query) : {};
// Providing an id overwrites giving a query in the URL
if (req.params.id) {
query = {'_id': new BSON.ObjectID(req.params.id)};
}
var options = req.params.options || {};
var test = ['limit','sort','fields','skip','hint','explain','snapshot','timeout'];
for( o in req.query ) {
if( test.indexOf(o) >= 0 ) {
options[o] = req.query[o];
}
}
var db = new mongo.Db(req.params.db, new mongo.Server(config.db.host, config.db.port, {'auto_reconnect':true}));
db.open(function(err,db) {
db.authenticate(config.db.username, config.db.password, function () {
db.collection(req.params.collection, function(err, collection) {
collection.find(query, options, function(err, cursor) {
cursor.toArray(function(err, docs){
var result = [];
if(req.params.id) {
if(docs.length > 0) {
result = util.flavorize(docs[0], "out");
res.header('Content-Type', 'application/json');
result2 = {};
result2[req.params.collection] = result;
res.send(result2);
} else {
res.send(404);
}
} else {
docs.forEach(function(doc){
result.push(util.flavorize(doc, "out"));
});
res.header('Content-Type', 'application/json');
result2 = {};
result2[req.params.collection] = result;
res.send(result2);
}
db.close();
});
});
});
});
});
});
/**
* Insert
*/
app.post('/:db/:collection', function(req, res) {
if(req.body) {
var db = new mongo.Db(req.params.db, new mongo.Server(config.db.host, config.db.port, {'auto_reconnect':true}));
db.open(function(err, db) {
db.authenticate(config.db.username, config.db.password, function () {
db.collection(req.params.collection, function(err, collection) {
// We only support inserting one document at a time
collection.insert(Array.isArray(req.body) ? req.body[0] : req.body, function(err, docs) {
res.header('Location', '/'+req.params.db+'/'+req.params.collection+'/'+docs[0]._id.toHexString());
res.header('Content-Type', 'application/json');
var result = {};
result[req.params.collection] = util.flavorize(docs[0], "out");
res.send(result);
db.close();
});
});
});
});
} else {
res.header('Content-Type', 'application/json');
res.send('{"ok":0}',200);
}
});
/**
* Update
*/
app.put('/:db/:collection/:id', function(req, res) {
var spec = {'_id': new BSON.ObjectID(req.params.id)};
var db = new mongo.Db(req.params.db, new mongo.Server(config.db.host, config.db.port, {'auto_reconnect':true}));
db.open(function(err, db) {
db.authenticate(config.db.username, config.db.password, function () {
db.collection(req.params.collection, function(err, collection) {
collection.update(spec, req.body, true, function(err, docs) {
collection.findOne({_id:new BSON.ObjectID(req.params.id)}, function(err, item) {
res.header('Content-Type', 'application/json');
var result = {};
result[req.params.collection] = util.flavorize(item, "out");
res.send(result);
db.close();
});
});
});
});
});
});
/**
* Delete
*/
app.del('/:db/:collection/:id', function(req, res) {
var spec = {'_id': new BSON.ObjectID(req.params.id)};
var db = new mongo.Db(req.params.db, new mongo.Server(config.db.host, config.db.port, {'auto_reconnect':true}));
db.open(function(err, db) {
db.authenticate(config.db.username, config.db.password, function () {
db.collection(req.params.collection, function(err, collection) {
collection.remove(spec, function(err, docs) {
res.header('Content-Type', 'application/json');
res.send('{"ok":1}');
db.close();
});
});
});
});
});
|
var path = require('path')
var binPath = require('phantomjs').path
var falafel = require('falafel')
var execFile = require('child_process').execFile
var dargs = require('dargs')
module.exports = function(url, opts, fn, done) {
if (typeof opts === 'function') {
done = fn
fn = opts
opts = {}
}
var script = path.join(__dirname, 'phantom.js')
var key = '--- ' + +Date.now() + ' ---'
function isWrapper(node) {
return (
node.type === 'FunctionExpression' &&
node.parent &&
Array.isArray(node.parent.arguments) &&
node.parent.arguments[0].value === key
)
}
if (typeof fn === 'function') {
var output = ''
falafel('(' + fn + '("' + key + '"))', function(node) {
// Pull out the contents of the surrounding body function
if (isWrapper(node)) {
for (var i = 0; i < node.body.body.length; i++) {
output += node.body.body[i].source()
}
}
})
fn = output
}
// Serialize and run phantomjs
fn = JSON.stringify(fn.toString())
var args = dargs(opts).concat([script, url, fn, key])
execFile(binPath, args, function(err, stdout, stderr) {
if (err || stderr) return done(err || new Error(stderr), null, stdout)
var data = stdout.split(key).slice(1, -1).join('').replace(/\n|\r\n/g, '')
try {
data = JSON.parse(data)
} catch (err) {
return done(new Error('Failed to parse the response from phantomjs ' + err.message), null, stdout)
}
return done(null, data, stdout)
})
}
|
Object.toJSON = function(object) {
return JSON.stringify(object);
};
|
var Zet = require('./zet')
var Serializable = require('./serialization').Serializable
module.exports = Zet.declare({
superclass: Serializable,
CLASS_ID: 'NamedSerializable',
defineBody: function (self) {
// Constructor Function
self.NAME_KEY = NAME_KEY
/** Constructor for named serializable
* @param id (optional): GUID for this object. If none given, a V4 random GUID is used.
* @param name: The name for the object
**/
self.construct = function construct(id, name) {
if (name == null) {
name = null
}
self.inherited(construct, [id])
self._name = name
}
/** Get the name for the object **/
self.getName = function getName() {
return self._name
}
/** Set the name for the object **/
self.setName = function setName(name) {
if (name == null) {
name = null
} else if (name instanceof String || typeof name === 'string') {
self._name = name
} else {
throw new Error("Set name failed, was not a string.")
}
}
/** Equality operator **/
self.eq = function eq(other) {
return (self.inherited(eq, [other]) && (self._name === other._name))
}
self.initializeFromToken = function initializeFromToken(token, context) {
self.inherited(initializeFromToken, [token, context])
self._name = untokenizeObject(token.getitem(self.NAME_KEY, true, null), context)
}
self.saveToToken = function saveToToken() {
var token = self.inherited(saveToToken)
if (self._name != null) {
token.setitem(self.NAME_KEY, tokenizeObject(self._name))
}
return token
}
}
}) |
$(function() {
$('#sample').html( langs.shell );
$('#lang').on('change', function() {
$('#sample').html(langs[ $(this).val() ]);
});
$('#demoForm').on('submit', function(e) {
e.preventDefault();
$('#demoData').fadeIn();
$('#demoMeta').text( 'Loading. ..' );
$.ajax({
url: 'https://url-meta.herokuapp.com/',
data: $(this).serialize(),
type: 'GET',
success: function(r) {
$('#demoMeta').text( JSON.stringify(r, null, 2) );
console.log(r);
},
error: function(err) {
$('#demoMeta').text( 'Some unknown error occured. Please try again.' );
console.log(err);
}
});
});
}); |
module.exports = function(grunt) {
var banner = '/*! SAFDOM v<%= pkg.version %> | (c) Alex Offshore | aopdg.com */';
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
uglify: {
options: {
preserveComments: false,
sourceMap: true,
sourceMapName: 'dist/safdom.min.map',
ASCIIOnly: true,
report: 'min',
screwIE8: true,
beautify: {
ascii_only: true
},
banner: banner,
compress: {
conditionals: true,
evaluate: true,
loops: true,
hoist_vars: false,
if_return: true,
join_vars: true,
warnings: true,
}
},
build: {
src: 'src/safdom.js',
dest: 'dist/safdom.min.js'
},
},
});
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.registerTask('build', ['uglify']);
grunt.registerTask('default', ['build']);
};
|
angular
.module('movielist')
.directive('mlRuntimeDropdownSlider', runtimeDropdownSliderDirective);
function runtimeDropdownSliderDirective() {
return {
restrict: 'E',
scope: {
runtime: '=mlRuntime',
range: '=mlRange'
},
bindToController: true,
templateUrl: 'app/movies/client/runtime-dropdown-slider/runtime-dropdown-slider.html',
controllerAs: 'runtimeDropdownSliderCtrl',
controller: RuntimeDropdownSliderController
};
}
function RuntimeDropdownSliderController($scope, $reactive, $timeout) {
const ctrl = this;
$reactive(ctrl).attach($scope);
ctrl.refreshSlider = refreshSlider;
return;
function refreshSlider() {
$timeout(refresh);
return;
function refresh() {
$scope.$broadcast('rzSliderForceRender');
}
}
} |
#!/usr/bin/env node
/*eslint no-console:0*/
var program = require("commander");
program
.version("0.0.1")
.command("validate <path> <host>")
.alias("val")
.description("Validate swagger documentation. Pass path to swagger.json and Url to the API.")
.action(function(path, host){
console.log(path + " " + host);
});
program.on("--help", function() {
console.log(" Examples:");
console.log();
console.log(" $ layback validate ./swagger.json http://localhost/:3000");
console.log();
});
program.parse(process.argv);
|
Ergo.defineClass('Ergo.widgets.TabBar', {
extends: 'Ergo.widgets.List',
defaults: {
cls: 'tabs tab-bar',
dynamic: false,
defaultItem: {
}
}
}, 'widgets:tab-bar');
|
import util from './util';
import Store from '../api/store/index';
import Note from '../models/Note';
import Notebook from '../models/Notebook';
let store = new Store(util.platform);
class Meta{
constructor(){
}
get data(){
return store.readFile('/meta.json').then((content) => {
if(content){
let metaData = JSON.parse(content);
metaData.notebooks.forEach((notebook) => {
this._sortNotebook(notebook);
notebook.notes.forEach((noteItem) => {
if(!noteItem.localVersion){
noteItem.localVersion = 1;
}
if(!noteItem.remoteVersion){
noteItem.remoteVersion = 0;
}
});
});
return metaData;
}else{
return this._initData();
}
});
}
async _initData(){
let newNotebook = new Notebook({
title:'TooNote'
});
newNotebook.addNote(new Note({
title:'快速入门\\欢迎使用TooNote',
}).getMeta());
let data = {
init:false,
recent:[],
notebooks:[newNotebook.getMeta()]
};
await store.writeFile('/meta.json', JSON.stringify(data));
return data;
}
async init(){
let data = await this.data;
data.init = true;
await store.writeFile('/meta.json',JSON.stringify(data));
}
async addNote(notebookId, note){
let data = await this.data;
var targetNotebook = data.notebooks.filter(function(metaNotebook){
return metaNotebook.id === notebookId;
})[0];
targetNotebook.notes.push(note.getMeta());
this._sortNotebook(targetNotebook);
await store.writeFile('/meta.json', JSON.stringify(data));
return note;
}
async deleteNote(noteId){
let data = await this.data;
data.notebooks.forEach((notebook)=>{
notebook.notes.forEach((note, index)=>{
if(note.id === noteId){
notebook.notes.splice(index, 1);
this._sortNotebook(notebook);
}
});
});
await store.writeFile('/meta.json', JSON.stringify(data));
}
async updateNote(note){
let data = await this.data;
data.notebooks.forEach((notebook)=>{
notebook.notes.forEach((noteItem)=>{
if(note.id === noteItem.id){
noteItem.title = note.title;
noteItem.localVersion = note.localVersion;
noteItem.remoteVersion = note.remoteVersion;
// noteItem.pureTitle = note.
this._sortNotebook(notebook);
}
});
});
await store.writeFile('/meta.json', JSON.stringify(data));
return data;
}
async findNoteById(noteId){
let data = await this.data;
let target;
data.notebooks.forEach((notebook)=>{
notebook.notes.forEach((note)=>{
if(note.id === noteId){
target = note;
}
});
});
return target;
}
async searchNote(keyword){
let data = await this.data;
let ret = [];
data.notebooks.forEach((notebook)=>{
notebook.notes.forEach((note)=>{
if(note.title.toLowerCase().indexOf(keyword) > -1){
ret.push(note);
}
});
});
return ret;
}
async findNotebookOfNote(noteId){
let data = await this.data;
let target;
data.notebooks.forEach((notebook)=>{
notebook.notes.forEach((note)=>{
if(note.id === noteId){
target = notebook;
}
});
});
return target;
}
/* async exchange(id1, id2){
let data = await this.data;
let notebook1, notebook2;
let note1, note2;
let index1, index2;
data.notebooks.forEach((notebook) => {
notebook.notes.forEach((note, index) => {
if(note.id === id1){
notebook1 = notebook;
note1 = note;
index1 = index;
}
if(note.id === id2){
notebook2 = notebook;
note2 = note;
index2 = index;
}
});
});
// 只能交换同一笔记本中的笔记
if(notebook1 !== notebook2) return data;
// 交换
notebook1.notes.splice(index1, 1, note2);
notebook1.notes.splice(index2, 1, note1);
await store.writeFile('/meta.json', JSON.stringify(data));
return data;
} */
_sortNotebook(notebook){
notebook.notes.sort((noteItem1, noteItem2) => {
return noteItem1.createdAt < noteItem2.createdAt;
});
}
}
let meta = new Meta();
export default meta;
|
var videofeedApp = angular.module('videofeedApp', []);
videofeedApp.config(function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
});
videofeedApp.controller('VideoListController', function VideoListController($scope, $http, $sce) {
$scope.title = "Video Feed";
$http.get('https://cdn.playbuzz.com/content/feed/items').then(function(response) {
$scope.items = response.data.items;
var youtubeUrl = 'https://www.youtube.com/embed/';
var facebookUrl = 'http://www.facebook.com/video/embed?video_id=';
for (var i = $scope.items.length - 1; i >= 0; i--) {
$scope.trustSrcYoutube = function(videoId) {
var videoSrc = youtubeUrl + videoId;
return $sce.trustAsResourceUrl(videoSrc);
}
$scope.trustSrcFacebook = function(videoId) {
var videoSrc = facebookUrl + videoId;
return $sce.trustAsResourceUrl(videoSrc);
}
}
}).catch(function(e){
console.log('error');
});
});
videofeedApp.filter('thousandSuffix', function () {
return function (input, decimals) {
var exp, rounded,
suffixes = ['k', 'M', 'G', 'T', 'P', 'E'];
if(window.isNaN(input)) {
return null;
}
if(input < 1000) {
return input;
}
exp = Math.floor(Math.log(input) / Math.log(1000));
return (input / Math.pow(1000, exp)).toFixed(decimals) + suffixes[exp - 1];
};
}); |
toId = function(text) {
if (text && text.id) text = text.id;
else if (text && text.userid) text = text.userid;
return string(text).toLowerCase().replace(/[^a-z0-9]+/g, '');
};
string = function(str) {
if (typeof str === 'string' || typeof str === 'number') return ''+str;
return '';
}
require("sugar");
fs = require("fs");
fs.exists = require("path").exists;
fs.existsSync = require("path").existsSync;
var LearnsetsG6 = require('./learnsets-g6.js');
var Tools = require('./tools.js');
// A-C, D-I, J-O, P-R, S-Z
var keys = Object.keys(LearnsetsG6).sort();
var buf = '';
var curFile = 'a';
for (var i=0; i<keys.length; i++) {
var key = keys[i];
if (!key) continue;
if (key.charAt(0) === 'd' && curFile === 'a') {
fs.writeFileSync('learnsets-g6/learnsets-g6-A-to-C.txt', buf);
buf = '';
curFile = 'd';
}
if (key.charAt(0) === 'j' && curFile === 'd') {
fs.writeFileSync('learnsets-g6/learnsets-g6-D-to-I.txt', buf);
buf = '';
curFile = 'j';
}
if (key.charAt(0) === 'p' && curFile === 'j') {
fs.writeFileSync('learnsets-g6/learnsets-g6-J-to-O.txt', buf);
buf = '';
curFile = 'p';
}
if (key.charAt(0) === 's' && curFile === 'p') {
fs.writeFileSync('learnsets-g6/learnsets-g6-P-to-R.txt', buf);
buf = '';
curFile = 's';
}
console.log(key.charAt(0)+' '+curFile);
buf += '== '+Tools.getTemplate(key).name+' ==\n\n';
for (var j in LearnsetsG6[key].level) {
buf += 'L? - '+Tools.getMove(LearnsetsG6[key].level[j]).name+'\n';
}
for (var j in LearnsetsG6[key].tm) {
buf += 'TM - '+Tools.getMove(LearnsetsG6[key].tm[j]).name+'\n';
}
for (var j in LearnsetsG6[key].egg) {
buf += 'Egg - '+Tools.getMove(LearnsetsG6[key].egg[j]).name+'\n';
}
buf += '\n';
}
fs.writeFileSync('learnsets-g6/learnsets-g6-S-to-Z.txt', buf);
|
/**
* Created by charlie on 9/30/16.
*/
import Vue from 'vue'
// import { mixin } from '../common/utils'
import VhNotification from './impl.vue'
let NotificationConstructor = Vue.extend(VhNotification)
let instance
let instances = []
let seed = 1
let Notification = function (options) {
options = options || {}
let userOnClose = options.onClose
let id = 'notification_' + seed++
options.onClose = function () {
Notification.close(id, userOnClose)
}
instance = new NotificationConstructor({
data: options
})
instance.id = id
instance.vm = instance.$mount()
document.body.appendChild(instance.vm.$el)
instance.vm.visible = true
instance.dom = instance.vm.$el
let topDist = 0
for (let i = 0, len = instances.length; i < len; i++) {
topDist += instances[i].$el.offsetHeight + 16
}
topDist += 16
instance.top = topDist
instances.push(instance)
return instance
}
Notification.close = function (id, userOnClose) {
let index
let removedHeight
let len = instances.length
for (let i = 0; i < len; i++) {
if (id === instances[i].id) {
if (typeof userOnClose === 'function') {
userOnClose(instances[i])
}
index = i
removedHeight = instances[i].dom.offsetHeight
instances.splice(i, 1)
break
}
}
if (len > 1) {
for (let i = index; i < len - 1; i++) {
instances[i].dom.style.top = parseInt(instances[i].dom.style.top, 10) - removedHeight - 16 + 'px'
}
}
}
let NotificationFactory = {
alert (message, options) {
options = options || {}
options.message = message
options.title = options.title || '提示'
return Notification(options)
},
success (message, options) {
options = options || {}
options.type = 'success'
options.message = message
options.title = options.title || '提示'
return Notification(options)
},
warn (message, options) {
options = options || {}
options.type = 'warning'
options.message = message
options.title = options.title || '提示'
return Notification(options)
},
error (message, options) {
options = options || {}
options.type = 'error'
options.message = message
options.title = options.title || '提示'
return Notification(options)
},
info (message, options) {
options = options || {}
options.type = 'info'
options.message = message
options.title = options.title || '提示'
return Notification(options)
}
}
export {
NotificationFactory as default,
Notification
}
|
/// <reference path="../../scripts/p5.d.ts" />
/* tslint:disable: no-unused-variable */
/* tslint:disable: comment-format */
var NOC_I_06_b;
(function (NOC_I_06_b) {
'use strict';
var Walker = (function () {
function Walker(s) {
this.s = s;
this.pos = this.s.createVector(this.s.width / 2, this.s.height / 2);
this.prevPos = this.s.createVector(this.s.width / 2, this.s.height / 2);
this.nOff = this.s.random(10000);
}
Walker.prototype.display = function () {
this.s.stroke(0);
this.s.line(this.prevPos.x, this.prevPos.y, this.pos.x, this.pos.y);
};
Walker.prototype.step = function () {
this.prevPos.set(this.pos.x, this.pos.y);
var maxStepSize = 20;
var stepSize = this.s.map(this.s.noise(this.nOff), 0, 1, 0, maxStepSize);
this.nOff += 0.01;
// 0, 1, 2, or 3
var choice = this.s.floor(this.s.random(4));
if (choice === 0) {
this.pos.x += stepSize;
}
else if (choice === 1) {
this.pos.x -= stepSize;
}
else if (choice === 2) {
this.pos.y += stepSize;
}
else {
this.pos.y -= stepSize;
}
this.pos.x = this.s.constrain(this.pos.x, 0, this.s.width - 1);
this.pos.y = this.s.constrain(this.pos.y, 0, this.s.height - 1);
};
return Walker;
})();
NOC_I_06_b.sketch = function (s) {
var walker;
s.setup = function () {
s.createCanvas(640, 360);
walker = new Walker(s);
s.background(255);
};
s.draw = function () {
walker.step();
walker.display();
};
};
})(NOC_I_06_b || (NOC_I_06_b = {}));
var myp5 = new p5(NOC_I_06_b.sketch);
//# sourceMappingURL=Sketch.js.map |
const { resolve } = require('path')
module.exports = {
rootDir: resolve(__dirname, '../..'),
srcDir: __dirname,
modules: ['@@/lib/module'],
build: {
extractCSS: true
},
framework7: {
routes: {
index: {
tabs: [
{ path: '', id: 'tab1' },
{ path: '/tab2', id: 'tab2' },
{ path: '/tab3', id: 'tab3' }
]
}
}
}
}
|
(function() {
window.vtex.i18n["en-US"] = {
shippingData: {
shippingAddressTitle: "Delivery address",
addNewAddress: "Add New address",
chooseAddress: "Choose a delivery address",
or: "or",
deliveryCountry: "Country",
seeDetails: "See details",
shipOtherAddress: "Delivery in another address",
editCurrentAddress: "Edit current address",
youGotOtherSingular: "You have another ",
savedWouldYouSingular: " saved address. Would you like to display it?",
youGotOtherPlural: "You have other ",
savedWouldYouPlural: " saved addresses. Would you like to display them?",
shippingOptions: "Choose the delivery options",
chooseShippingOption: "Choose your shipping option",
chooseOtherShippingOption: "Choose another shipping option",
shippingOption: "Shipping option",
shippingEstimate: "Estimate",
shipping: "Shipping:",
ofSeller: "of the seller ",
followingProducts: " Products from",
workingDay: "business day",
workingDays: "business days",
day: "day",
days: "days",
select: "Select",
deliveryDate: "Delivery date",
deliveryHour: "Delivery hour",
fromToHour: "From __from__ to __to__",
scheduled: "Scheduled",
toSchedule: "(to schedule)",
chooseScheduledDate: "Choose your shipping date",
cancelEditAddress: "Back to address list",
upTo: "Up to",
deliverAtAddressOf: "Deliver at address of:",
atAddressOf: "At address of:",
shippingAddress: {
postalCode: "Postal code ",
addressLine1: "Address Line 1",
addressLine2: "Address Line 2",
street: "Street ",
number: "Number ",
additionalInfo: "Additional info (eg: apt 201)",
reference: "Close to",
district: "District ",
commercial: "Commercial address",
city: "City ",
locality: "Locality ",
exteriorNumber: "Exterior Number",
interiorNumber: "Interior Number",
state: "State ",
colony: "Colony",
province: "Province",
region: "Region ",
community: "Community ",
direction: "Direction",
department: "Departament",
municipality: "Municipality",
type: "Address type",
receiver: "Receiver ",
addressId: "Address name (ex: Home)",
identifierUsed: "The address name must be unique, type a different one from the ones already saved."
}
},
paymentData: {
payment: "Payment ",
secureEnvironment: "Safe Environment",
paymentMethod: "Payment method",
showCredits: "Show credits from Wedding List and Loyalty Program",
backCreditCardList: "Go back to the credit card list",
confirm: "Buy now",
finishing: "One moment while we process your payment.",
sameBillingAddress: "My billing address is ",
billingAddress: "Billing address",
totalIsFree: "The total cost of this purchase is free!",
upToInstallment: "Up to",
requiresAuthentication: "For your safety, this payment method requires authentication",
addPayment: "Add another payment",
newPayment: "New payment",
payUsingMoreThanOneMethod: "Do you want to pay using more than one method?",
paymentGroup: {
MercadoPago: {
name: "Mercado Pago",
description: "Pay with your Mercado Pago account."
},
payPal: {
name: "PayPal",
subtitle: "Why pay with PayPal?",
protectionTitle: "Consumer protection",
protectionDescription: "your product will be delivered or you can get your money back*.",
easyTitle: "Easy and fast",
easyDescription: "use only your e-mail and password.",
safeTitle: "Ultra Safe",
safeDescription: "your payment data won't be shared.",
helpTitle: "Need help? Call us:",
helpNumber: "0800 892-1555",
postScript: "*Depends on requirements of Consumer Protection Program.",
installmentsBefore: "up to",
installmentsNumber: "x",
installmentsAfter: "no interest",
installmentsCash: "cash"
},
safetypay: {
name: 'Online Debit',
descriptionText: "Pay with online debit via Interner Banking:",
descriptionBanks: "Banco do Brasil, HSBC, Banrisul, Bradesco and Itaú.",
warrantedTitle: "Warranted",
warrantedDescription: "Stay calm. We offer the warranty of a certified environment.",
fastTitle: "Fast",
fastDescription: "Just authorize the payment on your bank and go on with the order.",
safeTitle: "Safe",
safeDescription: "No registration need and no payment data stored.",
helpTitle: "Need help? Send us an e-mail: support@safetypay.com"
},
Bcash: {
name: "Bcash",
description: "Pay with your Bcash account."
},
giftCard: {
name: "Gift card",
discount: "Discounts",
useGiftCard: "Use gift card",
dontUseGiftCard: "Don't use gift card",
codeCard: "Gift card code",
used: "Used codes",
code: "Code",
alreadyUsed: "This code was already used",
totalAlreadyPaid: "All of the value is already covered",
showDiscounts: "You have discount coupons to use. Should we show them?",
provider: "Type"
},
debit: {
name: "Online Debit",
description: "This option is only valid for clients who have access to the Internet Banking option selected. After checkout, the bank will send us the confirmation within two days. Then, your order will be ready to be shipped as per the estimated time.",
chooseBank: "Select your bank:"
},
debitCard: {
name: "Debit Card",
firstCard: "First card",
secondCard: "Second card",
value: "Value ",
number: "Number ",
holderName: "Cardholder name ",
dueDate: "Good thru",
dueMonth: "MM",
dueYear: "YY",
ccv: "Security code",
help: "The card security code is located on the back of the card and is typically a separate group of 3 digits to the right of the signature strip."
},
availableInstallments: "Installments",
loadingInstallments: "Loading installments",
installmentsCaption: "Select number of installments",
creditCard: {
name: "Credit card",
creditCard: "Credit card",
firstCard: "First card",
secondCard: "Second card",
removeCard: "Remove card",
documentType: "Document type",
document: "Document",
hasCPF: "I have a brazilian ID (CPF)",
cpfOwner: "Cardholder CPF",
noCPF: "I don't have a brazilian ID (CPF)",
value: "Value ",
number: "Number ",
holderName: "Cardholder name ",
dueDate: "Good thru",
dueMonth: "MM",
dueYear: "YY",
ccv: "Security code.",
helpHiperCard: "If you Hipercard have a sequence of 6 digits above the 13 digits main sequence, you will need to type all numbers, starting with the 6 little ones, totalizing 19 digits.",
help: "3 digits number located on the back of the card.",
helpAmex: "4 digits number located on the front of the card.",
payWithTwo: "Pay with two cards",
payWithOne: "Pay with one card",
payInCash: "To pay in cash",
installments: " interest free",
installmentsInterestPrefix: " payments of",
installmentsInterestSuffix: "(monthly interest rate of",
installmentsInterestPeriod: "%)",
installmentsInterest: "interest",
endingIn: "ending in",
invalidValue: "Invalid value",
invalidDate: "Invalid date",
invalidDigits: "Invalid digits",
useAnotherCard: "Use another card",
scanner: {
scanCard: "Scan credit card",
swipeCard: "Scan credit card",
swipeCardInstruction: "Please, swipe the card in the magnetic reader",
typeCard: "type your info",
useAnotherCard: "Use another card"
}
},
bankInvoice: {
name: "Invoice",
description: "The invoice will be available for printing after the checkout. You can pay in any bank, or take down its number and pay by the phone or Internet.",
chooseBank: "Select your bank:"
},
evolucard: {
name: "Evolucard",
description: "Pay with Evolucard."
},
promissory: {
name: "Credit Card",
description: "Our staff will call you to finish your checkout process."
},
alignet: {
name: "Alignet",
description: "Pay with Alignet."
},
pagSeguro: {
name: "PagSeguro",
description: "Pay with the UOL's PagSeguro."
},
peela: {
name: "Peela",
description: "Pay with your Peela card."
}
}
},
modal: {
paymentUnauthorizedReviewData: "Please review your payment details",
paymentUnauthorizedMessage1: "Your purchase has not been finalized due to some problem in the authorization of payment.",
paymentUnauthorizedMessage2: "You may have filled some data incorrectly or may have been some problem with the card in case of card purchase.",
paymentUnauthorizedChangeData: "Reviewing data or pay otherwise",
showDetails: "View details"
},
global: {
add: "Add",
edit: "Edit",
save: "Save",
"continue": "Next step",
continue_: "Continue",
cancel: "cancel",
"delete": "Delete",
remove: "remove",
help: "Help",
waiting: "Waiting for more information",
value: "Value",
valueUsing: "Value using",
total: "Total",
totalValue: "Total value",
quantity: "Qty.",
image: "Image",
product: "Product",
delivery: "Delivery",
exempt: "Exempt",
price: "Price",
priceFrom: "from",
from: "From",
"for": "Por",
or: "or",
to: "to",
gift: "Gift",
keepCredit: "keep credit",
addCredit: "use credit",
notRequired: "Optional",
loading: "Loading...",
changeLocale: "Change Language",
error: "Error: ",
back_: "Go back",
backTo: "Go back to ",
backToCart: "Go back to cart",
selected: "Selected",
thanks: "Thank you!",
unavailable: "unavailable",
unkownError: "An unexpected error ocurred, we are trying to solve it. Try again later.",
validationErrorInThisForm: "There is a validation error. Please correct any fields and try again.",
free: "Free",
pageIsLoadingPrompt: "There are pending operations - please, wait a moment.",
BRA: "Brasil",
ARG: "Argentina",
ECU: "Ecuador",
CHL: "Chile",
USA: "USA",
URY: "Uruguay",
COL: "Colombia",
PRY: "Paraguay",
PER: "Peru",
MEX: "Mexico",
goToShipping: "Go to Shipping",
goToPayment: "Go to Payment",
optinNewsLetter: "I want to receive the newsletter.",
saveData: "I want to buy faster next time. ",
howSaveDataWorks: "How does it work?",
didYouMean: "Did you mean:",
saveDataDetailsTitle: "Streamlines your next purchase",
saveDataDetails: "In the next purchase, you will not need to fill out the registration form. Your data is 100% safe.",
'loyalty-program': "Loyalty Program",
errorServer: "There was an error in our servers. Please try again later.",
close: "Close",
send: "Submit",
note: "Note",
addNote: "Add note"
}
};
}).call(this);
|
/***********************
jquery-surf.js
Copyright (C) Drecom Co.,Ltd
Licensed under MIT
***********************/
(function($) {
var name_space = 'surf';
$.fn[name_space] = function(options) {
var element = this;
var default_options = {
axis : 'x',
duration : '200',
page_template : -1,
page_template_url : './templates/default.tpl',
main_view : '#ui-surf-main-view',
page_holder : '#ui-surf-page-holder',
surf_page_num : 'ui-surf-page-',
surf_page : '.ui-surf-page',
prev_button : '#ui-surf-prev-link',
next_button : '#ui-surf-next-link',
ui_surf : '.ui-surf',
ui_surf_axis : 'ui-surf-axis-',
prev_button_html : '<div id="ui-surf-prev-link">△</div>',
next_button_html : '<div id="ui-surf-next-link">▼</div>',
next : function(page, surf) {
if (page < 1) {
return false;
}
$.ajax( {
url : './json/' + page + '.json',
success : function(data) {
var html = surf.RenderTemplate( {
rankings : data
});
surf.insertAndMoveTo(page, html);
},
dataType : 'json'
});
return true;
},
prev : function() {
}
};
var settings = $.extend(default_options, options);
if (typeof (settings.page_template) == 'string') {
var surf_template = $.createTemplate(settings.page_template);
} else {
var surf_template = $.createTemplateURL(settings.page_template_url);
}
function surfRenderedPage(page) {
var holder = $(settings.main_view).children(
'ul' + settings.page_holder);
var rendered_page = holder
.children('li' + settings.surf_page + ':nth-child(' + page + ')');
if (rendered_page.length > 0) {
return rendered_page;
} else {
return 0;
}
}
;
function surfPageNumber(page) {
var page_elements = $('ul' + settings.page_holder + ' li' + settings.surf_page);
return (page_elements.index(page) + 1);
}
;
function surfRenderTemplate(data) {
return $.processTemplateToText(surf_template, data);
}
;
function surfInsertAndMoveTo(page, html) {
var holder = $(settings.main_view).children(
'ul' + settings.page_holder);
if (surfRenderedPage(page) == 0) {
holder.append('<li id="' + settings.surf_page_num + page
+ '" class="' + settings.surf_page.replace('.','') + '">' + html + '</li>');
}
surfMoveTo(holder.children('li' + settings.surf_page + ':last'));
}
;
function surfMoveTo(to) {
var view = $(settings.main_view);
view.scrollTo(to, settings.duration, {
axis : settings.axis
});
var page_number = surfPageNumber(to);
if (page_number < 1) {
page_number = 1;
}
$.data($(settings.ui_surf).get(0), name_space).current_page = page_number;
}
;
var surf = {
renderTemplate : surfRenderTemplate,
insertAndMoveTo : surfInsertAndMoveTo,
pageNumber : surfPageNumber,
renderedPage : surfRenderedPage,
moveTo : surfMoveTo
};
return element
.each(function() {
$(this).addClass(settings.ui_surf.replace('.',''));
$(this).addClass(settings.ui_surf_axis + settings.axis);
$(settings.prev_button_html).appendTo($(this));
$(
'<div id="' + settings.main_view.replace("#",'') + '"><ul id="' + settings.page_holder.replace('#','') + '"></ul></div>')
.appendTo($(this));
$(settings.next_button_html).appendTo($(this));
var ui_surf = $(this);
var ui_surf_page_holder = $(settings.page_holder);
$.data(ui_surf.get(0), name_space, {
current_page : 0
});
$(this)
.children(settings.next_button)
.click(
function() {
var current_page = $.data(ui_surf
.get(0), name_space).current_page;
var rendered_page = surfRenderedPage(current_page + 1);
if (rendered_page) {
return surfMoveTo(rendered_page);
}
$.data(ui_surf.get(0), name_space).processing = 1;
settings.next(current_page + 1, surf);
$.data(ui_surf.get(0), name_space).processing = 0;
});
$(this)
.children(settings.prev_button)
.click(
function() {
var current_page = $.data(ui_surf
.get(0), name_space).current_page;
var rendered_page = surfRenderedPage(current_page - 1);
if (rendered_page) {
return surfMoveTo(rendered_page);
}
settings.prev(current_page - 1, surf);
});
$(this).children(settings.next_button).click();
});
};
})(jQuery);
|
var searchData=
[
['b',['b',['../structlfgui_1_1color.html#aeb0a907229a752e83162d675165d33de',1,'lfgui::color']]],
['beam',['beam',['../namespacelfgui.html#a765b713f4249e73e28aaa97f10bf6285a5435eeb714f3a0739ca75b3b0eb8cfb3',1,'lfgui']]],
['bitmap',['bitmap',['../structlfgui_1_1font_1_1bitmap.html',1,'lfgui::font']]],
['bitmap',['bitmap',['../structlfgui_1_1font_1_1bitmap.html#a5446aae7c782f3c6c9c43be6fbce119d',1,'lfgui::font::bitmap::bitmap()'],['../structlfgui_1_1font_1_1bitmap.html#a60e00952dcee45a76d62c196897015cf',1,'lfgui::font::bitmap::bitmap(const bitmap &o)'],['../structlfgui_1_1font_1_1bitmap.html#a1562ad60e2c847f0451e7312502da9d7',1,'lfgui::font::bitmap::bitmap(bitmap &&o)']]],
['blend_5fpixel',['blend_pixel',['../classlfgui_1_1image.html#a05fd1dc817a757144e9ad8402d0d92f8',1,'lfgui::image']]],
['blend_5fpixel_5fsafe',['blend_pixel_safe',['../classlfgui_1_1image.html#ad7fe4e3b8024f33fa21318ae246e679e',1,'lfgui::image']]],
['bool_5fem',['bool_em',['../structlfgui_1_1event__function.html#a2479302e103daff65a3c0b8ce34f604c',1,'lfgui::event_function::bool_em()'],['../structlfgui_1_1event__function_3_01void_01_4.html#a6e57c2f2cc1d5077637d7207c8f276d3',1,'lfgui::event_function< void >::bool_em()']]],
['bottom',['bottom',['../structlfgui_1_1rect.html#add41abdbad26a08fe350c2e3e667930d',1,'lfgui::rect']]],
['busy',['busy',['../namespacelfgui.html#a765b713f4249e73e28aaa97f10bf6285a8bc1b2f84252c3df4edd53e4aad097a7',1,'lfgui']]],
['button',['button',['../classlfgui_1_1button.html',1,'lfgui']]],
['button',['button',['../classlfgui_1_1event__mouse.html#ab450079ce09c29ad91684a67c709e042',1,'lfgui::event_mouse::button()'],['../classlfgui_1_1button.html#a506c5657c3254ae986a82f3529f831d8',1,'lfgui::button::button(int x, int y, int width, int height=25, const std::string &text="", color text_color=color({0, 0, 0}), int border_width=10)'],['../classlfgui_1_1button.html#a43fef38954ec44715ac3a8ab1b9eb2fb',1,'lfgui::button::button(int width=100, int height=20, const std::string &text="", color text_color=color({0, 0, 0}), int border_width=10)'],['../classlfgui_1_1button.html#ae993668d387910d9a63a31799cb4f73b',1,'lfgui::button::button(const std::string &text="", color text_color=color({0, 0, 0}), int border_width=10)']]],
['button_2eh',['button.h',['../button_8h.html',1,'']]],
['button_5fstate',['button_state',['../classlfgui_1_1event__mouse.html#ac4b15f9566f53c57a963b0693bf98437',1,'lfgui::event_mouse']]],
['button_5fstate_5flast',['button_state_last',['../classlfgui_1_1gui.html#a37a61b3714c34fad77f6f8a871d3c85f',1,'lfgui::gui']]]
];
|
$(document).ready(function () {
$(document).on("scroll", onScroll);
$('a[href^="#"]').on('click', function (e) {
e.preventDefault();
$(document).off("scroll");
$('a').each(function () {
$(this).removeClass('active');
})
$(this).addClass('active');
var target = this.hash;
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 500, 'swing', function () {
window.location.hash = target;
$(document).on("scroll", onScroll);
});
});
});
function onScroll(event){
var scrollPosition = $(document).scrollTop();
$('nav a').each(function () {
var currentLink = $(this);
var refElement = $(currentLink.attr("href"));
if (refElement.position().top <= scrollPosition && refElement.position().top + refElement.height() > scrollPosition) {
$('nav ul li a').removeClass("active");
currentLink.addClass("active");
}
else{
currentLink.removeClass("active");
}
});
}
|
angular.module( 'cf')
.factory('accountsService', ['$rootScope','$q', 'usersService',
function($rootScope,$q,usersService) {
var accounts = [
{id:1,pucId:11,name:'Disponible',accountType:'ASSETS', companyId:1, initialBalance: "0"},
{id:4,pucId:15,name:'Propiedad planta y equipo',accountType:'ASSETS', companyId:1, initialBalance: "0"},
{id:7,pucId:23,name:'Cuentas por pagar',accountType:'LIABILITIES', companyId:1, initialBalance: "0"},
{id:8,pucId:31,name:'Capital social',accountType:'EQUITY', companyId:1, initialBalance: "0"},
{id:9,pucId:3605,name:'Utilidad del ejercicio',accountType:'EQUITY', companyId:1, initialBalance: "0"}
];
return {
list: function() {
var deferred = $q.defer();
var currentUser = usersService.getCurrentUser();
var result = _(accounts).filter(function(a) {
return a.companyId == currentUser.companyId;
});
deferred.resolve(result);
return deferred.promise;
},
create: function(account) {
var deferred = $q.defer();
//Mock web user registration web service
//TODO: verify not repeated puc
account.id = accounts.length;
accounts.push(account);
deferred.resolve(account);
return deferred.promise;
}
};
}]);
|
var request = require('request');
exports.Shortener = Shortener;
function Shortener() {}
Shortener.prototype.google = function(longurl, key, callback) {
var options = {
url: 'https://www.googleapis.com/urlshortener/v1/url?key=' + key,
headers: {
'Content-Type': 'application/json'
},
method: 'POST',
json: {
'longUrl': longurl
}
};
sendRequest(options, function(body) {
callback({
'longUrl': body.longUrl,
'shortUrl': body.id
});
});
};
Shortener.prototype.bitly = function(longurl, key, format, callback) {
var options = {
url: 'https://api-ssl.bitly.com/v3/shorten?access_token=' + key +
'&longUrl=' + longurl + '&format=' + format || 'json',
method: 'GET'
};
sendRequest(options, function(body) {
callback({
'longUrl': body.data.long_url,
'shortUrl': body.data.url
});
});
};
Shortener.prototype.readability = function(longurl, callback) {
var options = {
url: 'http://www.readability.com/api/shortener/v1/urls',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
form: {
url: longurl
},
method: 'POST'
};
sendRequest(options, function(body) {
callback({
'longUrl': longurl,
'shortUrl': body.meta.rdd_url
});
});
};
Shortener.prototype.mtny = function(longurl, callback) {
var options = {
url: 'http://mtny.mobi/api/?url=' + longurl + '&ismobile=false&type=json',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
method: 'GET'
};
sendRequest(options, function(body) {
callback({
'longUrl': longurl,
'shortUrl': body.url
});
});
};
Shortener.prototype.adfly = function(longurl, key, uid, callback, params) {
var params = params || {};
var options = {
url: 'http://api.adf.ly/api.php?key=' + key +
'&uid=' + uid + '&advert_type=' + (params.advType || 'int') +
'&domain=' + (params.domain || 'adf.ly') +
'&url=' + longurl,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
method: 'GET'
};
sendRequest(options, function(body) {
callback({
'longUrl': longurl,
'shortUrl': body
});
});
};
function sendRequest(options, callback) {
request(options, function(err, res, body) {
if(err) throw err;
if(typeof body === 'string') {
try {
body = JSON.parse(body);
} catch(err) { }
}
callback(body);
});
}
|
module.exports = function (tgen) {
tgen.preset("waves-5", {
width: 256,
height: 256,
items: [
[0, "waves"],
[
0,
"waves",
{
blend: "difference",
},
],
[
0,
"waves",
{
blend: "linearburn",
},
],
[
0,
"waves",
{
blend: "difference",
},
],
[
0,
"waves",
{
blend: "linearburn",
},
],
[
0,
"brightness",
{
adjust: 10,
legacy: true,
},
],
[
0,
"vibrance",
{
adjust: 10,
},
],
],
});
};
|
// import { fromJS } from 'immutable';
// import { makeSelectAffirmationsDomain } from '../selectors';
// const selector = makeSelectAffirmationsDomain();
describe('makeSelectAffirmationsDomain', () => {
it('Expect to have unit tests specified', () => {
expect(true).toEqual(false);
});
});
|
var its = require('../utils/shopItems');
class Store {
canBuyItem(socket, item) {
return (socket.player.score >= item.price);
}
getItemById(id) {
var me = this;
for (var i = 0; i < me.itemArray.length; ++i) {
if (me.itemArray[i].id == id)
return me.itemArray[i];
}
return null;
}
constructor(serv) {
var me = this;
this.serv = serv;
this.items = its.items;
this.itemArray = [];
for (var p in me.items) {
if (me.items.hasOwnProperty(p)) {
me.itemArray.push(me.items[p]);
}
}
}
}
module.exports = Store; |
var BASE_URL = localStorage["api_endpoint"];
function makeDD(change) {
var dd = document.createElement('dd');
dd.title = JSON.stringify(change, null, " ");
dd.style.marginBottom = "8px";
var subject = change.subject;
if (subject.length > 80) {
subject = subject.substr(0, 80) + '[...]';
}
dd.innerHTML = '<b>(' + change.owner.name + ')</b> ' + subject;
if (change.read)
dd.className = "read";
return dd;
}
function initUI(items) {
var list = document.getElementById('list');
list.innerHTML = "";
var refresh = document.getElementById('refresh');
refresh.addEventListener('click', function(e) {
chrome.runtime.reload();
});
for (var i = 0; i < items.changes.length; i++) {
var change = items.changes[i];
if (change.reviewed)
continue;
try {
change.read = new Date(items.timestamps[change._number]) >= new Date(change.updated);
} catch (e) {
}
var dt = document.createElement('dt');
var a = document.createElement('a');
a.href = "#";
a.addEventListener('click', function(e) {
chrome.tabs.create({
url: BASE_URL + "/" + this.textContent
})
})
a.textContent = change._number;
dt.appendChild(a);
list.appendChild(dt);
list.appendChild(makeDD(change));
}
}
document.addEventListener('DOMContentLoaded', function() {
chrome.storage.local.get(["changes", "timestamps"], initUI);
});
chrome.storage.onChanged.addListener(function(changes, namespace) {
if (changes.changes && changes.timestamps) {
initUI({
"changes": changes.changes.newValue,
"timestamps": changes.timestamps.newValue
});
} else {
chrome.storage.local.get(["changes", "timestamps"], initUI);
}
});
|
'use strict';
var test = require('ava');
var crayola = require('./');
test('returns a random crayola color', function (t) {
t.assert(crayola() !== null && typeof crayola() === 'object');
});
test('returns all the colors', function (t) {
t.assert(Array.isArray(crayola.colors));
t.assert(crayola.colors[3] !== null && typeof crayola() === 'object');
});
|
import "babel-polyfill";
import thunkMiddleware from "redux-thunk";
import React from "react";
import { render } from "react-dom";
import { Provider } from "react-redux";
import { createStore, compose, applyMiddleware, combineReducers } from "redux";
import { Taxon } from "inaturalistjs";
import photosReducer, { reloadPhotos, hydrateFromUrlParams } from "./ducks/photos";
import configReducer, { setConfig } from "../../shared/ducks/config";
import taxonReducer, { setTaxon, fetchTerms } from "../shared/ducks/taxon";
import photoModalReducer from "../shared/ducks/photo_modal";
import App from "./components/app";
const rootReducer = combineReducers( {
photos: photosReducer,
config: configReducer,
taxon: taxonReducer,
photoModal: photoModalReducer
} );
const store = createStore(
rootReducer,
compose(
applyMiddleware(
thunkMiddleware
),
// enable Redux DevTools if available
window.devToolsExtension ? window.devToolsExtension() : applyMiddleware()
)
);
if ( CURRENT_USER !== undefined && CURRENT_USER !== null ) {
store.dispatch( setConfig( {
currentUser: CURRENT_USER
} ) );
}
if ( PREFERRED_PLACE !== undefined && PREFERRED_PLACE !== null ) {
// we use this for requesting localized taoxn names
store.dispatch( setConfig( {
preferredPlace: PREFERRED_PLACE
} ) );
}
/* global SERVER_PAYLOAD */
const serverPayload = SERVER_PAYLOAD;
if ( serverPayload.place !== undefined && serverPayload.place !== null ) {
store.dispatch( setConfig( {
chosenPlace: serverPayload.place
} ) );
}
if ( serverPayload.chosenTab ) {
store.dispatch( setConfig( {
chosenTab: serverPayload.chosenTab
} ) );
}
if ( serverPayload.ancestorsShown ) {
store.dispatch( setConfig( {
ancestorsShown: serverPayload.ancestorsShown
} ) );
}
const taxon = new Taxon( serverPayload.taxon );
store.dispatch( setTaxon( taxon ) );
// fetch taxon terms before rendering the photo browser, in case
// we need to verify a term grouping by termID
store.dispatch( fetchTerms( ) ).then( ( ) => {
const urlParams = $.deparam( window.location.search.replace( /^\?/, "" ) );
store.dispatch( hydrateFromUrlParams( urlParams ) );
window.onpopstate = e => {
// user returned from BACK
store.dispatch( hydrateFromUrlParams( e.state ) );
};
store.dispatch( reloadPhotos( ) );
render(
<Provider store={store}>
<App taxon={taxon} />
</Provider>,
document.getElementById( "app" )
);
} );
|
const primitives = require('../dist/jaak-primitives')
const customThemeA = require('./fixtures/custom-theme-a')
const defaultTheme = require('./fixtures/default-theme')
const mergedThemeA = require('./fixtures/merged-theme-a')
describe('jaak-primitives :: theme', () => {
it('Should return the default theme', () => {
const actual = primitives.theme()
const expected = defaultTheme
expect(actual).toEqual(expected)
})
it('Should return a custom theme', () => {
const actual = primitives.theme(customThemeA)
const expected = mergedThemeA
expect(actual).toEqual(expected)
})
it('Should throw an error if customTheme is not of type object', () => {
const actual = () => primitives.theme(customThemeA.toString())
expect(actual).toThrow()
})
})
|
/*global parser:true */
"use strict";
if (typeof exports !== 'undefined') {
var edn = exports;
} else {
var edn = window.edn = {};
}
// Internal: Jison Parser constructor.
function Parser() {}
Parser.prototype = parser;
// Public: Parse edn String.
//
// str - edn String
// options -
// tags - Tag dispatch functions (default: edn.tags)
//
// Returns a value.
edn.parse = function (str, options) {
var parser = new Parser();
parser.yy.options = extendDefaultOptions(options);
return parser.parse(str);
};
// Public: Registered printer functions.
//
// Maps key type names to a stringify function.
//
// Examples
//
// edn.types['myapp/Person'] = function (person) {
// return '#myapp/Person {:name "'+person.name'"}';
// }
//
edn.printers = {};
// Public: Convert Object to edn String.
//
// obj - Object
// options -
// printers - Printer functions (default: edn.printers)
// converters - Conversion functions (default: edn.converters)
// types - Type checker functions (default: edn.types)
//
// Returns edn String.
edn.stringify = function (obj, options) {
options = extendDefaultOptions(options);
if (obj && obj.toEDN) {
return obj.toEDN();
}
obj = edn.convert(obj, options);
var type = edn.typeOf(obj, options);
if (type) {
var printer = options.printers[type];
if (printer) {
return printer(obj);
} else {
throw new Error("No printer function for type " + type);
}
} else {
throw new Error("No printer function for object " + obj);
}
};
edn.values = {};
// Public: Attempts to get primitive value of edn value.
//
// The returned value will be lossy. For an example, lists and vectors
// will be unwrapped into plain old Arrays making it impossible to
// know the original type.
//
// obj - edn Object
// deep - Recursive (default: true)
// options -
// values - valueOf functions (default: edn.values)
//
// Returns value.
edn.valueOf = function (obj, deep, options) {
if (deep == void 0) deep = true;
options = extendDefaultOptions(options);
function valueOf(obj) {
var type = edn.typeOf(obj, options);
if (type) {
var f = options.values[type];
return f ? f(obj, deep, valueOf) : obj;
} else {
return obj;
}
}
return valueOf(obj);
};
// Public: Registered equality functions.
//
// Maps key type names to a isEqual function.
//
// Examples
//
// edn.equal['myapp/Person'] = function (a, b) {
// return a.name == b.name;
// }
//
edn.equal = {};
// Public: Deep compare edn values.
//
// In general, two values will be equal if they serialize to the same
// edn string. With the expection of maps and sets which may serialize
// in a different order but are still collections of the same values.
//
// a - An edn value
// b - Another edn value
// options -
// equal - isEqual compare functions (default: edn.equal)
// converters - Conversion functions (default: edn.converters)
// types - Type checker functions (default: edn.types)
//
// Returns true if values are equal, otherwise false.
edn.isEqual = function (a, b, options) {
options = extendDefaultOptions(options);
function isEqual(a, b) {
a = edn.convert(a, options);
b = edn.convert(b, options);
var aType = edn.typeOf(a, options);
var bType = edn.typeOf(b, options);
var eq = options.equal[aType];
if (a === b) {
return true;
} else if (aType !== bType) {
return false;
} else if (eq) {
return eq(a, b, isEqual);
} else {
throw new Error("No equal function for type " + aType);
}
}
return isEqual(a, b);
};
// Internal: Registered object converter functions.
//
// Maps key type names to a function that returns an
// edn built-in object.
//
// Examples
//
// edn.converters['myapp/Person'] = function (person) {
// return edn.generic('myapp/Person', {name: person.name});
// }
//
edn.converters = {};
// Internal: Attempt to convert object to EDN value.
//
// obj - Object
// options -
// converters - Conversion functions (default: edn.converters)
// types - Type checker functions (default: edn.types)
//
// Returns EDN value.
edn.convert = function (obj, options) {
options = extendDefaultOptions(options);
if (obj && obj.asEDN) {
return obj.asEDN();
} else {
var type = edn.typeOf(obj, options);
if (type) {
var f = options.converters[type];
return f ? f(obj) : obj;
} else {
throw new Error("No type for object " + obj);
}
}
};
// Public: Registered type checking functions.
//
// Maps key type names to type checking function.
//
// Examples
//
// edn.types['myapp/Person'] = function (obj) {
// return obj instanceof Person;
// }
//
edn.types = {};
// Internal: Get object type String.
//
// Used internally for looking up printers and tag converters.
//
// obj - Object to detect type of
// options -
// types - Type checker functions (default: edn.types)
//
// Returns type String or null;
edn.typeOf = function (obj, options) {
options = extendDefaultOptions(options);
var matchedTypes = [];
for (var type in options.types) {
if (options.types[type](obj)) {
matchedTypes.push(type);
}
}
if (matchedTypes.length == 1) {
return matchedTypes[0];
} else if (matchedTypes.length > 1) {
throw new Error(
"Conflicted types " + matchedTypes.join(', ') + " for object " + obj);
} else {
return null;
}
};
// Internal: Merge user options with defaults.
//
// options - User options Object
//
// Returns new options Object.
function extendDefaultOptions(options) {
// Recursive optimization if defaults have already been
// merged with user options.
if (options && options._defaults) {
return options;
}
var obj = {
_defaults: true,
types: Object.create(edn.types),
converters: Object.create(edn.converters),
values: Object.create(edn.values),
equal: Object.create(edn.equal),
printers: Object.create(edn.printers),
tags: Object.create(edn.tags)
};
if (options) {
extend(obj.types, options.types);
extend(obj.converters, options.converters);
extend(obj.values, options.values);
extend(obj.equal, options.equal);
extend(obj.printers, options.printers);
extend(obj.tags, options.tags);
}
return obj;
}
// Internal: Copy object properties onto target object.
//
// target - Target Object
// source - Source Object to copy from
//
// Returns nothing.
function extend(target, source) {
var k;
for (k in source)
target[k] = source[k];
}
// Internal: Compare valueOf objects.
//
// a - Object
// b - Object
//
// Returns true if values are equal, otherwise false.
function compareValues(a, b) {
return a.valueOf() == b.valueOf();
}
// Internal: Compare Array objects.
//
// a - Array
// b - Array
// isEqual - isEqual function
//
// Returns true if all collection values are equal.
function compareArrayValues(a, b, isEqual) {
var aLen = a.length;
var bLen = b.length;
if (aLen != bLen) {
return false;
}
for (var i = 0; i < aLen; i++) {
if (!isEqual(a[i], b[i])) {
return false;
}
}
return true;
}
// Internal: Invoke object's valueOf function.
//
// obj - Object
//
// Return value.
function valueOf(obj) {
return obj.valueOf();
}
// Make Object#toString available
var toString = Object.prototype.toString;
// Built-in Elements
//
// nil
//
// nil represents nil, null or nothing. It should be read as an object
// with similar meaning on the target platform.
(function () {
// Public: Register typeof check for null.
//
// obj - Any value
//
// Returns true if object is null, otherwise false.
edn.types.nil = function (obj) {
return obj === null;
};
// Public: Stringify nil.
//
// Returns String.
edn.printers.nil = function () {
return "nil";
};
// Public: Compare nil values.
//
// a - nil value
// b - nil value
//
// Always returns true since two nil types are always equal.
edn.equal.nil = function (a, b) {
return true;
};
// Public: Register typeof check for undefined.
//
// obj - Any value
//
// Returns true if object is undefined, otherwise false.
edn.types.undefined = function (obj) {
return obj === void 0;
};
// Public: Convert undefined to null.
//
// Returns null.
edn.converters.undefined = function () {
return null;
};
})();
// Booleans
//
// true and false should be mapped to booleans.
//
// If a platform has canonic values for true and false, it is a
// further semantic of booleans that all instances of true yield that
// (identical) value, and similarly for false.
(function () {
// Public: Register typeof check for boolean.
//
// obj - Any value
//
// Returns true if object is a boolean, otherwise false.
edn.types.boolean = function (obj) {
return toString.call(obj) === '[object Boolean]';
};
// Public: Stringify boolean.
//
// Returns String.
edn.printers.boolean = function (bool) {
return bool.valueOf() ? "true" : "false";
};
// Public: Compare boolean values.
//
// a - boolean value
// b - boolean value
//
// Returns true if values are equal.
edn.equal.boolean = compareValues;
})();
// Strings
//
// Strings are enclosed in "double quotes". May span multiple lines.
// Standard C/Java escape characters \t \r \n are supported.
(function () {
// Public: Register typeof check for string.
//
// obj - Any value
//
// Returns true if object is a string, otherwise false.
edn.types.string = function (obj) {
return toString.call(obj) === '[object String]';
};
// Public: Stringify string.
//
// Returns String.
edn.printers.string = function (str) {
return JSON.stringify(str);
};
// Public: Compare string values.
//
// a - string value
// b - string value
//
// Returns true if values are equal.
edn.equal.string = compareValues;
})();
// Characters
//
// Characters are preceded by a backslash: \c. \newline, \return,
// \space and \tab yield the corresponding characters. Backslash
// cannot be followed by whitespace.
edn.Character = (function () {
var pool = {};
// Public: Create a new Character object.
//
// Calling the Character function returns an interned Character. The
// constructor always returns a new object. The function call is the
// prefered api.
function Character(c) {
// If called as function, try to pull an existing interned character
// from the pool
if (!(this instanceof Character)) {
var char = pool[c];
if (!char) {
char = new Character(c);
Object.freeze(char);
pool[c] = char;
}
return char;
}
// Internal: Returns the String character.
this.char = c;
}
// Public: Get the primitive string value.
//
// Returns String.
Character.prototype.valueOf = function () {
return this.char;
};
// Public: String representation of the Character.
//
// Returns String.
Character.prototype.toString = function () {
return this.char;
};
// Internal: Node.js console.log inspect printer.
//
// Returns String.
Character.prototype.inspect = function () {
return "[edn.Character " + require('util').inspect(this.char) + "]";
};
// Public: Register typeof check for Character.
//
// obj - Any value
//
// Returns true if object is a Character, otherwise false.
edn.types.character = function (obj) {
return obj instanceof Character;
};
// Public: Stringify Character object.
//
// char - Character object
//
// Returns String.
edn.printers.character = function (char) {
char = char.valueOf();
switch (char) {
case "\n":
return "\\newline";
case "\r":
return "\\return";
case " ":
return "\\space";
case "\t":
return "\\tab";
default:
return "\\" + char[0];
}
};
// Public: Get valueOf returns primitive string.
edn.values.character = valueOf;
// Public: Compare character values.
edn.equal.character = compareValues;
// Public: Alias for Character function.
edn.character = Character;
// Expose Character to parser
parser.yy.Character = Character;
return Character;
})();
// Symbols
//
// Symbols are used to represent identifiers, and should map to
// something other than strings, if possible.
//
// Symbols begin with a non-numeric character and can contain
// alphanumeric characters and . * + ! - _ ? $ % & =. If -, + or . are
// the first character, the second character must be non-numeric.
// Additionally, : # are allowed as constituent characters in symbols
// other than as the first character.
//
// / has special meaning in symbols. It can be used once only in the
// middle of a symbol to separate the prefix (often a namespace) from
// the name, e.g. my-namespace/foo. / by itself is a legal symbol, but
// otherwise neither the prefix nor the name part can be empty when
// the symbol contains /.
//
// If a symbol has a prefix and /, the following name component should
// follow the first-character restrictions for symbols as a whole.
// This is to avoid ambiguity in reading contexts where prefixes might
// be presumed as implicitly included namespaces and elided
// thereafter.
edn.Symbol = (function () {
var pool = {};
// Public: Create a new Symbol object.
//
// Calling the Symbol function returns an interned Symbol. The
// constructor always returns a new object. The function call is the
// prefered api.
//
// nsname - String with "/" seperating the name and namespace
//
// or
//
// namespace - String namespace
// name - String name
function Symbol(namespace, name) {
// If called as function, try to pull an existing interned symbol
// from the pool
if (!(this instanceof Symbol)) {
var nsname = joinNamespace(namespace, name);
var sym = pool[nsname];
if (!sym) {
sym = new Symbol(namespace, name);
// Interned symbols are immutable
Object.freeze(sym);
pool[sym.valueOf()] = sym;
}
return sym;
}
var parts = splitNamespacedName(namespace, name);
// Public: Returns the String namespace.
this.namespace = parts[0];
// Public: Returns the String name.
this.name = parts[1];
}
// Internal: Return seperated namespace and name.
//
// nsname - String with "/" seperating the name and namespace
//
// or
//
// namespace - String namespace
// name - String name
//
// Returns Array pair with {0:namespace, 1:name}.
function splitNamespacedName(namespace, name) {
if (namespace && name) {
return [namespace, name];
} else {
var parts = namespace.split('/', 2);
if (namespace == '/') {
return [null, '/'];
} else if (parts.length == 2) {
return parts;
} else {
return [null, parts[0]];
}
}
}
// Internal: Join namespace and name.
//
// nsname - String with "/" seperating the name and namespace
//
// or
//
// namespace - String namespace
// name - String name
//
// Returns joined String.
function joinNamespace(namespace, name) {
if (namespace && name) {
return [namespace, name].join('/');
} else {
return namespace;
}
}
// Public: Get the primitive string value.
//
// Returns String.
Symbol.prototype.valueOf = function () {
if (this.namespace) {
return [this.namespace, this.name].join('/');
} else {
return this.name;
}
};
// Public: String representation of the Symbol.
//
// Returns String.
Symbol.prototype.toString = function () {
return this.valueOf();
};
// Internal: Node.js console.log inspect printer.
//
// Returns String.
Symbol.prototype.inspect = function () {
return "[edn.Symbol " + this.toString() + "]";
};
// Public: Register typeof check for Symbol.
//
// obj - Any value
//
// Returns true if object is a Symbol, otherwise false.
edn.types.symbol = function (obj) {
return obj instanceof Symbol;
};
// Public: Stringify Symbol object.
//
// symbol - Symbol object
//
// Returns String.
edn.printers.symbol = function (symbol) {
return symbol.toString();
};
// Public: Get valueOf returns primitive string.
edn.values.symbol = valueOf;
// Public: Compare symbol values.
//
// a - symbol value
// b - symbol value
//
// Returns true if values are equal.
edn.equal.symbol = compareValues;
// Public: Alias for Symbol function.
edn.symbol = Symbol;
// Expose Symbol to parser
parser.yy.Symbol = Symbol;
return Symbol;
})();
// Keywords
//
// Keywords are identifiers that typically designate themselves. They
// are semantically akin to enumeration values. Keywords follow the
// rules of symbols, except they can (and must) begin with a colon,
// e.g. :fred or :my/fred. If the target platform does not have a
// keyword type distinct from a symbol type, the same type can be used
// without conflict, since the mandatory leading : of keywords is
// disallowed for symbols.
//
// If the target platform supports some notion of interning, it is a
// further semantic of keywords that all instances of the same keyword
// yield the identical object.
edn.Keyword = (function () {
var pool = {};
// Public: Create a new Keyword object.
//
// Calling the Keyword function returns an interned Keyword. The
// constructor always returns a new object. The function call is the
// prefered api.
//
// nsname - String with "/" seperating the name and namespace
//
// or
//
// namespace - String namespace
// name - String name
//
// or
//
// symbol - edn.Symbol
function Keyword(namespace, name) {
// Get internal symbol for keyword nsname
var sym;
if (namespace instanceof edn.Symbol) {
sym = namespace;
} else {
sym = edn.Symbol(namespace, name);
}
// If called as function, try to pull an existing interned keyword
// from the pool
if (!(this instanceof Keyword)) {
var key = pool[sym.valueOf()];
if (!key) {
key = new Keyword(namespace, name);
// Interned keywords are immutable
Object.freeze(key);
pool[sym.valueOf()] = key;
}
return key;
}
// Internal: Returns internal Symbol.
this.symbol = sym;
// Public: Returns the String namespace.
this.namespace = sym.namespace;
// Public: Returns the String name.
this.name = sym.name;
}
// Public: Get the primitive string value.
//
// Returns String.
Keyword.prototype.valueOf = function () {
return this.symbol.valueOf();
};
// Public: String representation of the Keyword.
//
// Returns String.
Keyword.prototype.toString = function () {
return ":" + this.symbol.toString();
};
// Internal: Node.js console.log inspect printer.
//
// Returns String.
Keyword.prototype.inspect = function () {
return "[edn.Keyword " + this.toString() + "]";
};
// Public: Register typeof check for Keyword.
//
// obj - Any value
//
// Returns true if object is a Keyword, otherwise false.
edn.types.keyword = function (obj) {
return obj instanceof Keyword;
};
// Public: Stringify Keyword object.
//
// keyword - Keyword object
//
// Returns String.
edn.printers.keyword = function (keyword) {
return keyword.toString();
};
// Public: Get valueOf returns primitive string.
edn.values.keyword = valueOf;
// Public: Compare keyword values.
//
// a - keyword value
// b - keyword value
//
// Returns true if values are equal.
edn.equal.keyword = compareValues;
// Public: Alias for Keyword function.
edn.keyword = Keyword;
// Expose Keyword to parser
parser.yy.Keyword = Keyword;
return Keyword;
})();
// Integers
//
// Integers consist of the digits 0 - 9, optionally prefixed by - to
// indicate a negative number, or (redundantly) by +. An integer can
// have the suffix N to indicate that arbitrary precision is desired.
// -0 is a valid integer not distinct from 0.
(function () {
// Public: Tag Number as a integer type.
//
// n - Number
//
// Returns new Number.
edn.integer = function (n) {
// Skip tagging integers
// n = Object(n);
// n.type = 'integer';
return n;
};
// Expose Integer to parser
parser.yy.Integer = edn.integer;
// Public: Register typeof check for Integer.
//
// obj - Any value
//
// Returns true if object is a Integer, otherwise false.
edn.types.integer = function (obj) {
if (obj && obj.type) {
return obj.type == 'integer';
} else {
return (toString.call(obj) === '[object Number]') &&
Math.floor(obj) == obj;
}
};
// Public: Stringify Integer object.
//
// n - Number object
//
// Returns String.
edn.printers.integer = function (n) {
return n.toString();
};
// Public: Get valueOf returns primitive number.
edn.values.integer = valueOf;
// Public: Compare integer values.
//
// a - integer value
// b - integer value
//
// Returns true if values are equal.
edn.equal.integer = compareValues;
})();
// Floating point numbers
//
// 64-bit (double) precision is expected.
//
// In addition, a floating-point number may have the suffix M to
// indicate that exact precision is desired.
(function () {
// Public: Tag Number as a float type.
//
// n - Number
//
// Returns new Number.
edn.float = function (n) {
n = Object(n);
n.type = 'float';
return n;
};
// Expose Integer to parser
parser.yy.Float = edn.float;
// Public: Register typeof check for Float.
//
// obj - Any value
//
// Returns true if object is a Float, otherwise false.
edn.types.float = function (obj) {
if (obj && obj.type) {
return obj.type == 'float';
} else {
return (toString.call(obj) === '[object Number]') &&
Math.floor(obj) != obj;
}
};
// Public: Stringify Float object.
//
// n - Number object
//
// Returns String.
edn.printers.float = function (n) {
var s = n.toString();
if (!/\./.test(s)) s += ".0";
return s;
};
// Public: Get valueOf returns primitive number.
edn.values.float = valueOf;
// Public: Compare float values.
//
// a - float value
// b - float value
//
// Returns true if values are equal.
edn.equal.float = compareValues;
})();
// Lists
//
// A list is a sequence of values. Lists are represented by zero or
// more elements enclosed in parentheses (). Note that lists can be
// heterogeneous.
//
// (a b 42)
(function () {
// Public: Tag Array as a List type.
//
// ary - Array
//
// Returns new List Array.
edn.list = function (ary) {
ary = ary.slice(0);
ary.type = 'list';
return ary;
};
// Expose List to parser
parser.yy.List = edn.list;
// Public: Register typeof check for List.
//
// obj - Any value
//
// Returns true if object is a List, otherwise false.
edn.types.list = function (obj) {
return toString.call(obj) === '[object Array]' &&
obj.type === 'list';
};
// Public: Stringify Array/List object.
//
// ary - Array object
//
// Returns String.
edn.printers.list = function (ary) {
return '(' + ary.map(edn.stringify).join(' ') + ')';
};
// Public: Get valueOf returns primitive array.
edn.values.list = function (ary, deep, valueOf) {
if (deep) {
return ary.map(valueOf);
} else {
return ary.slice(0);
}
};
// Public: Compare list collections.
//
// a - list value
// b - list value
//
// Returns true collection of values is equal.
edn.equal.list = compareArrayValues;
})();
// Vectors
//
// A vector is a sequence of values that supports random access.
// Vectors are represented by zero or more elements enclosed in square
// brackets []. Note that vectors can be heterogeneous.
//
// [a b 42]
(function () {
// Public: Tag Array as a Vector type.
//
// ary - Array
//
// Returns new Vector Array.
edn.vector = function (ary) {
ary = ary.slice(0);
ary.type = 'vector';
return ary;
};
// Expose Vector to parser
parser.yy.Vector = edn.vector;
// Public: Register typeof check for Vector.
//
// obj - Any value
//
// Returns true if object is a Vector, otherwise false.
edn.types.vector = function (obj) {
return toString.call(obj) === '[object Array]' &&
obj.type === 'vector';
};
// Public: Stringify Vector object.
//
// ary - Array object
//
// Returns String.
edn.printers.vector = function (ary) {
return '[' + ary.map(edn.stringify).join(' ') + ']';
};
// Public: Get valueOf returns primitive array.
edn.values.vector = function (ary, deep, valueOf) {
if (deep) {
return ary.map(valueOf);
} else {
return ary.slice(0);
}
};
// Public: Compare vector collections.
//
// a - vector value
// b - vector value
//
// Returns true collection of values is equal.
edn.equal.vector = compareArrayValues;
// Public: Register typeof check for Array.
//
// obj - Any value
//
// Returns true if object is a Array, otherwise false.
edn.types.array = function (obj) {
return toString.call(obj) === '[object Array]' &&
typeof obj.type == 'undefined';
};
// Public: Convert Array to Vector object.
//
// ary - Array object
//
// Returns Vector object.
edn.converters.array = function (ary) {
return edn.vector(ary);
};
})();
// Maps
//
// A map is a collection of associations between keys and values. Maps
// are represented by zero or more key and value pairs enclosed in
// curly braces {}. Each key should appear at most once. No semantics
// should be associated with the order in which the pairs appear.
//
// {:a 1, "foo" :bar, [1 2 3] four}
//
// Note that keys and values can be elements of any type. The use of
// commas above is optional, as they are parsed as whitespace.
if (false && typeof Map !== 'undefined') {
edn.Map = Map;
} else {
// Backport Harmony Map
// http://wiki.ecmascript.org/doku.php?id=harmony:simple_maps_and_sets
//
// Though, its disabled until Map supports iteration. Yeah, wtf.
// Guess we'll need to wait till we have Harmony iterators.
edn.Map = (function () {
// Public: Create a new Map object.
function Map() {
if (!(this instanceof Map)) {
return new Map();
}
// Internal: Returns Array of keys.
// API not finalized. May change in a minor release.
Object.defineProperty(this, 'keys', {
configurable: false,
enumerable: false,
writable: false,
value: []
});
// Internal: Returns Array of values.
// API not finalized. May change in a minor release.
Object.defineProperty(this, 'values', {
configurable: false,
enumerable: false,
writable: false,
value: []
});
// Internal: Returns Array of [key, value] pairs.
// API not finalized. May change in a minor release.
Object.defineProperty(this, 'items', {
configurable: false,
enumerable: false,
writable: false,
value: []
});
// Internal: Hack to expose and enumerable property to play
// nice with node's deepEqual function. Maybe some day it will
// eventually support comparing Maps.
Object.defineProperty(this, '_map', {
enumerable: true,
get: function () {
var obj = {};
this.items.forEach(function (item) {
obj[edn.stringify(item[0])] = item[1];
});
return obj;
}
});
}
// Internal: Check if two objects are egal.
//
// http://wiki.ecmascript.org/doku.php?id=harmony:egal
//
// Returns true or false.
var objectIs;
if (Object.is) {
objectIs = Object.is;
} else {
objectIs = function (x, y) {
if (x === y) {
if (x === 0) {
return 1 / x === 1 / y;
} else {
return true;
}
}
return x !== x && y !== y;
};
}
// Internal: Find index of value in Array.
//
// Similar to Array.prototype.indexOf, but uses Object.is.
//
// http://wiki.ecmascript.org/doku.php?id=harmony:simple_maps_and_sets
//
// keys - Array of keys to search.
// key - Object key to search for.
//
// Return Number index of value in Array. Otherwise returns -1 key
// is not keys Array.
function indexOfIdentical(keys, key) {
for (var i = 0, length = keys.length; i < length; i++) {
if (objectIs(keys[i], key)) {
return i;
}
}
return -1;
}
// Public: Find associated value for key in the map.
//
// key - Object
//
// Returns the value associated to the key. Or "undefined" if
// there is none.
Map.prototype.get = function (key) {
var index = indexOfIdentical(this.keys, key);
return index < 0 ? undefined : this.values[index];
};
// Public: Check if key is associated to a value in the map.
//
// key - Object
//
// Returns true if value has been associated to the key in the
// map. Otherwise returns false.
Map.prototype.has = function (key) {
return indexOfIdentical(this.keys, key) >= 0;
};
// Public: Associated the value for a key in the map.
//
// key - Object
// value - Object
//
// Returns the value argument.
Map.prototype.set = function (key, value) {
var keys = this.keys;
var values = this.values;
var items = this.items;
var _map = this._map;
var index = indexOfIdentical(keys, key);
if (index < 0) index = keys.length;
keys[index] = key;
values[index] = value;
items[index] = [key, value];
return value;
};
// Public: Removes the key and value from the map.
//
// key - Object
//
// Returns true if key was removed. Returns false if key did not
// exist in map.
Map.prototype['delete'] = function (key) {
var keys = this.keys;
var values = this.values;
var items = this.items;
var _map = this._map;
var index = indexOfIdentical(keys, key);
if (index < 0) return false;
keys.splice(index, 1);
values.splice(index, 1);
items.splice(index, 1);
return true;
};
// Public: String representation of the Map.
//
// Returns String.
Map.prototype.toString = function () {
return '[object Map]';
};
// Internal: Node.js console.log inspect printer.
//
// Returns String.
Map.prototype.inspect = function () {
return "[edn.Map " + require('util').inspect(this.items) + "]";
};
return Map;
})();
}
(function () {
// Public: Convert flat Array of key and values to Map.
//
// values - Array of [k1, v1, k2, v2, ...]
//
// Returns new Map.
edn.map = function (values) {
var map = new edn.Map();
for (var i = 0; i < values.length; i += 2) {
map.set(values[i], values[i + 1]);
}
return map;
};
// Expose Map to parser
parser.yy.Map = edn.map;
// Public: Register typeof check for Map.
//
// obj - Any value
//
// Returns true if object is a Map, otherwise false.
edn.types.map = function (obj) {
return obj instanceof edn.Map;
};
// Public: Stringify Map object.
//
// map - Map object
//
// Returns String.
edn.printers.map = function (map) {
var m = map.items.map(function (item) {
return edn.stringify(item[0]) + " " + edn.stringify(item[1]);
});
return "{" + m.join(", ") + "}";
};
// Public: Get valueOf returns primitive array.
edn.values.map = function (map, deep, valueOf) {
var safe = map.keys.every(function (key) {
return typeof valueOf(key) != 'object';
});
if (safe) {
var obj = {};
map.items.forEach(function (item) {
var value = item[1];
if (deep) value = valueOf(value);
obj[valueOf(item[0])] = value;
});
return obj;
}
return map;
};
// Public: Compare map collections.
//
// a - map value
// b - map value
// isEqual - isEqual function
//
// Returns true collection of values is equal.
edn.equal.map = function (a, b, isEqual) {
var aItems = a.items;
var bItems = b.items;
if (aItems.length != bItems.length) {
return false;
}
return aItems.every(function (aItem) {
var bItem = bItems.filter(function (bItem) {
return isEqual(aItem[0], bItem[0]);
})[0];
if (bItem) {
return isEqual(aItem[1], bItem[1]);
} else {
return false;
}
});
};
// Public: Register type of check for plain Object.
//
// obj - Any value
//
// Returns true if object is a direct prototype of Object,
// otherwise false.
edn.types.object = function (obj) {
return obj && (typeof obj === 'object') &&
(Object.getPrototypeOf(obj) === Object.prototype);
};
// Public: Convert Object to and EDN map.
//
// obj - Plain Object
//
// Returns a Map object.
edn.converters.object = function (obj) {
var map = new edn.Map();
Object.keys(obj).forEach(function (key) {
map.set(edn.keyword(key), obj[key]);
});
return map;
};
})();
// Sets
//
// A set is a collection of unique values. Sets are represented by
// zero or more elements enclosed in curly braces preceded by # #{}.
// No semantics should be associated with the order in which the
// elements appear. Note that sets can be heterogeneous.
//
// #{a b [1 2 3]}
//
if (false && typeof Set !== 'undefined') {
edn.Set = Set;
} else {
// Backport Harmony Set
// http://wiki.ecmascript.org/doku.php?id=harmony:simple_maps_and_sets
//
// Disabled until Set supports iteration
edn.Set = (function () {
// Public: Create a new Set object.
function Set() {
if (!(this instanceof Set)) {
return new Set();
}
// Internal: Hack to expose and enumerable property to play
// nice with node's deepEqual function. Maybe some day it will
// eventually support comparing Sets and Maps.
Object.defineProperty(this, '_map', {
configurable: false,
enumerable: true,
writable: false,
value: new edn.Map()
});
// Internal: Returns Array of values.
// API not finalized. May change in a minor release.
Object.defineProperty(this, 'values', {
configurable: false,
enumerable: false,
get: function () { return this._map.keys; }
});
}
// Public: Check if value is in set.
//
// value - Object
//
// Returns true if value exists in the set. Otherwise returns
// false.
Set.prototype.has = function (value) {
return this._map.has(value);
};
// Public: Add the value to the set.
//
// value - Object
//
// Returns 'undefined';
Set.prototype.add = function (value) {
this._map.set(value, true);
return 'undefined';
};
// Public: Removes the value from the set.
//
// value - Object
//
// Returns 'undefined';
Set.prototype['delete'] = function (value) {
this._map['delete'](value);
return 'undefined';
};
// Public: String representation of the Set.
//
// Returns String.
Set.prototype.toString = function () {
return '[object Set]';
};
// Internal: Node.js console.log inspect printer.
//
// Returns String.
Set.prototype.inspect = function () {
return "[edn.Set " + require('util').inspect(this.values) + "]";
};
return Set;
})();
}
(function () {
// Public: Convert Array to Set.
//
// values - Array of values
//
// Returns new Set.
edn.set = function (values) {
var set = new edn.Set();
if (values) {
values.forEach(function (v) {
set.add(v);
});
}
return set;
};
// Expose Set to parser
parser.yy.Set = edn.set;
// Public: Register typeof check for Set.
//
// obj - Any value
//
// Returns true if object is a Set, otherwise false.
edn.types.set = function (obj) {
return obj instanceof edn.Set;
};
// Public: Stringify Set object.
//
// set - Set object
//
// Returns String.
edn.printers.set = function (set) {
return "#{" + set.values.map(edn.stringify).join(" ") + "}";
};
// Public: Get valueOf returns primitive array.
edn.values.set = function (set, deep, valueOf) {
if (deep) {
return set.values.map(valueOf);
} else {
return set.values.slice(0);
}
};
// Public: Compare set collections.
//
// a - set value
// b - set value
// isEqual - isEqual function
//
// Returns true collection of values is equal.
edn.equal.set = function (a, b, isEqual) {
var aValues = a.values;
var bValues = b.values;
if (aValues.length != bValues.length) {
return false;
}
return aValues.every(function (aValue) {
return bValues.some(function (bValue) {
return isEqual(aValue, bValue);
});
});
};
})();
// Tagged Elements
//
// edn supports extensibility through a simple mechanism. # followed
// immediately by a symbol starting with an alphabetic character
// indicates that that symbol is a tag. A tag indicates the semantic
// interpretation of the following element. It is envisioned that a
// reader implementation will allow clients to register handlers for
// specific tags. Upon encountering a tag, the reader will first read
// the next element, then pass the result to the corresponding handler
// for further interpretation, and the result of the handler will be
// the data value yielded by the tag + tagged element, i.e. reading a
// tag and tagged element yields one value. This value is the value to
// be returned to the program and is not further interpreted as edn
// data by the reader.
edn.tags = {};
// Public: Dispatch tag and tagged element.
//
// If a handler is registered for the tag, it will be invoked with the
// element returning a new value.
//
// Otherwise, the default handler will be invoked which will return an
// Generic object wrapper. If `edn.tags.default` is set to null, an
// error will be throw instead.
//
// Returns a value or raises an error if theres no tag handler.
edn.dispatchTag = function (tag, element, options) {
options = extendDefaultOptions(options);
var f = options.tags[tag];
if (f) {
return f(element);
} else if (options.tags.default) {
return options.tags.default(tag, element);
} else {
throw new Error("No reader function for tag " + tag);
}
};
// Expose tag to parser
parser.yy.Tag = edn.dispatchTag;
edn.Generic = (function () {
// Public: Create a new Generic object.
//
// tag - Symbol tag
// element - Any value
function Generic(tag, element) {
if (!(this instanceof Generic)) {
return new Generic(tag, element);
}
if (!(tag instanceof edn.Symbol)) {
tag = edn.Symbol(tag);
}
// Public: Returns the Symbol tag
this.tag = tag;
// Public: Returns the element value
this.element = element;
Object.freeze(this);
}
// Public: Get primitive string value.
//
// Returns String.
Generic.prototype.valueOf = function () {
return this.element;
};
// Public: String representation of the UUID.
//
// Returns String.
Generic.prototype.toString = function () {
return '[object Generic]';
};
// Internal: Node.js console.log inspect printer.
//
// Returns String.
Generic.prototype.inspect = function () {
return "[edn.Generic " + this.tag + " " +
require('util').inspect(this.element) + "]";
};
// Public: Register typeof check for Generic.
//
// obj - Any value
//
// Returns true if object is a Generic, otherwise false.
edn.types.generic = function (obj) {
return obj instanceof Generic;
};
// Public: Stringify Generic object.
//
// obj - Generic object
//
// Returns String.
edn.printers.generic = function (obj) {
return "#" + obj.tag + " " + edn.stringify(obj.element);
};
// Public: Get valueOf returns primitive array.
edn.values.generic = function (obj, deep, valueOf) {
return valueOf(obj.element);
};
// Public: Compare generic value.
//
// a - generic value
// b - generic value
// isEqual - isEqual function
//
// Returns true if tag and elements are equal.
edn.equal.generic = function (a, b, isEqual) {
return isEqual(a.tag, b.tag) && isEqual(a.element, b.element);
};
// Public: Register default handler for generic tags.
//
// tag - Symbol tag
// element - Any value
edn.tags.default = Generic;
// Public: Alias for Generic function.
edn.generic = Generic;
return Generic;
})();
// Built-in Tagged Elements
//
// Date built-in tagged element
//
// #inst "rfc-3339-format"
// #inst "1985-04-12T23:20:50.52Z"
//
// An instant in time. The tagged element is a string in RFC-3339 format.
(function () {
// Public: Convert 'inst' tag to Date object.
//
// str - ISO Date String
//
// Returns Date object.
edn.tags.inst = function (str) {
return new Date(Date.parse(str));
};
// Public: Register typeof check for Date.
//
// obj - Any value
//
// Returns true if object is a Date, otherwise false.
edn.types.inst = function (obj) {
return obj instanceof Date;
};
// Public: Convert Date to and EDN value.
//
// date - Date object
//
// Returns an Generic object.
edn.converters.inst = function (date) {
return edn.generic('inst', date.toISOString());
};
})();
// UUID built-in tagged element
//
// #uuid "f81d4fae-7dec-11d0-a765-00a0c91e6bf6"
//
// A UUID. The tagged element is a canonical UUID string representation.
edn.UUID = (function () {
// Public: Create a new UUID object.
//
// value - String value.
function UUID(value) {
if (!(this instanceof UUID)) {
return new UUID(value);
}
// Internal: Returns the String value.
this.value = value;
// Public: Returns the Number length of the value String.
Object.defineProperty(this, 'length', {
enumerable: false,
value: value.length
});
Object.freeze(this);
}
// Public: Get primitive string value.
//
// Returns String.
UUID.prototype.valueOf = function () {
return this.value;
};
// Public: String representation of the UUID.
//
// Returns String.
UUID.prototype.toString = function () {
return this.value;
};
// Internal: Node.js console.log inspect printer.
//
// Returns String.
UUID.prototype.inspect = function () {
return "[edn.UUID " + this.value + "]";
};
// Public: Convert 'uuid' tag to UUID object.
//
// str - String
//
// Returns UUID object.
edn.tags.uuid = function (str) {
return new UUID(str);
};
// Public: Register typeof check for UUID.
//
// obj - Any value
//
// Returns true if object is a UUID, otherwise false.
edn.types.uuid = function (obj) {
return obj instanceof UUID;
};
// Public: Convert UUID to and EDN value.
//
// uuid - UUID object
//
// Returns an Generic object.
edn.converters.uuid = function (uuid) {
return edn.generic('uuid', uuid.value);
};
// Public: Alias for UUID function.
edn.uuid = UUID;
return UUID;
})();
|
'use strict';
var lstat = require('fs').lstat;
var readdir = require('fs').readdir;
var isArray = require('util').isArray;
var joinPath = require('path').join;
/**
* Constructor
*
* @param String {dir} (optional)
* @param RegExp {filter} (optional)
*/
function RecDirReader(dir, filter) {
if (this === undefined) return new RecDirReader(dir, filter);
this._wc = 0;
this._dir = dir || '.';
this._filter = filter || /.*/;
}
require('util').inherits(RecDirReader, require('events').EventEmitter);
/**
* Set filter RegExp.
*
* @param RegExp {filter} (optional)
* @return RecDirReader
*/
RecDirReader.prototype.filter = function(filter) {
this._filter = filter;
return this;
};
/**
* Set directory to {dir}.
*
* @param String {dir}
* @return RecDirReader
*/
RecDirReader.prototype.dir = function(dir) {
this._dir = dir;
return this;
};
/**
* Decrease the Wait Counter and emit the "end" event if it reaches 0.
*/
RecDirReader.prototype._decreaseWaitCount = function() {
if (--this._wc === 0) this.emit('end');
};
/**
* Emit an "error" event if there's a listener for the "error" event.
*
* @param Error {err}
*/
RecDirReader.prototype._emitError = function(err) {
if (Object.hasOwnProperty.call(this._events, 'error')) this.emit('error', err);
};
/**
* Start directory scan.
*
* @param String dir
* @return RecDirReader
*/
RecDirReader.prototype.scan = function(dir) {
var self = this;
// Use the standard directory if {dir} is not set.
if (dir === undefined) dir = this._dir;
// Consider, that {dir} can also be an array with directories.
if (isArray(dir)) {
dir.forEach(function(dir) {
self.scan(dir);
});
return this;
}
this._wc++;
readdir(dir, function(err, filenames) {
if (err) {
self._emitError(err);
} else if (filenames.length === 0) {
self.emit('empty', dir);
} else {
filenames.forEach(function(filename) {
var file = joinPath(dir, filename);
self._wc++;
lstat(file, function(err, stat) {
if (err) {
self._emitError(err);
} else {
self.emit('any', file, stat);
if (stat.isDirectory()) {
self.emit('directory', file, stat);
self.scan(file);
} else if (self._filter.test(file)) {
if (stat.isFile()) self.emit('file', file, stat);
else if (stat.isSymbolicLink()) self.emit('symboliclink', file, stat);
else if (stat.isBlockDevice()) self.emit('blockdevice', file, stat);
else if (stat.isCharacterDevice()) self.emit('characterdevice', file, stat);
else if (stat.isFIFO()) self.emit('fifo', file, stat);
else if (stat.isSocket()) self.emit('socket', file, stat);
}
}
self._decreaseWaitCount();
});
});
}
self._decreaseWaitCount();
});
return this;
};
exports = module.exports = RecDirReader;
|
/// <reference path="./global.d.ts" />
// @ts-check
//
// The lines above enable type checking for this file. Various IDEs interpret
// the @ts-check and reference directives. Together, they give you helpful
// autocompletion when implementing this exercise. You don't need to understand
// them in order to use it.
//
// In your own projects, files, and code, you can play with @ts-check as well.
export class TranslationService {
/**
* Creates a new service
* @param {ExternalApi} api the original api
*/
constructor(api) {
this.api = api;
}
/**
* Attempts to retrieve the translation for the given text.
*
* - Returns whichever translation can be retrieved, regardless the quality
* - Forwards any error from the translation api
*
* @param {string} text
* @returns {Promise<string>}
*/
free(text) {
throw new Error('Implement the free function');
}
/**
* Batch translates the given texts using the free service.
*
* - Resolves all the translations (in the same order), if they all succeed
* - Rejects with the first error that is encountered
* - Rejects with a BatchIsEmpty error if no texts are given
*
* @param {string[]} texts
* @returns {Promise<string[]>}
*/
batch(texts) {
throw new Error('Implement the batch function');
}
/**
* Requests the service for some text to be translated.
*
* Note: the request service is flaky, and it may take up to three times for
* it to accept the request.
*
* @param {string} text
* @returns {Promise<void>}
*/
request(text) {
throw new Error('Implement the request function');
}
/**
* Retrieves the translation for the given text
*
* - Rejects with an error if the quality can not be met
* - Requests a translation if the translation is not available, then retries
*
* @param {string} text
* @param {number} minimumQuality
* @returns {Promise<string>}
*/
premium(text, minimumQuality) {
throw new Error('Implement the premium function');
}
}
/**
* This error is used to indicate a translation was found, but its quality does
* not meet a certain threshold. Do not change the name of this error.
*/
export class QualityThresholdNotMet extends Error {
/**
* @param {string} text
*/
constructor(text) {
super(
`
The translation of ${text} does not meet the requested quality threshold.
`.trim()
);
this.text = text;
}
}
/**
* This error is used to indicate the batch service was called without any
* texts to translate (it was empty). Do not change the name of this error.
*/
export class BatchIsEmpty extends Error {
constructor() {
super(
`
Requested a batch translation, but there are no texts in the batch.
`.trim()
);
}
}
|
/*!
* author Tony Beltramelli
* http://www.tonybeltramelli.com
*
*/
PopInManager = function() {
};
PopInManager.prototype.constructor = PopInManager;
PopInManager.prototype.show = function(title, description)
{
this.build(title, "<p>"+description+"</p>");
$("#popInManager").delay(1200).fadeOut(500, this.remove);
};
PopInManager.prototype.showHomePopUp = function()
{
var content = '<p>This website is an experiment build with love and the latest web technologies HTML5, WebGL and CSS3.</p><br/>';
var step1 = '<div class="step"><li class="button">1 - Create</li><p>First, create your own design for your aircraft from body to blades.</p></div>';
var step2 = '<div class="step"><li class="button">2 - Fly</li><p>Then, take the commands and fly with it in an infinitely big world.</p></div>';
var step3 = '<div class="step"><li class="button">3 - Share</li><p>Finally, share it with your friends and explore the WebCopter gallery.</p></div>';
var button = '<a class="button nav" href="#">Start</a>';
this.build("Hi there !", "<div class='description'>"+content+step1+step2+step3+button+"</div>", true);
var self = this;
$("#popInManager a.button").click(function(e)
{
e.preventDefault();
$("#popInManager").fadeOut(500, self.remove);
});
};
PopInManager.prototype.showAbout = function()
{
var p1 = '<p>This website is an experiment created with the latest web technologies HTML5, WebGL, OpenGL Shaders and CSS3.</p><br/>';
var p2 = '<p>The free Javascript librairies <a target="_blank" href="http://mrdoob.github.com/three.js/">three.js</a> and <a target="_blank" href="http://jquery.com//">jQuery</a> have been used.</p><br/>';
var p3 = '<p>Build with love by <a href="http://www.tonybeltramelli.com" target="_blank">Tony Beltramelli</a>.</p>';
this.build("WTF", "<div class='description'>"+p1+p2+p3+"</div>", true);
};
PopInManager.prototype.showCommands = function()
{
var content = '<p class="ready">Get ready to fly in an infinite world.</p>';
var keysContent = '<img src="images/keys.png" alt="keys to fly"/><p>You can fly either with W A S D keys or the arrow keys.</p><div class="clear"></div>';
this.build("How to fly", "<div class='description'>"+keysContent+content+"</div>", true);
};
PopInManager.prototype.showCompatibilityMessage = function()
{
var content = '<div class="browsers"><p>Sorry, your graphics card or your web browser do not properly support the latest web technologies HTML5 / WebGL. <br /> Please download one of the web browser below for free or get <a href="http://khronos.org/webgl/wiki/Getting_a_WebGL_Implementation">WebGL implementation informations</a>.</p><a class="browser" href="http://www.google.fr/chrome" target="_blank"><img src="images/chrome.jpg" alt="chrome logo"/></a><a class="browser" href="http://www.mozilla.org/firefox/" target="_blank"><img src="images/firefox.jpg" alt="firefox logo"/></a><div class="clear"></div></div>';
this.build("Not supported", "<div class='description'>"+content+"</div>", true);
};
PopInManager.prototype.build = function(title, description, big)
{
$("body").append("<div id='popInManager'><div></div></div>");
if(big) $("#popInManager").addClass("big");
$("#popInManager > div").append("<h3>"+title+"</h3><a href='#' class='closeBtn'></a>");
$("#popInManager > div").append(description);
$("#popInManager").fadeOut(0);
$("#popInManager").fadeIn(500);
var self = this;
$("#popInManager .closeBtn").click(function(e){
$("#popInManager").fadeOut(500, self.remove);
});
this.position();
};
PopInManager.prototype.position = function()
{
var topPosition = $("#popInManager").height()/2 - $("#popInManager > div").height()/2;
$("#popInManager > div").css("top", topPosition+"px");
};
PopInManager.prototype.remove = function(){
$("#popInManager").detach();
}; |
var Canal = require('../canal.js');
var expect = require("expect.js");
describe("Test flatten", function(){
it("flatten() [1 2]", function()
{
var result = Canal.of([ [ 1, 2 ], [ 2, 3 ], [ 3, 4 ] ]) //
.flatten().collect();
expect(result).to.eql([ [ 1, 2 ], [ 2, 3 ], [ 3, 4 ] ]);
});
it("flatten() [1 [2 3]]", function()
{
var result = Canal
.of([ [ 1, [ 2, 3 ] ], [ 2, [ 3, 4 ] ], [ 3, [ 4, 5 ] ] ]) //
.flatten().collect();
expect(result).to.eql([ [ 1, 2, 3 ], [ 2, 3, 4 ], [ 3, 4, 5 ] ]);
});
it("flatten() [1 [2 3] 4]", function()
{
var result = Canal.of(
[ [ 1, [ 2, 3 ], 4 ], [ 2, [ 3, 4 ], 5 ], [ 3, [ 4, 5 ], 6 ] ]) //
.flatten().collect();
expect(result).to.eql(
[ [ 1, 2, 3, 4 ], [ 2, 3, 4, 5 ], [ 3, 4, 5, 6 ] ]);
});
it("flatten() [1 [2 [3]]]", function()
{
var result = Canal.of(
[ [ 1, [ 2, [ 3 ] ] ], [ 2, [ 3, [ 4 ] ] ], [ 3, [ 4, [ 5 ] ] ] ]) //
.flatten().collect();
expect(result).to.eql([ [ 1, 2, 3 ], [ 2, 3, 4 ], [ 3, 4, 5 ] ]);
});
it("flatten(1) [1 [2 [3]]]", function()
{
var result = Canal.of(
[ [ 1, [ 2, [ 3 ] ] ], [ 2, [ 3, [ 4 ] ] ], [ 3, [ 4, [ 5 ] ] ] ]) //
.flatten(1).collect();
expect(result).to.eql([ [ 1, 2, [ 3 ] ], [ 2, 3, [ 4 ] ],
[ 3, 4, [ 5 ] ] ]);
});
it("flatten() [[[1] 2] 3]", function()
{
var result = Canal.of(
[ [ [ [ 1 ], 2 ], 3 ], [ [ [ 2 ], 3 ], 4 ], [ [ [ 3 ], 4 ], 5 ] ]) //
.flatten().collect();
expect(result).to.eql([ [ 1, 2, 3 ], [ 2, 3, 4 ], [ 3, 4, 5 ] ]);
});
it("flatten(1) [[[1] 2] 3]", function()
{
var result = Canal.of(
[ [ [ [ 1 ], 2 ], 3 ], [ [ [ 2 ], 3 ], 4 ], [ [ [ 3 ], 4 ], 5 ] ]) //
.flatten(1).collect();
expect(result).to.eql([ [ [ 1 ], 2, 3 ], [ [ 2 ], 3, 4 ],
[ [ 3 ], 4, 5 ] ]);
});
it("flatten() empty", function()
{
var result = Canal.of([]) //
.flatten().collect();
expect(result).to.eql([]);
});
});
|
module.exports = function (grunt) {
// custom task
grunt.registerMultiTask('merge-templates', 'Merges the templates in the index.php.', function () {
var fileList = grunt.file.expand(grunt.config('merge-templates.default.files'));
var index = grunt.file.read(grunt.config('merge-templates.default.index'));
index = index.replace(/<!-- templates -->([\w\W]*)<!-- \/templates -->/gm, '');
var templates = '\t<!-- templates -->\n';
fileList.forEach(function (filepath) {
grunt.log.writeln('Merging "' + filepath + '"...');
var template = grunt.file.read(filepath);
templates += '\n<script type="text/html" id="' + /.*\/(.*?).html/gm.exec(filepath)[1] + '">\n\t' + template.split('\n').join('\n\t') + '\n</script>\n';
});
templates += '\n<!-- /templates -->\n';
templates = templates.split('\n').join('\n\t');
index = index.replace('</body>', templates + '\n</body>');
grunt.log.writeln('Writing index...');
grunt.file.write(grunt.config('merge-templates.default.index'), index);
});
} |
"use strict";
const setupTask = require('utils').setupTask;
const calcTasks = require("calcTasks");
module.exports = {
getTask : function(creep){
var room = creep.room
var creepsByTask = _(Game.creeps).filter( (c) => c.task && c.task.roomName == room.name).groupBy('task.type').value();
var mineMineralTasks = calcTasks.calcMineMineralTasks(room,creepsByTask);
var myIndex = _.findIndex(mineMineralTasks, (t) => t.assigned == 0);
if(myIndex != -1){
creep.task = mineMineralTasks[myIndex];
return OK;
}
else{
return;
}
},
run : function(creep){
if(!creep.task){
this.getTask(creep);
}
}
}
|
(function() {
console.log('Main.js loaded!');
})();
|
/**
* Native Component Test Template By => create-module script
* @version 1.2.0
*
*/
import React from 'react';
import { shallow } from 'enzyme';
import Icon from 'ui/Icon/Icon.native';
describe('test/app/ui/Icon/Icon.test.js', () => {
it('Render', () => {
const props = {};
const wrapper = shallow(<Icon {...props} />);
expect(wrapper).toMatchSnapshot();
});
});
|
/**
* @module opcua.server
*/
import assert from "better-assert";
import async from "async";
import NodeClass from "lib/datamodel/NodeClass";
import NodeId, {
resolveNodeId,
makeNodeId,
NodeIdType } from "lib/datamodel/NodeId";
import NumericRange from "lib/datamodel/numeric-range/NumericRange";
import { BrowseDirection, BrowseResult } from "lib/services/browse_service";
import {
ReadRequest,
AttributeIds,
TimestampsToReturn
} from "lib/services/read_service";
import BaseNode from "lib/address_space/BaseNode";
import UAObject from "lib/address_space/UAObject";
import UAVariable from "lib/address_space/UAVariable";
import { HistoryReadRequest, HistoryReadDetails, HistoryReadResult } from "lib/services/historizing_service";
import DataValue from "lib/datamodel/DataValue";
import { Variant } from "lib/datamodel/variant";
import { DataType } from "lib/datamodel/variant";
import { VariantArrayType } from "lib/datamodel/variant";
import { isValidVariant } from "lib/datamodel/variant";
import LocalizedText from "lib/datamodel/LocalizedText";
import BuildInfo from "lib/datamodel/Buildinfo";
import util from "util";
import { StatusCodes } from "lib/datamodel/opcua_status_code";
import { StatusCode } from "lib/datamodel/opcua_status_code";
import _ from "underscore";
import AddressSpace from "lib/address_space/AddressSpace";
import generateAddressSpace from "lib/address_space/generateAddressSpace";
import ServerSession from "lib/server/ServerSession";
import { VariableIds } from "lib/opcua_node_ids";
import { MethodIds } from "lib/opcua_node_ids";
import { ObjectIds } from "lib/opcua_node_ids";
import ReferenceType from "lib/address_space/ReferenceType";
import { EventEmitter } from "events";
import { ServerState } from "schemas/39394884f696ff0bf66bacc9a8032cc074e0158e/ServerState_enum";
import { ServerStatus } from "_generated_/_auto_generated_ServerStatus";
import { ServerDiagnosticsSummary } from "_generated_/_auto_generated_ServerDiagnosticsSummary";
import { constructFilename } from "lib/misc/utils";
import { ApplicationDescription } from "lib/services/get_endpoints_service";
import ServerCapabilities from "./ServerCapabilities";
import bindExtObjArrayNode from "lib/address_space/extension-object-array-node/bindExtObjArrayNode";
import ServerSidePublishEngine from "lib/server/ServerSidePublishEngine";
import { TransferResult } from "_generated_/_auto_generated_TransferResult";
import { CallMethodResult } from "lib/services/call_service";
import Argument from "lib/datamodel/argument-list/Argument";
import apply_timestamps from "lib/datamodel/DataValue/apply_timestamps";
import { WriteValue } from "lib/services/write_service";
import {
make_debugLog,
checkDebugFlag,
trace_from_this_projet_only
} from "lib/misc/utils";
import d from "lib/address_space/add-method/install";
const debugLog = make_debugLog(__filename);
const doDebug = checkDebugFlag(__filename);
/**
* @class ServerEngine
* @extends EventEmitter
* @uses ServerSidePublishEngine
* @param options {Object}
* @param options.buildInfo
* @param [options.isAuditing = false ] {Boolean}
* @param [options.serverCapabilities]
* @param [options.serverCapabilities.serverProfileArray]
* @param [options.serverCapabilities.localeIdArray]
* @param options.applicationUri {String} the application URI.
* @constructor
*/
class ServerEngine extends EventEmitter {
constructor(options = {}) {
super(...arguments);
options.buildInfo = options.buildInfo || {};
EventEmitter.apply(this, arguments);
this._sessions = {};
this._closedSessions = {};
this.isAuditing = _.isBoolean(options.isAuditing) ? options.isAuditing : false;
// ---------------------------------------------------- ServerStatus
this.serverStatus = new ServerStatus({
startTime: new Date(),
currentTime: new Date(),
state: ServerState.NoConfiguration,
buildInfo: options.buildInfo,
secondsTillShutdown: 10,
shutdownReason: { text: "" }
});
var self = this;
this.serverStatus.__defineGetter__("secondsTillShutdown", () => self.secondsTillShutdown());
this.serverStatus.__defineGetter__("currentTime", () => new Date());
this.serverStatus.__defineSetter__("currentTime", (value) => {
// DO NOTHING currentTime is readonly
});
// --------------------------------------------------- ServerCapabilities
options.serverCapabilities = options.serverCapabilities || {};
options.serverCapabilities.serverProfileArray = options.serverCapabilities.serverProfileArray || [];
options.serverCapabilities.localeIdArray = options.serverCapabilities.localeIdArray || ["en-EN", "fr-FR"];
this.serverCapabilities = new ServerCapabilities(options.serverCapabilities);
// --------------------------------------------------- serverDiagnosticsSummary
this.serverDiagnosticsSummary = new ServerDiagnosticsSummary({
});
assert(this.serverDiagnosticsSummary.hasOwnProperty("currentSessionCount"));
var self = this;
this.serverDiagnosticsSummary.__defineGetter__("currentSessionCount", () => Object.keys(self._sessions).length);
assert(this.serverDiagnosticsSummary.hasOwnProperty("currentSubscriptionCount"));
this.serverDiagnosticsSummary.__defineGetter__("currentSubscriptionCount", () => {
// currentSubscriptionCount returns the total number of subscriptions
// that are currently active on all sessions
let counter = 0;
_.values(self._sessions).forEach((session) => {
counter += session.currentSubscriptionCount;
});
return counter;
});
this.status = "creating";
this.setServerState(ServerState.NoConfiguration);
this.addressSpace = null;
this._shutdownTask = [];
this._applicationUri = options.applicationUri || "<unset _applicationUri>";
}
/**
* register a function that will be called when the server will perform its shut down.
* @method registerShutdownTask
*/
registerShutdownTask(task) {
assert(_.isFunction(task));
this._shutdownTask.push(task);
}
/**
* @method shutdown
*/
shutdown() {
const self = this;
self.status = "shutdown";
self.setServerState(ServerState.Shutdown);
// delete any existing sessions
const tokens = Object.keys(self._sessions).map((key) => {
const session = self._sessions[key];
return session.authenticationToken;
});
// xx console.log("xxxxxxxxx ServerEngine.shutdown must terminate "+ tokens.length," sessions");
tokens.forEach((token) => {
self.closeSession(token, true, "Terminated");
});
// all sessions must have been terminated
assert(self.currentSessionCount === 0);
self._shutdownTask.push(disposeAddressSpace);
// perform registerShutdownTask
self._shutdownTask.forEach((task) => {
task.call(self);
});
}
/**
* @method secondsTillShutdown
* @return {UInt32} the approximate number of seconds until the server will be shut down. The
* value is only relevant once the state changes into SHUTDOWN.
*/
secondsTillShutdown() {
return; // ToDo: implement a correct solution here
1;
}
setServerState(serverState) {
assert(serverState !== null && serverState !== undefined);
this.serverStatus.state = serverState;
}
/**
* @method initialize
* @async
*
* @param options {Object}
* @param options.nodeset_filename {String} - [option](default : 'mini.Node.Set2.xml' )
* @param callback
*/
initialize(options, callback) {
const self = this;
assert(!self.addressSpace); // check that 'initialize' has not been already called
self.status = "initializing";
options = options || {};
assert(_.isFunction(callback));
options.nodeset_filename = options.nodeset_filename || standard_nodeset_file;
const startTime = new Date();
debugLog("Loading ", options.nodeset_filename, "...");
self.addressSpace = new AddressSpace();
// register namespace 1 (our namespace);
const serverNamespaceIndex = self.addressSpace.registerNamespace(self.serverNamespaceUrn);
assert(serverNamespaceIndex === 1);
generateAddressSpace(self.addressSpace, options.nodeset_filename, () => {
const endTime = new Date();
debugLog("Loading ", options.nodeset_filename, " done : ", endTime - startTime, " ms");
function findObjectNodeId(name) {
const obj = self.addressSpace.findNode(name);
return obj ? obj.nodeId : null;
}
self.FolderTypeId = findObjectNodeId("FolderType");
self.BaseObjectTypeId = findObjectNodeId("BaseObjectType");
self.BaseDataVariableTypeId = findObjectNodeId("BaseDataVariableType");
self.rootFolder = self.addressSpace.findNode("RootFolder");
assert(self.rootFolder.readAttribute);
self.setServerState(ServerState.Running);
function bindVariableIfPresent(nodeId, opts) {
assert(nodeId instanceof NodeId);
assert(!nodeId.isEmpty());
const obj = self.addressSpace.findNode(nodeId);
if (obj) {
__bindVariable(self, nodeId, opts);
}
return obj;
}
// -------------------------------------------- install default get/put handler
const server_NamespaceArray_Id = makeNodeId(VariableIds.Server_NamespaceArray); // ns=0;i=2255
bindVariableIfPresent(server_NamespaceArray_Id, {
get() {
return new Variant({
dataType: DataType.String,
arrayType: VariantArrayType.Array,
value: self.addressSpace.getNamespaceArray()
});
},
set: null // read only
});
const server_NameUrn_var = new Variant({
dataType: DataType.String,
arrayType: VariantArrayType.Array,
value: [
self.serverNameUrn // this is us !
]
});
const server_ServerArray_Id = makeNodeId(VariableIds.Server_ServerArray); // ns=0;i=2254
bindVariableIfPresent(server_ServerArray_Id, {
get() {
return server_NameUrn_var;
},
set: null // read only
});
function bindStandardScalar(id, dataType, func, setter_func) {
assert(_.isNumber(id));
assert(_.isFunction(func));
assert(_.isFunction(setter_func) || !setter_func);
assert(dataType !== null); // check invalid dataType
let setter_func2 = null;
if (setter_func) {
setter_func2 = (variant) => {
const variable2 = !!variant.value;
setter_func(variable2);
return StatusCodes.Good;
};
}
const nodeId = makeNodeId(id);
// make sur the provided function returns a valid value for the variant type
// This test may not be exhaustive but it will detect obvious mistakes.
assert(isValidVariant(VariantArrayType.Scalar, dataType, func()));
return bindVariableIfPresent(nodeId, {
get() {
return new Variant({
dataType,
arrayType: VariantArrayType.Scalar,
value: func()
});
},
set: setter_func2
});
}
function bindStandardArray(id, variantDataType, dataType, func) {
assert(_.isFunction(func));
assert(variantDataType !== null); // check invalid dataType
const nodeId = makeNodeId(id);
// make sur the provided function returns a valid value for the variant type
// This test may not be exhaustive but it will detect obvious mistakes.
assert(isValidVariant(VariantArrayType.Array, dataType, func()));
bindVariableIfPresent(nodeId, {
get() {
const value = func();
assert(_.isArray(value));
return new Variant({
dataType: variantDataType,
arrayType: VariantArrayType.Array,
value
});
},
set: null // read only
});
}
bindStandardScalar(VariableIds.Server_ServiceLevel,
DataType.Byte, () => 255);
bindStandardScalar(VariableIds.Server_Auditing,
DataType.Boolean, () => self.isAuditing);
function bindServerDiagnostics() {
let serverDiagnostics_Enabled = false;
bindStandardScalar(VariableIds.Server_ServerDiagnostics_EnabledFlag,
DataType.Boolean, () => serverDiagnostics_Enabled, (newFlag) => {
serverDiagnostics_Enabled = newFlag;
});
const serverDiagnosticsSummary_var = new Variant({
dataType: DataType.ExtensionObject,
value: self.serverDiagnosticsSummary
});
bindVariableIfPresent(makeNodeId(VariableIds.Server_ServerDiagnostics_ServerDiagnosticsSummary), {
get() {
return serverDiagnosticsSummary_var;
},
set: null
});
const serverDiagnosticsSummary = self.addressSpace.findNode(makeNodeId(VariableIds.Server_ServerDiagnostics_ServerDiagnosticsSummary));
if (serverDiagnosticsSummary) {
serverDiagnosticsSummary.bindExtensionObject();
}
}
function bindServerStatus() {
bindVariableIfPresent(makeNodeId(VariableIds.Server_ServerStatus), {
get() {
const serverStatus_var = new Variant({
dataType: DataType.ExtensionObject,
value: self.serverStatus.clone()
});
return serverStatus_var;
},
set: null
});
const serverStatus = self.addressSpace.findNode(makeNodeId(VariableIds.Server_ServerStatus));
if (serverStatus) {
serverStatus.bindExtensionObject();
serverStatus.miminumSamplingInterval = 250;
}
const currentTimeNode = self.addressSpace.findNode(makeNodeId(VariableIds.Server_ServerStatus_CurrentTime));
if (currentTimeNode) {
currentTimeNode.miminumSamplingInterval = 250;
}
}
function bindServerCapabilities() {
bindStandardArray(VariableIds.Server_ServerCapabilities_ServerProfileArray,
DataType.String, "String", () => self.serverCapabilities.serverProfileArray);
bindStandardArray(VariableIds.Server_ServerCapabilities_LocaleIdArray,
DataType.String, "LocaleId", () => self.serverCapabilities.localeIdArray);
bindStandardScalar(VariableIds.Server_ServerCapabilities_MinSupportedSampleRate,
DataType.Double, () => self.serverCapabilities.minSupportedSampleRate);
bindStandardScalar(VariableIds.Server_ServerCapabilities_MaxBrowseContinuationPoints,
DataType.UInt16, () => self.serverCapabilities.maxBrowseContinuationPoints);
bindStandardScalar(VariableIds.Server_ServerCapabilities_MaxQueryContinuationPoints,
DataType.UInt16, () => self.serverCapabilities.maxQueryContinuationPoints);
bindStandardScalar(VariableIds.Server_ServerCapabilities_MaxHistoryContinuationPoints,
DataType.UInt16, () => self.serverCapabilities.maxHistoryContinuationPoints);
bindStandardArray(VariableIds.Server_ServerCapabilities_SoftwareCertificates,
DataType.ByteString, "SoftwareCertificates", () => self.serverCapabilities.softwareCertificates);
bindStandardScalar(VariableIds.Server_ServerCapabilities_MaxArrayLength,
DataType.UInt32, () => self.serverCapabilities.maxArrayLength);
bindStandardScalar(VariableIds.Server_ServerCapabilities_MaxStringLength,
DataType.UInt32, () => self.serverCapabilities.maxStringLength);
function bindOperationLimits(operationLimits) {
assert(_.isObject(operationLimits));
function upperCaseFirst(str) {
return str.slice(0, 1).toUpperCase() + str.slice(1);
}
// Xx bindStandardArray(VariableIds.Server_ServerCapabilities_OperationLimits_MaxNodesPerWrite,
// Xx DataType.UInt32, "UInt32", function () { return operationLimits.maxNodesPerWrite; });
const keys = Object.keys(operationLimits);
keys.forEach((key) => {
const uid = `Server_ServerCapabilities_OperationLimits_${upperCaseFirst(key)}`;
const nodeId = makeNodeId(VariableIds[uid]);
// xx console.log("xxx Binding ".bgCyan,uid,nodeId.toString());
assert(!nodeId.isEmpty());
bindStandardScalar(VariableIds[uid],
DataType.UInt32, () => operationLimits[key]);
});
}
bindOperationLimits(self.serverCapabilities.operationLimits);
}
bindServerDiagnostics();
bindServerStatus();
bindServerCapabilities();
function bindExtraStuff() {
// mainly for compliance
// The version number for the data type description. i=104
bindStandardScalar(VariableIds.DataTypeDescriptionType_DataTypeVersion,
DataType.UInt16, () => 0.0);
// i=111
bindStandardScalar(VariableIds.ModellingRuleType_NamingRule,
DataType.UInt16, () => 0.0);
// i=112
bindStandardScalar(VariableIds.ModellingRule_Mandatory_NamingRule,
DataType.UInt16, () => 0.0);
// i=113
bindStandardScalar(VariableIds.ModellingRule_Optional_NamingRule,
DataType.UInt16, () => 0.0);
}
bindExtraStuff();
self.__internal_bindMethod(makeNodeId(MethodIds.Server_GetMonitoredItems), getMonitoredItemsId.bind(self));
function prepareServerDiagnostics() {
const addressSpace = self.addressSpace;
if (!addressSpace.rootFolder.objects) {
return;
}
const server = addressSpace.rootFolder.objects.server;
if (!server) {
return;
}
// create SessionsDiagnosticsSummary
const serverDiagnostics = server.getComponentByName("ServerDiagnostics");
if (!serverDiagnostics) {
return;
}
const subscriptionDiagnosticsArray = serverDiagnostics.getComponentByName("SubscriptionDiagnosticsArray");
assert(subscriptionDiagnosticsArray instanceof UAVariable);
bindExtObjArrayNode(subscriptionDiagnosticsArray, "SubscriptionDiagnosticsType", "subscriptionId");
}
prepareServerDiagnostics();
self.status = "initialized";
setImmediate(callback);
});
}
__findObject(nodeId) {
// coerce nodeToBrowse to NodeId
try {
nodeId = resolveNodeId(nodeId);
} catch (err) {
return null;
}
assert(nodeId instanceof NodeId);
return this.addressSpace.findNode(nodeId);
}
/**
*
* @method browseSingleNode
* @param nodeId {NodeId|String} : the nodeid of the element to browse
* @param browseDescription
* @param browseDescription.browseDirection {BrowseDirection} :
* @param browseDescription.referenceTypeId {String|NodeId}
* @param [session] {ServerSession}
* @return {BrowseResult}
*/
browseSingleNode(nodeId, browseDescription, session) {
// create default browseDescription
browseDescription = browseDescription || {};
browseDescription.browseDirection = browseDescription.browseDirection || BrowseDirection.Forward;
const self = this;
assert(self.addressSpace instanceof AddressSpace); // initialize not called
assert(browseDescription.browseDirection);
// xx console.log(util.inspect(browseDescription,{colors:true,depth:5}));
browseDescription = browseDescription || {};
if (typeof nodeId === "string") {
const node = self.addressSpace.findNode(self.addressSpace.resolveNodeId(nodeId));
if (node) {
nodeId = node.nodeId;
}
}
const browseResult = {
statusCode: StatusCodes.Good,
continuationPoint: null,
references: null
};
if (browseDescription.browseDirection === BrowseDirection.Invalid) {
browseResult.statusCode = StatusCodes.BadBrowseDirectionInvalid;
return new BrowseResult(browseResult);
}
// check if referenceTypeId is correct
if (browseDescription.referenceTypeId instanceof NodeId) {
if (browseDescription.referenceTypeId.value === 0) {
browseDescription.referenceTypeId = null;
} else {
const rf = self.addressSpace.findNode(browseDescription.referenceTypeId);
if (!rf || !(rf instanceof ReferenceType)) {
browseResult.statusCode = StatusCodes.BadReferenceTypeIdInvalid;
return new BrowseResult(browseResult);
}
}
}
const obj = self.__findObject(nodeId);
if (!obj) {
// Object Not Found
browseResult.statusCode = StatusCodes.BadNodeIdUnknown;
// xx console.log("xxxxxx browsing ",nodeId.toString() , " not found" );
} else {
browseResult.statusCode = StatusCodes.Good;
browseResult.references = obj.browseNode(browseDescription, session);
}
return new BrowseResult(browseResult);
}
/**
*
* @method browse
* @param nodesToBrowse {BrowseDescription[]}
* @param [session] {ServerSession}
* @return {BrowseResult[]}
*/
browse(nodesToBrowse, session) {
const self = this;
assert(self.addressSpace instanceof AddressSpace); // initialize not called
assert(_.isArray(nodesToBrowse));
const results = [];
nodesToBrowse.forEach((browseDescription) => {
const nodeId = resolveNodeId(browseDescription.nodeId);
const r = self.browseSingleNode(nodeId, browseDescription, session);
results.push(r);
});
return results;
}
/**
*
* @method readSingleNode
* @param nodeId
* @param attributeId {AttributeId}
* @param [timestampsToReturn=TimestampsToReturn.Neither]
* @return {DataValue}
*/
readSingleNode(nodeId, attributeId, timestampsToReturn) {
return this._readSingleNode({
nodeId,
attributeId
}, timestampsToReturn);
}
_readSingleNode(nodeToRead, timestampsToReturn) {
const self = this;
const nodeId = nodeToRead.nodeId;
const attributeId = nodeToRead.attributeId;
const indexRange = nodeToRead.indexRange;
const dataEncoding = nodeToRead.dataEncoding;
assert(self.addressSpace instanceof AddressSpace); // initialize not called
if (timestampsToReturn === TimestampsToReturn.Invalid) {
return new DataValue({ statusCode: StatusCodes.BadTimestampsToReturnInvalid });
}
timestampsToReturn = (_.isObject(timestampsToReturn)) ? timestampsToReturn : TimestampsToReturn.Neither;
const obj = self.__findObject(nodeId);
if (!obj) {
// may be return BadNodeIdUnknown in dataValue instead ?
// Object Not Found
return new DataValue({ statusCode: StatusCodes.BadNodeIdUnknown });
}
// check access
// BadUserAccessDenied
// BadNotReadable
// invalid attributes : BadNodeAttributesInvalid
// invalid range : BadIndexRangeInvalid
try {
var dataValue = obj.readAttribute(attributeId, indexRange, dataEncoding);
assert(dataValue.statusCode instanceof StatusCode);
assert(dataValue.isValid());
} catch (err) {
console.log(" Internal error reading ", obj.nodeId.toString());
console.log(" ", err.message);
return new DataValue({ statusCode: StatusCodes.BadInternalError });
}
dataValue = apply_timestamps(dataValue, timestampsToReturn, attributeId);
return dataValue;
}
/**
*
* @method read
* @param readRequest {ReadRequest}
* @param readRequest.timestampsToReturn {TimestampsToReturn}
* @param readRequest.nodesToRead
* @param readRequest.maxAge {Number} maxAge - must be greater or equal than zero.
*
* Maximum age of the value to be read in milliseconds. The age of the value is based on the difference between the
* ServerTimestamp and the time when the Server starts processing the request. For example if the Client specifies a
* maxAge of 500 milliseconds and it takes 100 milliseconds until the Server starts processing the request, the age
* of the returned value could be 600 milliseconds prior to the time it was requested.
* If the Server has one or more values of an Attribute that are within the maximum age, it can return any one of the
* values or it can read a new value from the data source. The number of values of an Attribute that a Server has
* depends on the number of MonitoredItems that are defined for the Attribute. In any case, the Client can make no
* assumption about which copy of the data will be returned.
* If the Server does not have a value that is within the maximum age, it shall attempt to read a new value from the
* data source.
* If the Server cannot meet the requested maxAge, it returns its 'best effort' value rather than rejecting the
* request.
* This may occur when the time it takes the Server to process and return the new data value after it has been
* accessed is greater than the specified maximum age.
* If maxAge is set to 0, the Server shall attempt to read a new value from the data source.
* If maxAge is set to the max Int32 value or greater, the Server shall attempt to geta cached value. Negative values
* are invalid for maxAge.
*
* @return {DataValue[]}
*/
read(readRequest) {
assert(readRequest instanceof ReadRequest);
assert(readRequest.maxAge >= 0);
const self = this;
const timestampsToReturn = readRequest.timestampsToReturn;
const nodesToRead = readRequest.nodesToRead;
assert(self.addressSpace instanceof AddressSpace); // initialize not called
assert(_.isArray(nodesToRead));
const dataValues = nodesToRead.map((readValueId) => {
assert(readValueId.indexRange instanceof NumericRange);
return self._readSingleNode(readValueId, timestampsToReturn);
});
assert(dataValues.length === readRequest.nodesToRead.length);
return dataValues;
}
/**
*
* @method writeSingleNode
* @param writeValue {DataValue}
* @param callback {Function}
* @param callback.err {Error|null}
* @param callback.statusCode {StatusCode}
* @async
*/
writeSingleNode(writeValue, callback) {
const self = this;
assert(_.isFunction(callback));
assert(writeValue._schema.name === "WriteValue");
assert(writeValue.value instanceof DataValue);
if (writeValue.value.value === null) {
return callback(null, StatusCodes.BadTypeMismatch);
}
assert(writeValue.value.value instanceof Variant);
assert(self.addressSpace instanceof AddressSpace); // initialize not called
const nodeId = writeValue.nodeId;
const obj = self.__findObject(nodeId);
if (!obj) {
callback(null, StatusCodes.BadNodeIdUnknown);
} else {
obj.writeAttribute(writeValue, callback);
}
}
/**
* write a collection of nodes
* @method write
* @param nodesToWrite {Object[]}
* @param callback {Function}
* @param callback.err
* @param callback.results {StatusCode[]}
* @async
*/
write(nodesToWrite, callback) {
assert(_.isFunction(callback));
const self = this;
assert(self.addressSpace instanceof AddressSpace); // initialize not called
function performWrite(writeValue, inner_callback) {
assert(writeValue instanceof WriteValue);
self.writeSingleNode(writeValue, inner_callback);
}
async.map(nodesToWrite, performWrite, (err, statusCodes) => {
assert(_.isArray(statusCodes));
callback(err, statusCodes);
});
}
/**
*
* @method historyReadSingleNode
* @param nodeId
* @param attributeId {AttributeId}
* @param historyReadDetails {HistoryReadDetails}
* @param [timestampsToReturn=TimestampsToReturn.Neither]
* @param callback {Function}
* @param callback.err
* @param callback.results {HistoryReadResult}
*/
historyReadSingleNode(nodeId, attributeId, historyReadDetails, timestampsToReturn, callback) {
this._historyReadSingleNode({
nodeId,
attributeId
}, historyReadDetails, timestampsToReturn, callback);
}
_historyReadSingleNode(nodeToRead, historyReadDetails, timestampsToReturn, callback) {
const self = this;
const nodeId = nodeToRead.nodeId;
const indexRange = nodeToRead.indexRange;
const dataEncoding = nodeToRead.dataEncoding;
const continuationPoint = nodeToRead.continuationPoint;
assert(self.addressSpace instanceof AddressSpace); // initialize not called
if (timestampsToReturn === TimestampsToReturn.Invalid) {
return new DataValue({ statusCode: StatusCodes.BadTimestampsToReturnInvalid });
}
timestampsToReturn = (_.isObject(timestampsToReturn)) ? timestampsToReturn : TimestampsToReturn.Neither;
const obj = self.__findObject(nodeId);
if (!obj) {
// may be return BadNodeIdUnknown in dataValue instead ?
// Object Not Found
callback(null, new HistoryReadResult({ statusCode: StatusCodes.BadNodeIdUnknown }));
} else {
if (!obj.historyRead) {
// note : Object and View may also support historyRead to provide Event historical data
// todo implement historyRead for Object and View
const msg = ` this node doesn't provide historyRead! probably not a UAVariable\n ${obj.nodeId.toString()} ${obj.browseName.toString()}\nwith ${nodeToRead.toString()}\nHistoryReadDetails ${historyReadDetails.toString()}`;
if (doDebug) {
console.log("ServerEngine#_historyReadSingleNode ".cyan, msg.white.bold);
}
const err = new Error(msg);
// object has no historyRead method
return setImmediate(callback.bind(null, err));
}
// check access
// BadUserAccessDenied
// BadNotReadable
// invalid attributes : BadNodeAttributesInvalid
// invalid range : BadIndexRangeInvalid
obj.historyRead(historyReadDetails, indexRange, dataEncoding, continuationPoint, (err, result) => {
assert(result.statusCode instanceof StatusCode);
assert(result.isValid());
// result = apply_timestamps(result, timestampsToReturn, attributeId);
callback(err, result);
});
}
}
/**
*
* @method historyRead
* @param historyReadRequest {HistoryReadRequest}
* @param historyReadRequest.requestHeader {RequestHeader}
* @param historyReadRequest.historyReadDetails {HistoryReadDetails}
* @param historyReadRequest.timestampsToReturn {TimestampsToReturn}
* @param historyReadRequest.releaseContinuationPoints {Boolean}
* @param historyReadRequest.nodesToRead {HistoryReadValueId[]}
* @param callback {Function}
* @param callback.err
* @param callback.results {HistoryReadResult[]}
*/
historyRead(historyReadRequest, callback) {
assert(historyReadRequest instanceof HistoryReadRequest);
assert(_.isFunction(callback));
const self = this;
const timestampsToReturn = historyReadRequest.timestampsToReturn;
const historyReadDetails = historyReadRequest.historyReadDetails;
const nodesToRead = historyReadRequest.nodesToRead;
assert(historyReadDetails instanceof HistoryReadDetails);
assert(self.addressSpace instanceof AddressSpace); // initialize not called
assert(_.isArray(nodesToRead));
const historyData = [];
async.eachSeries(nodesToRead, (readValueId, cbNode) => {
self._historyReadSingleNode(readValueId, historyReadDetails, timestampsToReturn, (err, result) => {
if (err && !result) {
result = new HistoryReadResult({ statusCode: StatusCodes.BadInternalError });
}
historyData.push(result);
async.setImmediate(cbNode); // it's not guaranteed that the historical read process is really asynchronous
});
}, (err) => {
assert(historyData.length === nodesToRead.length);
callback(err, historyData);
});
}
/**
* @method bindMethod
* @param nodeId {NodeId} the node id of the method
* @param func
* @param func.inputArguments {Array<Variant>}
* @param func.context {Object}
* @param func.callback {Function}
* @param func.callback.err {Error}
* @param func.callback.callMethodResult {CallMethodResult}
*/
__internal_bindMethod(nodeId, func) {
const self = this;
assert(_.isFunction(func));
assert(nodeId instanceof NodeId);
const methodNode = self.addressSpace.findNode(nodeId);
if (!methodNode) {
return;
}
if (methodNode && methodNode.bindMethod) {
methodNode.bindMethod(func);
} else {
// xx console.log((new Error()).stack);
console.error("WARNING: cannot bind a method with id ".yellow + nodeId.toString().cyan + ". please check your nodeset.xml file or add this node programmatically".yellow);
console.error(trace_from_this_projet_only(new Error()));
}
}
getOldestUnactivatedSession() {
const self = this;
const tmp = _.filter(self._sessions, session => session.status === "new");
if (tmp.length === 0) {
return null;
}
let session = tmp[0];
for (let i = 1; i < session.length; i++) {
const c = tmp[i];
if (session.creationDate.getTime() < c.creationDate.getTime()) {
session = c;
}
}
return session;
}
/**
* create a new server session object.
* @class ServerEngine
* @method createSession
* @param [options] {Object}
* @param [options.sessionTimeout = 1000] {Number} sessionTimeout
* @param [options.clientDescription] {ApplicationDescription}
* @return {ServerSession}
*/
createSession(options) {
options = options || {};
const self = this;
self.serverDiagnosticsSummary.cumulatedSessionCount += 1;
self.clientDescription = options.clientDescription || new ApplicationDescription({});
const sessionTimeout = options.sessionTimeout || 1000;
assert(_.isNumber(sessionTimeout));
const session = new ServerSession(self, self.cumulatedSessionCount, sessionTimeout);
const key = session.authenticationToken.toString();
self._sessions[key] = session;
// see spec OPC Unified Architecture, Part 2 page 26 Release 1.02
// TODO : When a Session is created, the Server adds an entry for the Client
// in its SessionDiagnosticsArray Variable
session.on("new_subscription", (subscription) => {
self.serverDiagnosticsSummary.cumulatedSubscriptionCount += 1;
// add the subscription diagnostics in our subscriptions diagnostics array
});
session.on("subscription_terminated", (subscription) => {
// remove the subscription diagnostics in our subscriptions diagnostics array
});
// OPC Unified Architecture, Part 4 23 Release 1.03
// Sessions are terminated by the Server automatically if the Client fails to issue a Service request on the Session
// within the timeout period negotiated by the Server in the CreateSession Service response. This protects the
// Server against Client failures and against situations where a failed underlying connection cannot be
// re-established. Clients shall be prepared to submit requests in a timely manner to prevent the Session from
// closing automatically. Clients may explicitly terminate sessions using the CloseSession Service.
session.on("timeout", () => {
// the session hasn't been active for a while , probably because the client has disconnected abruptly
// it is now time to close the session completely
self.serverDiagnosticsSummary.sessionTimeoutCount += 1;
session.sessionName = session.sessionName || "";
console.log("Server: closing SESSION ".cyan, session.status, session.sessionName.yellow, " because of timeout = ".cyan, session.sessionTimeout, " has expired without a keep alive".cyan);
const channel = session.channel;
if (channel) {
console.log("channel = ".bgCyan, channel.remoteAddress, " port = ", channel.remotePort);
}
// If a Server terminates a Session for any other reason, Subscriptions associated with the Session,
// are not deleted. => deleteSubscription= false
self.closeSession(session.authenticationToken, /* deleteSubscription=*/false,/* reason =*/"Timeout");
});
return session;
}
/**
* @method closeSession
* @param authenticationToken
* @param deleteSubscriptions {Boolean} : true if sessions's subscription shall be deleted
* @param {String} [reason = "CloseSession"] the reason for closing the session (shall be "Timeout", "Terminated" or "CloseSession")
*
*
* what the specs say:
* -------------------
*
* If a Client invokes the CloseSession Service then all Subscriptions associated with the Session are also deleted
* if the deleteSubscriptions flag is set to TRUE. If a Server terminates a Session for any other reason, Subscriptions
* associated with the Session, are not deleted. Each Subscription has its own lifetime to protect against data loss
* in the case of a Session termination. In these cases, the Subscription can be reassigned to another Client before
* its lifetime expires.
*/
closeSession(authenticationToken, deleteSubscriptions, reason) {
const self = this;
reason = reason || "CloseSession";
assert(_.isString(reason));
assert(reason === "Timeout" || reason === "Terminated" || reason === "CloseSession" || reason === "Forcing");
debugLog("ServerEngine.closeSession ", authenticationToken.toString(), deleteSubscriptions);
const key = authenticationToken.toString();
const session = self.getSession(key);
assert(session);
if (!deleteSubscriptions) {
if (!self._orphanPublishEngine) {
self._orphanPublishEngine = new ServerSidePublishEngine({ maxPublishRequestInQueue: 0 });
}
ServerSidePublishEngine.transferSubscriptions(session.publishEngine, self._orphanPublishEngine);
}
session.close(deleteSubscriptions, reason);
assert(session.status === "closed");
// TODO make sure _closedSessions gets cleaned at some point
self._closedSessions[key] = session;
delete self._sessions[key];
}
findSubscription(subscriptionId) {
const self = this;
// xx console.log("findSubscription ", subscriptionId);
const subscriptions = [];
_.map(self._sessions, (session) => {
if (subscriptions.length) return;
const subscription = session.publishEngine.getSubscriptionById(subscriptionId);
if (subscription) {
// xx console.log("foundSubscription ", subscriptionId, " in session", session.sessionName);
subscriptions.push(subscription);
}
});
if (subscriptions.length) {
assert(subscriptions.length === 1);
return subscriptions[0];
}
return self.findOrphanSubscription(subscriptionId);
}
findOrphanSubscription(subscriptionId) {
const self = this;
if (!self._orphanPublishEngine) {
return null;
}
return self._orphanPublishEngine.getSubscriptionById(subscriptionId);
}
deleteOrphanSubscription(subscription) {
const self = this;
assert(self.findSubscription(subscription.id));
const c = self._orphanPublishEngine.subscriptionCount;
subscription.terminate();
assert(self._orphanPublishEngine.subscriptionCount === c - 1);
return StatusCodes.Good;
}
/**
*
* @param session {ServerSession}
* @param subscriptionId {IntegerId}
* @param sendInitialValues {Boolean}
* @return {TransferResult}
*/
transferSubscription(session, subscriptionId, sendInitialValues) {
const self = this;
assert(session instanceof ServerSession);
assert(_.isNumber(subscriptionId));
assert(_.isBoolean(sendInitialValues));
if (subscriptionId <= 0) {
return new TransferResult({ statusCode: StatusCodes.BadSubscriptionIdInvalid });
}
const subscription = self.findSubscription(subscriptionId);
if (!subscription) {
return new TransferResult({ statusCode: StatusCodes.BadSubscriptionIdInvalid });
}
// // now check that new session has sufficient right
// if (session.authenticationToken.toString() != subscription.authenticationToken.toString()) {
// console.log("ServerEngine#transferSubscription => BadUserAccessDenied");
// return new TransferResult({ statusCode: StatusCodes.BadUserAccessDenied });
// }
if (session.publishEngine === subscription.publishEngine) {
// subscription is already in this session !!
return new TransferResult({ statusCode: StatusCodes.BadNothingToDo });
}
const nbSubscriptionBefore = session.publishEngine.subscriptionCount;
ServerSidePublishEngine.transferSubscription(subscription, session.publishEngine, sendInitialValues);
assert(subscription.publishEngine === session.publishEngine);
assert(session.publishEngine.subscriptionCount === nbSubscriptionBefore + 1);
// TODO If the Server transfers the Subscription to the new Session, the Server shall issue a
// TODO StatusChangeNotification notificationMessage with the status code Good_SubscriptionTransferred
// TODO to the old Session.
return new TransferResult({
statusCode: StatusCodes.Good,
availableSequenceNumbers: subscription.getAvailableSequenceNumbers()
});
}
/**
* retrieve a session by its authenticationToken.
*
* @method getSession
* @param authenticationToken
* @param activeOnly
* @return {ServerSession}
*/
getSession(authenticationToken, activeOnly) {
const self = this;
if (!authenticationToken || (authenticationToken.identifierType && (authenticationToken.identifierType.value !== NodeIdType.BYTESTRING.value))) {
return null; // wrong type !
}
const key = authenticationToken.toString();
let session = self._sessions[key];
if (!activeOnly && !session) {
session = self._closedSessions[key];
}
return session;
}
/**
* @method browsePath
* @param browsePath
* @return {BrowsePathResult}
*/
browsePath(browsePath) {
return this.addressSpace.browsePath(browsePath);
}
/**
*
* performs a call to ```asyncRefresh``` on all variable nodes that provide an async refresh func.
*
* @method refreshValues
* @param nodesToRefresh {Array<Object>} an array containing the node to consider
* Each element of the array shall be of the form { nodeId: <xxx>, attributeIds: <value> }.
*
* @param callback {Function}
* @param callback.err {null|Error}
* @param callback.data {Array} : an array containing value read
* The array length matches the number of nodeIds that are candidate for an async refresh (i.e: nodes that are of type
* Variable with asyncRefresh func }
*
* @async
*/
refreshValues(nodesToRefresh, callback) {
const self = this;
const objs = {};
for (let i = 0; i < nodesToRefresh.length; i++) {
const nodeToRefresh = nodesToRefresh[i];
// only consider node for which the caller wants to read the Value attribute
// assuming that Value is requested if attributeId is missing,
if (nodeToRefresh.attributeId && nodeToRefresh.attributeId !== AttributeIds.Value) {
continue;
}
// ... and that are valid object and instances of Variables ...
const obj = self.addressSpace.findNode(nodeToRefresh.nodeId);
if (!obj || !(obj instanceof UAVariable)) {
continue;
}
// ... and that have been declared as asynchronously updating
if (!_.isFunction(obj.refreshFunc)) {
continue;
}
const key = obj.nodeId.toString();
if (objs[key]) {
continue;
}
objs[key] = obj;
}
if (Object.keys(objs).length == 0) {
// nothing to do
return callback(null, []);
}
// perform all asyncRefresh in parallel
async.map(objs, (obj, inner_callback) => {
obj.asyncRefresh(inner_callback);
}, (err, arrResult) => {
callback(err, arrResult);
});
}
get startTime() {
return this.serverStatus.startTime;
}
get currentTime() {
return this.serverStatus.currentTime;
}
get buildInfo() {
return this.serverStatus.buildInfo;
}
/**
* the number of active sessions
* @property currentSessionCount
* @type {Number}
*/
get currentSessionCount() {
return this.serverDiagnosticsSummary.currentSessionCount;
}
/**
* the cumulated number of sessions that have been opened since this object exists
* @property cumulatedSessionCount
* @type {Number}
*/
get cumulatedSessionCount() {
return this.serverDiagnosticsSummary.cumulatedSessionCount;
}
/**
* the number of active subscriptions.
* @property currentSubscriptionCount
* @type {Number}
*/
get currentSubscriptionCount() {
return this.serverDiagnosticsSummary.currentSubscriptionCount;
}
/**
* the cumulated number of subscriptions that have been created since this object exists
* @property cumulatedSubscriptionCount
* @type {Number}
*/
get cumulatedSubscriptionCount() {
return this.serverDiagnosticsSummary.cumulatedSubscriptionCount;
}
get rejectedSessionCount() {
return this.serverDiagnosticsSummary.rejectedSessionCount;
}
get rejectedRequestsCount() {
return this.serverDiagnosticsSummary.rejectedRequestsCount;
}
get sessionAbortCount() {
return this.serverDiagnosticsSummary.sessionAbortCount;
}
get sessionTimeoutCount() {
return this.serverDiagnosticsSummary.sessionTimeoutCount;
}
get publishingIntervalCount() {
return this.serverDiagnosticsSummary.publishingIntervalCount;
}
/**
* the name of the server
* @property serverName
* @type String
*/
get serverName() {
return this.serverStatus.buildInfo.productName;
}
/**
* the server urn
* @property serverNameUrn
* @type String
*/
get serverNameUrn() {
return this._applicationUri;
}
/**
* the urn of the server namespace
* @property serverNamespaceName
* @type String
*/
get serverNamespaceUrn() {
return this._applicationUri; // "urn:" + this.serverName;
}
}
function disposeAddressSpace() {
if (this.addressSpace) {
this.addressSpace.dispose();
delete this.addressSpace;
}
this._shutdownTask = [];
}
// binding methods
function getMonitoredItemsId(inputArguments, context, callback) {
assert(_.isArray(inputArguments));
assert(_.isFunction(callback));
assert(context.hasOwnProperty("session"), " expecting a session id in the context object");
const session = context.session;
if (!session) {
return callback(null, { statusCode: StatusCodes.BadInternalError });
}
const subscriptionId = inputArguments[0].value;
const subscription = session.getSubscription(subscriptionId);
if (!subscription) {
return callback(null, { statusCode: StatusCodes.BadSubscriptionIdInvalid });
}
const result = subscription.getMonitoredItems();
assert(result.statusCode);
assert(_.isArray(result.serverHandles));
assert(_.isArray(result.clientHandles));
assert(result.serverHandles.length === result.clientHandles.length);
const callMethodResult = new CallMethodResult({
statusCode: result.statusCode,
outputArguments: [
{ dataType: DataType.UInt32, arrayType: VariantArrayType.Array, value: result.serverHandles },
{ dataType: DataType.UInt32, arrayType: VariantArrayType.Array, value: result.clientHandles }
]
});
callback(null, callMethodResult);
}
function __bindVariable(self, nodeId, options) {
options = options || {};
// must have a get and a set property
assert(_.difference(["get", "set"], _.keys(options)).length === 0);
const obj = self.addressSpace.findNode(nodeId);
if (obj && obj.bindVariable) {
obj.bindVariable(options);
assert(_.isFunction(obj.asyncRefresh));
assert(_.isFunction(obj.refreshFunc));
} else {
// xx console.log((new Error()).stack);
console.log("Warning: cannot bind object with id ", nodeId.toString(), " please check your nodeset.xml file or add this node programmatically");
}
}
const standard_nodeset_file = constructFilename("nodesets/Opc.Ua.NodeSet2.xml");
const mini_nodeset_filename = constructFilename("lib/server/mini.Node.Set2.xml");
const part8_nodeset_filename = constructFilename("nodesets/Opc.Ua.NodeSet2.Part8.xml");
const di_nodeset_filename = constructFilename("nodesets/Opc.Ua.Di.NodeSet2.xml");
const adi_nodeset_filename = constructFilename("nodesets/Opc.Ua.Adi.NodeSet2.xml");
export {
adi_nodeset_filename,
mini_nodeset_filename,
part8_nodeset_filename,
di_nodeset_filename,
standard_nodeset_file
};
export default ServerEngine;
|
App.messages = App.cable.subscriptions.create('ProductsChannel', {
received: function(data) {
product = JSON.parse(data.product);
product.action = data.action;
if(product.is_available && (product.action == "status" || product.action == "create" || product.action == "update" ))
{
item = '<div data-id="'+product.id+'" class="four wide column">' +
'<div id="'+product.id+'" class="ui card product" >' +
' <div class="image"><img src="'+product.image.url+'" class="ui medium image" /></div>' +
' <div class="ui bottom attached content">' +
' <p> ' +
'<label for="">'+product.name+'</label> ' +
'<span for="" style="float: right">'+product.price+'</span> ' +
'</p> ' +
'</div>' +
' </div>' +
' </div>';
if(product.action == "update")
{
$('[data-id=' + product.id + ']').remove();
}
$('#productGrid').append(item);
}
if(!product.is_available && (product.action == "status" || product.action == "update"))
$('[data-id=' + product.id + ']').remove();
if(product.is_available && product.action == "delete" )
$('[data-id=' + product.id + ']').remove();
},
renderMessage: function(data) {
console.log(data)
}
}); |
'use strict';
import CompositeKeyWeakMap from '../utils/CompositeKeyWeakMap';
export default new CompositeKeyWeakMap();
|
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import ProgressBar from '../src/ProgressBar';
const getProgressBarNode = function (wrapper) {
return React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithClass(wrapper, 'progress-bar'));
};
describe('ProgressBar', function () {
it('Should output a progress bar with wrapper', function () {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={0} max={10} now={0} />
);
assert.equal(React.findDOMNode(instance).nodeName, 'DIV');
assert.ok(React.findDOMNode(instance).className.match(/\bprogress\b/));
assert.ok(getProgressBarNode(instance).className.match(/\bprogress-bar\b/));
assert.equal(getProgressBarNode(instance).getAttribute('role'), 'progressbar');
});
it('Should have the default class', function () {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={0} max={10} now={0} bsStyle='default' />
);
assert.ok(getProgressBarNode(instance).className.match(/\bprogress-bar-default\b/));
});
it('Should have the primary class', function () {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={0} max={10} now={0} bsStyle='primary' />
);
assert.ok(getProgressBarNode(instance).className.match(/\bprogress-bar-primary\b/));
});
it('Should have the success class', function () {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={0} max={10} now={0} bsStyle='success' />
);
assert.ok(getProgressBarNode(instance).className.match(/\bprogress-bar-success\b/));
});
it('Should have the warning class', function () {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={0} max={10} now={0} bsStyle='warning' />
);
assert.ok(getProgressBarNode(instance).className.match(/\bprogress-bar-warning\b/));
});
it('Should default to min:0, max:100', function () {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar now={5} />
);
let bar = getProgressBarNode(instance);
assert.equal(bar.getAttribute('aria-valuemin'), '0');
assert.equal(bar.getAttribute('aria-valuemax'), '100');
});
it('Should have 0% computed width', function () {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={0} max={10} now={0} />
);
assert.equal(getProgressBarNode(instance).style.width, '0%');
});
it('Should have 10% computed width', function () {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={0} max={10} now={1} />
);
assert.equal(getProgressBarNode(instance).style.width, '10%');
});
it('Should have 100% computed width', function () {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={0} max={10} now={10} />
);
assert.equal(getProgressBarNode(instance).style.width, '100%');
});
it('Should have 50% computed width with non-zero min', function () {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={1} max={11} now={6} />
);
assert.equal(getProgressBarNode(instance).style.width, '50%');
});
it('Should not have label', function () {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={0} max={10} now={5} bsStyle='primary' />
);
assert.equal(React.findDOMNode(instance).innerText, '');
});
it('Should have label', function () {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={0} max={10} now={5} bsStyle='primary'
label='min:%(min)s, max:%(max)s, now:%(now)s, percent:%(percent)s, bsStyle:%(bsStyle)s' />
);
assert.equal(React.findDOMNode(instance).innerText, 'min:0, max:10, now:5, percent:50, bsStyle:primary');
});
it('Should have screen reader only label', function () {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={0} max={10} now={5} bsStyle='primary' srOnly
label='min:%(min)s, max:%(max)s, now:%(now)s, percent:%(percent)s, bsStyle:%(bsStyle)s' />
);
let srLabel = ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'sr-only');
assert.equal(React.findDOMNode(srLabel).innerText, 'min:0, max:10, now:5, percent:50, bsStyle:primary');
});
it('Should have a label that is a React component', function () {
let customLabel = (
<strong className="special-label">My label</strong>
);
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={0} max={10} now={5} bsStyle='primary' label={customLabel} />
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'special-label'));
});
it('Should have screen reader only label that wraps a React component', function () {
let customLabel = (
<strong className="special-label">My label</strong>
);
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={0} max={10} now={5} bsStyle='primary' label={customLabel} srOnly />
);
let srLabel = ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'sr-only');
let component = ReactTestUtils.findRenderedDOMComponentWithClass(srLabel, 'special-label');
assert.ok(component);
});
it('Should show striped bar', function () {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={1} max={11} now={6} striped />
);
assert.ok(React.findDOMNode(instance).className.match(/\bprogress-striped\b/));
});
it('Should show animated striped bar', function () {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar min={1} max={11} now={6} active />
);
assert.ok(React.findDOMNode(instance).className.match(/\bprogress-striped\b/));
assert.ok(React.findDOMNode(instance).className.match(/\bactive\b/));
});
it('Should show stacked bars', function () {
let instance = ReactTestUtils.renderIntoDocument(
<ProgressBar>
<ProgressBar key={1} now={50} />
<ProgressBar key={2} now={30} />
</ProgressBar>
);
let wrapper = React.findDOMNode(instance);
let bar1 = wrapper.firstChild;
let bar2 = wrapper.lastChild;
assert.ok(wrapper.className.match(/\bprogress\b/));
assert.ok(bar1.className.match(/\bprogress-bar\b/));
assert.equal(bar1.style.width, '50%');
assert.ok(bar2.className.match(/\bprogress-bar\b/));
assert.equal(bar2.style.width, '30%');
});
});
|
// By doing so, we won't mess up with `require` keyword
window.requireNode = window.require;
// auto reload
var gulp;
var remote = requireNode('remote');
try {
gulp = requireNode('gulp');
} catch(e) {
// There is no gulp in production build, so we have to use
// try-catch to throw errors in console for this
}
if (gulp) {
gulp.task('reload', function() {
remote.getCurrentWindow().reload();
});
gulp.watch([
'src/frontend/**/*.*',
'src/backend/**/*.*'
], ['reload']);
}
|
var Kernel_View_Ui_Entry = AbstractView.extend({
label: '',
initialize: function (options) {
this.label = (options && options.label) ?
options.label : '';
this.enterCallbacks = (options && options.onEnter) ? [options.onEnter] : [];
this.blurCallbacks = (options && options.onBlur) ? [options.onBlur] : [];
this.stopTypingCallbacks = (options && options.onStopTyping) ? [options.onStopTyping] : [];
this.isPasswordField = options && options.password;
this.isAutoFocus = options && options.autoFocus;
this.hidden = options.hidden;
},
render: function (options) {
AbstractView.prototype.render.call(this, _.extend({
templateObj: {
fieldType: this.isPasswordField ? "password" : "text",
autoFocus: this.isAutoFocus ? "autofocus" : "",
label: this.label,
hidden: this.hidden,
}
}, options));
this.initListenersAfterRender();
if (this.value != undefined) this.setValue(this.value);
this.value = undefined;
return this;
},
initListenersAfterRender: function () {
var _this = this;
var triggerChange = function (event) {
_this.trigger('change', event.target.value, event);
};
var callEnterCallbacks = function (event) {
if (event.keyCode == 13) {
_.each(_this.enterCallbacks, function (callback) {
callback(_this.getValue());
});
}
};
var callBlurCallbacks = function (event) {
_.each(_this.blurCallbacks, function (callback) {
callback(_this.getValue());
});
};
var callStopTypingCallbacks = function (event) {
_.each(_this.stopTypingCallbacks, function (callback) {
callback(_this.getValue());
});
};
this.$('input')
.on('change', triggerChange)
.on('input', triggerChange)
.on('keyup', callEnterCallbacks)
.on('blur', callBlurCallbacks)
.on('keyup', _.debounce(callStopTypingCallbacks, 500));
},
setValue: function (value) {
if (!this.rendered) {
this.value = value;
} else {
return this.$('input')[0].value = value;
}
},
getValue: function () {
return this.$('input')[0].value;
},
onEnter: function (callback) {
this.enterCallbacks.push(callback);
},
onBlur: function (callback) {
this.blurCallbacks.push(callback);
},
focus: function () {
this.$('input').focus();
},
hide: function () {
this.$el.addClass('hidden');
},
show: function () {
this.$el.removeClass('hidden');
}
});
|
var _ = require('lodash'),
async = require('async'),
mongoose = require('mongoose'),
Payment = mongoose.model('Payment'),
Member = mongoose.model('Member'),
ConfigService = require('../services/ConfigService'),
PaymentError = require('../errors/PaymentError');
/**
* Manages member's payments.
*
* @exports services/PaymentsService
* @type {Object}
*/
var PaymentsService = {
/**
* Pays monthly payment for specified member.
* Requires 'member' and 'month' properties to be present.
* Sets 'accountingMonth' and 'amount' from current configuration.
* If 'agent' not present, reads from member's set agent.
*
* @param {Object} data Payment data
* @param {Function} cb
* @return {undefined}
*/
pay: function(data, cb) {
var member;
if (!data.member || !data.month) {
return cb(new PaymentError('Missing member and/or month'));
}
async.waterfall([
// If agent not set in payment, set agent to member's agent
function(_cb) {
Member.findById(data.member).exec(function(err, _member) {
if (err) return _cb(err);
member = _member;
// Check if already paid
if (member.paidMonths && member.paidMonths.indexOf(data.month) !== -1) {
return _cb(new PaymentError('Month already paid'));
}
if (!data.agent) {
data.agent = member.agent;
}
_cb(null, data);
});
},
// Sets current accounting month and amount, save payment
function(data, _cb) {
ConfigService.get(function(err, config) {
if (err) return _cb(err);
data.accountingMonth = config.accountingMonth;
var amount = ConfigService.getMonthPaymentAmount(config, data.month);
if (amount instanceof Error) {
return _cb(amount);
}
data.amount = amount;
Payment.create(data, _cb);
});
},
// Update member's paid months using $addToSet with sorting
function(payment, _cb) {
Member.update(
{ _id : member._id },
{ $addToSet :
{
paidMonths : {
$each: [ payment.month ],
$sort: 1
}
}
},
function(err, res) {
_cb(err, payment);
}
);
}
], cb);
},
/**
* Remove payment by 'id'.
*
* @param {String} id
* @param {Function} cb
*/
unpay: function(id, cb) {
async.waterfall([
// Remove payment
function(cb) {
Payment.findOneAndRemove({_id: id}, cb);
},
// Get member
function getMember(payment, cb) {
Member.findById(payment.member, function(err, res) {
if (err) return cb(err);
cb(null, payment, res);
});
},
// Remove paid month
function removePaidMonth(payment, member, cb) {
member.paidMonths.splice(member.paidMonths.indexOf(payment.month), 1);
member.save(function(err, res) {
if (err) return cb(err);
cb(null, payment);
});
},
], cb);
},
/**
* Update given payment.
*
* @param {Object} payment
* @param {Object} data
* @param {Function} cb
*/
update: function (payment, data, cb) {
_.extend(payment, _.pick(data, ['agent', 'amount']));
payment.save(function (err, payment) {
if (err) return cb(err);
cb(null, payment);
});
},
};
module.exports = PaymentsService;
|
'use strict';
module.exports = {
db: 'mongodb://localhost/spot-dev',
app: {
title: 'spot - Development Environment'
},
facebook: {
clientID: process.env.FACEBOOK_ID || 'APP_ID',
clientSecret: process.env.FACEBOOK_SECRET || 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/facebook/callback'
},
twitter: {
clientID: process.env.TWITTER_KEY || 'CONSUMER_KEY',
clientSecret: process.env.TWITTER_SECRET || 'CONSUMER_SECRET',
callbackURL: 'http://localhost:3000/auth/twitter/callback'
},
google: {
clientID: process.env.GOOGLE_ID || 'APP_ID',
clientSecret: process.env.GOOGLE_SECRET || 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/google/callback'
},
linkedin: {
clientID: process.env.LINKEDIN_ID || 'APP_ID',
clientSecret: process.env.LINKEDIN_SECRET || 'APP_SECRET',
callbackURL: 'http://localhost:3000/auth/linkedin/callback'
}
}; |
'use strict';
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var Click = new Schema(
{ clicks: Number },
{ versionKey: false }
);
module.exports = mongoose.model('Click', Click); |
import resolve from "../helpers/resolve";
/**
* Resolves presets options which can be either direct object data,
* or a module name to require.
*/
export function resolvePresets(presets: Array<string | Object>, dirname: string, prefix?: string, onResolve?) {
return presets.map((val) => {
if (typeof val === "string") {
let presetLoc = prefix && resolve(`${prefix}-${val}`, dirname) || resolve(val, dirname);
if (presetLoc) {
let val = require(presetLoc);
onResolve && onResolve(val, presetLoc);
return val;
} else {
throw new Error(`Couldn't find preset ${JSON.stringify(val)} relative to directory ${JSON.stringify(dirname)}`);
}
} else if (typeof val === "object") {
onResolve && onResolve(val);
return val;
} else {
throw new Error(`Unsupported preset format: ${val}.`);
}
});
}
|
var app = angular.module("ive");
// Relationship recorded_at edit controller
app.controller("recordedAtEditController", function($scope, $rootScope, $routeParams, $interval, $filter, $translate, $location, config, $window, $authenticationService, $relationshipService) {
/*************************************************
FUNCTIONS
*************************************************/
/**
* [redirect description]
* @param {[type]} path [description]
* @return {[type]} [description]
*/
$scope.redirect = function(path){
$location.url(path);
};
/**
* [send description]
* @return {[type]} [description]
*/
$scope.send = function(){
// Validate input
if($scope.editRelationshipForm.$invalid) {
// Update UI
$scope.editRelationshipForm.relationship_preferred.$pristine = false;
} else {
$scope.$parent.loading = { status: true, message: $filter('translate')('SAVING_RELATIONSHIP') };
$relationshipService.edit($scope.relationship_label, $scope.relationship.relationship_id, $scope.relationship)
.then(function onSuccess(response) {
$scope.relationship = response.data;
$scope.redirect("/relationships/" + $scope.relationship_label + "/" + $scope.relationship.relationship_id);
})
.catch(function onError(response) {
$window.alert(response.data);
});
}
};
/**
* [startPreview description]
* @param {[type]} video [description]
* @return {[type]} [description]
*/
$scope.startPreview = function(video) {
// store the interval promise
$scope.currentPreview = 1;
$scope.maxPreview = video.thumbnails;
// stops any running interval to avoid two intervals running at the same time
$interval.cancel(promise);
// store the interval promise
promise = $interval(function() {
if($scope.relationship.thumbnails > 1){
if($scope.currentPreview >= $scope.maxPreview){
$scope.currentPreview = 1;
}
$scope.relationship.thumbnail = $filter('thumbnail')($scope.relationship, $scope.currentPreview);
}
$scope.currentPreview++;
}, config.thumbnailSpeed);
};
/**
* [stopPreview description]
* @param {[type]} video [description]
* @return {[type]} [description]
*/
$scope.stopPreview = function(video) {
$interval.cancel(promise);
};
/*************************************************
LISTENERS
*************************************************/
$scope.$on('$destroy', function() {
$interval.cancel(promise);
});
/*************************************************
INIT
*************************************************/
$scope.$parent.loading = { status: true, message: $filter('translate')('LOADING_RELATIONSHIP') };
$scope.relationship_label = 'recorded_at';
var promise;
$relationshipService.retrieve_by_id($scope.relationship_label, $routeParams.relationship_id)
.then(function onSuccess(response) {
$scope.relationship = response.data;
$scope.$parent.loading = { status: false, message: "" };
})
.catch(function onError(response) {
$window.alert(response.data);
});
});
|
const checkSafety = (row, col, solutions) => {
for (let i = 0; i < solutions.length; i += 1) {
const queenSolution = solutions[i];
const firstDiagonal = row - col;
const secondDiagonal = row + col;
const firstDiagonalQueen = queenSolution[0] - queenSolution[1];
const secondDiagonalQueen = queenSolution[0] + queenSolution[1];
if (firstDiagonal === firstDiagonalQueen) {
return false;
}
if (secondDiagonal === secondDiagonalQueen) {
return false;
}
if (col === queenSolution[1]) {
return false;
}
}
return true;
};
const solveQueenBacktrack = (n, row, solutions, overall) => {
if (n === row) {
overall.push(solutions);
return true;
}
for (let col = 0; col < n; col += 1) {
let isQueenSafe = true;
for (let queenIndex = 0; queenIndex < solutions.length; queenIndex += 1) {
// check if current row and col is safe
if (!checkSafety(row, col, solutions) || !isQueenSafe) {
isQueenSafe = false;
}
}
if (!isQueenSafe) {
continue;
}
solutions.push([row, col]);
// this is the backtrack
if (solveQueenBacktrack(n, row + 1, [...solutions], overall)) {
continue;
}
// actually this is the "back" in the backtrack
solutions.pop();
}
return false;
};
const solveNQueens = (n) => {
const final = [];
solveQueenBacktrack(n, 0, [], final);
const queenStyle = [];
for (let i = 0; i < final.length; i += 1) {
const strAns = [];
for (let j = 0; j < final[i].length; j += 1) {
const dots = new Array(n).fill('.');
dots.splice(final[i][j][1], 1, 'Q');
strAns.push(dots.join(''));
}
queenStyle.push(strAns);
}
return queenStyle;
};
console.log(solveNQueens(5));
console.log(solveNQueens(4));
console.log(solveNQueens(1));
|
var debug = require('debug')('domain:commandDispatcher'),
_ = require('lodash'),
dotty = require('dotty'),
DuplicateCommandError = require('./errors/duplicateCommandError');
/**
* CommandDispatcher constructor
* @param {Object} tree The tree object.
* @param {Object} definition The definition object.
* @param {Object} commandBunper The commandBumper object. [optional]
* @constructor
*/
function CommandDispatcher (tree, definition, commandBumper) {
if (!tree || !_.isObject(tree) || !_.isFunction(tree.getCommandHandler)) {
var err = new Error('Please pass a valid tree!');
debug(err);
throw err;
}
if (!definition || !_.isObject(definition)) {
var err = new Error('Please pass a valid command definition!');
debug(err);
throw err;
}
this.tree = tree;
this.definition = definition;
this.commandBumper = commandBumper;
}
CommandDispatcher.prototype = {
/**
* Returns the target information of this command.
* @param {Object} cmd The passed command.
* @returns {{name: 'commandName', aggregateId: 'aggregateId', version: 0, aggregate: 'aggregateName', context: 'contextName'}}
*/
getTargetInformation: function (cmd) {
if (!cmd || !_.isObject(cmd)) {
var err = new Error('Please pass a valid command!');
debug(err);
throw err;
}
var aggregateId = null;
if (dotty.exists(cmd, this.definition.aggregateId)) {
aggregateId = dotty.get(cmd, this.definition.aggregateId);
} else {
debug('no aggregateId found, seems to be for a new aggregate');
}
var name = dotty.get(cmd, this.definition.name);
var version = 0;
if (dotty.exists(cmd, this.definition.version)) {
version = dotty.get(cmd, this.definition.version);
} else {
debug('no version found, handling as version: 0');
}
var aggregate = null;
if (dotty.exists(cmd, this.definition.aggregate)) {
aggregate = dotty.get(cmd, this.definition.aggregate);
} else {
debug('no aggregate found, will lookup in all aggregates');
}
var context = null;
if (dotty.exists(cmd, this.definition.context)) {
context = dotty.get(cmd, this.definition.context);
} else {
debug('no aggregateName found, will lookup in all contexts');
}
return {
name: name,
aggregateId: aggregateId,
version: version,
aggregate: aggregate,
context: context
};
},
/**
* Dispatches a command.
* @param {Object} cmd The passed command.
* @param {Function} callback The function, that will be called when this action is completed.
* `function(err, evts){}`
*/
dispatch: function (cmd, callback) {
if (!cmd || !_.isObject(cmd)) {
var err = new Error('Please pass a valid command!');
debug(err);
throw err;
}
if (!callback || !_.isFunction(callback)) {
var err = new Error('Please pass a valid callback!');
debug(err);
throw err;
}
var target = this.getTargetInformation(cmd);
var commandHandler = this.tree.getCommandHandler(target);
// if (!commandHandler) {
// commandHandler = this.tree.getCommandHandlerByOldTarget(target);
// }
if (!commandHandler) {
var err = new Error('No command handler found for ' + target.name);
debug(err);
return callback(err);
}
if (!this.commandBumper) {
return commandHandler.handle(cmd, callback);
}
var key = target.context + target.aggregate + target.aggregateId + dotty.get(cmd, this.definition.id);
this.commandBumper.add(key, function (err, added) {
if (err) {
return callback(err);
}
if (!added) {
return callback(new DuplicateCommandError('Command already seen!'));
}
commandHandler.handle(cmd, callback);
});
}
};
module.exports = CommandDispatcher;
|
'use strict';
const Router = require('express').Router;
const parseJSON = require('body-parser').json();
const createError = require('http-errors');
const debug = require('debug')('inventory:cart order route');
const CartOrder = require('../model/cart-order.js');
const Customer = require('../model/customer.js');
const cartOrderRouter = module.exports = Router();
cartOrderRouter.post('/api/orders/:customerID/:storeID/cart-order', parseJSON, function(request, response, next) {
debug('POST: /api/orders/:customerID/:storeID/cartOrder');
Customer.addCartOrder(request.params.customerID, request.params.storeID, request.body)
.then(order => response.status(201).json(order))
.catch(err => next(err));
});
cartOrderRouter.get('/api/orders', function(request, response, next) {
debug('GET: /api/orders');
CartOrder.find({})
.then(arrayOfOrders => {
if (arrayOfOrders.length === 0) return Promise.reject(createError(416, 'No data found.'));
response.json(arrayOfOrders.map(order => order._id));
})
.catch(err => next(err));
});
cartOrderRouter.get('/api/orders/:orderID', function(request, response, next) {
debug('GET: /api/orders/:orderID');
CartOrder.findById(request.params.orderID)
.populate('products')
.then(order => response.json(order))
.catch(() => next(createError(404, 'Not found.')));
});
cartOrderRouter.put('/api/orders/:orderID', parseJSON, function(request, response, next) {
debug('PUT: /api/orders/:orderID');
if (Object.getOwnPropertyNames(request.body).length === 0) next(createError(400, 'No body posted.'));
CartOrder.findByIdAndUpdate(request.params.orderID, request.body, {new: true})
.then(order => response.json(order))
.catch(() => next(createError(404, 'Not found.')));
});
cartOrderRouter.delete('/api/orders/:orderID', function(request, response, next) {
debug('DELETE: /api/orders/:orderID');
Customer.removeCartOrder(request.params.orderID)
.then(() => response.status(204).send())
.catch(() => next(createError(404, 'Not found.')));
});
|
var authService = require('./auth_service');
var sessionService = require('./session_service');
module.exports = angular.module('app.components.services', [
authService.name,
sessionService.name
]);
|
window.Rendxx = window.Rendxx || {};
window.Rendxx.Game = window.Rendxx.Game || {};
window.Rendxx.Game.Ghost = window.Rendxx.Game.Ghost || {};
window.Rendxx.Game.Ghost.Renderer2D = window.Rendxx.Game.Ghost.Renderer2D || {};
/**
* Setup map, including light, wall and other stuff
* y
* |
* |
* o------x
* /
* /
* z
*/
(function (RENDERER) {
var Data = RENDERER.Data;
var _Data = {
keyData: "key_1",
prefix_furniture: "f_",
prefix_door: "d_",
status: {
furniture: {
None: 0,
Closed: 1,
Opened: 2
},
door: {
Locked: 0,
Opened: 1,
Closed: 2,
Blocked: 3,
Destroyed: 4,
NoPower: 5
},
generator: {
Broken: 0,
Fixing: 1,
Worked: 2
}
},
canvasLimit :4096
};
var Map = function (entity) {
// private data ----------------------------
var that = this,
GridSize = Data.grid.size,
_modelData = null,
_mapData = null,
_mapSetupData = null,
gameData = null,
itemStatus = null,
itemData = null,
root = entity.root,
_tex = {},
_frames = {},
_scene = entity.env.scene['map'],
_layers = entity.env.layers,
_loadCount = 0,
_dangerCache=0,
_animation = {},
// static map
_topMap = null,
_btmMap = null,
// mesh
mesh_door = null, // door
mesh_furniture = null, // furniture
mesh_generator = null, // generator
mesh_generatorLight = null,
mesh_key = null; // key objects: funiture id: key object
// public data -----------------------------
this.width = 0;
this.height = 0;
this.objectPos = { // id: [x, y]
furniture: {},
door: {},
body: {},
generator: {}
};
this.posEnd = null;
this.dark = null;
this.danger = 0;
this.shadowMap = null;
this.blockMap = null;
this.blockItemSet = {};
// callback --------------------------------
this.onLoaded = null;
// public method ---------------------------
/**
* load map with given data
*/
this.loadData = function (mapData, modelData, mapSetupData) {
_modelData = modelData;
_mapData = mapData;
_mapSetupData = mapSetupData;
itemStatus = {};
itemData = {};
_loadCount = 1;
_topMap = new PIXI.Container();
_btmMap = new PIXI.Container();
setupStaticMap(_scene);
setupGround(_btmMap, mapData.grid, mapData.item.ground);
setupWall(_topMap, mapData.wall, mapData.item.wall);
setupDoor(_scene, mapData.item.door);
setupBlockMap(mapData, modelData);
setupBody();
setupFurniture(_scene, _btmMap, mapData.item.furniture);
setupGenerator(_scene, _topMap, mapData.item.generator);
setupStuff(_topMap, mapData.item.stuff);
setupKey(_scene);
setupLight(_scene);
createEndPos(_mapSetupData.position.end);
_loadCount--;
onLoaded();
};
// update data from system
this.update = function (data_in) {
gameData = data_in;
//updateKey();
updateFuniture();
updateDoor();
updateGenerator();
updateBody();
updateLight();
};
// render model
this.render = function () {
};
// get data ---------------------------------
this.isDoorLock = function (idx) {
return itemStatus['door'][idx].status === _Data.status.door.Locked;
};
// private method ---------------------------
var setupLight = function () {
_layers['light'] = new PIXI.Container();
_scene.addChild(_layers['light']);
var graphics = new PIXI.Graphics();
graphics.lineStyle(0);
graphics.beginFill(0x111111, 1);
graphics.drawRect(0, 0, that.width * GridSize, that.height * GridSize);
graphics.alpha = 0.6;
_layers['light'].addChild(graphics);
that.dark = graphics;
var graphics = new PIXI.Graphics();
graphics.lineStyle(0);
graphics.beginFill(0x990000, 1);
graphics.drawRect(0, 0, that.width * GridSize, that.height * GridSize);
graphics.alpha = 0;
_layers['light'].addChild(graphics);
that.danger = graphics;
};
var setupBlockMap = function (mapData, modelData) {
that.blockMap = [];
that.blockItemSet = {};
for (var i = 0; i < mapData.grid.height; i++) {
that.blockMap[i] = [];
for (var j = 0; j < mapData.grid.width; j++) {
that.blockMap[i][j] = null;
}
}
var walls = mapData.item.wall;
for (var k = 0; k < walls.length; k++) {
if (walls[k] === null) continue;
var wall = walls[k];
var pos = [
(wall.left) * GridSize,
(wall.top) * GridSize,
(wall.right + 1) * GridSize,
(wall.bottom + 1) * GridSize,
(wall.right + wall.left + 1) / 2 * GridSize,
(wall.top + wall.bottom + 1) / 2 * GridSize
];
for (var i = wall.top; i <= wall.bottom; i++) {
for (var j = wall.left; j <= wall.right; j++) {
that.blockItemSet['w_' + k] = pos;
that.blockMap[i][j] = 'w_' + k;
}
}
}
var furnitures = mapData.item.furniture;
for (var k = 0; k < furnitures.length; k++) {
if (furnitures[k] === null) continue;
var furniture = furnitures[k];
if (modelData.items[Data.categoryName.furniture][furniture.id].blockSight !== true) continue;
var pos = [
(furniture.left) * GridSize,
(furniture.top) * GridSize,
(furniture.right + 1) * GridSize,
(furniture.bottom + 1) * GridSize,
(furniture.right + furniture.left + 1) / 2 * GridSize,
(furniture.top + furniture.bottom + 1) / 2 * GridSize
];
for (var i = furniture.top; i <= furniture.bottom; i++) {
for (var j = furniture.left; j <= furniture.right; j++) {
that.blockItemSet['f_' + k] = pos;
that.blockMap[i][j] = 'f_' + k;
}
}
}
var doors = mapData.item.door;
for (var k = 0; k < doors.length; k++) {
if (doors[k] === null) continue;
var door = doors[k];
var pos = [
(door.left) * GridSize,
(door.top) * GridSize,
(door.right + 1) * GridSize,
(door.bottom + 1) * GridSize,
(door.right + door.left + 1) / 2 * GridSize,
(door.top + door.bottom + 1) / 2 * GridSize
];
for (var i = door.top; i <= door.bottom; i++) {
for (var j = door.left; j <= door.right; j++) {
that.blockItemSet['d_' + k] = pos;
that.blockMap[i][j] = 'd_' + k;
}
}
}
};
var setupGround = function (scene, grid, ground_in) {
/*create ground*/
that.width = grid.width;
that.height = grid.height;
_layers['ground'] = new PIXI.Container();
scene.addChild(_layers['ground']);
var fileArr = [];
for (var i = 0, l = ground_in.length; i < l; i++) {
if (ground_in[i] === null) continue;
_loadCount++;
loadGroundTex(fileArr, _modelData.items[Data.categoryName.ground][ground_in[i].id]);
}
var arr = [];
for (var i in fileArr) {
arr.push(fileArr[i]);
}
PIXI.loader.add(arr).load(function (loader, resources) {
for (var i = 0, l = ground_in.length; i < l; i++) {
if (ground_in[i] === null) continue;
createGround(i, ground_in[i], _layers['ground'], function (idx, dat) {
var id = dat.id;
_loadCount--;
onLoaded();
});
}
});
};
var setupWall = function (scene, wall, wallTop) {
_layers['wallShadow'] = new PIXI.Container();
scene.addChild(_layers['wallShadow']);
for (var i = 0, l = wallTop.length; i < l; i++) {
if (wallTop[i] === null) continue;
_loadCount++;
createWallShadow(i, wallTop[i], _layers['wallShadow'], function (idx, dat) {
var id = dat.id;
_loadCount--;
onLoaded();
});
}
var fileArr = [];
for (var i = 0, l = wallTop.length; i < l; i++) {
if (wallTop[i] === null) continue;
_loadCount++;
loadWallTex(fileArr, _modelData.items[Data.categoryName.wall][wallTop[i].id]);
}
_layers['wall'] = new PIXI.Container();
scene.addChild(_layers['wall']);
var arr = [];
for (var i in fileArr) {
arr.push(fileArr[i]);
}
PIXI.loader.add(arr).load(function (loader, resources) {
for (var i = 0, l = wallTop.length; i < l; i++) {
if (wallTop[i] === null) continue;
createWall(i, wallTop[i], _layers['wall'], function (idx, dat) {
var id = dat.id;
_loadCount--;
onLoaded();
});
}
});
_layers['wallEdge'] = new PIXI.Container();
scene.addChild(_layers['wallEdge']);
for (var i = 0, l = wall.length; i < l; i++) {
if (wall[i] === null) continue;
_loadCount++;
createWallEdge(i, wall[i], _layers['wallEdge'], function (idx, dat) {
var id = dat.id;
_loadCount--;
onLoaded();
});
}
};
var setupDoor = function (scene, doors) {
mesh_door = {};
_layers['door'] = new PIXI.Container();
scene.addChild(_layers['door']);
itemStatus['door'] = {};
itemData['door'] = {};
var fileArr = [];
for (var i = 0, l = doors.length; i < l; i++) {
if (doors[i] === null) continue;
_loadCount++;
loadDoorTex(fileArr, _modelData.items[Data.categoryName.door][doors[i].id]);
}
var arr = [];
for (var i in fileArr) {
arr.push(fileArr[i]);
}
PIXI.loader.add(arr).load(function (loader, resources) {
for (var i = 0, l = doors.length; i < l; i++) {
if (doors[i] === null) continue;
createDoor(i, doors[i], _layers['door'], function (idx, dat, mesh, isElectric) {
var id = dat.id;
mesh_door[idx] = (mesh);
itemStatus['door'][idx] = isElectric ? _Data.status.door.NoPower : _Data.status.door.Closed;
_loadCount--;
onLoaded();
});
}
});
};
var setupFurniture = function (scene, staticScene, furniture) {
mesh_furniture = {};
itemStatus['furniture'] = {};
_layers['furniture'] = new PIXI.Container();
scene.addChild(_layers['furniture']);
var fileArr = [];
for (var i = 0, l = furniture.length; i < l; i++) {
if (furniture[i] === null) continue;
_loadCount++;
loadFurnitureTex(fileArr, _modelData.items[Data.categoryName.furniture][furniture[i].id]);
}
var arr = [];
for (var i in fileArr) {
arr.push(fileArr[i]);
}
PIXI.loader.add(arr).load(function (loader, resources) {
for (var i = 0, l = furniture.length; i < l; i++) {
if (furniture[i] === null) continue;
createFurniture(i, furniture[i], _layers['furniture'], staticScene, function (idx, dat, mesh) {
var id = dat.id;
mesh_furniture[idx] = (mesh);
itemStatus['furniture'][idx] = (mesh == null) ? _Data.status.furniture.None : _Data.status.furniture.Closed;
_loadCount--;
onLoaded();
});
}
});
};
var setupGenerator = function (scene, staticScene, generator) {
generator = generator || [];
mesh_generator = {};
mesh_generatorLight = {};
itemStatus['generator'] = {};
_layers['generator'] = new PIXI.Container();
scene.addChild(_layers['generator']);
var fileArr = [];
for (var i = 0, l = generator.length; i < l; i++) {
if (generator[i] === null) continue;
_loadCount++;
loadGeneratorTex(fileArr, _modelData.items[Data.categoryName.generator][generator[i].id]);
}
var arr = [];
for (var i in fileArr) {
arr.push(fileArr[i]);
}
arr.push({
name: 'g_light_white',
url: root + Data.files.path[Data.categoryName.sprite] + 'GeneratorLight.png',
onComplete: function (loader, resources) {
_tex['g_light_white'] = PIXI.loader.resources['g_light_white'].texture;
}
});
arr.push({
name: 'g_light_red',
url: root + Data.files.path[Data.categoryName.sprite] + 'GeneratorLight.red.png',
onComplete: function (loader, resources) {
_tex['g_light_red'] = PIXI.loader.resources['g_light_red'].texture;
}
});
arr.push({
name: 'g_light_green',
url: root + Data.files.path[Data.categoryName.sprite] + 'GeneratorLight.green.png',
onComplete: function (loader, resources) {
_tex['g_light_green'] = PIXI.loader.resources['g_light_green'].texture;
}
});
PIXI.loader.add(arr).load(function (loader, resources) {
for (var i = 0, l = generator.length; i < l; i++) {
if (generator[i] === null) continue;
createGenerator(i, generator[i], _layers['generator'], staticScene, function (idx, dat, mesh, meshLight) {
var id = dat.id;
mesh_generator[idx] = (mesh);
mesh_generatorLight[idx] = (meshLight);
itemStatus['generator'][idx] = _Data.status.generator.Broken;
_loadCount--;
onLoaded();
});
}
});
};
var setupBody = function () {
itemData['body'] = {};
};
var setupStuff = function (scene, stuff) {
_layers['stuff'] = new PIXI.Container();
scene.addChild(_layers['stuff']);
if (stuff === null || stuff.length === 0) return;
var fileArr = [];
for (var i = 0, l = stuff.length; i < l; i++) {
if (stuff[i] === null) continue;
_loadCount++;
loadStuffTex(fileArr, _modelData.items[Data.categoryName.stuff][stuff[i].id]);
}
var arr = [];
for (var i in fileArr) {
arr.push(fileArr[i]);
}
PIXI.loader.add(arr).load(function (loader, resources) {
for (var i = 0, l = stuff.length; i < l; i++) {
if (stuff[i] === null) continue;
createStuff(stuff[i], _layers['stuff'], function (dat) {
var id = dat.id;
_loadCount--;
onLoaded();
});
}
});
};
var setupKey = function (scene) {
if (mesh_key !== null) {
}
mesh_key = {};
};
var onLoaded = function () {
if (_loadCount > 0) return;
var offset_x = -1 * GridSize / 2;
var offset_y = -1 * GridSize / 2;
entity.env.scene['map'].position.set(offset_x, offset_y);
entity.env.scene['character'].position.set(offset_x, offset_y);
entity.env.scene['effort'].position.set(offset_x, offset_y);
entity.env.scene['marker'].position.set(offset_x, offset_y);
loadBaseMap(_scene, _btmMap, _topMap);
if (that.onLoaded) that.onLoaded();
};
// Add items ----------------------------------------------------------
var loadGroundTex = function (fileArr, para) {
fileArr['g_' + para.id] = ({
name: 'g_' + para.id,
url: root + Data.files.path[Data.categoryName.ground] + para.id + '/' + para.model2D[0],
onComplete: function (loader, resources) {
_tex['g_' + para.id] = PIXI.loader.resources['g_' + para.id].texture;
}
});
};
var createGround = function (idx, dat, layer, onSuccess) {
if (dat === null) return null;
var id = dat.id;
var para = _modelData.items[Data.categoryName.ground][id];
var x = dat.left * GridSize;
var y = dat.top * GridSize;
var w = (dat.right - dat.left + 1) * GridSize;
var h = (dat.bottom - dat.top + 1) * GridSize;
var obj = new PIXI.extras.TilingSprite(_tex['g_' + para.id], w, h);
obj.anchor.x = 0;
obj.anchor.y = 0;
obj.position.x = x;
obj.position.y = y;
layer.addChild(obj);
onSuccess(idx, dat);
};
var loadWallTex = function (fileArr, para) {
fileArr['wall_' + para.id] = ({
name: 'wall_' + para.id,
url: root + Data.files.path[Data.categoryName.wall] + para.id + '/' + para.model2D[0],
onComplete: function (loader, resources) {
_tex['wall_' + para.id] = PIXI.loader.resources['wall_' + para.id].texture;
}
});
};
var createWallEdge = function (idx, dat, layer, onSuccess) {
if (dat === null) return null;
var id = dat.id;
var para = _modelData.items[Data.categoryName.wall][id];
var r = dat.rotation;
var len = dat.len * GridSize;
var x = dat.left * GridSize;
var y = dat.top * GridSize;
var x2 = 0;
var y2 = 0;
var wid = GridSize / 8;
switch (r) {
case 0:
x -= wid / 2;
x2 = x + len + wid;
y2 = y;
break;
case 1:
y -= wid / 2;
x2 = x;
y2 = y + len + wid;
break;
case 2:
x -= wid / 2;
x2 = x + len + wid;
y2 = y;
break;
case 3:
y -= wid / 2;
x2 = x;
y2 = y + len + wid;
break;
}
var graphics = new PIXI.Graphics();
graphics.lineStyle(wid, 0x111111, 1);
graphics.moveTo(x, y);
graphics.lineTo(x2, y2);
layer.addChild(graphics);
onSuccess(idx, dat);
};
var createWall = function (idx, dat, layer, onSuccess) {
if (dat === null) return null;
var id = dat.id;
var para = _modelData.items[Data.categoryName.wall][id];
var x = dat.left * GridSize;
var y = dat.top * GridSize;
var r = dat.rotation;
var w = (dat.right - dat.left + 1) * GridSize;
var h = (dat.bottom - dat.top + 1) * GridSize;
var obj = new PIXI.extras.TilingSprite(_tex['wall_' + para.id], w, h);
obj.anchor.x = 0;
obj.anchor.y = 0;
obj.position.x = x;
obj.position.y = y;
layer.addChild(obj);
onSuccess(idx, dat);
};
var createWallShadow = function (idx, dat, layer, onSuccess) {
if (dat === null) return null;
var id = dat.id;
var para = _modelData.items[Data.categoryName.wall][id];
var x = dat.left * GridSize;
var y = dat.top * GridSize;
var r = dat.rotation;
var w = (dat.right - dat.left + 1) * GridSize;
var h = (dat.bottom - dat.top + 1) * GridSize;
var graphics = new PIXI.Graphics();
graphics.lineStyle(0);
graphics.beginFill(0x000000);
graphics.drawRect(x - 8, y - 8, w + 16, h + 16);
graphics.endFill();
graphics.alpha = 0.4;
var blurFilter = new PIXI.filters.BlurFilter();
blurFilter.padding = 10;
blurFilter.blurX = 10;
blurFilter.blurY = 10;
graphics.filters = [blurFilter];
layer.addChild(graphics);
onSuccess(idx, dat);
};
var loadFurnitureTex = function (fileArr, para) {
if (!para.hasOwnProperty('action') || para['action'] == null) {
fileArr['f_' + para.id] = ({
name: 'f_' + para.id,
url: root + Data.files.path[Data.categoryName.furniture] + para.id + '/' + para.model2D[0],
onComplete: function (loader, resources) {
_tex['f_' + para.id] = PIXI.loader.resources['f_' + para.id].texture;
}
});
} else {
fileArr['f_' + para.id] = ({
name: 'f_' + para.id,
url: root + Data.files.path[Data.categoryName.furniture] + para.id + '/animation_2d.json',
onComplete: function (loader, resources) {
var _f = [];
for (var i = 0; i < 10; i++) {
var val = i < 10 ? '0' + i : i;
_f.push(PIXI.Texture.fromFrame('sprite00' + val));
}
_frames['f_' + para.id] = _f;
}
});
}
};
var createFurniture = function (idx, dat, layer, layer2, onSuccess) {
if (dat === null) return null;
var id = dat.id;
var para = _modelData.items[Data.categoryName.furniture][id];
var x = dat.left * GridSize;
var y = dat.top * GridSize;
var r = dat.rotation;
var w = para.dimension[0] * GridSize;
var h = (para.dimension[1]) * GridSize;
//console.log(dat);
//aconsole.log(id, 'x:' + x, 'y:' + y, 'w:' + w, 'h:' + h, 'r:' + r);
var offset_x = -GridSize / 2;
var offset_y = -GridSize / 2;
switch (r) {
case 1:
offset_x = h + GridSize / 2;
break;
case 2:
offset_x = w + GridSize / 2;
offset_y = h + GridSize / 2;
break;
case 3:
offset_y = w + GridSize / 2;
break;
}
that.objectPos.furniture[idx] = [(dat.left + dat.right) / 2 * GridSize, (dat.top + dat.bottom) / 2 * GridSize];
_animation['furniture'] = _animation['furniture'] || {};
_animation['furniture'][idx] = {};
if (!para.hasOwnProperty('action') || para['action'] == null) {
var obj = new PIXI.Sprite(_tex['f_' + para.id]);
obj.anchor.x = 0;
obj.anchor.y = 0;
obj.position.x = x + offset_x;
obj.position.y = y + offset_y;
obj.rotation = (r - 4) / 2 * Math.PI;
layer2.addChild(obj);
_animation['furniture'][idx][_Data.status.furniture.None] = function () {
};
onSuccess(idx, dat, obj);
} else {
var item = new PIXI.extras.MovieClip(_frames['f_' + para.id]);
item.loop = false;
item.position.x = x + offset_x;
item.position.y = y + offset_y;
item.rotation = (r - 4) / 2 * Math.PI;
layer.addChild(item);
_animation['furniture'][idx][_Data.status.furniture.None] = function () {
item.gotoAndStop(0);
};
_animation['furniture'][idx][_Data.status.furniture.Opened] = function () {
item.animationSpeed = 1;
item.gotoAndPlay(0);
};
_animation['furniture'][idx][_Data.status.furniture.Closed] = function () {
item.animationSpeed = -1;
item.gotoAndPlay(9);
};
onSuccess(idx, dat, item);
}
};
var loadDoorTex = function (fileArr, para) {
fileArr['door_' + para.id] = ({
name: 'door_' + para.id,
url: root + Data.files.path[Data.categoryName.door] + para.id + '/animation_2d.json',
onComplete: function (loader, resources) {
var _f = [];
for (var i = 0; i < 10; i++) {
var val = i < 10 ? '0' + i : i;
_f.push(PIXI.Texture.fromFrame('sprite00' + val));
}
_frames['door_' + para.id] = _f;
}
});
};
var createDoor = function (idx, dat, layer, onSuccess) {
if (dat === null) return null;
var id = dat.id;
var para = _modelData.items[Data.categoryName.door][id];
var x = dat.left * GridSize;
var y = dat.top * GridSize;
var r = dat.rotation;
var w = para.dimension[0] * GridSize;
var h = (para.dimension[1]) * GridSize;
var isElectric = para.electric === true;
var offset_x = -GridSize / 2;
var offset_y = -GridSize / 2;
switch (r) {
case 1:
offset_x = h + GridSize / 2;
break;
case 2:
offset_x = w + GridSize / 2;
offset_y = h + GridSize / 2;
break;
case 3:
offset_y = w + GridSize / 2;
break;
}
itemData['door'][idx] = {
x: (dat.left + dat.right) / 2 * GridSize,
y: (dat.top + dat.bottom) / 2 * GridSize,
r: r,
w: w,
h: h
}
that.objectPos.door[idx] = [(dat.left + dat.right) / 2 * GridSize, (dat.top + dat.bottom) / 2 * GridSize];
_animation['door'] = _animation['door'] || {};
_animation['door'][idx] = {};
var item = new PIXI.extras.MovieClip(_frames['door_' + para.id]);
item.loop = false;
item.position.x = x + offset_x;
item.position.y = y + offset_y;
item.rotation = (r - 4) / 2 * Math.PI;
layer.addChild(item);
_animation['door'][idx][_Data.status.door.Locked] = function () {
item.gotoAndStop(0);
};
_animation['door'][idx][_Data.status.door.Opened] = function () {
item.animationSpeed = 1;
item.gotoAndPlay(0);
};
_animation['door'][idx][_Data.status.door.Closed] = function () {
item.animationSpeed = -1;
item.gotoAndPlay(9);
};
_animation['door'][idx][_Data.status.door.Blocked] = function () {
item.gotoAndStop(0);
};
_animation['door'][idx][_Data.status.door.Destroyed] = function () {
item.gotoAndStop(0);
item.visible = false;
};
_animation['door'][idx][_Data.status.door.NoPower] = function () {
item.gotoAndStop(0);
};
onSuccess(idx, dat, item, isElectric);
};
var loadStuffTex = function (fileArr, para) {
fileArr['stuff_' + para.id] = ({
name: 'stuff_' + para.id,
url: root + Data.files.path[Data.categoryName.stuff] + para.id + '/' + para.model2D[0],
onComplete: function (loader, resources) {
_tex['stuff_' + para.id] = PIXI.loader.resources['stuff_' + para.id].texture;
}
});
};
var loadGeneratorTex = function (fileArr, para) {
fileArr['g_' + para.id] = ({
name: 'g_' + para.id,
url: root + Data.files.path[Data.categoryName.generator] + para.id + '/' + para.model2D[0],
onComplete: function (loader, resources) {
_tex['g_' + para.id] = PIXI.loader.resources['g_' + para.id].texture;
}
});
};
var createGenerator = function (idx, dat, layer, layer2, onSuccess) {
if (dat === null) return null;
var id = dat.id;
var para = _modelData.items[Data.categoryName.generator][id];
var x = dat.left * GridSize;
var y = dat.top * GridSize;
var r = dat.rotation;
var w = para.dimension[0] * GridSize;
var h = (para.dimension[1]) * GridSize;
//console.log(dat);
//aconsole.log(id, 'x:' + x, 'y:' + y, 'w:' + w, 'h:' + h, 'r:' + r);
var offset_x = -GridSize / 2;
var offset_y = -GridSize / 2;
switch (r) {
case 1:
offset_x = h + GridSize / 2;
break;
case 2:
offset_x = w + GridSize / 2;
offset_y = h + GridSize / 2;
break;
case 3:
offset_y = w + GridSize / 2;
break;
}
that.objectPos.generator[idx] = [(dat.left + dat.right) / 2 * GridSize, (dat.top + dat.bottom) / 2 * GridSize];
_animation['generator'] = _animation['generator'] || {};
_animation['generator'][idx] = {};
var obj = new PIXI.Sprite(_tex['g_' + para.id]);
obj.anchor.x = 0;
obj.anchor.y = 0;
obj.position.x = x + offset_x;
obj.position.y = y + offset_y;
obj.rotation = (r - 4) / 2 * Math.PI;
layer2.addChild(obj);
var _frames = [];
_frames.push(_tex['g_light_red']);
_frames.push(_tex['g_light_white']);
_frames.push(_tex['g_light_green']);
var objLight = new PIXI.extras.MovieClip(_frames);
objLight.anchor.x = 0.5;
objLight.anchor.y = 0.5;
objLight.scale.x = 2;
objLight.scale.y = 2;
objLight.position.x = x + GridSize / 2;
objLight.position.y = y + GridSize / 2;
layer.addChild(objLight);
_animation['generator'][idx][_Data.status.generator.Broken] = function () {
objLight.gotoAndStop(0);
};
_animation['generator'][idx][_Data.status.generator.Fixing] = function () {
objLight.gotoAndStop(1);
};
_animation['generator'][idx][_Data.status.generator.Worked] = function () {
objLight.gotoAndStop(2);
};
onSuccess(idx, dat, obj, objLight);
};
var createStuff = function (dat, layer, onSuccess) {
if (dat === null) return null;
var id = dat.id;
var x = dat.left * GridSize;
var y = dat.top * GridSize;
var r = dat.rotation;
var w = GridSize;
var h = GridSize;
var para = _modelData.items[Data.categoryName.stuff][id];
var obj = new PIXI.Sprite(_tex['stuff_' + para.id]);
var offset_x = 0;
var offset_y = 0;
switch (r) {
case 1:
offset_x = h;
break;
case 2:
offset_x = w;
offset_y = h;
break;
case 3:
offset_y = w;
break;
}
obj.anchor.x = 0;
obj.anchor.y = 0;
obj.position.x = x + offset_x;
obj.position.y = y + offset_y;
obj.rotation = (r - 4) / 2 * Math.PI;
layer.addChild(obj);
onSuccess(dat);
};
var removeKey = function (idx, scene, onSuccess) {
};
// Update items ----------------------------------------------------------
var updateFuniture = function () {
// update furniture
for (var i in gameData.f) {
if (gameData.f[i].status !== itemStatus['furniture'][i] && itemStatus['furniture'][i] !== null) {
itemStatus['furniture'][i] = gameData.f[i].status;
_animation['furniture'][i][itemStatus['furniture'][i]]();
}
}
};
var updateDoor = function () {
// update door
for (var i in gameData.d) {
if (itemStatus['door'][i] !== null) {
if (gameData.d[i].status !== itemStatus['door'][i]) {
itemStatus['door'][i] = gameData.d[i].status;
_animation['door'][i][itemStatus['door'][i]]();
var door = _mapData.item.door[i];
var s = (gameData.d[i].status === _Data.status.door.Opened || gameData.d[i].status === _Data.status.door.Destroyed) ? null : 'd_' + i;
for (var i = door.top; i <= door.bottom; i++) {
for (var j = door.left; j <= door.right; j++) {
that.blockMap[i][j] = s;
}
}
}
}
}
};
var updateGenerator = function () {
for (var i in gameData.g) {
if (itemStatus['generator'][i] !== null) {
if (gameData.g[i].status !== itemStatus['generator'][i]) {
itemStatus['generator'][i] = gameData.g[i].status;
_animation['generator'][i][itemStatus['generator'][i]]();
}
}
}
};
var updateBody = function () {
// update body
for (var i in gameData.b) {
if (itemData['body'][i] === undefined || itemData['body'][i] === null) {
if (entity.characters !== null && entity.characters[i] !== null) {
itemData['body'][i] = {
x: entity.characters[i].x,
y: entity.characters[i].y,
}
that.objectPos.body[i] = [entity.characters[i].x, entity.characters[i].y];
}
}
}
};
var updateKey = function () {
// update key
if (_mapData === null) return;
};
var updateLight = function () {
if (!gameData.hasOwnProperty('da')) return;
if (_dangerCache === gameData.da) return;
_dangerCache = gameData.da;
that.danger.alpha=(_dangerCache / 400);
};
var createEndPos = function (dat) {
if (that.posEnd !== null) return;
that.posEnd = [];
_layers['pos'] = new PIXI.Container();
_scene.addChild(_layers['pos']);
PIXI.loader.add('end', root + Data.files.path[Data.categoryName.sprite] + 'Sprite_EndPos.png').load(function (loader, resources) {
_tex['end'] = resources['end'].texture;
for (var i = 0; i < dat.length; i++) {
var obj = new PIXI.Sprite(_tex['end']);
obj.anchor.x = 0;
obj.anchor.y = 0;
obj.position.x = dat[i][0] * GridSize;
obj.position.y = dat[i][1] * GridSize;
_layers['pos'].addChild(obj);
that.posEnd[i] = obj;
}
});
};
// Base map -------------------------------------------------------
var setupStaticMap = function (scene) {
_layers['btnMap'] = new PIXI.Container();
_layers['topMap'] = new PIXI.Container();
_layers['shadowMap'] = new PIXI.Container();
scene.addChild(_layers['btnMap']);
};
var loadBaseMap = function (scene, btnMap, topMap) {
// btn
_loadMap(_layers['btnMap'],btnMap);
// top
scene.addChild(_layers['topMap']);
_loadMap(_layers['topMap'], topMap);
// shadow map
var blurFilter = new PIXI.filters.BlurFilter();
blurFilter.blurX = 1;
blurFilter.blurY = 1;
var grayFilter = new PIXI.filters.GrayFilter();
var colorFilter = new PIXI.filters.ColorMatrixFilter();
colorFilter.matrix = [
1, 0, 0, 0,
0, 1, 0, 0,
0, 0, 1, 0,
0, 0, 0, 1
];
colorFilter.brightness(0.9);
_layers['door'].visible = false;
that.shadowMap = new PIXI.Container();
_loadMap(that.shadowMap, scene, [blurFilter, grayFilter, colorFilter]);
_layers['door'].visible = true;
scene.filters = null;
scene.addChild(_layers['shadowMap']);
//_layers['shadowMap'].alpha = 0.75;
//clear up
btnMap.destroy();
topMap.destroy();
};
var _loadMap = function (layer, texObj, filters) {
var w = Math.floor(texObj.width / _Data.canvasLimit);
var h = Math.floor(texObj.height / _Data.canvasLimit);
var createSprite = function (renderTexture, filters) {
var spr = new PIXI.Sprite(renderTexture);
if (filters != null) {
var spr2 = spr;
spr2.filters = filters;
renderTexture.render(spr2);
spr = new PIXI.Sprite(renderTexture);
spr2.destroy();
}
return spr;
};
for (var i = 0; i < w; i++) {
for (var j = 0; j < h; j++) {
var renderTexture = new PIXI.RenderTexture(entity.env.renderer, _Data.canvasLimit, _Data.canvasLimit);
var m = new PIXI.Matrix();
m.translate(-i * _Data.canvasLimit, -j * _Data.canvasLimit);
renderTexture.render(texObj, m)
var spr = createSprite(renderTexture, filters);
spr.position.set(i * _Data.canvasLimit, j * _Data.canvasLimit);
layer.addChild(spr);
}
var renderTexture = new PIXI.RenderTexture(entity.env.renderer, _Data.canvasLimit, texObj.height - h * _Data.canvasLimit);
var m = new PIXI.Matrix();
m.translate(-i * _Data.canvasLimit, -h * _Data.canvasLimit);
renderTexture.render(texObj, m)
var spr = createSprite(renderTexture, filters);
spr.position.set(i * _Data.canvasLimit, h * _Data.canvasLimit);
layer.addChild(spr);
}
for (var j = 0; j < h; j++) {
var renderTexture = new PIXI.RenderTexture(entity.env.renderer, texObj.width - w * _Data.canvasLimit, _Data.canvasLimit);
var m = new PIXI.Matrix();
m.translate(-w * _Data.canvasLimit, -j * _Data.canvasLimit);
renderTexture.render(texObj, m)
var spr = createSprite(renderTexture, filters);
spr.position.set(w * _Data.canvasLimit, j * _Data.canvasLimit);
layer.addChild(spr);
}
var renderTexture = new PIXI.RenderTexture(entity.env.renderer, texObj.width - w * _Data.canvasLimit, texObj.height - h * _Data.canvasLimit);
var m = new PIXI.Matrix();
m.translate(-w * _Data.canvasLimit, -h * _Data.canvasLimit);
renderTexture.render(texObj, m);
var spr = createSprite(renderTexture, filters);
spr.position.set(w * _Data.canvasLimit, h * _Data.canvasLimit);
layer.addChild(spr);
};
// Setup ----------------------------------------------------------
var _setupTex = function () {
_tex = {};
};
var _init = function () {
_setupTex();
};
_init();
};
/**
* Game map
* @param {game entity} entity - Game entity
* @param {object} mapData - data used to setup a map
*/
RENDERER.Map = Map;
})(window.Rendxx.Game.Ghost.Renderer2D); |
//=====> HELPER FUNCTIONS
function updateIndices() {
var memberList = $('.list-members');
memberList.find('.user-new').each(function(i) {
$(this).find('input').attr('name', 'users[' + i + ']');
$(this).find('select').attr('name', 'roles[' + i + ']');
});
memberList.find('.user-changed').each(function(i) {
$(this).find('input').attr('name', 'userUps[' + i + ']');
$(this).find('select').attr('name', 'roleUps[' + i + ']');
});
}
function getItemContainer(element) {
return element.closest('.list-group-item');
}
function initMember(memberRow) {
// Replace title with select on click
memberRow.find('.fa-edit').parent().click(function(event) {
event.preventDefault();
var saveBtn = $('.btn-members-save');
if (!saveBtn.is(':visible'))
saveBtn.fadeIn('fast');
// Mark user as changed
var container = getItemContainer($(this)).addClass('user-changed');
var input = $('#select-role').clone().removeAttr('id').attr('form', 'save');
var roleId = container.find('.role-id').text();
input.find('option:eq(' + roleId + ')').attr('selected', '');
// Add input
container.find('span').replaceWith(input.show());
var username = container.find('.username').text().trim();
container.append('<input type="hidden" form="save" value="' + username + '" />');
// Remove edit button and update input names
$(this).find('.fa-edit').parent().remove();
updateIndices();
});
// Set form input on modal when delete is clicked
memberRow.find('.fa-trash').parent().click(function(event) {
event.preventDefault();
$('#modal-user-delete').find('input[name=username]').val(getItemContainer($(this)).find('.username').text().trim());
});
}
//=====> DOCUMENT READY
$(function() {
initMember($('.list-members').find('.list-group-item'));
initUserSearch(function(result) {
var alert = $('.member-error');
var message = alert.find('span');
if (!result.isSuccess) {
message.text('Could not find user with name "' + result.username + '".');
alert.fadeIn();
return;
}
alert.fadeOut();
var saveBtn = $('.btn-members-save');
if (!saveBtn.is(':visible'))
saveBtn.fadeIn('fast');
var user = result.user;
// Check if user is already defined
if ($('.list-members').find('a[href="/' + user.username + '"]').length) {
return;
}
// Build result row
var resultRow = $('#row-user').clone().removeAttr('id').addClass('user-new');
resultRow.find('.username').attr('href', '/' + user.username).text(user.username);
resultRow.find('input').attr('form', 'save').val(user.id);
resultRow.find('select').attr('form', 'save');
resultRow.find('svg').click(function() {
$(this).parent().remove();
updateIndices();
});
var avatarImg = resultRow.find('.user-avatar');
if (user.hasOwnProperty('avatarUrl')) {
var avatarUrl = user['avatarUrl'];
avatarImg.css('background-image', 'url(' + avatarUrl + ')');
} else
avatarImg.remove();
// Add result to list
$('.user-search').parent().before(resultRow);
updateIndices();
});
updateIndices();
});
|
require([
'underscore',
'handlebars',
'moment'
], function (_, Handlebars, moment) {
Handlebars.registerHelper('groupByDate', function (items, options) {
// First, group intervals by date
var grouped = {};
for (var i = 0; i < items.length; i++) {
var date = moment(items[i].from).format('YYYY.MM.DD');
if (!(date in grouped)) {
grouped[date] = [];
}
grouped[date].push(items[i]);
}
// Then sort them
var sorted = [];
for (var date in grouped) {
sorted.push({
date: date,
times: _(grouped[date]).sortBy(function (interval) {
return interval.from;
}).reverse()
});
}
sorted = _(sorted).sortBy(function (date) {
return date;
});
var output = "";
// Pass object to function
for (var i = sorted.length - 1; i >= 0; i--) {
output += options.fn(sorted[i]);
}
return output;
});
}); |
'use strict';
var joi = require('joi');
/**
* Validates provided params using the provided schema.
* @param {Object} params Params to validate.
* @param {Object} schema Joi schema to use for validation.
* @return {Object} Validated params.
* @throws Error if params are invalid.
*/
exports.validateParams = function(params, schema) {
var validation_result = joi.validate(params,
schema,
{
stripUnknown: true
});
if (validation_result.error) {
throw new Error('Failed to validate params: ' + validation_result.error);
}
return validation_result.value;
};
|
import { runView } from '../run';
import * as cases from './cases';
runView('classes overload', cases);
|
/**
* @license
* Copyright Google Inc. All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
// THIS CODE IS GENERATED - DO NOT MODIFY
// See angular/tools/gulp-tasks/cldr/extract.js
(function(global) {
global.ng = global.ng || {};
global.ng.common = global.ng.common || {};
global.ng.common.locales = global.ng.common.locales || {};
const u = undefined;
function plural(n) {
let i = Math.floor(Math.abs(n));
if (i === 0 || i === 1) return 1;
return 5;
}
global.ng.common.locales['fr-cg'] = [
'fr-CG',
[['AM', 'PM'], u, u],
u,
[
['D', 'L', 'M', 'M', 'J', 'V', 'S'], ['dim.', 'lun.', 'mar.', 'mer.', 'jeu.', 'ven.', 'sam.'],
['dimanche', 'lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi'],
['di', 'lu', 'ma', 'me', 'je', 've', 'sa']
],
u,
[
['J', 'F', 'M', 'A', 'M', 'J', 'J', 'A', 'S', 'O', 'N', 'D'],
[
'janv.', 'févr.', 'mars', 'avr.', 'mai', 'juin', 'juil.', 'août', 'sept.', 'oct.', 'nov.',
'déc.'
],
[
'janvier', 'février', 'mars', 'avril', 'mai', 'juin', 'juillet', 'août', 'septembre',
'octobre', 'novembre', 'décembre'
]
],
u,
[['av. J.-C.', 'ap. J.-C.'], u, ['avant Jésus-Christ', 'après Jésus-Christ']],
1,
[6, 0],
['dd/MM/y', 'd MMM y', 'd MMMM y', 'EEEE d MMMM y'],
['HH:mm', 'HH:mm:ss', 'HH:mm:ss z', 'HH:mm:ss zzzz'],
['{1} {0}', '{1} \'à\' {0}', u, u],
[',', '\u202f', ';', '%', '+', '-', 'E', '×', '‰', '∞', 'NaN', ':'],
['#,##0.###', '#,##0 %', '#,##0.00 ¤', '#E0'],
'FCFA',
'franc CFA (BEAC)',
{
'ARS': ['$AR', '$'],
'AUD': ['$AU', '$'],
'BEF': ['FB'],
'BMD': ['$BM', '$'],
'BND': ['$BN', '$'],
'BZD': ['$BZ', '$'],
'CAD': ['$CA', '$'],
'CLP': ['$CL', '$'],
'CNY': [u, '¥'],
'COP': ['$CO', '$'],
'CYP': ['£CY'],
'EGP': [u, '£E'],
'FJD': ['$FJ', '$'],
'FKP': ['£FK', '£'],
'FRF': ['F'],
'GBP': ['£GB', '£'],
'GIP': ['£GI', '£'],
'HKD': [u, '$'],
'IEP': ['£IE'],
'ILP': ['£IL'],
'ITL': ['₤IT'],
'JPY': [u, '¥'],
'KMF': [u, 'FC'],
'LBP': ['£LB', '£L'],
'MTP': ['£MT'],
'MXN': ['$MX', '$'],
'NAD': ['$NA', '$'],
'NIO': [u, '$C'],
'NZD': ['$NZ', '$'],
'RHD': ['$RH'],
'RON': [u, 'L'],
'RWF': [u, 'FR'],
'SBD': ['$SB', '$'],
'SGD': ['$SG', '$'],
'SRD': ['$SR', '$'],
'TOP': [u, '$T'],
'TTD': ['$TT', '$'],
'TWD': [u, 'NT$'],
'USD': ['$US', '$'],
'UYU': ['$UY', '$'],
'WST': ['$WS'],
'XCD': [u, '$'],
'XPF': ['FCFP'],
'ZMW': [u, 'Kw']
},
plural,
[
[
['minuit', 'midi', 'mat.', 'ap.m.', 'soir', 'nuit'], u,
['minuit', 'midi', 'du matin', 'de l’après-midi', 'du soir', 'du matin']
],
[
['minuit', 'midi', 'mat.', 'ap.m.', 'soir', 'nuit'], u,
['minuit', 'midi', 'matin', 'après-midi', 'soir', 'nuit']
],
[
'00:00', '12:00', ['04:00', '12:00'], ['12:00', '18:00'], ['18:00', '24:00'],
['00:00', '04:00']
]
]
];
})(typeof globalThis !== 'undefined' && globalThis || typeof global !== 'undefined' && global ||
typeof window !== 'undefined' && window);
|
import { ModuleNamespace } from 'es-module-loader/core/loader-polyfill.js';
import RegisterLoader from 'es-module-loader/core/register-loader.js';
import { global, baseURI, CONFIG, PLAIN_RESOLVE, PLAIN_RESOLVE_SYNC, resolveIfNotPlain, resolvedPromise,
extend, emptyModule, applyPaths, scriptLoad, protectedCreateNamespace, getMapMatch, noop, preloadScript, isModule, isNode, checkInstantiateWasm } from './common.js';
export { ModuleNamespace }
export default SystemJSProductionLoader;
function SystemJSProductionLoader () {
RegisterLoader.call(this);
// internal configuration
this[CONFIG] = {
baseURL: baseURI,
paths: {},
map: {},
submap: {},
bundles: {},
depCache: {},
wasm: false
};
// support the empty module, as a concept
this.registry.set('@empty', emptyModule);
}
SystemJSProductionLoader.plainResolve = PLAIN_RESOLVE;
SystemJSProductionLoader.plainResolveSync = PLAIN_RESOLVE_SYNC;
var systemJSPrototype = SystemJSProductionLoader.prototype = Object.create(RegisterLoader.prototype);
systemJSPrototype.constructor = SystemJSProductionLoader;
systemJSPrototype[SystemJSProductionLoader.resolve = RegisterLoader.resolve] = function (key, parentKey) {
var resolved = resolveIfNotPlain(key, parentKey || baseURI);
if (resolved !== undefined)
return Promise.resolve(resolved);
// plain resolution
var loader = this;
return resolvedPromise
.then(function () {
return loader[PLAIN_RESOLVE](key, parentKey);
})
.then(function (resolved) {
resolved = resolved || key;
// if in the registry then we are done
if (loader.registry.has(resolved))
return resolved;
// then apply paths
// baseURL is fallback
var config = loader[CONFIG];
return applyPaths(config.baseURL, config.paths, resolved);
});
};
systemJSPrototype.newModule = function (bindings) {
return new ModuleNamespace(bindings);
};
systemJSPrototype.isModule = isModule;
systemJSPrototype.resolveSync = function (key, parentKey) {
var resolved = resolveIfNotPlain(key, parentKey || baseURI);
if (resolved !== undefined)
return resolved;
// plain resolution
resolved = this[PLAIN_RESOLVE_SYNC](key, parentKey) || key;
if (this.registry.has(resolved))
return resolved;
// then apply paths
var config = this[CONFIG];
return applyPaths(config.baseURL, config.paths, resolved);
};
systemJSPrototype.import = function () {
return RegisterLoader.prototype.import.apply(this, arguments)
.then(function (m) {
return m.__useDefault ? m.default: m;
});
};
systemJSPrototype[PLAIN_RESOLVE] = systemJSPrototype[PLAIN_RESOLVE_SYNC] = plainResolve;
systemJSPrototype[SystemJSProductionLoader.instantiate = RegisterLoader.instantiate] = coreInstantiate;
systemJSPrototype.config = function (cfg) {
var config = this[CONFIG];
if (cfg.baseURL) {
config.baseURL = resolveIfNotPlain(cfg.baseURL, baseURI) || resolveIfNotPlain('./' + cfg.baseURL, baseURI);
if (config.baseURL[config.baseURL.length - 1] !== '/')
config.baseURL += '/';
}
if (cfg.paths)
extend(config.paths, cfg.paths);
if (cfg.map) {
var val = cfg.map;
for (var p in val) {
if (!Object.hasOwnProperty.call(val, p))
continue;
var v = val[p];
if (typeof v === 'string') {
config.map[p] = v;
}
// object submap
else {
// normalize parent with URL and paths only
var resolvedParent = resolveIfNotPlain(p, baseURI) || applyPaths(config.baseURL, config.paths, p);
extend(config.submap[resolvedParent] || (config.submap[resolvedParent] = {}), v);
}
}
}
for (var p in cfg) {
if (!Object.hasOwnProperty.call(cfg, p))
continue;
var val = cfg[p];
switch (p) {
case 'baseURL':
case 'paths':
case 'map':
break;
case 'bundles':
for (var p in val) {
if (!Object.hasOwnProperty.call(val, p))
continue;
var v = val[p];
for (var i = 0; i < v.length; i++)
config.bundles[this.resolveSync(v[i], undefined)] = p;
}
break;
case 'depCache':
for (var p in val) {
if (!Object.hasOwnProperty.call(val, p))
continue;
var resolvedParent = this.resolveSync(p, undefined);
config.depCache[resolvedParent] = (config.depCache[resolvedParent] || []).concat(val[p]);
}
break;
case 'wasm':
config.wasm = typeof WebAssembly !== 'undefined' && !!val;
break;
default:
throw new TypeError('The SystemJS production build does not support the "' + p + '" configuration option.');
}
}
};
// getConfig configuration cloning
systemJSPrototype.getConfig = function (name) {
var config = this[CONFIG];
var map = {};
extend(map, config.map);
for (var p in config.submap) {
if (!Object.hasOwnProperty.call(config.submap, p))
continue;
map[p] = extend({}, config.submap[p]);
}
var depCache = {};
for (var p in config.depCache) {
if (!Object.hasOwnProperty.call(config.depCache, p))
continue;
depCache[p] = [].concat(config.depCache[p]);
}
var bundles = {};
for (var p in config.bundles) {
if (!Object.hasOwnProperty.call(config.bundles, p))
continue;
bundles[p] = [].concat(config.bundles[p]);
}
return {
baseURL: config.baseURL,
paths: extend({}, config.paths),
depCache: depCache,
bundles: bundles,
map: map,
wasm: config.wasm
};
};
// ensure System.register and System.registerDynamic decanonicalize
systemJSPrototype.register = function (key, deps, declare) {
if (typeof key === 'string')
key = this.resolveSync(key, undefined);
return RegisterLoader.prototype.register.call(this, key, deps, declare);
};
systemJSPrototype.registerDynamic = function (key, deps, executingRequire, execute) {
if (typeof key === 'string')
key = this.resolveSync(key, undefined);
return RegisterLoader.prototype.registerDynamic.call(this, key, deps, executingRequire, execute);
};
function plainResolve (key, parentKey) {
var config = this[CONFIG];
// Apply contextual submap
if (parentKey) {
var parent = getMapMatch(config.submap, parentKey);
var submap = config.submap[parent];
var mapMatch = submap && getMapMatch(submap, key);
if (mapMatch) {
var target = submap[mapMatch] + key.substr(mapMatch.length);
return resolveIfNotPlain(target, parent) || target;
}
}
// Apply global map
var map = config.map;
var mapMatch = getMapMatch(map, key);
if (mapMatch) {
var target = map[mapMatch] + key.substr(mapMatch.length);
return resolveIfNotPlain(target, parent) || target;
}
}
function doScriptLoad (url, processAnonRegister) {
return new Promise(function (resolve, reject) {
return scriptLoad(url, 'anonymous', undefined, function () {
processAnonRegister();
resolve();
}, reject);
});
}
var loadedBundles = {};
function coreInstantiate (key, processAnonRegister) {
var config = this[CONFIG];
var wasm = config.wasm;
var bundle = config.bundles[key];
if (bundle) {
var loader = this;
var bundleUrl = loader.resolveSync(bundle, undefined);
if (loader.registry.has(bundleUrl))
return;
return loadedBundles[bundleUrl] || (loadedBundles[bundleUrl] = doScriptLoad(bundleUrl, processAnonRegister).then(function () {
// bundle treated itself as an empty module
// this means we can reload bundles by deleting from the registry
if (!loader.registry.has(bundleUrl))
loader.registry.set(bundleUrl, loader.newModule({}));
delete loadedBundles[bundleUrl];
}));
}
var depCache = config.depCache[key];
if (depCache) {
var preloadFn = wasm ? fetch : preloadScript;
for (var i = 0; i < depCache.length; i++)
this.resolve(depCache[i], key).then(preloadFn);
}
if (wasm) {
var loader = this;
return fetch(key)
.then(function(res) {
if (res.ok)
return res.arrayBuffer();
else
throw new Error('Fetch error: ' + res.status + ' ' + res.statusText);
})
.then(function (fetched) {
return checkInstantiateWasm(loader, fetched, processAnonRegister)
.then(function (wasmInstantiated) {
if (wasmInstantiated)
return;
// not wasm -> convert buffer into utf-8 string to execute as a module
// TextDecoder compatibility matches WASM currently. Need to keep checking this.
// The TextDecoder interface is documented at http://encoding.spec.whatwg.org/#interface-textdecoder
var source = new TextDecoder('utf-8').decode(new Uint8Array(fetched));
(0, eval)(source + '\n//# sourceURL=' + key);
processAnonRegister();
});
});
}
return doScriptLoad(key, processAnonRegister);
}
|
define(['app/app'], function(App) {
module('Integration: NavMain', {
setup: function() {
},
teardown: function() {
App.reset();
}
});
test('Navigation Links', function() {
expect(3);
visit('/');
andThen(function() {
equal(find('nav li:nth-child(1)').text().trim(), 'home');
equal(find('nav li:nth-child(2)').text().trim(), 'games');
equal(find('nav li:nth-child(3)').text().trim(), 'about');
});
});
});
|
import PIXI from 'pixi.js';
import resourses from '../constants/resourses';
import {spriteStore, gameSounds} from '../constants/presets';
// import 'yuki-createjs'
import 'yuki-createjs/lib/soundjs-0.6.2.combined'
import es6Promise from 'es6-promise';
/**
* Звуки
*/
let soundPath = './assets/audio/';
let soundsArr = [];
for(let i=1; i<=8; i+=1)
soundsArr.push({src: "0" + i + ".ogg", id:"sound0" + i})
let p1 = new es6Promise.Promise((resolve, reject) => {
createjs.Sound.on("fileload", ()=>{
Object.assign(gameSounds, createjs.Sound);
resolve();
});
});
createjs.Sound.alternateExtensions = ["mp3"];
createjs.Sound.registerSounds(soundsArr, soundPath);
/**
* Картинки и атласы
*/
const loader = PIXI.loader;
const path = resourses.path.assets;
let assets = resourses.loadAssets;
assets = assets.map((item)=>{
let str = new RegExp('xml');
let path2 = str.test(item) ? path + 'fonts/info/' : path + 'images/';
return path2 + item;
});
/**
* Функция загрузки json-атласов.
* Создаёт спрайты и загоняет их в модуль spritesStore
* В коллбеке передаём старт рендера
* @param callback
*/
let p2 = new es6Promise.Promise((resolve, reject) => {
setTimeout(resolve, 1000, "one");
loader.add(assets);
loader.load(()=>{
// Загоняем сырые данные из json-файлов в хранилище спрайтов (spritesStore) по группам
for(let key in resourses.namesMap){
let spriteGroup = resourses.namesMap[key]; // anums, chips, bgNumbers...
spriteStore[key] = {};
for(let keyInGroup in spriteGroup){
// keyInGroup for chips: chip0, chipSm0, chip1...
spriteStore[key][keyInGroup] = PIXI.utils.TextureCache[ spriteGroup[keyInGroup] ];
}
}
resolve();
});
});
let assetLoader = (callback)=>{
es6Promise.all([p1, p2]).then(value => {
callback();
}, reason => {
console.log(reason)
});
};
export {assetLoader}; |
/*
Focalize.js - Dynamic HTML5 presentations
Copyright (C) 2013 Rubén Béjar {https://www.rubenbejar.com/}
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see {http://www.gnu.org/licenses/}.
*/
function FocalizeModule() {
var Focalize = {};
// Simple assertion. Probably it should not be here. I have not
// found a simple, up-to-date, not-tied-to-a-testing-framework library
// for contract based design that I like. This should be enough for now.
function assert(exp, msg) {
var message = msg || "Assertion failed";
if (!exp) {
// console.assert does not work in Firefox
// As the Error will be reported as thrown from here, at least I
// will output the trace so I can find out from where was this called
console.trace();
throw new Error(message);
}
};
// Valid types: "number", "string", "object"
function assertIsType(value, type, msg) {
var message = msg || "Wrong type found";
var valueType = typeof value;
if (valueType !== type) {
// this makes sure we have a failed assertion
assert(false, message);
}
};
// Copied from: <https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript>
// Get URL Get parameter. Example: var paramX = getParamaterByName('paramX');
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
Focalize.ValidStates = {onStarting : "ON STARTING",
onPresentation : "ON PRESENTATION",
onThumbnails : "ON THUMBNAILS"};
Focalize.currSlideIdx = 0;
Focalize.currSeqIdx = 0;
Focalize.$slides = [];
Focalize.numSlides = 0;
Focalize.seqChanges = [];
Focalize.numSeqs = 0;
Focalize.$seqs = [];
Focalize.seqNames = [];
Focalize.seqNumSlides = [];
Focalize.$slideDivs = [];
Focalize.slideNames = [];
Focalize.styleConfiguration = {};
Focalize.motios = [];
Focalize.$thumbContainer = null;
Focalize.thumbs = {};
Focalize.status = Focalize.ValidStates.onStarting;
/**
* Used to start the presentation from a style JSON file. As this
* causes trouble with Chrome/ium on local files (a common use
* case) this should not be used. I am keeping it just as a
* reference and a reminder, but I show it as deprecated.
* Use Focalize.loadPresentation instead
* @param styleJSON_URL
* @deprecated
*/
Focalize.loadPresentation_DEPRECATED = function(styleJSON_URL) {
// I can't put this code inside the start function because
// if I try to call fullScreen inside the getJSON callback
// (to make sure the JSON is loaded before creating anything)
// the browser says fullScreen has not been called in a
// function triggered by a user event
$(document).ready(function(){
// This code is just to prevent Firefox from reporting a not
// well formedJSON file, even when the JSON is OK.
$.ajaxSetup({beforeSend: function(xhr){
if (xhr.overrideMimeType) {
xhr.overrideMimeType("application/json");
}
}});
// This does not work in Chromium, as its default policy is not
// allowing AJAX request on local files. I haven't found a good solution
$.getJSON(styleJSON_URL, function(data) {
Focalize.styleConfiguration = data;
// And after the JSON file is loaded, we actually allow the user
// to load the presentation
Focalize.load();
});
});
};
Focalize.load = function() {
$(document).ready(function(){
// If there is a hash in the url, we will open the
// presentation in not full screen at that slide (if
// the slide does not exist, it opens the first slide).
// If you could call full screen from any code,
// I could use a parameter in the URL to find out
// if the user wants to open full or not full screen.
// But this is not possible (only from a user generated
// event).
// You can always click 'F' to go full screen after
// opening
candidateSlideIdx = parseInt(window.location.hash.slice(1));
if (candidateSlideIdx || candidateSlideIdx === 0) {
Focalize.notFullScreenStart();
}
$("body").append("<h1 class='remove-before-start' " +
"style='position: fixed; margin: 0 auto; top: 1%; left:0; right: 0;'>"+
$("title").text()+"</h1>");
$("body").append("<h2 class='remove-before-start' " +
"style='position: fixed; margin: 0 auto; top: 10%; left:0; right: 0;'>This is a <a href='https://github.com/rbejar/Focalize.js' target='_blank'>Focalize.js</a> presentation</h2>");
$("body").append("<button class='remove-before-start' " +
"style='position: fixed; margin:0 auto; top:25%; left:0; right:0; width:30%; height:20%;' " +
"onclick='Focalize.fullScreenStart()'>" +
"<h2>Full Screen Presentation</h2></button>");
$("body").append("<button class='remove-before-start' " +
"style='position: fixed; margin:0 auto; bottom: 25%; left:0; right:0; width: 30%; height:20%;' " +
"onclick='Focalize.notFullScreenStart()'>" +
"<h2>Windowed Presentation</h2></button>");
$("body").append("<h3 class='remove-before-start' " +
"style='position: fixed; margin: 0 auto; bottom: 1%; left:0; right: 0;'>Presentation tips: T (slide Thumbnails), F (Full screen)</h3>");
});
};
Focalize.fullScreenStart = function () {
$(document).ready(function() {
$("html").bind("fscreenopen", function() {
$('.remove-before-start').remove();
Focalize.startPresentation();
});
$("html").fullscreen();
});
};
Focalize.notFullScreenStart = function (callBackFunction) {
$(document).ready(function(){
$('.remove-before-start').remove();
if (callBackFunction) {
Focalize.startPresentation(callBackFunction);
} else {
Focalize.startPresentation();
}
});
};
/**
* Returns if the screen is in landscape (width > height). By
* default it returns true (i.e. if it does not know, it assumes it is).
*/
Focalize.isLandscapeScreen = function() {
if ($(window).height() > 0) {
return ($(window).width() > $(window).height());
} else {
return true;
}
};
Focalize.isValidSlide = function(slideIdx) {
return (slideIdx >= 0 && slideIdx < Focalize.numSlides);
};
Focalize.isValidSeq = function(seqIdx) {
return (seqIdx >= 0 && seqIdx < Focalize.numSeqs);
};
/**
* Returns the index of the sequence that contains the slide slideIdx
* (slide indexes start at 0)
* @param slideIdx
*/
Focalize.seqOfSlide = function(slideIdx) {
var i;
for (i = 1; i < Focalize.seqChanges.length; i++) {
if (slideIdx < Focalize.seqChanges[i]) {
return i-1;
}
}
return 0;
};
/**
* Returns the configuration data for the sequence which index is seqIdx
* @param seqIdx
*/
Focalize.seqConfigData = function(seqIdx) {
assert(Focalize.isValidSeq(seqIdx),
"seqIdx is " + seqIdx + " in Focalize.seqConfigDataf");
var i;
for (i = 0; i < Focalize.styleConfiguration.sequences.length; i++) {
if (Focalize.styleConfiguration.sequences[i].name === Focalize.seqNames[seqIdx]) {
return Focalize.styleConfiguration.sequences[i];
}
}
throw new Error("Sequence configuration data not found for seqIdx " + seqIdx);
return null;
};
/**
* Returns the configuration data for the slide which index is slideIdx
* @param slideIdx
*/
Focalize.slideConfigData = function(slideIdx) {
assert(Focalize.isValidSlide(slideIdx));
var i;
for (i = 0; i < Focalize.styleConfiguration.slides.length; i++) {
if (Focalize.styleConfiguration.slides[i].name === Focalize.slideNames[slideIdx]) {
return Focalize.styleConfiguration.slides[i];
}
}
throw new Error("Slide configuration data not found for slideIdx " + slideIdx);
return null;
};
/**
* Attach event handlers to the presentation. Only those related
* to user input (moving between slides etc.)
*/
Focalize.attachEventHandlers = function() {
$(document).on("keyup", Focalize.keyPresentationHandler);
// click event does not get right click in Chromium; mouseup gets left
// and right clicks properly in both Firefox and Chromium
// Mouseup instead of mousedown, so we can put links in slides and
// allow the user to follow them by clicking. It does not work
// very well, but it works (as long as the target of the link
// is _blank)
$(document).mouseup(Focalize.mousePresentationHandler);
$(document).hammer().on("swipe", Focalize.touchPresentationHandler);
$(document).hammer().on("pinchin", Focalize.touchPresentationHandler);
$(document).hammer().on("pinchout", Focalize.touchPresentationHandler);
};
/**
* Detach event handlers from the presentation. Only those related
* to user input (moving between slides etc.)
*/
Focalize.detachEventHandlers = function() {
$(document).unbind("keyup");
$(document).unbind("mouseup");
$(document).hammer().off("swipe", Focalize.touchPresentationHandler);
$(document).hammer().off("pinchin", Focalize.touchPresentationHandler);
$(document).hammer().off("pinchout", Focalize.touchPresentationHandler);
};
/**
* Creates background and other elements common for a sequence of slides
* @param seqIdx Which sequence?
*/
Focalize.$createSeqDiv = function(seqIdx) {
var i;
var seqConfigData = Focalize.seqConfigData(seqIdx);
//var seqWidthPx = Focalize.seqNumSlides[currSeqIdx] * $("html").width();
var seqWidthPercent = Focalize.seqNumSlides[seqIdx]*100;
var $seqDiv = $("<div></div>").addClass("seqToDisplay " + seqConfigData.containerCSSClass);
var $backgroundDiv = $("<div></div>").addClass("backgroundDiv");
var $backLayerDiv;
/* Explanation regarding background-size: height is 100% so it always takes
* the full div, which height should be the right one in percentage to the page.
* Width is trickier. I am using a percentage, because it is the only way I have
* found to prevent really ugly issues when the user plays (or has played) with
* the zoom in the browser. The background width in percentage is relative to the
* div, which is seqWidthPercent. But seqWidthPercent depends on the number of
* slides, so the background width has to depend on them too. Finally, I need the
* pagesWide coefficient to keep the proper aspect ratio.
*
* This solution is not perfect, and seems to work slightly better in Firefox than in
* Chromium, but it is far better than nothing, and seems to work reasonably fine
* unless the zoom levels are very big or very small.*/
for (i = 0; i < seqConfigData.backgroundLayers.length; i++) {
$backLayerDiv = $("<div></div>").addClass(seqConfigData.backgroundLayers[i].cssClass
+" backToScroll"+i)
.css({width: seqWidthPercent+"%",
"background-size":seqConfigData.backgroundLayers[i].pagesWide*100/Focalize.seqNumSlides[seqIdx]+"% 100%"});
$backgroundDiv.append($backLayerDiv);
}
for (i = 0; i < seqConfigData.animatedBackgroundLayers.length; i++) {
$backLayerDiv = $("<div></div>").addClass(seqConfigData.animatedBackgroundLayers[i].cssClass
+" backToScroll"+i+" backToPan"+i)
.css({width: seqWidthPercent+"%",
"background-size":seqConfigData.animatedBackgroundLayers[i].pagesWide*100/Focalize.seqNumSlides[seqIdx]+"% 100%"
});
$backgroundDiv.append($backLayerDiv);
// Create motio object for animation
Focalize.motios[i] = new Motio($backLayerDiv.get(0));
}
$seqDiv.append($backgroundDiv);
return $seqDiv;
};
Focalize.$createSlideDiv = function($slideChildren, seqIdx) {
var $slideDiv = $("<div></div>")
.addClass(Focalize.seqConfigData(seqIdx).slideCommonsCSSClass);
$slideDiv.append($slideChildren);
return $slideDiv;
};
/**
* Creates and returns a div for the title of the slide. It may
* be an empty div if the slide has no title (i.e. if its
* titleLayerCSSClass is an empty string).
*/
Focalize.$createTitleDiv = function(slideIdx) {
var $titleDiv;
var $titleTextAreaDiv;
var $titleContents;
if (Focalize.slideConfigData(slideIdx).titleLayerCSSClass !== "") {
$titleDiv = $("<div></div>")
.addClass(Focalize.slideConfigData(slideIdx).titleLayerCSSClass);
$titleTextAreaDiv = $("<div></div>")
.addClass(Focalize.slideConfigData(slideIdx).titleTextAreaCSSClass);
$titleContents = Focalize.$slides[slideIdx].find("h1")
.addClass(Focalize.slideConfigData(slideIdx).cssClass);
$titleTextAreaDiv.append($titleContents);
$titleDiv.append($titleTextAreaDiv);
} else { // No title
$titleDiv = $("<div></div>");
}
return $titleDiv;
};
/**
* Lays out certain content (i.e. certain allowed HTML elements)
* in a div.
*
* @param slideIdx Index of the slide which content we are laying out
* @param content An array of objects (order is important). Example:
* [{type: "H2", // must be uppercase
* $element: a jQueryObject},
* {type: "H3",
* $element: a jQueryObject}...];
* @param $contentDiv a jQueryObject with a div where the content will be appended
* @returns $contentDiv with content properly laid out and appended
*/
Focalize.layoutContent = function(slideIdx, content, $contentDiv) {
var $contentElementDivs = [];
var $allContentElements = $();
var numElements = content.length;
if (numElements <= 0) {
return $contentDiv;
}
// If we actually have elements to lay out...
// Returns the layout type to use depending on the elements in content array
var chooseLayoutType = function() {
// 0: layout undefined for the current content
// 1: every element is h2, h3 or h4, more than one element
// 2: a single element, of type h2, h3 or h4
// 3: a single img
// 4: a single img along with a single figcaption (I assume they are enclosed
// in a figure element, but I do not take that into account)
// 5: several imgs (2..N) DEFINE N!
// ...
var i;
if (numElements <= 0) {
return 0;
}
var numOfEachElement = {
H2:0,H3:0,H4:0,IMG:0,FIGURE:0,
FIGCAPTION:0, UNSUPPORTED:0
};
var elementTypeArray = [];
var currentTag = "";
for (i = 0; i < numElements; i++) {
currentTag = content[i].type.toUpperCase(); // toUpperCase, just in case ;-)
switch (currentTag) {
case "H2":
case "H3":
case "H4":
case "IMG":
case "FIGCAPTION":
elementTypeArray[i] = currentTag;
numOfEachElement[currentTag] += 1;
break;
default:
elementTypeArray[i] = "UNSUPPORTED";
numOfEachElement["UNSUPPORTED"] += 1;
break;
}
}
var numH2H3H4 = numOfEachElement["H2"] +
numOfEachElement["H3"] +
numOfEachElement["H4"];
var returnedLayoutType = 0;
if (numOfEachElement["UNSUPPORTED"] > 0) {
returnedLayoutType = 0;
} else if (numH2H3H4 === 1 && numOfEachElement["IMG"] === 0) {
returnedLayoutType = 2;
} else if (numH2H3H4 > 1 && numOfEachElement["IMG"] === 0) {
returnedLayoutType = 1;
} else if (numH2H3H4 === 0 && numOfEachElement["IMG"] === 1 &&
numOfEachElement["FIGCAPTION"] === 0) {
returnedLayoutType = 3;
} else if (numOfEachElement["FIGCAPTION"]===1 && numOfEachElement["IMG"] === 1) {
returnedLayoutType = 4;
} else if (numH2H3H4 === 0 && numOfEachElement["IMG"] > 1 &&
numOfEachElement["FIGCAPTION"] === 0) {
returnedLayoutType = 5;
}
else {
returnedLayoutType = 0;
}
return {layoutType: returnedLayoutType, elementArray: elementTypeArray};
};
/**
* Each layoutFunction takes an elementArray (an array of HTML tag names
* as strings in upperCase) and a content (the same content array received
* by Focalize.layoutContent) and returns an array of divs with those elements
* laid out somehow (ever function is specialized in a layout for
* certain elements; if the wrong elements are include in the elementArray,
* the result is unpredictable, and possibly very wrong.
* As a guideline, the returned divs should be absolute positioned, with sizes
* in percentages if needed, and with a z-index right for the style (e.g.
* the same z-index as the foreground area for the contents.)
* These divs will be added (in order) to the content div for the slide.
*/
var layoutFunctions = [];
// Layout function 0: No layout available. Show an error instead of the content
layoutFunctions[0] = function(elementArray, content) {
var $contentElementDivs = [];
$contentElementDivs[0] = $("<div></div>");
$contentElementDivs[0].append($("<h2>NO LAYOUT AVAILABLE FOR THIS SLIDE. CHECK ITS CONTENTS.</h2>")
.css({
position: "absolute",
top: 0,
left: 0,
width: "100%",
height: "100%",
overflow: "hidden",
color: "red",
"z-index": 200000,
background: "transparent"
}));
return $contentElementDivs;
};
// Layout function 1: all elements are h2, h3, h4 (show like an unordered list)
layoutFunctions[1] = function(elementArray, content) {
var i;
var $contentElementDivs = [];
// elementWeights are relative to each other
var elementWeights = {"H2": 1,
"H3": 0.85,
"H4": 0.65};
// elementIndents are in percentage of the available width
var elementIndents = {"H2": 0,
"H3": 3,
"H4": 6};
var totalRelativeHeight = 0;
var numElements = elementArray.length;
if (numElements === 0) {
return;
}
for (i = 0; i < numElements; i++) {
totalRelativeHeight += elementWeights[elementArray[i]];
}
var numberOfGaps = numElements - 1;
var gapSize = 2; /*Percentage*/
var totalPercentHeight = 100 - (gapSize * numberOfGaps);
var currentElementHeight;
var currentElementTop = 0;
for (i = 0; i < numElements; i++) {
currentElementHeight = (elementWeights[elementArray[i]] / totalRelativeHeight)
* totalPercentHeight;
$contentElementDivs[i] = $("<div></div>")
.css({
position: "absolute",
top: currentElementTop+"%",
left: (0 + elementIndents[elementArray[i]])+"%",
right: 0,
height: currentElementHeight+"%",
overflow: "visible",
"z-index": 201,
background: "transparent",
});
$contentElementDivs[i].append(content[i].$element
.addClass(Focalize.slideConfigData(slideIdx).cssClass)
.css({"text-align":"left"}));
currentElementTop = currentElementTop + currentElementHeight + gapSize;
}
return $contentElementDivs;
};
// Layout function 2: a single element H2, H3 or H4
layoutFunctions[2] = function(elementArray, content) {
var $contentElementDivs = [];
$contentElementDivs[0] = $("<div></div>").addClass("simple-city-layout-single-h");
$contentElementDivs[0].append(content[0].$element
.addClass(Focalize.slideConfigData(slideIdx).cssClass))
.css({"text-align":"center"});
return $contentElementDivs;
};
// Layout function 3: a single element img
layoutFunctions[3] = function(elementArray, content) {
var $contentElementDivs = [];
$contentElementDivs[0] = $("<div></div>").addClass("simple-city-layout-single-img");
// Image centered, takes all availabe height while keeping
// aspect ratio. This seems a sensible choice as long as the
// presentation is in landscape, as should be on any desktop
// screen. For smarthpones or tablets, if they are held
// in portrait, this could lead to images which are not
// entirely shown (fill 100% vertical space, and keep aspect
// ratio, may mean that the whole picture is not shown). Landscape
// should be used in mobile devices anyway.
// The display block + margins are necessary for the centering
$contentElementDivs[0].append(content[0].$element
.addClass(Focalize.slideConfigData(slideIdx).cssClass +
" simple-city-layout-single-img"));
return $contentElementDivs;
};
// Layout function 4: a single element img with a figcaption. If the
// figcaption comes first, it will be on top of the img. Otherwise,
// at the bottom
layoutFunctions[4] = function(elementArray, content) {
var $contentElementDivs = [];
var theFigCaption;
var theImg;
var aspectRatio;
if (content[0].type === "IMG") { // Image on top
theImg = content[0];
theFigCaption = content[1];
// Image
$contentElementDivs[0] = $("<div></div>").addClass("simple-city-layout-img-figcaption")
.css({top:0,left:0,right:0, bottom:"15%"});
// I use the same CSS style for the img than in the layout with single img
$contentElementDivs[0].append(theImg.$element
.addClass(Focalize.slideConfigData(slideIdx).cssClass +
" simple-city-layout-single-img"));
// FigCaption
$contentElementDivs[1] = $("<div></div>").addClass("simple-city-layout-img-figcaption")
.css({top:"86%",left:0,right:0,bottom:0});
$contentElementDivs[1].append(theFigCaption.$element
.addClass(Focalize.slideConfigData(slideIdx).cssClass).css({"text-align":"center"}));
} else { // Caption on top
theImg = content[1];
theFigCaption = content[0];
// FigCaption
$contentElementDivs[0] = $("<div></div>").addClass("simple-city-layout-img-figcaption")
.css({top:0,left:0,right:0,bottom:"86%"});
$contentElementDivs[0].append(theFigCaption.$element
.addClass(Focalize.slideConfigData(slideIdx).cssClass).css({"text-align":"center"}));
// Image
$contentElementDivs[1] = $("<div></div>").addClass("simple-city-layout-img-figcaption")
.css({top:"15%",left:0,right:0, bottom:0});
// I use the same CSS style for the img than in the layout with single img
$contentElementDivs[1].append(theImg.$element
.addClass(Focalize.slideConfigData(slideIdx).cssClass +
" simple-city-layout-single-img"));
}
return $contentElementDivs;
};
// Layout function 5: all elements are img (more than one)
layoutFunctions[5] = function(elementArray, content) {
var i;
var cssString;
var $contentElementDivs = [];
var numElements = elementArray.length;
var aspectRatios = [];
for (i = 0; i < numElements; i++) {
aspectRatios[i] = content[i].$element.height() > 0 ?
content[i].$element.width() / content[i].$element.height() : 1;
}
// I will be assuming landscape mode by default, as it should
// be (in desktops is not a problem, but in mobile it could be)
// Some adjustments in Focalize.adjustContents could be done...
// 2 images, layout top/down or left/right according to
// their aspect ratios. If undecided, left/right
if (numElements === 2) {
if (aspectRatios[0] > 1 && aspectRatios[1] > 1) {
// top/down
$contentElementDivs[0] = $("<div></div>").addClass("simple-city-layout-img-top");
$contentElementDivs[0].append(content[0].$element
.addClass(Focalize.slideConfigData(slideIdx).cssClass +
" simple-city-layout-full-height"));
$contentElementDivs[1] = $("<div></div>").addClass("simple-city-layout-img-bottom");
$contentElementDivs[1].append(content[1].$element
.addClass(Focalize.slideConfigData(slideIdx).cssClass +
" simple-city-layout-full-height"));
} else {
// left/right
// In this case, check aspect ratios individually to choose css class
if (aspectRatios[0] < 1) {
cssString = "simple-city-layout-full-height";
} else {
cssString = "simple-city-layout-full-width";
}
$contentElementDivs[0] = $("<div></div>").addClass("simple-city-layout-img-left");
$contentElementDivs[0].append(content[0].$element
.addClass(Focalize.slideConfigData(slideIdx).cssClass +
" " + cssString));
if (aspectRatios[1] < 1) {
cssString = "simple-city-layout-full-height";
} else {
cssString = "simple-city-layout-full-width";
}
$contentElementDivs[1] = $("<div></div>").addClass("simple-city-layout-img-right");
$contentElementDivs[1].append(content[1].$element
.addClass(Focalize.slideConfigData(slideIdx).cssClass +
" " + cssString));
}
}
return $contentElementDivs;
};
var chosenLayout = chooseLayoutType();
$contentElementDivs = layoutFunctions[chosenLayout.layoutType](chosenLayout.elementArray,
content);
for (i = 0; i < $contentElementDivs.length; i++) {
$allContentElements = $allContentElements.add($contentElementDivs[i]);
}
return $contentDiv.append($allContentElements);
};
/**
* Fit texts, images etc. in a **single** slide to their calculated divs.
* Must be called after the $slideToAdjust has been appended
* to its final div, so the sizes are right and the
* fitting may work properly
*/
Focalize.adjustSlideContents = function($slideToAdjust) {
var $textFittedElems = $slideToAdjust.find(".textFitted");
// Remove any previous textFit fittings in $slideToAdjust
// (if there were any) before fitting again.
// This helps with some issues I had with the thumbnails
// and I think it is not a bad idea in any case
$textFittedElems.attr("style", "");
// 500 as maxFontSize means: make it as big as it gets
// alignHoriz: true is not working for me in Firefox (though it does in Chromium)
textFit($slideToAdjust.find("h1"), {alignVert: true, minFontSize: 5, maxFontSize: 500});
textFit($slideToAdjust.find("h2,h3,h4"),{alignVert: true, multiLine: true, minFontSize: 5, maxFontSize: 500});
textFit($slideToAdjust.find("figCaption"),{alignVert: true, multiLine: true, minFontSize: 5, maxFontSize: 500});
// After textFirtting elements, find out which one has the
// smallest font-size and give that size to all of them, so
// every element in the same category (e.g. H2) have the same size
var minimumSize = function (elementType, currentMin) {
var i;
var $textFitSpan = $slideToAdjust.find(elementType + " > .textFitted");
var min = currentMin;
var currSize;
for (i = 0; i < $textFitSpan.length; i++) {
currSize = parseFloat($textFitSpan.eq(i).css("font-size"));
if (currSize < min) {
min = currSize;
}
}
// If min is "too big" it will not be very different from
// the previous elements, so we force it to be smaller.
// 0.15 is a magic number. Should be a style decision
if (min > Math.floor(currentMin - 0.15 * currentMin)) {
min = Math.floor(currentMin - 0.15 * currentMin);
}
// We never allow the minimum font size below 5
// (magic number, seems minimum enough)
if (min < 5) {
min = 5;
}
$textFitSpan.css({"font-size":min+"px"});
return min;
};
// Llamamos en orden y así cada elemento será menor que el
// de la categoría anterior
var currentMin = Number.MAX_VALUE;
currentMin = minimumSize("h2", currentMin);
currentMin = minimumSize("h3", currentMin);
currentMin = minimumSize("h4", currentMin);
// TODO: some fitting could be done with images too. For instance
// if the user has changed from landscape to portrait in the
// middle of the presentation (something that should be avoided),
// we may choose to adjust images differently in their containers. We
// may change these images css class from simple-city-layout-full-width to
// simple-city-layout-full-height (or vice versa), or even we may
// choose to change the layout (this would be far more work)
/* Alternatives to fitText that I've tried with
* worse results.
*/
// $("."+Focalize.slideConfigData(newSlideIdx).cssClass)
// .jSlabify({fixedHeight:true, constrainHeight: true,
// hCenter: true, vCenter: true,
// maxWordSpace: 0.9,
// maxLetterSpace: 1.2 });
// maxWordSpace defaults to 3 and maxLetterSpace defaults to 1.5,
// and I think that is too much, at least for
// the titles. Maybe this could be configured in the style json file.
// However, I can't tweak it very well: it always seems too much or too little...
// I have also briefly tried FitText, BigText and SlabText.
// Neither of them takes into consideration
// vertical space, so they do not seem to offer
// anything better for my needs than jSlabify.
// RESPONSIVE MEASURE must be applied to selectors that include a single element
//$("h1").
// responsiveMeasure({
// Variables you can pass in:
// idealLineLength: (defaults to 66),
// minimumFontSize: (defaults to 16),
// maximumFontSize: (defaults to 300),
// ratio: (defaults to 4/3)
//})
// PARECE QUE EL QUE MÁS ME GUSTA ES texFit (HACE LO
// MISMO QUE JSLABIFY, INCLUYENDO ADAPTARSE A ANCHO Y ALTO
// PERO EL RESULTADO ME GUSTA MÁS (PERO DESDE LUEGO DISTA
// MUCHO DE SER PERFECTO PARA LO QUE BUSCO. POR EJEMPLO
// ES CAPAZ DE DEJAR UNA PALABRA SUELTA EN UNA LÍNEA DESPUÉS
// DE HABER LLENADO LA ANTERIOR)
};
Focalize.$createContentDiv = function(slideIdx) {
var i;
var $contentDiv = $("<div></div>")
.addClass(Focalize.slideConfigData(slideIdx).contentLayerCSSClass);
var $contentTextAreaDiv = $("<div></div>")
.addClass(Focalize.slideConfigData(slideIdx).contentTextAreaCSSClass);
var $contentTextAreaBufferDiv = $("<div></div>")
.addClass(Focalize.slideConfigData(slideIdx).contentTextAreaBufferCSSClass);
var $currElem;
var content = [];
// I am not interested in figure elements, I will assume they
// are there; I want imgs and figcaptions
var $validContentElements = Focalize.$slides[slideIdx].find("h2,h3,h4,img,figcaption");
for (i = 0; i < $validContentElements.length; i++) {
$currElem = $validContentElements.eq(i);
content[i] = {};
content[i].type = $currElem.get(0).tagName.toUpperCase(); // toUpperCase, just in case... ;-)
content[i].$element = $currElem;
}
$contentTextAreaDiv = Focalize.layoutContent(slideIdx, content, $contentTextAreaDiv);
// Could I use a layout plugin? My first tests with jLayout have
// not been very successful, and my needs do not seem complex...
$contentDiv.append($contentTextAreaBufferDiv);
$contentTextAreaBufferDiv.append($contentTextAreaDiv);
return $contentDiv;
};
/**
* Show slide with index newSlideIdx. The exact behavior will depend
* on if there is a change of sequence, and if it is a "next" or "previous"
* slide, or a different one.
* callBackFunction will be called (if present) after the new slide
* has been appended to the page (not necessarily after everything is completely
* adjusted and rendered).
* The slide newSlideIdx must exist.
* @param newSlideIdx
* @param callBackFunction
*/
Focalize.displaySlide = function(newSlideIdx, mustChangeHash,
callBackFunction) {
assert(Focalize.isValidSlide(newSlideIdx));
var i;
var isSeqChange = false;
var leapForwardInSeq = false;
var leapBackwardsInSeq = false;
var jumpSlides = 0;
var currSeqIdx = Focalize.currSeqIdx;
var currSlideIdx = Focalize.currSlideIdx;
var newSeqIdx = Focalize.seqOfSlide(newSlideIdx);
if (mustChangeHash) {
// Change Window Hash
window.location.hash = "#" + newSlideIdx;
}
if (newSeqIdx !== Focalize.currSeqIdx) {
isSeqChange = true;
} else {
if (newSlideIdx > (Focalize.currSlideIdx)) {
leapForwardInSeq = true;
jumpSlides = newSlideIdx - Focalize.currSlideIdx;
} else if (newSlideIdx < (Focalize.currSlideIdx)) {
leapBackwardsInSeq = true;
jumpSlides = Focalize.currSlideIdx - newSlideIdx;
}
}
if (isSeqChange || Focalize.status === Focalize.ValidStates.onStarting) {
$(".seqToDisplay").remove();
var $seqToDisplay = Focalize.$createSeqDiv(Focalize.seqOfSlide(newSlideIdx));
$(".focalize-presentation").after($seqToDisplay);
// Animate the animated layers of the new sequence
var newSeqConfigData = Focalize.seqConfigData(newSeqIdx);
for (i = 0; i < newSeqConfigData.animatedBackgroundLayers.length; i++) {
Focalize.motios[i].set('fps', newSeqConfigData.animatedBackgroundLayers[i].framesPerSecond);
Focalize.motios[i].set('speedX', -newSeqConfigData.animatedBackgroundLayers[i].panSpeed);
Focalize.motios[i].play();
}
}
// we must use clone in order to prevent making changes to our
// "master" slideDivs. This way we can make any changes to the
// slideDivs (adding classes, changing position...) without
// "destroying" the originals (allowing thus to return to
// any previous slide in its "start" state)
var $slideToDisplay = Focalize.$slideDivs[newSlideIdx].clone();
$slideToDisplay.addClass("slideToDisplay");
var $slideToRemove = $(".slideToDisplay");
var currSeqConfigData = Focalize.seqConfigData(currSeqIdx);
var currSlideConfigData = Focalize.slideConfigData(currSlideIdx);
var seqConfigData = Focalize.seqConfigData(newSeqIdx);
var slideConfigData = Focalize.slideConfigData(newSlideIdx);
var changeSlideToDisplay = function(seqName, slideName) {
$slideToRemove.remove();
// Maybe the user should have a certain degree of control
// on the use of transitions for slides (at least activate / deactivate
// for a given slide)
//$slideToDisplay.css({opacity:0.9, scale:0.8});
//$slideToDisplay.css({opacity:0, scale:0.5});
//$slideToDisplay.css({left:$("html").width()});
//$slideToDisplay.css({ rotateX: 180 });
if (Focalize.preInTransition) {
Focalize.preInTransition($slideToDisplay, seqName, slideName);
}
$(".seqToDisplay").append($slideToDisplay);
Focalize.adjustSlideContents($slideToDisplay);
//$slideToDisplay.transition({ opacity:1, scale: 1 }, 300);
//$slideToDisplay.transition({opacity:1, scale: 1, delay: 50 }, 300);
//$slideToDisplay.transition({ x:"-="+$("html").width()+"px"}, "fast", "easeOutQuint");
//$slideToDisplay.transition({ rotateX: 0 }, "slow");
if (Focalize.postInTransition) {
Focalize.postInTransition($slideToDisplay, seqName, slideName);
}
if (callBackFunction)
callBackFunction();
};
if ($slideToRemove.length === 0) {
// In first slide...
changeSlideToDisplay(seqConfigData.name,
slideConfigData.name);
} else {
if (leapForwardInSeq) {
if (Focalize.outTransition) {
Focalize.outTransition($slideToRemove, currSeqConfigData.name,
currSlideConfigData.name);
}
for (i = 0; i < seqConfigData.backgroundLayers.length; i++) {
$(".backToScroll"+i).transition({ x: "-="+
Math.floor($("html").width()*jumpSlides*
seqConfigData.backgroundLayers[i].scrollSpeed)
+"px" }, "slow");
}
$slideToRemove.css({position : "absolute", width : "100%"})
.transition({ x: "-="+$("html").width()+"px" }, "slow",
function() {changeSlideToDisplay(seqConfigData.name, slideConfigData.name);});
} else if (leapBackwardsInSeq) {
if (Focalize.outTransition) {
Focalize.outTransition($slideToRemove, currSeqConfigData.name,
currSlideConfigData.name);
}
for (i = 0; i < seqConfigData.backgroundLayers.length; i++) {
$(".backToScroll"+i).transition({ x: "+="+
Math.floor($("html").width()*jumpSlides*
seqConfigData.backgroundLayers[i].scrollSpeed)
+"px" }, "slow");
}
$slideToRemove.css({position : "absolute", width : "100%"})
.transition({ x: "+="+$("html").width()+"px" }, "slow",
function() {changeSlideToDisplay(seqConfigData.name, slideConfigData.name);});
}
}
Focalize.currSlideIdx = newSlideIdx;
Focalize.currSeqIdx = newSeqIdx;
};
Focalize.keyPresentationHandler = function(event) {
// console.log(event.which);
// which is normalized among browsers, keyCode is not
// The idea behind the detachEventHandlers() is to prevent a
// new event from being captured
// before the action triggered by this one is over
switch (event.which) {
case 39: // right arrow
case 40: // down arrow
case 78: // n
case 34: // page down
case 13: // return
case 32: // space
if (Focalize.status === Focalize.ValidStates.onPresentation) {
Focalize.detachEventHandlers();
Focalize.nextSlide();
event.preventDefault();
event.stopPropagation();
}
break;
case 37: // left arrow
case 38: // up arrow
case 80: // p
case 33 : // page up
case 8: // backspace
if (Focalize.status === Focalize.ValidStates.onPresentation) {
Focalize.detachEventHandlers();
Focalize.previousSlide();
event.preventDefault();
event.stopPropagation();
}
break;
//case 112: // F1 - Chromium does not allow to capture this key (it is its help)
//case 9: // Tab - Firefox behaves "weird" if I use this key... ???
case 84: // t
if (Focalize.status === Focalize.ValidStates.onPresentation) {
Focalize.showThumbs();
event.preventDefault();
event.stopPropagation();
} else if (Focalize.status === Focalize.ValidStates.onThumbnails) {
Focalize.hideThumbs();
event.preventDefault();
event.stopPropagation();
}
break;
case 70: // f
if (Focalize.status === Focalize.ValidStates.onPresentation ||
Focalize.status === Focalize.ValidStates.onThumbnails) {
event.preventDefault();
event.stopPropagation();
$("html").fullscreen();
}
break;
default:
// Nothing. I have found it important not to interfere at all
// with keys I do not use.
}
};
Focalize.mousePresentationHandler = function(event) {
// The idea behind the detachEventHandlers() is to prevent a
// new event from being captured
// before the action triggered by this one is over
switch (event.which) {
case 1: // left button
if (Focalize.status === Focalize.ValidStates.onPresentation) {
Focalize.detachEventHandlers();
event.preventDefault();
event.stopPropagation();
Focalize.nextSlide();
}
break;
case 3: // right button
if (Focalize.status === Focalize.ValidStates.onPresentation) {
Focalize.detachEventHandlers();
event.preventDefault();
event.stopPropagation();
Focalize.previousSlide();
}
break;
default:
// Nothing. I have found it important not to interfere at all
// with clicks I do not use.
}
};
Focalize.touchPresentationHandler = function(ev) {
if (ev.type === "swipe") {
if (ev.gesture.direction === "left") {
if (Focalize.status === Focalize.ValidStates.onPresentation) {
Focalize.detachEventHandlers();
Focalize.nextSlide();
// I don't really know if I need all these
ev.preventDefault();
ev.stopPropagation();
ev.gesture.stopPropagation();
ev.gesture.preventDefault();
ev.gesture.stopDetect();
}
} else if (ev.gesture.direction === "right") {
if (Focalize.status === Focalize.ValidStates.onPresentation) {
Focalize.detachEventHandlers();
Focalize.previousSlide();
// I don't really know if I need all these
ev.preventDefault();
ev.stopPropagation();
ev.gesture.stopPropagation();
ev.gesture.preventDefault();
ev.gesture.stopDetect() ;
}
}
} else if (ev.type === "pinchin") {
if (Focalize.status === Focalize.ValidStates.onPresentation) {
Focalize.showThumbs();
event.preventDefault();
event.stopPropagation();
ev.gesture.stopPropagation();
ev.gesture.preventDefault();
ev.gesture.stopDetect() ;
}
} else if (ev.type === "pinchout") {
if (Focalize.status === Focalize.ValidStates.onThumbnails) {
Focalize.hideThumbs();
event.preventDefault();
event.stopPropagation();
ev.gesture.stopPropagation();
ev.gesture.preventDefault();
ev.gesture.stopDetect() ;
}
}
};
Focalize.nextSlide = function() {
var newSlideIdx = Focalize.currSlideIdx;
newSlideIdx = Focalize.currSlideIdx + 1;
if (Focalize.isValidSlide(newSlideIdx)){
Focalize.displaySlide(newSlideIdx, true, Focalize.attachEventHandlers);
} else {
Focalize.attachEventHandlers();
}
};
Focalize.previousSlide = function() {
var newSlideIdx = Focalize.currSlideIdx;
newSlideIdx = Focalize.currSlideIdx - 1;
if (Focalize.isValidSlide(newSlideIdx)) {
Focalize.displaySlide(newSlideIdx, true, Focalize.attachEventHandlers);
} else {
Focalize.attachEventHandlers();
}
};
Focalize.startPresentation = function (callBackFunction) {
var i,j, currSlide;
var $allSeqs = $(".focalize-sequence");
var $currSeq, $currSeqSlides;
Focalize.$slides = [];
Focalize.numSlides = 0;
Focalize.seqChanges = []; // indexes of the slides that start a new sequence
Focalize.numSeqs = $allSeqs.size();
Focalize.$seqs = [];
Focalize.seqNames = [];
Focalize.seqNumSlides = []; // number of slides in each sequence
Focalize.$slideDivs = [];
Focalize.currSlideIdx = 0;
Focalize.currSeqIdx = 0;
// Calculate number of slides
for (i = 0; i < Focalize.numSeqs; i++) {
$currSeq = $(".focalize-sequence").eq(i);
$currSeqSlides = $currSeq.find(".focalize-slide");
for (j = 0; j < $currSeqSlides.size(); j++) {
Focalize.numSlides += 1;
}
}
currSlide = 0;
for (i = 0; i < Focalize.numSeqs; i++) {
$currSeq = $(".focalize-sequence").eq(i);
$currSeqSlides = $currSeq.find(".focalize-slide");
Focalize.$seqs[i] = $currSeq;
Focalize.seqNames[i] = $currSeq.data('seq-name');
Focalize.seqChanges[i] = currSlide;
Focalize.seqNumSlides[i] = $currSeqSlides.length;
for (j = 0; j < $currSeqSlides.size(); j++) {
Focalize.$slides[currSlide] = $currSeq.find(".focalize-slide").eq(j);
Focalize.slideNames[currSlide] = Focalize.$slides[currSlide].data('slide-name');
var $titleDiv = Focalize.$createTitleDiv(currSlide);
var $slideChildren = $titleDiv;
var $contentDiv = Focalize.$createContentDiv(currSlide);
$slideChildren = $slideChildren.add($contentDiv);
Focalize.$slideDivs[currSlide] = Focalize.$createSlideDiv($slideChildren, i);
currSlide += 1;
}
}
// Disable right click menu just before starting
$(document).bind("contextmenu", function(event) {
return false;
});
Focalize.attachEventHandlers();
// Experimental: this should make mobile browsers behave better
// (prevent undesired scrolls/zooms...)
$("head").append("<meta name='viewport' content='user-scalable=no,"+
"width=device-width, initial-scale=1, maximum-scale=1'>");
// Create thumbContainer now that the slides have been loaded
Focalize.createThumbContainer(3); // 3 is a magic number
Focalize.$thumbContainer.hide();
$(".focalize-presentation").after(Focalize.$thumbContainer);
// Asociamos displaySlide a cambios en el #N
// (número de página en la URL)
$(window).on('hashchange',function(){
// This event happens when the user changes the hash in the address
// bar of the navigator, but also when we change it in code
// As for now I can't distinguish, we make sure at least that
// the displaySlide function does not change the hash to prevent
// some unnecesary calls to this function when the hash number
// is right
if (Focalize.isHashNumberAValidSlideIdx()) {
Focalize.displaySlide(Focalize.validSlideIdxFromHashNumber(), false);
} else {
// when the hash number is wrong, we need it to change
Focalize.displaySlide(Focalize.validSlideIdxFromHashNumber(), true);
}
});
// I can't know if the hash contains a valid slide number until I have
// counted the slides in the presentation, so I do it after counting them
newSlideIdx = Focalize.validSlideIdxFromHashNumber();
// Display initial slide to start the presentation
if (newSlideIdx != 0) {
// If I don't display first de slide 0, make the change of
// status to onPresentation and then display the slide
// newSlideIdx, the background and the navigation will
// not work properly. This is something to improve
// as it smells pretty badly...
Focalize.displaySlide(0, false);
Focalize.status = Focalize.ValidStates.onPresentation;
Focalize.displaySlide(newSlideIdx, true, callBackFunction);
} else {
Focalize.displaySlide(0, true, callBackFunction);
Focalize.status = Focalize.ValidStates.onPresentation;
}
};
// Returns true if the hash number in the url is a valid slide idx
Focalize.isHashNumberAValidSlideIdx = function() {
candidateSlideIdx = parseInt(window.location.hash.slice(1));
return Focalize.isValidSlide(candidateSlideIdx);
}
// Returns a valid slide idx from the hash number in the window.location (url)
// If the hash is a number, and Focalize.isValideSlide is true, returns the hash number.
// If the hash is not a number, or not a slide, it returns 0.
Focalize.validSlideIdxFromHashNumber = function() {
candidateSlideIdx = parseInt(window.location.hash.slice(1));
var newSlideIdx = 0;
if (Focalize.isValidSlide(candidateSlideIdx)) {
newSlideIdx = candidateSlideIdx; // Extracted from the hash
}
return newSlideIdx;
}
Focalize.showThumbs = function() {
var i,j;
var numSlide = 0;
Focalize.status = Focalize.ValidStates.onThumbnails;
// Highlight current slide
for (i = 0; i < Focalize.thumbs.nRows; i++) {
for (j = 0; j < Focalize.thumbs.nCols &&
numSlide < Focalize.numSlides; j++) {
if (Focalize.currSlideIdx === numSlide) {
Focalize.thumbs.$divs[i][j].addClass("yellow-frame");
} else {
Focalize.thumbs.$divs[i][j].removeClass("yellow-frame");
}
numSlide += 1;
}
}
Focalize.$thumbContainer.show();
Focalize.$thumbContainer.find(".slideThumb").each(function() {
Focalize.adjustSlideContents($(this));
});
/*Focalize.createThumbContainer(4);
$(".focalize-presentation").after(Focalize.$thumbContainer);
// We must delay the adjust Contents (i.e. text fitting) until
// we actually have our thumbnails "on screen"
Focalize.$thumbContainer.find(".slideThumb").each(function() {
Focalize.adjustSlideContents($(this));
});*/
};
Focalize.hideThumbs = function() {
Focalize.status = Focalize.ValidStates.onPresentation;
Focalize.$thumbContainer.hide();
// Focalize.$thumbContainer.remove();
};
Focalize.createThumbContainer = function(nCols) {
if (!nCols) {
var nCols = 4;
}
var i,j, numSlide;
var $titleDiv, $contentDiv;
var zIndex = 30000;
var nRows = Math.ceil(Focalize.numSlides / nCols);
// A "full screen" black div to cover the slides
Focalize.$thumbContainer = $("<div></div>")
.css({
position: "fixed",
top: 0,
left: 0,
right: 0,
bottom: 0,
overflow: "auto",
"z-index": 30000,
background: "black"
});
// A slightly smaller div to provide some margin to the
// thumbs to prevent unwanted scroll bars
var $innerThumbContainer = $("<div></div>")
.css({
position: "absolute",
top: 2,
left: 5,
right: 5,
bottom: 2,
overflow: "show",
"z-index": 30000,
background: "transparent"
});
Focalize.$thumbContainer.append($innerThumbContainer);
// Create a grid of divs to show the thumbnails of each slide
var $divs = Focalize.createDivGrid(nCols, nRows, 0.5, 0.5, zIndex);
/*
* I need this function out of the fors. If I define the internal function in the
* bind to the click event, as usual, first of all I am creating too many
* functions and, even worse, it would not work as expected as those
* functions would capture the variable numSlide and not its current
* value (closure) as I would need.
*/
var slideOpener = function(n) {
return function() {
Focalize.hideThumbs();
Focalize.displaySlide(n, true);
};
};
numSlide = 0;
for (i = 0; i < nRows; i++) {
for (j = 0; j < nCols && numSlide < Focalize.numSlides; j++) {
var slideThumbClass = "slideThumb";
// Cloning is a precaution, as we will be fitting the texts etc. and we
// do not want those changes to show on the "master" slides
$divs[i][j].append(Focalize.$slideDivs[numSlide].clone().addClass(slideThumbClass));
$divs[i][j].bind("click", slideOpener(numSlide));
$innerThumbContainer.append($divs[i][j]);
numSlide += 1;
}
}
Focalize.thumbs = {
nCols : nCols,
nRows : nRows,
$divs: $divs
};
};
/**
*
* @param {Number} nCols
* @param {Number} nRows
* @param {Object} colGapSize In percentage
* @param {Object} rowGapSize In percentage
* @param {Object} colWeights (optional; all the same weight if not provided)
* @param {Object} rowWeights (optional; all the same weight if not provided)
* @param zIndex
*/
Focalize.createDivGrid = function(nCols, nRows, colGapSize, rowGapSize, zIndex,
colWeights, rowWeights) {
assert(nCols > 0, "nCols must be provided and greater than 0");
assert(nRows > 0, "nRows must be provided and greater than 0");
assert(colGapSize >= 0 && colGapSize <= 100, "colGapSize must be provided and [0..100]");
assert(rowGapSize >= 0 && rowGapSize <= 100, "rowGapSize must be provided and [0..100]");
assertIsType(zIndex, "number", "zIndex must be provided and be a number");
if (colWeights) {
assert(colWeights.length === nCols, "colWeights must be an Array of exactly nCols");
}
if (rowWeights) {
assert(rowWeights.length === nRows, "rowWeights must be an Array of exactly nRows");
}
var i,j;
var currDivHeight, currDivWidth;
var totalRelativeHeight = 0;
var totalRelativeWidth = 0;
var nColGaps = nCols - 1;
var nRowGaps = nRows - 1;
var $divs = [];
var currDivTop = 0;
var currDivLeft = 0;
if (!colWeights) {
colWeights = [];
for (i = 0; i < nCols; i++) {
colWeights[i] = 1;
}
}
if (!rowWeights) {
rowWeights = [];
for (i = 0; i < nRows; i++) {
rowWeights[i] = 1;
}
}
//var totalPercentHeight = 100 - (rowGapSize * nRowGaps);
// To keep rows which are not to squeezed, I will make the maximum
// height higher than 100%
var totalPercentHeight = (nRows * 30) - (rowGapSize * nRowGaps);
var totalPercentWidth = 100 - (colGapSize * nColGaps);
for (i = 0; i < nRows; i++) {
totalRelativeHeight += rowWeights[i];
}
for (i = 0; i < nCols; i++) {
totalRelativeWidth += colWeights[i];
}
for (i = 0; i < nRows; i++) {
$divs[i] = [];
currDivLeft = 0;
for (j = 0; j < nCols; j++) {
currDivHeight = (rowWeights[i] / totalRelativeHeight) * totalPercentHeight;
currDivWidth = (colWeights[j] / totalRelativeWidth) * totalPercentWidth;
$divs[i][j] = $("<div></div>")
.css({
position: "absolute",
top: currDivTop+"%",
left: currDivLeft+"%",
width: currDivWidth+"%",
height: currDivHeight+"%",
overflow: "visible",
"z-index": zIndex,
background: "transparent",
});
currDivLeft = currDivLeft + currDivWidth + colGapSize;
}
currDivTop = currDivTop + currDivHeight + rowGapSize;
}
return $divs;
};
return Focalize;
};
var Focalize = FocalizeModule();
|
/**
* (c) 2014 Beau Sorensen
* MIT Licensed
* For all details and documentation:
* https://github.com/sorensen/possibles
*/
;(function() {
'use strict';
/**
* Find all unique combinations of the given array elements
* http://codereview.stackexchange.com/questions/7001/better-way-to-generate-all-combinations
*
* @param {Array} input
* @return {Array} multi-dimentional combinations
*/
function combs(arr, depth) {
var resp = []
, len = arr.length
, total = (1 << len) // total combinations
for (var i = 1; i < total; i++) {
var tmp = []
, good = true
for (var k = 0; k < len; k++) {
if ((i & (1 << k))) {
tmp.push(arr[k])
}
// Check for combination depth
if (depth && tmp.length > depth) {
good = false
continue
}
}
// Prevent partial combinations from depth result
good && resp.push(tmp)
}
return resp
}
/*!
* Current library version, should match `package.json`
*/
combs.VERSION = '0.0.1'
/*!
* Module exports.
*/
typeof exports !== 'undefined'
? module.exports = combs
: this.combs = combs
}).call(this); |
console.log('Delete keyword based delete:');
const arr = [1,2,3,4,5];
delete arr[2]
console.log(arr);
// [ 1, 2, , 4, 5 ]
console.log(arr[2]);
// undefined
console.log('\nSplice based delete:');
const arr2 = [1,2,3,4,5];
arr2.splice(arr2, 2, 1);
console.log(arr2);
// [ 1, 3, 4, 5 ]
console.log(arr2[2]);
// 4
console.log('\nlength based delete:');
const arr3 = [1,2,3,4,5];
arr3.length = 4;
console.log(arr3);
// [ 1, 2, 3, 4 ]
arr3.length = 1;
console.log(arr3);
// [ 1 ]
const arr4 = [1,2,3,4,5];
arr4.forEach((element) => {
console.log(element);
if (element === 3) {
arr4.length = 0;
}
});
// 1
// 2
// 3
console.log('\nfilter based delete:');
const arr5 = [1,2,3,4,5];
const newArr = arr5.filter((element) => element !== 3);
console.log(arr5);
// [ 1, 2, 3, 4, 5 ]
console.log(newArr);
// [ 1, 2, 4, 5 ]
|
/**
* Created by Evgeniy_Generalov on 10/28/2016.
*/
"use strict";
var StaticResponseExpectation_1 = require("../expectation/StaticResponseExpectation");
function request(options) {
return new StaticResponseExpectation_1.StaticResponseExpectation(options);
}
exports.request = request;
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoicmVxdWVzdC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9jbGllbnQvbW9jay9yZXF1ZXN0LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBOztHQUVHOztBQUdILHNGQUFtRjtBQUduRixpQkFBd0IsT0FBb0I7SUFDMUMsTUFBTSxDQUFDLElBQUkscURBQXlCLENBQUMsT0FBTyxDQUFDLENBQUM7QUFDaEQsQ0FBQztBQUZELDBCQUVDIn0= |
require([
'app/MapController'
], function (
WidgetUnderTest
) {
describe('app/MapController', function () {
var widget;
beforeEach(function () {
widget = WidgetUnderTest;
});
afterEach(function () {
if (widget) {
widget = null;
}
});
describe('setExpression', function () {
it('should set visibility to false when no expression is set', function () {
var layer = {
name: 'layer',
setDefinitionExpression: jasmine.createSpy('def'),
setVisibility: jasmine.createSpy('vis')
};
var filters = [{
expression: '',
layer: layer
}];
widget.filters = filters;
widget.setExpression();
expect(layer.setDefinitionExpression.calls.count()).toEqual(1);
expect(layer.setVisibility.calls.count()).toEqual(1);
expect(layer.setDefinitionExpression).toHaveBeenCalledWith('1=2');
expect(layer.setVisibility).toHaveBeenCalledWith(false);
});
it('should set visibility to true when there is an expression is set', function () {
var layer = {
name: 'layer',
setDefinitionExpression: jasmine.createSpy('def'),
setVisibility: jasmine.createSpy('vis'),
addEventListener: function () {}
};
var filters = [{
expression: 'a = b',
layer: layer
}];
widget.filters = filters;
widget.setExpression();
expect(layer.setDefinitionExpression.calls.count()).toEqual(1);
expect(layer.setVisibility.calls.count()).toEqual(1);
expect(layer.setDefinitionExpression).toHaveBeenCalledWith('a = b');
expect(layer.setVisibility).toHaveBeenCalledWith(true);
});
it('should combine multiple expressions', function () {
var layer = {
name: 'layer',
setDefinitionExpression: jasmine.createSpy('def'),
setVisibility: jasmine.createSpy('vis'),
addEventListener: function () {}
};
var filters = [{
expression: 'a = b',
layer: layer
}, {
expression: 'b = c',
layer: layer
}];
widget.filters = filters;
widget.setExpression();
expect(layer.setDefinitionExpression.calls.count()).toEqual(1);
expect(layer.setVisibility.calls.count()).toEqual(1);
expect(layer.setDefinitionExpression).toHaveBeenCalledWith('a = b AND b = c');
expect(layer.setVisibility).toHaveBeenCalledWith(true);
});
it('should only use active filter expression', function () {
var layer = {
name: 'layer',
setDefinitionExpression: jasmine.createSpy('def'),
setVisibility: jasmine.createSpy('vis'),
addEventListener: function () {}
};
var filters = [{
expression: '',
layer: layer
}, {
expression: 'b = c',
layer: layer
}];
widget.filters = filters;
widget.setExpression();
expect(layer.setDefinitionExpression.calls.count()).toEqual(1);
expect(layer.setVisibility.calls.count()).toEqual(1);
expect(layer.setDefinitionExpression).toHaveBeenCalledWith('b = c');
expect(layer.setVisibility).toHaveBeenCalledWith(true);
});
it('should remove filters', function () {
var layer = {
name: 'layer',
setDefinitionExpression: jasmine.createSpy('def'),
setVisibility: jasmine.createSpy('vis'),
addEventListener: function () {}
};
var filters = [{
expression: 'a = b',
layer: layer
}, {
expression: 'b = c',
layer: layer
}];
widget.filters = filters;
widget.setExpression();
widget.filters[0].expression = 'c = d';
widget.setExpression();
var callCount = 2;
expect(layer.setDefinitionExpression.calls.count()).toEqual(callCount);
expect(layer.setVisibility.calls.count()).toEqual(callCount);
expect(layer.setDefinitionExpression.calls.argsFor(0)).toEqual(['a = b AND b = c']);
expect(layer.setVisibility.calls.argsFor(0)).toEqual([true]);
expect(layer.setDefinitionExpression.calls.argsFor(1)).toEqual(['c = d AND b = c']);
expect(layer.setVisibility.calls.argsFor(1)).toEqual([true]);
});
});
});
});
|
pageMechanic = function() {
$('[data-toggle="tooltip"]').tooltip();
if (checkUrl("simulated_tests/new")) {
console.log('[INFO] enginePage called at: simulated_tests/new.');
var engineDatepickers = function() {
$('#page .input-group.date').datepicker({
todayBtn: "linked",
keyboardNavigation: false,
forceParse: false,
calendarWeeks: true,
autoclose: true,
format: 'dd/mm/yyyy',
});
}
var engineSelects = function() {
$('#page .chosen-select').chosen({width: 'inherit'});
}
engineDatepickers();
engineSelects();
$('#dates').on('cocoon:after-insert', function() {
engineDatepickers();
});
$('#questions').on('cocoon:after-insert', function() {
engineSelects();
});
$('.add-question').trigger('click');
} else if (checkUrl("(simulated_tests)/[0-9]+")) {
// console.log('[INFO] enginePage called at: simulated_tests/[0-9]+.');
// simulatedTestTable = $('#simulated-test-table');
// if (simulatedTestTable.length > 0) {
// jQuery.extend( jQuery.fn.dataTableExt.oSort, {
// "only-float-pre": function ( a ) {
// result = parseFloat(a.match(/[0-9]*\.[0-9]*\%/g)[0].replace("%", ""));
// return result;
// },
// "only-float-asc": function ( a, b ) {
// return ((a < b) ? -1 : ((a > b) ? 1 : 0));
// },
// "only-float-desc": function ( a, b ) {
// return ((a < b) ? 1 : ((a > b) ? -1 : 0));
// }
// });
// var t = simulatedTestTable.dataTable({
// responsive: true,
// "order": [[ 3, "desc" ], [ 4, "desc" ], [ 5, "desc" ], [ 6, "desc" ], [ 7, "desc" ],],
// "aoColumnDefs": [
// { "sType": 'only-float', "asSorting": [ "desc", "asc"], "aTargets": [ 3, 4, 5, 6, 7 ], },
// { "orderable": false, "targets": [2], }
// ],
// language: {
// "sEmptyTable": "Nenhum registro encontrado",
// "sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
// "sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
// "sInfoFiltered": "(Filtrados de _MAX_ registros)",
// "sInfoPostFix": "",
// "sInfoThousands": ".",
// "sLengthMenu": "_MENU_ resultados por página",
// "sLoadingRecords": "Carregando...",
// "sProcessing": "Processando...",
// "sZeroRecords": "Nenhum registro encontrado",
// "sSearch": "Pesquisar ",
// "oPaginate": {
// "sNext": "Próximo",
// "sPrevious": "Anterior",
// "sFirst": "Primeiro",
// "sLast": "Último"
// },
// "oAria": {
// "sSortAscending": ": Ordenar colunas de forma ascendente",
// "sSortDescending": ": Ordenar colunas de forma descendente"
// }
// },
// });
// } else {
// console.log('[INFO] simulatedTestTable already loaded.');
// }
} else if (checkUrl("(simulated_tests/)[0-9]+(/edit_questions)[a-zA-Z0-9\/\?\=\%\&\\+\.\%\-\_]*")) {
console.log('[INFO] enginePage called at: simulated_tests/[0-9]+/edit_questions.');
var engineSelects = function() {
$('#page .chosen-select').chosen({width: 'inherit'});
}
engineSelects();
$('#questions .question .knowledge-area-select').change(function() {
select = $(this);
question = select.closest('.question');
question.find('.knowledge-object-select option').prop('selected', false);
question.find('.skill-select option').prop('selected', false);
question.find('.chosen-container').remove();
question.find('.knowledge-object-select.chosen-select').chosen('destroy');
question.find('.skill-select.chosen-select').chosen('destroy');
question.find('.knowledge-object-select').addClass('hidden').removeClass('chosen-select');
question.find('.skill-select').addClass('hidden').removeClass('chosen-select');
question.find('.from-knowledge-area-' + select.val()).removeClass('hidden').addClass('chosen-select').chosen({width: 'inherit'});
});
} else if (checkUrl("(simulated_tests/)[0-9]+(/edit)[a-zA-Z0-9\/\?\=\%\&\\+\.\%\-\_]*")) {
console.log('[INFO] enginePage called at: simulated_tests/[0-9]+/edit.');
var engineDatepickers = function() {
$('#page .input-group.date').datepicker({
todayBtn: "linked",
keyboardNavigation: false,
forceParse: false,
calendarWeeks: true,
autoclose: true,
format: 'dd/mm/yyyy',
});
}
engineDatepickers();
$('#dates').on('cocoon:after-insert', function() {
engineDatepickers();
});
} else if (checkUrl("(simulated_tests/)[0-9\/]*(show_statistic_report)[a-zA-Z0-9\/\?\=\%\&\\+\.\%\-\_]*")) {
console.log('[INFO] enginePage called at: simulated_tests/[0-9]+/show_statistic_report.');
var resource1 = $('table#statistic-report-resource__general tr').get().map(function(row) {
return $(row).find('td').get().map(function(cell) {
return $(cell).html();
});
});
var resource2 = $('table#statistic-report-resource__1 tr').get().map(function(row) {
return $(row).find('td').get().map(function(cell) {
return $(cell).html();
});
});
var resource3 = $('table#statistic-report-resource__2 tr').get().map(function(row) {
return $(row).find('td').get().map(function(cell) {
return $(cell).html();
});
});
graph1 = $("#statistic-report-graph1");
graph2 = $("#statistic-report-graph2");
graph3 = $("#statistic-report-graph3");
engineGraphs(graph1, resource1, "Médias de Acertos Geral");
engineGraphs(graph2, resource2, "Médias de Acertos por Área de Conhecimento - Parte 1");
engineGraphs(graph3, resource3, "Médias de Acertos por Área de Conhecimento - Parte 2");
$('.nestable-list').nestable();
$('[data-action="collapse"]').trigger('click');
} else if (checkUrl("(simulated_tests/)[0-9]+(/new_answers)")){
console.log('[INFO] enginePage called at: simulated_tests/[0-9]+/new_answers.');
var newAnswersDropzone = new Dropzone("#new-answers-dropzone", {
paramName: "answers",
autoProcessQueue: false,
});
newAnswersDropzone.element.querySelector("button[type=submit]").addEventListener("click", function(e) {
e.preventDefault();
e.stopPropagation();
newAnswersDropzone.processQueue();
});
} else if (checkUrl("simulated_tests/show_answer_cards")){
$('#simulated_test_id').chosen({width: 'inherit'});
} else if (checkUrl("students/[0-9]+/dashboard")) {
console.log('[INFO] enginePage called at: students/[0-9]+/dashboard.');
if ($('table#dashboard-simulated-test-graph-resource').length > 0) {
var resource = $('table#dashboard-simulated-test-graph-resource tr').get().map(function(row) {
return $(row).find('td').get().map(function(cell) {
return $(cell).html();
});
});
categories = [];
for (i = 2; i < resource.length; ++i) {
categories.push(resource[i][0]);
}
data = [];
for (j = 1; j < resource[0].length; ++j) {
data[j-1] = {};
data[j-1]["data"] = [];
data[j-1]["name"] = resource[0][j];
data[j-1]["color"] = resource[1][j];
for (k = 2; k < resource.length; ++k) {
data[j-1]["data"].push(parseFloat(resource[k][j]));
}
}
$('#dashboard-simulated-test-graph').highcharts({
chart: {
type: 'column',
height: 220,
},
title: { text: ' ' },
legend: {
layout: 'horizontal',
align: 'center',
verticalAlign: 'top',
},
credits: false,
xAxis: {
categories: categories,
crosshair: true
},
yAxis: {
// min: 0,
// max: 100,
tickInterval: 10,
title: {
text: 'Porcentagem de acertos'
}
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y:.1f} %</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: data
});
}
} else if (checkUrl("students/new")) {
} else if (checkUrl("students/[0-9]+")) {
console.log('[INFO] enginePage called at: students/[0-9]+.');
$('.histograms').each(function(index){
table1 = $(this).find('table.statistic-report-resource__general tr');
table2 = $(this).find('table.statistic-report-resource__1 tr');
table3 = $(this).find('table.statistic-report-resource__2 tr');
graph1 = $(this).find('.histogram1');
graph2 = $(this).find('.histogram2');
graph3 = $(this).find('.histogram3');
var resource1 = table1.get().map(function(row) {
return $(row).find('td').get().map(function(cell) {
return $(cell).html();
});
});
var resource2 = table2.get().map(function(row) {
return $(row).find('td').get().map(function(cell) {
return $(cell).html();
});
});
var resource3 = table3.get().map(function(row) {
return $(row).find('td').get().map(function(cell) {
return $(cell).html();
});
});
engineGraphs(graph1, resource1, "Médias de Acertos Geral");
engineGraphs(graph2, resource2, "Médias de Acertos por Área de Conhecimento - Parte 2");
engineGraphs(graph3, resource3, "Médias de Acertos por Área de Conhecimento - Parte 2");
});
$('.nestable-list').nestable();
$('[data-action="collapse"]').trigger('click');
$('span.pie').peity('pie', { fill: ['#1ab394', '#d7d7d7', '#ffffff'] });
} else if (checkUrl("students")) {
console.log('[INFO] enginePage called at: students.');
studentsTable = $('#students-table');
if (studentsTable.length > 0) {
var t = studentsTable.dataTable({
responsive: true,
"columnDefs": [ { "targets": [4, 5, 6], "orderable": false } ],
language: {
"sEmptyTable": "Nenhum registro encontrado",
"sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
"sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
"sInfoFiltered": "(Filtrados de _MAX_ registros)",
"sInfoPostFix": "",
"sInfoThousands": ".",
"sLengthMenu": "_MENU_ resultados por página",
"sLoadingRecords": "Carregando...",
"sProcessing": "Processando...",
"sZeroRecords": "Nenhum registro encontrado",
"sSearch": "Pesquisar ",
"oPaginate": {
"sNext": "Próximo",
"sPrevious": "Anterior",
"sFirst": "Primeiro",
"sLast": "Último"
},
"oAria": {
"sSortAscending": ": Ordenar colunas de forma ascendente",
"sSortDescending": ": Ordenar colunas de forma descendente"
}
},
});
} else {
console.log('[INFO] studentsTable already loaded.');
}
} else if (checkUrl("students/results")) {
console.log('[INFO] enginePage called at: students/results.');
studentsResultsTable = $('#students-results-table');
if (studentsResultsTable.length > 0) {
var t = studentsResultsTable.dataTable({
responsive: true,
language: {
"sEmptyTable": "Nenhum registro encontrado",
"sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
"sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
"sInfoFiltered": "(Filtrados de _MAX_ registros)",
"sInfoPostFix": "",
"sInfoThousands": ".",
"sLengthMenu": "_MENU_ resultados por página",
"sLoadingRecords": "Carregando...",
"sProcessing": "Processando...",
"sZeroRecords": "Nenhum registro encontrado",
"sSearch": "Pesquisar ",
"oPaginate": {
"sNext": "Próximo",
"sPrevious": "Anterior",
"sFirst": "Primeiro",
"sLast": "Último"
},
"oAria": {
"sSortAscending": ": Ordenar colunas de forma ascendente",
"sSortDescending": ": Ordenar colunas de forma descendente"
}
},
});
}
} else if (checkUrl("(students/)[0-9]+(/show_simulated_tests)[a-zA-Z0-9\/\?\=\%\&\\+\.\%\-\_]*")) {
console.log('[INFO] enginePage called at: students/0-9/show_simulated_tests.');
$('.histograms').each(function(index){
table = $(this).find('table tr');
graph1 = $(this).find('.histogram1');
graph2 = $(this).find('.histogram2');
var resource = table.get().map(function(row) {
return $(row).find('td').get().map(function(cell) {
return $(cell).html();
});
});
engineGraphs(graph1, resource.slice(0, 3), "Médias de Acertos por Área de Conhecimento - Parte 1");
engineGraphs(graph2, resource.slice(3, 5), "Médias de Acertos por Área de Conhecimento - Parte 2");
});
$('.nestable-list').nestable();
$('[data-action="collapse"]').trigger('click');
$('span.pie').peity('pie', { fill: ['#1ab394', '#d7d7d7', '#ffffff'] });
} else if (checkUrl("(students/)[0-9]+(/simulated_tests)")) {
console.log('[INFO] enginePage called at: students/[0-9]+/simulated_tests.');
availableSimulatedTestsTable = $('#avaliable-simulated-tests-table');
registeredSimulatedTestsTable = $('#registered-simulated-tests-table');
if (availableSimulatedTestsTable.length > 0) {
var t = availableSimulatedTestsTable.dataTable({
responsive: true,
"columnDefs": [ { "targets": [2, 3, 4], "orderable": false } ],
language: {
"sEmptyTable": "Nenhum registro encontrado",
"sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
"sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
"sInfoFiltered": "(Filtrados de _MAX_ registros)",
"sInfoPostFix": "",
"sInfoThousands": ".",
"sLengthMenu": "_MENU_ resultados por página",
"sLoadingRecords": "Carregando...",
"sProcessing": "Processando...",
"sZeroRecords": "Nenhum registro encontrado",
"sSearch": "Pesquisar ",
"oPaginate": {
"sNext": "Próximo",
"sPrevious": "Anterior",
"sFirst": "Primeiro",
"sLast": "Último"
},
"oAria": {
"sSortAscending": ": Ordenar colunas de forma ascendente",
"sSortDescending": ": Ordenar colunas de forma descendente"
}
},
});
}
if (registeredSimulatedTestsTable.length > 0) {
var t = registeredSimulatedTestsTable.dataTable({
responsive: true,
"columnDefs": [ { "targets": [2], "orderable": false } ],
language: {
"sEmptyTable": "Nenhum registro encontrado",
"sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
"sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
"sInfoFiltered": "(Filtrados de _MAX_ registros)",
"sInfoPostFix": "",
"sInfoThousands": ".",
"sLengthMenu": "_MENU_ resultados por página",
"sLoadingRecords": "Carregando...",
"sProcessing": "Processando...",
"sZeroRecords": "Nenhum registro encontrado",
"sSearch": "Pesquisar ",
"oPaginate": {
"sNext": "Próximo",
"sPrevious": "Anterior",
"sFirst": "Primeiro",
"sLast": "Último"
},
"oAria": {
"sSortAscending": ": Ordenar colunas de forma ascendente",
"sSortDescending": ": Ordenar colunas de forma descendente"
}
},
});
}
} else if (checkUrl("users")) {
console.log('[INFO] enginePage called at: users.');
usersTable = $('#users-table');
if (usersTable.length > 0) {
var t = usersTable.dataTable({
responsive: true,
"columnDefs": [ { "targets": [2, 3], "orderable": false } ],
language: {
"sEmptyTable": "Nenhum registro encontrado",
"sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
"sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
"sInfoFiltered": "(Filtrados de _MAX_ registros)",
"sInfoPostFix": "",
"sInfoThousands": ".",
"sLengthMenu": "_MENU_ resultados por página",
"sLoadingRecords": "Carregando...",
"sProcessing": "Processando...",
"sZeroRecords": "Nenhum registro encontrado",
"sSearch": "Pesquisar ",
"oPaginate": {
"sNext": "Próximo",
"sPrevious": "Anterior",
"sFirst": "Primeiro",
"sLast": "Último"
},
"oAria": {
"sSortAscending": ": Ordenar colunas de forma ascendente",
"sSortDescending": ": Ordenar colunas de forma descendente"
}
},
});
} else {
console.log('[INFO] studentsTable already loaded.');
}
} else if (checkUrl("knowledge_areas")) {
console.log('[INFO] enginePage called at: knowledge_areas.');
table = $('#knowledge-areas-table');
if (table.length > 0) {
var t = table.dataTable({
responsive: true,
"columnDefs": [ { "targets": [2, 3], "orderable": false } ],
language: {
"sEmptyTable": "Nenhum registro encontrado",
"sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
"sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
"sInfoFiltered": "(Filtrados de _MAX_ registros)",
"sInfoPostFix": "",
"sInfoThousands": ".",
"sLengthMenu": "_MENU_ resultados por página",
"sLoadingRecords": "Carregando...",
"sProcessing": "Processando...",
"sZeroRecords": "Nenhum registro encontrado",
"sSearch": "Pesquisar ",
"oPaginate": {
"sNext": "Próximo",
"sPrevious": "Anterior",
"sFirst": "Primeiro",
"sLast": "Último"
},
"oAria": {
"sSortAscending": ": Ordenar colunas de forma ascendente",
"sSortDescending": ": Ordenar colunas de forma descendente"
}
},
});
} else {
console.log('[INFO] studentsTable already loaded.');
}
} else if (checkUrl("knowledge_objects")) {
console.log('[INFO] enginePage called at: knowledge_objects.');
table = $('#knowledge-objects-table');
if (table.length > 0) {
var t = table.dataTable({
responsive: true,
"columnDefs": [ { "targets": [2, 3], "orderable": false } ],
language: {
"sEmptyTable": "Nenhum registro encontrado",
"sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
"sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
"sInfoFiltered": "(Filtrados de _MAX_ registros)",
"sInfoPostFix": "",
"sInfoThousands": ".",
"sLengthMenu": "_MENU_ resultados por página",
"sLoadingRecords": "Carregando...",
"sProcessing": "Processando...",
"sZeroRecords": "Nenhum registro encontrado",
"sSearch": "Pesquisar ",
"oPaginate": {
"sNext": "Próximo",
"sPrevious": "Anterior",
"sFirst": "Primeiro",
"sLast": "Último"
},
"oAria": {
"sSortAscending": ": Ordenar colunas de forma ascendente",
"sSortDescending": ": Ordenar colunas de forma descendente"
}
},
});
} else {
console.log('[INFO] studentsTable already loaded.');
}
} else if (checkUrl("competences")) {
console.log('[INFO] enginePage called at: competences.');
table = $('#competences-table');
if (table.length > 0) {
var t = table.dataTable({
responsive: true,
"order": [[ 1, "desc" ], [ 0, "desc" ]],
"columnDefs": [ { "targets": [2, 3], "orderable": false } ],
language: {
"sEmptyTable": "Nenhum registro encontrado",
"sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
"sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
"sInfoFiltered": "(Filtrados de _MAX_ registros)",
"sInfoPostFix": "",
"sInfoThousands": ".",
"sLengthMenu": "_MENU_ resultados por página",
"sLoadingRecords": "Carregando...",
"sProcessing": "Processando...",
"sZeroRecords": "Nenhum registro encontrado",
"sSearch": "Pesquisar ",
"oPaginate": {
"sNext": "Próximo",
"sPrevious": "Anterior",
"sFirst": "Primeiro",
"sLast": "Último"
},
"oAria": {
"sSortAscending": ": Ordenar colunas de forma ascendente",
"sSortDescending": ": Ordenar colunas de forma descendente"
}
},
});
} else {
console.log('[INFO] studentsTable already loaded.');
}
} else if (checkUrl("skills")) {
console.log('[INFO] enginePage called at: skills.');
table = $('#skills-table');
if (table.length > 0) {
var t = table.dataTable({
responsive: true,
"order": [[ 2, "desc" ], [ 1, "desc" ], [ 0, "asc" ]],
"columnDefs": [ { "targets": [3, 4], "orderable": false } ],
language: {
"sEmptyTable": "Nenhum registro encontrado",
"sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
"sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
"sInfoFiltered": "(Filtrados de _MAX_ registros)",
"sInfoPostFix": "",
"sInfoThousands": ".",
"sLengthMenu": "_MENU_ resultados por página",
"sLoadingRecords": "Carregando...",
"sProcessing": "Processando...",
"sZeroRecords": "Nenhum registro encontrado",
"sSearch": "Pesquisar ",
"oPaginate": {
"sNext": "Próximo",
"sPrevious": "Anterior",
"sFirst": "Primeiro",
"sLast": "Último"
},
"oAria": {
"sSortAscending": ": Ordenar colunas de forma ascendente",
"sSortDescending": ": Ordenar colunas de forma descendente"
}
},
});
} else {
console.log('[INFO] studentsTable already loaded.');
}
} else if (checkUrl("jobs")) {
console.log('[INFO] enginePage called at: jobs.');
table = $('#jobs-table');
if (table.length > 0) {
var t = table.dataTable({
responsive: true,
"order": [[ 0, "asc" ]],
"columnDefs": [ { "targets": [1, 2], "orderable": false } ],
language: {
"sEmptyTable": "Nenhum registro encontrado",
"sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
"sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
"sInfoFiltered": "(Filtrados de _MAX_ registros)",
"sInfoPostFix": "",
"sInfoThousands": ".",
"sLengthMenu": "_MENU_ resultados por página",
"sLoadingRecords": "Carregando...",
"sProcessing": "Processando...",
"sZeroRecords": "Nenhum registro encontrado",
"sSearch": "Pesquisar ",
"oPaginate": {
"sNext": "Próximo",
"sPrevious": "Anterior",
"sFirst": "Primeiro",
"sLast": "Último"
},
"oAria": {
"sSortAscending": ": Ordenar colunas de forma ascendente",
"sSortDescending": ": Ordenar colunas de forma descendente"
}
},
});
} else {
console.log('[INFO] studentsTable already loaded.');
}
} else if (checkUrl("grades")) {
console.log('[INFO] enginePage called at: grades.');
table = $('#grades-table');
if (table.length > 0) {
var t = table.dataTable({
responsive: true,
"order": [[ 0, "asc" ]],
"columnDefs": [ { "targets": [1, 2], "orderable": false } ],
language: {
"sEmptyTable": "Nenhum registro encontrado",
"sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
"sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
"sInfoFiltered": "(Filtrados de _MAX_ registros)",
"sInfoPostFix": "",
"sInfoThousands": ".",
"sLengthMenu": "_MENU_ resultados por página",
"sLoadingRecords": "Carregando...",
"sProcessing": "Processando...",
"sZeroRecords": "Nenhum registro encontrado",
"sSearch": "Pesquisar ",
"oPaginate": {
"sNext": "Próximo",
"sPrevious": "Anterior",
"sFirst": "Primeiro",
"sLast": "Último"
},
"oAria": {
"sSortAscending": ": Ordenar colunas de forma ascendente",
"sSortDescending": ": Ordenar colunas de forma descendente"
}
},
});
} else {
console.log('[INFO] studentsTable already loaded.');
}
} else if (checkUrl("normals")) {
console.log('[INFO] enginePage called at: normals.');
table = $('#normals-table');
if (table.length > 0) {
var t = table.dataTable({
responsive: true,
"order": [[ 0, "asc" ]],
"columnDefs": [ { "targets": [1, 2], "orderable": false } ],
language: {
"sEmptyTable": "Nenhum registro encontrado",
"sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
"sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
"sInfoFiltered": "(Filtrados de _MAX_ registros)",
"sInfoPostFix": "",
"sInfoThousands": ".",
"sLengthMenu": "_MENU_ resultados por página",
"sLoadingRecords": "Carregando...",
"sProcessing": "Processando...",
"sZeroRecords": "Nenhum registro encontrado",
"sSearch": "Pesquisar ",
"oPaginate": {
"sNext": "Próximo",
"sPrevious": "Anterior",
"sFirst": "Primeiro",
"sLast": "Último"
},
"oAria": {
"sSortAscending": ": Ordenar colunas de forma ascendente",
"sSortDescending": ": Ordenar colunas de forma descendente"
}
},
});
} else {
console.log('[INFO] normalsTable already loaded.');
}
} else if (checkUrl("subjects")) {
console.log('[INFO] enginePage called at: subjects.');
table = $('#subjects-table');
if (table.length > 0) {
var t = table.dataTable({
responsive: true,
"order": [[ 0, "asc" ]],
"columnDefs": [ { "targets": [1, 2], "orderable": false } ],
language: {
"sEmptyTable": "Nenhum registro encontrado",
"sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
"sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
"sInfoFiltered": "(Filtrados de _MAX_ registros)",
"sInfoPostFix": "",
"sInfoThousands": ".",
"sLengthMenu": "_MENU_ resultados por página",
"sLoadingRecords": "Carregando...",
"sProcessing": "Processando...",
"sZeroRecords": "Nenhum registro encontrado",
"sSearch": "Pesquisar ",
"oPaginate": {
"sNext": "Próximo",
"sPrevious": "Anterior",
"sFirst": "Primeiro",
"sLast": "Último"
},
"oAria": {
"sSortAscending": ": Ordenar colunas de forma ascendente",
"sSortDescending": ": Ordenar colunas de forma descendente"
}
},
});
} else {
console.log('[INFO] studentsTable already loaded.');
}
} else if (checkUrl("exams/new")) {
console.log('[INFO] enginePage called at: exam/new.');
var engineDatepickers = function() {
$('#page .input-group.date').datepicker({
todayBtn: "linked",
keyboardNavigation: false,
forceParse: false,
calendarWeeks: true,
autoclose: true,
format: 'dd/mm/yyyy',
});
}
var engineSelects = function() {
$('#page .chosen-select').chosen({width: 'inherit'});
}
engineDatepickers();
engineSelects();
$('#exam_dates').on('cocoon:after-insert', function() {
engineDatepickers();
});
$('#exam_questions').on('cocoon:after-insert', function() {
engineSelects();
});
$('.add-question').trigger('click');
} else if (checkUrl("(exams)/[0-9]+")) {
console.log('[INFO] enginePage called at: exams/[0-9]+.');
examTable = $('#exam-table');
if (examTable.length > 0) {
jQuery.extend( jQuery.fn.dataTableExt.oSort, {
"only-float-pre": function ( a ) {
result = parseFloat(a.match(/[0-9]*\.[0-9]*\%/g)[0].replace("%", ""));
return result;
},
"only-float-asc": function ( a, b ) {
return ((a < b) ? -1 : ((a > b) ? 1 : 0));
},
"only-float-desc": function ( a, b ) {
return ((a < b) ? 1 : ((a > b) ? -1 : 0));
}
});
targets = [3,]
for (i = 0; i < parseInt(examTable.attr('data-subjects')); i++) {
targets.push(3 + 1 + i);
}
var t = examTable.dataTable({
responsive: true,
"order": [[ 3, "desc" ],],
"aoColumnDefs": [
{ "sType": 'only-float', "asSorting": [ "desc", "asc"], "aTargets": targets, },
{ "orderable": false, "targets": [2], }
],
language: {
"sEmptyTable": "Nenhum registro encontrado",
"sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
"sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
"sInfoFiltered": "(Filtrados de _MAX_ registros)",
"sInfoPostFix": "",
"sInfoThousands": ".",
"sLengthMenu": "_MENU_ resultados por página",
"sLoadingRecords": "Carregando...",
"sProcessing": "Processando...",
"sZeroRecords": "Nenhum registro encontrado",
"sSearch": "Pesquisar ",
"oPaginate": {
"sNext": "Próximo",
"sPrevious": "Anterior",
"sFirst": "Primeiro",
"sLast": "Último"
},
"oAria": {
"sSortAscending": ": Ordenar colunas de forma ascendente",
"sSortDescending": ": Ordenar colunas de forma descendente"
}
},
});
} else {
console.log('[INFO] examTable already loaded.');
}
} else if (checkUrl("exams")) {
// console.log('[INFO] enginePage called at: exams.');
// examsTable = $('#exams-table');
// if (examsTable.length > 0) {
// var t = examsTable.dataTable({
// responsive: true,
// "columnDefs": [ { "targets": [2, 3, 4, 5, 6], "orderable": false } ],
// language: {
// "sEmptyTable": "Nenhum registro encontrado",
// "sInfo": "Mostrando de _START_ até _END_ de _TOTAL_ registros",
// "sInfoEmpty": "Mostrando 0 até 0 de 0 registros",
// "sInfoFiltered": "(Filtrados de _MAX_ registros)",
// "sInfoPostFix": "",
// "sInfoThousands": ".",
// "sLengthMenu": "_MENU_ resultados por página",
// "sLoadingRecords": "Carregando...",
// "sProcessing": "Processando...",
// "sZeroRecords": "Nenhum registro encontrado",
// "sSearch": "Pesquisar ",
// "oPaginate": {
// "sNext": "Próximo",
// "sPrevious": "Anterior",
// "sFirst": "Primeiro",
// "sLast": "Último"
// },
// "oAria": {
// "sSortAscending": ": Ordenar colunas de forma ascendente",
// "sSortDescending": ": Ordenar colunas de forma descendente"
// }
// },
// });
// } else {
// console.log('[INFO] examsTable already loaded.');
// }
} else if (checkUrl("(exams/)[0-9]+(/edit_questions)[a-zA-Z0-9\/\?\=\%\&\\+\.\%\-\_]*")) {
console.log('[INFO] enginePage called at: exams/[0-9]+/edit_questions.');
var engineSelects = function() {
$('#page .chosen-select').chosen({width: 'inherit'});
}
engineSelects();
$('#questions .question .knowledge-area-select').change(function() {
select = $(this);
question = select.closest('.question');
question.find('.knowledge-object-select option').prop('selected', false);
question.find('.skill-select option').prop('selected', false);
question.find('.chosen-container').remove();
question.find('.knowledge-object-select.chosen-select').chosen('destroy');
question.find('.skill-select.chosen-select').chosen('destroy');
question.find('.knowledge-object-select').addClass('hidden').removeClass('chosen-select');
question.find('.skill-select').addClass('hidden').removeClass('chosen-select');
question.find('.from-knowledge-area-' + select.val()).removeClass('hidden').addClass('chosen-select').chosen({width: 'inherit'});
});
} else if (checkUrl("(exams/)[0-9]+(/edit)[a-zA-Z0-9\/\?\=\%\&\\+\.\%\-\_]*")) {
console.log('[INFO] enginePage called at: exams/[0-9]+/edit.');
var engineDatepickers = function() {
$('#page .input-group.date').datepicker({
todayBtn: "linked",
keyboardNavigation: false,
forceParse: false,
calendarWeeks: true,
autoclose: true,
format: 'dd/mm/yyyy',
});
}
engineDatepickers();
$('#dates').on('cocoon:after-insert', function() {
engineDatepickers();
});
} else if (checkUrl("(exams/)[0-9\/]*(show_statistic_report)[a-zA-Z0-9\/\?\=\%\&\\+\.\%\-\_]*")) {
console.log('[INFO] enginePage called at: exams/[0-9]+/show_statistic_report.');
var resource1 = $('table#statistic-report-resource__1 tr').get().map(function(row) {
return $(row).find('td').get().map(function(cell) {
return $(cell).html();
});
});
var resource2 = $('table#statistic-report-resource__2 tr').get().map(function(row) {
return $(row).find('td').get().map(function(cell) {
return $(cell).html();
});
});
var resource2__categories = $('table#statistic-report-resource__2 td[data-cat]').get().map(function(cell) {
return $(cell).attr('data-cat');
});
console.log(resource2__categories)
graph1 = $("#statistic-report-graph1");
engineGraphs(graph1, resource1, "Acertos", ["0", "10", "20", "30", "40", "50", "60", "70", "80", "90", "100"], 'Notas', 'Porcentagem de Alunos', '%');
graph2 = $("#statistic-report-graph2");
engineGraphs(graph2, resource2, "Acertos por Questão", resource2__categories, 'Questões', 'Porcentam de Alunos', '%');
$('.nestable-list').nestable();
$('[data-action="collapse"]').trigger('click');
} else if (checkUrl("(exams/)[0-9]+(/new_answers)")){
console.log('[INFO] enginePage called at: exams/[0-9]+/new_answers.');
var newAnswersDropzone = new Dropzone("#new-answers-dropzone", {
paramName: "answers",
autoProcessQueue: false,
});
newAnswersDropzone.element.querySelector("button[type=submit]").addEventListener("click", function(e) {
e.preventDefault();
e.stopPropagation();
newAnswersDropzone.processQueue();
});
} else {
console.log('[INFO] enginePage called at generic page.');
if ($('table#dashboard-simulated-test-graph-resource').length > 0) {
var resource = $('table#dashboard-simulated-test-graph-resource tr').get().map(function(row) {
return $(row).find('td').get().map(function(cell) {
return $(cell).html();
});
});
categories = [];
for (i = 2; i < resource.length; ++i) {
categories.push(resource[i][0]);
}
data = [];
for (j = 1; j < resource[0].length; ++j) {
data[j-1] = {};
data[j-1]["data"] = [];
data[j-1]["name"] = resource[0][j];
data[j-1]["color"] = resource[1][j];
for (k = 2; k < resource.length; ++k) {
data[j-1]["data"].push(parseFloat(resource[k][j]));
}
}
$('#dashboard-simulated-test-graph').highcharts({
chart: {
type: 'column',
height: 220,
},
title: { text: ' ' },
legend: {
layout: 'horizontal',
align: 'center',
verticalAlign: 'top',
},
credits: false,
xAxis: {
categories: categories,
crosshair: true
},
yAxis: {
min: 0,
max: 100,
tickInterval: 20,
title: {
text: 'Porcentagem de acertos'
}
},
tooltip: {
headerFormat: '<span style="font-size:10px">{point.key}</span><table>',
pointFormat: '<tr><td style="color:{series.color};padding:0">{series.name}: </td>' +
'<td style="padding:0"><b>{point.y:.1f} %</b></td></tr>',
footerFormat: '</table>',
shared: true,
useHTML: true
},
plotOptions: {
column: {
pointPadding: 0.2,
borderWidth: 0
}
},
series: data
});
}
if ($('#flot-chart1').length > 0) {
var d1 = [[1262304000000, 6], [1264982400000, 3057], [1267401600000, 20434], [1270080000000, 31982], [1272672000000, 26602], [1275350400000, 27826], [1277942400000, 24302], [1280620800000, 24237], [1283299200000, 21004], [1285891200000, 12144], [1288569600000, 10577], [1291161600000, 10295]];
var d2 = [[1262304000000, 5], [1264982400000, 200], [1267401600000, 1605], [1270080000000, 6129], [1272672000000, 11643], [1275350400000, 19055], [1277942400000, 30062], [1280620800000, 39197], [1283299200000, 37000], [1285891200000, 27000], [1288569600000, 21000], [1291161600000, 17000]];
var data1 = [
{ label: "Data 1", data: d1, color: '#17a084'},
{ label: "Data 2", data: d2, color: '#127e68' }
];
$.plot($("#flot-chart1"), data1, {
xaxis: {
tickDecimals: 0
},
series: {
lines: {
show: true,
fill: true,
fillColor: {
colors: [{
opacity: 1
}, {
opacity: 1
}]
},
},
points: {
width: 0.1,
show: false
},
},
grid: {
show: false,
borderWidth: 0
},
legend: {
show: false,
}
});
}
}
}
$(document).ready(function() {
// pageMechanic();
}) |
'use strict';
import angular from 'angular';
import uirouter from 'angular-ui-router';
import routes from './message.routes';
import MessageCtrl from './message.ctrl';
import database from '../../modules/database';
import pagetitle from '../../modules/page-title.js';
var messagePage = angular.module('messagePage', [uirouter, database, pagetitle])
.config(routes)
.controller('MessageCtrl', MessageCtrl)
.name;
export default messagePage; |
import { join } from 'path'
import { readFile } from 'fs'
import { promisify } from 'bluebird'
const readFileAsync = promisify(readFile),
breakingOptions = ['flags', 'make', 'configure']
function getOptionsComment (options) {
const optionMarkers = breakingOptions.map(key => {
return `${ key }: ${ JSON.stringify(options[key]) }`
})
return '/** xbin-options ' + optionMarkers.join(', ').replace(/\*\//g, '*\/') + ' **/'
}
export async function compile (compiler, next) {
if (compiler.download) {
return next()
}
const thirdPartyMain = await compiler.readFileAsync('lib/_third_party_main.js')
let thirdPartyMainContent = await readFileAsync(join(__dirname, '_third_party_main.js'))
if (compiler.name) {
thirdPartyMainContent = thirdPartyMainContent.toString().replace('xbin-output.js', compiler.name)
}
thirdPartyMain.contents = getOptionsComment(compiler) + thirdPartyMainContent
await next()
return compiler.buildAsync()
}
|
'use strict';
// Controller for viewing info of a location on the map
angular.module('locations').controller('LocationMapController', ['$scope', 'Authentication', 'Locations', 'editable', 'location',
function ($scope, Authentication, Locations, editable, location) {
$scope.authentication = Authentication;
if (!location) {
//TODO: prevent from going on
}
//MAP PARAMETERS
$scope.defaults = {
scrollWheelZoom: true
};
// map center
$scope.center = {};
// one marker only
$scope.markers = {
marker : {
lat: 0,
lng: 0,
focus: true,
draggable: editable
}
};
// apply input location
updateMapCenter(location);
updateMarkerPosition(location);
// helper functions
function updateMapCenter(location) {
$scope.center = {
lat: location.lat,
lng: location.lng,
zoom: 15
};
}
function updateMarkerPosition(location) {
$scope.markers.marker.lat = location.lat;
$scope.markers.marker.lng = location.lng;
}
}
]);
|
class softwaredistribution_vistawebcontrol {
constructor() {
// uint UserLocale () {get}
this.UserLocale = undefined;
}
// OptInRestriction CheckOptInRestrictions (OptInRestriction)
CheckOptInRestrictions(OptInRestriction) {
}
// void ElevatedOptInToUpdateService (string, Variant, _FILETIME, uint,...
ElevatedOptInToUpdateService() {
}
// AutomaticUpdatesNotificationLevelSetting GetAutomaticUpdatesNotifica...
GetAutomaticUpdatesNotificationLevel() {
}
// AutomaticUpdatesReadOnly GetAutomaticUpdatesReadOnly ()
GetAutomaticUpdatesReadOnly() {
}
// OptInErrorContext GetErrorContext ()
GetErrorContext() {
}
// bool GetFeaturedUpdatesEnabled ()
GetFeaturedUpdatesEnabled() {
}
// AutomaticUpdatesReadOnly GetFeaturedUpdatesEnabledReadOnly ()
GetFeaturedUpdatesEnabledReadOnly() {
}
// bool GetIncludeRecommendedUpdates ()
GetIncludeRecommendedUpdates() {
}
// AutomaticUpdatesReadOnly GetIncludeRecommendedUpdatesReadOnly ()
GetIncludeRecommendedUpdatesReadOnly() {
}
// bool GetNonAdministratorsElevated ()
GetNonAdministratorsElevated() {
}
// AutomaticUpdatesReadOnly GetNonAdministratorsElevatedReadOnly ()
GetNonAdministratorsElevatedReadOnly() {
}
// Variant GetOSVersionInfo (OSVersionField, int)
GetOSVersionInfo(OSVersionField, int) {
}
// bool GetUpdateServiceOptInStatus (string)
GetUpdateServiceOptInStatus(string) {
}
// void LaunchWindowsUpdateApplication ()
LaunchWindowsUpdateApplication() {
}
// void OptInToUpdateService (string, uint)
OptInToUpdateService(string, uint) {
}
}
module.exports = softwaredistribution_vistawebcontrol;
|
var express = require('express'),
router = express.Router(),
bodyParser = require('body-parser'),
expJwt = require('express-jwt'),
expressValidator = require('express-validator'),
util = require('util'),
config = require('../config'),
logging = require('../logging'),
logger = logging.createLogger('admin-api');
var reportsDir = config.get('GIT_REPORTS_DIR'),
gitPushCmd = config.get('GIT_PUSH_CMD') || 'git push origin master',
directoryStore = require('./directoryStore')(reportsDir, gitPushCmd);
module.exports = function(signingSecret) {
router.use(bodyParser.urlencoded({ extended: false }));
router.use(bodyParser.json());
router.use(expressValidator({
customValidators: {
isValidFolderName: function(value) {
return /^(([/a-zA-Z0-9_]|\s)+)$/.test(value);
},
isValidFileName: function(value) {
return /^(([a-zA-Z0-9_.]|\s)+)$/.test(value);
}
}
}));
router.get('/', function(req, res) {
res.send('Hotrod reporting API. Nothing to see here');
});
// Require valid JWT token for all routes below here
router.use(expJwt({ secret: signingSecret }));
router.get('/reports', function(req, res, next) {
req.checkQuery('folder', 'Invalid folder param').len(1, 100).isValidFolderName();
req.checkQuery('folder', 'Missing required folder param').notEmpty();
req.checkQuery('file', 'Invalid file param').optional().isValidFileName();
var errors = req.validationErrors(true);
if (errors) {
return res.status(400).json(errors);
}
var file = req.query.file;
var folder = req.query.folder;
if (file) {
directoryStore.getFile(folder, file, function(err, report) {
if (err) {
if (err.code === 'ENOENT') {
return res.status(404).send(util.format('File "%s/%s" does not exist', folder, file));
}
return next(err);
}
res.send(report);
});
} else {
// TODO: recursively build up tree structure. For now just returning files in first folder found
var folderTree = {
directories: [],
files: []
};
directoryStore.getFiles(folder, function(err, files) {
if (err) {
if (err.code === 'ENOENT') {
return res.status(404).send(util.format('Folder "%s" does not exist', folder));
}
return next(err);
}
folderTree.files = files;
res.json(folderTree);
});
}
});
router.post('/reports', function(req, res, next) {
req.checkBody('folder', 'Invalid folder param').len(1, 100).isValidFolderName();
req.checkBody('folder', 'Missing required folder param').notEmpty();
req.checkBody('file', 'Invalid file param').isValidFileName();
req.checkBody('file', 'Missing required file param').notEmpty();
req.checkBody('content', 'Must provide the file content').notEmpty();
req.checkBody('message', 'Must provide a commit message with valid length').len(1, 500);
req.checkBody('message', 'Must provide a commit message').notEmpty();
var errors = req.validationErrors(true);
if (errors) {
return res.status(400).json(errors);
}
var file = req.body.file;
var folder = req.body.folder;
var content = req.body.content;
var message = req.body.message;
// TODO: read existing file content and see if it's changed (avoid error on commit)
// directoryStore.getFile
directoryStore.commit(folder, file, content, message, function(err) {
if (err) {
return next(err);
}
res.status(200).send('Committed changes');
});
});
router.use(function(err, req, res, next) {
if (err.name === 'UnauthorizedError') {
res.status(401).send('invalid token');
} else {
next(err);
}
});
return router;
};
|
/* eslint no-console: 0 */
/* eslint no-path-concat: 0 */
var fs = require('fs-extra')
var version = process.env.npm_package_version
var name = process.env.npm_package_name
const filterFunc = (src, dest) => {
// Dont copy .map files - we dont want this in our production environment
if (src.endsWith('.map')) {
return false
} else {
return true
}
}
if (process.argv.length !== 3) {
console.log('Usage: ' + __filename + ' <content_server_directory>')
process.exit(-1)
}
const contentServer = process.argv.slice(2)[0]
var dest = contentServer + '/' + name + '/' + version
console.log('dest = ' + dest)
fs.mkdirsSync(dest)
fs.copy('./dist', dest, { filter: filterFunc }, function (err) {
if (err) return console.error(err)
console.log('Successfully copied ./dist folder to ' + dest)
})
|
require('../../app/app.js');
const angular = require('angular');
require('angular-mocks');
describe('score service tests', () => {
var ScoreService;
beforeEach(angular.mock.module('app'));
beforeEach(angular.mock.inject(function(_ScoreService_) {
ScoreService = _ScoreService_;
}));
it('should be a service', () => {
expect(typeof ScoreService).toBe('object');
expect(typeof ScoreService.createScore).toBe('function');
expect(typeof ScoreService.getScores).toBe('function');
expect(typeof ScoreService.getScore).toBe('function');
expect(typeof ScoreService.getScoreId).toBe('function');
expect(typeof ScoreService.updateScore).toBe('function');
expect(typeof ScoreService.resetScore).toBe('function');
});
describe('score REST tests', () => {
var $httpBackend;
beforeEach(angular.mock.inject(function(_$httpBackend_) {
$httpBackend = _$httpBackend_;
}));
afterEach(() => {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
it('should create a new score', () => {
$httpBackend.expectPOST('http://localhost:3000/api/users/userId/scores')
.respond(200, {data: { __v: 0,
userId: 'userId',
category: 'JavaScript',
difficulty: 'Easy',
totalQuestions: 10,
completedQuestions: 10,
questionsCorrect: 7,
questionsWrong: 3,
_id: '57291b9b611f7e8e61ea5983' }});
ScoreService.createScore({
userId: 'userId',
category: 'JavaScript',
difficulty: 'Easy',
totalQuestions: 10,
completedQuestions: 10,
questionsCorrect: 7,
questionsWrong: 3});
$httpBackend.flush();
});
it('should get all scores', () => {
$httpBackend.expectGET('http://localhost:3000/api/users/userId/scores')
.respond(200, {data: [ { _id: '57290f03f6a07b025e139afe',
userId: 'userId',
category: 'JavaScript',
difficulty: 'Easy',
totalQuestions: 10,
completedQuestions: 10,
questionsCorrect: 7,
questionsWrong: 3,
__v: 0 }]})
ScoreService.getScores('userId');
$httpBackend.flush();
});
it('should get score id', () => {
$httpBackend.expectGET('http://localhost:3000/api/users/userId/scores?category=JavaScript&difficulty=Easy')
.respond(200, {"message": "Returned ScoreId", "data": {"scoreId": "57292656a257bb6665801e22"}})
ScoreService.getScoreId({userId: 'userId', category: 'JavaScript', difficulty: 'Easy'});
$httpBackend.flush();
});
it('should get a score', () => {
$httpBackend.expectGET('http://localhost:3000/api/users/userId/scores/scoreId')
.respond(200, {data: { _id: 'scoreId',
userId: 'userId',
category: 'JavaScript',
difficulty: 'Easy',
totalQuestions: 10,
completedQuestions: 10,
questionsCorrect: 7,
questionsWrong: 3,
__v: 0 }})
ScoreService.getScore({userId: 'userId', scoreId: 'scoreId'});
$httpBackend.flush();
});
it('should update a score', () => {
$httpBackend.expectPUT('http://localhost:3000/api/users/userId/scores/scoreId')
.respond(200, {message: 'Updated Score'});
ScoreService.updateScore({userId: 'userId', scoreId: 'scoreId', questionsRight: 8, questionsWrong: 2}, 'scoreId');
$httpBackend.flush();
});
it('should remove a score', () => {
$httpBackend.expectDELETE('http://localhost:3000/api/users/userId/scores/scoreId')
.respond(200, {message: 'Deleted Score'});
ScoreService.resetScore({userId: 'userId', scoreId: 'scoreId'});
$httpBackend.flush();
});
});
});
|
"use strict";
var strictify = require('../../lib').helpers.strictify;
describe("<Strictify helper>", function() {
it("should replace spaces by ANDs", function() {
strictify("Jack Bob")
.should.be.exactly("Jack AND Bob");
strictify("Jack Bob Bobby")
.should.be.exactly("Jack AND Bob AND Bobby");
});
it("should ignore quotes", function() {
strictify('"Jack Bob"')
.should.be.exactly('"Jack Bob"');
strictify('"Jack Bob" Bobby')
.should.be.exactly('"Jack Bob" AND Bobby');
});
});
|
version https://git-lfs.github.com/spec/v1
oid sha256:7aa80b43b95b74bc318d46be11b2ad2ab87b630de06ed7d7bfa232042ee1e7cb
size 42434
|
/**
* Subject: maintain list of observers
* Observer: provides a update interface for objects and notification
* ConcreteSubject: Broadcast notification;
* ConcteteObserver: stores a reference to the concreteSubject
*/
// subject prototype
function ObserverList () {
this.ObserverList = [];
}
ObserverList.prototype.add = function ( obj ) {
return this.ObserverList.push ( obj );
};
ObserverList.prototype.count = function () {
return this.ObserverList.length;
};
ObserverList.prototype.get = function ( index ) {
if ( index > -1 && index < this.ObserverList.length ) {
return this.ObserverList[ index ];
}
};
ObserverList.prototype.indexOf = function ( obj, startIndex ) {
var i = startIndex;
while ( i < this.ObserverList.length ) {
if ( this.observerList[i] == obj ) {
return i;
}
i++;
}
return -1;
};
ObserverList.prototype.removeAt = function ( index ) {
this.observerList.splice( index, 1 );
};
// subject
function Subject () {
this.observers = new ObserverList();
}
Subject.prototype.addObserver = function ( observer ) {
this.observers.add( observer );
}
Subject.prototype.removeObserver = function ( observer ) {
this.observers.removeAt( this.observers.indexOf( observer, 0 ) );
};
Subject.prototype.notify = function ( context ) {
var observerCount = this.observers.count();
for (var i = 0; i < observerCount; i++) {
this.observers.get(i).update( context );
}
};
// observer
function Observer () {
this.update = function () {
// ...
};
}
// Extend an object with an extension
function extend( obj, extension ) {
for (var key in extension) {
obj[key] = extension[key];
}
}
// references to DOM elements
var controlChecbox = document.getElementById("mainCheckbox"),
addBtn = document.getElementById("addNewObserver"),
container = document.getElementById("observersContainer");
/**
* Concrete Subject
*/
extend( controlChecbox, new Subject() );
controlChecbox.onclick = function () {
controlChecbox.notify( controlChecbox.checked );
};
addBtn.onclick = addNewObserver;
/**
* Concrete Observer
*/
function addNewObserver() {
// create new checkbox
var check = document.createElement("input");
check.type = "checkbox";
extend( check, new Observer() );
check.update = function ( value ) {
this.checked = value;
};
// add new observer to list
controlChecbox.addObserver( check );
container.appendChild( check );
};
|
/**
* @fileoverview added by tsickle
* @suppress {checkTypes} checked by tsc
*/
goog.module('test_files.jsdoc_types.untyped.jsdoc_types');var module = module || {id: 'test_files/jsdoc_types.untyped/jsdoc_types.js'};/**
* This test tests importing a type across module boundaries,
* ensuring that the type gets the proper name in JSDoc comments.
*/
var module1 = goog.require('test_files.jsdoc_types.untyped.module1');
var module2_1 = goog.require('test_files.jsdoc_types.untyped.module2');
var module2_2 = module2_1;
var module2_3 = module2_1;
var default_1 = goog.require('test_files.jsdoc_types.untyped.default');
// Check that imported types get the proper names in JSDoc.
let /** @type {?} */ useNamespacedClass = new module1.Class();
let /** @type {?} */ useNamespacedClassAsType;
let /** @type {?} */ useNamespacedType;
// Should be references to the symbols in module2, perhaps via locals.
let /** @type {?} */ useLocalClass = new module2_1.ClassOne();
let /** @type {?} */ useLocalClassRenamed = new module2_2.ClassOne();
let /** @type {?} */ useLocalClassRenamedTwo = new module2_3.ClassTwo();
let /** @type {?} */ useLocalClassAsTypeRenamed;
let /** @type {?} */ useLocalInterface;
let /** @type {?} */ useClassWithParams;
// This is purely a value; it doesn't need renaming.
let /** @type {?} */ useLocalValue = module2_1.value;
// Check a default import.
let /** @type {?} */ useDefaultClass = new default_1.default();
let /** @type {?} */ useDefaultClassAsType;
// NeverTyped should be {?}, even in typed mode.
let /** @type {?} */ useNeverTyped;
let /** @type {?} */ useNeverTyped2;
|
export default async (ctx, next) => {
// api server through koa-router
if (ctx.path.match(/^\/api/)) {
return await require('./api').routes()(ctx, next)
}
// others react-router to render
await require('./render')(ctx, next)
}
|
export var customGeometry = {
main:function(){
var _self = this;
this.group = new THREE.Group();
this.geometry = new THREE.PlaneGeometry(100, 100 );
this.material = new THREE.MeshBasicMaterial( { map:this.textures } );
this.mesh = new THREE.Mesh( this.geometry,this.material );
var a= new THREE.Geometry();
a.vertices.push(
new THREE.Vector3( 0,0,0 ),
new THREE.Vector3( 150,0,0 ),
new THREE.Vector3( 150,150,0 ),
new THREE.Vector3( 115,55,0 )
);
a.faces.push(new THREE.Face3( 0,1,3 )
, new THREE.Face3( 1,2,3)
);
// a.colors.push(new THREE.Color( 0xff0000 ),new THREE.Color( 0x00ff00 ),new THREE.Color(0x0000ff),new THREE.Color(0xffffff)) ;
let colors=[] ;
colors.push(new THREE.Color( 0xff0000 ),new THREE.Color( 0x00ff00 ),new THREE.Color(0x0000ff),new THREE.Color(0xffffff)) ;
for(let j=0; j < a.faces.length ; j++ ){
// for(let t = 0 ;t<3;t++){
// a.faces[j].vertexColors.push(a.colors[t])
// }
a.faces[j].color = colors[j]
}
var b = new THREE.MeshBasicMaterial( { vertexColors:true }); // vertexColors 表示去face 里面的成员颜色 //color表示取 统一颜色
var r = new THREE.MeshBasicMaterial( {map:this.textures})
var tt =[b,r]
// var c = new THREE.Mesh(a,b);
var c = new THREE.Mesh(a,b)
c.geometry.center();
this.group.add(c);
var d = c.clone();
this.group.add(d)
c.position.set(-75,0,0);
d.position.set(75,0,0)
c.geometry.computeBoundingBox() ;
c.geometry.computeBoundingSphere() ;
this.mesh.geometry.computeBoundingSphere() ;
this.scene.add(this.group);
this.group.position.set(150,150,0)
var k = c.clone();
this.scene.add(k)
k.position.set(0,0,0)
var w = c.clone()
this.scene.add(w);
w.position.set(75,0,0)
var temp = this.group.children[0]
console.log(111,temp.geometry.boundingSphere.applyMatrix4(temp.matrixWorld) ,temp.matrixWorld);
}
}
|
(function () {
'use strict';
angular
.module('rentler.core')
.directive('rValidateClass', ValidateClassDirective);
ValidateClassDirective.$inject = ['Validation'];
function ValidateClassDirective(Validation) {
var directive = {
restrict: 'A',
require: ['^form', '^rValidator', '?^ngRepeat'],
link: link
};
return directive;
function link(scope, element, attrs, ctrls) {
// Get controllers
var formCtrl = ctrls[0],
rValidatorCtrl = ctrls[1],
ngRepeatCtrl = ctrls[2];
// No validation
if (!rValidatorCtrl) return;
// Get validator
var validator = _.get(rValidatorCtrl, 'validator');
// Initialize field name
var fieldName = '';
var fieldNameOptions = {
attrFieldName: attrs.rValidateClass,
ngRepeatCtrl: ngRepeatCtrl,
validator: validator
};
assignFieldName();
// Watch field name for collections
if (ngRepeatCtrl) ngRepeatCtrl.listeners.push(assignFieldName);
function assignFieldName() {
fieldName = Validation.getFieldName(fieldNameOptions);
}
// Verify field is in schema
var schemaFieldName = fieldName.replace(/\[\d+\]/g, '.collection');
if (!_.has(validator.schema, schemaFieldName)) return;
// Add to validation listeners
rValidatorCtrl.listeners.push(listener);
function listener() {
// Not submitted no validation
if (!formCtrl.$submitted || !_.has(validator.errors, fieldName)) return;
// Get errors length
var length = validator.errors[fieldName].length;
// Add approriate classes
if (length === 0) element.removeClass(Validation.getClasses().error).addClass(Validation.getClasses().success);
else if (length > 0) element.addClass(Validation.getClasses().error).removeClass(Validation.getClasses().success);
}
// Cleanup
scope.$on('$destroy', function () {
_.pull(rValidatorCtrl.listeners, listener);
if (ngRepeatCtrl) _.pull(ngRepeatCtrl.listeners, assignFieldName);
});
}
}
})(); |
import React from 'react';
import PropTypes from 'prop-types';
const Undo = (props) => {
const color = props.color == 'inherit' ? undefined : props.color;
const aria = props.title ? 'svg-undo-title' : '' +
props.title && props.description ? ' ' : '' +
props.description ? 'svg-undo-desc' : '';
return (
<svg width={props.width} height={props.height} viewBox='0 0 24 24'
xmlns='http://www.w3.org/2000/svg' role='img'
aria-labelledby={aria}
>
{!props.title ? null :
<title id='svg-undo-title'>{props.title}</title>
}
{!props.description ? null :
<desc id='svg-undo-desc'>{props.description}</desc>
}
<path fill={color} d="M12.5 8c-2.65 0-5.05.99-6.9 2.6L2 7v9h9l-3.62-3.62c1.39-1.16 3.16-1.88 5.12-1.88 3.54 0 6.55 2.31 7.6 5.5l2.37-.78C21.08 11.03 17.15 8 12.5 8z"/>
</svg>
);
};
Undo.defaultProps = {
color: 'inherit',
width: undefined,
height: undefined,
title: '',
description: ''
};
Undo.propTypes = {
color: PropTypes.string,
width: PropTypes.string,
height: PropTypes.string,
title: PropTypes.string,
description: PropTypes.string
};
export default Undo;
|
/*! jQuery UI - v1.9.2 - 2013-12-13
* http://jqueryui.com
* Includes: jquery.ui.widget.js
* Copyright 2013 jQuery Foundation and other contributors; Licensed MIT */
(function( $, undefined ) {
var uuid = 0,
slice = Array.prototype.slice,
_cleanData = $.cleanData;
$.cleanData = function( elems ) {
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
try {
$( elem ).triggerHandler( "remove" );
// http://bugs.jquery.com/ticket/8235
} catch( e ) {}
}
_cleanData( elems );
};
$.widget = function( name, base, prototype ) {
var fullName, existingConstructor, constructor, basePrototype,
namespace = name.split( "." )[ 0 ];
name = name.split( "." )[ 1 ];
fullName = namespace + "-" + name;
if ( !prototype ) {
prototype = base;
base = $.Widget;
}
// create selector for plugin
$.expr[ ":" ][ fullName.toLowerCase() ] = function( elem ) {
return !!$.data( elem, fullName );
};
$[ namespace ] = $[ namespace ] || {};
existingConstructor = $[ namespace ][ name ];
constructor = $[ namespace ][ name ] = function( options, element ) {
// allow instantiation without "new" keyword
if ( !this._createWidget ) {
return new constructor( options, element );
}
// allow instantiation without initializing for simple inheritance
// must use "new" keyword (the code above always passes args)
if ( arguments.length ) {
this._createWidget( options, element );
}
};
// extend with the existing constructor to carry over any static properties
$.extend( constructor, existingConstructor, {
version: prototype.version,
// copy the object used to create the prototype in case we need to
// redefine the widget later
_proto: $.extend( {}, prototype ),
// track widgets that inherit from this widget in case this widget is
// redefined after a widget inherits from it
_childConstructors: []
});
basePrototype = new base();
// we need to make the options hash a property directly on the new instance
// otherwise we'll modify the options hash on the prototype that we're
// inheriting from
basePrototype.options = $.widget.extend( {}, basePrototype.options );
$.each( prototype, function( prop, value ) {
if ( $.isFunction( value ) ) {
prototype[ prop ] = (function() {
var _super = function() {
return base.prototype[ prop ].apply( this, arguments );
},
_superApply = function( args ) {
return base.prototype[ prop ].apply( this, args );
};
return function() {
var __super = this._super,
__superApply = this._superApply,
returnValue;
this._super = _super;
this._superApply = _superApply;
returnValue = value.apply( this, arguments );
this._super = __super;
this._superApply = __superApply;
return returnValue;
};
})();
}
});
constructor.prototype = $.widget.extend( basePrototype, {
// TODO: remove support for widgetEventPrefix
// always use the name + a colon as the prefix, e.g., draggable:start
// don't prefix for widgets that aren't DOM-based
widgetEventPrefix: existingConstructor ? basePrototype.widgetEventPrefix : name
}, prototype, {
constructor: constructor,
namespace: namespace,
widgetName: name,
// TODO remove widgetBaseClass, see #8155
widgetBaseClass: fullName,
widgetFullName: fullName
});
// If this widget is being redefined then we need to find all widgets that
// are inheriting from it and redefine all of them so that they inherit from
// the new version of this widget. We're essentially trying to replace one
// level in the prototype chain.
if ( existingConstructor ) {
$.each( existingConstructor._childConstructors, function( i, child ) {
var childPrototype = child.prototype;
// redefine the child widget using the same prototype that was
// originally used, but inherit from the new version of the base
$.widget( childPrototype.namespace + "." + childPrototype.widgetName, constructor, child._proto );
});
// remove the list of existing child constructors from the old constructor
// so the old child constructors can be garbage collected
delete existingConstructor._childConstructors;
} else {
base._childConstructors.push( constructor );
}
$.widget.bridge( name, constructor );
};
$.widget.extend = function( target ) {
var input = slice.call( arguments, 1 ),
inputIndex = 0,
inputLength = input.length,
key,
value;
for ( ; inputIndex < inputLength; inputIndex++ ) {
for ( key in input[ inputIndex ] ) {
value = input[ inputIndex ][ key ];
if ( input[ inputIndex ].hasOwnProperty( key ) && value !== undefined ) {
// Clone objects
if ( $.isPlainObject( value ) ) {
target[ key ] = $.isPlainObject( target[ key ] ) ?
$.widget.extend( {}, target[ key ], value ) :
// Don't extend strings, arrays, etc. with objects
$.widget.extend( {}, value );
// Copy everything else by reference
} else {
target[ key ] = value;
}
}
}
}
return target;
};
$.widget.bridge = function( name, object ) {
var fullName = object.prototype.widgetFullName || name;
$.fn[ name ] = function( options ) {
var isMethodCall = typeof options === "string",
args = slice.call( arguments, 1 ),
returnValue = this;
// allow multiple hashes to be passed on init
options = !isMethodCall && args.length ?
$.widget.extend.apply( null, [ options ].concat(args) ) :
options;
if ( isMethodCall ) {
this.each(function() {
var methodValue,
instance = $.data( this, fullName );
if ( !instance ) {
return $.error( "cannot call methods on " + name + " prior to initialization; " +
"attempted to call method '" + options + "'" );
}
if ( !$.isFunction( instance[options] ) || options.charAt( 0 ) === "_" ) {
return $.error( "no such method '" + options + "' for " + name + " widget instance" );
}
methodValue = instance[ options ].apply( instance, args );
if ( methodValue !== instance && methodValue !== undefined ) {
returnValue = methodValue && methodValue.jquery ?
returnValue.pushStack( methodValue.get() ) :
methodValue;
return false;
}
});
} else {
this.each(function() {
var instance = $.data( this, fullName );
if ( instance ) {
instance.option( options || {} )._init();
} else {
$.data( this, fullName, new object( options, this ) );
}
});
}
return returnValue;
};
};
$.Widget = function( /* options, element */ ) {};
$.Widget._childConstructors = [];
$.Widget.prototype = {
widgetName: "widget",
widgetEventPrefix: "",
defaultElement: "<div>",
options: {
disabled: false,
// callbacks
create: null
},
_createWidget: function( options, element ) {
element = $( element || this.defaultElement || this )[ 0 ];
this.element = $( element );
this.uuid = uuid++;
this.eventNamespace = "." + this.widgetName + this.uuid;
this.options = $.widget.extend( {},
this.options,
this._getCreateOptions(),
options );
this.bindings = $();
this.hoverable = $();
this.focusable = $();
if ( element !== this ) {
// 1.9 BC for #7810
// TODO remove dual storage
$.data( element, this.widgetName, this );
$.data( element, this.widgetFullName, this );
this._on( true, this.element, {
remove: function( event ) {
if ( event.target === element ) {
this.destroy();
}
}
});
this.document = $( element.style ?
// element within the document
element.ownerDocument :
// element is window or document
element.document || element );
this.window = $( this.document[0].defaultView || this.document[0].parentWindow );
}
this._create();
this._trigger( "create", null, this._getCreateEventData() );
this._init();
},
_getCreateOptions: $.noop,
_getCreateEventData: $.noop,
_create: $.noop,
_init: $.noop,
destroy: function() {
this._destroy();
// we can probably remove the unbind calls in 2.0
// all event bindings should go through this._on()
this.element
.unbind( this.eventNamespace )
// 1.9 BC for #7810
// TODO remove dual storage
.removeData( this.widgetName )
.removeData( this.widgetFullName )
// support: jquery <1.6.3
// http://bugs.jquery.com/ticket/9413
.removeData( $.camelCase( this.widgetFullName ) );
this.widget()
.unbind( this.eventNamespace )
.removeAttr( "aria-disabled" )
.removeClass(
this.widgetFullName + "-disabled " +
"ui-state-disabled" );
// clean up events and states
this.bindings.unbind( this.eventNamespace );
this.hoverable.removeClass( "ui-state-hover" );
this.focusable.removeClass( "ui-state-focus" );
},
_destroy: $.noop,
widget: function() {
return this.element;
},
option: function( key, value ) {
var options = key,
parts,
curOption,
i;
if ( arguments.length === 0 ) {
// don't return a reference to the internal hash
return $.widget.extend( {}, this.options );
}
if ( typeof key === "string" ) {
// handle nested keys, e.g., "foo.bar" => { foo: { bar: ___ } }
options = {};
parts = key.split( "." );
key = parts.shift();
if ( parts.length ) {
curOption = options[ key ] = $.widget.extend( {}, this.options[ key ] );
for ( i = 0; i < parts.length - 1; i++ ) {
curOption[ parts[ i ] ] = curOption[ parts[ i ] ] || {};
curOption = curOption[ parts[ i ] ];
}
key = parts.pop();
if ( value === undefined ) {
return curOption[ key ] === undefined ? null : curOption[ key ];
}
curOption[ key ] = value;
} else {
if ( value === undefined ) {
return this.options[ key ] === undefined ? null : this.options[ key ];
}
options[ key ] = value;
}
}
this._setOptions( options );
return this;
},
_setOptions: function( options ) {
var key;
for ( key in options ) {
this._setOption( key, options[ key ] );
}
return this;
},
_setOption: function( key, value ) {
this.options[ key ] = value;
if ( key === "disabled" ) {
this.widget()
.toggleClass( this.widgetFullName + "-disabled ui-state-disabled", !!value )
.attr( "aria-disabled", value );
this.hoverable.removeClass( "ui-state-hover" );
this.focusable.removeClass( "ui-state-focus" );
}
return this;
},
enable: function() {
return this._setOption( "disabled", false );
},
disable: function() {
return this._setOption( "disabled", true );
},
_on: function( suppressDisabledCheck, element, handlers ) {
var delegateElement,
instance = this;
// no suppressDisabledCheck flag, shuffle arguments
if ( typeof suppressDisabledCheck !== "boolean" ) {
handlers = element;
element = suppressDisabledCheck;
suppressDisabledCheck = false;
}
// no element argument, shuffle and use this.element
if ( !handlers ) {
handlers = element;
element = this.element;
delegateElement = this.widget();
} else {
// accept selectors, DOM elements
element = delegateElement = $( element );
this.bindings = this.bindings.add( element );
}
$.each( handlers, function( event, handler ) {
function handlerProxy() {
// allow widgets to customize the disabled handling
// - disabled as an array instead of boolean
// - disabled class as method for disabling individual parts
if ( !suppressDisabledCheck &&
( instance.options.disabled === true ||
$( this ).hasClass( "ui-state-disabled" ) ) ) {
return;
}
return ( typeof handler === "string" ? instance[ handler ] : handler )
.apply( instance, arguments );
}
// copy the guid so direct unbinding works
if ( typeof handler !== "string" ) {
handlerProxy.guid = handler.guid =
handler.guid || handlerProxy.guid || $.guid++;
}
var match = event.match( /^(\w+)\s*(.*)$/ ),
eventName = match[1] + instance.eventNamespace,
selector = match[2];
if ( selector ) {
delegateElement.delegate( selector, eventName, handlerProxy );
} else {
element.bind( eventName, handlerProxy );
}
});
},
_off: function( element, eventName ) {
eventName = (eventName || "").split( " " ).join( this.eventNamespace + " " ) + this.eventNamespace;
element.unbind( eventName ).undelegate( eventName );
},
_delay: function( handler, delay ) {
function handlerProxy() {
return ( typeof handler === "string" ? instance[ handler ] : handler )
.apply( instance, arguments );
}
var instance = this;
return setTimeout( handlerProxy, delay || 0 );
},
_hoverable: function( element ) {
this.hoverable = this.hoverable.add( element );
this._on( element, {
mouseenter: function( event ) {
$( event.currentTarget ).addClass( "ui-state-hover" );
},
mouseleave: function( event ) {
$( event.currentTarget ).removeClass( "ui-state-hover" );
}
});
},
_focusable: function( element ) {
this.focusable = this.focusable.add( element );
this._on( element, {
focusin: function( event ) {
$( event.currentTarget ).addClass( "ui-state-focus" );
},
focusout: function( event ) {
$( event.currentTarget ).removeClass( "ui-state-focus" );
}
});
},
_trigger: function( type, event, data ) {
var prop, orig,
callback = this.options[ type ];
data = data || {};
event = $.Event( event );
event.type = ( type === this.widgetEventPrefix ?
type :
this.widgetEventPrefix + type ).toLowerCase();
// the original event may come from any element
// so we need to reset the target on the new event
event.target = this.element[ 0 ];
// copy original event properties over to the new event
orig = event.originalEvent;
if ( orig ) {
for ( prop in orig ) {
if ( !( prop in event ) ) {
event[ prop ] = orig[ prop ];
}
}
}
this.element.trigger( event, data );
return !( $.isFunction( callback ) &&
callback.apply( this.element[0], [ event ].concat( data ) ) === false ||
event.isDefaultPrevented() );
}
};
$.each( { show: "fadeIn", hide: "fadeOut" }, function( method, defaultEffect ) {
$.Widget.prototype[ "_" + method ] = function( element, options, callback ) {
if ( typeof options === "string" ) {
options = { effect: options };
}
var hasOptions,
effectName = !options ?
method :
options === true || typeof options === "number" ?
defaultEffect :
options.effect || defaultEffect;
options = options || {};
if ( typeof options === "number" ) {
options = { duration: options };
}
hasOptions = !$.isEmptyObject( options );
options.complete = callback;
if ( options.delay ) {
element.delay( options.delay );
}
if ( hasOptions && $.effects && ( $.effects.effect[ effectName ] || $.uiBackCompat !== false && $.effects[ effectName ] ) ) {
element[ method ]( options );
} else if ( effectName !== method && element[ effectName ] ) {
element[ effectName ]( options.duration, options.easing, callback );
} else {
element.queue(function( next ) {
$( this )[ method ]();
if ( callback ) {
callback.call( element[ 0 ] );
}
next();
});
}
};
});
// DEPRECATED
if ( $.uiBackCompat !== false ) {
$.Widget.prototype._getCreateOptions = function() {
return $.metadata && $.metadata.get( this.element[0] )[ this.widgetName ];
};
}
})( jQuery );
|
(function($){
$(document).ready(function(){
$(window).scroll(function(){
// 屏幕滚动数据
var m = $(document).scrollTop();
var lefts = $('.left');
lefts.each(function(){
var that = $(this);
var left = that.offset().top;
var currentId = '';
if((m+300)>left){
currentId = '#'+that.attr('id');
}else{
return false;
}
var currentLink = $('.right').find('.active');
if(currentId && currentId != currentLink.attr('href')){
currentLink.removeClass('active');
$('.right').find('[href='+currentId+']').addClass('active');
}
})
})
})
})(jQuery); |
var url = "http://api.justin.tv/api/stream/list.json";
var stream = "?channel=tobiwandota,versuta,minidota,wagamamatv,netolicrc,sexybamboe,dendi,wepla,alaito&callback=?";
var streamSelection = [];
var streamDota = ["dendi","tobiwandota","starladder1","wagamamatv","onemoregametv2","versuta","4cejkee","beyondthesummit","minidota"];
var streamWoW = ["styrka","affinitiibl","amiye","slootbag","zuperwtf","killars","syiler","sco","healthbar"];
var streamProm = ["styrka","greenyb","healthbar","velna","amiye","kynks"];
var streamdata = [];
function removeA(arr) {
var what, a = arguments, L = a.length, ax;
while (L > 1 && arr.length) {
what = a[--L];
while ((ax= arr.indexOf(what)) !== -1) {
arr.splice(ax, 1);
}
}
return arr;
}
$('#streamAdd').click(function() {
streamSelection.push($('#streamName').val());
$('#streamName').val('');
});
$('#streamRemove').click(function() {
removeA(streamSelection, $('#streamName').val());
$('#streamName').val('');
});
$('#streamUpdate').click(function() {
if (streamSelection.length !== 0) streamUpdate(streamSelection);
});
$('#streamDota').click(function() {
streamUpdate(streamDota);
});
$('#streamWoW').click(function() {
streamUpdate(streamWoW);
});
$('#streamProm').click(function() {
streamUpdate(streamProm);
});
function streamCategory(selection) {
$('#streams').html('');
loadStreams();
}
function streamUpdate(selection) {
stream = "?channel=" + selection.toString() + "&callback=?";
$('#streams').html('<i class="icon-spinner icon-4x icon-spin"></i>');
loadStreams();
}
function loadStreams() {
$.getJSON(url + stream, function(data) {
var datact = 0;
$.each(data, function(id, node) {
streamdata[datact] = [];
$.each(node, function(key, val) {
if (key==='title') streamdata[datact].title = val;
if (key==='stream_count') streamdata[datact].viewers = val;
if (key==='meta_game') streamdata[datact].game = val;
if(key==='channel') {
streamdata[datact].stream = val.embed_code;
streamdata[datact].name = val.login;
}
});
datact++;
});
$('#streams').html('');
for (i=0;i<datact;i++) {
if (i%3===0) {
$('#streams').append('<article class="row">');
}
$('#streams').children().last().append('<section id="' + streamdata[i].name + '" class="one third padded"> <h3>' + streamdata[i].name + '</h3>' + streamdata[i].stream + '<p>' + streamdata[i].title + '</p> </section>');
if (i%3===2) {
$('#streams').append('</article>');
}
}
if (i%3!==2) {
$('#streams').append('</article>');
}
});
}
$('document').ready(loadStreams());
|
var toString = Object.prototype.toString;
module.exports = (value) => toString.call(value) === '[object Arguments]'; |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.