code stringlengths 2 1.05M |
|---|
import httpProxy from 'http-proxy';
export default function(options) {
const PathRewrite = function(rewriteRules, path) {
for(var regex in rewriteRules) {
var value = rewriteRules[regex];
path = path.replace(regex, value)
}
return path;
}
const proxy = httpProxy.createProxyServer({});
// 捕获异常
proxy.on('error', (err, req, res) => {
res.writeHead(500, {
'Content-Type': 'text/plain',
});
res.end('Something went wrong. And we are reporting a custom error message.');
});
proxy.on('proxyReq', function(proxyReq, req, res) {
if(options.pathRewrite) {
proxyReq.path = PathRewrite(options.pathRewrite, proxyReq.path);
}
if(options.proxyReq && typeof options.proxyReq === 'function') {
options.proxyReq(proxyReq, req, res);
}
});
return function(req, res, next) {
try {
proxy.web(req, res, options);
} catch (error) {
next();
}
}
} |
export function randomInt (min, max) {
return Math.floor(min + Math.random() * (max - min + 1))
}
|
$(function() {
var editor = editormd("editormd", {
path: "/plugins/editor-md/lib/",
height: 500,
emoji: true,
onfullscreen : function() {
$("#editormd").css('margin-top', '46px').css('z-index', '3');
}
});
$("button[type=submit]").click(function () {
var markdown = editor.getMarkdown();
var html = editor.getPreviewedHTML();
$.post('/admin/sp/edit', {
id: $('input[name=id]').val(),
markdown: markdown,
html: html
}, function (result) {
if (result.code !== 1) {
toastr['error'](result.message);
}
})
});
}); |
/**
* olojs.document
* ============================================================================
* This module contains functions to parse, evaluate and render any string of
* text formatted as olo-document.
*
* ```js
* source = "Twice x is <% 2*x %>!";
* context = olojs.document.createContext({x:10});
* evaluate = olojs.document.parse(source);
* namespace = await evaluate(context); // {x:10}
* text = await context.str(namespace); // "Twice x is 20"
* ```
*/
const swan = require('./expression');
/**
* olojs.document.parse - function
* ----------------------------------------------------------------------------
* Compiles a document source into an `evaluate` function that takes as input
* a document context object and returns the document namespace object.
*
* ```js
* evaluate = olojs.document.parse(source);
* namespace = await evaluate(context);
* ```
*
* - `source` is a string containing olo-document markup
* - `evaluate` is an asynchronous function that evaluates the document and
* returns its namespace
* - `namespace` is an object containing all the names defined by the inline
* expressions of the document.
*
* The document namespace stringifies to a text obtained by replacing every
* inline expression with its value, therefore in javascript
* `await context.str(namespace)` will return the rendered document.
*/
exports.parse = function (source) {
source = String(source);
// Find all the swan expressions in the source, store them in an array and
// replace them with a placeholder.
const parsedExpressions = [];
source = source.replace(/<%([\s\S]+?)%>/g, (match, expressionSource) => {
let i = parsedExpressions.length;
let parsedExpression;
try {
parsedExpression = swan.parse(expressionSource);
} catch (error) {
parsedExpression = context => {throw error};
}
parsedExpression.source = expressionSource;
parsedExpressions.push( parsedExpression );
return `<%%>`;
});
const textChunks = source.split('<%%>');
const $text = Symbol("Rendered document");
// The returned `evaluate` function
return async (context) => {
context = Object.assign(Object.create(Object.getPrototypeOf(context)), context);
var text = textChunks[0] || "";
// Make the namespace sringify to the rendered text
context.__str__ = async ns => ns.__render__ ? await swan.O.apply(ns.__render__, text) : text;
// Evaluate each expression in the given context and replace the
// expression source with the stringified expression value
for (let i=0; i<parsedExpressions.length; i++) {
let evaluateExpression = parsedExpressions[i];
try {
var value = await evaluateExpression(context);
} catch (error) {
// Delegate error rendering to the custom `context.$renderError` function
var value = context.$renderError(error);
}
text += await context.str(value) + textChunks[i+1];
}
// Extract the document namespace,
// discarding the global context variables.
return Object.assign({}, context);
};
}
/**
* olojs.document.createContext - function
* ----------------------------------------------------------------------------
* Creates a custom document evaluation context, by adding to the basic
* context all the names defined in the passed namespace.
*
* ```js
* context = olojs.document.createContext(...namespaces)
* ```
* - `namespaces`: list of objects; each of them, from left to right, will be
* mixed-in to the basic document context
* - `context`: an object containing all the named values and function that
* will be visible to the document inline expressions.
*/
exports.createContext = function (...namespaces) {
return swan.createContext(documentGlobals, ...namespaces);
}
const documentGlobals = {
$renderError: error => `Error: ${error.message}\n\n${error.swanStack}`,
};
|
module.exports = function home(app, models){
app.get('/', function(req, res){
if(req.isAuthenticated()){
res.render('home/index');
}else{
res.redirect('/auth/login');
}
});
}; |
define(["require", "exports", 'durandal/system', 'knockout'], function(require, exports, system, ko) {
var Third = (function () {
function Third() {
var _this = this;
this.title = 'Third Tab';
this.thirdVm = ko.observable(null);
this.activate = function (id) {
system.log('Third Tab Activated');
return _this.loadObservables(id);
};
this.deactivate = function () {
system.log('Third Tab Deactivated');
};
this.loadObservables = function (id) {
return _this.thirdVm({ id: id, name: 'Third Tab Content' });
};
}
return Third;
})();
return Third;
});
//# sourceMappingURL=third.js.map
|
/**
* Unset project variables in configs/configuration.json
*/
module.exports = function vDelCommand (program, helpers) {
program
.command('vdel <variable>')
.description('Unset / delete one variable from configs/configuration.json')
.action( function run (variable) {
const we = helpers.getWe();
we.unSetConfig(variable, (err)=> {
if (err) throw err;
});
});
}; |
var itemtypenames
if (itemtypenames == undefined) itemtypenames = [ "Small Caliber Main Gun",
"Medium Caliber Main Gun",
"Large Caliber Main Gun",
"Secondary Gun",
"Anti-Aircraft Gun",
"Anti-Aircraft Shell",
"Armor Piercing Shell",
"Torpedos & Submarine",
"Carrier-Based Fighter",
"Carrier-Based Torpedo Bomber",
"Carrier-Based Dive Bomber",
"Carrier-Based Reconn",
"Seaplane",
"Radar",
"Anti-submarine Warfare",
"Engine",
"Extra Armor",
"Land-Based Attack Aircraft",
"Supply Transport Container" ]
// Id, Name, Rarity, Internal Rarity, Type, Break Materials[, is AA]
var items = [
[1, "12cm単装砲", 1, 0, 0, [0, 1, 1, 0]],
[2, "12.7cm連装砲", 1, 0, 0, [0, 1, 2, 0]],
[3, "10cm連装高角砲", 2, 1, 0, [0, 1, 3, 0], true],
[4, "14cm単装砲", 1, 0, 1, [0, 2, 1, 0]],
[5, "15.5cm三連装砲", 2, 0, 1, [0, 2, 5, 0]],
[6, "20.3cm連装砲", 2, 0, 1, [0, 3, 4, 0]],
[65, "15.2cm連装砲", 2, 2, 1, [0, 2, 3, 0]],
[7, "35.6cm連装砲", 1, 0, 2, [0, 10, 15, 0]],
[8, "41cm連装砲", 2, 1, 2, [0, 12, 20, 0]],
[9, "46cm三連装砲", 3, 2, 2, [0, 24, 25, 0]],
[10, "12.7cm連装高角砲", 1, 0, 3, [0, 2, 2, 0], true],
[11, "15.2cm単装砲", 1, 0, 3, [0, 2, 2, 0]],
[12, "15.5cm三連装副砲", 2, 1, 3, [0, 2, 5, 0]],
[66, "8cm高角砲", 3, 3, 3, [0, 1, 2, 0], true],
[37, "7.7mm機銃", 1, 0, 4, [0, 1, 1, 0]],
[38, "12.7mm単装機銃", 1, 0, 4, [0, 1, 1, 0]],
[39, "25mm連装機銃", 2, 0, 4, [0, 2, 1, 0]],
[40, "25mm三連装機銃", 2, 1, 4, [0, 3, 1, 0]],
[49, "25mm単装機銃", 2, 1, 4, [0, 1, 1, 0]],
[35, "三式弾", 2, 0, 5, [0, 9, 6, 3]],
[36, "九一式徹甲弾", 3, 1, 6, [0, 3, 9, 0]],
[13, "61cm三連装魚雷", 1, 0, 7, [1, 1, 1, 0]],
[14, "61cm四連装魚雷", 1, 0, 7, [1, 2, 2, 0]],
[15, "61cm四連装(酸素)魚雷", 2, 1, 7, [2, 2, 2, 0]],
[41, "甲標的", 1, 1, 7, [0, 7, 7, 0]],
[19, "九六式艦戦", 1, 0, 8, [1, 1, 0, 1]],
[20, "零式艦戦21型", 1, 0, 8, [1, 1, 0, 2]],
[21, "零式艦戦52型", 2, 1, 8, [1, 2, 0, 3]],
[22, "試製烈風 後期型", 3, 3, 8, [2, 2, 0, 9]],
[55, "紫電改二", 3, 2, 8, [2, 2, 0, 7]],
[181, "零式艦戦32型", 2, 3, 8, [1, 2, 0, 2]],
[16, "九七式艦攻", 1, 0, 9, [1, 1, 0, 2]],
[17, "天山", 2, 1, 9, [2, 4, 0, 4]],
[18, "流星", 3, 2, 9, [2, 5, 0, 10]],
[52, "流星改", 3, 3, 9, [2, 6, 0, 10]],
[23, "九九式艦爆", 1, 0, 10, [1, 1, 0, 2]],
[24, "彗星", 2, 1, 10, [2, 3, 0, 3]],
[57, "彗星一二型甲", 3, 2, 10, [2, 3, 0, 4]],
[60, "零式艦戦62型(爆戦)", 3, 2, 10, [1, 3, 0, 3]],
[54, "彩雲", 3, 2, 11, [2, 0, 0, 11]],
[61, "二式艦上偵察機", 2, 1, 11, [3, 1, 0, 13]],
[25, "零式水上偵察機", 1, 1, 12, [1, 1, 0, 2]],
[26, "瑞雲", 2, 1, 12, [2, 3, 0, 5]],
[59, "零式水上観測機", 2, 1, 12, [1, 1, 0, 2]],
[163, "Ro.43水偵", 3, 3, 12, [1, 1, 0, 2]],
[27, "13号対空電探", 2, 1, 13, [0, 0, 10, 10]],
[28, "22号対水上電探", 2, 1, 13, [0, 0, 15, 15]],
[29, "33号対水上電探", 3, 2, 13, [0, 0, 20, 15]],
[30, "21号対空電探", 2, 2, 13, [0, 0, 20, 20]],
[31, "32号対水上電探", 3, 3, 13, [0, 0, 20, 25]],
[32, "42号対空電探", 3, 4, 13, [0, 0, 25, 25]],
[44, "九四式爆雷投射機", 1, 0, 14, [0, 2, 1, 1]],
[45, "三式爆雷投射機", 3, 2, 14, [0, 3, 1, 1]],
[46, "九三式水中聴音機", 1, 0, 14, [0, 0, 1, 1]],
[47, "三式水中探信儀", 3, 2, 14, [0, 0, 1, 2]],
[33, "改良型艦本式タービン", 1, 0, 15, [10, 0, 10, 0]],
[34, "強化型艦本式缶", 2, 1, 15, [10, 0, 20, 0]],
[72, "増設バルジ(中型艦)", 2, 2, 16, [0, 0, 12, 0]],
[73, "増設バルジ(大型艦)", 2, 2, 16, [0, 0, 30, 0]],
[168, "九六式陸攻", 1, 1, 17, [7, 4, 0, 12]],
[75, "ドラム缶(輸送用)", 1, 0, 18, [0, 0, 1, 0]]
]
var materialNames = ["Fuel", "Ammunition", "Steel", "Bauxite"]
function developResult(id, percentage, materials, hqlevel) {
this.id = id
this.percentage = percentage
this.successful = true
for (var i = 0; i < 4; ++i) {
if (items[id][5][i] * 10 > materials[i]) {
this.successful = false
break
}
}
if (items[id][3] * 10 > hqlevel) this.successful = false
this.toTRNode = function() {
var node = document.createElement("tr")
if (this.successful) node.className = "success"
else {
node.className = "fail"
var title = "Require"
for (var i = 0; i < 4; ++i) {
if (items[id][5][i] * 10 > materials[i]) {
title += "\n" + getString(materialNames[i]) + " ≥ " + (items[id][5][i] * 10)
}
}
if (items[id][3] * 10 > hqlevel) {
title += "\n" + getString("HQ Level") + " ≥ " + (items[id][3] * 10)
}
node.title = getString(title)
}
var tdnode = document.createElement("td")
tdnode.className = "type" + (items[id][6] ? 4 : items[id][4])
tdnode.appendChild(document.createTextNode(items[id][1]))
node.appendChild(tdnode)
tdnode = document.createElement("td")
tdnode.appendChild(document.createTextNode(percentage + "%"))
node.appendChild(tdnode)
return node
}
} |
const { Model } = require('../../../');
const { expect } = require('chai');
module.exports = (session) => {
describe(`relations should be loaded lazily #1202`, () => {
let knex = session.knex;
let Person;
let loadedRelations = [];
before(() => {
return knex.schema
.dropTableIfExists('cousins')
.dropTableIfExists('persons')
.createTable('persons', (table) => {
table.increments('id').primary();
table.integer('parentId');
table.string('name');
})
.createTable('cousins', (table) => {
table.integer('id1');
table.integer('id2');
});
});
after(() => {
return knex.schema.dropTableIfExists('cousins').dropTableIfExists('persons');
});
beforeEach(() => {
loadedRelations = [];
Person = class Person extends Model {
static get tableName() {
return 'persons';
}
static get relationMappings() {
return {
parent: {
relation: Model.BelongsToOneRelation,
modelClass() {
loadedRelations.push('parent');
return Person;
},
join: {
from: 'persons.parentId',
to: 'persons.id',
},
},
cousins: {
relation: Model.ManyToManyRelation,
modelClass() {
loadedRelations.push('cousins');
return Person;
},
join: {
from: 'persons.id',
through: {
from: 'cousins.id1',
to: 'cousins.id2',
},
to: 'persons.id',
},
},
};
}
};
Person.knex(knex);
});
beforeEach(() => Person.query().delete());
beforeEach(() => {
// This is what you get when you cannot use insertGraph.
return session
.knex('persons')
.insert({ name: 'Meinhart ' })
.returning('id')
.then(([id]) => {
return session.knex('persons').insert({ name: 'Arnold', parentId: id }).returning('id');
})
.then(([arnoldId]) => {
return Promise.all([
session.knex('persons').insert({ name: 'Hans' }).returning('id'),
session.knex('persons').insert({ name: 'Urs' }).returning('id'),
]).then(([[hansId], [ursId]]) => {
return Promise.all([
session.knex('cousins').insert({ id1: arnoldId, id2: hansId }),
session.knex('cousins').insert({ id1: arnoldId, id2: ursId }),
]);
});
});
});
it('inserting a model should not load relations', () => {
return Person.query()
.insert({ name: 'Arnold' })
.then(() => {
expect(loadedRelations).to.have.length(0);
});
});
it('updating a model should not load relations', () => {
return Person.query()
.patch({ name: 'Arnold' })
.findById(1)
.then(() => {
expect(loadedRelations).to.have.length(0);
});
});
it('finding a model should not load relations', () => {
return Person.query()
.findOne({ name: 'Arnold' })
.then((result) => {
expect(result).to.containSubset({ name: 'Arnold' });
expect(loadedRelations).to.have.length(0);
});
});
it('toJSON a model should not load relations', () => {
return Person.query()
.findOne({ name: 'Arnold' })
.then((result) => {
result.toJSON();
result.$toDatabaseJson();
expect(loadedRelations).to.have.length(0);
});
});
it('eager should only load relations in the expression', () => {
return Person.query()
.withGraphFetched('parent')
.then(() => {
expect(loadedRelations).to.eql(['parent']);
return Person.query().withGraphFetched('cousins');
})
.then(() => {
expect(loadedRelations).to.eql(['parent', 'cousins']);
});
});
it('joinEager should only load relations in the expression', () => {
return Person.query()
.withGraphJoined('parent')
.then(() => {
expect(loadedRelations).to.eql(['parent']);
return Person.query().withGraphJoined('cousins');
})
.then(() => {
expect(loadedRelations).to.eql(['parent', 'cousins']);
});
});
it('$relatedQuery should only load the queried relation', () => {
return Person.query()
.findOne({ name: 'Arnold' })
.then((arnold) => {
return arnold.$relatedQuery('cousins');
})
.then(() => {
expect(loadedRelations).to.eql(['cousins']);
});
});
it('insertGraph should only load relations in the graph', () => {
return Person.query()
.insertGraph({
name: 'Sami',
parent: {
name: 'Liisa',
},
})
.then(() => {
expect(loadedRelations).to.eql(['parent']);
});
});
it('fromJson should only load relations that are present in the object', () => {
Person.fromJson({
name: 'Ardnold',
cousins: [
{
name: 'Hans',
},
],
});
expect(loadedRelations).to.eql(['cousins']);
});
});
};
|
/**
* Created by Jos�Pablo on 10/28/2015.
*/
angular.module('MetronicApp').controller('HomeCtrl',['$scope',function($scope){
$scope.usuario = "Hola";
}]); |
import TabInterface from './tab.interface';
/**
* Tab class.
*
* @ngInject
*/
export default class Tab implements TabInterface {
/**
* Constructor of the class
*
* @param {TabInterface} item
*/
constructor(item: Object) {
this.label = item.label;
this.state = item.state;
}
}
|
"use strict";
// I don't think that this is used anywhere yet!
class FieldFormat {
constructor(engine, data={}) {
this.engine = engine;
this.data = data;
['id'].map(key => this[key] = data[key] ? data[key] : this.constructor[key]);
}
}
FieldFormat.id = '';
module.exports = FieldFormat;
|
'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _base = require('./base');
var _base2 = _interopRequireDefault(_base);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function FeatureUnavailableError(message, debug, code, kinveyRequestId) {
this.name = 'FeatureUnavailableError';
this.message = message || 'Requested functionality is unavailable in this API version.';
this.debug = debug || undefined;
this.code = code || undefined;
this.kinveyRequestId = kinveyRequestId || undefined;
this.stack = new Error().stack;
}
FeatureUnavailableError.prototype = Object.create(_base2.default.prototype);
FeatureUnavailableError.prototype.constructor = FeatureUnavailableError;
exports.default = FeatureUnavailableError; |
define([
'jidejs/ui/layout/BorderPane', './issueList', './details', './TemplateView',
'jidejs/ui/control/MenuBar', 'jidejs/ui/control/MenuItem', 'jidejs/ui/control/Hyperlink',
'jidejs/base/Observable', 'jidejs/base/Window'
], function(BorderPane, issueList, details, TemplateView, MenuBar, MenuItem, Hyperlink, Observable, Window) {
"use strict";
// Create the about view
var aboutView = BorderPane.margin(BorderPane.region(new TemplateView({
template: 'about-view-tpl'
}), 'center'), '0');
// and join issueList to details view for easier usage
var appPage = new BorderPane({
children: [
BorderPane.margin(BorderPane.region(issueList, 'left'), '0'),
BorderPane.margin(BorderPane.region(details, 'center'), '0 10px')
]
});
// this observable stores the currently active page
var activePage = Observable(appPage);
// automatically replace the displayed page
activePage.subscribe(function(event) {
if(event.oldValue) {
appLayout.children.remove(event.oldValue);
}
appLayout.children.add(event.value);
});
// this observable stores the currently active menu item
var activeMenu = Observable();
// automatically add/remove the "active" css class
activeMenu.subscribe(function(event) {
if(event.oldValue) event.oldValue.classList.remove('active');
event.value.classList.add('active');
});
// make sure the aboutView knows it should be placed at the "center" slot
BorderPane.region(aboutView, 'center');
// a simple function that returns a function that updates the active page and menu.
function selectPage(page) {
return function() {
activePage.set(page);
activeMenu.set(this);
};
}
// this is the menu displayed at the top of the page
var menu = new MenuBar({
'BorderPane.margin': '0',
classList: ['navbar-fixed-top'],
children: [
// display our brand using Bootstrap display
new Hyperlink({
classList: ['brand'],
href: 'http://js.jidesoft.com',
text: 'jide.js',
style: {
'margin-left': '-10px'
}
}),
new MenuItem({
text: 'Issues',
on: {
click: selectPage(appPage)
}
}),
new MenuItem({
text: 'About',
on: {
click: selectPage(aboutView)
}
})
]
});
// activate the "Issues" page
activeMenu.set(menu.children.get(1));
var footer;
// create the app layout
var appLayout = new BorderPane({
width: '100%',
// height: Window.heightProperty,
children: [
BorderPane.margin(BorderPane.region(menu, 'top'), '0'),
BorderPane.margin(BorderPane.region(appPage, 'center'), '0'),
footer = BorderPane.region(new TemplateView({
classList: ['inverse'],
'BorderPane.margin': '0',
template: 'app-bottom-bar-tpl'
}), 'bottom')
]
});
return appLayout;
}); |
function Base64() {
// private property
var _keyStr = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
// public method for encoding
this.encode = function (input) {
var output = '';
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = _utf8_encode(input);
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output += _keyStr.charAt(enc1) + _keyStr.charAt(enc2) + _keyStr.charAt(enc3) + _keyStr.charAt(enc4);
}
return output;
}
// public method for decoding
this.decode = function (input) {
var output = '';
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, '');
while (i < input.length) {
enc1 = _keyStr.indexOf(input.charAt(i++));
enc2 = _keyStr.indexOf(input.charAt(i++));
enc3 = _keyStr.indexOf(input.charAt(i++));
enc4 = _keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output += String.fromCharCode(chr1);
if (enc3 !== 64) {
output += String.fromCharCode(chr2);
}
if (enc4 !== 64) {
output += String.fromCharCode(chr3);
}
}
output = _utf8_decode(output);
return output;
}
// private method for UTF-8 encoding
var _utf8_encode = function (str) {
str = str.replace(/\r\n/g,'\n');
var utftext = '';
for (var n = 0; n < str.length; n++) {
var c = str.charCodeAt(n);
if (c < 128) {
utftext += String.fromCharCode(c);
} else if((c > 127) && (c < 2048)) {
utftext += String.fromCharCode((c >> 6) | 192);
utftext += String.fromCharCode((c & 63) | 128);
} else {
utftext += String.fromCharCode((c >> 12) | 224);
utftext += String.fromCharCode(((c >> 6) & 63) | 128);
utftext += String.fromCharCode((c & 63) | 128);
}
}
return utftext;
}
// private method for UTF-8 decoding
var _utf8_decode = function (utftext) {
var str = '';
var i = 0;
var c = c1 = c2 = 0;
while ( i < utftext.length ) {
c = utftext.charCodeAt(i);
if (c < 128) {
str += String.fromCharCode(c);
i++;
} else if((c > 191) && (c < 224)) {
c2 = utftext.charCodeAt(i+1);
str += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
i += 2;
} else {
c2 = utftext.charCodeAt(i+1);
c3 = utftext.charCodeAt(i+2);
str += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
i += 3;
}
}
return str;
}
}
|
var assert = require('power-assert');
var isEmpty = require('../src/index').isEmpty;
describe('isEmpty', function() {
it('empty value', function() {
assert(isEmpty('') === true);
assert(isEmpty([]) === true);
assert(isEmpty(null) === true);
assert(isEmpty(void(0)) === true);
assert(isEmpty({}) === true);
(function() {
assert(isEmpty(arguments) === true);
})();
});
it('not empty value', function() {
assert(isEmpty('a') === false);
assert(isEmpty([0]) === false);
assert(isEmpty({foo:''}) === false);
(function() {
assert(isEmpty(arguments) === false);
})('');
});
});
|
"use strict";
var _this = this;
var _1 = require("../../../");
describe("SortingAccessor", function () {
beforeEach(function () {
_this.options = {
options: [
{ label: "None" },
{
label: "Highest Price",
field: 'price',
order: 'desc'
},
{
label: "Lowest Price",
field: 'price',
key: "cheap"
},
{
label: "Highly rated",
key: "rated",
fields: [
{ field: "rating", options: { order: "asc" } },
{ field: "price", options: { order: "desc", customKey: "custom" } }
]
},
{
label: "Cheapest",
key: "cheapest",
fields: [
{ field: "price", options: { order: 'desc' } },
{ field: "rated" }
]
}
]
};
_this.accessor = new _1.SortingAccessor("sort", _this.options);
});
it("constructor()", function () {
expect(_this.accessor.key).toBe("sort");
expect(_this.accessor.options).toBe(_this.options);
expect(_this.options.options).toEqual([
{ label: 'None', key: 'none' },
{ label: 'Highest Price', field: 'price', order: 'desc', key: 'price_desc' },
{ label: 'Lowest Price', field: 'price', key: 'cheap' },
{
label: "Highly rated",
key: "rated",
fields: [
{ field: "rating", options: { order: "asc" } },
{ field: "price", options: { order: "desc", customKey: "custom" } }
]
},
{
label: "Cheapest",
key: "cheapest",
fields: [
{ field: "price", options: { order: 'desc' } },
{ field: "rated" }
]
}
]);
});
it("buildOwnQuery()", function () {
_this.accessor.state = new _1.ValueState("cheap");
var query = new _1.ImmutableQuery();
var priceQuery = _this.accessor.buildOwnQuery(query);
expect(priceQuery.query.sort).toEqual(['price']);
_this.accessor.state = _this.accessor.state.clear();
query = _this.accessor.buildOwnQuery(query);
expect(query.query.sort).toEqual(undefined);
_this.options.options[1].defaultOption = true;
query = _this.accessor.buildOwnQuery(query);
expect(query.query.sort).toEqual([{ 'price': 'desc' }]);
// handle complex sort
_this.accessor.state = new _1.ValueState("rated");
query = _this.accessor.buildOwnQuery(query);
expect(query.query.sort).toEqual([{ 'rating': { order: 'asc' } }, { 'price': { order: 'desc', customKey: 'custom' } }]);
// empty options
_this.accessor.state = new _1.ValueState("cheapest");
query = _this.accessor.buildOwnQuery(query);
expect(query.query.sort).toEqual([{ 'price': { order: 'desc' } }, { 'rated': {} }]);
// handle no options
_this.accessor.options.options = [];
query = _this.accessor.buildOwnQuery(new _1.ImmutableQuery());
expect(query.query.sort).toEqual(undefined);
});
});
//# sourceMappingURL=SortingAccessorSpec.js.map |
const hooks = require('hooks');
hooks.beforeEach((transaction, done) => {
transaction.request.body = Buffer.from([0xFF, 0xEF, 0xBF, 0xBE]).toString('base64');
transaction.request.bodyEncoding = 'base64';
done();
});
|
(function() {
var app = angular.module('gemStore', ['store-products']);
app.controller('StoreController', [ '$http', function($http){
//this.products = $http({ method: 'GET', url: '/products.json' });
//$http.get('/products.json', { apiKey: 'myApiKey' });
var store = this;
store.products = [];
$http.get('store-products.json').success(function(data){
store.products = data;
});
//$http.post('/path/to/resource.json', { param: 'value' }); //post to server
//$http.delete('/path/to/resource.json'); //delete from server
//$http({ method: 'OPTIONS', url: '/path/to/resource.json' }); //post other methods to server using config object
}]);
/*
app.controller('GalleryController', function(){
this.current = 0;
this.setCurrent = function(imageNumber){
this.current = imageNumber || 0;
};
});
*/
app.controller("ReviewController", function(){
this.review = {};
this.addReview = function(product) {
this.review.createdOn = Date.now();
product.reviews.push(this.review);
this.review = {};
};
});
})();
|
angular.module('wikidataTimeline')
.factory('$wikidata', ['$http', '$q', function($http, $q) {
var WD = {};
WD.languages = ['en', 'fr'];
WD.sitelinks = [ 'wikisource', 'commonswiki', 'wikibooks', 'wikiquote', 'wiki', 'wikinews' ];
/**
* converts a wikidata datetime to a JS Date
* @todo: expand to get time part as well
* @param {string} dateTimeStr ex: +1952-03-11T00:00:00Z
* @return {Date}
*/
WD.parseDateTime = function(dateTimeStr) {
var match = dateTimeStr.match(/^([+-]?\d+)-(\d\d)-(\d\d)/);
if (match && match.length == 4) {
var result = new Date(match[1], match[2] - 1, match[3]);
result.setFullYear(match[1]); // 30 != 1930, javascript!
return result;
} else {
return undefined;
}
};
/**
* Creates a sitelink's url from the given params
* @param {string} lang the lang
* @param {string} sitelink the sitelink suffix
* @return {string} string the url
*/
WD.makeSitelinkUrl = function(lang, sitelink, title) {
switch(sitelink) {
case 'wiki':
return "https://" + lang + ".wikipedia.org/w/index.php?title=" + title;
case 'commonswiki':
return "https://commons.wikimedia.org/w/index.php?title=" + title;
default:
return "https://" + lang + "." + sitelink + ".org/w/index.php?title=" + title;
}
};
/**
* @class
*/
WD.Entity = function(entity) {
this.isTrimmed = false;
this.entity = entity;
};
/**
* Gets the array of property's values. If not found, returns undefined.
*
* @param {String} prop - a property PID
* @return {Array} of values or undefined
*/
WD.Entity.prototype.getClaim = function(prop) {
return this.entity.claims[prop];
};
/**
* Returns wikidata url
*
* @return {string} wikidata url
*/
WD.Entity.prototype.url = function(prop) {
return "https://www.wikidata.org/wiki/" + this.entity.id;
};
/**
* Get's a claim's value. Uses the first statement.
*
* @param {String} prop - a property PID
* @return {String} The value
*/
WD.Entity.prototype.getClaimValue = function(prop) {
var claim = this.entity.claims[prop];
if(!claim) return undefined;
// TODO: if there is a preferred statement, use it
// TODO: else pick first normal ranked statement
var statement = claim[0];
var type = statement.mainsnak.snaktype;
switch(type) {
case 'value':
return statement.mainsnak.datavalue.value;
default:
// TODO: Add other cases
return statement.mainsnak.datavalue.value;
}
};
/**
* Returns the first of the arguments that has 1 or more claims. If none
* found, returns undefined.
*
* @param list of string property IDs
* @return {Array} of values or undefined
*/
WD.Entity.prototype.getFirstClaim = function() {
for (var i = 0; i < arguments.length; i++) {
if(this.getClaim(arguments[i])) {
return this.getClaim(arguments[i]);
}
};
return undefined;
};
/**
* Returns an entity's label. If langs provided, finds langs, otherwise uses
* APIs defaults.
* @param {array<string>} [langs] langs to look for label. Defaults to WD params
* @param {Boolean} [returnObject=false] if true, returns an object ({language, value})
* @return {string|object} string if !returnObject, else {language, value} object
*/
WD.Entity.prototype.getLabel = function(langs, returnObject) {
if (typeof langs == 'undefined') {
langs = WD.languages;
}
if(typeof langs == "string") {
langs = [ langs ];
}
if (!this.entity.labels) {
return "";
}
// iterate through langs until we find one we have
for(var i = 0; i < langs.length; ++i) {
var obj = this.entity.labels[langs[i]];
if(obj) {
if (returnObject) {
return obj;
} else {
return obj.value;
}
}
}
// no luck. Try to return any label.
for(var lang in this.entity.labels) {
if(returnObject) {
return this.entity.labels[lang];
} else {
return this.entity.labels[lang].value;
}
}
// still nothing?!? return empty string
return "";
};
/**
* Returns an entity's sitelink. If langs provided, finds langs, otherwise uses
* APIs defaults.
* @param {string|array<string>} sitelinks the sitelinks to get. See WD.sitelinks for valid options.
* @param {string|array<string>} [langs] langs to look for label. Defaults to WD params
* @return {string} string the url
*/
WD.Entity.prototype.getSitelink = function(sitelinks, langs) {
if (typeof langs == 'undefined') {
langs = WD.languages;
}
if (typeof langs == "string") {
langs = [ langs ];
}
if (typeof sitelinks == "string") {
sitelinks = [ sitelinks ]
}
if (!this.entity.sitelinks) {
return null;
}
// iterate through langs/sitelink pairs
for(var i = 0; i < sitelinks.length; ++i) {
for(var j = 0; j < langs.length; ++j) {
var sl = this.entity.sitelinks[sitelinks[i]] || this.entity.sitelinks[langs[j].replace(/\-/g, '_') + sitelinks[i]];
if (sl) {
return WD.makeSitelinkUrl(langs[j], sitelinks[i], sl.title);
}
}
}
// no luck. Return null
return null;
};
/**
* Deletes any unneeded items. Define the properties to keep. Everything else
* deleted.
* @param {object} config defines how to trim
* @config {array<string>} claims
* @config {array<string>} descriptions
* @config {*} id
* @config {array<string>} labels
* @config {*} lastrevid
* @config {*} modified
* @config {*} ns
* @config {*} pageid
* @config {array<string>} sitelinks
* @config {*} title
* @config {*} type
*/
WD.Entity.prototype.trimIncludeOnly = function(config) {
var neverRemove = ['id'];
for (var key in this.entity) {
if(neverRemove.indexOf(key) !== -1) {
continue;
}
if (typeof config[key] !== 'undefined') {
if (['claims', 'descriptions', 'labels', 'sitelinks'].indexOf(key) !== -1) {
for (var p in this.entity[key]) {
if (config[key].indexOf(p) == -1) {
delete this.entity[key][p];
}
}
}
} else {
delete this.entity[key];
}
}
return this;
};
/**
* @param {string} wikidata query
* @returns {Promise<QID[]>}
*/
WD.WDQ = function(query) {
// first convert to a SPARQL query
return $http({
url: '//tools.wmflabs.org/wdq2sparql/w2s.php',
params: {
wdq: query
}
}).then(function (response) {
var contentType = response.headers()['content-type'];
if (contentType.indexOf('text/plain') != -1) {
// avoid duplicate items; replace the outermost SELECT with DISTINCT
var sparql = response.data
.replace(/^SELECT (\S+)/i, function($0, $1) {
return $1.toLowerCase() == 'distinct' ? $0 : 'SELECT DISTINCT ' + $1;
});
return WD.wdqs(sparql);
} else {
return $q.reject();
}
}).then(function (response) {
return response.data.results.bindings.map(function (o) {
return o.item.value.replace('http://www.wikidata.org/entity/', '');
});
});
};
/**
* Query the Wikidata Query Service
* @param {string} sparql the SPARQL query
* @return {Promise}
*/
WD.wdqs = function(sparql) {
return $http({
url: 'https://query.wikidata.org/sparql',
params: {
query: sparql,
format: 'json'
}
});
};
WD.api = {};
var api = WD.api;
api.baseURL = 'https://www.wikidata.org/w/api.php';
/**
* @name QueryState
* @enum {number}
*/
WD.QueryStates = {
Active: 1,
Pausing: 2,
Paused: 3,
Complete: 4
};
/**
* See {@link https://www.wikidata.org/w/api.php?action=help&modules=wbgetentities}
* Executes the query in 50-sized chunks
* @async
* @param {array<integer>} ids the IDs to get
* @param {array<string>} props props to get back for each item
* @param {object} opts @todo
* @return {Object} publicApi
* @return {Function} publicApi.onChunkComplete
* @return {Function} publicApi.onFullCompletion
* @return {Function} publicApi.pause
* @return {Function} publicApi.resume
* @return {Function} publicApi.getState the state of the query.
* See {@link QueryState}
*/
api.wbgetentities = function(ids, props, opts) {
ids = ids.map(function(id) { return 'Q' + id; });
// split into 50-sized chunks
var idChunks = [];
for(var i = 0; i < ids.length; ++i) {
if (i % 50 == 0) {
idChunks.push([]);
}
idChunks[idChunks.length - 1].push(ids[i]);
}
var state = WD.QueryStates.Active;
var api = {
onChunkCompletion: function() {},
onFullCompletion: function() {}
};
var publicApi = {
onChunkCompletion: function(fn) {
api.onChunkCompletion = fn;
return publicApi;
},
onFullCompletion: function(fn) {
api.onFullCompletion = fn;
return publicApi;
},
pause: function() {
state = WD.QueryStates.Pausing;
return publicApi;
},
resume: function() {
if (state == WD.QueryStates.Paused) {
state = WD.QueryStates.Active;
queryForNextChunk();
}
return publicApi;
},
getState: function() {
return state;
}
};
function queryForNextChunk() {
if (state == WD.QueryStates.Active) {
$http({
url: WD.api.baseURL,
method: 'jsonp',
params: {
action: 'wbgetentities',
ids: idChunks.shift().join('|'),
languages: WD.languages.join('|'),
props: props.join('|'),
format: 'json',
cache: true
}
})
.then(_onChunkCompletion);
}
};
function _onChunkCompletion(response) {
if (state == WD.QueryStates.Pausing) {
state = WD.QueryStates.Paused;
}
api.onChunkCompletion(response);
if (idChunks.length === 0) {
state = WD.QueryStates.Complete;
api.onFullCompletion();
} else {
queryForNextChunk();
}
}
queryForNextChunk();
return publicApi;
};
return WD;
}]);
|
define(['vm/ConstantPool/ConstantPoolFactory', 'vm/Attributes/AttributeFactory', 'vm/FieldInfoFactory', 'vm/MethodFactory', 'util/Util', 'vm/Class'],
function(ConstantPoolFactory, AttributeFactory, FieldInfoFactory, MethodFactory, Util, Class) {
"use strict";
var ClassFactory = {};
ClassFactory.parseClass = function(jcr) {
var i;
//u4 magic;
var magic = jcr.getUintField(4);
//Why not?
Util.assert(magic === 0xCAFEBABE && "ERROR: Magic value 0xCAFEBABE not found! Instead: " + magic);
//u2 minor_version;
var minorVersion = jcr.getUintField(2);
//u2 major_version;
var majorVersion = jcr.getUintField(2);
var constantPool = ConstantPoolFactory.parseConstantPool(jcr);
//u2 access_flags;
var accessFlags = jcr.getUintField(2);
//u2 this_class;
var thisClassIndex = jcr.getUintField(2);
var thisClassName = constantPool.getClassInfo(thisClassIndex);
var klass = new Class(minorVersion, majorVersion, constantPool, accessFlags, thisClassName);
//Register the class. This is very important, or else we could get into infinite loading loops.
//Trying a Hack to load system
if (thisClassName === "System"){
JVM.registerClass("java/lang/System", klass);
}else if (thisClassName === "PrintStream"){
JVM.registerClass("java/io/PrintStream", klass);
}else{
JVM.registerClass(thisClassName, klass);
}
//u2 super_class;
var superClassIndex = jcr.getUintField(2);
var superClassName = constantPool.getClassInfo(superClassIndex);
//u2 interfaces_count;
var interfacesCount = jcr.getUintField(2);
var interfaces = [];
var interfaceIndex;
//u2 interfaces[interfaces_count];
for(i = 0; i < interfacesCount; i++) {
interfaceIndex = jcr.getUintField(2);
interfaces[i] = constantPool.getClassInfo(interfaceIndex);
}
//u2 fields_count;
var fieldsCount = jcr.getUintField(2);
var fields = [];
//field_info fields[fields_count];
for(i = 0; i < fieldsCount; i++) {
fields[i] = FieldInfoFactory.parseFieldInfo(jcr, klass, constantPool);
}
//u2 methods_count;
var methodsCount = jcr.getUintField(2);
var methods = [];
//method_info methods[methods_count];
for(i = 0; i < methodsCount; i++) {
methods[i] = MethodFactory.parseMethod(jcr, klass, constantPool);
}
//u2 attributes_count;
var attributesCount = jcr.getUintField(2);
//attribute_info attributes[attributes_count];
var attributes = AttributeFactory.parseAttributes(jcr, attributesCount, constantPool);
klass.finishInstantiation(superClassName, interfaces, fields, methods, attributes, fields);
return klass;
};
return ClassFactory;
}
); |
'use strict';
var gulp = require('gulp');
var csslint = require('gulp-csslint');
var jshint = require('gulp-jshint');
var nodemon = require('gulp-nodemon');
var livereload = require('gulp-livereload');
var uglify = require('gulp-uglifyjs');
var concat = require('gulp-concat');
var minifyCSS = require('gulp-minify-css');
var rename = require('gulp-rename');
var mocha = require('gulp-mocha');
var karma = require('gulp-karma');
var applicationJavaScriptFiles,
applicationCSSFiles,
applicationTestFiles;
gulp.task('jshint', function() {
gulp.src(['gulpFile.js', 'server.js', 'config/**/*.js', 'app/**/*.js', 'public/js/**/*.js', 'public/modules/**/*.js'])
.pipe(jshint())
.pipe(jshint.reporter('default'));
});
gulp.task('csslint', function() {
gulp.src(['public/modules/**/css/*.css'])
.pipe(csslint('.csslintrc'))
.pipe(csslint.reporter());
});
gulp.task('nodemon', function (done) {
nodemon({ script: 'server.js', env: { 'NODE_ENV': 'development' }})
.on('restart');
});
gulp.task('uglify', function() {
gulp.src(applicationJavaScriptFiles)
.pipe(uglify('application.min.js',
{
outSourceMap : true
}))
.pipe(gulp.dest('public/dist'));
});
gulp.task('cssmin', function () {
gulp.src(applicationCSSFiles)
.pipe(concat('application.css'))
.pipe(minifyCSS())
.pipe(rename('application.min.css'))
.pipe(gulp.dest('public/dist'));
});
gulp.task('mochaTest', function () {
process.env.NODE_ENV = 'test';
gulp.src(['server.js','app/tests/**/*.js'])
.pipe(mocha({reporter: 'spec'}));
});
gulp.task('karma', function () {
gulp.src(applicationTestFiles)
.pipe(karma({
configFile: 'karma.conf.js',
action: 'run'
}))
.on('error', function(err) {
// Make sure failed tests cause gulp to exit non-zero
throw err;
});
});
gulp.task('watch', function() {
var server = livereload();
gulp.watch(['gulpFile.js', 'server.js', 'config/**/*.js', 'app/**/*.js', 'public/js/**/*.js', 'public/modules/**/*.js'], ['jshint']);
gulp.watch(['public/**/css/*.css'], ['csslint']);
gulp.watch(['gruntfile.js', 'server.js', 'config/**/*.js', 'app/**/*.js', 'public/modules/**/views/*.html', 'public/js/**/*.js', 'public/modules/**/*.js', 'public/**/css/*.css']).on('change', function(file) {
server.changed(file.path);
});
});
gulp.task('loadConfig', function() {
var init = require('./config/init')();
var config = require('./config/config');
applicationJavaScriptFiles = config.assets.js;
applicationCSSFiles = config.assets.css;
applicationTestFiles = config.assets.lib.js.concat(config.assets.js, config.assets.tests);
});
// Default task(s).
gulp.task('default', ['jshint', 'csslint','nodemon', 'watch']);
// Lint task(s).
gulp.task('lint', ['jshint', 'csslint']);
// Build task(s).
gulp.task('build', ['jshint', 'csslint', 'loadConfig', 'uglify', 'cssmin']);
// Test task.
gulp.task('test', ['loadConfig', 'mochaTest', 'karma']);
|
;(function(){
angular.module("Jal-Stats", ['ngRoute'], function($routeProvider){
$routeProvider
.when('/', {
redirectTo: '/login'
})
.when('/login', {
templateUrl: 'partials/login.html',
controller: function($http){
var login = { };
login.send = function(){
$http.get('https://rocky-falls-8228.herokuapp.com/api/users/' + '/whoami', {
headers: {
Authorization: "Basic" + btoa(login.user.username + ':' + login.user.password)
}
}).then(function(response){
$http.defaults.headers.common.Authorization = "Basic" + btoa(
login.user.username + ':' + login.user.password
);
})//END OF PROMISE
}//END OF .SEND
},
controllerAs: 'login'
}) //END OF LOGIN
.when('/signup', {
templateUrl: 'partials/signup.html',
controller: function($http){
var signup = { };
signup.createUser = function(){
$http.post('https://rocky-falls-8228.herokuapp.com/api/users/')
}
},
controllerAs: 'signup'
}) //END OF SIGNUP
.when('/activity-form', {
templateUrl: 'partials/activity-form.html',
controller: function($http, $location){
this.activities = { };
this.logActivity = function(){
$http.post('https://rocky-falls-8228.herokuapp.com/api/activities/')
this.activities = { };
$location.path('/activity-form');
}
},
controllerAs: 'activityCreate'
}) //END OF ACTIVITY FORM
.when('/activity-display/:activities_id', {
templateUrl: 'partials/activity-display.html',
controller: function($http, $routeParams, $rootScope){
console.log($routeParams);
$http.get('https://rocky-falls-8228.herokuapp.com/api/activities/'+ $routeParams.activities_id)
},
}) //END OF ACTIVITY DISPLAY
.when('/activity-homepage', {
templateUrl: 'partials/activity-homepage.html',
controller: function($http, $rootScope){
$http.get('https://rocky-falls-8228.herokuapp.com/api/activities/')
.then(function(response){
$rootScope.activities = response.data;
})
}
// secondController: function($http, $rootScope){
// var newActivity = { };
// newActivity.createActivity = function(){
// $http.post('https://rocky-falls-8228.herokuapp.com/api/activities/')
// }
// // var newActivity = { };
// }, //END SECOND CONTROLLER
// controllerAs: 'newActivity'
})//END OF ACTIVITY HOMEPAGE
}); // END OF JAL-STATS MODULE
})(); //END OF IFFE
|
/* ===========================================================
* OCNav - Offcanvas plugin for Bootstrap
*
* author: @geedmo
* uri: http://geedmo.com
*
* Copyright (c) 2014, Geedmo. All rights reserved.
* Released under CodeCanyon Regular License: http://codecanyon.net/licenses
* =========================================================== */
!function() {
var activeClass = 'active';
$(function() {
var menuWrapper = $('.oc-wrapper');
$('.oc-toggle').click(function(){
var $target = $($(this).data('target'))
$target.toggleClass(activeClass)[0].offsetWidth
menuWrapper.toggleClass(activeClass)
$('html,body').animate({scrollTop: 0});
return false;
})
$('.oc-close').click(function(){
var $target = $(this).parents('.oc-navbar').eq(0);
$target.removeClass(activeClass)[0].offsetWidth
menuWrapper.removeClass(activeClass)
return false;
})
var toggler = $('.oc-toggle').eq(0);
checkReponsive();
$(window).resize(checkReponsive)
function checkReponsive(){
var responsive = toggler.is(':visible');
if(!responsive) {
menuWrapper.removeClass(activeClass)
$('.oc-navbar').removeClass(activeClass)
}
}
});
}(window.jQuery); |
'use strict'
/* global describe, it */
const assert = require('assert')
const supertest = require('supertest')
describe('Registered User ReviewController', () => {
let registeredUser, userID, customerID
before((done) => {
registeredUser = supertest.agent(global.app.packs.express.server)
// Login as Registered
registeredUser
.post('/auth/local/register')
.set('Accept', 'application/json') //set header for this test
.send({
email: 'reviewcontroller@example.com',
password: 'registered1234'
})
.expect(200)
.end((err, res) => {
assert.ok(res.body.user.id)
assert.ok(res.body.user.current_customer_id)
userID = res.body.user.id
customerID = res.body.user.current_customer_id
done(err)
})
})
it('should exist', () => {
assert(global.app.api.controllers['ReviewController'])
})
it('should not get reviews', (done) => {
registeredUser
.get('/reviews')
.expect(403)
.end((err, res) => {
done(err)
})
})
})
|
const { stringifyJSONForWeb } = require('desktop/components/util/json.coffee')
export const SuperSubArticlesQuery = (ids) => {
return `
{
articles(ids: ${stringifyJSONForWeb(ids)}, published: true) {
thumbnail_title
thumbnail_image
title
slug
}
}
`
}
export const SuperArticleQuery = (id) => {
return `
{
articles(super_article_for: "${id}", published: true ) {
is_super_article
thumbnail_title
title
slug
super_article {
partner_link
partner_link_title
partner_logo
partner_logo_link
partner_fullscreen_header_logo
secondary_partner_logo
secondary_logo_text
secondary_logo_link
footer_blurb
footer_title
related_articles
}
}
}
`
}
|
/**
* Created by Paul-Guillaume Déjardin on 15/04/16.
* Copyright © 2016 Xebia IT Architects. All rights reserved.
*/
var express = require('express'),
router = express.Router(),
postgresStore = require('../oauth/postgresStore');
module.exports = function (app) {
app.use('/users', app.oauth.authorise(), router);
};
router.get('/', function (req, res) {
postgresStore.getUserByToken(req.query.access_token, function(err, result) {
if (err) res.status(500).end();
if (result) {
return res.send(result)
}
return res.status(404).end();
});
});
|
'use strict';
angular.module('webApp').constant('CONFIG', {
povej : {
buttons : {
favorite : true,
volume : false,
keyboard : false,
fullscreen : true
}
}
});
// disable cordova plugins
angular
.module('webApp')
.factory('$cordovaFile', [function(){}])
.factory('$cordovaNetwork', [function(){}])
;
// disable modules
angular.module('ngAnimate', []);
angular.module('hmTouchEvents', []); |
jest.unmock('../src/index');
import index from '../src/index';
describe('<%= name %> tests', () => {
it('succeeds', () => {
expect(index())
.toBe(true);
});
});
|
import React, { PureComponent } from 'react';
import PropTypes from 'prop-types';
// offsetX 水平偏移量, 百分百或字符串
class ProgressBar extends PureComponent {
constructor(props) {
super(props);
this.handleChangeProgress = this.handleChangeProgress.bind(this);
}
handleChangeProgress(e) {
const clkProgress =
(e.clientX - this.progress.getBoundingClientRect().left) / this.progress.clientWidth;
this.props.onChangeProgress(clkProgress, true);
}
render() {
const { offsetX, percent } = this.props;
const style = { marginTop: '15px', marginLeft: offsetX, cursor: 'pointer' };
return (
<div
className="ui red tiny progress"
data-percent={percent * 100}
style={style}
ref={(progress) => { this.progress = progress; }}
onClick={this.handleChangeProgress}
>
<div className="bar" style={{ width: `${percent * 100}%`, minWidth: 0 }} />
</div>
);
}
}
ProgressBar.propTypes = {
offsetX: PropTypes.string,
percent: PropTypes.number,
onChangeProgress: PropTypes.func
};
ProgressBar.defaultProps = {
offsetX: '0',
percent: 0,
onChangeProgress: () => {}
};
export default ProgressBar;
|
const Device = require('../../../objects/device');
const spawn = require('../../../utils/spawn');
const sdkPaths = require('../utils/sdk-paths');
const deserializeDevices = function(list) {
let devices = [];
if (list === undefined) { return devices; }
let items = list.split('\n');
items = items.splice(1, items.length - 1);
items.forEach((item) => {
if (item.trim() === '') { return; }
let device = new Device({
name: item.split('model:')[1].split(' ')[0],
uuid: item.split(' ')[0],
deviceType: 'device',
platform: 'android'
});
devices.push(device);
});
return devices;
};
module.exports = function() {
let adbPath = sdkPaths().adb;
let list = [
adbPath,
['devices', '-l']
];
return spawn(...list).then((result) => {
let devices = deserializeDevices(result.stdout);
return devices.reverse();
});
};
|
angular.module('pizzaBuilder')
/**
* main contorller of /new route
*/
.controller('NewController', ['$scope', '$location', 'Components', 'Data', function($scope, $location, Components, Data) {
// some data to fill inputs in view
$scope.title = 'Dodaj';
/**
* Add new pizza to pizzaList
*
* @param {String} name name of pizza
*/
$scope.save = function(name) {
var pizza = {
name: name,
components: Components.getSelection()
};
if ($scope.$parent.useExpress) {
Data
.post('http://localhost:' + Data.PORT + '/list', pizza)
.then(function(response) {
$location.path('/');
$scope.$parent.pizzaList.push(pizza);
});
} else {
$scope.$parent.pizzaList.push(pizza);
$location.path('/');
}
};
}]);
|
(function() {
var dependencies = [
"babel.editor",
"babel.execution",
"babel.cmd",
"babel.script",
"babel.errors",
"babel.stack",
"babel.dump"
];
var module = angular.module("babel.exercice", dependencies);
module.service("$Generator", function() {
/**
* Génère un nombre entier aléatoire.
*
* @param Number max (optionel)
* @param Number min (optionel)
*
* @return Number un nombre entier aléatoire.
*/
this.nextInt = function(max, min) {
if(!angular.isDefined(max)) {
return Math.floor(Math.random() * Number.MAX_VALUE);
}
else if(!angular.isDefined(min)) {
return Math.floor(Math.random() * max);
}
else {
return Math.floor(Math.random() * (max - min) + min);
}
};
/**
* Retourne un paramètre aléatoire.
*
* @return Object paramètre choisi.
*/
this.nextOf = function() {
if(this.params.length <= 0) {
return undefined;
}
else {
return this.nextIn(this.params);
}
};
/**
* Retourne un objet aléatoire contenu dans un tableau.
*
* @param Array array tableau contenant les valeurs.
*
* @return Object valeur aléatoire du tableau passé en paramètre.
*/
this.nextIn = function(array) {
return array[this.nextInt(array.length)];
};
/**
* Génère un tableau de valeurs aléatoires.
*
* @param Number size taille du tableau.
*
* @param Callback callback fonction de génération.
*
* @return Array un tableau de valeurs aléatoires.
*/
this.generateArray = function(size, callback) {
var result = new Array();
for(var i = 0; i < size; ++i) {
result.push(callback(i));
}
return result;
};
});
module.factory("Exercice", ["Script", "ExecutionSession", function(Script, ExecutionSession) {
function Exercice() {
this.constraints = [];
this.tests = [];
this.script = new Script();
this.errors = [];
}
Exercice.prototype.unitTest = function(callback) {
this.tests.push(callback);
};
Exercice.prototype.constraint = function(query) {
this.constraints.push(query);
};
Exercice.prototype.validate = function() {
this.errors = [];
var self = this;
if(!this.script.isValid()) {
this.errors = ["Il y a des erreurs de syntaxe : " + this.script.error];
return false;
}
angular.forEach(this.constraints, function(constraint) {
var result = self.script.ast.validate(constraint);
if(!result.isValid()) {
result.each(function() {
self.errors.push(this.error);
});
}
});
if(this.errors.length > 0) {
return false;
}
angular.forEach(this.tests, function(unitTest) {
if(!unitTest.apply(self)) {
return false;
}
});
return true;
};
Exercice.prototype.init = function() {
this.script = new Script(this.initialCode);
};
return Exercice;
}]);
/**
solution :::
var result = [];
var j = 0;
for(var i = 0; i < array.length; ++i) {
if(result.length == 0) {
result.push(array[i]);
}
else {
var stop = false;
for(j = 0; j < result.length && !stop; ++j) {
if(result[j] > array[i]) {
var start = result.slice(0, j);
var end = result.slice(j);
start.push(array[i]);
result = start.concat(end);
stop = true;
}
}
if(j >= result.length) {
result.push(array[i]);
}
}
}
print(result);
return [];
*/
module.directive("exercice", [
"Script",
"$Generator",
"Exercice",
function(Script, $Generator, Exercice) {
return {
"restrict":"E",
"scope":{
"category":"@",
"title":"@"
},
"templateUrl":"templates/exercice.html",
"link": function(scope, iElem, iAttrs) {
scope.exercice = new Exercice();
scope.exercice.script = new Script(
"function sort(array) {\n\n}",
"javascript"
);
scope.exercice.script.lockLine(0);
scope.exercice.script.lockLine(2);
/**
* Un test unitaire.
*/
scope.exercice.unitTest(function() {
var self = this;
function validate(initial, result) {
if(result == null || result == undefined || !(result instanceof Array)) {
self.errors.push("La fonction sort ne retourne pas un tableau.");
return false;
}
if(initial.length == 0) {
if(result.length == 0) {
return true;
}
else {
self.errors.push("sort(["+initial+"]) retourne [" + result + "] au lieu de [].");
return false;
}
}
if(initial.length == 1) {
if(result.length == 1 && result[0] == initial[0]) {
return true;
}
else {
self.errors.push("sort(["+initial+"]) retourne [" + result + "] au lieu de ["+initial+"].");
return false;
}
}
if(initial.length != result.length) {
self.errors.push("sort(["+initial+"]) retourne [" + result + "] qui n'est pas correctement trié.");
return false;
}
for(var i = 1; i < result.length; ++i) {
if(result[i-1] > result[i]) {
self.errors.push("sort(["+initial+"]) retourne [" + result + "] qui n'est pas correctement trié.");
return false;
}
}
return true;
};
var exec = this.script.createExecutionSession();
exec.prepare();
for(var i = 0; i < 13; ++i) {
var initial = $Generator.generateArray(i, function() {
return $Generator.nextInt(100);
});
var result = exec.call("sort", initial).returned;
if(!validate(initial, result)) {
return false;
}
}
return true;
});
scope.exercice.constraint('root . function sort [error:"Il n\'y a pas de fonction sort."] [named:premiereErreur] with { root . return } [error:"La fonction sort ne retourne rien."] [named:secondeErreur ]');
scope.$$exec = undefined;
scope.$syntaxError = function() {
return !scope.exercice.script.isValid();
};
scope.$watch(function() {
return scope.exercice.script.content()
}, function() {
scope.$$exec = undefined;
})
scope.$startStepByStep = function() {
if(scope.exercice.script.isValid()) {
scope.$$exec = scope.exercice.script.createExecutionSession();
scope.exercice.stack = [];
scope.exercice.dumpGlobal = [];
scope.exercice.dumpLocal = [];
scope.$$cmdContent = "";
}
};
scope.$endStepByStep = function() {
scope.$$exec = undefined;
};
scope.$execute = function() {
if(scope.exercice.script.isValid()) {
exec = scope.exercice.script.createExecutionSession();
exec.run();
scope.$$cmdContent = exec.out();
}
};
scope.$validate = function() {
scope.$$cmdContent = "";
if(scope.exercice.validate()) {
scope.$$cmdContent = "Le script est valide !";
}
};
/* dernier noeud parcouru */
scope.$previousNode = null;
/* dernier noeud surlequel le script s'est arrêté */
scope.$previousNodePausedOn = null;
/* dernière ligne marquée en tant que prochaine instruction à exécuter */
scope.$lastMarkedLine = null;
/* dernier blocStatement rencontré */
scope.$lastBlockEncountered = null;
/* bloc dont on souhaite aller à la fin */
scope.$blockToGoToTheEnd = null;
/* dernier bloc dont on est allé à la fin */
scope.$lastBlockGottenToTheEnd = null;
/**
* Retourne la liste des types de noeud surlesquels une pause s'avère intéressante (step-by-step 'instruction-by-instruction').
*
* @return la liste des types de noeud surlesquels une pause s'avère intéressante. Les données de la liste peuvent être au format suivant :
* 'XXXX' => Pause on the node if (node.type == XXXX)
* 'XXXX preceded by YYYY' => Pause on the node if (node.type == XXXX) and (previousNode == YYYY)
* 'XXXX not preceded by YYYY' => Pause on the node if (node.type == XXXX) and (previousNode != YYYY)
*
* NB: a 'not preceded by' must also be defined alone to work properly. fi : 'ExpressionStatement'
*/
scope.$interestingNodeTypes = function() {
return [
'ExpressionStatement',
'VariableDeclaration',
'ReturnStatement',
'UpdateExpression preceded by ForStatement', // Ajoute une pause lors de l'update de la variable de boucle
'BinaryExpression preceded by ForStatement', // Ajoute une pause lors du check de la condition de boucle
'BinaryExpression preceded by WhileStatement', // Ajoute une pause lors du check de la condition de boucle
'ExpressionStatement not preceded by CallExpression' // Empêche une pause sur la fonction appelant une autre lorsque cette dernière a retournée une valeur
];
};
/**
* Dit si un step-by-step doit être mis en pause suite à l'arrivée sur un noeud.
*
* @param stepByStepType
* le type de stepByStep ('detailed-step-by-step', 'instruction-by-instruction', 'get-out-of-block')
* @param node
* un noeud
* @return true si le step-by-step doit être mis en pause.
*/
scope.$nodeRequiringAPause = function(stepByStepType, node) {
if (stepByStepType === 'instruction-by-instruction') {
var interestingNodeTypes = scope.$interestingNodeTypes();
var checkPrecededBy = scope.$previousNode != null && interestingNodeTypes.indexOf(node.type + " preceded by " + scope.$previousNode.type) != -1;
var checkNotPrecededBy = scope.$previousNode == null || interestingNodeTypes.indexOf(node.type + " not preceded by " + scope.$previousNode.type) == -1;
var checkInList = interestingNodeTypes.indexOf(node.type) != -1 && checkNotPrecededBy;
var checkDifferentNode = node != scope.$previousNodePausedOn;
return (checkInList && checkDifferentNode) || checkPrecededBy;
}
if (stepByStepType === 'get-out-of-block') {
if (scope.$blockToGoToTheEnd !== null && node === scope.$blockToGoToTheEnd.body[scope.$blockToGoToTheEnd.body.length - 1]) {
scope.$lastBlockGottenToTheEnd = scope.$blockToGoToTheEnd;
return true;
}
return false;
}
// 'detailed-step-by-step'
return true;
};
/**
* Marque la ligne correspondant au noeud en tant que prochaine instruction
* à exécuter et met en valeur le noeud au sein de cette ligne.
*/
scope.$highlightNode = function(node) {
scope.exercice.script.select(
scope.exercice.script.toPosition(node.start),
scope.exercice.script.toPosition(node.end)
);
if (scope.$lastMarkedLine != null) {
scope.exercice.script.unmarkLine(scope.$lastMarkedLine);
}
scope.$lastMarkedLine = scope.exercice.script.toPosition(node.start).line;
scope.exercice.script.markLine(scope.$lastMarkedLine);
};
/**
* Démarque la ligne correspondant au noeud en tant que prochaine instruction
* à exécuter et supprime la mise en valeur du noeud au sein de cette ligne.
*/
scope.$unhighlightLastNodeHighlighted = function() {
if (scope.$lastMarkedLine != null) {
scope.exercice.script.unmarkLine(scope.$lastMarkedLine);
scope.exercice.script.select(scope.$editor.$toPosition(0));
scope.$lastMarkedLine = null;
scope.$previousNode = null;
scope.$previousNodePausedOn = null;
scope.$lastBlockEncountered = null;
scope.$blockToGoToTheEnd = null;
scope.$lastBlockGottenToTheEnd = null;
}
};
scope.$goToEndOfBlock = function() {
// Si on est déjà à la fin du bloc en cours
if (scope.$blockToGoToTheEnd != null && scope.$previousNodePausedOn === scope.$blockToGoToTheEnd.body[scope.$blockToGoToTheEnd.body.length - 1]) {
return false;
}
// Si on est dans le corps principal du programme
if (scope.$stack.length === 0) {
scope.$blockToGoToTheEnd = null;
}
// Si on est dans un autre bloc
else {
scope.$blockToGoToTheEnd = scope.$lastBlockEncountered;
}
scope.$next('get-out-of-block');
};
/**
* Va à la prochaine étape d'un step-by-step.
*
* @param stepByStepType
* le type de stepByStep ('detailed-step-by-step', 'instruction-by-instruction')
*/
scope.$next = function(stepByStepType) {
var node = scope.$$exec.nextNode().$$node;
if (angular.isDefined(Node)) {
scope.exercice.stack = scope.$$exec.stack(scope);
if (node.type == 'BlockStatement') {
scope.$lastBlockEncountered = node;
}
// Faire une pause sur le noeud s'il le requiert, sinon aller au prochain
if (scope.$nodeRequiringAPause(stepByStepType, node)) {
scope.$previousNodePausedOn = node;
scope.$previousNode = node;
scope.$highlightNode(node);
var $dump = scope.$$exec.dump();
var global = $dump["global"]
delete $dump["global"];
if (global)
scope.exercice.dumpGlobal = $dump;
else
scope.exercice.dumpLocal = $dump;
}
else {
scope.$previousNode = node;
if (!scope.$$exec.step()) {
return;
}
scope.$next(stepByStepType);
return;
}
}
else {
scope.$unhighlightLastNodeHighlighted();
}
if(!scope.$$exec.step()) {
scope.$$cmdContent = scope.$$exec.out();
scope.$unhighlightLastNodeHighlighted();
scope.$$exec = undefined;
}
else {
scope.$$cmdContent = scope.$$exec.out();
}
};
}
};
}]);
})();
|
/*jshint laxcomma: true, smarttabs: true, node:true, mocha: true*/
'use strict';
/**
* Allows for filtering case sensitve filtering of records
* @module tastypie-bookshelf/lib/resource/filters/exact
* @author Eric Satterwhite
* @since 1.0.0
* @requires cage/string
* @example ?foobar__exact=igh
*/
module.exports = function exact(qb, field, term){
return qb.where(field, term);
};
|
$.getJSON("https://twitter.madeat.eu/1.1/statuses/user_timeline.json?screen_name=fab13santiago&count=1", function(data) {
var tweet = linkify(data[0].text);
$('.tweet').html(tweet);
});
function linkify(inputText) {
var replacedText, replacePattern1, replacePattern2, replacePattern3;
//URLs starting with http://, https://, or ftp://
replacePattern1 = /(\b(https?|ftp):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/gim;
replacedText = inputText.replace(replacePattern1, '<a href="$1" target="_blank">$1</a>');
//URLs starting with "www." (without // before it, or it'd re-link the ones done above).
replacePattern2 = /(^|[^\/])(www\.[\S]+(\b|$))/gim;
replacedText = replacedText.replace(replacePattern2, '$1<a href="http://$2" target="_blank">$2</a>');
//Change email addresses to mailto:: links.
replacePattern3 = /(([a-zA-Z0-9\-\_\.])+@[a-zA-Z\_]+?(\.[a-zA-Z]{2,6})+)/gim;
replacedText = replacedText.replace(replacePattern3, '<a href="mailto:$1">$1</a>');
return replacedText;
} |
const SongFormatterMixin = {
getSongName: function(song) {
if (song.hasOwnProperty("name")) {
return song.name;
} else {
var urlSplit = song.url.split("/");
return urlSplit[urlSplit.length - 1];
}
}
}
export default SongFormatterMixin |
'use strict';
var translator = require('../lib/translator');
describe('Translator', function() {
var itemData;
var translateHook;
beforeEach(function() {
itemData = { name: 'itemOne' };
translateHook = jasmine.createSpy('translateHook').andReturn(itemData);
delete translator.item;
});
describe('ruleFor', function() {
it('throws on non function', function() {
expect(function() {
translator.ruleFor('item', 'invalid hook');
}).toThrow();
expect(translator.item).not.toBeDefined();
});
it('assigns a rule', function() {
translator.ruleFor('item', translateHook);
expect(translator.item).toEqual(jasmine.any(Function));
});
});
describe('to', function() {
function ruleForItem(otherItem) {
return {
name: otherItem.key
};
}
beforeEach(function() {
translator.ruleFor('item', ruleForItem);
});
it('returns valid value for known name', function() {
var converted = translator.to('item', { key: 'test'});
expect(converted).toEqual({ name: 'test' });
});
describe('errors', function() {
function validateData(data) {
expect(function() {
translator.translate('item', data);
}).toThrow();
}
it('throws on invalid object data', function() {
['data', 123, [], null, undefined ].forEach(validateData);
});
it('throws on invalid hook return value', function() {
translator.ruleFor('item', function() {});
expect(function() {
translator.translate('item', {});
}).toThrow();
});
it('throws on nonexistent rule call', function() {
expect(function() {
translator.translate('nonexistent', {});
}).toThrow();
});
});
});
});
|
var FileRequest, Request, fs,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
fs = require('fs');
Request = require('./request');
FileRequest = (function(_super) {
__extends(FileRequest, _super);
function FileRequest() {
return FileRequest.__super__.constructor.apply(this, arguments);
}
FileRequest.prototype.getContent = function(callback) {
return callback(null, fs.readFileSync(this.parsedUrl.path).toString());
};
return FileRequest;
})(Request);
module.exports = FileRequest;
|
#!/usr/bin/env node
// requires
require('console.table')
var fs = require('fs')
var program = require('commander')
var wc_db = require('wc_db')
var qpm_media = require('../')
var solidbot = require('solidbot');
/**
* version as a command
*/
function bin(argv) {
// setup config
var config = require('../config/config.js')
program
.option('-d, --database <database>', 'Database')
.parse(argv)
var defaultDatabase = 'media'
config.database = program.database || config.database || defaultDatabase
var uri = process.argv[2] || ''
params = {}
params.uri = uri
qpm_media.getUserId(params).then(function(ret){
console.log(ret.ret)
ret.conn.close()
}).catch(function (err) {
console.error(err)
})
}
// If one import this file, this is a module, otherwise a library
if (require.main === module) {
bin(process.argv)
}
module.exports = bin
|
var CILJS = require("../CilJs.Runtime/Runtime");
var asm1 = {};
var asm = asm1;
var asm0 = CILJS.findAssembly("mscorlib");
asm.FullName = "MethodInfoInvoke.cs.ciljs, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null";/* System.String A.X(String)*/
asm.x6000002 = function X(arg0, arg1)
{
var t0;
var loc0;
t0 = asm0["System.Object"]();
/* IL_00: nop */
/* IL_01: ldarg.1 */
/* IL_02: ldc.i4.0 */
/* IL_03: newarr System.Object */
/* IL_08: call Void WriteLine(System.String, System.Object[]) */
asm0.x6000073(arg1,CILJS.newArray(t0,0));
/* IL_0D: nop */
/* IL_0E: ldarg.0 */
/* IL_0F: ldfld String Y */
/* IL_14: ldarg.1 */
/* IL_15: call String Concat(System.String, System.String) */
/* IL_1A: stloc.0 */
loc0 = asm0.x60000bb(arg0.AY,arg1);
/* IL_1D: ldloc.0 */
/* IL_1E: ret */
return loc0;
};;/* A..ctor(String)*/
asm.x6000001 = function _ctor(arg0, arg1)
{
/* IL_00: ldarg.0 */
/* IL_01: call Void .ctor() */
/* IL_06: nop */
/* IL_07: nop */
/* IL_08: ldarg.0 */
/* IL_09: ldarg.1 */
/* IL_0A: stfld String Y */
arg0.AY = arg1;
/* IL_0F: ret */
return ;
};;/* static System.Void Program.Main()*/
asm.x6000003_init = function ()
{
(asm1.A().init)();
asm.x6000003 = asm.x6000003_;
};;
asm.x6000003 = function ()
{
asm.x6000003_init();
return asm.x6000003_();
};;
asm.x6000003_ = function Main()
{
var t0;
var t1;
var st_06;
var st_07;
var st_08;
var st_09;
var st_0A;
var st_0B;
var st_0C;
var st_0D;
var st_0E;
var st_0F;
var loc0;
CILJS.initBaseTypes();
t0 = asm1.A();
t1 = asm0["System.Object"]();
/* IL_00: nop */
/* IL_01: ldtoken A */
/* IL_06: call Type GetTypeFromHandle(System.RuntimeTypeHandle) */
/* IL_0B: call TypeInfo GetTypeInfo(System.Type) */
/* IL_10: callvirt MethodInfo[] GetMethods() */
/* IL_15: ldc.i4.0 */
/* IL_16: ldelem.ref */
/* IL_17: stloc.0 */
loc0 = CILJS.ldelemRef(((asm0.x60001c4(asm0.x6000045(CILJS.newHandle(asm0["System.RuntimeTypeHandle"](),t0))).vtable)["asm0.x6000055"])(asm0.x60001c4(asm0.x6000045(CILJS.newHandle(asm0["System.RuntimeTypeHandle"](),t0)))),0);
/* IL_18: ldloc.0 */
st_0C = loc0;
/* IL_19: ldstr Hello */
st_06 = CILJS.newString("Hello");
/* IL_1E: newobj Void .ctor(System.String) */
st_0D = CILJS.newobj(t0,asm1.x6000001,[null, st_06]);
/* IL_23: ldc.i4.1 */
st_07 = 1;
/* IL_24: newarr System.Object */
st_08 = CILJS.newArray(t1,st_07);
/* IL_29: dup */
st_0E = st_09 = st_08;
/* IL_2A: ldc.i4.0 */
st_0A = 0;
/* IL_2B: ldstr World */
st_0B = CILJS.newString("World");
/* IL_30: stelem.ref */
CILJS.stelemRef(st_09,st_0A,st_0B);
/* IL_31: callvirt Object Invoke(System.Object, System.Object[]) */
st_0F = asm0.x60001c0(st_0C,st_0D,st_0E);
/* IL_36: call Void WriteLine(System.Object) */
asm0.x6000072(st_0F);
/* IL_3B: nop */
/* IL_3C: ret */
return ;
};/* Program..ctor()*/
asm.x6000004 = function _ctor(arg0)
{
/* IL_00: ldarg.0 */
/* IL_01: call Void .ctor() */
/* IL_06: nop */
/* IL_07: ret */
return ;
};;
asm.A = CILJS.declareType(
[],
function ()
{
return asm0["System.Object"]();
},
function (type)
{
type.init = CILJS.nop;
CILJS.initType(type,asm,"A",false,false,false,false,false,[],[
[asm1, "x6000002", "X"]
],asm0["System.Object"](),CILJS.isInstDefault(type),Array,"asm1.t2000002",null);
type.TypeMetadataName = "asm1.t2000002";
CILJS.declareVirtual(type,"asm0.x600009b",asm0,"x600009b");
CILJS.declareVirtual(type,"asm0.x600009e",asm0,"x600009e");
CILJS.declareVirtual(type,"asm0.x600009f",asm0,"x600009f");
},
function ()
{
return function A()
{
A.init();
this.AY = null;
};
});
asm.Program = CILJS.declareType(
[],
function ()
{
return asm0["System.Object"]();
},
function (type)
{
type.init = CILJS.nop;
CILJS.initType(type,asm,"Program",false,false,false,false,false,[],[],asm0["System.Object"](),CILJS.isInstDefault(type),Array,"asm1.t2000003",null);
type.TypeMetadataName = "asm1.t2000003";
CILJS.declareVirtual(type,"asm0.x600009b",asm0,"x600009b");
CILJS.declareVirtual(type,"asm0.x600009e",asm0,"x600009e");
CILJS.declareVirtual(type,"asm0.x600009f",asm0,"x600009f");
},
function ()
{
return function Program()
{
Program.init();
};
});
asm.entryPoint = asm.x6000003;
CILJS.declareAssembly("MethodInfoInvoke.cs.ciljs",asm);
if (typeof module != "undefined"){
module.exports = asm1;
}
//# sourceMappingURL=MethodInfoInvoke.cs.ciljs.exe.js.map
|
module.exports = env => {
let config;
if (!env || env.dev) {
config = require('./config/webpack.dev');
} else if (env.dist) {
config = require('./config/webpack.dist');
} else if (env.prod) {
config = require('./config/webpack.prod');
} else if (env.test) {
config = require('./config/webpack.test');
}
return config;
};
|
var module = angular.module('chatControllerModule', ['chatServiceModule', 'settingsServiceModule']);
module.controller('ChatController', [ '$scope', 'settingsService', 'chatService', ChatController]);
function ChatController($scope, settingsService, chatService) {
var self = this;
$scope.connected = true;
$scope.ready = false;
self.settingsReady = false;
self.usersReady = false;
self.messagesReady = false;
$scope.connect = function() {
chatService.connect();
};
$scope.openSettings = settingsService.openSettings;
$scope.$on('connectionUpdated', function() {
$scope.connected = chatService.connected;
});
$scope.$on('settingsLoaded', function(event, settings) {
self.settingsReady = true;
$scope.settings = settings;
$scope.ready = self.settingsReady && self.usersReady && self.messagesReady;
});
$scope.$on('connectedUsersUpdated', function() {
self.usersReady = true;
$scope.ready = self.settingsReady && self.usersReady && self.messagesReady;
});
$scope.$on('messagesUpdated', function() {
self.messagesReady = true;
$scope.ready = self.settingsReady && self.usersReady && self.messagesReady;
});
} |
var group__CMSIS__RTOS__SemaphoreMgmt_structosSemaphoreAttr__t =
[
[ "name", "group__CMSIS__RTOS__SemaphoreMgmt.html#ab74e6bf80237ddc4109968cedc58c151", null ],
[ "attr_bits", "group__CMSIS__RTOS__SemaphoreMgmt.html#a6e93b49cb79c12f768d72580c7731f30", null ],
[ "cb_mem", "group__CMSIS__RTOS__SemaphoreMgmt.html#a1e100dc33d403841ed3c344e3397868e", null ],
[ "cb_size", "group__CMSIS__RTOS__SemaphoreMgmt.html#aa55a4335d12dc2785dc00fdc292d1159", null ]
]; |
define('ember-bootstrap/components/bs-collapse', ['exports', 'ember'], function (exports, _ember) {
'use strict';
var computed = _ember['default'].computed;
var observer = _ember['default'].observer;
/**
An Ember component that mimics the behaviour of Bootstrap's collapse.js plugin, see http://getbootstrap.com/javascript/#collapse
```hbs
{{#bs-collapse collapsed=collapsed}}
<div class="well">
<h2>Collapse</h2>
<p>This is collapsible content</p>
</div>
{{/bs-collapse}}
```
@class Collapse
@namespace Components
@extends Ember.Component
@public
*/
exports['default'] = _ember['default'].Component.extend({
classNameBindings: ['collapse', 'in', 'collapsing'],
attributeBindings: ['style'],
/**
* Collapsed/expanded state
*
* @property collapsed
* @type boolean
* @default true
* @public
*/
collapsed: true,
/**
* True if this item is expanded
*
* @property active
* @protected
*/
active: false,
collapse: computed.not('transitioning'),
collapsing: computed.alias('transitioning'),
'in': computed.and('collapse', 'active'),
/**
* true if the component is currently transitioning
*
* @property transitioning
* @type boolean
* @protected
*/
transitioning: false,
/**
* @property collapseSize
* @type number
* @protected
*/
collapseSize: null,
/**
* The size of the element when collapsed. Defaults to 0.
*
* @property collapsedSize
* @type number
* @default 0
* @public
*/
collapsedSize: 0,
/**
* The size of the element when expanded. When null the value is calculated automatically to fit the containing elements.
*
* @property expandedSize
* @type number
* @default null
* @public
*/
expandedSize: null,
/**
* Usually the size (height) of the element is only set while transitioning, and reseted afterwards. Set to true to always set a size.
*
* @property resetSizeWhenNotCollapsing
* @type boolean
* @default true
* @private
*/
resetSizeWhenNotCollapsing: true,
/**
* The direction (height/width) of the collapse animation.
* When setting this to 'width' you should also define custom CSS transitions for the width property, as the Bootstrap
* CSS does only support collapsible elements for the height direction.
*
* @property collapseDimension
* @type string
* @default 'height'
* @public
*/
collapseDimension: 'height',
style: computed('collapseSize', function () {
var size = this.get('collapseSize');
var dimension = this.get('collapseDimension');
if (_ember['default'].isEmpty(size)) {
return new _ember['default'].Handlebars.SafeString('');
}
return new _ember['default'].Handlebars.SafeString(dimension + ': ' + size + 'px');
}),
/**
* Triggers the show transition
*
* @method show
* @protected
*/
show: function show() {
var complete = function complete() {
this.set('transitioning', false);
if (this.get('resetSizeWhenNotCollapsing')) {
this.set('collapseSize', null);
}
this.sendAction('didShow');
};
this.sendAction('willShow');
this.setProperties({
transitioning: true,
collapseSize: this.get('collapsedSize'),
active: true
});
if (!_ember['default'].$.support.transition) {
return complete.call(this);
}
this.$().one('bsTransitionEnd', _ember['default'].run.bind(this, complete))
// @todo: make duration configurable
.emulateTransitionEnd(350);
_ember['default'].run.next(this, function () {
if (!this.get('isDestroyed')) {
this.set('collapseSize', this.getExpandedSize('show'));
}
});
},
/**
* Get the size of the element when expanded
*
* @method getExpandedSize
* @param $action
* @return {Number}
* @private
*/
getExpandedSize: function getExpandedSize($action) {
var expandedSize = this.get('expandedSize');
if (_ember['default'].isPresent(expandedSize)) {
return expandedSize;
}
var collapseElement = this.$();
var prefix = $action === 'show' ? 'scroll' : 'offset';
var measureProperty = _ember['default'].String.camelize(prefix + '-' + this.get('collapseDimension'));
return collapseElement[0][measureProperty];
},
/**
* Triggers the hide transition
*
* @method hide
* @protected
*/
hide: function hide() {
var complete = function complete() {
this.set('transitioning', false);
if (this.get('resetSizeWhenNotCollapsing')) {
this.set('collapseSize', null);
}
this.sendAction('didHide');
};
this.sendAction('willHide');
this.setProperties({
transitioning: true,
collapseSize: this.getExpandedSize('hide'),
active: false
});
if (!_ember['default'].$.support.transition) {
return complete.call(this);
}
this.$().one('bsTransitionEnd', _ember['default'].run.bind(this, complete))
// @todo: make duration configurable
.emulateTransitionEnd(350);
_ember['default'].run.next(this, function () {
if (!this.get('isDestroyed')) {
this.set('collapseSize', this.get('collapsedSize'));
}
});
},
_onCollapsedChange: observer('collapsed', function () {
var collapsed = this.get('collapsed');
var active = this.get('active');
if (collapsed !== active) {
return;
}
if (collapsed === false) {
this.show();
} else {
this.hide();
}
}),
_onInit: _ember['default'].on('init', function () {
this.set('active', !this.get('collapsed'));
}),
_updateCollapsedSize: observer('collapsedSize', function () {
if (!this.get('resetSizeWhenNotCollapsing') && this.get('collapsed') && !this.get('collapsing')) {
this.set('collapseSize', this.get('collapsedSize'));
}
}),
_updateExpandedSize: observer('expandedSize', function () {
if (!this.get('resetSizeWhenNotCollapsing') && !this.get('collapsed') && !this.get('collapsing')) {
this.set('collapseSize', this.get('expandedSize'));
}
})
});
}); |
var item_8php =
[
[ "fix_attached_file_permissions", "item_8php.html#a3daae7944f737bd30412a0d042207c0f", null ],
[ "fix_attached_photo_permissions", "item_8php.html#a7b63a9d0cd02096e17dcf11f4afa7c10", null ],
[ "handle_tag", "item_8php.html#abd0e603a6696051af16476eb968d52e7", null ],
[ "item_content", "item_8php.html#a764bbb2e9a885a86fb23d0b5e4a09221", null ],
[ "item_post", "item_8php.html#a693cd09805755ab85bbb5ecae69a48c3", null ]
]; |
'use strict';
// Development specific configuration
// ==================================
module.exports = {
// MongoDB connection options
mongo: {
uri: 'mongodb://localhost/huecommand-dev'
},
seedDB: true
};
|
function IndexedLinkedList() {
this.list = {};
this.length = 0;
this.head = null;
this.tail = null;
}
/**
* Remove from head
*/
IndexedLinkedList.prototype.dequeue = function() {
return this._removeItem(this.head);
};
/**
* Remove item at given index
* @param index
*/
IndexedLinkedList.prototype.remove = function(index) {
this._removeItem(this.list[index]);
};
/**
* Add at head
* @param index
* @param data
*/
IndexedLinkedList.prototype.push = function(index, data) {
var item = this._resetIndex(index, data);
// Link it to the list
if(this.head != null)
this.head.prev = item;
item.prev = null;
item.next = this.head;
this.head = item;
if(this.length == 0)
this.tail = item;
// Change the list length
this.length++;
};
/**
* Add at tail
* @param index
* @param data
*/
IndexedLinkedList.prototype.enqueue = function(index, data) {
var item = this._resetIndex(index, data);
// Link it to the list
if(this.tail != null)
this.tail.next = item;
item.next = null;
item.prev = this.tail;
this.tail = item;
if(this.length == 0)
this.head = item;
// Change the list length
this.length++;
};
/**
* Unlink the item from the list, if it exists
* @param index
* @param data
* @private
*/
IndexedLinkedList.prototype._resetIndex = function(index, data) {
// Remove the item if it exists
try {
this.remove(index);
}
catch(error) {}
// Add the item to the list
return this._set(index, data);
};
/**
* Set the data for an item; create the item if it doesn't exist
* @param index
* @param data
* @private
*/
IndexedLinkedList.prototype._set = function(index, data) {
if(typeof this.list[index] == 'object') // item already exists
this.list[index].data = data;
else {
this.list[index] = {
data: data,
next: undefined,
prev: undefined
}
}
return this.list[index];
};
/**
* Remove given item from the list
* @param item
* @returns {*|string|CanvasPixelArray|Object[]}
* @private
*/
IndexedLinkedList.prototype._removeItem = function(item) {
if(typeof item != 'object' || item == null)
throw new Error('undefined_item');
else {
// Set next item's prev to current item's prev
if(item.next == null) // item is at tail
this.tail = item.prev;
else // item is not at tail
item.next.prev = item.prev;
if(item.prev == null) // item is at head
this.head = item.next;
else // item is not at head
item.prev.next = item.next;
this.length--;
return item.data;
}
};
module.exports = function() {
return new IndexedLinkedList();
}; |
/**
* @author: @AngularClass
*/
const webpack = require('webpack');
const helpers = require('./helpers');
/*
* Webpack Plugins
*/
// problem with copy-webpack-plugin
const AssetsPlugin = require('assets-webpack-plugin');
const NormalModuleReplacementPlugin = require('webpack/lib/NormalModuleReplacementPlugin');
const ContextReplacementPlugin = require('webpack/lib/ContextReplacementPlugin');
const CommonsChunkPlugin = require('webpack/lib/optimize/CommonsChunkPlugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ForkCheckerPlugin = require('awesome-typescript-loader').ForkCheckerPlugin;
const HtmlWebpackPlugin = require('html-webpack-plugin');
const LoaderOptionsPlugin = require('webpack/lib/LoaderOptionsPlugin');
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');
/*
* Webpack Constants
*/
const HMR = helpers.hasProcessFlag('hot');
const METADATA = {
title: 'Angular2 Webpack Starter by @gdi2290 from @AngularClass',
baseUrl: '/',
isDevServer: helpers.isWebpackDevServer()
};
/*
* Webpack configuration
*
* See: http://webpack.github.io/docs/configuration.html#cli
*/
module.exports = function (options) {
isProd = options.env === 'production';
return {
/*
* Cache generated modules and chunks to improve performance for multiple incremental builds.
* This is enabled by default in watch mode.
* You can pass false to disable it.
*
* See: http://webpack.github.io/docs/configuration.html#cache
*/
//cache: false,
/*
* The entry point for the bundle
* Our Angular.js app
*
* See: http://webpack.github.io/docs/configuration.html#entry
*/
entry: {
'polyfills': './src/polyfills.browser.ts',
'vendor': './src/vendor.browser.ts',
'main': './src/main.browser.ts'
},
/*
* Options affecting the resolving of modules.
*
* See: http://webpack.github.io/docs/configuration.html#resolve
*/
resolve: {
/*
* An array of extensions that should be used to resolve modules.
*
* See: http://webpack.github.io/docs/configuration.html#resolve-extensions
*/
extensions: ['.ts', '.js', '.json'],
// An array of directory names to be resolved to the current directory
modules: [helpers.root('src'), helpers.root('node_modules')],
},
/*
* Options affecting the normal modules.
*
* See: http://webpack.github.io/docs/configuration.html#module
*/
module: {
rules: [
/*
* Typescript loader support for .ts and Angular 2 async routes via .async.ts
* Replace templateUrl and stylesUrl with require()
*
* See: https://github.com/s-panferov/awesome-typescript-loader
* See: https://github.com/TheLarkInn/angular2-template-loader
*/
{
test: /\.ts$/,
use: [
'@angularclass/hmr-loader?pretty=' + !isProd + '&prod=' + isProd,
'awesome-typescript-loader',
'angular2-template-loader',
'angular-router-loader'
],
exclude: [/\.(spec|e2e)\.ts$/]
},
/*
* Json loader support for *.json files.
*
* See: https://github.com/webpack/json-loader
*/
{
test: /\.json$/,
use: 'json-loader'
},
/*
* to string and css loader support for *.css files
* Returns file content as string
*
*/
{
test: /\.css$/,
use: ['to-string-loader', 'css-loader']
},
/* Raw loader support for *.html
* Returns file content as string
*
* See: https://github.com/webpack/raw-loader
*/
{
test: /\.html$/,
use: 'raw-loader',
exclude: [helpers.root('src/index.html')]
},
/* File loader for supporting images, for example, in CSS files.
*/
{
test: /\.(jpg|png|gif)$/,
use: 'file-loader'
},
],
},
/*
* Add additional plugins to the compiler.
*
* See: http://webpack.github.io/docs/configuration.html#plugins
*/
plugins: [
new AssetsPlugin({
path: helpers.root('dist'),
filename: 'webpack-assets.json',
prettyPrint: true
}),
/*
* Plugin: ForkCheckerPlugin
* Description: Do type checking in a separate process, so webpack don't need to wait.
*
* See: https://github.com/s-panferov/awesome-typescript-loader#forkchecker-boolean-defaultfalse
*/
new ForkCheckerPlugin(),
/*
* Plugin: CommonsChunkPlugin
* Description: Shares common code between the pages.
* It identifies common modules and put them into a commons chunk.
*
* See: https://webpack.github.io/docs/list-of-plugins.html#commonschunkplugin
* See: https://github.com/webpack/docs/wiki/optimization#multi-page-app
*/
new CommonsChunkPlugin({
name: ['polyfills', 'vendor'].reverse()
}),
/**
* Plugin: ContextReplacementPlugin
* Description: Provides context to Angular's use of System.import
*
* See: https://webpack.github.io/docs/list-of-plugins.html#contextreplacementplugin
* See: https://github.com/angular/angular/issues/11580
*/
new ContextReplacementPlugin(
// The (\\|\/) piece accounts for path separators in *nix and Windows
/angular(\\|\/)core(\\|\/)src(\\|\/)linker/,
helpers.root('src'), // location of your src
{
// your Angular Async Route paths relative to this root directory
}
),
/*
* Plugin: CopyWebpackPlugin
* Description: Copy files and directories in webpack.
*
* Copies project static assets.
*
* See: https://www.npmjs.com/package/copy-webpack-plugin
*/
new CopyWebpackPlugin([
{ from: 'src/assets', to: 'assets' },
{ from: 'src/meta'},
{ from: 'node_modules/bootstrap-material-design/dist', to: 'assets/bootstrap-material-design'}
]),
/*
* Plugin: HtmlWebpackPlugin
* Description: Simplifies creation of HTML files to serve your webpack bundles.
* This is especially useful for webpack bundles that include a hash in the filename
* which changes every compilation.
*
* See: https://github.com/ampedandwired/html-webpack-plugin
*/
new HtmlWebpackPlugin({
template: 'src/index.html',
title: METADATA.title,
chunksSortMode: 'dependency',
metadata: METADATA,
inject: 'head'
}),
/*
* Plugin: ScriptExtHtmlWebpackPlugin
* Description: Enhances html-webpack-plugin functionality
* with different deployment options for your scripts including:
*
* See: https://github.com/numical/script-ext-html-webpack-plugin
*/
new ScriptExtHtmlWebpackPlugin({
defaultAttribute: 'defer'
}),
/**
* Plugin LoaderOptionsPlugin (experimental)
*
* See: https://gist.github.com/sokra/27b24881210b56bbaff7
*/
new LoaderOptionsPlugin({}),
// Fix Angular 2
new NormalModuleReplacementPlugin(
/facade(\\|\/)async/,
helpers.root('node_modules/@angular/core/src/facade/async.js')
),
new NormalModuleReplacementPlugin(
/facade(\\|\/)collection/,
helpers.root('node_modules/@angular/core/src/facade/collection.js')
),
new NormalModuleReplacementPlugin(
/facade(\\|\/)errors/,
helpers.root('node_modules/@angular/core/src/facade/errors.js')
),
new NormalModuleReplacementPlugin(
/facade(\\|\/)lang/,
helpers.root('node_modules/@angular/core/src/facade/lang.js')
),
new NormalModuleReplacementPlugin(
/facade(\\|\/)math/,
helpers.root('node_modules/@angular/core/src/facade/math.js')
),
],
/*
* Include polyfills or mocks for various node stuff
* Description: Node configuration
*
* See: https://webpack.github.io/docs/configuration.html#node
*/
node: {
global: true,
crypto: 'empty',
process: true,
module: false,
clearImmediate: false,
setImmediate: false
}
};
}
|
module.exports = move;
var fse = require('fs-extra');
function move(src, dest, options, cb, self) {
if (!cb) { return move(src, dest, {}, options, this); }
if (!self) { self = this; }
var absPathSrc = self.pathHelper.absolutePath(src);
var relPathSrc = self.pathHelper.relativePath(absPathSrc);
var absPathDest = self.pathHelper.absolutePath(dest);
var relPathDest = self.pathHelper.relativePath(absPathDest);
fse.move(absPathSrc, absPathDest, function(err) {
if (err) { return cb(err); }
cb(null, {
src: relPathSrc,
dest: relPathDest
});
});
} |
import babel from "rollup-plugin-babel";
module.exports = {
input: "src/DiodePublic.js",
output: {
file: "lib/DiodePublic.js",
format: "cjs"
},
external: [
"react",
"react-is",
"lodash.mergewith",
"deep-extend",
"object-assign",
"hoist-non-react-statics",
"lodash.find"
],
plugins: [
babel({
exclude: "node_modules/**"
})
]
};
|
var fs = require('fs');
var path = require('path');
var probe = require('node-ffprobe');
var db = require('./index').db;
var Pila = require('./pila');
var ModelHelpers = require('../../lib/model_helpers');
var hostname = ModelHelpers.hostname;
var Audio = {
all: function(callback) {
Pila.findByName(hostname, (pila) => {
callback(pila.audios);
})
},
findBySlug: function(slug, callback) {
Pila.findByName(hostname, (pila) => {
callback(pila.audios[slug]);
})
},
delete: function(slug, callback) {
Pila.findByName(hostname, (pila) => {
var audio = pila.audios[slug];
console.log('Audio.delete audio.name:', audio.name, 'from:', audio.path);
// Actually remove file.
fs.unlink(audio.path);
// Update pila.audios.
delete pila.audios[slug];
Pila.updatePila(pila, (pila) => {
// Return result.
callback({message: 'Audio successfully deleted.', audios: pila.audios});
})
})
},
add: function(name, path, baseUrl, callback) {
var repository = {name: name, path: path};
repository.slug = name.replace(/\s/g, '_').replace(/\./g, '_').toLowerCase();
this.getLocalFiles(path, (err, files) => {
if (err) throw err;
Pila.findByName(hostname, (pila) => {
// If no repositories create empty object.
if (!pila.repositories) {
pila.repositories = {};
}
// If repository isn't in the repositories add it.
if (pila.repositories[repository.slug] == undefined) {
pila.repositories[repository.slug] = repository;
}
if (files.length == 0) {
pila.audios = {};
} else {
console.log('files.length:', files.length);
var i, j, tempFiles, chunk = 200;
for (i=0, j = files.length; i < j; i += chunk) {
tempFiles = files.slice(i, i + chunk);
//console.log(tempFiles);
// Use a counter to execute the res.json.
var counter = 0;
tempFiles.forEach((file) => {
this.getAudioDetails(file, repository, baseUrl, (audio) => {
console.log('audio.slug:', audio.slug);
pila.audios[audio.slug] = audio;
counter++;
if (counter == tempFiles.length) {
Pila.updatePila(pila, (pila) => {
console.log('Updated me with ' + tempFiles.length + ' audios...');
})
callback(pila.audios);
}
});
})
}
}
});
});
},
update: function(audio, callback) {
Pila.findByName(hostname, (pila) => {
pila.audios[audio.slug] = audio;
Pila.updatePila(pila, (pila) => {
callback({message: 'Updated audio: ' + audio.slug, audio: audio});
})
})
},
getAudioDetails: function(file, repository, baseUrl, callback) {
var audio = {};
var parts = file.split('/');
var filename = parts[parts.length - 1];
audio.slug = filename.slice(0, file.length - 4).replace(/\s/g, '_').replace(/\./g, '_').toLowerCase();
audio.repository = repository;
audio.playbackTime = 0;
console.log('probing file:', file);
probe(file, function(err, probeData) {
if (err) {
console.log('probe err:', err);
audio.name = filename;
audio.path = file;
audio.duration = 0;
audio.type = 'audio';
audio.httpUrl = baseUrl + '/audios/' + audio.slug;
callback(audio);
} else {
audio.name = probeData.filename;
audio.path = probeData.file;
if (probeData.format) {
audio.duration = probeData.format.duration;
} else {
audio.duration = 0;
}
audio.type = 'audio';
audio.httpUrl = baseUrl + '/audios/' + audio.slug;
callback(audio);
}
});
},
getLocalFiles: function(dir, done) {
var results = [];
fs.readdir(dir, (err, list) => {
if (err) return done(err);
var pending = list.length;
if (!pending) return done(null, results);
list.forEach((file) => {
file = path.resolve(dir, file);
fs.stat(file, (err, stat) => {
if (stat && stat.isDirectory()) {
this.getLocalFiles(file, (err, res) => {
results = results.concat(res);
if (!--pending) done(null, results);
});
} else {
var ext = file.substr(file.length - 4);
if (/\.mp3|\.m4a|\.mp4|\.ogg|\.mkv|\.wav/g.exec(ext) !== null) {
// return path + '/' + file;
results.push(file);
}
if (!--pending) done(null, results);
}
});
});
});
},
}
module.exports = Audio;
|
define(function (require) {
var plot_core = require("plot_core");
var sys = require("sys");
var common = require("common");
var dbg = require("dbg");
var res = require("res");
var pp = res.pp;
var people = [];
var exports = {
running: {},
};
var sx = sys.sx;
var sy = sys.sy;
var btn_gap = 50;
var touched = false;
var tc_pre_things = {};
var touch_enable = true;
var running = false;
var result = {
};
exports.result = result;
var message;
var gap = {
def: 70,
fast: 40,
slow: 200,
}
exports.gap = gap;
var people_move_time = 500;
function touch_wait(cb) {
var a = setInterval(
function () {
if (touched) {
touched = false;
if (touch_enable) {
clearInterval(a);
cb();
}
}
}, 100
)
};
var rnd;
rnd.today = new Date();
rnd.seed = rnd.today.getTime();
function rnd() {
rnd.seed = (rnd.seed * 9301 + 49297) % 233280;
return rnd.seed / (233280.0);
};
function rand(min, max) {
// console.log(min,max)
var number = max - min + 1
number = Math.ceil(rnd() * number) + min - 1
return number;
};
exports.rand = rand;
function message_create() {
var t = $('#chat_text')
var container = $("#chat_content");
var name_img = $('#name_all')
var skip;
t.fadeOut_real = t.fadeOut;
t.fadeOut = function () {
// console.log("faddeee",arguments)
name_img.fadeOut(arguments);
t.fadeOut_real.apply(t, arguments);
}
t.setNString = function (text, cb, gap) {
// console.log($("<label>" + text + "</label>").children())
container.html("")
var ele = $("<label>" + text + "</label>");
var data = [];
var running = true;
var text_bak = text;
var ret = function (cmd) {
switch (cmd) {
case "fast":
running = false;
container[0].innerHTML = text_bak;
cb();
break;
}
}
function push(a) {
data.push(a)
}
text = ele[0].innerHTML;
ele.children().each(function () {
// console.log(1,text);
text = text.split(this.outerHTML)
// console.log(2,text);
push(text[0])
push(this)
var a = "";
var start = true;
for (var i = 1; i < text.length; i++) {
if (start) {
start = false;
} else {
a += this.outerHTML;
}
a += text[i];
// console.log("a",a);
}
text = a;
// console.log(3,text);
})
push(text)
var index = 0;
// var gap = 200;
function play() {
if (index == data.length) {
cb();
return;
}
var thing = data[index];
if (thing) {
switch (typeof (thing)) {
case "string":
function t_put(ttt) {
// console.info(t);
container[0].innerHTML += ttt;
}
var j = 0;
function word_play() {}
word_play();
for (var i = 0; i < thing.length; i++) {
setTimeout(
function () {
if (!running)
return;
t_put(thing[j]);
j++;
}, gap * i
)
}
setTimeout(
function () {
if (!running)
return;
index++;
play();
}, gap * thing.length
)
break;
case "object":
var m = thing.innerHTML;
// console.log(thing.outerHTML)
thing.innerHTML = "";
thing = $(thing)
container.append(thing);
var j = 0;
var len = m.length;
// console.log(len);
for (var i = 0; i < len; i++) {
setTimeout(
function () {
if (!running)
return;
thing.text(thing.text() + m[j]);
j++;
}, gap * i
)
}
setTimeout(
function () {
if (!running)
return;
index++;
play();
}, gap * len
)
break;
}
} else {
index++;
play();
}
}
play();
return ret;
}
var charIndex = -1;
var stringLength = 0;
var inputText;
var text_content = $("#chat_text_content");
var name_text = $("#name_content")
var name_all = $("#name_all")
var name;
name_all.hide()
t.setName = function (text) {
if (text) {
name = text;
name_all.show()
name_text.text(name)
} else {
name_all.hide()
name_text.text("")
}
}
var currentStyle = 'inline';
return t;
}
function plot_resume(ret) {
setTimeout(function () {
plot_core.resume(ret);
}, 0)
}
exports.tm = function () {
touch_enable = false;
var arg_len = 0;
var it;
if (arguments[0] && !arguments[1] && Array.isArray(arguments[0])) {
it = arguments[0];
} else {
for (var i in arguments) {
var empty = true;
for (var j in arguments[i]) {
empty = false;
break;
}
if (empty)
arguments[i] = undefined
else {
arg_len++;
}
}
arguments.length = arg_len;
it = arguments;
}
var len = it.length
var menu_value = false;
var div_btn = $("#div-btn");
var cb = function (index, v) {
div_btn.empty();
setTimeout(function () {
touched = false;
}, 0);
// var js_arg={};
// js_arg = {
// index: index,
// value: v
// };
// {
// index:index,
// v:v
// }
// plot_resume({
// index:index,
// value:v
// });
plot_resume(index);
}
function menu_btn_create(index, content, len) {
var id = "menu_btn" + index
// console.log(typeof (content))
switch (typeof (content)) {
case "string":
var vertical_offset = 0;
if (message.css("display") != "none") {
vertical_offset = 180;
}
var btn = $(`<button id='${id}' class="menu_btn btn btn-primary">
</button>`);
btn.data("index", index)
.css("top", (sy - vertical_offset) * 0.5 + ((len - 1) / (-2) + index) * btn_gap + "px")
.html(content)
.click(function () {
menu_value = parseInt($(this).data("index"));
cb(index, content);
})
div_btn.append(btn)
break;
case "object":
switch (content.type) {
case undefined:
console.log('you should define the "type" key in the object params of tm');
break;
case "btn":
case "disabled_btn":
var disabled = content.type == "btn" ? "" : "disabled";
var vertical_offset = 0;
if (message.css("display") != "none") {
vertical_offset = 210;
}
var btn = $(`<button id='${id}' class="menu_btn btn btn-primary ${disabled}">
</button>`);
btn.css("top", (sy - vertical_offset) * 0.5 + ((len - 1) / (-2) + index) * btn_gap + "px")
.data("index", index)
.html(content.data)
.click(function () {
menu_value = parseInt($(this).data("index"));
cb(index, content.data);
})
div_btn.append(btn)
break;
case "input_with_btn":
var input_id = "menu_btn_" + index;
var input_button = "menu_btn_btn" + index;
var placeholder = "";
var btn = "";
if (content.data.placeholder != undefined) {
placeholder = content.data.placeholder;
}
if (content.data.btn != undefined) {
btn = content.data.btn;
}
var input_div = $(`<div class="input-group">
<input type="text" class="form-control" placeholder="${placeholder}">
<span class="input-group-btn">
<button miao_index="${index}"class="btn btn-default" type="button">${btn}</button>
</span>
</div>`)
input_div.css("top", (sy - 180) * 0.5 + ((len - 1) / (-2) + index) * btn_gap + "px")
// if (content.data.width == undefined) {
// input_div.css("width", "30%")
// } else {
// input_div.css("width", content.data.width)
// }
var input = input_div.find("input")
var index_this = index;
input_div.find("button").click(function () {
menu_value = {
data: input.val(),
index: index_this
}
cb(menu_value.index, menu_value.data);
})
div_btn.append(input_div);
input_div.css("left", "480" - parseInt(input_div.css("width")) / 2 + "px")
break;
default:
break;
}
break;
}
return;
}
for (var i = 0; i < len; i++) {
var btn = menu_btn_create(i, it[i], len)
};
return menu_value;
};
var pp_pre;
exports.tcc = function () {
var args = [].slice.call(arguments, 0);
args.splice(1, 0, pp_pre);
exports.tc.apply(this, args);
}
var tc_fast_mode = false;
exports.tcn = function () {
tc_fast_mode = true;
exports.tc.apply(this, arguments);
}
exports.tc = function (text, name, gapnum, color) {
tc_pre_things.name = name;
tc_pre_things.gapnum = gapnum;
tc_pre_things.color = color;
touched = false;
touch_enable = true;
if (!gapnum) {
gapnum = exports.gap.def
}
if (text) {
text=text.replace(/,/g,",").replace(/\./g,"。").replace(/!/g,"!").replace(/\?/g,"?");
message.show();
if (name) {
pp_pre = name;
switch (typeof (name)) {
case "string":
message.setName(name)
break;
case "object":
message.setName(name.name)
// $("#div-half img").animate({opacity:"0.5"});
// $("#div-half img").css("opacity", 0.5);
// $("#pp" + name.name).animate({opacity:"1"});
// if (name == pp.you)
// break;
$("#div-half img").each(function () {
if ($(this).attr("id") != ("pp" + name.name)) {
$(this).animate({
opacity: "0.5"
}, "fast");
} else {
$(this).animate({
opacity: "1"
}, "fast");
}
})
break;
}
} else {
message.setName(false)
}
} else {
message.hide()
}
var text_processing = true;
function cb1() {
text_processing = false;
if (tc_fast_mode) {
cb2();
tc_fast_mode = false;
}
}
var handle = message.setNString(text, cb1, gapnum)
function cb2() {
if (text_processing) {
// console.log("slkjswer")
handle("fast");
// message.fast();
touch_wait(cb2);
} else {
// $("#div-half img").css("opacity", 1);
console.log("resume");
plot_resume();
}
}
if (dbg.isinfastmode) {
cb2();
} else {
if (name != "跳过") {
// $await(touch_wait())
if (!tc_fast_mode)
touch_wait(cb2);
}
}
}
exports.th = function () {
if (dbg.isinfastmode) {
var people_move_time_this = 10;
} else {
people_move_time_this = people_move_time;
}
//message.setName(name.name)
var input = arguments;
var remove = false
var show = false
for (var j in people) {
var found = false;
if (!people[j]) {
continue;
}
for (var i in input) {
if (people[j].name == input[i].name) {
found = true
continue;
}
}
if (!found) {
people[j].fadeOut(people_move_time_this, function () {
$(this.remove())
}) //.remove();
people[j].miaoindex = j
people[j] = undefined
remove = true
}
}
if (remove) {
setTimeout(
pp_show, people_move_time_this * 1.2
)
} else {
pp_show();
}
function get_half(name, pos) {
var id = "pp" + name.name
var pp = $(`<img id="${id}" class="pp"/>`)
$("#div-half").append(pp)
pp.attr("indexx", pos)
pp.attr("src", name.half)
pp.css("position", "absolute")
pp.css("top", 40 + "px")
if (pos == 0) {
pp.css("right", "auto");
pp.css("left", pos_covert(pos, pp) + "px")
} else if (pos == 2) {
pp.css("left", "auto");
pp.css("right", pos_covert(0, pp) + "px")
} else {
pp.css("left", 0);
pp.css("right", 0);
}
return pp;
}
function pos_covert(pos, pp) {
var width = parseInt(pp.prop("width"));
var height = parseInt(pp.prop("height"));
if (width < 250)
width = 250;
return (sx / 6 * (pos * 2 + 1)) - width / 2;
}
function pp_show() {
for (let i in input) {
var found = false;
if (!input[i]) {
continue;
}
for (var j in people) {
if (!people[j]) {
continue;
}
if (people[j].name == input[i].name) {
found = true;
//print("found")
if (people[j].pos != i) {
//print("not",i)
show = true
people[j].pos = i
people[j].animate({
left: pos_covert(people[j].pos, people[j]) + "px"
}, people_move_time_this)
}
}
}
if (!found) {
var ppp = get_half(input[i], i)
ppp.hide();
ppp.name = input[i].name
ppp.pos = i;
people[people.length] = ppp
show = true
ppp.fadeIn(people_move_time_this);
}
}
if (show) {
setTimeout(plot_resume, people_move_time_this);
} else {
plot_resume();
}
}
};
var current_background = 0;
var bg;
exports.tmood = function (background) {
var mood = $("#div-mood .mood");
mood.attr("src", background);
function after_touched() {
mood.hide();
plot_resume();
}
if (dbg.isinfastmode) {
after_touched();
} else {
if (name != "跳过") {
// $await(touch_wait())
touch_wait(after_touched);
}
}
}
exports.ts = function (background, time) {
touch_enable = false;
var fadeout_time = 800;
if (dbg.isinfastmode) {
time = 10;
}
// touch_enable = true;
if (time == undefined || time == false) {
time = fadeout_time;
}
if (background == current_background) {
time = 0.01
}
running = true;
message.fadeOut(time);
function get_url(u) {
return `url("${u}")`;
}
if (!current_background) {
bg.hide();
console.log(bg, background)
bg.css("background-image", get_url(background));
console.log(bg, bg.css("background-image"))
bg.fadeIn(time);
setTimeout(function () {
plot_resume();
}, time);
} else {
bg.fadeOut(time)
setTimeout(function () {
bg.css("background-image", get_url(background));
bg.fadeIn(time);
}, time);
setTimeout(function () {
plot_resume();
console.log("ppp");
}, 2 * time + 10);
}
current_background = background;
running = false
}
window.plot = exports;
exports.init = function () {
bg = $("#scene_chat #div-bg");
message = message_create();
$("#scene_chat").on("click", function () {
touched = true;
})
}
return exports;
}) |
'use strict';
;(function() {
var config = require('./config');
var bunyan = require('bunyan');
var formatter = require('bunyan-format');
var format = formatter(config.loggingConfigs);
var streams = [{level: config.consoleLogLevel, stream: format }];
if (config.logToFile) {
streams.push({ level: 'error', path: config.logfile });
}
module.exports = function(name) {
return bunyan.createLogger({
name: (config.logPrefix + name),
streams: streams,
});
};
})();
|
/**
* Copyright (c) 2012 Andreas Madsen
* MIT License
*/
var vows = require('vows'),
assert = require('assert'),
common = require('../common.js'),
prope = require(common.watcher('interface.js'));
common.reset();
function startImmortal(callback) {
prope.createInterface(common.fixture('longlive.js'), {
strategy: 'daemon',
options: {
errorLoop: true
}
}, callback);
}
var monitor = null;
vows.describe('testing simultaneous error').addBatch({
'when starting immortal': {
topic: function () {
var self = this;
startImmortal(function (error, prope) {
monitor = prope;
self.callback(error, prope);
});
},
'no errors should occurre in startup': function (error, monitor) {
assert.ifError(error);
assert.isNull(monitor.error);
}
}
}).addBatch({
'when immortal group is ready': {
topic: function () {
var self = this;
monitor.ready();
monitor.once('process', function () {
self.callback(null, monitor);
});
},
'an error should occurre in this regression': {
topic: function (monitor) {
var self = this;
var pids = common.copy(monitor.pid);
monitor.once('reconnect', function () {
self.callback(null, monitor, pids);
});
},
'the old pump and child process should be dead': function (error, monitor, pids) {
assert.ifError(error);
assert.equal(monitor.pid.daemon, pids.daemon);
assert.isNumber(pids.monitor);
assert.isFalse(common.isAlive(pids.monitor));
assert.isNumber(pids.process);
assert.isFalse(common.isAlive(pids.process));
},
'the error should not contain something': function (error, monitor) {
assert.ifError(error);
assert.equal(monitor.error.indexOf('eeeee'), 0);
assert.ok(monitor.error.length <= (1024*1024) && monitor.error.length > (1024*1000));
}
}
}
}).addBatch({
'when immortal stops': {
topic: function () {
var self = this;
var pids = common.copy(monitor.pid);;
monitor.shutdown(function () {
monitor.close(function () {
setTimeout(function () {
self.callback(null, monitor, pids);
}, 100);
});
});
},
'the immortal group should be dead': function (error, monitor, pid) {
assert.ifError(error);
assert.isNumber(pid.daemon);
assert.isFalse(common.isAlive(pid.daemon));
assert.isNumber(pid.monitor);
assert.isFalse(common.isAlive(pid.monitor));
assert.isNull(pid.process);
}
}
}).exportTo(module);
|
var World = null;
(function () {
"use strict";
// The code below uses https://code.google.com/p/selenium/wiki/WebDriverJs
// https://github.com/assaf/zombie
// http://phantomjs.org/
// https://github.com/LearnBoost/soda
// https://github.com/admc/wd
World = function World(ready) {
var Webdriver = require('../../rtd/webdrivers/cucumber-webdriver.js')('chrome', 2000, 2000);
var Actions = require('./actions.js')(this);
var world = this;
Webdriver.getBrowser(function (browser) {
world.webdriver = Webdriver.driver;
world.browser = browser;
world.actions = Actions;
ready();
});
};
})();
module.exports = {
World: World
};
|
var housingData = require('../../housing.json');
exports.view = function(req, res){
//console.log(housingData);
// get variables from request query
var city = req.query.city.toLowerCase();
var occupants = parseInt(req.query.occupants);
var maxArea = 45 + ((occupants-1)*15);
var cost = (req.query.cost !=='')?parseInt(req.query.cost):0;
// print passed results
console.log("The passed city is: "+ city);
console.log("The passed occupants is: "+ occupants);
console.log("The Max area allowed is: "+ maxArea);
console.log("The passed cost is: "+ cost);
var housingDataLength = housingData.length;
var searchResults = [];
for (i = 0; i < housingDataLength; i++) {
// Get variables of each listing from json file
var listingCity = housingData[i].city.toLowerCase();
var listingArea = housingData[i].area;
var listingCost = housingData[i].cost;
console.log('The city of listing #' + i +' is: '+listingCity);
console.log('The cost of listing #' + i +' is: '+listingCost);
console.log('The area of listing #' + i +' is: '+listingArea);
if (listingCity === city){
console.log("passed city");
if (listingCost <= cost || cost === 0){
console.log("passed cost");
if (listingArea <= maxArea){
console.log("passed cost AND ALL TESTS");
searchResults.push(housingData[i]);
}
}
}
}
res.render('search/all-listingsVB', {
'house': searchResults, 'searchQuery':{"city":city, "occupants":occupants, "cost":cost}});
}; |
var express = require('express');
var mongoose = require('mongoose');
var queries = require('./db/queries.js');
var schema = require('./db/schema.js');
var app = express();
mongoose.connect('mongodb://54.159.218.143:27017/cis450');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log("db connected");
});
app.set('port', (process.env.PORT || 5000));
app.use(express.static(__dirname + '/public'));
app.use(express.static(__dirname + '/bower_components'));
// views is directory for all template files
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.get('/', function(request, response) {
response.render('pages/index');
});
app.get('/api/genres', function(request, response) {
queries.genres().then(function(value) {
response.json(value);
});
});
app.get('/api/songs/:song_id/similar', function(request, response) {
var song_id = request.params.song_id;
if (!song_id) {
response.send('invalid');
} else {
queries.similarSongs(song_id, request.query.n).then(function(value) {
response.json(value);
});
}
});
app.get('/api/songs/name/:song_name/tags', function(request, response) {
var song_name = request.params.song_name;
if (!song_name) {
response.send('invalid');
} else {
queries.songTags(song_name).then(function(value) {
response.json(value);
});
}
});
app.get('/api/songs/:song_id/tags', function(request, response) {
var song_id = request.params.song_id;
if (!song_id) {
response.send('invalid');
} else {
queries.songTagsById(song_id, request.query.n).then(function(value) {
response.json(value);
});
}
});
app.get('/api/artists/:artist_name/songs', function(request, response) {
var artist_name = request.params.artist_name;
if (!artist_name) {
response.send('invalid');
} else {
queries.artistSongs(artist_name).then(function(value) {
response.json(value);
});
}
});
app.get('/api/artists/:artist_name/genres', function(request, response) {
var artist_name = request.params.artist_name;
if (!artist_name) {
response.send('invalid');
} else {
queries.artistGenres(artist_name).then(function(value) {
response.json(value);
});
}
});
app.get('/api/songs/covered', function(request, response) {
queries.commonlyCoveredSongs().then(function(value) {
response.json(value);
});
});
app.get('/api/songs/similar', function(request, response) {
queries.findCommon().then(function(value) {
response.json(value);
});
});
app.get('/api/songs/popular', function(request, response) {
queries.mostPopularSongs().then(function(value) {
response.json(value);
});
});
app.get('/api/autocomplete/songs/:song_name', function(request, response) {
queries.autocompleteSongs(request.params.song_name).then(function(value) {
response.json(value);
});
});
app.get('/api/autocomplete/artists/:artist_name', function(request, response) {
queries.autocompleteArtists(request.params.artist_name).then(function(value) {
response.json(value);
});
});
app.use(function(req, res) {
// support ui router
res.render('pages/index');
});
app.listen(app.get('port'), function() {
console.log('Node app is running on port', app.get('port'));
});
|
const EventEmitter = require('events');
// How to make sure EventEmitter constructor is called? (super keyword)
module.exports = class Greetr extends EventEmitter {
constructor() {
super();
this.greeting = 'Hello'
}
greet(data){
console.log(`${this.greeting} : ${data}`);
this.emit('greet', data);
}
}
|
/*
---
MooTools: the javascript framework
web build:
- http://mootools.net/core/6ee878a38312482d057ff0d6192abbd8
packager build:
- packager build Core/Element.Delegation Core/Request.JSON Core/DOMReady
...
*/
/*
---
name: Core
description: The heart of MooTools.
license: MIT-style license.
copyright: Copyright (c) 2006-2014 [Valerio Proietti](http://mad4milk.net/).
authors: The MooTools production team (http://mootools.net/developers/)
inspiration:
- Class implementation inspired by [Base.js](http://dean.edwards.name/weblog/2006/03/base/) Copyright (c) 2006 Dean Edwards, [GNU Lesser General Public License](http://opensource.org/licenses/lgpl-license.php)
- Some functionality inspired by [Prototype.js](http://prototypejs.org) Copyright (c) 2005-2007 Sam Stephenson, [MIT License](http://opensource.org/licenses/mit-license.php)
provides: [Core, MooTools, Type, typeOf, instanceOf, Native]
...
*/
/*! MooTools: the javascript framework. license: MIT-style license. copyright: Copyright (c) 2006-2014 [Valerio Proietti](http://mad4milk.net/).*/
(function(){
this.MooTools = {
version: '1.5.1',
build: '0542c135fdeb7feed7d9917e01447a408f22c876'
};
// typeOf, instanceOf
var typeOf = this.typeOf = function(item){
if (item == null) return 'null';
if (item.$family != null) return item.$family();
if (item.nodeName){
if (item.nodeType == 1) return 'element';
if (item.nodeType == 3) return (/\S/).test(item.nodeValue) ? 'textnode' : 'whitespace';
} else if (typeof item.length == 'number'){
if ('callee' in item) return 'arguments';
if ('item' in item) return 'collection';
}
return typeof item;
};
var instanceOf = this.instanceOf = function(item, object){
if (item == null) return false;
var constructor = item.$constructor || item.constructor;
while (constructor){
if (constructor === object) return true;
constructor = constructor.parent;
}
/*<ltIE8>*/
if (!item.hasOwnProperty) return false;
/*</ltIE8>*/
return item instanceof object;
};
// Function overloading
var Function = this.Function;
var enumerables = true;
for (var i in {toString: 1}) enumerables = null;
if (enumerables) enumerables = ['hasOwnProperty', 'valueOf', 'isPrototypeOf', 'propertyIsEnumerable', 'toLocaleString', 'toString', 'constructor'];
Function.prototype.overloadSetter = function(usePlural){
var self = this;
return function(a, b){
if (a == null) return this;
if (usePlural || typeof a != 'string'){
for (var k in a) self.call(this, k, a[k]);
if (enumerables) for (var i = enumerables.length; i--;){
k = enumerables[i];
if (a.hasOwnProperty(k)) self.call(this, k, a[k]);
}
} else {
self.call(this, a, b);
}
return this;
};
};
Function.prototype.overloadGetter = function(usePlural){
var self = this;
return function(a){
var args, result;
if (typeof a != 'string') args = a;
else if (arguments.length > 1) args = arguments;
else if (usePlural) args = [a];
if (args){
result = {};
for (var i = 0; i < args.length; i++) result[args[i]] = self.call(this, args[i]);
} else {
result = self.call(this, a);
}
return result;
};
};
Function.prototype.extend = function(key, value){
this[key] = value;
}.overloadSetter();
Function.prototype.implement = function(key, value){
this.prototype[key] = value;
}.overloadSetter();
// From
var slice = Array.prototype.slice;
Function.from = function(item){
return (typeOf(item) == 'function') ? item : function(){
return item;
};
};
Array.from = function(item){
if (item == null) return [];
return (Type.isEnumerable(item) && typeof item != 'string') ? (typeOf(item) == 'array') ? item : slice.call(item) : [item];
};
Number.from = function(item){
var number = parseFloat(item);
return isFinite(number) ? number : null;
};
String.from = function(item){
return item + '';
};
// hide, protect
Function.implement({
hide: function(){
this.$hidden = true;
return this;
},
protect: function(){
this.$protected = true;
return this;
}
});
// Type
var Type = this.Type = function(name, object){
if (name){
var lower = name.toLowerCase();
var typeCheck = function(item){
return (typeOf(item) == lower);
};
Type['is' + name] = typeCheck;
if (object != null){
object.prototype.$family = (function(){
return lower;
}).hide();
}
}
if (object == null) return null;
object.extend(this);
object.$constructor = Type;
object.prototype.$constructor = object;
return object;
};
var toString = Object.prototype.toString;
Type.isEnumerable = function(item){
return (item != null && typeof item.length == 'number' && toString.call(item) != '[object Function]' );
};
var hooks = {};
var hooksOf = function(object){
var type = typeOf(object.prototype);
return hooks[type] || (hooks[type] = []);
};
var implement = function(name, method){
if (method && method.$hidden) return;
var hooks = hooksOf(this);
for (var i = 0; i < hooks.length; i++){
var hook = hooks[i];
if (typeOf(hook) == 'type') implement.call(hook, name, method);
else hook.call(this, name, method);
}
var previous = this.prototype[name];
if (previous == null || !previous.$protected) this.prototype[name] = method;
if (this[name] == null && typeOf(method) == 'function') extend.call(this, name, function(item){
return method.apply(item, slice.call(arguments, 1));
});
};
var extend = function(name, method){
if (method && method.$hidden) return;
var previous = this[name];
if (previous == null || !previous.$protected) this[name] = method;
};
Type.implement({
implement: implement.overloadSetter(),
extend: extend.overloadSetter(),
alias: function(name, existing){
implement.call(this, name, this.prototype[existing]);
}.overloadSetter(),
mirror: function(hook){
hooksOf(this).push(hook);
return this;
}
});
new Type('Type', Type);
// Default Types
var force = function(name, object, methods){
var isType = (object != Object),
prototype = object.prototype;
if (isType) object = new Type(name, object);
for (var i = 0, l = methods.length; i < l; i++){
var key = methods[i],
generic = object[key],
proto = prototype[key];
if (generic) generic.protect();
if (isType && proto) object.implement(key, proto.protect());
}
if (isType){
var methodsEnumerable = prototype.propertyIsEnumerable(methods[0]);
object.forEachMethod = function(fn){
if (!methodsEnumerable) for (var i = 0, l = methods.length; i < l; i++){
fn.call(prototype, prototype[methods[i]], methods[i]);
}
for (var key in prototype) fn.call(prototype, prototype[key], key);
};
}
return force;
};
force('String', String, [
'charAt', 'charCodeAt', 'concat', 'contains', 'indexOf', 'lastIndexOf', 'match', 'quote', 'replace', 'search',
'slice', 'split', 'substr', 'substring', 'trim', 'toLowerCase', 'toUpperCase'
])('Array', Array, [
'pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift', 'concat', 'join', 'slice',
'indexOf', 'lastIndexOf', 'filter', 'forEach', 'every', 'map', 'some', 'reduce', 'reduceRight'
])('Number', Number, [
'toExponential', 'toFixed', 'toLocaleString', 'toPrecision'
])('Function', Function, [
'apply', 'call', 'bind'
])('RegExp', RegExp, [
'exec', 'test'
])('Object', Object, [
'create', 'defineProperty', 'defineProperties', 'keys',
'getPrototypeOf', 'getOwnPropertyDescriptor', 'getOwnPropertyNames',
'preventExtensions', 'isExtensible', 'seal', 'isSealed', 'freeze', 'isFrozen'
])('Date', Date, ['now']);
Object.extend = extend.overloadSetter();
Date.extend('now', function(){
return +(new Date);
});
new Type('Boolean', Boolean);
// fixes NaN returning as Number
Number.prototype.$family = function(){
return isFinite(this) ? 'number' : 'null';
}.hide();
// Number.random
Number.extend('random', function(min, max){
return Math.floor(Math.random() * (max - min + 1) + min);
});
// forEach, each
var hasOwnProperty = Object.prototype.hasOwnProperty;
Object.extend('forEach', function(object, fn, bind){
for (var key in object){
if (hasOwnProperty.call(object, key)) fn.call(bind, object[key], key, object);
}
});
Object.each = Object.forEach;
Array.implement({
/*<!ES5>*/
forEach: function(fn, bind){
for (var i = 0, l = this.length; i < l; i++){
if (i in this) fn.call(bind, this[i], i, this);
}
},
/*</!ES5>*/
each: function(fn, bind){
Array.forEach(this, fn, bind);
return this;
}
});
// Array & Object cloning, Object merging and appending
var cloneOf = function(item){
switch (typeOf(item)){
case 'array': return item.clone();
case 'object': return Object.clone(item);
default: return item;
}
};
Array.implement('clone', function(){
var i = this.length, clone = new Array(i);
while (i--) clone[i] = cloneOf(this[i]);
return clone;
});
var mergeOne = function(source, key, current){
switch (typeOf(current)){
case 'object':
if (typeOf(source[key]) == 'object') Object.merge(source[key], current);
else source[key] = Object.clone(current);
break;
case 'array': source[key] = current.clone(); break;
default: source[key] = current;
}
return source;
};
Object.extend({
merge: function(source, k, v){
if (typeOf(k) == 'string') return mergeOne(source, k, v);
for (var i = 1, l = arguments.length; i < l; i++){
var object = arguments[i];
for (var key in object) mergeOne(source, key, object[key]);
}
return source;
},
clone: function(object){
var clone = {};
for (var key in object) clone[key] = cloneOf(object[key]);
return clone;
},
append: function(original){
for (var i = 1, l = arguments.length; i < l; i++){
var extended = arguments[i] || {};
for (var key in extended) original[key] = extended[key];
}
return original;
}
});
// Object-less types
['Object', 'WhiteSpace', 'TextNode', 'Collection', 'Arguments'].each(function(name){
new Type(name);
});
// Unique ID
var UID = Date.now();
String.extend('uniqueID', function(){
return (UID++).toString(36);
});
})();
/*
---
name: Array
description: Contains Array Prototypes like each, contains, and erase.
license: MIT-style license.
requires: [Type]
provides: Array
...
*/
Array.implement({
/*<!ES5>*/
every: function(fn, bind){
for (var i = 0, l = this.length >>> 0; i < l; i++){
if ((i in this) && !fn.call(bind, this[i], i, this)) return false;
}
return true;
},
filter: function(fn, bind){
var results = [];
for (var value, i = 0, l = this.length >>> 0; i < l; i++) if (i in this){
value = this[i];
if (fn.call(bind, value, i, this)) results.push(value);
}
return results;
},
indexOf: function(item, from){
var length = this.length >>> 0;
for (var i = (from < 0) ? Math.max(0, length + from) : from || 0; i < length; i++){
if (this[i] === item) return i;
}
return -1;
},
map: function(fn, bind){
var length = this.length >>> 0, results = Array(length);
for (var i = 0; i < length; i++){
if (i in this) results[i] = fn.call(bind, this[i], i, this);
}
return results;
},
some: function(fn, bind){
for (var i = 0, l = this.length >>> 0; i < l; i++){
if ((i in this) && fn.call(bind, this[i], i, this)) return true;
}
return false;
},
/*</!ES5>*/
clean: function(){
return this.filter(function(item){
return item != null;
});
},
invoke: function(methodName){
var args = Array.slice(arguments, 1);
return this.map(function(item){
return item[methodName].apply(item, args);
});
},
associate: function(keys){
var obj = {}, length = Math.min(this.length, keys.length);
for (var i = 0; i < length; i++) obj[keys[i]] = this[i];
return obj;
},
link: function(object){
var result = {};
for (var i = 0, l = this.length; i < l; i++){
for (var key in object){
if (object[key](this[i])){
result[key] = this[i];
delete object[key];
break;
}
}
}
return result;
},
contains: function(item, from){
return this.indexOf(item, from) != -1;
},
append: function(array){
this.push.apply(this, array);
return this;
},
getLast: function(){
return (this.length) ? this[this.length - 1] : null;
},
getRandom: function(){
return (this.length) ? this[Number.random(0, this.length - 1)] : null;
},
include: function(item){
if (!this.contains(item)) this.push(item);
return this;
},
combine: function(array){
for (var i = 0, l = array.length; i < l; i++) this.include(array[i]);
return this;
},
erase: function(item){
for (var i = this.length; i--;){
if (this[i] === item) this.splice(i, 1);
}
return this;
},
empty: function(){
this.length = 0;
return this;
},
flatten: function(){
var array = [];
for (var i = 0, l = this.length; i < l; i++){
var type = typeOf(this[i]);
if (type == 'null') continue;
array = array.concat((type == 'array' || type == 'collection' || type == 'arguments' || instanceOf(this[i], Array)) ? Array.flatten(this[i]) : this[i]);
}
return array;
},
pick: function(){
for (var i = 0, l = this.length; i < l; i++){
if (this[i] != null) return this[i];
}
return null;
},
hexToRgb: function(array){
if (this.length != 3) return null;
var rgb = this.map(function(value){
if (value.length == 1) value += value;
return parseInt(value, 16);
});
return (array) ? rgb : 'rgb(' + rgb + ')';
},
rgbToHex: function(array){
if (this.length < 3) return null;
if (this.length == 4 && this[3] == 0 && !array) return 'transparent';
var hex = [];
for (var i = 0; i < 3; i++){
var bit = (this[i] - 0).toString(16);
hex.push((bit.length == 1) ? '0' + bit : bit);
}
return (array) ? hex : '#' + hex.join('');
}
});
/*
---
name: Function
description: Contains Function Prototypes like create, bind, pass, and delay.
license: MIT-style license.
requires: Type
provides: Function
...
*/
Function.extend({
attempt: function(){
for (var i = 0, l = arguments.length; i < l; i++){
try {
return arguments[i]();
} catch (e){}
}
return null;
}
});
Function.implement({
attempt: function(args, bind){
try {
return this.apply(bind, Array.from(args));
} catch (e){}
return null;
},
/*<!ES5-bind>*/
bind: function(that){
var self = this,
args = arguments.length > 1 ? Array.slice(arguments, 1) : null,
F = function(){};
var bound = function(){
var context = that, length = arguments.length;
if (this instanceof bound){
F.prototype = self.prototype;
context = new F;
}
var result = (!args && !length)
? self.call(context)
: self.apply(context, args && length ? args.concat(Array.slice(arguments)) : args || arguments);
return context == that ? result : context;
};
return bound;
},
/*</!ES5-bind>*/
pass: function(args, bind){
var self = this;
if (args != null) args = Array.from(args);
return function(){
return self.apply(bind, args || arguments);
};
},
delay: function(delay, bind, args){
return setTimeout(this.pass((args == null ? [] : args), bind), delay);
},
periodical: function(periodical, bind, args){
return setInterval(this.pass((args == null ? [] : args), bind), periodical);
}
});
/*
---
name: Number
description: Contains Number Prototypes like limit, round, times, and ceil.
license: MIT-style license.
requires: Type
provides: Number
...
*/
Number.implement({
limit: function(min, max){
return Math.min(max, Math.max(min, this));
},
round: function(precision){
precision = Math.pow(10, precision || 0).toFixed(precision < 0 ? -precision : 0);
return Math.round(this * precision) / precision;
},
times: function(fn, bind){
for (var i = 0; i < this; i++) fn.call(bind, i, this);
},
toFloat: function(){
return parseFloat(this);
},
toInt: function(base){
return parseInt(this, base || 10);
}
});
Number.alias('each', 'times');
(function(math){
var methods = {};
math.each(function(name){
if (!Number[name]) methods[name] = function(){
return Math[name].apply(null, [this].concat(Array.from(arguments)));
};
});
Number.implement(methods);
})(['abs', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'exp', 'floor', 'log', 'max', 'min', 'pow', 'sin', 'sqrt', 'tan']);
/*
---
name: String
description: Contains String Prototypes like camelCase, capitalize, test, and toInt.
license: MIT-style license.
requires: [Type, Array]
provides: String
...
*/
String.implement({
//<!ES6>
contains: function(string, index){
return (index ? String(this).slice(index) : String(this)).indexOf(string) > -1;
},
//</!ES6>
test: function(regex, params){
return ((typeOf(regex) == 'regexp') ? regex : new RegExp('' + regex, params)).test(this);
},
trim: function(){
return String(this).replace(/^\s+|\s+$/g, '');
},
clean: function(){
return String(this).replace(/\s+/g, ' ').trim();
},
camelCase: function(){
return String(this).replace(/-\D/g, function(match){
return match.charAt(1).toUpperCase();
});
},
hyphenate: function(){
return String(this).replace(/[A-Z]/g, function(match){
return ('-' + match.charAt(0).toLowerCase());
});
},
capitalize: function(){
return String(this).replace(/\b[a-z]/g, function(match){
return match.toUpperCase();
});
},
escapeRegExp: function(){
return String(this).replace(/([-.*+?^${}()|[\]\/\\])/g, '\\$1');
},
toInt: function(base){
return parseInt(this, base || 10);
},
toFloat: function(){
return parseFloat(this);
},
hexToRgb: function(array){
var hex = String(this).match(/^#?(\w{1,2})(\w{1,2})(\w{1,2})$/);
return (hex) ? hex.slice(1).hexToRgb(array) : null;
},
rgbToHex: function(array){
var rgb = String(this).match(/\d{1,3}/g);
return (rgb) ? rgb.rgbToHex(array) : null;
},
substitute: function(object, regexp){
return String(this).replace(regexp || (/\\?\{([^{}]+)\}/g), function(match, name){
if (match.charAt(0) == '\\') return match.slice(1);
return (object[name] != null) ? object[name] : '';
});
}
});
/*
---
name: Browser
description: The Browser Object. Contains Browser initialization, Window and Document, and the Browser Hash.
license: MIT-style license.
requires: [Array, Function, Number, String]
provides: [Browser, Window, Document]
...
*/
(function(){
var document = this.document;
var window = document.window = this;
var parse = function(ua, platform){
ua = ua.toLowerCase();
platform = (platform ? platform.toLowerCase() : '');
var UA = ua.match(/(opera|ie|firefox|chrome|trident|crios|version)[\s\/:]([\w\d\.]+)?.*?(safari|(?:rv[\s\/:]|version[\s\/:])([\w\d\.]+)|$)/) || [null, 'unknown', 0];
if (UA[1] == 'trident'){
UA[1] = 'ie';
if (UA[4]) UA[2] = UA[4];
} else if (UA[1] == 'crios'){
UA[1] = 'chrome';
}
platform = ua.match(/ip(?:ad|od|hone)/) ? 'ios' : (ua.match(/(?:webos|android)/) || platform.match(/mac|win|linux/) || ['other'])[0];
if (platform == 'win') platform = 'windows';
return {
extend: Function.prototype.extend,
name: (UA[1] == 'version') ? UA[3] : UA[1],
version: parseFloat((UA[1] == 'opera' && UA[4]) ? UA[4] : UA[2]),
platform: platform
};
};
var Browser = this.Browser = parse(navigator.userAgent, navigator.platform);
if (Browser.name == 'ie'){
Browser.version = document.documentMode;
}
Browser.extend({
Features: {
xpath: !!(document.evaluate),
air: !!(window.runtime),
query: !!(document.querySelector),
json: !!(window.JSON)
},
parseUA: parse
});
// Request
Browser.Request = (function(){
var XMLHTTP = function(){
return new XMLHttpRequest();
};
var MSXML2 = function(){
return new ActiveXObject('MSXML2.XMLHTTP');
};
var MSXML = function(){
return new ActiveXObject('Microsoft.XMLHTTP');
};
return Function.attempt(function(){
XMLHTTP();
return XMLHTTP;
}, function(){
MSXML2();
return MSXML2;
}, function(){
MSXML();
return MSXML;
});
})();
Browser.Features.xhr = !!(Browser.Request);
// String scripts
Browser.exec = function(text){
if (!text) return text;
if (window.execScript){
window.execScript(text);
} else {
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.text = text;
document.head.appendChild(script);
document.head.removeChild(script);
}
return text;
};
String.implement('stripScripts', function(exec){
var scripts = '';
var text = this.replace(/<script[^>]*>([\s\S]*?)<\/script>/gi, function(all, code){
scripts += code + '\n';
return '';
});
if (exec === true) Browser.exec(scripts);
else if (typeOf(exec) == 'function') exec(scripts, text);
return text;
});
// Window, Document
Browser.extend({
Document: this.Document,
Window: this.Window,
Element: this.Element,
Event: this.Event
});
this.Window = this.$constructor = new Type('Window', function(){});
this.$family = Function.from('window').hide();
Window.mirror(function(name, method){
window[name] = method;
});
this.Document = document.$constructor = new Type('Document', function(){});
document.$family = Function.from('document').hide();
Document.mirror(function(name, method){
document[name] = method;
});
document.html = document.documentElement;
if (!document.head) document.head = document.getElementsByTagName('head')[0];
if (document.execCommand) try {
document.execCommand("BackgroundImageCache", false, true);
} catch (e){}
/*<ltIE9>*/
if (this.attachEvent && !this.addEventListener){
var unloadEvent = function(){
this.detachEvent('onunload', unloadEvent);
document.head = document.html = document.window = null;
window = this.Window = document = null;
};
this.attachEvent('onunload', unloadEvent);
}
// IE fails on collections and <select>.options (refers to <select>)
var arrayFrom = Array.from;
try {
arrayFrom(document.html.childNodes);
} catch(e){
Array.from = function(item){
if (typeof item != 'string' && Type.isEnumerable(item) && typeOf(item) != 'array'){
var i = item.length, array = new Array(i);
while (i--) array[i] = item[i];
return array;
}
return arrayFrom(item);
};
var prototype = Array.prototype,
slice = prototype.slice;
['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift', 'concat', 'join', 'slice'].each(function(name){
var method = prototype[name];
Array[name] = function(item){
return method.apply(Array.from(item), slice.call(arguments, 1));
};
});
}
/*</ltIE9>*/
})();
/*
---
name: Object
description: Object generic methods
license: MIT-style license.
requires: Type
provides: [Object, Hash]
...
*/
(function(){
var hasOwnProperty = Object.prototype.hasOwnProperty;
Object.extend({
subset: function(object, keys){
var results = {};
for (var i = 0, l = keys.length; i < l; i++){
var k = keys[i];
if (k in object) results[k] = object[k];
}
return results;
},
map: function(object, fn, bind){
var results = {};
for (var key in object){
if (hasOwnProperty.call(object, key)) results[key] = fn.call(bind, object[key], key, object);
}
return results;
},
filter: function(object, fn, bind){
var results = {};
for (var key in object){
var value = object[key];
if (hasOwnProperty.call(object, key) && fn.call(bind, value, key, object)) results[key] = value;
}
return results;
},
every: function(object, fn, bind){
for (var key in object){
if (hasOwnProperty.call(object, key) && !fn.call(bind, object[key], key)) return false;
}
return true;
},
some: function(object, fn, bind){
for (var key in object){
if (hasOwnProperty.call(object, key) && fn.call(bind, object[key], key)) return true;
}
return false;
},
keys: function(object){
var keys = [];
for (var key in object){
if (hasOwnProperty.call(object, key)) keys.push(key);
}
return keys;
},
values: function(object){
var values = [];
for (var key in object){
if (hasOwnProperty.call(object, key)) values.push(object[key]);
}
return values;
},
getLength: function(object){
return Object.keys(object).length;
},
keyOf: function(object, value){
for (var key in object){
if (hasOwnProperty.call(object, key) && object[key] === value) return key;
}
return null;
},
contains: function(object, value){
return Object.keyOf(object, value) != null;
},
toQueryString: function(object, base){
var queryString = [];
Object.each(object, function(value, key){
if (base) key = base + '[' + key + ']';
var result;
switch (typeOf(value)){
case 'object': result = Object.toQueryString(value, key); break;
case 'array':
var qs = {};
value.each(function(val, i){
qs[i] = val;
});
result = Object.toQueryString(qs, key);
break;
default: result = key + '=' + encodeURIComponent(value);
}
if (value != null) queryString.push(result);
});
return queryString.join('&');
}
});
})();
/*
---
name: Slick.Parser
description: Standalone CSS3 Selector parser
provides: Slick.Parser
...
*/
;(function(){
var parsed,
separatorIndex,
combinatorIndex,
reversed,
cache = {},
reverseCache = {},
reUnescape = /\\/g;
var parse = function(expression, isReversed){
if (expression == null) return null;
if (expression.Slick === true) return expression;
expression = ('' + expression).replace(/^\s+|\s+$/g, '');
reversed = !!isReversed;
var currentCache = (reversed) ? reverseCache : cache;
if (currentCache[expression]) return currentCache[expression];
parsed = {
Slick: true,
expressions: [],
raw: expression,
reverse: function(){
return parse(this.raw, true);
}
};
separatorIndex = -1;
while (expression != (expression = expression.replace(regexp, parser)));
parsed.length = parsed.expressions.length;
return currentCache[parsed.raw] = (reversed) ? reverse(parsed) : parsed;
};
var reverseCombinator = function(combinator){
if (combinator === '!') return ' ';
else if (combinator === ' ') return '!';
else if ((/^!/).test(combinator)) return combinator.replace(/^!/, '');
else return '!' + combinator;
};
var reverse = function(expression){
var expressions = expression.expressions;
for (var i = 0; i < expressions.length; i++){
var exp = expressions[i];
var last = {parts: [], tag: '*', combinator: reverseCombinator(exp[0].combinator)};
for (var j = 0; j < exp.length; j++){
var cexp = exp[j];
if (!cexp.reverseCombinator) cexp.reverseCombinator = ' ';
cexp.combinator = cexp.reverseCombinator;
delete cexp.reverseCombinator;
}
exp.reverse().push(last);
}
return expression;
};
var escapeRegExp = function(string){// Credit: XRegExp 0.6.1 (c) 2007-2008 Steven Levithan <http://stevenlevithan.com/regex/xregexp/> MIT License
return string.replace(/[-[\]{}()*+?.\\^$|,#\s]/g, function(match){
return '\\' + match;
});
};
var regexp = new RegExp(
/*
#!/usr/bin/env ruby
puts "\t\t" + DATA.read.gsub(/\(\?x\)|\s+#.*$|\s+|\\$|\\n/,'')
__END__
"(?x)^(?:\
\\s* ( , ) \\s* # Separator \n\
| \\s* ( <combinator>+ ) \\s* # Combinator \n\
| ( \\s+ ) # CombinatorChildren \n\
| ( <unicode>+ | \\* ) # Tag \n\
| \\# ( <unicode>+ ) # ID \n\
| \\. ( <unicode>+ ) # ClassName \n\
| # Attribute \n\
\\[ \
\\s* (<unicode1>+) (?: \
\\s* ([*^$!~|]?=) (?: \
\\s* (?:\
([\"']?)(.*?)\\9 \
)\
) \
)? \\s* \
\\](?!\\]) \n\
| :+ ( <unicode>+ )(?:\
\\( (?:\
(?:([\"'])([^\\12]*)\\12)|((?:\\([^)]+\\)|[^()]*)+)\
) \\)\
)?\
)"
*/
"^(?:\\s*(,)\\s*|\\s*(<combinator>+)\\s*|(\\s+)|(<unicode>+|\\*)|\\#(<unicode>+)|\\.(<unicode>+)|\\[\\s*(<unicode1>+)(?:\\s*([*^$!~|]?=)(?:\\s*(?:([\"']?)(.*?)\\9)))?\\s*\\](?!\\])|(:+)(<unicode>+)(?:\\((?:(?:([\"'])([^\\13]*)\\13)|((?:\\([^)]+\\)|[^()]*)+))\\))?)"
.replace(/<combinator>/, '[' + escapeRegExp(">+~`!@$%^&={}\\;</") + ']')
.replace(/<unicode>/g, '(?:[\\w\\u00a1-\\uFFFF-]|\\\\[^\\s0-9a-f])')
.replace(/<unicode1>/g, '(?:[:\\w\\u00a1-\\uFFFF-]|\\\\[^\\s0-9a-f])')
);
function parser(
rawMatch,
separator,
combinator,
combinatorChildren,
tagName,
id,
className,
attributeKey,
attributeOperator,
attributeQuote,
attributeValue,
pseudoMarker,
pseudoClass,
pseudoQuote,
pseudoClassQuotedValue,
pseudoClassValue
){
if (separator || separatorIndex === -1){
parsed.expressions[++separatorIndex] = [];
combinatorIndex = -1;
if (separator) return '';
}
if (combinator || combinatorChildren || combinatorIndex === -1){
combinator = combinator || ' ';
var currentSeparator = parsed.expressions[separatorIndex];
if (reversed && currentSeparator[combinatorIndex])
currentSeparator[combinatorIndex].reverseCombinator = reverseCombinator(combinator);
currentSeparator[++combinatorIndex] = {combinator: combinator, tag: '*'};
}
var currentParsed = parsed.expressions[separatorIndex][combinatorIndex];
if (tagName){
currentParsed.tag = tagName.replace(reUnescape, '');
} else if (id){
currentParsed.id = id.replace(reUnescape, '');
} else if (className){
className = className.replace(reUnescape, '');
if (!currentParsed.classList) currentParsed.classList = [];
if (!currentParsed.classes) currentParsed.classes = [];
currentParsed.classList.push(className);
currentParsed.classes.push({
value: className,
regexp: new RegExp('(^|\\s)' + escapeRegExp(className) + '(\\s|$)')
});
} else if (pseudoClass){
pseudoClassValue = pseudoClassValue || pseudoClassQuotedValue;
pseudoClassValue = pseudoClassValue ? pseudoClassValue.replace(reUnescape, '') : null;
if (!currentParsed.pseudos) currentParsed.pseudos = [];
currentParsed.pseudos.push({
key: pseudoClass.replace(reUnescape, ''),
value: pseudoClassValue,
type: pseudoMarker.length == 1 ? 'class' : 'element'
});
} else if (attributeKey){
attributeKey = attributeKey.replace(reUnescape, '');
attributeValue = (attributeValue || '').replace(reUnescape, '');
var test, regexp;
switch (attributeOperator){
case '^=' : regexp = new RegExp( '^'+ escapeRegExp(attributeValue) ); break;
case '$=' : regexp = new RegExp( escapeRegExp(attributeValue) +'$' ); break;
case '~=' : regexp = new RegExp( '(^|\\s)'+ escapeRegExp(attributeValue) +'(\\s|$)' ); break;
case '|=' : regexp = new RegExp( '^'+ escapeRegExp(attributeValue) +'(-|$)' ); break;
case '=' : test = function(value){
return attributeValue == value;
}; break;
case '*=' : test = function(value){
return value && value.indexOf(attributeValue) > -1;
}; break;
case '!=' : test = function(value){
return attributeValue != value;
}; break;
default : test = function(value){
return !!value;
};
}
if (attributeValue == '' && (/^[*$^]=$/).test(attributeOperator)) test = function(){
return false;
};
if (!test) test = function(value){
return value && regexp.test(value);
};
if (!currentParsed.attributes) currentParsed.attributes = [];
currentParsed.attributes.push({
key: attributeKey,
operator: attributeOperator,
value: attributeValue,
test: test
});
}
return '';
};
// Slick NS
var Slick = (this.Slick || {});
Slick.parse = function(expression){
return parse(expression);
};
Slick.escapeRegExp = escapeRegExp;
if (!this.Slick) this.Slick = Slick;
}).apply(/*<CommonJS>*/(typeof exports != 'undefined') ? exports : /*</CommonJS>*/this);
/*
---
name: Slick.Finder
description: The new, superfast css selector engine.
provides: Slick.Finder
requires: Slick.Parser
...
*/
;(function(){
var local = {},
featuresCache = {},
toString = Object.prototype.toString;
// Feature / Bug detection
local.isNativeCode = function(fn){
return (/\{\s*\[native code\]\s*\}/).test('' + fn);
};
local.isXML = function(document){
return (!!document.xmlVersion) || (!!document.xml) || (toString.call(document) == '[object XMLDocument]') ||
(document.nodeType == 9 && document.documentElement.nodeName != 'HTML');
};
local.setDocument = function(document){
// convert elements / window arguments to document. if document cannot be extrapolated, the function returns.
var nodeType = document.nodeType;
if (nodeType == 9); // document
else if (nodeType) document = document.ownerDocument; // node
else if (document.navigator) document = document.document; // window
else return;
// check if it's the old document
if (this.document === document) return;
this.document = document;
// check if we have done feature detection on this document before
var root = document.documentElement,
rootUid = this.getUIDXML(root),
features = featuresCache[rootUid],
feature;
if (features){
for (feature in features){
this[feature] = features[feature];
}
return;
}
features = featuresCache[rootUid] = {};
features.root = root;
features.isXMLDocument = this.isXML(document);
features.brokenStarGEBTN
= features.starSelectsClosedQSA
= features.idGetsName
= features.brokenMixedCaseQSA
= features.brokenGEBCN
= features.brokenCheckedQSA
= features.brokenEmptyAttributeQSA
= features.isHTMLDocument
= features.nativeMatchesSelector
= false;
var starSelectsClosed, starSelectsComments,
brokenSecondClassNameGEBCN, cachedGetElementsByClassName,
brokenFormAttributeGetter;
var selected, id = 'slick_uniqueid';
var testNode = document.createElement('div');
var testRoot = document.body || document.getElementsByTagName('body')[0] || root;
testRoot.appendChild(testNode);
// on non-HTML documents innerHTML and getElementsById doesnt work properly
try {
testNode.innerHTML = '<a id="'+id+'"></a>';
features.isHTMLDocument = !!document.getElementById(id);
} catch(e){};
if (features.isHTMLDocument){
testNode.style.display = 'none';
// IE returns comment nodes for getElementsByTagName('*') for some documents
testNode.appendChild(document.createComment(''));
starSelectsComments = (testNode.getElementsByTagName('*').length > 1);
// IE returns closed nodes (EG:"</foo>") for getElementsByTagName('*') for some documents
try {
testNode.innerHTML = 'foo</foo>';
selected = testNode.getElementsByTagName('*');
starSelectsClosed = (selected && !!selected.length && selected[0].nodeName.charAt(0) == '/');
} catch(e){};
features.brokenStarGEBTN = starSelectsComments || starSelectsClosed;
// IE returns elements with the name instead of just id for getElementsById for some documents
try {
testNode.innerHTML = '<a name="'+ id +'"></a><b id="'+ id +'"></b>';
features.idGetsName = document.getElementById(id) === testNode.firstChild;
} catch(e){};
if (testNode.getElementsByClassName){
// Safari 3.2 getElementsByClassName caches results
try {
testNode.innerHTML = '<a class="f"></a><a class="b"></a>';
testNode.getElementsByClassName('b').length;
testNode.firstChild.className = 'b';
cachedGetElementsByClassName = (testNode.getElementsByClassName('b').length != 2);
} catch(e){};
// Opera 9.6 getElementsByClassName doesnt detects the class if its not the first one
try {
testNode.innerHTML = '<a class="a"></a><a class="f b a"></a>';
brokenSecondClassNameGEBCN = (testNode.getElementsByClassName('a').length != 2);
} catch(e){};
features.brokenGEBCN = cachedGetElementsByClassName || brokenSecondClassNameGEBCN;
}
if (testNode.querySelectorAll){
// IE 8 returns closed nodes (EG:"</foo>") for querySelectorAll('*') for some documents
try {
testNode.innerHTML = 'foo</foo>';
selected = testNode.querySelectorAll('*');
features.starSelectsClosedQSA = (selected && !!selected.length && selected[0].nodeName.charAt(0) == '/');
} catch(e){};
// Safari 3.2 querySelectorAll doesnt work with mixedcase on quirksmode
try {
testNode.innerHTML = '<a class="MiX"></a>';
features.brokenMixedCaseQSA = !testNode.querySelectorAll('.MiX').length;
} catch(e){};
// Webkit and Opera dont return selected options on querySelectorAll
try {
testNode.innerHTML = '<select><option selected="selected">a</option></select>';
features.brokenCheckedQSA = (testNode.querySelectorAll(':checked').length == 0);
} catch(e){};
// IE returns incorrect results for attr[*^$]="" selectors on querySelectorAll
try {
testNode.innerHTML = '<a class=""></a>';
features.brokenEmptyAttributeQSA = (testNode.querySelectorAll('[class*=""]').length != 0);
} catch(e){};
}
// IE6-7, if a form has an input of id x, form.getAttribute(x) returns a reference to the input
try {
testNode.innerHTML = '<form action="s"><input id="action"/></form>';
brokenFormAttributeGetter = (testNode.firstChild.getAttribute('action') != 's');
} catch(e){};
// native matchesSelector function
features.nativeMatchesSelector = root.matches || /*root.msMatchesSelector ||*/ root.mozMatchesSelector || root.webkitMatchesSelector;
if (features.nativeMatchesSelector) try {
// if matchesSelector trows errors on incorrect sintaxes we can use it
features.nativeMatchesSelector.call(root, ':slick');
features.nativeMatchesSelector = null;
} catch(e){};
}
try {
root.slick_expando = 1;
delete root.slick_expando;
features.getUID = this.getUIDHTML;
} catch(e){
features.getUID = this.getUIDXML;
}
testRoot.removeChild(testNode);
testNode = selected = testRoot = null;
// getAttribute
features.getAttribute = (features.isHTMLDocument && brokenFormAttributeGetter) ? function(node, name){
var method = this.attributeGetters[name];
if (method) return method.call(node);
var attributeNode = node.getAttributeNode(name);
return (attributeNode) ? attributeNode.nodeValue : null;
} : function(node, name){
var method = this.attributeGetters[name];
return (method) ? method.call(node) : node.getAttribute(name);
};
// hasAttribute
features.hasAttribute = (root && this.isNativeCode(root.hasAttribute)) ? function(node, attribute){
return node.hasAttribute(attribute);
} : function(node, attribute){
node = node.getAttributeNode(attribute);
return !!(node && (node.specified || node.nodeValue));
};
// contains
// FIXME: Add specs: local.contains should be different for xml and html documents?
var nativeRootContains = root && this.isNativeCode(root.contains),
nativeDocumentContains = document && this.isNativeCode(document.contains);
features.contains = (nativeRootContains && nativeDocumentContains) ? function(context, node){
return context.contains(node);
} : (nativeRootContains && !nativeDocumentContains) ? function(context, node){
// IE8 does not have .contains on document.
return context === node || ((context === document) ? document.documentElement : context).contains(node);
} : (root && root.compareDocumentPosition) ? function(context, node){
return context === node || !!(context.compareDocumentPosition(node) & 16);
} : function(context, node){
if (node) do {
if (node === context) return true;
} while ((node = node.parentNode));
return false;
};
// document order sorting
// credits to Sizzle (http://sizzlejs.com/)
features.documentSorter = (root.compareDocumentPosition) ? function(a, b){
if (!a.compareDocumentPosition || !b.compareDocumentPosition) return 0;
return a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1;
} : ('sourceIndex' in root) ? function(a, b){
if (!a.sourceIndex || !b.sourceIndex) return 0;
return a.sourceIndex - b.sourceIndex;
} : (document.createRange) ? function(a, b){
if (!a.ownerDocument || !b.ownerDocument) return 0;
var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange();
aRange.setStart(a, 0);
aRange.setEnd(a, 0);
bRange.setStart(b, 0);
bRange.setEnd(b, 0);
return aRange.compareBoundaryPoints(Range.START_TO_END, bRange);
} : null ;
root = null;
for (feature in features){
this[feature] = features[feature];
}
};
// Main Method
var reSimpleSelector = /^([#.]?)((?:[\w-]+|\*))$/,
reEmptyAttribute = /\[.+[*$^]=(?:""|'')?\]/,
qsaFailExpCache = {};
local.search = function(context, expression, append, first){
var found = this.found = (first) ? null : (append || []);
if (!context) return found;
else if (context.navigator) context = context.document; // Convert the node from a window to a document
else if (!context.nodeType) return found;
// setup
var parsed, i,
uniques = this.uniques = {},
hasOthers = !!(append && append.length),
contextIsDocument = (context.nodeType == 9);
if (this.document !== (contextIsDocument ? context : context.ownerDocument)) this.setDocument(context);
// avoid duplicating items already in the append array
if (hasOthers) for (i = found.length; i--;) uniques[this.getUID(found[i])] = true;
// expression checks
if (typeof expression == 'string'){ // expression is a string
/*<simple-selectors-override>*/
var simpleSelector = expression.match(reSimpleSelector);
simpleSelectors: if (simpleSelector){
var symbol = simpleSelector[1],
name = simpleSelector[2],
node, nodes;
if (!symbol){
if (name == '*' && this.brokenStarGEBTN) break simpleSelectors;
nodes = context.getElementsByTagName(name);
if (first) return nodes[0] || null;
for (i = 0; node = nodes[i++];){
if (!(hasOthers && uniques[this.getUID(node)])) found.push(node);
}
} else if (symbol == '#'){
if (!this.isHTMLDocument || !contextIsDocument) break simpleSelectors;
node = context.getElementById(name);
if (!node) return found;
if (this.idGetsName && node.getAttributeNode('id').nodeValue != name) break simpleSelectors;
if (first) return node || null;
if (!(hasOthers && uniques[this.getUID(node)])) found.push(node);
} else if (symbol == '.'){
if (!this.isHTMLDocument || ((!context.getElementsByClassName || this.brokenGEBCN) && context.querySelectorAll)) break simpleSelectors;
if (context.getElementsByClassName && !this.brokenGEBCN){
nodes = context.getElementsByClassName(name);
if (first) return nodes[0] || null;
for (i = 0; node = nodes[i++];){
if (!(hasOthers && uniques[this.getUID(node)])) found.push(node);
}
} else {
var matchClass = new RegExp('(^|\\s)'+ Slick.escapeRegExp(name) +'(\\s|$)');
nodes = context.getElementsByTagName('*');
for (i = 0; node = nodes[i++];){
className = node.className;
if (!(className && matchClass.test(className))) continue;
if (first) return node;
if (!(hasOthers && uniques[this.getUID(node)])) found.push(node);
}
}
}
if (hasOthers) this.sort(found);
return (first) ? null : found;
}
/*</simple-selectors-override>*/
/*<query-selector-override>*/
querySelector: if (context.querySelectorAll){
if (!this.isHTMLDocument
|| qsaFailExpCache[expression]
//TODO: only skip when expression is actually mixed case
|| this.brokenMixedCaseQSA
|| (this.brokenCheckedQSA && expression.indexOf(':checked') > -1)
|| (this.brokenEmptyAttributeQSA && reEmptyAttribute.test(expression))
|| (!contextIsDocument //Abort when !contextIsDocument and...
// there are multiple expressions in the selector
// since we currently only fix non-document rooted QSA for single expression selectors
&& expression.indexOf(',') > -1
)
|| Slick.disableQSA
) break querySelector;
var _expression = expression, _context = context;
if (!contextIsDocument){
// non-document rooted QSA
// credits to Andrew Dupont
var currentId = _context.getAttribute('id'), slickid = 'slickid__';
_context.setAttribute('id', slickid);
_expression = '#' + slickid + ' ' + _expression;
context = _context.parentNode;
}
try {
if (first) return context.querySelector(_expression) || null;
else nodes = context.querySelectorAll(_expression);
} catch(e){
qsaFailExpCache[expression] = 1;
break querySelector;
} finally {
if (!contextIsDocument){
if (currentId) _context.setAttribute('id', currentId);
else _context.removeAttribute('id');
context = _context;
}
}
if (this.starSelectsClosedQSA) for (i = 0; node = nodes[i++];){
if (node.nodeName > '@' && !(hasOthers && uniques[this.getUID(node)])) found.push(node);
} else for (i = 0; node = nodes[i++];){
if (!(hasOthers && uniques[this.getUID(node)])) found.push(node);
}
if (hasOthers) this.sort(found);
return found;
}
/*</query-selector-override>*/
parsed = this.Slick.parse(expression);
if (!parsed.length) return found;
} else if (expression == null){ // there is no expression
return found;
} else if (expression.Slick){ // expression is a parsed Slick object
parsed = expression;
} else if (this.contains(context.documentElement || context, expression)){ // expression is a node
(found) ? found.push(expression) : found = expression;
return found;
} else { // other junk
return found;
}
/*<pseudo-selectors>*//*<nth-pseudo-selectors>*/
// cache elements for the nth selectors
this.posNTH = {};
this.posNTHLast = {};
this.posNTHType = {};
this.posNTHTypeLast = {};
/*</nth-pseudo-selectors>*//*</pseudo-selectors>*/
// if append is null and there is only a single selector with one expression use pushArray, else use pushUID
this.push = (!hasOthers && (first || (parsed.length == 1 && parsed.expressions[0].length == 1))) ? this.pushArray : this.pushUID;
if (found == null) found = [];
// default engine
var j, m, n;
var combinator, tag, id, classList, classes, attributes, pseudos;
var currentItems, currentExpression, currentBit, lastBit, expressions = parsed.expressions;
search: for (i = 0; (currentExpression = expressions[i]); i++) for (j = 0; (currentBit = currentExpression[j]); j++){
combinator = 'combinator:' + currentBit.combinator;
if (!this[combinator]) continue search;
tag = (this.isXMLDocument) ? currentBit.tag : currentBit.tag.toUpperCase();
id = currentBit.id;
classList = currentBit.classList;
classes = currentBit.classes;
attributes = currentBit.attributes;
pseudos = currentBit.pseudos;
lastBit = (j === (currentExpression.length - 1));
this.bitUniques = {};
if (lastBit){
this.uniques = uniques;
this.found = found;
} else {
this.uniques = {};
this.found = [];
}
if (j === 0){
this[combinator](context, tag, id, classes, attributes, pseudos, classList);
if (first && lastBit && found.length) break search;
} else {
if (first && lastBit) for (m = 0, n = currentItems.length; m < n; m++){
this[combinator](currentItems[m], tag, id, classes, attributes, pseudos, classList);
if (found.length) break search;
} else for (m = 0, n = currentItems.length; m < n; m++) this[combinator](currentItems[m], tag, id, classes, attributes, pseudos, classList);
}
currentItems = this.found;
}
// should sort if there are nodes in append and if you pass multiple expressions.
if (hasOthers || (parsed.expressions.length > 1)) this.sort(found);
return (first) ? (found[0] || null) : found;
};
// Utils
local.uidx = 1;
local.uidk = 'slick-uniqueid';
local.getUIDXML = function(node){
var uid = node.getAttribute(this.uidk);
if (!uid){
uid = this.uidx++;
node.setAttribute(this.uidk, uid);
}
return uid;
};
local.getUIDHTML = function(node){
return node.uniqueNumber || (node.uniqueNumber = this.uidx++);
};
// sort based on the setDocument documentSorter method.
local.sort = function(results){
if (!this.documentSorter) return results;
results.sort(this.documentSorter);
return results;
};
/*<pseudo-selectors>*//*<nth-pseudo-selectors>*/
local.cacheNTH = {};
local.matchNTH = /^([+-]?\d*)?([a-z]+)?([+-]\d+)?$/;
local.parseNTHArgument = function(argument){
var parsed = argument.match(this.matchNTH);
if (!parsed) return false;
var special = parsed[2] || false;
var a = parsed[1] || 1;
if (a == '-') a = -1;
var b = +parsed[3] || 0;
parsed =
(special == 'n') ? {a: a, b: b} :
(special == 'odd') ? {a: 2, b: 1} :
(special == 'even') ? {a: 2, b: 0} : {a: 0, b: a};
return (this.cacheNTH[argument] = parsed);
};
local.createNTHPseudo = function(child, sibling, positions, ofType){
return function(node, argument){
var uid = this.getUID(node);
if (!this[positions][uid]){
var parent = node.parentNode;
if (!parent) return false;
var el = parent[child], count = 1;
if (ofType){
var nodeName = node.nodeName;
do {
if (el.nodeName != nodeName) continue;
this[positions][this.getUID(el)] = count++;
} while ((el = el[sibling]));
} else {
do {
if (el.nodeType != 1) continue;
this[positions][this.getUID(el)] = count++;
} while ((el = el[sibling]));
}
}
argument = argument || 'n';
var parsed = this.cacheNTH[argument] || this.parseNTHArgument(argument);
if (!parsed) return false;
var a = parsed.a, b = parsed.b, pos = this[positions][uid];
if (a == 0) return b == pos;
if (a > 0){
if (pos < b) return false;
} else {
if (b < pos) return false;
}
return ((pos - b) % a) == 0;
};
};
/*</nth-pseudo-selectors>*//*</pseudo-selectors>*/
local.pushArray = function(node, tag, id, classes, attributes, pseudos){
if (this.matchSelector(node, tag, id, classes, attributes, pseudos)) this.found.push(node);
};
local.pushUID = function(node, tag, id, classes, attributes, pseudos){
var uid = this.getUID(node);
if (!this.uniques[uid] && this.matchSelector(node, tag, id, classes, attributes, pseudos)){
this.uniques[uid] = true;
this.found.push(node);
}
};
local.matchNode = function(node, selector){
if (this.isHTMLDocument && this.nativeMatchesSelector){
try {
return this.nativeMatchesSelector.call(node, selector.replace(/\[([^=]+)=\s*([^'"\]]+?)\s*\]/g, '[$1="$2"]'));
} catch(matchError){}
}
var parsed = this.Slick.parse(selector);
if (!parsed) return true;
// simple (single) selectors
var expressions = parsed.expressions, simpleExpCounter = 0, i, currentExpression;
for (i = 0; (currentExpression = expressions[i]); i++){
if (currentExpression.length == 1){
var exp = currentExpression[0];
if (this.matchSelector(node, (this.isXMLDocument) ? exp.tag : exp.tag.toUpperCase(), exp.id, exp.classes, exp.attributes, exp.pseudos)) return true;
simpleExpCounter++;
}
}
if (simpleExpCounter == parsed.length) return false;
var nodes = this.search(this.document, parsed), item;
for (i = 0; item = nodes[i++];){
if (item === node) return true;
}
return false;
};
local.matchPseudo = function(node, name, argument){
var pseudoName = 'pseudo:' + name;
if (this[pseudoName]) return this[pseudoName](node, argument);
var attribute = this.getAttribute(node, name);
return (argument) ? argument == attribute : !!attribute;
};
local.matchSelector = function(node, tag, id, classes, attributes, pseudos){
if (tag){
var nodeName = (this.isXMLDocument) ? node.nodeName : node.nodeName.toUpperCase();
if (tag == '*'){
if (nodeName < '@') return false; // Fix for comment nodes and closed nodes
} else {
if (nodeName != tag) return false;
}
}
if (id && node.getAttribute('id') != id) return false;
var i, part, cls;
if (classes) for (i = classes.length; i--;){
cls = this.getAttribute(node, 'class');
if (!(cls && classes[i].regexp.test(cls))) return false;
}
if (attributes) for (i = attributes.length; i--;){
part = attributes[i];
if (part.operator ? !part.test(this.getAttribute(node, part.key)) : !this.hasAttribute(node, part.key)) return false;
}
if (pseudos) for (i = pseudos.length; i--;){
part = pseudos[i];
if (!this.matchPseudo(node, part.key, part.value)) return false;
}
return true;
};
var combinators = {
' ': function(node, tag, id, classes, attributes, pseudos, classList){ // all child nodes, any level
var i, item, children;
if (this.isHTMLDocument){
getById: if (id){
item = this.document.getElementById(id);
if ((!item && node.all) || (this.idGetsName && item && item.getAttributeNode('id').nodeValue != id)){
// all[id] returns all the elements with that name or id inside node
// if theres just one it will return the element, else it will be a collection
children = node.all[id];
if (!children) return;
if (!children[0]) children = [children];
for (i = 0; item = children[i++];){
var idNode = item.getAttributeNode('id');
if (idNode && idNode.nodeValue == id){
this.push(item, tag, null, classes, attributes, pseudos);
break;
}
}
return;
}
if (!item){
// if the context is in the dom we return, else we will try GEBTN, breaking the getById label
if (this.contains(this.root, node)) return;
else break getById;
} else if (this.document !== node && !this.contains(node, item)) return;
this.push(item, tag, null, classes, attributes, pseudos);
return;
}
getByClass: if (classes && node.getElementsByClassName && !this.brokenGEBCN){
children = node.getElementsByClassName(classList.join(' '));
if (!(children && children.length)) break getByClass;
for (i = 0; item = children[i++];) this.push(item, tag, id, null, attributes, pseudos);
return;
}
}
getByTag: {
children = node.getElementsByTagName(tag);
if (!(children && children.length)) break getByTag;
if (!this.brokenStarGEBTN) tag = null;
for (i = 0; item = children[i++];) this.push(item, tag, id, classes, attributes, pseudos);
}
},
'>': function(node, tag, id, classes, attributes, pseudos){ // direct children
if ((node = node.firstChild)) do {
if (node.nodeType == 1) this.push(node, tag, id, classes, attributes, pseudos);
} while ((node = node.nextSibling));
},
'+': function(node, tag, id, classes, attributes, pseudos){ // next sibling
while ((node = node.nextSibling)) if (node.nodeType == 1){
this.push(node, tag, id, classes, attributes, pseudos);
break;
}
},
'^': function(node, tag, id, classes, attributes, pseudos){ // first child
node = node.firstChild;
if (node){
if (node.nodeType == 1) this.push(node, tag, id, classes, attributes, pseudos);
else this['combinator:+'](node, tag, id, classes, attributes, pseudos);
}
},
'~': function(node, tag, id, classes, attributes, pseudos){ // next siblings
while ((node = node.nextSibling)){
if (node.nodeType != 1) continue;
var uid = this.getUID(node);
if (this.bitUniques[uid]) break;
this.bitUniques[uid] = true;
this.push(node, tag, id, classes, attributes, pseudos);
}
},
'++': function(node, tag, id, classes, attributes, pseudos){ // next sibling and previous sibling
this['combinator:+'](node, tag, id, classes, attributes, pseudos);
this['combinator:!+'](node, tag, id, classes, attributes, pseudos);
},
'~~': function(node, tag, id, classes, attributes, pseudos){ // next siblings and previous siblings
this['combinator:~'](node, tag, id, classes, attributes, pseudos);
this['combinator:!~'](node, tag, id, classes, attributes, pseudos);
},
'!': function(node, tag, id, classes, attributes, pseudos){ // all parent nodes up to document
while ((node = node.parentNode)) if (node !== this.document) this.push(node, tag, id, classes, attributes, pseudos);
},
'!>': function(node, tag, id, classes, attributes, pseudos){ // direct parent (one level)
node = node.parentNode;
if (node !== this.document) this.push(node, tag, id, classes, attributes, pseudos);
},
'!+': function(node, tag, id, classes, attributes, pseudos){ // previous sibling
while ((node = node.previousSibling)) if (node.nodeType == 1){
this.push(node, tag, id, classes, attributes, pseudos);
break;
}
},
'!^': function(node, tag, id, classes, attributes, pseudos){ // last child
node = node.lastChild;
if (node){
if (node.nodeType == 1) this.push(node, tag, id, classes, attributes, pseudos);
else this['combinator:!+'](node, tag, id, classes, attributes, pseudos);
}
},
'!~': function(node, tag, id, classes, attributes, pseudos){ // previous siblings
while ((node = node.previousSibling)){
if (node.nodeType != 1) continue;
var uid = this.getUID(node);
if (this.bitUniques[uid]) break;
this.bitUniques[uid] = true;
this.push(node, tag, id, classes, attributes, pseudos);
}
}
};
for (var c in combinators) local['combinator:' + c] = combinators[c];
var pseudos = {
/*<pseudo-selectors>*/
'empty': function(node){
var child = node.firstChild;
return !(child && child.nodeType == 1) && !(node.innerText || node.textContent || '').length;
},
'not': function(node, expression){
return !this.matchNode(node, expression);
},
'contains': function(node, text){
return (node.innerText || node.textContent || '').indexOf(text) > -1;
},
'first-child': function(node){
while ((node = node.previousSibling)) if (node.nodeType == 1) return false;
return true;
},
'last-child': function(node){
while ((node = node.nextSibling)) if (node.nodeType == 1) return false;
return true;
},
'only-child': function(node){
var prev = node;
while ((prev = prev.previousSibling)) if (prev.nodeType == 1) return false;
var next = node;
while ((next = next.nextSibling)) if (next.nodeType == 1) return false;
return true;
},
/*<nth-pseudo-selectors>*/
'nth-child': local.createNTHPseudo('firstChild', 'nextSibling', 'posNTH'),
'nth-last-child': local.createNTHPseudo('lastChild', 'previousSibling', 'posNTHLast'),
'nth-of-type': local.createNTHPseudo('firstChild', 'nextSibling', 'posNTHType', true),
'nth-last-of-type': local.createNTHPseudo('lastChild', 'previousSibling', 'posNTHTypeLast', true),
'index': function(node, index){
return this['pseudo:nth-child'](node, '' + (index + 1));
},
'even': function(node){
return this['pseudo:nth-child'](node, '2n');
},
'odd': function(node){
return this['pseudo:nth-child'](node, '2n+1');
},
/*</nth-pseudo-selectors>*/
/*<of-type-pseudo-selectors>*/
'first-of-type': function(node){
var nodeName = node.nodeName;
while ((node = node.previousSibling)) if (node.nodeName == nodeName) return false;
return true;
},
'last-of-type': function(node){
var nodeName = node.nodeName;
while ((node = node.nextSibling)) if (node.nodeName == nodeName) return false;
return true;
},
'only-of-type': function(node){
var prev = node, nodeName = node.nodeName;
while ((prev = prev.previousSibling)) if (prev.nodeName == nodeName) return false;
var next = node;
while ((next = next.nextSibling)) if (next.nodeName == nodeName) return false;
return true;
},
/*</of-type-pseudo-selectors>*/
// custom pseudos
'enabled': function(node){
return !node.disabled;
},
'disabled': function(node){
return node.disabled;
},
'checked': function(node){
return node.checked || node.selected;
},
'focus': function(node){
return this.isHTMLDocument && this.document.activeElement === node && (node.href || node.type || this.hasAttribute(node, 'tabindex'));
},
'root': function(node){
return (node === this.root);
},
'selected': function(node){
return node.selected;
}
/*</pseudo-selectors>*/
};
for (var p in pseudos) local['pseudo:' + p] = pseudos[p];
// attributes methods
var attributeGetters = local.attributeGetters = {
'for': function(){
return ('htmlFor' in this) ? this.htmlFor : this.getAttribute('for');
},
'href': function(){
return ('href' in this) ? this.getAttribute('href', 2) : this.getAttribute('href');
},
'style': function(){
return (this.style) ? this.style.cssText : this.getAttribute('style');
},
'tabindex': function(){
var attributeNode = this.getAttributeNode('tabindex');
return (attributeNode && attributeNode.specified) ? attributeNode.nodeValue : null;
},
'type': function(){
return this.getAttribute('type');
},
'maxlength': function(){
var attributeNode = this.getAttributeNode('maxLength');
return (attributeNode && attributeNode.specified) ? attributeNode.nodeValue : null;
}
};
attributeGetters.MAXLENGTH = attributeGetters.maxLength = attributeGetters.maxlength;
// Slick
var Slick = local.Slick = (this.Slick || {});
Slick.version = '1.1.7';
// Slick finder
Slick.search = function(context, expression, append){
return local.search(context, expression, append);
};
Slick.find = function(context, expression){
return local.search(context, expression, null, true);
};
// Slick containment checker
Slick.contains = function(container, node){
local.setDocument(container);
return local.contains(container, node);
};
// Slick attribute getter
Slick.getAttribute = function(node, name){
local.setDocument(node);
return local.getAttribute(node, name);
};
Slick.hasAttribute = function(node, name){
local.setDocument(node);
return local.hasAttribute(node, name);
};
// Slick matcher
Slick.match = function(node, selector){
if (!(node && selector)) return false;
if (!selector || selector === node) return true;
local.setDocument(node);
return local.matchNode(node, selector);
};
// Slick attribute accessor
Slick.defineAttributeGetter = function(name, fn){
local.attributeGetters[name] = fn;
return this;
};
Slick.lookupAttributeGetter = function(name){
return local.attributeGetters[name];
};
// Slick pseudo accessor
Slick.definePseudo = function(name, fn){
local['pseudo:' + name] = function(node, argument){
return fn.call(node, argument);
};
return this;
};
Slick.lookupPseudo = function(name){
var pseudo = local['pseudo:' + name];
if (pseudo) return function(argument){
return pseudo.call(this, argument);
};
return null;
};
// Slick overrides accessor
Slick.override = function(regexp, fn){
local.override(regexp, fn);
return this;
};
Slick.isXML = local.isXML;
Slick.uidOf = function(node){
return local.getUIDHTML(node);
};
if (!this.Slick) this.Slick = Slick;
}).apply(/*<CommonJS>*/(typeof exports != 'undefined') ? exports : /*</CommonJS>*/this);
/*
---
name: Element
description: One of the most important items in MooTools. Contains the dollar function, the dollars function, and an handful of cross-browser, time-saver methods to let you easily work with HTML Elements.
license: MIT-style license.
requires: [Window, Document, Array, String, Function, Object, Number, Slick.Parser, Slick.Finder]
provides: [Element, Elements, $, $$, IFrame, Selectors]
...
*/
var Element = this.Element = function(tag, props){
var konstructor = Element.Constructors[tag];
if (konstructor) return konstructor(props);
if (typeof tag != 'string') return document.id(tag).set(props);
if (!props) props = {};
if (!(/^[\w-]+$/).test(tag)){
var parsed = Slick.parse(tag).expressions[0][0];
tag = (parsed.tag == '*') ? 'div' : parsed.tag;
if (parsed.id && props.id == null) props.id = parsed.id;
var attributes = parsed.attributes;
if (attributes) for (var attr, i = 0, l = attributes.length; i < l; i++){
attr = attributes[i];
if (props[attr.key] != null) continue;
if (attr.value != null && attr.operator == '=') props[attr.key] = attr.value;
else if (!attr.value && !attr.operator) props[attr.key] = true;
}
if (parsed.classList && props['class'] == null) props['class'] = parsed.classList.join(' ');
}
return document.newElement(tag, props);
};
if (Browser.Element){
Element.prototype = Browser.Element.prototype;
// IE8 and IE9 require the wrapping.
Element.prototype._fireEvent = (function(fireEvent){
return function(type, event){
return fireEvent.call(this, type, event);
};
})(Element.prototype.fireEvent);
}
new Type('Element', Element).mirror(function(name){
if (Array.prototype[name]) return;
var obj = {};
obj[name] = function(){
var results = [], args = arguments, elements = true;
for (var i = 0, l = this.length; i < l; i++){
var element = this[i], result = results[i] = element[name].apply(element, args);
elements = (elements && typeOf(result) == 'element');
}
return (elements) ? new Elements(results) : results;
};
Elements.implement(obj);
});
if (!Browser.Element){
Element.parent = Object;
Element.Prototype = {
'$constructor': Element,
'$family': Function.from('element').hide()
};
Element.mirror(function(name, method){
Element.Prototype[name] = method;
});
}
Element.Constructors = {};
var IFrame = new Type('IFrame', function(){
var params = Array.link(arguments, {
properties: Type.isObject,
iframe: function(obj){
return (obj != null);
}
});
var props = params.properties || {}, iframe;
if (params.iframe) iframe = document.id(params.iframe);
var onload = props.onload || function(){};
delete props.onload;
props.id = props.name = [props.id, props.name, iframe ? (iframe.id || iframe.name) : 'IFrame_' + String.uniqueID()].pick();
iframe = new Element(iframe || 'iframe', props);
var onLoad = function(){
onload.call(iframe.contentWindow);
};
if (window.frames[props.id]) onLoad();
else iframe.addListener('load', onLoad);
return iframe;
});
var Elements = this.Elements = function(nodes){
if (nodes && nodes.length){
var uniques = {}, node;
for (var i = 0; node = nodes[i++];){
var uid = Slick.uidOf(node);
if (!uniques[uid]){
uniques[uid] = true;
this.push(node);
}
}
}
};
Elements.prototype = {length: 0};
Elements.parent = Array;
new Type('Elements', Elements).implement({
filter: function(filter, bind){
if (!filter) return this;
return new Elements(Array.filter(this, (typeOf(filter) == 'string') ? function(item){
return item.match(filter);
} : filter, bind));
}.protect(),
push: function(){
var length = this.length;
for (var i = 0, l = arguments.length; i < l; i++){
var item = document.id(arguments[i]);
if (item) this[length++] = item;
}
return (this.length = length);
}.protect(),
unshift: function(){
var items = [];
for (var i = 0, l = arguments.length; i < l; i++){
var item = document.id(arguments[i]);
if (item) items.push(item);
}
return Array.prototype.unshift.apply(this, items);
}.protect(),
concat: function(){
var newElements = new Elements(this);
for (var i = 0, l = arguments.length; i < l; i++){
var item = arguments[i];
if (Type.isEnumerable(item)) newElements.append(item);
else newElements.push(item);
}
return newElements;
}.protect(),
append: function(collection){
for (var i = 0, l = collection.length; i < l; i++) this.push(collection[i]);
return this;
}.protect(),
empty: function(){
while (this.length) delete this[--this.length];
return this;
}.protect()
});
(function(){
// FF, IE
var splice = Array.prototype.splice, object = {'0': 0, '1': 1, length: 2};
splice.call(object, 1, 1);
if (object[1] == 1) Elements.implement('splice', function(){
var length = this.length;
var result = splice.apply(this, arguments);
while (length >= this.length) delete this[length--];
return result;
}.protect());
Array.forEachMethod(function(method, name){
Elements.implement(name, method);
});
Array.mirror(Elements);
/*<ltIE8>*/
var createElementAcceptsHTML;
try {
createElementAcceptsHTML = (document.createElement('<input name=x>').name == 'x');
} catch (e){}
var escapeQuotes = function(html){
return ('' + html).replace(/&/g, '&').replace(/"/g, '"');
};
/*</ltIE8>*/
/*<ltIE9>*/
// #2479 - IE8 Cannot set HTML of style element
var canChangeStyleHTML = (function(){
var div = document.createElement('style'),
flag = false;
try {
div.innerHTML = '#justTesing{margin: 0px;}';
flag = !!div.innerHTML;
} catch(e){}
return flag;
})();
/*</ltIE9>*/
Document.implement({
newElement: function(tag, props){
if (props){
if (props.checked != null) props.defaultChecked = props.checked;
if ((props.type == 'checkbox' || props.type == 'radio') && props.value == null) props.value = 'on';
/*<ltIE9>*/ // IE needs the type to be set before changing content of style element
if (!canChangeStyleHTML && tag == 'style'){
var styleElement = document.createElement('style');
styleElement.setAttribute('type', 'text/css');
if (props.type) delete props.type;
return this.id(styleElement).set(props);
}
/*</ltIE9>*/
/*<ltIE8>*/// Fix for readonly name and type properties in IE < 8
if (createElementAcceptsHTML){
tag = '<' + tag;
if (props.name) tag += ' name="' + escapeQuotes(props.name) + '"';
if (props.type) tag += ' type="' + escapeQuotes(props.type) + '"';
tag += '>';
delete props.name;
delete props.type;
}
/*</ltIE8>*/
}
return this.id(this.createElement(tag)).set(props);
}
});
})();
(function(){
Slick.uidOf(window);
Slick.uidOf(document);
Document.implement({
newTextNode: function(text){
return this.createTextNode(text);
},
getDocument: function(){
return this;
},
getWindow: function(){
return this.window;
},
id: (function(){
var types = {
string: function(id, nocash, doc){
id = Slick.find(doc, '#' + id.replace(/(\W)/g, '\\$1'));
return (id) ? types.element(id, nocash) : null;
},
element: function(el, nocash){
Slick.uidOf(el);
if (!nocash && !el.$family && !(/^(?:object|embed)$/i).test(el.tagName)){
var fireEvent = el.fireEvent;
// wrapping needed in IE7, or else crash
el._fireEvent = function(type, event){
return fireEvent(type, event);
};
Object.append(el, Element.Prototype);
}
return el;
},
object: function(obj, nocash, doc){
if (obj.toElement) return types.element(obj.toElement(doc), nocash);
return null;
}
};
types.textnode = types.whitespace = types.window = types.document = function(zero){
return zero;
};
return function(el, nocash, doc){
if (el && el.$family && el.uniqueNumber) return el;
var type = typeOf(el);
return (types[type]) ? types[type](el, nocash, doc || document) : null;
};
})()
});
if (window.$ == null) Window.implement('$', function(el, nc){
return document.id(el, nc, this.document);
});
Window.implement({
getDocument: function(){
return this.document;
},
getWindow: function(){
return this;
}
});
[Document, Element].invoke('implement', {
getElements: function(expression){
return Slick.search(this, expression, new Elements);
},
getElement: function(expression){
return document.id(Slick.find(this, expression));
}
});
var contains = {contains: function(element){
return Slick.contains(this, element);
}};
if (!document.contains) Document.implement(contains);
if (!document.createElement('div').contains) Element.implement(contains);
// tree walking
var injectCombinator = function(expression, combinator){
if (!expression) return combinator;
expression = Object.clone(Slick.parse(expression));
var expressions = expression.expressions;
for (var i = expressions.length; i--;)
expressions[i][0].combinator = combinator;
return expression;
};
Object.forEach({
getNext: '~',
getPrevious: '!~',
getParent: '!'
}, function(combinator, method){
Element.implement(method, function(expression){
return this.getElement(injectCombinator(expression, combinator));
});
});
Object.forEach({
getAllNext: '~',
getAllPrevious: '!~',
getSiblings: '~~',
getChildren: '>',
getParents: '!'
}, function(combinator, method){
Element.implement(method, function(expression){
return this.getElements(injectCombinator(expression, combinator));
});
});
Element.implement({
getFirst: function(expression){
return document.id(Slick.search(this, injectCombinator(expression, '>'))[0]);
},
getLast: function(expression){
return document.id(Slick.search(this, injectCombinator(expression, '>')).getLast());
},
getWindow: function(){
return this.ownerDocument.window;
},
getDocument: function(){
return this.ownerDocument;
},
getElementById: function(id){
return document.id(Slick.find(this, '#' + ('' + id).replace(/(\W)/g, '\\$1')));
},
match: function(expression){
return !expression || Slick.match(this, expression);
}
});
if (window.$$ == null) Window.implement('$$', function(selector){
if (arguments.length == 1){
if (typeof selector == 'string') return Slick.search(this.document, selector, new Elements);
else if (Type.isEnumerable(selector)) return new Elements(selector);
}
return new Elements(arguments);
});
// Inserters
var inserters = {
before: function(context, element){
var parent = element.parentNode;
if (parent) parent.insertBefore(context, element);
},
after: function(context, element){
var parent = element.parentNode;
if (parent) parent.insertBefore(context, element.nextSibling);
},
bottom: function(context, element){
element.appendChild(context);
},
top: function(context, element){
element.insertBefore(context, element.firstChild);
}
};
inserters.inside = inserters.bottom;
// getProperty / setProperty
var propertyGetters = {}, propertySetters = {};
// properties
var properties = {};
Array.forEach([
'type', 'value', 'defaultValue', 'accessKey', 'cellPadding', 'cellSpacing', 'colSpan',
'frameBorder', 'rowSpan', 'tabIndex', 'useMap'
], function(property){
properties[property.toLowerCase()] = property;
});
properties.html = 'innerHTML';
properties.text = (document.createElement('div').textContent == null) ? 'innerText': 'textContent';
Object.forEach(properties, function(real, key){
propertySetters[key] = function(node, value){
node[real] = value;
};
propertyGetters[key] = function(node){
return node[real];
};
});
/*<ltIE9>*/
propertySetters.text = (function(setter){
return function(node, value){
if (node.get('tag') == 'style') node.set('html', value);
else node[properties.text] = value;
};
})(propertySetters.text);
propertyGetters.text = (function(getter){
return function(node){
return (node.get('tag') == 'style') ? node.innerHTML : getter(node);
};
})(propertyGetters.text);
/*</ltIE9>*/
// Booleans
var bools = [
'compact', 'nowrap', 'ismap', 'declare', 'noshade', 'checked',
'disabled', 'readOnly', 'multiple', 'selected', 'noresize',
'defer', 'defaultChecked', 'autofocus', 'controls', 'autoplay',
'loop'
];
var booleans = {};
Array.forEach(bools, function(bool){
var lower = bool.toLowerCase();
booleans[lower] = bool;
propertySetters[lower] = function(node, value){
node[bool] = !!value;
};
propertyGetters[lower] = function(node){
return !!node[bool];
};
});
// Special cases
Object.append(propertySetters, {
'class': function(node, value){
('className' in node) ? node.className = (value || '') : node.setAttribute('class', value);
},
'for': function(node, value){
('htmlFor' in node) ? node.htmlFor = value : node.setAttribute('for', value);
},
'style': function(node, value){
(node.style) ? node.style.cssText = value : node.setAttribute('style', value);
},
'value': function(node, value){
node.value = (value != null) ? value : '';
}
});
propertyGetters['class'] = function(node){
return ('className' in node) ? node.className || null : node.getAttribute('class');
};
/* <webkit> */
var el = document.createElement('button');
// IE sets type as readonly and throws
try { el.type = 'button'; } catch(e){}
if (el.type != 'button') propertySetters.type = function(node, value){
node.setAttribute('type', value);
};
el = null;
/* </webkit> */
/*<IE>*/
/*<ltIE9>*/
// #2479 - IE8 Cannot set HTML of style element
var canChangeStyleHTML = (function(){
var div = document.createElement('style'),
flag = false;
try {
div.innerHTML = '#justTesing{margin: 0px;}';
flag = !!div.innerHTML;
} catch(e){}
return flag;
})();
/*</ltIE9>*/
var input = document.createElement('input'), volatileInputValue, html5InputSupport;
// #2178
input.value = 't';
input.type = 'submit';
volatileInputValue = input.value != 't';
// #2443 - IE throws "Invalid Argument" when trying to use html5 input types
try {
input.type = 'email';
html5InputSupport = input.type == 'email';
} catch(e){}
input = null;
if (volatileInputValue || !html5InputSupport) propertySetters.type = function(node, type){
try {
var value = node.value;
node.type = type;
node.value = value;
} catch (e){}
};
/*</IE>*/
/* getProperty, setProperty */
/* <ltIE9> */
var pollutesGetAttribute = (function(div){
div.random = 'attribute';
return (div.getAttribute('random') == 'attribute');
})(document.createElement('div'));
var hasCloneBug = (function(test){
test.innerHTML = '<object><param name="should_fix" value="the unknown" /></object>';
return test.cloneNode(true).firstChild.childNodes.length != 1;
})(document.createElement('div'));
/* </ltIE9> */
var hasClassList = !!document.createElement('div').classList;
var classes = function(className){
var classNames = (className || '').clean().split(" "), uniques = {};
return classNames.filter(function(className){
if (className !== "" && !uniques[className]) return uniques[className] = className;
});
};
var addToClassList = function(name){
this.classList.add(name);
};
var removeFromClassList = function(name){
this.classList.remove(name);
};
Element.implement({
setProperty: function(name, value){
var setter = propertySetters[name.toLowerCase()];
if (setter){
setter(this, value);
} else {
/* <ltIE9> */
var attributeWhiteList;
if (pollutesGetAttribute) attributeWhiteList = this.retrieve('$attributeWhiteList', {});
/* </ltIE9> */
if (value == null){
this.removeAttribute(name);
/* <ltIE9> */
if (pollutesGetAttribute) delete attributeWhiteList[name];
/* </ltIE9> */
} else {
this.setAttribute(name, '' + value);
/* <ltIE9> */
if (pollutesGetAttribute) attributeWhiteList[name] = true;
/* </ltIE9> */
}
}
return this;
},
setProperties: function(attributes){
for (var attribute in attributes) this.setProperty(attribute, attributes[attribute]);
return this;
},
getProperty: function(name){
var getter = propertyGetters[name.toLowerCase()];
if (getter) return getter(this);
/* <ltIE9> */
if (pollutesGetAttribute){
var attr = this.getAttributeNode(name), attributeWhiteList = this.retrieve('$attributeWhiteList', {});
if (!attr) return null;
if (attr.expando && !attributeWhiteList[name]){
var outer = this.outerHTML;
// segment by the opening tag and find mention of attribute name
if (outer.substr(0, outer.search(/\/?['"]?>(?![^<]*<['"])/)).indexOf(name) < 0) return null;
attributeWhiteList[name] = true;
}
}
/* </ltIE9> */
var result = Slick.getAttribute(this, name);
return (!result && !Slick.hasAttribute(this, name)) ? null : result;
},
getProperties: function(){
var args = Array.from(arguments);
return args.map(this.getProperty, this).associate(args);
},
removeProperty: function(name){
return this.setProperty(name, null);
},
removeProperties: function(){
Array.each(arguments, this.removeProperty, this);
return this;
},
set: function(prop, value){
var property = Element.Properties[prop];
(property && property.set) ? property.set.call(this, value) : this.setProperty(prop, value);
}.overloadSetter(),
get: function(prop){
var property = Element.Properties[prop];
return (property && property.get) ? property.get.apply(this) : this.getProperty(prop);
}.overloadGetter(),
erase: function(prop){
var property = Element.Properties[prop];
(property && property.erase) ? property.erase.apply(this) : this.removeProperty(prop);
return this;
},
hasClass: hasClassList ? function(className){
return this.classList.contains(className);
} : function(className){
return classes(this.className).contains(className);
},
addClass: hasClassList ? function(className){
classes(className).forEach(addToClassList, this);
return this;
} : function(className){
this.className = classes(className + ' ' + this.className).join(' ');
return this;
},
removeClass: hasClassList ? function(className){
classes(className).forEach(removeFromClassList, this);
return this;
} : function(className){
var classNames = classes(this.className);
classes(className).forEach(classNames.erase, classNames);
this.className = classNames.join(' ');
return this;
},
toggleClass: function(className, force){
if (force == null) force = !this.hasClass(className);
return (force) ? this.addClass(className) : this.removeClass(className);
},
adopt: function(){
var parent = this, fragment, elements = Array.flatten(arguments), length = elements.length;
if (length > 1) parent = fragment = document.createDocumentFragment();
for (var i = 0; i < length; i++){
var element = document.id(elements[i], true);
if (element) parent.appendChild(element);
}
if (fragment) this.appendChild(fragment);
return this;
},
appendText: function(text, where){
return this.grab(this.getDocument().newTextNode(text), where);
},
grab: function(el, where){
inserters[where || 'bottom'](document.id(el, true), this);
return this;
},
inject: function(el, where){
inserters[where || 'bottom'](this, document.id(el, true));
return this;
},
replaces: function(el){
el = document.id(el, true);
el.parentNode.replaceChild(this, el);
return this;
},
wraps: function(el, where){
el = document.id(el, true);
return this.replaces(el).grab(el, where);
},
getSelected: function(){
this.selectedIndex; // Safari 3.2.1
return new Elements(Array.from(this.options).filter(function(option){
return option.selected;
}));
},
toQueryString: function(){
var queryString = [];
this.getElements('input, select, textarea').each(function(el){
var type = el.type;
if (!el.name || el.disabled || type == 'submit' || type == 'reset' || type == 'file' || type == 'image') return;
var value = (el.get('tag') == 'select') ? el.getSelected().map(function(opt){
// IE
return document.id(opt).get('value');
}) : ((type == 'radio' || type == 'checkbox') && !el.checked) ? null : el.get('value');
Array.from(value).each(function(val){
if (typeof val != 'undefined') queryString.push(encodeURIComponent(el.name) + '=' + encodeURIComponent(val));
});
});
return queryString.join('&');
}
});
// appendHTML
var appendInserters = {
before: 'beforeBegin',
after: 'afterEnd',
bottom: 'beforeEnd',
top: 'afterBegin',
inside: 'beforeEnd'
};
Element.implement('appendHTML', ('insertAdjacentHTML' in document.createElement('div')) ? function(html, where){
this.insertAdjacentHTML(appendInserters[where || 'bottom'], html);
return this;
} : function(html, where){
var temp = new Element('div', {html: html}),
children = temp.childNodes,
fragment = temp.firstChild;
if (!fragment) return this;
if (children.length > 1){
fragment = document.createDocumentFragment();
for (var i = 0, l = children.length; i < l; i++){
fragment.appendChild(children[i]);
}
}
inserters[where || 'bottom'](fragment, this);
return this;
});
var collected = {}, storage = {};
var get = function(uid){
return (storage[uid] || (storage[uid] = {}));
};
var clean = function(item){
var uid = item.uniqueNumber;
if (item.removeEvents) item.removeEvents();
if (item.clearAttributes) item.clearAttributes();
if (uid != null){
delete collected[uid];
delete storage[uid];
}
return item;
};
var formProps = {input: 'checked', option: 'selected', textarea: 'value'};
Element.implement({
destroy: function(){
var children = clean(this).getElementsByTagName('*');
Array.each(children, clean);
Element.dispose(this);
return null;
},
empty: function(){
Array.from(this.childNodes).each(Element.dispose);
return this;
},
dispose: function(){
return (this.parentNode) ? this.parentNode.removeChild(this) : this;
},
clone: function(contents, keepid){
contents = contents !== false;
var clone = this.cloneNode(contents), ce = [clone], te = [this], i;
if (contents){
ce.append(Array.from(clone.getElementsByTagName('*')));
te.append(Array.from(this.getElementsByTagName('*')));
}
for (i = ce.length; i--;){
var node = ce[i], element = te[i];
if (!keepid) node.removeAttribute('id');
/*<ltIE9>*/
if (node.clearAttributes){
node.clearAttributes();
node.mergeAttributes(element);
node.removeAttribute('uniqueNumber');
if (node.options){
var no = node.options, eo = element.options;
for (var j = no.length; j--;) no[j].selected = eo[j].selected;
}
}
/*</ltIE9>*/
var prop = formProps[element.tagName.toLowerCase()];
if (prop && element[prop]) node[prop] = element[prop];
}
/*<ltIE9>*/
if (hasCloneBug){
var co = clone.getElementsByTagName('object'), to = this.getElementsByTagName('object');
for (i = co.length; i--;) co[i].outerHTML = to[i].outerHTML;
}
/*</ltIE9>*/
return document.id(clone);
}
});
[Element, Window, Document].invoke('implement', {
addListener: function(type, fn){
if (window.attachEvent && !window.addEventListener){
collected[Slick.uidOf(this)] = this;
}
if (this.addEventListener) this.addEventListener(type, fn, !!arguments[2]);
else this.attachEvent('on' + type, fn);
return this;
},
removeListener: function(type, fn){
if (this.removeEventListener) this.removeEventListener(type, fn, !!arguments[2]);
else this.detachEvent('on' + type, fn);
return this;
},
retrieve: function(property, dflt){
var storage = get(Slick.uidOf(this)), prop = storage[property];
if (dflt != null && prop == null) prop = storage[property] = dflt;
return prop != null ? prop : null;
},
store: function(property, value){
var storage = get(Slick.uidOf(this));
storage[property] = value;
return this;
},
eliminate: function(property){
var storage = get(Slick.uidOf(this));
delete storage[property];
return this;
}
});
/*<ltIE9>*/
if (window.attachEvent && !window.addEventListener){
var gc = function(){
Object.each(collected, clean);
if (window.CollectGarbage) CollectGarbage();
window.removeListener('unload', gc);
}
window.addListener('unload', gc);
}
/*</ltIE9>*/
Element.Properties = {};
Element.Properties.style = {
set: function(style){
this.style.cssText = style;
},
get: function(){
return this.style.cssText;
},
erase: function(){
this.style.cssText = '';
}
};
Element.Properties.tag = {
get: function(){
return this.tagName.toLowerCase();
}
};
Element.Properties.html = {
set: function(html){
if (html == null) html = '';
else if (typeOf(html) == 'array') html = html.join('');
/*<ltIE9>*/
if (this.styleSheet && !canChangeStyleHTML) this.styleSheet.cssText = html;
else /*</ltIE9>*/this.innerHTML = html;
},
erase: function(){
this.set('html', '');
}
};
var supportsHTML5Elements = true, supportsTableInnerHTML = true, supportsTRInnerHTML = true;
/*<ltIE9>*/
// technique by jdbarlett - http://jdbartlett.com/innershiv/
var div = document.createElement('div');
div.innerHTML = '<nav></nav>';
supportsHTML5Elements = (div.childNodes.length == 1);
if (!supportsHTML5Elements){
var tags = 'abbr article aside audio canvas datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video'.split(' '),
fragment = document.createDocumentFragment(), l = tags.length;
while (l--) fragment.createElement(tags[l]);
}
div = null;
/*</ltIE9>*/
/*<IE>*/
supportsTableInnerHTML = Function.attempt(function(){
var table = document.createElement('table');
table.innerHTML = '<tr><td></td></tr>';
return true;
});
/*<ltFF4>*/
var tr = document.createElement('tr'), html = '<td></td>';
tr.innerHTML = html;
supportsTRInnerHTML = (tr.innerHTML == html);
tr = null;
/*</ltFF4>*/
if (!supportsTableInnerHTML || !supportsTRInnerHTML || !supportsHTML5Elements){
Element.Properties.html.set = (function(set){
var translations = {
table: [1, '<table>', '</table>'],
select: [1, '<select>', '</select>'],
tbody: [2, '<table><tbody>', '</tbody></table>'],
tr: [3, '<table><tbody><tr>', '</tr></tbody></table>']
};
translations.thead = translations.tfoot = translations.tbody;
return function(html){
/*<ltIE9>*/
if (this.styleSheet) return set.call(this, html);
/*</ltIE9>*/
var wrap = translations[this.get('tag')];
if (!wrap && !supportsHTML5Elements) wrap = [0, '', ''];
if (!wrap) return set.call(this, html);
var level = wrap[0], wrapper = document.createElement('div'), target = wrapper;
if (!supportsHTML5Elements) fragment.appendChild(wrapper);
wrapper.innerHTML = [wrap[1], html, wrap[2]].flatten().join('');
while (level--) target = target.firstChild;
this.empty().adopt(target.childNodes);
if (!supportsHTML5Elements) fragment.removeChild(wrapper);
wrapper = null;
};
})(Element.Properties.html.set);
}
/*</IE>*/
/*<ltIE9>*/
var testForm = document.createElement('form');
testForm.innerHTML = '<select><option>s</option></select>';
if (testForm.firstChild.value != 's') Element.Properties.value = {
set: function(value){
var tag = this.get('tag');
if (tag != 'select') return this.setProperty('value', value);
var options = this.getElements('option');
value = String(value);
for (var i = 0; i < options.length; i++){
var option = options[i],
attr = option.getAttributeNode('value'),
optionValue = (attr && attr.specified) ? option.value : option.get('text');
if (optionValue === value) return option.selected = true;
}
},
get: function(){
var option = this, tag = option.get('tag');
if (tag != 'select' && tag != 'option') return this.getProperty('value');
if (tag == 'select' && !(option = option.getSelected()[0])) return '';
var attr = option.getAttributeNode('value');
return (attr && attr.specified) ? option.value : option.get('text');
}
};
testForm = null;
/*</ltIE9>*/
/*<IE>*/
if (document.createElement('div').getAttributeNode('id')) Element.Properties.id = {
set: function(id){
this.id = this.getAttributeNode('id').value = id;
},
get: function(){
return this.id || null;
},
erase: function(){
this.id = this.getAttributeNode('id').value = '';
}
};
/*</IE>*/
})();
/*
---
name: Event
description: Contains the Event Type, to make the event object cross-browser.
license: MIT-style license.
requires: [Window, Document, Array, Function, String, Object]
provides: Event
...
*/
(function(){
var _keys = {};
var normalizeWheelSpeed = function(event){
var normalized;
if (event.wheelDelta){
normalized = event.wheelDelta % 120 == 0 ? event.wheelDelta / 120 : event.wheelDelta / 12;
} else {
var rawAmount = event.deltaY || event.detail || 0;
normalized = -(rawAmount % 3 == 0 ? rawAmount / 3 : rawAmount * 10);
}
return normalized;
}
var DOMEvent = this.DOMEvent = new Type('DOMEvent', function(event, win){
if (!win) win = window;
event = event || win.event;
if (event.$extended) return event;
this.event = event;
this.$extended = true;
this.shift = event.shiftKey;
this.control = event.ctrlKey;
this.alt = event.altKey;
this.meta = event.metaKey;
var type = this.type = event.type;
var target = event.target || event.srcElement;
while (target && target.nodeType == 3) target = target.parentNode;
this.target = document.id(target);
if (type.indexOf('key') == 0){
var code = this.code = (event.which || event.keyCode);
this.key = _keys[code];
if (type == 'keydown' || type == 'keyup'){
if (code > 111 && code < 124) this.key = 'f' + (code - 111);
else if (code > 95 && code < 106) this.key = code - 96;
}
if (this.key == null) this.key = String.fromCharCode(code).toLowerCase();
} else if (type == 'click' || type == 'dblclick' || type == 'contextmenu' || type == 'wheel' || type == 'DOMMouseScroll' || type.indexOf('mouse') == 0){
var doc = win.document;
doc = (!doc.compatMode || doc.compatMode == 'CSS1Compat') ? doc.html : doc.body;
this.page = {
x: (event.pageX != null) ? event.pageX : event.clientX + doc.scrollLeft,
y: (event.pageY != null) ? event.pageY : event.clientY + doc.scrollTop
};
this.client = {
x: (event.pageX != null) ? event.pageX - win.pageXOffset : event.clientX,
y: (event.pageY != null) ? event.pageY - win.pageYOffset : event.clientY
};
if (type == 'DOMMouseScroll' || type == 'wheel' || type == 'mousewheel') this.wheel = normalizeWheelSpeed(event);
this.rightClick = (event.which == 3 || event.button == 2);
if (type == 'mouseover' || type == 'mouseout'){
var related = event.relatedTarget || event[(type == 'mouseover' ? 'from' : 'to') + 'Element'];
while (related && related.nodeType == 3) related = related.parentNode;
this.relatedTarget = document.id(related);
}
} else if (type.indexOf('touch') == 0 || type.indexOf('gesture') == 0){
this.rotation = event.rotation;
this.scale = event.scale;
this.targetTouches = event.targetTouches;
this.changedTouches = event.changedTouches;
var touches = this.touches = event.touches;
if (touches && touches[0]){
var touch = touches[0];
this.page = {x: touch.pageX, y: touch.pageY};
this.client = {x: touch.clientX, y: touch.clientY};
}
}
if (!this.client) this.client = {};
if (!this.page) this.page = {};
});
DOMEvent.implement({
stop: function(){
return this.preventDefault().stopPropagation();
},
stopPropagation: function(){
if (this.event.stopPropagation) this.event.stopPropagation();
else this.event.cancelBubble = true;
return this;
},
preventDefault: function(){
if (this.event.preventDefault) this.event.preventDefault();
else this.event.returnValue = false;
return this;
}
});
DOMEvent.defineKey = function(code, key){
_keys[code] = key;
return this;
};
DOMEvent.defineKeys = DOMEvent.defineKey.overloadSetter(true);
DOMEvent.defineKeys({
'38': 'up', '40': 'down', '37': 'left', '39': 'right',
'27': 'esc', '32': 'space', '8': 'backspace', '9': 'tab',
'46': 'delete', '13': 'enter'
});
})();
/*
---
name: Element.Event
description: Contains Element methods for dealing with events. This file also includes mouseenter and mouseleave custom Element Events, if necessary.
license: MIT-style license.
requires: [Element, Event]
provides: Element.Event
...
*/
(function(){
Element.Properties.events = {set: function(events){
this.addEvents(events);
}};
[Element, Window, Document].invoke('implement', {
addEvent: function(type, fn){
var events = this.retrieve('events', {});
if (!events[type]) events[type] = {keys: [], values: []};
if (events[type].keys.contains(fn)) return this;
events[type].keys.push(fn);
var realType = type,
custom = Element.Events[type],
condition = fn,
self = this;
if (custom){
if (custom.onAdd) custom.onAdd.call(this, fn, type);
if (custom.condition){
condition = function(event){
if (custom.condition.call(this, event, type)) return fn.call(this, event);
return true;
};
}
if (custom.base) realType = Function.from(custom.base).call(this, type);
}
var defn = function(){
return fn.call(self);
};
var nativeEvent = Element.NativeEvents[realType];
if (nativeEvent){
if (nativeEvent == 2){
defn = function(event){
event = new DOMEvent(event, self.getWindow());
if (condition.call(self, event) === false) event.stop();
};
}
this.addListener(realType, defn, arguments[2]);
}
events[type].values.push(defn);
return this;
},
removeEvent: function(type, fn){
var events = this.retrieve('events');
if (!events || !events[type]) return this;
var list = events[type];
var index = list.keys.indexOf(fn);
if (index == -1) return this;
var value = list.values[index];
delete list.keys[index];
delete list.values[index];
var custom = Element.Events[type];
if (custom){
if (custom.onRemove) custom.onRemove.call(this, fn, type);
if (custom.base) type = Function.from(custom.base).call(this, type);
}
return (Element.NativeEvents[type]) ? this.removeListener(type, value, arguments[2]) : this;
},
addEvents: function(events){
for (var event in events) this.addEvent(event, events[event]);
return this;
},
removeEvents: function(events){
var type;
if (typeOf(events) == 'object'){
for (type in events) this.removeEvent(type, events[type]);
return this;
}
var attached = this.retrieve('events');
if (!attached) return this;
if (!events){
for (type in attached) this.removeEvents(type);
this.eliminate('events');
} else if (attached[events]){
attached[events].keys.each(function(fn){
this.removeEvent(events, fn);
}, this);
delete attached[events];
}
return this;
},
fireEvent: function(type, args, delay){
var events = this.retrieve('events');
if (!events || !events[type]) return this;
args = Array.from(args);
events[type].keys.each(function(fn){
if (delay) fn.delay(delay, this, args);
else fn.apply(this, args);
}, this);
return this;
},
cloneEvents: function(from, type){
from = document.id(from);
var events = from.retrieve('events');
if (!events) return this;
if (!type){
for (var eventType in events) this.cloneEvents(from, eventType);
} else if (events[type]){
events[type].keys.each(function(fn){
this.addEvent(type, fn);
}, this);
}
return this;
}
});
Element.NativeEvents = {
click: 2, dblclick: 2, mouseup: 2, mousedown: 2, contextmenu: 2, //mouse buttons
wheel: 2, mousewheel: 2, DOMMouseScroll: 2, //mouse wheel
mouseover: 2, mouseout: 2, mousemove: 2, selectstart: 2, selectend: 2, //mouse movement
keydown: 2, keypress: 2, keyup: 2, //keyboard
orientationchange: 2, // mobile
touchstart: 2, touchmove: 2, touchend: 2, touchcancel: 2, // touch
gesturestart: 2, gesturechange: 2, gestureend: 2, // gesture
focus: 2, blur: 2, change: 2, reset: 2, select: 2, submit: 2, paste: 2, input: 2, //form elements
load: 2, unload: 1, beforeunload: 2, resize: 1, move: 1, DOMContentLoaded: 1, readystatechange: 1, //window
hashchange: 1, popstate: 2, // history
error: 1, abort: 1, scroll: 1, message: 2 //misc
};
Element.Events = {
mousewheel: {
base: 'onwheel' in document ? 'wheel' : 'onmousewheel' in document ? 'mousewheel' : 'DOMMouseScroll'
}
};
var check = function(event){
var related = event.relatedTarget;
if (related == null) return true;
if (!related) return false;
return (related != this && related.prefix != 'xul' && typeOf(this) != 'document' && !this.contains(related));
};
if ('onmouseenter' in document.documentElement){
Element.NativeEvents.mouseenter = Element.NativeEvents.mouseleave = 2;
Element.MouseenterCheck = check;
} else {
Element.Events.mouseenter = {
base: 'mouseover',
condition: check
};
Element.Events.mouseleave = {
base: 'mouseout',
condition: check
};
}
/*<ltIE9>*/
if (!window.addEventListener){
Element.NativeEvents.propertychange = 2;
Element.Events.change = {
base: function(){
var type = this.type;
return (this.get('tag') == 'input' && (type == 'radio' || type == 'checkbox')) ? 'propertychange' : 'change';
},
condition: function(event){
return event.type != 'propertychange' || event.event.propertyName == 'checked';
}
};
}
/*</ltIE9>*/
})();
/*
---
name: Element.Delegation
description: Extends the Element native object to include the delegate method for more efficient event management.
license: MIT-style license.
requires: [Element.Event]
provides: [Element.Delegation]
...
*/
(function(){
var eventListenerSupport = !!window.addEventListener;
Element.NativeEvents.focusin = Element.NativeEvents.focusout = 2;
var bubbleUp = function(self, match, fn, event, target){
while (target && target != self){
if (match(target, event)) return fn.call(target, event, target);
target = document.id(target.parentNode);
}
};
var map = {
mouseenter: {
base: 'mouseover',
condition: Element.MouseenterCheck
},
mouseleave: {
base: 'mouseout',
condition: Element.MouseenterCheck
},
focus: {
base: 'focus' + (eventListenerSupport ? '' : 'in'),
capture: true
},
blur: {
base: eventListenerSupport ? 'blur' : 'focusout',
capture: true
}
};
/*<ltIE9>*/
var _key = '$delegation:';
var formObserver = function(type){
return {
base: 'focusin',
remove: function(self, uid){
var list = self.retrieve(_key + type + 'listeners', {})[uid];
if (list && list.forms) for (var i = list.forms.length; i--;){
// the form may have been destroyed, so it won't have the
// removeEvent method anymore. In that case the event was
// removed as well.
if (list.forms[i].removeEvent) list.forms[i].removeEvent(type, list.fns[i]);
}
},
listen: function(self, match, fn, event, target, uid){
var form = (target.get('tag') == 'form') ? target : event.target.getParent('form');
if (!form) return;
var listeners = self.retrieve(_key + type + 'listeners', {}),
listener = listeners[uid] || {forms: [], fns: []},
forms = listener.forms, fns = listener.fns;
if (forms.indexOf(form) != -1) return;
forms.push(form);
var _fn = function(event){
bubbleUp(self, match, fn, event, target);
};
form.addEvent(type, _fn);
fns.push(_fn);
listeners[uid] = listener;
self.store(_key + type + 'listeners', listeners);
}
};
};
var inputObserver = function(type){
return {
base: 'focusin',
listen: function(self, match, fn, event, target){
var events = {blur: function(){
this.removeEvents(events);
}};
events[type] = function(event){
bubbleUp(self, match, fn, event, target);
};
event.target.addEvents(events);
}
};
};
if (!eventListenerSupport) Object.append(map, {
submit: formObserver('submit'),
reset: formObserver('reset'),
change: inputObserver('change'),
select: inputObserver('select')
});
/*</ltIE9>*/
var proto = Element.prototype,
addEvent = proto.addEvent,
removeEvent = proto.removeEvent;
var relay = function(old, method){
return function(type, fn, useCapture){
if (type.indexOf(':relay') == -1) return old.call(this, type, fn, useCapture);
var parsed = Slick.parse(type).expressions[0][0];
if (parsed.pseudos[0].key != 'relay') return old.call(this, type, fn, useCapture);
var newType = parsed.tag;
parsed.pseudos.slice(1).each(function(pseudo){
newType += ':' + pseudo.key + (pseudo.value ? '(' + pseudo.value + ')' : '');
});
old.call(this, type, fn);
return method.call(this, newType, parsed.pseudos[0].value, fn);
};
};
var delegation = {
addEvent: function(type, match, fn){
var storage = this.retrieve('$delegates', {}), stored = storage[type];
if (stored) for (var _uid in stored){
if (stored[_uid].fn == fn && stored[_uid].match == match) return this;
}
var _type = type, _match = match, _fn = fn, _map = map[type] || {};
type = _map.base || _type;
match = function(target){
return Slick.match(target, _match);
};
var elementEvent = Element.Events[_type];
if (_map.condition || elementEvent && elementEvent.condition){
var __match = match, condition = _map.condition || elementEvent.condition;
match = function(target, event){
return __match(target, event) && condition.call(target, event, type);
};
}
var self = this, uid = String.uniqueID();
var delegator = _map.listen ? function(event, target){
if (!target && event && event.target) target = event.target;
if (target) _map.listen(self, match, fn, event, target, uid);
} : function(event, target){
if (!target && event && event.target) target = event.target;
if (target) bubbleUp(self, match, fn, event, target);
};
if (!stored) stored = {};
stored[uid] = {
match: _match,
fn: _fn,
delegator: delegator
};
storage[_type] = stored;
return addEvent.call(this, type, delegator, _map.capture);
},
removeEvent: function(type, match, fn, _uid){
var storage = this.retrieve('$delegates', {}), stored = storage[type];
if (!stored) return this;
if (_uid){
var _type = type, delegator = stored[_uid].delegator, _map = map[type] || {};
type = _map.base || _type;
if (_map.remove) _map.remove(this, _uid);
delete stored[_uid];
storage[_type] = stored;
return removeEvent.call(this, type, delegator, _map.capture);
}
var __uid, s;
if (fn) for (__uid in stored){
s = stored[__uid];
if (s.match == match && s.fn == fn) return delegation.removeEvent.call(this, type, match, fn, __uid);
} else for (__uid in stored){
s = stored[__uid];
if (s.match == match) delegation.removeEvent.call(this, type, match, s.fn, __uid);
}
return this;
}
};
[Element, Window, Document].invoke('implement', {
addEvent: relay(addEvent, delegation.addEvent),
removeEvent: relay(removeEvent, delegation.removeEvent)
});
})();
/*
---
name: Class
description: Contains the Class Function for easily creating, extending, and implementing reusable Classes.
license: MIT-style license.
requires: [Array, String, Function, Number]
provides: Class
...
*/
(function(){
var Class = this.Class = new Type('Class', function(params){
if (instanceOf(params, Function)) params = {initialize: params};
var newClass = function(){
reset(this);
if (newClass.$prototyping) return this;
this.$caller = null;
var value = (this.initialize) ? this.initialize.apply(this, arguments) : this;
this.$caller = this.caller = null;
return value;
}.extend(this).implement(params);
newClass.$constructor = Class;
newClass.prototype.$constructor = newClass;
newClass.prototype.parent = parent;
return newClass;
});
var parent = function(){
if (!this.$caller) throw new Error('The method "parent" cannot be called.');
var name = this.$caller.$name,
parent = this.$caller.$owner.parent,
previous = (parent) ? parent.prototype[name] : null;
if (!previous) throw new Error('The method "' + name + '" has no parent.');
return previous.apply(this, arguments);
};
var reset = function(object){
for (var key in object){
var value = object[key];
switch (typeOf(value)){
case 'object':
var F = function(){};
F.prototype = value;
object[key] = reset(new F);
break;
case 'array': object[key] = value.clone(); break;
}
}
return object;
};
var wrap = function(self, key, method){
if (method.$origin) method = method.$origin;
var wrapper = function(){
if (method.$protected && this.$caller == null) throw new Error('The method "' + key + '" cannot be called.');
var caller = this.caller, current = this.$caller;
this.caller = current; this.$caller = wrapper;
var result = method.apply(this, arguments);
this.$caller = current; this.caller = caller;
return result;
}.extend({$owner: self, $origin: method, $name: key});
return wrapper;
};
var implement = function(key, value, retain){
if (Class.Mutators.hasOwnProperty(key)){
value = Class.Mutators[key].call(this, value);
if (value == null) return this;
}
if (typeOf(value) == 'function'){
if (value.$hidden) return this;
this.prototype[key] = (retain) ? value : wrap(this, key, value);
} else {
Object.merge(this.prototype, key, value);
}
return this;
};
var getInstance = function(klass){
klass.$prototyping = true;
var proto = new klass;
delete klass.$prototyping;
return proto;
};
Class.implement('implement', implement.overloadSetter());
Class.Mutators = {
Extends: function(parent){
this.parent = parent;
this.prototype = getInstance(parent);
},
Implements: function(items){
Array.from(items).each(function(item){
var instance = new item;
for (var key in instance) implement.call(this, key, instance[key], true);
}, this);
}
};
})();
/*
---
name: Class.Extras
description: Contains Utility Classes that can be implemented into your own Classes to ease the execution of many common tasks.
license: MIT-style license.
requires: Class
provides: [Class.Extras, Chain, Events, Options]
...
*/
(function(){
this.Chain = new Class({
$chain: [],
chain: function(){
this.$chain.append(Array.flatten(arguments));
return this;
},
callChain: function(){
return (this.$chain.length) ? this.$chain.shift().apply(this, arguments) : false;
},
clearChain: function(){
this.$chain.empty();
return this;
}
});
var removeOn = function(string){
return string.replace(/^on([A-Z])/, function(full, first){
return first.toLowerCase();
});
};
this.Events = new Class({
$events: {},
addEvent: function(type, fn, internal){
type = removeOn(type);
this.$events[type] = (this.$events[type] || []).include(fn);
if (internal) fn.internal = true;
return this;
},
addEvents: function(events){
for (var type in events) this.addEvent(type, events[type]);
return this;
},
fireEvent: function(type, args, delay){
type = removeOn(type);
var events = this.$events[type];
if (!events) return this;
args = Array.from(args);
events.each(function(fn){
if (delay) fn.delay(delay, this, args);
else fn.apply(this, args);
}, this);
return this;
},
removeEvent: function(type, fn){
type = removeOn(type);
var events = this.$events[type];
if (events && !fn.internal){
var index = events.indexOf(fn);
if (index != -1) delete events[index];
}
return this;
},
removeEvents: function(events){
var type;
if (typeOf(events) == 'object'){
for (type in events) this.removeEvent(type, events[type]);
return this;
}
if (events) events = removeOn(events);
for (type in this.$events){
if (events && events != type) continue;
var fns = this.$events[type];
for (var i = fns.length; i--;) if (i in fns){
this.removeEvent(type, fns[i]);
}
}
return this;
}
});
this.Options = new Class({
setOptions: function(){
var options = this.options = Object.merge.apply(null, [{}, this.options].append(arguments));
if (this.addEvent) for (var option in options){
if (typeOf(options[option]) != 'function' || !(/^on[A-Z]/).test(option)) continue;
this.addEvent(option, options[option]);
delete options[option];
}
return this;
}
});
})();
/*
---
name: Request
description: Powerful all purpose Request Class. Uses XMLHTTPRequest.
license: MIT-style license.
requires: [Object, Element, Chain, Events, Options, Browser]
provides: Request
...
*/
(function(){
var empty = function(){},
progressSupport = ('onprogress' in new Browser.Request);
var Request = this.Request = new Class({
Implements: [Chain, Events, Options],
options: {/*
onRequest: function(){},
onLoadstart: function(event, xhr){},
onProgress: function(event, xhr){},
onComplete: function(){},
onCancel: function(){},
onSuccess: function(responseText, responseXML){},
onFailure: function(xhr){},
onException: function(headerName, value){},
onTimeout: function(){},
user: '',
password: '',
withCredentials: false,*/
url: '',
data: '',
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
},
async: true,
format: false,
method: 'post',
link: 'ignore',
isSuccess: null,
emulation: true,
urlEncoded: true,
encoding: 'utf-8',
evalScripts: false,
evalResponse: false,
timeout: 0,
noCache: false
},
initialize: function(options){
this.xhr = new Browser.Request();
this.setOptions(options);
this.headers = this.options.headers;
},
onStateChange: function(){
var xhr = this.xhr;
if (xhr.readyState != 4 || !this.running) return;
this.running = false;
this.status = 0;
Function.attempt(function(){
var status = xhr.status;
this.status = (status == 1223) ? 204 : status;
}.bind(this));
xhr.onreadystatechange = empty;
if (progressSupport) xhr.onprogress = xhr.onloadstart = empty;
if (this.timer){
clearTimeout(this.timer);
delete this.timer;
}
this.response = {text: this.xhr.responseText || '', xml: this.xhr.responseXML};
if (this.options.isSuccess.call(this, this.status))
this.success(this.response.text, this.response.xml);
else
this.failure();
},
isSuccess: function(){
var status = this.status;
return (status >= 200 && status < 300);
},
isRunning: function(){
return !!this.running;
},
processScripts: function(text){
if (this.options.evalResponse || (/(ecma|java)script/).test(this.getHeader('Content-type'))) return Browser.exec(text);
return text.stripScripts(this.options.evalScripts);
},
success: function(text, xml){
this.onSuccess(this.processScripts(text), xml);
},
onSuccess: function(){
this.fireEvent('complete', arguments).fireEvent('success', arguments).callChain();
},
failure: function(){
this.onFailure();
},
onFailure: function(){
this.fireEvent('complete').fireEvent('failure', this.xhr);
},
loadstart: function(event){
this.fireEvent('loadstart', [event, this.xhr]);
},
progress: function(event){
this.fireEvent('progress', [event, this.xhr]);
},
timeout: function(){
this.fireEvent('timeout', this.xhr);
},
setHeader: function(name, value){
this.headers[name] = value;
return this;
},
getHeader: function(name){
return Function.attempt(function(){
return this.xhr.getResponseHeader(name);
}.bind(this));
},
check: function(){
if (!this.running) return true;
switch (this.options.link){
case 'cancel': this.cancel(); return true;
case 'chain': this.chain(this.caller.pass(arguments, this)); return false;
}
return false;
},
send: function(options){
if (!this.check(options)) return this;
this.options.isSuccess = this.options.isSuccess || this.isSuccess;
this.running = true;
var type = typeOf(options);
if (type == 'string' || type == 'element') options = {data: options};
var old = this.options;
options = Object.append({data: old.data, url: old.url, method: old.method}, options);
var data = options.data, url = String(options.url), method = options.method.toLowerCase();
switch (typeOf(data)){
case 'element': data = document.id(data).toQueryString(); break;
case 'object': case 'hash': data = Object.toQueryString(data);
}
if (this.options.format){
var format = 'format=' + this.options.format;
data = (data) ? format + '&' + data : format;
}
if (this.options.emulation && !['get', 'post'].contains(method)){
var _method = '_method=' + method;
data = (data) ? _method + '&' + data : _method;
method = 'post';
}
if (this.options.urlEncoded && ['post', 'put'].contains(method)){
var encoding = (this.options.encoding) ? '; charset=' + this.options.encoding : '';
this.headers['Content-type'] = 'application/x-www-form-urlencoded' + encoding;
}
if (!url) url = document.location.pathname;
var trimPosition = url.lastIndexOf('/');
if (trimPosition > -1 && (trimPosition = url.indexOf('#')) > -1) url = url.substr(0, trimPosition);
if (this.options.noCache)
url += (url.indexOf('?') > -1 ? '&' : '?') + String.uniqueID();
if (data && (method == 'get' || method == 'delete')){
url += (url.indexOf('?') > -1 ? '&' : '?') + data;
data = null;
}
var xhr = this.xhr;
if (progressSupport){
xhr.onloadstart = this.loadstart.bind(this);
xhr.onprogress = this.progress.bind(this);
}
xhr.open(method.toUpperCase(), url, this.options.async, this.options.user, this.options.password);
if ((this.options.withCredentials) && 'withCredentials' in xhr) xhr.withCredentials = true;
xhr.onreadystatechange = this.onStateChange.bind(this);
Object.each(this.headers, function(value, key){
try {
xhr.setRequestHeader(key, value);
} catch (e){
this.fireEvent('exception', [key, value]);
}
}, this);
this.fireEvent('request');
xhr.send(data);
if (!this.options.async) this.onStateChange();
else if (this.options.timeout) this.timer = this.timeout.delay(this.options.timeout, this);
return this;
},
cancel: function(){
if (!this.running) return this;
this.running = false;
var xhr = this.xhr;
xhr.abort();
if (this.timer){
clearTimeout(this.timer);
delete this.timer;
}
xhr.onreadystatechange = empty;
if (progressSupport) xhr.onprogress = xhr.onloadstart = empty;
this.xhr = new Browser.Request();
this.fireEvent('cancel');
return this;
}
});
var methods = {};
['get', 'post', 'put', 'delete', 'patch', 'head', 'GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD'].each(function(method){
methods[method] = function(data){
var object = {
method: method
};
if (data != null) object.data = data;
return this.send(object);
};
});
Request.implement(methods);
Element.Properties.send = {
set: function(options){
var send = this.get('send').cancel();
send.setOptions(options);
return this;
},
get: function(){
var send = this.retrieve('send');
if (!send){
send = new Request({
data: this, link: 'cancel', method: this.get('method') || 'post', url: this.get('action')
});
this.store('send', send);
}
return send;
}
};
Element.implement({
send: function(url){
var sender = this.get('send');
sender.send({data: this, url: url || sender.options.url});
return this;
}
});
})();
/*
---
name: JSON
description: JSON encoder and decoder.
license: MIT-style license.
SeeAlso: <http://www.json.org/>
requires: [Array, String, Number, Function]
provides: JSON
...
*/
if (typeof JSON == 'undefined') this.JSON = {};
(function(){
var special = {'\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '"' : '\\"', '\\': '\\\\'};
var escape = function(chr){
return special[chr] || '\\u' + ('0000' + chr.charCodeAt(0).toString(16)).slice(-4);
};
JSON.validate = function(string){
string = string.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, '@').
replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']').
replace(/(?:^|:|,)(?:\s*\[)+/g, '');
return (/^[\],:{}\s]*$/).test(string);
};
JSON.encode = JSON.stringify ? function(obj){
return JSON.stringify(obj);
} : function(obj){
if (obj && obj.toJSON) obj = obj.toJSON();
switch (typeOf(obj)){
case 'string':
return '"' + obj.replace(/[\x00-\x1f\\"]/g, escape) + '"';
case 'array':
return '[' + obj.map(JSON.encode).clean() + ']';
case 'object': case 'hash':
var string = [];
Object.each(obj, function(value, key){
var json = JSON.encode(value);
if (json) string.push(JSON.encode(key) + ':' + json);
});
return '{' + string + '}';
case 'number': case 'boolean': return '' + obj;
case 'null': return 'null';
}
return null;
};
JSON.secure = true;
JSON.decode = function(string, secure){
if (!string || typeOf(string) != 'string') return null;
if (secure == null) secure = JSON.secure;
if (secure){
if (JSON.parse) return JSON.parse(string);
if (!JSON.validate(string)) throw new Error('JSON could not decode the input; security is enabled and the value is not secure.');
}
return eval('(' + string + ')');
};
})();
/*
---
name: Request.JSON
description: Extends the basic Request Class with additional methods for sending and receiving JSON data.
license: MIT-style license.
requires: [Request, JSON]
provides: Request.JSON
...
*/
Request.JSON = new Class({
Extends: Request,
options: {
/*onError: function(text, error){},*/
secure: true
},
initialize: function(options){
this.parent(options);
Object.append(this.headers, {
'Accept': 'application/json',
'X-Request': 'JSON'
});
},
success: function(text){
var json;
try {
json = this.response.json = JSON.decode(text, this.options.secure);
} catch (error){
this.fireEvent('error', [text, error]);
return;
}
if (json == null) this.onFailure();
else this.onSuccess(json, text);
}
});
/*
---
name: DOMReady
description: Contains the custom event domready.
license: MIT-style license.
requires: [Browser, Element, Element.Event]
provides: [DOMReady, DomReady]
...
*/
(function(window, document){
var ready,
loaded,
checks = [],
shouldPoll,
timer,
testElement = document.createElement('div');
var domready = function(){
clearTimeout(timer);
if (!ready) {
Browser.loaded = ready = true;
document.removeListener('DOMContentLoaded', domready).removeListener('readystatechange', check);
document.fireEvent('domready');
window.fireEvent('domready');
}
// cleanup scope vars
document = window = testElement = null;
};
var check = function(){
for (var i = checks.length; i--;) if (checks[i]()){
domready();
return true;
}
return false;
};
var poll = function(){
clearTimeout(timer);
if (!check()) timer = setTimeout(poll, 10);
};
document.addListener('DOMContentLoaded', domready);
/*<ltIE8>*/
// doScroll technique by Diego Perini http://javascript.nwbox.com/IEContentLoaded/
// testElement.doScroll() throws when the DOM is not ready, only in the top window
var doScrollWorks = function(){
try {
testElement.doScroll();
return true;
} catch (e){}
return false;
};
// If doScroll works already, it can't be used to determine domready
// e.g. in an iframe
if (testElement.doScroll && !doScrollWorks()){
checks.push(doScrollWorks);
shouldPoll = true;
}
/*</ltIE8>*/
if (document.readyState) checks.push(function(){
var state = document.readyState;
return (state == 'loaded' || state == 'complete');
});
if ('onreadystatechange' in document) document.addListener('readystatechange', check);
else shouldPoll = true;
if (shouldPoll) poll();
Element.Events.domready = {
onAdd: function(fn){
if (ready) fn.call(this);
}
};
// Make sure that domready fires before load
Element.Events.load = {
base: 'load',
onAdd: function(fn){
if (loaded && this == window) fn.call(this);
},
condition: function(){
if (this == window){
domready();
delete Element.Events.load;
}
return true;
}
};
// This is based on the custom load event
window.addEvent('load', function(){
loaded = true;
});
})(window, document);
|
const hyperHTML = require('hyperhtml');
hyperHTML.Component = function () {
const newTarget = this.__proto__.constructor;
return Reflect.construct(HTMLElement, arguments, newTarget);
}
Object.setPrototypeOf(hyperHTML.Component, HTMLElement);
Object.setPrototypeOf(hyperHTML.Component.prototype, HTMLElement.prototype);
// lazy load body
Object.defineProperty(hyperHTML, 'body', { get() { return hyperHTML.bind(document.body) } });
|
import React from 'react';
const tabbedNavigationButton = props => (
<li className="tabbedNavigationButton">
<input
checked={!!props.selected}
id={props.id}
name="tab"
onChange={() => props.onSelect(props.id)}
type="radio" />
<label htmlFor={props.id}>
<span className="narrowTitle">{props.title.narrow}</span>
<span className="wideTitle">{props.title.wide}</span>
</label>
</li>
);
tabbedNavigationButton.propTypes = {
id: React.PropTypes.string.isRequired,
onSelect: React.PropTypes.func.isRequired,
selected: React.PropTypes.bool,
title: React.PropTypes.shape({
narrow: React.PropTypes.string.isRequired,
wide: React.PropTypes.string.isRequired
}).isRequired
};
export default tabbedNavigationButton; |
'use strict';
module.exports = {
app: {
title: 'SurveyProject',
description: 'Survey site using mean stack',
keywords: 'MongoDB, Express, AngularJS, Node.js'
},
port: process.env.PORT || 3000,
templateEngine: 'swig',
sessionSecret: 'MEAN',
sessionCollection: 'sessions',
assets: {
lib: {
css: [
'public/lib/bootstrap/dist/css/bootstrap.css',
'public/lib/bootstrap/dist/css/bootstrap-theme.css',
],
js: [
'public/lib/angular/angular.js',
'public/lib/angular-resource/angular-resource.js',
'public/lib/angular-cookies/angular-cookies.js',
'public/lib/angular-animate/angular-animate.js',
'public/lib/angular-touch/angular-touch.js',
'public/lib/angular-sanitize/angular-sanitize.js',
'public/lib/angular-ui-router/release/angular-ui-router.js',
'public/lib/angular-ui-utils/ui-utils.js',
'public/lib/angular-bootstrap/ui-bootstrap-tpls.js'
]
},
css: [
'public/modules/**/css/*.css'
],
js: [
'public/config.js',
'public/application.js',
'public/modules/*/*.js',
'public/modules/*/*[!tests]*/*.js'
],
tests: [
'public/lib/angular-mocks/angular-mocks.js',
'public/modules/*/tests/*.js'
]
}
}; |
import { createStore, compose, applyMiddleware } from 'redux';
import rootReducer from '../reducers';
// thunk is used for async api calls
import thunk from 'redux-thunk';
export default function configureStore(initialState) {
return createStore(rootReducer, initialState, compose(
applyMiddleware(thunk)
));
}
|
// FIXME(samgoldman) Remove top-level interface once Babel supports
// `declare interface` syntax.
// FIXME(samgoldman) Remove this once rxjs$Subject<T> can mixin rxjs$Observer<T>
interface rxjs$IObserver<-T> {
closed?: boolean,
next(value: T): mixed,
error(error: any): mixed,
complete(): mixed
}
type rxjs$PartialObserver<-T> =
| {
+next: (value: T) => mixed,
+error?: (error: any) => mixed,
+complete?: () => mixed
}
| {
+next?: (value: T) => mixed,
+error: (error: any) => mixed,
+complete?: () => mixed
}
| {
+next?: (value: T) => mixed,
+error?: (error: any) => mixed,
+complete: () => mixed
};
interface rxjs$ISubscription {
unsubscribe(): void
}
type rxjs$TeardownLogic = rxjs$ISubscription | (() => void);
type rxjs$EventListenerOptions =
| {
capture?: boolean,
passive?: boolean,
once?: boolean
}
| boolean;
type rxjs$ObservableInput<T> = rxjs$Observable<T> | Promise<T> | Iterable<T>;
declare class rxjs$Observable<+T> {
static bindCallback(
callbackFunc: (callback: (_: void) => any) => any,
selector?: void,
scheduler?: rxjs$SchedulerClass
): () => rxjs$Observable<void>,
static bindCallback<U>(
callbackFunc: (callback: (result: U) => any) => any,
selector?: void,
scheduler?: rxjs$SchedulerClass
): () => rxjs$Observable<U>,
static bindCallback<T, U>(
callbackFunc: (v1: T, callback: (result: U) => any) => any,
selector?: void,
scheduler?: rxjs$SchedulerClass
): (v1: T) => rxjs$Observable<U>,
static bindCallback<T, T2, U>(
callbackFunc: (v1: T, v2: T2, callback: (result: U) => any) => any,
selector?: void,
scheduler?: rxjs$SchedulerClass
): (v1: T, v2: T2) => rxjs$Observable<U>,
static bindCallback<T, T2, T3, U>(
callbackFunc: (v1: T, v2: T2, v3: T3, callback: (result: U) => any) => any,
selector?: void,
scheduler?: rxjs$SchedulerClass
): (v1: T, v2: T2, v3: T3) => rxjs$Observable<U>,
static bindCallback<T, T2, T3, T4, U>(
callbackFunc: (
v1: T,
v2: T2,
v3: T3,
v4: T4,
callback: (result: U) => any
) => any,
selector?: void,
scheduler?: rxjs$SchedulerClass
): (v1: T, v2: T2, v3: T3, v4: T4) => rxjs$Observable<U>,
static bindCallback<T, T2, T3, T4, T5, U>(
callbackFunc: (
v1: T,
v2: T2,
v3: T3,
v4: T4,
v5: T5,
callback: (result: U) => any
) => any,
selector?: void,
scheduler?: rxjs$SchedulerClass
): (v1: T, v2: T2, v3: T3, v4: T4, v5: T5) => rxjs$Observable<U>,
static bindCallback<T, T2, T3, T4, T5, T6, U>(
callbackFunc: (
v1: T,
v2: T2,
v3: T3,
v4: T4,
v5: T5,
v6: T6,
callback: (result: U) => any
) => any,
selector?: void,
scheduler?: rxjs$SchedulerClass
): (v1: T, v2: T2, v3: T3, v4: T4, v5: T5, v6: T6) => rxjs$Observable<U>,
static bindCallback<U>(
callbackFunc: (callback: (...args: Array<any>) => any) => any,
selector: (...args: Array<any>) => U,
scheduler?: rxjs$SchedulerClass
): () => rxjs$Observable<U>,
static bindCallback<T, U>(
callbackFunc: (v1: T, callback: (...args: Array<any>) => any) => any,
selector: (...args: Array<any>) => U,
scheduler?: rxjs$SchedulerClass
): (v1: T) => rxjs$Observable<U>,
static bindCallback<T, T2, U>(
callbackFunc: (
v1: T,
v2: T2,
callback: (...args: Array<any>) => any
) => any,
selector: (...args: Array<any>) => U,
scheduler?: rxjs$SchedulerClass
): (v1: T, v2: T2) => rxjs$Observable<U>,
static bindCallback<T, T2, T3, U>(
callbackFunc: (
v1: T,
v2: T2,
v3: T3,
callback: (...args: Array<any>) => any
) => any,
selector: (...args: Array<any>) => U,
scheduler?: rxjs$SchedulerClass
): (v1: T, v2: T2, v3: T3) => rxjs$Observable<U>,
static bindCallback<T, T2, T3, T4, U>(
callbackFunc: (
v1: T,
v2: T2,
v3: T3,
v4: T4,
callback: (...args: Array<any>) => any
) => any,
selector: (...args: Array<any>) => U,
scheduler?: rxjs$SchedulerClass
): (v1: T, v2: T2, v3: T3, v4: T4) => rxjs$Observable<U>,
static bindCallback<T, T2, T3, T4, T5, U>(
callbackFunc: (
v1: T,
v2: T2,
v3: T3,
v4: T4,
v5: T5,
callback: (...args: Array<any>) => any
) => any,
selector: (...args: Array<any>) => U,
scheduler?: rxjs$SchedulerClass
): (v1: T, v2: T2, v3: T3, v4: T4, v5: T5) => rxjs$Observable<U>,
static bindCallback<T, T2, T3, T4, T5, T6, U>(
callbackFunc: (
v1: T,
v2: T2,
v3: T3,
v4: T4,
v5: T5,
v6: T6,
callback: (...args: Array<any>) => any
) => any,
selector: (...args: Array<any>) => U,
scheduler?: rxjs$SchedulerClass
): (v1: T, v2: T2, v3: T3, v4: T4, v5: T5, v6: T6) => rxjs$Observable<U>,
static bindCallback<T>(
callbackFunc: Function,
selector?: void,
scheduler?: rxjs$SchedulerClass
): (...args: Array<any>) => rxjs$Observable<T>,
static bindCallback<T>(
callbackFunc: Function,
selector?: (...args: Array<any>) => T,
scheduler?: rxjs$SchedulerClass
): (...args: Array<any>) => rxjs$Observable<T>,
static bindNodeCallback<U>(
callbackFunc: (callback: (err: any, result: U) => any) => any,
selector?: void,
scheduler?: rxjs$SchedulerClass
): () => rxjs$Observable<U>,
static bindNodeCallback<T, U>(
callbackFunc: (v1: T, callback: (err: any, result: U) => any) => any,
selector?: void,
scheduler?: rxjs$SchedulerClass
): (v1: T) => rxjs$Observable<U>,
static bindNodeCallback<T, T2, U>(
callbackFunc: (
v1: T,
v2: T2,
callback: (err: any, result: U) => any
) => any,
selector?: void,
scheduler?: rxjs$SchedulerClass
): (v1: T, v2: T2) => rxjs$Observable<U>,
static bindNodeCallback<T, T2, T3, U>(
callbackFunc: (
v1: T,
v2: T2,
v3: T3,
callback: (err: any, result: U) => any
) => any,
selector?: void,
scheduler?: rxjs$SchedulerClass
): (v1: T, v2: T2, v3: T3) => rxjs$Observable<U>,
static bindNodeCallback<T, T2, T3, T4, U>(
callbackFunc: (
v1: T,
v2: T2,
v3: T3,
v4: T4,
callback: (err: any, result: U) => any
) => any,
selector?: void,
scheduler?: rxjs$SchedulerClass
): (v1: T, v2: T2, v3: T3, v4: T4) => rxjs$Observable<U>,
static bindNodeCallback<T, T2, T3, T4, T5, U>(
callbackFunc: (
v1: T,
v2: T2,
v3: T3,
v4: T4,
v5: T5,
callback: (err: any, result: U) => any
) => any,
selector?: void,
scheduler?: rxjs$SchedulerClass
): (v1: T, v2: T2, v3: T3, v4: T4, v5: T5) => rxjs$Observable<U>,
static bindNodeCallback<T, T2, T3, T4, T5, T6, U>(
callbackFunc: (
v1: T,
v2: T2,
v3: T3,
v4: T4,
v5: T5,
v6: T6,
callback: (err: any, result: U) => any
) => any,
selector?: void,
scheduler?: rxjs$SchedulerClass
): (v1: T, v2: T2, v3: T3, v4: T4, v5: T5, v6: T6) => rxjs$Observable<U>,
static bindNodeCallback<T>(
callbackFunc: Function,
selector?: void,
scheduler?: rxjs$SchedulerClass
): (...args: Array<any>) => rxjs$Observable<T>,
static bindNodeCallback<T>(
callbackFunc: Function,
selector?: (...args: Array<any>) => T,
scheduler?: rxjs$SchedulerClass
): (...args: Array<any>) => rxjs$Observable<T>,
static concat(...sources: rxjs$Observable<T>[]): rxjs$Observable<T>,
static create(
subscribe: (
observer: rxjs$Observer<T>
) => rxjs$ISubscription | Function | void
): rxjs$Observable<T>,
static defer(
observableFactory: () => rxjs$Observable<T> | Promise<T>
): rxjs$Observable<T>,
static from(
input: rxjs$ObservableInput<T>,
scheduler?: rxjs$SchedulerClass
): rxjs$Observable<T>,
static fromEvent(
element: any,
eventName: string,
...none: Array<void>
): rxjs$Observable<T>,
static fromEvent(
element: any,
eventName: string,
options: rxjs$EventListenerOptions,
...none: Array<void>
): rxjs$Observable<T>,
static fromEvent(
element: any,
eventName: string,
selector: () => T,
...none: Array<void>
): rxjs$Observable<T>,
static fromEvent(
element: any,
eventName: string,
options: rxjs$EventListenerOptions,
selector: () => T
): rxjs$Observable<T>,
static fromEventPattern(
addHandler: (handler: (item: T) => void) => void,
removeHandler: (handler: (item: T) => void) => void,
selector?: () => T
): rxjs$Observable<T>,
static fromPromise(promise: Promise<T>): rxjs$Observable<T>,
static empty<U>(): rxjs$Observable<U>,
static interval(period: number): rxjs$Observable<number>,
static timer(
initialDelay: number | Date,
period?: number,
scheduler?: rxjs$SchedulerClass
): rxjs$Observable<number>,
static merge<T, U>(
source0: rxjs$Observable<T>,
source1: rxjs$Observable<U>
): rxjs$Observable<T | U>,
static merge<T, U, V>(
source0: rxjs$Observable<T>,
source1: rxjs$Observable<U>,
source2: rxjs$Observable<V>
): rxjs$Observable<T | U | V>,
static merge(...sources: rxjs$Observable<T>[]): rxjs$Observable<T>,
static never<U>(): rxjs$Observable<U>,
static of(...values: T[]): rxjs$Observable<T>,
static range(
start?: number,
count?: number,
scheduler?: rxjs$SchedulerClass
): rxjs$Observable<number>,
static throw(error: any): rxjs$Observable<any>,
audit(
durationSelector: (value: T) => rxjs$Observable<any> | Promise<any>
): rxjs$Observable<T>,
race(other: rxjs$Observable<T>): rxjs$Observable<T>,
repeat(count?: number): rxjs$Observable<T>,
buffer(bufferBoundaries: rxjs$Observable<any>): rxjs$Observable<Array<T>>,
bufferCount(
bufferSize: number,
startBufferEvery?: number
): rxjs$Observable<Array<T>>,
bufferTime(
bufferTimeSpan: number,
bufferCreationInterval?: number,
maxBufferSize?: number,
scheduler?: rxjs$SchedulerClass
): rxjs$Observable<Array<T>>,
catch<U>(
selector: (err: any, caught: rxjs$Observable<T>) => rxjs$Observable<U>
): rxjs$Observable<U>,
concat<U>(...sources: rxjs$Observable<U>[]): rxjs$Observable<T | U>,
concatAll<U>(): rxjs$Observable<U>,
concatMap<U>(
f: (value: T, index: number) => rxjs$ObservableInput<U>,
_: void
): rxjs$Observable<U>,
concatMap<U, V>(
f: (value: T, index: number) => rxjs$ObservableInput<U>,
resultSelector: (
outerValue: T,
innerValue: U,
outerIndex: number,
innerIndex: number
) => V
): rxjs$Observable<V>,
debounceTime(
dueTime: number,
scheduler?: rxjs$SchedulerClass
): rxjs$Observable<T>,
defaultIfEmpty<U>(defaultValue: U): rxjs$Observable<T | U>,
delay(dueTime: number, scheduler?: rxjs$SchedulerClass): rxjs$Observable<T>,
distinctUntilChanged(compare?: (x: T, y: T) => boolean): rxjs$Observable<T>,
distinct<U>(
keySelector?: (value: T) => U,
flushes?: rxjs$Observable<mixed>
): rxjs$Observable<T>,
distinctUntilKeyChanged(
key: string,
compare?: (x: mixed, y: mixed) => boolean
): rxjs$Observable<T>,
elementAt(index: number, defaultValue?: T): rxjs$Observable<T>,
exhaustMap<U>(
project: (value: T, index: number) => rxjs$ObservableInput<U>,
_: void
): rxjs$Observable<U>,
exhaustMap<U, V>(
project: (value: T, index: number) => rxjs$ObservableInput<U>,
resultSelector: (
outerValue: T,
innerValue: U,
outerIndex: number,
innerIndex: number
) => V
): rxjs$Observable<V>,
expand(
project: (value: T, index: number) => rxjs$Observable<T>,
concurrent?: number,
scheduler?: rxjs$SchedulerClass
): rxjs$Observable<T>,
filter(
predicate: (value: T, index: number) => boolean,
thisArg?: any
): rxjs$Observable<T>,
finally(f: () => mixed): rxjs$Observable<T>,
first(
predicate?: (value: T, index: number, source: rxjs$Observable<T>) => boolean
): rxjs$Observable<T>,
first<U>(
predicate: ?(
value: T,
index: number,
source: rxjs$Observable<T>
) => boolean,
resultSelector: (value: T, index: number) => U
): rxjs$Observable<U>,
first<U>(
predicate: ?(
value: T,
index: number,
source: rxjs$Observable<T>
) => boolean,
resultSelector: ?(value: T, index: number) => U,
defaultValue: U
): rxjs$Observable<U>,
groupBy<K>(
keySelector: (value: T) => K,
_: void
): rxjs$Observable<rxjs$GroupedObservable<K, T>>,
groupBy<K, V>(
keySelector: (value: T) => K,
elementSelector: (value: T) => V,
durationSelector?: (
grouped: rxjs$GroupedObservable<K, V>
) => rxjs$Observable<any>
): rxjs$Observable<rxjs$GroupedObservable<K, V>>,
ignoreElements<U>(): rxjs$Observable<U>,
let<U>(
project: (self: rxjs$Observable<T>) => rxjs$Observable<U>
): rxjs$Observable<U>,
// Alias for `let`
letBind<U>(
project: (self: rxjs$Observable<T>) => rxjs$Observable<U>
): rxjs$Observable<U>,
switch(): T, // assumption: T is Observable
// Alias for `mergeMap`
flatMap<U>(
project: (value: T, index: number) => rxjs$ObservableInput<U>,
concurrency?: number
): rxjs$Observable<U>,
flatMap<U, V>(
project: (value: T, index: number) => rxjs$ObservableInput<U>,
resultSelector: (
outerValue: T,
innerValue: U,
outerIndex: number,
innerIndex: number
) => V,
concurrency?: number
): rxjs$Observable<V>,
flatMapTo<U>(innerObservable: rxjs$Observable<U>): rxjs$Observable<U>,
flatMapTo<U, V>(
innerObservable: rxjs$Observable<U>,
resultSelector: (
outerValue: T,
innerValue: U,
outerIndex: number,
innerIndex: number
) => V,
concurrent?: number
): rxjs$Observable<V>,
switchMap<U>(
project: (value: T, index: number) => rxjs$ObservableInput<U>,
_: void
): rxjs$Observable<U>,
switchMap<U, V>(
project: (value: T, index: number) => rxjs$ObservableInput<U>,
resultSelector: (
outerValue: T,
innerValue: U,
outerIndex: number,
innerIndex: number
) => V
): rxjs$Observable<V>,
switchMapTo<U>(innerObservable: rxjs$Observable<U>): rxjs$Observable<U>,
map<U>(f: (value: T) => U): rxjs$Observable<U>,
mapTo<U>(value: U): rxjs$Observable<U>,
merge(other: rxjs$Observable<T>): rxjs$Observable<T>,
mergeAll<U>(): rxjs$Observable<U>,
mergeMap<U>(
project: (value: T, index: number) => rxjs$ObservableInput<U>,
concurrency?: number
): rxjs$Observable<U>,
mergeMap<U, V>(
project: (value: T, index: number) => rxjs$ObservableInput<U>,
resultSelector: (
outerValue: T,
innerValue: U,
outerIndex: number,
innerIndex: number
) => V,
concurrency?: number
): rxjs$Observable<V>,
mergeMapTo<U>(innerObservable: rxjs$Observable<U>): rxjs$Observable<U>,
mergeMapTo<U, V>(
innerObservable: rxjs$Observable<U>,
resultSelector: (
outerValue: T,
innerValue: U,
outerIndex: number,
innerIndex: number
) => V,
concurrent?: number
): rxjs$Observable<V>,
multicast(
subjectOrSubjectFactory: rxjs$Subject<T> | (() => rxjs$Subject<T>)
): rxjs$ConnectableObservable<T>,
observeOn(scheduler: rxjs$SchedulerClass): rxjs$Observable<T>,
pairwise(): rxjs$Observable<[T, T]>,
publish(): rxjs$ConnectableObservable<T>,
publishLast(): rxjs$ConnectableObservable<T>,
reduce<U>(
accumulator: (
acc: U,
currentValue: T,
index: number,
source: rxjs$Observable<T>
) => U,
seed: U
): rxjs$Observable<U>,
sample(notifier: rxjs$Observable<any>): rxjs$Observable<T>,
sampleTime(
delay: number,
scheduler?: rxjs$SchedulerClass
): rxjs$Observable<T>,
publishReplay(
bufferSize?: number,
windowTime?: number,
scheduler?: rxjs$SchedulerClass
): rxjs$ConnectableObservable<T>,
retry(retryCount: ?number): rxjs$Observable<T>,
retryWhen(
notifier: (errors: rxjs$Observable<Error>) => rxjs$Observable<any>
): rxjs$Observable<T>,
scan<U>(f: (acc: U, value: T) => U, initialValue: U): rxjs$Observable<U>,
share(): rxjs$Observable<T>,
skip(count: number): rxjs$Observable<T>,
skipUntil(other: rxjs$Observable<any> | Promise<any>): rxjs$Observable<T>,
skipWhile(
predicate: (value: T, index: number) => boolean
): rxjs$Observable<T>,
startWith(...values: Array<T>): rxjs$Observable<T>,
subscribeOn(scheduler: rxjs$SchedulerClass): rxjs$Observable<T>,
take(count: number): rxjs$Observable<T>,
takeUntil(other: rxjs$Observable<any>): rxjs$Observable<T>,
takeWhile(
predicate: (value: T, index: number) => boolean
): rxjs$Observable<T>,
do(
onNext?: (value: T) => mixed,
onError?: (error: any) => mixed,
onCompleted?: () => mixed
): rxjs$Observable<T>,
do(observer: {
next?: (value: T) => mixed,
error?: (error: any) => mixed,
complete?: () => mixed
}): rxjs$Observable<T>,
throttleTime(duration: number): rxjs$Observable<T>,
timeout(due: number | Date, _: void): rxjs$Observable<T>,
timeoutWith<U>(
due: number | Date,
withObservable: rxjs$Observable<U>,
scheduler?: rxjs$SchedulerClass
): rxjs$Observable<T | U>,
toArray(): rxjs$Observable<T[]>,
toPromise(): Promise<T>,
subscribe(observer: rxjs$PartialObserver<T>): rxjs$Subscription,
subscribe(
onNext: ?(value: T) => mixed,
onError: ?(error: any) => mixed,
onCompleted: ?() => mixed
): rxjs$Subscription,
static combineLatest<A, B>(
a: rxjs$Observable<A>,
resultSelector: (a: A) => B
): rxjs$Observable<B>,
static combineLatest<A, B, C>(
a: rxjs$Observable<A>,
b: rxjs$Observable<B>,
resultSelector: (a: A, b: B) => C
): rxjs$Observable<C>,
static combineLatest<A, B, C, D>(
a: rxjs$Observable<A>,
b: rxjs$Observable<B>,
c: rxjs$Observable<C>,
resultSelector: (a: A, b: B, c: C) => D
): rxjs$Observable<D>,
static combineLatest<A, B, C, D, E>(
a: rxjs$Observable<A>,
b: rxjs$Observable<B>,
c: rxjs$Observable<C>,
d: rxjs$Observable<D>,
resultSelector: (a: A, b: B, c: C, d: D) => E
): rxjs$Observable<E>,
static combineLatest<A, B, C, D, E, F>(
a: rxjs$Observable<A>,
b: rxjs$Observable<B>,
c: rxjs$Observable<C>,
d: rxjs$Observable<D>,
e: rxjs$Observable<E>,
resultSelector: (a: A, b: B, c: C, d: D, e: E) => F
): rxjs$Observable<F>,
static combineLatest<A, B, C, D, E, F, G>(
a: rxjs$Observable<A>,
b: rxjs$Observable<B>,
c: rxjs$Observable<C>,
d: rxjs$Observable<D>,
e: rxjs$Observable<E>,
f: rxjs$Observable<F>,
resultSelector: (a: A, b: B, c: C, d: D, e: E, f: F) => G
): rxjs$Observable<G>,
static combineLatest<A, B, C, D, E, F, G, H>(
a: rxjs$Observable<A>,
b: rxjs$Observable<B>,
c: rxjs$Observable<C>,
d: rxjs$Observable<D>,
e: rxjs$Observable<E>,
f: rxjs$Observable<F>,
g: rxjs$Observable<G>,
resultSelector: (a: A, b: B, c: C, d: D, e: E, f: F, g: G) => H
): rxjs$Observable<H>,
static combineLatest<A>(a: rxjs$Observable<A>, _: void): rxjs$Observable<[A]>,
static combineLatest<A, B>(
a: rxjs$Observable<A>,
b: rxjs$Observable<B>,
_: void
): rxjs$Observable<[A, B]>,
static combineLatest<A, B, C>(
a: rxjs$Observable<A>,
b: rxjs$Observable<B>,
c: rxjs$Observable<C>,
_: void
): rxjs$Observable<[A, B, C]>,
static combineLatest<A, B, C, D>(
a: rxjs$Observable<A>,
b: rxjs$Observable<B>,
c: rxjs$Observable<C>,
d: rxjs$Observable<D>,
_: void
): rxjs$Observable<[A, B, C, D]>,
static combineLatest<A, B, C, D, E>(
a: rxjs$Observable<A>,
b: rxjs$Observable<B>,
c: rxjs$Observable<C>,
d: rxjs$Observable<D>,
e: rxjs$Observable<E>,
_: void
): rxjs$Observable<[A, B, C, D, E]>,
static combineLatest<A, B, C, D, E, F>(
a: rxjs$Observable<A>,
b: rxjs$Observable<B>,
c: rxjs$Observable<C>,
d: rxjs$Observable<D>,
e: rxjs$Observable<E>,
f: rxjs$Observable<F>,
_: void
): rxjs$Observable<[A, B, C, D, E, F]>,
static combineLatest<A, B, C, D, E, F, G>(
a: rxjs$Observable<A>,
b: rxjs$Observable<B>,
c: rxjs$Observable<C>,
d: rxjs$Observable<D>,
e: rxjs$Observable<E>,
f: rxjs$Observable<F>,
g: rxjs$Observable<G>,
_: void
): rxjs$Observable<[A, B, C, D, E, F, G]>,
static combineLatest<A, B, C, D, E, F, G, H>(
a: rxjs$Observable<A>,
b: rxjs$Observable<B>,
c: rxjs$Observable<C>,
d: rxjs$Observable<D>,
e: rxjs$Observable<E>,
f: rxjs$Observable<F>,
g: rxjs$Observable<G>,
h: rxjs$Observable<H>,
_: void
): rxjs$Observable<[A, B, C, D, E, F, G, H]>,
combineLatest<A>(a: rxjs$Observable<A>, _: void): rxjs$Observable<[T, A]>,
combineLatest<A, B>(
a: rxjs$Observable<A>,
resultSelector: (a: A) => B
): rxjs$Observable<B>,
combineLatest<A, B, C>(
a: rxjs$Observable<A>,
b: rxjs$Observable<B>,
resultSelector: (a: A, b: B) => C
): rxjs$Observable<C>,
combineLatest<A, B, C, D>(
a: rxjs$Observable<A>,
b: rxjs$Observable<B>,
c: rxjs$Observable<C>,
resultSelector: (a: A, b: B, c: C) => D
): rxjs$Observable<D>,
combineLatest<A, B, C, D, E>(
a: rxjs$Observable<A>,
b: rxjs$Observable<B>,
c: rxjs$Observable<C>,
d: rxjs$Observable<D>,
resultSelector: (a: A, b: B, c: C, d: D) => E
): rxjs$Observable<E>,
combineLatest<A, B, C, D, E, F>(
a: rxjs$Observable<A>,
b: rxjs$Observable<B>,
c: rxjs$Observable<C>,
d: rxjs$Observable<D>,
e: rxjs$Observable<E>,
resultSelector: (a: A, b: B, c: C, d: D, e: E) => F
): rxjs$Observable<F>,
combineLatest<A, B, C, D, E, F, G>(
a: rxjs$Observable<A>,
b: rxjs$Observable<B>,
c: rxjs$Observable<C>,
d: rxjs$Observable<D>,
e: rxjs$Observable<E>,
f: rxjs$Observable<F>,
resultSelector: (a: A, b: B, c: C, d: D, e: E, f: F) => G
): rxjs$Observable<G>,
combineLatest<A, B, C, D, E, F, G, H>(
a: rxjs$Observable<A>,
b: rxjs$Observable<B>,
c: rxjs$Observable<C>,
d: rxjs$Observable<D>,
e: rxjs$Observable<E>,
f: rxjs$Observable<F>,
g: rxjs$Observable<G>,
resultSelector: (a: A, b: B, c: C, d: D, e: E, f: F, g: G) => H
): rxjs$Observable<H>,
static forkJoin<A, B>(
a: rxjs$Observable<A>,
resultSelector: (a: A) => B
): rxjs$Observable<B>,
static forkJoin<A, B, C>(
a: rxjs$Observable<A>,
b: rxjs$Observable<B>,
resultSelector: (a: A, b: B) => C
): rxjs$Observable<C>,
static forkJoin<A, B, C, D>(
a: rxjs$Observable<A>,
b: rxjs$Observable<B>,
c: rxjs$Observable<C>,
resultSelector: (a: A, b: B, c: C) => D
): rxjs$Observable<D>,
static forkJoin<A, B, C, D, E>(
a: rxjs$Observable<A>,
b: rxjs$Observable<B>,
c: rxjs$Observable<C>,
d: rxjs$Observable<D>,
resultSelector: (a: A, b: B, c: C, d: D) => E
): rxjs$Observable<E>,
static forkJoin<A, B, C, D, E, F>(
a: rxjs$Observable<A>,
b: rxjs$Observable<B>,
c: rxjs$Observable<C>,
d: rxjs$Observable<D>,
e: rxjs$Observable<E>,
resultSelector: (a: A, b: B, c: C, d: D, e: E) => F
): rxjs$Observable<F>,
static forkJoin<A, B, C, D, E, F, G>(
a: rxjs$Observable<A>,
b: rxjs$Observable<B>,
c: rxjs$Observable<C>,
d: rxjs$Observable<D>,
e: rxjs$Observable<E>,
f: rxjs$Observable<F>,
resultSelector: (a: A, b: B, c: C, d: D, e: E, f: F) => G
): rxjs$Observable<G>,
static forkJoin<A, B, C, D, E, F, G, H>(
a: rxjs$Observable<A>,
b: rxjs$Observable<B>,
c: rxjs$Observable<C>,
d: rxjs$Observable<D>,
e: rxjs$Observable<E>,
f: rxjs$Observable<F>,
g: rxjs$Observable<G>,
resultSelector: (a: A, b: B, c: C, d: D, e: E, f: F, g: G) => H
): rxjs$Observable<H>,
static forkJoin<A, B>(
a: rxjs$Observable<A>,
b: rxjs$Observable<B>,
_: void
): rxjs$Observable<[A, B]>,
static forkJoin<A, B, C>(
a: rxjs$Observable<A>,
b: rxjs$Observable<B>,
c: rxjs$Observable<C>,
_: void
): rxjs$Observable<[A, B, C]>,
static forkJoin<A, B, C, D>(
a: rxjs$Observable<A>,
b: rxjs$Observable<B>,
c: rxjs$Observable<C>,
d: rxjs$Observable<D>,
_: void
): rxjs$Observable<[A, B, C, D]>,
static forkJoin<A, B, C, D, E>(
a: rxjs$Observable<A>,
b: rxjs$Observable<B>,
c: rxjs$Observable<C>,
d: rxjs$Observable<D>,
e: rxjs$Observable<E>,
_: void
): rxjs$Observable<[A, B, C, D, E]>,
static forkJoin<A, B, C, D, E, F>(
a: rxjs$Observable<A>,
b: rxjs$Observable<B>,
c: rxjs$Observable<C>,
d: rxjs$Observable<D>,
e: rxjs$Observable<E>,
f: rxjs$Observable<F>,
_: void
): rxjs$Observable<[A, B, C, D, E, F]>,
static forkJoin<A, B, C, D, E, F, G>(
a: rxjs$Observable<A>,
b: rxjs$Observable<B>,
c: rxjs$Observable<C>,
d: rxjs$Observable<D>,
e: rxjs$Observable<E>,
f: rxjs$Observable<F>,
g: rxjs$Observable<G>,
_: void
): rxjs$Observable<[A, B, C, D, E, F, G]>,
static forkJoin<A, B, C, D, E, F, G, H>(
a: rxjs$Observable<A>,
b: rxjs$Observable<B>,
c: rxjs$Observable<C>,
d: rxjs$Observable<D>,
e: rxjs$Observable<E>,
f: rxjs$Observable<F>,
g: rxjs$Observable<G>,
h: rxjs$Observable<H>,
_: void
): rxjs$Observable<[A, B, C, D, E, F, G, H]>,
withLatestFrom<A>(a: rxjs$Observable<A>, _: void): rxjs$Observable<[T, A]>,
withLatestFrom<A, B>(
a: rxjs$Observable<A>,
resultSelector: (a: A) => B
): rxjs$Observable<B>,
withLatestFrom<A, B, C>(
a: rxjs$Observable<A>,
b: rxjs$Observable<B>,
resultSelector: (a: A, b: B) => C
): rxjs$Observable<C>,
withLatestFrom<A, B, C, D>(
a: rxjs$Observable<A>,
b: rxjs$Observable<B>,
c: rxjs$Observable<C>,
resultSelector: (a: A, b: B, c: C) => D
): rxjs$Observable<D>,
withLatestFrom<A, B, C, D, E>(
a: rxjs$Observable<A>,
b: rxjs$Observable<B>,
c: rxjs$Observable<C>,
d: rxjs$Observable<D>,
resultSelector: (a: A, b: B, c: C, d: D) => E
): rxjs$Observable<E>,
withLatestFrom<A, B, C, D, E, F>(
a: rxjs$Observable<A>,
b: rxjs$Observable<B>,
c: rxjs$Observable<C>,
d: rxjs$Observable<D>,
e: rxjs$Observable<E>,
resultSelector: (a: A, b: B, c: C, d: D, e: E) => F
): rxjs$Observable<F>,
withLatestFrom<A, B, C, D, E, F, G>(
a: rxjs$Observable<A>,
b: rxjs$Observable<B>,
c: rxjs$Observable<C>,
d: rxjs$Observable<D>,
e: rxjs$Observable<E>,
f: rxjs$Observable<F>,
resultSelector: (a: A, b: B, c: C, d: D, e: E, f: F) => G
): rxjs$Observable<G>,
withLatestFrom<A, B, C, D, E, F, G, H>(
a: rxjs$Observable<A>,
b: rxjs$Observable<B>,
c: rxjs$Observable<C>,
d: rxjs$Observable<D>,
e: rxjs$Observable<E>,
f: rxjs$Observable<F>,
g: rxjs$Observable<G>,
resultSelector: (a: A, b: B, c: C, d: D, e: E, f: F, g: G) => H
): rxjs$Observable<H>,
static using<R: rxjs$ISubscription>(
resourceFactory: () => ?R,
observableFactory: (resource: R) => rxjs$Observable<T> | Promise<T> | void
): rxjs$Observable<T>,
_subscribe(observer: rxjs$Subscriber<T>): rxjs$Subscription,
_isScalar: boolean,
source: ?rxjs$Observable<any>,
operator: ?rxjs$Operator<any, any>
}
declare class rxjs$ConnectableObservable<T> extends rxjs$Observable<T> {
connect(): rxjs$Subscription,
refCount(): rxjs$Observable<T>
}
declare class rxjs$GroupedObservable<K, V> extends rxjs$Observable<V> {
key: K
}
declare class rxjs$Observer<T> {
next(value: T): mixed,
error(error: any): mixed,
complete(): mixed
}
declare interface rxjs$Operator<T, R> {
call(subscriber: rxjs$Subscriber<R>, source: any): rxjs$TeardownLogic
}
// FIXME(samgoldman) should be `mixins rxjs$Observable<T>, rxjs$Observer<T>`
// once Babel parsing support exists: https://phabricator.babeljs.io/T6821
declare class rxjs$Subject<T> extends rxjs$Observable<T> {
asObservable(): rxjs$Observable<T>,
observers: Array<rxjs$Observer<T>>,
unsubscribe(): void,
// Copied from rxjs$Observer<T>
next(value: T): mixed,
error(error: any): mixed,
complete(): mixed,
// For use in subclasses only:
_next(value: T): void
}
declare class rxjs$AnonymousSubject<T> extends rxjs$Subject<T> {
source: ?rxjs$Observable<T>,
destination: ?rxjs$Observer<T>,
constructor(
destination?: rxjs$IObserver<T>,
source?: rxjs$Observable<T>
): void,
next(value: T): void,
error(err: any): void,
complete(): void
}
declare class rxjs$BehaviorSubject<T> extends rxjs$Subject<T> {
constructor(initialValue: T): void,
getValue(): T
}
declare class rxjs$ReplaySubject<T> extends rxjs$Subject<T> {
constructor(
bufferSize?: number,
windowTime?: number,
scheduler?: rxjs$SchedulerClass
): void
}
declare class rxjs$Subscription {
unsubscribe(): void,
add(teardown: rxjs$TeardownLogic): rxjs$Subscription
}
declare class rxjs$Subscriber<T> extends rxjs$Subscription {
static create<T>(
next?: (x?: T) => void,
error?: (e?: any) => void,
complete?: () => void
): rxjs$Subscriber<T>,
constructor(
destinationOrNext?: rxjs$PartialObserver<any> | ((value: T) => void),
error?: (e?: any) => void,
complete?: () => void
): void,
next(value?: T): void,
error(err?: any): void,
complete(): void,
unsubscribe(): void
}
declare class rxjs$SchedulerClass {
schedule<T>(
work: (state?: T) => void,
delay?: number,
state?: T
): rxjs$Subscription
}
declare class rxjs$TimeoutError extends Error {}
declare module "rxjs" {
declare module.exports: {
Observable: typeof rxjs$Observable,
Observer: typeof rxjs$Observer,
ConnectableObservable: typeof rxjs$ConnectableObservable,
Subject: typeof rxjs$Subject,
Subscriber: typeof rxjs$Subscriber,
AnonymousSubject: typeof rxjs$AnonymousSubject,
BehaviorSubject: typeof rxjs$BehaviorSubject,
ReplaySubject: typeof rxjs$ReplaySubject,
Scheduler: {
asap: rxjs$SchedulerClass,
queue: rxjs$SchedulerClass,
animationFrame: rxjs$SchedulerClass,
async: rxjs$SchedulerClass
},
Subscription: typeof rxjs$Subscription,
TimeoutError: typeof rxjs$TimeoutError
};
}
declare module "rxjs/Observable" {
declare module.exports: {
Observable: typeof rxjs$Observable
};
}
declare module "rxjs/Observer" {
declare module.exports: {
Observer: typeof rxjs$Observer
};
}
declare module "rxjs/BehaviorSubject" {
declare module.exports: {
BehaviorSubject: typeof rxjs$BehaviorSubject
};
}
declare module "rxjs/ReplaySubject" {
declare module.exports: {
ReplaySubject: typeof rxjs$ReplaySubject
};
}
declare module "rxjs/Subject" {
declare module.exports: {
Subject: typeof rxjs$Subject,
AnonymousSubject: typeof rxjs$AnonymousSubject
};
}
declare module "rxjs/Subscriber" {
declare module.exports: {
Subscriber: typeof rxjs$Subscriber
};
}
declare module "rxjs/Subscription" {
declare module.exports: {
Subscription: typeof rxjs$Subscription
};
}
declare module "rxjs/testing/TestScheduler" {
declare module.exports: {
TestScheduler: typeof rxjs$SchedulerClass
};
}
|
/// <reference path="typings/node/node.d.ts" />
/// <reference path="typings/genetic-algorithm/interfaces.d.ts" />
var Randomizer = (function () {
function Randomizer(random) {
if (typeof random === "undefined") { random = Math.random; }
this.random = random;
}
Randomizer.prototype.randomInt = function (max) {
return Math.round(this.random() * max) * 10 / 10;
};
Randomizer.prototype.randomBetween = function (from, to, step) {
var out = +from + this.random() * (to - from);
out = Math.round(out / step) * step;
return out * 10 / 10;
};
return Randomizer;
})();
module.exports = Randomizer;
|
Package.describe({
name: "nova:debug",
summary: "Telescope debug package",
version: "1.2.0",
git: "https://github.com/TelescopeJS/Telescope.git"
});
Package.onUse(function (api) {
api.versionsFrom(['METEOR@1.0']);
api.use([
'fourseven:scss',
// Nova packages
'nova:core@1.2.0',
'nova:posts@1.2.0',
'nova:users@1.2.0',
'nova:email@1.2.0',
'nova:comments@1.2.0'
]);
api.addFiles([
'lib/stylesheets/debug.scss'
], ['client']);
api.addFiles([
'lib/components.js',
'lib/routes.jsx',
'lib/globals.js'
], ['client', 'server']);
api.addFiles([
'lib/server/methods.js'
], ['server']);
api.export([
'Telescope',
'Posts',
'Comments',
'Users',
'Categories'
], ['client', 'server']);
});
|
// VARS SCROLL LISTENER
var canScroll = true;
var transitionsTiming = 900;
var pauseToLoadSection = 500;
var lastSectionId = 15;
// SCROLL LISTENER
// $('#mbrtWrapper').on('mousewheel', function(event) {
// // CONTROL TRIGGERING
// // Change section only if the current section has been fully loaded
// if(canScroll && event.deltaY != 0){
// // DELAY DEACTIVATING AND REACTIVATING 'CAN SCROLL' FLAG WHILE SCROLLING BETWEEN SECTIONS
// delayBetweenSections();
// // CHECK IF JS IS DETECTING MOUSEWHEEL
// // console.log('Scroll started.');
// // console.log(event.deltaX, event.deltaY, event.deltaFactor);
// // Detect if user is scrolling down
// if (event.deltaY < 0 && currentSectionId < lastSectionId) {
// // CHANGE TO NEXT SECTION
// scrollNextSection();
// // CONDITIONAL TO KNOW WHAT SECTION IS
// switch (currentSectionId) {
// // From Index to Welcome Section
// case 0:
// showMainNavs();
// currentSectionId = 1;
// window.history.pushState("object or string", "section", "?welcome");
// break;
// // From Welcome to Services Section
// case 1:
// activeNextNavBar();
// currentSectionId = 2;
// window.history.pushState("object or string", "section", "?services");
// break;
// // From Services to Branding cover Section
// case 2:
// activeNextNavBar();
// currentSectionId = 3;
// window.history.pushState("object or string", "section", "?branding");
// break;
// // From Branding cover to Logos carousel Section
// case 3:
// activeNextNavBar();
// currentSectionId = 4;
// window.history.pushState("object or string", "section", "?logos");
// break;
// // From Logos carousel to Stationery carousel Section
// case 4:
// activeNextNavBar();
// currentSectionId = 5;
// window.history.pushState("object or string", "section", "?stationery");
// break;
// // From Stationery carousel to Brand Communication cover Section
// case 5:
// activeNextNavBar();
// currentSectionId = 6;
// window.history.pushState("object or string", "section", "?communication");
// break;
// // From Brand Communication cover to Packaging Carousel Section
// case 6:
// activeNextNavBar();
// currentSectionId = 7;
// window.history.pushState("object or string", "section", "?packaging");
// break;
// // From Packaging Carousel to Uniforms Carousel Section
// case 7:
// activeNextNavBar();
// currentSectionId = 8;
// window.history.pushState("object or string", "section", "?uniforms");
// break;
// // From Uniforms Carousel to POS Carousel Section
// case 8:
// activeNextNavBar();
// currentSectionId = 9;
// window.history.pushState("object or string", "section", "?pos");
// break;
// // From POS Carousel to Interiorism Carousel Section
// case 9:
// activeNextNavBar();
// currentSectionId = 10;
// window.history.pushState("object or string", "section", "?interiorism");
// break;
// // From Interiorism Carousel to Advertisign Carousel Section
// case 10:
// activeNextNavBar();
// currentSectionId = 11;
// window.history.pushState("object or string", "section", "?advertising");
// break;
// // From Advertising Carousel to Web Design & Development Cover Section
// case 11:
// activeNextNavBar();
// currentSectionId = 12;
// window.history.pushState("object or string", "section", "?web");
// break;
// // From Web D&D Cover to Lucky Website Carousel Section
// case 12:
// activeNextNavBar();
// currentSectionId = 13;
// window.history.pushState("object or string", "section", "?lucky");
// break;
// // From Lucky Website Carousel to Camila Website Carousel Section
// case 13:
// activeNextNavBar();
// currentSectionId = 14;
// window.history.pushState("object or string", "section", "?camila");
// break;
// // From Camila Website Carousel to Contact Final Section
// case 14:
// activeNextNavBar();
// currentSectionId = 15;
// window.history.pushState("object or string", "section", "?contact");
// break;
// }
// }
// // Detect if user is scrolling up
// else if ( event.deltaY > 0 && currentSectionId > 0){
// // CHANGE TO PREVIOUS SECTION
// scrollPreviousSection();
// // CONDITIONAL TO KNOW WHAT SECTION IS
// switch (currentSectionId) {
// // From Welcome to Index Section
// case 1:
// hideMainNavs();
// currentSectionId = 0;
// window.history.pushState("object or string", "section", "?index");
// break;
// // From Services to Welcome Section
// case 2:
// activePreviousNavBar();
// currentSectionId = 1;
// window.history.pushState("object or string", "section", "?welcome");
// break;
// // From Branding cover to Services Section
// case 3:
// activePreviousNavBar();
// currentSectionId = 2;
// window.history.pushState("object or string", "section", "?services");
// break;
// // From Logos carousel to Branding cover Section
// case 4:
// activePreviousNavBar();
// currentSectionId = 3;
// window.history.pushState("object or string", "section", "?branding");
// break;
// // From Stationery carousel to Logos carousel Section
// case 5:
// activePreviousNavBar();
// currentSectionId = 4;
// window.history.pushState("object or string", "section", "?logos");
// break;
// // From Brand Communications cover to Stationery carousel Section
// case 6:
// activePreviousNavBar();
// currentSectionId = 5;
// window.history.pushState("object or string", "section", "?stationery");
// break;
// // From Packaging Carousel to Brand Communications cover Section
// case 7:
// activePreviousNavBar();
// currentSectionId = 6;
// window.history.pushState("object or string", "section", "?communication");
// break;
// // From Uniforms Carousel to Packaging Carousel Section
// case 8:
// activePreviousNavBar();
// currentSectionId = 7;
// window.history.pushState("object or string", "section", "?packaging");
// break;
// // From POS Carousel to Uniforms Carousel Section
// case 9:
// activePreviousNavBar();
// currentSectionId = 8;
// window.history.pushState("object or string", "section", "?uniforms");
// break;
// // From Interiorism Carousel to POS Carousel Section
// case 10:
// activePreviousNavBar();
// currentSectionId = 9;
// window.history.pushState("object or string", "section", "?pos");
// break;
// // From Advertising Carousel to Interiorism Carousel Section
// case 11:
// activePreviousNavBar();
// currentSectionId = 10;
// window.history.pushState("object or string", "section", "?interiorism");
// break;
// // From Website Design & Development cover to Advertising Carousel Section
// case 12:
// activePreviousNavBar();
// currentSectionId = 11;
// window.history.pushState("object or string", "section", "?advertising");
// break;
// // From Lucky Website Carousel to Website Design & Development cover Section
// case 13:
// activePreviousNavBar();
// currentSectionId = 12;
// window.history.pushState("object or string", "section", "?web");
// break;
// // From Camila Website Carousel to Lucky Website Carousel Section
// case 14:
// activePreviousNavBar();
// currentSectionId = 13;
// window.history.pushState("object or string", "section", "?lucky");
// break;
// // From Contact Final Section to Camila Website Carousel Section
// case 15:
// activePreviousNavBar();
// currentSectionId = 14;
// window.history.pushState("object or string", "section", "?camila");
// break;
// }
// }
// } else{
// // PREVENT OVERLAPING CHANGE SECTION ANIMATIONS
// // If there is an animation running to change the section, wait until it's over to change of section again
// event.preventDefault();
// // NOTICE YOU HAVE TO WAIT TO SCROLL AGAIN
// // console.log("You can't scroll yet, canScroll: " + canScroll);
// }
// });
// HELPER FUNCTIONS
// CHANGE TO PREVIOUS OR NEXT SECTION BY ID
function navigateNextSection(fromThis, toThis){
fromThis.addClass('passed-up');
fromThis.removeClass('is-active');
toThis.addClass('is-active');
toThis.removeClass('coming-up');
}
function navigatePrevSection(fromThis, toThis){
fromThis.addClass('coming-up');
fromThis.removeClass('is-active');
toThis.addClass('is-active');
toThis.removeClass('passed-up');
}
// CHANGE OF SECTION BY CLASSES
function scrollNextSection(){
// CHANGE POSITION OF CURRENT SECTION TO 'PASSED' SECTION
$('.is-active').addClass('passed-up');
$('.is-active').removeClass('is-active');
// CHANGE POSITION OF THE FIRST 'COMING UP' SECTION TO CURRENT 'ACTIVE' SECTION
comingUpSections = $('#mbrtWrapper').find('.coming-up');
$(comingUpSections[0]).addClass('is-active');
$(comingUpSections[0]).removeClass('coming-up');
}
function scrollPreviousSection(){
// CHANGE POSITION OF CURRENT SECTION TO 'COMING UP' SECTION
$('.is-active').addClass('coming-up');
$('.is-active').removeClass('is-active');
// CHANGE POSITION OF THE LAST 'PASSED UP' SECTION TO CURRENT 'ACTIVE' SECTION
passedUpSections = $('#mbrtWrapper').find('.passed-up');
$(passedUpSections[passedUpSections.length - 1]).addClass('is-active');
$(passedUpSections[passedUpSections.length - 1]).removeClass('passed-up');
}
// DELAY WHILE SCROLLING TO NEXT OR PREVIOUS SECTIONS
function delayBetweenSections(){
canScroll = false;
setTimeout(function(){
canScroll = true;
},transitionsTiming + pauseToLoadSection);
}
|
// ## Globals
var argv = require('minimist')(process.argv.slice(2));
var autoprefixer = require('gulp-autoprefixer');
var browserSync = require('browser-sync').create();
var changed = require('gulp-changed');
var concat = require('gulp-concat');
var flatten = require('gulp-flatten');
var gulp = require('gulp');
var gulpif = require('gulp-if');
var imagemin = require('gulp-imagemin');
var jshint = require('gulp-jshint');
var lazypipe = require('lazypipe');
var less = require('gulp-less');
var merge = require('merge-stream');
var minifyCss = require('gulp-minify-css');
var plumber = require('gulp-plumber');
var rev = require('gulp-rev');
var runSequence = require('run-sequence');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglify');
// Bless CSS
var bless = require('gulp-bless');
// Fonts CSS
var replace = require('gulp-replace');
var gutil = require('gulp-util');
var concatutil = require('gulp-concat-util');
// Upload via FTP
var vinylftp = require('vinyl-ftp');
var emptycache = require('gulp-open');
var ftppass = require('./.ftppass.json');
var dotenv = require('dotenv').config({path: '../../../../.env'});
// See https://github.com/austinpray/asset-builder
var manifest = require('asset-builder')('./assets/manifest.json');
// `path` - Paths to base asset directories. With trailing slashes.
// - `path.source` - Path to the source files. Default: `assets/`
// - `path.dist` - Path to the build directory. Default: `dist/`
var path = manifest.paths;
// `config` - Store arbitrary configuration values here.
var config = manifest.config || {};
// `globs` - These ultimately end up in their respective `gulp.src`.
// - `globs.js` - Array of asset-builder JS dependency objects. Example:
// ```
// {type: 'js', name: 'main.js', globs: []}
// ```
// - `globs.css` - Array of asset-builder CSS dependency objects. Example:
// ```
// {type: 'css', name: 'main.css', globs: []}
// ```
// - `globs.fonts` - Array of font path globs.
// - `globs.images` - Array of image path globs.
// - `globs.bower` - Array of all the main Bower files.
var globs = manifest.globs;
// `project` - paths to first-party assets.
// - `project.js` - Array of first-party JS assets.
// - `project.css` - Array of first-party CSS assets.
var project = manifest.getProjectGlobs();
// CLI options
var enabled = {
// Enable static asset revisioning when `--production`
rev: argv.production,
// Disable source maps when `--production`
maps: !argv.production,
// Fail styles task on error when `--production`
failStyleTask: argv.production,
// Fail due to JSHint warnings only when `--production`
failJSHint: argv.production,
// Strip debug statments from javascript when `--production`
stripJSDebug: argv.production
};
// Path to the compiled assets manifest in the dist directory
var revManifest = path.dist + 'assets.json';
// ## Reusable Pipelines
// See https://github.com/OverZealous/lazypipe
// ### CSS processing pipeline
// Example
// ```
// gulp.src(cssFiles)
// .pipe(cssTasks('main.css')
// .pipe(gulp.dest(path.dist + 'styles'))
// ```
var cssTasks = function(filename) {
return lazypipe()
.pipe(function() {
return gulpif(!enabled.failStyleTask, plumber());
})
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.init());
})
.pipe(function() {
return gulpif('*.less', less());
})
.pipe(function() {
return gulpif('*.scss', sass({
outputStyle: 'nested', // libsass doesn't support expanded yet
precision: 10,
includePaths: ['.'],
errLogToConsole: !enabled.failStyleTask
}));
})
.pipe(concat, filename)
.pipe(autoprefixer, {
browsers: [
'last 2 versions',
'android 4',
'opera 12',
'ie >= 9'
]
})
.pipe(minifyCss, {
advanced: false,
rebase: false
})
.pipe(function() {
return gulpif(enabled.rev, rev());
})
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.write('.', {
sourceRoot: 'assets/styles/'
}));
})();
};
// ### JS processing pipeline
// Example
// ```
// gulp.src(jsFiles)
// .pipe(jsTasks('main.js')
// .pipe(gulp.dest(path.dist + 'scripts'))
// ```
var jsTasks = function(filename) {
return lazypipe()
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.init());
})
.pipe(concat, filename)
.pipe(uglify, {
compress: {
'drop_debugger': enabled.stripJSDebug
}
})
.pipe(function() {
return gulpif(enabled.rev, rev());
})
.pipe(function() {
return gulpif(enabled.maps, sourcemaps.write('.', {
sourceRoot: 'assets/scripts/'
}));
})();
};
// ### Write to rev manifest
// If there are any revved files then write them to the rev manifest.
// See https://github.com/sindresorhus/gulp-rev
var writeToManifest = function(directory) {
return lazypipe()
.pipe(gulp.dest, path.dist + directory)
.pipe(browserSync.stream, {match: '**/*.{js,css}'})
.pipe(rev.manifest, revManifest, {
base: path.dist,
merge: true
})
.pipe(gulp.dest, path.dist)();
};
// ## Gulp tasks
// Run `gulp -T` for a task summary
// ### Styles
// `gulp styles` - Compiles, combines, and optimizes Bower CSS and project CSS.
// By default this task will only log a warning if a precompiler error is
// raised. If the `--production` flag is set: this task will fail outright.
gulp.task('styles', ['wiredep'], function() {
var merged = merge();
manifest.forEachDependency('css', function(dep) {
var cssTasksInstance = cssTasks(dep.name);
if (!enabled.failStyleTask) {
cssTasksInstance.on('error', function(err) {
console.error(err.message);
this.emit('end');
});
}
merged.add(gulp.src(dep.globs, {base: 'styles'})
.pipe(cssTasksInstance));
});
return merged
.pipe(writeToManifest('styles'));
});
// ### Font CSS task
// Take all the fontcss stylesheets and concat them into a single SCSS file
gulp.task ('font-css', function() {
return gulp.src([path.source + 'fonts/**/style.css', path.source + 'fonts/**/font.css']) //Gather up all the 'style.css' & 'font.css' files
.pipe(concat('_fonts.scss')) //Concat them all into a single file
.pipe(concatutil.header('/* !!! WARNING !!! \nThis file is auto-generated. \nDo not edit it or else you will lose changes next time you compile! */\n\n'))
.pipe(replace("url('fonts/", "url('../fonts/"))
.pipe(gulp.dest(path.source + ['styles/components'])); // Put them in the assets/styles/components folder
});
// ### Bless
// CSS post-processor which splits CSS files suitably for Internet Explorer < 10. Bless + Gulp = gulp-bless.
gulp.task('bless', function() {
return gulp.src(path.dist + 'styles/*.css')
.pipe(bless())
.pipe(gulp.dest(path.dist + 'styles'));
});
// ### Scripts
// `gulp scripts` - Runs JSHint then compiles, combines, and optimizes Bower JS
// and project JS.
gulp.task('scripts', ['jshint'], function() {
var merged = merge();
manifest.forEachDependency('js', function(dep) {
merged.add(
gulp.src(dep.globs, {base: 'scripts'})
.pipe(jsTasks(dep.name))
);
});
return merged
.pipe(writeToManifest('scripts'));
});
// ### Fonts
// `gulp fonts` - Grabs all the fonts and outputs them in a flattened directory
// structure. See: https://github.com/armed/gulp-flatten
gulp.task('fonts', function() {
return gulp.src(globs.fonts)
.pipe(flatten())
.pipe(gulp.dest(path.dist + 'fonts'))
.pipe(browserSync.stream());
});
// ### Images
// `gulp images` - Run lossless compression on all the images.
gulp.task('images', function() {
return gulp.src(globs.images)
.pipe(imagemin({
progressive: true,
interlaced: true,
svgoPlugins: [{removeUnknownsAndDefaults: false}, {cleanupIDs: false}]
}))
.pipe(gulp.dest(path.dist + 'images'))
.pipe(browserSync.stream());
});
// ### JSHint
// `gulp jshint` - Lints configuration JSON and project JS.
gulp.task('jshint', function() {
return gulp.src([
'bower.json', 'gulpfile.js'
].concat(project.js))
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'))
.pipe(gulpif(enabled.failJSHint, jshint.reporter('fail')));
});
// ### Upload
gulp.task('upload', function(callback) {
runSequence('rmdirdist', 'ftpupload', 'emptycache', callback);
});
// ### Remove remote dist directory
gulp.task( 'rmdirdist', function (cb) {
var conn = vinylftp.create( ftppass );
conn.rmdir( '/public_html/app/themes/piano-rivera/dist', cb );
});
// ### Upload Vinyl FTP
gulp.task('ftpupload', function (callback) {
var conn = vinylftp.create({
host: ftppass.host,
user: ftppass.user,
password: ftppass.password,
log: gutil.log
});
var globs = [
'*.php',
'*.png',
'dist/**',
'dist/scripts/*(.js|+(-*.js))',
'dist/styles/*(.css|+(-*.css))',
'lang/**',
'lib/**',
'templates/*.php',
'views/*.twig'
];
// using base = '.' will transfer everything to /public_html correctly
// turn off buffering in gulp.src for best performance
return gulp.src( globs, { base: '.', buffer: false } )
.pipe( conn.newer( '/public_html/app/themes/piano-rivera' ) ) // only upload newer files
.pipe( conn.dest( '/public_html/app/themes/piano-rivera' ) );
});
// ### Empty Cache
gulp.task('emptycache', function(cb) {
gulp.src('')
.pipe(emptycache({uri: 'http://www.piano-rivera.nl/?w3tcEmptyCache=' + process.env.W3T_CACHE_SECRET}));
});
// ### Clean
// `gulp clean` - Deletes the build folder entirely.
gulp.task('clean', require('del').bind(null, [path.dist]));
// `gulp clean-font-css` - Remove the font-face SCSS file if a cleanup is run
gulp.task('clean-font-css', require('del').bind(null, [path.source + 'styles/components/_fonts.scss']));
// ### Watch
// `gulp watch` - Use BrowserSync to proxy your dev server and synchronize code
// changes across devices. Specify the hostname of your dev server at
// `manifest.config.devUrl`. When a modification is made to an asset, run the
// build step for that asset and inject the changes into the page.
// See: http://www.browsersync.io
gulp.task('watch', function() {
browserSync.init({
files: ['{lib,templates,views}/**/*.{php,twig}', '*.php'],
proxy: config.devUrl,
snippetOptions: {
whitelist: ['/wp-admin/admin-ajax.php'],
blacklist: ['/wp-admin/**']
}
});
gulp.watch([path.source + 'fonts/**/style.css', path.source + 'fonts/**/font.css'], ['font-css']);
gulp.watch([path.source + 'styles/**/*'], ['styles']);
gulp.watch([path.source + 'styles/**/*'], ['bless']);
gulp.watch([path.source + 'scripts/**/*'], ['jshint', 'scripts']);
gulp.watch([path.source + 'fonts/**/*'], ['fonts']);
gulp.watch([path.source + 'images/**/*'], ['images']);
gulp.watch(['bower.json', 'assets/manifest.json'], ['build']);
});
// ### Build
// `gulp build` - Run all the build tasks but don't clean up beforehand.
// Generally you should be running `gulp` instead of `gulp build`.
gulp.task('build', function(callback) {
var tasks = [
'font-css',
'styles',
'bless',
'scripts',
['fonts', 'images']
];
// only add upload to task list if `--production`
if (argv.production) {
tasks = tasks.concat(['upload']);
}
runSequence.apply(
this,
tasks.concat([callback])
);
});
// ### Wiredep
// `gulp wiredep` - Automatically inject Less and Sass Bower dependencies. See
// https://github.com/taptapship/wiredep
gulp.task('wiredep', function() {
var wiredep = require('wiredep').stream;
return gulp.src(project.css)
.pipe(wiredep())
.pipe(changed(path.source + 'styles', {
hasChanged: changed.compareSha1Digest
}))
.pipe(gulp.dest(path.source + 'styles'));
});
// ### Gulp
// `gulp` - Run a complete build. To compile for production run `gulp --production`.
gulp.task('default', ['clean', 'clean-font-css'], function() {
gulp.start('build');
});
|
export default {
logging: "Iniciando sesión...",
logCall: "Registrar llamada",
editLog: "Editar registro",
select: "Seleccionar una grabación que coincida",
OnHold: "En espera",
Ringing: "Llamando",
CallConnected: "Llamada conectada",
unknownUser: "Usuario desconocido",
unknownNumber: "Anónimo",
unavailable: "No disponible",
viewDetails: "Ver detalles",
addEntity: "Crear nuevo",
addLog: "Registro",
text: "Mensaje",
call: "Llamar",
missedCall: "Perdida",
inboundCall: "Entrante",
outboundCall: "Saliente"
};
// @key: @#@"logging"@#@ @source: @#@"Logging..."@#@
// @key: @#@"logCall"@#@ @source: @#@"Log Call"@#@
// @key: @#@"editLog"@#@ @source: @#@"Edit Log"@#@
// @key: @#@"select"@#@ @source: @#@"Select a matching record"@#@
// @key: @#@"OnHold"@#@ @source: @#@"On Hold"@#@
// @key: @#@"Ringing"@#@ @source: @#@"Ringing"@#@
// @key: @#@"CallConnected"@#@ @source: @#@"Call Connected"@#@
// @key: @#@"unknownUser"@#@ @source: @#@"Unknown User"@#@
// @key: @#@"unknownNumber"@#@ @source: @#@"Anonymous"@#@
// @key: @#@"unavailable"@#@ @source: @#@"Unavailable"@#@
// @key: @#@"viewDetails"@#@ @source: @#@"View Details"@#@
// @key: @#@"addEntity"@#@ @source: @#@"Create New"@#@
// @key: @#@"addLog"@#@ @source: @#@"Log"@#@
// @key: @#@"text"@#@ @source: @#@"Text"@#@
// @key: @#@"call"@#@ @source: @#@"Call"@#@
// @key: @#@"missedCall"@#@ @source: @#@"Missed"@#@
// @key: @#@"inboundCall"@#@ @source: @#@"Inbound"@#@
// @key: @#@"outboundCall"@#@ @source: @#@"Outbound"@#@
|
// namespace
window.semantic = {
handler: {}
};
// Allow for console.log to not break IE
if (typeof window.console == "undefined" || typeof window.console.log == "undefined") {
window.console = {
log : function() {},
info : function(){},
warn : function(){}
};
}
if(typeof window.console.group == 'undefined' || typeof window.console.groupEnd == 'undefined' || typeof window.console.groupCollapsed == 'undefined') {
window.console.group = function(){};
window.console.groupEnd = function(){};
window.console.groupCollapsed = function(){};
}
if(typeof window.console.markTimeline == 'undefined') {
window.console.markTimeline = function(){};
}
window.console.clear = function(){};
// ready event
semantic.ready = function() {
// selector cache
var
$sortableTables = $('.sortable.table'),
$sticky = $('.ui.sticky'),
$themeDropdown = $('.theme.dropdown'),
$ui = $('.ui').not('.hover, .down'),
$swap = $('.theme.menu .item'),
$menu = $('#menu'),
$hideMenu = $('#menu .hide.item'),
$sortTable = $('.sortable.table'),
$demo = $('.demo'),
$container = $('.main.container'),
$allHeaders = $('.main.container > h2, .main.container > .tab > h2, .main.container > .tab > .examples h2'),
$sectionHeaders = $container.children('h2'),
$followMenu = $container.find('.following.menu'),
$sectionExample = $container.find('.example'),
$exampleHeaders = $sectionExample.children('h4'),
$footer = $('.page > .footer'),
$menuMusic = $('.ui.main.menu .music.item'),
$menuPopup = $('.ui.main.menu .popup.item'),
$pageDropdown = $('.ui.main.menu .page.dropdown'),
$pageTabMenu = $('.tab.header.segment .tabular.menu'),
$pageTabs = $('.tab.header.segment .menu .item'),
$languageDropdown = $('.language.dropdown'),
$languageModal = $('.language.modal'),
$downloadPopup = $('.download.button'),
$downloads = $('.download.popup'),
$downloadFramework = $('.framework.column .button'),
$downloadInput = $('.download.popup input'),
$downloadStandalone = $('.standalone.column .button'),
$helpPopup = $('.header .help.icon'),
$example = $('.example'),
$shownExample = $example.filter('.shown'),
$overview = $('.header.segment .overview'),
//$developer = $('.header .developer.item'),
//$designer = $('.header .designer.item'),
$sidebarButton = $('.fixed.launch.button'),
$code = $('div.code').not('.existing'),
$existingCode = $('.existing.code'),
languageDropdownUsed = false,
requestAnimationFrame = window.requestAnimationFrame
|| window.mozRequestAnimationFrame
|| window.webkitRequestAnimationFrame
|| window.msRequestAnimationFrame
|| function(callback) { setTimeout(callback, 0); },
// alias
handler
;
// event handlers
handler = {
createIcon: function() {
$example
.each(function(){
$('<i/>')
.addClass('icon code')
.insertAfter( $(this).children(':first-child') )
;
})
;
},
createWaypoints: function() {
$sectionHeaders
.visibility({
once: false,
offset: 70,
onTopVisible: handler.activate.accordion,
onTopPassed: handler.activate.section,
onBottomPassed: handler.activate.section,
onTopPassedReverse: handler.activate.previous
})
;
$sectionExample
.visibility({
once: false,
offset: 70,
onTopPassed: handler.activate.example,
onBottomPassedReverse: handler.activate.example
})
;
$footer
.visibility({
once: false,
onTopVisible: function() {
var
$title = $followMenu.find('> .item > .title').last()
;
$followMenu
.accordion('open', $title)
;
}
})
;
},
activate: {
previous: function() {
var
$menuItems = $followMenu.children('.item'),
$section = $menuItems.filter('.active'),
index = $menuItems.index($section)
;
if($section.prev().size() > 0) {
$section
.removeClass('active')
.prev('.item')
.addClass('active')
;
$followMenu
.accordion('open', index - 1)
;
}
},
accordion: function() {
var
$section = $(this),
index = $sectionHeaders.index($section),
$followSection = $followMenu.children('.item'),
$activeSection = $followSection.eq(index)
;
$followMenu
.accordion('open', index)
;
},
section: function() {
var
$section = $(this),
index = $sectionHeaders.index($section),
$followSection = $followMenu.children('.item'),
$activeSection = $followSection.eq(index)
;
$followSection
.removeClass('active')
;
$activeSection
.addClass('active')
;
},
example: function() {
var
$section = $(this).children('h4').eq(0),
index = $exampleHeaders.index($section),
$followSection = $followMenu.find('.menu > .item'),
$activeSection = $followSection.eq(index),
inClosedTab = ($(this).closest('.tab:not(.active)').size() > 0),
anotherExample = ($(this).filter('.another.example').size() > 0)
;
if(!inClosedTab && !anotherExample) {
$followSection
.removeClass('active')
;
$activeSection
.addClass('active')
;
}
}
},
translatePage: function(languageCode, text, $choice) {
languageDropdownUsed = true;
window.Transifex.live.translateTo(languageCode, true);
},
showLanguageModal: function(languageCode) {
var
$choice = $languageDropdown.find('[data-value="' + languageCode + '"]').eq(0),
percent = $choice.data('percent') || 0,
text = $choice.text()
;
if(percent < 100 && languageDropdownUsed) {
languageDropdownUsed = false;
$languageModal
.modal()
.find('.header .name')
.html(text)
.end()
.find('.complete')
.html(percent)
.end()
;
$languageModal
.modal('show', function() {
$('.language.modal .progress .bar').css('width', percent + '%');
})
;
}
},
tryCreateMenu: function(event) {
if($(window).width() > 640) {
if($container.find('.following.menu').size() === 0) {
handler.createMenu();
handler.createWaypoints();
$(window).off('resize.menu');
}
}
},
createAnchors: function() {
$allHeaders
.each(function() {
var
$section = $(this),
safeName = $section.text().trim().replace(/\s+/g, '-').replace(/[^-,'A-Za-z0-9]+/g, '').toLowerCase(),
id = window.escape(safeName),
$anchor = $('<a />').addClass('anchor').attr('id', id)
;
$section
.append($anchor)
;
})
;
$example
.each(function() {
var
$title = $(this).children('h4').eq(0),
safeName = $title.text().trim().replace(/\s+/g, '-').replace(/[^-,'A-Za-z0-9]+/g, '').toLowerCase(),
id = window.escape(safeName),
$anchor = $('<a />').addClass('anchor').attr('id', id)
;
if($title.size() > 0) {
$title.after($anchor);
}
})
;
},
createMenu: function() {
// grab each h3
var
html = '',
$sticky,
$rail
;
$sectionHeaders
.each(function(index) {
var
$currentHeader = $(this),
$nextElements = $currentHeader.nextUntil('h2'),
$examples = $nextElements.find('.example').andSelf().filter('.example'),
activeClass = (index === 0)
? 'active '
: '',
safeName = $currentHeader.text().trim().replace(/\s+/g, '-').replace(/[^-,'A-Za-z0-9]+/g, '').toLowerCase(),
id = window.escape(safeName),
$anchor = $('<a />').addClass('anchor').attr('id', id)
;
html += '<div class="item">';
if($examples.size() === 0) {
html += '<a class="'+activeClass+'title" href="#'+id+'"><b>' + $(this).text() + '</b></a>';
}
else {
html += '<a class="'+activeClass+'title"><i class="dropdown icon"></i> <b>' + $(this).text() + '</b></a>';
}
if($examples.size() > 0) {
html += '<div class="'+activeClass+'content menu">';
$examples
.each(function() {
var
$title = $(this).children('h4').eq(0),
safeName = $title.text().trim().replace(/\s+/g, '-').replace(/[^-,'A-Za-z0-9]+/g, '').toLowerCase(),
id = window.escape(safeName),
$anchor = $('<a />').addClass('anchor').attr('id', id)
;
if($title.size() > 0) {
html += '<a class="item" href="#'+id+'">' + $title.text() + '</a>';
}
})
;
html += '</div>';
}
html += '</div>';
})
;
$followMenu = $('<div />')
.addClass('ui secondary vertical following fluid accordion menu')
.html(html)
;
$sticky = $('<div />')
.addClass('ui sticky hidden transition')
.html($followMenu)
;
$rail = $('<div />')
.addClass('ui close right rail')
.html($sticky)
.prependTo($container)
;
$sticky
.transition('fade', function() {
$sticky.sticky({
context: $container,
offset: 50
});
})
;
$followMenu
.accordion({
exclusive: false,
onChange: function() {
$sticky.sticky('refresh');
}
})
.find('.menu a[href], .title[href]')
.on('click', handler.scrollTo)
;
},
scrollTo: function(event) {
var
id = $(this).attr('href').replace('#', ''),
$element = $('#'+id),
position = $element.offset().top
;
$element
.addClass('active')
;
$('html, body')
.animate({
scrollTop: position
}, 500)
;
location.hash = '#' + id;
event.stopImmediatePropagation();
event.preventDefault();
return false;
},
less: {
parseFile: function(content) {
var
variables = {},
lines = content.match(/^(@[\s|\S]+?;)/gm),
name,
value
;
if(lines) {
$.each(lines, function(index, line) {
// clear whitespace
line = $.trim(line);
// match variables only
if(line[0] == '@') {
name = line.match(/^@(.+?):/);
value = line.match(/:\s*([\s|\S]+?;)/);
if( ($.isArray(name) && name.length >= 2) && ($.isArray(value) && value.length >= 2) ) {
name = name[1];
value = value[1];
variables[name] = value;
}
}
});
}
console.log(variables);
return variables;
},
changeTheme: function(theme) {
var
$themeDropdown = $(this),
variableURL = '/src/themes/{$theme}/{$type}s/{$element}.variables',
overrideURL = '/src/themes/{$theme}/{$type}s/{$element}.overrides',
urlData = {
theme : typeof(theme === 'string')
? theme.toLowerCase()
: theme,
type : $themeDropdown.data('type'),
element : $themeDropdown.data('element')
}
;
$themeDropdown
.api({
on : 'now',
debug : true,
url : variableURL,
dataType : 'text',
urlData : urlData,
onSuccess: function(content) {
window.less.modifyVars( handler.less.parseFile(content) );
$themeDropdown
.api({
on : 'now',
url : overrideURL,
dataType : 'text',
urlData : urlData,
onSuccess: function(content) {
if( $('style.override').size() > 0 ) {
$('style.override').remove();
}
console.log(content);
$('<style>' + content + '</style>')
.addClass('override')
.appendTo('body')
;
$('.sticky').sticky('refresh');
}
})
;
}
})
;
}
},
create: {
examples: function(json) {
var
types = json['Types'],
text = json['Text'],
states = json['States'],
variations = json['Variations'],
$element,
html
;
$.each(types, function(name, type){
html += '<h2 class="ui dividing header">' + name + '</h2';
if($.isPlainObject(type)) {
$.each(type, function(name, subType) {
$element = $.zc(subType);
$element = handler.create.text($element, text);
html += '<h3 class="ui header">' + name + '</h3';
html += handler.create.variations($element, variations);
});
}
else {
$element = $.zc(type);
$element = handler.create.text($element);
html += handler.create.variations($element, variations);
}
});
// Each TYPE
// show type name
// html = koan (html)
// each text
// find label
// if(obj)
// replace random text
// else
// replace text
// end
// Each variation
// (if obj)
// each
// add class
// (else)
// add class
// label = property
// class = class
// show html
// end
// end
},
element: function(koan, type, text, variation) {
},
variations: function($element, variations) {
$.each(variations, function(name, variation){
});
},
text: function($element, text) {
$.each(text, function(selector, text) {
$element.find(selector).text(text);
});
return $element;
}
},
changeMode: function(value) {
if(value == 'overview') {
handler.showOverview();
}
else {
handler.hideOverview();
if(value == 'design') {
handler.designerMode();
}
if(value == 'code') {
handler.developerMode();
}
}
$sectionHeaders.visibility('refresh');
$sectionExample.visibility('refresh');
$footer.visibility('refresh');
},
showOverview: function() {
var
$body = $('body'),
$example = $('.example')
;
$body.addClass('overview');
$example.each(function() {
$(this).children().not('.ui.header:eq(0), .example p:eq(0)').hide();
});
$example.filter('.another').css('display', 'none');
$('.sticky').sticky('refresh');
},
hideOverview: function() {
var
$body = $('body'),
$example = $('.example')
;
$body.removeClass('overview');
$example.each(function() {
$(this).children().not('.ui.header:eq(0), .example p:eq(0)').css('display', '');
});
$example.filter('.another').removeAttr('style');
$('.sticky').sticky('refresh');
},
developerMode: function() {
var
$body = $('body'),
$example = $('.example').not('.no')
;
$example
.each(function() {
$.proxy(handler.createCode, $(this))('developer');
})
;
$('.sticky').sticky('refresh');
},
designerMode: function() {
var
$body = $('body'),
$example = $('.example').not('.no')
;
$example
.each(function() {
$.proxy(handler.createCode, $(this))('designer');
})
;
$('.sticky').sticky('refresh');
},
openMusic: function() {
var
url = 'http://www.stratus.sc/player?links=https://soundcloud.com/into-the-light/sets/sui&popup=true',
newWindow = window.open(url,'name','height=196,width=733')
;
if(window.focus) {
newWindow.focus();
}
},
getIndent: function(text) {
var
lines = text.split("\n"),
firstLine = (lines[0] === '')
? lines[1]
: lines[0],
spacesPerIndent = 2,
leadingSpaces = firstLine.length - firstLine.replace(/^\s*/g, '').length,
indent
;
if(leadingSpaces !== 0) {
indent = leadingSpaces;
}
else {
// string has already been trimmed, get first indented line and subtract 2
$.each(lines, function(index, line) {
leadingSpaces = line.length - line.replace(/^\s*/g, '').length;
if(leadingSpaces !== 0) {
indent = leadingSpaces - spacesPerIndent;
return false;
}
});
}
return indent || 4;
},
generateCode: function() {
var
$example = $(this).closest('.example'),
$annotation = $example.find('.annotation'),
$code = $annotation.find('.code'),
$header = $example.not('.another').children('.ui.header:first-of-type').eq(0).add('p:first-of-type'),
$ignored = $('i.code:last-child, .wireframe, .anchor, .code, .existing, .pointing.below.label, .instructive, .language.label, .annotation, br, .ignore, .ignored'),
$demo = $example.children().not($header).not($ignored),
code = ''
;
if( $code.size() === 0) {
$demo
.each(function() {
var
$this = $(this).clone(false),
$wireframe = $this.find('.wireframe').add($this.filter('.wireframe'))
;
$wireframe
.each(function() {
var
src = $(this).attr('src'),
image = (src.search('image') !== -1),
paragraph = (src.search('paragraph') !== -1)
;
if(paragraph) {
$(this).replaceWith('<p></p>');
}
else if(image) {
$(this).replaceWith('<img>');
}
})
;
// remove wireframe images
$this.find('.wireframe').remove();
if($this.not('br').not('.wireframe')) {
// allow inline styles only with this one class
if($this.is('.my-container')) {
code += $this.get(0).outerHTML + "\n";
}
else {
code += $this.removeAttr('style').get(0).outerHTML + "\n";
}
}
})
;
}
$example.data('code', code);
return code;
},
createCode: function(type) {
var
$example = $(this).closest('.example'),
$header = $example.children('.ui.header:first-of-type').eq(0).add('p:first-of-type'),
$annotation = $example.find('.annotation'),
$code = $annotation.find('.code'),
$ignoredContent = $('.ui.popup, i.code:last-child, .anchor, .code, .existing.segment, .instructive, .language.label, .annotation, br, .ignore, style, script, .ignored'),
$demo = $example.children().not($header).not($ignoredContent),
code = $example.data('code') || $.proxy(handler.generateCode, this)()
;
if( $code.hasClass('existing') ) {
$code.removeClass('existing');
$.proxy(handler.initializeCode, $code)(true);
}
if($annotation.size() === 0) {
$annotation = $('<div/>')
.addClass('annotation')
.hide()
.appendTo($example)
;
}
if( $example.find('.instructive').size() === 0) {
$code = $('<div/>')
.data('type', 'html')
.addClass('code')
.html(code)
.hide()
.appendTo($annotation)
;
$.proxy(handler.initializeCode, $code)(true);
}
if( ($annotation.eq(0).is(':visible') || type == 'designer') && type != 'developer' ) {
$annotation.transition('hide');
$demo.css('display','');
}
else {
$demo.hide();
$header.css('display', '');
$annotation.transition('fade');
}
if(type === undefined) {
$sectionHeaders.visibility('refresh');
$sectionExample.visibility('refresh');
$footer.visibility('refresh');
}
},
createAnnotation: function() {
if(!$(this).data('type')) {
$(this).data('type', 'html');
}
$(this)
.wrap('<div class="annotation">')
.parent()
.hide()
;
},
makeCode: function() {
if(window.hljs !== undefined) {
$code
.filter(':visible')
.each(handler.initializeCode)
;
$existingCode
.each(handler.createAnnotation)
;
}
else {
console.log('Syntax highlighting not found');
}
},
initializeCode: function(codeSample) {
var
$code = $(this).show(),
$codeTag = $('<code></code>'),
codeSample = codeSample || false,
code = $code.html(),
existingCode = $code.hasClass('existing'),
evaluatedCode = $code.hasClass('evaluated'),
contentType = $code.data('type') || 'html',
title = $code.data('title') || false,
demo = $code.data('demo') || false,
preview = $code.data('preview') || false,
label = $code.data('label') || false,
preserve = $code.data('preserve') || false,
displayType = {
html : 'HTML',
javascript : 'Javascript',
css : 'CSS',
text : 'Command Line',
sh : 'Command Line'
},
padding = 20,
name = (codeSample === true)
? 'instructive'
: 'existing',
formattedCode = code,
whiteSpace,
indent,
styledCode,
$label,
codeHeight
;
var entityMap = {
"&": "&",
"<": "<",
">": ">",
'"': '"',
"'": ''',
"/": '/'
};
contentType = contentType.toLowerCase();
function escapeHTML(string) {
return String(string).replace(/[&<>"'\/]/g, function (s) {
return entityMap[s];
});
}
// evaluate if specified
if(evaluatedCode) {
eval(code);
}
// should trim whitespace
if(preserve) {
formattedCode = code;
}
else {
indent = handler.getIndent(code) || 2;
whiteSpace = new RegExp('\\n\\s{' + indent + '}', 'g');
formattedCode = $.trim(code).replace(whiteSpace, '\n');
}
if(contentType != 'javascript' && contentType != 'less') {
formattedCode = escapeHTML(formattedCode);
}
// replace with <code>
$codeTag
.addClass($code.attr('class'))
.html(formattedCode)
;
$code
.replaceWith($codeTag)
;
$code = $codeTag;
$code
.html(formattedCode)
;
// wrap
$code = $code
.wrap('<div class="ui ' + name + ' segment"></div>')
.wrap('<pre></pre>')
;
// color code
window.hljs.highlightBlock($code[0]);
// add label
if(title) {
$('<div>')
.addClass('ui attached top label')
.html('<span class="title">' + title + '</span>' + '<em>' + (displayType[contentType] || contentType) + '</em>')
.prependTo( $code.closest('.segment') )
;
}
if(label) {
$('<div>')
.addClass('ui pointing below language label')
.html(displayType[contentType] || contentType)
.insertBefore ( $code.closest('.segment') )
;
}
// add run code button
if(demo) {
$('<a>')
.addClass('ui pointing below label')
.html('Run Code')
.on('click', function() {
eval(code);
})
.insertBefore ( $code.closest('.segment') )
;
}
// add preview if specified
if(preview) {
$(code)
.insertAfter( $code.closest('.segment') )
;
}
$code.removeClass('hidden');
},
resetDownloads: function() {
$downloads
.find('.grid')
.hide()
.filter('.choice.grid')
.css('display', 'table')
;
},
selectAll: function () {
this.setSelectionRange(0, this.value.length);
},
chooseStandalone: function() {
$downloads
.find('.grid')
.hide()
.filter('.standalone.grid')
.css('display', 'table')
;
$downloadPopup.popup('reposition');
},
chooseFramework: function() {
$downloads
.find('.grid')
.hide()
.filter('.framework.grid')
.css('display', 'table')
;
$downloadPopup.popup('reposition');
},
swapStyle: function() {
var
theme = $(this).data('theme')
;
$(this)
.addClass('active')
.siblings()
.removeClass('active')
;
$('head link.ui')
.each(function() {
var
href = $(this).attr('href'),
subDirectory = href.split('/')[3],
newLink = href.replace(subDirectory, theme)
;
$(this)
.attr('href', newLink)
;
})
;
}
};
semantic.handler = handler;
handler.createAnchors();
if( $pageTabs.size() > 0 ) {
$pageTabs
.tab({
context : '.main.container',
childrenOnly : true,
history : true,
onTabInit : function() {
handler.makeCode();
$container = ($('.fixed.column').size() > 0 )
? $(this).find('.examples')
: $(this)
;
$(this).find('> .rail .ui.sticky, .fixed .ui.sticky')
.sticky({
context: $container,
offset: 0
})
;
$sectionHeaders = $container.children('h2');
$sectionExample = $container.find('.example');
$exampleHeaders = $sectionExample.children('h4');
// create code
handler.tryCreateMenu();
$(window).on('resize.menu', function() {
handler.tryCreateMenu();
});
},
onTabLoad : function() {
$sticky.filter(':visible').sticky('refresh');
}
})
;
}
else {
handler.makeCode();
handler.tryCreateMenu();
$(window).on('resize.menu', function() {
handler.tryCreateMenu();
});
}
window.hljs.configure({
languages: [
'xml',
'css',
'javascript'
]
});
$menu
.sidebar({
transition : 'uncover',
mobileTransition : 'uncover'
})
;
$('.launch.button, .view-ui, .launch.item')
.on('touchstart click', function(event) {
$menu.sidebar('show');
event.preventDefault();
})
;
handler.createIcon();
$example
.each(function() {
$.proxy(handler.generateCode, this)();
})
.find('i.code')
.popup({
position: 'top right',
offset: 5,
variation: 'inverted',
content: 'View Source'
})
.on('click', handler.createCode)
.end()
.not('.no').eq(0)
.find('i.code')
.popup('destroy')
.end()
.popup({
on : 'hover',
variation: 'inverted',
delay: {
show: 300,
hide: 100
},
position : 'top right',
offset : 5,
content : 'View Source',
target : $example.eq(0).find('i.code')
})
;
$menuMusic
.on('click', handler.openMusic)
;
$shownExample
.each(handler.createCode)
;
$downloadPopup
.popup({
transition : 'horizontal flip',
duration : 350,
position : 'bottom center',
on : 'click',
onHidden : handler.resetDownloads
})
;
$downloadInput
.on('mouseup', handler.selectAll)
;
$downloadFramework
.on('click', handler.chooseFramework)
;
$downloadStandalone
.on('click', handler.chooseStandalone)
;
$themeDropdown
.dropdown({
onChange: handler.less.changeTheme
})
;
if($.fn.tablesort !== undefined && $sortTable.size() > 0) {
$sortTable
.tablesort()
;
}
$helpPopup
.popup({
position: 'bottom right'
})
;
$swap
.on('click', handler.swapStyle)
;
$overview
.dropdown({
action: 'select',
onChange: handler.changeMode
})
;
$menuPopup
.popup({
position : 'bottom center',
delay: {
show: 500,
hide: 50
}
})
;
$pageDropdown
.dropdown({
on : 'hover',
action : 'nothing',
allowTab : false
})
;
$languageDropdown
.popup({
position : 'bottom center',
delay : {
show: 500,
hide: 50
}
})
.dropdown({
allowTab : false,
on : 'click',
onShow : function() {
$(this).popup('hide');
},
onChange: handler.translatePage
})
;
//$.fn.api.settings.base = '//api.semantic-ui.com';
$.extend($.fn.api.settings.api, {
categorySearch: '//api.semantic-ui.com/search/category/{query}',
search: '//api.semantic-ui.com/search/{query}'
});
if(window.Transifex !== undefined) {
window.Transifex.live.onTranslatePage(handler.showLanguageModal);
}
};
// attach ready event
$(document)
.ready(semantic.ready)
;
|
/**
* Copyright reelyActive 2015
* We believe in an open Internet of Things
*/
var pdu = require('../../common/util/pdu.js');
/**
* Parse generic data.
* @param {string} payload The raw payload as a hexadecimal-string.
* @param {number} cursor The start index within the payload.
* @param {Object} advertiserData The object containing all parsed data.
*/
function process(payload, cursor, advertiserData, adType) {
var genericData = payload.substr(cursor+4, pdu.getTagDataLength(payload, cursor));
advertiserData[adType] = genericData;
}
module.exports.process = process; |
var assert = require('assert');
var path = require('path');
var moduleName = path.basename(__filename).split('.')[0];
var expandFunction = require('../src/expand-function');
describe(moduleName, function() {
var shouldReturn = 'should return: ';
describe('empty dictionary', function() {
it(shouldReturn + '[]', function() {
var expand = expandFunction({
dictionary: [],
distance: 1
});
assert.deepEqual(expand('node'), []);
});
});
describe('0 distance', function() {
it(shouldReturn + '["hello"]', function() {
var expand = expandFunction({
dictionary: ['hello'],
distance: 0
});
assert.deepEqual(expand('hello'), [simpleNodeInfo('hello')]);
});
});
describe('1 distance', function() {
it(shouldReturn + '[]', function() {
var expand = expandFunction({
dictionary: ['rick'],
distance: 1
});
assert.deepEqual(expand('rick'), []);
});
it(shouldReturn + '["pick"]', function() {
var expand = expandFunction({
dictionary: ['pick'],
distance: 1
});
assert.deepEqual(expand('rick'), [simpleNodeInfo('pick')]);
});
it(shouldReturn + '["pick", "sick"]', function() {
var expand = expandFunction({
dictionary: ['pick', 'sick', 'blob'],
distance: 1
});
assert.deepEqual(expand('rick'), [simpleNodeInfo('pick'), simpleNodeInfo('sick')]);
});
});
});
function simpleNodeInfo(nodeId) {
return {
id: nodeId,
distanceFromParent: 1
};
}
|
import React, { Component } from 'react';
import './Footer.css';
class Footer extends Component {
render() {
return (
<footer>
Whatcolorisit? By <a href="http://nrouviere.fr" target="_blank">Nicolas Rouvière</a> with
<a href="https://facebook.github.io/react/" target="_blank"> React</a>.
See sources on <a href="https://github.com/WaSa42/whatcolorisit" target="_blank">GitHub</a>.
</footer>
);
}
}
export default Footer;
|
var basic = require('../functions/basic.js');
var consoleLogger = require('../functions/basic.js').consoleLogger;
var userDB = require('../db/user_db.js');
function getTheUser(req) {
return req.customData.theUser;
}
function getTheCurrentGrillStatus(req) {
return req.customData.currentGrillStatus;
}
var receivedLogger = function (module) {
var rL = require('../functions/basic.js').receivedLogger;
rL('logout_handler', module);
};
var successLogger = function (module, text) {
var sL = require('../functions/basic.js').successLogger;
return sL('logout_handler', module, text);
};
var errorLogger = function (module, text, err) {
var eL = require('../functions/basic.js').errorLogger;
return eL('logout_handler', module, text, err);
};
module.exports = {
logoutHarvardLogin: function (req, res) {
var module = 'logoutHarvardLogin';
receivedLogger(module);
//delete the harvard cs50 ID session
req.logout();
consoleLogger(successLogger(module));
//send a success so that the user will be logged out and redirected to login by angular responseHandler
res.status(200).send({
msg: 'LogoutHarvardLogin success'
});
},
logoutClientSession: function (req, res) {
var module = 'logoutClientSession';
receivedLogger(module);
var theUser = getTheUser(req);
//change the user's grill to default
userDB.updateGrillName(theUser.openId, 'default', error, error, success);
function success() {
consoleLogger(successLogger(module));
//the logout_api toggles the customLoggedInStatus -- respond with a success, angular client will redirect
res.status(200).send({
code: 200,
notify: false,
redirect: true,
redirectPage: "/clientHome.html"
});
}
function error(status, err) {
consoleLogger(errorLogger(module, err, err));
res.status(500).send({
code: 500,
notify: true,
type: 'error',
msg: 'An error occurred while trying to log you out. Please try again'
});
}
},
logoutClientFull: function (req, res) {
var module = 'logoutClientFull';
receivedLogger(module);
var theUser = getTheUser(req);
//change the user's grill to default
userDB.updateGrillName(theUser.openId, 'default', error, error, success);
function success() {
//delete the harvard cs50 ID session
req.logout();
consoleLogger(successLogger(module));
//send a success so that the user will be logged out and redirected to login by clientAngular
res.status(200).send({
code: 200,
notify: false,
redirect: true,
redirectPage: "/index.html"
});
}
function error(status, err) {
consoleLogger(errorLogger(module, err, err));
res.status(500).send({
code: 500,
notify: true,
type: 'error',
msg: 'An error occurred while trying to log you out. Please try again'
});
}
},
logoutAdminSession: function (req, res) {
var module = 'logoutAdminSession';
receivedLogger(module);
var theUser = getTheUser(req);
//change the user's grill to default
userDB.updateGrillName(theUser.openId, 'default', error, error, success);
function success() {
consoleLogger(successLogger(module));
//the logout_api toggles the customLoggedInStatus -- respond with a success, client will redirect
res.status(200).send({
code: 200,
notify: false,
redirect: true,
redirectPage: "/adminHome.html"
});
}
function error(status, err) {
consoleLogger(errorLogger(module, err, err));
res.status(500).send({
code: 500,
notify: true,
type: 'error',
msg: 'An error occurred while trying to log you out. Please try again'
});
}
},
logoutAdminFull: function (req, res) {
var module = 'logoutAdminFull';
receivedLogger(module);
var theUser = getTheUser(req);
//change the user's grill to default
userDB.updateGrillName(theUser.openId, 'default', error, error, success);
function success() {
req.logout();
consoleLogger(successLogger(module));
res.status(200).send({
code: 200,
notify: false,
redirect: true,
redirectPage: "/index.html"
});
}
function error(status, err) {
consoleLogger(errorLogger(module, err, err));
res.status(500).send({
code: 500,
notify: true,
type: 'error',
msg: 'An error occurred while trying to log you out. Please try again'
});
}
}
}; |
module.exports = function() {
NS.foobar = function() {
throw new Error();
};
return {
NS: NS
};
}; |
var protocol_a_s_i_cache_delegate_p =
[
[ "cachedResponseDataForURL:", "protocol_a_s_i_cache_delegate-p.html#aecbe916ea3557016f61ce515163daf1a", null ],
[ "cachedResponseHeadersForURL:", "protocol_a_s_i_cache_delegate-p.html#a4ab21eaae8e114a36ce38f62ed283a30", null ],
[ "canUseCachedDataForRequest:", "protocol_a_s_i_cache_delegate-p.html#a296943b1f70852648f589f30cfcba945", null ],
[ "clearCachedResponsesForStoragePolicy:", "protocol_a_s_i_cache_delegate-p.html#a7904f2e85a0f312f835d9e7c082f517b", null ],
[ "defaultCachePolicy", "protocol_a_s_i_cache_delegate-p.html#a4214906094e035da718d37c643b6b8bc", null ],
[ "expiryDateForRequest:maxAge:", "protocol_a_s_i_cache_delegate-p.html#af31a0ff1aa2ff7f80e27c374f1c39012", null ],
[ "isCachedDataCurrentForRequest:", "protocol_a_s_i_cache_delegate-p.html#ae704a29f0af8520767deb5c67db82274", null ],
[ "pathToCachedResponseDataForURL:", "protocol_a_s_i_cache_delegate-p.html#ae73e91015c4d010e7f79c095bd20d52b", null ],
[ "pathToCachedResponseHeadersForURL:", "protocol_a_s_i_cache_delegate-p.html#a8472343a64bac837fcc86a7f404d8f53", null ],
[ "pathToStoreCachedResponseDataForRequest:", "protocol_a_s_i_cache_delegate-p.html#af8335eeec6ec6cfeee3aeebfc26e779c", null ],
[ "pathToStoreCachedResponseHeadersForRequest:", "protocol_a_s_i_cache_delegate-p.html#a2df6b465306b89a7ec18f69de02aefb9", null ],
[ "removeCachedDataForRequest:", "protocol_a_s_i_cache_delegate-p.html#a3998558bf0d56d6fe4c0b3421713cadf", null ],
[ "removeCachedDataForURL:", "protocol_a_s_i_cache_delegate-p.html#a92810dd55c970d03966b898feeead0f1", null ],
[ "storeResponseForRequest:maxAge:", "protocol_a_s_i_cache_delegate-p.html#a827731a07f9d6a4aea3fd37241722288", null ],
[ "updateExpiryForRequest:maxAge:", "protocol_a_s_i_cache_delegate-p.html#aa04b6e613c7509a196a6c756ccd4b995", null ]
]; |
//= require 'shader-script'
// ShaderScript isn't production ready yet and shouldn't be sent to
// client code. So this file is here to ensure SS is loaded only
// in Jax development, and not in development of projects that
// depend on Jax.
//
// Otherwise, this file would live in `helpers/shaderscript_helper.js`.
|
'use babel'
import quickSelect from 'atom-quick-select'
import path from 'path'
import glob from 'glob'
module.exports = {
config: {
showBundledPackages: {
type: 'boolean',
default: false
}
},
activate (state) {
this.disposable = atom.commands.add(
'atom-workspace', 'readme:show-list', () => this.showList()
)
},
deactivate () {
this.disposable.dispose()
},
async showList () {
const pkg = await quickSelect(this.loadPackages(), {
normalizeItem: ({ name }) => ({ label: name })
})
if (pkg) {
this.openReadme(pkg)
}
},
openReadme (pkg) {
const readme = glob.sync('readme*', { nocase: true, cwd: pkg.path }).pop()
if (readme) {
let fileUri = path.join(pkg.path, readme)
if (atom.packages.isPackageActive('markdown-preview')) {
fileUri = `markdown-preview://${encodeURI(fileUri)}`
}
atom.workspace.open(fileUri, { searchAllPanes: true })
}
},
loadPackages () {
var items = atom.packages.getActivePackages()
if (!atom.config.get('readme.showBundledPackages')) {
items = items.filter((pkg) => !pkg.bundledPackage)
}
return items
.sort((a, b) => a.name.localeCompare(b.name))
}
}
|
'use strict';
describe('Service: EditZoneService', function () {
// load the service's module
beforeEach(module('yeomanApp'));
// instantiate service
var EditZoneService;
beforeEach(inject(function(_EditZoneService_) {
EditZoneService = _EditZoneService_;
}));
it('should do something', function () {
expect(!!EditZoneService).toBe(true);
});
});
|
import Ember from 'ember';
import StorageArray from 'ember-local-storage/local/array';
export default StorageArray.extend({
storageKey: 'anonymous-likes',
initialContent: Ember.A()
});
|
exports = module.exports = require('./src/zephyros');
|
'use strict'
var utils = require('./_utils'),
eslint = require('./eslint'),
build = require('./build'),
chokidar = require('chokidar')
module.exports = function(options) {
options = utils.extend({
// chokidar events we are going to watch
// generally you should not touch them
watchEvents: [
'change',
'add',
'unlink',
'unlinkDir',
'addDir'
]
}, options)
// return a promise based on a certain task triggered
var runOnlyOn = function(event) {
if (~options.watchEvents.indexOf(event)) {
// go to the next task
return Promise.resolve()
} else {
return Promise.reject()
}
}
// run eslint when a source file gets updated
utils.print('Watching the files in the src/**/**/*.js path', 'cool')
chokidar.watch('src/**/**/*.js', {
ignoreInitial: true
}).on('all', function(event) {
// this tasks will run only if the current event matches the ones in the watchEvents array
runOnlyOn(event)
.then(eslint)
.then(build)
})
}
|
// ==========================================================================
// Project: SproutCore - JavaScript Application Framework
// Copyright: ©2006-2011 Strobe Inc. and contributors.
// portions copyright @2009 Apple Inc.
// License: Licensed under MIT license (see license.js)
// ==========================================================================
var view, content ;
module("SC.CollectionView.reload", {
setup: function() {
content = "1 2 3 4 5 6 7 8 9 10".w().map(function(x) {
return SC.Object.create({ value: x });
});
view = SC.CollectionView.create({
content: content,
isVisibleInWindow: YES
});
}
});
/*
Verfies that the item views for the passed collection view match exactly the
content array passed. If shouldShowAllContent is also YES then verifies
that the nowShowing range is showing the entire content range.
@param {SC.CollectionView} view the view to test
@param {SC.Array} content the content array
@param {Boolean} shouldShowAllContent
@param {String} testName optional test name
@returns {void}
*/
function verifyItemViews(view, content, shouldShowAllContent, testName) {
var nowShowing = view.get('nowShowing'),
childViews = view.get('childViews');
if (testName === undefined) testName='';
if (shouldShowAllContent) {
ok(nowShowing.isEqual(SC.IndexSet.create(0, content.get('length'))), '%@ nowShowing (%@) should equal (0..%@)'.fmt(testName, nowShowing, content.get('length')-1));
}
equals(childViews.get('length'), nowShowing.get('length'), '%@ view.childViews.length should match nowShowing.length'.fmt(testName));
// childViews should be in same order as nowShowing indexes at all times.
var iter= 0;
nowShowing.forEach(function(idx) {
var itemView = childViews.objectAt(iter),
item = content.objectAt(idx);
ok(itemView, 'childViews[%@] should have itemView'.fmt(iter));
if (itemView) {
equals(itemView.get('content'), item, '%@ childViews[%@].content should equal content[%@]'.fmt(testName, iter,idx));
}
iter++;
});
}
// ..........................................................
// BASIC TESTS
//
test("should only reload when isVisibleInWindow", function() {
view.set('isVisibleInWindow', NO);
//view.isVisibleInWindow = NO ;
var len = view.getPath('childViews.length');
SC.run(function() {
view.reload();
});
equals(view.getPath('childViews.length'), len, 'view.childViews.length should not change while offscreen');
SC.RunLoop.begin();
view.set('isVisibleInWindow', YES);
SC.RunLoop.end();
equals(view.getPath('childViews.length'), content.get('length'), 'view.childViews.length should change when moved onscreen if reload is pending');
});
test("should automatically reload if content is set when collection view is first created", function() {
ok(view.get('content'), 'precond - should have content');
SC.RunLoop.begin();
SC.RunLoop.end();
verifyItemViews(view, content, YES);
});
test("reload(null) should generate item views for all items", function() {
SC.RunLoop.begin();
view.reload();
SC.RunLoop.end(); // allow reload to run
verifyItemViews(view, content, YES);
});
test("reload(index set) should update item view for items in index only", function() {
// make sure views are loaded first time
SC.run(function() { view.reload(); });
// now get a couple of child views.
var cv1 = view.childViews[1], cv2 = view.childViews[3];
// and then reload them
SC.run(function() { view.reload(SC.IndexSet.create(1).add(3)); });
ok(cv1 !== view.childViews[1], 'view.childViews[1] should be new instance after view.reload(<1,3>) actual: %@ expected: %@'.fmt(view.childViews[1], cv1));
ok(cv2 !== view.childViews[3], 'view.childViews[3] should be new instance after view.reload(<1,3>) actual: %@ expected: %@'.fmt(view.childViews[3], cv2));
// verify integrity
verifyItemViews(view, content, YES);
});
test("adding items to content should reload item views at end", function() {
SC.run(function() {
content.pushObject(SC.Object.create());
});
verifyItemViews(view, content, YES);
});
test("removing items from content should remove item views", function() {
SC.run(function() {
content.popObject();
});
verifyItemViews(view, content, YES);
});
// ..........................................................
// SPECIAL CASES
//
test("remove and readd item", function() {
// first remove an item.
var item = content.objectAt(0);
SC.run(function() { content.removeAt(0); });
verifyItemViews(view, content, YES, 'after content.removeAt(0)');
// then readd the item
SC.run(function() { content.insertAt(0, item); });
verifyItemViews(view, content, YES, 'after content.insertAt(0,item)');
// then add another item
item = SC.Object.create();
SC.run(function() { content.pushObject(item); });
verifyItemViews(view, content, YES, 'after content.pushObject(item)');
// and remove the item
SC.run(function() { content.popObject(); });
verifyItemViews(view, content, YES, 'after content.popObject(item)');
});
test("reloading should only render nowShowing component", function() {
var expected = SC.IndexSet.create(0,2).add(6);
view = SC.CollectionView.create({
content: content,
computeNowShowing: function() {
return expected;
},
isVisibleInWindow: YES
});
SC.RunLoop.begin();
view.reload();
SC.RunLoop.end();
same(view.get('nowShowing'), expected, 'precond - should have limited now showing');
equals(view.get('childViews').get('length'), expected.get('length'), 'should only render number of child views in IndexSet');
});
|
import React, {Component} from 'react';
import './SlidesBtn.styl';
import IconSlides from 'Resources/icon-slides.svg';
import IconNext from 'Resources/icon-next.svg';
class SlidesBtn extends Component {
render() {
return (
<div className="slidesBtn">
<span className="pixels">
<img src="res/pixels.gif" />
</span>
<IconSlides />
<span className="labelWrap">
<span className="label">
<span className="description">For a full overview,<br /></span>
<span className="cta">See Slides <IconNext /></span>
</span>
</span>
</div>
)
}
};
export default SlidesBtn;
|
/* pointer.js */
module.exports = require('/single.js');
/* end */ |
var punt = require('punt');
var redis = require("redis");
var LOG_LENGTH = 2500;
module.exports.createServer = function(options) {
return new UDPServer(options);
};
function UDPServer(options) {
options.redis = options.redis || {};
options.redis.host = options.redis.host || '127.0.0.1';
options.redis.port = options.redis.port || 6379;
options.limit = options.limit || LOG_LENGTH;
this.options = options;
};
UDPServer.prototype.onMessage = function(msg) {
if (Array.isArray(msg)) {
for (var i = 0,
j = msg.length; i < j; i++) {
this.writeToRing(msg[i]);
};
} else {
this.writeToRing(msg);
}
};
UDPServer.prototype.writeToRing = function(msg) {
var self = this;
this.redis.get('token:' + msg.token, function(err, result) {
if (err)
return console.log(err);
if (!result)
return console.log('not found', msg);
var json = JSON.parse(result);
var output = JSON.stringify({
channel : json.channel,
source : json.source,
timestamp : +(msg.ts),
line : msg.log,
token : msg.token
});
self.redis.lpush('session:' + json.session, output, function(err) {
if (err)
return console.log(err);
self.redis.ltrim('session:' + json.session, 0, self.options.limit, function() {
if (err)
return console.log(err);
});
});
self.subscription.publish(json.session, output);
});
};
UDPServer.prototype.start = function() {
var self = this;
var conf = this.options.redis;
this.redis = redis.createClient(conf.port, conf.host);
this.subscription = redis.createClient(conf.port, conf.host);
if (this.options.redis.auth) {
this.redis.auth(this.options.redis.auth);
this.subscription.auth(this.options.redis.auth);
}
this.redis.on('error', function(err) {
return console.log(err);
});
this.subscription.on('error', function(err) {
return console.log(err);
});
this.server = punt.bind(this.options.host + ':' + this.options.port);
this.server.on('message', this.onMessage.bind(this));
};
UDPServer.prototype.stop = function() {
this.server.sock.close();
this.redis.quit();
this.subscription.quit();
};
|
(function () {
'use strict';
angular
.module('users')
.controller('EditProfileController', EditProfileController);
EditProfileController.$inject = ['$scope', '$http', '$location', 'UsersService', 'Authentication', 'Notification'];
function EditProfileController($scope, $http, $location, UsersService, Authentication, Notification) {
var vm = this;
vm.user = Authentication.user;
vm.updateUserProfile = updateUserProfile;
// Update a user profile
function updateUserProfile(isValid) {
if (!isValid) {
$scope.$broadcast('show-errors-check-validity', 'vm.userForm');
return false;
}
var user = new UsersService(vm.user);
user.$update(function (response) {
$scope.$broadcast('show-errors-reset', 'vm.userForm');
Notification.success({ message: '<i class="glyphicon glyphicon-ok"></i> Edit profile successful!' });
Authentication.user = response;
}, function (response) {
Notification.error({ message: response.data.message, title: '<i class="glyphicon glyphicon-remove"></i> Edit profile failed!' });
});
}
}
}());
|
/*!
* froala_editor v1.2.7 (https://www.froala.com/wysiwyg-editor)
* License https://www.froala.com/wysiwyg-editor/terms
* Copyright 2014-2015 Froala Labs
*/
(function ($) {
$.Editable.commands = $.extend($.Editable.commands, {
insertOrderedList: {
title: 'Numbered List',
icon: 'fa fa-list-ol',
refresh: function () {},
callback: function (cmd) {
this.formatList(cmd);
},
undo: true
},
insertUnorderedList: {
title: 'Bulleted List',
icon: 'fa fa-list-ul',
refresh: function () {},
callback: function (cmd) {
this.formatList(cmd);
},
undo: true
}
});
$.Editable.prototype.refreshLists = function () {
var $element = $(this.getSelectionElement());
var $parents = this.parents($element, 'ul, ol');
if ($parents.length > 0) {
var cmd = 'insertUnorderedList';
if ($parents[0].tagName == 'OL') {
cmd = 'insertOrderedList';
}
this.$editor.find('button[data-cmd="' + cmd + '"]').addClass('active');
}
}
$.Editable.prototype.processBackspace = function ($li) {
var $prev_li = $li.prev();
if ($prev_li.length) {
this.removeMarkers();
// There is an UL or OL before. Join with the last li.
if ($prev_li.get(0).tagName == 'UL' || $prev_li.get(0).tagName == 'OL') {
$prev_li = $prev_li.find('li:last');
}
// Check if previous li has a list.
while ($prev_li.find('> ul, > ol').length) {
$prev_li = $prev_li.find('> ul li:last, > ol li:last');
}
// Search for blocks inside the previous LI.
var blocks = $prev_li.find('> p, > h1, > h3, > h4, > h5, > h6, > div, > pre, > blockquote');
if ($prev_li.text().length === 0 && $prev_li.find('img, table, input, iframe, video').length === 0) {
$prev_li.remove();
}
else {
// Do that only when the previous LI is not empty.
if (!this.emptyElement($prev_li.get(0))) {
this.keep_enter = true;
$li.find('> p, > h1, > h3, > h4, > h5, > h6, > div, > pre, > blockquote').each (function (index, el) {
$(el).replaceWith($(el).html());
})
this.keep_enter = false;
}
// There are blocks inside the previous LI.
if (blocks.length) {
// Place cursor at the end of the previous LI.
$(blocks[blocks.length - 1]).append(this.markers_html);
// No nested list.
if ($li.find('ul, ol').length === 0) {
$(blocks[blocks.length - 1]).append($li.html());
}
else {
var add_after = false;
var contents = $li.contents();
for (var i = 0; i < contents.length; i++) {
var nd = contents[i];
if (['OL', 'UL'].indexOf(contents[i].tagName) >= 0) add_after = true;
if (!add_after) {
$(blocks[blocks.length - 1]).append(nd);
}
else {
$(blocks[blocks.length - 1]).after(nd);
}
}
this.$element.find('breakli').remove();
var ns = blocks[blocks.length - 1].nextSibling;
if (ns && ns.tagName == 'BR') {
$(ns).remove();
}
}
} else {
if (!this.emptyElement($prev_li.get(0))) {
$prev_li.append(this.markers_html);
$prev_li.append($li.html());
}
else {
this.$element.find('breakli').replaceWith(this.markers_html);
$prev_li.html($li.html())
}
}
$li.remove();
this.cleanupLists();
this.restoreSelectionByMarkers();
}
this.$element.find('breakli').remove();
} else {
this.$element.find('breakli').remove();
if (this.parents($li, 'ul').length) {
this.formatList('insertUnorderedList', false);
} else {
this.formatList('insertOrderedList', false);
}
}
this.sync();
}
$.Editable.prototype.liBackspace = function () {
// There is text in li.
if (this.text() !== '') return true;
var $li;
var element = this.getSelectionElement();
// We are in table. Resume default action.
var possible_parents = this.parents($(element), 'table, li');
if (possible_parents.length > 0 && possible_parents[0].tagName === 'TABLE') {
return true;
}
if (element.tagName == 'LI') {
$li = $(element);
} else {
$li = this.parents($(element), 'li:first');
}
this.removeMarkers();
if (this.emptyElement($li.get(0))) {
$li.prepend('<breakli></breakli>');
if ($li.find('br').length == 1) $li.find('br').remove();
}
else {
this.insertHTML('<breakli></breakli>');
}
if ($li.find('breakli').prev().length && $li.find('breakli').prev().get(0).tagName === 'TABLE') {
if ($li.find('breakli').next().length && $li.find('breakli').next().get(0).tagName === 'BR') {
this.setSelection($li.find('breakli').prev().find('td:first').get(0));
$li.find('breakli').next().remove();
this.$element.find('breakli').remove();
return false;
}
}
var html = $li.html();
var tag;
var li_html = [];
for (var i = 0; i < html.length; i++) {
chr = html.charAt(i);
// Tag start.
if (chr == '<') {
// Tag end.
var j = html.indexOf('>', i + 1);
if (j !== -1) {
// Get tag.
tag = html.substring(i, j + 1);
var tag_name = this.tagName(tag);
i = j;
// Do break here.
if (tag_name == 'breakli') {
if (!this.isClosingTag(tag)) {
if (!this.isClosingTag(li_html[li_html.length - 1])) {
this.processBackspace($li);
return false;
}
}
} else {
li_html.push(tag);
}
}
} else {
this.$element.find('breakli').remove();
return true;
}
}
this.$element.find('breakli').remove();
return true;
}
$.Editable.prototype.textLiEnter = function ($li) {
this.removeMarkers();
this.insertSimpleHTML('<breakli></breakli>', false);
var html = $li.html();
var tag;
var open_tags = [];
var tag_indexes = {};
var li_html = [];
var chars = 0;
var i;
var attrs = $li.prop('attributes');
var props = '';
for (i = 0; i < attrs.length; i++) props += ' ' + attrs[i].name + '="' + attrs[i].value + '"';
var last_is_char = false;
for (i = 0; i < html.length; i++) {
chr = html.charAt(i);
// Tag start.
if (chr == '<') {
// Tag end.
var j = html.indexOf('>', i + 1);
if (j !== -1) {
// Get tag.
tag = html.substring(i, j + 1);
var tag_name = this.tagName(tag);
i = j;
// Do break here.
if (tag_name == 'breakli') {
if (!this.isClosingTag(tag)) {
for (var k = open_tags.length - 1; k >= 0; k--) {
var open_tag_name = this.tagName(open_tags[k]);
li_html.push('</' + open_tag_name + '>');
}
li_html.push('</li>');
li_html.push('<li' + props + '>');
for (var p = 0; p < open_tags.length; p++) {
li_html.push(open_tags[p]);
}
li_html.push('<span class="f-marker" data-type="false" data-collapsed="true" data-id="0" data-fr-verified="true"></span><span class="f-marker" data-type="true" data-collapsed="true" data-id="0" data-fr-verified="true"></span>');
last_is_char = false;
}
} else {
li_html.push(tag);
last_is_char = false;
if (!this.isSelfClosingTag(tag)) {
if (this.isClosingTag(tag)) {
var idx = tag_indexes[tag_name].pop();
// Remove the open tag.
open_tags.splice(idx, 1);
} else {
open_tags.push(tag);
if (tag_indexes[tag_name] === undefined) tag_indexes[tag_name] = [];
tag_indexes[tag_name].push(open_tags.length - 1);
}
}
}
}
}
else {
chars++;
if (chr.charCodeAt(0) == 32 && !last_is_char) {
li_html.push(' ');
}
else {
li_html.push(chr);
last_is_char = true;
}
}
}
var $li_parent = $($li.parents('ul, ol')[0]);
$li.replaceWith('<li' + props + '>' + li_html.join('') + '</li>');
// Make tables consistent in p.
$li_parent.find('p:empty + table').prev().remove();
$li_parent.find('p + table').each (function (index, table) {
var $table = $(table);
$table.prev().append($table.clone())
$table.remove();
})
$li_parent.find('table + p').each (function (index, p) {
var $p = $(p);
$p.append($p.prev().clone())
$p.prev().remove();
})
// Empty elements add invisible space.
this.keep_enter = true;
$li_parent.find(this.valid_nodes.join(',')).each ($.proxy(function (index, el) {
if ($(el).text().trim() === '' && $(el).find(this.valid_nodes.join(',')).length === 0) {
$(el).prepend($.Editable.INVISIBLE_SPACE);
}
}, this));
this.keep_enter = false;
}
$.Editable.prototype.liEnter = function () {
var $li;
var element = this.getSelectionElement();
// We are in table. Resume default action.
var possible_parents = this.parents($(element), 'table, li')
if (possible_parents.length > 0 && possible_parents[0].tagName == 'TABLE') {
return true;
}
if (element.tagName == 'LI') {
$li = $(element);
} else {
$li = this.parents($(element), 'li:first');
}
if (this.getSelectionTextInfo($li.get(0)).atStart && this.text() === '') {
$li.before('<li>' + $.Editable.INVISIBLE_SPACE + '</li>');
}
else {
if (this.trim($li.text()).length === 0 && $li.find('img, table, iframe, input, object').length === 0) {
this.outdent(false);
return false;
} else {
this.textLiEnter($li);
}
this.$element.find('breakli').remove();
this.restoreSelectionByMarkers();
}
this.sync();
return false;
}
$.Editable.prototype.listTab = function () {
var $el = $(this.getSelectionElement());
if (this.parents($el, 'ul, ol').length > 0 && this.parents($el, 'table').length === 0) {
this.indent();
return false;
}
}
$.Editable.prototype.listShiftTab = function () {
var $el = $(this.getSelectionElement());
if (this.parents($el, 'ul, ol').length > 0 && this.parents($el, 'table').length === 0) {
this.outdent();
return false;
}
}
$.Editable.prototype.indentList = function ($element, outdent) {
if ($element.get(0).tagName === 'LI') {
if (!outdent) {
this.indentLi($element);
}
else {
this.outdentLi($element);
}
this.cleanupLists();
return false;
}
return true;
}
$.Editable.prototype.initList = function () {
this.addListener('tab', this.listTab);
this.addListener('shift+tab', this.listShiftTab);
this.addListener('refresh', this.refreshLists);
this.addListener('indent', this.indentList);
if (!this.isImage && !this.isLink && !this.options.editInPopup) {
this.$element.on('keydown', $.proxy(function (e) {
if (['TEXTAREA', 'INPUT'].indexOf(e.target.tagName) < 0) {
if (!this.isHTML) {
var keyCode = e.which;
var element = this.getSelectionElement();
if (element.tagName == 'LI' || this.parents($(element), 'li').length > 0) {
if (keyCode == 13 && !e.shiftKey && this.options.multiLine) {
return this.liEnter();
}
if (keyCode == 8) {
return this.liBackspace();
}
}
}
}
}, this));
}
};
$.Editable.initializers.push($.Editable.prototype.initList);
/**
* Format list.
*
* @param val
*/
$.Editable.prototype.formatList = function (cmd, reposition) {
if (this.browser.msie && $.Editable.getIEversion() < 9) {
document.execCommand(cmd, false, false);
return false;
}
if (reposition === undefined) reposition = true;
var tag_name;
var replace_list = false;
var all = true;
var replaced = false;
var $element;
var elements = this.getSelectionElements();
// Check if lists should be replaced.
var $parents = this.parents($(elements[0]), 'ul, ol');
if ($parents.length) {
if ($parents[0].tagName === 'UL') {
if (cmd != 'insertUnorderedList') {
replace_list = true;
}
} else {
if (cmd != 'insertOrderedList') {
replace_list = true;
}
}
}
this.saveSelectionByMarkers();
if (replace_list) {
tag_name = 'ol';
if (cmd === 'insertUnorderedList') tag_name = 'ul';
var $list = $($parents[0]);
$list.replaceWith('<' + tag_name + '>' + $list.html() + '</' + tag_name + '>');
}
else {
// Clean elements.
for (var i = 0; i < elements.length; i++) {
$element = $(elements[i]);
// Wrap
if ($element.get(0).tagName == 'TD' || $element.get(0).tagName == 'TH') {
this.wrapTextInElement($element);
}
// Check if current element rezides in LI.
if (this.parents($element, 'li').length > 0 || $element.get(0).tagName == 'LI') {
var $li;
if ($element.get(0).tagName == 'LI') {
$li = $element;
}
else {
$li = $($element.parents('li')[0]);
}
// Mark where to close and open again ol.
var $p_list = this.parents($element, 'ul, ol');
if ($p_list.length > 0) {
tag_name = $p_list[0].tagName.toLowerCase();
$li.before('<span class="close-' + tag_name + '" data-fr-verified="true"></span>');
$li.after('<span class="open-' + tag_name + '" data-fr-verified="true"></span>');
}
if (this.parents($($p_list[0]), 'ol, ul').length === 0 || replace_list) {
if ($li.find(this.valid_nodes.join(',')).length === 0) {
var ht = $li.html().replace(/\u200B/gi, '');
if (!this.options.paragraphy) {
ht += $li.find('br').length > 0 ? '' : this.br;
}
else {
if ($li.text().replace(/\u200B/gi, '').length === 0) {
ht += $li.find('br').length > 0 ? '' : this.br;
}
ht = '<' + this.options.defaultTag + this.attrs($li.get(0)) + '>' + ht;
ht = ht + '</' + this.options.defaultTag + '>';
}
$li.replaceWith(ht);
} else {
$li.replaceWith($li.html().replace(/\u200B/gi, ''));
}
}
replaced = true;
}
else {
all = false;
}
}
if (replaced) {
this.cleanupLists();
}
if (all === false || replace_list === true) {
this.wrapText();
this.restoreSelectionByMarkers();
elements = this.getSelectionElements();
this.saveSelectionByMarkers();
this.elementsToList(elements, cmd);
this.unwrapText();
this.cleanupLists();
}
}
if (this.options.paragraphy && !replace_list) this.wrapText(true);
this.restoreSelectionByMarkers();
if (reposition) this.repositionEditor();
if (cmd == 'insertUnorderedList') {
cmd = 'unorderedListInserted';
} else {
cmd = 'orderedListInserted';
}
this.triggerEvent(cmd);
};
$.Editable.prototype.elementsToList = function (elements, cmd) {
var list_tag = '<ol>';
if (cmd == 'insertUnorderedList') {
list_tag = '<ul>';
}
if (elements[0] == this.$element.get(0)) {
elements = this.$element.find('> ' + this.valid_nodes.join(', >'));
}
for (var j = 0; j < elements.length; j++) {
var $list = $(list_tag);
$element = $(elements[j]);
// Main element skip.
if ($element.get(0) == this.$element.get(0)) {
continue;
}
// Table cell.
if ($element.get(0).tagName === 'TD' || $element.get(0).tagName === 'TH') {
this.wrapTextInElement($element, true);
this.elementsToList($element.find('> ' + this.valid_nodes.join(', >')), cmd);
}
// Other.
else {
// Append cloned list.
if ($element.attr('class') === '') $element.removeAttr('class');
if ($element.get(0).tagName == this.options.defaultTag && $element.get(0).attributes.length === 0) {
$list.append($('<li>').html($element.clone().html()));
}
else {
$list.append($('<li>').html($element.clone()));
}
$element.replaceWith($list);
}
}
}
$.Editable.prototype.indentLi = function ($li) {
var $list = $li.parents('ul, ol');
var tag_name = $list.get(0).tagName.toLowerCase();
if ($li.find('> ul, > ol').length > 0 && $li.prev('li').length > 0) {
this.wrapTextInElement($li);
$li.find('> ' + this.valid_nodes.join(' , > ')).each (function (i, el) {
$(el).wrap('<' + tag_name + '></' + tag_name + '>').wrap('<li></li>');
});
$li.prev('li').append($li.find('> ul, > ol'))
$li.remove()
}
else if ($li.find('> ul, > ol').length === 0 && $li.prev('li').length > 0) {
$li.prev().append($('<' + tag_name + '>').append($li.clone()));
$li.remove();
$($list.find('li').get().reverse()).each(function (i, el) {
var $el = $(el);
if ($el.find(' > ul, > ol').length > 0) {
if ($el.prev() && $el.prev().find(' > ul, > ol').length > 0 && $el.contents().length === 1) {
$el.prev().append($el.html())
$el.remove();
}
}
});
}
}
$.Editable.prototype.outdentLi = function ($li) {
var $list = $($li.parents('ul, ol')[0]);
var $list_parent = this.parents($list, 'ul, ol');
var tag_name = $list.get(0).tagName.toLowerCase();
// The first li in a nested list.
if ($li.prev('li').length === 0 && this.parents($li, 'li').length > 0) {
$li.before('<span class="close-' + tag_name + '" data-fr-verified="true"></span>');
$li.before('<span class="close-li" data-fr-verified="true"></span>');
$li.before('<span class="open-li" data-fr-verified="true"></span>');
$li.after('<span class="open-' + tag_name + '" data-fr-verified="true"></span>');
$li.replaceWith($li.html());
}
else {
$li.before('<span class="close-' + tag_name + '" data-fr-verified="true"></span>');
$li.after('<span class="open-' + tag_name + '" data-fr-verified="true"></span>');
// Nested list item.
if (this.parents($li, 'li').length > 0) {
$li.before('<span class="close-li" data-fr-verified="true"></span>');
$li.after('<span class="open-li" data-fr-verified="true"></span>');
}
}
// First item in list.
if (!$list_parent.length) {
if ($li.find(this.valid_nodes.join(',')).length === 0) {
$li.replaceWith($li.html().replace(/\u200b/gi, '') + this.br);
} else {
$li.find(this.valid_nodes.join(', ')).each($.proxy(function (i, el) {
if (this.emptyElement(el)) $(el).append(this.br);
}, this));
$li.replaceWith($li.html().replace(/\u200b/gi, ''));
}
}
}
$.Editable.prototype.listTextEmpty = function (element) {
var text = $(element).text().replace(/(\r\n|\n|\r|\t|\u200B)/gm, '');
return (text === '' || element === this.$element.get(0)) && $(element).find('br').length === 1;
}
})(jQuery);
|
const fs = require('fs')
const path = require('path')
const config = require('./locals')
const exec = require('child_process').exec
const files = fs.readdirSync(config.samplePath)
files.forEach((filename) => {
const fullname = path.join(config.samplePath, filename)
const outname = path.join('./assets/samples', `${filename.split('.')[0]}.ogg`)
const ffmpeg = path.join(config.ffmpegPath, 'ffmpeg.exe')
const cmd = `${ffmpeg} -i ${fullname} -codec:a libvorbis ${outname}`
exec(cmd, (error) => {
if (error) {
console.error(error)
}
console.log(filename)
})
})
|
(function(){
/**
* not yet implemented.
*
* @class LocalizationUtility
* @constructor
* @namespace <%= nameSpace.toLowerCase() %>.localization
*/
var LocalizationUtility = function() {
if (LocalizationUtility.instance===null) {
LocalizationUtility.instance = this;
this.initialize();
}else{
<%= nameSpace %>.logger.error('You should not call the constructor for ' + this.toString() + ' directly. It is a singleton, so you should use getInstance()');
}
};
LocalizationUtility.instance = null;
LocalizationUtility.getInstance = function (){
if(LocalizationUtility.instance===null){
LocalizationUtility.instance = new LocalizationUtility();
}
return LocalizationUtility.instance;
};
LocalizationUtility.localizationHash = [];
LocalizationUtility.localizedContent = [];
LocalizationUtility.getContent = function ($sectionKey, $fieldKey){
var returnValue = (LocalizationUtility.localizationHash[$sectionKey] && LocalizationUtility.localizationHash[$sectionKey][$fieldKey]) ? LocalizationUtility.localizationHash[$sectionKey][$fieldKey] : '';
if(returnValue == '')
<%= nameSpace %>.logger.warn($sectionKey+', '+$fieldKey+' was not found in the localization hash');
return returnValue.replace('®', '<sup>®</sup>').replace('(MD)', '<sup>MD</sup>');
};
LocalizationUtility.prepData = function(){
LocalizationUtility.localizationHash = LocalizationUtility.flattenData();
};
LocalizationUtility.flattenData = function(){
var flattenedMap = [];
for (var i = LocalizationUtility.localizedContent.length - 1; i >= 0; i--){
var section = LocalizationUtility.localizedContent[i];
var fields = [];
for (var ii = section.fields.length - 1; ii >= 0; ii--){
var field = section.fields[ii];
fields[field.key] = field.value;
};
flattenedMap[section.key] = fields;
};
return flattenedMap;
};
LocalizationUtility.repopulate = function($localizedContent){
LocalizationUtility.localizedContent = $localizedContent;
LocalizationUtility.prepData();
new <%= nameSpace %>.LocalizationProxyEvent(<%= nameSpace %>.LocalizationEvent.REPOPULATED).dispatch();
};
LocalizationUtility.initialized = false;
var p = LocalizationUtility.prototype;
p.initialize = function (){};
/**
* toString returns the class name.
*
* @method toString
* @return {String} Class name.
*/
p.toString = function (){
return '[LocalizationUtility]';
};
<%= nameSpace %>.LocalizationUtility = LocalizationUtility;
}()); |
var request = require('superagent');
var config = require('../config');
var utils = require('./utils');
var extend = require('extend');
var count = 1;
var query = {
view : 'pointToSOIL(-121.9921875,39.02771884021161,8192)',
tq : 'SELECT *',
tqx : 'reqId:'
};
module.exports = {
getAll : getAll
};
function getAll(query, callback) {
request
.post(config().ahbServer+config().ahbBulkSoilUrl)
.send({coordinates: query})
.end(function(err, resp){
if( err ) {
return callback(err);
}
resp = resp.body;
// HACK
resp.coordinates.forEach(function(item){
item.maxAWS = item.maxaws;
delete item.maxaws;
for( var key in item ) {
item[key] = parseFloat(item[key]);
}
});
callback(null, resp.coordinates);
});
} |
/**
* Main application routes
*/
'use strict';
var errors = require('./components/errors');
var path = require('path');
module.exports = function(app) {
// Insert routes below
app.use('/api/polls', require('./api/poll'));
app.use('/api/things', require('./api/thing'));
app.use('/api/users', require('./api/user'));
app.use('/auth', require('./auth'));
// All undefined asset or api routes should return a 404
app.route('/:url(api|auth|components|app|bower_components|assets)/*')
.get(errors[404]);
// All other routes should redirect to the index.html
app.route('/*')
.get(function(req, res) {
res.sendFile(path.resolve(app.get('appPath') + '/index.html'));
});
};
|
import { FETCHED_EVALS, FETCHED_EVAL } from '../sagas/event'
export function EvalInfoReducer (state = {}, action) {
switch (action.type) {
case FETCHED_EVAL:
return action.payload
default:
}
return state
}
export function EvalListReducer (state = [], action) {
switch (action.type) {
case FETCHED_EVALS:
return action.payload
default:
}
return state
}
|
var SocketIO = require('socket.io')
var di = require('di')
var util = require('util')
var Promise = require('bluebird')
var root = global || window || this
var cfg = require('./config')
var logger = require('./logger')
var constant = require('./constants')
var watcher = require('./watcher')
var plugin = require('./plugin')
var ws = require('./web-server')
var preprocessor = require('./preprocessor')
var Launcher = require('./launcher').Launcher
var FileList = require('./file-list')
var reporter = require('./reporter')
var helper = require('./helper')
var events = require('./events')
var EventEmitter = events.EventEmitter
var Executor = require('./executor')
var Browser = require('./browser')
var BrowserCollection = require('./browser_collection')
var EmitterWrapper = require('./emitter_wrapper')
var processWrapper = new EmitterWrapper(process)
function createSocketIoServer (webServer, executor, config) {
var server = new SocketIO(webServer, {
// avoid destroying http upgrades from socket.io to get proxied websockets working
destroyUpgrade: false,
path: config.urlRoot + 'socket.io/',
transports: config.transports
})
// hack to overcome circular dependency
executor.socketIoSockets = server.sockets
return server
}
function setupLogger (level, colors) {
var logLevel = logLevel || constant.LOG_INFO
var logColors = helper.isDefined(colors) ? colors : true
logger.setup(logLevel, logColors, [constant.CONSOLE_APPENDER])
}
// Constructor
var Server = function (cliOptions, done) {
EventEmitter.call(this)
setupLogger(cliOptions.logLevel, cliOptions.colors)
this.log = logger.create()
var config = cfg.parseConfig(cliOptions.configFile, cliOptions)
var modules = [{
helper: ['value', helper],
logger: ['value', logger],
done: ['value', done || process.exit],
emitter: ['value', this],
launcher: ['type', Launcher],
config: ['value', config],
preprocess: ['factory', preprocessor.createPreprocessor],
fileList: ['type', FileList],
webServer: ['factory', ws.create],
socketServer: ['factory', createSocketIoServer],
executor: ['type', Executor],
// TODO(vojta): remove
customFileHandlers: ['value', []],
// TODO(vojta): remove, once karma-dart does not rely on it
customScriptTypes: ['value', []],
reporter: ['factory', reporter.createReporters],
capturedBrowsers: ['type', BrowserCollection],
args: ['value', {}],
timer: ['value', {
setTimeout: function () { return setTimeout.apply(root, arguments)},
clearTimeout: function (timeoutId) { clearTimeout(timeoutId)}
}]
}]
// Load the plugins
modules = modules.concat(plugin.resolve(config.plugins))
this._injector = new di.Injector(modules)
}
// Inherit from events.EventEmitter
util.inherits(Server, EventEmitter)
// Public Methods
// --------------
// Start the server
Server.prototype.start = function () {
this._injector.invoke(this._start, this)
}
/**
* Backward-compatibility with karma-intellij bundled with WebStorm.
* Deprecated since version 0.13, to be removed in 0.14
*/
Server.start = function (cliOptions, done) {
var server = new Server(cliOptions, done)
server.start()
}
// Get properties from the injector
//
// token - String
Server.prototype.get = function (token) {
return this._injector.get(token)
}
// Force a refresh of the file list
Server.prototype.refreshFiles = function () {
if (!this._fileList) return Promise.resolve()
return this._fileList.refresh()
}
// Private Methods
// ---------------
Server.prototype._start = function (config, launcher, preprocess, fileList, webServer,
capturedBrowsers, socketServer, executor, done) {
var self = this
self._fileList = fileList
config.frameworks.forEach(function (framework) {
self._injector.get('framework:' + framework)
})
// A map of launched browsers.
var singleRunDoneBrowsers = Object.create(null)
// Passing fake event emitter, so that it does not emit on the global,
// we don't care about these changes.
var singleRunBrowsers = new BrowserCollection(new EventEmitter())
// Some browsers did not get captured.
var singleRunBrowserNotCaptured = false
webServer.on('error', function (e) {
if (e.code === 'EADDRINUSE') {
self.log.warn('Port %d in use', config.port)
config.port++
webServer.listen(config.port)
} else {
throw e
}
})
var afterPreprocess = function () {
if (config.autoWatch) {
self._injector.invoke(watcher.watch)
}
webServer.listen(config.port, function () {
self.log.info('Karma v%s server started at http://%s:%s%s', constant.VERSION, config.hostname,
config.port, config.urlRoot)
if (config.browsers && config.browsers.length) {
self._injector.invoke(launcher.launch, launcher).forEach(function (browserLauncher) {
singleRunDoneBrowsers[browserLauncher.id] = false
})
}
})
}
fileList.refresh().then(afterPreprocess, afterPreprocess)
self.on('browsers_change', function () {
// TODO(vojta): send only to interested browsers
socketServer.sockets.emit('info', capturedBrowsers.serialize())
})
self.on('browser_register', function (browser) {
launcher.markCaptured(browser.id)
// TODO(vojta): This is lame, browser can get captured and then
// crash (before other browsers get captured).
if (launcher.areAllCaptured()) {
self.emit('browsers_ready')
if (config.autoWatch) {
executor.schedule()
}
}
})
var EVENTS_TO_REPLY = ['start', 'info', 'karma_error', 'result', 'complete']
socketServer.sockets.on('connection', function (socket) {
self.log.debug('A browser has connected on socket ' + socket.id)
var replySocketEvents = events.bufferEvents(socket, EVENTS_TO_REPLY)
socket.on('complete', function (data, ack) {
ack()
})
socket.on('register', function (info) {
var newBrowser
var isRestart
if (info.id) {
newBrowser = capturedBrowsers.getById(info.id) || singleRunBrowsers.getById(info.id)
}
if (newBrowser) {
isRestart = newBrowser.state === Browser.STATE_DISCONNECTED
newBrowser.reconnect(socket)
// We are restarting a previously disconnected browser.
if (isRestart && config.singleRun) {
newBrowser.execute(config.client)
}
} else {
newBrowser = self._injector.createChild([{
id: ['value', info.id || null],
fullName: ['value', info.name],
socket: ['value', socket]
}]).instantiate(Browser)
newBrowser.init()
// execute in this browser immediately
if (config.singleRun) {
newBrowser.execute(config.client)
singleRunBrowsers.add(newBrowser)
}
}
replySocketEvents()
})
})
var emitRunCompleteIfAllBrowsersDone = function () {
// all browsers done
var isDone = Object.keys(singleRunDoneBrowsers).reduce(function (isDone, id) {
return isDone && singleRunDoneBrowsers[id]
}, true)
if (isDone) {
var results = singleRunBrowsers.getResults()
if (singleRunBrowserNotCaptured) {
results.exitCode = 1
}
self.emit('run_complete', singleRunBrowsers, results)
}
}
if (config.singleRun) {
self.on('browser_complete', function (completedBrowser) {
if (completedBrowser.lastResult.disconnected &&
completedBrowser.disconnectsCount <= config.browserDisconnectTolerance) {
self.log.info('Restarting %s (%d of %d attempts)', completedBrowser.name,
completedBrowser.disconnectsCount, config.browserDisconnectTolerance)
if (!launcher.restart(completedBrowser.id)) {
singleRunDoneBrowsers[completedBrowser.id] = true
emitRunCompleteIfAllBrowsersDone()
}
} else {
singleRunDoneBrowsers[completedBrowser.id] = true
if (launcher.kill(completedBrowser.id)) {
// workaround to supress "disconnect" warning
completedBrowser.state = Browser.STATE_DISCONNECTED
}
emitRunCompleteIfAllBrowsersDone()
}
})
self.on('browser_process_failure', function (browserLauncher) {
singleRunDoneBrowsers[browserLauncher.id] = true
singleRunBrowserNotCaptured = true
emitRunCompleteIfAllBrowsersDone()
})
self.on('run_complete', function (browsers, results) {
self.log.debug('Run complete, exiting.')
disconnectBrowsers(results.exitCode)
})
self.emit('run_start', singleRunBrowsers)
}
if (config.autoWatch) {
self.on('file_list_modified', function () {
self.log.debug('List of files has changed, trying to execute')
executor.schedule()
})
}
var webServerCloseTimeout = 3000
var disconnectBrowsers = function (code) {
// Slightly hacky way of removing disconnect listeners
// to suppress "browser disconnect" warnings
// TODO(vojta): change the client to not send the event (if disconnected by purpose)
var sockets = socketServer.sockets.sockets
sockets.forEach(function (socket) {
socket.removeAllListeners('disconnect')
if (!socket.disconnected) {
// Disconnect asynchronously. Socket.io mutates the `sockets.sockets` array
// underneath us so this would skip every other browser/socket.
process.nextTick(socket.disconnect.bind(socket))
}
})
var removeAllListenersDone = false
var removeAllListeners = function () {
// make sure we don't execute cleanup twice
if (removeAllListenersDone) {
return
}
removeAllListenersDone = true
webServer.removeAllListeners()
processWrapper.removeAllListeners()
done(code || 0)
}
self.emitAsync('exit').then(function () {
// don't wait forever on webServer.close() because
// pending client connections prevent it from closing.
var closeTimeout = setTimeout(removeAllListeners, webServerCloseTimeout)
// shutdown the server...
webServer.close(function () {
clearTimeout(closeTimeout)
removeAllListeners()
})
})
}
processWrapper.on('SIGINT', disconnectBrowsers)
processWrapper.on('SIGTERM', disconnectBrowsers)
// Handle all unhandled exceptions, so we don't just exit but
// disconnect the browsers before exiting.
processWrapper.on('uncaughtException', function (error) {
self.log.error(error)
disconnectBrowsers(1)
})
}
// Export
// ------
module.exports = Server
|
module.exports = function($http, $q, EventEmitter) {
var events = EventEmitter('youtube'),
apiUrl = 'http://127.0.0.1:3000/search';
// Exposed method designed to be used
// for querying, returns a promise
function search(query) {
return $http.post(apiUrl, {
query: query
});
}
return {
on: events.on,
search: search
};
};
|
import Navbar from './navbar.vue'
export default Navbar
|
'use strict';
module.exports = function(app) {
var workerthreads = require('../../app/controllers/workerthreads.server.controller');
// Workerthreads Routes
app.route('/workerthreads')
.get(workerthreads.list)
.post(workerthreads.create);
};
|
module.exports = (function () {
return {
DEFAULT_VALUE_NAME: 'Value',
CANVAS_WIDTH: 300,
CANVAS_HEIGHT: 201,
// game1 constants
GAME1_BOARD_TOP_LEFT_POINT_X: 50,
GAME1_BOARD_TOP_LEFT_POINT_Y: 100,
GAME1_BOARD_WIDTH: 200,
GAME1_BOARD_HEIGHT: 10,
GAME1_BOARD_FILL: 'black',
GAME1_BOARD_STROKE: 'none',
GAME1_BOARD_STROKE_WIDTH: 1,
GAME1_BALL_START_X: 150,
GAME1_BALL_START_Y: 90,
GAME1_BALL_RADIUS: 10,
GAME1_BALL_FILL: 'red',
GAME1_BALL_STROKE: 'none',
GAME1_BALL_STROKE_WIDTH: 1,
GAME1_BALL_STEP: 1.5,
GAME1_BALL_MIN_X: 50,
GAME1_BALL_MAX_X: 250,
GAME1_INITIAL_ROTATION_ANGLE: 0,
GAME1_ROTATION_ANGLE_STEP: 0.02,
GAME1_ROTATION_ANGLE_STEP_WHEN_PRESSED: 0.05,
GAME1_ROT_ANGLE_STEP_MODIFIER: 100,
GAME1_ROT_ANGLE_STEP_MODIFIER_WHEN_PRESSED: 2000,
// game2 constants:
GAME2_PLAYER_TOP_LEFT_POINT_X: 145,
GAME2_PLAYER_TOP_LEFT_POINT_Y: 90,
GAME2_PLAYER_WIDTH: 10,
GAME2_PLAYER_HEIGHT: 20,
GAME2_PLAYER_MIN_Y: 50,
GAME2_PLAYER_MAX_Y: 130,
GAME2_PLAYER_STEP: 20,
GAME2_PLAYER_FILL: 'blue',
GAME2_PLAYER_STROKE: 'black',
GAME2_PLAYER_STROKE_WIDTH: 2,
GAME2_RP_OBSTACLE_START_POINT_A_X: -20,
GAME2_RP_OBSTACLE_START_POINT_A_Y: 50,
GAME2_RP_OBSTACLE_START_POINT_B_X: -20,
GAME2_RP_OBSTACLE_START_POINT_B_Y: 60,
GAME2_RP_OBSTACLE_START_POINT_C_X: -5,
GAME2_RP_OBSTACLE_START_POINT_C_Y: 55,
GAME2_OBSTACLES_STEP: 2,
GAME2_RP_OBSTACLE_FILL: 'black',
GAME2_RP_OBSTACLE_STROKE: 'none',
GAME2_RP_OBSTACLE_STROKE_WIDTH: 1,
GAME2_LP_OBSTACLE_START_POINT_A_X: 320,
GAME2_LP_OBSTACLE_START_POINT_A_Y: 90,
GAME2_LP_OBSTACLE_START_POINT_B_X: 320,
GAME2_LP_OBSTACLE_START_POINT_B_Y: 100,
GAME2_LP_OBSTACLE_START_POINT_C_X: 305,
GAME2_LP_OBSTACLE_START_POINT_C_Y: 95,
GAME2_LP_OBSTACLE_FILL: 'black',
GAME2_LP_OBSTACLE_STROKE: 'none',
GAME2_LP_OBSTACLE_STROKE_WIDTH: 1,
GAME2_POINT_TO_RESET_RP_OBSTACLE_X: 200,
GAME2_POINT_TO_RESET_LP_OBSTACLE_X: 120,
GAME2_BACKGROUND_TOP_LEFT_X: 145,
GAME2_BACKGROUND_TOP_LEFT_Y: 50,
GAME2_BACKGROUND_RECTS_WIDTH: 10,
GAME2_BACKGROUND_RECTS_HEIGHT: 20,
GAME2_BACKGROUND_RECTS_COUNT: 5,
GAME2_BACKGROUND_RECTS_FILL: 'none',
GAME2_BACKGROUND_RECTS_STROKE: 'black',
GAME2_BACKGROUND_RECTS_STROKE_WIDTH: 2,
// game3 constants:
GAME3_PLAYER_TOP_LEFT_POINT_X: 50,
GAME3_PLAYER_TOP_LEFT_POINT_Y: 180,
GAME3_PLAYER_BOTTOM_LEFT_POINT_X: 50,
GAME3_PLAYER_BOTTOM_LEFT_POINT_Y: 200,
GAME3_PLAYER_RIGHT_POINT_X: 65,
GAME3_PLAYER_RIGHT_POINT_Y: 190,
GAME3_PLAYER_MIN_Y: 0,
GAME3_PLAYER_MAX_Y: 180,
GAME3_PLAYER_STEP: 2,
GAME3_PLAYER_FILL: 'azure',
GAME3_PLAYER_STROKE: 'purple',
GAME3_PLAYER_STROKE_WIDTH: 2,
GAME3_OBSTACLE_START_POINT_X: 300,
GAME3_POINT_TO_RELEASE_NEW_OBSTACLE_X: 140,
GAME3_POINT_TO_REMOVE_OBSTACLE_X: 0,
GAME3_OBSTACLE_WIDTH: 15,
GAME3_OBSTACLE_HEIGHT: 50,
GAME3_OBSTACLE_MAX_Y: 150,
GAME3_OBSTACLE_STEP: 2,
GAME3_OBSTACLE_FILL: 'black',
GAME3_OBSTACLE_STROKE: 'none',
GAME3_OBSTACLE_STROKE_WIDTH: 1,
// game4 constants:
GAME4_PLAYER_TOP_LEFT_POINT_X: 150,
GAME4_PLAYER_TOP_LEFT_POINT_Y: 100,
GAME4_PLAYER_WIDTH: 30,
GAME4_PLAYER_HEIGHT: 30,
GAME4_PLAYER_MIN_X: 0,
GAME4_PLAYER_MAX_X: 270,
GAME4_PLAYER_MIN_Y: 0,
GAME4_PLAYER_MAX_Y: 170,
GAME4_PLAYER_STEP: 3,
GAME4_PLAYER_FILL: 'green',
GAME4_PLAYER_STROKE: 'none',
GAME4_PLAYER_STROKE_WIDTH: 1,
GAME4_OBSTACLE_CREATION_INTERVAL: 4000,
GAME4_OBSTACLE_WIDTH: 40,
GAME4_OBSTACLE_HEIGHT: 40,
GAME4_OBSTACLE_MAX_X: 260,
GAME4_OBSTACLE_MAX_Y: 160,
GAME4_OBSTACLE_COUNTER_START_VALUE: 10,
GAME4_OBSTACLE_COUNTER_STEP: 1000,
GAME4_OBSTACLE_FILL: 'grey',
GAME4_OBSTACLE_STROKE: 'none',
GAME4_OBSTACLE_STROKE_WIDTH: 1,
};
}()); |
export const handleError = (routeCallback) => {
return (req, res, next) => {
routeCallback(req,res).catch(next);
};
};
|
/*!
* @overview es6-promise - a tiny implementation of Promises/A+.
* @copyright Copyright (c) 2014 Yehuda Katz, Tom Dale, Stefan Penner and contributors (Conversion to ES6 API by Jake Archibald)
* @license Licensed under MIT license
* See https://raw.githubusercontent.com/stefanpenner/es6-promise/master/LICENSE
* @version v4.2.4+314e4831
*/
/* jshint ignore:start */
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() :
typeof define === 'function' && define.amd ? define(factory) :
(global.ES6Promise = factory());
}(this, (function () { 'use strict';
function objectOrFunction(x) {
var type = typeof x;
return x !== null && (type === 'object' || type === 'function');
}
function isFunction(x) {
return typeof x === 'function';
}
var _isArray = void 0;
if (Array.isArray) {
_isArray = Array.isArray;
} else {
_isArray = function (x) {
return Object.prototype.toString.call(x) === '[object Array]';
};
}
var isArray = _isArray;
var len = 0;
var vertxNext = void 0;
var customSchedulerFn = void 0;
var asap = function asap(callback, arg) {
queue[len] = callback;
queue[len + 1] = arg;
len += 2;
if (len === 2) {
// If len is 2, that means that we need to schedule an async flush.
// If additional callbacks are queued before the queue is flushed, they
// will be processed by this flush that we are scheduling.
if (customSchedulerFn) {
customSchedulerFn(flush);
} else {
scheduleFlush();
}
}
};
function setScheduler(scheduleFn) {
customSchedulerFn = scheduleFn;
}
function setAsap(asapFn) {
asap = asapFn;
}
var browserWindow = typeof window !== 'undefined' ? window : undefined;
var browserGlobal = browserWindow || {};
var BrowserMutationObserver = browserGlobal.MutationObserver || browserGlobal.WebKitMutationObserver;
var isNode = typeof self === 'undefined' && typeof process !== 'undefined' && {}.toString.call(process) === '[object process]';
// test for web worker but not in IE10
var isWorker = typeof Uint8ClampedArray !== 'undefined' && typeof importScripts !== 'undefined' && typeof MessageChannel !== 'undefined';
// node
function useNextTick() {
// node version 0.10.x displays a deprecation warning when nextTick is used recursively
// see https://github.com/cujojs/when/issues/410 for details
return function () {
return process.nextTick(flush);
};
}
// vertx
function useVertxTimer() {
if (typeof vertxNext !== 'undefined') {
return function () {
vertxNext(flush);
};
}
return useSetTimeout();
}
function useMutationObserver() {
var iterations = 0;
var observer = new BrowserMutationObserver(flush);
var node = document.createTextNode('');
observer.observe(node, { characterData: true });
return function () {
node.data = iterations = ++iterations % 2;
};
}
// web worker
function useMessageChannel() {
var channel = new MessageChannel();
channel.port1.onmessage = flush;
return function () {
return channel.port2.postMessage(0);
};
}
function useSetTimeout() {
// Store setTimeout reference so es6-promise will be unaffected by
// other code modifying setTimeout (like sinon.useFakeTimers())
var globalSetTimeout = setTimeout;
return function () {
return globalSetTimeout(flush, 1);
};
}
var queue = new Array(1000);
function flush() {
for (var i = 0; i < len; i += 2) {
var callback = queue[i];
var arg = queue[i + 1];
callback(arg);
queue[i] = undefined;
queue[i + 1] = undefined;
}
len = 0;
}
function attemptVertx() {
try {
var vertx = Function('return this')().require('vertx');
vertxNext = vertx.runOnLoop || vertx.runOnContext;
return useVertxTimer();
} catch (e) {
return useSetTimeout();
}
}
var scheduleFlush = void 0;
// Decide what async method to use to triggering processing of queued callbacks:
if (isNode) {
scheduleFlush = useNextTick();
} else if (BrowserMutationObserver) {
scheduleFlush = useMutationObserver();
} else if (isWorker) {
scheduleFlush = useMessageChannel();
} else if (browserWindow === undefined && typeof require === 'function') {
scheduleFlush = attemptVertx();
} else {
scheduleFlush = useSetTimeout();
}
function then(onFulfillment, onRejection) {
var parent = this;
var child = new this.constructor(noop);
if (child[PROMISE_ID] === undefined) {
makePromise(child);
}
var _state = parent._state;
if (_state) {
var callback = arguments[_state - 1];
asap(function () {
return invokeCallback(_state, child, callback, parent._result);
});
} else {
subscribe(parent, child, onFulfillment, onRejection);
}
return child;
}
/**
`Promise.resolve` returns a promise that will become resolved with the
passed `value`. It is shorthand for the following:
```javascript
let promise = new Promise(function(resolve, reject){
resolve(1);
});
promise.then(function(value){
// value === 1
});
```
Instead of writing the above, your code now simply becomes the following:
```javascript
let promise = Promise.resolve(1);
promise.then(function(value){
// value === 1
});
```
@method resolve
@static
@param {Any} value value that the returned promise will be resolved with
Useful for tooling.
@return {Promise} a promise that will become fulfilled with the given
`value`
*/
function resolve$1(object) {
var Constructor = this;
if (object && typeof object === 'object' && object.constructor === Constructor) {
return object;
}
var promise = new Constructor(noop);
resolve(promise, object);
return promise;
}
var PROMISE_ID = Math.random().toString(36).substring(2);
function noop() {}
var PENDING = void 0;
var FULFILLED = 1;
var REJECTED = 2;
var TRY_CATCH_ERROR = { error: null };
function selfFulfillment() {
return new TypeError("You cannot resolve a promise with itself");
}
function cannotReturnOwn() {
return new TypeError('A promises callback cannot return that same promise.');
}
function getThen(promise) {
try {
return promise.then;
} catch (error) {
TRY_CATCH_ERROR.error = error;
return TRY_CATCH_ERROR;
}
}
function tryThen(then$$1, value, fulfillmentHandler, rejectionHandler) {
try {
then$$1.call(value, fulfillmentHandler, rejectionHandler);
} catch (e) {
return e;
}
}
function handleForeignThenable(promise, thenable, then$$1) {
asap(function (promise) {
var sealed = false;
var error = tryThen(then$$1, thenable, function (value) {
if (sealed) {
return;
}
sealed = true;
if (thenable !== value) {
resolve(promise, value);
} else {
fulfill(promise, value);
}
}, function (reason) {
if (sealed) {
return;
}
sealed = true;
reject(promise, reason);
}, 'Settle: ' + (promise._label || ' unknown promise'));
if (!sealed && error) {
sealed = true;
reject(promise, error);
}
}, promise);
}
function handleOwnThenable(promise, thenable) {
if (thenable._state === FULFILLED) {
fulfill(promise, thenable._result);
} else if (thenable._state === REJECTED) {
reject(promise, thenable._result);
} else {
subscribe(thenable, undefined, function (value) {
return resolve(promise, value);
}, function (reason) {
return reject(promise, reason);
});
}
}
function handleMaybeThenable(promise, maybeThenable, then$$1) {
if (maybeThenable.constructor === promise.constructor && then$$1 === then && maybeThenable.constructor.resolve === resolve$1) {
handleOwnThenable(promise, maybeThenable);
} else {
if (then$$1 === TRY_CATCH_ERROR) {
reject(promise, TRY_CATCH_ERROR.error);
TRY_CATCH_ERROR.error = null;
} else if (then$$1 === undefined) {
fulfill(promise, maybeThenable);
} else if (isFunction(then$$1)) {
handleForeignThenable(promise, maybeThenable, then$$1);
} else {
fulfill(promise, maybeThenable);
}
}
}
function resolve(promise, value) {
if (promise === value) {
reject(promise, selfFulfillment());
} else if (objectOrFunction(value)) {
handleMaybeThenable(promise, value, getThen(value));
} else {
fulfill(promise, value);
}
}
function publishRejection(promise) {
if (promise._onerror) {
promise._onerror(promise._result);
}
publish(promise);
}
function fulfill(promise, value) {
if (promise._state !== PENDING) {
return;
}
promise._result = value;
promise._state = FULFILLED;
if (promise._subscribers.length !== 0) {
asap(publish, promise);
}
}
function reject(promise, reason) {
if (promise._state !== PENDING) {
return;
}
promise._state = REJECTED;
promise._result = reason;
asap(publishRejection, promise);
}
function subscribe(parent, child, onFulfillment, onRejection) {
var _subscribers = parent._subscribers;
var length = _subscribers.length;
parent._onerror = null;
_subscribers[length] = child;
_subscribers[length + FULFILLED] = onFulfillment;
_subscribers[length + REJECTED] = onRejection;
if (length === 0 && parent._state) {
asap(publish, parent);
}
}
function publish(promise) {
var subscribers = promise._subscribers;
var settled = promise._state;
if (subscribers.length === 0) {
return;
}
var child = void 0,
callback = void 0,
detail = promise._result;
for (var i = 0; i < subscribers.length; i += 3) {
child = subscribers[i];
callback = subscribers[i + settled];
if (child) {
invokeCallback(settled, child, callback, detail);
} else {
callback(detail);
}
}
promise._subscribers.length = 0;
}
function tryCatch(callback, detail) {
try {
return callback(detail);
} catch (e) {
TRY_CATCH_ERROR.error = e;
return TRY_CATCH_ERROR;
}
}
function invokeCallback(settled, promise, callback, detail) {
var hasCallback = isFunction(callback),
value = void 0,
error = void 0,
succeeded = void 0,
failed = void 0;
if (hasCallback) {
value = tryCatch(callback, detail);
if (value === TRY_CATCH_ERROR) {
failed = true;
error = value.error;
value.error = null;
} else {
succeeded = true;
}
if (promise === value) {
reject(promise, cannotReturnOwn());
return;
}
} else {
value = detail;
succeeded = true;
}
if (promise._state !== PENDING) {
// noop
} else if (hasCallback && succeeded) {
resolve(promise, value);
} else if (failed) {
reject(promise, error);
} else if (settled === FULFILLED) {
fulfill(promise, value);
} else if (settled === REJECTED) {
reject(promise, value);
}
}
function initializePromise(promise, resolver) {
try {
resolver(function resolvePromise(value) {
resolve(promise, value);
}, function rejectPromise(reason) {
reject(promise, reason);
});
} catch (e) {
reject(promise, e);
}
}
var id = 0;
function nextId() {
return id++;
}
function makePromise(promise) {
promise[PROMISE_ID] = id++;
promise._state = undefined;
promise._result = undefined;
promise._subscribers = [];
}
function validationError() {
return new Error('Array Methods must be provided an Array');
}
var Enumerator = function () {
function Enumerator(Constructor, input) {
this._instanceConstructor = Constructor;
this.promise = new Constructor(noop);
if (!this.promise[PROMISE_ID]) {
makePromise(this.promise);
}
if (isArray(input)) {
this.length = input.length;
this._remaining = input.length;
this._result = new Array(this.length);
if (this.length === 0) {
fulfill(this.promise, this._result);
} else {
this.length = this.length || 0;
this._enumerate(input);
if (this._remaining === 0) {
fulfill(this.promise, this._result);
}
}
} else {
reject(this.promise, validationError());
}
}
Enumerator.prototype._enumerate = function _enumerate(input) {
for (var i = 0; this._state === PENDING && i < input.length; i++) {
this._eachEntry(input[i], i);
}
};
Enumerator.prototype._eachEntry = function _eachEntry(entry, i) {
var c = this._instanceConstructor;
var resolve$$1 = c.resolve;
if (resolve$$1 === resolve$1) {
var _then = getThen(entry);
if (_then === then && entry._state !== PENDING) {
this._settledAt(entry._state, i, entry._result);
} else if (typeof _then !== 'function') {
this._remaining--;
this._result[i] = entry;
} else if (c === Promise$1) {
var promise = new c(noop);
handleMaybeThenable(promise, entry, _then);
this._willSettleAt(promise, i);
} else {
this._willSettleAt(new c(function (resolve$$1) {
return resolve$$1(entry);
}), i);
}
} else {
this._willSettleAt(resolve$$1(entry), i);
}
};
Enumerator.prototype._settledAt = function _settledAt(state, i, value) {
var promise = this.promise;
if (promise._state === PENDING) {
this._remaining--;
if (state === REJECTED) {
reject(promise, value);
} else {
this._result[i] = value;
}
}
if (this._remaining === 0) {
fulfill(promise, this._result);
}
};
Enumerator.prototype._willSettleAt = function _willSettleAt(promise, i) {
var enumerator = this;
subscribe(promise, undefined, function (value) {
return enumerator._settledAt(FULFILLED, i, value);
}, function (reason) {
return enumerator._settledAt(REJECTED, i, reason);
});
};
return Enumerator;
}();
/**
`Promise.all` accepts an array of promises, and returns a new promise which
is fulfilled with an array of fulfillment values for the passed promises, or
rejected with the reason of the first passed promise to be rejected. It casts all
elements of the passed iterable to promises as it runs this algorithm.
Example:
```javascript
let promise1 = resolve(1);
let promise2 = resolve(2);
let promise3 = resolve(3);
let promises = [ promise1, promise2, promise3 ];
Promise.all(promises).then(function(array){
// The array here would be [ 1, 2, 3 ];
});
```
If any of the `promises` given to `all` are rejected, the first promise
that is rejected will be given as an argument to the returned promises's
rejection handler. For example:
Example:
```javascript
let promise1 = resolve(1);
let promise2 = reject(new Error("2"));
let promise3 = reject(new Error("3"));
let promises = [ promise1, promise2, promise3 ];
Promise.all(promises).then(function(array){
// Code here never runs because there are rejected promises!
}, function(error) {
// error.message === "2"
});
```
@method all
@static
@param {Array} entries array of promises
@param {String} label optional string for labeling the promise.
Useful for tooling.
@return {Promise} promise that is fulfilled when all `promises` have been
fulfilled, or rejected if any of them become rejected.
@static
*/
function all(entries) {
return new Enumerator(this, entries).promise;
}
/**
`Promise.race` returns a new promise which is settled in the same way as the
first passed promise to settle.
Example:
```javascript
let promise1 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 1');
}, 200);
});
let promise2 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 2');
}, 100);
});
Promise.race([promise1, promise2]).then(function(result){
// result === 'promise 2' because it was resolved before promise1
// was resolved.
});
```
`Promise.race` is deterministic in that only the state of the first
settled promise matters. For example, even if other promises given to the
`promises` array argument are resolved, but the first settled promise has
become rejected before the other promises became fulfilled, the returned
promise will become rejected:
```javascript
let promise1 = new Promise(function(resolve, reject){
setTimeout(function(){
resolve('promise 1');
}, 200);
});
let promise2 = new Promise(function(resolve, reject){
setTimeout(function(){
reject(new Error('promise 2'));
}, 100);
});
Promise.race([promise1, promise2]).then(function(result){
// Code here never runs
}, function(reason){
// reason.message === 'promise 2' because promise 2 became rejected before
// promise 1 became fulfilled
});
```
An example real-world use case is implementing timeouts:
```javascript
Promise.race([ajax('foo.json'), timeout(5000)])
```
@method race
@static
@param {Array} promises array of promises to observe
Useful for tooling.
@return {Promise} a promise which settles in the same way as the first passed
promise to settle.
*/
function race(entries) {
var Constructor = this;
if (!isArray(entries)) {
return new Constructor(function (_, reject) {
return reject(new TypeError('You must pass an array to race.'));
});
} else {
return new Constructor(function (resolve, reject) {
var length = entries.length;
for (var i = 0; i < length; i++) {
Constructor.resolve(entries[i]).then(resolve, reject);
}
});
}
}
/**
`Promise.reject` returns a promise rejected with the passed `reason`.
It is shorthand for the following:
```javascript
let promise = new Promise(function(resolve, reject){
reject(new Error('WHOOPS'));
});
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
Instead of writing the above, your code now simply becomes the following:
```javascript
let promise = Promise.reject(new Error('WHOOPS'));
promise.then(function(value){
// Code here doesn't run because the promise is rejected!
}, function(reason){
// reason.message === 'WHOOPS'
});
```
@method reject
@static
@param {Any} reason value that the returned promise will be rejected with.
Useful for tooling.
@return {Promise} a promise rejected with the given `reason`.
*/
function reject$1(reason) {
var Constructor = this;
var promise = new Constructor(noop);
reject(promise, reason);
return promise;
}
function needsResolver() {
throw new TypeError('You must pass a resolver function as the first argument to the promise constructor');
}
function needsNew() {
throw new TypeError("Failed to construct 'Promise': Please use the 'new' operator, this object constructor cannot be called as a function.");
}
/**
Promise objects represent the eventual result of an asynchronous operation. The
primary way of interacting with a promise is through its `then` method, which
registers callbacks to receive either a promise's eventual value or the reason
why the promise cannot be fulfilled.
Terminology
-----------
- `promise` is an object or function with a `then` method whose behavior conforms to this specification.
- `thenable` is an object or function that defines a `then` method.
- `value` is any legal JavaScript value (including undefined, a thenable, or a promise).
- `exception` is a value that is thrown using the throw statement.
- `reason` is a value that indicates why a promise was rejected.
- `settled` the final resting state of a promise, fulfilled or rejected.
A promise can be in one of three states: pending, fulfilled, or rejected.
Promises that are fulfilled have a fulfillment value and are in the fulfilled
state. Promises that are rejected have a rejection reason and are in the
rejected state. A fulfillment value is never a thenable.
Promises can also be said to *resolve* a value. If this value is also a
promise, then the original promise's settled state will match the value's
settled state. So a promise that *resolves* a promise that rejects will
itself reject, and a promise that *resolves* a promise that fulfills will
itself fulfill.
Basic Usage:
------------
```js
let promise = new Promise(function(resolve, reject) {
// on success
resolve(value);
// on failure
reject(reason);
});
promise.then(function(value) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Advanced Usage:
---------------
Promises shine when abstracting away asynchronous interactions such as
`XMLHttpRequest`s.
```js
function getJSON(url) {
return new Promise(function(resolve, reject){
let xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.onreadystatechange = handler;
xhr.responseType = 'json';
xhr.setRequestHeader('Accept', 'application/json');
xhr.send();
function handler() {
if (this.readyState === this.DONE) {
if (this.status === 200) {
resolve(this.response);
} else {
reject(new Error('getJSON: `' + url + '` failed with status: [' + this.status + ']'));
}
}
};
});
}
getJSON('/posts.json').then(function(json) {
// on fulfillment
}, function(reason) {
// on rejection
});
```
Unlike callbacks, promises are great composable primitives.
```js
Promise.all([
getJSON('/posts'),
getJSON('/comments')
]).then(function(values){
values[0] // => postsJSON
values[1] // => commentsJSON
return values;
});
```
@class Promise
@param {Function} resolver
Useful for tooling.
@constructor
*/
var Promise$1 = function () {
function Promise(resolver) {
this[PROMISE_ID] = nextId();
this._result = this._state = undefined;
this._subscribers = [];
if (noop !== resolver) {
typeof resolver !== 'function' && needsResolver();
this instanceof Promise ? initializePromise(this, resolver) : needsNew();
}
}
/**
The primary way of interacting with a promise is through its `then` method,
which registers callbacks to receive either a promise's eventual value or the
reason why the promise cannot be fulfilled.
```js
findUser().then(function(user){
// user is available
}, function(reason){
// user is unavailable, and you are given the reason why
});
```
Chaining
--------
The return value of `then` is itself a promise. This second, 'downstream'
promise is resolved with the return value of the first promise's fulfillment
or rejection handler, or rejected if the handler throws an exception.
```js
findUser().then(function (user) {
return user.name;
}, function (reason) {
return 'default name';
}).then(function (userName) {
// If `findUser` fulfilled, `userName` will be the user's name, otherwise it
// will be `'default name'`
});
findUser().then(function (user) {
throw new Error('Found user, but still unhappy');
}, function (reason) {
throw new Error('`findUser` rejected and we're unhappy');
}).then(function (value) {
// never reached
}, function (reason) {
// if `findUser` fulfilled, `reason` will be 'Found user, but still unhappy'.
// If `findUser` rejected, `reason` will be '`findUser` rejected and we're unhappy'.
});
```
If the downstream promise does not specify a rejection handler, rejection reasons will be propagated further downstream.
```js
findUser().then(function (user) {
throw new PedagogicalException('Upstream error');
}).then(function (value) {
// never reached
}).then(function (value) {
// never reached
}, function (reason) {
// The `PedgagocialException` is propagated all the way down to here
});
```
Assimilation
------------
Sometimes the value you want to propagate to a downstream promise can only be
retrieved asynchronously. This can be achieved by returning a promise in the
fulfillment or rejection handler. The downstream promise will then be pending
until the returned promise is settled. This is called *assimilation*.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// The user's comments are now available
});
```
If the assimliated promise rejects, then the downstream promise will also reject.
```js
findUser().then(function (user) {
return findCommentsByAuthor(user);
}).then(function (comments) {
// If `findCommentsByAuthor` fulfills, we'll have the value here
}, function (reason) {
// If `findCommentsByAuthor` rejects, we'll have the reason here
});
```
Simple Example
--------------
Synchronous Example
```javascript
let result;
try {
result = findResult();
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
findResult(function(result, err){
if (err) {
// failure
} else {
// success
}
});
```
Promise Example;
```javascript
findResult().then(function(result){
// success
}, function(reason){
// failure
});
```
Advanced Example
--------------
Synchronous Example
```javascript
let author, books;
try {
author = findAuthor();
books = findBooksByAuthor(author);
// success
} catch(reason) {
// failure
}
```
Errback Example
```js
function foundBooks(books) {
}
function failure(reason) {
}
findAuthor(function(author, err){
if (err) {
failure(err);
// failure
} else {
try {
findBoooksByAuthor(author, function(books, err) {
if (err) {
failure(err);
} else {
try {
foundBooks(books);
} catch(reason) {
failure(reason);
}
}
});
} catch(error) {
failure(err);
}
// success
}
});
```
Promise Example;
```javascript
findAuthor().
then(findBooksByAuthor).
then(function(books){
// found books
}).catch(function(reason){
// something went wrong
});
```
@method then
@param {Function} onFulfilled
@param {Function} onRejected
Useful for tooling.
@return {Promise}
*/
/**
`catch` is simply sugar for `then(undefined, onRejection)` which makes it the same
as the catch block of a try/catch statement.
```js
function findAuthor(){
throw new Error('couldn't find that author');
}
// synchronous
try {
findAuthor();
} catch(reason) {
// something went wrong
}
// async with promises
findAuthor().catch(function(reason){
// something went wrong
});
```
@method catch
@param {Function} onRejection
Useful for tooling.
@return {Promise}
*/
Promise.prototype.catch = function _catch(onRejection) {
return this.then(null, onRejection);
};
/**
`finally` will be invoked regardless of the promise's fate just as native
try/catch/finally behaves
Synchronous example:
```js
findAuthor() {
if (Math.random() > 0.5) {
throw new Error();
}
return new Author();
}
try {
return findAuthor(); // succeed or fail
} catch(error) {
return findOtherAuther();
} finally {
// always runs
// doesn't affect the return value
}
```
Asynchronous example:
```js
findAuthor().catch(function(reason){
return findOtherAuther();
}).finally(function(){
// author was either found, or not
});
```
@method finally
@param {Function} callback
@return {Promise}
*/
Promise.prototype.finally = function _finally(callback) {
var promise = this;
var constructor = promise.constructor;
return promise.then(function (value) {
return constructor.resolve(callback()).then(function () {
return value;
});
}, function (reason) {
return constructor.resolve(callback()).then(function () {
throw reason;
});
});
};
return Promise;
}();
Promise$1.prototype.then = then;
Promise$1.all = all;
Promise$1.race = race;
Promise$1.resolve = resolve$1;
Promise$1.reject = reject$1;
Promise$1._setScheduler = setScheduler;
Promise$1._setAsap = setAsap;
Promise$1._asap = asap;
/*global self*/
function polyfill() {
var local = void 0;
if (typeof global !== 'undefined') {
local = global;
} else if (typeof self !== 'undefined') {
local = self;
} else {
try {
local = Function('return this')();
} catch (e) {
throw new Error('polyfill failed because global object is unavailable in this environment');
}
}
var P = local.Promise;
if (P) {
var promiseToString = null;
try {
promiseToString = Object.prototype.toString.call(P.resolve());
} catch (e) {
// silently ignored
}
if (promiseToString === '[object Promise]' && !P.cast) {
return;
}
}
local.Promise = Promise$1;
}
// Strange compat..
Promise$1.polyfill = polyfill;
Promise$1.Promise = Promise$1;
return Promise$1;
})));
/* jshint ignore:end */ |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.