code stringlengths 2 1.05M |
|---|
/**
*
* This game was designed with a different font in mind, install the Star Jedi Rounded font here: http://www.fontspace.com/category/star%20wars
* Once installed, restart your browser to immerse yourself in the experience. :D
*
*/
/**
▄█ ▄█▄ ▄████████ ▀█████████▄ ▄████████ ▄█
███ ▄███▀ ███ ███ ███ ███ ███ ███ ███
███▐██▀ ███ █▀ ███ ███ ███ ███ ███▌
▄█████▀ ▄███▄▄▄ ▄███▄▄▄██▀ ███ ███ ███▌
▀▀█████▄ ▀▀███▀▀▀ ▀▀███▀▀▀██▄ ▀███████████ ███▌
███▐██▄ ███ █▄ ███ ██▄ ███ ███ ███
███ ▀███▄ ███ ███ ███ ███ ███ ███ ███
███ ▀█▀ ██████████ ▄█████████▀ ███ █▀ █▀
▀
________ _________ __________
___ __ \__________________ /___ _________ /___(_)____________________
__ /_/ /_ ___/ __ \ __ /_ / / / ___/ __/_ /_ __ \_ __ \_ ___/
_ ____/_ / / /_/ / /_/ / / /_/ // /__ / /_ _ / / /_/ / / / /(__ )
/_/ /_/ \____/\__,_/ \__,_/ \___/ \__/ /_/ \____//_/ /_//____/
- ⠠⠠⠉⠕⠙⠑⠀⠠⠠⠊⠎⠀⠠⠠⠏⠕⠑⠞⠗⠽ - C O D E I S P O E T R Y = -.-. --- -.. . .. ... .--. --- . - .-. -.-- =
*/
/** --- CONSTANTS --- **/
var NUMBER_OF_ARCS = 37;
var MENU_STAR_SIZE = 2;
var MENU_LOGO_INCREASE = 8;
/** --- DYNAMIC GLOBAL VARIABLES --- **/
var currScreen = "loading";
var transitionFill = 0;
var transition = null;
var transitionFirstTime = false;
var keys = [];
var mouseOverButton = "";
var cacheImageNo = 0;
var menuStarsPos = [];
for(var i = 0; i < 300; i++) {
menuStarsPos.push({x: random(0, width), y: random(0, height)});
}
var menuLogoSize = 0;
var playLogoSize = 3.5;
/** --- UTILITY FUNCTIONS --- **/
var button = function(x, y, w, h, r, t, ts, tf, htf, f, hf) {
if(dist(x, y, mouseX, mouseY) < w / 2) {
if(mouseIsPressed) {
mouseOverButton = t;
}
fill(hf);
} else {
fill(f);
}
noStroke();
ellipse(x, y, w, h);
if(dist(x, y, mouseX, mouseY) < w / 2) {
fill(htf);
} else {
fill(tf);
}
textAlign(CENTER, CENTER);
textSize(ts);
text(t, x, y);
};
var cacheImage = function(imgFunction, w, h) {
var c = createGraphics(w, h, JAVA2D);
if(!c) {
return;
}
c = imgFunction(c);
return(c.get());
};
/** --- RENDERING & INPUT --- **/
var PreCache = {
starWarsLogo: function(c) {
c.background(0, 0, 0, 0);
c.stroke(255, 232, 31);
c.strokeWeight(4);
c.strokeCap(SQUARE);
c.fill(0);
c.pushMatrix();
c.scale(0.7);
c.translate(230, -30);
//s & t
c.beginShape();
c.vertex(193,112);
c.vertex(71,112);
c.bezierVertex(47,115,46,142,71,162);
c.vertex(2,162);
c.vertex(2,191);
c.vertex(87,191);
c.bezierVertex(130,171,91,136,91,136);
c.vertex(127,136);
c.vertex(127,191);
c.vertex(158,191);
c.vertex(158,136);
c.vertex(193,136);
c.vertex(193,110);
c.endShape();
//a
c.beginShape();
c.vertex(206,112);
c.vertex(182,191);
c.vertex(211,191);
c.vertex(216,179);
c.vertex(242,179);
c.vertex(246,191);
c.vertex(277,191);
c.vertex(252,112);
c.vertex(205.0,112);
c.endShape();
c.beginShape();
c.vertex(230,137);
c.vertex(223,156);
c.vertex(236,156);
c.vertex(230,137);
c.endShape();
//R
c.beginShape();
c.vertex(284,112);
c.vertex(284,191);
c.vertex(314,191);
c.vertex(314,170);
c.vertex(338,191);
c.vertex(395,191);
c.vertex(395,162);
c.vertex(351,162);
c.bezierVertex(376,140,360,118,351,112);
c.vertex(282,112);
c.endShape();
c.beginShape();
c.vertex(316,133);
c.vertex(336,133);
c.bezierVertex(339,138,336,143,336,143);
c.vertex(316,143);
c.vertex(316,131);
c.endShape();
//translate(0,25);
//W
c.beginShape();
c.vertex(36,199);
c.vertex(1,199);
c.vertex(29,280);
c.vertex(55,280);
c.vertex(65,250);
c.vertex(75,280);
c.vertex(103,280);
c.vertex(125,199);
c.vertex(96,199);
c.vertex(91,217);
c.vertex(84,199);
c.vertex(48,199);
c.vertex(42,217);
c.vertex(36,199);
c.endShape();
//a
c.pushMatrix();
c.translate(-64,87);
c.beginShape();
c.vertex(206,112);
c.vertex(182,192);
c.vertex(211,192);
c.vertex(216,179);
c.vertex(242,179);
c.vertex(246,192);
c.vertex(277,192);
c.vertex(252,112);
c.vertex(205.0,112);
c.endShape();
c.beginShape();
c.vertex(230,137);
c.vertex(223,156);
c.vertex(236,156);
c.vertex(230,137);
c.endShape();
c.popMatrix();
c.pushMatrix();
c.translate(-63,88);
//R
c.beginShape();
c.vertex(284,112);
c.vertex(284,191);
c.vertex(314,191);
c.vertex(314,170);
c.vertex(338,191);
c.vertex(416,191);
c.bezierVertex(416,191,456,172,419,137);
c.vertex(457,137);
c.vertex(457,112);
c.vertex(408,112);
c.bezierVertex(362,120,388,155,395,162);
c.vertex(351,162);
c.bezierVertex(376,140,360,118,351,112);
c.vertex(282,112);
c.endShape();
c.beginShape();
c.vertex(316,133);
c.vertex(336,133);
c.bezierVertex(339,138,336,143,336,143);
c.vertex(316,143);
c.vertex(316,131);
c.endShape();
c.popMatrix();
c.popMatrix();
return c;
},
red: function(c) {
c.background(0, 0, 0, 0);
c.stroke(255, 232, 31);
c.strokeWeight(4);
c.strokeCap(SQUARE);
c.fill(255, 0, 0);
c.rect(0, 0, 200, 200);
return c;
},
green: function(c) {
c.background(0, 0, 0, 0);
c.stroke(255, 232, 31);
c.strokeWeight(4);
c.strokeCap(SQUARE);
c.fill(13, 255, 0);
c.rect(0, 0, 200, 200);
return c;
},
blue: function(c) {
c.background(0, 0, 0, 0);
c.stroke(255, 232, 31);
c.strokeWeight(4);
c.strokeCap(SQUARE);
c.fill(0, 21, 255);
c.rect(0, 0, 200, 200);
return c;
},
yellow: function(c) {
c.background(0, 0, 0, 0);
c.stroke(255, 232, 31);
c.strokeWeight(4);
c.strokeCap(SQUARE);
c.fill(255, 234, 0);
c.rect(0, 0, 200, 200);
return c;
},
orange: function(c) {
c.background(0, 0, 0, 0);
c.stroke(255, 232, 31);
c.strokeWeight(4);
c.strokeCap(SQUARE);
c.fill(255, 170, 0);
c.rect(0, 0, 200, 200);
return c;
}
};
var Cache = {
Bitmap: {
},
Sound: {
}
};
var Loading = {
draw: function() {
background(0, 0, 0);
var counter = 0;
for(var i in PreCache) {
if(counter === cacheImageNo) {
Cache.Bitmap[i] = cacheImage(PreCache[i], width, height);
cacheImageNo++;
break;
}
counter++;
}
strokeCap(SQUARE);
colorMode(HSB);
// Gives the Shadow
stroke(frameCount * 0.2 % 255, 255, 255, 80);
strokeWeight(3);
// Draws the Shadow
for(var i = 1; i < NUMBER_OF_ARCS; i++) {
arc(width / 2, height / 2, (NUMBER_OF_ARCS + 1) * 20 + -i * 15, (NUMBER_OF_ARCS + 1) * 20 + -i * 15, frameCount / 2 * i % 360 - 180, frameCount / 2 * i % 360);
}
strokeWeight(3);
// Controls Color
stroke(frameCount * 0.2 % 255, 255, 255);
noFill();
// Draws the main arcs
for(var i = 1; i < NUMBER_OF_ARCS; i++) {
arc(width / 2, height / 2, (NUMBER_OF_ARCS + 1) * 20 + -i * 15, (NUMBER_OF_ARCS + 1) * 20 + -i * 15, frameCount / 2 * i % 360 - 180, frameCount / 2 * i % 360);
}
colorMode(RGB);
var counter2 = 0;
for(var i in Cache.Bitmap) {
if(counter2 === cacheImageNo - 1) {
image(Cache.Bitmap[i], width / 2, 300, 120, 120);
if(counter2 === Object.keys(PreCache).length-1) {
currScreen = "menu";
transitionFill -= 5;
}
break;
}
counter2++;
}
}
};
var Menu = {
draw: function() {
background(0, 0, 0);
fill(255, 255, 255);
for(var i = 0; i < menuStarsPos.length; i++) {
ellipse(menuStarsPos[i].x, menuStarsPos[i].y, MENU_STAR_SIZE, MENU_STAR_SIZE);
}
image(Cache.Bitmap.starWarsLogo, width / 2, height / 2, menuLogoSize, menuLogoSize);
fill(255, 232, 31);
textSize(40);
text("The Final Frontier", 300, 220);
button(300, 350, 125, 125, 10, "Play", 24, color(0, 0, 0), color(255, 242, 0), color(255, 255, 255), color(0, 0, 0));
button(180, 350, 80, 80, 10, "options", 15, color(0, 0, 0), color(255, 242, 0), color(255, 255, 255), color(0, 0, 0));
button(420, 350, 80, 80, 10, "Credits", 15, color(0, 0, 0), color(255, 242, 0), color(255, 255, 255), color(0, 0, 0));
if(menuLogoSize < width) {
menuLogoSize += MENU_LOGO_INCREASE;
}
}
};
var Play = {
draw: function() {
background(0, 0, 0);
fill(255, 255, 255);
for(var i = 0; i < menuStarsPos.length; i++) {
ellipse(menuStarsPos[i].x, menuStarsPos[i].y, MENU_STAR_SIZE, MENU_STAR_SIZE);
}
pushMatrix();
translate(width / 2, height / 2 + width / 4 * playLogoSize);
scale(playLogoSize);
image(Cache.Bitmap.starWarsLogo, 0, 0);
popMatrix();
if(playLogoSize > 0) {
playLogoSize -= 0.01 * playLogoSize;
}
}
};
var GameHandler = {
transitionScene: function(scene) {
if(transitionFill < 255 && transition) {
transitionFill += 2;
} else if(transitionFill > -1 && transition === false) {
transitionFill -= 2;
} else if(transitionFill >= 255 && transition) {
transition = false;
} else if(transitionFill <= -3 && transition === false) {
transition = null;
} else if(transition === null && transitionFill < -1) {
transition = true;
}
if(!transition && transitionFill > -3) {
scene.draw();
}
fill(0, 0, 0, transitionFill);
rect(width / 2, height / 2, width, height);
},
update: function() {
// Default Styling
noStroke();
strokeWeight(1);
rectMode(CENTER);
imageMode(CENTER);
textAlign(CENTER, CENTER);
textFont(createFont("Star Jedi Rounded"));
mouseOverButton = "";
switch(currScreen) {
case "loading":
Loading.draw();
break;
case "menu":
this.transitionScene(Menu);
break;
case "play":
this.transitionScene(Play);
break;
}
}
};
mouseReleased = function() {
if(mouseOverButton !== "") {
currScreen = mouseOverButton.toLowerCase();
transitionFill -= 5;
}
};
draw = function() {
GameHandler.update();
};
var setLoopThrowTimer = function() {
this[["KAInfiniteLoopSetTimeout"][0]](40000);
};
setLoopThrowTimer();
|
/*!
* jQuery doTimeout: Like setTimeout, but better! - v1.0 - 3/3/2010
* http://benalman.com/projects/jquery-dotimeout-plugin/
*
* Copyright (c) 2010 "Cowboy" Ben Alman
* Dual licensed under the MIT and GPL licenses.
* http://benalman.com/about/license/
*/
// Script: jQuery doTimeout: Like setTimeout, but better!
//
// *Version: 1.0, Last updated: 3/3/2010*
//
// Project Home - http://benalman.com/projects/jquery-dotimeout-plugin/
// GitHub - http://github.com/cowboy/jquery-dotimeout/
// Source - http://github.com/cowboy/jquery-dotimeout/raw/master/jquery.ba-dotimeout.js
// (Minified) - http://github.com/cowboy/jquery-dotimeout/raw/master/jquery.ba-dotimeout.min.js (1.0kb)
//
// About: License
//
// Copyright (c) 2010 "Cowboy" Ben Alman,
// Dual licensed under the MIT and GPL licenses.
// http://benalman.com/about/license/
//
// About: Examples
//
// These working examples, complete with fully commented code, illustrate a few
// ways in which this plugin can be used.
//
// Debouncing - http://benalman.com/code/projects/jquery-dotimeout/examples/debouncing/
// Delays, Polling - http://benalman.com/code/projects/jquery-dotimeout/examples/delay-poll/
// Hover Intent - http://benalman.com/code/projects/jquery-dotimeout/examples/hoverintent/
//
// About: Support and Testing
//
// Information about what version or versions of jQuery this plugin has been
// tested with, what browsers it has been tested in, and where the unit tests
// reside (so you can test it yourself).
//
// jQuery Versions - 1.3.2, 1.4.2
// Browsers Tested - Internet Explorer 6-8, Firefox 2-3.6, Safari 3-4, Chrome 4-5, Opera 9.6-10.1.
// Unit Tests - http://benalman.com/code/projects/jquery-dotimeout/unit/
//
// About: Release History
//
// 1.0 - (3/3/2010) Callback can now be a string, in which case it will call
// the appropriate $.method or $.fn.method, depending on where .doTimeout
// was called. Callback must now return `true` (not just a truthy value)
// to poll.
// 0.4 - (7/15/2009) Made the "id" argument optional, some other minor tweaks
// 0.3 - (6/25/2009) Initial release
(function($) {
'$:nomunge'; // Used by YUI compressor.
var cache = {},
// Reused internal string.
doTimeout = 'doTimeout',
// A convenient shortcut.
aps = Array.prototype.slice;
// Method: jQuery.doTimeout
//
// Initialize, cancel, or force execution of a callback after a delay.
//
// If delay and callback are specified, a doTimeout is initialized. The
// callback will execute, asynchronously, after the delay. If an id is
// specified, this doTimeout will override and cancel any existing doTimeout
// with the same id. Any additional arguments will be passed into callback
// when it is executed.
//
// If the callback returns true, the doTimeout loop will execute again, after
// the delay, creating a polling loop until the callback returns a non-true
// value.
//
// Note that if an id is not passed as the first argument, this doTimeout will
// NOT be able to be manually canceled or forced. (for debouncing, be sure to
// specify an id).
//
// If id is specified, but delay and callback are not, the doTimeout will be
// canceled without executing the callback. If force_mode is specified, the
// callback will be executed, synchronously, but will only be allowed to
// continue a polling loop if force_mode is true (provided the callback
// returns true, of course). If force_mode is false, no polling loop will
// continue, even if the callback returns true.
//
// Usage:
//
// > jQuery.doTimeout( [ id, ] delay, callback [, arg ... ] );
// > jQuery.doTimeout( id [, force_mode ] );
//
// Arguments:
//
// id - (String) An optional unique identifier for this doTimeout. If id is
// not specified, the doTimeout will NOT be able to be manually canceled or
// forced.
// delay - (Number) A zero-or-greater delay in milliseconds after which
// callback will be executed.
// callback - (Function) A function to be executed after delay milliseconds.
// callback - (String) A jQuery method to be executed after delay
// milliseconds. This method will only poll if it explicitly returns
// true.
// force_mode - (Boolean) If true, execute that id's doTimeout callback
// immediately and synchronously, continuing any callback return-true
// polling loop. If false, execute the callback immediately and
// synchronously but do NOT continue a callback return-true polling loop.
// If omitted, cancel that id's doTimeout.
//
// Returns:
//
// If force_mode is true, false or undefined and there is a
// yet-to-be-executed callback to cancel, true is returned, but if no
// callback remains to be executed, undefined is returned.
$[doTimeout] = function() {
return p_doTimeout.apply(window, [ 0 ].concat(aps.call(arguments)));
};
// Method: jQuery.fn.doTimeout
//
// Initialize, cancel, or force execution of a callback after a delay.
// Operates like <jQuery.doTimeout>, but the passed callback executes in the
// context of the jQuery collection of elements, and the id is stored as data
// on the first element in that collection.
//
// If delay and callback are specified, a doTimeout is initialized. The
// callback will execute, asynchronously, after the delay. If an id is
// specified, this doTimeout will override and cancel any existing doTimeout
// with the same id. Any additional arguments will be passed into callback
// when it is executed.
//
// If the callback returns true, the doTimeout loop will execute again, after
// the delay, creating a polling loop until the callback returns a non-true
// value.
//
// Note that if an id is not passed as the first argument, this doTimeout will
// NOT be able to be manually canceled or forced (for debouncing, be sure to
// specify an id).
//
// If id is specified, but delay and callback are not, the doTimeout will be
// canceled without executing the callback. If force_mode is specified, the
// callback will be executed, synchronously, but will only be allowed to
// continue a polling loop if force_mode is true (provided the callback
// returns true, of course). If force_mode is false, no polling loop will
// continue, even if the callback returns true.
//
// Usage:
//
// > jQuery('selector').doTimeout( [ id, ] delay, callback [, arg ... ] );
// > jQuery('selector').doTimeout( id [, force_mode ] );
//
// Arguments:
//
// id - (String) An optional unique identifier for this doTimeout, stored as
// jQuery data on the element. If id is not specified, the doTimeout will
// NOT be able to be manually canceled or forced.
// delay - (Number) A zero-or-greater delay in milliseconds after which
// callback will be executed.
// callback - (Function) A function to be executed after delay milliseconds.
// callback - (String) A jQuery.fn method to be executed after delay
// milliseconds. This method will only poll if it explicitly returns
// true (most jQuery.fn methods return a jQuery object, and not `true`,
// which allows them to be chained and prevents polling).
// force_mode - (Boolean) If true, execute that id's doTimeout callback
// immediately and synchronously, continuing any callback return-true
// polling loop. If false, execute the callback immediately and
// synchronously but do NOT continue a callback return-true polling loop.
// If omitted, cancel that id's doTimeout.
//
// Returns:
//
// When creating a <jQuery.fn.doTimeout>, the initial jQuery collection of
// elements is returned. Otherwise, if force_mode is true, false or undefined
// and there is a yet-to-be-executed callback to cancel, true is returned,
// but if no callback remains to be executed, undefined is returned.
$.fn[doTimeout] = function() {
var args = aps.call(arguments),
result = p_doTimeout.apply(this, [ doTimeout + args[0] ].concat(args));
return typeof args[0] === 'number' || typeof args[1] === 'number'
? this
: result;
};
function p_doTimeout(jquery_data_key) {
var that = this,
elem,
data = {},
// Allows the plugin to call a string callback method.
method_base = jquery_data_key ? $.fn : $,
// Any additional arguments will be passed to the callback.
args = arguments,
slice_args = 4,
id = args[1],
delay = args[2],
callback = args[3];
if (typeof id !== 'string') {
slice_args--;
id = jquery_data_key = 0;
delay = args[1];
callback = args[2];
}
// If id is passed, store a data reference either as .data on the first
// element in a jQuery collection, or in the internal cache.
if (jquery_data_key) { // Note: key is 'doTimeout' + id
// Get id-object from the first element's data, otherwise initialize it to {}.
elem = that.eq(0);
elem.data(jquery_data_key, data = elem.data(jquery_data_key) || {});
} else if (id) {
// Get id-object from the cache, otherwise initialize it to {}.
data = cache[ id ] || ( cache[ id ] = {} );
}
// Clear any existing timeout for this id.
data.id && clearTimeout(data.id);
delete data.id;
// Clean up when necessary.
function cleanup() {
if (jquery_data_key) {
elem.removeData(jquery_data_key);
} else if (id) {
delete cache[ id ];
}
}
;
// Yes, there actually is a setTimeout call in here!
function actually_setTimeout() {
data.id = setTimeout(function() {
data.fn();
}, delay);
}
;
if (callback) {
// A callback (and delay) were specified. Store the callback reference for
// possible later use, and then setTimeout.
data.fn = function(no_polling_loop) {
// If the callback value is a string, it is assumed to be the name of a
// method on $ or $.fn depending on where doTimeout was executed.
if (typeof callback === 'string') {
callback = method_base[ callback ];
}
callback.apply(that, aps.call(args, slice_args)) === true && !no_polling_loop
// Since the callback returned true, and we're not specifically
// canceling a polling loop, do it again!
? actually_setTimeout()
// Otherwise, clean up and quit.
: cleanup();
};
// Set that timeout!
actually_setTimeout();
} else if (data.fn) {
// No callback passed. If force_mode (delay) is true, execute the data.fn
// callback immediately, continuing any callback return-true polling loop.
// If force_mode is false, execute the data.fn callback immediately but do
// NOT continue a callback return-true polling loop. If force_mode is
// undefined, simply clean up. Since data.fn was still defined, whatever
// was supposed to happen hadn't yet, so return true.
delay === undefined ? cleanup() : data.fn(delay === false);
return true;
} else {
// Since no callback was passed, and data.fn isn't defined, it looks like
// whatever was supposed to happen already did. Clean up and quit!
cleanup();
}
}
;
})(jQuery);
|
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M17 3H7c-1.1 0-1.99.9-1.99 2L5 21l7-3 7 3V5c0-1.1-.9-2-2-2zm0 15l-5-2.18L7 18V5h10v13z" />
, 'TurnedInNotTwoTone');
|
module.exports = require('./lib/bradoc')
|
/*
* This file is part of thumbor-toy project.
*
* (c) Raphaël Benitte <thumbor-toy@rbenitte.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import Reflux from 'reflux';
export default Reflux.createActions([
'open',
'close',
'toggle'
]);
|
const db = require('../../database/database');
db.query(`create table if not exists "contacts" (
_id serial primary key,
name varchar(256) not null,
email varchar(256) not null,
phone varchar(256),
message varchar(256)
)`, (err) => {
if (err) {
console.error(err);
}
});
module.exports = db;
|
/*
* @flow
*/
import type {Suite} from "flow-dev-tools/src/test/Suite";
const {suite, test} = require('flow-dev-tools/src/test/Tester');
const files = [
'other/explicitly_included.js',
'src/implicitly_included.js',
'src/explicitly_ignored.js',
'other/implicitly_ignored.js',
'src/explicit_lib.js',
'src/flow-typed/implicit_lib.js',
];
module.exports = (suite(({addFile, flowCmd, removeFile}) => [
test('No --all flag and implicit root', [
flowCmd(['ls'])
.stderr(
`
Could not find a .flowconfig in . or any of its parent directories.
See "flow init --help" for more info
`,
)
.sortedStdout('')
.because("Assumes current directory is root, and there's no .flowconfig"),
flowCmd(['ls', '--strip-root', 'src'])
.stderr('')
.sortedStdout(
`
.flowconfig
explicit_lib.js
flow-typed/implicit_lib.js
implicitly_included.js
`,
)
.because('Infers root and only shows included files in src directory'),
flowCmd(['ls', '--strip-root', 'src', 'other'])
.stderr('')
.sortedStdout(
`
../other/explicitly_included.js
.flowconfig
explicit_lib.js
flow-typed/implicit_lib.js
implicitly_included.js
`,
)
.because('Infers root and will show included files in both directories'),
flowCmd(['ls', '--strip-root', 'other', 'src'])
.stderr(
`
Could not find a .flowconfig in other or any of its parent directories.
See "flow init --help" for more info
`,
)
.sortedStdout('')
.because('Infers root from first arg, which is not a flow root'),
flowCmd(['ls', '--strip-root', 'src/doesNotExist.js'])
.sortedStdout('')
.sortedStdout('')
.because("Won't show files that don't exist")
]),
test('Explicit root will not filter out files in other/',[
flowCmd([
'ls',
'--strip-root',
'--root',
'src',
])
.stderr('')
.sortedStdout(
`
../other/explicitly_included.js
.flowconfig
explicit_lib.js
flow-typed/implicit_lib.js
implicitly_included.js
`,
),
]),
test('--all should all libs, included files, and explicitly ignored files', [
flowCmd([
'ls',
'--strip-root',
'--all',
'--root',
'src',
])
.stderr('')
.sortedStdout(
`
../other/explicitly_included.js
.flowconfig
explicit_lib.js
explicitly_ignored.js
flow-typed/implicit_lib.js
implicitly_included.js
`,
),
]),
test('Implicit/Explicit Included/Ignored/Lib should be correct', [
flowCmd([
'ls',
'--strip-root',
'--root', 'src',
'--all',
'--explain',
].concat(files)) // Explicitly list out files
.stderr('')
.sortedStdout(
`
ExplicitLib explicit_lib.js
ExplicitlyIgnored explicitly_ignored.js
ExplicitlyIncluded ../other/explicitly_included.js
ImplicitLib flow-typed/implicit_lib.js
ImplicitlyIgnored ../other/implicitly_ignored.js
ImplicitlyIncluded implicitly_included.js
`,
),
]),
test('JSON output without --explain should be an array', [
flowCmd([
'ls',
'--json',
'--strip-root',
'--root', 'src',
'--all',
].concat(files).concat(['src/.flowconfig']))
.stderr('')
.stdout(
`
[
"../other/explicitly_included.js",
"../other/implicitly_ignored.js",
".flowconfig",
"explicit_lib.js",
"explicitly_ignored.js",
"flow-typed/implicit_lib.js",
"implicitly_included.js"
]
`,
),
]),
test('JSON output with --explain should be JSON object',[
flowCmd([
'ls',
'--json',
'--strip-root',
'--root', 'src',
'--all',
'--explain'
].concat(files).concat(['src/.flowconfig']))
.stderr('')
.stdout(
`
{
"../other/explicitly_included.js": {
"explanation": "ExplicitlyIncluded"
},
"../other/implicitly_ignored.js": {
"explanation": "ImplicitlyIgnored"
},
".flowconfig": {
"explanation": "ConfigFile"
},
"explicit_lib.js": {
"explanation": "ExplicitLib"
},
"explicitly_ignored.js": {
"explanation": "ExplicitlyIgnored"
},
"flow-typed/implicit_lib.js": {
"explanation": "ImplicitLib"
},
"implicitly_included.js": {
"explanation": "ImplicitlyIncluded"
}
}
`,
),
]),
test('Listing files over stdin', [
addFile('stdin_file.txt'),
flowCmd(['ls', '--strip-root', '--root', 'src', '--all', '--input-file', '-'], 'stdin_file.txt')
.stderr('')
.sortedStdout(
`
../other/explicitly_included.js
.flowconfig
explicit_lib.js
explicitly_ignored.js
flow-typed/implicit_lib.js
implicitly_included.js
`,
)
.because('Same as if we passed src/ and other/explicitly_include.js from the command line'),
flowCmd(['ls', '--strip-root', '--root', 'src', '--all', '--input-file', '-', 'other/implicitly_ignored.js'], 'stdin_file.txt')
.stderr('')
.sortedStdout(
`
../other/explicitly_included.js
../other/implicitly_ignored.js
.flowconfig
explicit_lib.js
explicitly_ignored.js
flow-typed/implicit_lib.js
implicitly_included.js
`,
)
.because('flow ls will combine command line with the input file'),
]),
test('Input file on disk', [
addFile('stdin_file.txt'),
flowCmd(['ls', '--strip-root', '--root', 'src', '--all', '--input-file', 'stdin_file.txt'])
.stderr('')
.sortedStdout(
`
../other/explicitly_included.js
.flowconfig
explicit_lib.js
explicitly_ignored.js
flow-typed/implicit_lib.js
implicitly_included.js
`,
)
.because('Same as if we passed src/ and other/explicitly_include.js from the command line'),
flowCmd(['ls', '--strip-root', '--root', 'src', '--all', '--input-file', 'stdin_file.txt', 'other/implicitly_ignored.js'])
.stderr('')
.sortedStdout(
`
../other/explicitly_included.js
../other/implicitly_ignored.js
.flowconfig
explicit_lib.js
explicitly_ignored.js
flow-typed/implicit_lib.js
implicitly_included.js
`,
)
.because('flow ls will combine command line with the input file'),
]),
test('Non-existent files and directories', [
flowCmd(['ls', '--strip-root', 'src/foobar'])
.stderr(
`
Could not find file or directory src/foobar; canceling search for .flowconfig.
See "flow init --help" for more info
`,
)
.because('We try to use foobar to infer the root, so we complain when it doesnt exist'),
flowCmd(['ls', '--strip-root', '--root', 'src', 'src/foobar', 'src/implicitly_included.js'])
.stderr(``)
.stdout(
`
implicitly_included.js
`,
)
.because('We just filter out non-existent files'),
flowCmd(['ls', '--strip-root', '--imaginary', '--root', 'src', 'src/foobar', 'src/implicitly_included.js', 'src/flow-typed/baz.js'])
.stderr(``)
.stdout(
`
foobar
implicitly_included.js
flow-typed/baz.js
`,
)
.because('With --imaginary we include non-existent files. Non-existent files are never considered to be libs.'),
flowCmd(['ls', '--strip-root', '--explain', '--imaginary', '--root', 'src', 'src/foobar', 'src/baz', 'src/implicitly_included.js', 'src/flow-typed/baz'])
.stderr(``)
.stdout(
`
ImplicitlyIncluded foobar
ImplicitlyIncluded baz
ImplicitlyIncluded implicitly_included.js
ImplicitlyIncluded flow-typed/baz
`,
)
.because('--explain should work with --imaginary as expected. Non-existent files are never considered to be libs.'),
flowCmd(['ls', '--all', '--strip-root', '--root', 'src', 'src/foobar', 'src/implicitly_included.js'])
.stderr(``)
.stdout(
`
implicitly_included.js
`,
)
.because('We just filter out non-existent files. --all does not imply --imaginary'),
flowCmd(['ls', '--all', '--imaginary', '--strip-root', '--explain', '--root', 'src', 'foobar', 'src/foobar', 'src/implicitly_included.js'])
.stderr(``)
.stdout(
`
ImplicitlyIgnored ../foobar
ImplicitlyIncluded foobar
ImplicitlyIncluded implicitly_included.js
`,
)
.because('../foobar is implicitly ignored and only listed with the --all flag'),
]),
]).beforeEach(({addFile, addFiles, removeFile}) => [
addFile('src/_flowconfig', 'src/.flowconfig')
.addFiles(...files)
.removeFile('.flowconfig')
]): Suite);
|
(function() {
var checkVersion = Dagaz.Model.checkVersion;
Dagaz.Model.checkVersion = function(design, name, value) {
if (name != "renju-extension") {
checkVersion(design, name, value);
}
}
var go = Dagaz.Controller.go;
Dagaz.Controller.go = function(url) {
var design = Dagaz.Model.design;
var board = Dagaz.Controller.app.board;
url = url + "?setup=";
var prev = null; var cnt = 0;
_.each(design.allPositions(), function(pos) {
var piece = board.getPiece(pos);
var s = "";
if (piece !== null) {
var type = piece.player - 1;
s = s + type + ":1";
}
if ((prev === null) || (prev != s)) {
if (prev !== null) {
url = url + prev;
if (cnt > 0) {
url = url + "+" + cnt;
}
url = url + ";";
}
prev = s;
cnt = 0;
} else {
cnt++;
}
});
url = url + prev;
if (cnt > 0) {
url = url + "+" + cnt;
}
url = url + ";";
go(url);
}
Dagaz.Model.getLine = function(design, board, player, pos, dir, ix) {
var p = design.navigate(player, pos, dir);
if (p === null) return 0;
var piece = board.getPiece(p);
if (piece === null) return 0;
if (piece.player != board.player) return 0;
return +piece.getValue(ix);
}
var updateLine = function(design, board, player, pos, ix, vl, dir, move) {
var p = design.navigate(player, pos, dir);
while (p !== null) {
var piece = board.getPiece(p);
if ((piece === null) || (piece.player != board.player)) break;
piece = piece.setValue(ix, vl);
move.movePiece(p, p, piece);
p = design.navigate(player, p, dir);
}
}
var CheckInvariants = Dagaz.Model.CheckInvariants;
Dagaz.Model.CheckInvariants = function(board) {
var design = Dagaz.Model.design;
var dirs = [];
dirs.push(design.getDirection("n")); dirs.push(design.getDirection("ne"));
dirs.push(design.getDirection("e")); dirs.push(design.getDirection("se"));
_.each(board.moves, function(move) {
if (_.isUndefined(move.failed) && move.isDropMove()) {
var pos = move.actions[0][1][0];
var piece = move.actions[0][2][0];
for (var ix = 0; ix < dirs.length; ix++) {
var vl = 1;
vl += Dagaz.Model.getLine(design, board, board.player, pos, dirs[ix], ix);
vl += Dagaz.Model.getLine(design, board, 0, pos, dirs[ix], ix);
updateLine(design, board, board.player, pos, ix, vl, dirs[ix], move);
updateLine(design, board, 0, pos, ix, vl, dirs[ix], move);
piece = piece.setValue(ix, vl);
}
move.actions[0][2] = [ piece ];
}
});
CheckInvariants(board);
}
})();
|
(function (global, factory) {
if (typeof define === "function" && define.amd) {
define(["a"], factory);
} else if (typeof exports !== "undefined") {
factory(require("a"));
} else {
var mod = {
exports: {}
};
factory(global.a);
global.input = mod.exports;
}
})(typeof globalThis !== "undefined" ? globalThis : typeof self !== "undefined" ? self : this, function (_a) {
"use strict";
_a = babelHelpers.interopRequireDefault(_a);
});
|
// Generated by CoffeeScript 1.9.0
var Capabilities, Util, path, _,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
__hasProp = {}.hasOwnProperty;
_ = require('underscore')._;
path = require('path');
Util = module.parent.exports;
Capabilities = (function(_super) {
__extends(Capabilities, _super);
Capabilities.prototype.__modules = [];
Capabilities.prototype.__loaded_modules = [];
function Capabilities() {
var name, _i, _len, _ref;
_ref = ['mongoose', 'mongodb', 'rikki-tikki-client'];
for (_i = 0, _len = _ref.length; _i < _len; _i++) {
name = _ref[_i];
if (_.map(_.pluck(require.cache, 'filename'), function(p) {
return path.dirname(p).split(path.sep).pop();
}).indexOf("" + name) > -1) {
this.__modules = _.union(this.__modules, name);
}
if (Util.detectModule(name)) {
this.__loaded_modules.push(name);
}
}
}
Capabilities.prototype.detectedModules = function() {
return this.__modules;
};
Capabilities.prototype.loadedModules = function() {
return this.__loaded_modules;
};
Capabilities.prototype.clientSupported = function() {
return 0 <= this.detectedModules().indexOf('rikki-tikki-client');
};
Capabilities.prototype.clientLoaded = function() {
return 0 <= this.loadedModules().indexOf('rikki-tikki-client');
};
Capabilities.prototype.mongooseSupported = function() {
return 0 <= this.detectedModules().indexOf('mongoose');
};
Capabilities.prototype.mongooseLoaded = function() {
return 0 <= this.loadedModules().indexOf('mongoose');
};
Capabilities.prototype.nativeSupported = function() {
return 0 <= this.detectedModules().indexOf('mongodb');
};
Capabilities.prototype.nativeLoaded = function() {
return 0 <= this.loadedModules().indexOf('mongodb');
};
Capabilities.prototype.expressSupported = function() {
return 0 <= this.detectedModules().indexOf('express');
};
Capabilities.prototype.expressLoaded = function() {
return 0 <= this.loadedModules().indexOf('express');
};
Capabilities.prototype.hapiSupported = function() {
return 0 <= this.detectedModules().indexOf('hapi');
};
Capabilities.prototype.hapiLoaded = function() {
return 0 <= this.loadedModules().indexOf('hapi');
};
return Capabilities;
})(Object);
module.exports = Capabilities;
|
var events = require("events"),
util = require("util"),
colors = require("colors"),
Firmata = require("firmata").Board,
_ = require("lodash"),
__ = require("../lib/fn.js"),
Repl = require("../lib/repl.js"),
serialport = require("serialport"),
Pins = require("../lib/board.pins.js"),
Options = require("../lib/board.options.js"),
// temporal = require("temporal"),
board,
boards,
rport,
Serial;
boards = [];
rport = /usb|acm|com/i;
/**
* Process Codes
* SIGHUP 1 Term Hangup detected on controlling terminal
or death of controlling process
* SIGINT 2 Term Interrupt from keyboard
* SIGQUIT 3 Core Quit from keyboard
* SIGILL 4 Core Illegal Instruction
* SIGABRT 6 Core Abort signal from abort(3)
* SIGFPE 8 Core Floating point exception
* SIGKILL 9 Term Kill signal
* SIGSEGV 11 Core Invalid memory reference
* SIGPIPE 13 Term Broken pipe: write to pipe with no readers
* SIGALRM 14 Term Timer signal from alarm(2)
* SIGTERM 15 Term Termination signal
*
*
*
* http://www.slac.stanford.edu/BFROOT/www/Computing/Environment/Tools/Batch/exitcode.html
*
*/
Serial = {
used: [],
detect: function( callback ) {
this.info( "Board", "Connecting..." );
// If a |port| was explicitly provided to the Board constructor,
// invoke the detection callback and return immediately
if ( this.port ) {
callback.call( this, this.port );
return;
}
serialport.list(function(err, result) {
var ports,
length;
ports = result.filter(function(val) {
var available = true;
// Match only ports that Arduino cares about
// ttyUSB#, cu.usbmodem#, COM#
if ( !rport.test(val.comName) ) {
available = false;
}
// Don't allow already used/encountered usb device paths
if ( Serial.used.indexOf(val.comName) > -1 ) {
available = false;
}
return available;
}).map(function(val) {
return val.comName;
});
length = ports.length;
// If no ports are detected when scanning /dev/, then there is
// nothing left to do and we can safely exit the program
if ( !length ) {
// Alert user that no devices were detected
this.error( "Board", "No USB devices detected" );
// Exit the program by sending SIGABRT
process.exit(3);
// Return (not that it matters, but this is a good way
// to indicate to readers of the code that nothing else
// will happen in this function)
return;
}
// Continue with connection routine attempts
this.info(
"Serial",
"Found possible serial port" + ( length > 1 ? "s" : "" ),
ports.toString().grey
);
// Get the first available device path from the list of
// detected ports
callback.call( this, ports[0] );
}.bind(this));
},
connect: function( usb, callback ) {
var err, found, connected, eventType;
// Add the usb device path to the list of device paths that
// are currently in use - this is used by the filter function
// above to remove any device paths that we've already encountered
// or used to avoid blindly attempting to reconnect on them.
Serial.used.push( usb );
try {
found = new Firmata( usb, function( error ) {
if ( error !== undefined ) {
err = error;
}
// Execute "ready" callback
callback.call( this, err, "ready", found );
}.bind(this));
// Made this far, safely connected
connected = true;
} catch ( error ) {
err = error;
}
if ( err ) {
err = err.message || err;
}
// Determine the type of event that will be passed on to
// the board emitter in the callback passed to Serial.detect(...)
eventType = connected ? "connected" : "error";
// Execute "connected" callback
callback.call( this, err, eventType, found );
}
};
/**
* Board
* @constructor
*
* @param {Object} opts
*/
function Board( opts ) {
if ( !(this instanceof Board) ) {
return new Board( opts );
}
// Ensure opts is an object
opts = opts || {};
var inject, timer;
inject = {};
// Initialize this Board instance with
// param specified properties.
_.assign( this, opts );
// Easily track state of hardware
this.ready = false;
// Initialize instance property to reference firmata board
this.firmata = null;
// Registry of devices by pin address
this.register = [];
// Identify for connected hardware cache
if ( !this.id ) {
this.id = __.uid();
}
// If no debug flag, default to false
// TODO: Remove override
this.debug = true;
if ( !("debug" in this) ) {
this.debug = false;
}
if ( !("repl" in this) ) {
this.repl = true;
}
// Specially processed pin capabilities object
// assigned when board is initialized and ready
this.pins = null;
// Human readable name (if one can be detected)
this.type = '';
// Create a Repl instance and store as
// instance property of this firmata/board.
// This will reduce the amount of boilerplate
// code required to _always_ have a Repl
// session available.
//
// If a sesssion exists, use it
// (instead of creating a new session)
//
if ( this.repl ) {
if ( Repl.ref ) {
inject[ this.id ] = this;
Repl.ref.on( "ready", function() {
Repl.ref.inject( inject );
});
this.repl = Repl.ref;
} else {
inject[ this.id ] = inject.board = this;
this.repl = new Repl( inject );
}
}
// Used for testing only
if ( this.mock ) {
this.ready = true;
this.firmata = new Firmata( this.mock, function() {} );
// NEED A DUMMY OF THE PINS OBJECT
//
//
this.pins = Board.Pins( this );
// Execute "connected" and "ready" callbacks
this.emit( "connected", null );
this.emit( "ready", null );
} else if ( opts.firmata ) {
// If you already have a connected firmata instance
this.firmata = opts.firmata;
this.ready = true;
this.pins = Board.Pins( this );
this.emit( "connected", null );
this.emit( "ready", null );
} else {
Serial.detect.call( this, function( port ) {
Serial.connect.call( this, port, function( err, type, firmata ) {
if ( err ) {
this.error( "Board", err );
} else {
// Assign found firmata to instance
this.firmata = firmata;
this.info(
"Board " + ( type === "connected" ? "->" : "<-" ) + " Serialport",
type,
port.grey
);
}
if ( type === "connected" ) {
// 10 Second timeout...
//
// If "ready" hasn't fired and cleared the timer within
// 10 seconds of the connected event, then it's likely
// that Firmata simply isn't loaded onto the board.
timer = setTimeout(function() {
this.error(
"StandardFirmata",
"A timeout occurred while connecting to the Board. \n" +
"Please check that you've properly loaded StandardFirmata onto the Arduino"
);
process.emit("SIGINT");
}.bind(this), 1e5);
process.on( "SIGINT", function() {
this.warn( "Board", "Closing: firmata, serialport" );
// On ^c, make sure we close the process after the
// firmata and serialport are closed. Approx 100ms
// TODO: this sucks, need better solution
setTimeout(function() {
process.exit();
}, 100);
}.bind(this));
}
if ( type === "ready" ) {
clearTimeout( timer );
// Update instance `ready` flag
this.ready = true;
this.port = port;
this.pins = Board.Pins( this );
// In multi-board mode, block the REPL from
// activation. This will be started directly
// by the Board.Array constructor.
if ( !Repl.isBlocked ) {
process.stdin.emit( "data", 1 );
}
}
// emit connect|ready event
this.emit( type, err );
});
});
}
// Cache instance to allow access from module constructors
boards.push( this );
}
// Inherit event api
util.inherits( Board, events.EventEmitter );
/**
* pinMode, analogWrite, analogRead, digitalWrite, digitalRead
*
* Pass through methods
*/
[
"pinMode",
"analogWrite", "analogRead",
"digitalWrite", "digitalRead"
].forEach(function( method ) {
Board.prototype[ method ] = function( pin, arg ) {
this.firmata[ method ]( pin, arg );
return this;
};
});
Board.prototype.serialize = function( filter ) {
var blacklist, special;
blacklist = this.serialize.blacklist;
special = this.serialize.special;
return JSON.stringify(
this.register.map(function( device ) {
return Object.getOwnPropertyNames( device ).reduce(function( data, prop ) {
var value = device[ prop ];
if ( blacklist.indexOf(prop) === -1 &&
typeof value !== "function" ) {
data[ prop ] = special[ prop ] ?
special[ prop ]( value ) : value;
if ( filter ) {
data[ prop ] = filter( prop, data[ prop ], device );
}
}
return data;
}, {});
}, this)
);
};
Board.prototype.serialize.blacklist = [
"board", "firmata", "_events"
];
Board.prototype.serialize.special = {
mode: function(value) {
return [ "INPUT", "OUTPUT", "ANALOG", "PWM", "SERVO" ][ value ] || "unknown";
}
};
/**
* shiftOut
*
*/
Board.prototype.shiftOut = function( dataPin, clockPin, isBigEndian, value ) {
var mask, write;
write = function( value, mask ) {
this.digitalWrite( clockPin, this.firmata.LOW );
this.digitalWrite(
dataPin, this.firmata[ value & mask ? "HIGH" : "LOW" ]
);
this.digitalWrite( clockPin, this.firmata.HIGH );
}.bind(this);
if ( arguments.length === 3 ) {
value = arguments[2];
isBigEndian = true;
}
if ( isBigEndian ) {
for ( mask = 128; mask > 0; mask = mask >> 1 ) {
write( value, mask );
}
} else {
for ( mask = 0; mask < 128; mask = mask << 1 ) {
write( value, mask );
}
}
};
Board.prototype.log = function( /* type, module, message [, long description] */ ) {
var args = [].slice.call( arguments ),
type = args.shift(),
module = args.shift(),
message = args.shift(),
color = Board.prototype.log.types[ type ];
if ( this.debug ) {
console.log([
// Timestamp
String(+new Date()).grey,
// Module, color matches type of log
module.magenta,
// Message
message[ color ],
// Miscellaneous args
args.join(", ")
].join(" "));
}
};
Board.prototype.log.types = {
error: "red",
fail: "orange",
warn: "yellow",
info: "cyan"
};
// Make shortcuts to all logging methods
Object.keys( Board.prototype.log.types ).forEach(function( type ) {
Board.prototype[ type ] = function() {
var args = [].slice.call( arguments );
args.unshift( type );
this.log.apply( this, args );
};
});
/**
* delay, loop, queue
*
* Pass through methods to temporal
*/
/*
[
"delay", "loop", "queue"
].forEach(function( method ) {
Board.prototype[ method ] = function( time, callback ) {
temporal[ method ]( time, callback );
return this;
};
});
// Alias wait to delay to match existing Johnny-five API
Board.prototype.wait = Board.prototype.delay;
*/
// -----THIS IS A TEMPORARY FIX UNTIL THE ISSUES WITH TEMPORAL ARE RESOLVED-----
// Aliasing.
// (temporary, while ironing out API details)
// The idea is to match existing hardware programming apis
// or simply find the words that are most intuitive.
// Eventually, there should be a queuing process
// for all new callbacks added
//
// TODO: Repalce with temporal or compulsive API
Board.prototype.wait = function( time, callback ) {
setTimeout( callback.bind(this), time );
return this;
};
Board.prototype.loop = function( time, callback ) {
setInterval( callback.bind(this), time );
return this;
};
// ----------
// Static API
// ----------
// Board.map( val, fromLow, fromHigh, toLow, toHigh )
//
// Re-maps a number from one range to another.
// Based on arduino map()
Board.map = __.map;
// Board.constrain( val, lower, upper )
//
// Constrains a number to be within a range.
// Based on arduino constrain()
Board.constrain = __.constrain;
// Board.range( upper )
// Board.range( lower, upper )
// Board.range( lower, upper, tick )
//
// Returns a new array range
//
Board.range = __.range;
// Board.range.prefixed( prefix, upper )
// Board.range.prefixed( prefix, lower, upper )
// Board.range.prefixed( prefix, lower, upper, tick )
//
// Returns a new array range, each value prefixed
//
Board.range.prefixed = __.range.prefixed;
// Board.uid()
//
// Returns a reasonably unique id string
//
Board.uid = __.uid;
// Board.mount()
// Board.mount( index )
// Board.mount( object )
//
// Return hardware instance, based on type of param:
// @param {arg}
// object, user specified
// number/index, specified in cache
// none, defaults to first in cache
//
// Notes:
// Used to reduce the amount of boilerplate
// code required in any given module or program, by
// giving the developer the option of omitting an
// explicit Board reference in a module
// constructor's options
Board.mount = function( arg ) {
var index = typeof arg === "number" && arg,
hardware;
// board was explicitly provided
if ( arg && arg.board ) {
return arg.board;
}
// index specified, attempt to return
// hardware instance. Return null if not
// found or not available
if ( index ) {
hardware = boards[ index ];
return hardware && hardware || null;
}
// If no arg specified and hardware instances
// exist in the cache
if ( boards.length ) {
return boards[ 0 ];
}
// No mountable hardware
return null;
};
/**
* Board.Device
*
* Initialize a new device instance
*
* Board.Device is a |this| senstive constructor,
* and must be called as:
*
* Board.Device.call( this, opts );
*
*
*
* TODO: Migrate all constructors to use this
* to avoid boilerplate
*/
Board.Device = function( opts ) {
// Board specific properties
this.board = Board.mount( opts );
this.firmata = this.board.firmata;
// Device/Module instance properties
this.id = opts.id || null;
// Pin or Pins address(es)
opts = Board.Pins.normalize( opts, this.board );
if ( typeof opts.pins !== "undefined" ) {
this.pins = opts.pins || [];
}
if ( typeof opts.pin !== "undefined" ) {
this.pin = opts.pin || 0;
}
this.board.register.push( this );
};
/**
* Pin Capability Signature Mapping
*/
Board.Pins = Pins;
Board.Options = Options;
// Define a user-safe, unwritable hardware cache access
Object.defineProperty( Board, "cache", {
get: function() {
return boards;
}
});
/**
* Board event constructor.
* opts:
* type - event type. eg: "read", "change", "up" etc.
* target - the instance for which the event fired.
* 0..* other properties
*/
Board.Event = function( opts ) {
if ( !(this instanceof Board.Event) ) {
return new Board.Event( opts );
}
opts = opts || {};
// default event is read
this.type = opts.type || "read";
// actual target instance
this.target = opts.target || null;
// Initialize this Board instance with
// param specified properties.
_.assign( this, opts );
};
/**
* Boards or Board.Array; Used when the program must connect to
* more then one board.
*
* @memberof Board
*
* @param {Array} ports List of port objects { id: ..., port: ... }
* List of id strings (initialized in order)
*
* @return {Boards} board object references
*/
Board.Array = function( ports ) {
if ( !(this instanceof Board.Array) ) {
return new Board.Array( ports );
}
if ( !Array.isArray(ports) ) {
throw new Error("Expected ports to be an array");
}
Array.call( this, ports.length );
var initialized, count;
initialized = {};
count = ports.length;
// Block initialization of the program's
// REPL until all boards are ready.
Repl.isBlocked = true;
ports.forEach(function( port, k ) {
var opts;
if ( typeof port === "string" ) {
opts = {
id: port
};
} else {
opts = port;
}
this[ k ] = initialized[ opts.id ] = new Board( opts );
this[ k ].on("ready", function() {
this[ k ].info( "Board ID: ", opts.id.green );
this.length++;
if ( !--count ) {
Repl.isBlocked = false;
process.stdin.emit( "data", 1 );
this.emit( "ready", initialized );
}
}.bind(this));
}, this);
};
util.inherits( Board.Array, events.EventEmitter );
Board.Array.prototype.each = Array.prototype.forEach;
module.exports = Board;
// References:
// http://arduino.cc/en/Main/arduinoBoardUno
|
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M9 5v2h6.59L4 18.59 5.41 20 17 8.41V15h2V5z" />
, 'CallMade');
|
/*
* svg-to-png
* https://github.com/filamentgroup/svg-to-png
*
* Copyright (c) 2013 Jeffrey Lembeck/Filament Group
* Licensed under the MIT license.
*/
/*global require:true*/
/*global __dirname:true*/
/*global console:true*/
(function(exports) {
"use strict";
var os = require( 'os' );
var fs = require( 'fs' );
var path = require( 'path' );
try {
var Imagemin = require('imagemin');
} catch(e) {
var imageminNotInstalled = true;
}
var RSVP = require( './rsvp' );
var phantomJsPath = require('phantomjs').path;
var phantomfile = path.join( __dirname, 'phantomscript.js' );
var execFile = require('child_process').execFile;
var convertNoCompress = function( files, outputDir, opts ){
return new RSVP.Promise(function(resolve, reject){
execFile( phantomJsPath,
[
phantomfile,
JSON.stringify(files),
outputDir,
opts.defaultWidth,
opts.defaultHeight
],
function(err, stdout, stderr){
if( err ){
console.log("\nSomething went wrong with phantomjs...");
if( stderr ){
console.log( stderr );
}
reject( err );
} else {
console.log( stdout );
resolve( outputDir );
}
});
});
};
var convertCompress = function( files, outputDir, opts ){
if( imageminNotInstalled ){
throw "Imagemin dependency is not installed.";
}
var tempDir = path.join( os.tmpdir(), "svg-to-png" + (new Date()).getTime() );
return new RSVP.Promise(function(resolve, reject){
execFile( phantomJsPath,
[
phantomfile,
JSON.stringify(files),
tempDir,
opts.defaultWidth,
opts.defaultHeight
],
function(err, stdout, stderr){
if( err ){
console.log("\nSomething went wrong with phantomjs...");
if( stderr ){
console.log( stderr );
}
reject( err );
} else {
console.log( stdout );
opts = opts || {};
opts.optimizationLevel = opts.optimizationLevel || 3;
var imagemin = new Imagemin()
.src( tempDir + '/*.{gif,jpg,png,svg}' )
.dest(outputDir)
.use(Imagemin.optipng(opts));
imagemin.run(function (err, files) {
if (err) {
reject(err);
}
resolve(files);
});
}
});
});
};
exports.convert = function( input, output, opts ){
opts = opts || {};
var files;
if( typeof input === "string" && fs.existsSync( input ) && fs.lstatSync( input ).isDirectory()){
files = fs.readdirSync( input ).map( function( file ){
return path.join( input, file );
});
} else if( typeof input === "string" && fs.existsSync( input ) && fs.lstatSync( input ).isFile() ) {
files = [ input ];
} else if( Array.isArray( input ) ){
files = input;
} else {
throw new Error( "Input must be Array of files or String that is a directory" );
}
if( !files.every( function( file ){
return path.extname(file) === ".svg";
})){
throw new Error( "All files passed into svg-to-png must be SVG files, that includes all files in a directory" );
}
if( !files.length ){
throw new Error( "Input must be Array of SVG files or String that is a directory that contains some of those" );
}
if( typeof output !== "string" ){
throw new Error( "Output folder must be defined and a String" );
}
if( !opts.defaultWidth ){
opts.defaultWidth = "400px";
}
if( !opts.defaultHeight ){
opts.defaultHeight = "300px";
}
// take it to phantomjs to do the rest
console.log( "svg-to-png now spawning phantomjs..." );
console.log('(using path: ' + phantomJsPath + ')');
if( opts.compress ){
return convertCompress( files, output, opts );
} else {
return convertNoCompress( files, output, opts );
}
};
}(typeof exports === 'object' && exports || this));
|
/**
* Created by yakuncyk on 2017/4/4.
*/
var p1 = new Promise(function(resolve, reject) {
resolve('p1 done')
})
var p2 = new Promise(function(resolve, reject) {
setTimeout(function() {
resolve('p2 done')
}, 3000)
})
var p3 = new Promise(function(resolve, reject) {
setTimeout(function() {
// reject('p3 done')
resolve('p3 done')
}, 3000)
})
Promise.all([p1, p2, p3])
.then(function(valueArr) {
console.log('dones', valueArr)
})
.catch(function(errs) {
console.error('errors', errs)
}) |
const config = require('module-config').default(module.id);
const scriptjs = require('scriptjs');
let scriptjsExtend = scriptjs;
/**
* Overrides original scriptjs loader to resolve path to local modules before loading
* (Local modules are considered paths, that don't start with 'https://', 'http://' or '//')
*/
if ('bundlesPath' in config) {
const scriptpath = config.bundlesPath;
scriptjsExtend = function $script(paths, idOrDone, optDone) {
paths = Array.isArray(paths) ? paths : [paths];
paths = paths.map(function(path) {
if (!/^(?:https?:)?\/\//.test(path)) {
path = path.indexOf('.js') === -1 ? scriptpath + path + '.js' : scriptpath + path;
}
return path;
});
scriptjs(paths, idOrDone, optDone);
};
Object.assign(scriptjsExtend, scriptjs);
scriptjsExtend.order = function(scripts, id, done) {
(function callback(s) {
s = scripts.shift();
!scripts.length ? scriptjsExtend(s, id, done) : scriptjsExtend(s, callback);
}());
};
scriptjsExtend.ready = function(deps, ready, req) {
scriptjs.ready(deps, ready, req);
return scriptjsExtend;
};
}
module.exports = scriptjsExtend;
|
const childProcess = require('child_process')
const fs = require('fs')
const path = require('path')
const electronLink = require('electron-link')
const CONFIG = require('../config')
const vm = require('vm')
module.exports = function (packagedAppPath) {
const snapshotScriptPath = path.join(CONFIG.buildOutputPath, 'startup.js')
const coreModules = new Set(['electron', 'atom', 'shell', 'WNdb', 'lapack', 'remote'])
const baseDirPath = path.join(CONFIG.intermediateAppPath, 'static')
let processedFiles = 0
return electronLink({
baseDirPath,
mainPath: path.resolve(baseDirPath, '..', 'src', 'initialize-application-window.js'),
cachePath: path.join(CONFIG.atomHomeDirPath, 'snapshot-cache'),
auxiliaryData: CONFIG.snapshotAuxiliaryData,
shouldExcludeModule: (modulePath) => {
if (processedFiles > 0) {
process.stdout.write('\r')
}
process.stdout.write(`Generating snapshot script at "${snapshotScriptPath}" (${++processedFiles})`)
const relativePath = path.relative(baseDirPath, modulePath)
return (
modulePath.endsWith('.node') ||
coreModules.has(modulePath) ||
(relativePath.startsWith(path.join('..', 'src')) && relativePath.endsWith('-element.js')) ||
relativePath.startsWith(path.join('..', 'node_modules', 'dugite')) ||
relativePath === path.join('..', 'exports', 'atom.js') ||
relativePath === path.join('..', 'src', 'electron-shims.js') ||
relativePath === path.join('..', 'src', 'safe-clipboard.js') ||
relativePath === path.join('..', 'node_modules', 'atom-keymap', 'lib', 'command-event.js') ||
relativePath === path.join('..', 'node_modules', 'babel-core', 'index.js') ||
relativePath === path.join('..', 'node_modules', 'cached-run-in-this-context', 'lib', 'main.js') ||
relativePath === path.join('..', 'node_modules', 'coffee-script', 'lib', 'coffee-script', 'register.js') ||
relativePath === path.join('..', 'node_modules', 'cson-parser', 'node_modules', 'coffee-script', 'lib', 'coffee-script', 'register.js') ||
relativePath === path.join('..', 'node_modules', 'decompress-zip', 'lib', 'decompress-zip.js') ||
relativePath === path.join('..', 'node_modules', 'debug', 'node.js') ||
relativePath === path.join('..', 'node_modules', 'fs-extra', 'lib', 'index.js') ||
relativePath === path.join('..', 'node_modules', 'git-utils', 'lib', 'git.js') ||
relativePath === path.join('..', 'node_modules', 'glob', 'glob.js') ||
relativePath === path.join('..', 'node_modules', 'graceful-fs', 'graceful-fs.js') ||
relativePath === path.join('..', 'node_modules', 'htmlparser2', 'lib', 'index.js') ||
relativePath === path.join('..', 'node_modules', 'markdown-preview', 'node_modules', 'htmlparser2', 'lib', 'index.js') ||
relativePath === path.join('..', 'node_modules', 'roaster', 'node_modules', 'htmlparser2', 'lib', 'index.js') ||
relativePath === path.join('..', 'node_modules', 'task-lists', 'node_modules', 'htmlparser2', 'lib', 'index.js') ||
relativePath === path.join('..', 'node_modules', 'iconv-lite', 'lib', 'index.js') ||
relativePath === path.join('..', 'node_modules', 'less', 'index.js') ||
relativePath === path.join('..', 'node_modules', 'less', 'lib', 'less', 'fs.js') ||
relativePath === path.join('..', 'node_modules', 'less', 'lib', 'less-node', 'index.js') ||
relativePath === path.join('..', 'node_modules', 'less', 'node_modules', 'graceful-fs', 'graceful-fs.js') ||
relativePath === path.join('..', 'node_modules', 'minimatch', 'minimatch.js') ||
relativePath === path.join('..', 'node_modules', 'node-fetch', 'lib', 'fetch-error.js') ||
relativePath === path.join('..', 'node_modules', 'nsfw', 'node_modules', 'fs-extra', 'lib', 'index.js') ||
relativePath === path.join('..', 'node_modules', 'superstring', 'index.js') ||
relativePath === path.join('..', 'node_modules', 'oniguruma', 'src', 'oniguruma.js') ||
relativePath === path.join('..', 'node_modules', 'request', 'index.js') ||
relativePath === path.join('..', 'node_modules', 'resolve', 'index.js') ||
relativePath === path.join('..', 'node_modules', 'resolve', 'lib', 'core.js') ||
relativePath === path.join('..', 'node_modules', 'scandal', 'node_modules', 'minimatch', 'minimatch.js') ||
relativePath === path.join('..', 'node_modules', 'settings-view', 'node_modules', 'glob', 'glob.js') ||
relativePath === path.join('..', 'node_modules', 'settings-view', 'node_modules', 'minimatch', 'minimatch.js') ||
relativePath === path.join('..', 'node_modules', 'spellchecker', 'lib', 'spellchecker.js') ||
relativePath === path.join('..', 'node_modules', 'spelling-manager', 'node_modules', 'natural', 'lib', 'natural', 'index.js') ||
relativePath === path.join('..', 'node_modules', 'tar', 'tar.js') ||
relativePath === path.join('..', 'node_modules', 'temp', 'lib', 'temp.js') ||
relativePath === path.join('..', 'node_modules', 'tmp', 'lib', 'tmp.js') ||
relativePath === path.join('..', 'node_modules', 'tree-view', 'node_modules', 'minimatch', 'minimatch.js')
)
}
}).then((snapshotScript) => {
fs.writeFileSync(snapshotScriptPath, snapshotScript)
process.stdout.write('\n')
console.log('Verifying if snapshot can be executed via `mksnapshot`')
vm.runInNewContext(snapshotScript, undefined, {filename: snapshotScriptPath, displayErrors: true})
const generatedStartupBlobPath = path.join(CONFIG.buildOutputPath, 'snapshot_blob.bin')
console.log(`Generating startup blob at "${generatedStartupBlobPath}"`)
childProcess.execFileSync(
path.join(CONFIG.repositoryRootPath, 'script', 'node_modules', 'electron-mksnapshot', 'bin', 'mksnapshot'),
[snapshotScriptPath, '--startup_blob', generatedStartupBlobPath]
)
let startupBlobDestinationPath
if (process.platform === 'darwin') {
startupBlobDestinationPath = `${packagedAppPath}/Contents/Frameworks/Electron Framework.framework/Resources/snapshot_blob.bin`
} else {
startupBlobDestinationPath = path.join(packagedAppPath, 'snapshot_blob.bin')
}
console.log(`Moving generated startup blob into "${startupBlobDestinationPath}"`)
fs.unlinkSync(startupBlobDestinationPath)
fs.renameSync(generatedStartupBlobPath, startupBlobDestinationPath)
})
}
|
import React, {PropTypes} from 'react'
const Todo = ({onClick, completed, text}) => (
<li onClick={onClick}
className={completed
? 'text-success'
: 'text-danger'}
style={{
'cursor': 'pointer'
}}>
{text}
</li>
)
Todo.propTypes = {
onClick: PropTypes.func.isRequired,
completed: PropTypes.bool.isRequired,
text: PropTypes.string.isRequired
}
export default Todo
|
/**
* @fileoverview Tests for config object.
* @author Seth McLaughlin
*/
/* eslint no-undefined: "off" */
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const assert = require("chai").assert,
path = require("path"),
fs = require("fs"),
os = require("os"),
Config = require("../../lib/config"),
environments = require("../../conf/environments"),
sinon = require("sinon"),
mockFs = require("mock-fs");
const DIRECTORY_CONFIG_HIERARCHY = require("../fixtures/config-hierarchy/file-structure.json");
require("shelljs/global");
const proxyquire = require("proxyquire").noCallThru().noPreserveCache();
/* global mkdir, rm, cp */
/**
* Creates a stubbed Config object that will bypass normal require() to load
* plugins by name from the objects specified.
* @param {Object} plugins The keys are the package names, values are plugin objects.
* @returns {Config} The stubbed instance of Config.
* @private
*/
function createStubbedConfigWithPlugins(plugins) {
// stub out plugins
const StubbedPlugins = proxyquire("../../lib/config/plugins", plugins);
// stub out config file to use stubbed plugins
const StubbedConfigFile = proxyquire("../../lib/config/config-file", {
"./plugins": StubbedPlugins
});
// stub out Config to use stub config file
return proxyquire("../../lib/config", {
"./config/config-file": StubbedConfigFile,
"./config/plugins": StubbedPlugins
});
}
/**
* Asserts that two configs are equal. This is necessary because assert.deepEqual()
* gets confused when properties are in different orders.
* @param {Object} actual The config object to check.
* @param {Object} expected What the config object should look like.
* @returns {void}
* @private
*/
function assertConfigsEqual(actual, expected) {
if (actual.env && expected.env) {
assert.deepEqual(actual.env, expected.env);
}
if (actual.parserOptions && expected.parserOptions) {
assert.deepEqual(actual.parserOptions, expected.parserOptions);
}
if (actual.globals && expected.globals) {
assert.deepEqual(actual.globals, expected.globals);
}
if (actual.rules && expected.rules) {
assert.deepEqual(actual.rules, expected.rules);
}
if (actual.plugins && expected.plugins) {
assert.deepEqual(actual.plugins, expected.plugins);
}
}
//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------
describe("Config", () => {
let fixtureDir,
sandbox;
/**
* Returns the path inside of the fixture directory.
* @returns {string} The path inside the fixture directory.
* @private
*/
function getFixturePath() {
const args = Array.prototype.slice.call(arguments);
args.unshift("config-hierarchy");
args.unshift(fixtureDir);
return path.join.apply(path, args);
}
/**
* Mocks the current CWD path
* @param {string} fakeCWDPath - fake CWD path
* @returns {void}
* @private
*/
function mockCWDResponse(fakeCWDPath) {
sandbox.stub(process, "cwd")
.returns(fakeCWDPath);
}
// copy into clean area so as not to get "infected" by this project's .eslintrc files
before(() => {
fixtureDir = `${os.tmpdir()}/eslint/fixtures`;
mkdir("-p", fixtureDir);
cp("-r", "./tests/fixtures/config-hierarchy", fixtureDir);
});
beforeEach(() => {
sandbox = sinon.sandbox.create();
});
afterEach(() => {
sandbox.verifyAndRestore();
});
after(() => {
rm("-r", fixtureDir);
});
describe("new Config()", () => {
// https://github.com/eslint/eslint/issues/2380
it("should not modify baseConfig when format is specified", () => {
const customBaseConfig = { foo: "bar" },
configHelper = new Config({ baseConfig: customBaseConfig, format: "foo" });
// at one point, customBaseConfig.format would end up equal to "foo"...that's bad
assert.deepEqual(customBaseConfig, { foo: "bar" });
assert.equal(configHelper.options.format, "foo");
});
});
describe("findLocalConfigFiles()", () => {
/**
* Returns the path inside of the fixture directory.
* @returns {string} The path inside the fixture directory.
* @private
*/
function getFakeFixturePath() {
const args = Array.prototype.slice.call(arguments);
args.unshift("config-hierarchy");
args.unshift("fixtures");
args.unshift("eslint");
args.unshift(process.cwd());
return path.join.apply(path, args);
}
before(() => {
mockFs({
eslint: {
fixtures: {
"config-hierarchy": DIRECTORY_CONFIG_HIERARCHY
}
}
});
});
after(() => {
mockFs.restore();
});
it("should return the path when an .eslintrc file is found", () => {
const configHelper = new Config(),
expected = getFakeFixturePath("broken", ".eslintrc"),
actual = configHelper.findLocalConfigFiles(getFakeFixturePath("broken"))[0];
assert.equal(actual, expected);
});
it("should return an empty array when an .eslintrc file is not found", () => {
const configHelper = new Config(),
actual = configHelper.findLocalConfigFiles(getFakeFixturePath());
assert.isArray(actual);
assert.lengthOf(actual, 0);
});
it("should return package.json only when no other config files are found", () => {
const configHelper = new Config(),
expected0 = getFakeFixturePath("packagejson", "subdir", "package.json"),
expected1 = getFakeFixturePath("packagejson", ".eslintrc"),
actual = configHelper.findLocalConfigFiles(getFakeFixturePath("packagejson", "subdir"));
assert.isArray(actual);
assert.lengthOf(actual, 2);
assert.equal(actual[0], expected0);
assert.equal(actual[1], expected1);
});
it("should return the only one config file even if there are multiple found", () => {
const configHelper = new Config(),
expected = getFakeFixturePath("broken", ".eslintrc"),
// The first element of the array is the .eslintrc in the same directory.
actual = configHelper.findLocalConfigFiles(getFakeFixturePath("broken"));
assert.equal(actual.length, 1);
assert.equal(actual, expected);
});
it("should return all possible files when multiple are found", () => {
const configHelper = new Config(),
expected = [
getFakeFixturePath("fileexts/subdir/subsubdir/", ".eslintrc.json"),
getFakeFixturePath("fileexts/subdir/", ".eslintrc.yml"),
getFakeFixturePath("fileexts", ".eslintrc.js")
],
actual = configHelper.findLocalConfigFiles(getFakeFixturePath("fileexts/subdir/subsubdir"));
assert.deepEqual(actual, expected);
});
it("should return an empty array when a package.json file is not found", () => {
const configHelper = new Config(),
actual = configHelper.findLocalConfigFiles(getFakeFixturePath());
assert.isArray(actual);
assert.lengthOf(actual, 0);
});
});
describe("getConfig()", () => {
it("should return the project config when called in current working directory", () => {
const configHelper = new Config({ cwd: process.cwd() }),
actual = configHelper.getConfig();
assert.equal(actual.rules.strict[1], "global");
});
it("should not retain configs from previous directories when called multiple times", () => {
const firstpath = path.resolve(__dirname, "..", "fixtures", "configurations", "single-quotes", "subdir", ".eslintrc");
const secondpath = path.resolve(__dirname, "..", "fixtures", "configurations", "single-quotes", ".eslintrc");
const configHelper = new Config({ cwd: process.cwd() });
let config;
config = configHelper.getConfig(firstpath);
assert.equal(config.rules["no-new"], 0);
config = configHelper.getConfig(secondpath);
assert.equal(config.rules["no-new"], 1);
});
it("should throw an error when an invalid path is given", () => {
const configPath = path.resolve(__dirname, "..", "fixtures", "configurations", "foobaz", ".eslintrc");
const homePath = "does-not-exist";
const StubbedConfig = proxyquire("../../lib/config", { "user-home": homePath });
const configHelper = new StubbedConfig({ cwd: process.cwd() });
sandbox.stub(fs, "readdirSync").throws(new Error());
assert.throws(() => {
configHelper.getConfig(configPath);
}, "No ESLint configuration found.");
});
it("should throw error when a configuration file doesn't exist", () => {
const configPath = path.resolve(__dirname, "..", "fixtures", "configurations", ".eslintrc");
const configHelper = new Config({ cwd: process.cwd() });
sandbox.stub(fs, "readFileSync").throws(new Error());
assert.throws(() => {
configHelper.getConfig(configPath);
}, "Cannot read config file");
});
it("should throw error when a configuration file is not require-able", () => {
const configPath = ".eslintrc";
const configHelper = new Config({ cwd: process.cwd() });
sandbox.stub(fs, "readFileSync").throws(new Error());
assert.throws(() => {
configHelper.getConfig(configPath);
}, "Cannot read config file");
});
it("should cache config when the same directory is passed twice", () => {
const configPath = path.resolve(__dirname, "..", "fixtures", "configurations", "single-quotes", ".eslintrc");
const configHelper = new Config({ cwd: process.cwd() });
sandbox.spy(configHelper, "findLocalConfigFiles");
// If cached this should be called only once
configHelper.getConfig(configPath);
const callcount = configHelper.findLocalConfigFiles.callcount;
configHelper.getConfig(configPath);
assert.equal(configHelper.findLocalConfigFiles.callcount, callcount);
});
// make sure JS-style comments don't throw an error
it("should load the config file when there are JS-style comments in the text", () => {
const configPath = path.resolve(__dirname, "..", "fixtures", "configurations", "comments.json"),
configHelper = new Config({ configFile: configPath }),
semi = configHelper.useSpecificConfig.rules.semi,
strict = configHelper.useSpecificConfig.rules.strict;
assert.equal(semi, 1);
assert.equal(strict, 0);
});
// make sure YAML files work correctly
it("should load the config file when a YAML file is used", () => {
const configPath = path.resolve(__dirname, "..", "fixtures", "configurations", "env-browser.yaml"),
configHelper = new Config({ configFile: configPath }),
noAlert = configHelper.useSpecificConfig.rules["no-alert"],
noUndef = configHelper.useSpecificConfig.rules["no-undef"];
assert.equal(noAlert, 0);
assert.equal(noUndef, 2);
});
it("should contain the correct value for parser when a custom parser is specified", () => {
const configPath = path.resolve(__dirname, "../fixtures/configurations/parser/.eslintrc.json"),
configHelper = new Config({ cwd: process.cwd() }),
config = configHelper.getConfig(configPath);
assert.equal(config.parser, path.resolve(path.dirname(configPath), "./custom.js"));
});
// Configuration hierarchy ---------------------------------------------
// https://github.com/eslint/eslint/issues/3915
it("should correctly merge environment settings", () => {
const configHelper = new Config({ useEslintrc: true, cwd: process.cwd() }),
file = getFixturePath("envs", "sub", "foo.js"),
expected = {
rules: {},
env: {
browser: true,
node: false
},
globals: environments.browser.globals
},
actual = configHelper.getConfig(file);
assertConfigsEqual(actual, expected);
});
// Default configuration - blank
it("should return a blank config when using no .eslintrc", () => {
const configHelper = new Config({ useEslintrc: false }),
file = getFixturePath("broken", "console-wrong-quotes.js"),
expected = {
rules: {},
globals: {},
env: {}
},
actual = configHelper.getConfig(file);
assertConfigsEqual(actual, expected);
});
it("should return a blank config when baseConfig is set to false and no .eslintrc", () => {
const configHelper = new Config({ baseConfig: false, useEslintrc: false }),
file = getFixturePath("broken", "console-wrong-quotes.js"),
expected = {
rules: {},
globals: {},
env: {}
},
actual = configHelper.getConfig(file);
assertConfigsEqual(actual, expected);
});
// No default configuration
it("should return an empty config when not using .eslintrc", () => {
const configHelper = new Config({ useEslintrc: false }),
file = getFixturePath("broken", "console-wrong-quotes.js"),
actual = configHelper.getConfig(file);
assertConfigsEqual(actual, {});
});
it("should return a modified config when baseConfig is set to an object and no .eslintrc", () => {
const configHelper = new Config({
baseConfig: {
env: {
node: true
},
rules: {
quotes: [2, "single"]
}
},
useEslintrc: false
}),
file = getFixturePath("broken", "console-wrong-quotes.js"),
expected = {
env: {
node: true
},
rules: {
quotes: [2, "single"]
}
},
actual = configHelper.getConfig(file);
assertConfigsEqual(actual, expected);
});
it("should return a modified config without plugin rules enabled when baseConfig is set to an object with plugin and no .eslintrc", () => {
const customRule = require("../fixtures/rules/custom-rule");
const examplePluginName = "eslint-plugin-example";
const requireStubs = {};
requireStubs[examplePluginName] = {
rules: { "example-rule": customRule },
// rulesConfig support removed in 2.0.0, so this should have no effect
rulesConfig: { "example-rule": 1 }
};
const StubbedConfig = proxyquire("../../lib/config", requireStubs);
const configHelper = new StubbedConfig({
baseConfig: {
env: {
node: true
},
rules: {
quotes: [2, "single"]
},
plugins: [examplePluginName]
},
useEslintrc: false
}),
file = getFixturePath("broken", "plugins", "console-wrong-quotes.js"),
expected = {
env: {
node: true
},
rules: {
quotes: [2, "single"]
}
},
actual = configHelper.getConfig(file);
assertConfigsEqual(actual, expected);
});
// Project configuration - second level .eslintrc
it("should merge configs when local .eslintrc overrides parent .eslintrc", () => {
const configHelper = new Config({ cwd: process.cwd() }),
file = getFixturePath("broken", "subbroken", "console-wrong-quotes.js"),
expected = {
env: {
node: true
},
rules: {
"no-console": 1,
quotes: [2, "single"]
}
},
actual = configHelper.getConfig(file);
expected.env.node = true;
assertConfigsEqual(actual, expected);
});
// Project configuration - third level .eslintrc
it("should merge configs when local .eslintrc overrides parent and grandparent .eslintrc", () => {
const configHelper = new Config({ cwd: process.cwd() }),
file = getFixturePath("broken", "subbroken", "subsubbroken", "console-wrong-quotes.js"),
expected = {
env: {
node: true
},
rules: {
"no-console": 0,
quotes: [1, "double"]
}
},
actual = configHelper.getConfig(file);
expected.env.node = true;
assertConfigsEqual(actual, expected);
});
// Project configuration - root set in second level .eslintrc
it("should not return configurations in parents of config with root:true", () => {
const configHelper = new Config({ cwd: process.cwd() }),
file = getFixturePath("root-true", "parent", "root", "wrong-semi.js"),
expected = {
rules: {
semi: [2, "never"]
}
},
actual = configHelper.getConfig(file);
assertConfigsEqual(actual, expected);
});
// Project configuration - root set in second level .eslintrc
it("should return project config when called with a relative path from a subdir", () => {
const configHelper = new Config({ cwd: getFixturePath("root-true", "parent", "root", "subdir") }),
dir = ".",
expected = {
rules: {
semi: [2, "never"]
}
},
actual = configHelper.getConfig(dir);
assertConfigsEqual(actual, expected);
});
// Command line configuration - --config with first level .eslintrc
it("should merge command line config when config file adds to local .eslintrc", () => {
const configHelper = new Config({
configFile: getFixturePath("broken", "add-conf.yaml"),
cwd: process.cwd()
}),
file = getFixturePath("broken", "console-wrong-quotes.js"),
expected = {
env: {
node: true
},
rules: {
quotes: [2, "double"],
semi: [1, "never"]
}
},
actual = configHelper.getConfig(file);
expected.env.node = true;
assertConfigsEqual(actual, expected);
});
// Command line configuration - --config with first level .eslintrc
it("should merge command line config when config file overrides local .eslintrc", () => {
const configHelper = new Config({
configFile: getFixturePath("broken", "override-conf.yaml"),
cwd: process.cwd()
}),
file = getFixturePath("broken", "console-wrong-quotes.js"),
expected = {
env: {
node: true
},
rules: {
quotes: [0, "double"]
}
},
actual = configHelper.getConfig(file);
expected.env.node = true;
assertConfigsEqual(actual, expected);
});
// Command line configuration - --config with second level .eslintrc
it("should merge command line config when config file adds to local and parent .eslintrc", () => {
const configHelper = new Config({
configFile: getFixturePath("broken", "add-conf.yaml"),
cwd: process.cwd()
}),
file = getFixturePath("broken", "subbroken", "console-wrong-quotes.js"),
expected = {
env: {
node: true
},
rules: {
quotes: [2, "single"],
"no-console": 1,
semi: [1, "never"]
}
},
actual = configHelper.getConfig(file);
expected.env.node = true;
assertConfigsEqual(actual, expected);
});
// Command line configuration - --config with second level .eslintrc
it("should merge command line config when config file overrides local and parent .eslintrc", () => {
const configHelper = new Config({
configFile: getFixturePath("broken", "override-conf.yaml"),
cwd: process.cwd()
}),
file = getFixturePath("broken", "subbroken", "console-wrong-quotes.js"),
expected = {
env: {
node: true
},
rules: {
quotes: [0, "single"],
"no-console": 1
}
},
actual = configHelper.getConfig(file);
expected.env.node = true;
assertConfigsEqual(actual, expected);
});
// Command line configuration - --rule with --config and first level .eslintrc
it("should merge command line config and rule when rule and config file overrides local .eslintrc", () => {
const configHelper = new Config({
configFile: getFixturePath("broken", "override-conf.yaml"),
rules: {
quotes: [1, "double"]
},
cwd: process.cwd()
}),
file = getFixturePath("broken", "console-wrong-quotes.js"),
expected = {
env: {
node: true
},
rules: {
quotes: [1, "double"]
}
},
actual = configHelper.getConfig(file);
expected.env.node = true;
assertConfigsEqual(actual, expected);
});
// Command line configuration - --plugin
it("should merge command line plugin with local .eslintrc", () => {
// stub out Config to use stub config file
const StubbedConfig = createStubbedConfigWithPlugins({
"eslint-plugin-example": {},
"eslint-plugin-another-plugin": {}
});
const configHelper = new StubbedConfig({
plugins: ["another-plugin"],
cwd: process.cwd()
}),
file = getFixturePath("broken", "plugins", "console-wrong-quotes.js"),
expected = {
plugins: [
"example",
"another-plugin"
]
},
actual = configHelper.getConfig(file);
assertConfigsEqual(actual, expected);
});
it("should merge multiple different config file formats", () => {
const configHelper = new Config({ cwd: process.cwd() }),
file = getFixturePath("fileexts/subdir/subsubdir/foo.js"),
expected = {
env: {
browser: true
},
rules: {
semi: [2, "always"],
eqeqeq: 2
}
},
actual = configHelper.getConfig(file);
assertConfigsEqual(actual, expected);
});
it("should load user config globals", () => {
const configPath = path.resolve(__dirname, "..", "fixtures", "globals", "conf.yaml"),
configHelper = new Config({ configFile: configPath, useEslintrc: false });
const expected = {
globals: {
foo: true
}
};
const actual = configHelper.getConfig(configPath);
assertConfigsEqual(actual, expected);
});
it("should not load disabled environments", () => {
const configPath = path.resolve(__dirname, "..", "fixtures", "environments", "disable.yaml");
const configHelper = new Config({ configFile: configPath, useEslintrc: false });
const config = configHelper.getConfig(configPath);
assert.isUndefined(config.globals.window);
});
it("should error on fake environments", () => {
const configPath = path.resolve(__dirname, "..", "fixtures", "environments", "fake.yaml");
assert.throw(() => {
new Config({ configFile: configPath, useEslintrc: false, cwd: process.cwd() }); // eslint-disable-line no-new
});
});
it("should gracefully handle empty files", () => {
const configPath = path.resolve(__dirname, "..", "fixtures", "configurations", "env-node.json"),
configHelper = new Config({ configFile: configPath, cwd: process.cwd() });
configHelper.getConfig(path.resolve(__dirname, "..", "fixtures", "configurations", "empty", "empty.json"));
});
// Meaningful stack-traces
it("should include references to where an `extends` configuration was loaded from", () => {
const configPath = path.resolve(__dirname, "..", "fixtures", "config-extends", "error.json");
assert.throws(() => {
const configHelper = new Config({ useEslintrc: false, configFile: configPath });
configHelper.getConfig(configPath);
}, /Referenced from:.*?error\.json/);
});
// Keep order with the last array element taking highest precedence
it("should make the last element in an array take the highest precedence", () => {
const configPath = path.resolve(__dirname, "..", "fixtures", "config-extends", "array", ".eslintrc"),
configHelper = new Config({ useEslintrc: false, configFile: configPath }),
expected = {
rules: { "no-empty": 1, "comma-dangle": 2, "no-console": 2 },
env: { browser: false, node: true, es6: true }
},
actual = configHelper.getConfig(configPath);
assertConfigsEqual(actual, expected);
});
describe("with env in a child configuration file", () => {
it("should overwrite parserOptions of the parent with env of the child", () => {
const config = new Config({ cwd: process.cwd() });
const targetPath = getFixturePath("overwrite-ecmaFeatures", "child", "foo.js");
const expected = {
rules: {},
env: { commonjs: true },
parserOptions: { ecmaFeatures: { globalReturn: true } }
};
const actual = config.getConfig(targetPath);
assertConfigsEqual(actual, expected);
});
});
describe("personal config file within home directory", () => {
/**
* Returns the path inside of the fixture directory.
* @returns {string} The path inside the fixture directory.
* @private
*/
function getFakeFixturePath() {
const args = Array.prototype.slice.call(arguments);
args.unshift("config-hierarchy");
args.unshift("fixtures");
args.unshift("eslint");
args.unshift(process.cwd());
return path.join.apply(path, args);
}
/**
* Mocks the file system for personal-config files
* @returns {undefined}
* @private
*/
function mockPersonalConfigFileSystem() {
mockFs({
eslint: {
fixtures: {
"config-hierarchy": DIRECTORY_CONFIG_HIERARCHY
}
}
});
}
afterEach(() => {
mockFs.restore();
});
it("should load the personal config if no local config was found", () => {
const projectPath = getFakeFixturePath("personal-config", "project-without-config"),
homePath = getFakeFixturePath("personal-config", "home-folder"),
filePath = getFakeFixturePath("personal-config", "project-without-config", "foo.js");
const StubbedConfig = proxyquire("../../lib/config", { "user-home": homePath });
mockPersonalConfigFileSystem();
mockCWDResponse(projectPath);
const config = new StubbedConfig({ cwd: process.cwd() }),
actual = config.getConfig(filePath),
expected = {
parserOptions: {},
env: {},
globals: {},
parser: undefined,
rules: {
"home-folder-rule": 2
}
};
assert.deepEqual(actual, expected);
});
it("should ignore the personal config if a local config was found", () => {
const projectPath = getFakeFixturePath("personal-config", "home-folder", "project"),
homePath = getFakeFixturePath("personal-config", "home-folder"),
filePath = getFakeFixturePath("personal-config", "home-folder", "project", "foo.js");
const StubbedConfig = proxyquire("../../lib/config", { "user-home": homePath });
mockPersonalConfigFileSystem();
mockCWDResponse(projectPath);
const config = new StubbedConfig({ cwd: process.cwd() }),
actual = config.getConfig(filePath),
expected = {
parserOptions: {},
env: {},
globals: {},
parser: undefined,
rules: {
"project-level-rule": 2
}
};
assert.deepEqual(actual, expected);
});
it("should ignore the personal config if config is passed through cli", () => {
const configPath = getFakeFixturePath("quotes-error.json");
const projectPath = getFakeFixturePath("personal-config", "project-without-config"),
homePath = getFakeFixturePath("personal-config", "home-folder"),
filePath = getFakeFixturePath("personal-config", "project-without-config", "foo.js");
const StubbedConfig = proxyquire("../../lib/config", { "user-home": homePath });
mockPersonalConfigFileSystem();
mockCWDResponse(projectPath);
const config = new StubbedConfig({ configFile: configPath, cwd: process.cwd() }),
actual = config.getConfig(filePath),
expected = {
parserOptions: {},
env: {},
globals: {},
parser: undefined,
rules: {
quotes: [2, "double"]
}
};
assert.deepEqual(actual, expected);
});
it("should still load the project config if the current working directory is the same as the home folder", () => {
const projectPath = getFakeFixturePath("personal-config", "project-with-config"),
filePath = getFakeFixturePath("personal-config", "project-with-config", "subfolder", "foo.js");
const StubbedConfig = proxyquire("../../lib/config", { "user-home": projectPath });
mockPersonalConfigFileSystem();
mockCWDResponse(projectPath);
const config = new StubbedConfig({ cwd: process.cwd() }),
actual = config.getConfig(filePath),
expected = {
parserOptions: {},
env: {},
globals: {},
parser: undefined,
rules: {
"project-level-rule": 2,
"subfolder-level-rule": 2
}
};
assert.deepEqual(actual, expected);
});
});
describe("when no local or personal config is found", () => {
/**
* Returns the path inside of the fixture directory.
* @returns {string} The path inside the fixture directory.
* @private
*/
function getFakeFixturePath() {
const args = Array.prototype.slice.call(arguments);
args.unshift("config-hierarchy");
args.unshift("fixtures");
args.unshift("eslint");
args.unshift(process.cwd());
return path.join.apply(path, args);
}
/**
* Mocks the file system for personal-config files
* @returns {undefined}
* @private
*/
function mockPersonalConfigFileSystem() {
mockFs({
eslint: {
fixtures: {
"config-hierarchy": DIRECTORY_CONFIG_HIERARCHY
}
}
});
}
afterEach(() => {
mockFs.restore();
});
it("should throw an error if no local config and no personal config was found", () => {
const projectPath = getFakeFixturePath("personal-config", "project-without-config"),
homePath = getFakeFixturePath("personal-config", "folder-does-not-exist"),
filePath = getFakeFixturePath("personal-config", "project-without-config", "foo.js");
const StubbedConfig = proxyquire("../../lib/config", { "user-home": homePath });
mockPersonalConfigFileSystem();
mockCWDResponse(projectPath);
const config = new StubbedConfig({ cwd: process.cwd() });
assert.throws(() => {
config.getConfig(filePath);
}, "No ESLint configuration found");
});
it("should throw an error if no local config was found and ~/package.json contains no eslintConfig section", () => {
const projectPath = getFakeFixturePath("personal-config", "project-without-config"),
homePath = getFakeFixturePath("personal-config", "home-folder-with-packagejson"),
filePath = getFakeFixturePath("personal-config", "project-without-config", "foo.js");
const StubbedConfig = proxyquire("../../lib/config", { "user-home": homePath });
mockPersonalConfigFileSystem();
mockCWDResponse(projectPath);
const configHelper = new StubbedConfig({ cwd: process.cwd() });
assert.throws(() => {
configHelper.getConfig(filePath);
}, "No ESLint configuration found");
});
it("should not throw an error if no local config and no personal config was found but useEslintrc is false", () => {
const projectPath = getFakeFixturePath("personal-config", "project-without-config"),
homePath = getFakeFixturePath("personal-config", "folder-does-not-exist"),
filePath = getFakeFixturePath("personal-config", "project-without-config", "foo.js");
const StubbedConfig = proxyquire("../../lib/config", { "user-home": homePath });
mockPersonalConfigFileSystem();
mockCWDResponse(projectPath);
const config = new StubbedConfig({
cwd: process.cwd(),
useEslintrc: false
});
assert.doesNotThrow(() => {
config.getConfig(filePath);
}, "No ESLint configuration found");
});
it("should not throw an error if no local config and no personal config was found but rules are specified", () => {
const projectPath = getFakeFixturePath("personal-config", "project-without-config"),
homePath = getFakeFixturePath("personal-config", "folder-does-not-exist"),
filePath = getFakeFixturePath("personal-config", "project-without-config", "foo.js");
const StubbedConfig = proxyquire("../../lib/config", { "user-home": homePath });
mockPersonalConfigFileSystem();
mockCWDResponse(projectPath);
const config = new StubbedConfig({
cwd: process.cwd(),
rules: { quotes: [2, "single"] }
});
assert.doesNotThrow(() => {
config.getConfig(filePath);
}, "No ESLint configuration found");
});
it("should not throw an error if no local config and no personal config was found but baseConfig is specified", () => {
const projectPath = getFakeFixturePath("personal-config", "project-without-config"),
homePath = getFakeFixturePath("personal-config", "folder-does-not-exist"),
filePath = getFakeFixturePath("personal-config", "project-without-config", "foo.js");
const StubbedConfig = proxyquire("../../lib/config", { "user-home": homePath });
mockPersonalConfigFileSystem();
mockCWDResponse(projectPath);
const config = new StubbedConfig({
cwd: process.cwd(),
baseConfig: {}
});
assert.doesNotThrow(() => {
config.getConfig(filePath);
}, "No ESLint configuration found");
});
});
});
describe("Plugin Environments", () => {
it("should load environments from plugin", () => {
const StubbedConfig = createStubbedConfigWithPlugins({
"eslint-plugin-test": {
environments: { example: { globals: { test: false } } }
}
});
const configPath = path.resolve(__dirname, "..", "fixtures", "environments", "plugin.yaml"),
configHelper = new StubbedConfig({
reset: true, configFile: configPath, useEslintrc: false
}),
expected = {
env: {
"test/example": true
},
plugins: ["test"]
},
actual = configHelper.getConfig(configPath);
assertConfigsEqual(actual, expected);
});
});
});
|
function trigger(eventName, data) {
document.dispatchEvent(new document.defaultView.CustomEvent(eventName, {detail: data}));
}
export default trigger;
|
'use strict';
const chai = require('chai'),
expect = chai.expect,
Support = require(__dirname + '/../support'),
DataTypes = require(__dirname + '/../../../lib/data-types'),
sinon = require('sinon');
if (Support.sequelize.dialect.supports.upserts) {
describe(Support.getTestDialectTeaser('Hooks'), () => {
beforeEach(function() {
this.User = this.sequelize.define('User', {
username: {
type: DataTypes.STRING,
allowNull: false,
unique: true //Either Primary Key/Unique Keys should be passed to upsert
},
mood: {
type: DataTypes.ENUM,
values: ['happy', 'sad', 'neutral']
}
});
return this.sequelize.sync({ force: true });
});
describe('#upsert', () => {
describe('on success', () => {
it('should run hooks', function() {
const beforeHook = sinon.spy(),
afterHook = sinon.spy();
this.User.beforeUpsert(beforeHook);
this.User.afterUpsert(afterHook);
return this.User.upsert({username: 'Toni', mood: 'happy'}).then(() => {
expect(beforeHook).to.have.been.calledOnce;
expect(afterHook).to.have.been.calledOnce;
});
});
});
describe('on error', () => {
it('should return an error from before', function() {
const beforeHook = sinon.spy(),
afterHook = sinon.spy();
this.User.beforeUpsert(() => {
beforeHook();
throw new Error('Whoops!');
});
this.User.afterUpsert(afterHook);
return expect(this.User.upsert({username: 'Toni', mood: 'happy'})).to.be.rejected.then(() => {
expect(beforeHook).to.have.been.calledOnce;
expect(afterHook).not.to.have.been.called;
});
});
it('should return an error from after', function() {
const beforeHook = sinon.spy(),
afterHook = sinon.spy();
this.User.beforeUpsert(beforeHook);
this.User.afterUpsert(() => {
afterHook();
throw new Error('Whoops!');
});
return expect(this.User.upsert({username: 'Toni', mood: 'happy'})).to.be.rejected.then(() => {
expect(beforeHook).to.have.been.calledOnce;
expect(afterHook).to.have.been.calledOnce;
});
});
});
describe('preserves changes to values', () => {
it('beforeUpsert', function(){
let hookCalled = 0;
const valuesOriginal = { mood: 'sad', username: 'leafninja' };
this.User.beforeUpsert(values => {
values.mood = 'happy';
hookCalled++;
});
return this.User.upsert(valuesOriginal).then(() => {
expect(valuesOriginal.mood).to.equal('happy');
expect(hookCalled).to.equal(1);
});
});
});
});
});
}
|
window.app.controller('AccountController', ['$scope', '$rootScope', '$http', function ($scope, $rootScope, $http) {
//---- common vars ----//
$scope.token = window.localStorage.getItem('token');
//---- public functions ----//
$scope.saveAccount = function () {
$http.post('/api/account', $scope.account).then(function () {
$scope.success = 'Account updated';
console.log('post:account');
})
.catch(function () {
$scope.error = 'Fail updating';
});
};
$scope.isNotValid = function () {
if ($scope.newPwd !== $scope.again) {
$scope.alert = 'Password does not match';
return true;
} else {
$scope.alert = '';
}
if (!$scope.password || !$scope.newPwd) {
return true;
} else {
$scope.alert = '';
}
};
$scope.changePwd = function () {
var query = {};
query.password = $scope.password;
query.newPwd = $scope.newPwd;
query.again = $scope.again;
$http.post('/api/security', query)
.then(function () {
$scope.success = 'Password updated';
console.log('post:account');
})
.catch(function () {
$scope.error = 'Fail updating';
});
};
//---- private functions ----//
var getAccount = function () {
$http.get('/api/account')
.then(function (data) {
$scope.account = data;
console.log('info:account');
})
.catch(function () {
$scope.error = 'Fail geting account details';
console.log('get:account');
});
};
//---- event listeners ----//
$rootScope.$on('change:model', function (event, data) {
window.location.pathname = '/' + data + '/new';
console.log('change:model');
});
//---- init ---//
if ($scope.token) {
getAccount();
}
}]);
|
/*!
* typeahead.js 0.11.1
* https://github.com/twitter/typeahead.js
* Copyright 2013-2015 Twitter, Inc. and other contributors; Licensed MIT
*/
(function(root, factory) {
if (typeof define === "function" && define.amd) {
define("bloodhound", [ "jquery" ], function(a0) {
return root["Bloodhound"] = factory(a0);
});
} else if (typeof exports === "object") {
module.exports = factory(require("jquery"));
} else {
root["Bloodhound"] = factory(jQuery);
}
})(this, function($) {
var _ = function() {
"use strict";
return {
isMsie: function() {
return /(msie|trident)/i.test(navigator.userAgent) ? navigator.userAgent.match(/(msie |rv:)(\d+(.\d+)?)/i)[2] : false;
},
isBlankString: function(str) {
return !str || /^\s*$/.test(str);
},
escapeRegExChars: function(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
},
isString: function(obj) {
return typeof obj === "string";
},
isNumber: function(obj) {
return typeof obj === "number";
},
isArray: $.isArray,
isFunction: $.isFunction,
isObject: $.isPlainObject,
isUndefined: function(obj) {
return typeof obj === "undefined";
},
isElement: function(obj) {
return !!(obj && obj.nodeType === 1);
},
isJQuery: function(obj) {
return obj instanceof $;
},
toStr: function toStr(s) {
return _.isUndefined(s) || s === null ? "" : s + "";
},
bind: $.proxy,
each: function(collection, cb) {
$.each(collection, reverseArgs);
function reverseArgs(index, value) {
return cb(value, index);
}
},
map: $.map,
filter: $.grep,
every: function(obj, test) {
var result = true;
if (!obj) {
return result;
}
$.each(obj, function(key, val) {
if (!(result = test.call(null, val, key, obj))) {
return false;
}
});
return !!result;
},
some: function(obj, test) {
var result = false;
if (!obj) {
return result;
}
$.each(obj, function(key, val) {
if (result = test.call(null, val, key, obj)) {
return false;
}
});
return !!result;
},
mixin: $.extend,
identity: function(x) {
return x;
},
clone: function(obj) {
return $.extend(true, {}, obj);
},
getIdGenerator: function() {
var counter = 0;
return function() {
return counter++;
};
},
templatify: function templatify(obj) {
return $.isFunction(obj) ? obj : template;
function template() {
return String(obj);
}
},
defer: function(fn) {
setTimeout(fn, 0);
},
debounce: function(func, wait, immediate) {
var timeout, result;
return function() {
var context = this, args = arguments, later, callNow;
later = function() {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
}
};
callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
}
return result;
};
},
throttle: function(func, wait) {
var context, args, timeout, result, previous, later;
previous = 0;
later = function() {
previous = new Date();
timeout = null;
result = func.apply(context, args);
};
return function() {
var now = new Date(), remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0) {
clearTimeout(timeout);
timeout = null;
previous = now;
result = func.apply(context, args);
} else if (!timeout) {
timeout = setTimeout(later, remaining);
}
return result;
};
},
stringify: function(val) {
return _.isString(val) ? val : JSON.stringify(val);
},
noop: function() {}
};
}();
var VERSION = "0.11.1";
var tokenizers = function() {
"use strict";
return {
nonword: nonword,
whitespace: whitespace,
obj: {
nonword: getObjTokenizer(nonword),
whitespace: getObjTokenizer(whitespace)
}
};
function whitespace(str) {
str = _.toStr(str);
return str ? str.split(/\s+/) : [];
}
function nonword(str) {
str = _.toStr(str);
return str ? str.split(/\W+/) : [];
}
function getObjTokenizer(tokenizer) {
return function setKey(keys) {
keys = _.isArray(keys) ? keys : [].slice.call(arguments, 0);
return function tokenize(o) {
var tokens = [];
_.each(keys, function(k) {
tokens = tokens.concat(tokenizer(_.toStr(o[k])));
});
return tokens;
};
};
}
}();
var LruCache = function() {
"use strict";
function LruCache(maxSize) {
this.maxSize = _.isNumber(maxSize) ? maxSize : 100;
this.reset();
if (this.maxSize <= 0) {
this.set = this.get = $.noop;
}
}
_.mixin(LruCache.prototype, {
set: function set(key, val) {
var tailItem = this.list.tail, node;
if (this.size >= this.maxSize) {
this.list.remove(tailItem);
delete this.hash[tailItem.key];
this.size--;
}
if (node = this.hash[key]) {
node.val = val;
this.list.moveToFront(node);
} else {
node = new Node(key, val);
this.list.add(node);
this.hash[key] = node;
this.size++;
}
},
get: function get(key) {
var node = this.hash[key];
if (node) {
this.list.moveToFront(node);
return node.val;
}
},
reset: function reset() {
this.size = 0;
this.hash = {};
this.list = new List();
}
});
function List() {
this.head = this.tail = null;
}
_.mixin(List.prototype, {
add: function add(node) {
if (this.head) {
node.next = this.head;
this.head.prev = node;
}
this.head = node;
this.tail = this.tail || node;
},
remove: function remove(node) {
node.prev ? node.prev.next = node.next : this.head = node.next;
node.next ? node.next.prev = node.prev : this.tail = node.prev;
},
moveToFront: function(node) {
this.remove(node);
this.add(node);
}
});
function Node(key, val) {
this.key = key;
this.val = val;
this.prev = this.next = null;
}
return LruCache;
}();
var PersistentStorage = function() {
"use strict";
var LOCAL_STORAGE;
try {
LOCAL_STORAGE = window.localStorage;
LOCAL_STORAGE.setItem("~~~", "!");
LOCAL_STORAGE.removeItem("~~~");
} catch (err) {
LOCAL_STORAGE = null;
}
function PersistentStorage(namespace, override) {
this.prefix = [ "__", namespace, "__" ].join("");
this.ttlKey = "__ttl__";
this.keyMatcher = new RegExp("^" + _.escapeRegExChars(this.prefix));
this.ls = override || LOCAL_STORAGE;
!this.ls && this._noop();
}
_.mixin(PersistentStorage.prototype, {
_prefix: function(key) {
return this.prefix + key;
},
_ttlKey: function(key) {
return this._prefix(key) + this.ttlKey;
},
_noop: function() {
this.get = this.set = this.remove = this.clear = this.isExpired = _.noop;
},
_safeSet: function(key, val) {
try {
this.ls.setItem(key, val);
} catch (err) {
if (err.name === "QuotaExceededError") {
this.clear();
this._noop();
}
}
},
get: function(key) {
if (this.isExpired(key)) {
this.remove(key);
}
return decode(this.ls.getItem(this._prefix(key)));
},
set: function(key, val, ttl) {
if (_.isNumber(ttl)) {
this._safeSet(this._ttlKey(key), encode(now() + ttl));
} else {
this.ls.removeItem(this._ttlKey(key));
}
return this._safeSet(this._prefix(key), encode(val));
},
remove: function(key) {
this.ls.removeItem(this._ttlKey(key));
this.ls.removeItem(this._prefix(key));
return this;
},
clear: function() {
var i, keys = gatherMatchingKeys(this.keyMatcher);
for (i = keys.length; i--; ) {
this.remove(keys[i]);
}
return this;
},
isExpired: function(key) {
var ttl = decode(this.ls.getItem(this._ttlKey(key)));
return _.isNumber(ttl) && now() > ttl ? true : false;
}
});
return PersistentStorage;
function now() {
return new Date().getTime();
}
function encode(val) {
return JSON.stringify(_.isUndefined(val) ? null : val);
}
function decode(val) {
return $.parseJSON(val);
}
function gatherMatchingKeys(keyMatcher) {
var i, key, keys = [], len = LOCAL_STORAGE.length;
for (i = 0; i < len; i++) {
if ((key = LOCAL_STORAGE.key(i)).match(keyMatcher)) {
keys.push(key.replace(keyMatcher, ""));
}
}
return keys;
}
}();
var Transport = function() {
"use strict";
var pendingRequestsCount = 0, pendingRequests = {}, maxPendingRequests = 6, sharedCache = new LruCache(10);
function Transport(o) {
o = o || {};
this.cancelled = false;
this.lastReq = null;
this._send = o.transport;
this._get = o.limiter ? o.limiter(this._get) : this._get;
this._cache = o.cache === false ? new LruCache(0) : sharedCache;
}
Transport.setMaxPendingRequests = function setMaxPendingRequests(num) {
maxPendingRequests = num;
};
Transport.resetCache = function resetCache() {
sharedCache.reset();
};
_.mixin(Transport.prototype, {
_fingerprint: function fingerprint(o) {
o = o || {};
return o.url + o.type + $.param(o.data || {});
},
_get: function(o, cb) {
var that = this, fingerprint, jqXhr;
fingerprint = this._fingerprint(o);
if (this.cancelled || fingerprint !== this.lastReq) {
return;
}
if (jqXhr = pendingRequests[fingerprint]) {
jqXhr.done(done).fail(fail);
} else if (pendingRequestsCount < maxPendingRequests) {
pendingRequestsCount++;
pendingRequests[fingerprint] = this._send(o).done(done).fail(fail).always(always);
} else {
this.onDeckRequestArgs = [].slice.call(arguments, 0);
}
function done(resp) {
cb(null, resp);
that._cache.set(fingerprint, resp);
}
function fail() {
cb(true);
}
function always() {
pendingRequestsCount--;
delete pendingRequests[fingerprint];
if (that.onDeckRequestArgs) {
that._get.apply(that, that.onDeckRequestArgs);
that.onDeckRequestArgs = null;
}
}
},
get: function(o, cb) {
var resp, fingerprint;
cb = cb || $.noop;
o = _.isString(o) ? {
url: o
} : o || {};
fingerprint = this._fingerprint(o);
this.cancelled = false;
this.lastReq = fingerprint;
if (resp = this._cache.get(fingerprint)) {
cb(null, resp);
} else {
this._get(o, cb);
}
},
cancel: function() {
this.cancelled = true;
}
});
return Transport;
}();
var SearchIndex = window.SearchIndex = function() {
"use strict";
var CHILDREN = "c", IDS = "i";
function SearchIndex(o) {
o = o || {};
if (!o.datumTokenizer || !o.queryTokenizer) {
$.error("datumTokenizer and queryTokenizer are both required");
}
this.identify = o.identify || _.stringify;
this.datumTokenizer = o.datumTokenizer;
this.queryTokenizer = o.queryTokenizer;
this.reset();
}
_.mixin(SearchIndex.prototype, {
bootstrap: function bootstrap(o) {
this.datums = o.datums;
this.trie = o.trie;
},
add: function(data) {
var that = this;
data = _.isArray(data) ? data : [ data ];
_.each(data, function(datum) {
var id, tokens;
that.datums[id = that.identify(datum)] = datum;
tokens = normalizeTokens(that.datumTokenizer(datum));
_.each(tokens, function(token) {
var node, chars, ch;
node = that.trie;
chars = token.split("");
while (ch = chars.shift()) {
node = node[CHILDREN][ch] || (node[CHILDREN][ch] = newNode());
node[IDS].push(id);
}
});
});
},
get: function get(ids) {
var that = this;
return _.map(ids, function(id) {
return that.datums[id];
});
},
search: function search(query) {
var that = this, tokens, matches;
tokens = normalizeTokens(this.queryTokenizer(query));
_.each(tokens, function(token) {
var node, chars, ch, ids;
if (matches && matches.length === 0) {
return false;
}
node = that.trie;
chars = token.split("");
while (node && (ch = chars.shift())) {
node = node[CHILDREN][ch];
}
if (node && chars.length === 0) {
ids = node[IDS].slice(0);
matches = matches ? getIntersection(matches, ids) : ids;
} else {
matches = [];
return false;
}
});
return matches ? _.map(unique(matches), function(id) {
return that.datums[id];
}) : [];
},
all: function all() {
var values = [];
for (var key in this.datums) {
values.push(this.datums[key]);
}
return values;
},
reset: function reset() {
this.datums = {};
this.trie = newNode();
},
serialize: function serialize() {
return {
datums: this.datums,
trie: this.trie
};
}
});
return SearchIndex;
function normalizeTokens(tokens) {
tokens = _.filter(tokens, function(token) {
return !!token;
});
tokens = _.map(tokens, function(token) {
return token.toLowerCase();
});
return tokens;
}
function newNode() {
var node = {};
node[IDS] = [];
node[CHILDREN] = {};
return node;
}
function unique(array) {
var seen = {}, uniques = [];
for (var i = 0, len = array.length; i < len; i++) {
if (!seen[array[i]]) {
seen[array[i]] = true;
uniques.push(array[i]);
}
}
return uniques;
}
function getIntersection(arrayA, arrayB) {
var ai = 0, bi = 0, intersection = [];
arrayA = arrayA.sort();
arrayB = arrayB.sort();
var lenArrayA = arrayA.length, lenArrayB = arrayB.length;
while (ai < lenArrayA && bi < lenArrayB) {
if (arrayA[ai] < arrayB[bi]) {
ai++;
} else if (arrayA[ai] > arrayB[bi]) {
bi++;
} else {
intersection.push(arrayA[ai]);
ai++;
bi++;
}
}
return intersection;
}
}();
var Prefetch = function() {
"use strict";
var keys;
keys = {
data: "data",
protocol: "protocol",
thumbprint: "thumbprint"
};
function Prefetch(o) {
this.url = o.url;
this.ttl = o.ttl;
this.cache = o.cache;
this.prepare = o.prepare;
this.transform = o.transform;
this.transport = o.transport;
this.thumbprint = o.thumbprint;
this.storage = new PersistentStorage(o.cacheKey);
}
_.mixin(Prefetch.prototype, {
_settings: function settings() {
return {
url: this.url,
type: "GET",
dataType: "json"
};
},
store: function store(data) {
if (!this.cache) {
return;
}
this.storage.set(keys.data, data, this.ttl);
this.storage.set(keys.protocol, location.protocol, this.ttl);
this.storage.set(keys.thumbprint, this.thumbprint, this.ttl);
},
fromCache: function fromCache() {
var stored = {}, isExpired;
if (!this.cache) {
return null;
}
stored.data = this.storage.get(keys.data);
stored.protocol = this.storage.get(keys.protocol);
stored.thumbprint = this.storage.get(keys.thumbprint);
isExpired = stored.thumbprint !== this.thumbprint || stored.protocol !== location.protocol;
return stored.data && !isExpired ? stored.data : null;
},
fromNetwork: function(cb) {
var that = this, settings;
if (!cb) {
return;
}
settings = this.prepare(this._settings());
this.transport(settings).fail(onError).done(onResponse);
function onError() {
cb(true);
}
function onResponse(resp) {
cb(null, that.transform(resp));
}
},
clear: function clear() {
this.storage.clear();
return this;
}
});
return Prefetch;
}();
var Remote = function() {
"use strict";
function Remote(o) {
this.url = o.url;
this.prepare = o.prepare;
this.transform = o.transform;
this.transport = new Transport({
cache: o.cache,
limiter: o.limiter,
transport: o.transport
});
}
_.mixin(Remote.prototype, {
_settings: function settings() {
return {
url: this.url,
type: "GET",
dataType: "json"
};
},
get: function get(query, cb) {
var that = this, settings;
if (!cb) {
return;
}
query = query || "";
settings = this.prepare(query, this._settings());
return this.transport.get(settings, onResponse);
function onResponse(err, resp) {
err ? cb([]) : cb(that.transform(resp));
}
},
cancelLastRequest: function cancelLastRequest() {
this.transport.cancel();
}
});
return Remote;
}();
var oParser = function() {
"use strict";
return function parse(o) {
var defaults, sorter;
defaults = {
initialize: true,
identify: _.stringify,
datumTokenizer: null,
queryTokenizer: null,
sufficient: 5,
sorter: null,
local: [],
prefetch: null,
remote: null
};
o = _.mixin(defaults, o || {});
!o.datumTokenizer && $.error("datumTokenizer is required");
!o.queryTokenizer && $.error("queryTokenizer is required");
sorter = o.sorter;
o.sorter = sorter ? function(x) {
return x.sort(sorter);
} : _.identity;
o.local = _.isFunction(o.local) ? o.local() : o.local;
o.prefetch = parsePrefetch(o.prefetch);
o.remote = parseRemote(o.remote);
return o;
};
function parsePrefetch(o) {
var defaults;
if (!o) {
return null;
}
defaults = {
url: null,
ttl: 24 * 60 * 60 * 1e3,
cache: true,
cacheKey: null,
thumbprint: "",
prepare: _.identity,
transform: _.identity,
transport: null
};
o = _.isString(o) ? {
url: o
} : o;
o = _.mixin(defaults, o);
!o.url && $.error("prefetch requires url to be set");
o.transform = o.filter || o.transform;
o.cacheKey = o.cacheKey || o.url;
o.thumbprint = VERSION + o.thumbprint;
o.transport = o.transport ? callbackToDeferred(o.transport) : $.ajax;
return o;
}
function parseRemote(o) {
var defaults;
if (!o) {
return;
}
defaults = {
url: null,
cache: true,
prepare: null,
replace: null,
wildcard: null,
limiter: null,
rateLimitBy: "debounce",
rateLimitWait: 300,
transform: _.identity,
transport: null
};
o = _.isString(o) ? {
url: o
} : o;
o = _.mixin(defaults, o);
!o.url && $.error("remote requires url to be set");
o.transform = o.filter || o.transform;
o.prepare = toRemotePrepare(o);
o.limiter = toLimiter(o);
o.transport = o.transport ? callbackToDeferred(o.transport) : $.ajax;
delete o.replace;
delete o.wildcard;
delete o.rateLimitBy;
delete o.rateLimitWait;
return o;
}
function toRemotePrepare(o) {
var prepare, replace, wildcard;
prepare = o.prepare;
replace = o.replace;
wildcard = o.wildcard;
if (prepare) {
return prepare;
}
if (replace) {
prepare = prepareByReplace;
} else if (o.wildcard) {
prepare = prepareByWildcard;
} else {
prepare = idenityPrepare;
}
return prepare;
function prepareByReplace(query, settings) {
settings.url = replace(settings.url, query);
return settings;
}
function prepareByWildcard(query, settings) {
settings.url = settings.url.replace(wildcard, encodeURIComponent(query));
return settings;
}
function idenityPrepare(query, settings) {
return settings;
}
}
function toLimiter(o) {
var limiter, method, wait;
limiter = o.limiter;
method = o.rateLimitBy;
wait = o.rateLimitWait;
if (!limiter) {
limiter = /^throttle$/i.test(method) ? throttle(wait) : debounce(wait);
}
return limiter;
function debounce(wait) {
return function debounce(fn) {
return _.debounce(fn, wait);
};
}
function throttle(wait) {
return function throttle(fn) {
return _.throttle(fn, wait);
};
}
}
function callbackToDeferred(fn) {
return function wrapper(o) {
var deferred = $.Deferred();
fn(o, onSuccess, onError);
return deferred;
function onSuccess(resp) {
_.defer(function() {
deferred.resolve(resp);
});
}
function onError(err) {
_.defer(function() {
deferred.reject(err);
});
}
};
}
}();
var Bloodhound = function() {
"use strict";
var old;
old = window && window.Bloodhound;
function Bloodhound(o) {
o = oParser(o);
this.sorter = o.sorter;
this.identify = o.identify;
this.sufficient = o.sufficient;
this.local = o.local;
this.remote = o.remote ? new Remote(o.remote) : null;
this.prefetch = o.prefetch ? new Prefetch(o.prefetch) : null;
this.index = new SearchIndex({
identify: this.identify,
datumTokenizer: o.datumTokenizer,
queryTokenizer: o.queryTokenizer
});
o.initialize !== false && this.initialize();
}
Bloodhound.noConflict = function noConflict() {
window && (window.Bloodhound = old);
return Bloodhound;
};
Bloodhound.tokenizers = tokenizers;
_.mixin(Bloodhound.prototype, {
__ttAdapter: function ttAdapter() {
var that = this;
return this.remote ? withAsync : withoutAsync;
function withAsync(query, sync, async) {
return that.search(query, sync, async);
}
function withoutAsync(query, sync) {
return that.search(query, sync);
}
},
_loadPrefetch: function loadPrefetch() {
var that = this, deferred, serialized;
deferred = $.Deferred();
if (!this.prefetch) {
deferred.resolve();
} else if (serialized = this.prefetch.fromCache()) {
this.index.bootstrap(serialized);
deferred.resolve();
} else {
this.prefetch.fromNetwork(done);
}
return deferred.promise();
function done(err, data) {
if (err) {
return deferred.reject();
}
that.add(data);
that.prefetch.store(that.index.serialize());
deferred.resolve();
}
},
_initialize: function initialize() {
var that = this, deferred;
this.clear();
(this.initPromise = this._loadPrefetch()).done(addLocalToIndex);
return this.initPromise;
function addLocalToIndex() {
that.add(that.local);
}
},
initialize: function initialize(force) {
return !this.initPromise || force ? this._initialize() : this.initPromise;
},
add: function add(data) {
this.index.add(data);
return this;
},
get: function get(ids) {
ids = _.isArray(ids) ? ids : [].slice.call(arguments);
return this.index.get(ids);
},
search: function search(query, sync, async) {
var that = this, local;
local = this.sorter(this.index.search(query));
sync(this.remote ? local.slice() : local);
if (this.remote && local.length < this.sufficient) {
this.remote.get(query, processRemote);
} else if (this.remote) {
this.remote.cancelLastRequest();
}
return this;
function processRemote(remote) {
var nonDuplicates = [];
_.each(remote, function(r) {
!_.some(local, function(l) {
return that.identify(r) === that.identify(l);
}) && nonDuplicates.push(r);
});
async && async(nonDuplicates);
}
},
all: function all() {
return this.index.all();
},
clear: function clear() {
this.index.reset();
return this;
},
clearPrefetchCache: function clearPrefetchCache() {
this.prefetch && this.prefetch.clear();
return this;
},
clearRemoteCache: function clearRemoteCache() {
Transport.resetCache();
return this;
},
ttAdapter: function ttAdapter() {
return this.__ttAdapter();
}
});
return Bloodhound;
}();
return Bloodhound;
});
(function(root, factory) {
if (typeof define === "function" && define.amd) {
define("typeahead.js", [ "jquery" ], function(a0) {
return factory(a0);
});
} else if (typeof exports === "object") {
module.exports = factory(require("jquery"));
} else {
factory(jQuery);
}
})(this, function($) {
var _ = function() {
"use strict";
return {
isMsie: function() {
return /(msie|trident)/i.test(navigator.userAgent) ? navigator.userAgent.match(/(msie |rv:)(\d+(.\d+)?)/i)[2] : false;
},
isBlankString: function(str) {
return !str || /^\s*$/.test(str);
},
escapeRegExChars: function(str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, "\\$&");
},
isString: function(obj) {
return typeof obj === "string";
},
isNumber: function(obj) {
return typeof obj === "number";
},
isArray: $.isArray,
isFunction: $.isFunction,
isObject: $.isPlainObject,
isUndefined: function(obj) {
return typeof obj === "undefined";
},
isElement: function(obj) {
return !!(obj && obj.nodeType === 1);
},
isJQuery: function(obj) {
return obj instanceof $;
},
toStr: function toStr(s) {
return _.isUndefined(s) || s === null ? "" : s + "";
},
bind: $.proxy,
each: function(collection, cb) {
$.each(collection, reverseArgs);
function reverseArgs(index, value) {
return cb(value, index);
}
},
map: $.map,
filter: $.grep,
every: function(obj, test) {
var result = true;
if (!obj) {
return result;
}
$.each(obj, function(key, val) {
if (!(result = test.call(null, val, key, obj))) {
return false;
}
});
return !!result;
},
some: function(obj, test) {
var result = false;
if (!obj) {
return result;
}
$.each(obj, function(key, val) {
if (result = test.call(null, val, key, obj)) {
return false;
}
});
return !!result;
},
mixin: $.extend,
identity: function(x) {
return x;
},
clone: function(obj) {
return $.extend(true, {}, obj);
},
getIdGenerator: function() {
var counter = 0;
return function() {
return counter++;
};
},
templatify: function templatify(obj) {
return $.isFunction(obj) ? obj : template;
function template() {
return String(obj);
}
},
defer: function(fn) {
setTimeout(fn, 0);
},
debounce: function(func, wait, immediate) {
var timeout, result;
return function() {
var context = this, args = arguments, later, callNow;
later = function() {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
}
};
callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
}
return result;
};
},
throttle: function(func, wait) {
var context, args, timeout, result, previous, later;
previous = 0;
later = function() {
previous = new Date();
timeout = null;
result = func.apply(context, args);
};
return function() {
var now = new Date(), remaining = wait - (now - previous);
context = this;
args = arguments;
if (remaining <= 0) {
clearTimeout(timeout);
timeout = null;
previous = now;
result = func.apply(context, args);
} else if (!timeout) {
timeout = setTimeout(later, remaining);
}
return result;
};
},
stringify: function(val) {
return _.isString(val) ? val : JSON.stringify(val);
},
noop: function() {}
};
}();
var WWW = function() {
"use strict";
var defaultClassNames = {
wrapper: "twitter-typeahead",
input: "tt-input",
hint: "tt-hint",
menu: "tt-menu",
dataset: "tt-dataset",
suggestion: "tt-suggestion",
selectable: "tt-selectable",
empty: "tt-empty",
open: "tt-open",
cursor: "tt-cursor",
highlight: "tt-highlight"
};
return build;
function build(o) {
var www, classes;
classes = _.mixin({}, defaultClassNames, o);
www = {
css: buildCss(),
classes: classes,
html: buildHtml(classes),
selectors: buildSelectors(classes)
};
return {
css: www.css,
html: www.html,
classes: www.classes,
selectors: www.selectors,
mixin: function(o) {
_.mixin(o, www);
}
};
}
function buildHtml(c) {
return {
wrapper: '<span class="' + c.wrapper + '"></span>',
menu: '<div class="' + c.menu + '"></div>'
};
}
function buildSelectors(classes) {
var selectors = {};
_.each(classes, function(v, k) {
selectors[k] = "." + v;
});
return selectors;
}
function buildCss() {
var css = {
wrapper: {
position: "relative",
display: "inline-block"
},
hint: {
position: "absolute",
top: "0",
left: "0",
borderColor: "transparent",
boxShadow: "none",
opacity: "1"
},
input: {
position: "relative",
verticalAlign: "top",
backgroundColor: "transparent"
},
inputWithNoHint: {
position: "relative",
verticalAlign: "top"
},
menu: {
position: "absolute",
top: "100%",
left: "0",
zIndex: "100",
display: "none"
},
ltr: {
left: "0",
right: "auto"
},
rtl: {
left: "auto",
right: " 0"
}
};
if (_.isMsie()) {
_.mixin(css.input, {
backgroundImage: "url(data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7)"
});
}
return css;
}
}();
var EventBus = function() {
"use strict";
var namespace, deprecationMap;
namespace = "typeahead:";
deprecationMap = {
render: "rendered",
cursorchange: "cursorchanged",
select: "selected",
autocomplete: "autocompleted"
};
function EventBus(o) {
if (!o || !o.el) {
$.error("EventBus initialized without el");
}
this.$el = $(o.el);
}
_.mixin(EventBus.prototype, {
_trigger: function(type, args) {
var $e;
$e = $.Event(namespace + type);
(args = args || []).unshift($e);
this.$el.trigger.apply(this.$el, args);
return $e;
},
before: function(type) {
var args, $e;
args = [].slice.call(arguments, 1);
$e = this._trigger("before" + type, args);
return $e.isDefaultPrevented();
},
trigger: function(type) {
var deprecatedType;
this._trigger(type, [].slice.call(arguments, 1));
if (deprecatedType = deprecationMap[type]) {
this._trigger(deprecatedType, [].slice.call(arguments, 1));
}
}
});
return EventBus;
}();
var EventEmitter = function() {
"use strict";
var splitter = /\s+/, nextTick = getNextTick();
return {
onSync: onSync,
onAsync: onAsync,
off: off,
trigger: trigger
};
function on(method, types, cb, context) {
var type;
if (!cb) {
return this;
}
types = types.split(splitter);
cb = context ? bindContext(cb, context) : cb;
this._callbacks = this._callbacks || {};
while (type = types.shift()) {
this._callbacks[type] = this._callbacks[type] || {
sync: [],
async: []
};
this._callbacks[type][method].push(cb);
}
return this;
}
function onAsync(types, cb, context) {
return on.call(this, "async", types, cb, context);
}
function onSync(types, cb, context) {
return on.call(this, "sync", types, cb, context);
}
function off(types) {
var type;
if (!this._callbacks) {
return this;
}
types = types.split(splitter);
while (type = types.shift()) {
delete this._callbacks[type];
}
return this;
}
function trigger(types) {
var type, callbacks, args, syncFlush, asyncFlush;
if (!this._callbacks) {
return this;
}
types = types.split(splitter);
args = [].slice.call(arguments, 1);
while ((type = types.shift()) && (callbacks = this._callbacks[type])) {
syncFlush = getFlush(callbacks.sync, this, [ type ].concat(args));
asyncFlush = getFlush(callbacks.async, this, [ type ].concat(args));
syncFlush() && nextTick(asyncFlush);
}
return this;
}
function getFlush(callbacks, context, args) {
return flush;
function flush() {
var cancelled;
for (var i = 0, len = callbacks.length; !cancelled && i < len; i += 1) {
cancelled = callbacks[i].apply(context, args) === false;
}
return !cancelled;
}
}
function getNextTick() {
var nextTickFn;
if (window.setImmediate) {
nextTickFn = function nextTickSetImmediate(fn) {
setImmediate(function() {
fn();
});
};
} else {
nextTickFn = function nextTickSetTimeout(fn) {
setTimeout(function() {
fn();
}, 0);
};
}
return nextTickFn;
}
function bindContext(fn, context) {
return fn.bind ? fn.bind(context) : function() {
fn.apply(context, [].slice.call(arguments, 0));
};
}
}();
var highlight = function(doc) {
"use strict";
var defaults = {
node: null,
pattern: null,
tagName: "strong",
className: null,
wordsOnly: false,
caseSensitive: false
};
return function hightlight(o) {
var regex;
o = _.mixin({}, defaults, o);
if (!o.node || !o.pattern) {
return;
}
o.pattern = _.isArray(o.pattern) ? o.pattern : [ o.pattern ];
regex = getRegex(o.pattern, o.caseSensitive, o.wordsOnly);
traverse(o.node, hightlightTextNode);
function hightlightTextNode(textNode) {
var match, patternNode, wrapperNode;
if (match = regex.exec(textNode.data)) {
wrapperNode = doc.createElement(o.tagName);
o.className && (wrapperNode.className = o.className);
patternNode = textNode.splitText(match.index);
patternNode.splitText(match[0].length);
wrapperNode.appendChild(patternNode.cloneNode(true));
textNode.parentNode.replaceChild(wrapperNode, patternNode);
}
return !!match;
}
function traverse(el, hightlightTextNode) {
var childNode, TEXT_NODE_TYPE = 3;
for (var i = 0; i < el.childNodes.length; i++) {
childNode = el.childNodes[i];
if (childNode.nodeType === TEXT_NODE_TYPE) {
i += hightlightTextNode(childNode) ? 1 : 0;
} else {
traverse(childNode, hightlightTextNode);
}
}
}
};
function getRegex(patterns, caseSensitive, wordsOnly) {
var escapedPatterns = [], regexStr;
for (var i = 0, len = patterns.length; i < len; i++) {
escapedPatterns.push(_.escapeRegExChars(patterns[i]));
}
regexStr = wordsOnly ? "\\b(" + escapedPatterns.join("|") + ")\\b" : "(" + escapedPatterns.join("|") + ")";
return caseSensitive ? new RegExp(regexStr) : new RegExp(regexStr, "i");
}
}(window.document);
var Input = function() {
"use strict";
var specialKeyCodeMap;
specialKeyCodeMap = {
9: "tab",
27: "esc",
37: "left",
39: "right",
13: "enter",
38: "up",
40: "down"
};
function Input(o, www) {
o = o || {};
if (!o.input) {
$.error("input is missing");
}
www.mixin(this);
this.$hint = $(o.hint);
this.$input = $(o.input);
this.query = this.$input.val();
this.queryWhenFocused = this.hasFocus() ? this.query : null;
this.$overflowHelper = buildOverflowHelper(this.$input);
this._checkLanguageDirection();
if (this.$hint.length === 0) {
this.setHint = this.getHint = this.clearHint = this.clearHintIfInvalid = _.noop;
}
}
Input.normalizeQuery = function(str) {
return _.toStr(str).replace(/^\s*/g, "").replace(/\s{2,}/g, " ");
};
_.mixin(Input.prototype, EventEmitter, {
_onBlur: function onBlur() {
this.resetInputValue();
this.trigger("blurred");
},
_onFocus: function onFocus() {
this.queryWhenFocused = this.query;
this.trigger("focused");
},
_onKeydown: function onKeydown($e) {
var keyName = specialKeyCodeMap[$e.which || $e.keyCode];
this._managePreventDefault(keyName, $e);
if (keyName && this._shouldTrigger(keyName, $e)) {
this.trigger(keyName + "Keyed", $e);
}
},
_onInput: function onInput() {
this._setQuery(this.getInputValue());
this.clearHintIfInvalid();
this._checkLanguageDirection();
},
_managePreventDefault: function managePreventDefault(keyName, $e) {
var preventDefault;
switch (keyName) {
case "up":
case "down":
preventDefault = !withModifier($e);
break;
default:
preventDefault = false;
}
preventDefault && $e.preventDefault();
},
_shouldTrigger: function shouldTrigger(keyName, $e) {
var trigger;
switch (keyName) {
case "tab":
trigger = !withModifier($e);
break;
default:
trigger = true;
}
return trigger;
},
_checkLanguageDirection: function checkLanguageDirection() {
var dir = (this.$input.css("direction") || "ltr").toLowerCase();
if (this.dir !== dir) {
this.dir = dir;
this.$hint.attr("dir", dir);
this.trigger("langDirChanged", dir);
}
},
_setQuery: function setQuery(val, silent) {
var areEquivalent, hasDifferentWhitespace;
areEquivalent = areQueriesEquivalent(val, this.query);
hasDifferentWhitespace = areEquivalent ? this.query.length !== val.length : false;
this.query = val;
if (!silent && !areEquivalent) {
this.trigger("queryChanged", this.query);
} else if (!silent && hasDifferentWhitespace) {
this.trigger("whitespaceChanged", this.query);
}
},
bind: function() {
var that = this, onBlur, onFocus, onKeydown, onInput;
onBlur = _.bind(this._onBlur, this);
onFocus = _.bind(this._onFocus, this);
onKeydown = _.bind(this._onKeydown, this);
onInput = _.bind(this._onInput, this);
this.$input.on("blur.tt", onBlur).on("focus.tt", onFocus).on("keydown.tt", onKeydown);
if (!_.isMsie() || _.isMsie() > 9) {
this.$input.on("input.tt", onInput);
} else {
this.$input.on("keydown.tt keypress.tt cut.tt paste.tt", function($e) {
if (specialKeyCodeMap[$e.which || $e.keyCode]) {
return;
}
_.defer(_.bind(that._onInput, that, $e));
});
}
return this;
},
focus: function focus() {
this.$input.focus();
},
blur: function blur() {
this.$input.blur();
},
getLangDir: function getLangDir() {
return this.dir;
},
getQuery: function getQuery() {
return this.query || "";
},
setQuery: function setQuery(val, silent) {
this.setInputValue(val);
this._setQuery(val, silent);
},
hasQueryChangedSinceLastFocus: function hasQueryChangedSinceLastFocus() {
return this.query !== this.queryWhenFocused;
},
getInputValue: function getInputValue() {
return this.$input.val();
},
setInputValue: function setInputValue(value) {
this.$input.val(value);
this.clearHintIfInvalid();
this._checkLanguageDirection();
},
resetInputValue: function resetInputValue() {
this.setInputValue(this.query);
},
getHint: function getHint() {
return this.$hint.val();
},
setHint: function setHint(value) {
this.$hint.val(value);
},
clearHint: function clearHint() {
this.setHint("");
},
clearHintIfInvalid: function clearHintIfInvalid() {
var val, hint, valIsPrefixOfHint, isValid;
val = this.getInputValue();
hint = this.getHint();
valIsPrefixOfHint = val !== hint && hint.indexOf(val) === 0;
isValid = val !== "" && valIsPrefixOfHint && !this.hasOverflow();
!isValid && this.clearHint();
},
hasFocus: function hasFocus() {
return this.$input.is(":focus");
},
hasOverflow: function hasOverflow() {
var constraint = this.$input.width() - 2;
this.$overflowHelper.text(this.getInputValue());
return this.$overflowHelper.width() >= constraint;
},
isCursorAtEnd: function() {
var valueLength, selectionStart, range;
valueLength = this.$input.val().length;
selectionStart = this.$input[0].selectionStart;
if (_.isNumber(selectionStart)) {
return selectionStart === valueLength;
} else if (document.selection) {
range = document.selection.createRange();
range.moveStart("character", -valueLength);
return valueLength === range.text.length;
}
return true;
},
destroy: function destroy() {
this.$hint.off(".tt");
this.$input.off(".tt");
this.$overflowHelper.remove();
this.$hint = this.$input = this.$overflowHelper = $("<div>");
}
});
return Input;
function buildOverflowHelper($input) {
return $('<pre aria-hidden="true"></pre>').css({
position: "absolute",
visibility: "hidden",
whiteSpace: "pre",
fontFamily: $input.css("font-family"),
fontSize: $input.css("font-size"),
fontStyle: $input.css("font-style"),
fontVariant: $input.css("font-variant"),
fontWeight: $input.css("font-weight"),
wordSpacing: $input.css("word-spacing"),
letterSpacing: $input.css("letter-spacing"),
textIndent: $input.css("text-indent"),
textRendering: $input.css("text-rendering"),
textTransform: $input.css("text-transform")
}).insertAfter($input);
}
function areQueriesEquivalent(a, b) {
return Input.normalizeQuery(a) === Input.normalizeQuery(b);
}
function withModifier($e) {
return $e.altKey || $e.ctrlKey || $e.metaKey || $e.shiftKey;
}
}();
var Dataset = function() {
"use strict";
var keys, nameGenerator;
keys = {
val: "tt-selectable-display",
obj: "tt-selectable-object"
};
nameGenerator = _.getIdGenerator();
function Dataset(o, www) {
o = o || {};
o.templates = o.templates || {};
o.templates.notFound = o.templates.notFound || o.templates.empty;
if (!o.source) {
$.error("missing source");
}
if (!o.node) {
$.error("missing node");
}
if (o.name && !isValidName(o.name)) {
$.error("invalid dataset name: " + o.name);
}
www.mixin(this);
this.highlight = !!o.highlight;
this.name = o.name || nameGenerator();
this.limit = o.limit || 5;
this.displayFn = getDisplayFn(o.display || o.displayKey);
this.templates = getTemplates(o.templates, this.displayFn);
this.source = o.source.__ttAdapter ? o.source.__ttAdapter() : o.source;
this.async = _.isUndefined(o.async) ? this.source.length > 2 : !!o.async;
this._resetLastSuggestion();
this.$el = $(o.node).addClass(this.classes.dataset).addClass(this.classes.dataset + "-" + this.name);
}
Dataset.extractData = function extractData(el) {
var $el = $(el);
if ($el.data(keys.obj)) {
return {
val: $el.data(keys.val) || "",
obj: $el.data(keys.obj) || null
};
}
return null;
};
_.mixin(Dataset.prototype, EventEmitter, {
_overwrite: function overwrite(query, suggestions) {
suggestions = suggestions || [];
if (suggestions.length) {
this._renderSuggestions(query, suggestions);
} else if (this.async && this.templates.pending) {
this._renderPending(query);
} else if (!this.async && this.templates.notFound) {
this._renderNotFound(query);
} else {
this._empty();
}
this.trigger("rendered", this.name, suggestions, false);
},
_append: function append(query, suggestions) {
suggestions = suggestions || [];
if (suggestions.length && this.$lastSuggestion.length) {
this._appendSuggestions(query, suggestions);
} else if (suggestions.length) {
this._renderSuggestions(query, suggestions);
} else if (!this.$lastSuggestion.length && this.templates.notFound) {
this._renderNotFound(query);
}
this.trigger("rendered", this.name, suggestions, true);
},
_renderSuggestions: function renderSuggestions(query, suggestions) {
var $fragment;
$fragment = this._getSuggestionsFragment(query, suggestions);
this.$lastSuggestion = $fragment.children().last();
this.$el.html($fragment).prepend(this._getHeader(query, suggestions)).append(this._getFooter(query, suggestions));
},
_appendSuggestions: function appendSuggestions(query, suggestions) {
var $fragment, $lastSuggestion;
$fragment = this._getSuggestionsFragment(query, suggestions);
$lastSuggestion = $fragment.children().last();
this.$lastSuggestion.after($fragment);
this.$lastSuggestion = $lastSuggestion;
},
_renderPending: function renderPending(query) {
var template = this.templates.pending;
this._resetLastSuggestion();
// *** appabse_change *** 2015/8/15 - start
// template && this.$el.html(template({
// query: query,
// dataset: this.name
// }));
// *** appabse_change *** 2015/8/15 - end
},
_renderNotFound: function renderNotFound(query) {
var template = this.templates.notFound;
this._resetLastSuggestion();
template && this.$el.html(template({
query: query,
dataset: this.name
}));
},
_empty: function empty() {
this.$el.empty();
this._resetLastSuggestion();
},
_getSuggestionsFragment: function getSuggestionsFragment(query, suggestions) {
var that = this, fragment;
fragment = document.createDocumentFragment();
_.each(suggestions, function getSuggestionNode(suggestion) {
var $el, context;
context = that._injectQuery(query, suggestion);
$el = $(that.templates.suggestion(context)).data(keys.obj, suggestion).data(keys.val, that.displayFn(suggestion)).addClass(that.classes.suggestion + " " + that.classes.selectable);
fragment.appendChild($el[0]);
});
this.highlight && highlight({
className: this.classes.highlight,
node: fragment,
pattern: query
});
return $(fragment);
},
_getFooter: function getFooter(query, suggestions) {
return this.templates.footer ? this.templates.footer({
query: query,
suggestions: suggestions,
dataset: this.name
}) : null;
},
_getHeader: function getHeader(query, suggestions) {
return this.templates.header ? this.templates.header({
query: query,
suggestions: suggestions,
dataset: this.name
}) : null;
},
_resetLastSuggestion: function resetLastSuggestion() {
this.$lastSuggestion = $();
},
_injectQuery: function injectQuery(query, obj) {
return _.isObject(obj) ? _.mixin({
_query: query
}, obj) : obj;
},
update: function update(query) {
var that = this, canceled = false, syncCalled = false, rendered = 0;
this.cancel();
this.cancel = function cancel() {
canceled = true;
that.cancel = $.noop;
that.async && that.trigger("asyncCanceled", query);
};
this.source(query, sync, async);
!syncCalled && sync([]);
function sync(suggestions) {
if (syncCalled) {
return;
}
syncCalled = true;
suggestions = (suggestions || []).slice(0, that.limit);
rendered = suggestions.length;
that._overwrite(query, suggestions);
if (rendered < that.limit && that.async) {
that.trigger("asyncRequested", query);
}
}
function async(suggestions) {
suggestions = suggestions || [];
if (!canceled && rendered < that.limit) {
that.cancel = $.noop;
rendered += suggestions.length;
that._append(query, suggestions.slice(0, that.limit - rendered));
that.async && that.trigger("asyncReceived", query);
}
}
},
cancel: $.noop,
clear: function clear() {
this._empty();
this.cancel();
this.trigger("cleared");
},
isEmpty: function isEmpty() {
return this.$el.is(":empty");
},
destroy: function destroy() {
this.$el = $("<div>");
}
});
return Dataset;
function getDisplayFn(display) {
display = display || _.stringify;
return _.isFunction(display) ? display : displayFn;
function displayFn(obj) {
return obj[display];
}
}
function getTemplates(templates, displayFn) {
return {
notFound: templates.notFound && _.templatify(templates.notFound),
pending: templates.pending && _.templatify(templates.pending),
header: templates.header && _.templatify(templates.header),
footer: templates.footer && _.templatify(templates.footer),
suggestion: templates.suggestion || suggestionTemplate
};
function suggestionTemplate(context) {
return $("<div>").text(displayFn(context));
}
}
function isValidName(str) {
return /^[_a-zA-Z0-9-]+$/.test(str);
}
}();
var Menu = function() {
"use strict";
function Menu(o, www) {
var that = this;
o = o || {};
if (!o.node) {
$.error("node is required");
}
www.mixin(this);
this.$node = $(o.node);
this.query = null;
this.datasets = _.map(o.datasets, initializeDataset);
function initializeDataset(oDataset) {
var node = that.$node.find(oDataset.node).first();
oDataset.node = node.length ? node : $("<div>").appendTo(that.$node);
return new Dataset(oDataset, www);
}
}
_.mixin(Menu.prototype, EventEmitter, {
_onSelectableClick: function onSelectableClick($e) {
// *** appabse_change *** 2015/8/15 - start
//this.trigger("selectableClicked", $($e.currentTarget));
// *** appabse_change *** 2015/8/15 - end
},
_onRendered: function onRendered(type, dataset, suggestions, async) {
this.$node.toggleClass(this.classes.empty, this._allDatasetsEmpty());
this.trigger("datasetRendered", dataset, suggestions, async);
},
_onCleared: function onCleared() {
this.$node.toggleClass(this.classes.empty, this._allDatasetsEmpty());
this.trigger("datasetCleared");
},
_propagate: function propagate() {
this.trigger.apply(this, arguments);
},
_allDatasetsEmpty: function allDatasetsEmpty() {
return _.every(this.datasets, isDatasetEmpty);
function isDatasetEmpty(dataset) {
return dataset.isEmpty();
}
},
_getSelectables: function getSelectables() {
return this.$node.find(this.selectors.selectable);
},
_removeCursor: function _removeCursor() {
var $selectable = this.getActiveSelectable();
$selectable && $selectable.removeClass(this.classes.cursor);
},
_ensureVisible: function ensureVisible($el) {
var elTop, elBottom, nodeScrollTop, nodeHeight;
elTop = $el.position().top;
elBottom = elTop + $el.outerHeight(true);
nodeScrollTop = this.$node.scrollTop();
nodeHeight = this.$node.height() + parseInt(this.$node.css("paddingTop"), 10) + parseInt(this.$node.css("paddingBottom"), 10);
if (elTop < 0) {
this.$node.scrollTop(nodeScrollTop + elTop);
} else if (nodeHeight < elBottom) {
this.$node.scrollTop(nodeScrollTop + (elBottom - nodeHeight));
}
},
bind: function() {
var that = this, onSelectableClick;
onSelectableClick = _.bind(this._onSelectableClick, this);
this.$node.on("click.tt", this.selectors.selectable, onSelectableClick);
_.each(this.datasets, function(dataset) {
dataset.onSync("asyncRequested", that._propagate, that).onSync("asyncCanceled", that._propagate, that).onSync("asyncReceived", that._propagate, that).onSync("rendered", that._onRendered, that).onSync("cleared", that._onCleared, that);
});
return this;
},
isOpen: function isOpen() {
return this.$node.hasClass(this.classes.open);
},
open: function open() {
this.$node.addClass(this.classes.open);
},
close: function close() {
this.$node.removeClass(this.classes.open);
this._removeCursor();
},
setLanguageDirection: function setLanguageDirection(dir) {
this.$node.attr("dir", dir);
},
selectableRelativeToCursor: function selectableRelativeToCursor(delta) {
var $selectables, $oldCursor, oldIndex, newIndex;
$oldCursor = this.getActiveSelectable();
$selectables = this._getSelectables();
oldIndex = $oldCursor ? $selectables.index($oldCursor) : -1;
newIndex = oldIndex + delta;
newIndex = (newIndex + 1) % ($selectables.length + 1) - 1;
newIndex = newIndex < -1 ? $selectables.length - 1 : newIndex;
return newIndex === -1 ? null : $selectables.eq(newIndex);
},
setCursor: function setCursor($selectable) {
this._removeCursor();
if ($selectable = $selectable && $selectable.first()) {
$selectable.addClass(this.classes.cursor);
this._ensureVisible($selectable);
}
},
getSelectableData: function getSelectableData($el) {
return $el && $el.length ? Dataset.extractData($el) : null;
},
getActiveSelectable: function getActiveSelectable() {
var $selectable = this._getSelectables().filter(this.selectors.cursor).first();
return $selectable.length ? $selectable : null;
},
getTopSelectable: function getTopSelectable() {
var $selectable = this._getSelectables().first();
return $selectable.length ? $selectable : null;
},
update: function update(query) {
var isValidUpdate = query !== this.query;
if (isValidUpdate) {
this.query = query;
_.each(this.datasets, updateDataset);
}
return isValidUpdate;
function updateDataset(dataset) {
dataset.update(query);
}
},
empty: function empty() {
_.each(this.datasets, clearDataset);
this.query = null;
this.$node.addClass(this.classes.empty);
function clearDataset(dataset) {
dataset.clear();
}
},
destroy: function destroy() {
this.$node.off(".tt");
this.$node = $("<div>");
_.each(this.datasets, destroyDataset);
function destroyDataset(dataset) {
dataset.destroy();
}
}
});
return Menu;
}();
var DefaultMenu = function() {
"use strict";
var s = Menu.prototype;
function DefaultMenu() {
Menu.apply(this, [].slice.call(arguments, 0));
}
_.mixin(DefaultMenu.prototype, Menu.prototype, {
open: function open() {
!this._allDatasetsEmpty() && this._show();
return s.open.apply(this, [].slice.call(arguments, 0));
},
close: function close() {
this._hide();
return s.close.apply(this, [].slice.call(arguments, 0));
},
_onRendered: function onRendered() {
if (this._allDatasetsEmpty()) {
this._hide();
} else {
this.isOpen() && this._show();
}
return s._onRendered.apply(this, [].slice.call(arguments, 0));
},
_onCleared: function onCleared() {
if (this._allDatasetsEmpty()) {
this._hide();
} else {
this.isOpen() && this._show();
}
return s._onCleared.apply(this, [].slice.call(arguments, 0));
},
setLanguageDirection: function setLanguageDirection(dir) {
this.$node.css(dir === "ltr" ? this.css.ltr : this.css.rtl);
return s.setLanguageDirection.apply(this, [].slice.call(arguments, 0));
},
_hide: function hide() {
this.$node.hide();
},
_show: function show() {
this.$node.css("display", "block");
}
});
return DefaultMenu;
}();
var Typeahead = function() {
"use strict";
function Typeahead(o, www) {
var onFocused, onBlurred, onEnterKeyed, onTabKeyed, onEscKeyed, onUpKeyed, onDownKeyed, onLeftKeyed, onRightKeyed, onQueryChanged, onWhitespaceChanged;
o = o || {};
if (!o.input) {
$.error("missing input");
}
if (!o.menu) {
$.error("missing menu");
}
if (!o.eventBus) {
$.error("missing event bus");
}
www.mixin(this);
this.eventBus = o.eventBus;
this.minLength = _.isNumber(o.minLength) ? o.minLength : 1;
this.input = o.input;
this.menu = o.menu;
this.enabled = true;
this.active = false;
this.input.hasFocus() && this.activate();
this.dir = this.input.getLangDir();
this._hacks();
this.menu.bind().onSync("selectableClicked", this._onSelectableClicked, this).onSync("asyncRequested", this._onAsyncRequested, this).onSync("asyncCanceled", this._onAsyncCanceled, this).onSync("asyncReceived", this._onAsyncReceived, this).onSync("datasetRendered", this._onDatasetRendered, this).onSync("datasetCleared", this._onDatasetCleared, this);
onFocused = c(this, "activate", "open", "_onFocused");
onBlurred = c(this, "deactivate", "_onBlurred");
onEnterKeyed = c(this, "isActive", "isOpen", "_onEnterKeyed");
// *** appabse_change *** 2015/8/30 - start
// onTabKeyed = c(this, "isActive", "isOpen", "_onTabKeyed");
// onRightKeyed = c(this, "isActive", "isOpen", "_onRightKeyed");
// onUpKeyed = c(this, "isActive", "open", "_onUpKeyed");
// onDownKeyed = c(this, "isActive", "open", "_onDownKeyed");
// onLeftKeyed = c(this, "isActive", "isOpen", "_onLeftKeyed");
onTabKeyed = '';
onRightKeyed = '';
// *** appabse_change *** 2015/8/30 - end
onEscKeyed = c(this, "isActive", "_onEscKeyed");
onQueryChanged = c(this, "_openIfActive", "_onQueryChanged");
onWhitespaceChanged = c(this, "_openIfActive", "_onWhitespaceChanged");
this.input.bind().onSync("focused", onFocused, this).onSync("blurred", onBlurred, this).onSync("enterKeyed", onEnterKeyed, this).onSync("tabKeyed", onTabKeyed, this).onSync("escKeyed", onEscKeyed, this).onSync("upKeyed", onUpKeyed, this).onSync("downKeyed", onDownKeyed, this).onSync("leftKeyed", onLeftKeyed, this).onSync("rightKeyed", onRightKeyed, this).onSync("queryChanged", onQueryChanged, this).onSync("whitespaceChanged", onWhitespaceChanged, this).onSync("langDirChanged", this._onLangDirChanged, this);
}
_.mixin(Typeahead.prototype, {
_hacks: function hacks() {
var $input, $menu;
$input = this.input.$input || $("<div>");
$menu = this.menu.$node || $("<div>");
$input.on("blur.tt", function($e) {
var active, isActive, hasActive;
active = document.activeElement;
isActive = $menu.is(active);
hasActive = $menu.has(active).length > 0;
if (_.isMsie() && (isActive || hasActive)) {
$e.preventDefault();
$e.stopImmediatePropagation();
_.defer(function() {
$input.focus();
});
}
});
$menu.on("mousedown.tt", function($e) {
$e.preventDefault();
});
},
_onSelectableClicked: function onSelectableClicked(type, $el) {
this.select($el);
},
_onDatasetCleared: function onDatasetCleared() {
this._updateHint();
},
_onDatasetRendered: function onDatasetRendered(type, dataset, suggestions, async) {
this._updateHint();
this.eventBus.trigger("render", suggestions, async, dataset);
},
_onAsyncRequested: function onAsyncRequested(type, dataset, query) {
this.eventBus.trigger("asyncrequest", query, dataset);
},
_onAsyncCanceled: function onAsyncCanceled(type, dataset, query) {
this.eventBus.trigger("asynccancel", query, dataset);
},
_onAsyncReceived: function onAsyncReceived(type, dataset, query) {
this.eventBus.trigger("asyncreceive", query, dataset);
},
_onFocused: function onFocused() {
this._minLengthMet() && this.menu.update(this.input.getQuery());
},
_onBlurred: function onBlurred() {
if (this.input.hasQueryChangedSinceLastFocus()) {
this.eventBus.trigger("change", this.input.getQuery());
}
},
_onEnterKeyed: function onEnterKeyed(type, $e) {
var $selectable;
if ($selectable = this.menu.getActiveSelectable()) {
this.select($selectable) && $e.preventDefault();
}
},
_onTabKeyed: function onTabKeyed(type, $e) {
var $selectable;
if ($selectable = this.menu.getActiveSelectable()) {
this.select($selectable) && $e.preventDefault();
} else if ($selectable = this.menu.getTopSelectable()) {
this.autocomplete($selectable) && $e.preventDefault();
}
},
_onEscKeyed: function onEscKeyed() {
this.close();
},
_onUpKeyed: function onUpKeyed() {
this.moveCursor(-1);
},
_onDownKeyed: function onDownKeyed() {
this.moveCursor(+1);
},
_onLeftKeyed: function onLeftKeyed() {
if (this.dir === "rtl" && this.input.isCursorAtEnd()) {
this.autocomplete(this.menu.getTopSelectable());
}
},
_onRightKeyed: function onRightKeyed() {
if (this.dir === "ltr" && this.input.isCursorAtEnd()) {
this.autocomplete(this.menu.getTopSelectable());
}
},
_onQueryChanged: function onQueryChanged(e, query) {
this._minLengthMet(query) ? this.menu.update(query) : this.menu.empty();
},
_onWhitespaceChanged: function onWhitespaceChanged() {
this._updateHint();
},
_onLangDirChanged: function onLangDirChanged(e, dir) {
if (this.dir !== dir) {
this.dir = dir;
this.menu.setLanguageDirection(dir);
}
},
_openIfActive: function openIfActive() {
this.isActive() && this.open();
},
_minLengthMet: function minLengthMet(query) {
query = _.isString(query) ? query : this.input.getQuery() || "";
return query.length >= this.minLength;
},
_updateHint: function updateHint() {
var $selectable, data, val, query, escapedQuery, frontMatchRegEx, match;
$selectable = this.menu.getTopSelectable();
data = this.menu.getSelectableData($selectable);
val = this.input.getInputValue();
if (data && !_.isBlankString(val) && !this.input.hasOverflow()) {
query = Input.normalizeQuery(val);
escapedQuery = _.escapeRegExChars(query);
frontMatchRegEx = new RegExp("^(?:" + escapedQuery + ")(.+$)", "i");
match = frontMatchRegEx.exec(data.val);
match && this.input.setHint(val + match[1]);
} else {
this.input.clearHint();
}
},
isEnabled: function isEnabled() {
return this.enabled;
},
enable: function enable() {
this.enabled = true;
},
disable: function disable() {
this.enabled = false;
},
isActive: function isActive() {
return this.active;
},
activate: function activate() {
if (this.isActive()) {
return true;
} else if (!this.isEnabled() || this.eventBus.before("active")) {
return false;
} else {
this.active = true;
this.eventBus.trigger("active");
return true;
}
},
deactivate: function deactivate() {
if (!this.isActive()) {
return true;
} else if (this.eventBus.before("idle")) {
return false;
} else {
this.active = false;
this.close();
this.eventBus.trigger("idle");
return true;
}
},
isOpen: function isOpen() {
return this.menu.isOpen();
},
open: function open() {
if (!this.isOpen() && !this.eventBus.before("open")) {
this.menu.open();
this._updateHint();
this.eventBus.trigger("open");
}
return this.isOpen();
},
close: function close() {
if (this.isOpen() && !this.eventBus.before("close")) {
this.menu.close();
this.input.clearHint();
this.input.resetInputValue();
this.eventBus.trigger("close");
}
return !this.isOpen();
},
setVal: function setVal(val) {
this.input.setQuery(_.toStr(val));
},
getVal: function getVal() {
return this.input.getQuery();
},
select: function select($selectable) {
var data = this.menu.getSelectableData($selectable);
if (data && !this.eventBus.before("select", data.obj)) {
this.input.setQuery(data.val, true);
this.eventBus.trigger("select", data.obj);
this.close();
return true;
}
return false;
},
autocomplete: function autocomplete($selectable) {
var query, data, isValid;
query = this.input.getQuery();
data = this.menu.getSelectableData($selectable);
isValid = data && query !== data.val;
if (isValid && !this.eventBus.before("autocomplete", data.obj)) {
this.input.setQuery(data.val);
this.eventBus.trigger("autocomplete", data.obj);
return true;
}
return false;
},
moveCursor: function moveCursor(delta) {
var query, $candidate, data, payload, cancelMove;
query = this.input.getQuery();
$candidate = this.menu.selectableRelativeToCursor(delta);
data = this.menu.getSelectableData($candidate);
payload = data ? data.obj : null;
cancelMove = this._minLengthMet() && this.menu.update(query);
if (!cancelMove && !this.eventBus.before("cursorchange", payload)) {
this.menu.setCursor($candidate);
if (data) {
this.input.setInputValue(data.val);
} else {
this.input.resetInputValue();
this._updateHint();
}
this.eventBus.trigger("cursorchange", payload);
return true;
}
return false;
},
destroy: function destroy() {
this.input.destroy();
this.menu.destroy();
}
});
return Typeahead;
function c(ctx) {
var methods = [].slice.call(arguments, 1);
return function() {
var args = [].slice.call(arguments);
_.each(methods, function(method) {
return ctx[method].apply(ctx, args);
});
};
}
}();
(function() {
"use strict";
var old, keys, methods;
old = $.fn.typeahead;
keys = {
www: "tt-www",
attrs: "tt-attrs",
typeahead: "tt-typeahead"
};
methods = {
initialize: function initialize(o, datasets) {
var www;
datasets = _.isArray(datasets) ? datasets : [].slice.call(arguments, 1);
o = o || {};
www = WWW(o.classNames);
return this.each(attach);
function attach() {
var $input, $wrapper, $hint, $menu, defaultHint, defaultMenu, eventBus, input, menu, typeahead, MenuConstructor;
_.each(datasets, function(d) {
d.highlight = !!o.highlight;
});
$input = $(this);
$wrapper = $(www.html.wrapper);
$hint = $elOrNull(o.hint);
$menu = $elOrNull(o.menu);
defaultHint = o.hint !== false && !$hint;
defaultMenu = o.menu !== false && !$menu;
defaultHint && ($hint = buildHintFromInput($input, www));
defaultMenu && ($menu = $(www.html.menu).css(www.css.menu));
$hint && $hint.val("");
$input = prepInput($input, www);
if (defaultHint || defaultMenu) {
$wrapper.css(www.css.wrapper);
$input.css(defaultHint ? www.css.input : www.css.inputWithNoHint);
$input.wrap($wrapper).parent().prepend(defaultHint ? $hint : null).append(defaultMenu ? $menu : null);
}
MenuConstructor = defaultMenu ? DefaultMenu : Menu;
eventBus = new EventBus({
el: $input
});
input = new Input({
hint: $hint,
input: $input
}, www);
menu = new MenuConstructor({
node: $menu,
datasets: datasets
}, www);
typeahead = new Typeahead({
input: input,
menu: menu,
eventBus: eventBus,
minLength: o.minLength
}, www);
$input.data(keys.www, www);
$input.data(keys.typeahead, typeahead);
}
},
isEnabled: function isEnabled() {
var enabled;
ttEach(this.first(), function(t) {
enabled = t.isEnabled();
});
return enabled;
},
enable: function enable() {
ttEach(this, function(t) {
t.enable();
});
return this;
},
disable: function disable() {
ttEach(this, function(t) {
t.disable();
});
return this;
},
isActive: function isActive() {
var active;
ttEach(this.first(), function(t) {
active = t.isActive();
});
return active;
},
activate: function activate() {
ttEach(this, function(t) {
t.activate();
});
return this;
},
deactivate: function deactivate() {
ttEach(this, function(t) {
t.deactivate();
});
return this;
},
isOpen: function isOpen() {
var open;
ttEach(this.first(), function(t) {
open = t.isOpen();
});
return open;
},
open: function open() {
ttEach(this, function(t) {
t.open();
});
return this;
},
close: function close() {
ttEach(this, function(t) {
t.close();
});
return this;
},
select: function select(el) {
var success = false, $el = $(el);
ttEach(this.first(), function(t) {
success = t.select($el);
});
return success;
},
autocomplete: function autocomplete(el) {
var success = false, $el = $(el);
ttEach(this.first(), function(t) {
success = t.autocomplete($el);
});
return success;
},
moveCursor: function moveCursoe(delta) {
var success = false;
ttEach(this.first(), function(t) {
success = t.moveCursor(delta);
});
return success;
},
val: function val(newVal) {
var query;
if (!arguments.length) {
ttEach(this.first(), function(t) {
query = t.getVal();
});
return query;
} else {
ttEach(this, function(t) {
t.setVal(newVal);
});
return this;
}
},
destroy: function destroy() {
ttEach(this, function(typeahead, $input) {
revert($input);
typeahead.destroy();
});
return this;
}
};
$.fn.typeahead = function(method) {
if (methods[method]) {
return methods[method].apply(this, [].slice.call(arguments, 1));
} else {
return methods.initialize.apply(this, arguments);
}
};
$.fn.typeahead.noConflict = function noConflict() {
$.fn.typeahead = old;
return this;
};
function ttEach($els, fn) {
$els.each(function() {
var $input = $(this), typeahead;
(typeahead = $input.data(keys.typeahead)) && fn(typeahead, $input);
});
}
function buildHintFromInput($input, www) {
return $input.clone().addClass(www.classes.hint).removeData().css(www.css.hint).css(getBackgroundStyles($input)).prop("readonly", true).removeAttr("id name placeholder required").attr({
autocomplete: "off",
spellcheck: "false",
tabindex: -1
});
}
function prepInput($input, www) {
$input.data(keys.attrs, {
dir: $input.attr("dir"),
autocomplete: $input.attr("autocomplete"),
spellcheck: $input.attr("spellcheck"),
style: $input.attr("style")
});
$input.addClass(www.classes.input).attr({
autocomplete: "off",
spellcheck: false
});
try {
!$input.attr("dir") && $input.attr("dir", "auto");
} catch (e) {}
return $input;
}
function getBackgroundStyles($el) {
return {
backgroundAttachment: $el.css("background-attachment"),
backgroundClip: $el.css("background-clip"),
backgroundColor: $el.css("background-color"),
backgroundImage: $el.css("background-image"),
backgroundOrigin: $el.css("background-origin"),
backgroundPosition: $el.css("background-position"),
backgroundRepeat: $el.css("background-repeat"),
backgroundSize: $el.css("background-size")
};
}
function revert($input) {
var www, $wrapper;
www = $input.data(keys.www);
$wrapper = $input.parent().filter(www.selectors.wrapper);
_.each($input.data(keys.attrs), function(val, key) {
_.isUndefined(val) ? $input.removeAttr(key) : $input.attr(key, val);
});
$input.removeData(keys.typeahead).removeData(keys.www).removeData(keys.attr).removeClass(www.classes.input);
if ($wrapper.length) {
$input.detach().insertAfter($wrapper);
$wrapper.remove();
}
}
function $elOrNull(obj) {
var isValid, $el;
isValid = _.isJQuery(obj) || _.isElement(obj);
$el = isValid ? $(obj).first() : [];
return $el.length ? $el : null;
}
})();
}); |
import React, { Component, PropTypes } from 'react';
import { connect } from 'react-redux';
import SummaryWidget from 'components/SummaryWidget';
import getMetrics from './SummaryMetrics';
import { bindActionCreators } from 'redux';
import { addMetrics } from 'redux/modules/track-ids';
export class SummaryView extends Component {
constructor (props) {
super();
this.metrics = getMetrics(props.data);
this.saveMetrics = this.saveMetrics.bind(this);
}
static propTypes = {
data: PropTypes.object,
addMetrics: PropTypes.func
}
componentWillMount () {
this.saveMetrics();
}
saveMetrics () {
const { addMetrics } = this.props;
addMetrics(this.metrics);
}
render () {
const { trackIds, airThreats, ramThreats } = this.metrics;
const labels = ['Air Threats', 'RAM Threats'];
const values = [airThreats.size, ramThreats.size];
return (
<div style={{
display: 'flex',
flex: '1'
}}>
<SummaryWidget
title={`${trackIds.size} Threats`}
values={values}
labels={labels}
style={{
display: 'flex'
}}
/>
</div>
);
};
}
const mapDispatchToProps = (dispatch) => bindActionCreators({
addMetrics
}, dispatch);
const mapStateToProps = (state) => ({
data: state.data
});
export default connect(mapStateToProps, mapDispatchToProps)(SummaryView);
|
import * as React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M12 2C8.43 2 5.23 3.54 3.01 6L12 22l8.99-16C18.78 3.55 15.57 2 12 2zM7 7c0-1.1.9-2 2-2s2 .9 2 2-.9 2-2 2-2-.9-2-2zm5 8c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z" />
, 'LocalPizzaSharp');
|
var ScriptUtils = require('../../../src/goo/scripts/ScriptUtils');
describe('ScriptUtils', function () {
it('defaults missing keys', function () {
var parametersDefinition = [{
key: 'a',
type: 'int',
'default': 123
}, {
key: 'b',
type: 'string',
'default': 'asd'
}];
var parametersValues = {};
ScriptUtils.fillDefaultValues(parametersValues, parametersDefinition);
var expected = {
'a': 123,
'b': 'asd'
};
expect(parametersValues).toEqual(expected);
});
it('defaults the defaults for all types', function () {
var parametersDefinition = [{
key: 'a',
type: 'int'
}, {
key: 'b',
type: 'float'
}, {
key: 'c',
type: 'string'
}, {
key: 'd',
type: 'vec3'
}, {
key: 'e',
type: 'boolean'
}, {
key: 'f',
type: 'texture'
}, {
key: 'g',
type: 'entity'
}];
var parametersValues = {};
ScriptUtils.fillDefaultValues(parametersValues, parametersDefinition);
var expected = {
'a': 0,
'b': 0,
'c': '',
'd': [0, 0, 0],
'e': false,
'f': null,
'g': null
};
expect(parametersValues).toEqual(expected);
});
}); |
import { AppContainer } from 'react-hot-loader';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
const rootEl = document.getElementById('root');
ReactDOM.render(
<AppContainer>
<App />
</AppContainer>,
rootEl
);
if (module.hot) {
module.hot.accept('./App', () => {
// If you use Webpack 2 in ES modules mode, you can
// use <App /> here rather than require() a <NextApp />.
const NextApp = require('./App').default;
ReactDOM.render(
<AppContainer>
<NextApp />
</AppContainer>,
rootEl
);
});
} |
import { expect } from 'chai';
import { getCredentials, api, request, credentials } from '../../data/api-data.js';
import { createRoom } from '../../data/rooms.helper';
describe('[Subscriptions]', function() {
this.retries(0);
before((done) => getCredentials(done));
it('/subscriptions.get', (done) => {
request.get(api('subscriptions.get'))
.set(credentials)
.expect('Content-Type', 'application/json')
.expect(200)
.expect((res) => {
expect(res.body).to.have.property('success', true);
expect(res.body).to.have.property('update');
expect(res.body).to.have.property('remove');
})
.end(done);
});
it('/subscriptions.get?updatedSince', (done) => {
request.get(api('subscriptions.get'))
.set(credentials)
.query({
updatedSince: new Date(),
})
.expect(200)
.expect((res) => {
expect(res.body).to.have.property('success', true);
expect(res.body).to.have.property('update').that.have.lengthOf(0);
expect(res.body).to.have.property('remove').that.have.lengthOf(0);
})
.end(done);
});
it('/subscriptions.getOne:', () => {
let testChannel;
it('create an channel', (done) => {
request.post(api('channels.create'))
.set(credentials)
.send({
name: `channel.test.${ Date.now() }`,
})
.end((err, res) => {
testChannel = res.body.channel;
done();
});
});
it('subscriptions.getOne', (done) => {
request.get(api('subscriptions.getOne'))
.set(credentials)
.query({
roomId: testChannel._id,
})
.expect('Content-Type', 'application/json')
.expect(200)
.expect((res) => {
expect(res.body).to.have.property('success', true);
expect(res.body).to.have.property('subscription').and.to.be.an('object');
})
.end(done);
});
});
describe('[/subscriptions.read]', () => {
let testChannel;
it('create a channel', (done) => {
createRoom({ type: 'c', name: `channel.test.${ Date.now() }` })
.end((err, res) => {
testChannel = res.body.channel;
done();
});
});
let testGroup;
it('create a group', (done) => {
createRoom({ type: 'p', name: `channel.test.${ Date.now() }` })
.end((err, res) => {
testGroup = res.body.group;
done();
});
});
let testDM;
it('create a DM', (done) => {
createRoom({ type: 'd', username: 'rocket.cat' })
.end((err, res) => {
testDM = res.body.room;
done();
});
});
it('should mark public channels as read', (done) => {
request.post(api('subscriptions.read'))
.set(credentials)
.send({
rid: testChannel._id,
})
.expect(200)
.expect((res) => {
expect(res.body).to.have.property('success', true);
})
.end(done);
});
it('should mark groups as read', (done) => {
request.post(api('subscriptions.read'))
.set(credentials)
.send({
rid: testGroup._id,
})
.expect(200)
.expect((res) => {
expect(res.body).to.have.property('success', true);
})
.end(done);
});
it('should mark DMs as read', (done) => {
request.post(api('subscriptions.read'))
.set(credentials)
.send({
rid: testDM._id,
})
.expect(200)
.expect((res) => {
expect(res.body).to.have.property('success', true);
})
.end(done);
});
it('should fail on mark inexistent public channel as read', (done) => {
request.post(api('subscriptions.read'))
.set(credentials)
.send({
rid: 'foobar123-somechannel',
})
.expect(400)
.expect((res) => {
expect(res.body).to.have.property('success', false);
expect(res.body).to.have.property('error');
})
.end(done);
});
it('should fail on mark inexistent group as read', (done) => {
request.post(api('subscriptions.read'))
.set(credentials)
.send({
rid: 'foobar123-somegroup',
})
.expect(400)
.expect((res) => {
expect(res.body).to.have.property('success', false);
expect(res.body).to.have.property('error');
})
.end(done);
});
it('should fail on mark inexistent DM as read', (done) => {
request.post(api('subscriptions.read'))
.set(credentials)
.send({
rid: 'foobar123-somedm',
})
.expect(400)
.expect((res) => {
expect(res.body).to.have.property('success', false);
expect(res.body).to.have.property('error');
})
.end(done);
});
it('should fail on invalid params', (done) => {
request.post(api('subscriptions.read'))
.set(credentials)
.send({
rid: 12345,
})
.expect(400)
.expect((res) => {
expect(res.body).to.have.property('success', false);
expect(res.body).to.have.property('error');
})
.end(done);
});
it('should fail on empty params', (done) => {
request.post(api('subscriptions.read'))
.set(credentials)
.send({})
.expect(400)
.expect((res) => {
expect(res.body).to.have.property('success', false);
expect(res.body).to.have.property('error');
})
.end(done);
});
});
describe('[/subscriptions.unread]', () => {
let testChannel;
it('create an channel', (done) => {
request.post(api('channels.create'))
.set(credentials)
.send({
name: `channel.test.${ Date.now() }`,
})
.end((err, res) => {
testChannel = res.body.channel;
done();
});
});
it('should fail when there are no messages on an channel', (done) => {
request.post(api('subscriptions.unread'))
.set(credentials)
.send({
roomId: testChannel._id,
})
.expect(400)
.expect((res) => {
expect(res.body).to.have.property('success', false);
expect(res.body).to.have.property('error');
expect(res.body).to.have.property('errorType', 'error-no-message-for-unread');
})
.end(done);
});
it('sending message', (done) => {
request.post(api('chat.sendMessage'))
.set(credentials)
.send({
message: {
rid: testChannel._id,
msg: 'Sample message',
},
})
.expect('Content-Type', 'application/json')
.expect(200)
.expect((res) => {
expect(res.body).to.have.property('success', true);
expect(res.body).to.have.property('message').and.to.be.an('object');
})
.end(done);
});
it('should return success: true when make as unread successfully', (done) => {
request.post(api('subscriptions.unread'))
.set(credentials)
.send({
roomId: testChannel._id,
})
.expect(200)
.expect((res) => {
expect(res.body).to.have.property('success', true);
})
.end(done);
});
it('should fail on invalid params', (done) => {
request.post(api('subscriptions.unread'))
.set(credentials)
.send({
roomId: 12345,
})
.expect(400)
.expect((res) => {
expect(res.body).to.have.property('success', false);
expect(res.body).to.have.property('error');
})
.end(done);
});
it('should fail on empty params', (done) => {
request.post(api('subscriptions.unread'))
.set(credentials)
.send({})
.expect(400)
.expect((res) => {
expect(res.body).to.have.property('success', false);
expect(res.body).to.have.property('error');
})
.end(done);
});
});
});
|
'use strict'
var path = require('path')
var fs = require('fs')
var rand = require('crypto-rand')
var request = require('request')
var Crypto = require('crypto-js')
global.__base = path.join(__dirname, '..', '/')
global.__workingDir = path.join(__base, 'src')
var Config = require(path.join(__base, 'src/worker/config.js'))
var ConfigWorker = new Config()
global.__config = ConfigWorker.load(path.join(__base, 'configs/config.json'))
global.__config.server.port = process.env.PORT || global.__config.server.port
global.__config.authentification.status = process.env.AUTH
var Rand = require('crypto-rand')
var Crypto = require('crypto-js')
var token = Crypto.SHA256(Rand.rand().toString()).toString()
global.__DBtoken = token
var Database = require(path.join(__base, 'src/database/server.js'))
var DBPort = process.env.DB_PORT || global.__config.database.port
var DB = new Database(DBPort, token)
var assert = require('chai').assert
describe('Fontend', function () {})
describe('Backend', function () {
describe('Log', function () {
var Log = require(path.join(__base, 'src/worker/log.js'))
var LogWorker = new Log()
var LogWorker2 = new Log({})
it('Log info', function (done) {
LogWorker.info('This is an info.')
done()
})
it('Log warning', function (done) {
LogWorker.warning('This is a warning.')
done()
})
it('Log error', function (done) {
LogWorker.error('This is an error.')
done()
})
})
describe('Auth', function () {
var username = 'foo' + rand.rand()
var username2 = 'foo2' + rand.rand()
var Auth = require(path.join(__base, 'src/worker/auth.js'))
describe('createInvite()', function () {
it('Invite key: ' + __config.server.masterKey, function (done) {
Auth.createInvite(__config.server.masterKey, function (invite) {
assert.typeOf(invite, 'string')
done()
})
})
it('Invite key: Unknown', function (done) {
Auth.createInvite('', function (invite) {
assert(!invite)
done()
})
})
})
describe('Register()', function () {
it('User: foo, Pass: bar, Invite: Valid invitation', function (done) {
Auth.createInvite(__config.server.masterKey, function (invite) {
Auth.register(username, 'bar', invite, function (token) {
assert.typeOf(token, 'string')
done()
})
})
})
it('User: foo, Pass: bar, Invite: Valid invitation', function (done) {
Auth.createInvite(__config.server.masterKey, function (invite) {
Auth.register(username, 'bar', invite, function (token) {
assert(!token)
done()
})
})
})
it('User: foo, Pass: bar, Invite: Invalid invitation', function (done) {
Auth.register(username2, 'bar', '', function (token) {
assert(!token)
done()
})
})
})
describe('Loggin()', function () {
it('User: foo, Pass: bar', function (done) {
Auth.login(username, 'bar', 'localhost', 86400000, function (token) {
assert.typeOf(token, 'string')
done()
})
})
it('User: Unknown, Pass: bar', function (done) {
Auth.login(username2, 'bar', 'localhost', 86400000, function (token) {
assert(!token)
done()
})
})
it('User: foo, Pass: Wrong', function (done) {
Auth.login(username, 'test', 'localhost', 86400000, function (token) {
assert(!token)
done()
})
})
})
describe('Logout()', function () {
it('User: foo, Token: valid', function (done) {
Auth.login(username, 'bar', 'localhost', 86400000, function (token) {
Auth.logout(username, token, function (loggedOut) {
assert(loggedOut)
done()
})
})
})
it('User: Unknown, Token: valid', function (done) {
Auth.logout(username2, '', function (loggedOut) {
assert(!loggedOut)
done()
})
})
it('User: foo, Token: invalid', function (done) {
Auth.login(username, 'bar', 'localhost', 86400000, function (token) {
Auth.logout(username, token + '1', function (loggedOut) {
assert(!loggedOut)
done()
})
})
})
})
describe('ChangePass()', function () {
it('Change password User: foo, OldPass: bar, NewPass: rab', function (done) {
Auth.changePass(username, 'bar', 'rab', function (passwordChanged) {
assert(passwordChanged)
done()
})
})
it('Change password User: Unknown, OldPass: bar, NewPass: rab', function (done) {
Auth.changePass(username2, 'bar', 'rab', function (passwordChanged) {
assert(!passwordChanged)
done()
})
})
it('Change password User: foo, OldPass: Wrong, NewPass: rab', function (done) {
Auth.changePass(username, 'bar1', 'rab', function (passwordChanged) {
assert(!passwordChanged)
done()
})
})
it('Change password User: foo, OldPass: rad, NewPass: bar', function (done) {
Auth.changePass(username, 'rab', 'bar', function (passwordChanged) {
assert(passwordChanged)
done()
})
})
})
describe('CheckLogged()', function () {
it('User: foo', function (done) {
Auth.login(username, 'bar', 'localhost', 86400000, function (token) {
Auth.checkLogged(username, token, function (isLogged) {
assert(isLogged)
done()
})
})
})
it('User: Unknown', function (done) {
Auth.checkLogged(username2, '', function (isLogged) {
assert(!isLogged)
done()
})
})
})
describe('LastSeen()', function () {
it('User: foo', function (done) {
Auth.lastSeen(username, function (timestamp) {
assert(timestamp)
done()
})
})
})
})
describe('MediaInfo', function () {
var MediaInfo = require(path.join(__base, 'src/worker/mediaInfo.js'))
describe('GetInfo()', function () {
this.timeout(30000)
it('Type: series, Query: Game of thrones', function (done) {
MediaInfo.getInfo('series', 'Game of Thrones', function (res) {
assert.equal(res.query, 'Game of Thrones')
done()
})
})
it('Type: movie, Query: Alien', function (done) {
MediaInfo.getInfo('films', 'Alien', function (res) {
assert.equal(res.query, 'Alien')
done()
})
})
it('Type: movie, Query: Unknown', function (done) {
MediaInfo.getInfo('films', 'blbablabla', function (res) {
assert.typeOf(res.err, 'string')
done()
})
})
})
})
describe('SearchTorrent', function () {
var SearchT = require(path.join(__base, 'src/worker/searchtorrent.js'))
describe('Search()', function () {
this.timeout(30000)
it('Search: Game of thrones', function (done) {
SearchT.search('Game of Thrones', function (res) {
assert.typeOf(res, 'object')
assert(res.tv)
assert(res.mv)
done()
})
})
})
describe('Latest()', function () {
this.timeout(30000)
it('Get latest', function (done) {
SearchT.latest(function (res) {
assert.typeOf(res, 'object')
assert(res.tv)
assert(res.mv)
done()
})
})
})
})
describe('Client', function () {
var Client = require(path.join(__base, 'src/worker/client.js'))
var ClientWorker = new Client()
describe('Dowload()', function () {
this.timeout(305000)
it('Dowload ubuntu', function (done) {
ClientWorker.download('magnet:?xt=urn:btih:63c393906fc843e7e4d1cba6bd4c5e16bf9e8e4b&dn=CentOS-7-x86_64-NetInstall-1511', 'magnet:?xt=urn:btih:63c393906fc843e7e4d1cba6bd4c5e16bf9e8e4b&dn=CentOS-7-x86_64-NetInstall-1511',
function (hash) {
assert.equal(hash, '63c393906fc843e7e4d1cba6bd4c5e16bf9e8e4b')
}, function () {
ClientWorker.stop()
done()
})
})
})
})
describe('Server', function () {
var Server = require(path.join(__base, 'src/controller/main.js'))
var ServerWorker = new Server(1)
var url = 'http://localhost:' + __config.server.port
var user = 'test' + rand.rand()
var pass = 'test'
describe('POST and GET Auth', function () {
it('get / without login', function (done) {
this.timeout(30000)
request(url, function (err, res, body) {
assert(!err)
if (!err && res.statusCode === 200) {
assert(body.match('<title>Login - Lunik - Torrent</title>'))
}
done()
})
})
it('genInvite + register + login + changePass + logout', function (done) {
// gentoken
request.get({
url: url + '/auth/invite',
qs: {
masterKey: __config.server.masterKey
}
}, function (err, res, body) {
assert(!err)
if (!err && res.statusCode === 200) {
var invite = JSON.parse(body).invitationCode
assert(invite)
}
})
request.post({
url: url + '/auth/invite',
form: {
masterKey: __config.server.masterKey
}
}, function (err, res, body) {
assert(!err)
if (!err && res.statusCode === 200) {
var invite = JSON.parse(body).invitationCode
assert(invite)
// register
request.post({
url: url + '/auth/register',
form: {
user: user,
pass: pass,
invite: invite
}
}, function (err, res, body) {
assert(!err)
if (!err && res.statusCode === 200) {
var token = JSON.parse(body).token
assert(token)
// login
request.post({
url: url + '/auth/login',
form: {
user: user,
pass: pass
}
}, function (err, res, body) {
assert(!err)
if (!err && res.statusCode === 200) {
var token = JSON.parse(body).token
assert(token)
// logout
request.post({
url: url + '/auth/logout',
form: {
user: user,
token: token
}
}, function (err, res, body) {
assert(!err)
if (!err && res.statusCode === 200) {
err = JSON.parse(body).err
assert(!err)
request.post({
url: url + '/auth/changepass',
form: {
user: user,
oldpass: pass,
newpass: pass + 1
}
}, function (err, res, body) {
assert(!err)
if (!err && res.statusCode === 200) {
err = JSON.parse(body).err
assert(!err)
request.post({
url: url + '/auth/changepass',
form: {
user: user,
oldpass: pass + 1,
newpass: pass
}
}, function (err, res, body) {
assert(!err)
if (!err && res.statusCode === 200) {
err = JSON.parse(body).err
assert(!err)
}
done()
})
}
})
}
})
}
})
}
})
}
})
})
it('GET /files', function (done) {
Auth(url, user, pass, function (token) {
var file = 'ok' + rand.rand()
var r = rand.rand()
fs.writeFile(path.join(__base, __config.directory.path, file), r, function (err) {
assert(!err)
request.get({
url: url + '/files?f=' + file,
headers: {
Cookie: 'user=' + user + ';token=' + token
}
}, function (err, res, body) {
assert(!err)
if (!err && res.statusCode === 200) {
assert.equal(body, r)
assert(!JSON.parse(body).err)
}
done()
})
})
})
})
it('GET /direct', function () {
var file = 'ok' + rand.rand()
var r = rand.rand()
fs.writeFile(path.join(__base, __config.directory.path, file), r, function (err) {
assert(!err)
request.get({
url: url + '/directdl/' + Crypto.AES.encode(file, '').toString()
}, function (err, res, body) {
assert(!err)
if (!err && res.statusCode === 200) {
assert.equal(body, r)
assert(!JSON.parse(body).err)
}
done()
})
})
})
it('POST List-t', function (done) {
Auth(url, user, pass, function (token) {
request.get({
url: url + '/torrent/list',
headers: {
Cookie: 'user=' + user + ';token=' + token
}
}, function (err, res, body) {
if (!err && res.statusCode === 200) {
body = JSON.parse(body)
assert(!body.err)
assert(Array.isArray(body))
}
done()
})
})
})
it('GET List-d', function (done) {
Auth(url, user, pass, function (token) {
var dir = 'ok' + rand.rand()
fs.mkdir(path.join(__base, __config.directory.path, dir), function (err) {
assert(!err)
request.get({
url: url + '/directory/list',
headers: {
Cookie: 'user=' + user + ';token=' + token
},
qs: {
dir: dir
}
}, function (err, res, body) {
if (!err && res.statusCode === 200) {
body = JSON.parse(body)
assert(!body.err)
assert.typeOf(body, 'object')
}
done()
})
})
})
})
it('POST remove-d', function (done) {
Auth(url, user, pass, function (token) {
var file = 'ok' + rand.rand()
fs.writeFile(path.join(__base, __config.directory.path, file), 'ok', function (err) {
assert(!err)
request.post({
url: url + '/directory/remove',
headers: {
Cookie: 'user=' + user + ';token=' + token
},
form: {
file: file
}
}, function (err, res, body) {
if (!err && res.statusCode === 200) {
body = JSON.parse(body)
assert(!body.err)
assert.equal(body.file, file)
done()
}
})
})
})
})
it('POST rename-d', function (done) {
Auth(url, user, pass, function (token) {
var file = 'ok' + rand.rand()
var file2 = 'ok' + rand.rand()
fs.writeFile(path.join(__base, __config.directory.path, file), 'ok', function (err) {
assert(!err)
request.post({
url: url + '/directory/rename',
headers: {
Cookie: 'user=' + user + ';token=' + token
},
form: {
path: '/',
oldname: file,
newname: file2
}
}, function (err, res, body) {
if (!err && res.statusCode === 200) {
body = JSON.parse(body)
assert(!body.err)
assert.equal(body.oldname, file)
assert.equal(body.newname, file2)
done()
}
})
})
})
})
it('POST mdkir-d', function (done) {
Auth(url, user, pass, function (token) {
var dir = 'ok' + rand.rand()
request.post({
url: url + '/directory/mkdir',
headers: {
Cookie: 'user=' + user + ';token=' + token
},
form: {
path: '/',
name: dir
}
}, function (err, res, body) {
if (!err && res.statusCode === 200) {
body = JSON.parse(body)
assert(!body.err)
assert.equal(body.name, dir)
done()
}
})
})
})
it('POST mdkir-d', function (done) {
Auth(url, user, pass, function (token) {
var dir = 'ok' + rand.rand()
var file = 'ok' + rand.rand()
fs.mkdir(path.join(__base, __config.directory.path, dir), function (err) {
assert(!err)
fs.writeFile(path.join(__base, __config.directory.path, file), 'ok', function (err) {
assert(!err)
request.post({
url: url + '/directory/mv',
headers: {
Cookie: 'user=' + user + ';token=' + token
},
form: {
path: '/',
file: file,
folder: dir
}
}, function (err, res, body) {
if (!err && res.statusCode === 200) {
body = JSON.parse(body)
assert(!body.err)
assert.equal(body.file, file)
done()
}
})
})
})
})
})
it('POST search-t', function (done) {
this.timeout(30000)
Auth(url, user, pass, function (token) {
request.post({
url: url + '/torrent/search',
headers: {
Cookie: 'user=' + user + ';token=' + token
},
form: {
query: 'Game of Thrones'
}
}, function (err, res, body) {
if (!err && res.statusCode === 200) {
body = JSON.parse(body)
assert(!body.err)
assert.typeOf(body, 'object')
done()
}
})
})
})
it('GET info-d', function (done) {
this.timeout(30000)
Auth(url, user, pass, function (token) {
request.get({
url: url + '/directory/info',
headers: {
Cookie: 'user=' + user + ';token=' + token
},
qs: {
type: 'series',
query: 'Game of Thrones'
}
}, function (err, res, body) {
if (!err && res.statusCode === 200) {
body = JSON.parse(body)
assert(!body.err)
assert.typeOf(body, 'object')
done()
}
})
})
})
it('GET lock-d', function (done) {
var file = 'ok' + rand.rand()
Auth(url, user, pass, function (token) {
fs.writeFile(path.join(__base, __config.directory.path, file), 'ok', function (err) {
assert(!err)
request.get({
url: url + '/directory/lock?f=' + file,
headers: {
Cookie: 'user=' + user + ';token=' + token
}
}, function (err, res, body) {
if (!err && res.statusCode === 200) {
body = JSON.parse(body)
assert(!body.err)
done()
}
})
})
})
})
it('POST download-t && remove-t', function (done) {
this.timeout(30000)
Auth(url, user, pass, function (token) {
request.post({
url: url + '/torrent/download',
headers: {
Cookie: 'user=' + user + ';token=' + token
},
form: {
url: 'magnet:?xt=urn:btih:fe00c3de0ce28bcc6724f309aa8e0fcc5e6e0bf4&dn=CentOS-6.8-i386-netinstall'
}
}, function (err, res, body) {
if (!err && res.statusCode === 200) {
body = JSON.parse(body)
assert(!body.err)
request.post({
url: url + '/torrent/remove',
headers: {
Cookie: 'user=' + user + ';token=' + token
},
form: {
hash: 'fe00c3de0ce28bcc6724f309aa8e0fcc5e6e0bf4'
}
}, function (err, res, body) {
if (!err && res.statusCode === 200) {
body = JSON.parse(body)
assert.equal(body.hash, 'fe00c3de0ce28bcc6724f309aa8e0fcc5e6e0bf4')
assert(!body.err)
}
done()
})
}
})
})
})
})
})
describe('Directory', function () {
var Directory = require(path.join(__base, 'src/worker/directory.js'))
describe('Mkdir()', function () {
it('Create dir', function (done) {
Directory.mkdir('/', 'ok' + rand.rand())
done()
})
})
describe('List()', function () {
it('Scan / ', function (done) {
Directory.list('/', function (folder) {
assert.typeOf(folder, 'object')
done()
})
})
})
describe('Mv()', function () {
it('Mv dir into dir', function (done) {
var recip = 'ok' + rand.rand()
var dir = 'ok' + rand.rand()
Directory.mkdir('/', recip)
Directory.mkdir('/', dir)
Directory.mv('/', dir, recip, function (err) {
assert(!err)
done()
})
})
})
describe('Rename()', function () {
it('change dir name', function (done) {
var dir = 'ok' + rand.rand()
var newname = 'ok' + rand.rand()
Directory.mkdir('/', dir)
Directory.rename('/', dir, newname, function (err) {
assert(!err)
done()
})
})
})
describe('SetOwner()', function () {
it('setOwner of dir', function (done) {
var dir = 'ok' + rand.rand()
Directory.mkdir('/', dir)
Directory.setOwner(dir, 'test')
done()
})
})
describe('Remove()', function () {
it('remove dir', function (done) {
var dir = 'ok' + rand.rand()
Directory.mkdir('/', dir)
Directory.remove(dir, function (err) {
assert(!err)
done()
})
})
})
describe('Downloading()', function () {
it('setDownloading', function (done) {
var dir = 'ok' + rand.rand()
Directory.mkdir('/', dir)
Directory.setDownloading(dir, function (err) {
assert(!err)
Directory.setDownloading(dir, function (err) {
assert(!err)
Directory.isDownloading(dir, function (isdl) {
assert(isdl)
Directory.finishDownloading(dir, function (err) {
assert(!err)
Directory.finishDownloading(dir, function (err) {
assert(!err)
done()
})
})
})
})
})
})
})
})
describe('torrent', function () {
var Torrent = require(path.join(__base, 'src/worker/torrent.js'))
describe('Start()', function () {
it('start multiple torrent', function (done) {
this.timeout(300000)
Torrent.start('nobody', 'magnet:?xt=urn:btih:406bcd979f0f2650e859324d97efd0a1139328a0&dn=CentOS-5.11-i386-netinstall')
Torrent.start('nobody', 'magnet:?xt=urn:btih:2700d4801a22ab198428bf1b4a85b097bf0497d3&dn=CentOS-5.11-x86_64-netinstall')
Torrent.start('nobody', 'magnet:?xt=urn:btih:90289fd34dfc1cf8f316a268add8354c85334458&dn=ubuntu-16.04.1-server-amd64.iso')
Torrent.start('nobody', 'magnet:?xt=urn:btih:6bf4c6b4b86dbfcc79180b042abc2bd60a9ca3a4&dn=ubuntu-16.10-server-i386.iso')
setTimeout(function () {
done()
}, 10000)
})
})
describe('remove()', function () {
it('start and remove', function (done) {
this.timeout(300000)
Torrent.start('nobody', 'magnet:?xt=urn:btih:288f8018277b8c474f304a059b064e017bd55e9f&dn=ubuntu-16.04.1-server-i386.iso')
setTimeout(function () {
Torrent.getInfo(function (data) {
assert(Array.isArray(data))
Torrent.remove('288f8018277b8c474f304a059b064e017bd55e9f')
done()
})
}, 10000)
})
})
})
})
function Auth (url, user, pass, cb) {
request.post({
url: url + '/auth/login',
form: {
user: user,
pass: pass
}
}, function (err, res, body) {
if (!err && res.statusCode === 200) {
var token = JSON.parse(body).token
cb(token)
}
})
}
|
import React, { useState, useEffect } from 'react';
import NotAuthorizedPage from '../../../components/NotAuthorizedPage';
import PageSkeleton from '../../../components/PageSkeleton';
import { usePermission } from '../../../contexts/AuthorizationContext';
import { useRouteParameter, useRoute, useCurrentRoute } from '../../../contexts/RouterContext';
import { useMethod } from '../../../contexts/ServerContext';
import AppDetailsPage from './AppDetailsPage';
import AppInstallPage from './AppInstallPage';
import AppLogsPage from './AppLogsPage';
import AppsPage from './AppsPage';
import AppsProvider from './AppsProvider';
import MarketplacePage from './MarketplacePage';
function AppsRoute() {
const [isLoading, setLoading] = useState(true);
const canViewAppsAndMarketplace = usePermission('manage-apps');
const isAppsEngineEnabled = useMethod('apps/is-enabled');
const appsWhatIsItRoute = useRoute('admin-apps-disabled');
useEffect(() => {
let mounted = true;
const initialize = async () => {
if (!canViewAppsAndMarketplace) {
return;
}
if (!(await isAppsEngineEnabled())) {
appsWhatIsItRoute.push();
return;
}
if (!mounted) {
return;
}
setLoading(false);
};
initialize();
return () => {
mounted = false;
};
}, [canViewAppsAndMarketplace, isAppsEngineEnabled, appsWhatIsItRoute]);
const [currentRouteName] = useCurrentRoute();
const isMarketPlace = currentRouteName === 'admin-marketplace';
const context = useRouteParameter('context');
const id = useRouteParameter('id');
const version = useRouteParameter('version');
if (!canViewAppsAndMarketplace) {
return <NotAuthorizedPage />;
}
if (isLoading) {
return <PageSkeleton />;
}
return (
<AppsProvider>
{(!context && isMarketPlace && <MarketplacePage />) ||
(!context && !isMarketPlace && <AppsPage />) ||
(context === 'details' && <AppDetailsPage id={id} marketplaceVersion={version} />) ||
(context === 'logs' && <AppLogsPage id={id} />) ||
(context === 'install' && <AppInstallPage />)}
</AppsProvider>
);
}
export default AppsRoute;
|
var nx = {
nx: {
isInitialized: false,
maxY: 0,
maxYTick: 0,
series: null,
showWithData: null,
},
nax: {
isInitialized: false,
maxY: 0,
maxYTick: 0,
series: null,
showWithData: null,
},
ngx: {
isInitialized: false,
maxY: 0,
maxYTick: 0,
series: null,
showWithData: null,
},
ngax: {
isInitialized: false,
maxY: 0,
maxYTick: 0,
series: null,
showWithData: null,
},
draw: function (name, title, colors, filenames, data, refPlotValue,
placeholder, legendPlaceholder, glossary, order) {
var listsOfLengths = data.listsOfLengths;
var refLength = data.refLen;
var info = nx[name];
if (!info.isInitialized) {
var plotsN = filenames.length;
info.series = new Array(plotsN);
for (var i = 0; i < plotsN; i++) {
var lengths = listsOfLengths[order[i]];
var size = lengths.length;
if (name == 'ngx' || name == 'ngax') {
sumLen = refLength;
} else {
var sumLen = 0;
for (var j = 0; j < lengths.length; j++) {
sumLen += lengths[j];
}
}
info.series[i] = {
data: [],
label: filenames[order[i]],
number: i,
color: colors[order[i]],
};
info.series[i].data.push([0.0, lengths[0]]);
var currentLen = 0;
var x = 0.0;
for (var k = 0; k < size; k++) {
currentLen += lengths[k];
info.series[i].data.push([x, lengths[k]]);
x = currentLen * 100.0 / sumLen;
info.series[i].data.push([x, lengths[k]]);
}
if (info.series[i].data[0][1] > info.maxY) {
info.maxY = info.series[i].data[0][1];
}
var lastPt = info.series[i].data[info.series[i].data.length-1];
info.series[i].data.push([lastPt[0], 0]);
}
for (i = 0; i < plotsN; i++) {
info.series[i].lines = {
show: true,
lineWidth: 1,
}
}
// for (i = 0; i < plotsN; i++) {
// plotsData[i].points = {
// show: true,
// radius: 1,
// fill: 1,
// fillColor: false,
// }
// }
info.showWithData = function(series, colors) {
var plot = $.plot(placeholder, series, {
shadowSize: 0,
colors: colors,
legend: {
container: $('useless-invisible-element-that-does-not-even-exist'),
},
grid: {
borderWidth: 1,
hoverable: true,
autoHighlight: false,
mouseActiveRadius: 1000,
},
yaxis: {
min: 0,
// max: info.maxY,
labelWidth: 120,
reserveSpace: true,
lineWidth: 0.5,
color: '#000',
tickFormatter: getBpTickFormatter(info.maxY),
minTickSize: 1,
},
xaxis: {
min: 0,
max: 100,
lineWidth: 0.5,
color: '#000',
tickFormatter: function (val, axis) {
if (val == 100) {
return ' x<span class="rhs"> </span>=<span class="rhs"> </span>100%'
} else {
return val;
}
}
},
minTickSize: 1,
}
);
var firstLabel = $('.yAxis .tickLabel').last();
firstLabel.prepend(title + '<span class="rhs"> </span>=<span class="rhs"> </span>');
bindTip(placeholder, series, plot, toPrettyString, '%', 'top right');
};
info.isInitialized = true;
}
$.each(info.series, function(i, series) {
$('#legend-placeholder').find('#label_' + series.number + '_id').click(function() {
showPlotWithInfo(info);
});
});
showPlotWithInfo(info);
$('#contigs_are_ordered').hide();
$('#gc_info').hide();
}
};
|
////////////////////////////////////////////////////////////////////////////////
// Page State
//
// Contains all information pertaining to the page's state that is not
// stored in other business objects (controls).
////////////////////////////////////////////////////////////////////////////////
var app = app || {};
app.data = function (data) {
// tag collection
data.pagestate = {
// mediaid for the last played video
lastPlayed: null
};
return data;
}(app.data || {});
|
'use strict';
//Setting up route
angular.module('functionary-resume-educations').config(['$stateProvider',
function($stateProvider) {
// Functionary resume educations state routing
$stateProvider.
state('listFunctionaryResumeEducations', {
url: '/functionary-resume-educations',
templateUrl: 'modules/functionary-resume-educations/views/list-functionary-resume-educations.client.view.html'
}).
state('createFunctionaryResumeEducation', {
url: '/functionary-resume-educations/create',
templateUrl: 'modules/functionary-resume-educations/views/create-functionary-resume-education.client.view.html'
}).
state('viewFunctionaryResumeEducation', {
url: '/functionary-resume-educations/:functionaryResumeEducationId',
templateUrl: 'modules/functionary-resume-educations/views/view-functionary-resume-education.client.view.html'
}).
state('editFunctionaryResumeEducation', {
url: '/functionary-resume-educations/:functionaryResumeEducationId/edit',
templateUrl: 'modules/functionary-resume-educations/views/edit-functionary-resume-education.client.view.html'
});
}
]); |
'use strict';
var libjsonnet = require('./lib/libjsonnet');
var Jsonnet = function() {
var jsonnet_make = libjsonnet.cwrap('jsonnet_make', 'number', []);
this.vm = jsonnet_make();
this.jsonnet_cleanup_string = libjsonnet.cwrap('jsonnet_cleanup_string', 'number', ['number', 'number']);
this.jsonnet_evaluate_snippet = libjsonnet.cwrap('jsonnet_evaluate_snippet', 'number', ['number', 'string', 'string', 'number']);
this.jsonnet_destroy = libjsonnet.cwrap('jsonnet_destroy', 'number', ['number']);
};
module.exports = Jsonnet;
Jsonnet.prototype.eval = function(code) {
var error_ptr = libjsonnet._malloc(4);
var output_ptr = this.jsonnet_evaluate_snippet(this.vm, "snippet", code, error_ptr);
var error = libjsonnet.getValue(error_ptr, 'i32*');
libjsonnet._free(error_ptr);
var result = libjsonnet.Pointer_stringify(output_ptr);
this.jsonnet_cleanup_string(this.vm, output_ptr);
if (error) {
throw new Error(result);
}
return JSON.parse(result);
};
Jsonnet.prototype.evalFile = function(filepath) {
var code = libjsonnet.read(filepath);
return this.eval(code);
};
Jsonnet.prototype.destroy = function() {
this.jsonnet_destroy(this.vm);
};
|
/**
* @author Richard Davey <rich@photonstorm.com>
* @copyright 2022 Photon Storm Ltd.
* @license {@link https://opensource.org/licenses/MIT|MIT License}
*/
/**
* Apply `Math.ceil()` to each coordinate of the given Point.
*
* @function Phaser.Geom.Point.Ceil
* @since 3.0.0
*
* @generic {Phaser.Geom.Point} O - [point,$return]
*
* @param {Phaser.Geom.Point} point - The Point to ceil.
*
* @return {Phaser.Geom.Point} The Point with `Math.ceil()` applied to its coordinates.
*/
var Ceil = function (point)
{
return point.setTo(Math.ceil(point.x), Math.ceil(point.y));
};
module.exports = Ceil;
|
exports = module.exports = function (express, middleware, handlers, path) {
var router = express();
router.route(path)
.get(handlers.auth);
return router;
}; |
var Emitter = require('emitter-component');
var Hammer = require('../module/hammer');
var moment = require('../module/moment');
var util = require('../util');
var DataSet = require('../DataSet');
var DataView = require('../DataView');
var Range = require('./Range');
var Core = require('./Core');
var TimeAxis = require('./component/TimeAxis');
var CurrentTime = require('./component/CurrentTime');
var CustomTime = require('./component/CustomTime');
var ItemSet = require('./component/ItemSet');
var printStyle = require('../shared/Validator').printStyle;
var allOptions = require('./optionsTimeline').allOptions;
var configureOptions = require('./optionsTimeline').configureOptions;
var Configurator = require('../shared/Configurator').default;
var Validator = require('../shared/Validator').default;
/**
* Create a timeline visualization
* @param {HTMLElement} container
* @param {vis.DataSet | vis.DataView | Array} [items]
* @param {vis.DataSet | vis.DataView | Array} [groups]
* @param {Object} [options] See Timeline.setOptions for the available options.
* @constructor
* @extends Core
*/
function Timeline (container, items, groups, options) {
if (!(this instanceof Timeline)) {
throw new SyntaxError('Constructor must be called with the new operator');
}
// if the third element is options, the forth is groups (optionally);
if (!(Array.isArray(groups) || groups instanceof DataSet || groups instanceof DataView) && groups instanceof Object) {
var forthArgument = options;
options = groups;
groups = forthArgument;
}
// TODO: REMOVE THIS in the next MAJOR release
// see https://github.com/almende/vis/issues/2511
if (options && options.throttleRedraw) {
console.warn("Timeline option \"throttleRedraw\" is DEPRICATED and no longer supported. It will be removed in the next MAJOR release.");
}
var me = this;
this.defaultOptions = {
start: null,
end: null,
autoResize: true,
orientation: {
axis: 'bottom', // axis orientation: 'bottom', 'top', or 'both'
item: 'bottom' // not relevant
},
moment: moment,
width: null,
height: null,
maxHeight: null,
minHeight: null
};
this.options = util.deepExtend({}, this.defaultOptions);
// Create the DOM, props, and emitter
this._create(container);
if (!options || (options && typeof options.rtl == "undefined")) {
var directionFromDom, domNode = this.dom.root;
while (!directionFromDom && domNode) {
directionFromDom = window.getComputedStyle(domNode, null).direction;
domNode = domNode.parentElement;
}
this.options.rtl = (directionFromDom && (directionFromDom.toLowerCase() == "rtl"));
} else {
this.options.rtl = options.rtl;
}
this.options.rollingMode = options && options.rollingMode;
// all components listed here will be repainted automatically
this.components = [];
this.body = {
dom: this.dom,
domProps: this.props,
emitter: {
on: this.on.bind(this),
off: this.off.bind(this),
emit: this.emit.bind(this)
},
hiddenDates: [],
util: {
getScale: function () {
return me.timeAxis.step.scale;
},
getStep: function () {
return me.timeAxis.step.step;
},
toScreen: me._toScreen.bind(me),
toGlobalScreen: me._toGlobalScreen.bind(me), // this refers to the root.width
toTime: me._toTime.bind(me),
toGlobalTime : me._toGlobalTime.bind(me)
}
};
// range
this.range = new Range(this.body, this.options);
this.components.push(this.range);
this.body.range = this.range;
// time axis
this.timeAxis = new TimeAxis(this.body, this.options);
this.timeAxis2 = null; // used in case of orientation option 'both'
this.components.push(this.timeAxis);
// current time bar
this.currentTime = new CurrentTime(this.body, this.options);
this.components.push(this.currentTime);
// item set
this.itemSet = new ItemSet(this.body, this.options);
this.components.push(this.itemSet);
this.itemsData = null; // DataSet
this.groupsData = null; // DataSet
this.dom.root.onclick = function (event) {
me.emit('click', me.getEventProperties(event))
};
this.dom.root.ondblclick = function (event) {
me.emit('doubleClick', me.getEventProperties(event))
};
this.dom.root.oncontextmenu = function (event) {
me.emit('contextmenu', me.getEventProperties(event))
};
this.dom.root.onmouseover = function (event) {
me.emit('mouseOver', me.getEventProperties(event))
};
if(window.PointerEvent) {
this.dom.root.onpointerdown = function (event) {
me.emit('mouseDown', me.getEventProperties(event))
};
this.dom.root.onpointermove = function (event) {
me.emit('mouseMove', me.getEventProperties(event))
};
this.dom.root.onpointerup = function (event) {
me.emit('mouseUp', me.getEventProperties(event))
};
} else {
this.dom.root.onmousemove = function (event) {
me.emit('mouseMove', me.getEventProperties(event))
};
this.dom.root.onmousedown = function (event) {
me.emit('mouseDown', me.getEventProperties(event))
};
this.dom.root.onmouseup = function (event) {
me.emit('mouseUp', me.getEventProperties(event))
};
}
//Single time autoscale/fit
this.fitDone = false;
this.on('changed', function (){
if (this.itemsData == null || this.options.rollingMode) return;
if (!me.fitDone) {
me.fitDone = true;
if (me.options.start != undefined || me.options.end != undefined) {
if (me.options.start == undefined || me.options.end == undefined) {
var range = me.getItemRange();
}
var start = me.options.start != undefined ? me.options.start : range.min;
var end = me.options.end != undefined ? me.options.end : range.max;
me.setWindow(start, end, {animation: false});
}
else {
me.fit({animation: false});
}
}
});
// apply options
if (options) {
this.setOptions(options);
}
// IMPORTANT: THIS HAPPENS BEFORE SET ITEMS!
if (groups) {
this.setGroups(groups);
}
// create itemset
if (items) {
this.setItems(items);
}
// draw for the first time
this._redraw();
}
// Extend the functionality from Core
Timeline.prototype = new Core();
/**
* Load a configurator
* @return {Object}
* @private
*/
Timeline.prototype._createConfigurator = function () {
return new Configurator(this, this.dom.container, configureOptions);
};
/**
* Force a redraw. The size of all items will be recalculated.
* Can be useful to manually redraw when option autoResize=false and the window
* has been resized, or when the items CSS has been changed.
*
* Note: this function will be overridden on construction with a trottled version
*/
Timeline.prototype.redraw = function() {
this.itemSet && this.itemSet.markDirty({refreshItems: true});
this._redraw();
};
Timeline.prototype.setOptions = function (options) {
// validate options
let errorFound = Validator.validate(options, allOptions);
if (errorFound === true) {
console.log('%cErrors have been found in the supplied options object.', printStyle);
}
Core.prototype.setOptions.call(this, options);
if ('type' in options) {
if (options.type !== this.options.type) {
this.options.type = options.type;
// force recreation of all items
var itemsData = this.itemsData;
if (itemsData) {
var selection = this.getSelection();
this.setItems(null); // remove all
this.setItems(itemsData); // add all
this.setSelection(selection); // restore selection
}
}
}
};
/**
* Set items
* @param {vis.DataSet | Array | null} items
*/
Timeline.prototype.setItems = function(items) {
// convert to type DataSet when needed
var newDataSet;
if (!items) {
newDataSet = null;
}
else if (items instanceof DataSet || items instanceof DataView) {
newDataSet = items;
}
else {
// turn an array into a dataset
newDataSet = new DataSet(items, {
type: {
start: 'Date',
end: 'Date'
}
});
}
// set items
this.itemsData = newDataSet;
this.itemSet && this.itemSet.setItems(newDataSet);
};
/**
* Set groups
* @param {vis.DataSet | Array} groups
*/
Timeline.prototype.setGroups = function(groups) {
// convert to type DataSet when needed
var newDataSet;
if (!groups) {
newDataSet = null;
}
else {
var filter = function(group) {
return group.visible !== false;
}
if (groups instanceof DataSet || groups instanceof DataView) {
newDataSet = new DataView(groups,{filter: filter});
}
else {
// turn an array into a dataset
newDataSet = new DataSet(groups.filter(filter));
}
}
this.groupsData = newDataSet;
this.itemSet.setGroups(newDataSet);
};
/**
* Set both items and groups in one go
* @param {{items: Array | vis.DataSet, groups: Array | vis.DataSet}} data
*/
Timeline.prototype.setData = function (data) {
if (data && data.groups) {
this.setGroups(data.groups);
}
if (data && data.items) {
this.setItems(data.items);
}
};
/**
* Set selected items by their id. Replaces the current selection
* Unknown id's are silently ignored.
* @param {string[] | string} [ids] An array with zero or more id's of the items to be
* selected. If ids is an empty array, all items will be
* unselected.
* @param {Object} [options] Available options:
* `focus: boolean`
* If true, focus will be set to the selected item(s)
* `animation: boolean | {duration: number, easingFunction: string}`
* If true (default), the range is animated
* smoothly to the new window. An object can be
* provided to specify duration and easing function.
* Default duration is 500 ms, and default easing
* function is 'easeInOutQuad'.
* Only applicable when option focus is true.
*/
Timeline.prototype.setSelection = function(ids, options) {
this.itemSet && this.itemSet.setSelection(ids);
if (options && options.focus) {
this.focus(ids, options);
}
};
/**
* Get the selected items by their id
* @return {Array} ids The ids of the selected items
*/
Timeline.prototype.getSelection = function() {
return this.itemSet && this.itemSet.getSelection() || [];
};
/**
* Adjust the visible window such that the selected item (or multiple items)
* are centered on screen.
* @param {String | String[]} id An item id or array with item ids
* @param {Object} [options] Available options:
* `animation: boolean | {duration: number, easingFunction: string}`
* If true (default), the range is animated
* smoothly to the new window. An object can be
* provided to specify duration and easing function.
* Default duration is 500 ms, and default easing
* function is 'easeInOutQuad'.
*/
Timeline.prototype.focus = function(id, options) {
if (!this.itemsData || id == undefined) return;
var ids = Array.isArray(id) ? id : [id];
// get the specified item(s)
var itemsData = this.itemsData.getDataSet().get(ids, {
type: {
start: 'Date',
end: 'Date'
}
});
// calculate minimum start and maximum end of specified items
var start = null;
var end = null;
itemsData.forEach(function (itemData) {
var s = itemData.start.valueOf();
var e = 'end' in itemData ? itemData.end.valueOf() : itemData.start.valueOf();
if (start === null || s < start) {
start = s;
}
if (end === null || e > end) {
end = e;
}
});
if (start !== null && end !== null) {
// calculate the new middle and interval for the window
var middle = (start + end) / 2;
var interval = Math.max((this.range.end - this.range.start), (end - start) * 1.1);
var animation = (options && options.animation !== undefined) ? options.animation : true;
this.range.setRange(middle - interval / 2, middle + interval / 2, { animation: animation });
}
};
/**
* Set Timeline window such that it fits all items
* @param {Object} [options] Available options:
* `animation: boolean | {duration: number, easingFunction: string}`
* If true (default), the range is animated
* smoothly to the new window. An object can be
* provided to specify duration and easing function.
* Default duration is 500 ms, and default easing
* function is 'easeInOutQuad'.
*/
Timeline.prototype.fit = function (options) {
var animation = (options && options.animation !== undefined) ? options.animation : true;
var range;
var dataset = this.itemsData && this.itemsData.getDataSet();
if (dataset.length === 1 && dataset.get()[0].end === undefined) {
// a single item -> don't fit, just show a range around the item from -4 to +3 days
range = this.getDataRange();
this.moveTo(range.min.valueOf(), {animation});
}
else {
// exactly fit the items (plus a small margin)
range = this.getItemRange();
this.range.setRange(range.min, range.max, { animation: animation });
}
};
/**
* Determine the range of the items, taking into account their actual width
* and a margin of 10 pixels on both sides.
* @return {{min: Date | null, max: Date | null}}
*/
Timeline.prototype.getItemRange = function () {
// get a rough approximation for the range based on the items start and end dates
var range = this.getDataRange();
var min = range.min !== null ? range.min.valueOf() : null;
var max = range.max !== null ? range.max.valueOf() : null;
var minItem = null;
var maxItem = null;
if (min != null && max != null) {
var interval = (max - min); // ms
if (interval <= 0) {
interval = 10;
}
var factor = interval / this.props.center.width;
function getStart(item) {
return util.convert(item.data.start, 'Date').valueOf()
}
function getEnd(item) {
var end = item.data.end != undefined ? item.data.end : item.data.start;
return util.convert(end, 'Date').valueOf();
}
// calculate the date of the left side and right side of the items given
util.forEach(this.itemSet.items, function (item) {
if (item.groupShowing) {
item.show();
item.repositionX();
}
var start = getStart(item);
var end = getEnd(item);
if (this.options.rtl) {
var startSide = start - (item.getWidthRight() + 10) * factor;
var endSide = end + (item.getWidthLeft() + 10) * factor;
} else {
var startSide = start - (item.getWidthLeft() + 10) * factor;
var endSide = end + (item.getWidthRight() + 10) * factor;
}
if (startSide < min) {
min = startSide;
minItem = item;
}
if (endSide > max) {
max = endSide;
maxItem = item;
}
}.bind(this));
if (minItem && maxItem) {
var lhs = minItem.getWidthLeft() + 10;
var rhs = maxItem.getWidthRight() + 10;
var delta = this.props.center.width - lhs - rhs; // px
if (delta > 0) {
if (this.options.rtl) {
min = getStart(minItem) - rhs * interval / delta; // ms
max = getEnd(maxItem) + lhs * interval / delta; // ms
} else {
min = getStart(minItem) - lhs * interval / delta; // ms
max = getEnd(maxItem) + rhs * interval / delta; // ms
}
}
}
}
return {
min: min != null ? new Date(min) : null,
max: max != null ? new Date(max) : null
}
};
/**
* Calculate the data range of the items start and end dates
* @returns {{min: Date | null, max: Date | null}}
*/
Timeline.prototype.getDataRange = function() {
var min = null;
var max = null;
var dataset = this.itemsData && this.itemsData.getDataSet();
if (dataset) {
dataset.forEach(function (item) {
var start = util.convert(item.start, 'Date').valueOf();
var end = util.convert(item.end != undefined ? item.end : item.start, 'Date').valueOf();
if (min === null || start < min) {
min = start;
}
if (max === null || end > max) {
max = end;
}
});
}
return {
min: min != null ? new Date(min) : null,
max: max != null ? new Date(max) : null
}
};
/**
* Generate Timeline related information from an event
* @param {Event} event
* @return {Object} An object with related information, like on which area
* The event happened, whether clicked on an item, etc.
*/
Timeline.prototype.getEventProperties = function (event) {
var clientX = event.center ? event.center.x : event.clientX;
var clientY = event.center ? event.center.y : event.clientY;
if (this.options.rtl) {
var x = util.getAbsoluteRight(this.dom.centerContainer) - clientX;
} else {
var x = clientX - util.getAbsoluteLeft(this.dom.centerContainer);
}
var y = clientY - util.getAbsoluteTop(this.dom.centerContainer);
var item = this.itemSet.itemFromTarget(event);
var group = this.itemSet.groupFromTarget(event);
var customTime = CustomTime.customTimeFromTarget(event);
var snap = this.itemSet.options.snap || null;
var scale = this.body.util.getScale();
var step = this.body.util.getStep();
var time = this._toTime(x);
var snappedTime = snap ? snap(time, scale, step) : time;
var element = util.getTarget(event);
var what = null;
if (item != null) {what = 'item';}
else if (customTime != null) {what = 'custom-time';}
else if (util.hasParent(element, this.timeAxis.dom.foreground)) {what = 'axis';}
else if (this.timeAxis2 && util.hasParent(element, this.timeAxis2.dom.foreground)) {what = 'axis';}
else if (util.hasParent(element, this.itemSet.dom.labelSet)) {what = 'group-label';}
else if (util.hasParent(element, this.currentTime.bar)) {what = 'current-time';}
else if (util.hasParent(element, this.dom.center)) {what = 'background';}
return {
event: event,
item: item ? item.id : null,
group: group ? group.groupId : null,
what: what,
pageX: event.srcEvent ? event.srcEvent.pageX : event.pageX,
pageY: event.srcEvent ? event.srcEvent.pageY : event.pageY,
x: x,
y: y,
time: time,
snappedTime: snappedTime
}
};
/**
* Toggle Timeline rolling mode
*/
Timeline.prototype.toggleRollingMode = function () {
if (this.range.rolling) {
this.range.stopRolling();
} else {
if (this.options.rollingMode == undefined) {
this.setOptions(this.options)
}
this.range.startRolling();
}
}
module.exports = Timeline;
|
module.exports = {
command: 'pull',
desc: 'downloads remote content and merges with local',
builder: (yargs) => {
return yargs
.usage('enduro juice pull')
.options({
'force': {
alias: 'f',
describe: 'will not pull before pack, overriding whatever is in juicebar',
},
})
},
handler: function (cli_arguments) {
const enduro_instance = require('../../index')
enduro_instance.init()
.then(() => {
const juicebox = require(enduro.enduro_path + '/libs/juicebox/juicebox')
if (enduro.flags.force) {
return juicebox.pull(true)
} else {
return juicebox.pull()
}
})
}
}
|
function fn() {
var foo = () => {
return arguments;
};
}
var bar = () => arguments;
var baz = () => () => arguments;
|
import _ from 'lodash'
import { EventEmitter } from 'events'
import { setImmediate } from 'timers'
import bitcore from 'bitcore-lib'
import script2addresses from 'script2addresses'
import ElapsedTime from 'elapsed-time'
import makeConcurrent from 'make-concurrent'
import PUtils from 'promise-useful-utils'
import config from '../lib/config'
import logger from '../lib/logger'
import { ZERO_HASH } from '../lib/const'
import util from '../lib/util'
import SQL from '../lib/sql'
function callWithLock (target, name, descriptor) {
let fn = target[`${name}WithoutLock`] = descriptor.value
descriptor.value = async function () {
return this._withLock(() => fn.apply(this, arguments))
}
}
/**
* @event Sync#latest
* @param {{hash: string, height: number}} latest
*/
/**
* @event Sync#tx
* @param {string} txId
*/
/**
* @class Sync
* @extends events.EventEmitter
*/
export default class Sync extends EventEmitter {
/**
* @constructor
* @param {Storage} storage
* @param {Network} network
* @param {Service} service
*/
constructor (storage, network, service) {
super()
this._storage = storage
this._network = network
this._service = service
let networkName = config.get('chromanode.network')
this._bitcoinNetwork = bitcore.Networks.get(networkName)
this._latest = null
this._blockchainLatest = null
this._lock = new util.SmartLock()
this._orphanedTx = {
deps: {}, // txId -> txId[]
orphans: {} // txId -> txId[]
}
}
/**
*/
@makeConcurrent({concurrency: 1})
_withLock (fn) { return fn() }
/**
* @param {bitcore.Transaction.Output} output
* @return {string[]}
*/
_getAddresses (output) {
if (output.script === null) {
return []
}
let result = script2addresses(output.script.toBuffer(), this._bitcoinNetwork, false)
return result.addresses
}
/**
* @param {Objects} [opts]
* @param {pg.Client} [opts.client]
* @return {Promise<{hash: string, height: number}>}
*/
_getLatest (opts) {
let execute = ::this._storage.executeTransaction
if (_.has(opts, 'client')) {
execute = (fn) => fn(opts.client)
}
return execute(async (client) => {
let result = await client.queryAsync(SQL.select.blocks.latest)
if (result.rowCount === 0) {
return {hash: ZERO_HASH, height: -1}
}
let row = result.rows[0]
return {hash: row.hash.toString('hex'), height: row.height}
})
}
_importOrphaned (txId) {
// are we have orphaned tx that depends from this txId?
let orphans = this._orphanedTx.orphans[txId]
if (orphans === undefined) {
return
}
delete this._orphanedTx.orphans[txId]
// check every orphaned tx
for (let orphaned of orphans) {
// all deps resolved?
let deps = _.without(this._orphanedTx.deps[orphaned], txId)
if (deps.length > 0) {
this._orphanedTx.deps[orphaned] = deps
continue
}
// run import if all resolved transactions
delete this._orphanedTx.deps[orphaned]
setImmediate(() => this._runTxImports([orphaned]))
logger.warn(`Run import for orphaned tx: ${orphaned}`)
}
}
/**
* @param {bitcore.Transaction} tx
* @return {Promise}
*/
_importUnconfirmedTx (tx) {
let txId = tx.id
let prevTxIds = _.uniq(
tx.inputs.map((input) => input.prevTxId.toString('hex')))
return this._lock.withLock(prevTxIds.concat(txId), () => {
let stopwatch = ElapsedTime.new().start()
return this._storage.executeTransaction(async (client) => {
// transaction already in database?
let result = await client.queryAsync(
SQL.select.transactions.exists, [`\\x${txId}`])
if (result.rows[0].exists === true) {
return true
}
// all inputs exists?
result = await client.queryAsync(
SQL.select.transactions.existsMany, [prevTxIds.map((i) => `\\x${i}`)])
let deps = _.difference(
prevTxIds, result.rows.map((row) => row.txid.toString('hex')))
// some input not exists yet, mark as orphaned and delay
if (deps.length > 0) {
this._orphanedTx.deps[txId] = deps
for (let dep of deps) {
this._orphanedTx.orphans[dep] = _.union(this._orphanedTx.orphans[dep], [txId])
}
logger.warn(`Orphan tx: ${txId} (deps: ${deps.join(', ')})`)
return false
}
// import transaction
let pImportTx = client.queryAsync(SQL.insert.transactions.unconfirmed, [
`\\x${txId}`,
`\\x${tx.toString()}`
])
// import intputs
let pImportInputs = tx.inputs.map(async (input, index) => {
let {rows} = await client.queryAsync(SQL.update.history.addUnconfirmedInput, [
`\\x${txId}`,
`\\x${input.prevTxId.toString('hex')}`,
input.outputIndex
])
return rows.map((row) => {
let address = row.address.toString()
return this._service.broadcastAddress(address, txId, null, null, {client: client})
})
})
// import outputs
let pImportOutputs = tx.outputs.map((output, index) => {
let addresses = this._getAddresses(output)
return addresses.map((address) => {
let pImport = client.queryAsync(SQL.insert.history.unconfirmedOutput, [
address,
`\\x${txId}`,
index,
output.satoshis,
`\\x${output.script.toHex()}`
])
let pBroadcast = this._service.broadcastAddress(address, txId, null, null, {client: client})
return [pImport, pBroadcast]
})
})
// wait all imports and broadcasts
await* _.flattenDeep([
pImportTx,
pImportInputs,
pImportOutputs,
this._service.broadcastTx(txId, null, null, {client: client}),
this._service.addTx(txId, false, {client: client})
])
logger.verbose(`Import unconfirmed tx ${txId}, elapsed time: ${stopwatch.getValue()}`)
return true
})
.catch((err) => {
logger.error(`Import unconfirmed tx: ${err.stack}`)
return false
})
})
}
/**
* @param {string[]} txIds
*/
_runTxImports (txIds) {
let self = this
let concurrency = 10
let done = 0
return new Promise((resolve) => {
async function next (index) {
if (index >= txIds.length) {
if (done === txIds.length) {
resolve()
}
return
}
let txId = txIds[index]
try {
// get tx from bitcoind
let tx = await self._network.getTx(txId)
// ... and run import
let imported = await self._importUnconfirmedTx(tx)
if (imported) {
setImmediate(::self._importOrphaned, txId)
self.emit('tx', txId)
}
} catch (err) {
logger.error(`Tx import (${txId}): ${err.stack}`)
}
done += 1
next(index + concurrency)
}
for (let i = 0; i < concurrency; ++i) { next(i) }
})
.catch(err => {
logger.error(`_runTxImports (txIds.length is ${txIds.length}): ${err.stack}`)
})
}
/**
* @param {bitcore.Block} block
* @param {number} height
* @param {pg.Client} client
* @return {Promise}
*/
_importBlock (block, height, client) {
let txIds = _.pluck(block.transactions, 'id')
let existingTx = {}
let allTxIds = _.uniq(_.flatten(block.transactions.map((tx) => {
return tx.inputs.map((i) => i.prevTxId.toString('hex'))
}).concat(txIds)))
return this._lock.withLock(allTxIds, async () => {
// import header
let pImportHeader = client.queryAsync(SQL.insert.blocks.row, [
height,
`\\x${block.hash}`,
`\\x${block.header.toString()}`,
`\\x${txIds.join('')}`
])
// import transactions & outputs
let pImportTxAndOutputs = await* block.transactions.map(async (tx, txIndex) => {
let txId = txIds[txIndex]
let pImportTx
let pBroadcastAddreses
// tx already in storage ?
let result = await client.queryAsync(SQL.select.transactions.exists, [`\\x${txId}`])
// if already exist, mark output as confirmed and broadcast addresses
if (result.rows[0].exists === true) {
existingTx[txId] = true
pBroadcastAddreses = PUtils.try(async () => {
let [, {rows}] = await* [
client.queryAsync(SQL.update.transactions.makeConfirmed, [height, `\\x${txId}`]),
client.queryAsync(SQL.update.history.makeOutputConfirmed, [height, `\\x${txId}`])
]
return rows.map((row) => {
let address = row.address.toString()
return this._service.broadcastAddress(address, txId, block.hash, height, {client: client})
})
})
} else {
// import transaction
pImportTx = client.queryAsync(SQL.insert.transactions.confirmed, [
`\\x${txId}`,
height,
`\\x${tx.toString()}`
])
// import outputs only if transaction not imported yet
pBroadcastAddreses = await* tx.outputs.map((output, index) => {
let addresses = this._getAddresses(output)
return Promise.all(addresses.map(async (address) => {
// wait output import, it's important!
await client.queryAsync(SQL.insert.history.confirmedOutput, [
address,
`\\x${txId}`,
index,
output.satoshis,
`\\x${output.script.toHex()}`,
height
])
return this._service.broadcastAddress(address, txId, block.hash, height, {client: client})
}))
})
}
return [
pImportTx,
this._service.broadcastTx(txId, block.hash, height, {client: client}),
this._service.addTx(txId, true, {client: client}),
pBroadcastAddreses
]
})
// import inputs
let pImportInputs = block.transactions.map((tx, txIndex) => {
let txId = txIds[txIndex]
return tx.inputs.map(async (input, index) => {
// skip coinbase
let prevTxId = input.prevTxId.toString('hex')
if (index === 0 &&
input.outputIndex === 0xFFFFFFFF &&
prevTxId === ZERO_HASH) {
return
}
let result
if (existingTx[txId] === true) {
result = await client.queryAsync(SQL.update.history.makeInputConfirmed, [
height,
`\\x${prevTxId}`,
input.outputIndex
])
} else {
result = await client.queryAsync(SQL.update.history.addConfirmedInput, [
`\\x${txId}`,
height,
`\\x${prevTxId}`,
input.outputIndex
])
}
await* result.rows.map((row) => {
let address = row.address.toString()
return this._service.broadcastAddress(address, txId, block.hash, height, {client: client})
})
})
})
await* _.flattenDeep([
pImportHeader,
pImportTxAndOutputs,
pImportInputs,
this._service.broadcastBlock(block.hash, height, {client: client}),
this._service.addBlock(block.hash, {client: client})
])
})
}
/**
* @param {boolean} [updateBitcoindMempool=false]
* @return {Promise}
*/
@callWithLock
async _runBlockImport (updateBitcoindMempool = false) {
let stopwatch = new ElapsedTime()
let block
while (true) {
try {
this._blockchainLatest = await this._network.getLatest()
while (true) {
// are blockchain have new blocks?
if (this._latest.height === this._blockchainLatest.height) {
this._blockchainLatest = await this._network.getLatest()
}
// synced with bitcoind, out
if (this._latest.hash === this._blockchainLatest.hash) {
break
}
// find latest block in storage that located in blockchain
let latest = this._latest
while (true) {
stopwatch.reset().start()
let blockHeight = Math.min(latest.height + 1, this._blockchainLatest.height)
block = await this._network.getBlock(blockHeight)
logger.verbose(`Downloading block ${blockHeight}, elapsed time: ${stopwatch.getValue()}`)
// found latest that we need
if (latest.hash === util.encode(block.header.prevHash)) {
break
}
// update latest
let {rows} = await this._storage.executeQuery(
SQL.select.blocks.byHeight, [latest.height - 1])
latest = {hash: rows[0].hash.toString('hex'), height: rows[0].height}
}
// was reorg found?
let reorgProcess = latest.hash !== this._latest.hash
while (latest.hash !== this._latest.hash) {
let height = Math.max(latest.height, this._latest.height - 1) // or Allocation failed on large reorgs
await this._lock.exclusiveLock(async () => {
stopwatch.reset().start()
this._latest = await this._storage.executeTransaction(async (client) => {
let blocks = await client.queryAsync(SQL.delete.blocks.fromHeight, [height])
let txs = await client.queryAsync(SQL.update.transactions.makeUnconfirmed, [height])
let hist1 = await client.queryAsync(SQL.update.history.makeOutputsUnconfirmed, [height])
let hist2 = await client.queryAsync(SQL.update.history.makeInputsUnconfirmed, [height])
await* _.flattenDeep([
blocks.rows.map((row) => {
return this._service.removeBlock(
row.hash.toString('hex'), {client: client})
}),
txs.rows.map((row) => {
return this._service.broadcastTx(
row.txid.toString('hex'), null, null, {client: client})
}),
hist1.rows.concat(hist2.rows).map((row) => {
return this._service.broadcastAddress(
row.address.toString(), row.txid.toString('hex'), null, null, {client: client})
})
])
return await this._getLatest({client: client})
})
logger.warn(`Make reorg step (back to ${height - 1}), elapsed time: ${stopwatch.getValue()}`)
})
}
if (reorgProcess) {
logger.warn(`Reorg finished (back to ${latest.height}), elapsed time: ${stopwatch.getValue()}`)
}
// import block
stopwatch.reset().start()
this._latest = await this._storage.executeTransaction(async (client) => {
await this._importBlock(block, latest.height + 1, client)
return await this._getLatest({client: client})
})
logger.verbose(`Import block #${latest.height + 1}, elapsed time: ${stopwatch.getValue()} (hash: ${this._latest.hash})`)
logger.info(`New latest! ${this._latest.hash}:${this._latest.height}`)
this.emit('latest', this._latest)
// notify that tx was imported
for (let txId of _.pluck(block.transactions, 'id')) {
setImmediate(::this._importOrphaned, txId)
this.emit('tx', txId)
}
}
break
} catch (err) {
logger.error(`Block import error: ${err.stack}`)
while (true) {
try {
this._latest = await this._getLatest()
break
} catch (err) {
logger.error(`Block import (get latest): ${err.stack}`)
await PUtils.delay(1000)
}
}
}
}
await this._runMempoolUpdateWithoutLock(updateBitcoindMempool)
}
/**
* @param {boolean} [updateBitcoindMempool=false]
* @return {Promise}
*/
@callWithLock
async _runMempoolUpdate (updateBitcoindMempool) {
let stopwatch = new ElapsedTime()
while (true) {
// sync with bitcoind mempool
try {
stopwatch.reset().start()
let [nTxIds, sTxIds] = await* [
this._network.getMempoolTxs(),
this._storage.executeQuery(SQL.select.transactions.unconfirmed)
]
sTxIds = sTxIds.rows.map((row) => row.txid.toString('hex'))
let rTxIds = _.difference(sTxIds, nTxIds)
if (rTxIds.length > 0 && updateBitcoindMempool) {
let {rows} = await this._storage.executeQuery(
SQL.select.transactions.byTxIds, [rTxIds.map((txId) => `\\x${txId}`)])
rTxIds = []
let txs = util.toposort(rows.map((row) => bitcore.Transaction(row.tx)))
while (txs.length > 0) {
let tx = txs.pop()
try {
await this._network.sendTx(tx.toString())
} catch (err) {
rTxIds.push(tx.id)
}
}
}
// remove tx that not in mempool but in our storage
if (rTxIds.length > 0) {
await this._lock.exclusiveLock(async () => {
for (let start = 0; start < rTxIds.length; start += 250) {
let txIds = rTxIds.slice(start, start + 250)
await this._storage.executeTransaction(async (client) => {
while (txIds.length > 0) {
let result = await client.queryAsync(
SQL.delete.transactions.unconfirmedByTxIds, [txIds.map((txId) => `\\x${txId}`)])
if (result.rows.length === 0) {
return
}
let removedTxIds = result.rows.map((row) => row.txid.toString('hex'))
let params = [removedTxIds.map((txId) => `\\x${txId}`)]
result = await client.queryAsync(SQL.delete.history.unconfirmedByTxIds, params)
txIds = _.filter(result.rows, 'txid').map((row) => row.txid.toString('hex'))
await client.queryAsync(SQL.update.history.deleteUnconfirmedInputsByTxIds, params)
await* removedTxIds.map((txId) => this._service.removeTx(txId, false, {client: client}))
}
})
}
})
}
// add skipped tx in our storage
this._runTxImports(_.difference(nTxIds, sTxIds))
logger.info(`Update mempool finished, elapsed time: ${stopwatch.getValue()}`)
break
} catch (err) {
logger.error(`On updating mempool: ${err.stack}`)
await PUtils.delay(5000)
}
}
}
/**
*/
async run () {
// update latests
this._latest = await this._getLatest()
this._blockchainLatest = await this._network.getLatest()
// show info message
logger.info(`Got ${this._latest.height + 1} blocks in current db, out of ${this._blockchainLatest.height + 1} block at bitcoind`)
// make sure that we have latest block
await this._runBlockImport(true)
// set handlers
this._network.on('connect', () => this._runMempoolUpdate(true))
this._network.on('tx', txId => this._runTxImports([txId]))
this._network.on('block', ::this._runBlockImport)
// and run sync again
await this._runBlockImport(true)
}
}
|
var _ = require('lodash'),
api = require('../../../api'),
config = require('../../../config'),
BaseMapGenerator = require('./base-generator');
// A class responsible for generating a sitemap from posts and keeping it updated
function TagsMapGenerator(opts) {
_.extend(this, opts);
BaseMapGenerator.apply(this, arguments);
}
// Inherit from the base generator class
_.extend(TagsMapGenerator.prototype, BaseMapGenerator.prototype);
_.extend(TagsMapGenerator.prototype, {
bindEvents: function () {
var self = this;
this.dataEvents.on('tag.added', self.addOrUpdateUrl.bind(self));
this.dataEvents.on('tag.edited', self.addOrUpdateUrl.bind(self));
this.dataEvents.on('tag.deleted', self.removeUrl.bind(self));
},
getData: function () {
return api.tags.browse({
context: {
internal: true
},
filter: 'visibility:public',
limit: 'all'
}).then(function (resp) {
return resp.tags;
});
},
getUrlForDatum: function (tag) {
return config.urlFor('tag', {tag: tag}, true);
},
getPriorityForDatum: function () {
// TODO: We could influence this with meta information
return 0.6;
}
});
module.exports = TagsMapGenerator;
|
module.exports = function() {
this.checkoutStrategy = 1;
this.disableFilters = 0;
this.dirMode = 0;
this.fileMode = 0;
this.fileOpenFlags = 0;
this.notifyFlags = 0;
};
|
(function () {
'use strict';
angular
.module('app.services')
.factory('speakerService', speakerService);
speakerService.$inject = ['$http'];
function speakerService($http){
return {
getSpeakers : getSpeakers
};
function getSpeakers () {
return $http.get('/api/speakers')
.then(getSpeakersComplete)
.catch(getSpeakersFailed);
function getSpeakersComplete(response) {
return response.data;
}
function getSpeakersFailed(error){
// todo: should implement logger
return error;
}
}
}
})(); |
// Load modules
var Url = require('url');
var Code = require('code');
var Hawk = require('../lib');
var Lab = require('lab');
// Declare internals
var internals = {};
// Test shortcuts
var lab = exports.lab = Lab.script();
var describe = lab.experiment;
var it = lab.test;
var expect = Code.expect;
describe('Client', function () {
describe('header()', function () {
it('returns a valid authorization header (sha1)', function (done) {
var credentials = {
id: '123456',
key: '2983d45yun89q',
algorithm: 'sha1'
};
var header = Hawk.client.header('http://example.net/somewhere/over/the/rainbow', 'POST', {credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about'}).field;
expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="bsvY3IfUllw6V5rvk4tStEvpBhE=", ext="Bazinga!", mac="qbf1ZPG/r/e06F4ht+T77LXi5vw="');
done();
});
it('returns a valid authorization header (sha256)', function (done) {
var credentials = {
id: '123456',
key: '2983d45yun89q',
algorithm: 'sha256'
};
var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', {credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain'}).field;
expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", ext="Bazinga!", mac="q1CwFoSHzPZSkbIvl0oYlD+91rBUEvFk763nMjMndj8="');
done();
});
it('returns a valid authorization header (no ext)', function (done) {
var credentials = {
id: '123456',
key: '2983d45yun89q',
algorithm: 'sha256'
};
var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', {credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain'}).field;
expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", mac="HTgtd0jPI6E4izx8e4OHdO36q00xFCU0FolNq3RiCYs="');
done();
});
it('returns a valid authorization header (null ext)', function (done) {
var credentials = {
id: '123456',
key: '2983d45yun89q',
algorithm: 'sha256'
};
var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', {credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain', ext: null}).field;
expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", mac="HTgtd0jPI6E4izx8e4OHdO36q00xFCU0FolNq3RiCYs="');
done();
});
it('returns a valid authorization header (empty payload)', function (done) {
var credentials = {
id: '123456',
key: '2983d45yun89q',
algorithm: 'sha256'
};
var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', {credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: '', contentType: 'text/plain'}).field;
expect(header).to.equal('Hawk id=\"123456\", ts=\"1353809207\", nonce=\"Ygvqdz\", hash=\"q/t+NNAkQZNlq/aAD6PlexImwQTxwgT2MahfTa9XRLA=\", mac=\"U5k16YEzn3UnBHKeBzsDXn067Gu3R4YaY6xOt9PYRZM=\"');
done();
});
it('returns a valid authorization header (pre hashed payload)', function (done) {
var credentials = {
id: '123456',
key: '2983d45yun89q',
algorithm: 'sha256'
};
var options = {credentials: credentials, timestamp: 1353809207, nonce: 'Ygvqdz', payload: 'something to write about', contentType: 'text/plain'};
options.hash = Hawk.crypto.calculatePayloadHash(options.payload, credentials.algorithm, options.contentType);
var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', options).field;
expect(header).to.equal('Hawk id="123456", ts="1353809207", nonce="Ygvqdz", hash="2QfCt3GuY9HQnHWyWD3wX68ZOKbynqlfYmuO2ZBRqtY=", mac="HTgtd0jPI6E4izx8e4OHdO36q00xFCU0FolNq3RiCYs="');
done();
});
it('errors on missing uri', function (done) {
var header = Hawk.client.header('', 'POST');
expect(header.field).to.equal('');
expect(header.err).to.equal('Invalid argument type');
done();
});
it('errors on invalid uri', function (done) {
var header = Hawk.client.header(4, 'POST');
expect(header.field).to.equal('');
expect(header.err).to.equal('Invalid argument type');
done();
});
it('errors on missing method', function (done) {
var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', '');
expect(header.field).to.equal('');
expect(header.err).to.equal('Invalid argument type');
done();
});
it('errors on invalid method', function (done) {
var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 5);
expect(header.field).to.equal('');
expect(header.err).to.equal('Invalid argument type');
done();
});
it('errors on missing options', function (done) {
var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST');
expect(header.field).to.equal('');
expect(header.err).to.equal('Invalid argument type');
done();
});
it('errors on invalid credentials (id)', function (done) {
var credentials = {
key: '2983d45yun89q',
algorithm: 'sha256'
};
var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', {credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207});
expect(header.field).to.equal('');
expect(header.err).to.equal('Invalid credential object');
done();
});
it('errors on missing credentials', function (done) {
var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', {ext: 'Bazinga!', timestamp: 1353809207});
expect(header.field).to.equal('');
expect(header.err).to.equal('Invalid credential object');
done();
});
it('errors on invalid credentials', function (done) {
var credentials = {
id: '123456',
algorithm: 'sha256'
};
var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', {credentials: credentials, ext: 'Bazinga!', timestamp: 1353809207});
expect(header.field).to.equal('');
expect(header.err).to.equal('Invalid credential object');
done();
});
it('errors on invalid algorithm', function (done) {
var credentials = {
id: '123456',
key: '2983d45yun89q',
algorithm: 'hmac-sha-0'
};
var header = Hawk.client.header('https://example.net/somewhere/over/the/rainbow', 'POST', {credentials: credentials, payload: 'something, anything!', ext: 'Bazinga!', timestamp: 1353809207});
expect(header.field).to.equal('');
expect(header.err).to.equal('Unknown algorithm');
done();
});
});
describe('authenticate()', function () {
it('returns false on invalid header', function (done) {
var res = {
headers: {
'server-authorization': 'Hawk mac="abc", bad="xyz"'
}
};
expect(Hawk.client.authenticate(res, {})).to.equal(false);
done();
});
it('returns false on invalid mac', function (done) {
var res = {
headers: {
'content-type': 'text/plain',
'server-authorization': 'Hawk mac="_IJRsMl/4oL+nn+vKoeVZPdCHXB4yJkNnBbTbHFZUYE=", hash="f9cDF/TDm7TkYRLnGwRMfeDzT6LixQVLvrIKhh0vgmM=", ext="response-specific"'
}
};
var artifacts = {
method: 'POST',
host: 'example.com',
port: '9000',
resource: '/resource/4?filter=a',
ts: '1362336900',
nonce: 'eb5S_L',
hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=',
ext: 'some-app-data',
app: undefined,
dlg: undefined,
mac: 'BlmSe8K+pbKIb6YsZCnt4E1GrYvY1AaYayNR82dGpIk=',
id: '123456'
};
var credentials = {
id: '123456',
key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
algorithm: 'sha256',
user: 'steve'
};
expect(Hawk.client.authenticate(res, credentials, artifacts)).to.equal(false);
done();
});
it('returns true on ignoring hash', function (done) {
var res = {
headers: {
'content-type': 'text/plain',
'server-authorization': 'Hawk mac="XIJRsMl/4oL+nn+vKoeVZPdCHXB4yJkNnBbTbHFZUYE=", hash="f9cDF/TDm7TkYRLnGwRMfeDzT6LixQVLvrIKhh0vgmM=", ext="response-specific"'
}
};
var artifacts = {
method: 'POST',
host: 'example.com',
port: '9000',
resource: '/resource/4?filter=a',
ts: '1362336900',
nonce: 'eb5S_L',
hash: 'nJjkVtBE5Y/Bk38Aiokwn0jiJxt/0S2WRSUwWLCf5xk=',
ext: 'some-app-data',
app: undefined,
dlg: undefined,
mac: 'BlmSe8K+pbKIb6YsZCnt4E1GrYvY1AaYayNR82dGpIk=',
id: '123456'
};
var credentials = {
id: '123456',
key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
algorithm: 'sha256',
user: 'steve'
};
expect(Hawk.client.authenticate(res, credentials, artifacts)).to.equal(true);
done();
});
it('fails on invalid WWW-Authenticate header format', function (done) {
var header = 'Hawk ts="1362346425875", tsm="PhwayS28vtnn3qbv0mqRBYSXebN/zggEtucfeZ620Zo=", x="Stale timestamp"';
expect(Hawk.client.authenticate({headers: {'www-authenticate': header}}, {})).to.equal(false);
done();
});
it('fails on invalid WWW-Authenticate header format', function (done) {
var credentials = {
id: '123456',
key: 'werxhqb98rpaxn39848xrunpaw3489ruxnpa98w4rxn',
algorithm: 'sha256',
user: 'steve'
};
var header = 'Hawk ts="1362346425875", tsm="hwayS28vtnn3qbv0mqRBYSXebN/zggEtucfeZ620Zo=", error="Stale timestamp"';
expect(Hawk.client.authenticate({headers: {'www-authenticate': header}}, credentials)).to.equal(false);
done();
});
it('skips tsm validation when missing ts', function (done) {
var header = 'Hawk error="Stale timestamp"';
expect(Hawk.client.authenticate({headers: {'www-authenticate': header}}, {})).to.equal(true);
done();
});
});
describe('message()', function () {
it('generates authorization', function (done) {
var credentials = {
id: '123456',
key: '2983d45yun89q',
algorithm: 'sha1'
};
var auth = Hawk.client.message('example.com', 80, 'I am the boodyman', {credentials: credentials, timestamp: 1353809207, nonce: 'abc123'});
expect(auth).to.exist();
expect(auth.ts).to.equal(1353809207);
expect(auth.nonce).to.equal('abc123');
done();
});
it('errors on invalid host', function (done) {
var credentials = {
id: '123456',
key: '2983d45yun89q',
algorithm: 'sha1'
};
var auth = Hawk.client.message(5, 80, 'I am the boodyman', {credentials: credentials, timestamp: 1353809207, nonce: 'abc123'});
expect(auth).to.not.exist();
done();
});
it('errors on invalid port', function (done) {
var credentials = {
id: '123456',
key: '2983d45yun89q',
algorithm: 'sha1'
};
var auth = Hawk.client.message('example.com', '80', 'I am the boodyman', {credentials: credentials, timestamp: 1353809207, nonce: 'abc123'});
expect(auth).to.not.exist();
done();
});
it('errors on missing host', function (done) {
var credentials = {
id: '123456',
key: '2983d45yun89q',
algorithm: 'sha1'
};
var auth = Hawk.client.message('example.com', 0, 'I am the boodyman', {credentials: credentials, timestamp: 1353809207, nonce: 'abc123'});
expect(auth).to.not.exist();
done();
});
it('errors on null message', function (done) {
var credentials = {
id: '123456',
key: '2983d45yun89q',
algorithm: 'sha1'
};
var auth = Hawk.client.message('example.com', 80, null, {credentials: credentials, timestamp: 1353809207, nonce: 'abc123'});
expect(auth).to.not.exist();
done();
});
it('errors on missing message', function (done) {
var credentials = {
id: '123456',
key: '2983d45yun89q',
algorithm: 'sha1'
};
var auth = Hawk.client.message('example.com', 80, undefined, {credentials: credentials, timestamp: 1353809207, nonce: 'abc123'});
expect(auth).to.not.exist();
done();
});
it('errors on invalid message', function (done) {
var credentials = {
id: '123456',
key: '2983d45yun89q',
algorithm: 'sha1'
};
var auth = Hawk.client.message('example.com', 80, 5, {credentials: credentials, timestamp: 1353809207, nonce: 'abc123'});
expect(auth).to.not.exist();
done();
});
it('errors on missing options', function (done) {
var credentials = {
id: '123456',
key: '2983d45yun89q',
algorithm: 'sha1'
};
var auth = Hawk.client.message('example.com', 80, 'I am the boodyman');
expect(auth).to.not.exist();
done();
});
it('errors on invalid credentials (id)', function (done) {
var credentials = {
key: '2983d45yun89q',
algorithm: 'sha1'
};
var auth = Hawk.client.message('example.com', 80, 'I am the boodyman', {credentials: credentials, timestamp: 1353809207, nonce: 'abc123'});
expect(auth).to.not.exist();
done();
});
it('errors on invalid credentials (key)', function (done) {
var credentials = {
id: '123456',
algorithm: 'sha1'
};
var auth = Hawk.client.message('example.com', 80, 'I am the boodyman', {credentials: credentials, timestamp: 1353809207, nonce: 'abc123'});
expect(auth).to.not.exist();
done();
});
});
});
|
(function(global) {
// simplified version of Object.assign for es3
function assign() {
var result = {};
for (var i = 0, len = arguments.length; i < len; i++) {
var arg = arguments[i];
for (var prop in arg) {
result[prop] = arg[prop];
}
}
return result;
}
var sjsPaths = {};
if (typeof systemJsPaths !== "undefined") {
sjsPaths = systemJsPaths;
}
System.config({
transpiler: 'plugin-babel',
defaultExtension: 'js',
paths: assign(
{
// paths serve as alias
"npm:": "https://unpkg.com/",
}, sjsPaths),
map: assign(
{
// css plugin
'css': 'npm:systemjs-plugin-css/css.js',
// babel transpiler
'plugin-babel': 'npm:systemjs-plugin-babel@0.0.25/plugin-babel.js',
'systemjs-babel-build': 'npm:systemjs-plugin-babel@0.0.25/systemjs-babel-browser.js',
// react
react: 'npm:react@16.12.0',
'react-dom': 'npm:react-dom@16.12.0',
'react-dom-factories': 'npm:react-dom-factories',
redux: 'npm:redux@3.6.0',
'react-redux': 'npm:react-redux@5.0.6',
'prop-types': 'npm:prop-types',
'object-assign': 'npm:object-assign',
'cookie': 'npm:cookie',
'react-color': 'npm:react-color@2.17.3',
'reactcss': 'npm:reactcss@1.2.3',
'lodash': 'npm:lodash@4.17.15',
'material-colors': 'npm:material-colors@1.2.6',
'@icons/material': 'npm:@icons/material@0.2.4',
'tinycolor2': 'npm:tinycolor2@1.4.1',
'prismjs': 'npm:prismjs@1.21.0',
app: appLocation + 'app'
},
systemJsMap
), // systemJsMap comes from index.html
packages: {
react: {
main: './umd/react.production.min.js'
},
'react-dom': {
main: './umd/react-dom.production.min.js'
},
'prop-types': {
main: './prop-types.min.js',
defaultExtension: 'js'
},
redux: {
main: './dist/redux.min.js',
defaultExtension: 'js'
},
'react-redux': {
main: './dist/react-redux.min.js',
defaultExtension: 'js'
},
'react-color': {
main: './lib/index.js',
map: {
'./lib/components/common': './lib/components/common/index.js'
}
},
'reactcss': {
main: './lib/index.js',
},
'lodash': {
main: './lodash.min.js',
},
'material-colors': {
main: './dist/colors.js',
},
'tinycolor2': {
main: './dist/tinycolor-min.js',
},
app: {
defaultExtension: 'jsx'
}
},
meta: {
'*.jsx': {
babelOptions: {
react: true
}
},
'*.css': { loader: 'css' }
}
});
})(this);
|
/**
* Copyright (c) Tiny Technologies, Inc. All rights reserved.
* Licensed under the LGPL or a commercial license.
* For LGPL see License.txt in the project root for license information.
* For commercial licenses see https://www.tiny.cloud/
*
* Version: 5.1.6 (2020-01-28)
*/
(function () {
'use strict';
var Cell = function (initial) {
var value = initial;
var get = function () {
return value;
};
var set = function (v) {
value = v;
};
var clone = function () {
return Cell(get());
};
return {
get: get,
set: set,
clone: clone
};
};
var global = tinymce.util.Tools.resolve('tinymce.PluginManager');
var global$1 = tinymce.util.Tools.resolve('tinymce.Env');
var global$2 = tinymce.util.Tools.resolve('tinymce.util.Delay');
var fireResizeEditor = function (editor) {
return editor.fire('ResizeEditor');
};
var Events = { fireResizeEditor: fireResizeEditor };
var getAutoResizeMinHeight = function (editor) {
return editor.getParam('min_height', editor.getElement().offsetHeight, 'number');
};
var getAutoResizeMaxHeight = function (editor) {
return editor.getParam('max_height', 0, 'number');
};
var getAutoResizeOverflowPadding = function (editor) {
return editor.getParam('autoresize_overflow_padding', 1, 'number');
};
var getAutoResizeBottomMargin = function (editor) {
return editor.getParam('autoresize_bottom_margin', 50, 'number');
};
var shouldAutoResizeOnInit = function (editor) {
return editor.getParam('autoresize_on_init', true, 'boolean');
};
var Settings = {
getAutoResizeMinHeight: getAutoResizeMinHeight,
getAutoResizeMaxHeight: getAutoResizeMaxHeight,
getAutoResizeOverflowPadding: getAutoResizeOverflowPadding,
getAutoResizeBottomMargin: getAutoResizeBottomMargin,
shouldAutoResizeOnInit: shouldAutoResizeOnInit
};
var isFullscreen = function (editor) {
return editor.plugins.fullscreen && editor.plugins.fullscreen.isFullscreen();
};
var wait = function (editor, oldSize, times, interval, callback) {
global$2.setEditorTimeout(editor, function () {
resize(editor, oldSize);
if (times--) {
wait(editor, oldSize, times, interval, callback);
} else if (callback) {
callback();
}
}, interval);
};
var toggleScrolling = function (editor, state) {
var body = editor.getBody();
if (body) {
body.style.overflowY = state ? '' : 'hidden';
if (!state) {
body.scrollTop = 0;
}
}
};
var parseCssValueToInt = function (dom, elm, name, computed) {
var value = parseInt(dom.getStyle(elm, name, computed), 10);
return isNaN(value) ? 0 : value;
};
var resize = function (editor, oldSize) {
var deltaSize, resizeHeight, contentHeight;
var dom = editor.dom;
var doc = editor.getDoc();
if (!doc) {
return;
}
if (isFullscreen(editor)) {
toggleScrolling(editor, true);
return;
}
var docEle = doc.documentElement;
var resizeBottomMargin = Settings.getAutoResizeBottomMargin(editor);
resizeHeight = Settings.getAutoResizeMinHeight(editor);
var marginTop = parseCssValueToInt(dom, docEle, 'margin-top', true);
var marginBottom = parseCssValueToInt(dom, docEle, 'margin-bottom', true);
contentHeight = docEle.offsetHeight + marginTop + marginBottom + resizeBottomMargin;
if (contentHeight < 0) {
contentHeight = 0;
}
var containerHeight = editor.getContainer().offsetHeight;
var contentAreaHeight = editor.getContentAreaContainer().offsetHeight;
var chromeHeight = containerHeight - contentAreaHeight;
if (contentHeight + chromeHeight > Settings.getAutoResizeMinHeight(editor)) {
resizeHeight = contentHeight + chromeHeight;
}
var maxHeight = Settings.getAutoResizeMaxHeight(editor);
if (maxHeight && resizeHeight > maxHeight) {
resizeHeight = maxHeight;
toggleScrolling(editor, true);
} else {
toggleScrolling(editor, false);
}
if (resizeHeight !== oldSize.get()) {
deltaSize = resizeHeight - oldSize.get();
dom.setStyle(editor.getContainer(), 'height', resizeHeight + 'px');
oldSize.set(resizeHeight);
Events.fireResizeEditor(editor);
if (global$1.browser.isSafari() && global$1.mac) {
var win = editor.getWin();
win.scrollTo(win.pageXOffset, win.pageYOffset);
}
if (editor.hasFocus()) {
editor.selection.scrollIntoView(editor.selection.getNode());
}
if (global$1.webkit && deltaSize < 0) {
resize(editor, oldSize);
}
}
};
var setup = function (editor, oldSize) {
editor.on('init', function () {
var overflowPadding = Settings.getAutoResizeOverflowPadding(editor);
var dom = editor.dom;
dom.setStyles(editor.getBody(), {
'paddingLeft': overflowPadding,
'paddingRight': overflowPadding,
'min-height': 0
});
});
editor.on('NodeChange SetContent keyup FullscreenStateChanged ResizeContent', function () {
resize(editor, oldSize);
});
if (Settings.shouldAutoResizeOnInit(editor)) {
editor.on('init', function () {
wait(editor, oldSize, 20, 100, function () {
wait(editor, oldSize, 5, 1000);
});
});
}
};
var Resize = {
setup: setup,
resize: resize
};
var register = function (editor, oldSize) {
editor.addCommand('mceAutoResize', function () {
Resize.resize(editor, oldSize);
});
};
var Commands = { register: register };
function Plugin () {
global.add('autoresize', function (editor) {
if (!editor.settings.hasOwnProperty('resize')) {
editor.settings.resize = false;
}
if (!editor.inline) {
var oldSize = Cell(0);
Commands.register(editor, oldSize);
Resize.setup(editor, oldSize);
}
});
}
Plugin();
}());
|
"use strict";
var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;
var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _jsxRuntime = require("../../lib/jsxRuntime");
var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));
var _objectWithoutProperties2 = _interopRequireDefault(require("@babel/runtime/helpers/objectWithoutProperties"));
var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
var React = _interopRequireWildcard(require("react"));
var _dom = require("../../lib/dom");
var _ConfigProviderContext = require("./ConfigProviderContext");
var _useIsomorphicLayoutEffect = require("../../lib/useIsomorphicLayoutEffect");
var _useObjectMemo = require("../../hooks/useObjectMemo");
var _utils = require("../../lib/utils");
var _warnOnce = require("../../lib/warnOnce");
var _scheme2 = require("../../helpers/scheme");
var _AppearanceProvider = require("../AppearanceProvider/AppearanceProvider");
var _excluded = ["children"];
var warn = (0, _warnOnce.warnOnce)("ConfigProvider");
function useSchemeDetector(node, _scheme) {
var inherit = _scheme === "inherit";
var getScheme = React.useCallback(function () {
if (!inherit || !_dom.canUseDOM || !node) {
return undefined;
}
return node.getAttribute("scheme");
}, [inherit, node]);
var _React$useState = React.useState(getScheme()),
_React$useState2 = (0, _slicedToArray2.default)(_React$useState, 2),
resolvedScheme = _React$useState2[0],
setScheme = _React$useState2[1];
React.useEffect(function () {
if (!inherit || !node) {
return _utils.noop;
}
setScheme(getScheme());
var observer = new MutationObserver(function () {
return setScheme(getScheme());
});
observer.observe(node, {
attributes: true,
attributeFilter: ["scheme"]
});
return function () {
return observer.disconnect();
};
}, [getScheme, inherit, node]);
return _scheme === "inherit" ? resolvedScheme : _scheme;
}
var deriveAppearance = function deriveAppearance(scheme) {
return scheme === _scheme2.Scheme.SPACE_GRAY || scheme === _scheme2.Scheme.VKCOM_DARK ? "dark" : "light";
};
var ConfigProvider = function ConfigProvider(_ref) {
var children = _ref.children,
props = (0, _objectWithoutProperties2.default)(_ref, _excluded);
var config = (0, _objectSpread2.default)((0, _objectSpread2.default)({}, _ConfigProviderContext.defaultConfigProviderProps), props);
var platform = config.platform,
appearance = config.appearance;
var scheme = (0, _scheme2.normalizeScheme)({
scheme: config.scheme,
platform: platform,
appearance: appearance
});
var _useDOM = (0, _dom.useDOM)(),
document = _useDOM.document;
var target = document === null || document === void 0 ? void 0 : document.body;
(0, _useIsomorphicLayoutEffect.useIsomorphicLayoutEffect)(function () {
if (scheme === "inherit") {
return _utils.noop;
}
if (process.env.NODE_ENV === "development" && target !== null && target !== void 0 && target.hasAttribute("scheme")) {
warn('<body scheme> was set before VKUI mount - did you forget scheme="inherit"?');
}
target === null || target === void 0 ? void 0 : target.setAttribute("scheme", scheme);
return function () {
return target === null || target === void 0 ? void 0 : target.removeAttribute("scheme");
};
}, [scheme]);
var realScheme = useSchemeDetector(target, scheme);
var derivedAppearance = deriveAppearance(realScheme);
(0, _useIsomorphicLayoutEffect.useIsomorphicLayoutEffect)(function () {
var VKUITokensClassName = (0, _AppearanceProvider.generateVKUITokensClassName)(platform, derivedAppearance);
target === null || target === void 0 ? void 0 : target.classList.add(VKUITokensClassName);
return function () {
target === null || target === void 0 ? void 0 : target.classList.remove(VKUITokensClassName);
};
}, [platform, derivedAppearance]);
var configContext = (0, _useObjectMemo.useObjectMemo)((0, _objectSpread2.default)({
appearance: derivedAppearance
}, config));
return (0, _jsxRuntime.createScopedElement)(_ConfigProviderContext.ConfigProviderContext.Provider, {
value: configContext
}, (0, _jsxRuntime.createScopedElement)(_AppearanceProvider.AppearanceProvider, {
appearance: configContext.appearance
}, children));
}; // eslint-disable-next-line import/no-default-export
var _default = ConfigProvider;
exports.default = _default;
//# sourceMappingURL=ConfigProvider.js.map |
define(
//begin v1.x content
{
"field-sat-relative+0": "este sábado",
"field-sat-relative+1": "el próximo sábado",
"field-dayperiod": "a. m./p. m.",
"field-sun-relative+-1": "el domingo pasado",
"field-mon-relative+-1": "el lunes pasado",
"field-minute": "Minuto",
"field-day-relative+-1": "ayer",
"field-weekday": "Día de la semana",
"field-day-relative+-2": "anteayer",
"field-era": "Era",
"field-hour": "Hora",
"field-sun-relative+0": "este domingo",
"field-sun-relative+1": "el próximo domingo",
"field-wed-relative+-1": "el miércoles pasado",
"field-day-relative+0": "hoy",
"field-day-relative+1": "mañana",
"field-day-relative+2": "pasado mañana",
"dateFormat-long": "d 'de' MMMM 'de' y G",
"field-tue-relative+0": "este martes",
"field-zone": "Zona horaria",
"field-tue-relative+1": "el próximo martes",
"field-week-relative+-1": "la semana pasada",
"dateFormat-medium": "dd/MM/y G",
"field-year-relative+0": "este año",
"field-year-relative+1": "el próximo año",
"field-sat-relative+-1": "el sábado pasado",
"field-year-relative+-1": "el año pasado",
"field-year": "Año",
"field-fri-relative+0": "este viernes",
"field-fri-relative+1": "el próximo viernes",
"field-week": "Semana",
"field-week-relative+0": "esta semana",
"field-week-relative+1": "la próxima semana",
"field-month-relative+0": "este mes",
"field-month": "Mes",
"field-month-relative+1": "el próximo mes",
"field-fri-relative+-1": "el viernes pasado",
"field-second": "Segundo",
"field-tue-relative+-1": "el martes pasado",
"field-day": "Día",
"field-mon-relative+0": "este lunes",
"field-mon-relative+1": "el próximo lunes",
"field-thu-relative+0": "este jueves",
"field-second-relative+0": "ahora",
"dateFormat-short": "dd/MM/yy GGGGG",
"field-thu-relative+1": "el próximo jueves",
"dateFormat-full": "EEEE, d 'de' MMMM 'de' y G",
"field-wed-relative+0": "este miércoles",
"field-wed-relative+1": "el próximo miércoles",
"field-month-relative+-1": "el mes pasado",
"field-thu-relative+-1": "el jueves pasado"
}
//end v1.x content
); |
/* *
*
* (c) 2009-2019 Øystein Moseng
*
* Handle forcing series markers.
*
* License: www.highcharts.com/license
*
* !!!!!!! SOURCE GETS TRANSPILED BY TYPESCRIPT. EDIT TS FILE ONLY. !!!!!!!
*
* */
'use strict';
import H from '../../../../parts/Globals.js';
var merge = H.merge;
/* eslint-disable no-invalid-this, valid-jsdoc */
/**
* @private
*/
function isWithinDescriptionThreshold(series) {
var a11yOptions = series.chart.options.accessibility;
return series.points.length <
a11yOptions.series.pointDescriptionEnabledThreshold ||
a11yOptions.series.pointDescriptionEnabledThreshold === false;
}
/**
* @private
*/
function isWithinNavigationThreshold(series) {
var navOptions = series.chart.options.accessibility
.keyboardNavigation.seriesNavigation;
return series.points.length <
navOptions.pointNavigationEnabledThreshold ||
navOptions.pointNavigationEnabledThreshold === false;
}
/**
* @private
*/
function shouldForceMarkers(series) {
var chartA11yEnabled = series.chart.options.accessibility.enabled, seriesA11yEnabled = (series.options.accessibility &&
series.options.accessibility.enabled) !== false, withinDescriptionThreshold = isWithinDescriptionThreshold(series), withinNavigationThreshold = isWithinNavigationThreshold(series);
return chartA11yEnabled && seriesA11yEnabled &&
(withinDescriptionThreshold || withinNavigationThreshold);
}
/**
* @private
*/
function unforceMarkerOptions(series) {
var resetMarkerOptions = series.resetA11yMarkerOptions;
merge(true, series.options, {
marker: {
enabled: resetMarkerOptions.enabled,
states: {
normal: {
opacity: resetMarkerOptions.states &&
resetMarkerOptions.states.normal &&
resetMarkerOptions.states.normal.opacity
}
}
}
});
}
/**
* @private
*/
function forceZeroOpacityMarkerOptions(options) {
merge(true, options, {
marker: {
enabled: true,
states: {
normal: {
opacity: 0
}
}
}
});
}
/**
* @private
*/
function getPointMarkerOpacity(pointOptions) {
return pointOptions.marker.states &&
pointOptions.marker.states.normal &&
pointOptions.marker.states.normal.opacity || 1;
}
/**
* @private
*/
function forceDisplayPointMarker(pointOptions) {
merge(true, pointOptions.marker, {
states: {
normal: {
opacity: getPointMarkerOpacity(pointOptions)
}
}
});
}
/**
* @private
*/
function handleForcePointMarkers(points) {
var i = points.length;
while (i--) {
var pointOptions = points[i].options;
if (pointOptions.marker) {
if (pointOptions.marker.enabled) {
forceDisplayPointMarker(pointOptions);
}
else {
forceZeroOpacityMarkerOptions(pointOptions);
}
}
}
}
/**
* @private
*/
function addForceMarkersEvents() {
/**
* Keep track of forcing markers.
* @private
*/
H.addEvent(H.Series, 'render', function () {
var series = this, options = series.options;
if (shouldForceMarkers(series)) {
if (options.marker && options.marker.enabled === false) {
series.a11yMarkersForced = true;
forceZeroOpacityMarkerOptions(series.options);
}
if (series._hasPointMarkers && series.points && series.points.length) {
handleForcePointMarkers(series.points);
}
}
else if (series.a11yMarkersForced && series.resetMarkerOptions) {
delete series.a11yMarkersForced;
unforceMarkerOptions(series);
}
});
/**
* Keep track of options to reset markers to if no longer forced.
* @private
*/
H.addEvent(H.Series, 'afterSetOptions', function (e) {
this.resetA11yMarkerOptions = merge(e.options.marker || {}, this.userOptions.marker || {});
});
}
export default addForceMarkersEvents;
|
!function(r){var n={};function u(e){if(n[e])return n[e].exports;var t=n[e]={i:e,l:!1,exports:{}};return r[e].call(t.exports,t,t.exports,u),t.l=!0,t.exports}u.m=r,u.c=n,u.d=function(e,t,r){u.o(e,t)||Object.defineProperty(e,t,{configurable:!1,enumerable:!0,get:r})},u.n=function(e){var t=e&&e.__esModule?function(){return e.default}:function(){return e};return u.d(t,"a",t),t},u.o=function(e,t){return Object.prototype.hasOwnProperty.call(e,t)},u.p="",u(u.s=95)}({0:function(e,t){e.exports=__AJS},4:function(e,t,r){e.exports=r(0)(5)},95:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0}),r(96),t.default=window.AJS,e.exports=t.default},96:function(e,t,r){"use strict";Object.defineProperty(t,"__esModule",{value:!0});var n=o(r(97)),u=o(r(4));function o(e){return e&&e.__esModule?e:{default:e}}var f=(0,u.default)("aui-header",{type:u.default.type.CLASSNAME,created:function(e){(0,n.default)(e)}});t.default=f,e.exports=t.default},97:function(e,t,r){e.exports=r(0)(87)}}); |
/* @flow */
import toFastProperties from "to-fast-properties";
import compact from "lodash/array/compact";
import loClone from "lodash/lang/clone";
import each from "lodash/collection/each";
import uniq from "lodash/array/uniq";
let t = exports;
/**
* Registers `is[Type]` and `assert[Type]` generated functions for a given `type`.
* Pass `skipAliasCheck` to force it to directly compare `node.type` with `type`.
*/
function registerType(type: string, skipAliasCheck?: boolean) {
let is = t[`is${type}`] = function (node, opts) {
return t.is(type, node, opts, skipAliasCheck);
};
t[`assert${type}`] = function (node, opts) {
opts = opts || {};
if (!is(node, opts)) {
throw new Error(`Expected type ${JSON.stringify(type)} with option ${JSON.stringify(opts)}`);
}
};
}
export const STATEMENT_OR_BLOCK_KEYS = ["consequent", "body", "alternate"];
export const FLATTENABLE_KEYS = ["body", "expressions"];
export const FOR_INIT_KEYS = ["left", "init"];
export const COMMENT_KEYS = ["leadingComments", "trailingComments", "innerComments"];
export const INHERIT_KEYS = {
optional: ["typeAnnotation", "typeParameters", "returnType"],
force: ["_scopeInfo", "_paths", "start", "loc", "end"]
};
export const BOOLEAN_NUMBER_BINARY_OPERATORS = [">", "<", ">=", "<="];
export const EQUALITY_BINARY_OPERATORS = ["==", "===", "!=", "!=="];
export const COMPARISON_BINARY_OPERATORS = EQUALITY_BINARY_OPERATORS.concat(["in", "instanceof"]);
export const BOOLEAN_BINARY_OPERATORS = [].concat(COMPARISON_BINARY_OPERATORS, BOOLEAN_NUMBER_BINARY_OPERATORS);
export const NUMBER_BINARY_OPERATORS = ["-", "/", "*", "**", "&", "|", ">>", ">>>", "<<", "^"];
export const BOOLEAN_UNARY_OPERATORS = ["delete", "!"];
export const NUMBER_UNARY_OPERATORS = ["+", "-", "++", "--", "~"];
export const STRING_UNARY_OPERATORS = ["typeof"];
import "./definitions/init";
import { VISITOR_KEYS, ALIAS_KEYS, NODE_FIELDS, BUILDER_KEYS } from "./definitions";
export { VISITOR_KEYS, ALIAS_KEYS, NODE_FIELDS, BUILDER_KEYS };
import * as _react from "./react";
export { _react as react };
/**
* Registers `is[Type]` and `assert[Type]` for all types.
*/
for (let type in t.VISITOR_KEYS) {
registerType(type, true);
}
/**
* Flip `ALIAS_KEYS` for faster access in the reverse direction.
*/
t.FLIPPED_ALIAS_KEYS = {};
each(t.ALIAS_KEYS, function (aliases, type) {
each(aliases, function (alias) {
let types = t.FLIPPED_ALIAS_KEYS[alias] = t.FLIPPED_ALIAS_KEYS[alias] || [];
types.push(type);
});
});
/**
* Registers `is[Alias]` and `assert[Alias]` functions for all aliases.
*/
each(t.FLIPPED_ALIAS_KEYS, function (types, type) {
t[type.toUpperCase() + "_TYPES"] = types;
registerType(type, false);
});
export const TYPES = Object.keys(t.VISITOR_KEYS).concat(Object.keys(t.FLIPPED_ALIAS_KEYS));
/**
* Returns whether `node` is of given `type`.
*
* For better performance, use this instead of `is[Type]` when `type` is unknown.
* Optionally, pass `skipAliasCheck` to directly compare `node.type` with `type`.
*/
export function is(type: string, node: Object, opts?: Object): boolean {
if (!node) return false;
let matches = isType(node.type, type);
if (!matches) return false;
if (typeof opts === "undefined") {
return true;
} else {
return t.shallowEqual(node, opts);
}
}
/**
* Test if a `nodeType` is a `targetType` or if `targetType` is an alias of `nodeType`.
*/
export function isType(nodeType: string, targetType: string): boolean {
if (nodeType === targetType) return true;
let aliases = t.FLIPPED_ALIAS_KEYS[targetType];
if (aliases) {
if (aliases[0] === nodeType) return true;
for (let alias of (aliases: Array<string>)) {
if (nodeType === alias) return true;
}
}
return false;
}
each(t.BUILDER_KEYS, function (keys, type) {
function builder() {
if (arguments.length > keys.length) {
// todo: error
}
let node = {};
node.type = type;
let i = 0;
for (let key of (keys: Array<string>)) {
let field = t.NODE_FIELDS[type][key];
let arg = arguments[i++];
if (arg === undefined) arg = loClone(field.default);
node[key] = arg;
}
for (let key in node) {
validate(node, key, node[key]);
}
return node;
}
t[type] = builder;
t[type[0].toLowerCase() + type.slice(1)] = builder;
});
/**
* Description
*/
export function validate(node?: Object, key: string, val: any) {
if (!node) return;
let fields = t.NODE_FIELDS[node.type];
if (!fields) return;
let field = fields[key];
if (!field || !field.validate) return;
if (field.optional && val == null) return;
field.validate(node, key, val);
}
/**
* Test if an object is shallowly equal.
*/
export function shallowEqual(actual: Object, expected: Object): boolean {
let keys = Object.keys(expected);
for (let key of (keys: Array<string>)) {
if (actual[key] !== expected[key]) {
return false;
}
}
return true;
}
/**
* Append a node to a member expression.
*/
export function appendToMemberExpression(member: Object, append: Object, computed?: boolean): Object {
member.object = t.memberExpression(member.object, member.property, member.computed);
member.property = append;
member.computed = !!computed;
return member;
}
/**
* Prepend a node to a member expression.
*/
export function prependToMemberExpression(member: Object, prepend: Object): Object {
member.object = t.memberExpression(prepend, member.object);
return member;
}
/**
* Ensure the `key` (defaults to "body") of a `node` is a block.
* Casting it to a block if it is not.
*/
export function ensureBlock(node: Object, key: string = "body"): Object {
return node[key] = t.toBlock(node[key], node);
}
/**
* Create a shallow clone of a `node` excluding `_private` properties.
*/
export function clone(node: Object): Object {
let newNode = {};
for (let key in node) {
if (key[0] === "_") continue;
newNode[key] = node[key];
}
return newNode;
}
/**
* Create a deep clone of a `node` and all of it's child nodes
* exluding `_private` properties.
*/
export function cloneDeep(node: Object): Object {
let newNode = {};
for (let key in node) {
if (key[0] === "_") continue;
let val = node[key];
if (val) {
if (val.type) {
val = t.cloneDeep(val);
} else if (Array.isArray(val)) {
val = val.map(t.cloneDeep);
}
}
newNode[key] = val;
}
return newNode;
}
/**
* Build a function that when called will return whether or not the
* input `node` `MemberExpression` matches the input `match`.
*
* For example, given the match `React.createClass` it would match the
* parsed nodes of `React.createClass` and `React["createClass"]`.
*/
export function buildMatchMemberExpression(match:string, allowPartial?: boolean): Function {
let parts = match.split(".");
return function (member) {
// not a member expression
if (!t.isMemberExpression(member)) return false;
let search = [member];
let i = 0;
while (search.length) {
let node = search.shift();
if (allowPartial && i === parts.length) {
return true;
}
if (t.isIdentifier(node)) {
// this part doesn't match
if (parts[i] !== node.name) return false;
} else if (t.isStringLiteral(node)) {
// this part doesn't match
if (parts[i] !== node.value) return false;
} else if (t.isMemberExpression(node)) {
if (node.computed && !t.isStringLiteral(node.property)) {
// we can't deal with this
return false;
} else {
search.push(node.object);
search.push(node.property);
continue;
}
} else {
// we can't deal with this
return false;
}
// too many parts
if (++i > parts.length) {
return false;
}
}
return true;
};
}
/**
* Remove comment properties from a node.
*/
export function removeComments(node: Object): Object {
for (let key of COMMENT_KEYS) {
delete node[key];
}
return node;
}
/**
* Inherit all unique comments from `parent` node to `child` node.
*/
export function inheritsComments(child: Object, parent: Object): Object {
inheritTrailingComments(child, parent);
inheritLeadingComments(child, parent);
inheritInnerComments(child, parent);
return child;
}
export function inheritTrailingComments(child: Object, parent: Object) {
_inheritComments("trailingComments", child, parent);
}
export function inheritLeadingComments(child: Object, parent: Object) {
_inheritComments("leadingComments", child, parent);
}
export function inheritInnerComments(child: Object, parent: Object) {
_inheritComments("innerComments", child, parent);
}
function _inheritComments(key, child, parent) {
if (child && parent) {
child[key] = uniq(compact([].concat(child[key], parent[key])));
}
}
/**
* Inherit all contextual properties from `parent` node to `child` node.
*/
export function inherits(child: Object, parent: Object): Object {
if (!child || !parent) return child;
for (let key of (t.INHERIT_KEYS.optional: Array<string>)) {
if (child[key] == null) {
child[key] = parent[key];
}
}
for (let key of (t.INHERIT_KEYS.force: Array<string>)) {
child[key] = parent[key];
}
t.inheritsComments(child, parent);
return child;
}
/**
* TODO
*/
export function assertNode(node?) {
if (!isNode(node)) {
throw new TypeError("Not a valid node " + (node && node.type));
}
}
/**
* TODO
*/
export function isNode(node?): boolean {
return !!(node && VISITOR_KEYS[node.type]);
}
// Optimize property access.
toFastProperties(t);
toFastProperties(t.VISITOR_KEYS);
//
export * from "./retrievers";
export * from "./validators";
export * from "./converters";
export * from "./flow";
|
module.exports={A:{A:{"2":"J C G E B A TB"},B:{"2":"D X g","194":"H L"},C:{"2":"0 3 RB F I J C G E B A D X g H L M N O P Q R S T U V W t Y Z a b c d e f K h i j k l m n o p q v w x y z PB OB","322":"2 4 s r"},D:{"2":"0 2 4 8 F I J C G E B A D X g H L M N O P Q R S T U V W t Y Z a b c d e f K h i j k l m n o p q v w x y z s r DB","194":"AB SB BB"},E:{"1":"A IB JB","2":"7 F I J C G E B CB EB FB GB HB"},F:{"2":"1 5 6 E A D H L M N O P Q R S T U V W t Y Z a b c d e f K h i j k l m n o p KB LB MB NB QB","194":"q"},G:{"1":"A bB","2":"7 9 G u UB VB WB XB YB ZB aB"},H:{"2":"cB"},I:{"2":"3 F r dB eB fB gB u hB iB"},J:{"2":"C B"},K:{"2":"1 5 6 B A D K"},L:{"2":"8"},M:{"2":"s"},N:{"2":"B A"},O:{"2":"jB"},P:{"2":"F I"},Q:{"2":"kB"},R:{"2":"lB"}},B:1,C:"ES6 module"};
|
var DataSet = require("./index.js")
var test = require("tape")
var document = require("global/document")
var element = require("element")
test("can fetch records out of DS", function (assert) {
var elem = document.body
var ds = DataSet(elem)
ds.foo = "bar"
var ds2 = DataSet(elem)
assert.equal(ds2.foo, "bar")
assert.end()
})
test("can fetch pre existing records out of DOM", function (assert) {
var elem = element("<div data-foo='bar' data-baz='oh yeah'></div>")
var ds = DataSet(elem)
assert.equal(ds.foo, "bar")
assert.deepEqual(ds.baz, "oh yeah")
assert.end()
})
test("setting dash names", function (assert) {
var elem = document.createElement("div")
DataSet(elem)["foo-bar"] = "baz"
var elem2 = element("<div data-foo-bar='baz'></div>")
var ds = DataSet(elem)
var ds2 = DataSet(elem2)
assert.equal(ds["foo-bar"], "baz")
assert.equal(ds2["foo-bar"], "baz")
assert.end()
})
|
var owl = require('owl.js'),
TodoItemCollection = require('./TodoItemCollection'),
TodoView = require('./TodoView');
function TodoController() {
this.appView = require('./appView');
}
TodoController.prototype = {
init: function() {
var that = this,
todoItemCollection,
todoView;
todoItemCollection = new TodoItemCollection();
todoItemCollection.fetch().then(function() {
todoView = new TodoView({
controller: this,
collection: todoItemCollection
});
that.appView.showMain(todoView);
});
}
};
module.exports = TodoController; |
/* Copyright (c) 2012 Sven "FuzzYspo0N" Bergström, 2013 Robert XD Hawkins
originally written for: http://buildnewgames.com/real-time-multiplayer/
substantially modified for collective behavior experiments
MIT Licensed.
*/
var
use_https = true,
gameport = 8888,
https = require('https'),
fs = require('fs'),
app = require('express')(),
_ = require('underscore');
try {
var privateKey = fs.readFileSync('/etc/apache2/ssl/private.key'),
certificate = fs.readFileSync('/etc/apache2/ssl/ssl.crt'),
options = {key: privateKey, cert: certificate},
server = require('https').createServer(options,app).listen(gameport),
io = require('socket.io')(server);
} catch (err) {
console.log("cannot find SSL certificates; falling back to http");
var server = app.listen(gameport),
io = require('socket.io')(server);
}
var game_server = require('./game.server.js');
var utils = require('./utils.js');
var global_player_set = {};
// Log something so we know that server-side setup succeeded
console.log("info - socket.io started");
console.log('\t :: Express :: Listening on port ' + gameport );
// This handler will listen for requests on /*, any file from the
// root of our server. See expressjs documentation for more info
app.get( '/*' , function( req, res ) {
// this is the current file they have requested
var file = req.params[0];
console.log('\t :: Express :: file requested: ' + file);
if(req.query.id && !valid_id(req.query.id)) {
res.re
('http://rxdhawkins.net:8888/forms/invalid.html');
} else {
if(req.query.id && req.query.id in global_player_set) {
res.redirect('http://rxdhawkins.net:8888/forms/duplicate.html');
} else {
res.sendfile("./" + file); // give them what they want
}
}
});
// Socket.io will call this function when a client connects. We check
// to see if the client supplied a id. If so, we distinguish them by
// that, otherwise we assign them one at random
io.on('connection', function (client) {
// Recover query string information and set condition
var hs = client.handshake;
var query = require('url').parse(client.handshake.headers.referer, true).query;
var id;
if( !(query.id && query.id in global_player_set) ) {
if(query.id) {
global_player_set[query.id] = true;
// use id from query string if exists
id = query.id;
} else {
// otherwise, create new one
id = utils.UUID();
}
if(valid_id(id)) {
console.log("user connecting...");
initialize(query, client, id);
}
}
});
var valid_id = function(id) {
return id.length == 41;
};
var initialize = function(query, client, id) {
client.userid = id;
client.emit('onconnected', { id: client.userid } );
// Good to know when they connected
console.log('\t socket.io:: player ' + client.userid + ' connected');
//Pass off to game.server.js code
game_server.findGame(client);
// Now we want set up some callbacks to handle messages that clients will send.
// We'll just pass messages off to the server_onMessage function for now.
client.on('message', function(m) {
game_server.server_onMessage(client, m);
});
// When this client disconnects, we want to tell the game server
// about that as well, so it can remove them from the game they are
// in, and make sure the other player knows that they left and so on.
client.on('disconnect', function () {
console.log('\t socket.io:: client id ' + client.userid
+ ' disconnected from game id ' + client.game.id);
//If the client was in a game set by game_server.findGame,
//we can tell the game server to update that game state.
if(client.userid && client.game && client.game.id)
//player leaving a game should change that game
game_server.endGame(client.game.id, client.userid);
});
};
|
var execSync = require('child_process').execSync;
module.exports = {
// Push master (including version bump) to `release` branch.
afterPush: function() {
console.log('pushing master to release branch');
var output = execSync('git push origin master:release', { encoding: 'utf8' });
console.log(output);
}
};
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @emails react-core
*/
'use strict';
let EventPluginGetListener;
let EventPluginRegistry;
let React;
let ReactDOM;
let ReactDOMComponentTree;
let listenToEvent;
let ReactDOMEventListener;
let ReactTestUtils;
let ReactFeatureFlags;
let idCallOrder;
const recordID = function(id) {
idCallOrder.push(id);
};
const recordIDAndStopPropagation = function(id, event) {
recordID(id);
event.stopPropagation();
};
const recordIDAndReturnFalse = function(id, event) {
recordID(id);
return false;
};
const LISTENER = jest.fn();
const ON_CLICK_KEY = 'onClick';
const ON_CHANGE_KEY = 'onChange';
const ON_MOUSE_ENTER_KEY = 'onMouseEnter';
let GRANDPARENT;
let PARENT;
let CHILD;
let BUTTON;
let getListener;
let putListener;
let deleteAllListeners;
let container;
function registerSimpleTestHandler() {
putListener(CHILD, ON_CLICK_KEY, LISTENER);
const listener = getListener(CHILD, ON_CLICK_KEY);
expect(listener).toEqual(LISTENER);
return getListener(CHILD, ON_CLICK_KEY);
}
// We should probably remove this file at some point, it's just full of
// internal API usage.
describe('ReactBrowserEventEmitter', () => {
beforeEach(() => {
jest.resetModules();
LISTENER.mockClear();
ReactFeatureFlags = require('shared/ReactFeatureFlags');
EventPluginGetListener = require('react-dom/src/events/getListener')
.default;
EventPluginRegistry = require('legacy-events/EventPluginRegistry');
React = require('react');
ReactDOM = require('react-dom');
ReactDOMComponentTree = require('../client/ReactDOMComponentTree');
if (ReactFeatureFlags.enableModernEventSystem) {
listenToEvent = require('../events/DOMModernPluginEventSystem')
.listenToEvent;
} else {
listenToEvent = require('../events/DOMLegacyEventPluginSystem')
.legacyListenToEvent;
}
ReactDOMEventListener = require('../events/ReactDOMEventListener');
ReactTestUtils = require('react-dom/test-utils');
container = document.createElement('div');
document.body.appendChild(container);
let GRANDPARENT_PROPS = {};
let PARENT_PROPS = {};
let CHILD_PROPS = {};
let BUTTON_PROPS = {};
function Child(props) {
return <div ref={c => (CHILD = c)} {...props} />;
}
class ChildWrapper extends React.PureComponent {
render() {
return <Child {...this.props} />;
}
}
function renderTree() {
ReactDOM.render(
<div ref={c => (GRANDPARENT = c)} {...GRANDPARENT_PROPS}>
<div ref={c => (PARENT = c)} {...PARENT_PROPS}>
<ChildWrapper {...CHILD_PROPS} />
<button disabled={true} ref={c => (BUTTON = c)} {...BUTTON_PROPS} />
</div>
</div>,
container,
);
}
renderTree();
getListener = function(node, eventName) {
const inst = ReactDOMComponentTree.getInstanceFromNode(node);
return EventPluginGetListener(inst, eventName);
};
putListener = function(node, eventName, listener) {
switch (node) {
case CHILD:
CHILD_PROPS[eventName] = listener;
break;
case PARENT:
PARENT_PROPS[eventName] = listener;
break;
case GRANDPARENT:
GRANDPARENT_PROPS[eventName] = listener;
break;
case BUTTON:
BUTTON_PROPS[eventName] = listener;
break;
}
// Rerender with new event listeners
renderTree();
};
deleteAllListeners = function(node) {
switch (node) {
case CHILD:
CHILD_PROPS = {};
break;
case PARENT:
PARENT_PROPS = {};
break;
case GRANDPARENT:
GRANDPARENT_PROPS = {};
break;
case BUTTON:
BUTTON_PROPS = {};
break;
}
renderTree();
};
idCallOrder = [];
});
afterEach(() => {
document.body.removeChild(container);
container = null;
});
it('should store a listener correctly', () => {
registerSimpleTestHandler();
const listener = getListener(CHILD, ON_CLICK_KEY);
expect(listener).toBe(LISTENER);
});
it('should retrieve a listener correctly', () => {
registerSimpleTestHandler();
const listener = getListener(CHILD, ON_CLICK_KEY);
expect(listener).toEqual(LISTENER);
});
it('should not retrieve listeners on a disabled interactive element', () => {
putListener(BUTTON, ON_MOUSE_ENTER_KEY, recordID.bind(null, BUTTON));
const listener = getListener(BUTTON, ON_MOUSE_ENTER_KEY);
expect(listener).toBe(null);
});
it('should clear all handlers when asked to', () => {
registerSimpleTestHandler();
deleteAllListeners(CHILD);
const listener = getListener(CHILD, ON_CLICK_KEY);
expect(listener).toBe(undefined);
});
it('should invoke a simple handler registered on a node', () => {
registerSimpleTestHandler();
CHILD.click();
expect(LISTENER).toHaveBeenCalledTimes(1);
});
it('should not invoke handlers if ReactDOMEventListener is disabled', () => {
registerSimpleTestHandler();
ReactDOMEventListener.setEnabled(false);
CHILD.click();
expect(LISTENER).toHaveBeenCalledTimes(0);
ReactDOMEventListener.setEnabled(true);
CHILD.click();
expect(LISTENER).toHaveBeenCalledTimes(1);
});
it('should bubble simply', () => {
putListener(CHILD, ON_CLICK_KEY, recordID.bind(null, CHILD));
putListener(PARENT, ON_CLICK_KEY, recordID.bind(null, PARENT));
putListener(GRANDPARENT, ON_CLICK_KEY, recordID.bind(null, GRANDPARENT));
CHILD.click();
expect(idCallOrder.length).toBe(3);
expect(idCallOrder[0]).toBe(CHILD);
expect(idCallOrder[1]).toBe(PARENT);
expect(idCallOrder[2]).toBe(GRANDPARENT);
});
it('should bubble to the right handler after an update', () => {
putListener(GRANDPARENT, ON_CLICK_KEY, recordID.bind(null, 'GRANDPARENT'));
putListener(PARENT, ON_CLICK_KEY, recordID.bind(null, 'PARENT'));
putListener(CHILD, ON_CLICK_KEY, recordID.bind(null, 'CHILD'));
CHILD.click();
expect(idCallOrder).toEqual(['CHILD', 'PARENT', 'GRANDPARENT']);
idCallOrder = [];
// Update just the grand parent without updating the child.
putListener(
GRANDPARENT,
ON_CLICK_KEY,
recordID.bind(null, 'UPDATED_GRANDPARENT'),
);
CHILD.click();
expect(idCallOrder).toEqual(['CHILD', 'PARENT', 'UPDATED_GRANDPARENT']);
});
it('should continue bubbling if an error is thrown', () => {
putListener(CHILD, ON_CLICK_KEY, recordID.bind(null, CHILD));
putListener(PARENT, ON_CLICK_KEY, function() {
recordID(PARENT);
throw new Error('Handler interrupted');
});
putListener(GRANDPARENT, ON_CLICK_KEY, recordID.bind(null, GRANDPARENT));
expect(function() {
ReactTestUtils.Simulate.click(CHILD);
}).toThrow();
expect(idCallOrder.length).toBe(3);
expect(idCallOrder[0]).toBe(CHILD);
expect(idCallOrder[1]).toBe(PARENT);
expect(idCallOrder[2]).toBe(GRANDPARENT);
});
it('should set currentTarget', () => {
putListener(CHILD, ON_CLICK_KEY, function(event) {
recordID(CHILD);
expect(event.currentTarget).toBe(CHILD);
});
putListener(PARENT, ON_CLICK_KEY, function(event) {
recordID(PARENT);
expect(event.currentTarget).toBe(PARENT);
});
putListener(GRANDPARENT, ON_CLICK_KEY, function(event) {
recordID(GRANDPARENT);
expect(event.currentTarget).toBe(GRANDPARENT);
});
CHILD.click();
expect(idCallOrder.length).toBe(3);
expect(idCallOrder[0]).toBe(CHILD);
expect(idCallOrder[1]).toBe(PARENT);
expect(idCallOrder[2]).toBe(GRANDPARENT);
});
it('should support stopPropagation()', () => {
putListener(CHILD, ON_CLICK_KEY, recordID.bind(null, CHILD));
putListener(
PARENT,
ON_CLICK_KEY,
recordIDAndStopPropagation.bind(null, PARENT),
);
putListener(GRANDPARENT, ON_CLICK_KEY, recordID.bind(null, GRANDPARENT));
CHILD.click();
expect(idCallOrder.length).toBe(2);
expect(idCallOrder[0]).toBe(CHILD);
expect(idCallOrder[1]).toBe(PARENT);
});
it('should support overriding .isPropagationStopped()', () => {
// Ew. See D4504876.
putListener(CHILD, ON_CLICK_KEY, recordID.bind(null, CHILD));
putListener(PARENT, ON_CLICK_KEY, function(e) {
recordID(PARENT, e);
// This stops React bubbling but avoids touching the native event
e.isPropagationStopped = () => true;
});
putListener(GRANDPARENT, ON_CLICK_KEY, recordID.bind(null, GRANDPARENT));
CHILD.click();
expect(idCallOrder.length).toBe(2);
expect(idCallOrder[0]).toBe(CHILD);
expect(idCallOrder[1]).toBe(PARENT);
});
it('should stop after first dispatch if stopPropagation', () => {
putListener(
CHILD,
ON_CLICK_KEY,
recordIDAndStopPropagation.bind(null, CHILD),
);
putListener(PARENT, ON_CLICK_KEY, recordID.bind(null, PARENT));
putListener(GRANDPARENT, ON_CLICK_KEY, recordID.bind(null, GRANDPARENT));
CHILD.click();
expect(idCallOrder.length).toBe(1);
expect(idCallOrder[0]).toBe(CHILD);
});
it('should not stopPropagation if false is returned', () => {
putListener(CHILD, ON_CLICK_KEY, recordIDAndReturnFalse.bind(null, CHILD));
putListener(PARENT, ON_CLICK_KEY, recordID.bind(null, PARENT));
putListener(GRANDPARENT, ON_CLICK_KEY, recordID.bind(null, GRANDPARENT));
CHILD.click();
expect(idCallOrder.length).toBe(3);
expect(idCallOrder[0]).toBe(CHILD);
expect(idCallOrder[1]).toBe(PARENT);
expect(idCallOrder[2]).toBe(GRANDPARENT);
});
/**
* The entire event registration state of the world should be "locked-in" at
* the time the event occurs. This is to resolve many edge cases that come
* about from a listener on a lower-in-DOM node causing structural changes at
* places higher in the DOM. If this lower-in-DOM node causes new content to
* be rendered at a place higher-in-DOM, we need to be careful not to invoke
* these new listeners.
*/
it('should invoke handlers that were removed while bubbling', () => {
const handleParentClick = jest.fn();
const handleChildClick = function(event) {
deleteAllListeners(PARENT);
};
putListener(CHILD, ON_CLICK_KEY, handleChildClick);
putListener(PARENT, ON_CLICK_KEY, handleParentClick);
CHILD.click();
expect(handleParentClick).toHaveBeenCalledTimes(1);
});
it('should not invoke newly inserted handlers while bubbling', () => {
const handleParentClick = jest.fn();
const handleChildClick = function(event) {
putListener(PARENT, ON_CLICK_KEY, handleParentClick);
};
putListener(CHILD, ON_CLICK_KEY, handleChildClick);
CHILD.click();
expect(handleParentClick).toHaveBeenCalledTimes(0);
});
it('should have mouse enter simulated by test utils', () => {
putListener(CHILD, ON_MOUSE_ENTER_KEY, recordID.bind(null, CHILD));
ReactTestUtils.Simulate.mouseEnter(CHILD);
expect(idCallOrder.length).toBe(1);
expect(idCallOrder[0]).toBe(CHILD);
});
it('should listen to events only once', () => {
spyOnDevAndProd(EventTarget.prototype, 'addEventListener');
listenToEvent(ON_CLICK_KEY, document);
listenToEvent(ON_CLICK_KEY, document);
expect(EventTarget.prototype.addEventListener).toHaveBeenCalledTimes(1);
});
it('should work with event plugins without dependencies', () => {
spyOnDevAndProd(EventTarget.prototype, 'addEventListener');
listenToEvent(ON_CLICK_KEY, document);
expect(EventTarget.prototype.addEventListener.calls.argsFor(0)[0]).toBe(
'click',
);
});
it('should work with event plugins with dependencies', () => {
spyOnDevAndProd(EventTarget.prototype, 'addEventListener');
listenToEvent(ON_CHANGE_KEY, document);
const setEventListeners = [];
const listenCalls = EventTarget.prototype.addEventListener.calls.allArgs();
for (let i = 0; i < listenCalls.length; i++) {
setEventListeners.push(listenCalls[i][1]);
}
const module = EventPluginRegistry.registrationNameModules[ON_CHANGE_KEY];
const dependencies = module.eventTypes.change.dependencies;
expect(setEventListeners.length).toEqual(dependencies.length);
for (let i = 0; i < setEventListeners.length; i++) {
expect(dependencies.indexOf(setEventListeners[i])).toBeTruthy();
}
});
});
|
/*
Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved.
For licensing, see LICENSE.md or http://ckeditor.com/license
*/
CKEDITOR.plugins.setLang( 'bidi', 'ja', {
ltr: 'テキストの向き : 左から右へ',
rtl: 'テキストの向き : 右から左へ'
});
|
/* global require, describe, it, beforeEach */
'use strict';
var mpath = './../../../../app/middleware/logs/logs.js';
// MODULES //
var // Expectation library:
chai = require( 'chai' ),
// Stub required modules:
proxyquire = require( 'proxyquire' ),
// Module to be tested:
logs = require( mpath );
// VARIABLES //
var expect = chai.expect,
assert = chai.assert;
// TESTS //
describe( 'app/middleware/logs/logs', function tests() {
// SETUP //
var request, response, next;
request = {
'body': [
{
'log': 'beep'
}
],
get: function( header ) {
if ( header === 'X-Request-Client' ) {
return 'beep';
}
}
};
response = {};
next = function(){};
// TESTS //
it( 'should export a function', function test() {
expect( logs ).to.be.a( 'function' );
});
it( 'should dump client-side logs', function test( done ) {
var logs = proxyquire( mpath, {
'logger': {
info: function( blob ) {
assert.strictEqual( blob.cid, 'beep' );
assert.deepEqual( blob.logs, request.body );
done();
}
}
});
logs( request, response, next );
});
it( 'should invoke a callback after dumping client-side logs', function test( done ) {
next = function next() {
assert.ok( true );
done();
};
logs( request, response, next );
});
});
|
const React = require('react');
const { Button } = require('react-native-ui-lib');
class RnnButton extends React.PureComponent {
render() {
return (
<Button
{...this.props}
style={{
marginBottom: 8,
}}
/>
)
}
}
module.exports = RnnButton |
'use strict';
require('../common');
const { PassThrough } = require('stream');
const readline = require('readline');
const assert = require('assert');
const ctrlU = { ctrl: true, name: 'u' };
{
const input = new PassThrough();
const rl = readline.createInterface({
terminal: true,
input: input,
prompt: ''
});
const tests = [
[1, 'a'],
[2, 'ab'],
[2, '丁']
];
// The non-ICU JS implementation of character width calculation is only aware
// of the wide/narrow distinction. Only test these more advanced cases when
// ICU is available.
if (process.binding('config').hasIntl) {
tests.push(
[0, '\u0301'], // COMBINING ACUTE ACCENT
[1, 'a\u0301'], // á
[0, '\u20DD'], // COMBINING ENCLOSING CIRCLE
[2, 'a\u20DDb'], // a⃝b
[0, '\u200E'] // LEFT-TO-RIGHT MARK
);
}
for (const [cursor, string] of tests) {
rl.write(string);
assert.strictEqual(rl._getCursorPos().cols, cursor);
rl.write(null, ctrlU);
}
}
|
var gulp = require('gulp');
var rename = require('gulp-rename');
var source = require('vinyl-source-stream');
var streamify = require('gulp-streamify');
var uglify = require('gulp-uglify');
var jscs = require('gulp-jscs');
var del = require('del');
var browserify = require('browserify');
var shim = require('browserify-shim');
var DEST = 'dist/';
var SRC = 'src/**/*.js';
var TEST = 'test/**/*.js';
var PKG = 'react-ga';
var LINT_DIRS = [
SRC,
TEST
];
var TEST_TASKS = [
'jscs'
];
var BUILD_TASKS = [
'jscs',
'clean',
'package'
];
gulp.task('jscs', function () {
return gulp.src(LINT_DIRS)
.pipe(jscs())
.pipe(jscs.reporter());
});
gulp.task('clean', function () {
return del([DEST]);
});
gulp.task('package', function () {
return browserify('./src/index.js', {
standalone: 'ReactGA'
})
.transform(shim)
.bundle()
.pipe(source(PKG + '.js'))
.pipe(gulp.dest(DEST))
.pipe(rename(PKG + '.min.js'))
.pipe(streamify(uglify()))
.pipe(gulp.dest(DEST));
});
gulp.task('test', TEST_TASKS);
gulp.task('build', BUILD_TASKS);
|
const { ipcRenderer } = require('electron');
// Ensure fetch works from isolated world origin
fetch('https://localhost:1234').catch(err => {
ipcRenderer.send('isolated-fetch-error', err.message);
});
|
Clazz.declarePackage ("J.adapter.readers.quantum");
Clazz.load (["J.adapter.readers.quantum.SpartanInputReader"], "J.adapter.readers.quantum.SpartanSmolReader", ["java.lang.Boolean", "java.util.Hashtable", "JU.BC", "$.PT", "$.SB", "J.adapter.readers.quantum.SpartanArchive", "J.util.Logger"], function () {
c$ = Clazz.decorateAsClass (function () {
this.iHaveModelStatement = false;
this.isCompoundDocument = false;
this.inputOnly = false;
this.espCharges = false;
this.endCheck = "END Directory Entry ";
this.title = null;
this.spartanArchive = null;
this.titles = null;
this.haveCharges = false;
Clazz.instantialize (this, arguments);
}, J.adapter.readers.quantum, "SpartanSmolReader", J.adapter.readers.quantum.SpartanInputReader);
$_V(c$, "initializeReader",
function () {
this.modelName = "Spartan file";
this.isCompoundDocument = (this.readLine ().indexOf ("Compound Document File Directory") >= 0);
this.inputOnly = this.checkFilterKey ("INPUT");
this.espCharges = !this.checkFilterKey ("MULLIKEN");
});
$_V(c$, "checkLine",
function () {
var lcline;
if (this.isCompoundDocument && (lcline = this.line.toLowerCase ()).equals ("begin directory entry molecule") || this.line.indexOf ("JMOL_MODEL") >= 0 && !this.line.startsWith ("END")) {
if (this.modelNumber > 0) this.applySymmetryAndSetTrajectory ();
this.iHaveModelStatement = true;
var modelNo = this.getModelNumber ();
this.modelNumber = (this.bsModels == null && modelNo != -2147483648 ? modelNo : this.modelNumber + 1);
this.bondData = "";
if (!this.doGetModel (this.modelNumber, null)) return this.checkLastModel ();
if (this.modelAtomCount == 0) this.atomSetCollection.newAtomSet ();
this.moData = new java.util.Hashtable ();
this.moData.put ("isNormalized", Boolean.TRUE);
if (modelNo == -2147483648) {
modelNo = this.modelNumber;
this.title = "Model " + modelNo;
} else {
this.title = this.titles.get ("Title" + modelNo);
this.title = "Profile " + modelNo + (this.title == null ? "" : ": " + this.title);
}J.util.Logger.info (this.title);
this.atomSetCollection.setAtomSetName (this.title);
this.atomSetCollection.setAtomSetAuxiliaryInfo ("isPDB", Boolean.FALSE);
this.atomSetCollection.setCurrentAtomSetNumber (modelNo);
if (this.isCompoundDocument) this.readTransform ();
return true;
}if (this.iHaveModelStatement && !this.doProcessLines) return true;
if ((this.line.indexOf ("BEGIN") == 0)) {
lcline = this.line.toLowerCase ();
if (lcline.endsWith ("input")) {
this.bondData = "";
this.readInputRecords ();
if (this.atomSetCollection.errorMessage != null) {
this.continuing = false;
return false;
}if (this.title != null) this.atomSetCollection.setAtomSetName (this.title);
this.setCharges ();
if (this.inputOnly) {
this.continuing = false;
return false;
}} else if (lcline.endsWith ("_output")) {
return true;
} else if (lcline.endsWith ("output")) {
this.readOutput ();
return false;
} else if (lcline.endsWith ("molecule") || lcline.endsWith ("molecule:asbinarystring")) {
this.readTransform ();
return false;
} else if (lcline.endsWith ("proparc") || lcline.endsWith ("propertyarchive")) {
this.readProperties ();
return false;
} else if (lcline.endsWith ("archive")) {
this.readArchive ();
return false;
}return true;
}if (this.line.indexOf ("5D shell") >= 0) this.moData.put ("calculationType", this.calculationType = this.line);
return true;
});
$_V(c$, "finalizeReader",
function () {
this.finalizeReaderASCR ();
if (this.atomCount > 0 && this.spartanArchive != null && this.atomSetCollection.getBondCount () == 0 && this.bondData != null) this.spartanArchive.addBonds (this.bondData, 0);
if (this.moData != null) {
var n = this.atomSetCollection.getAtomSetCollectionAuxiliaryInfo ("HOMO_N");
if (n != null) this.moData.put ("HOMO", Integer.$valueOf (n.intValue ()));
}});
$_M(c$, "readTransform",
($fz = function () {
var $private = Clazz.checkPrivateMethod (arguments);
if ($private != null) {
return $private.apply (this, arguments);
}
var mat;
var binaryCodes = this.readLine ();
var tokens = J.adapter.smarter.AtomSetCollectionReader.getTokensStr (binaryCodes.trim ());
if (tokens.length < 16) return;
var bytes = Clazz.newByteArray (tokens.length, 0);
for (var i = 0; i < tokens.length; i++) bytes[i] = JU.PT.parseIntRadix (tokens[i], 16);
mat = Clazz.newFloatArray (16, 0);
var bc = new JU.BC ();
for (var i = 16, j = bytes.length - 8; --i >= 0; j -= 8) mat[i] = bc.bytesToDoubleToFloat (bytes, j, false);
this.setTransform (mat[0], mat[1], mat[2], mat[4], mat[5], mat[6], mat[8], mat[9], mat[10]);
}, $fz.isPrivate = true, $fz));
$_M(c$, "readOutput",
($fz = function () {
this.titles = new java.util.Hashtable ();
var header = new JU.SB ();
var pt;
while (this.readLine () != null && !this.line.startsWith ("END ")) {
header.append (this.line).append ("\n");
if ((pt = this.line.indexOf (")")) > 0) this.titles.put ("Title" + this.parseIntRange (this.line, 0, pt), (this.line.substring (pt + 1).trim ()));
}
this.atomSetCollection.setAtomSetCollectionAuxiliaryInfo ("fileHeader", header.toString ());
}, $fz.isPrivate = true, $fz));
$_M(c$, "readArchive",
($fz = function () {
this.spartanArchive = new J.adapter.readers.quantum.SpartanArchive (this, this.bondData, this.endCheck);
if (this.readArchiveHeader ()) {
this.modelAtomCount = this.spartanArchive.readArchive (this.line, false, this.atomCount, false);
if (this.atomCount == 0 || !this.isTrajectory) this.atomCount += this.modelAtomCount;
}}, $fz.isPrivate = true, $fz));
$_M(c$, "setCharges",
($fz = function () {
if (this.haveCharges || this.atomSetCollection.getAtomCount () == 0) return;
this.haveCharges = (this.espCharges && this.atomSetCollection.setAtomSetCollectionPartialCharges ("ESPCHARGES") || this.atomSetCollection.setAtomSetCollectionPartialCharges ("MULCHARGES") || this.atomSetCollection.setAtomSetCollectionPartialCharges ("Q1_CHARGES") || this.atomSetCollection.setAtomSetCollectionPartialCharges ("ESPCHARGES"));
}, $fz.isPrivate = true, $fz));
$_M(c$, "readProperties",
($fz = function () {
if (this.spartanArchive == null) {
this.readLine ();
return;
}this.spartanArchive.readProperties ();
this.readLine ();
this.setCharges ();
}, $fz.isPrivate = true, $fz));
$_M(c$, "getModelNumber",
($fz = function () {
try {
var pt = this.line.indexOf ("JMOL_MODEL ") + 11;
return this.parseIntAt (this.line, pt);
} catch (e) {
if (Clazz.exceptionOf (e, NumberFormatException)) {
return 0;
} else {
throw e;
}
}
}, $fz.isPrivate = true, $fz));
$_M(c$, "readArchiveHeader",
($fz = function () {
var modelInfo = this.readLine ();
if (J.util.Logger.debugging) J.util.Logger.debug (modelInfo);
if (modelInfo.indexOf ("Error:") == 0) return false;
this.atomSetCollection.setCollectionName (modelInfo);
this.modelName = this.readLine ();
if (J.util.Logger.debugging) J.util.Logger.debug (this.modelName);
this.readLine ();
return true;
}, $fz.isPrivate = true, $fz));
});
|
svgEditor.readLang({
lang: "uk",
dir : "ltr",
common: {
"ok": "Зберегти",
"cancel": "Скасування",
"key_backspace": "backspace",
"key_del": "delete",
"key_down": "down",
"key_up": "up",
"more_opts": "More Options",
"url": "URL",
"width": "Width",
"height": "Height"
},
misc: {
"powered_by": "Powered by"
},
ui: {
"toggle_stroke_tools": "Show/hide more stroke tools",
"palette_info": "Натисніть для зміни кольору заливки, Shift-Click змінити обвід",
"zoom_level": "Зміна масштабу",
"panel_drag": "Drag left/right to resize side panel"
},
properties: {
"id": "Identify the element",
"fill_color": "Зміна кольору заливки",
"stroke_color": "Зміна кольору інсульт",
"stroke_style": "Зміна стилю інсульт тире",
"stroke_width": "Зміни ширина штриха",
"pos_x": "Change X coordinate",
"pos_y": "Change Y coordinate",
"linecap_butt": "Linecap: Butt",
"linecap_round": "Linecap: Round",
"linecap_square": "Linecap: Square",
"linejoin_bevel": "Linejoin: Bevel",
"linejoin_miter": "Linejoin: Miter",
"linejoin_round": "Linejoin: Round",
"angle": "Зміна кута повороту",
"blur": "Change gaussian blur value",
"opacity": "Зміна вибраного пункту непрозорості",
"circle_cx": "CX зміну кола координата",
"circle_cy": "Зміни гуртка CY координати",
"circle_r": "Зміна кола's радіус",
"ellipse_cx": "Зміни еліпса CX координати",
"ellipse_cy": "Зміни еліпса CY координати",
"ellipse_rx": "Х Зміни еліпса радіусом",
"ellipse_ry": "Зміни у еліпса радіусом",
"line_x1": "Зміни починає координати лінія х",
"line_x2": "Зміни за період, що закінчився лінія координати х",
"line_y1": "Зміни лінія починає Y координата",
"line_y2": "Зміна за період, що закінчився лінія Y координата",
"rect_height": "Зміни прямокутник висотою",
"rect_width": "Зміна ширини прямокутника",
"corner_radius": "Зміни прямокутник Corner Radius",
"image_width": "Зміни ширина зображення",
"image_height": "Зміна висоти зображення",
"image_url": "Змінити URL",
"node_x": "Change node's x coordinate",
"node_y": "Change node's y coordinate",
"seg_type": "Change Segment type",
"straight_segments": "Straight",
"curve_segments": "Curve",
"text_contents": "Зміна змісту тексту",
"font_family": "Зміни Сімейство шрифтів",
"font_size": "Змінити розмір шрифту",
"bold": "Товстий текст",
"italic": "Похилий текст"
},
tools: {
"main_menu": "Main Menu",
"bkgnd_color_opac": "Зміна кольору тла / непрозорість",
"connector_no_arrow": "No arrow",
"fitToContent": "За розміром змісту",
"fit_to_all": "За розміром весь вміст",
"fit_to_canvas": "Розмір полотна",
"fit_to_layer_content": "За розміром шар змісту",
"fit_to_sel": "Вибір розміру",
"align_relative_to": "Вирівняти по відношенню до ...",
"relativeTo": "в порівнянні з:",
"сторінка": "сторінка",
"largest_object": "найбільший об'єкт",
"selected_objects": "обраними об'єктами",
"smallest_object": "маленький об'єкт",
"new_doc": "Нове зображення",
"open_doc": "Відкрити зображення",
"export_png": "Export as PNG",
"save_doc": "Зберегти малюнок",
"import_doc": "Import SVG",
"align_to_page": "Align Element to Page",
"align_bottom": "Вирівняти по нижньому краю",
"align_center": "Вирівняти по центру",
"align_left": "По лівому краю",
"align_middle": "Вирівняти Близького",
"align_right": "По правому краю",
"align_top": "Вирівняти по верхньому краю",
"mode_select": "Виберіть інструмент",
"mode_fhpath": "Pencil Tool",
"mode_line": "Line Tool",
"mode_connect": "Connect two objects",
"mode_rect": "Rectangle Tool",
"mode_square": "Square Tool",
"mode_fhrect": "Вільної руки Прямокутник",
"mode_ellipse": "Еліпс",
"mode_circle": "Коло",
"mode_fhellipse": "Вільної руки Еліпс",
"mode_path": "Path Tool",
"mode_shapelib": "Shape library",
"mode_text": "Текст Tool",
"mode_image": "Image Tool",
"mode_zoom": "Zoom Tool",
"mode_eyedropper": "Eye Dropper Tool",
"no_embed": "NOTE: This image cannot be embedded. It will depend on this path to be displayed",
"undo": "Скасувати",
"redo": "Повтор",
"tool_source": "Змінити вихідний",
"wireframe_mode": "Wireframe Mode",
"toggle_grid": "Show/Hide Grid",
"clone": "Clone Element(s)",
"del": "Delete Element(s)",
"group": "Група елементів",
"make_link": "Make (hyper)link",
"set_link_url": "Set link URL (leave empty to remove)",
"to_path": "Convert to Path",
"reorient_path": "Reorient path",
"ungroup": "Елементи розгрупувати",
"docprops": "Властивості документа",
"imagelib": "Image Library",
"move_bottom": "Перемістити вниз",
"move_top": "Перемістити догори",
"node_clone": "Clone Node",
"node_delete": "Delete Node",
"node_link": "Link Control Points",
"add_subpath": "Add sub-path",
"openclose_path": "Open/close sub-path",
"source_save": "Зберегти",
"cut": "Cut",
"copy": "Copy",
"paste": "Paste",
"paste_in_place": "Paste in Place",
"delete": "Delete",
"group": "Group",
"move_front": "Bring to Front",
"move_up": "Bring Forward",
"move_down": "Send Backward",
"move_back": "Send to Back"
},
layers: {
"layer":"Layer",
"layers": "Layers",
"del": "Видалити шар",
"move_down": "Перемістити шар на",
"new": "Новий шар",
"rename": "Перейменувати Шар",
"move_up": "Переміщення шару до",
"dupe": "Duplicate Layer",
"merge_down": "Merge Down",
"merge_all": "Merge All",
"move_elems_to": "Move elements to:",
"move_selected": "Move selected elements to a different layer"
},
config: {
"image_props": "Image Properties",
"doc_title": "Title",
"doc_dims": "Canvas Dimensions",
"included_images": "Included Images",
"image_opt_embed": "Embed data (local files)",
"image_opt_ref": "Use file reference",
"editor_prefs": "Editor Preferences",
"icon_size": "Icon size",
"language": "Language",
"background": "Editor Background",
"editor_img_url": "Image URL",
"editor_bg_note": "Note: Background will not be saved with image.",
"icon_large": "Large",
"icon_medium": "Medium",
"icon_small": "Small",
"icon_xlarge": "Extra Large",
"select_predefined": "Виберіть зумовлений:",
"units_and_rulers": "Units & Rulers",
"show_rulers": "Show rulers",
"base_unit": "Base Unit:",
"grid": "Grid",
"snapping_onoff": "Snapping on/off",
"snapping_stepsize": "Snapping Step-Size:",
"grid_color": "Grid color"
},
shape_cats: {
"basic": "Basic",
"object": "Objects",
"symbol": "Symbols",
"arrow": "Arrows",
"flowchart": "Flowchart",
"animal": "Animals",
"game": "Cards & Chess",
"dialog_balloon": "Dialog balloons",
"electronics": "Electronics",
"math": "Mathematical",
"music": "Music",
"misc": "Miscellaneous",
"raphael_1": "raphaeljs.com set 1",
"raphael_2": "raphaeljs.com set 2"
},
imagelib: {
"select_lib": "Select an image library",
"show_list": "Show library list",
"import_single": "Import single",
"import_multi": "Import multiple",
"open": "Open as new document"
},
notification: {
"invalidAttrValGiven":"Invalid value given",
"noContentToFitTo":"No content to fit to",
"dupeLayerName":"There is already a layer named that!",
"enterUniqueLayerName":"Please enter a unique layer name",
"enterNewLayerName":"Please enter the new layer name",
"layerHasThatName":"Layer already has that name",
"QmoveElemsToLayer":"Move selected elements to layer '%s'?",
"QwantToClear":"Do you want to clear the drawing?\nThis will also erase your undo history!",
"QwantToOpen":"Do you want to open a new file?\nThis will also erase your undo history!",
"QerrorsRevertToSource":"There were parsing errors in your SVG source.\nRevert back to original SVG source?",
"QignoreSourceChanges":"Ignore changes made to SVG source?",
"featNotSupported":"Feature not supported",
"enterNewImgURL":"Enter the new image URL",
"defsFailOnSave": "NOTE: Due to a bug in your browser, this image may appear wrong (missing gradients or elements). It will however appear correct once actually saved.",
"loadingImage":"Loading image, please wait...",
"saveFromBrowser": "Select \"Save As...\" in your browser to save this image as a %s file.",
"noteTheseIssues": "Also note the following issues: ",
"unsavedChanges": "There are unsaved changes.",
"enterNewLinkURL": "Enter the new hyperlink URL",
"errorLoadingSVG": "Error: Unable to load SVG data",
"URLloadFail": "Unable to load from URL",
"retrieving": "Retrieving \"%s\"..."
}
}); |
/**
* @file Using layout algorithm transform the raw data to layout information.
* @author Deqing Li(annong035@gmail.com)
*/
import * as zrUtil from 'zrender/src/core/util';
import * as numberUtil from '../../util/number';
export default function (ecModel, api) {
ecModel.eachSeriesByType('themeRiver', function (seriesModel) {
var data = seriesModel.getData();
var single = seriesModel.coordinateSystem;
var layoutInfo = {};
// use the axis boundingRect for view
var rect = single.getRect();
layoutInfo.rect = rect;
var boundaryGap = seriesModel.get('boundaryGap');
var axis = single.getAxis();
layoutInfo.boundaryGap = boundaryGap;
if (axis.orient === 'horizontal') {
boundaryGap[0] = numberUtil.parsePercent(boundaryGap[0], rect.height);
boundaryGap[1] = numberUtil.parsePercent(boundaryGap[1], rect.height);
var height = rect.height - boundaryGap[0] - boundaryGap[1];
themeRiverLayout(data, seriesModel, height);
}
else {
boundaryGap[0] = numberUtil.parsePercent(boundaryGap[0], rect.width);
boundaryGap[1] = numberUtil.parsePercent(boundaryGap[1], rect.width);
var width = rect.width - boundaryGap[0] - boundaryGap[1];
themeRiverLayout(data, seriesModel, width);
}
data.setLayout('layoutInfo', layoutInfo);
});
}
/**
* The layout information about themeriver
*
* @param {module:echarts/data/List} data data in the series
* @param {module:echarts/model/Series} seriesModel the model object of themeRiver series
* @param {number} height value used to compute every series height
*/
function themeRiverLayout(data, seriesModel, height) {
if (!data.count()) {
return;
}
var coordSys = seriesModel.coordinateSystem;
// the data in each layer are organized into a series.
var layerSeries = seriesModel.getLayerSeries();
// the points in each layer.
var layerPoints = zrUtil.map(layerSeries, function (singleLayer) {
return zrUtil.map(singleLayer.indices, function (idx) {
var pt = coordSys.dataToPoint(data.get('time', idx));
pt[1] = data.get('value', idx);
return pt;
});
});
var base = computeBaseline(layerPoints);
var baseLine = base.y0;
var ky = height / base.max;
// set layout information for each item.
var n = layerSeries.length;
var m = layerSeries[0].indices.length;
var baseY0;
for (var j = 0; j < m; ++j) {
baseY0 = baseLine[j] * ky;
data.setItemLayout(layerSeries[0].indices[j], {
layerIndex: 0,
x: layerPoints[0][j][0],
y0: baseY0,
y: layerPoints[0][j][1] * ky
});
for (var i = 1; i < n; ++i) {
baseY0 += layerPoints[i - 1][j][1] * ky;
data.setItemLayout(layerSeries[i].indices[j], {
layerIndex: i,
x: layerPoints[i][j][0],
y0: baseY0,
y: layerPoints[i][j][1] * ky
});
}
}
}
/**
* Compute the baseLine of the rawdata
* Inspired by Lee Byron's paper Stacked Graphs - Geometry & Aesthetics
*
* @param {Array.<Array>} data the points in each layer
* @return {Object}
*/
function computeBaseline(data) {
var layerNum = data.length;
var pointNum = data[0].length;
var sums = [];
var y0 = [];
var max = 0;
var temp;
var base = {};
for (var i = 0; i < pointNum; ++i) {
for (var j = 0, temp = 0; j < layerNum; ++j) {
temp += data[j][i][1];
}
if (temp > max) {
max = temp;
}
sums.push(temp);
}
for (var k = 0; k < pointNum; ++k) {
y0[k] = (max - sums[k]) / 2;
}
max = 0;
for (var l = 0; l < pointNum; ++l) {
var sum = sums[l] + y0[l];
if (sum > max) {
max = sum;
}
}
base.y0 = y0;
base.max = max;
return base;
} |
/*
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for
* license information.
*
* Code generated by Microsoft (R) AutoRest Code Generator.
* Changes may cause incorrect behavior and will be lost if the code is
* regenerated.
*/
'use strict';
/**
* The response of a list operation.
*/
class ResponseWithContinuationArmTemplate extends Array {
/**
* Create a ResponseWithContinuationArmTemplate.
* @member {string} [nextLink] Link for next set of results.
*/
constructor() {
super();
}
/**
* Defines the metadata of ResponseWithContinuationArmTemplate
*
* @returns {object} metadata of ResponseWithContinuationArmTemplate
*
*/
mapper() {
return {
required: false,
serializedName: 'ResponseWithContinuation[ArmTemplate]',
type: {
name: 'Composite',
className: 'ResponseWithContinuationArmTemplate',
modelProperties: {
value: {
required: false,
serializedName: '',
type: {
name: 'Sequence',
element: {
required: false,
serializedName: 'ArmTemplateElementType',
type: {
name: 'Composite',
className: 'ArmTemplate'
}
}
}
},
nextLink: {
required: false,
serializedName: 'nextLink',
type: {
name: 'String'
}
}
}
}
};
}
}
module.exports = ResponseWithContinuationArmTemplate;
|
/**
* Tests if a value is a thenable (promise).
*/
module.exports = function _isThenable(value) {
return (value != null) && (value === Object(value)) && typeof value.then === 'function';
};
|
function IDServerAPI(url, auth, auth_cb) {
this.url = url;
var _url = url;
var deprecationWarningSent = false;
function deprecationWarning() {
if (!deprecationWarningSent) {
deprecationWarningSent = true;
if (!window.console) return;
console.log(
"DEPRECATION WARNING: '*_async' method names will be removed",
"in a future version. Please use the identical methods without",
"the'_async' suffix.");
}
}
if (typeof(_url) != "string" || _url.length == 0) {
_url = "http://localhost:7031";
}
var _auth = auth ? auth : { 'token' : '', 'user_id' : ''};
var _auth_cb = auth_cb;
this.kbase_ids_to_external_ids = function (ids, _callback, _errorCallback) {
return json_call_ajax("IDServerAPI.kbase_ids_to_external_ids",
[ids], 1, _callback, _errorCallback);
};
this.kbase_ids_to_external_ids_async = function (ids, _callback, _error_callback) {
deprecationWarning();
return json_call_ajax("IDServerAPI.kbase_ids_to_external_ids", [ids], 1, _callback, _error_callback);
};
this.external_ids_to_kbase_ids = function (external_db, ext_ids, _callback, _errorCallback) {
return json_call_ajax("IDServerAPI.external_ids_to_kbase_ids",
[external_db, ext_ids], 1, _callback, _errorCallback);
};
this.external_ids_to_kbase_ids_async = function (external_db, ext_ids, _callback, _error_callback) {
deprecationWarning();
return json_call_ajax("IDServerAPI.external_ids_to_kbase_ids", [external_db, ext_ids], 1, _callback, _error_callback);
};
this.register_ids = function (prefix, db_name, ids, _callback, _errorCallback) {
return json_call_ajax("IDServerAPI.register_ids",
[prefix, db_name, ids], 1, _callback, _errorCallback);
};
this.register_ids_async = function (prefix, db_name, ids, _callback, _error_callback) {
deprecationWarning();
return json_call_ajax("IDServerAPI.register_ids", [prefix, db_name, ids], 1, _callback, _error_callback);
};
this.allocate_id_range = function (kbase_id_prefix, count, _callback, _errorCallback) {
return json_call_ajax("IDServerAPI.allocate_id_range",
[kbase_id_prefix, count], 1, _callback, _errorCallback);
};
this.allocate_id_range_async = function (kbase_id_prefix, count, _callback, _error_callback) {
deprecationWarning();
return json_call_ajax("IDServerAPI.allocate_id_range", [kbase_id_prefix, count], 1, _callback, _error_callback);
};
this.register_allocated_ids = function (prefix, db_name, assignments, _callback, _errorCallback) {
return json_call_ajax("IDServerAPI.register_allocated_ids",
[prefix, db_name, assignments], 0, _callback, _errorCallback);
};
this.register_allocated_ids_async = function (prefix, db_name, assignments, _callback, _error_callback) {
deprecationWarning();
return json_call_ajax("IDServerAPI.register_allocated_ids", [prefix, db_name, assignments], 0, _callback, _error_callback);
};
this.get_identifier_prefix = function (_callback, _errorCallback) {
return json_call_ajax("IDServerAPI.get_identifier_prefix",
[], 1, _callback, _errorCallback);
};
this.get_identifier_prefix_async = function (_callback, _error_callback) {
deprecationWarning();
return json_call_ajax("IDServerAPI.get_identifier_prefix", [], 1, _callback, _error_callback);
};
/*
* JSON call using jQuery method.
*/
function json_call_ajax(method, params, numRets, callback, errorCallback) {
var deferred = $.Deferred();
if (typeof callback === 'function') {
deferred.done(callback);
}
if (typeof errorCallback === 'function') {
deferred.fail(errorCallback);
}
var rpc = {
params : params,
method : method,
version: "1.1",
id: String(Math.random()).slice(2),
};
var beforeSend = null;
var token = (_auth_cb && typeof _auth_cb === 'function') ? _auth_cb()
: (_auth.token ? _auth.token : null);
if (token != null) {
beforeSend = function (xhr) {
xhr.setRequestHeader("Authorization", token);
}
}
var xhr = jQuery.ajax({
url: _url,
dataType: "text",
type: 'POST',
processData: false,
data: JSON.stringify(rpc),
beforeSend: beforeSend,
success: function (data, status, xhr) {
var result;
try {
var resp = JSON.parse(data);
result = (numRets === 1 ? resp.result[0] : resp.result);
} catch (err) {
deferred.reject({
status: 503,
error: err,
url: _url,
resp: data
});
return;
}
deferred.resolve(result);
},
error: function (xhr, textStatus, errorThrown) {
var error;
if (xhr.responseText) {
try {
var resp = JSON.parse(xhr.responseText);
error = resp.error;
} catch (err) { // Not JSON
error = "Unknown error - " + xhr.responseText;
}
} else {
error = "Unknown Error";
}
deferred.reject({
status: 500,
error: error
});
}
});
var promise = deferred.promise();
promise.xhr = xhr;
return promise;
}
}
|
define(function(require) {
var registerSuite = require('intern!object');
var w3cTest = require('../support/w3cTest');
var name = 'pointerevent_setpointercapture_disconnected-manual';
registerSuite({
name: name,
main: function() {
return w3cTest(this.remote, name + '.html')
.findById('target0')
.moveMouseTo(50, 25)
.clickMouseButton(0)
.end()
.checkResults();
}
});
});
|
import React from 'react';
import { render } from 'react-dom';
import { Tab, Tabs, TabList, TabPanel } from '../../src/index';
import '../../style/react-tabs.css';
const App = () => {
return (
<div style={{ padding: 50 }}>
<Tabs>
<TabList>
<Tab>The Simpsons</Tab>
<Tab>Futurama</Tab>
</TabList>
<TabPanel>
<Tabs>
<TabList>
<Tab>Homer Simpson</Tab>
<Tab>Marge Simpson</Tab>
<Tab>Bart Simpson</Tab>
<Tab>Lisa Simpson</Tab>
<Tab>Maggie Simpson</Tab>
</TabList>
<TabPanel>
<p>Husband of Marge; father of Bart, Lisa, and Maggie.</p>
<img src="https://upload.wikimedia.org/wikipedia/en/thumb/0/02/Homer_Simpson_2006.png/212px-Homer_Simpson_2006.png" alt="Homer Simpson" />
</TabPanel>
<TabPanel>
<p>Wife of Homer; mother of Bart, Lisa, and Maggie.</p>
<img src="https://upload.wikimedia.org/wikipedia/en/thumb/0/0b/Marge_Simpson.png/220px-Marge_Simpson.png" alt="Marge Simpson" />
</TabPanel>
<TabPanel>
<p>Oldest child and only son of Homer and Marge; brother of Lisa and Maggie.</p>
<img src="https://upload.wikimedia.org/wikipedia/en/a/aa/Bart_Simpson_200px.png" alt="Bart Simpson" />
</TabPanel>
<TabPanel>
<p>Middle child and eldest daughter of Homer and Marge; sister of Bart and Maggie.</p>
<img src="https://upload.wikimedia.org/wikipedia/en/thumb/e/ec/Lisa_Simpson.png/200px-Lisa_Simpson.png" alt="Lisa Simpson" />
</TabPanel>
<TabPanel>
<p>Youngest child and daughter of Homer and Marge; sister of Bart and Lisa.</p>
<img src="https://upload.wikimedia.org/wikipedia/en/thumb/9/9d/Maggie_Simpson.png/223px-Maggie_Simpson.png" alt="Maggie Simpson" />
</TabPanel>
</Tabs>
</TabPanel>
<TabPanel>
<Tabs>
<TabList>
<Tab>Philip J. Fry</Tab>
<Tab>Turanga Leela</Tab>
<Tab>Bender Bending Rodriguez</Tab>
<Tab>Amy Wong</Tab>
<Tab>Professor Hubert J. Farnsworth</Tab>
<Tab>Doctor John Zoidberg</Tab>
</TabList>
<TabPanel>
<p>Protagonist, from the 20th Century. Delivery boy. Many times great-uncle to Professor Hubert Farnsworth. Suitor of Leela.</p>
<img src="https://upload.wikimedia.org/wikipedia/en/thumb/2/28/Philip_Fry.png/175px-Philip_Fry.png" alt="Philip J. Fry" />
</TabPanel>
<TabPanel>
<p>Mutant cyclops. Captain of the Planet Express Ship. Love interest of Fry.</p>
<img src="https://upload.wikimedia.org/wikipedia/en/thumb/d/d4/Turanga_Leela.png/150px-Turanga_Leela.png" alt="Turanga Leela" />
</TabPanel>
<TabPanel>
<p>A kleptomaniacal, lazy, cigar-smoking, heavy-drinking robot who is Fry's best friend. Built in Tijuana, Mexico, he is the Planet Express Ship's cook.</p>
<img src="https://upload.wikimedia.org/wikipedia/en/thumb/a/a6/Bender_Rodriguez.png/220px-Bender_Rodriguez.png" alt="Bender Bending Rodriguez" />
</TabPanel>
<TabPanel>
<p>Chinese-Martian intern at Planet Express. Fonfon Ru of Kif Kroker.</p>
<img src="https://upload.wikimedia.org/wikipedia/en/thumb/f/fd/FuturamaAmyWong.png/140px-FuturamaAmyWong.png" alt="Amy Wong" />
</TabPanel>
<TabPanel>
<p>Many times great-nephew of Fry. CEO and owner of Planet Express delivery company. Tenured professor of Mars University.</p>
<img src="https://upload.wikimedia.org/wikipedia/en/thumb/0/0f/FuturamaProfessorFarnsworth.png/175px-FuturamaProfessorFarnsworth.png" alt="Professor Hubert J. Farnsworth" />
</TabPanel>
<TabPanel>
<p>Alien from Decapod 10. Planet Express' staff doctor and steward. Has a medical degree and Ph.D in art history.</p>
<img src="https://upload.wikimedia.org/wikipedia/en/thumb/4/4a/Dr_John_Zoidberg.png/200px-Dr_John_Zoidberg.png" alt="Doctor John Zoidberg" />
</TabPanel>
</Tabs>
</TabPanel>
</Tabs>
</div>
);
};
render(<App />, document.getElementById('example'));
|
(function(e){e.color={};e.color.make=function(c,a,d,f){var b={};b.r=c||0;b.g=a||0;b.b=d||0;b.a=null!=f?f:1;b.add=function(a,c){for(var d=0;d<a.length;++d)b[a.charAt(d)]+=c;return b.normalize()};b.scale=function(a,d){for(var c=0;c<a.length;++c)b[a.charAt(c)]*=d;return b.normalize()};b.toString=function(){return 1<=b.a?"rgb("+[b.r,b.g,b.b].join()+")":"rgba("+[b.r,b.g,b.b,b.a].join()+")"};b.normalize=function(){function a(b,c,d){return c<b?b:c>d?d:c}b.r=a(0,parseInt(b.r),255);b.g=a(0,parseInt(b.g),255);
b.b=a(0,parseInt(b.b),255);b.a=a(0,b.a,1);return b};b.clone=function(){return e.color.make(b.r,b.b,b.g,b.a)};return b.normalize()};e.color.extract=function(c,a){var d;do{d=c.css(a).toLowerCase();if(""!=d&&"transparent"!=d)break;c=c.parent()}while(c.length&&!e.nodeName(c.get(0),"body"));"rgba(0, 0, 0, 0)"==d&&(d="transparent");return e.color.parse(d)};e.color.parse=function(c){var a,d=e.color.make;if(a=/rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(c))return d(parseInt(a[1],
10),parseInt(a[2],10),parseInt(a[3],10));if(a=/rgba\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(c))return d(parseInt(a[1],10),parseInt(a[2],10),parseInt(a[3],10),parseFloat(a[4]));if(a=/rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(c))return d(2.55*parseFloat(a[1]),2.55*parseFloat(a[2]),2.55*parseFloat(a[3]));if(a=/rgba\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\s*\)/.exec(c))return d(2.55*
parseFloat(a[1]),2.55*parseFloat(a[2]),2.55*parseFloat(a[3]),parseFloat(a[4]));if(a=/#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(c))return d(parseInt(a[1],16),parseInt(a[2],16),parseInt(a[3],16));if(a=/#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(c))return d(parseInt(a[1]+a[1],16),parseInt(a[2]+a[2],16),parseInt(a[3]+a[3],16));c=e.trim(c).toLowerCase();if("transparent"==c)return d(255,255,255,0);a=g[c]||[0,0,0];return d(a[0],a[1],a[2])};var g={aqua:[0,255,255],azure:[240,255,255],beige:[245,
245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,
144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]}})(jQuery);
|
var helpers = require('../helpers');
var Joi = require('joi');
var assert = require('assert');
describe('basic embedded schema', function() {
var res = { items: null };
var expected = {
count: 50,
schema: Joi.object().keys({
user_email: Joi.string().email().required(),
job: Joi.object().keys({
company: Joi.string().required(),
phone: Joi.string().regex(helpers.regex.phone).required(),
duties: Joi.string().required(),
}).length(3).required()
}).length(2)
};
before(function(done) {
var schemaPath = helpers.resolveSchemaPath('20_embedded_basic.json');
var opts = {
size: 50,
};
helpers.generate(schemaPath, opts, function (err, items) {
if (err) return done(err);
res.items = items;
done();
});
});
it('should have the correct size', function () {
assert.equal(expected.count, res.items.length);
});
it('should produce correct schema structure', function () {
res.items.forEach(function (item) {
Joi.validate(item, expected.schema, function(err) {
assert.ifError(err);
});
});
});
it('should produce entries with random content', function (done) {
helpers.sampleAndStrip(res.items, 2, function (sample) {
assert.notDeepEqual(sample[0], sample[1]);
done();
});
});
});
describe('schema with parallel embedded fields', function() {
var res = { items: null };
var expected = {
count: 33,
schema: Joi.object().keys({
user_email: Joi.string().email().required(),
job: Joi.object().keys({
company: Joi.string().required(),
phone: Joi.string().regex(helpers.regex.phone).required(),
duties: Joi.string().required(),
}).length(3).required(),
payment_method: Joi.object().keys({
type: Joi.string().required(),
card: Joi.number().integer().required(),
expiration: Joi.string().regex(helpers.regex.exp).required()
}).length(3).required()
}).length(3)
};
before(function(done) {
var schemaPath = helpers.resolveSchemaPath('21_embedded_multi.json');
var opts = {
size: 33,
};
helpers.generate(schemaPath, opts, function (err, items) {
if (err) return done(err);
res.items = items;
done();
});
});
it('should have the correct size', function () {
assert.equal(expected.count, res.items.length);
});
it('should produce correct schema structure', function () {
res.items.forEach(function (item) {
Joi.validate(item, expected.schema, function(err) {
assert.ifError(err);
});
});
});
it('should produce entries with random content', function (done) {
helpers.sampleAndStrip(res.items, 2, function (sample) {
assert.notDeepEqual(sample[0], sample[1]);
done();
});
});
});
describe('schema with high level of embedding', function() {
var res = { items: null };
var expected = {
count: 23,
schema: Joi.object().keys({
user_email: Joi.string().email().required(),
personalities: Joi.object().keys({
favorites: Joi.object().keys({
number: Joi.number().integer().max(10).required(),
city: Joi.string().required(),
radio: Joi.string().required()
}).length(3).required(),
rating: Joi.number().integer().max(6).required(),
}).length(2).required()
}).length(2)
};
before(function(done) {
var schemaPath = helpers.resolveSchemaPath('22_embedded_level.json');
var opts = {
size: 23,
};
helpers.generate(schemaPath, opts, function (err, items) {
if (err) return done(err);
res.items = items;
done();
});
});
it('should have the correct size', function () {
assert.equal(expected.count, res.items.length);
});
it('should produce correct schema structure', function () {
res.items.forEach(function (item) {
Joi.validate(item, expected.schema, function(err) {
assert.ifError(err);
});
});
});
it('should produce entries with random content', function (done) {
helpers.sampleAndStrip(res.items, 2, function (sample) {
assert.notDeepEqual(sample[0], sample[1]);
done();
});
});
});
describe('complex embedded schema', function() {
var res = { items: null };
var expected = {
count: 19,
schema: Joi.object().keys({
user_email: Joi.string().email().required(),
job: Joi.object().keys({
company: Joi.string().required(),
phone: Joi.string().regex(helpers.regex.phone).required(),
duties: Joi.string().required(),
}).length(3).required(),
personalities: Joi.object().keys({
favorites: Joi.object().keys({
number: Joi.number().integer().max(10).required(),
city: Joi.string().required(),
radio: Joi.string().required()
}).length(3).required(),
rating: Joi.number().integer().max(6).required(),
}).length(2).required(),
payment_method: Joi.object().keys({
type: Joi.string().required(),
card: Joi.number().integer().required(),
expiration: Joi.string().regex(helpers.regex.exp).required()
}).length(3).required()
}).length(4)
};
before(function(done) {
var schemaPath = helpers.resolveSchemaPath('23_embedded_complex.json');
var opts = {
size: 19,
};
helpers.generate(schemaPath, opts, function (err, items) {
if (err) return done(err);
res.items = items;
done();
});
});
it('should have the correct size', function () {
assert.equal(expected.count, res.items.length);
});
it('should produce correct schema structure', function () {
res.items.forEach(function (item) {
Joi.validate(item, expected.schema, function(err) {
assert.ifError(err);
});
});
});
it('should produce entries with random content', function (done) {
helpers.sampleAndStrip(res.items, 2, function (sample) {
assert.notDeepEqual(sample[0], sample[1]);
done();
});
});
});
|
import React from 'react-native';
import Root from './src/root';
const {
AppRegistry,
} = React;
AppRegistry.registerComponent('Quilt', () => Root);
|
define(['./toArray', '../array/find'], function (toArray, find) {
/**
* Return first non void argument
*/
function defaults(var_args){
return find(toArray(arguments), nonVoid);
}
function nonVoid(val){
return val != null;
}
return defaults;
});
|
/**
* Created by joshuarose on 1/8/14.
*/
questApp.controller('results-list-controller', function($scope, userService, $state) {
$scope.results = "";
$scope.loggedIn = false;
$scope.empty = true;
$scope.showDelete = false;
$scope.offline = false;
$scope.init = function () {
if (dpd === undefined){
$scope.offline = true;
return;
}
if (userService.loggedIn) {
$scope.loggedIn = true;
dpd.results.get({owner: userService.currentUser.username }, function(results, error) {
if(error){
return;
}
$scope.results = results;
if (results.length > 0){
$scope.empty = false;
}
$scope.$apply();
});
}
else {
$state.go('tab.login');
}
};
$scope.deleteResult = function (item) {
dpd.results.del(item.id, function (result, error){
});
$scope.results.splice($scope.results.indexOf(item), 1);
$scope.$apply();
};
$scope.leftButtons = [
{
type: "button-positive",
content: "<i class='ion-edit'></i>",
tap : function (e) {
if ($scope.showDelete){
$scope.showDelete = false;
}
else{
$scope.showDelete = true;
}
}
}
];
$scope.init();
}); |
/* ph replacements */
/* className, /SeedlessBanana/g, SeedlessBanana */
/* endph */
/* ph stamps */
/* /^(?!withSeeds{1})(?!withSeedsSymbol{1}).*$/ */
/* endph */
/* stamp withSeedsSymbol */
/* endstamp */
export default class SeedlessBanana {
constructor() {
/* ph constructor */
/* endph */
}
/* stamp withSeeds */
/* endstamp */
eat() {
/* ph onomatopoeia */
return "puaj";
/* endph */
}
/* stamp throwAway */
/* endstamp */
}
|
var fs = require('fs');
|
var fs = require('fs');
[
'base',
'base-override-app',
'base-override-touch',
'base-override-app-touch',
'app_base-override-app',
'app_base-override-app-touch',
'app',
'app-override-touch',
'touch_base-override-touch',
'touch_app-override-touch',
'touch_base-override-app-touch',
'touch'
].forEach(function(fn){
fs.writeFileSync(name + '.tmpl',
'<b:style src="' + name + '.css"/>\n<!-- ' + name + ' -->'
);
fs.writeFileSync(name + '.css',
'.' + fn.substring(2, fn.length - 5) + ' {}'
);
});
|
$(function() {
$('.inbox').on('click', function(e) {
var msgId = e.target.dataset.id;
$("#msgbody" + msgId).toggle();
});
}); |
"use strict";
var React = require('react');
var invariant = require('react/lib/invariant');
var assign = Object.assign || require('object.assign');
var matchRoutes = require('./matchRoutes');
var Environment = require('./environment');
var RouterMixin = {
mixins: [Environment.Mixin],
propTypes: {
path: React.PropTypes.string,
contextual: React.PropTypes.bool,
onBeforeNavigation: React.PropTypes.func,
onNavigation: React.PropTypes.func
},
childContextTypes: {
router: React.PropTypes.any
},
getChildContext: function() {
return {
router: this
};
},
contextTypes: {
router: React.PropTypes.any
},
getInitialState: function() {
return this.getRouterState(this.props);
},
componentWillReceiveProps: function(nextProps) {
var nextState = this.getRouterState(nextProps);
this.delegateSetRoutingState(nextState);
},
getRouterState: function(props) {
var path;
var prefix;
var parent = props.contextual && this.getParentRouter();
if (parent) {
var parentMatch = parent.getMatch();
invariant(
props.path ||
isString(parentMatch.unmatchedPath) ||
parentMatch.matchedPath === parentMatch.path,
"contextual router has nothing to match on: %s", parentMatch.unmatchedPath
);
path = props.path || parentMatch.unmatchedPath || '/';
prefix = parent.state.prefix + parentMatch.matchedPath;
} else {
path = props.path || this.getEnvironment().getPath();
invariant(
isString(path),
("router operate in environment which cannot provide path, " +
"pass it a path prop; or probably you want to make it contextual")
);
prefix = '';
}
if (path[0] !== '/') {
path = '/' + path;
}
var match = matchRoutes(this.getRoutes(props), path);
var handler = match.getHandler();
return {
match: match,
handler: handler,
prefix: prefix,
navigation: {}
};
},
getEnvironment: function() {
if (this.props.environment) {
return this.props.environment;
}
if (this.props.hash) {
return Environment.hashEnvironment;
}
if (this.props.contextual && this.context.router) {
return this.context.router.getEnvironment();
}
return Environment.defaultEnvironment;
},
/**
* Return parent router or undefined.
*/
getParentRouter: function() {
var current = this.context.router;
var environment = this.getEnvironment();
if (current) {
if (current.getEnvironment() === environment) {
return current;
}
}
},
/**
* Return current match.
*/
getMatch: function() {
return this.state.match;
},
/**
* Make href scoped for the current router.
*/
makeHref: function(href) {
return join(this.state.prefix, href);
},
/**
* Navigate to a path
*
* @param {String} path
* @param {Function} navigation
* @param {Callback} cb
*/
navigate: function(path, navigation, cb) {
path = join(this.state.prefix, path);
this.getEnvironment().setPath(path, navigation, cb);
},
/**
* Set new path.
*
* This function is called by environment.
*
* @private
*
* @param {String} path
* @param {Function} navigation
* @param {Callback} cb
*/
setPath: function(path, navigation, cb) {
var match = matchRoutes(this.getRoutes(this.props), path);
var handler = match.getHandler();
var state = {
match: match,
handler: handler,
prefix: this.state.prefix,
navigation: navigation
};
assign(navigation, {match: match});
if (this.props.onBeforeNavigation &&
this.props.onBeforeNavigation(path, navigation) === false) {
return;
}
if (navigation.onBeforeNavigation &&
navigation.onBeforeNavigation(path, navigation) === false) {
return;
}
this.delegateSetRoutingState(state, function() {
if (this.props.onNavigation) {
this.props.onNavigation();
}
cb();
}.bind(this));
},
/**
* Return the current path
*/
getPath: function () {
return this.state.match.path;
},
/**
* Try to delegate state update to a setRoutingState method (might be provided
* by router itself) or use replaceState.
*/
delegateSetRoutingState: function(state, cb) {
if (this.setRoutingState) {
this.setRoutingState(state, cb);
} else {
this.replaceState(state, cb);
}
}
};
function join(a, b) {
return (a + b).replace(/\/\//g, '/');
}
function isString(o) {
return Object.prototype.toString.call(o) === '[object String]';
}
module.exports = RouterMixin;
|
/**
* Install babel
*/
require('babel-register');
require('./web/server/server.js');
|
import React from 'react';
import ReactDOM from 'react-dom';
import JqxComboBox from '../../../jqwidgets-react/react_jqxcombobox.js';
class App extends React.Component {
componentDidMount() {
this.refs.myComboBox.checkIndex(0);
this.refs.myComboBox.on('checkChange', (event) => {
if (event.args) {
let item = event.args.item;
if (item) {
let valueElement = document.createElement('div');
valueElement.innerHTML = 'Value: ' + item.value;
let labelElement = document.createElement('div');
labelElement.innerHTML = 'Label: ' + item.label;
let checkedElement = document.createElement('div');
checkedElement.innerHTML = 'Checked: ' + item.checked;
let selectionLog = document.getElementById('selectionlog');
while (selectionLog.firstChild) {
selectionLog.removeChild(selectionLog.firstChild);
}
selectionLog.appendChild(labelElement);
selectionLog.appendChild(valueElement);
selectionLog.appendChild(checkedElement);
let items = this.refs.myComboBox.getCheckedItems();
let checkedItems = '';
$.each(items, function (index) {
checkedItems += this.label + ', ';
});
document.getElementById('checkedItemsLog').innerHTML = checkedItems;
}
}
});
}
render() {
let source =
{
datatype: 'json',
datafields: [
{ name: 'CompanyName' },
{ name: 'ContactName' }
],
id: 'id',
url: '../sampledata/customers.txt',
async: false
};
let dataAdapter = new $.jqx.dataAdapter(source);
return (
<div>
<JqxComboBox ref='myComboBox' style={{ float: 'left' }}
width={200} height={25} source={dataAdapter} checkboxes={true}
displayMember={'ContactName'} valueMember={'CompanyName'}
/>
<div style={{ float: 'left', marginLeft: 20, fontSize: 13, fontFamily: 'Verdana' }}>
<div id='selectionlog' />
<div style={{ maxWidth: 300, marginTop: 20 }} id='checkedItemsLog' />
</div>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
var express = require('express');
var app = express();//调用函数可以得到应用对象app
/**
* 配置路由
* get 表示请求的方法
* '/' 表示请求的路径
* function 代表当请求到来的时候执行的回调函数
* 路由的特点是一旦匹配就不再往下继续匹配了
*
* 路由 -根据请求的方法和请求的路径匹配对应的处理函数
*/
app.get('/',function(req,res){
res.end('homepage');
});
//不考虑请求的方法,只匹配路径
app.all('/user',function(req,res){
res.end('user');
});
//不考虑方法,也不考虑路径
app.all('*',function(req,res){
res.end('404');
});
app.listen(9090); |
/**
* @fileoverview Tests for require newline before `return` statement
* @author Kai Cataldo
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
var rule = require("../../../lib/rules/newline-before-return"),
RuleTester = require("../../../lib/testers/rule-tester");
//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------
var ruleTester = new RuleTester();
ruleTester.run("newline-before-return", rule, {
valid: [
"function a() {\nreturn;\n}",
"function a() {\n\nreturn;\n}",
"function a() {\nvar b;\n\nreturn;\n}",
"function a() {\nif (b) return;\n}",
"function a() {\nif (b) { return; }\n}",
"function a() {\nif (b) {\nreturn;\n}\n}",
"function a() {\nif (b) {\n\nreturn;\n}\n}",
"function a() {\nif (b) {\nreturn;\n}\n\nreturn c;\n}",
"function a() {\nif (b) {\n\nreturn;\n}\n\nreturn c;\n}",
"function a() {\nif (!b) {\nreturn;\n} else {\nreturn b;\n}\n}",
"function a() {\nif (!b) {\nreturn;\n} else {\n\nreturn b;\n}\n}",
"function a() {\nif (b) {\nreturn b;\n} else if (c) {\nreturn c;\n}\n}",
"function a() {\nif (b) {\nreturn b;\n} else if (c) {\nreturn c;\n} else {\nreturn d;\n}\n}",
"function a() {\nif (b) {\nreturn b;\n} else if (c) {\nreturn c;\n} else {\nreturn d;\n}\n\nreturn a;\n}",
"function a() {\nif (b) return b;\nelse if (c) return c;\nelse return d;\n}",
"function a() {\nif (b) return b;\nelse if (c) return c;\nelse {\nreturn d;\n}\n}",
"function a() {\nif (b) return b;\nelse if (c) return c;\nelse {\ne();\n\nreturn d;\n}\n}",
"function a() {\nwhile (b) return;\n}",
"function a() {\n while (b) \nreturn;\n}",
"function a() {\n while (b) { return; }\n}",
"function a() {\n while (b) {\nreturn;\n}\n}",
"function a() {\n while (b) {\nc();\n\nreturn;\n}\n}",
"function a() {\nvar c;\nwhile (b) {\n c = d; //comment\n}\n\nreturn c;\n}",
"function a() {\ndo return;\nwhile (b);\n}",
"function a() {\ndo \nreturn;\nwhile (b);\n}",
"function a() {\ndo { return; } while (b);\n}",
"function a() {\ndo { return; }\nwhile (b);\n}",
"function a() {\ndo {\nreturn;\n} while (b);\n}",
"function a() {\ndo {\nc();\n\nreturn;\n} while (b);\n}",
"function a() {\nfor (var b; b < c; b++) return;\n}",
"function a() {\nfor (var b; b < c; b++)\nreturn;\n}",
"function a() {\nfor (var b; b < c; b++) {\nreturn;\n}\n}",
"function a() {\nfor (var b; b < c; b++) {\nc();\n\nreturn;\n}\n}",
"function a() {\nfor (var b; b < c; b++) {\nif (d) {\nbreak; //comment\n}\n\nreturn;\n}\n}",
"function a() {\nfor (b in c)\nreturn;\n}",
"function a() {\nfor (b in c) { return; }\n}",
"function a() {\nfor (b in c) {\nreturn;\n}\n}",
"function a() {\nfor (b in c) {\nd();\n\nreturn;\n}\n}",
{
code: "function a() {\nfor (b of c) return;\n}",
parserOptions: { ecmaVersion: 6 }
},
{
code: "function a() {\nfor (b of c)\nreturn;\n}",
parserOptions: { ecmaVersion: 6 }
},
{
code: "function a() {\nfor (b of c) {\nreturn;\n}\n}",
parserOptions: { ecmaVersion: 6 }
},
{
code: "function a() {\nfor (b of c) {\nd();\n\nreturn;\n}\n}",
parserOptions: { ecmaVersion: 6 }
},
"function a() {\nswitch (b) {\ncase 'b': return;\n}\n}",
"function a() {\nswitch (b) {\ncase 'b':\nreturn;\n}\n}",
"function a() {\nswitch (b) {\ncase 'b': {\nreturn;\n}\n}\n}",
"function a() {\n//comment\nreturn b;\n}",
"function a() {\n{\n//comment\n}\n\nreturn\n}",
"function a() {\nvar b = {\n//comment\n};\n\nreturn;\n}",
"function a() {/*multi-line\ncomment*/return b;\n}",
"function a() {\n/*comment\ncomment*/\n//comment\nreturn b;\n}",
"function a() {\n/*comment\ncomment*/\n//comment\nif (b) return;\n}",
"function a() {\n/*comment\ncomment*/\n//comment\nif (b) {\nc();\n\nreturn b;\n} else {\n//comment\nreturn d;\n}\n\n/*multi-line\ncomment*/\nreturn e;\n}",
"function a() {\nif (b) { //comment\nreturn;\n}\n\nreturn c;\n}",
"function a() {\nif (b) { return; } //comment\n\nreturn c;\n}",
"function a() {\nif (b) { return; } /*multi-line\ncomment*/\n\nreturn c;\n}",
"function a() {\nif (b) { return; }\n\n/*multi-line\ncomment*/ return c;\n}",
{
code: "return;",
parserOptions: { ecmaFeatures: { globalReturn: true } }
},
{
code: "var a;\n\nreturn;",
parserOptions: { ecmaFeatures: { globalReturn: true } }
},
{
code: "// comment\nreturn;",
parserOptions: { ecmaFeatures: { globalReturn: true } }
},
{
code: "/* comment */\nreturn;",
parserOptions: { ecmaFeatures: { globalReturn: true } }
},
{
code: "/* multi-line\ncomment */\nreturn;",
parserOptions: { ecmaFeatures: { globalReturn: true } }
}
],
invalid: [
{
code: "function a() {\nvar b;\nreturn;\n}",
errors: ["Expected newline before return statement."]
},
{
code: "function a() {\nif (b) return b;\nelse if (c) return c;\nelse {\ne();\nreturn d;\n}\n}",
errors: ["Expected newline before return statement."]
},
{
code: "function a() {\n while (b) {\nc();\nreturn;\n}\n}",
errors: ["Expected newline before return statement."]
},
{
code: "function a() {\ndo {\nc();\nreturn;\n} while (b);\n}",
errors: ["Expected newline before return statement."]
},
{
code: "function a() {\nfor (var b; b < c; b++) {\nc();\nreturn;\n}\n}",
errors: ["Expected newline before return statement."]
},
{
code: "function a() {\nfor (b in c) {\nd();\nreturn;\n}\n}",
errors: ["Expected newline before return statement."]
},
{
code: "function a() {\nfor (b of c) {\nd();\nreturn;\n}\n}",
parserOptions: { ecmaVersion: 6 },
errors: ["Expected newline before return statement."]
},
{
code: "function a() {\nif (b) {\nc();\n}\n//comment\nreturn b;\n}",
errors: ["Expected newline before return statement."]
},
{
code: "function a() {\nif (b) {\nc();\n}\n//comment\nreturn b;\n}",
errors: ["Expected newline before return statement."]
},
{
code: "function a() {\n/*comment\ncomment*/\nif (b) {\nc();\nreturn b;\n} else {\n//comment\n\nreturn d;\n}\n/*multi-line\ncomment*/\nreturn e;\n}",
errors: ["Expected newline before return statement.", "Expected newline before return statement."]
},
{
code: "function a() {\nif (b) { return; } //comment\nreturn c;\n}",
errors: ["Expected newline before return statement."]
},
{
code: "function a() {\nif (b) { return; } /*multi-line\ncomment*/\nreturn c;\n}",
errors: ["Expected newline before return statement."]
},
{
code: "function a() {\nif (b) { return; }\n/*multi-line\ncomment*/ return c;\n}",
errors: ["Expected newline before return statement."]
},
{
code: "function a() {\nif (b) { return; } /*multi-line\ncomment*/ return c;\n}",
errors: ["Expected newline before return statement."]
},
{
code: "var a;\nreturn;",
parserOptions: { ecmaFeatures: { globalReturn: true } },
errors: ["Expected newline before return statement."]
},
{
code: "function a() {\n{\n//comment\n}\nreturn\n}",
errors: ["Expected newline before return statement."]
},
{
code: "function a() {\nvar c;\nwhile (b) {\n c = d; //comment\n}\nreturn c;\n}",
errors: ["Expected newline before return statement."]
},
{
code: "function a() {\nfor (var b; b < c; b++) {\nif (d) {\nbreak; //comment\n}\nreturn;\n}\n}",
errors: ["Expected newline before return statement."]
}
]
});
|
/*!
* Connect - HTTPServer
* Copyright(c) 2010 Sencha Inc.
* Copyright(c) 2011 TJ Holowaychuk
* MIT Licensed
*/
/**
* Module dependencies.
*/
var escapeHtml = require('escape-html');
var http = require('http')
, parseurl = require('parseurl')
, debug = require('debug')('connect:dispatcher');
// prototype
var app = module.exports = {};
// environment
var env = process.env.NODE_ENV || 'development';
/**
* Utilize the given middleware `handle` to the given `route`,
* defaulting to _/_. This "route" is the mount-point for the
* middleware, when given a value other than _/_ the middleware
* is only effective when that segment is present in the request's
* pathname.
*
* For example if we were to mount a function at _/admin_, it would
* be invoked on _/admin_, and _/admin/settings_, however it would
* not be invoked for _/_, or _/posts_.
*
* Examples:
*
* var app = connect();
* app.use(connect.favicon());
* app.use(connect.logger());
* app.use(connect.static(__dirname + '/public'));
*
* If we wanted to prefix static files with _/public_, we could
* "mount" the `static()` middleware:
*
* app.use('/public', connect.static(__dirname + '/public'));
*
* This api is chainable, so the following is valid:
*
* connect()
* .use(connect.favicon())
* .use(connect.logger())
* .use(connect.static(__dirname + '/public'))
* .listen(3000);
*
* @param {String|Function|Server} route, callback or server
* @param {Function|Server} callback or server
* @return {Server} for chaining
* @api public
*/
app.use = function(route, fn){
// default route to '/'
if ('string' != typeof route) {
fn = route;
route = '/';
}
// wrap sub-apps
if ('function' == typeof fn.handle) {
var server = fn;
fn.route = route;
fn = function(req, res, next){
server.handle(req, res, next);
};
}
// wrap vanilla http.Servers
if (fn instanceof http.Server) {
fn = fn.listeners('request')[0];
}
// strip trailing slash
if ('/' == route[route.length - 1]) {
route = route.slice(0, -1);
}
// add the middleware
debug('use %s %s', route || '/', fn.name || 'anonymous');
this.stack.push({ route: route, handle: fn });
return this;
};
/**
* Handle server requests, punting them down
* the middleware stack.
*
* @api private
*/
app.handle = function(req, res, out) {
var stack = this.stack
, search = 1 + req.url.indexOf('?')
, pathlength = search ? search - 1 : req.url.length
, fqdn = 1 + req.url.substr(0, pathlength).indexOf('://')
, protohost = fqdn ? req.url.substr(0, req.url.indexOf('/', 2 + fqdn)) : ''
, removed = ''
, slashAdded = false
, index = 0;
function next(err) {
var layer, path, c;
if (slashAdded) {
req.url = req.url.substr(1);
slashAdded = false;
}
req.url = protohost + removed + req.url.substr(protohost.length);
req.originalUrl = req.originalUrl || req.url;
removed = '';
// next callback
layer = stack[index++];
// all done
if (!layer) {
// delegate to parent
if (out) return out(err);
// unhandled error
if (err) {
// default to 500
if (res.statusCode < 400) res.statusCode = 500;
debug('default %s', res.statusCode);
// respect err.status
if (err.status) res.statusCode = err.status;
// production gets a basic error message
var msg = 'production' == env
? http.STATUS_CODES[res.statusCode]
: err.stack || err.toString();
msg = escapeHtml(msg);
// log to stderr in a non-test env
if ('test' != env) console.error(err.stack || err.toString());
if (res.headersSent) return req.socket.destroy();
res.setHeader('Content-Type', 'text/html');
res.setHeader('Content-Length', Buffer.byteLength(msg));
if ('HEAD' == req.method) return res.end();
res.end(msg);
} else if (!res.headersSent) {
debug('default 404');
res.statusCode = 404;
res.setHeader('Content-Type', 'text/html');
if ('HEAD' == req.method) return res.end();
res.end('Cannot ' + escapeHtml(req.method) + ' ' + escapeHtml(req.originalUrl) + '\n');
}
return;
}
try {
path = parseurl(req).pathname;
if (undefined == path) path = '/';
// skip this layer if the route doesn't match.
if (0 != path.toLowerCase().indexOf(layer.route.toLowerCase())) return next(err);
c = path[layer.route.length];
if (c && '/' != c && '.' != c) return next(err);
// Call the layer handler
// Trim off the part of the url that matches the route
removed = layer.route;
req.url = protohost + req.url.substr(protohost.length + removed.length);
// Ensure leading slash
if (!fqdn && '/' != req.url[0]) {
req.url = '/' + req.url;
slashAdded = true;
}
debug('%s %s : %s', layer.handle.name || 'anonymous', layer.route, req.originalUrl);
var arity = layer.handle.length;
if (err) {
if (arity === 4) {
layer.handle(err, req, res, next);
} else {
next(err);
}
} else if (arity < 4) {
layer.handle(req, res, next);
} else {
next();
}
} catch (e) {
next(e);
}
}
next();
};
/**
* Listen for connections.
*
* This method takes the same arguments
* as node's `http.Server#listen()`.
*
* HTTP and HTTPS:
*
* If you run your application both as HTTP
* and HTTPS you may wrap them individually,
* since your Connect "server" is really just
* a JavaScript `Function`.
*
* var connect = require('connect')
* , http = require('http')
* , https = require('https');
*
* var app = connect();
*
* http.createServer(app).listen(80);
* https.createServer(options, app).listen(443);
*
* @return {http.Server}
* @api public
*/
app.listen = function(){
var server = http.createServer(this);
return server.listen.apply(server, arguments);
};
|
console.log('loaded');
|
!function(r){function t(o){if(e[o])return e[o].exports;var n=e[o]={exports:{},id:o,loaded:!1};return r[o].call(n.exports,n,n.exports,t),n.loaded=!0,n.exports}var e={};return t.m=r,t.c=e,t.p="",t(0)}([function(r,t){"use strict"}]); |
module.exports={A:{A:{"2":"E A B iB","8":"K D G"},B:{"2":"2 C d J M H I","8":"AB"},C:{"1":"0 1 2 3 4 6 7 8 9 F N K D G E A B C d J M H I O P Q R S T U V W X Y Z a b c e f g h i j k l m n o L q r s t u v w x y z IB BB CB DB GB","129":"fB FB ZB YB"},D:{"1":"T","8":"0 1 2 3 4 6 7 8 9 F N K D G E A B C d J M H I O P Q R S U V W X Y Z a b c e f g h i j k l m n o L q r s t u v w x y z IB BB CB DB GB SB OB MB lB NB KB AB PB QB"},E:{"1":"5 A B C XB p aB","260":"F N K D G E RB JB TB UB VB WB"},F:{"2":"E","4":"5 B C bB cB dB eB p EB gB","8":"0 1 6 J M H I O P Q R S T U V W X Y Z a b c e f g h i j k l m n o L q r s t u v w x y z"},G:{"1":"G jB kB LB mB nB oB pB qB rB sB tB uB","8":"JB hB HB"},H:{"8":"vB"},I:{"8":"4 FB F wB xB yB zB HB 0B 1B"},J:{"1":"A","8":"D"},K:{"8":"5 A B C L p EB"},L:{"8":"KB"},M:{"1":"3"},N:{"2":"A B"},O:{"4":"2B"},P:{"8":"F 3B 4B 5B 6B 7B"},Q:{"8":"8B"},R:{"8":"9B"},S:{"1":"AC"}},B:2,C:"MathML"};
|
import ServiceManager from './SvcManager'
import EventsEmitter from 'EventsEmitter'
export default class BaseSvc extends EventsEmitter {
/////////////////////////////////////////////////////////////////
//
//
/////////////////////////////////////////////////////////////////
constructor(config = {}) {
super()
this._config = config
}
/////////////////////////////////////////////////////////////////
//
//
/////////////////////////////////////////////////////////////////
name() {
return this._name
}
/////////////////////////////////////////////////////////////////
//
//
/////////////////////////////////////////////////////////////////
config() {
return this._config
}
}
|
//>>built
define("dojox/data/restListener",["dojo","dijit","dojox"],function(f,g,e){f.provide("dojox.data.restListener");e.data.restListener=function(a){var b=a.channel,d=e.rpc.JsonRest,c=d.getServiceAndId(b).service,d=e.json.ref.resolveJson(a.result,{defaultId:"put"==a.event&&b,index:e.rpc.Rest._index,idPrefix:c.servicePath.replace(/[^\/]*$/,""),idAttribute:d.getIdAttribute(c),schemas:d.schemas,loader:d._loader,assignAbsoluteIds:!0}),b=e.rpc.Rest._index&&e.rpc.Rest._index[b];a="on"+a.event.toLowerCase();c=
c&&c._store;if(b&&b[a])b[a](d);else if(c)switch(a){case "onpost":c.onNew(d);break;case "ondelete":c.onDelete(b)}}}); |
const dateformat = require(`dateformat`)
exports.makeBlogPath = ({ id, createdAt, slug }) => {
const date = new Date(createdAt)
const formattedDate = dateformat(date, `yyyy-mm-dd`)
return `/${formattedDate}-${slug}`
}
|
"use strict";
var ts = require("typescript");
var SyntaxWalker = (function () {
function SyntaxWalker() {
}
SyntaxWalker.prototype.walk = function (node) {
this.visitNode(node);
};
SyntaxWalker.prototype.visitAnyKeyword = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitArrayLiteralExpression = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitArrowFunction = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitBinaryExpression = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitBindingElement = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitBindingPattern = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitBlock = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitBreakStatement = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitCallExpression = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitCallSignature = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitCaseClause = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitClassDeclaration = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitClassExpression = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitCatchClause = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitConditionalExpression = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitConstructorDeclaration = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitConstructorType = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitContinueStatement = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitDebuggerStatement = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitDefaultClause = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitDoStatement = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitElementAccessExpression = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitEnumDeclaration = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitExportAssignment = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitExpressionStatement = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitForStatement = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitForInStatement = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitForOfStatement = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitFunctionDeclaration = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitFunctionExpression = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitFunctionType = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitGetAccessor = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitIdentifier = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitIfStatement = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitImportDeclaration = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitImportEqualsDeclaration = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitIndexSignatureDeclaration = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitInterfaceDeclaration = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitJsxElement = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitJsxExpression = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitJsxSelfClosingElement = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitLabeledStatement = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitMethodDeclaration = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitMethodSignature = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitModuleDeclaration = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitNamedImports = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitNamespaceImport = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitNewExpression = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitObjectLiteralExpression = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitParameterDeclaration = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitPostfixUnaryExpression = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitPrefixUnaryExpression = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitPropertyAccessExpression = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitPropertyAssignment = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitPropertyDeclaration = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitPropertySignature = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitRegularExpressionLiteral = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitReturnStatement = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitSetAccessor = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitSourceFile = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitStringLiteral = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitSwitchStatement = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitTemplateExpression = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitThrowStatement = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitTryStatement = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitTypeAssertionExpression = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitTypeLiteral = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitTypeReference = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitVariableDeclaration = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitVariableStatement = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitWhileStatement = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitWithStatement = function (node) {
this.walkChildren(node);
};
SyntaxWalker.prototype.visitNode = function (node) {
switch (node.kind) {
case ts.SyntaxKind.AnyKeyword:
this.visitAnyKeyword(node);
break;
case ts.SyntaxKind.ArrayBindingPattern:
this.visitBindingPattern(node);
break;
case ts.SyntaxKind.ArrayLiteralExpression:
this.visitArrayLiteralExpression(node);
break;
case ts.SyntaxKind.ArrowFunction:
this.visitArrowFunction(node);
break;
case ts.SyntaxKind.BinaryExpression:
this.visitBinaryExpression(node);
break;
case ts.SyntaxKind.BindingElement:
this.visitBindingElement(node);
break;
case ts.SyntaxKind.Block:
this.visitBlock(node);
break;
case ts.SyntaxKind.BreakStatement:
this.visitBreakStatement(node);
break;
case ts.SyntaxKind.CallExpression:
this.visitCallExpression(node);
break;
case ts.SyntaxKind.CallSignature:
this.visitCallSignature(node);
break;
case ts.SyntaxKind.CaseClause:
this.visitCaseClause(node);
break;
case ts.SyntaxKind.ClassDeclaration:
this.visitClassDeclaration(node);
break;
case ts.SyntaxKind.ClassExpression:
this.visitClassExpression(node);
break;
case ts.SyntaxKind.CatchClause:
this.visitCatchClause(node);
break;
case ts.SyntaxKind.ConditionalExpression:
this.visitConditionalExpression(node);
break;
case ts.SyntaxKind.Constructor:
this.visitConstructorDeclaration(node);
break;
case ts.SyntaxKind.ConstructorType:
this.visitConstructorType(node);
break;
case ts.SyntaxKind.ContinueStatement:
this.visitContinueStatement(node);
break;
case ts.SyntaxKind.DebuggerStatement:
this.visitDebuggerStatement(node);
break;
case ts.SyntaxKind.DefaultClause:
this.visitDefaultClause(node);
break;
case ts.SyntaxKind.DoStatement:
this.visitDoStatement(node);
break;
case ts.SyntaxKind.ElementAccessExpression:
this.visitElementAccessExpression(node);
break;
case ts.SyntaxKind.EnumDeclaration:
this.visitEnumDeclaration(node);
break;
case ts.SyntaxKind.ExportAssignment:
this.visitExportAssignment(node);
break;
case ts.SyntaxKind.ExpressionStatement:
this.visitExpressionStatement(node);
break;
case ts.SyntaxKind.ForStatement:
this.visitForStatement(node);
break;
case ts.SyntaxKind.ForInStatement:
this.visitForInStatement(node);
break;
case ts.SyntaxKind.ForOfStatement:
this.visitForOfStatement(node);
break;
case ts.SyntaxKind.FunctionDeclaration:
this.visitFunctionDeclaration(node);
break;
case ts.SyntaxKind.FunctionExpression:
this.visitFunctionExpression(node);
break;
case ts.SyntaxKind.FunctionType:
this.visitFunctionType(node);
break;
case ts.SyntaxKind.GetAccessor:
this.visitGetAccessor(node);
break;
case ts.SyntaxKind.Identifier:
this.visitIdentifier(node);
break;
case ts.SyntaxKind.IfStatement:
this.visitIfStatement(node);
break;
case ts.SyntaxKind.ImportDeclaration:
this.visitImportDeclaration(node);
break;
case ts.SyntaxKind.ImportEqualsDeclaration:
this.visitImportEqualsDeclaration(node);
break;
case ts.SyntaxKind.IndexSignature:
this.visitIndexSignatureDeclaration(node);
break;
case ts.SyntaxKind.InterfaceDeclaration:
this.visitInterfaceDeclaration(node);
break;
case ts.SyntaxKind.JsxElement:
this.visitJsxElement(node);
break;
case ts.SyntaxKind.JsxExpression:
this.visitJsxExpression(node);
break;
case ts.SyntaxKind.JsxSelfClosingElement:
this.visitJsxSelfClosingElement(node);
break;
case ts.SyntaxKind.LabeledStatement:
this.visitLabeledStatement(node);
break;
case ts.SyntaxKind.MethodDeclaration:
this.visitMethodDeclaration(node);
break;
case ts.SyntaxKind.MethodSignature:
this.visitMethodSignature(node);
break;
case ts.SyntaxKind.ModuleDeclaration:
this.visitModuleDeclaration(node);
break;
case ts.SyntaxKind.NamedImports:
this.visitNamedImports(node);
break;
case ts.SyntaxKind.NamespaceImport:
this.visitNamespaceImport(node);
break;
case ts.SyntaxKind.NewExpression:
this.visitNewExpression(node);
break;
case ts.SyntaxKind.ObjectBindingPattern:
this.visitBindingPattern(node);
break;
case ts.SyntaxKind.ObjectLiteralExpression:
this.visitObjectLiteralExpression(node);
break;
case ts.SyntaxKind.Parameter:
this.visitParameterDeclaration(node);
break;
case ts.SyntaxKind.PostfixUnaryExpression:
this.visitPostfixUnaryExpression(node);
break;
case ts.SyntaxKind.PrefixUnaryExpression:
this.visitPrefixUnaryExpression(node);
break;
case ts.SyntaxKind.PropertyAccessExpression:
this.visitPropertyAccessExpression(node);
break;
case ts.SyntaxKind.PropertyAssignment:
this.visitPropertyAssignment(node);
break;
case ts.SyntaxKind.PropertyDeclaration:
this.visitPropertyDeclaration(node);
break;
case ts.SyntaxKind.PropertySignature:
this.visitPropertySignature(node);
break;
case ts.SyntaxKind.RegularExpressionLiteral:
this.visitRegularExpressionLiteral(node);
break;
case ts.SyntaxKind.ReturnStatement:
this.visitReturnStatement(node);
break;
case ts.SyntaxKind.SetAccessor:
this.visitSetAccessor(node);
break;
case ts.SyntaxKind.SourceFile:
this.visitSourceFile(node);
break;
case ts.SyntaxKind.StringLiteral:
this.visitStringLiteral(node);
break;
case ts.SyntaxKind.SwitchStatement:
this.visitSwitchStatement(node);
break;
case ts.SyntaxKind.TemplateExpression:
this.visitTemplateExpression(node);
break;
case ts.SyntaxKind.ThrowStatement:
this.visitThrowStatement(node);
break;
case ts.SyntaxKind.TryStatement:
this.visitTryStatement(node);
break;
case ts.SyntaxKind.TypeAssertionExpression:
this.visitTypeAssertionExpression(node);
break;
case ts.SyntaxKind.TypeLiteral:
this.visitTypeLiteral(node);
break;
case ts.SyntaxKind.TypeReference:
this.visitTypeReference(node);
break;
case ts.SyntaxKind.VariableDeclaration:
this.visitVariableDeclaration(node);
break;
case ts.SyntaxKind.VariableStatement:
this.visitVariableStatement(node);
break;
case ts.SyntaxKind.WhileStatement:
this.visitWhileStatement(node);
break;
case ts.SyntaxKind.WithStatement:
this.visitWithStatement(node);
break;
default:
this.walkChildren(node);
break;
}
};
SyntaxWalker.prototype.walkChildren = function (node) {
var _this = this;
ts.forEachChild(node, function (child) { return _this.visitNode(child); });
};
return SyntaxWalker;
}());
exports.SyntaxWalker = SyntaxWalker;
|
const mongoose = require('mongoose');
const user = require('./user');
user.createUserModel();
const User = mongoose.model('User');
const options = { discriminatorKey: 'kind' };
const StudentSchema = new mongoose.Schema({
firstName: String,
lastName: String,
isAdmin: {
type: Boolean,
default: false,
},
postsApplied: [{ type: mongoose.Schema.Types.ObjectId }],
postsFavourited: [{ type: mongoose.Schema.Types.ObjectId }],
featuredSkills: [{ type: String }],
profile: {
type: mongoose.Schema.Types.Mixed,
default: {
firstName: '',
middleName: '',
lastName: '',
DOB: '',
gender: '',
contactNo: '',
branch: '',
currentYear: '',
Email: '',
degree: '',
cgpa: '',
joiningYear: '',
higherSecondaryMarks: '',
higherSecondaryYear: '',
secondaryMarks: '',
secondaryYear: '',
internships: '',
projects: '',
positionOfResponsibility: '',
workSamples: '',
coCurricularActivities: '',
additinalDetails: '',
},
},
}, options);
module.exports.createStudentModel = () => {
User.discriminator('Student', StudentSchema);
};
|
import { combineReducers } from "redux";
import manufactureReducer from "./app/reducers/manufactureReducer";
import marketReducer from "./app/reducers/marketReducer";
import homeReducer from "./app/reducers/homeReducer";
import itemReducer from "./app/reducers/itemReducer";
import appReducer from "./app/reducers/appReducer";
import donateReducer from "./app/reducers/donateReducer";
import oreReducer from "./app/reducers/oreReducer";
import planetReducer from "./app/reducers/planetReducer";
import moonReducer from "./app/reducers/moonReducer";
import moonSheetReducer from "./app/reducers/moonsheetReducer";
import planetSheetReducer from "./app/reducers/planetsheetReducer";
import gasReducer from "./app/reducers/gasReducer";
export default combineReducers({
appReducer,
manufactureReducer,
marketReducer,
homeReducer,
itemReducer,
donateReducer,
oreReducer,
planetReducer,
moonReducer,
moonSheetReducer,
planetSheetReducer,
gasReducer
});
|
/**
* ag-grid-community - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v20.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
var context_1 = require("../context/context");
var gridOptionsWrapper_1 = require("../gridOptionsWrapper");
var eventService_1 = require("../eventService");
var expressionService_1 = require("../valueService/expressionService");
var animateSlideCellRenderer_1 = require("./cellRenderers/animateSlideCellRenderer");
var animateShowChangeCellRenderer_1 = require("./cellRenderers/animateShowChangeCellRenderer");
var groupCellRenderer_1 = require("./cellRenderers/groupCellRenderer");
var utils_1 = require("../utils");
var CellRendererFactory = /** @class */ (function () {
function CellRendererFactory() {
this.cellRendererMap = {};
}
CellRendererFactory_1 = CellRendererFactory;
CellRendererFactory.prototype.init = function () {
this.cellRendererMap[CellRendererFactory_1.ANIMATE_SLIDE] = animateSlideCellRenderer_1.AnimateSlideCellRenderer;
this.cellRendererMap[CellRendererFactory_1.ANIMATE_SHOW_CHANGE] = animateShowChangeCellRenderer_1.AnimateShowChangeCellRenderer;
this.cellRendererMap[CellRendererFactory_1.GROUP] = groupCellRenderer_1.GroupCellRenderer;
// this.registerRenderersFromGridOptions();
};
// private registerRenderersFromGridOptions(): void {
// let userProvidedCellRenderers = this.gridOptionsWrapper.getCellRenderers();
// _.iterateObject(userProvidedCellRenderers, (key: string, cellRenderer: {new(): ICellRenderer} | ICellRendererFunc)=> {
// this.addCellRenderer(key, cellRenderer);
// });
// }
CellRendererFactory.prototype.addCellRenderer = function (key, cellRenderer) {
this.cellRendererMap[key] = cellRenderer;
};
CellRendererFactory.prototype.getCellRenderer = function (key) {
var result = this.cellRendererMap[key];
if (utils_1._.missing(result)) {
console.warn('ag-Grid: unable to find cellRenderer for key ' + key);
return null;
}
return result;
};
var CellRendererFactory_1;
CellRendererFactory.ANIMATE_SLIDE = 'animateSlide';
CellRendererFactory.ANIMATE_SHOW_CHANGE = 'animateShowChange';
CellRendererFactory.GROUP = 'group';
__decorate([
context_1.Autowired('gridOptionsWrapper'),
__metadata("design:type", gridOptionsWrapper_1.GridOptionsWrapper)
], CellRendererFactory.prototype, "gridOptionsWrapper", void 0);
__decorate([
context_1.Autowired('expressionService'),
__metadata("design:type", expressionService_1.ExpressionService)
], CellRendererFactory.prototype, "expressionService", void 0);
__decorate([
context_1.Autowired('eventService'),
__metadata("design:type", eventService_1.EventService)
], CellRendererFactory.prototype, "eventService", void 0);
__decorate([
context_1.PostConstruct,
__metadata("design:type", Function),
__metadata("design:paramtypes", []),
__metadata("design:returntype", void 0)
], CellRendererFactory.prototype, "init", null);
CellRendererFactory = CellRendererFactory_1 = __decorate([
context_1.Bean('cellRendererFactory')
], CellRendererFactory);
return CellRendererFactory;
}());
exports.CellRendererFactory = CellRendererFactory;
|
/**
* ag-grid-community - Advanced Data Grid / Data Table supporting Javascript / React / AngularJS / Web Components
* @version v21.1.0
* @link http://www.ag-grid.com/
* @license MIT
*/
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var __param = (this && this.__param) || function (paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
};
Object.defineProperty(exports, "__esModule", { value: true });
var logger_1 = require("../logger");
var context_1 = require("../context/context");
var context_2 = require("../context/context");
var ExpressionService = /** @class */ (function () {
function ExpressionService() {
this.expressionToFunctionCache = {};
}
ExpressionService.prototype.setBeans = function (loggerFactory) {
this.logger = loggerFactory.create('ExpressionService');
};
ExpressionService.prototype.evaluate = function (expressionOrFunc, params) {
if (typeof expressionOrFunc === 'function') {
// valueGetter is a function, so just call it
var func = expressionOrFunc;
return func(params);
}
else if (typeof expressionOrFunc === 'string') {
// valueGetter is an expression, so execute the expression
var expression = expressionOrFunc;
return this.evaluateExpression(expression, params);
}
else {
console.error('ag-Grid: value should be either a string or a function', expressionOrFunc);
}
};
ExpressionService.prototype.evaluateExpression = function (expression, params) {
try {
var javaScriptFunction = this.createExpressionFunction(expression);
// the params don't have all these values, rather we add every possible
// value a params can have, which makes whatever is in the params available.
var result = javaScriptFunction(params.value, params.context, params.oldValue, params.newValue, params.value, params.node, params.data, params.colDef, params.rowIndex, params.api, params.columnApi, params.getValue, params.column, params.columnGroup);
return result;
}
catch (e) {
// the expression failed, which can happen, as it's the client that
// provides the expression. so print a nice message
// tslint:disable-next-line
console.log('Processing of the expression failed');
// tslint:disable-next-line
console.log('Expression = ' + expression);
// tslint:disable-next-line
console.log('Exception = ' + e);
return null;
}
};
ExpressionService.prototype.createExpressionFunction = function (expression) {
// check cache first
if (this.expressionToFunctionCache[expression]) {
return this.expressionToFunctionCache[expression];
}
// if not found in cache, return the function
var functionBody = this.createFunctionBody(expression);
var theFunction = new Function('x, ctx, oldValue, newValue, value, node, data, colDef, rowIndex, api, columnApi, getValue, column, columnGroup', functionBody);
// store in cache
this.expressionToFunctionCache[expression] = theFunction;
return theFunction;
};
ExpressionService.prototype.createFunctionBody = function (expression) {
// if the expression has the 'return' word in it, then use as is,
// if not, then wrap it with return and ';' to make a function
if (expression.indexOf('return') >= 0) {
return expression;
}
else {
return 'return ' + expression + ';';
}
};
__decorate([
__param(0, context_2.Qualifier('loggerFactory')),
__metadata("design:type", Function),
__metadata("design:paramtypes", [logger_1.LoggerFactory]),
__metadata("design:returntype", void 0)
], ExpressionService.prototype, "setBeans", null);
ExpressionService = __decorate([
context_1.Bean('expressionService')
], ExpressionService);
return ExpressionService;
}());
exports.ExpressionService = ExpressionService;
|
(function () {
'use strict';
angular.module('events')
.controller('EventsPhotoGalleryCtrl', function ($scope) {
var eventsPhotoGallery = this;
});
})();
|
;(function(){
'use strict';
var _ = require('lodash');
var path = require('path');
var Config = module.exports;
Config.initialize = initialize;
// Config.base = base;
// Config.options = options;
/**
* initialize Main application configuration
* set default config store values.
* The initialize function will be invoked for you.
* Everything else from the file must be invoke yourself.
* @param {Object} answers Answers from initail prompting.
* @return {Object} return Storage for usage later;
*/
function initialize (stream) {
var _this = this;
var storage = this.storage.get();
// var moduleName = stream.answers.module || _this.flags.module;
storage.moduleNames = _this.str().multi(stream.answers.moduleName);
storage.names = _this.str().multi(_this.title);
_this.modulePath = path.join( _this.dirs.modules, storage.moduleNames.slug );
_.assign( storage, _this.flags );
stream.filters = storage;
return stream;
}
/**
* [generators description]
* @return {[type]} [description]
*/
function base (stream) { return stream; }
/**
* [subGenerators description]
* @return {[type]} [description]
*/
function options (stream) {return stream; }
}).call(this);
|
"use strict";
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.TriStateCheckbox = void 0;
var _react = _interopRequireWildcard(require("react"));
var _propTypes = _interopRequireDefault(require("prop-types"));
var _ClassNames = require("../utils/ClassNames");
var _Tooltip = require("../tooltip/Tooltip");
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
var TriStateCheckbox = /*#__PURE__*/function (_Component) {
_inherits(TriStateCheckbox, _Component);
var _super = _createSuper(TriStateCheckbox);
function TriStateCheckbox(props) {
var _this;
_classCallCheck(this, TriStateCheckbox);
_this = _super.call(this, props);
_this.state = {
focused: false
};
_this.onClick = _this.onClick.bind(_assertThisInitialized(_this));
_this.onFocus = _this.onFocus.bind(_assertThisInitialized(_this));
_this.onBlur = _this.onBlur.bind(_assertThisInitialized(_this));
return _this;
}
_createClass(TriStateCheckbox, [{
key: "onClick",
value: function onClick(event) {
if (!this.props.disabled) {
this.toggle(event);
this.inputEL.focus();
}
}
}, {
key: "toggle",
value: function toggle(event) {
var newValue;
if (this.props.value === null || this.props.value === undefined) newValue = true;else if (this.props.value === true) newValue = false;else if (this.props.value === false) newValue = null;
if (this.props.onChange) {
this.props.onChange({
originalEvent: event,
value: newValue,
stopPropagation: function stopPropagation() {},
preventDefault: function preventDefault() {},
target: {
name: this.props.name,
id: this.props.id,
value: newValue
}
});
}
}
}, {
key: "onFocus",
value: function onFocus() {
this.setState({
focused: true
});
}
}, {
key: "onBlur",
value: function onBlur() {
this.setState({
focused: false
});
}
}, {
key: "componentDidMount",
value: function componentDidMount() {
if (this.props.tooltip && !this.props.disabled) {
this.renderTooltip();
}
}
}, {
key: "componentDidUpdate",
value: function componentDidUpdate(prevProps) {
if (prevProps.tooltip !== this.props.tooltip) {
if (this.tooltip) this.tooltip.updateContent(this.props.tooltip);else this.renderTooltip();
}
}
}, {
key: "componentWillUnmount",
value: function componentWillUnmount() {
if (this.tooltip) {
this.tooltip.destroy();
this.tooltip = null;
}
}
}, {
key: "renderTooltip",
value: function renderTooltip() {
this.tooltip = (0, _Tooltip.tip)({
target: this.element,
content: this.props.tooltip,
options: this.props.tooltipOptions
});
}
}, {
key: "render",
value: function render() {
var _this2 = this;
var containerClass = (0, _ClassNames.classNames)('p-tristatecheckbox p-checkbox p-component', this.props.className);
var boxClass = (0, _ClassNames.classNames)('p-checkbox-box', {
'p-highlight': (this.props.value || !this.props.value) && this.props.value !== null,
'p-disabled': this.props.disabled,
'p-focus': this.state.focused
});
var iconClass = (0, _ClassNames.classNames)('p-checkbox-icon p-c', {
'pi pi-check': this.props.value === true,
'pi pi-times': this.props.value === false
});
return /*#__PURE__*/_react.default.createElement("div", {
ref: function ref(el) {
return _this2.element = el;
},
id: this.props.id,
className: containerClass,
style: this.props.style,
onClick: this.onClick
}, /*#__PURE__*/_react.default.createElement("div", {
className: "p-hidden-accessible"
}, /*#__PURE__*/_react.default.createElement("input", {
ref: function ref(el) {
return _this2.inputEL = el;
},
type: "checkbox",
"aria-labelledby": this.props.ariaLabelledBy,
id: this.props.inputId,
name: this.props.name,
onFocus: this.onFocus,
onBlur: this.onBlur,
disabled: this.props.disabled
})), /*#__PURE__*/_react.default.createElement("div", {
className: boxClass,
ref: function ref(el) {
return _this2.box = el;
},
role: "checkbox",
"aria-checked": this.props.value === true
}, /*#__PURE__*/_react.default.createElement("span", {
className: iconClass
})));
}
}]);
return TriStateCheckbox;
}(_react.Component);
exports.TriStateCheckbox = TriStateCheckbox;
_defineProperty(TriStateCheckbox, "defaultProps", {
id: null,
inputId: null,
value: null,
name: null,
style: null,
className: null,
disabled: false,
tooltip: null,
tooltipOptions: null,
ariaLabelledBy: null,
onChange: null
});
_defineProperty(TriStateCheckbox, "propTypes", {
id: _propTypes.default.string,
inputId: _propTypes.default.string,
value: _propTypes.default.bool,
name: _propTypes.default.string,
style: _propTypes.default.object,
className: _propTypes.default.string,
disabled: _propTypes.default.bool,
tooltip: _propTypes.default.string,
tooltipOptions: _propTypes.default.object,
ariaLabelledBy: _propTypes.default.string,
onChange: _propTypes.default.func
}); |
/**
* Description:
* removes white space from text. useful for html values that cannot have spaces
* Usage:
* {{some_text | nospace}}
*/
app.filter('nospace', function () {
return function (value) {
return (!value) ? '' : value.replace(/ /g, '');
};
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.