code stringlengths 2 1.05M |
|---|
import scilab from "highlight.js/lib/languages/scilab";
export default scilab;
|
import RSBaseError from '../base';
export default class MissingApiKeyError extends RSBaseError {
getDescription() {
return 'Returned if the api key is missing in the request.';
}
_getCode() {
return 'missing_api_key';
}
_getStatusCode() {
return RSBaseError.FORBIDDEN;
}
_getMessage() {
return 'Api key is missing.';
}
}
|
import { moduleForComponent, test } from 'ember-qunit';
import hbs from 'htmlbars-inline-precompile';
moduleForComponent('nypr-input', 'Integration | Component | nypr input', {
integration: true
});
test('it renders', function(assert) {
this.render(hbs`{{nypr-input}}`);
assert.equal(this.$('.nypr-input').length, 1);
});
test('it displays a label', function(assert) {
let testLabel = '123';
this.set('label', testLabel);
this.render(hbs`{{nypr-input label=label}}`);
assert.equal(this.$('.nypr-input-label').text().trim(), testLabel);
});
test('it shows error text at the right times', function(assert) {
let testErrors = ['bad input'];
this.set('errors', testErrors);
this.render(hbs`{{nypr-input errors=errors}}`);
assert.equal(this.$('.nypr-input-error').length, 0, "it should not show error before touched");
this.$('.nypr-input').trigger('focusin');
assert.equal(this.$('.nypr-input-error').length, 0, "it should not show error on focus");
this.$('.nypr-input').trigger('focusout');
assert.equal(this.$('.nypr-input-error').length, 1, "it should show error after touched (focusout)");
assert.equal(this.$('.nypr-input-error').text().trim(), testErrors[0], "it should show the correct error message");
assert.ok(this.$('> div').hasClass('has-error'), "it should set the error class");
});
test('it shows error when you try to sumbit', function(assert) {
let testErrors = ['bad input'];
this.set('errors', testErrors);
this.set('submitted', undefined);
this.render(hbs`{{nypr-input errors=errors submitted=submitted}}`);
assert.equal(this.$('.nypr-input-error').length, 0, "it should not show error before submitted is set");
this.set('submitted', true);
assert.equal(this.$('.nypr-input-error').length, 1, "it should show error after submitted is set");
assert.equal(this.$('.nypr-input-error').text().trim(), testErrors[0], "it should show the correct error message");
});
test('it shows advice text at the right times', function(assert) {
let testClue = 'format: ###';
this.set('clue', testClue);
this.set('errors', undefined);
this.render(hbs`{{nypr-input clue=clue errors=errors}}`);
assert.equal(this.$('.nypr-input-advice').length, 0, "it should not show advice before focus");
this.$('.nypr-input').trigger('focusin');
assert.equal(this.$('.nypr-input-advice').length, 1, "it should show advice on focus");
assert.equal(this.$('.nypr-input-advice').text().trim(), testClue, "it should show the correct advice");
this.$('.nypr-input').trigger('focusout');
assert.equal(this.$('.nypr-input-advice').length, 1, "it should keep showing advice after touched (focusout)");
this.set('errors', ['bad input']);
assert.equal(this.$('.nypr-input-advice').length, 0, "it should not show advice when it shows an error");
});
test('it calls the onChange event', function(assert) {
let onChangeCalls = [];
this.set('changeAction', (e) => {
onChangeCalls.push(e);
});
this.render(hbs`{{nypr-input onChange=(action changeAction)}}`);
this.$('.nypr-input').val('abc');
this.$('.nypr-input').change();
assert.equal(onChangeCalls.length, 1);
});
test('it calls the onInput event', function(assert) {
let onInputCalls = [];
this.set('inputAction', (e) => {
onInputCalls.push(e);
});
this.render(hbs`{{nypr-input onInput=(action inputAction)}}`);
this.$('.nypr-input').val('a');
this.$('.nypr-input').trigger('input');
this.$('.nypr-input').val('ab');
this.$('.nypr-input').trigger('input');
this.$('.nypr-input').val('abc');
this.$('.nypr-input').trigger('input');
assert.equal(onInputCalls.length, 3);
});
|
module.exports = (function() {
"use strict";
/*
* Generated by PEG.js 0.9.0.
*
* http://pegjs.org/
*/
function peg$subclass(child, parent) {
function ctor() { this.constructor = child; }
ctor.prototype = parent.prototype;
child.prototype = new ctor();
}
function peg$SyntaxError(message, expected, found, location) {
this.message = message;
this.expected = expected;
this.found = found;
this.location = location;
this.name = "SyntaxError";
if (typeof Error.captureStackTrace === "function") {
Error.captureStackTrace(this, peg$SyntaxError);
}
}
peg$subclass(peg$SyntaxError, Error);
function peg$parse(input) {
var options = arguments.length > 1 ? arguments[1] : {},
parser = this,
peg$FAILED = {},
peg$startRuleFunctions = { pieces: peg$parsepieces },
peg$startRuleFunction = peg$parsepieces,
peg$c0 = "$",
peg$c1 = { type: "literal", value: "$", description: "\"$\"" },
peg$c2 = /^[a-zA-Z0-9]/,
peg$c3 = { type: "class", value: "[a-zA-Z0-9]", description: "[a-zA-Z0-9]" },
peg$c4 = ":",
peg$c5 = { type: "literal", value: ":", description: "\":\"" },
peg$c6 = function(d) { return { type: 'directive', value: d.join('') }; },
peg$c7 = /^[^{}]/,
peg$c8 = { type: "class", value: "[^{}]", description: "[^{}]" },
peg$c9 = function(c) { return { type: 'content', value: c.join('') }; },
peg$c10 = function(v) { return { type: 'placeholder', value: v }; },
peg$c11 = function(c) { return c.join(''); },
peg$c12 = { type: "other", description: "valid character" },
peg$c13 = /^[a-zA-Z0-9_.]/,
peg$c14 = { type: "class", value: "[a-zA-Z0-9_.]", description: "[a-zA-Z0-9_.]" },
peg$c15 = { type: "other", description: "placeholder start" },
peg$c16 = "{{",
peg$c17 = { type: "literal", value: "{{", description: "\"{{\"" },
peg$c18 = { type: "other", description: "placeholder end" },
peg$c19 = "}}",
peg$c20 = { type: "literal", value: "}}", description: "\"}}\"" },
peg$c21 = { type: "other", description: "whitespace" },
peg$c22 = /^[ \t\r\n]/,
peg$c23 = { type: "class", value: "[ \\t\\r\\n]", description: "[ \\t\\r\\n]" },
peg$currPos = 0,
peg$savedPos = 0,
peg$posDetailsCache = [{ line: 1, column: 1, seenCR: false }],
peg$maxFailPos = 0,
peg$maxFailExpected = [],
peg$silentFails = 0,
peg$result;
if ("startRule" in options) {
if (!(options.startRule in peg$startRuleFunctions)) {
throw new Error("Can't start parsing from rule \"" + options.startRule + "\".");
}
peg$startRuleFunction = peg$startRuleFunctions[options.startRule];
}
function text() {
return input.substring(peg$savedPos, peg$currPos);
}
function location() {
return peg$computeLocation(peg$savedPos, peg$currPos);
}
function expected(description) {
throw peg$buildException(
null,
[{ type: "other", description: description }],
input.substring(peg$savedPos, peg$currPos),
peg$computeLocation(peg$savedPos, peg$currPos)
);
}
function error(message) {
throw peg$buildException(
message,
null,
input.substring(peg$savedPos, peg$currPos),
peg$computeLocation(peg$savedPos, peg$currPos)
);
}
function peg$computePosDetails(pos) {
var details = peg$posDetailsCache[pos],
p, ch;
if (details) {
return details;
} else {
p = pos - 1;
while (!peg$posDetailsCache[p]) {
p--;
}
details = peg$posDetailsCache[p];
details = {
line: details.line,
column: details.column,
seenCR: details.seenCR
};
while (p < pos) {
ch = input.charAt(p);
if (ch === "\n") {
if (!details.seenCR) { details.line++; }
details.column = 1;
details.seenCR = false;
} else if (ch === "\r" || ch === "\u2028" || ch === "\u2029") {
details.line++;
details.column = 1;
details.seenCR = true;
} else {
details.column++;
details.seenCR = false;
}
p++;
}
peg$posDetailsCache[pos] = details;
return details;
}
}
function peg$computeLocation(startPos, endPos) {
var startPosDetails = peg$computePosDetails(startPos),
endPosDetails = peg$computePosDetails(endPos);
return {
start: {
offset: startPos,
line: startPosDetails.line,
column: startPosDetails.column
},
end: {
offset: endPos,
line: endPosDetails.line,
column: endPosDetails.column
}
};
}
function peg$fail(expected) {
if (peg$currPos < peg$maxFailPos) { return; }
if (peg$currPos > peg$maxFailPos) {
peg$maxFailPos = peg$currPos;
peg$maxFailExpected = [];
}
peg$maxFailExpected.push(expected);
}
function peg$buildException(message, expected, found, location) {
function cleanupExpected(expected) {
var i = 1;
expected.sort(function(a, b) {
if (a.description < b.description) {
return -1;
} else if (a.description > b.description) {
return 1;
} else {
return 0;
}
});
while (i < expected.length) {
if (expected[i - 1] === expected[i]) {
expected.splice(i, 1);
} else {
i++;
}
}
}
function buildMessage(expected, found) {
function stringEscape(s) {
function hex(ch) { return ch.charCodeAt(0).toString(16).toUpperCase(); }
return s
.replace(/\\/g, '\\\\')
.replace(/"/g, '\\"')
.replace(/\x08/g, '\\b')
.replace(/\t/g, '\\t')
.replace(/\n/g, '\\n')
.replace(/\f/g, '\\f')
.replace(/\r/g, '\\r')
.replace(/[\x00-\x07\x0B\x0E\x0F]/g, function(ch) { return '\\x0' + hex(ch); })
.replace(/[\x10-\x1F\x80-\xFF]/g, function(ch) { return '\\x' + hex(ch); })
.replace(/[\u0100-\u0FFF]/g, function(ch) { return '\\u0' + hex(ch); })
.replace(/[\u1000-\uFFFF]/g, function(ch) { return '\\u' + hex(ch); });
}
var expectedDescs = new Array(expected.length),
expectedDesc, foundDesc, i;
for (i = 0; i < expected.length; i++) {
expectedDescs[i] = expected[i].description;
}
expectedDesc = expected.length > 1
? expectedDescs.slice(0, -1).join(", ")
+ " or "
+ expectedDescs[expected.length - 1]
: expectedDescs[0];
foundDesc = found ? "\"" + stringEscape(found) + "\"" : "end of input";
return "Expected " + expectedDesc + " but " + foundDesc + " found.";
}
if (expected !== null) {
cleanupExpected(expected);
}
return new peg$SyntaxError(
message !== null ? message : buildMessage(expected, found),
expected,
found,
location
);
}
function peg$parsepieces() {
var s0, s1, s2, s3, s4, s5;
s0 = peg$currPos;
s1 = peg$parsedirective();
if (s1 === peg$FAILED) {
s1 = null;
}
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$currPos;
s4 = peg$parsecontent();
if (s4 === peg$FAILED) {
s4 = null;
}
if (s4 !== peg$FAILED) {
s5 = peg$parseplaceholder();
if (s5 !== peg$FAILED) {
s4 = [s4, s5];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$currPos;
s4 = peg$parsecontent();
if (s4 === peg$FAILED) {
s4 = null;
}
if (s4 !== peg$FAILED) {
s5 = peg$parseplaceholder();
if (s5 !== peg$FAILED) {
s4 = [s4, s5];
s3 = s4;
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
} else {
peg$currPos = s3;
s3 = peg$FAILED;
}
}
if (s2 !== peg$FAILED) {
s3 = peg$parsecontent();
if (s3 === peg$FAILED) {
s3 = null;
}
if (s3 !== peg$FAILED) {
s1 = [s1, s2, s3];
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
return s0;
}
function peg$parsedirective() {
var s0, s1, s2, s3;
s0 = peg$currPos;
if (input.charCodeAt(peg$currPos) === 36) {
s1 = peg$c0;
peg$currPos++;
} else {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c1); }
}
if (s1 !== peg$FAILED) {
s2 = [];
if (peg$c2.test(input.charAt(peg$currPos))) {
s3 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c3); }
}
while (s3 !== peg$FAILED) {
s2.push(s3);
if (peg$c2.test(input.charAt(peg$currPos))) {
s3 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c3); }
}
}
if (s2 !== peg$FAILED) {
if (input.charCodeAt(peg$currPos) === 58) {
s3 = peg$c4;
peg$currPos++;
} else {
s3 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c5); }
}
if (s3 !== peg$FAILED) {
peg$savedPos = s0;
s1 = peg$c6(s2);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
return s0;
}
function peg$parsecontent() {
var s0, s1, s2;
s0 = peg$currPos;
s1 = [];
if (peg$c7.test(input.charAt(peg$currPos))) {
s2 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c8); }
}
while (s2 !== peg$FAILED) {
s1.push(s2);
if (peg$c7.test(input.charAt(peg$currPos))) {
s2 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s2 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c8); }
}
}
if (s1 !== peg$FAILED) {
peg$savedPos = s0;
s1 = peg$c9(s1);
}
s0 = s1;
return s0;
}
function peg$parseplaceholder() {
var s0, s1, s2, s3, s4, s5;
s0 = peg$currPos;
s1 = peg$parsephs();
if (s1 !== peg$FAILED) {
s2 = [];
s3 = peg$parsews();
while (s3 !== peg$FAILED) {
s2.push(s3);
s3 = peg$parsews();
}
if (s2 !== peg$FAILED) {
s3 = peg$parsevariable();
if (s3 !== peg$FAILED) {
s4 = [];
s5 = peg$parsews();
while (s5 !== peg$FAILED) {
s4.push(s5);
s5 = peg$parsews();
}
if (s4 !== peg$FAILED) {
s5 = peg$parsephe();
if (s5 !== peg$FAILED) {
peg$savedPos = s0;
s1 = peg$c10(s3);
s0 = s1;
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
} else {
peg$currPos = s0;
s0 = peg$FAILED;
}
return s0;
}
function peg$parsevariable() {
var s0, s1, s2;
s0 = peg$currPos;
s1 = [];
s2 = peg$parsevc();
if (s2 !== peg$FAILED) {
while (s2 !== peg$FAILED) {
s1.push(s2);
s2 = peg$parsevc();
}
} else {
s1 = peg$FAILED;
}
if (s1 !== peg$FAILED) {
peg$savedPos = s0;
s1 = peg$c11(s1);
}
s0 = s1;
return s0;
}
function peg$parsevc() {
var s0, s1;
peg$silentFails++;
if (peg$c13.test(input.charAt(peg$currPos))) {
s0 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c14); }
}
peg$silentFails--;
if (s0 === peg$FAILED) {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c12); }
}
return s0;
}
function peg$parsephs() {
var s0, s1;
peg$silentFails++;
if (input.substr(peg$currPos, 2) === peg$c16) {
s0 = peg$c16;
peg$currPos += 2;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c17); }
}
peg$silentFails--;
if (s0 === peg$FAILED) {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c15); }
}
return s0;
}
function peg$parsephe() {
var s0, s1;
peg$silentFails++;
if (input.substr(peg$currPos, 2) === peg$c19) {
s0 = peg$c19;
peg$currPos += 2;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c20); }
}
peg$silentFails--;
if (s0 === peg$FAILED) {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c18); }
}
return s0;
}
function peg$parsews() {
var s0, s1;
peg$silentFails++;
if (peg$c22.test(input.charAt(peg$currPos))) {
s0 = input.charAt(peg$currPos);
peg$currPos++;
} else {
s0 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c23); }
}
peg$silentFails--;
if (s0 === peg$FAILED) {
s1 = peg$FAILED;
if (peg$silentFails === 0) { peg$fail(peg$c21); }
}
return s0;
}
peg$result = peg$startRuleFunction();
if (peg$result !== peg$FAILED && peg$currPos === input.length) {
return peg$result;
} else {
if (peg$result !== peg$FAILED && peg$currPos < input.length) {
peg$fail({ type: "end", description: "end of input" });
}
throw peg$buildException(
null,
peg$maxFailExpected,
peg$maxFailPos < input.length ? input.charAt(peg$maxFailPos) : null,
peg$maxFailPos < input.length
? peg$computeLocation(peg$maxFailPos, peg$maxFailPos + 1)
: peg$computeLocation(peg$maxFailPos, peg$maxFailPos)
);
}
}
return {
SyntaxError: peg$SyntaxError,
parse: peg$parse
};
})();
|
import { createStore, applyMiddleware } from 'redux';
import thunkMiddleware from 'redux-thunk';
import createLogger from 'redux-logger';
import connectorMiddleware from './middleware/connector';
import reducer from '../reducer';
let logger = createLogger();
if (__SERVER__) logger = () => next => action => next(action);
export default function configureStore(initialState, connector) {
const middlewares = applyMiddleware(
connectorMiddleware(connector),
thunkMiddleware,
logger
);
let createStoreWithMiddleware = middlewares(createStore);
return createStoreWithMiddleware(reducer, initialState);
}
|
var presentations = {
"2009-minsk_1-recode-in-time": {
"title": "Переверстать всё и в срок.",
"speakers": ["andrew-sumin"]
},
"2009-minsk_2-error": {
"title": "Ошибка. Осознание, примирение, извлечение пользы.",
"speakers": ["vadim-makishvili"]
},
"2009-minsk_3-web-fonts": {
"title": "Веб-шрифты vs. Шрифты для веба.",
"speakers": ["vadim-makeev"]
},
"2009-minsk_4-html5": {
"title": "HTML5. Будем знакомы!",
"speakers": ["pavel-lovtsevich"]
},
"2009-minsk_5-webhitech": {
"title": "WebHiTech. Итоги 2009 и планы 2010.",
"speakers": ["artemy-lomov"]
},
"2009-minsk_6-vml-svg-canvas": {
"title": "VML, SVG, Canvas: что дальше?",
"speakers": ["nikolay-matsievsky"]
},
"2009-minsk_7-troubles": {
"title": "Некоторые проблемы применения современных веб-технологий.",
"speakers": ["konstantin-efimov"]
},
"2009-msk_1-recode-in-time": {
"title": "Переверстать всё и в срок",
"speakers": ["andrew-sumin"]
},
"2009-msk_2-separation": {
"title": "Разделение труда при верстке",
"speakers": ["andrew-shitov"]
},
"2009-msk_3-error": {
"title": "Ошибка. Осознание, примирение, извлечение пользы",
"speakers": ["andrew-shitov"]
},
"2009-msk_4-vml-svg-canvas": {
"title": "VML, SVG, Canvas: что дальше?",
"speakers": ["nikolay-matsievsky"]
},
"2009-msk_5-web-fonts": {
"title": "Веб-шрифты vs. Шрифты для веба",
"speakers": ["vadim-makeev"]
},
"2009-msk_6-expressions": {
"title": "Систематизация экспрешнов в IE",
"speakers": ["roman-komarov"]
},
"2009-msk_7-optimization": {
"title": "Всё в одну строку. Об оптимизации кода веб-страниц",
"speakers": ["dmitriy-shilnikov"]
},
"2010-riga_1-latvian-webdev": {
"title": "Веб-вёрстка в Латвии: Вчера. Сегодня! Завтра?",
"speakers": ["nikita-seletsky"]
},
"2010-riga_2-mobile-sites": {
"title": "Особенности создания веб–сайтов для мобильных устройств",
"speakers": ["dmitry-dulepov"]
},
"2010-riga_3-evolution": {
"title": "HTML5 и CSS3. Эволюция веб-стандартов",
"speakers": ["anton-nemcev"]
},
"2010-riga_4-css-management": {
"title": "CSS-менеджмент. Три года спустя",
"speakers": ["vadim-makeev"]
},
"2010-riga_5-webdev-tools": {
"title": "Средства для разработчиков — какое вкуснее?",
"speakers": ["mikhail-baranov"]
},
"2010-riga_6-lean-startup": {
"title": "Lean Startup. От идеи до миллиона",
"speakers": ["maksim-bereza"]
},
"2010-spb_1-realtime": {
"title": "Доставка данных в реальном времени. Node.JS + WebSocket (Flash Socket) + Redis + Pub/Sub",
"speakers": ["aleksandr-beshkenadze"],
"videoId": "17255887"
},
"2010-spb_2-layout-future": {
"title": "CSS3: будущее механизмов раскладки. Обзор и анализ черновиков Grid, Flexbox и Template Layout",
"speakers": ["viacheslav-oliyanchuk"],
"videoId": "17494685"
},
"2010-spb_3-best-practices": {
"title": "Правила хорошего тона в вебе. Выбираем: стандарты разметки, уровень поддержки CSS, форматы графики, JS-библиотеку и средства анимации",
"speakers": ["nikolay-matsievsky"],
"videoId": "17496409"
},
"2010-spb_4-web-standards": {
"title": "Презентация проекта «Веб-стандарты»",
"speakers": ["vadim-makeev"],
"videoId": "17256050"
},
"2010-spb_5-caesarius": {
"title": "Слесарю слесарево. Новый подход к обратной совместимости вёрстки",
"speakers": ["vadim-makeev"],
"videoId": "17495746"
},
"2010-spb_6-web-inspectors": {
"title": "Обзор отладчиков для веб-разработки. Сравнение Firebug, IE Developer Toolbar, Opera Dragonfly и WebKit Web Inspector",
"speakers": ["mikhail-baranov"],
"videoId": "17255088"
},
"2010-kiev_1-web-standards": {
"title": "Веб-стандарты в большом проекте: что помогает, а что мешает",
"speakers": ["andrew-sumin"],
"videoId": "17254129"
},
"2010-kiev_2-fireworks": {
"title": "Про проектирование интерфейсов и немного про Adobe Fireworks",
"speakers": ["vadim-pacev"],
"videoId": "17248656"
},
"2010-kiev_3-web-in-curves": {
"title": "Веб в кривых. Второе рождение SVG",
"speakers": ["vadim-makeev"],
"videoId": "17252610"
},
"2010-kiev_4-performance": {
"title": "Введение в Web Performance: W3C, Webkit, IE9 и будущее",
"speakers": ["nikolay-matsievsky"],
"videoId": "17253770"
},
"2010-kiev_5-web-apps": {
"title": "Разработка веб-приложений. Обзорная экскурсия по актуальным решениям, библиотекам и техникам разработки на HTML и JavaScript",
"speakers": ["vitaly-rybalka"],
"videoId": "17249995"
},
"2010-kiev_6-js-api": {
"title": "Обзор новых API JavaScript. HTML5 и самостоятельные черновики W3C",
"speakers": ["anton-nemcev"],
"videoId": "17246164"
},
"2010-msk_1-drupal": {
"title": "Практика использования Drupal в компании RU-CENTER",
"speakers": ["daniil-malykh"],
"videoId": "19088402"
},
"2010-msk_2-usability": {
"title": "Типичные ошибки веб-разработчиков с точки зрения юзабилити",
"speakers": ["alexey-kopylov"],
"videoId": "19187344"
},
"2010-msk_3-python-server": {
"title": "Сервер-агрегатор на Python. Xscript/FEST",
"speakers": ["andrew-sumin"],
"videoId": "19078159"
},
"2010-msk_4-success": {
"title": "Веб-стандарты как критерий личной успешности",
"speakers": ["nikolay-matsievsky"],
"videoId": "19080563"
},
"2010-msk_5-goodbye-css3": {
"title": "Мечты и реальность. Прощай CSS3, здравствуй, IE6",
"speakers": ["olga-aleksashenko"],
"videoId": "19076020"
},
"2010-msk_6-bem": {
"title": "БЭМ! Принципы вёрстки проектов Яндекса",
"speakers": ["vadim-pacev"],
"videoId": "19071073"
},
"2010-msk_7-bem": {
"title": "Доктайп. Точка",
"speakers": ["vadim-makeev"],
"videoId": "19072506"
},
"2011-kiev_1-procrustes": {
"title": "Прокрустовы окна. Как вписаться в устройства с минимальными потерями",
"speakers": ["vadim-makeev"]
},
"2011-kiev_2-sass": {
"title": "Sass и Compass.",
"speakers": ["sergey-dyniovsky"],
"videoId": "33377362"
},
"2011-kiev_3-video-flash": {
"title": "Когда <video> убьёт Flash?",
"speakers": ["nikolay-matsievsky"],
"videoId": "33392045"
},
"2011-kiev_4-editable-html": {
"title": "Редактирование HTML в браузере. Как должно быть, как есть, и зачем это вообще нужно",
"speakers": ["anton-nemcev"]
},
"2011-kiev_5-check-list": {
"title": "Чек-лист вёрстки. Что можно отдавать клиенту, а что надо переделывать",
"speakers": ["igor-zenich"]
},
"2011-kiev_6-media-queries": {
"title": "CSS3 Media Queries: легкость превращений.",
"speakers": ["artemy-lomov"]
},
"2011-kiev_7-real-js": {
"title": "Настоящий JavaScript.",
"speakers": ["anton-kotenko"],
"videoId": "33393795"
},
"2011-minsk_1-edge": {
"title": "Adobe Edge. Веб-анимация по стандартам.",
"speakers": ["andrey-golovnev"],
"videoId": "33148794"
},
"2011-minsk_2-check-list": {
"title": "Чек-лист вёрстки. Что можно отдавать клиенту, а что надо переделывать.",
"speakers": ["igor-zenich"],
"videoId": "33216368"
},
"2011-minsk_3-conditional-css": {
"title": "Мухи отдельно, котлеты отдельно: Conditional Comments, Conditional CSS, Modernizr, CSS Conditional Rules.",
"speakers": ["pavel-lovtsevich"],
"videoId": "33160837"
},
"2011-minsk_4-media-queries": {
"title": "CSS3 Media Queries: легкость превращений.",
"speakers": ["artemy-lomov"],
"videoId": "33149535"
},
"2011-minsk_5-procrustes": {
"title": "Прокрустовы окна. Как вписаться в устройство с минимальными потерями.",
"speakers": ["vadim-makeev"],
"videoId": "33180097"
},
"2011-minsk_6-editable-html": {
"title": "Редактирование HTML в браузере. Как должно быть, как есть, и зачем это вообще нужно.",
"speakers": ["anton-nemcev"],
"videoId": "33214437"
},
"2011-minsk_7-bem": {
"title": "БЭМ. Реальный опыт двух компаний Mail.ru и hh.ru.",
"speakers": ["andrew-sumin"],
"videoId": "33153484"
},
"2011-minsk_8-console": {
"title": "Быстрая разработка. Краткий обзор средств для работы с кодом из консоли.",
"speakers": ["maxim-chervonny"],
"videoId": "33151436"
},
"2011-minsk_9-cloud": {
"title": "Презентация услуги CloudServer — облачного хостинга Active Technologies.",
"speakers": ["andrey-kupchenko"]
},
"2011-msk_1-console": {
"title": "Быстрая разработка. Краткий обзор средств для работы с кодом из консоли.",
"speakers": ["maxim-chervonny"]
},
"2011-msk_2-css-experiments": {
"title": "Обустраиваем лабораторию для бесчеловечных экспериментов над CSS.",
"speakers": ["roman-komarov"],
"videoId": "34190518"
},
"2011-msk_3-media-queries": {
"title": "CSS3 Media Queries: легкость превращений.",
"speakers": ["artemy-lomov"]
},
"2011-msk_4-vimi": {
"title": "Всё, что вы делаете в Vim неправильно.",
"speakers": ["viacheslav-oliyanchuk"],
"videoId": "34201803"
},
"2011-msk_5-pre-fixes": {
"title": "-Пре-фиксы: зачем и как правильно.",
"speakers": ["vadim-makeev"],
"videoId": "34197672"
},
"2011-msk_6-editable-html": {
"title": "Редактирование HTML в браузере. Как должно быть, как есть, и зачем это вообще нужно.",
"speakers": ["anton-nemcev"]
},
"2011-msk_7-csscomb": {
"title": "Причеши свой код. Правила хорошего тона в CSS.",
"speakers": ["viacheslav-oliyanchuk"],
"videoId": "34212051"
},
"2012-ekb_1-text-editor": {
"title": "Как сделать текстовый онлайн-редактор и испортить себе жизнь.",
"speakers": ["vasily-aksyonov"],
"description": "Проблемы создания редактора в вебе при текущем уровне поддержки Editing APIs браузерами.",
"videoId": "47626426"
},
"2012-ekb_2-css-selectors": {
"title": "Быстрый удар точно в цель.",
"speakers": ["artemy-lomov"],
"description": "Селекторы CSS в разрезе производительности, каскадности, независимости и избранных нововведений CSS3"
},
"2012-ekb_3-dart": {
"title": "Dart — светлая сторона силы?",
"speakers": ["mikhail-davydov"],
"description": "Язык Dart, его особенности. Для чего он создавался и какое у него будущее. Полезный опыт, который мы можем почерпнуть из Dart."
},
"2012-ekb_4-pre-fixes": {
"title": "Пре-фиксы. Зачем и как правильно.",
"speakers": ["vadim-makeev"],
"description": "Злободневный доклад о технологии префиксов в CSS, закрывающий вопрос об их необходимости, правилах применения и будущем технологии."
},
"2012-ekb_5-css3": {
"title": "Как должно быть и как на самом деле?",
"speakers": ["oleg-mokhov"],
"description": "Как в браузерах работают новые CSS3-свойства, почему получается по-разному и как с этим жить уже сейчас."
},
"2012-spb_1-jedi": {
"title": "Джедаями не рождаются",
"speakers": ["mikhail-baranov"],
"description": "Заметки о том, как нужно и как не нужно учить клиентским технологиям. Будет полезен руководителям, разработчикам и всем, кто хочет ими стать."
},
"2012-spb_2-css-selectors": {
"title": "Селекторы CSS в разрезе производительности",
"speakers": ["artemy-lomov"],
"description": "Принципы обработки стилей браузером, история и особенности работы селекторов, тестирование производительности."
},
"2012-spb_3-push-it": {
"title": "Жми сюда!",
"speakers": ["vadim-makeev"],
"description": "Кнопка, ссылка, псевдоссылка? Как правильно выбрать, сверстать и не наделать глупостей."
},
"2012-spb_4-schema.org": {
"title": "Schema.org. Современный семантический веб",
"speakers": ["sergey-mezentsev"],
"description": "Использование HTML5 microdata и Schema.org на сайте."
},
"2012-spb_5-js-performance": {
"title": "Трудности производительности",
"speakers": ["dmitry-makhnev"],
"description": "О важности производительности JavaScript каждого кирпичика вашего приложения."
},
"2012-spb_6-3d-css": {
"title": "На грани возможного",
"speakers": ["anton-nemcev"],
"description": "3D и 2D-анимация и эмоции в веб c помощью CSS."
},
"2012-spb_7-save-the-world": {
"title": "Спасаем мир вместе",
"speakers": ["roman-komarov"],
"description": "Несколько простых способов внести свой вклад в развитие фронтенда. Опенсорс, Гитхаб и всё такое."
},
"2012-kiev_1-speed-coding": {
"title": "Скоростная верстка в 8 рук или как не стать осьминогом",
"speakers": ["murad-rogozhnikov"],
"description": "Наш опыт устранения грабель коллективной вёрстки, или как банальные и неочевидные технологии и инструменты помогают достичь синергии в командной работе."
},
"2012-kiev_2-mcss": {
"title": "Многослойный CSS",
"speakers": ["robert-haritonov"],
"description": "Три слоя организации CSS для удобной командной работы над стилями. Рассказ об авторской методике и её сравнение с существующими: от OOCSS и SMACSS до БЭМа."
},
"2012-kiev_3-meteor": {
"title": "С реактивными костылями в будущее. Meteor JS",
"speakers": ["eugeny-chechurin"],
"description": "Эпоха динамических сайтов с новым динамическим фреймворком."
},
"2012-kiev_4-pushit": {
"title": "Жми сюда!",
"speakers": ["vadim-makeev"],
"description": "Кнопка, ссылка, псевдоссылка? Как правильно выбрать, сверстать и не наделать глупостей."
},
"2012-kiev_5-3d-css": {
"title": "На грани возможного",
"speakers": ["anton-nemcev"],
"description": "3D и 2D-анимация и эмоции в веб c помощью CSS."
},
"2012-kiev_6-html5-win8": {
"title": "HTML5-приложения для Windows 8",
"speakers": ["yury-artykh"],
"description": "Создание платных приложений для планшетов на Windows 8 с помощью HTML, CSS и JavaScript."
},
"2012-minsk_1-die-photoshop-die": {
"title": "Die Photoshop, die! Или стоит ли пропускать Photoshop в процессе разработки веб-дизайна?",
"speakers": ["ilya-pukhalski"],
"description": "Современные технологии позволяют разработчикам создавать удивительные отзывчивые сайты, браузерные и даже мобильные приложения. Как же запечатлеть всю эту динамику на статичном холсте? И стоит ли? Почему дизайнеру важно знать хотя бы немного о верстке, а верстальщику иметь представление о процессе дизайна? Ответы на все вопросы в рассказ об актуальном подходе «Без фотошопа»."
},
"2012-minsk_2-clear-and-sharp": {
"title": "Чётко и резко. Новая графика для экранов с высоким разрешением",
"speakers": ["vadim-makeev"],
"description": "Вряд ли кто обрадуется, если увидит вместо красивого и с пиксельной точностью отрисованного дизайна расплывшийся кусок мыла. Но именно так выглядят сегодня большинство сайтов на устройствах с экранами высокого разрешения. Меры, полумеры и просто трюки, чтобы ваш сайт выглядел безупречно — в этом докладе."
},
"2012-minsk_3-adaptive-design": {
"title": "Адаптивный веб-дизайн — Что? Где? Когда?",
"speakers": ["anna-selezneva"],
"description": "Рассказ о том, что такое адаптивный веб-дизайн, как и где его можно применять, что нужно учитывать при его создании и почему пора начать делать адаптивные сайты."
},
"2012-minsk_4-adaptive-images": {
"title": "Всем сестрам по серьгам. Адаптивные изображения",
"speakers": ["pavel-lovtsevich"]
},
"2012-minsk_5-mcss": {
"title": "Многослойный CSS",
"speakers": ["robert-haritonov"],
"description": "Три слоя организации CSS для удобной командной работы над стилями. Рассказ об авторской методике и её сравнение с существующими: от OOCSS и SMACSS до БЭМа."
},
"2012-minsk_6-jquery-extend": {
"title": "Способы расширения функционала jQuery",
"speakers": ["dmitry-petrov"],
"description": "Как и зачем писать расширения для jQuery, с примерами на CoffeeScript."
},
"2012-minsk_7-web-apps": {
"title": "Современные веб-приложения",
"speakers": ["ivan-chashkin"],
"description": "Применение принципа «graceful degradation» на примере тач-почты Mail.Ru."
},
"2012-minsk_8-webstorage": {
"title": "WebStorage и его применение для связи окон",
"speakers": ["roman-mitasov"],
"description": "Веб-клиент для Mail.ru Agent. Особенности разработки месенджера для веба. Плюсы, минусы и подводные камни клиентского хранения данных. Синхронизация интерфейса, межоконный роутер, одно соединения на все окна пользователя."
},
"2012-msk_1-current-css-w3c": {
"title": "Current work on CSS at W3C",
"description": "The W3C working group on CSS is working on many different specifications (called \"modules\") for new features in CSS. Some modules are finished, some are well advanced, some contain only very early ideas. This talk explains the relation between the modules and how they progress.",
"speakers": ["bert-bos"]
},
"2012-msk_2-semantic-i18n-w3c": {
"title": "New developments in Semantic Web and Internationalization at the W3C",
"description": "This talk introduces new developments in the areas of Semantic Web and Internationalization at W3C. Both seam to be unrelated; a closer look reveals that more and more multilingual resources are developed using Semantic Web technologies, and that the technicla building blocks of the multilingual web are relevant for these resources as well. The talk will explain these building blocks and their application in current and upcoming Semantic Web and general Web technologies.",
"speakers": ["felix-sasaki"]
},
"2012-msk_3-yandex-and-w3c": {
"title": "Yandex and W3C",
"description": "Yandex joined W3C a few weeks ago. Why? Do we think we can have an impact? What do we care about? How does W3C really work, and what will Yandex do there? Yandex’ representative to W3C, Chaals gives answers, and answers questions…",
"speakers": ["charles-mccathienevile"]
},
"2012-msk_4-svgo": {
"title": "SVGO: оптимизатор SVG",
"description": "Авторский рассказ об утилите для оптимизации SVG-файлов: причины возникновения, принцип работы и планы на будущее.",
"speakers": ["kir-belevich"]
},
"2012-msk_5-clear-and-sharp": {
"title": "Чётко и резко. Новая графика для экранов с высоким разрешением",
"description": "Вряд ли кто обрадуется, если увидит вместо красивого и с пиксельной точностью отрисованного дизайна расплывшийся кусок мыла. Но именно так выглядят сегодня большинство сайтов на устройствах с «ретиной» или просто экранах высокого разрешения. Меры, полумеры и просто трюки, чтобы ваш сайт выглядел безупречно — в этом докладе.",
"speakers": ["vadim-makeev"]
},
"2012-msk_6-javascript-patterns": {
"title": "Паттерны JavaScript",
"description": "Что это такое, почему это стоит использовать, основные паттерны и примеры их использования с обоснованием актуальности.",
"speakers": ["anton-nemcev"]
},
"2012-msk_7-grunt-frontend": {
"title": "Grunt: система сборки для фронтенд-разработчиков",
"description": "Современные сайты состоят из тысяч строк JavaScript и CSS, разбросанных по десяткам файлов. Если вывалить всё это пользователю в браузер, сайт будет загружаться дольше, чем мог бы. Справиться с этой, и многими другими задачами, помогают системы сборки. Grunt — одна из них, созданная специально для фронтенд-разработчиков.",
"speakers": ["artem-sapegin"]
},
"2012-msk_8-adaptive-web-design": {
"title": "Адаптивный веб-дизайн — Что? Где? Когда?",
"description": "Окружающий мир постоянно меняется, совершенствуются устройства, которые мы используем, и привычные, проверенные временем подходы разработки сайтов уже не гарантируют хороший результат. Пришло время выйти за рамки и начать делать удобные сайты.",
"speakers": ["anna-selezneva"]
},
"2012-msk_9-getting-touchy": {
"title": "Getting Touchy",
"description": "Beyond smartphones and tablets, touchscreens are finding their way into laptops and even desktop computers. With hardware support for touch becoming increasingly ubiquitous, it's time to explore what new possibilities are available to developers. This session will cover the basics of handling touch events - from making sure simple single-tap interactions are as responsive as possible, all the way to full multitouch, gesture-enabled, cross-browser interfaces.",
"speakers": ["patrick-lauke"]
},
"2012-msk_10-tech-vs-designer": {
"title": "Технолог — тоже дизайнер",
"description": "Технологу важно быть дизайнером. Без этого его интерфейсы будут если и неплохо выглядеть, то худо работать. Его кодом не воспользуются коллеги. А сам он утонет в рутине. Этот доклад не о техническом мастерстве, а о реализации хорошего дизайна даже там, куда не добрался дизайнер. Технические приёмы и личная эффективность технолога — необходимость для этого. Хотя, мотивация, настойчивость и изобретательность даже могут компенсировать недостаток умений.",
"speakers": ["artem-polikarpov"]
},
"2012-msk_11-round-table": {
"title": "Круглый стол с экспертами W3C, Яндекса и Opera Software",
"description": "Веб-стандарты, роль и ответственность W3C и мировых компаний за будущее интернета, возможность каждого принять участие в строительстве будущего. Вопросы и ответы вне рамок докладов.",
"speakers": [
"bert-bos",
"felix-sasaki",
"charles-mccathienevile",
"patrick-lauke"
]
}
}
|
/**
* @since 2017-05-11 14:20:23
* @author vivaxy
*/
import PropTypes from 'prop-types';
const createActionObject = function(obj, actionCreator) {
const result = {};
Object.keys(obj).forEach((key) => {
const value = obj[key];
if (typeof value === 'function') {
result[key] = actionCreator(value);
} else if (typeof value === 'object') {
result[key] = createActionObject(obj[key], actionCreator);
} else {
throw new Error('only Function and Object are accepted');
}
});
return result;
};
export default (Component) => {
const Provider = class Provider extends Component {
static childContextTypes = {
initialize: PropTypes.func,
store: PropTypes.object,
actions: PropTypes.object,
};
store = {};
actions = {};
state = {};
constructor(props, context) {
super(props, context);
this.actionCreator = this.actionCreator.bind(this);
this.initializeStoreAndActions = this.initializeStoreAndActions.bind(
this,
);
}
getChildContext() {
return {
initialize: this.initializeStoreAndActions,
store: this.store,
actions: this.actions,
};
}
initializeStoreAndActions(storeUpdater, actionsUpdater) {
Object.assign(
this.actions,
createActionObject(actionsUpdater(this.actions), this.actionCreator),
);
Object.assign(this.store, storeUpdater(this.store));
}
actionCreator(func) {
if (func._created) {
return func;
}
const action = (...args) => {
return func(...args)((newStore) => {
Object.assign(this.store, newStore);
this.setState({});
}, this.store);
};
action._created = true;
return action;
}
};
Provider.displayName = Component.name;
return Provider;
};
|
(function () {
'use strict';
angular.module('app.game', [])
.factory('cardService', function ($q, backendService) {
var cardService = {
cardsLoaded: false,
cards: [] // TODO: Maybe save the cards as an associative array for easier access.
};
cardService.getCards = function () {
if (cardService.cardsLoaded) {
return $q.when(cardService.cards);
}
var deferred = $q.defer();
backendService.methods.getCards()
.then(function (cards) {
cardService.cards = cards;
cardService.cardsLoaded = true;
deferred.resolve(cards);
}, function (msg) {
cardService.cards = [];
deferred.reject(msg);
});
return deferred.promise;
};
cardService.getCardById = function (cardId) {
var deferred = $q.defer();
cardService.getCards().then(function(cards) {
for (var i = 0; i < cards.length; i++) {
var card = cards[i];
if (card.id === Number(cardId)) {
deferred.resolve(cards[i]);
return;
}
}
deferred.reject('Card with id ' + cardId + ' not found');
}, function(msg) {
deferred.reject(msg);
});
return deferred.promise;
};
return cardService;
})
.filter('battleKing', function () {
return function (cards) {
var tempCards = [];
angular.forEach(cards, function (card) {
if (card.isBattleKing) {
tempCards.push(card);
}
});
return tempCards;
}
})
.filter('notBattleKing', function () {
return function (cards) {
var tempCards = [];
angular.forEach(cards, function (card) {
if (!card.isBattleKing) {
tempCards.push(card);
}
});
return tempCards;
}
})
.filter('faction', function () {
return function (cards, faction) {
var tempCards = [];
if (faction === undefined || faction === '') {
return tempCards;
}
angular.forEach(cards, function (card) {
if (card.faction === Number(faction)) {
tempCards.push(card);
}
});
return tempCards;
}
})
.filter('factions', function () {
return function (cards, factions) {
var tempCards = [];
if (factions === undefined || factions === []) {
return tempCards;
}
angular.forEach(factions, function (faction) {
angular.forEach(cards, function (card) {
if (card.faction === Number(faction)) {
tempCards.push(card);
}
});
});
return tempCards;
}
})
.factory('gwintFactionService', function () {
var gwintFactionService = {};
gwintFactionService.factions = [
{ id: 0, name: 'Neutral', perk: '', validDeckFaction: false },
{ id: 1, name: 'No Man\'s Land', perk: 'One randomly-chosen Monster Unit Card stays on the battlefield after each round.', validDeckFaction: true },
{ id: 2, name: 'Nilfgaard', perk: 'Win whenever there is a draw.', validDeckFaction: true },
{ id: 3, name: 'Northern Kingdom', perk: 'Draw a card from your deck whenever you win a round.', validDeckFaction: true },
{ id: 4, name: 'Scoia\'tael', perk: 'You devide who goes first at the start of battle.', validDeckFaction: true }
];
gwintFactionService.findFaction = function(factionId) {
if (factionId < gwintFactionService.factions.length) {
return gwintFactionService.factions[factionId];
} else {
return {
id: factionId,
name: 'Unknown',
perk: 'Unknown',
validDeckFaction: false
};
}
};
return gwintFactionService;
})
.filter('deckFaction', function () {
return function (factions) {
var tempFactions = [];
angular.forEach(factions, function (faction) {
if (faction.validDeckFaction) {
tempFactions.push(faction);
}
});
return tempFactions;
}
})
.factory('gwintTypeService', function () {
var gwintTypeService = {}
gwintTypeService.types = {
None: 0,
Melee: 1 << 0,
Ranged: 1 << 1,
RangedMelee: 1 << 0 | 1 << 1,
Siege: 1 << 2,
SiegeRangedMelee: 1 << 0 | 1 << 1 | 1 << 2,
Creature: 1 << 3,
Weather: 1 << 4,
Spell: 1 << 5,
RowModifier: 1 << 6,
Hero: 1 << 7,
Spy: 1 << 8,
FriendlyEffect: 1 << 9,
OffensiveEffect: 1 << 10,
GlobalEffect: 1 << 11
};
gwintTypeService.hasType = function (types, typeName) {
return (types & gwintTypeService.types[typeName]) > 0;
};
gwintTypeService.hasAnyType = function (type, typeNames) {
var typeMask = 0;
if (typeNames === undefined || typeNames === null || typeNames === []) {
return false;
}
angular.forEach(typeNames, function (typeName) {
typeMask = typeMask | gwintTypeService.types[typeName];
});
return (type & typeMask) > 0;
};
gwintTypeService.hasAllTypes = function (type, typeNames) {
var typeMask = 0;
if (typeNames === undefined || typeNames === null || typeNames === []) {
return false;
}
angular.forEach(typeNames, function (typeName) {
typeMask = typeMask | gwintTypeService.types[typeName];
});
return (type & typeMask) === typeMask;
};
return gwintTypeService;
})
.filter('gwintType', function (gwintTypeService) {
return function (cards, allowedTypes) {
var tempCards = [];
var allowedTypesMask = 0;
if (allowedTypes === undefined || allowedTypes === null || allowedTypes === []) {
return tempCards;
}
angular.forEach(allowedTypes, function (allowedType) {
allowedTypesMask = allowedTypesMask | gwintTypeService.types[allowedType];
});
angular.forEach(cards, function (card) {
if (card.type & allowedTypesMask) {
tempCards.push(card);
}
});
return tempCards;
}
})
.factory('gwintEffectService', function () {
var gwintEffectService = {
effects: {
None: 0,
Backstab: 1,
MoraleBoost: 2,
Ambush: 3,
ToughSkin: 4,
Bin2: 5,
Bin3: 6,
MeleeScorch: 7,
EleventhCard: 8,
ClearWeather: 9,
PickWeather: 10,
PickRain: 11,
PickFog: 12,
PickFrost: 13,
View3Enemy: 14,
Resurrect: 15,
ResurrectEnemy: 16,
Bin2Pick1: 17,
MeleeHorn: 18,
RangeHorn: 19,
SiegeHorn: 20,
SiegScorch: 21,
CounerKing: 22,
Melee: 23,
Ranged: 24,
Siege: 25,
UnsummonDummy: 26,
Horn: 27,
Draw: 28,
Scorch: 29,
ClearSky: 30,
SummonClones: 31,
ImproveNeighbours: 32,
Nurse: 33,
Draw2: 34,
SameTypeMorale: 35
}
};
gwintEffectService.hasEffect = function (effect, effectName) {
return effect === gwintEffectService.effects[effectName];
};
gwintEffectService.hasNotEffect = function (effect, effectName) {
return effect !== gwintEffectService.effects[effectName];
};
gwintEffectService.hasAnyEffect = function (effect, effectNames) {
if (effectNames === undefined || effectNames === null || effectNames === []) {
return false;
}
for (var i = 0; i < effectNames.length; i++) {
if (effect === gwintEffectService.effects[effectNames[i]]) {
return true;
}
}
return false;
};
return gwintEffectService;
})
.filter('gwintEffect', function (gwintEffectService) {
return function (cards, allowedEffects) {
var tempCards = [];
if (allowedEffects === undefined || allowedEffects === null || allowedEffects === []) {
return tempCards;
}
angular.forEach(cards, function (card) {
if (gwintEffectService.hasAnyEffect(card.effect, allowedEffects)) {
tempCards.push(card);
}
});
return tempCards;
}
})
.factory('gwintSideService', function (gwintTypeService) {
var gwintSideService = {};
gwintSideService.sides = {
self: {
canPlayCard: function (card) {
return !gwintTypeService.hasAnyType(card.type, ['Spy', 'OffensiveEffect']);
}
},
opponent: {
canPlayCard: function (card) {
return gwintTypeService.hasAnyType(card.type, ['Spy', 'OffensiveEffect', 'GlobalEffect']);
}
}
};
gwintSideService.canPlayCard = function (card, sideName) {
for (var side in gwintSideService.sides) {
if (!gwintSideService.sides.hasOwnProperty(side)) {
continue;
}
if (side !== sideName) {
continue;
}
return gwintSideService.sides[side].canPlayCard(card);
}
return false;
}
return gwintSideService;
})
.factory('gwintSlotService', function (gwintTypeService) {
var gwintSlotService = {};
gwintSlotService.slots = {
None: {
id: 0,
canPlayCard: function () {
return false;
}
},
Deck: {
id: 1,
canPlayCard: function () {
return false;
}
},
Hand: {
id: 2,
canPlayCard: function () {
return false;
}
},
Graveyard: {
id: 3,
canPlayCard: function () {
return false;
}
},
Melee: {
id: 4,
canPlayCard: function (card) {
return gwintTypeService.hasAllTypes(card.type, ['Melee', 'Creature']) ||
gwintTypeService.hasType(card.type, 'Spell') ||
gwintTypeService.hasType(card.type, 'GlobalEffect');
}
},
Ranged: {
id: 5,
canPlayCard: function (card) {
return gwintTypeService.hasAllTypes(card.type, ['Ranged', 'Creature']) ||
gwintTypeService.hasType(card.type, 'Spell') ||
gwintTypeService.hasType(card.type, 'GlobalEffect');
}
},
Siege: {
id: 6,
canPlayCard: function (card) {
return gwintTypeService.hasAllTypes(card.type, ['Siege', 'Creature']) ||
gwintTypeService.hasType(card.type, 'Spell') ||
gwintTypeService.hasType(card.type, 'GlobalEffect');
}
},
MeleeModifier: {
id: 7,
canPlayCard: function (card) {
return gwintTypeService.hasAllTypes(card.type, ['Melee', 'RowModifier']);
}
},
RangedModifier: {
id: 8,
canPlayCard: function (card) {
return gwintTypeService.hasAllTypes(card.type, ['Melee', 'RowModifier']);
}
},
SiegeModifier: {
id: 9,
canPlayCard: function (card) {
return gwintTypeService.hasAllTypes(card.type, ['Melee', 'RowModifier']);
}
},
Weather: {
id: 10,
canPlayCard: function (card) {
return gwintTypeService.hasType(card.type, 'Weather');
}
}
};
gwintSlotService.canPlayCard = function (card, slotId) {
for (var slotName in gwintSlotService.slots) {
if (!gwintSlotService.slots.hasOwnProperty(slotName)) {
continue;
}
var slot = gwintSlotService.slots[slotName];
if (slot.id !== slotId) {
continue;
}
return slot.canPlayCard(card);
}
return false;
};
gwintSlotService.getValidSlots = function (card) {
var tempSlots = [];
for (var slotName in gwintSlotService.slots) {
if (!gwintSlotService.slots.hasOwnProperty(slotName)) {
continue;
}
var slot = gwintSlotService.slots[slotName];
if (slot.canPlayCard(card)) {
tempSlots.push(slotName);
}
}
return tempSlots;
};
return gwintSlotService;
})
.directive('gwCard', function () {
return {
require: '^ngModel',
scope: {
cardId: '=ngModel'
},
templateUrl: 'templates/game/gw-card.html'
};
})
.directive('gwCardField', function () {
var controller = function ($scope, $log, cardService) {
$scope.card = {
id: 0,
power: 0,
ability: 0,
type: 0,
picture: 'cardcover'
};
cardService.getCardById($scope.playerCard.cardId).then(function (foundCard) {
$scope.card = foundCard;
}, function(error) {
$log.error(error);
});
};
return {
require: '^ngModel',
scope: {
playerCard: '=ngModel'
},
controller: controller,
templateUrl: 'templates/game/gw-card-field.html'
};
})
.directive('gwBattleKingCard', function () {
var controller = function ($scope, $log, cardService) {
$scope.card = {
id: 0,
picture: 'nor_ldr_foltest_bronze'
};
$scope.canUse = true;
cardService.getCardById($scope.cardId).then(function (foundCard) {
$scope.card = foundCard;
}, function(error) {
$log.error(error);
});
};
return {
require: '^ngModel',
scope: {
cardId: '=ngModel'
},
controller: controller,
templateUrl: 'templates/game/gw-battle-king-card.html'
};
})
.directive('gwBoard', function () {
var controller = function ($scope, $log, gwintFactionService) {
var methods = $scope.methods = {};
var game = $scope.game;
var input = {};
methods.selectCard = function (playerCard) {
input.playCard = playerCard;
$log.info('card selected: ' +playerCard.cardId);
// TODO: Hightlight the card
};
methods.getFactionName = function(factionId) {
return gwintFactionService.findFaction(factionId).name;
};
};
return {
require: '^ngModel',
scope: {
game: '=ngModel'
},
controller: controller,
templateUrl: 'templates/game/gw-board.html'
};
});
})(); |
import { Motion, rAF } from 'ember-animated';
import { BoxShadow, BoxShadowTween } from '../box-shadow';
export default function boxShadow(sprite, opts) {
return new BoxShadowMotion(sprite, opts).run();
}
export class BoxShadowMotion extends Motion {
*animate() {
let from;
if (this.opts.from) {
from = BoxShadow.fromUserProvidedShadow(this.opts.from);
} else {
from = BoxShadow.fromComputedStyle(
this.sprite.initialComputedStyle['box-shadow'],
);
}
let to;
if (this.opts.to) {
to = BoxShadow.fromUserProvidedShadow(this.opts.to);
} else {
to = BoxShadow.fromComputedStyle(
this.sprite.finalComputedStyle['box-shadow'],
);
}
let shadowTween = new BoxShadowTween(
from,
to,
this.duration,
this.opts.easing,
);
while (!shadowTween.done) {
this.sprite.applyStyles({
'box-shadow': shadowTween.currentValue
.map((shadow) => shadow.toString())
.join(','),
});
yield rAF();
}
}
}
|
Router.configure({
layoutTemplate: 'layout',
loadingTemplate: 'loading'
});
// using code from https://github.com/mizzao/meteor-accounts-testing
Meteor.insecureUserLogin = function(username, callback) {
return Accounts.callLoginMethod({
methodArguments: [{username: username}],
userCallback: callback
});
};
Meteor.startup(function() {
Session.setDefault("selectedTab", "playlist");
Session.setDefault("missedChats", 0);
Session.setDefault("missedPlaylist", 0);
});
|
export class ModalDemo {}
|
'use strict';
const fs = require('fs');
const path = require('path');
const gulp = require('gulp');
var bat = function() {
if(!fs.existsSync("development.bat") || !fs.existsSync("production.bat")) {
gulp.task("easy:gulp:by:orel:copy:bat", function () {
return gulp.src([
path.join(__dirname, '/development.bat'),
path.join(__dirname, '/production.bat')
])
.pipe(gulp.dest("./"));
})
.start("easy:gulp:by:orel:copy:bat");
}
};
module.exports = bat; |
const BaseElementCommand = require('./_baseElementCommand.js');
/**
* Search for an elements on the page, starting from the document root. The located element will be returned as web element JSON object (with an added .getId() convenience method).
* First argument is the element selector, either specified as a string or as an object (with 'selector' and 'locateStrategy' properties).
*
* @example
* module.exports = {
* 'demo Test': function(browser) {
* const resultElement = await browser.findElement('.features-container li:first-child');
*
* console.log('Element Id:', resultElement.getId());
* },
*
*
* @link /#find-element
* @syntax browser.findElement(selector, callback)
* @syntax await browser.findElement(selector);
* @param {string} selector The search target.
* @param {function} [callback] Callback function to be invoked with the result when the command finishes.
* @since 1.7.0
* @api protocol.elements
*/
const FindElements = require('./findElements.js');
module.exports = class FindElement extends FindElements {
async elementFound(response) {
if (response && response.value) {
const elementId = this.transport.getElementId(response.value);
response.value = Object.assign(response.value, {
get getId() {
return function() {
return elementId;
};
}
});
}
return response;
}
findElementAction() {
return this.findElement();
}
};
|
'use strict';
var os = require("os");
var BEEP_CODE = "\u0007";
var BEEP_DEFAULT_TIME = 100;
var interval;
var beep = function(print) {
process.stdout.write(BEEP_CODE);
if (print) {
process.stdout.write("\u2407\n");
}
}
var timer = function(fn, time, print) {
}
var beepBeeper = function(vale) {
if (value.length === 0) {
return;
}
setTimeoutout(function() {
if (value.shift() === "*") {
beep();
beepBeeper(value);
}
}, BEEP_DEFAULT_TIME);
}
var beepTimer = function(value) {
if (value.length === 0) {
return;
}
var time = value.shift();
setTimeout(function() {
beep(true);
}, time);
}
var beepTime = function(number) {
interval = setTimeout(function() {
if (number > 0) {
beep(true);
number--;
beepTime(number);
} else {
clearTimeout(interval);
return
}
}, BEEP_DEFAULT_TIME)
}
var beepPrint = function(obj) {
setTimeout(function() {
var str = obj.print;
beep(str);
}, obj.time)
}
/**
* @api @public
*
* Make beep in console and print it based on input
*
* Overloaded version
*
* @param {Object|String|Function|Array} input describe action to be taken by beep
* @return {String} ascii code for
*/
var makeBeep = function(input) {
var type = typeof input;
switch (type) {
case "function":
input();
beep();
break;
case "array":
beepTimer(input)
break;
case "object":
break;
case "string":
beepBeeper(input.split(""));
break;
case "number":
beepTime(input);
break;
default:
throw new Error("Not implememented Yet");
}
}
module.exports = makeBeep;
|
'use strict';
angular.module("ngLocale", [], ["$provide", function($provide) {
var PLURAL_CATEGORY = {ZERO: "zero", ONE: "one", TWO: "two", FEW: "few", MANY: "many", OTHER: "other"};
$provide.value("$locale", {
"DATETIME_FORMATS": {
"AMPMS": [
"\u0635",
"\u0645"
],
"DAY": [
"\u0627\u0644\u0623\u062d\u062f",
"\u0627\u0644\u0627\u062b\u0646\u064a\u0646",
"\u0627\u0644\u062b\u0644\u0627\u062b\u0627\u0621",
"\u0627\u0644\u0623\u0631\u0628\u0639\u0627\u0621",
"\u0627\u0644\u062e\u0645\u064a\u0633",
"\u0627\u0644\u062c\u0645\u0639\u0629",
"\u0627\u0644\u0633\u0628\u062a"
],
"ERANAMES": [
"\u0642\u0628\u0644 \u0627\u0644\u0645\u064a\u0644\u0627\u062f",
"\u0645\u064a\u0644\u0627\u062f\u064a"
],
"ERAS": [
"\u0642.\u0645",
"\u0645"
],
"FIRSTDAYOFWEEK": 0,
"MONTH": [
"\u064a\u0646\u0627\u064a\u0631",
"\u0641\u0628\u0631\u0627\u064a\u0631",
"\u0645\u0627\u0631\u0633",
"\u0625\u0628\u0631\u064a\u0644",
"\u0645\u0627\u064a\u0648",
"\u064a\u0648\u0646\u064a\u0648",
"\u064a\u0648\u0644\u064a\u0648",
"\u0623\u063a\u0634\u062a",
"\u0634\u062a\u0645\u0628\u0631",
"\u0623\u0643\u062a\u0648\u0628\u0631",
"\u0646\u0648\u0641\u0645\u0628\u0631",
"\u062f\u062c\u0645\u0628\u0631"
],
"SHORTDAY": [
"\u0627\u0644\u0623\u062d\u062f",
"\u0627\u0644\u0627\u062b\u0646\u064a\u0646",
"\u0627\u0644\u062b\u0644\u0627\u062b\u0627\u0621",
"\u0627\u0644\u0623\u0631\u0628\u0639\u0627\u0621",
"\u0627\u0644\u062e\u0645\u064a\u0633",
"\u0627\u0644\u062c\u0645\u0639\u0629",
"\u0627\u0644\u0633\u0628\u062a"
],
"SHORTMONTH": [
"\u064a\u0646\u0627\u064a\u0631",
"\u0641\u0628\u0631\u0627\u064a\u0631",
"\u0645\u0627\u0631\u0633",
"\u0625\u0628\u0631\u064a\u0644",
"\u0645\u0627\u064a\u0648",
"\u064a\u0648\u0646\u064a\u0648",
"\u064a\u0648\u0644\u064a\u0648",
"\u0623\u063a\u0634\u062a",
"\u0634\u062a\u0645\u0628\u0631",
"\u0623\u0643\u062a\u0648\u0628\u0631",
"\u0646\u0648\u0641\u0645\u0628\u0631",
"\u062f\u062c\u0645\u0628\u0631"
],
"WEEKENDRANGE": [
5,
6
],
"fullDate": "EEEE\u060c d MMMM\u060c y",
"longDate": "d MMMM\u060c y",
"medium": "dd\u200f/MM\u200f/y h:mm:ss a",
"mediumDate": "dd\u200f/MM\u200f/y",
"mediumTime": "h:mm:ss a",
"short": "d\u200f/M\u200f/y h:mm a",
"shortDate": "d\u200f/M\u200f/y",
"shortTime": "h:mm a"
},
"NUMBER_FORMATS": {
"CURRENCY_SYM": "MRO",
"DECIMAL_SEP": "\u066b",
"GROUP_SEP": "\u066c",
"PATTERNS": [
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 3,
"minFrac": 0,
"minInt": 1,
"negPre": "-",
"negSuf": "",
"posPre": "",
"posSuf": ""
},
{
"gSize": 3,
"lgSize": 3,
"maxFrac": 2,
"minFrac": 2,
"minInt": 1,
"negPre": "\u00a4\u00a0-",
"negSuf": "",
"posPre": "\u00a4\u00a0",
"posSuf": ""
}
]
},
"id": "ar-mr",
"pluralCat": function(n, opt_precision) { if (n == 0) { return PLURAL_CATEGORY.ZERO; } if (n == 1) { return PLURAL_CATEGORY.ONE; } if (n == 2) { return PLURAL_CATEGORY.TWO; } if (n % 100 >= 3 && n % 100 <= 10) { return PLURAL_CATEGORY.FEW; } if (n % 100 >= 11 && n % 100 <= 99) { return PLURAL_CATEGORY.MANY; } return PLURAL_CATEGORY.OTHER;}
});
}]);
|
define(['app'], function (app) {
app.factory('userService', ['$http', '$q', function ($http, $q) {
var userService = {};
//send email
userService.sendEmail = function (name, email, subject, content) {
var deferd = $q.defer();
$http.post('/email', {
name: name,
email: email,
subject: subject,
content: content
}).then(function (data) {
deferd.resolve(data);
},function (err) {
deferd.reject(err);
});
return deferd.promise;
};
return userService;
}]);
}); |
import url from 'url';
// assets.preview will be:
// - undefined
// - string e.g. 'static/preview.9adbb5ef965106be1cc3.bundle.js'
// - array of strings e.g.
// [ 'static/preview.9adbb5ef965106be1cc3.bundle.js',
// 'preview.0d2d3d845f78399fd6d5e859daa152a9.css',
// 'static/preview.9adbb5ef965106be1cc3.bundle.js.map',
// 'preview.0d2d3d845f78399fd6d5e859daa152a9.css.map' ]
export const urlsFromAssets = assets => {
if (!assets) {
return {
js: ['static/preview.bundle.js'],
css: [],
};
}
const urls = {
js: [],
css: [],
};
const re = /.+\.(\w+)$/;
Object.keys(assets)
// Don't load the manager script in the iframe
.filter(key => key !== 'manager')
.forEach(key => {
let assetList = assets[key];
if (!Array.isArray(assetList)) {
assetList = [assetList];
}
assetList.filter(assetUrl => re.exec(assetUrl)[1] !== 'map').forEach(assetUrl => {
urls[re.exec(assetUrl)[1]].push(assetUrl);
});
});
return urls;
};
export default function({ assets, publicPath, headHtml }) {
const urls = urlsFromAssets(assets);
const cssTags = urls.css
.map(u => `<link rel='stylesheet' type='text/css' href='${url.resolve(publicPath, u)}'>`)
.join('\n');
const scriptTags = urls.js
.map(u => `<script src="${url.resolve(publicPath, u)}"></script>`)
.join('\n');
return `
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script>
if (window.parent !== window) {
window.__REACT_DEVTOOLS_GLOBAL_HOOK__ = window.parent.__REACT_DEVTOOLS_GLOBAL_HOOK__;
}
</script>
<title>Storybook</title>
${headHtml}
${cssTags}
</head>
<body>
<div id="root"></div>
<div id="error-display"></div>
${scriptTags}
</body>
</html>
`;
}
|
// ==UserScript==
// @name Subpages link for wiki toobox menu
// @description This will add a new link into 'Toolbox' menu of wikipedia and other included wikies - 'Subpages'. It is a link to 'Special:PrefixIndex' page with prefix and namespace parameters extracted from current page title.
// @namespace linguamatics.com
// @include http://*.wikipedia.org/wiki/*
// @exclude *Special:*
// @version 1.2
// @grant none
// ==/UserScript==
// execute this after complete document load
var add_subpages_link_to_toolbox = function () {
"use strict";
// compute path to Special:PrefixIndex relevant for the current page
// e.g. title=Special:PrefixIndex&prefix=...&namespace=...
var namespace_list = {
"Talk": "1",
"User": "2",
"User_talk": "3",
"Linguapedia": "4",
"Linguapedia_talk": "5",
"File": "6",
"File_talk": "7",
"MediaWiki": "8",
"MediaWiki_talk": "9",
"Template": "10",
"Template_talk": "11",
"Help": "12",
"Help_talk": "13",
"Category": "14",
"Category_talk": "15"
};
var namespace = 0; // main namespace
var path = window.location.pathname.split('/');
var prefix = unescape(path.pop()); // get page title and move it out of path array
if (prefix.indexOf(":") !== -1){ // in not main namespace, e.g. "User:2aprilboy"
prefix = prefix.split(":");
namespace = namespace_list[prefix[0]];
prefix = prefix[1];
};
path = path.join('/') + '?title=Special:PrefixIndex&prefix=' + prefix + '&namespace=' + namespace;
// create <li><a>Subpages</a></li> element and append it to Toolbox menu
var li = document.createElement("li");
var a = document.createElement("a");
var text = document.createTextNode("Subpages");
a.appendChild(text);
a.setAttribute("href", path);
a.setAttribute("title", "List of all pages with prefix [alt-shift-s]");
a.setAttribute("accesskey", "s");
li.appendChild(a);
li.setAttribute("id", "t-subpages");
var toolbox_list = document.getElementById("p-tb").getElementsByTagName("div")[0].getElementsByTagName("ul")[0];
toolbox_list.insertBefore(li, toolbox_list.firstChild);
}
// wait for complete document load
document.onreadystatechange = function () {
"use strict";
if (document.readyState === "complete") {
add_subpages_link_to_toolbox();
}
}
|
import sameAs from 'src/validators/sameAs'
describe('sameAs validator', () => {
const parentVm = {
first: 'hello',
second: 'world',
undef: undefined,
nil: null,
empty: ''
}
it('should not validate different values', () => {
expect(sameAs('first')('world', parentVm)).to.be.false
expect(sameAs('second')('hello', parentVm)).to.be.false
expect(sameAs('first')(undefined, parentVm)).to.be.false
expect(sameAs('first')(null, parentVm)).to.be.false
expect(sameAs('first')('', parentVm)).to.be.false
expect(sameAs('undef')('any', parentVm)).to.be.false
expect(sameAs('nil')('any', parentVm)).to.be.false
expect(sameAs('empty')('any', parentVm)).to.be.false
})
it('should validate identical values', () => {
expect(sameAs('first')('hello', parentVm)).to.be.true
expect(sameAs('second')('world', parentVm)).to.be.true
expect(sameAs('undef')(undefined, parentVm)).to.be.true
expect(sameAs('nil')(null, parentVm)).to.be.true
expect(sameAs('empty')('', parentVm)).to.be.true
})
it('should allow function expression', () => {
expect(sameAs((p) => p.first)('hello', parentVm)).to.be.true
})
})
|
'use strict';
//Workouts service used for communicating with the workouts REST endpoints
angular.module('workouts').factory('Workouts', ['$resource',
function ($resource) {
return $resource('workouts/:workoutId', {
workoutId: '@_id'
}, {
update: {
method: 'PUT'
}
});
}
]); |
var AppDispatcher = require('../../dispatcher');
var fetch = require('../../core/fetch');
var URL = require('../../config/server');
var data = [{id:1, title : "toto", body:"ceci est un test"},{id:2, title:"tata",body:"deuxieme test"}]
var countId = 3;
module.exports = {
search: function search(scope, text){
window.setTimeout(function () {
var data = [{id:countId++, title : "toto", body:"ceci est un test"},{id:countId++, title:"tata",body:"deuxieme test"}]
AppDispatcher.handleServerAction({type: "search", data: {scope : scope, query: text, list: data}});
},1000);
}
};
|
module.exports = {
root: true,
parser: '@typescript-eslint/parser',
parserOptions: {
ecmaVersion: 2018,
sourceType: 'module'
},
extends: [
'plugin:@typescript-eslint/recommended',
'prettier/@typescript-eslint',
'plugin:prettier/recommended'
],
env: {
browser: true
},
rules: {
'@typescript-eslint/no-use-before-define': ['off'],
'@typescript-eslint/explicit-function-return-type': ['off'],
'@typescript-eslint/explicit-member-accessibility': ['off'],
'@typescript-eslint/no-explicit-any': ['off']
},
overrides: [{
files: ['test/**/*.ts'],
rules: {
'@typescript-eslint/no-unused-vars': ['off'],
'prefer-const': ['off']
}
}]
};
|
var gulp = require("gulp"),
resolve = require("json-refs").resolveRefs,
fs = require("fs");
// VisualStudio's one downside is to add BOMs to all UTF-8 files
gulp.task("strip-bom", function () {
// To-do: How does gulp.src search top down and replace files in place?
return gulp.src('1.txt').pipe(stripBom()).pipe(gulp.dest('dest'));
});
// To-do: Gulpify this! It should use gulp.src and gulp.dest.
gulp.task("schema", function () {
var $RefParser = require("json-schema-ref-parser");
// Dereferencing parses a root file plus all externally referenced files and produces a single JSON schema object
$RefParser.dereference("./api/swagger/index.yaml").then(function (schema) {
// While we are not using a JSON version at the moment it might be useful for other tools in the future.
fs.writeFile("./api/swagger/swagger.json", JSON.stringify(schema));
// Since all the $refs are now inlined the .definitions object is redundant and can be deleted
delete schema.definitions;
// Bundle the schema c/w local references and save as our new swagger.yaml (required by swagger node)
$RefParser.bundle(schema).then(function (schema) {
fs.writeFile("./api/swagger/swagger.yaml", $RefParser.YAML.stringify(schema));
});
}).catch(function (reason) {
console.error("Error dereferencing: %s", reason);
});
});
|
var expect = require('chai').expect;
var _ = require('lodash');
var ziti = require('../index');
var hooks = require('./hooks');
var ModelInstance = require('../lib/model-instance');
describe('Instance', function () {
var Product, Country, productCountry;
before(function () {
Product = require('./models/product');
Country = require('./models/country');
});
before(hooks.sync);
before(function (done) {
Country.save({ name: 'France' }).then(function (country) {
productCountry = country;
}).finally(done).catch(done);
});
after(hooks.clean);
describe('#set()', function () {
var torti;
before(function () {
torti = Product.build({ price: 10, name: 'torti' });
});
it('should check instance fields are correctly set at build', function (done) {
expect(torti).to.be.ok.and.to.be.an.instanceof(ModelInstance);
expect(torti.getValue('price')).to.equals(10);
done();
});
it('should set a field', function (done) {
torti.set('price', 12);
expect(torti.getValue('price')).to.equals(12);
done();
});
it('should set a field using a setter', function (done) {
torti.set('name', 'penne');
expect(torti.getValue('name')).to.equals('PENNE');
done();
});
});
describe('#get()', function () {
var torti;
before(function () {
torti = Product.build({ price: 10, name: 'torti' });
});
it('should check instance fields are correctly set at build', function (done) {
expect(torti).to.be.ok.and.to.be.an.instanceof(ModelInstance);
expect(torti.get('price')).to.equals(10);
done();
});
it('should set & get a field', function (done) {
torti.setValue('price', 12);
expect(torti.get('price')).to.equals(12);
done();
});
it('should get a field using a getter', function (done) {
expect(torti.get('name')).to.equals('TORTI:12');
done();
});
});
describe('#raw()', function () {
var torti;
before(function () {
torti = Product.build({ price: 10, name: 'torti' });
});
it('should get instance raw data', function (done) {
expect(torti).to.be.ok.and.to.be.an.instanceof(ModelInstance);
expect(torti.raw()).to.deep.equals({ price: 10, name: 'TORTI' });
done();
});
});
describe('#toJSON()', function () {
var torti;
before(function () {
torti = Product.build({ price: 10, name: 'torti' });
});
it('should get instance JSON representation', function (done) {
expect(torti).to.be.ok.and.to.be.an.instanceof(ModelInstance);
expect(torti.toJSON()).to.equals('{"price":10,"name":"TORTI"}');
done();
});
});
describe('#save()', function () {
it('should build and insert an instance into database', function (done) {
var torti = Product.build({ price: 10, name: 'torti', origin: productCountry });
expect(torti.get('origin_id')).to.be.above(0);
torti.save().then(function (torti) {
expect(torti).to.be.ok.and.to.be.an.instanceof(ModelInstance);
expect(torti.get('id')).to.be.above(0);
expect(torti.get('price')).to.equals(10);
expect(torti.get('name')).to.equals('TORTI:10');
expect(torti.get('origin_id')).to.be.above(0);
}).finally(done).catch(done);
});
it('should retrieve an instance and save should have no effect', function (done) {
Product.at({ price: 10 }).then(function (torti) {
expect(torti).to.be.ok.and.to.be.an.instanceof(ModelInstance);
expect(torti.get('id')).to.be.above(0);
expect(torti.get('price')).to.equals(10);
expect(torti.get('name')).to.equals('TORTI:10');
return torti.save();
}).then(function (torti) {
expect(torti).to.be.ok.and.to.be.an.instanceof(ModelInstance);
}).finally(done).catch(done);
});
it('should retrieve an instance, set a field and update database', function (done) {
Product.at({ price: 10 }).then(function (torti) {
expect(torti).to.be.ok.and.to.be.an.instanceof(ModelInstance);
expect(torti.get('id')).to.be.above(0);
expect(torti.get('price')).to.equals(10);
expect(torti.get('name')).to.equals('TORTI:10');
torti.set('price', torti.get('price') + 1);
return torti.save();
}).then(function (torti) {
expect(torti).to.be.ok.and.to.be.an.instanceof(ModelInstance);
expect(torti.get('price')).to.equals(11);
return Product.at({ price: 11 });
}).then(function (torti) {
expect(torti).to.be.ok.and.to.be.an.instanceof(ModelInstance);
expect(torti.get('price')).to.equals(11);
}).finally(done).catch(done);
});
});
describe('#update()', function () {
it('should update a field into database', function (done) {
Product.at({ price: 11 }).then(function (torti) {
return torti.update({ price: 12 })
}).then(function (torti) {
expect(torti).to.be.ok.and.to.be.an.instanceof(ModelInstance);
expect(torti.get('price')).to.equals(12);
return Product.at({ price: 12 })
}).then(function (torti) {
expect(torti).to.be.ok.and.to.be.an.instanceof(ModelInstance);
expect(torti.get('price')).to.equals(12);
}).finally(done).catch(done);
});
});
describe('#remove()', function () {
it('should remove an instance from database', function (done) {
Product.at({ price: 12 }).then(function (torti) {
return torti.remove();
}).then(function (torti) {
expect(torti).to.be.ok.and.to.be.an.instanceof(ModelInstance);
expect(torti._isNew).to.be.true;
return Product.at({ price: 12 });
}).then(function (torti) {
expect(torti).to.be.null;
}).finally(done).catch(done);
});
});
describe('#refresh()', function () {
it('should set a field and refresh the instance data', function (done) {
Product.save({ price: 10, name: 'torti', origin_id: productCountry.get('id') }).then(function (torti) {
expect(torti).to.be.ok.and.to.be.an.instanceof(ModelInstance);
torti.set({ price: 11 });
return torti.refresh();
}).then(function (torti) {
expect(torti).to.be.ok.and.to.be.an.instanceof(ModelInstance);
expect(torti.get('price')).to.equals(10);
}).finally(done).catch(done);
});
});
});
|
import Cookies from "utils/Cookies";// eslint-disable-line
import chai from "chai";// eslint-disable-line import/no-extraneous-dependencies
describe("Cookies.js", () => {
it("get&put", () => {
chai.assert.equal(Cookies.get("get", 1), 1);
Cookies.put("get", 2);
chai.assert.equal(Cookies.get("get", 1), 2);
});
it("remove", () => {
chai.assert.equal(Cookies.get("remove", 1), 1);
Cookies.put("remove", 2);
chai.assert.equal(Cookies.get("remove", 1), 2);
Cookies.remove("remove");
chai.assert.equal(Cookies.get("remove", 1), 1);
});
it("clearAll", () => {
chai.assert.equal(Cookies.get("clearAll", 1), 1);
Cookies.put("clearAll", 2);
chai.assert.equal(Cookies.get("clearAll", 1), 2);
Cookies.clearAll();
chai.assert.equal(Cookies.get("clearAll", 1), 2);
});
});
|
var QueryParametersCriterion = BaseCriterion.extend({
defaults: {
type: 'query_parameters'
}
}); |
requirejs.config({
baseUrl: "./assets/"
});
define('main', function(require) {
var angular = require('angular');
var profile = require('json!profile.json');
var elggAccounts = require('elgg/accounts/module').default;
var elggBlog = require('elgg/blog/module').default;
var elggCore = require('elgg/core/module').default;
var elggEvents = require('elgg/events/module').default;
var elggPhotos = require('elgg/photos/module').default;
var elggPosts = require('elgg/posts/module').default;
var demo = angular.module('demo', [
elggAccounts.name,
elggBlog.name,
elggCore.name,
elggEvents.name,
elggPhotos.name,
elggPosts.name,
]).value('profile', profile).run(function(profile) {
profile.appcache = profile.appcache || {};
// maxAge defaults to once-per-hour
var maxAge = profile.appcache.maxAge || 1000 * 60 * 60;
setInterval(function() {
applicationCache.update();
}, maxAge);
});
angular.bootstrap(document, [demo.name]);
});
require(['main']);
|
var test = require('tape');
var path = require('path');
var utils = require('../utils');
var root = __dirname;
utils.start({
log: 'silent',
root: root
}, function (site) {
site.once('build', function () {
test('should query pages and return the query result in templates', function (t) {
t.plan(1);
t.timeoutAfter(500);
var output = path.join('build', 'query', 'index.html');
var expected = path.join('expected', 'query.html');
utils.equal(t, root, output, expected);
});
});
});
|
/**
* Een simpele Ajax functie om data op te halen
* ik gebruik hem nu voor mockup data
*/
function getData (url, callback) {
var request = new XMLHttpRequest();
request.open('GET', url, true);
request.onload = function() {
if (this.status >= 200 && this.status < 400) {
var data = JSON.parse(this.response);
callback(data);
} else {
callback("{'response': 'error'}");
}
};
request.onerror = function() {
callback("{'response': 'connection error'}");
};
request.send();
};/**
* Child wordt gecalled als basis
* Select item wordt ge-extend met:
* true / false option
*/
function CheckboxItem (options) {
Child.call(this, options);
this.options = options.options;
this.element = document.createElement('input');
this.element.addEventListener('click', function(event){
this.value = event.target.checked ? this.options[1] : this.options[0];
this.changeStyle(this.target, this.css, (this.value+this.unit));
}.bind(this), false);
}
CheckboxItem.prototype = Object.create(Child.prototype);
CheckboxItem.prototype.constructor = Child;
/**
* De build functie voor de HTML op te bouwen
*/
CheckboxItem.prototype.built = function () {
var innerDiv = document.createElement('div');
this.element.type = "checkbox";
this.element.value = this.value;
innerDiv.appendChild(this.labelNode);
innerDiv.appendChild(this.element);
return innerDiv;
};/**
* Child wordt gecalled als basis
* Select item wordt ge-extend met:
* alle radio options
*/
function RadioItem (options) {
Child.call(this, options);
this.options = options.options;
this.element = document.createElement('div');
this.element.addEventListener('click', function(event){
if (event.target.type === "radio") {
this.value = this.options[event.target.dataset.count];
this.changeStyle(this.target, this.css, (this.value+this.unit));
}
}.bind(this), false);
}
RadioItem.prototype = Object.create(Child.prototype);
RadioItem.prototype.constructor = Child;
/**
* De build functie voor de HTML op te bouwen
*/
RadioItem.prototype.built = function () {
this.element.appendChild(this.labelNode);
for (var i = 0; i < this.options.length; i++) {
var innerDiv = document.createElement('div');
var radio = document.createElement('input')
radio.type = "radio";
radio.name = this.label;
radio.dataset.count = i;
var innerLabel = document.createElement('label');
innerLabel.innerHTML = this.options[i];
innerDiv.appendChild(innerLabel);
innerDiv.appendChild(radio);
this.element.appendChild(innerDiv);
}
return this.element;
};/**
* Child wordt gecalled als basis
* Select item wordt ge-extend met:
* -min
* -max
* -step
*/
function RangeItem (options) {
Child.call(this, options);
this.min = options.options.min;
this.max = options.options.max;
this.step = options.options.step;
this.element = document.createElement('input');
this.element.addEventListener('input', function(event){
this.value = event.srcElement.value;
this.changeStyle(this.target, this.css, (this.value+this.unit));
}.bind(this), false);
}
RangeItem.prototype = Object.create(Child.prototype);
RangeItem.prototype.constructor = Child;
/**
* De build functie voor de HTML op te bouwen
*/
RangeItem.prototype.built = function () {
var innerDiv = document.createElement('div');
this.element.type = "range";
this.element.min = this.min;
this.element.max = this.max;
this.element.step = this.step;
if (this.value && this.value >= this.min && this.value <= this.max) this.element.value = this.value;
innerDiv.appendChild(this.labelNode);
innerDiv.appendChild(this.element);
return innerDiv;
};/**
* Child wordt gecalled als basis
* Select item wordt ge-extend met de items in de lijst
*/
function SelectItem (options) {
Child.call(this, options);
this.items = options.options;
this.element = document.createElement('select');
this.element.addEventListener('input', function(event){
this.value = event.srcElement.value;
this.changeStyle(this.target, this.css, (this.value+this.unit));
}.bind(this), false);
}
SelectItem.prototype = Object.create(Child.prototype);
SelectItem.prototype.constructor = Child;
/**
* De build functie voor de HTML op te bouwen
*/
SelectItem.prototype.built = function () {
var innerDiv = document.createElement('div');
for (var i = 0; i < this.items.length; i++) {
var startTag = (this.value === this.items[i] ? "<option selected>" : "<option>");
this.element.innerHTML += startTag + this.items[i] +'</option>';
}
innerDiv.appendChild(this.labelNode);
innerDiv.appendChild(this.element);
return innerDiv;
};/**
* De basis van alle constructors
*/
function Fieldset (field) {
this.name = field.fieldsetName;
}
Fieldset.prototype.built = function () {
var fieldset = document.createElement('fieldset');
fieldset.innerHTML = '<legend>' + this.name + '</legend>';
return fieldset;
}
/**
* Child wordt hergebruikt voor de andere componenten
* alle basis instellingen staan hier in
* specifieke input dingen staan in de andere constructors
*/
function Child (options) {
this.label = options.label;
this.type = options.type;
this.target = options.target;
this.unit = options.unit;
this.value = options.value;
this.css = options.css;
var label = document.createElement('label');
var text = document.createTextNode(this.label);
label.appendChild(text);
this.labelNode = label;
}
Child.prototype.getStyle = function () {
return {
"target": this.target,
"property": this.css,
"value": (this.value+this.unit)
}
}
Child.prototype.changeStyle = function (target, property, value) {
addCSSRule(sheet, target, property + ":" + value);
}
;/**
* Hier maken we een stylesheet aan in de var "sheet"
*/
var sheet = (function() {
// Create the <style> tag
var style = document.createElement("style");
// WebKit hack :(
style.appendChild(document.createTextNode(""));
// Add the <style> element to the page
document.head.appendChild(style);
return style.sheet;
})();
/**
* Functie om makkelijk een regel toe te voegen
* addCSSRule(sheet, "header", "float: left");
*/
var prefix = "main" // prefix voor styles
function addCSSRule(sheet, selector, rules, index) {
selector = prefix + ' ' + selector;
if("insertRule" in sheet) {
sheet.insertRule(selector + "{" + rules + "}", sheet.cssRules.length);
}
else if("addRule" in sheet) {
sheet.addRule(selector, rules, sheet.cssRules.length);
}
};/**
* Hier halen we de data op
*/
getData('data/mockup.json', function(data){
buildFields(data);
});
/**
* Hier komen alle fields in te staan
* Dit gaan we later hergebruiken om de initiele styling aan te maken
*/
var fields = [];
/**
* De functie om alle velden in een object te zetten
* Hier worden de constructors aangeroepen
* om vervolgens HTML ervan te maken in function renderItems
*/
function buildFields (data) {
for (var i = 0; i < data.length; i++) {
fields.push(new Fieldset(data[i]));
if (data[i].children) {
fields[i].children = [];
for (var j = 0;j < data[i].children.length; j++) {
var current = data[i].children[j];
if (current.type === "select") {
fields[i].children.push(new SelectItem(current));
} else if (current.type === "range") {
fields[i].children.push(new RangeItem(current));
} else if (current.type === "checkbox") {
fields[i].children.push(new CheckboxItem(current));
} else if (current.type === "radio") {
fields[i].children.push(new RadioItem(current));
}
}
}
}
fields = fields;
renderItems(fields);
buildInitialCSS(fields);
}
/**
* De functie om alle velden te renderen op het scherm
* alles wordt op het einde ge-append naar het document
*/
function renderItems (fields) {
var div = document.createElement('div');
for (var i = 0; i < fields.length; i++) {
var currentField = fields[i].built();
console.log(currentField);
if (fields[i].children.length) {
for (var j = 0; j < fields[i].children.length; j++) {
currentField.appendChild(fields[i].children[j].built());
}
}
div.appendChild(currentField);
}
document.querySelector('aside').appendChild(div);
}
function buildInitialCSS (fields) {
for (var i = 0; i < fields.length; i++) {
if (fields[i].children.length) {
for (var j = 0; j < fields[i].children.length; j++) {
var style = fields[i].children[j].getStyle();
addCSSRule(sheet, style.target, style.property +":"+ style.value);
}
}
}
} |
'use babel';
'use strict';
/* jshint node: true */
/* jshint esversion: 6 */
/* global localStorage, console, atom, module */
const PebbleToolInterface = require('../pebbletool');
const OutputViewManager = require('../output-view-manager').OutputViewManager;
class PbRunPingCommand {
run() {
let args = ['ping'];
let options = {
cwd: atom.project.getPaths()[0]
};
let view = OutputViewManager.new();
PebbleToolInterface.cmd(args, options,
data => {
view.addLine(data);
}
).then(() => {
view.finish();
}).catch((e) => {
view.finish();
console.info('Pb-Run: exit code', e);
});
}
}
module.exports = PbRunPingCommand;
|
export const INCREMENT = 'INCREMENT'
export const CREATE_NODE = 'CREATE_NODE'
export const ADD_CHILD = 'ADD_CHILD'
export function increment(nodeId) {
return {
type: INCREMENT,
nodeId
}
}
let nextId = 0
export function createNode() {
return {
type: CREATE_NODE,
nodeId: `new_${nextId++}`
}
}
export function addChild(nodeId, childId) {
return {
type: ADD_CHILD,
nodeId,
childId
}
}
|
var gulp = require('gulp');
var exec = require('child_process').exec;
var git = require('gulp-git');
var bump = require('gulp-bump');
var filter = require('gulp-filter');
var tag_version = require('gulp-tag-version');
var gutil = require('gulp-util');
var pjson = require('./package.json');
/**
* Bumping version number and tagging the repository with it.
* Please read http://semver.org/
*
* You can use the commands
*
* gulp patch # makes v0.1.0 → v0.1.1
* gulp feature # makes v0.1.1 → v0.2.0
* gulp release # makes v0.2.1 → v1.0.0
*
* To bump the version numbers accordingly after you did a patch,
* introduced a feature or made a backwards-incompatible release.
*/
function inc(importance) {
// get all the files to bump version in
return gulp.src(['./package.json'])
// bump the version number in those files
.pipe(bump({type: importance}))
// save it back to filesystem
.pipe(gulp.dest('./'))
// commit the changed version number
.pipe(git.commit('bumps package version'))
// read only one file to get the version number
.pipe(filter('package.json'))
// **tag it in the repository**
.pipe(tag_version());
}
gulp.task('patch', function() { return inc('patch'); })
gulp.task('feature', function() { return inc('minor'); })
gulp.task('release', function() { return inc('major'); })
gulp.task('pushtags', function(done){
exec('git push --follow-tags',function (err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
done();
});
})
gulp.task('buildocker', function(done){
exec('docker build -t nblotti/login:v'+pjson.version+' .', {maxBuffer: 4096 * 500},function (err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
done();
}
);
})
gulp.task('pushdocker', function(done){
exec('docker push nblotti/login:v'+ pjson.version, {maxBuffer: 4096 * 500},function (err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
console.log('pushed version : ' + pjson.version);
done();
});
})
gulp.task('rollupdate', function(done){
exec('./kubectl rolling-update nblotti-login --image=nblotti/login:v'+ pjson.version +' --server="http://master:8080"',function (err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
console.log('pushed version : ' + pjson.version);
done();
});
})
gulp.task('gradleclean', function (cb) {
exec('gradle clean', function (err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
cb(err);
});
})
gulp.task('gradlebuild', function (cb) {
exec('gradle build', function (err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
cb(err);
});
})
gulp.task('gradlebootRun', function (cb) {
exec('gradle bootRun', function (err, stdout, stderr) {
console.log(stdout);
console.log(stderr);
cb(err);
});
})
gulp.task('bu', gulp.series('feature','pushtags','buildocker','pushdocker','rollupdate'));
|
import {jsDocument} from './unit/helpers/document';
import {initReporter} from './unit/helpers/reporter';
import requireHacker from 'require-hacker';
requireHacker.hook('png', () => 'module.exports = ""');
initReporter();
describe('JS Unit tests', () => {
beforeAll(() => {
});
jsDocument(true);
//require('./unit/application/application.unit');
//require('./unit/workspace/workspace.unit');
//require('./unit/page/page.unit');
//require('./unit/widget/widget.unit');
require('./unit/flow/flow.unit');
}); |
import './style.sss'
import MovableController from './directive'
import MovableBox from './MovableBox.vue'
const install = function (Vue) {
Vue.directive('Movable', MovableController)
Vue.directive('MovableController', MovableController)
Vue.component('MovableBox', MovableBox)
}
if (typeof window !== 'undefined' && window.Vue) {
window.Movable = MovableController
window.MovableController = MovableController
window.MovableBox = MovableBox
Vue.use(install)
}
export default{
install,
MovableBox,
MovableController
}
|
import { LOCATION_CHANGE } from 'react-router-redux';
import { map, omit } from 'lodash';
import { fork, put, select, call, takeLatest, take, cancel } from 'redux-saga/effects';
import request from 'utils/request';
import { generateSchema } from 'utils/schema';
import { getModelEntriesSucceeded, loadedModels, updateSchema } from './actions';
import { GET_MODEL_ENTRIES, LOAD_MODELS, LOADED_MODELS } from './constants';
import { makeSelectModels } from './selectors';
export function* modelEntriesGet(action) {
try {
const requestUrl = `/content-manager/explorer/${action.modelName}/count${action.source !== undefined ? `?source=${action.source}`: ''}`;
const response = yield call(request, requestUrl, { method: 'GET' });
yield put(getModelEntriesSucceeded(response.count));
} catch(error) {
strapi.notification.error('content-manager.error.model.fetch');
}
}
export const generateMenu = function () {
return request(`/content-manager/models`, {
method: 'GET',
})
.then(response => generateSchema(response))
.then(displayedModels => {
return [{
name: 'Content Types',
links: map(omit(displayedModels, 'plugins'), (model, key) => ({
label: model.labelPlural || model.label || key,
destination: key,
})),
}];
})
.catch((error) => {
strapi.notification.error('content-manager.error.model.fetch');
throw Error(error);
});
};
export function* getModels() {
try {
const response = yield call(request, `/content-manager/models`, {
method: 'GET',
});
yield put(loadedModels(response));
} catch (err) {
strapi.notification.error('content-manager.error.model.fetch');
}
}
export function* modelsLoaded() {
const models = yield select(makeSelectModels());
let schema;
try {
schema = generateSchema(models);
} catch (err) {
strapi.notification.error('content-manager.error.schema.generation');
throw new Error(err);
}
yield put(updateSchema(schema));
}
// Individual exports for testing
export function* defaultSaga() {
const loadModelsWatcher = yield fork(takeLatest, LOAD_MODELS, getModels);
const loadedModelsWatcher = yield fork(takeLatest, LOADED_MODELS, modelsLoaded);
const loadEntriesWatcher = yield fork(takeLatest, GET_MODEL_ENTRIES, modelEntriesGet);
yield take(LOCATION_CHANGE);
yield cancel(loadModelsWatcher);
yield cancel(loadedModelsWatcher);
yield cancel(loadEntriesWatcher);
}
// All sagas to be loaded
export default defaultSaga;
|
import React, { Component } from "react";
import ReactDOM from "react-dom";
import Typography from "@material-ui/core/Typography";
import IconButton from "@material-ui/core/IconButton";
import AvPause from "@material-ui/icons/pause";
import AvPlayArrow from "@material-ui/icons/PlayArrow";
import AvReplay from "@material-ui/icons/replay";
import { formatMilliseconds } from "../core/time";
class Remaining extends Component {
constructor(props, context) {
super(props);
this.internalTimer = {
startNew: opts => {
this.props.timer.startNew(opts);
},
onTick: ms => {
this.props.timer.onTick(ms);
},
stopActive: () => {
this.props.timer.stopActive();
}
};
this.state = {
allottedMilliseconds: props.allottedMilliseconds || 0,
remainingMilliseconds: props.allottedMilliseconds || 0,
started: false
};
this.start = this.start.bind(this);
this.pause = this.pause.bind(this);
this.restart = this.restart.bind(this);
this.renderStateMilliseconds = this.renderStateMilliseconds.bind(this);
this.renderPlaybackButton = this.renderPlaybackButton.bind(this);
this.finish = this.finish.bind(this);
this.tick = this.tick.bind(this);
this.hasFreshAllottedMilliseconds = this.hasFreshAllottedMilliseconds.bind(
this
);
this.height = "24px";
}
componentWillReceiveProps(newProps) {
this.initiateStartFromNewPropsIfNecessary(newProps);
}
hasFreshAllottedMilliseconds(props) {
if (props.allottedMilliseconds === undefined) return false;
if (props.allottedMilliseconds <= 0) return false;
if (props.allottedMilliseconds != this.state.allottedMilliseconds) {
return true;
}
if (props.started) return true;
return false;
}
initiateStartFromNewPropsIfNecessary(newProps) {
if (this.hasFreshAllottedMilliseconds(newProps)) {
this.setState(
{
allottedMilliseconds: newProps.allottedMilliseconds,
remainingMilliseconds: newProps.allottedMilliseconds
},
() => {
// Prevents going to sleep when dragged to the
// beginning but not yet released
if (newProps.started) {
this.start();
} else {
this.pause();
}
}
);
}
}
tick(milliseconds) {
this.setState({
remainingMilliseconds: milliseconds
});
}
start() {
let remaining = this.state.remainingMilliseconds;
if (remaining === 0) {
remaining = this.state.allottedMilliseconds;
}
this.setState({
remainingMilliseconds: remaining,
started: true
});
this.internalTimer.startNew({
callback: this.finish,
milliseconds: remaining,
tickInterval: 1000,
onTick: this.tick
});
}
pause() {
this.setState({
started: false
});
this.internalTimer.stopActive();
}
restart() {
this.pause();
this.setState(
{
remainingMilliseconds: this.state.allottedMilliseconds
},
() => {
this.start();
}
);
}
finish() {
this.setState(
{
remainingMilliseconds: this.state.allottedMilliseconds,
started: false
},
() => {
this.pause();
this.props.onFinished();
}
);
}
renderStateMilliseconds() {
return (
<span
style={{
display: "inline-block",
height: this.height,
lineHeight: this.height
}}
>
{formatMilliseconds(this.state.remainingMilliseconds)}
</span>
);
}
render() {
const buttonStyle = {
color: this.props.theme.palette.text.secondary,
height: this.height,
width: this.height
};
const iconStyle = {
height: this.height,
width: this.height,
margin: "0",
padding: "0",
position: "absolute"
};
return (
<div style={{ marginTop: "5px" }}>
<Typography
color="textSecondary"
style={{
padding: "0",
margin: "0",
position: "relative",
width: "80px",
margin: "0 auto",
height: this.height,
whiteSpace: "nowrap"
}}
>
{this.renderPlaybackButton(buttonStyle, iconStyle)}
{this.renderStateMilliseconds()}
{this.renderRestartButton(buttonStyle, iconStyle)}
</Typography>
</div>
);
}
renderRestartButton(buttonStyle, iconStyle) {
const disabled =
this.state.started ||
this.state.remainingMilliseconds === this.state.allottedMilliseconds;
const containerStyle = {
position: "absolute",
right: "-30px",
top: "0",
display: "inline-block"
};
const button = (
<IconButton
id="restart"
tooltip="Restart"
onClick={this.restart}
style={buttonStyle}
>
<AvReplay style={iconStyle} />
</IconButton>
);
return <span style={containerStyle}>{button}</span>;
}
renderPlaybackButton(buttonStyle, iconStyle) {
const isStarted = this.state.started;
let button;
if (isStarted) {
button = (
<IconButton
id="pause"
tooltip="Pause"
onClick={this.pause}
style={buttonStyle}
>
<AvPause style={iconStyle} />
</IconButton>
);
} else {
button = (
<IconButton
id="start"
tooltip="Start"
onClick={this.start}
style={buttonStyle}
>
<AvPlayArrow style={iconStyle} />
</IconButton>
);
}
const containerStyle = {
position: "absolute",
left: "-30px",
top: "0",
display: "inline-block"
};
return <span style={containerStyle}>{button}</span>;
}
}
Remaining.defaultProps = {
onFinished: () => {}
};
export default Remaining;
|
var require = {
baseUrl: '/src/',
paths: {
handlebars: '../bower_components/handlebars/handlebars',
text: '../bower_components/text/text',
underscore: '../bower_components/underscore/underscore',
backbone: '../bower_components/backbone/backbone',
marionette: '../bower_components/backbone.marionette/lib/backbone.marionette',
jquery: '../bower_components/jquery/dist/jquery',
localStorage: '../bower_components/backbone.localStorage/backbone.localStorage',
mocha: '../bower_components/mocha/mocha',
chai: '../bower_components/chai/chai',
"backbone.radio": "../bower_components/backbone.radio/build/backbone.radio",
when: '../bower_components/when/when',
masonry: '../bower_components/masonry/dist/masonry.pkgd',
imagesLoaded: '../bower_components/imagesloaded/imagesloaded.pkgd',
/* Foundation */
'foundation.core': '../bower_components/foundation/js/foundation/foundation',
'foundation.abide': '../bower_components/foundation/js/foundation/foundation.abide',
'foundation.accordion': '../bower_components/foundation/js/foundation/foundation.accordion',
'foundation.alert': '../bower_components/foundation/js/foundation/foundation.alert',
'foundation.clearing': '../bower_components/foundation/js/foundation/foundation.clearing',
'foundation.dropdown': '../bower_components/foundation/js/foundation/foundation.dropdown',
'foundation.equalizer': '../bower_components/foundation/js/foundation/foundation.equalizer',
'foundation.interchange': '../bower_components/foundation/js/foundation/foundation.interchange',
'foundation.joyride': '../bower_components/foundation/js/foundation/foundation.joyride',
'foundation.magellan': '../bower_components/foundation/js/foundation/foundation.magellan',
'foundation.offcanvas': '../bower_components/foundation/js/foundation/foundation.offcanvas',
'foundation.orbit': '../bower_components/foundation/js/foundation/foundation.orbit',
'foundation.reveal': '../bower_components/foundation/js/foundation/foundation.reveal',
'foundation.tab': '../bower_components/foundation/js/foundation/foundation.tab',
'foundation.tooltip': '../bower_components/foundation/js/foundation/foundation.tooltip',
'foundation.topbar': '../bower_components/foundation/js/foundation/foundation.topbar',
'fastclick': '../bower_components/foundation/js/vendor/fastclick',
'modernizr': '../bower_components/foundation/js/vendor/modernizr',
'placeholder': '../bower_components/foundation/js/vendor/placeholder'
},
shim: {
underscore: {
exports: '_'
},
backbone: {
exports: 'Backbone',
deps: ['jquery', 'underscore']
},
marionette: {
exports: 'Backbone.Marionette',
deps: ['backbone']
},
mocha: {
exports: 'mocha'
},
chai: {
exports: 'chai'
},
when: {
exports: 'When'
},
/* Foundation */
'foundation.core': {
deps: [
'jquery',
'modernizr'
],
exports: 'Foundation'
},
'foundation.abide': {
deps: [
'foundation.core'
]
},
'foundation.accordion': {
deps: [
'foundation.core'
]
},
'foundation.alert': {
deps: [
'foundation.core'
]
},
'foundation.clearing': {
deps: [
'foundation.core'
]
},
'foundation.dropdown': {
deps: [
'foundation.core'
]
},
'foundation.equalizer': {
deps: [
'foundation.core'
]
},
'foundation.interchange': {
deps: [
'foundation.core'
]
},
'foundation.joyride': {
deps: [
'foundation.core',
'jquery.cookie'
]
},
'foundation.magellan': {
deps: [
'foundation.core'
]
},
'foundation.offcanvas': {
deps: [
'foundation.core'
]
},
'foundation.orbit': {
deps: [
'foundation.core'
]
},
'foundation.reveal': {
deps: [
'foundation.core'
]
},
'foundation.tab': {
deps: [
'foundation.core'
]
},
'foundation.tooltip': {
deps: [
'foundation.core'
]
},
'foundation.topbar': {
deps: [
'foundation.core'
]
},
/* Vendor Scripts */
'jquery.cookie': {
deps: [
'jquery'
]
},
'fastclick': {
exports: 'FastClick'
},
'modernizr': {
exports: 'Modernizr'
},
'placeholder': {
exports: 'Placeholders'
},
handlebars: {
exports: 'Handlebars'
}
},
packages: [
{
name: 'hbs',
location: '../bower_components/requirejs-hbs',
main: 'hbs'
}, {
name: 'when',
location: '../bower_components/when',
main: 'when'
}
],
deps: ['jquery', 'underscore']
}; |
'use strict'
var Action = require('../action')
var request = require('request')
var util = require('util')
var table = require('../nodeTable')
var YAML = require('js-yaml')
var endpoint = process.env.CHIX_API_SERVER || 'https://api.chix.io/'
function dump (node, env) {
if (env.json) {
console.log(JSON.stringify(node, null, 2))
} else if (env.yaml) {
console.log(YAML.dump(node))
} else {
console.log(table(node))
}
}
function ListAction () {}
util.inherits(ListAction, Action)
ListAction.prototype.execute = function () {
var self = this
var args = this.env.parent.rawArgs
var ns = args[3]
var name = args[4]
var url = ['nodes']
var single
if (ns) {
url.push(ns)
}
if (name) {
single = true
url.push(name)
}
request(endpoint + url.join('/'), function (err, response, body) {
if (err) {
console.log(err)
} else if (response.statusCode === 200) {
var json = JSON.parse(body)
if (single) {
dump(json, self.env)
} else {
Object.keys(json).forEach(function (key) {
Object.keys(json[key]).forEach(function (name) {
var node = json[key][name]
console.log(table(node))
})
})
}
} else {
console.log(response.statusCode + ': Failed to retrieve list')
}
})
}
module.exports = ListAction
|
function customersController($scope,$http,$filter) {
$http.get("http://localhost:8080/service/usuario")
.success(function(response) {$scope.usuarios = response;});
$scope.edit = true;
$scope.error = false;
$scope.incomplete = false;
$scope.showFormUser = false;
$scope.editUser = function(id) {
if (id == 'new') {
$scope.showFormUser = true;
$scope.edit = true;
$scope.incomplete = true;
$scope.id = '';
$scope.usuario = '';
$scope.email = '';
$scope.senha = '';
$scope.dataCriacao = '';
} else if(id == 'cancel') {
$scope.showFormUser = false;
$scope.edit = true;
$scope.incomplete = true;
$scope.id = '';
$scope.usuario = '';
$scope.email = '';
$scope.senha = '';
$scope.dataCriacao = '';
} else {
$scope.showFormUser = true;
$scope.edit = false;
$scope.incomplete = false;
$scope.id = $scope.usuarios[id-1].id;
$scope.usuario = $scope.usuarios[id-1].usuario;
$scope.email = $scope.usuarios[id-1].email;
$scope.senha = $scope.usuarios[id-1].senha;
$scope.dataCriacao = $filter('date')($scope.usuarios[id-1].dataCriacao, 'dd/MM/yyyy HH:mm:ss')
}
};
//Não acessando length ao iniciar o programa e dá erro depois que corre campos para ????????
//$scope.test = function() {
// if ($scope.edit && (!$scope.usuario.length ||
// !$scope.email.length ||
// !$scope.senha.length)) {
// $scope.incomplete = true;
// } else {
// $scope.incomplete = false;
// }
//};
//
//$scope.$watch('usuario',function() {$scope.test();});
//$scope.$watch('email',function() {$scope.test();});
//$scope.$watch('senha', function() {$scope.test();});
$scope.saveUser = function() {
var dataObj = {
usuario : $scope.usuario,
email : $scope.email,
senha : $scope.senha,
dataCriacao: new Date()
};
var res = $http.post('http://localhost:8080/service/usuario', dataObj);
res.success(function(data, status, headers, config) {
$scope.message = data;
});
res.error(function(data, status, headers, config) {
alert( "failure message: " + JSON.stringify({data: data}));
});
}
}
|
var model = {nrOfGenes : 9,
size : 100,
genome : [],
lines : []};
var line = {x1 : 0, y1 : 0, x2 : 0, y2 : 0};
function initModel() {
model.size = Math.min(width, height) / 4;
model.genome[1] = model.genome[2] = model.genome[3] = model.genome[4] = model.genome[5] = 1;
model.genome[6] = model.genome[7] = -1;
model.genome[8] = 7;
}
function drawModel() {
var l = [];
var ox = 0, oy = 0;
var br = [];
var bs = [];
var lx = [];
var ly = [];
var stp = 1, nux = 0, nuy = 0, mag;
br[1] = 1;
bs[1] = 0;
lx[1] = ox;
ly[1] = oy;
var mi = 0;
while (true) {
mi ++;
//model.lines = l;
while (br[stp] == 0)
if (--stp == 0) {
model.lines = l;
return;
}
mag = model.size / (stp + 8);
switch (br[stp]) {
case 1:
nux = 0;
nuy = -model.genome[1] * mag;
break;
case 2:
nux = model.genome[2] * mag;
nuy = -model.genome[3] * mag;
break;
case 3:
nux = model.genome[4] * mag;
nuy = 0;
break;
case 4:
nux = model.genome[5] * mag;
nuy = -model.genome[6] * mag;
break;
case 5:
nux = 0;
nuy = -model.genome[7] * mag;
break;
case 6:
nux = -model.genome[5] * mag;
nuy = -model.genome[6] * mag;
break;
case 7:
nux = -model.genome[4] * mag;
nuy = 0;
break;
case 8:
nux = -model.genome[2] * mag;
nuy = -model.genome[3] * mag;
break;
default:
// throw "BUG";
console.print("BUG " + br[stp]);
break;
}
// Next branch.
br[stp + 1] = br[stp] + 1;
bs[stp + 1] = br[stp] - 1;
if (br[stp + 1] >= 9)
br[stp + 1] = 1;
if (bs[stp + 1] == 0)
bs[stp + 1] = 8;
lx[stp + 1] = lx[stp] + nux;
ly[stp + 1] = ly[stp] + nuy;
l.push({x1 : lx[stp], y1 : ly[stp], x2 : lx[stp + 1], y2 : ly[stp + 1]});
br[stp] = bs[stp];
bs[stp] = 0;
if (++stp >= model.genome[8])
br[stp] = bs[stp] = 0;
}
}
function perturbModel() {
var hi = 5;
var lo = -hi;
var n1 = model.nrOfGenes - 1;
var knobSpeed = [];
for (var i = 0; i < model.nrOfGenes; ++i) {
// Select a speed of -2, -1, 1, or 2.
knobSpeed[i] = Math.round(Math.random() * 2) + 1;
if (Math.random() < 0.5)
knobSpeed[i] = -knobSpeed[i];
}
// Randomly select a knob and try moving it in the same
// direction and at the same speed as before.
var idx = Math.round(Math.random() * model.nrOfGenes);
var willBe = model.genome[idx] + knobSpeed[idx];
var loc = (idx == 8) ? 5 : lo;
var hic = (idx == 8) ? 9 : hi;
if (willBe < loc) // Hit the low end, so bounce up.
model.genome[idx] += (knobSpeed[idx] = Math.round(Math.random() * 2) + 1);
else if (willBe > hic) // Hit the high end, so bounce down.
model.genome[idx] += (knobSpeed[idx] = Math.round(Math.random() * 2) - 2);
else
// Common case: haven't reached either end.
model.genome[idx] = willBe;
}
function step() {
drawModel();
perturbModel();
}
var width;
var height;
var context;
function createImageData(canvasId) {
var element = document.getElementById(canvasId);
context = element.getContext("2d");
element.width = $(document).width();
element.height = $(document).height();
width = element.width;
height = element.height;
}
function paint() {
context.clearRect(0, 0, width, height);
context.save();
context.fillStyle = "#ffffff";
context.strokeStyle = "rgb(" + 0 + "," + 0 + "," + 0 + ")";
context.fillRect(0, 0, width, height);
context.translate(width / 2, height / 2);
context.beginPath();
var lines = model.lines;
for (var i = 0; i < lines.length; i++) {
context.moveTo(lines[i].x1, lines[i].y1);
context.lineTo(lines[i].x2, lines[i].y2);
}
context.stroke();
context.restore();
} |
import faker from 'faker';
import colors from 'colors';
import log from 'npmlog';
import models from '../../models';
export const roles = [
{ title: 'Admin' },
{ title: 'Author' },
{ title: 'mai' }
];
export const users = [
{
firstname: 'Admin',
lastname: 'Admin',
username: 'Admin',
email: 'admin@admin.com',
password: 'password',
roleId: 1
}, {
firstname: 'Mai',
lastname: 'Iles',
username: 'maiiles',
email: 'mai@iles.com',
password: 'password',
roleId: 1
}, {
firstname: 'Hope',
lastname: 'Tommy',
username: 'hopetommy',
email: 'hope@tommy.com',
password: 'password',
roleId: 2
}, {
firstname: 'dami',
lastname: 'peju',
username: 'damipeju',
email: 'dami@peju.com',
password: 'password',
roleId: 2
}
];
export const documents = [{
title: 'seed document test',
content: faker.lorem.paragraph(),
access: 0,
ownerId: 1,
roleId: 1
}, {
title: 'public seed document test',
content: faker.lorem.paragraph(),
access: -1,
ownerId: 1,
roleId: 1
}, {
title: 'user 4 seed document test',
content: faker.lorem.paragraph(),
access: -1,
ownerId: 3,
roleId: 2
}];
const seeds = () => models.sequelize.sync({ force: true })
.then(() => models.Role.bulkCreate(roles)
.then(() => {
log.info('Users created'.cyan);
return models.User.bulkCreate(users, { individualHooks: true })
.then(() => {
log.info('Documents created'.yellow);
return models.Document.bulkCreate(documents);
});
}));
export default seeds;
|
// avoid circular dependency when using jest.mock()
let fetch;
try {
// note that jest is not a global, but is injected somehow into
// the environment. So we can't be safe and check for global.jest
// Hence the try/catch
fetch = jest.requireActual('node-fetch'); //eslint-disable-line no-undef
} catch (e) {
fetch = require('node-fetch');
}
const Request = fetch.Request;
const Response = fetch.Response;
const Headers = fetch.Headers;
const Stream = require('stream');
const FetchMock = require('./lib/index');
const http = require('http');
const { setUrlImplementation } = require('./lib/request-utils');
setUrlImplementation(require('whatwg-url').URL);
FetchMock.global = global;
FetchMock.statusTextMap = http.STATUS_CODES;
FetchMock.Stream = Stream;
FetchMock.config = Object.assign(FetchMock.config, {
Promise,
Request,
Response,
Headers,
fetch,
});
module.exports = FetchMock.createInstance();
|
// Saves options to chrome.storage
function save_options() {
var url_kintone = document.getElementById('option_kintone').value;
var url0 = document.getElementById('url0').value;
var command1 = document.getElementById('command1').value;
var detail1 = document.getElementById('detail1').value;
var url1 = document.getElementById('url1').value;
var command2 = document.getElementById('command2').value;
var detail2 = document.getElementById('detail2').value;
var url2 = document.getElementById('url2').value;
var command3 = document.getElementById('command3').value;
var detail3 = document.getElementById('detail3').value;
var url3 = document.getElementById('url3').value;
var command4 = document.getElementById('command4').value;
var detail4 = document.getElementById('detail4').value;
var url4 = document.getElementById('url4').value;
chrome.storage.sync.set({
url : url_kintone,
url0 : url0,
command1: command1,
detail1 : detail1,
url1 : url1,
command2: command2,
detail2 : detail2,
url2 : url2,
command3: command3,
detail3 : detail3,
url3 : url3,
command4: command4,
detail4 : detail4,
url4 : url4
}, function() {
// Update status to let user know options were saved.
var status = document.getElementById('status');
status.textContent = 'Options saved.';
setTimeout(function() {
status.textContent = '';
}, 750);
});
}
// Restores select box and checkbox state using the preferences
// stored in chrome.storage.
function restore_options() {
chrome.storage.sync.get({
url : '',
url0 : '',
command1: '',
detail1 : '',
url1 : '',
command2: '',
detail2 : '',
url2 : '',
command3: '',
detail3 : '',
url3 : '',
command4: '',
detail4 : '',
url4 : ''
}, function(items) {
document.getElementById('option_kintone').value = items.url;
document.getElementById('url0').value = items.url0;
document.getElementById('command1').value = items.command1;
document.getElementById('detail1').value = items.detail1;
document.getElementById('url1').value = items.url1;
document.getElementById('command2').value = items.command2;
document.getElementById('detail2').value = items.detail2;
document.getElementById('url2').value = items.url2;
document.getElementById('command3').value = items.command3;
document.getElementById('detail3').value = items.detail3;
document.getElementById('url3').value = items.url3;
document.getElementById('command4').value = items.command4;
document.getElementById('detail4').value = items.detail4;
document.getElementById('url4').value = items.url4;
});
}
document.addEventListener('DOMContentLoaded', restore_options);
document.getElementById('save').addEventListener('click',save_options); |
import styled from 'styled-components/native';
export default styled.View`
background-color: #FFF;
border-radius: 10px;
overflow: hidden;
width: 100%;
`;
|
//
// officegen: pptx charts
//
// Please refer to README.md for this module's documentations.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
module.exports = {
null: function (options) {
return {
'c:chartSpace': {
'@xmlns:c': 'http://schemas.openxmlformats.org/drawingml/2006/chart',
'@xmlns:a': 'http://schemas.openxmlformats.org/drawingml/2006/main',
'@xmlns:r':
'http://schemas.openxmlformats.org/officeDocument/2006/relationships',
'c:lang': { '@val': 'en-US' },
'c:date1904': { '@val': '1' },
'c:chart': {}
}
}
},
bar: function (options) {
options = options || {}
return {
'c:chartSpace': {
'@xmlns:c': 'http://schemas.openxmlformats.org/drawingml/2006/chart',
'@xmlns:a': 'http://schemas.openxmlformats.org/drawingml/2006/main',
'@xmlns:r':
'http://schemas.openxmlformats.org/officeDocument/2006/relationships',
'c:lang': { '@val': 'en-US' },
'c:chart': {
'c:plotArea': {
'c:layout': {},
'c:barChart': {
'c:barDir': { '@val': 'bar' },
'c:grouping': { '@val': 'clustered' },
'#text': [
{ 'c:axId': { '@val': '64451712' } },
{ 'c:axId': { '@val': '64453248' } }
]
},
'c:catAx': {
'c:axId': { '@val': '64451712' },
'c:scaling': {
'c:orientation': {
'@val': options.catAxisReverseOrder ? 'maxMin' : 'minMax'
}
},
'c:axPos': { '@val': 'l' },
'c:tickLblPos': { '@val': 'nextTo' },
'c:crossAx': { '@val': '64453248' },
'c:crosses': { '@val': 'autoZero' },
'c:auto': { '@val': '1' },
'c:lblAlgn': { '@val': 'ctr' },
'c:lblOffset': { '@val': '100' }
},
'c:valAx': {
'c:axId': { '@val': '64453248' },
'c:scaling': {
'c:orientation': { '@val': 'minMax' }
},
'c:axPos': { '@val': 'b' },
// "c:majorGridlines": {},
'c:numFmt': {
'@formatCode': 'General',
'@sourceLinked': '1'
},
'c:tickLblPos': { '@val': 'nextTo' },
'c:crossAx': { '@val': '64451712' },
'c:crosses': {
'@val': options.valAxisCrossAtMaxCategory ? 'max' : 'autoZero'
},
'c:crossBetween': { '@val': 'between' }
}
},
'c:legend': {
'c:legendPos': { '@val': 'r' },
'c:layout': {}
},
'c:plotVisOnly': { '@val': '1' }
},
'c:txPr': {
'a:bodyPr': {},
'a:lstStyle': {},
'a:p': {
'a:pPr': {
'a:defRPr': { '@sz': '1800' }
},
'a:endParaRPr': { '@lang': 'en-US' }
}
},
'c:externalData': { '@r:id': 'rId1' }
}
}
},
column: function (options) {
options = options || {}
return {
'c:chartSpace': {
'@xmlns:c': 'http://schemas.openxmlformats.org/drawingml/2006/chart',
'@xmlns:a': 'http://schemas.openxmlformats.org/drawingml/2006/main',
'@xmlns:r':
'http://schemas.openxmlformats.org/officeDocument/2006/relationships',
'c:lang': { '@val': 'en-US' },
'c:date1904': { '@val': '1' },
'c:chart': {
'c:plotArea': {
'c:layout': {},
'c:barChart': {
'c:barDir': { '@val': 'col' },
'c:grouping': { '@val': 'clustered' },
'c:overlap': { '@val': options.overlap || '0' },
'c:gapWidth': { '@val': options.gapWidth || '150' },
'#text': [
{ 'c:axId': { '@val': '64451712' } },
{ 'c:axId': { '@val': '64453248' } }
]
},
'c:catAx': {
'c:axId': { '@val': '64451712' },
'c:scaling': {
'c:orientation': {
'@val': options.catAxisReverseOrder ? 'maxMin' : 'minMax'
}
},
'c:axPos': { '@val': 'l' },
'c:tickLblPos': { '@val': 'nextTo' },
'c:crossAx': { '@val': '64453248' },
'c:crosses': { '@val': 'autoZero' },
'c:auto': { '@val': '1' },
'c:lblAlgn': { '@val': 'ctr' },
'c:lblOffset': { '@val': '100' }
},
'c:valAx': {
'c:axId': { '@val': '64453248' },
'c:scaling': {
'c:orientation': { '@val': 'minMax' }
},
'c:axPos': { '@val': 'b' },
// "c:majorGridlines": {},
'c:numFmt': {
'@formatCode': 'General',
'@sourceLinked': '1'
},
'c:tickLblPos': { '@val': 'nextTo' },
'c:crossAx': { '@val': '64451712' },
'c:crosses': {
'@val': options.valAxisCrossAtMaxCategory ? 'max' : 'autoZero'
},
'c:crossBetween': { '@val': 'between' }
}
},
'c:legend': {
'c:legendPos': { '@val': 'r' },
'c:layout': {}
},
'c:plotVisOnly': { '@val': '1' }
},
'c:txPr': {
'a:bodyPr': {},
'a:lstStyle': {},
'a:p': {
'a:pPr': {
'a:defRPr': { '@sz': '1800' }
},
'a:endParaRPr': { '@lang': 'en-US' }
}
},
'c:externalData': { '@r:id': 'rId1' }
}
}
},
'stacked-column': function (options) {
options = options || {}
return {
'c:chartSpace': {
'@xmlns:c': 'http://schemas.openxmlformats.org/drawingml/2006/chart',
'@xmlns:a': 'http://schemas.openxmlformats.org/drawingml/2006/main',
'@xmlns:r':
'http://schemas.openxmlformats.org/officeDocument/2006/relationships',
'c:lang': { '@val': 'en-US' },
'c:date1904': { '@val': '1' },
'c:chart': {
'c:plotArea': {
'c:layout': {},
'c:barChart': {
'c:barDir': { '@val': 'col' },
'c:grouping': { '@val': 'stacked' },
'c:overlap': { '@val': options.overlap || '100' },
'c:gapWidth': { '@val': options.gapWidth || '25' },
'#text': [
{ 'c:axId': { '@val': '64451712' } },
{ 'c:axId': { '@val': '64453248' } }
]
},
'c:catAx': {
'c:axId': { '@val': '64451712' },
'c:scaling': {
'c:orientation': {
'@val': options.catAxisReverseOrder ? 'maxMin' : 'minMax'
}
},
'c:axPos': { '@val': 'l' },
'c:tickLblPos': { '@val': 'nextTo' },
'c:crossAx': { '@val': '64453248' },
'c:crosses': { '@val': 'autoZero' },
'c:auto': { '@val': '1' },
'c:lblAlgn': { '@val': 'ctr' },
'c:lblOffset': { '@val': '100' }
},
'c:valAx': {
'c:axId': { '@val': '64453248' },
'c:scaling': {
'c:orientation': { '@val': 'minMax' }
},
'c:axPos': { '@val': 'b' },
// "c:majorGridlines": {},
'c:numFmt': {
'@formatCode': 'General',
'@sourceLinked': '1'
},
'c:tickLblPos': { '@val': 'nextTo' },
'c:crossAx': { '@val': '64451712' },
'c:crosses': {
'@val': options.valAxisCrossAtMaxCategory ? 'max' : 'autoZero'
},
'c:crossBetween': { '@val': 'between' }
}
},
'c:legend': {
'c:legendPos': { '@val': 'r' },
'c:layout': {}
},
'c:plotVisOnly': { '@val': '1' }
},
'c:txPr': {
'a:bodyPr': {},
'a:lstStyle': {},
'a:p': {
'a:pPr': {
'a:defRPr': { '@sz': '1800' }
},
'a:endParaRPr': { '@lang': 'en-US' }
}
},
'c:externalData': { '@r:id': 'rId1' }
}
}
},
'group-bar': function (options) {
options = options || {}
return {
'c:chartSpace': {
'@xmlns:c': 'http://schemas.openxmlformats.org/drawingml/2006/chart',
'@xmlns:a': 'http://schemas.openxmlformats.org/drawingml/2006/main',
'@xmlns:r':
'http://schemas.openxmlformats.org/officeDocument/2006/relationships',
'c:lang': { '@val': 'en-US' },
'c:date1904': { '@val': '1' },
'c:chart': {
'c:plotArea': {
'c:layout': {},
'c:barChart': {
'c:barDir': { '@val': 'bar' },
'c:grouping': { '@val': 'stacked' },
'c:overlap': { '@val': options.overlap || '100' },
'c:gapWidth': { '@val': options.gapWidth || '150' },
'#text': [
{ 'c:axId': { '@val': '64451712' } },
{ 'c:axId': { '@val': '64453248' } }
]
},
'c:catAx': {
'c:axId': { '@val': '64451712' },
'c:scaling': {
'c:orientation': {
'@val': options.catAxisReverseOrder ? 'maxMin' : 'minMax'
}
},
'c:axPos': { '@val': 'l' },
'c:tickLblPos': { '@val': 'nextTo' },
'c:crossAx': { '@val': '64453248' },
'c:crosses': { '@val': 'autoZero' },
'c:auto': { '@val': '1' },
'c:lblAlgn': { '@val': 'ctr' },
'c:lblOffset': { '@val': '100' }
},
'c:valAx': {
'c:axId': { '@val': '64453248' },
'c:scaling': {
'c:orientation': { '@val': 'minMax' }
},
'c:axPos': { '@val': 'b' },
// "c:majorGridlines": {},
'c:numFmt': {
'@formatCode': 'General',
'@sourceLinked': '1'
},
'c:tickLblPos': { '@val': 'nextTo' },
'c:crossAx': { '@val': '64451712' },
'c:crosses': {
'@val': options.valAxisCrossAtMaxCategory ? 'max' : 'autoZero'
},
'c:crossBetween': { '@val': 'between' }
}
},
'c:legend': {
'c:legendPos': { '@val': 'r' },
'c:layout': {}
},
'c:plotVisOnly': { '@val': '1' }
},
'c:txPr': {
'a:bodyPr': {},
'a:lstStyle': {},
'a:p': {
'a:pPr': {
'a:defRPr': { '@sz': '1800' }
},
'a:endParaRPr': { '@lang': 'en-US' }
}
},
'c:externalData': { '@r:id': 'rId1' }
}
}
},
pie: function (options) {
options = options || {}
return {
'c:chartSpace': {
'@xmlns:c': 'http://schemas.openxmlformats.org/drawingml/2006/chart',
'@xmlns:a': 'http://schemas.openxmlformats.org/drawingml/2006/main',
'@xmlns:r':
'http://schemas.openxmlformats.org/officeDocument/2006/relationships',
'c:lang': { '@val': 'en-US' },
'c:chart': {
'c:title': {
'c:layout': {}
},
'c:plotArea': {
'c:layout': {},
'c:pieChart': {
'c:varyColors': { '@val': '1' },
'c:firstSliceAng': { '@val': '0' },
'#text': []
}
},
'c:legend': {
'c:legendPos': { '@val': 'r' },
'c:layout': {}
},
'c:plotVisOnly': { '@val': '1' }
},
'c:txPr': {
'a:bodyPr': {},
'a:lstStyle': {},
'a:p': {
'a:pPr': {
'a:defRPr': { '@sz': '1800' }
},
'a:endParaRPr': { '@lang': 'en-US' }
}
},
'c:externalData': { '@r:id': 'rId1' }
}
}
},
line: function (options) {
options = options || {}
return {
'c:chartSpace': {
'@xmlns:c': 'http://schemas.openxmlformats.org/drawingml/2006/chart',
'@xmlns:a': 'http://schemas.openxmlformats.org/drawingml/2006/main',
'@xmlns:r':
'http://schemas.openxmlformats.org/officeDocument/2006/relationships',
'c:lang': { '@val': 'en-US' },
'c:chart': {
'c:plotArea': {
'c:layout': {},
'c:lineChart': {
'c:grouping': { '@val': 'standard' },
'#text': [
{ 'c:axId': { '@val': '64451712' } },
{ 'c:axId': { '@val': '64453248' } }
]
},
'c:catAx': {
'c:axId': { '@val': '64451712' },
'c:scaling': {
'c:orientation': {
'@val': options.catAxisReverseOrder ? 'maxMin' : 'minMax'
}
},
'c:axPos': { '@val': 'l' },
'c:tickLblPos': { '@val': 'nextTo' },
'c:crossAx': { '@val': '64453248' },
'c:crosses': { '@val': 'autoZero' },
'c:auto': { '@val': '1' },
'c:lblAlgn': { '@val': 'ctr' },
'c:lblOffset': { '@val': '100' }
},
'c:valAx': {
'c:axId': { '@val': '64453248' },
'c:scaling': {
'c:orientation': { '@val': 'minMax' }
},
'c:axPos': { '@val': 'b' },
// "c:majorGridlines": {},
'c:numFmt': {
'@formatCode': 'General',
'@sourceLinked': '1'
},
'c:tickLblPos': { '@val': 'nextTo' },
'c:crossAx': { '@val': '64451712' },
'c:crosses': {
'@val': options.valAxisCrossAtMaxCategory ? 'max' : 'autoZero'
},
'c:crossBetween': { '@val': 'between' }
}
},
'c:legend': {
'c:legendPos': { '@val': 'r' },
'c:layout': {}
},
'c:plotVisOnly': { '@val': '1' }
},
'c:txPr': {
'a:bodyPr': {},
'a:lstStyle': {},
'a:p': {
'a:pPr': {
'a:defRPr': { '@sz': '1800' }
},
'a:endParaRPr': { '@lang': 'en-US' }
}
},
'c:externalData': { '@r:id': 'rId1' }
}
}
},
area: function (options) {
options = options || {}
return {
'c:chartSpace': {
'@xmlns:c': 'http://schemas.openxmlformats.org/drawingml/2006/chart',
'@xmlns:a': 'http://schemas.openxmlformats.org/drawingml/2006/main',
'@xmlns:r':
'http://schemas.openxmlformats.org/officeDocument/2006/relationships',
'c:lang': { '@val': 'en-US' },
'c:chart': {
'c:plotArea': {
'c:layout': {},
'c:areaChart': {
'c:grouping': { '@val': 'standard' },
'#text': [
{ 'c:axId': { '@val': '64451712' } },
{ 'c:axId': { '@val': '64453248' } }
]
},
'c:catAx': {
'c:axId': { '@val': '64451712' },
'c:scaling': {
'c:orientation': {
'@val': options.catAxisReverseOrder ? 'maxMin' : 'minMax'
}
},
'c:axPos': { '@val': 'l' },
'c:tickLblPos': { '@val': 'nextTo' },
'c:crossAx': { '@val': '64453248' },
'c:crosses': { '@val': 'autoZero' },
'c:auto': { '@val': '1' },
'c:lblAlgn': { '@val': 'ctr' },
'c:lblOffset': { '@val': '100' }
},
'c:valAx': {
'c:axId': { '@val': '64453248' },
'c:scaling': {
'c:orientation': { '@val': 'minMax' }
},
'c:axPos': { '@val': 'b' },
// "c:majorGridlines": {},
'c:numFmt': {
'@formatCode': 'General',
'@sourceLinked': '1'
},
'c:tickLblPos': { '@val': 'nextTo' },
'c:crossAx': { '@val': '64451712' },
'c:crosses': {
'@val': options.valAxisCrossAtMaxCategory ? 'max' : 'autoZero'
},
'c:crossBetween': { '@val': 'between' }
}
},
'c:legend': {
'c:legendPos': { '@val': 'r' },
'c:layout': {}
},
'c:plotVisOnly': { '@val': '1' }
},
'c:txPr': {
'a:bodyPr': {},
'a:lstStyle': {},
'a:p': {
'a:pPr': {
'a:defRPr': { '@sz': '1800' }
},
'a:endParaRPr': { '@lang': 'en-US' }
}
},
'c:externalData': { '@r:id': 'rId1' }
}
}
},
doughnut: function (options) {
options = options || {}
return {
'c:chartSpace': {
'@xmlns:c': 'http://schemas.openxmlformats.org/drawingml/2006/chart',
'@xmlns:a': 'http://schemas.openxmlformats.org/drawingml/2006/main',
'@xmlns:r':
'http://schemas.openxmlformats.org/officeDocument/2006/relationships',
'c:lang': { '@val': 'en-US' },
'c:chart': {
'c:title': {
'c:layout': {}
},
'c:plotArea': {
'c:layout': {},
'c:doughnutChart': {
'c:varyColors': { '@val': '1' },
'c:firstSliceAng': { '@val': '0' },
'c:holeSize': { '@val': '75' },
'#text': []
}
},
'c:legend': {
'c:legendPos': { '@val': 'r' },
'c:layout': {}
},
'c:plotVisOnly': { '@val': '1' }
},
'c:txPr': {
'a:bodyPr': {},
'a:lstStyle': {},
'a:p': {
'a:pPr': {
'a:defRPr': { '@sz': '1800' }
},
'a:endParaRPr': { '@lang': 'en-US' }
}
},
'c:externalData': { '@r:id': 'rId1' }
}
}
}
}
|
/**
* @author Slayvin / http://slayvin.net
*/
import {
Color,
LinearEncoding,
LinearFilter,
MathUtils,
Matrix4,
Mesh,
PerspectiveCamera,
Plane,
RGBFormat,
ShaderMaterial,
UniformsUtils,
Vector3,
Vector4,
WebGLRenderTarget
} from "../../../build/three.module.js";
var Reflector = function ( geometry, options ) {
Mesh.call( this, geometry );
this.type = 'Reflector';
var scope = this;
options = options || {};
var color = ( options.color !== undefined ) ? new Color( options.color ) : new Color( 0x7F7F7F );
var textureWidth = options.textureWidth || 512;
var textureHeight = options.textureHeight || 512;
var clipBias = options.clipBias || 0;
var shader = options.shader || Reflector.ReflectorShader;
var encoding = options.encoding !== undefined ? options.encoding : LinearEncoding;
//
var reflectorPlane = new Plane();
var normal = new Vector3();
var reflectorWorldPosition = new Vector3();
var cameraWorldPosition = new Vector3();
var rotationMatrix = new Matrix4();
var lookAtPosition = new Vector3( 0, 0, - 1 );
var clipPlane = new Vector4();
var view = new Vector3();
var target = new Vector3();
var q = new Vector4();
var textureMatrix = new Matrix4();
var virtualCamera = new PerspectiveCamera();
var parameters = {
minFilter: LinearFilter,
magFilter: LinearFilter,
format: RGBFormat,
stencilBuffer: false,
encoding: encoding
};
var renderTarget = new WebGLRenderTarget( textureWidth, textureHeight, parameters );
if ( ! MathUtils.isPowerOfTwo( textureWidth ) || ! MathUtils.isPowerOfTwo( textureHeight ) ) {
renderTarget.texture.generateMipmaps = false;
}
var material = new ShaderMaterial( {
uniforms: UniformsUtils.clone( shader.uniforms ),
fragmentShader: shader.fragmentShader,
vertexShader: shader.vertexShader
} );
material.uniforms[ "tDiffuse" ].value = renderTarget.texture;
material.uniforms[ "color" ].value = color;
material.uniforms[ "textureMatrix" ].value = textureMatrix;
this.material = material;
this.onBeforeRender = function ( renderer, scene, camera ) {
reflectorWorldPosition.setFromMatrixPosition( scope.matrixWorld );
cameraWorldPosition.setFromMatrixPosition( camera.matrixWorld );
rotationMatrix.extractRotation( scope.matrixWorld );
normal.set( 0, 0, 1 );
normal.applyMatrix4( rotationMatrix );
view.subVectors( reflectorWorldPosition, cameraWorldPosition );
// Avoid rendering when reflector is facing away
if ( view.dot( normal ) > 0 ) return;
view.reflect( normal ).negate();
view.add( reflectorWorldPosition );
rotationMatrix.extractRotation( camera.matrixWorld );
lookAtPosition.set( 0, 0, - 1 );
lookAtPosition.applyMatrix4( rotationMatrix );
lookAtPosition.add( cameraWorldPosition );
target.subVectors( reflectorWorldPosition, lookAtPosition );
target.reflect( normal ).negate();
target.add( reflectorWorldPosition );
virtualCamera.position.copy( view );
virtualCamera.up.set( 0, 1, 0 );
virtualCamera.up.applyMatrix4( rotationMatrix );
virtualCamera.up.reflect( normal );
virtualCamera.lookAt( target );
virtualCamera.far = camera.far; // Used in WebGLBackground
virtualCamera.updateMatrixWorld();
virtualCamera.projectionMatrix.copy( camera.projectionMatrix );
// Update the texture matrix
textureMatrix.set(
0.5, 0.0, 0.0, 0.5,
0.0, 0.5, 0.0, 0.5,
0.0, 0.0, 0.5, 0.5,
0.0, 0.0, 0.0, 1.0
);
textureMatrix.multiply( virtualCamera.projectionMatrix );
textureMatrix.multiply( virtualCamera.matrixWorldInverse );
textureMatrix.multiply( scope.matrixWorld );
// Now update projection matrix with new clip plane, implementing code from: http://www.terathon.com/code/oblique.html
// Paper explaining this technique: http://www.terathon.com/lengyel/Lengyel-Oblique.pdf
reflectorPlane.setFromNormalAndCoplanarPoint( normal, reflectorWorldPosition );
reflectorPlane.applyMatrix4( virtualCamera.matrixWorldInverse );
clipPlane.set( reflectorPlane.normal.x, reflectorPlane.normal.y, reflectorPlane.normal.z, reflectorPlane.constant );
var projectionMatrix = virtualCamera.projectionMatrix;
q.x = ( Math.sign( clipPlane.x ) + projectionMatrix.elements[ 8 ] ) / projectionMatrix.elements[ 0 ];
q.y = ( Math.sign( clipPlane.y ) + projectionMatrix.elements[ 9 ] ) / projectionMatrix.elements[ 5 ];
q.z = - 1.0;
q.w = ( 1.0 + projectionMatrix.elements[ 10 ] ) / projectionMatrix.elements[ 14 ];
// Calculate the scaled plane vector
clipPlane.multiplyScalar( 2.0 / clipPlane.dot( q ) );
// Replacing the third row of the projection matrix
projectionMatrix.elements[ 2 ] = clipPlane.x;
projectionMatrix.elements[ 6 ] = clipPlane.y;
projectionMatrix.elements[ 10 ] = clipPlane.z + 1.0 - clipBias;
projectionMatrix.elements[ 14 ] = clipPlane.w;
// Render
scope.visible = false;
var currentRenderTarget = renderer.getRenderTarget();
var currentXrEnabled = renderer.xr.enabled;
var currentShadowAutoUpdate = renderer.shadowMap.autoUpdate;
renderer.xr.enabled = false; // Avoid camera modification
renderer.shadowMap.autoUpdate = false; // Avoid re-computing shadows
renderer.setRenderTarget( renderTarget );
renderer.state.buffers.depth.setMask( true ); // make sure the depth buffer is writable so it can be properly cleared, see #18897
if ( renderer.autoClear === false ) renderer.clear();
renderer.render( scene, virtualCamera );
renderer.xr.enabled = currentXrEnabled;
renderer.shadowMap.autoUpdate = currentShadowAutoUpdate;
renderer.setRenderTarget( currentRenderTarget );
// Restore viewport
var viewport = camera.viewport;
if ( viewport !== undefined ) {
renderer.state.viewport( viewport );
}
scope.visible = true;
};
this.getRenderTarget = function () {
return renderTarget;
};
};
Reflector.prototype = Object.create( Mesh.prototype );
Reflector.prototype.constructor = Reflector;
Reflector.ReflectorShader = {
uniforms: {
'color': {
value: null
},
'tDiffuse': {
value: null
},
'textureMatrix': {
value: null
}
},
vertexShader: [
'uniform mat4 textureMatrix;',
'varying vec4 vUv;',
'void main() {',
' vUv = textureMatrix * vec4( position, 1.0 );',
' gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );',
'}'
].join( '\n' ),
fragmentShader: [
'uniform vec3 color;',
'uniform sampler2D tDiffuse;',
'varying vec4 vUv;',
'float blendOverlay( float base, float blend ) {',
' return( base < 0.5 ? ( 2.0 * base * blend ) : ( 1.0 - 2.0 * ( 1.0 - base ) * ( 1.0 - blend ) ) );',
'}',
'vec3 blendOverlay( vec3 base, vec3 blend ) {',
' return vec3( blendOverlay( base.r, blend.r ), blendOverlay( base.g, blend.g ), blendOverlay( base.b, blend.b ) );',
'}',
'void main() {',
' vec4 base = texture2DProj( tDiffuse, vUv );',
' gl_FragColor = vec4( blendOverlay( base.rgb, color ), 1.0 );',
'}'
].join( '\n' )
};
export { Reflector };
|
'use strict';
// my first comment
var assert = require('assert');
var tasks = require('../task/01-strings-tasks');
it.optional = require('../extensions/it-optional');
describe('01-strings-tasks', function() {
it.optional('concatenateStrings should return concatenation of two strings', function() {
assert.equal('aabb', tasks.concatenateStrings('aa','bb'));
assert.equal('aa', tasks.concatenateStrings('aa',''));
assert.equal('bb', tasks.concatenateStrings('','bb'));
});
it.optional('getStringLength should return the length of string', function() {
assert.equal(5, tasks.getStringLength('aaaaa'), "'aaaaa' length should be 5");
assert.equal(0, tasks.getStringLength(''), "'' length should be 0");
});
it.optional('getStringFromTemplate should create a string from template using given parameters', function() {
assert.equal('Hello, John Doe!', tasks.getStringFromTemplate('John','Doe'));
assert.equal('Hello, Chuck Norris!', tasks.getStringFromTemplate('Chuck','Norris'));
});
it.optional('getFirstChar should return the first char from given string', function() {
assert.equal('J', tasks.getFirstChar('John Doe'));
assert.equal('c', tasks.getFirstChar('cat'));
});
it.optional('extractNameFromTemplate should parse the name from given string', function() {
assert.equal('John Doe', tasks.extractNameFromTemplate('Hello, John Doe!'));
assert.equal('Chuck Norris', tasks.extractNameFromTemplate('Hello, Chuck Norris!'));
});
it.optional('removeLeadingAndTrailingWhitespaces should remove leading and trailing whitespaces from the string', function() {
assert.equal('Abracadabra', tasks.removeLeadingAndTrailingWhitespaces(' Abracadabra'));
assert.equal('cat', tasks.removeLeadingAndTrailingWhitespaces('cat'));
assert.equal('Hello, World!', tasks.removeLeadingAndTrailingWhitespaces('\tHello, World! '));
});
it.optional('repeatString should repeat string specified number of times', function() {
assert.equal('AAAAA', tasks.repeatString('A', 5));
assert.equal('catcatcat', tasks.repeatString('cat', 3));
});
it.optional('removeFirstOccurrences should remove all specified values from a string', function() {
assert.equal('To be or to be', tasks.removeFirstOccurrences('To be or not to be', ' not'));
assert.equal('I like legs', tasks.removeFirstOccurrences('I like legends', 'end'));
assert.equal('ABAB', tasks.removeFirstOccurrences('ABABAB','BA'));
});
it.optional('unbracketTag should remove first and last angle brackets from tag string', function() {
assert.equal('div', tasks.unbracketTag('<div>'));
assert.equal('span', tasks.unbracketTag('<span>'));
assert.equal('a', tasks.unbracketTag('<a>'));
});
it.optional('convertToUpperCase should convert all chars from specified string into upper case', function() {
assert.equal('THUNDERSTRUCK', tasks.convertToUpperCase('Thunderstruck'));
assert.equal('ABCDEFGHIJKLMNOPQRSTUVWXYZ', tasks.convertToUpperCase('abcdefghijklmnopqrstuvwxyz'));
});
it.optional('extractEmails should extract emails from string list delimeted by semicolons', function() {
assert.deepEqual(
['angus.young@gmail.com', 'brian.johnson@hotmail.com', 'bon.scott@yahoo.com'],
tasks.extractEmails('angus.young@gmail.com;brian.johnson@hotmail.com;bon.scott@yahoo.com')
);
assert.deepEqual(
['info@gmail.com'],
tasks.extractEmails('info@gmail.com')
);
});
it.optional('getRectangleString should return the string reprentation of rectangle with specified size', function() {
assert.equal(
'┌────┐\n'+
'│ │\n'+
'│ │\n'+
'└────┘\n',
tasks.getRectangleString(6, 4)
);
assert.deepEqual(
'┌┐\n'+
'└┘\n',
tasks.getRectangleString(2, 2)
);
assert.deepEqual(
'┌──────────┐\n'+
'│ │\n'+
'└──────────┘\n',
tasks.getRectangleString(12, 3)
);
});
it.optional('encodeToRot13 should encode-decode string using ROT13 algorithm', function() {
assert.equal('uryyb', tasks.encodeToRot13('hello'));
assert.equal('Jul qvq gur puvpxra pebff gur ebnq?', tasks.encodeToRot13('Why did the chicken cross the road?'));
assert.equal('To get to the other side!', tasks.encodeToRot13('Gb trg gb gur bgure fvqr!'));
assert.equal(
'NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm',
tasks.encodeToRot13('ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz')
);
});
it.optional('isString should return true if argument ia a string', function() {
assert.equal(false, tasks.isString(), "undefined");
assert.equal(false, tasks.isString(null), "null");
assert.equal(false, tasks.isString([]), "[]");
assert.equal(true, tasks.isString('test'), "test");
assert.equal(true, tasks.isString(new String('test')), "new String('test')");
});
it.optional('getCardId should return the index of card in the initial deck', function() {
[
'A♣','2♣','3♣','4♣','5♣','6♣','7♣','8♣','9♣','10♣','J♣','Q♣','K♣',
'A♦','2♦','3♦','4♦','5♦','6♦','7♦','8♦','9♦','10♦','J♦','Q♦','K♦',
'A♥','2♥','3♥','4♥','5♥','6♥','7♥','8♥','9♥','10♥','J♥','Q♥','K♥',
'A♠','2♠','3♠','4♠','5♠','6♠','7♠','8♠','9♠','10♠','J♠','Q♠','K♠'
].forEach((val, index) => {
assert.equal(
index,
tasks.getCardId(val),
`Invalid id for card '${val}':`
)
});
});
});
|
/*
* jQuery UI Datepicker 1.8.18
*
* Copyright 2011, AUTHORS.txt (http://jqueryui.com/about)
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* http://docs.jquery.com/UI/Datepicker
*
* Depends:
* jquery.ui.core.js
*/
(function( $, undefined ) {
$.extend($.ui, { datepicker: { version: "1.8.18" } });
var PROP_NAME = 'datepicker';
var dpuuid = new Date().getTime();
var instActive;
/* Date picker manager.
Use the singleton instance of this class, $.datepicker, to interact with the date picker.
Settings for (groups of) date pickers are maintained in an instance object,
allowing multiple different settings on the same page. */
function Datepicker() {
this.debug = false; // Change this to true to start debugging
this._curInst = null; // The current instance in use
this._keyEvent = false; // If the last event was a key event
this._disabledInputs = []; // List of date picker inputs that have been disabled
this._datepickerShowing = false; // True if the popup picker is showing , false if not
this._inDialog = false; // True if showing within a "dialog", false if not
this._mainDivId = 'ui-datepicker-div'; // The ID of the main datepicker division
this._inlineClass = 'ui-datepicker-inline'; // The name of the inline marker class
this._appendClass = 'ui-datepicker-append'; // The name of the append marker class
this._triggerClass = 'ui-datepicker-trigger'; // The name of the trigger marker class
this._dialogClass = 'ui-datepicker-dialog'; // The name of the dialog marker class
this._disableClass = 'ui-datepicker-disabled'; // The name of the disabled covering marker class
this._unselectableClass = 'ui-datepicker-unselectable'; // The name of the unselectable cell marker class
this._currentClass = 'ui-datepicker-current-day'; // The name of the current day marker class
this._dayOverClass = 'ui-datepicker-days-cell-over'; // The name of the day hover marker class
this.regional = []; // Available regional settings, indexed by language code
this.regional[''] = { // Default regional settings
closeText: 'Done', // Display text for close link
prevText: 'Prev', // Display text for previous month link
nextText: 'Next', // Display text for next month link
currentText: 'Today', // Display text for current month link
monthNames: ['January','February','March','April','May','June',
'July','August','September','October','November','December'], // Names of months for drop-down and formatting
monthNamesShort: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], // For formatting
dayNames: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'], // For formatting
dayNamesShort: ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'], // For formatting
dayNamesMin: ['Su','Mo','Tu','We','Th','Fr','Sa'], // Column headings for days starting at Sunday
weekHeader: 'Wk', // Column header for week of the year
//dateFormat: 'mm/dd/yy', // See format options on parseDate
dateFormat: 'dd/mm/yy',
firstDay: 0, // The first day of the week, Sun = 0, Mon = 1, ...
isRTL: false, // True if right-to-left language, false if left-to-right
showMonthAfterYear: false, // True if the year select precedes month, false for month then year
yearSuffix: '' // Additional text to append to the year in the month headers
};
this._defaults = { // Global defaults for all the date picker instances
showOn: 'focus', // 'focus' for popup on focus,
// 'button' for trigger button, or 'both' for either
showAnim: 'fadeIn', // Name of jQuery animation for popup
showOptions: {}, // Options for enhanced animations
defaultDate: null, // Used when field is blank: actual date,
// +/-number for offset from today, null for today
appendText: '', // Display text following the input box, e.g. showing the format
buttonText: '...', // Text for trigger button
buttonImage: '', // URL for trigger button image
buttonImageOnly: false, // True if the image appears alone, false if it appears on a button
hideIfNoPrevNext: false, // True to hide next/previous month links
// if not applicable, false to just disable them
navigationAsDateFormat: false, // True if date formatting applied to prev/today/next links
gotoCurrent: false, // True if today link goes back to current selection instead
changeMonth: false, // True if month can be selected directly, false if only prev/next
changeYear: false, // True if year can be selected directly, false if only prev/next
yearRange: 'c-10:c+10', // Range of years to display in drop-down,
// either relative to today's year (-nn:+nn), relative to currently displayed year
// (c-nn:c+nn), absolute (nnnn:nnnn), or a combination of the above (nnnn:-n)
showOtherMonths: false, // True to show dates in other months, false to leave blank
selectOtherMonths: false, // True to allow selection of dates in other months, false for unselectable
showWeek: false, // True to show week of the year, false to not show it
calculateWeek: this.iso8601Week, // How to calculate the week of the year,
// takes a Date and returns the number of the week for it
shortYearCutoff: '+10', // Short year values < this are in the current century,
// > this are in the previous century,
// string value starting with '+' for current year + value
minDate: null, // The earliest selectable date, or null for no limit
maxDate: null, // The latest selectable date, or null for no limit
duration: 'fast', // Duration of display/closure
beforeShowDay: null, // Function that takes a date and returns an array with
// [0] = true if selectable, false if not, [1] = custom CSS class name(s) or '',
// [2] = cell title (optional), e.g. $.datepicker.noWeekends
beforeShow: null, // Function that takes an input field and
// returns a set of custom settings for the date picker
onSelect: null, // Define a callback function when a date is selected
onChangeMonthYear: null, // Define a callback function when the month or year is changed
onClose: null, // Define a callback function when the datepicker is closed
numberOfMonths: 1, // Number of months to show at a time
showCurrentAtPos: 0, // The position in multipe months at which to show the current month (starting at 0)
stepMonths: 1, // Number of months to step back/forward
stepBigMonths: 12, // Number of months to step back/forward for the big links
altField: '', // Selector for an alternate field to store selected dates into
altFormat: '', // The date format to use for the alternate field
constrainInput: true, // The input is constrained by the current date format
showButtonPanel: false, // True to show button panel, false to not show it
autoSize: false, // True to size the input for the date format, false to leave as is
disabled: false // The initial disabled state
};
$.extend(this._defaults, this.regional['']);
this.dpDiv = bindHover($('<div id="' + this._mainDivId + '" class="ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>'));
}
$.extend(Datepicker.prototype, {
/* Class name added to elements to indicate already configured with a date picker. */
markerClassName: 'hasDatepicker',
//Keep track of the maximum number of rows displayed (see #7043)
maxRows: 4,
/* Debug logging (if enabled). */
log: function () {
if (this.debug)
console.log.apply('', arguments);
},
// TODO rename to "widget" when switching to widget factory
_widgetDatepicker: function() {
return this.dpDiv;
},
/* Override the default settings for all instances of the date picker.
@param settings object - the new settings to use as defaults (anonymous object)
@return the manager object */
setDefaults: function(settings) {
extendRemove(this._defaults, settings || {});
return this;
},
/* Attach the date picker to a jQuery selection.
@param target element - the target input field or division or span
@param settings object - the new settings to use for this date picker instance (anonymous) */
_attachDatepicker: function(target, settings) {
// check for settings on the control itself - in namespace 'date:'
var inlineSettings = null;
for (var attrName in this._defaults) {
var attrValue = target.getAttribute('date:' + attrName);
if (attrValue) {
inlineSettings = inlineSettings || {};
try {
inlineSettings[attrName] = eval(attrValue);
} catch (err) {
inlineSettings[attrName] = attrValue;
}
}
}
var nodeName = target.nodeName.toLowerCase();
var inline = (nodeName == 'div' || nodeName == 'span');
if (!target.id) {
this.uuid += 1;
target.id = 'dp' + this.uuid;
}
var inst = this._newInst($(target), inline);
inst.settings = $.extend({}, settings || {}, inlineSettings || {});
if (nodeName == 'input') {
this._connectDatepicker(target, inst);
} else if (inline) {
this._inlineDatepicker(target, inst);
}
},
/* Create a new instance object. */
_newInst: function(target, inline) {
var id = target[0].id.replace(/([^A-Za-z0-9_-])/g, '\\\\$1'); // escape jQuery meta chars
return {id: id, input: target, // associated target
selectedDay: 0, selectedMonth: 0, selectedYear: 0, // current selection
drawMonth: 0, drawYear: 0, // month being drawn
inline: inline, // is datepicker inline or not
dpDiv: (!inline ? this.dpDiv : // presentation div
bindHover($('<div class="' + this._inlineClass + ' ui-datepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all"></div>')))};
},
/* Attach the date picker to an input field. */
_connectDatepicker: function(target, inst) {
var input = $(target);
inst.append = $([]);
inst.trigger = $([]);
if (input.hasClass(this.markerClassName))
return;
this._attachments(input, inst);
input.addClass(this.markerClassName).keydown(this._doKeyDown).
keypress(this._doKeyPress).keyup(this._doKeyUp).
bind("setData.datepicker", function(event, key, value) {
inst.settings[key] = value;
}).bind("getData.datepicker", function(event, key) {
return this._get(inst, key);
});
this._autoSize(inst);
$.data(target, PROP_NAME, inst);
//If disabled option is true, disable the datepicker once it has been attached to the input (see ticket #5665)
if( inst.settings.disabled ) {
this._disableDatepicker( target );
}
},
/* Make attachments based on settings. */
_attachments: function(input, inst) {
var appendText = this._get(inst, 'appendText');
var isRTL = this._get(inst, 'isRTL');
if (inst.append)
inst.append.remove();
if (appendText) {
inst.append = $('<span class="' + this._appendClass + '">' + appendText + '</span>');
input[isRTL ? 'before' : 'after'](inst.append);
}
input.unbind('focus', this._showDatepicker);
if (inst.trigger)
inst.trigger.remove();
var showOn = this._get(inst, 'showOn');
if (showOn == 'focus' || showOn == 'both') // pop-up date picker when in the marked field
input.focus(this._showDatepicker);
if (showOn == 'button' || showOn == 'both') { // pop-up date picker when button clicked
var buttonText = this._get(inst, 'buttonText');
var buttonImage = this._get(inst, 'buttonImage');
inst.trigger = $(this._get(inst, 'buttonImageOnly') ?
$('<img/>').addClass(this._triggerClass).
attr({ src: buttonImage, alt: buttonText, title: buttonText }) :
$('<button type="button"></button>').addClass(this._triggerClass).
html(buttonImage == '' ? buttonText : $('<img/>').attr(
{ src:buttonImage, alt:buttonText, title:buttonText })));
input[isRTL ? 'before' : 'after'](inst.trigger);
inst.trigger.click(function() {
if ($.datepicker._datepickerShowing && $.datepicker._lastInput == input[0])
$.datepicker._hideDatepicker();
else if ($.datepicker._datepickerShowing && $.datepicker._lastInput != input[0]) {
$.datepicker._hideDatepicker();
$.datepicker._showDatepicker(input[0]);
} else
$.datepicker._showDatepicker(input[0]);
return false;
});
}
},
/* Apply the maximum length for the date format. */
_autoSize: function(inst) {
if (this._get(inst, 'autoSize') && !inst.inline) {
var date = new Date(2009, 12 - 1, 20); // Ensure double digits
var dateFormat = this._get(inst, 'dateFormat');
if (dateFormat.match(/[DM]/)) {
var findMax = function(names) {
var max = 0;
var maxI = 0;
for (var i = 0; i < names.length; i++) {
if (names[i].length > max) {
max = names[i].length;
maxI = i;
}
}
return maxI;
};
date.setMonth(findMax(this._get(inst, (dateFormat.match(/MM/) ?
'monthNames' : 'monthNamesShort'))));
date.setDate(findMax(this._get(inst, (dateFormat.match(/DD/) ?
'dayNames' : 'dayNamesShort'))) + 20 - date.getDay());
}
inst.input.attr('size', this._formatDate(inst, date).length);
}
},
/* Attach an inline date picker to a div. */
_inlineDatepicker: function(target, inst) {
var divSpan = $(target);
if (divSpan.hasClass(this.markerClassName))
return;
divSpan.addClass(this.markerClassName).append(inst.dpDiv).
bind("setData.datepicker", function(event, key, value){
inst.settings[key] = value;
}).bind("getData.datepicker", function(event, key){
return this._get(inst, key);
});
$.data(target, PROP_NAME, inst);
this._setDate(inst, this._getDefaultDate(inst), true);
this._updateDatepicker(inst);
this._updateAlternate(inst);
//If disabled option is true, disable the datepicker before showing it (see ticket #5665)
if( inst.settings.disabled ) {
this._disableDatepicker( target );
}
// Set display:block in place of inst.dpDiv.show() which won't work on disconnected elements
// http://bugs.jqueryui.com/ticket/7552 - A Datepicker created on a detached div has zero height
inst.dpDiv.css( "display", "block" );
},
/* Pop-up the date picker in a "dialog" box.
@param input element - ignored
@param date string or Date - the initial date to display
@param onSelect function - the function to call when a date is selected
@param settings object - update the dialog date picker instance's settings (anonymous object)
@param pos int[2] - coordinates for the dialog's position within the screen or
event - with x/y coordinates or
leave empty for default (screen centre)
@return the manager object */
_dialogDatepicker: function(input, date, onSelect, settings, pos) {
var inst = this._dialogInst; // internal instance
if (!inst) {
this.uuid += 1;
var id = 'dp' + this.uuid;
this._dialogInput = $('<input type="text" id="' + id +
'" style="position: absolute; top: -100px; width: 0px; z-index: -10;"/>');
this._dialogInput.keydown(this._doKeyDown);
$('body').append(this._dialogInput);
inst = this._dialogInst = this._newInst(this._dialogInput, false);
inst.settings = {};
$.data(this._dialogInput[0], PROP_NAME, inst);
}
extendRemove(inst.settings, settings || {});
date = (date && date.constructor == Date ? this._formatDate(inst, date) : date);
this._dialogInput.val(date);
this._pos = (pos ? (pos.length ? pos : [pos.pageX, pos.pageY]) : null);
if (!this._pos) {
var browserWidth = document.documentElement.clientWidth;
var browserHeight = document.documentElement.clientHeight;
var scrollX = document.documentElement.scrollLeft || document.body.scrollLeft;
var scrollY = document.documentElement.scrollTop || document.body.scrollTop;
this._pos = // should use actual width/height below
[(browserWidth / 2) - 100 + scrollX, (browserHeight / 2) - 150 + scrollY];
}
// move input on screen for focus, but hidden behind dialog
this._dialogInput.css('left', (this._pos[0] + 20) + 'px').css('top', this._pos[1] + 'px');
inst.settings.onSelect = onSelect;
this._inDialog = true;
this.dpDiv.addClass(this._dialogClass);
this._showDatepicker(this._dialogInput[0]);
if ($.blockUI)
$.blockUI(this.dpDiv);
$.data(this._dialogInput[0], PROP_NAME, inst);
return this;
},
/* Detach a datepicker from its control.
@param target element - the target input field or division or span */
_destroyDatepicker: function(target) {
var $target = $(target);
var inst = $.data(target, PROP_NAME);
if (!$target.hasClass(this.markerClassName)) {
return;
}
var nodeName = target.nodeName.toLowerCase();
$.removeData(target, PROP_NAME);
if (nodeName == 'input') {
inst.append.remove();
inst.trigger.remove();
$target.removeClass(this.markerClassName).
unbind('focus', this._showDatepicker).
unbind('keydown', this._doKeyDown).
unbind('keypress', this._doKeyPress).
unbind('keyup', this._doKeyUp);
} else if (nodeName == 'div' || nodeName == 'span')
$target.removeClass(this.markerClassName).empty();
},
/* Enable the date picker to a jQuery selection.
@param target element - the target input field or division or span */
_enableDatepicker: function(target) {
var $target = $(target);
var inst = $.data(target, PROP_NAME);
if (!$target.hasClass(this.markerClassName)) {
return;
}
var nodeName = target.nodeName.toLowerCase();
if (nodeName == 'input') {
target.disabled = false;
inst.trigger.filter('button').
each(function() { this.disabled = false; }).end().
filter('img').css({opacity: '1.0', cursor: ''});
}
else if (nodeName == 'div' || nodeName == 'span') {
var inline = $target.children('.' + this._inlineClass);
inline.children().removeClass('ui-state-disabled');
inline.find("select.ui-datepicker-month, select.ui-datepicker-year").
removeAttr("disabled");
}
this._disabledInputs = $.map(this._disabledInputs,
function(value) { return (value == target ? null : value); }); // delete entry
},
/* Disable the date picker to a jQuery selection.
@param target element - the target input field or division or span */
_disableDatepicker: function(target) {
var $target = $(target);
var inst = $.data(target, PROP_NAME);
if (!$target.hasClass(this.markerClassName)) {
return;
}
var nodeName = target.nodeName.toLowerCase();
if (nodeName == 'input') {
target.disabled = true;
inst.trigger.filter('button').
each(function() { this.disabled = true; }).end().
filter('img').css({opacity: '0.5', cursor: 'default'});
}
else if (nodeName == 'div' || nodeName == 'span') {
var inline = $target.children('.' + this._inlineClass);
inline.children().addClass('ui-state-disabled');
inline.find("select.ui-datepicker-month, select.ui-datepicker-year").
attr("disabled", "disabled");
}
this._disabledInputs = $.map(this._disabledInputs,
function(value) { return (value == target ? null : value); }); // delete entry
this._disabledInputs[this._disabledInputs.length] = target;
},
/* Is the first field in a jQuery collection disabled as a datepicker?
@param target element - the target input field or division or span
@return boolean - true if disabled, false if enabled */
_isDisabledDatepicker: function(target) {
if (!target) {
return false;
}
for (var i = 0; i < this._disabledInputs.length; i++) {
if (this._disabledInputs[i] == target)
return true;
}
return false;
},
/* Retrieve the instance data for the target control.
@param target element - the target input field or division or span
@return object - the associated instance data
@throws error if a jQuery problem getting data */
_getInst: function(target) {
try {
return $.data(target, PROP_NAME);
}
catch (err) {
throw 'Missing instance data for this datepicker';
}
},
/* Update or retrieve the settings for a date picker attached to an input field or division.
@param target element - the target input field or division or span
@param name object - the new settings to update or
string - the name of the setting to change or retrieve,
when retrieving also 'all' for all instance settings or
'defaults' for all global defaults
@param value any - the new value for the setting
(omit if above is an object or to retrieve a value) */
_optionDatepicker: function(target, name, value) {
var inst = this._getInst(target);
if (arguments.length == 2 && typeof name == 'string') {
return (name == 'defaults' ? $.extend({}, $.datepicker._defaults) :
(inst ? (name == 'all' ? $.extend({}, inst.settings) :
this._get(inst, name)) : null));
}
var settings = name || {};
if (typeof name == 'string') {
settings = {};
settings[name] = value;
}
if (inst) {
if (this._curInst == inst) {
this._hideDatepicker();
}
var date = this._getDateDatepicker(target, true);
var minDate = this._getMinMaxDate(inst, 'min');
var maxDate = this._getMinMaxDate(inst, 'max');
extendRemove(inst.settings, settings);
// reformat the old minDate/maxDate values if dateFormat changes and a new minDate/maxDate isn't provided
if (minDate !== null && settings['dateFormat'] !== undefined && settings['minDate'] === undefined)
inst.settings.minDate = this._formatDate(inst, minDate);
if (maxDate !== null && settings['dateFormat'] !== undefined && settings['maxDate'] === undefined)
inst.settings.maxDate = this._formatDate(inst, maxDate);
this._attachments($(target), inst);
this._autoSize(inst);
this._setDate(inst, date);
this._updateAlternate(inst);
this._updateDatepicker(inst);
}
},
// change method deprecated
_changeDatepicker: function(target, name, value) {
this._optionDatepicker(target, name, value);
},
/* Redraw the date picker attached to an input field or division.
@param target element - the target input field or division or span */
_refreshDatepicker: function(target) {
var inst = this._getInst(target);
if (inst) {
this._updateDatepicker(inst);
}
},
/* Set the dates for a jQuery selection.
@param target element - the target input field or division or span
@param date Date - the new date */
_setDateDatepicker: function(target, date) {
var inst = this._getInst(target);
if (inst) {
this._setDate(inst, date);
this._updateDatepicker(inst);
this._updateAlternate(inst);
}
},
/* Get the date(s) for the first entry in a jQuery selection.
@param target element - the target input field or division or span
@param noDefault boolean - true if no default date is to be used
@return Date - the current date */
_getDateDatepicker: function(target, noDefault) {
var inst = this._getInst(target);
if (inst && !inst.inline)
this._setDateFromField(inst, noDefault);
return (inst ? this._getDate(inst) : null);
},
/* Handle keystrokes. */
_doKeyDown: function(event) {
var inst = $.datepicker._getInst(event.target);
var handled = true;
var isRTL = inst.dpDiv.is('.ui-datepicker-rtl');
inst._keyEvent = true;
if ($.datepicker._datepickerShowing)
switch (event.keyCode) {
case 9: $.datepicker._hideDatepicker();
handled = false;
break; // hide on tab out
case 13: var sel = $('td.' + $.datepicker._dayOverClass + ':not(.' +
$.datepicker._currentClass + ')', inst.dpDiv);
if (sel[0])
$.datepicker._selectDay(event.target, inst.selectedMonth, inst.selectedYear, sel[0]);
var onSelect = $.datepicker._get(inst, 'onSelect');
if (onSelect) {
var dateStr = $.datepicker._formatDate(inst);
// trigger custom callback
onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]);
}
else
$.datepicker._hideDatepicker();
return false; // don't submit the form
break; // select the value on enter
case 27: $.datepicker._hideDatepicker();
break; // hide on escape
case 33: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
-$.datepicker._get(inst, 'stepBigMonths') :
-$.datepicker._get(inst, 'stepMonths')), 'M');
break; // previous month/year on page up/+ ctrl
case 34: $.datepicker._adjustDate(event.target, (event.ctrlKey ?
+$.datepicker._get(inst, 'stepBigMonths') :
+$.datepicker._get(inst, 'stepMonths')), 'M');
break; // next month/year on page down/+ ctrl
case 35: if (event.ctrlKey || event.metaKey) $.datepicker._clearDate(event.target);
handled = event.ctrlKey || event.metaKey;
break; // clear on ctrl or command +end
case 36: if (event.ctrlKey || event.metaKey) $.datepicker._gotoToday(event.target);
handled = event.ctrlKey || event.metaKey;
break; // current on ctrl or command +home
case 37: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? +1 : -1), 'D');
handled = event.ctrlKey || event.metaKey;
// -1 day on ctrl or command +left
if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ?
-$.datepicker._get(inst, 'stepBigMonths') :
-$.datepicker._get(inst, 'stepMonths')), 'M');
// next month/year on alt +left on Mac
break;
case 38: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, -7, 'D');
handled = event.ctrlKey || event.metaKey;
break; // -1 week on ctrl or command +up
case 39: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, (isRTL ? -1 : +1), 'D');
handled = event.ctrlKey || event.metaKey;
// +1 day on ctrl or command +right
if (event.originalEvent.altKey) $.datepicker._adjustDate(event.target, (event.ctrlKey ?
+$.datepicker._get(inst, 'stepBigMonths') :
+$.datepicker._get(inst, 'stepMonths')), 'M');
// next month/year on alt +right
break;
case 40: if (event.ctrlKey || event.metaKey) $.datepicker._adjustDate(event.target, +7, 'D');
handled = event.ctrlKey || event.metaKey;
break; // +1 week on ctrl or command +down
default: handled = false;
}
else if (event.keyCode == 36 && event.ctrlKey) // display the date picker on ctrl+home
$.datepicker._showDatepicker(this);
else {
handled = false;
}
if (handled) {
event.preventDefault();
event.stopPropagation();
}
},
/* Filter entered characters - based on date format. */
_doKeyPress: function(event) {
var inst = $.datepicker._getInst(event.target);
if ($.datepicker._get(inst, 'constrainInput')) {
var chars = $.datepicker._possibleChars($.datepicker._get(inst, 'dateFormat'));
var chr = String.fromCharCode(event.charCode == undefined ? event.keyCode : event.charCode);
return event.ctrlKey || event.metaKey || (chr < ' ' || !chars || chars.indexOf(chr) > -1);
}
},
/* Synchronise manual entry and field/alternate field. */
_doKeyUp: function(event) {
var inst = $.datepicker._getInst(event.target);
if (inst.input.val() != inst.lastVal) {
try {
var date = $.datepicker.parseDate($.datepicker._get(inst, 'dateFormat'),
(inst.input ? inst.input.val() : null),
$.datepicker._getFormatConfig(inst));
if (date) { // only if valid
$.datepicker._setDateFromField(inst);
$.datepicker._updateAlternate(inst);
$.datepicker._updateDatepicker(inst);
}
}
catch (event) {
$.datepicker.log(event);
}
}
return true;
},
/* Pop-up the date picker for a given input field.
If false returned from beforeShow event handler do not show.
@param input element - the input field attached to the date picker or
event - if triggered by focus */
_showDatepicker: function(input) {
input = input.target || input;
if (input.nodeName.toLowerCase() != 'input') // find from button/image trigger
input = $('input', input.parentNode)[0];
if ($.datepicker._isDisabledDatepicker(input) || $.datepicker._lastInput == input) // already here
return;
var inst = $.datepicker._getInst(input);
if ($.datepicker._curInst && $.datepicker._curInst != inst) {
$.datepicker._curInst.dpDiv.stop(true, true);
if ( inst && $.datepicker._datepickerShowing ) {
$.datepicker._hideDatepicker( $.datepicker._curInst.input[0] );
}
}
var beforeShow = $.datepicker._get(inst, 'beforeShow');
var beforeShowSettings = beforeShow ? beforeShow.apply(input, [input, inst]) : {};
if(beforeShowSettings === false){
//false
return;
}
extendRemove(inst.settings, beforeShowSettings);
inst.lastVal = null;
$.datepicker._lastInput = input;
$.datepicker._setDateFromField(inst);
if ($.datepicker._inDialog) // hide cursor
input.value = '';
if (!$.datepicker._pos) { // position below input
$.datepicker._pos = $.datepicker._findPos(input);
$.datepicker._pos[1] += input.offsetHeight; // add the height
}
var isFixed = false;
$(input).parents().each(function() {
isFixed |= $(this).css('position') == 'fixed';
return !isFixed;
});
if (isFixed && $.browser.opera) { // correction for Opera when fixed and scrolled
$.datepicker._pos[0] -= document.documentElement.scrollLeft;
$.datepicker._pos[1] -= document.documentElement.scrollTop;
}
var offset = {left: $.datepicker._pos[0], top: $.datepicker._pos[1]};
$.datepicker._pos = null;
//to avoid flashes on Firefox
inst.dpDiv.empty();
// determine sizing offscreen
inst.dpDiv.css({position: 'absolute', display: 'block', top: '-1000px'});
$.datepicker._updateDatepicker(inst);
// fix width for dynamic number of date pickers
// and adjust position before showing
offset = $.datepicker._checkOffset(inst, offset, isFixed);
inst.dpDiv.css({position: ($.datepicker._inDialog && $.blockUI ?
'static' : (isFixed ? 'fixed' : 'absolute')), display: 'none',
left: offset.left + 'px', top: offset.top + 'px'});
if (!inst.inline) {
var showAnim = $.datepicker._get(inst, 'showAnim');
var duration = $.datepicker._get(inst, 'duration');
var postProcess = function() {
var cover = inst.dpDiv.find('iframe.ui-datepicker-cover'); // IE6- only
if( !! cover.length ){
var borders = $.datepicker._getBorders(inst.dpDiv);
cover.css({left: -borders[0], top: -borders[1],
width: inst.dpDiv.outerWidth(), height: inst.dpDiv.outerHeight()});
}
};
inst.dpDiv.zIndex($(input).zIndex()+1);
$.datepicker._datepickerShowing = true;
if ($.effects && $.effects[showAnim])
inst.dpDiv.show(showAnim, $.datepicker._get(inst, 'showOptions'), duration, postProcess);
else
inst.dpDiv[showAnim || 'show']((showAnim ? duration : null), postProcess);
if (!showAnim || !duration)
postProcess();
if (inst.input.is(':visible') && !inst.input.is(':disabled'))
inst.input.focus();
$.datepicker._curInst = inst;
}
},
/* Generate the date picker content. */
_updateDatepicker: function(inst) {
var self = this;
self.maxRows = 4; //Reset the max number of rows being displayed (see #7043)
var borders = $.datepicker._getBorders(inst.dpDiv);
instActive = inst; // for delegate hover events
inst.dpDiv.empty().append(this._generateHTML(inst));
var cover = inst.dpDiv.find('iframe.ui-datepicker-cover'); // IE6- only
if( !!cover.length ){ //avoid call to outerXXXX() when not in IE6
cover.css({left: -borders[0], top: -borders[1], width: inst.dpDiv.outerWidth(), height: inst.dpDiv.outerHeight()})
}
inst.dpDiv.find('.' + this._dayOverClass + ' a').mouseover();
var numMonths = this._getNumberOfMonths(inst);
var cols = numMonths[1];
var width = 17;
inst.dpDiv.removeClass('ui-datepicker-multi-2 ui-datepicker-multi-3 ui-datepicker-multi-4').width('');
if (cols > 1)
inst.dpDiv.addClass('ui-datepicker-multi-' + cols).css('width', (width * cols) + 'em');
inst.dpDiv[(numMonths[0] != 1 || numMonths[1] != 1 ? 'add' : 'remove') +
'Class']('ui-datepicker-multi');
inst.dpDiv[(this._get(inst, 'isRTL') ? 'add' : 'remove') +
'Class']('ui-datepicker-rtl');
if (inst == $.datepicker._curInst && $.datepicker._datepickerShowing && inst.input &&
// #6694 - don't focus the input if it's already focused
// this breaks the change event in IE
inst.input.is(':visible') && !inst.input.is(':disabled') && inst.input[0] != document.activeElement)
inst.input.focus();
// deffered render of the years select (to avoid flashes on Firefox)
if( inst.yearshtml ){
var origyearshtml = inst.yearshtml;
setTimeout(function(){
//assure that inst.yearshtml didn't change.
if( origyearshtml === inst.yearshtml && inst.yearshtml ){
inst.dpDiv.find('select.ui-datepicker-year:first').replaceWith(inst.yearshtml);
}
origyearshtml = inst.yearshtml = null;
}, 0);
}
},
/* Retrieve the size of left and top borders for an element.
@param elem (jQuery object) the element of interest
@return (number[2]) the left and top borders */
_getBorders: function(elem) {
var convert = function(value) {
return {thin: 1, medium: 2, thick: 3}[value] || value;
};
return [parseFloat(convert(elem.css('border-left-width'))),
parseFloat(convert(elem.css('border-top-width')))];
},
/* Check positioning to remain on screen. */
_checkOffset: function(inst, offset, isFixed) {
var dpWidth = inst.dpDiv.outerWidth();
var dpHeight = inst.dpDiv.outerHeight();
var inputWidth = inst.input ? inst.input.outerWidth() : 0;
var inputHeight = inst.input ? inst.input.outerHeight() : 0;
var viewWidth = document.documentElement.clientWidth + $(document).scrollLeft();
var viewHeight = document.documentElement.clientHeight + $(document).scrollTop();
offset.left -= (this._get(inst, 'isRTL') ? (dpWidth - inputWidth) : 0);
offset.left -= (isFixed && offset.left == inst.input.offset().left) ? $(document).scrollLeft() : 0;
offset.top -= (isFixed && offset.top == (inst.input.offset().top + inputHeight)) ? $(document).scrollTop() : 0;
// now check if datepicker is showing outside window viewport - move to a better place if so.
offset.left -= Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ?
Math.abs(offset.left + dpWidth - viewWidth) : 0);
offset.top -= Math.min(offset.top, (offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ?
Math.abs(dpHeight + inputHeight) : 0);
return offset;
},
/* Find an object's position on the screen. */
_findPos: function(obj) {
var inst = this._getInst(obj);
var isRTL = this._get(inst, 'isRTL');
while (obj && (obj.type == 'hidden' || obj.nodeType != 1 || $.expr.filters.hidden(obj))) {
obj = obj[isRTL ? 'previousSibling' : 'nextSibling'];
}
var position = $(obj).offset();
return [position.left, position.top];
},
/* Hide the date picker from view.
@param input element - the input field attached to the date picker */
_hideDatepicker: function(input) {
var inst = this._curInst;
if (!inst || (input && inst != $.data(input, PROP_NAME)))
return;
if (this._datepickerShowing) {
var showAnim = this._get(inst, 'showAnim');
var duration = this._get(inst, 'duration');
var self = this;
var postProcess = function() {
$.datepicker._tidyDialog(inst);
self._curInst = null;
};
if ($.effects && $.effects[showAnim])
inst.dpDiv.hide(showAnim, $.datepicker._get(inst, 'showOptions'), duration, postProcess);
else
inst.dpDiv[(showAnim == 'slideDown' ? 'slideUp' :
(showAnim == 'fadeIn' ? 'fadeOut' : 'hide'))]((showAnim ? duration : null), postProcess);
if (!showAnim)
postProcess();
this._datepickerShowing = false;
var onClose = this._get(inst, 'onClose');
if (onClose)
onClose.apply((inst.input ? inst.input[0] : null),
[(inst.input ? inst.input.val() : ''), inst]);
this._lastInput = null;
if (this._inDialog) {
this._dialogInput.css({ position: 'absolute', left: '0', top: '-100px' });
if ($.blockUI) {
$.unblockUI();
$('body').append(this.dpDiv);
}
}
this._inDialog = false;
}
},
/* Tidy up after a dialog display. */
_tidyDialog: function(inst) {
inst.dpDiv.removeClass(this._dialogClass).unbind('.ui-datepicker-calendar');
},
/* Close date picker if clicked elsewhere. */
_checkExternalClick: function(event) {
if (!$.datepicker._curInst)
return;
var $target = $(event.target),
inst = $.datepicker._getInst($target[0]);
if ( ( ( $target[0].id != $.datepicker._mainDivId &&
$target.parents('#' + $.datepicker._mainDivId).length == 0 &&
!$target.hasClass($.datepicker.markerClassName) &&
!$target.closest("." + $.datepicker._triggerClass).length &&
$.datepicker._datepickerShowing && !($.datepicker._inDialog && $.blockUI) ) ) ||
( $target.hasClass($.datepicker.markerClassName) && $.datepicker._curInst != inst ) )
$.datepicker._hideDatepicker();
},
/* Adjust one of the date sub-fields. */
_adjustDate: function(id, offset, period) {
var target = $(id);
var inst = this._getInst(target[0]);
if (this._isDisabledDatepicker(target[0])) {
return;
}
this._adjustInstDate(inst, offset +
(period == 'M' ? this._get(inst, 'showCurrentAtPos') : 0), // undo positioning
period);
this._updateDatepicker(inst);
},
/* Action for current link. */
_gotoToday: function(id) {
var target = $(id);
var inst = this._getInst(target[0]);
if (this._get(inst, 'gotoCurrent') && inst.currentDay) {
inst.selectedDay = inst.currentDay;
inst.drawMonth = inst.selectedMonth = inst.currentMonth;
inst.drawYear = inst.selectedYear = inst.currentYear;
}
else {
var date = new Date();
inst.selectedDay = date.getDate();
inst.drawMonth = inst.selectedMonth = date.getMonth();
inst.drawYear = inst.selectedYear = date.getFullYear();
}
this._notifyChange(inst);
this._adjustDate(target);
},
/* Action for selecting a new month/year. */
_selectMonthYear: function(id, select, period) {
var target = $(id);
var inst = this._getInst(target[0]);
inst['selected' + (period == 'M' ? 'Month' : 'Year')] =
inst['draw' + (period == 'M' ? 'Month' : 'Year')] =
parseInt(select.options[select.selectedIndex].value,10);
this._notifyChange(inst);
this._adjustDate(target);
},
/* Action for selecting a day. */
_selectDay: function(id, month, year, td) {
var target = $(id);
if ($(td).hasClass(this._unselectableClass) || this._isDisabledDatepicker(target[0])) {
return;
}
var inst = this._getInst(target[0]);
inst.selectedDay = inst.currentDay = $('a', td).html();
inst.selectedMonth = inst.currentMonth = month;
inst.selectedYear = inst.currentYear = year;
this._selectDate(id, this._formatDate(inst,
inst.currentDay, inst.currentMonth, inst.currentYear));
},
/* Erase the input field and hide the date picker. */
_clearDate: function(id) {
var target = $(id);
var inst = this._getInst(target[0]);
this._selectDate(target, '');
},
/* Update the input field with the selected date. */
_selectDate: function(id, dateStr) {
var target = $(id);
var inst = this._getInst(target[0]);
dateStr = (dateStr != null ? dateStr : this._formatDate(inst));
if (inst.input)
inst.input.val(dateStr);
this._updateAlternate(inst);
var onSelect = this._get(inst, 'onSelect');
if (onSelect)
onSelect.apply((inst.input ? inst.input[0] : null), [dateStr, inst]); // trigger custom callback
else if (inst.input)
inst.input.trigger('change'); // fire the change event
if (inst.inline)
this._updateDatepicker(inst);
else {
this._hideDatepicker();
this._lastInput = inst.input[0];
if (typeof(inst.input[0]) != 'object')
inst.input.focus(); // restore focus
this._lastInput = null;
}
},
/* Update any alternate field to synchronise with the main field. */
_updateAlternate: function(inst) {
var altField = this._get(inst, 'altField');
if (altField) { // update alternate field too
var altFormat = this._get(inst, 'altFormat') || this._get(inst, 'dateFormat');
var date = this._getDate(inst);
var dateStr = this.formatDate(altFormat, date, this._getFormatConfig(inst));
$(altField).each(function() { $(this).val(dateStr); });
}
},
/* Set as beforeShowDay function to prevent selection of weekends.
@param date Date - the date to customise
@return [boolean, string] - is this date selectable?, what is its CSS class? */
noWeekends: function(date) {
var day = date.getDay();
return [(day > 0 && day < 6), ''];
},
/* Set as calculateWeek to determine the week of the year based on the ISO 8601 definition.
@param date Date - the date to get the week for
@return number - the number of the week within the year that contains this date */
iso8601Week: function(date) {
var checkDate = new Date(date.getTime());
// Find Thursday of this week starting on Monday
checkDate.setDate(checkDate.getDate() + 4 - (checkDate.getDay() || 7));
var time = checkDate.getTime();
checkDate.setMonth(0); // Compare with Jan 1
checkDate.setDate(1);
return Math.floor(Math.round((time - checkDate) / 86400000) / 7) + 1;
},
/* Parse a string value into a date object.
See formatDate below for the possible formats.
@param format string - the expected format of the date
@param value string - the date in the above format
@param settings Object - attributes include:
shortYearCutoff number - the cutoff year for determining the century (optional)
dayNamesShort string[7] - abbreviated names of the days from Sunday (optional)
dayNames string[7] - names of the days from Sunday (optional)
monthNamesShort string[12] - abbreviated names of the months (optional)
monthNames string[12] - names of the months (optional)
@return Date - the extracted date value or null if value is blank */
parseDate: function (format, value, settings) {
if (format == null || value == null)
throw 'Invalid arguments';
value = (typeof value == 'object' ? value.toString() : value + '');
if (value == '')
return null;
var shortYearCutoff = (settings ? settings.shortYearCutoff : null) || this._defaults.shortYearCutoff;
shortYearCutoff = (typeof shortYearCutoff != 'string' ? shortYearCutoff :
new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10));
var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort;
var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames;
var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort;
var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames;
var year = -1;
var month = -1;
var day = -1;
var doy = -1;
var literal = false;
// Check whether a format character is doubled
var lookAhead = function(match) {
var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match);
if (matches)
iFormat++;
return matches;
};
// Extract a number from the string value
var getNumber = function(match) {
var isDoubled = lookAhead(match);
var size = (match == '@' ? 14 : (match == '!' ? 20 :
(match == 'y' && isDoubled ? 4 : (match == 'o' ? 3 : 2))));
var digits = new RegExp('^\\d{1,' + size + '}');
var num = value.substring(iValue).match(digits);
if (!num)
throw 'Missing number at position ' + iValue;
iValue += num[0].length;
return parseInt(num[0], 10);
};
// Extract a name from the string value and convert to an index
var getName = function(match, shortNames, longNames) {
var names = $.map(lookAhead(match) ? longNames : shortNames, function (v, k) {
return [ [k, v] ];
}).sort(function (a, b) {
return -(a[1].length - b[1].length);
});
var index = -1;
$.each(names, function (i, pair) {
var name = pair[1];
if (value.substr(iValue, name.length).toLowerCase() == name.toLowerCase()) {
index = pair[0];
iValue += name.length;
return false;
}
});
if (index != -1)
return index + 1;
else
throw 'Unknown name at position ' + iValue;
};
// Confirm that a literal character matches the string value
var checkLiteral = function() {
if (value.charAt(iValue) != format.charAt(iFormat))
throw 'Unexpected literal at position ' + iValue;
iValue++;
};
var iValue = 0;
for (var iFormat = 0; iFormat < format.length; iFormat++) {
if (literal)
if (format.charAt(iFormat) == "'" && !lookAhead("'"))
literal = false;
else
checkLiteral();
else
switch (format.charAt(iFormat)) {
case 'd':
day = getNumber('d');
break;
case 'D':
getName('D', dayNamesShort, dayNames);
break;
case 'o':
doy = getNumber('o');
break;
case 'm':
month = getNumber('m');
break;
case 'M':
month = getName('M', monthNamesShort, monthNames);
break;
case 'y':
year = getNumber('y');
break;
case '@':
var date = new Date(getNumber('@'));
year = date.getFullYear();
month = date.getMonth() + 1;
day = date.getDate();
break;
case '!':
var date = new Date((getNumber('!') - this._ticksTo1970) / 10000);
year = date.getFullYear();
month = date.getMonth() + 1;
day = date.getDate();
break;
case "'":
if (lookAhead("'"))
checkLiteral();
else
literal = true;
break;
default:
checkLiteral();
}
}
if (iValue < value.length){
throw "Extra/unparsed characters found in date: " + value.substring(iValue);
}
if (year == -1)
year = new Date().getFullYear();
else if (year < 100)
year += new Date().getFullYear() - new Date().getFullYear() % 100 +
(year <= shortYearCutoff ? 0 : -100);
if (doy > -1) {
month = 1;
day = doy;
do {
var dim = this._getDaysInMonth(year, month - 1);
if (day <= dim)
break;
month++;
day -= dim;
} while (true);
}
var date = this._daylightSavingAdjust(new Date(year, month - 1, day));
if (date.getFullYear() != year || date.getMonth() + 1 != month || date.getDate() != day)
throw 'Invalid date'; // E.g. 31/02/00
return date;
},
/* Standard date formats. */
ATOM: 'yy-mm-dd', // RFC 3339 (ISO 8601)
COOKIE: 'D, dd M yy',
ISO_8601: 'yy-mm-dd',
RFC_822: 'D, d M y',
RFC_850: 'DD, dd-M-y',
RFC_1036: 'D, d M y',
RFC_1123: 'D, d M yy',
RFC_2822: 'D, d M yy',
RSS: 'D, d M y', // RFC 822
TICKS: '!',
TIMESTAMP: '@',
W3C: 'yy-mm-dd', // ISO 8601
_ticksTo1970: (((1970 - 1) * 365 + Math.floor(1970 / 4) - Math.floor(1970 / 100) +
Math.floor(1970 / 400)) * 24 * 60 * 60 * 10000000),
/* Format a date object into a string value.
The format can be combinations of the following:
d - day of month (no leading zero)
dd - day of month (two digit)
o - day of year (no leading zeros)
oo - day of year (three digit)
D - day name short
DD - day name long
m - month of year (no leading zero)
mm - month of year (two digit)
M - month name short
MM - month name long
y - year (two digit)
yy - year (four digit)
@ - Unix timestamp (ms since 01/01/1970)
! - Windows ticks (100ns since 01/01/0001)
'...' - literal text
'' - single quote
@param format string - the desired format of the date
@param date Date - the date value to format
@param settings Object - attributes include:
dayNamesShort string[7] - abbreviated names of the days from Sunday (optional)
dayNames string[7] - names of the days from Sunday (optional)
monthNamesShort string[12] - abbreviated names of the months (optional)
monthNames string[12] - names of the months (optional)
@return string - the date in the above format */
formatDate: function (format, date, settings) {
if (!date)
return '';
var dayNamesShort = (settings ? settings.dayNamesShort : null) || this._defaults.dayNamesShort;
var dayNames = (settings ? settings.dayNames : null) || this._defaults.dayNames;
var monthNamesShort = (settings ? settings.monthNamesShort : null) || this._defaults.monthNamesShort;
var monthNames = (settings ? settings.monthNames : null) || this._defaults.monthNames;
// Check whether a format character is doubled
var lookAhead = function(match) {
var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match);
if (matches)
iFormat++;
return matches;
};
// Format a number, with leading zero if necessary
var formatNumber = function(match, value, len) {
var num = '' + value;
if (lookAhead(match))
while (num.length < len)
num = '0' + num;
return num;
};
// Format a name, short or long as requested
var formatName = function(match, value, shortNames, longNames) {
return (lookAhead(match) ? longNames[value] : shortNames[value]);
};
var output = '';
var literal = false;
if (date)
for (var iFormat = 0; iFormat < format.length; iFormat++) {
if (literal)
if (format.charAt(iFormat) == "'" && !lookAhead("'"))
literal = false;
else
output += format.charAt(iFormat);
else
switch (format.charAt(iFormat)) {
case 'd':
output += formatNumber('d', date.getDate(), 2);
break;
case 'D':
output += formatName('D', date.getDay(), dayNamesShort, dayNames);
break;
case 'o':
output += formatNumber('o',
Math.round((new Date(date.getFullYear(), date.getMonth(), date.getDate()).getTime() - new Date(date.getFullYear(), 0, 0).getTime()) / 86400000), 3);
break;
case 'm':
output += formatNumber('m', date.getMonth() + 1, 2);
break;
case 'M':
output += formatName('M', date.getMonth(), monthNamesShort, monthNames);
break;
case 'y':
output += (lookAhead('y') ? date.getFullYear() :
(date.getYear() % 100 < 10 ? '0' : '') + date.getYear() % 100);
break;
case '@':
output += date.getTime();
break;
case '!':
output += date.getTime() * 10000 + this._ticksTo1970;
break;
case "'":
if (lookAhead("'"))
output += "'";
else
literal = true;
break;
default:
output += format.charAt(iFormat);
}
}
return output;
},
/* Extract all possible characters from the date format. */
_possibleChars: function (format) {
var chars = '';
var literal = false;
// Check whether a format character is doubled
var lookAhead = function(match) {
var matches = (iFormat + 1 < format.length && format.charAt(iFormat + 1) == match);
if (matches)
iFormat++;
return matches;
};
for (var iFormat = 0; iFormat < format.length; iFormat++)
if (literal)
if (format.charAt(iFormat) == "'" && !lookAhead("'"))
literal = false;
else
chars += format.charAt(iFormat);
else
switch (format.charAt(iFormat)) {
case 'd': case 'm': case 'y': case '@':
chars += '0123456789';
break;
case 'D': case 'M':
return null; // Accept anything
case "'":
if (lookAhead("'"))
chars += "'";
else
literal = true;
break;
default:
chars += format.charAt(iFormat);
}
return chars;
},
/* Get a setting value, defaulting if necessary. */
_get: function(inst, name) {
return inst.settings[name] !== undefined ?
inst.settings[name] : this._defaults[name];
},
/* Parse existing date and initialise date picker. */
_setDateFromField: function(inst, noDefault) {
if (inst.input.val() == inst.lastVal) {
return;
}
var dateFormat = this._get(inst, 'dateFormat');
var dates = inst.lastVal = inst.input ? inst.input.val() : null;
var date, defaultDate;
date = defaultDate = this._getDefaultDate(inst);
var settings = this._getFormatConfig(inst);
try {
date = this.parseDate(dateFormat, dates, settings) || defaultDate;
} catch (event) {
this.log(event);
dates = (noDefault ? '' : dates);
}
inst.selectedDay = date.getDate();
inst.drawMonth = inst.selectedMonth = date.getMonth();
inst.drawYear = inst.selectedYear = date.getFullYear();
inst.currentDay = (dates ? date.getDate() : 0);
inst.currentMonth = (dates ? date.getMonth() : 0);
inst.currentYear = (dates ? date.getFullYear() : 0);
this._adjustInstDate(inst);
},
/* Retrieve the default date shown on opening. */
_getDefaultDate: function(inst) {
return this._restrictMinMax(inst,
this._determineDate(inst, this._get(inst, 'defaultDate'), new Date()));
},
/* A date may be specified as an exact value or a relative one. */
_determineDate: function(inst, date, defaultDate) {
var offsetNumeric = function(offset) {
var date = new Date();
date.setDate(date.getDate() + offset);
return date;
};
var offsetString = function(offset) {
try {
return $.datepicker.parseDate($.datepicker._get(inst, 'dateFormat'),
offset, $.datepicker._getFormatConfig(inst));
}
catch (e) {
// Ignore
}
var date = (offset.toLowerCase().match(/^c/) ?
$.datepicker._getDate(inst) : null) || new Date();
var year = date.getFullYear();
var month = date.getMonth();
var day = date.getDate();
var pattern = /([+-]?[0-9]+)\s*(d|D|w|W|m|M|y|Y)?/g;
var matches = pattern.exec(offset);
while (matches) {
switch (matches[2] || 'd') {
case 'd' : case 'D' :
day += parseInt(matches[1],10); break;
case 'w' : case 'W' :
day += parseInt(matches[1],10) * 7; break;
case 'm' : case 'M' :
month += parseInt(matches[1],10);
day = Math.min(day, $.datepicker._getDaysInMonth(year, month));
break;
case 'y': case 'Y' :
year += parseInt(matches[1],10);
day = Math.min(day, $.datepicker._getDaysInMonth(year, month));
break;
}
matches = pattern.exec(offset);
}
return new Date(year, month, day);
};
var newDate = (date == null || date === '' ? defaultDate : (typeof date == 'string' ? offsetString(date) :
(typeof date == 'number' ? (isNaN(date) ? defaultDate : offsetNumeric(date)) : new Date(date.getTime()))));
newDate = (newDate && newDate.toString() == 'Invalid Date' ? defaultDate : newDate);
if (newDate) {
newDate.setHours(0);
newDate.setMinutes(0);
newDate.setSeconds(0);
newDate.setMilliseconds(0);
}
return this._daylightSavingAdjust(newDate);
},
/* Handle switch to/from daylight saving.
Hours may be non-zero on daylight saving cut-over:
> 12 when midnight changeover, but then cannot generate
midnight datetime, so jump to 1AM, otherwise reset.
@param date (Date) the date to check
@return (Date) the corrected date */
_daylightSavingAdjust: function(date) {
if (!date) return null;
date.setHours(date.getHours() > 12 ? date.getHours() + 2 : 0);
return date;
},
/* Set the date(s) directly. */
_setDate: function(inst, date, noChange) {
var clear = !date;
var origMonth = inst.selectedMonth;
var origYear = inst.selectedYear;
var newDate = this._restrictMinMax(inst, this._determineDate(inst, date, new Date()));
inst.selectedDay = inst.currentDay = newDate.getDate();
inst.drawMonth = inst.selectedMonth = inst.currentMonth = newDate.getMonth();
inst.drawYear = inst.selectedYear = inst.currentYear = newDate.getFullYear();
if ((origMonth != inst.selectedMonth || origYear != inst.selectedYear) && !noChange)
this._notifyChange(inst);
this._adjustInstDate(inst);
if (inst.input) {
inst.input.val(clear ? '' : this._formatDate(inst));
}
},
/* Retrieve the date(s) directly. */
_getDate: function(inst) {
var startDate = (!inst.currentYear || (inst.input && inst.input.val() == '') ? null :
this._daylightSavingAdjust(new Date(
inst.currentYear, inst.currentMonth, inst.currentDay)));
return startDate;
},
/* Generate the HTML for the current state of the date picker. */
_generateHTML: function(inst) {
var today = new Date();
today = this._daylightSavingAdjust(
new Date(today.getFullYear(), today.getMonth(), today.getDate())); // clear time
var isRTL = this._get(inst, 'isRTL');
var showButtonPanel = this._get(inst, 'showButtonPanel');
var hideIfNoPrevNext = this._get(inst, 'hideIfNoPrevNext');
var navigationAsDateFormat = this._get(inst, 'navigationAsDateFormat');
var numMonths = this._getNumberOfMonths(inst);
var showCurrentAtPos = this._get(inst, 'showCurrentAtPos');
var stepMonths = this._get(inst, 'stepMonths');
var isMultiMonth = (numMonths[0] != 1 || numMonths[1] != 1);
var currentDate = this._daylightSavingAdjust((!inst.currentDay ? new Date(9999, 9, 9) :
new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
var minDate = this._getMinMaxDate(inst, 'min');
var maxDate = this._getMinMaxDate(inst, 'max');
var drawMonth = inst.drawMonth - showCurrentAtPos;
var drawYear = inst.drawYear;
if (drawMonth < 0) {
drawMonth += 12;
drawYear--;
}
if (maxDate) {
var maxDraw = this._daylightSavingAdjust(new Date(maxDate.getFullYear(),
maxDate.getMonth() - (numMonths[0] * numMonths[1]) + 1, maxDate.getDate()));
maxDraw = (minDate && maxDraw < minDate ? minDate : maxDraw);
while (this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1)) > maxDraw) {
drawMonth--;
if (drawMonth < 0) {
drawMonth = 11;
drawYear--;
}
}
}
inst.drawMonth = drawMonth;
inst.drawYear = drawYear;
var prevText = this._get(inst, 'prevText');
prevText = (!navigationAsDateFormat ? prevText : this.formatDate(prevText,
this._daylightSavingAdjust(new Date(drawYear, drawMonth - stepMonths, 1)),
this._getFormatConfig(inst)));
var prev = (this._canAdjustMonth(inst, -1, drawYear, drawMonth) ?
'<a class="ui-datepicker-prev ui-corner-all" onclick="DP_jQuery_' + dpuuid +
'.datepicker._adjustDate(\'#' + inst.id + '\', -' + stepMonths + ', \'M\');"' +
' title="' + prevText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'e' : 'w') + '">' + prevText + '</span></a>' :
(hideIfNoPrevNext ? '' : '<a class="ui-datepicker-prev ui-corner-all ui-state-disabled" title="'+ prevText +'"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'e' : 'w') + '">' + prevText + '</span></a>'));
var nextText = this._get(inst, 'nextText');
nextText = (!navigationAsDateFormat ? nextText : this.formatDate(nextText,
this._daylightSavingAdjust(new Date(drawYear, drawMonth + stepMonths, 1)),
this._getFormatConfig(inst)));
var next = (this._canAdjustMonth(inst, +1, drawYear, drawMonth) ?
'<a class="ui-datepicker-next ui-corner-all" onclick="DP_jQuery_' + dpuuid +
'.datepicker._adjustDate(\'#' + inst.id + '\', +' + stepMonths + ', \'M\');"' +
' title="' + nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'w' : 'e') + '">' + nextText + '</span></a>' :
(hideIfNoPrevNext ? '' : '<a class="ui-datepicker-next ui-corner-all ui-state-disabled" title="'+ nextText + '"><span class="ui-icon ui-icon-circle-triangle-' + ( isRTL ? 'w' : 'e') + '">' + nextText + '</span></a>'));
var currentText = this._get(inst, 'currentText');
var gotoDate = (this._get(inst, 'gotoCurrent') && inst.currentDay ? currentDate : today);
currentText = (!navigationAsDateFormat ? currentText :
this.formatDate(currentText, gotoDate, this._getFormatConfig(inst)));
var controls = (!inst.inline ? '<button type="button" class="ui-datepicker-close ui-state-default ui-priority-primary ui-corner-all" onclick="DP_jQuery_' + dpuuid +
'.datepicker._hideDatepicker();">' + this._get(inst, 'closeText') + '</button>' : '');
var buttonPanel = (showButtonPanel) ? '<div class="ui-datepicker-buttonpane ui-widget-content">' + (isRTL ? controls : '') +
(this._isInRange(inst, gotoDate) ? '<button type="button" class="ui-datepicker-current ui-state-default ui-priority-secondary ui-corner-all" onclick="DP_jQuery_' + dpuuid +
'.datepicker._gotoToday(\'#' + inst.id + '\');"' +
'>' + currentText + '</button>' : '') + (isRTL ? '' : controls) + '</div>' : '';
var firstDay = parseInt(this._get(inst, 'firstDay'),10);
firstDay = (isNaN(firstDay) ? 0 : firstDay);
var showWeek = this._get(inst, 'showWeek');
var dayNames = this._get(inst, 'dayNames');
var dayNamesShort = this._get(inst, 'dayNamesShort');
var dayNamesMin = this._get(inst, 'dayNamesMin');
var monthNames = this._get(inst, 'monthNames');
var monthNamesShort = this._get(inst, 'monthNamesShort');
var beforeShowDay = this._get(inst, 'beforeShowDay');
var showOtherMonths = this._get(inst, 'showOtherMonths');
var selectOtherMonths = this._get(inst, 'selectOtherMonths');
var calculateWeek = this._get(inst, 'calculateWeek') || this.iso8601Week;
var defaultDate = this._getDefaultDate(inst);
var html = '';
for (var row = 0; row < numMonths[0]; row++) {
var group = '';
this.maxRows = 4;
for (var col = 0; col < numMonths[1]; col++) {
var selectedDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, inst.selectedDay));
var cornerClass = ' ui-corner-all';
var calender = '';
if (isMultiMonth) {
calender += '<div class="ui-datepicker-group';
if (numMonths[1] > 1)
switch (col) {
case 0: calender += ' ui-datepicker-group-first';
cornerClass = ' ui-corner-' + (isRTL ? 'right' : 'left'); break;
case numMonths[1]-1: calender += ' ui-datepicker-group-last';
cornerClass = ' ui-corner-' + (isRTL ? 'left' : 'right'); break;
default: calender += ' ui-datepicker-group-middle'; cornerClass = ''; break;
}
calender += '">';
}
calender += '<div class="ui-datepicker-header ui-widget-header ui-helper-clearfix' + cornerClass + '">' +
(/all|left/.test(cornerClass) && row == 0 ? (isRTL ? next : prev) : '') +
(/all|right/.test(cornerClass) && row == 0 ? (isRTL ? prev : next) : '') +
this._generateMonthYearHeader(inst, drawMonth, drawYear, minDate, maxDate,
row > 0 || col > 0, monthNames, monthNamesShort) + // draw month headers
'</div><table class="ui-datepicker-calendar"><thead>' +
'<tr>';
var thead = (showWeek ? '<th class="ui-datepicker-week-col">' + this._get(inst, 'weekHeader') + '</th>' : '');
for (var dow = 0; dow < 7; dow++) { // days of the week
var day = (dow + firstDay) % 7;
thead += '<th' + ((dow + firstDay + 6) % 7 >= 5 ? ' class="ui-datepicker-week-end"' : '') + '>' +
'<span title="' + dayNames[day] + '">' + dayNamesMin[day] + '</span></th>';
}
calender += thead + '</tr></thead><tbody>';
var daysInMonth = this._getDaysInMonth(drawYear, drawMonth);
if (drawYear == inst.selectedYear && drawMonth == inst.selectedMonth)
inst.selectedDay = Math.min(inst.selectedDay, daysInMonth);
var leadDays = (this._getFirstDayOfMonth(drawYear, drawMonth) - firstDay + 7) % 7;
var curRows = Math.ceil((leadDays + daysInMonth) / 7); // calculate the number of rows to generate
var numRows = (isMultiMonth ? this.maxRows > curRows ? this.maxRows : curRows : curRows); //If multiple months, use the higher number of rows (see #7043)
this.maxRows = numRows;
var printDate = this._daylightSavingAdjust(new Date(drawYear, drawMonth, 1 - leadDays));
for (var dRow = 0; dRow < numRows; dRow++) { // create date picker rows
calender += '<tr>';
var tbody = (!showWeek ? '' : '<td class="ui-datepicker-week-col">' +
this._get(inst, 'calculateWeek')(printDate) + '</td>');
for (var dow = 0; dow < 7; dow++) { // create date picker days
var daySettings = (beforeShowDay ?
beforeShowDay.apply((inst.input ? inst.input[0] : null), [printDate]) : [true, '']);
var otherMonth = (printDate.getMonth() != drawMonth);
var unselectable = (otherMonth && !selectOtherMonths) || !daySettings[0] ||
(minDate && printDate < minDate) || (maxDate && printDate > maxDate);
tbody += '<td class="' +
((dow + firstDay + 6) % 7 >= 5 ? ' ui-datepicker-week-end' : '') + // highlight weekends
(otherMonth ? ' ui-datepicker-other-month' : '') + // highlight days from other months
((printDate.getTime() == selectedDate.getTime() && drawMonth == inst.selectedMonth && inst._keyEvent) || // user pressed key
(defaultDate.getTime() == printDate.getTime() && defaultDate.getTime() == selectedDate.getTime()) ?
// or defaultDate is current printedDate and defaultDate is selectedDate
' ' + this._dayOverClass : '') + // highlight selected day
(unselectable ? ' ' + this._unselectableClass + ' ui-state-disabled': '') + // highlight unselectable days
(otherMonth && !showOtherMonths ? '' : ' ' + daySettings[1] + // highlight custom dates
(printDate.getTime() == currentDate.getTime() ? ' ' + this._currentClass : '') + // highlight selected day
(printDate.getTime() == today.getTime() ? ' ui-datepicker-today' : '')) + '"' + // highlight today (if different)
((!otherMonth || showOtherMonths) && daySettings[2] ? ' title="' + daySettings[2] + '"' : '') + // cell title
(unselectable ? '' : ' onclick="DP_jQuery_' + dpuuid + '.datepicker._selectDay(\'#' +
inst.id + '\',' + printDate.getMonth() + ',' + printDate.getFullYear() + ', this);return false;"') + '>' + // actions
(otherMonth && !showOtherMonths ? ' ' : // display for other months
(unselectable ? '<span class="ui-state-default">' + printDate.getDate() + '</span>' : '<a class="ui-state-default' +
(printDate.getTime() == today.getTime() ? ' ui-state-highlight' : '') +
(printDate.getTime() == currentDate.getTime() ? ' ui-state-active' : '') + // highlight selected day
(otherMonth ? ' ui-priority-secondary' : '') + // distinguish dates from other months
'" href="#">' + printDate.getDate() + '</a>')) + '</td>'; // display selectable date
printDate.setDate(printDate.getDate() + 1);
printDate = this._daylightSavingAdjust(printDate);
}
calender += tbody + '</tr>';
}
drawMonth++;
if (drawMonth > 11) {
drawMonth = 0;
drawYear++;
}
calender += '</tbody></table>' + (isMultiMonth ? '</div>' +
((numMonths[0] > 0 && col == numMonths[1]-1) ? '<div class="ui-datepicker-row-break"></div>' : '') : '');
group += calender;
}
html += group;
}
html += buttonPanel + ($.browser.msie && parseInt($.browser.version,10) < 7 && !inst.inline ?
'<iframe src="javascript:false;" class="ui-datepicker-cover" frameborder="0"></iframe>' : '');
inst._keyEvent = false;
return html;
},
/* Generate the month and year header. */
_generateMonthYearHeader: function(inst, drawMonth, drawYear, minDate, maxDate,
secondary, monthNames, monthNamesShort) {
var changeMonth = this._get(inst, 'changeMonth');
var changeYear = this._get(inst, 'changeYear');
var showMonthAfterYear = this._get(inst, 'showMonthAfterYear');
var html = '<div class="ui-datepicker-title">';
var monthHtml = '';
// month selection
if (secondary || !changeMonth)
monthHtml += '<span class="ui-datepicker-month">' + monthNames[drawMonth] + '</span>';
else {
var inMinYear = (minDate && minDate.getFullYear() == drawYear);
var inMaxYear = (maxDate && maxDate.getFullYear() == drawYear);
monthHtml += '<select class="ui-datepicker-month" ' +
'onchange="DP_jQuery_' + dpuuid + '.datepicker._selectMonthYear(\'#' + inst.id + '\', this, \'M\');" ' +
'>';
for (var month = 0; month < 12; month++) {
if ((!inMinYear || month >= minDate.getMonth()) &&
(!inMaxYear || month <= maxDate.getMonth()))
monthHtml += '<option value="' + month + '"' +
(month == drawMonth ? ' selected="selected"' : '') +
'>' + monthNamesShort[month] + '</option>';
}
monthHtml += '</select>';
}
if (!showMonthAfterYear)
html += monthHtml + (secondary || !(changeMonth && changeYear) ? ' ' : '');
// year selection
if ( !inst.yearshtml ) {
inst.yearshtml = '';
if (secondary || !changeYear)
html += '<span class="ui-datepicker-year">' + drawYear + '</span>';
else {
// determine range of years to display
var years = this._get(inst, 'yearRange').split(':');
var thisYear = new Date().getFullYear();
var determineYear = function(value) {
var year = (value.match(/c[+-].*/) ? drawYear + parseInt(value.substring(1), 10) :
(value.match(/[+-].*/) ? thisYear + parseInt(value, 10) :
parseInt(value, 10)));
return (isNaN(year) ? thisYear : year);
};
var year = determineYear(years[0]);
var endYear = Math.max(year, determineYear(years[1] || ''));
year = (minDate ? Math.max(year, minDate.getFullYear()) : year);
endYear = (maxDate ? Math.min(endYear, maxDate.getFullYear()) : endYear);
inst.yearshtml += '<select class="ui-datepicker-year" ' +
'onchange="DP_jQuery_' + dpuuid + '.datepicker._selectMonthYear(\'#' + inst.id + '\', this, \'Y\');" ' +
'>';
for (; year <= endYear; year++) {
inst.yearshtml += '<option value="' + year + '"' +
(year == drawYear ? ' selected="selected"' : '') +
'>' + year + '</option>';
}
inst.yearshtml += '</select>';
html += inst.yearshtml;
inst.yearshtml = null;
}
}
html += this._get(inst, 'yearSuffix');
if (showMonthAfterYear)
html += (secondary || !(changeMonth && changeYear) ? ' ' : '') + monthHtml;
html += '</div>'; // Close datepicker_header
return html;
},
/* Adjust one of the date sub-fields. */
_adjustInstDate: function(inst, offset, period) {
var year = inst.drawYear + (period == 'Y' ? offset : 0);
var month = inst.drawMonth + (period == 'M' ? offset : 0);
var day = Math.min(inst.selectedDay, this._getDaysInMonth(year, month)) +
(period == 'D' ? offset : 0);
var date = this._restrictMinMax(inst,
this._daylightSavingAdjust(new Date(year, month, day)));
inst.selectedDay = date.getDate();
inst.drawMonth = inst.selectedMonth = date.getMonth();
inst.drawYear = inst.selectedYear = date.getFullYear();
if (period == 'M' || period == 'Y')
this._notifyChange(inst);
},
/* Ensure a date is within any min/max bounds. */
_restrictMinMax: function(inst, date) {
var minDate = this._getMinMaxDate(inst, 'min');
var maxDate = this._getMinMaxDate(inst, 'max');
var newDate = (minDate && date < minDate ? minDate : date);
newDate = (maxDate && newDate > maxDate ? maxDate : newDate);
return newDate;
},
/* Notify change of month/year. */
_notifyChange: function(inst) {
var onChange = this._get(inst, 'onChangeMonthYear');
if (onChange)
onChange.apply((inst.input ? inst.input[0] : null),
[inst.selectedYear, inst.selectedMonth + 1, inst]);
},
/* Determine the number of months to show. */
_getNumberOfMonths: function(inst) {
var numMonths = this._get(inst, 'numberOfMonths');
return (numMonths == null ? [1, 1] : (typeof numMonths == 'number' ? [1, numMonths] : numMonths));
},
/* Determine the current maximum date - ensure no time components are set. */
_getMinMaxDate: function(inst, minMax) {
return this._determineDate(inst, this._get(inst, minMax + 'Date'), null);
},
/* Find the number of days in a given month. */
_getDaysInMonth: function(year, month) {
return 32 - this._daylightSavingAdjust(new Date(year, month, 32)).getDate();
},
/* Find the day of the week of the first of a month. */
_getFirstDayOfMonth: function(year, month) {
return new Date(year, month, 1).getDay();
},
/* Determines if we should allow a "next/prev" month display change. */
_canAdjustMonth: function(inst, offset, curYear, curMonth) {
var numMonths = this._getNumberOfMonths(inst);
var date = this._daylightSavingAdjust(new Date(curYear,
curMonth + (offset < 0 ? offset : numMonths[0] * numMonths[1]), 1));
if (offset < 0)
date.setDate(this._getDaysInMonth(date.getFullYear(), date.getMonth()));
return this._isInRange(inst, date);
},
/* Is the given date in the accepted range? */
_isInRange: function(inst, date) {
var minDate = this._getMinMaxDate(inst, 'min');
var maxDate = this._getMinMaxDate(inst, 'max');
return ((!minDate || date.getTime() >= minDate.getTime()) &&
(!maxDate || date.getTime() <= maxDate.getTime()));
},
/* Provide the configuration settings for formatting/parsing. */
_getFormatConfig: function(inst) {
var shortYearCutoff = this._get(inst, 'shortYearCutoff');
shortYearCutoff = (typeof shortYearCutoff != 'string' ? shortYearCutoff :
new Date().getFullYear() % 100 + parseInt(shortYearCutoff, 10));
return {shortYearCutoff: shortYearCutoff,
dayNamesShort: this._get(inst, 'dayNamesShort'), dayNames: this._get(inst, 'dayNames'),
monthNamesShort: this._get(inst, 'monthNamesShort'), monthNames: this._get(inst, 'monthNames')};
},
/* Format the given date for display. */
_formatDate: function(inst, day, month, year) {
if (!day) {
inst.currentDay = inst.selectedDay;
inst.currentMonth = inst.selectedMonth;
inst.currentYear = inst.selectedYear;
}
var date = (day ? (typeof day == 'object' ? day :
this._daylightSavingAdjust(new Date(year, month, day))) :
this._daylightSavingAdjust(new Date(inst.currentYear, inst.currentMonth, inst.currentDay)));
return this.formatDate(this._get(inst, 'dateFormat'), date, this._getFormatConfig(inst));
}
});
/*
* Bind hover events for datepicker elements.
* Done via delegate so the binding only occurs once in the lifetime of the parent div.
* Global instActive, set by _updateDatepicker allows the handlers to find their way back to the active picker.
*/
function bindHover(dpDiv) {
var selector = 'button, .ui-datepicker-prev, .ui-datepicker-next, .ui-datepicker-calendar td a';
return dpDiv.bind('mouseout', function(event) {
var elem = $( event.target ).closest( selector );
if ( !elem.length ) {
return;
}
elem.removeClass( "ui-state-hover ui-datepicker-prev-hover ui-datepicker-next-hover" );
})
.bind('mouseover', function(event) {
var elem = $( event.target ).closest( selector );
if ($.datepicker._isDisabledDatepicker( instActive.inline ? dpDiv.parent()[0] : instActive.input[0]) ||
!elem.length ) {
return;
}
elem.parents('.ui-datepicker-calendar').find('a').removeClass('ui-state-hover');
elem.addClass('ui-state-hover');
if (elem.hasClass('ui-datepicker-prev')) elem.addClass('ui-datepicker-prev-hover');
if (elem.hasClass('ui-datepicker-next')) elem.addClass('ui-datepicker-next-hover');
});
}
/* jQuery extend now ignores nulls! */
function extendRemove(target, props) {
$.extend(target, props);
for (var name in props)
if (props[name] == null || props[name] == undefined)
target[name] = props[name];
return target;
};
/* Determine whether an object is an array. */
function isArray(a) {
return (a && (($.browser.safari && typeof a == 'object' && a.length) ||
(a.constructor && a.constructor.toString().match(/\Array\(\)/))));
};
/* Invoke the datepicker functionality.
@param options string - a command, optionally followed by additional parameters or
Object - settings for attaching new datepicker functionality
@return jQuery object */
$.fn.datepicker = function(options){
/* Verify an empty collection wasn't passed - Fixes #6976 */
if ( !this.length ) {
return this;
}
/* Initialise the date picker. */
if (!$.datepicker.initialized) {
$(document).mousedown($.datepicker._checkExternalClick).
find('body').append($.datepicker.dpDiv);
$.datepicker.initialized = true;
}
var otherArgs = Array.prototype.slice.call(arguments, 1);
if (typeof options == 'string' && (options == 'isDisabled' || options == 'getDate' || options == 'widget'))
return $.datepicker['_' + options + 'Datepicker'].
apply($.datepicker, [this[0]].concat(otherArgs));
if (options == 'option' && arguments.length == 2 && typeof arguments[1] == 'string')
return $.datepicker['_' + options + 'Datepicker'].
apply($.datepicker, [this[0]].concat(otherArgs));
return this.each(function() {
typeof options == 'string' ?
$.datepicker['_' + options + 'Datepicker'].
apply($.datepicker, [this].concat(otherArgs)) :
$.datepicker._attachDatepicker(this, options);
});
};
$.datepicker = new Datepicker(); // singleton instance
$.datepicker.initialized = false;
$.datepicker.uuid = new Date().getTime();
$.datepicker.version = "1.8.18";
// Workaround for #4055
// Add another global to avoid noConflict issues with inline event handlers
window['DP_jQuery_' + dpuuid] = $;
})(jQuery);
|
/**
* 对外提供的事件
*/
Dplayer.prototype._event = [
'ready',
'resize',
'play',
'pause',
'complete'
];
/**
* 事件注册器
* @param evnet_name 事件名
* @param fun 回调函数
*/
Dplayer.prototype.on = function(evnet_name, fun) {
if (this.index_of(this._event, evnet_name)) {
if (fun && fun instanceof Function) {
this['on_player_' + evnet_name] = fun;
} else {
this.error("注册函数参数错误");
}
} else {
this.warn("该事件不支持");
}
} |
'use strict';
module.exports = function(grunt) {
require('load-grunt-tasks')(grunt); // load all grunt tasks
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
options: {
jshintrc: '.jshintrc',
reporter: require('jshint-stylish')
},
all: [
'app.js',
'config.js',
'Gruntfile.js',
'controllers/{,*/}*.js',
'routes/{,*/}*.js'
]
},
express: {
options: {
port: process.env.PORT || 9000
},
dev: {
options: {
script: 'app.js'
}
}
},
watch: {
emberTemplates: {
files: 'public/js/templates/**/*.hbs',
tasks: ['emberTemplates'],
options: {
livereload: true
}
},
jade: {
files: ['views/**'],
options: {
livereload: true,
},
},
css: {
files: ['public/css/**'],
options: {
livereload: true
}
},
js: {
files: ['public/js/**'],
options: {
livereload: true
}
},
express: {
files: [
'app.js',
'config.js',
'controllers/**',
'routes/**'
],
tasks: ['express:dev'],
options: {
spawn: false,
livereload: true
}
}
},
open: {
server: {
url: 'http://localhost:<%= express.options.port %>'
}
},
emberTemplates: {
options: {
templateName: function(sourceFile) {
var templatePath = 'public/js/templates/';
return sourceFile.replace(templatePath, '');
}
},
compile: {
files: {
'public/js/templates/compiled-templates.js': 'public/js/templates/{,*/}*.hbs'
}
}
},
shell: {
mongo: {
command: 'ulimit -n 2048 && mongod --fork --logpath db/mongodb.log --dbpath db/'
}
}
});
grunt.registerTask('default', [
// 'shell:mongo',
'emberTemplates',
'express',
'open',
'watch'
]);
}; |
var Command = require('ronin').Command;
var chalk = require('chalk');
var inquirer = require('inquirer');
var ModuleGenerator = require('./../utils/generators/moduleGenerator');
var Generate = Command.extend({
desc: 'Generate boilerplate for a skywalker module',
options: {
name: {
type: 'string',
alias: 'n'
},
table: {
type: 'string',
alias: 't'
}
},
run: function (name, table) {
var confirm = {
type: 'confirm',
name: 'confirm',
message: 'Sei sicuro di voler procedere? Tutti i files già presenti per il modulo "' + name + '" saranno sovrascritti!',
default: false
};
inquirer.prompt([confirm], function(answers) {
if (answers.confirm) {
var generator = new ModuleGenerator();
generator.build({
name: name,
table: table
});
console.log(chalk.bold.green('All done!'));
} else {
console.log('Bye');
}
});
}
});
module.exports = Generate; |
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require('@angular/core');
var hero_1 = require('./hero');
var HeroDetailComponent = (function () {
function HeroDetailComponent() {
}
__decorate([
core_1.Input(),
__metadata('design:type', hero_1.Hero)
], HeroDetailComponent.prototype, "hero", void 0);
HeroDetailComponent = __decorate([
core_1.Component({
selector: 'my-hero-detail',
template: "\n <div *ngIf=\"hero\">\n <h2>{{hero.name}} \u8BE6\u60C5</h2>\n <div><label>id:</label>{{hero.id}}</div>\n <div>\n <label>name:</label>\n <input [(ngModel)]=\"hero.name\" placeholder=\"name\">\n </div>\n </div>"
}),
__metadata('design:paramtypes', [])
], HeroDetailComponent);
return HeroDetailComponent;
}());
exports.HeroDetailComponent = HeroDetailComponent;
//# sourceMappingURL=hero-detail.component.js.map |
module.exports = function(grunt) {
grunt.config('watch', {
sass: {
files: ['source/css/**/*.scss'],
tasks: ['compass'],
options: {
'spawn': true
}
},
scripts: {
files: ['source/js/source/**/*.js'],
tasks: ['uglify'],
options: {
'spawn': true
}
},
html: {
files: [
'source/_patterns/**/*.mustache',
'source/_patterns/**/*.json',
'source/css/**/*.css',
'source/js/**/*.js',
'source/api/*.json'
],
tasks: ['shell:patternlab'],
options: {
'spawn': false
}
}
});
grunt.loadNpmTasks('grunt-contrib-watch');
};
|
/**
* @author Dmitriy Yurchenko <evildev@evildev.ru>
* @copyright Copyright (c) Dmitriy Yurchenko <evildev@evildev.ru>, 2015
* @license MIT
*/
module.exports = {
basePath: __dirname + '/../',
components: {
db: require('./database.json'),
jabber: require('./jabber.json'),
server: {
host: 'consult.hitrade.local',
port: 8080
}
}
}; |
/*====+++++========+++++===*
* @Author: sovathana
* @Date: 2015-09-13 12:33:13
* @Last Modified by: sovathana
* @Last Modified time: 2015-09-13 12:33:50
* @Email: sovathana.phat@gmail.com
* @Facebook && Twitter : Sophatvathana
* @Project: Quick-q
* @FileName: index.js
*==========================
*/
'use strict';
module.exports = require('./lib/ngRolerr'); |
module.exports = function() {
'use strict';
return {
command: [
'list=(<%= jqueryToolbox.folder.src.js %>*)',
'(sleep 1 && touch ${list[0]}) > /dev/null 2>&1 &'
].join('\n')
};
};
|
const noProps = require('./no-props')
const simpleProps = require('./simple-props')
const objectProps = require('./modules-object-props')
const attributeProps = require('./modules-attribute-props')
const realForm = require('./real-world-form')
const suites = []
function runNextSuite() {
if (suites.length !== 0) {
suites.shift().run({ async: true })
} else {
console.log('\nAll benchmarks complete')
}
}
function addSuite(suite) {
suites.push(suite)
suite.on('start', (event) => {
console.log('\nBenchmarking', event.currentTarget.name)
}).
on('cycle', (event) => {
console.log(String(event.target))
}).
on('complete', function (event) {
const fastest = this.filter('fastest').map('name')
const fastestJSX = this.filter((bench) => bench.name.indexOf('jsx') !== -1).filter('fastest').map('name')
console.log(event.currentTarget.name, '- fastest is ' + fastest, ' fastest JSX is ', fastestJSX)
runNextSuite()
})
}
addSuite(noProps)
addSuite(simpleProps)
addSuite(objectProps)
addSuite(attributeProps)
addSuite(realForm)
runNextSuite()
|
var Mocha = require('mocha');
Mocha.reporters = require('./lib/reporters');
Mocha.Suite = require('./lib/suite');
Mocha.Runner = require('./lib/runner');
var Reporter = Mocha.prototype.reporter;
Mocha.prototype.reporter = function (reporter) {
var _reporter = reporter;
if ('string' === typeof reporter) {
try { _reporter = require('./lib/reporters/' + reporter); } catch (err) {};
if (!_reporter) try { _reporter = require(reporter); } catch (err) {};
}
return Reporter.call(this, _reporter);
};
module.exports = Mocha; |
var searchData=
[
['initializecontextfromhandle',['initializeContextFromHandle',['../d1/d45/classcv_1_1ocl_1_1Context.html#a4f09f3d6c49131f686272677278f0851',1,'cv::ocl::Context::initializeContextFromHandle()'],['../d8/d87/classcv_1_1ocl_1_1Platform.html#a4f09f3d6c49131f686272677278f0851',1,'cv::ocl::Platform::initializeContextFromHandle()']]]
];
|
// Karma configuration
// Generated on Tue Mar 19 2013 12:10:12 GMT+0000 (GMT)
// base path, that will be used to resolve files and exclude
basePath = '';
// list of files / patterns to load in the browser
files = [
JASMINE,
JASMINE_ADAPTER,
REQUIRE,
REQUIRE_ADAPTER,
'js/lib/jquery.min.js',
'js/lib/jquery.transit.min.js',
// jasmine-jquery.js
{
pattern: 'test/fixtures/*.html',
watched: true,
included: false,
served: true
},
{
pattern: 'css/*.css',
watched: true,
included: false,
served: true
},
{ pattern: 'js/src/*.js', included: false },
{ pattern: 'test/*.test.js', included: false },
'test/helpers/*.js',
'js/test-main.js'
];
// list of files to exclude
exclude = [
];
// test results reporter to use
// possible values: 'dots', 'progress', 'junit'
reporters = ['progress'];
// web server port
port = 9876;
// cli runner port
runnerPort = 9100;
// enable / disable colors in the output (reporters and logs)
colors = true;
// level of logging
// possible values: LOG_DISABLE || LOG_ERROR || LOG_WARN || LOG_INFO || LOG_DEBUG
logLevel = LOG_INFO;
// enable / disable watching file and executing tests whenever any file changes
autoWatch = true;
// Start these browsers, currently available:
// - Chrome
// - ChromeCanary
// - Firefox
// - Opera
// - Safari (only Mac)
// - PhantomJS
// - IE (only Windows)
browsers = ['Chrome'];
// If browser does not capture in given timeout [ms], kill it
captureTimeout = 60000;
// Continuous Integration mode
// if true, it capture browsers, run tests and exit
singleRun = false;
|
$(function() {
CMS.init({
// Name of your site or location of logo file, relative to root directory (img/logo.png)
siteName: 'Relevé',
// Tagline for your site
siteTagline: 'a movement in which the dancer rises on the tips of the toes',
// Email address
siteEmail: 'jaeck@releve.io',
// Name
siteAuthor: 'Jacek Relevé',
// Navigation items
siteNavItems: [
{ name: 'Github', href: 'https://github.com/releve', newWindow: false},
{ name: 'About'}
],
// Posts folder name
postsFolder: 'posts',
// Homepage posts snippet length
postSnippetLength: 120,
// Pages folder name
pagesFolder: 'pages',
// Order of sorting (true for newest to oldest)
sortDateOrder: true,
// Posts on Frontpage (blog style)
postsOnFrontpage: true,
// Page as Frontpage (static)
pageAsFrontpage: '',
// Posts/Blog on different URL
postsOnUrl: '',
// Site fade speed
fadeSpeed: 300,
// Site footer text
footerText: '© ' + new Date().getFullYear() + ' All Rights Reserved.',
// Mode 'Github' for Github Pages, 'Server' for Self Hosted. Defaults
// to Github
mode: 'Github',
// If Github mode is set, your Github username and repo name.
githubUserSettings: {
username: 'releve',
repo: 'releve.github.io'
},
// If Github mode is set, choose which Github branch to get files from.
// Defaults to Github pages branch (gh-pages)
githubSettings: {
branch: 'gh-pages',
host: 'https://api.github.com'
}
});
// Markdown settings
marked.setOptions({
renderer: new marked.Renderer(),
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: true,
smartLists: true,
smartypants: false
});
});
|
/*
* browser.js
*
* Created by MG on 2015/12/09.
* Copyright (c) 2015 MG. All rights reserved.
*/
var browser = {
versions: (function() {
var u = navigator.userAgent,
app = navigator.appVersion;
return {
trident: u.indexOf('Trident') > -1, // Internet Explorer
presto: u.indexOf('Presto') > -1, // Opera
webKit: u.indexOf('AppleWebKit') > -1, // Safari / Chrome
gecko: u.indexOf('Gecko') > -1 && u.indexOf('KHTML') === -1, // Firefox
mobile: !!u.match(/AppleWebKit.*Mobile.*/), // Mobile
ios: !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/), // iOS
android: u.indexOf('Android') > -1 || u.indexOf('Linux') > -1, // Android
iPhone: u.indexOf('iPhone') > -1, // iPhone
iPad: u.indexOf('iPad') > -1, // iPad
webApp: u.indexOf('Safari') === -1, //
weixin: u.indexOf('MicroMessenger') > -1, // WeChat
qq: u.match(/\sQQ/i) === ' qq', // QQ
fb: (u.indexOf('FBAN') > -1) || (u.indexOf('FBAV') > -1) // Facebook
};
})(),
query: (function() {
var url = location.search;
var req = {};
if (url.indexOf('?') !== -1) {
var str = url.substr(1);
var strs = str.split('&');
for (var i = 0; i < strs.length; i++) {
var strcomps = strs[i].split('=');
req[strcomps[0]] = decodeURIComponent(strcomps[1]);
}
}
return req;
})(),
language: (navigator.browserLanguage || navigator.language).toLowerCase(),
interactionEvent: 'click ontouchstart'
};
|
//! A page of the application. Contains the basic structure of the GUI including title, header, navigation, and footer.
import React from 'react';
import { connect } from 'dva';
import { Layout } from 'antd';
const { Header, Content, Footer, Sider } = Layout;
import DashHeader from './DashHeader';
import gstyles from '../static/css/globalStyle.css';
class AppPage extends React.Component {
render() {
return (
<Layout className={gstyles.application}>
<DashHeader title={this.props.title} />
<Content className={gstyles.content}>
{this.props.children}
</Content>
<Footer style={{ textAlign: 'center' }}>
TickGrinder Algorithmic Trading Platform; Created by Casey Primozic ©2017
</Footer>
</Layout>
);
}
}
function mapProps(state) {
return { title: state.global.title };
}
export default connect(mapProps)(AppPage);
|
/*global describe, it, beforeEach*/
define([
'expect',
'src/EventsEmitter'
], function (expect, EventsEmitter) {
'use strict';
describe('EventsEmitter', function () {
var emitter,
stack = [],
args = [],
context = {};
beforeEach(function () {
emitter = new EventsEmitter();
stack = [];
args = [];
});
describe('.on()', function () {
it('should add the specified listener to an event', function () {
emitter.on('click', function (arg1, arg2, arg3) {
stack.push('one');
if (arg1) {
args.push(arg1);
}
if (arg2) {
args.push(arg2);
}
if (arg3) {
args.push(arg3);
}
});
emitter.on('click', function (arg1, arg2, arg3) {
stack.push('two');
if (arg1) {
args.push(arg1);
}
if (arg2) {
args.push(arg2);
}
if (arg3) {
args.push(arg3);
}
});
emitter.on('click_dummy', function () {
stack.push('dummy');
});
emitter.emit('click', 1, 2, 3);
expect(stack).to.eql(['one', 'two']);
expect(args).to.eql([1, 2, 3, 1, 2, 3]);
});
it('should be able to specify the desired context', function () {
emitter.on('click', function () {
expect(this).to.be.equal(context);
}, context);
emitter.emit('click');
});
it('should not duplicate the same listener', function () {
function SomeClass() {}
SomeClass.prototype.foo = function () {
stack.push('foo');
};
var listener = function () {
stack.push('listener');
},
some1 = new SomeClass(),
some2 = new SomeClass();
emitter.on('other', listener);
emitter.on('other', listener);
emitter.emit('other');
emitter.on('foo', some1.foo, some1);
emitter.on('foo', some2.foo, some2);
emitter.emit('foo');
expect(stack).to.eql(['listener', 'foo', 'foo']);
});
});
describe('.once(event, fn, $context)', function () {
it('should listen only once', function () {
emitter.on('click', function () {
stack.push('one');
});
emitter.once('click', function () {
stack.push('two');
});
emitter.emit('click');
emitter.emit('click');
expect(stack).to.eql(['one', 'two', 'one']);
});
it('should be equal to on()', function () {
expect(emitter.once).to.be(emitter.one);
});
it('should remove the listener before executing the function', function () {
emitter.once('click', function () {
stack.push('one');
emitter.emit('click');
});
emitter.emit('click');
expect(stack).to.eql(['one']);
});
});
describe('.off(event, fn, $context)', function () {
it('should remove the specified listener', function () {
var listener = function () {
stack.push('listener');
},
other = function () {
stack.push('other');
},
once = function () {
stack.push('once');
},
context = {};
emitter.on('dummy', listener);
emitter.on('click', listener, context);
emitter.on('click', other);
emitter.once('click', once, context);
emitter.once('click', once);
emitter.off('click', listener);
emitter.off('click', once);
emitter.off('click', once, context);
emitter.emit('click');
emitter.off('click', listener, context);
emitter.emit('click');
emitter.off('click', other);
emitter.emit('click');
emitter.emit('dummy');
expect(stack).to.eql(['listener', 'other', 'other', 'listener']);
});
it('should not error out if the listener is removed several times', function () {
var listener = function () {
emitter.off('click', listener);
emitter.off('click', listener);
};
emitter.on('click', listener);
expect(function () {
emitter.emit('click');
}).to.not.throwException();
});
});
describe('.off($event.namespace, fn, $context)', function () {
it('should remove the specified listener', function () {
var listener = function () {
stack.push('listener');
},
other = function () {
stack.push('other');
},
once = function () {
stack.push('once');
},
context = {};
emitter.on('dummy.foo', listener);
emitter.on('click.foo', listener, context);
emitter.on('click.foo', other);
emitter.once('click.foo', once, context);
emitter.once('click.foo', once);
emitter.off('click.foo', listener);
emitter.off('click.foo', once);
emitter.off('click.foo', once, context);
emitter.emit('click');
emitter.off('click.foo', listener, context);
emitter.emit('click');
emitter.off('click.foo', other);
emitter.emit('click');
emitter.emit('dummy');
expect(stack).to.eql(['listener', 'other', 'other', 'listener']);
});
it('should remove the specified listener, just by its namespace', function () {
var listener = function () {
stack.push('listener');
},
other = function () {
stack.push('other');
},
once = function () {
stack.push('once');
},
context = {};
emitter.on('dummy.foo', listener);
emitter.on('click.foo', listener, context);
emitter.on('click.foo', other);
emitter.once('click.foo', once, context);
emitter.once('click.foo', once);
emitter.off('click.foo', listener);
emitter.off('.foo', once);
emitter.off('.foo', once, context);
emitter.emit('click');
emitter.off('.foo', listener, context);
emitter.emit('click');
emitter.off('.foo', other);
emitter.emit('click');
emitter.emit('dummy');
expect(stack).to.eql(['listener', 'other', 'other', 'listener']);
});
it('should not error out if the listener is removed several times', function () {
var listener = function () {
emitter.off('click.foo', listener);
emitter.off('click.foo', listener);
};
emitter.on('click.foo', listener);
expect(function () {
emitter.emit('click');
}).to.not.throwException();
});
});
describe('.off($event)', function () {
var listener1 = function () {
stack.push('listener1');
},
listener2 = function () {
stack.push('listener2');
},
listener3 = function () {
stack.push('listener3');
};
it('should remove all the listeners of a given event', function () {
emitter.on('click', listener1);
emitter.on('click', listener2);
emitter.on('dummy', listener3);
emitter.emit('click');
emitter.emit('dummy');
emitter.off('click');
emitter.emit('click');
emitter.emit('dummy');
expect(stack).to.eql(['listener1', 'listener2', 'listener3', 'listener3']);
});
it('should remove all the listeners (if no event is specified)', function () {
emitter.on('click', listener1);
emitter.on('click', listener2);
emitter.on('dummy', listener3);
emitter.emit('click');
emitter.emit('dummy');
emitter.off();
emitter.emit('click');
emitter.emit('dummy');
expect(stack).to.eql(['listener1', 'listener2', 'listener3']);
});
it('should not error out if the listener is removed several times', function () {
var listener = function () {
emitter.off('click.foo');
emitter.off('click.foo');
};
emitter.on('click.foo', listener);
expect(function () {
emitter.emit('click');
}).to.not.throwException();
});
});
describe('.off($event.namespace)', function () {
var listener1 = function () {
stack.push('listener1');
},
listener2 = function () {
stack.push('listener2');
},
listener3 = function () {
stack.push('listener3');
};
it('should remove all the listeners of a given event just on the passed namespace', function () {
emitter.on('click', listener1);
emitter.on('click.foo', listener2);
emitter.on('dummy', listener3);
emitter.emit('click');
emitter.emit('dummy');
emitter.off('click.foo');
emitter.emit('click');
emitter.emit('dummy');
expect(stack).to.eql(['listener1', 'listener2', 'listener3', 'listener1', 'listener3']);
});
it('should remove all the listeners of the namespace (if no event is specified)', function () {
emitter.on('click', listener1);
emitter.on('click.foo', listener2);
emitter.on('dummy.bar', listener3);
emitter.emit('click');
emitter.emit('dummy');
emitter.off('.foo');
emitter.off('.bar');
emitter.emit('click');
emitter.emit('dummy');
expect(stack).to.eql(['listener1', 'listener2', 'listener3', 'listener1']);
});
it('should not error out when used with .once()', function () {
emitter.once('foo.bar', function () {
emitter.off();
});
expect(function () {
emitter.emit('foo');
}).to.not.throwException();
});
it('should not error out if the listener is removed several times', function () {
var listener = function () {
emitter.off('click');
emitter.off('click');
};
emitter.on('click', listener);
expect(function () {
emitter.emit('click');
}).to.not.throwException();
});
});
describe('.has()', function () {
it('should should return true for added listeners and false for not added listeners', function () {
var someFunc = function () {},
otherFunc = function () {};
expect(emitter.has('click', someFunc)).to.be.equal(false);
expect(emitter.has('click')).to.be.equal(false);
emitter.on('click', someFunc);
emitter.on('click', otherFunc);
expect(emitter.has('click', someFunc)).to.be.equal(true);
expect(emitter.has('click', otherFunc)).to.be.equal(true);
expect(emitter.has('click')).to.be.equal(true);
expect(emitter.has('mouseover')).to.be.equal(false);
emitter.off('click', someFunc);
expect(emitter.has('click', someFunc)).to.be.equal(false);
expect(emitter.has('click', otherFunc)).to.be.equal(true);
expect(emitter.has('click')).to.be.equal(true);
emitter.off('click', otherFunc);
expect(emitter.has('click', otherFunc)).to.be.equal(false);
expect(emitter.has('click')).to.be.equal(false);
});
it('should return false even if there are "junk" listeners', function () {
var fn = function () {
emitter.off('click', fn);
};
emitter.on('click', fn);
emitter.emit('click');
expect(emitter.has('click')).to.be.equal(false);
});
it('should work with namespaces', function () {
var someFunc = function () {},
otherFunc = function () {};
emitter.on('click.foo', someFunc);
emitter.on('click.bar', otherFunc);
expect(emitter.has('.foo', someFunc)).to.be.equal(true);
expect(emitter.has('.foo', otherFunc)).to.be.equal(false);
expect(emitter.has('.bar')).to.be.equal(true);
expect(emitter.has('.other')).to.be.equal(false);
});
});
describe('.emit()', function () {
it('should respect the order of emit calls', function () {
var listener = function () {
stack.push('one');
},
listener2 = function () {
emitter.emit('ghost');
emitter.emit('other');
stack.push('two');
},
listener3 = function () {
stack.push('three');
},
listener4 = function () {
stack.push('four');
};
emitter.on('some', listener);
emitter.on('some', listener2);
emitter.on('some', listener3);
emitter.on('other', listener4);
emitter.emit('some');
expect(stack).to.eql(['one', 'four', 'two', 'three']);
});
it('should call listeners added while dispatching', function () {
var listener = function () {
stack.push('one');
emitter.on('some', listener2);
},
listener2 = function () {
stack.push('two');
};
emitter.on('some', listener);
emitter.emit('some');
expect(stack).to.eql(['one', 'two']);
});
it('should not call listeners removed while dispatching', function () {
var listener = function () {
stack.push('one');
emitter.off('other', listener2);
emitter.on('other', listener5);
},
listener2 = function () {
stack.push('two');
},
listener3 = function () {
emitter.off('other', listener);
stack.push('three');
},
listener4 = function () {
emitter.off('other', listener3);
emitter.on('other', listener6);
stack.push('four');
},
listener5 = function () {
stack.push('five');
},
listener6 = function () {
stack.push('six');
};
emitter.on('other', listener);
emitter.on('other', listener2);
emitter.on('other', listener3);
emitter.on('other', listener4);
emitter.emit('other');
expect(stack).to.eql(['one', 'three', 'four', 'five', 'six']);
});
it('should handle removing all listeners while dispatching', function () {
var listener = function () {
stack.push('one');
emitter.off();
},
listener2 = function () {
stack.push('two');
},
listener3 = function () {
stack.push('three');
};
emitter.on('some', listener);
emitter.on('some', listener2);
emitter.on('some', listener3);
emitter.emit('some');
expect(stack).to.eql(['one']);
stack = [];
emitter.off();
listener = function () {
stack.push('one');
emitter.off('some', listener2);
emitter.off('some', listener3);
};
listener2 = function () {
stack.push('two');
};
listener3 = function () {
stack.push('three');
};
emitter.on('some', listener);
emitter.on('some', listener2);
emitter.on('some', listener3);
emitter.emit('some');
expect(stack).to.eql(['one']);
});
it('should not catch any inner listener error', function () {
emitter.on('err', function () {
throw new Error('dummy error');
});
expect(function () {
emitter.emit('err');
}).to.throwException(/dummy error/);
});
it('should behave normally after a listener throws an error', function () {
var listener = function () {
stack.push('one');
},
listener2 = function () {
emitter.emit('other');
stack.push('two');
},
listener3 = function () {
throw new Error('dummy error');
},
listener4 = function () {
stack.push('four');
};
emitter.on('some', listener);
emitter.on('some', listener2);
emitter.on('some', listener3);
emitter.on('other', listener4);
expect(function () {
emitter.emit('some');
}).to.throwException(/dummy error/);
expect(function () {
emitter.emit('some');
}).to.throwException(/dummy error/);
expect(stack).to.eql(['one', 'four', 'two', 'one', 'four', 'two']);
});
});
describe('.forEach()', function () {
it('should cycle through all the events', function () {
emitter.forEach(function (event, fn) {
stack.push(event, fn);
});
var ctx = {},
listener = function () {
emitter.forEach(function (event, fn) {
stack.push(event, fn);
});
emitter.off('some', listener2);
emitter.off('some', listener3);
emitter.forEach(function (event, fn, context) {
stack.push(event, fn);
if (event === 'other') {
expect(context).to.be(ctx);
}
});
},
listener2 = function () {},
listener3 = function () {},
listener4 = function () {};
emitter.on('some', listener);
emitter.on('some', listener2);
emitter.on('some', listener3);
emitter.on('other', listener4, ctx);
emitter.emit('some');
expect(stack).to.eql(['some', listener, 'some', listener2, 'some', listener3, 'other', listener4, 'some', listener, 'other', listener4]);
});
it('should be able to execute the handler with the given context', function () {
var listener = function () {
stack.push(this);
},
listener2 = function () {
stack.push(this);
},
context = {};
emitter.on('some', listener);
emitter.on('some', listener2, context);
emitter.emit('some');
expect(stack.length).to.be.eql(2);
expect(stack[0]).to.be.eql(emitter);
expect(stack[1]).to.be.eql(context);
});
});
});
});
|
(function(angular) {
'use strict';
angular.module('scrum-dashboard-api').factory('Sprint', SprintFactory);
function SprintFactory($resource) {
return $resource('/api/v1/sprint/:sprintId', {
sprintId: '@id',
});
}
})(window.angular); |
$(document).ready(function () {
$('#container').highcharts({
chart: {
type: 'scatter',
zoomType: 'xy'
},
title: {
text: 'Masturbation level based on satisfaction with own sexlife'
},
subtitle: {
text: 'Source: Så liggar Sverige'
},
xAxis: {
title: {
enabled: true,
text: 'Satisfaction level 1-5 (the higher number, the more satisfied)'
},
startOnTick: false,
endOnTick: false,
showLastLabel: true
},
yAxis: {
title: {
text: 'Avg. masturbations per month'
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: 00,
y: 30,
floating: true,
backgroundColor: '#ffffff',
borderWidth: 1
},
plotOptions: {
scatter: {
marker: {
radius: 5,
states: {
hover: {
enabled: true,
lineColor: 'rgb(100,100,100)'
}
}
},
states: {
hover: {
marker: {
enabled: false
}
}
},
tooltip: {
headerFormat: '<b>{series.name}</b><br>',
pointFormat: 'Satisfaction level {point.x}, {point.y} masturbations'
}
}
},
series: [{
name: 'Female',
color: 'rgba(223, 83, 83, .5)',
data: [[1,2.96],[2,3.77],[3,2.37],[4,2.88],[5,3.32]]
}, {
name: 'Male',
color: 'rgba(119, 152, 191, .5)',
data: [[1, 13.85], [2, 9.31],[3, 7.72],[4,6.91],[5,7.36]]
},
{
type: 'line',
name: 'Male regression line',
data: [[1,12.11],[5,5.96]],
marker: {
enabled: false
},
states: {
hover: {
lineWidth: 0
}
},
enableMouseTracking: false
},
{
type: 'line',
name: 'Female regression line',
data: [[1,3.1],[5,3.02]],
marker: {
enabled: false
},
states: {
hover: {
lineWidth: 0
}
},
enableMouseTracking: false
}]
});
var s = "<h3>What does this tell us?</h3>";
s += "<p>Not only do men masturbate more. They also seem to use it as a substitute for sex with their partner, ie. the more satisfied they are with their own sexlife, the less they tend to masturbate. For women there doesn't seem to be any correlation between how satisfied they are with their sexlife and how much they masturbate. This is one of the few stats with a clear difference between men and women.</p>";
s += "<h3>Data quality</h3>";
s += "<h4>Men</h4>";
s += "<p>Sample size men: 1358</p>";
s += "Regression function: y = -1,5375x + 13,642";
s += "<p>R<sup>2</sup>: 0,73147</p>";
s += "<h4>Women</h4>";
s += "<p>Sample size women: 1310</p>";
s += "Regression function: y = -0,0191x + 3,1187";
s += "<p>R<sup>2</sup>: 0,0034</p>";
$("#details").append(s);
});
|
import {test} from 'j0';
export default function tests(fill, title) {
test(title, (test) => {
const v0 = 'v0';
const v1 = 'v1';
const v2 = 'v2';
const v3 = 'v3';
const v4 = 'v4';
const v5 = 'v5';
for (const [value, start, end, expected] of [
[v0, 3, undefined, [v1, v2, v3, v0, v0]],
[v0, 3, 4, [v1, v2, v3, v0, v5]],
[v0, 3, -1, [v1, v2, v3, v0, v5]],
[v0, -4, 0, [v1, v2, v3, v4, v5]],
[v0, -4, 3, [v1, v0, v0, v4, v5]],
[v0, -4, -2, [v1, v0, v0, v4, v5]],
]) {
test(`fill(${value}, ${start}, ${end}) → [${expected.join(', ')}]`, (test) => {
const array = [v1, v2, v3, v4, v5];
const actual = fill.call(array, value, start, end);
test.compare(actual, array);
test.compare(actual, expected);
});
}
});
}
|
let moduleRoot = '../es6';
if (process.env.TEST_RELEASE) {
moduleRoot = '../dist';
}
const datauri = require(moduleRoot);
const txt = `${__dirname}/fixture/test.txt`;
const html = `${__dirname}/fixture/test.html`;
describe('fileToDatauri', () => {
it('works with promise ', async () => {
const result = await datauri(txt);
result.should.be.equal('data:text/plain;charset=utf-8;base64,dGhpcyBpcyBhIHRlc3QK');
});
it('set mime by extension', async () => {
const result = await datauri(html);
result.should.be.equal('data:text/html;charset=utf-8;base64,dGhpcyBpcyBhIHRlc3QK');
});
it('works sync', () => {
const result = datauri.sync(txt);
result.should.be.equal('data:text/plain;charset=utf-8;base64,dGhpcyBpcyBhIHRlc3QK');
});
it('works with callbacks', done => {
datauri(txt, (err, result) => {
if (err) {
return done(err);
}
result.should.be.equal('data:text/plain;charset=utf-8;base64,dGhpcyBpcyBhIHRlc3QK');
done();
});
});
});
|
import { divvy, breakpoint } from 'hedron/lib/utils/';
export const compute = name =>
breakpoint(name, (props, name) =>
((divisions, size, shift) => `
${size ? `width: ${divvy(divisions, size)}%;` : ''}
${shift ? `margin-left: ${divvy(divisions, shift)}%;` : ''}
`)(props.divisions, props[name], props[`${name}Shift`]));
export const ifDefined = (prop, css = prop) =>
props => props[prop] ? `${css}: ${props[prop]}` : '';
|
#!/usr/bin/env node
(function() {
'use strict';
var compressor = require('node-minify');
var fileIn = __dirname + "/../dist/js/graph_editor.js";
var fileOut = __dirname + "/../dist/js/graph_editor-min.js";
new compressor.minify({
type: "uglifyjs",
fileIn: fileIn,
fileOut: fileOut,
callback: function(err){
}
});
})(); |
var http = require("http"),
request = require("@nathanfaucett/request"),
Benchmark = require("benchmark"),
express = require("express"),
layers = require("..");
var suite = new Benchmark.Suite(),
layersServer, expressServer;
function createLayersServer() {
var server, router;
if (!layersServer) {
server = layersServer = new http.Server(),
router = layers.Router.create();
router.use(function(req, res, next) {
next();
});
router.use(
"/grand_parent/:parent_id/grand_child",
function(req, res, next) {
next();
}
);
var scope = router.scope("/grand_parent/:parent_id/grand_child");
scope.route("/parent/:id/child")
.get(
function(req, res, next) {
next();
}
);
scope.route("/parent/:id/child")
.get(
function(req, res, next) {
next();
}
);
server.on("request", function(req, res) {
router.handler(req, res);
});
server.listen(9997);
}
}
function createExpressServer() {
var server, app;
if (!expressServer) {
server = expressServer = new http.Server(),
app = express();
server.on("request", app);
app.use(function(req, res, next) {
next();
});
app.use(
"/grand_parent/:parent_id/grand_child",
function(req, res, next) {
next();
}
);
app.get(
"/grand_parent/:parent_id/grand_child",
function(req, res, next) {
next();
}
);
app.get(
"/grand_parent/:parent_id/grand_child/parent/:id/child",
function(req, res, next) {
next();
}
);
server.listen(9999);
}
}
suite.add({
name: "express",
defer: true,
fn: function(deferred) {
createExpressServer();
function done() {
deferred.resolve();
expressServer.close();
}
request.get("http://localhost:9999/grand_parent", {
success: done,
error: done
});
}
});
suite.add({
name: "express_fullpath",
defer: true,
fn: function(deferred) {
createExpressServer();
function done() {
deferred.resolve();
expressServer.close();
}
request.get("http://localhost:9999/grand_parent/1/grand_child/parent/1/child", {
success: done,
error: done
});
}
});
suite.add({
name: "layers",
defer: true,
fn: function(deferred) {
createLayersServer();
function done() {
deferred.resolve();
layersServer.close();
}
request.get("http://localhost:9997/grand_parent", {
success: done,
error: done
});
}
});
suite.add({
name: "layers_fullpath",
defer: true,
fn: function(deferred) {
createLayersServer();
function done() {
deferred.resolve();
layersServer.close();
}
request.get("http://localhost:9997/grand_parent/1/grand_child/parent/1/child", {
success: done,
error: done
});
}
});
suite.on("cycle", function(event) {
console.log(String(event.target));
});
suite.on("complete", function() {
console.log("Fastest is " + this.filter("fastest").map("name"));
console.log("==========================================\n");
});
console.log("\n= middleware =================================");
suite.run();
|
// Regular expression that matches all symbols in the Mathematical Alphanumeric Symbols block as per Unicode v6.2.0:
/\uD835[\uDC00-\uDFFF]/; |
var bodyParser = require('body-parser');
var express = require('express');
var multer = require('multer');
module.exports = function createDynamicRouter (keystone) {
// ensure keystone nav has been initialised
// TODO: move this elsewhere (on demand generation, or client-side?)
if (!keystone.nav) {
keystone.nav = keystone.initNav();
}
var router = express.Router();
var IndexRoute = require('../routes/index');
var SigninRoute = require('../routes/signin');
var SignoutRoute = require('../routes/signout');
// Use bodyParser and multer to parse request bodies and file uploads
router.use(bodyParser.json({}));
router.use(bodyParser.urlencoded({ extended: true }));
router.use(multer({ includeEmptyFields: true }));
// Bind the request to the keystone instance
router.use(function (req, res, next) {
req.keystone = keystone;
next();
});
if (keystone.get('healthchecks')) {
router.use('/server-health', require('./createHealthchecksHandler')(keystone));
}
// Init API request helpers
router.use('/api', require('../middleware/apiError'));
router.use('/api', require('../middleware/logError'));
// #1: Session API
// TODO: this should respect keystone auth options
router.get('/api/session', require('../api/session/get'));
router.post('/api/session/signin', require('../api/session/signin'));
router.post('/api/session/signout', require('../api/session/signout'));
// #2: Session Routes
// Bind auth middleware (generic or custom) to * routes, allowing
// access to the generic signin page if generic auth is used
if (keystone.get('auth') === true) {
// TODO: poor separation of concerns; settings should be defaulted elsewhere
if (!keystone.get('signout url')) {
keystone.set('signout url', '/' + keystone.get('admin path') + '/signout');
}
if (!keystone.get('signin url')) {
keystone.set('signin url', '/' + keystone.get('admin path') + '/signin');
}
if (!keystone.nativeApp || !keystone.get('session')) {
router.all('*', keystone.session.persist);
}
router.all('/signin', SigninRoute);
router.all('/signout', SignoutRoute);
router.use(keystone.session.keystoneAuth);
} else if (typeof keystone.get('auth') === 'function') {
router.use(keystone.get('auth'));
}
// #3: Home route
router.get('/', IndexRoute);
// #4: Cloudinary and S3 specific APIs
// TODO: poor separation of concerns; should / could this happen elsewhere?
if (keystone.get('cloudinary config')) {
router.get('/api/cloudinary/get', require('../api/cloudinary').get);
router.get('/api/cloudinary/autocomplete', require('../api/cloudinary').autocomplete);
router.post('/api/cloudinary/upload', require('../api/cloudinary').upload);
}
if (keystone.get('s3 config')) {
router.post('/api/s3/upload', require('../api/s3').upload);
}
// #5: Core Lists API
var initList = require('../middleware/initList');
// lists
router.all('/api/counts', require('../api/counts'));
router.get('/api/:list', initList, require('../api/list/get'));
router.get('/api/:list/:format(export.csv|export.json)', initList, require('../api/list/download'));
router.post('/api/:list/create', initList, require('../api/list/create'));
router.post('/api/:list/update', initList, require('../api/list/update'));
router.post('/api/:list/:id/duplicate', initList, require('../api/list/duplicate'));
router.post('/api/:list/delete', initList, require('../api/list/delete'));
// items
router.get('/api/:list/:id', initList, require('../api/item/get'));
router.post('/api/:list/:id', initList, require('../api/item/update'));
router.post('/api/:list/:id/delete', initList, require('../api/list/delete'));
router.post('/api/:list/:id/sortOrder/:sortOrder/:newOrder', initList, require('../api/item/sortOrder'));
// #6: List Routes
router.all('/:list/:page([0-9]{1,5})?', IndexRoute);
router.all('/:list/:item', IndexRoute);
// TODO: catch 404s and errors with Admin-UI specific handlers
return router;
};
|
var about = angular.module('imasd.about', ['ngRoute']);
about.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/about', {
templateUrl: 'about/about.html',
controller: 'about'
});
$routeProvider.when('/misionVision', {
templateUrl: 'about/misionVision.html',
controller: 'misionVision'
});
$routeProvider.when('/technologies', {
templateUrl: 'about/technologies.html',
controller: 'technologies'
});
$routeProvider.when('/alliances', {
templateUrl: 'about/alliances.html',
controller: 'alliances'
});
}]);
about.controller('about', ['$scope', function($scope) {
//Clave de diccionario.
$scope.dictionary_key = 'aboutUs';
}]);
about.controller('misionVision', ['$scope', function($scope) {
//Clave de diccionario.
$scope.dictionary_key = 'mision';
}]);
about.controller('technologies', ['$scope', function($scope) {
//Clave de diccionario.
$scope.dictionary_key = 'technologies';
//Tecnologias
$scope.technologies=[
'Ajax','AngularJs','Bootflat','Botstrap','Bower','CSS3','Dojo','Git','Hibernate',
'HTML5','Java','JPA','Yeoman','JQuery','JSON','Jstl-Jsp','Maven','MongoDB',
'MsSQL','MySQL','Node','PHP','Spring Roo','Spring Security','Spring tool suite',
'Spring','Subversion','XML','Javascript'
];
}]);
about.controller('alliances', ['$scope', function($scope) {
//Clave de diccionario.
$scope.dictionary_key = 'alliances';
}]); |
/**
* This file is where you define your application routes and controllers.
*
* Start by including the middleware you want to run for every request;
* you can attach middleware to the pre('routes') and pre('render') events.
*
* For simplicity, the default setup for route controllers is for each to be
* in its own file, and we import all the files in the /routes/views directory.
*
* Each of these files is a route controller, and is responsible for all the
* processing that needs to happen for the route (e.g. loading data, handling
* form submissions, rendering the view template, etc).
*
* Bind each route pattern your application should respond to in the function
* that is exported from this module, following the examples below.
*
* See the Express application routing documentation for more information:
* http://expressjs.com/api.html#app.VERB
*/
var _ = require('underscore'),
keystone = require('keystone'),
middleware = require('./middleware'),
importRoutes = keystone.importer(__dirname);
// Common Middleware
keystone.pre('routes', middleware.initLocals);
keystone.pre('render', middleware.flashMessages);
// Import Route Controllers
var routes = {
views: importRoutes('./views')
};
// Setup Route Bindings
exports = module.exports = function(app) {
// Views
app.get('/', routes.views.index);
app.get('/report/:category?', routes.views.report);
app.get('/report/post/:post', routes.views.post);
//app.get('/report/post/ppt/:ppt',routes.views.ppt);
app.all('/marking', routes.views.marking);
// added
// Session
app.all('/join', routes.views.session.join);
app.all('/signin', routes.views.session.signin);
app.get('/signout', routes.views.session.signout);
app.all('/forgot-password', routes.views.session['forgot-password']);
app.all('/reset-password/:key', routes.views.session['reset-password']);
// NOTE: To protect a route so that only admins can see it, use the requireUser middleware:
// app.get('/protected', middleware.requireUser, routes.views.protected);
};
|
describe('DEBUG mode:', function() {
beforeEach(function() {
this.channel = Backbone.Radio.channel('myChannel');
this.Commands = _.clone(Backbone.Radio.Commands);
this.Requests = _.clone(Backbone.Radio.Requests);
stub(console, 'warn');
});
describe('when turned on', function() {
beforeEach(function() {
Backbone.Radio.DEBUG = true;
});
it('should log a console warning when firing a command on a channel without a handler', function() {
this.channel.command('some:event');
this.warning = 'An unhandled command was fired on the myChannel channel: "some:event"';
expect(console.warn).to.have.been.calledOnce.and.calledWithExactly(this.warning);
});
it('should log a console warning when firing a request on a channel without a handler', function() {
this.channel.request('some:event');
this.warning = 'An unhandled request was fired on the myChannel channel: "some:event"';
expect(console.warn).to.have.been.calledOnce.and.calledWithExactly(this.warning);
});
it('should log a console warning when firing a command on an object without a handler', function() {
this.Commands.command('some:event');
this.warning = 'An unhandled command was fired: "some:event"';
expect(console.warn).to.have.been.calledOnce.and.calledWithExactly(this.warning);
});
it('should log a console warning when firing a request on an object without a handler', function() {
this.Requests.request('some:event');
this.warning = 'An unhandled request was fired: "some:event"';
expect(console.warn).to.have.been.calledOnce.and.calledWithExactly(this.warning);
});
it('should log a console warning when unregistering a command that was never registered on a channel', function() {
this.channel.stopComplying('some:event');
this.warning = 'Attempted to remove the unregistered command on the myChannel channel: "some:event"';
expect(console.warn).to.have.been.calledOnce.and.calledWithExactly(this.warning);
});
it('should log a console warning when unregistering a request that was never registered on a channel', function() {
this.channel.stopReplying('some:event');
this.warning = 'Attempted to remove the unregistered request on the myChannel channel: "some:event"';
expect(console.warn).to.have.been.calledOnce.and.calledWithExactly(this.warning);
});
it('should log a console warning when unregistering a command that was never registered on an object', function() {
this.Commands.stopComplying('some:event');
this.warning = 'Attempted to remove the unregistered command: "some:event"';
expect(console.warn).to.have.been.calledOnce.and.calledWithExactly(this.warning);
});
it('should log a console warning when unregistering a request that was never registered on an object', function() {
this.Requests.stopReplying('some:event');
this.warning = 'Attempted to remove the unregistered request: "some:event"';
expect(console.warn).to.have.been.calledOnce.and.calledWithExactly(this.warning);
});
it('should log a console warning when unregistering a command that was never registered on an object', function() {
this.Commands.comply('some:event');
this.Commands.stopComplying('some:event');
expect(console.warn).to.not.have.been.called;
});
it('should log a console warning when unregistering a request that was never registered on an object', function() {
this.Requests.reply('some:event');
this.Requests.stopReplying('some:event');
expect(console.warn).to.not.have.been.called;
});
it('should log a console warning when unregistering a callback that was never registered on an object', function() {
this.Commands.stopComplying(undefined, function() {});
this.warning = 'Attempted to remove the unregistered command: "undefined"';
expect(console.warn).to.have.been.calledOnce.and.calledWithExactly(this.warning);
});
it('should log a console warning when unregistering a callback that was never registered on an object', function() {
this.Requests.stopReplying(undefined, function() {});
this.warning = 'Attempted to remove the unregistered request: "undefined"';
expect(console.warn).to.have.been.calledOnce.and.calledWithExactly(this.warning);
});
it('should not log a console warning when unregistering a callback that was registered on an object', function() {
this.callback = function() {};
this.Commands.comply('some:event', this.callback);
this.Commands.stopComplying(undefined, this.callback);
expect(console.warn).to.not.have.been.called;
});
it('should not log a console warning when unregistering a callback that was registered on an object', function() {
this.callback = function() {};
this.Requests.reply('some:event', this.callback);
this.Requests.stopReplying(undefined, this.callback);
expect(console.warn).to.not.have.been.called;
});
it('should log a console warning when unregistering a context that was never registered on an object', function() {
this.Commands.stopComplying(undefined, undefined, {});
this.warning = 'Attempted to remove the unregistered command: "undefined"';
expect(console.warn).to.have.been.calledOnce.and.calledWithExactly(this.warning);
});
it('should log a console warning when unregistering a context that was never registered on an object', function() {
this.Requests.stopReplying(undefined, undefined, {});
this.warning = 'Attempted to remove the unregistered request: "undefined"';
expect(console.warn).to.have.been.calledOnce.and.calledWithExactly(this.warning);
});
it('should not log a console warning when unregistering a context that was registered on an object', function() {
this.context = {};
this.Commands.comply('some:event', function() {}, this.context);
this.Commands.stopComplying(undefined, undefined, this.context);
expect(console.warn).to.not.have.been.called;
});
it('should not log a console warning when unregistering a context that was registered on an object', function() {
this.context = {};
this.Requests.reply('some:event', function() {}, this.context);
this.Requests.stopReplying(undefined, undefined, this.context);
expect(console.warn).to.not.have.been.called;
});
it('should not log a console warning when unregistering all commands when none were registered', function() {
this.Commands.stopComplying();
expect(console.warn).to.not.have.been.called;
});
it('should not log a console warning when unregistering all requests when none were registered', function() {
this.Requests.stopReplying();
expect(console.warn).to.not.have.been.called;
});
it('should log a console warning when registering a command that already was registered', function() {
this.Commands.comply('some:event', function() {});
this.Commands.comply('some:event', function() {});
this.warning = 'A command was overwritten: "some:event"';
expect(console.warn).to.have.been.calledOnce.and.calledWithExactly(this.warning);
});
it('should log a console warning when registering a request that already was registered', function() {
this.Requests.reply('some:event', function() {});
this.Requests.reply('some:event', function() {});
this.warning = 'A request was overwritten: "some:event"';
expect(console.warn).to.have.been.calledOnce.and.calledWithExactly(this.warning);
});
});
describe('when turned off', function() {
it('should not log a console warning when firing a command on a channel without a handler', function() {
this.channel.command('some:event');
expect(console.warn).to.not.have.been.called;
});
it('should not log a console warning when firing a request on a channel without a handler', function() {
this.channel.request('some:event');
expect(console.warn).to.not.have.been.called;
});
it('should not log a console warning when firing a command on an object without a handler', function() {
this.Commands.command('some:event');
expect(console.warn).to.not.have.been.called;
});
it('should not log a console warning when firing a request on an object without a handler', function() {
this.Requests.request('some:event');
expect(console.warn).to.not.have.been.called;
});
it('should not log a console warning when unregistering a command that was never registered on a channel', function() {
this.channel.stopComplying('some:event');
expect(console.warn).to.not.have.been.called;
});
it('should not log a console warning when unregistering a request that was never registered on a channel', function() {
this.channel.stopReplying('some:event');
expect(console.warn).to.not.have.been.called;
});
it('should not log a console warning when unregistering a command that was never registered on an object', function() {
this.Commands.stopComplying('some:event');
expect(console.warn).to.not.have.been.called;
});
it('should not log a console warning when unregistering a request that was never registered on an object', function() {
this.Requests.stopReplying('some:event');
expect(console.warn).to.not.have.been.called;
});
it('should not log a console warning when registering a command that already was registered', function() {
this.Commands.comply('some:event', function() {});
this.Commands.comply('some:event', function() {});
expect(console.warn).to.not.have.been.called;
});
it('should not log a console warning when registering a request that already was registered', function() {
this.Requests.reply('some:event', function() {});
this.Requests.reply('some:event', function() {});
expect(console.warn).to.not.have.been.called;
});
});
});
|
let sketch = function(p) {
let initial_size = 5;
let initial_deviation = 350;
let deviation = 100;
let number_of_interpolations = 8;
let points;
let current;
let filename = 'landslide';
let auto_download = false;
let use_custom_seed = false;
let custom_seed = 77714660;
let use_custom_palette = false;
let current_palette = 'dusk';
let THE_SEED;
let palettes = {
hieronymus: [141, 20, 350, 208, 31, 96],
sunset: [265, 6, 325, 38, 255, 107],
fiery: [14, 234, 27, 356, 248, 53],
blue_mountain: [60, 241, 189, 246, 216, 185],
purple_green: [44, 1, 166, 286, 165, 80],
orange_purple: [335, 54, 198, 312, 91, 261],
lavarock: [200, 32, 359, 27, 208, 187],
dusk: [206, 61, 51, 224, 26, 40],
rainbow: [260, 83, 17, 68, 227, 297]
};
p.setup = function() {
p.createCanvas(2000, 1200);
p.noStroke();
p.colorMode(p.HSB);
p.blendMode(p.MULTIPLY);
if (use_custom_seed) p.noLoop();
};
p.draw = function() {
if (auto_download) saveToFile();
THE_SEED = use_custom_seed ? custom_seed : p.floor(p.random(99999999));
p.randomSeed(THE_SEED);
display();
};
function init(ypos) {
points = [];
for (var i = 0; i < initial_size; i++) {
let vec = p.createVector(i / (initial_size - 1) * p.width, ypos, p.random(-1, 1));
move_nearby(vec, initial_deviation);
points.push(vec);
}
for (let b = 0; b < number_of_interpolations; b++) {
interpolate(points, initial_deviation);
}
}
function update() {
let c = deep_copy(points);
for (let b = 0; b < 8; b++) {
for (let i = 0; i < c.length; i++) {
move_nearby(c[i], deviation);
}
}
return c;
}
function display() {
p.clear();
p.background('#fff');
for (var h = 0; h < 6; h++) {
init(h * 250 - 100);
let hue = use_custom_palette ? palettes[current_palette][h] : p.random(360);
//console.log(hue);
p.fill(hue, 100, 95, 0.012);
for (var i = 0; i < 45; i++) {
current = update();
display_row();
}
}
}
function display_row() {
p.beginShape();
p.vertex(0, current[0].y);
for (let i = 0; i < current.length; i++) {
p.vertex(current[i].x, current[i].y);
}
p.vertex(p.width, current[current.length - 1].y);
p.vertex(p.width, p.height);
p.vertex(0, p.height);
p.endShape(p.CLOSE);
}
function interpolate(points, sd) {
for (var i = points.length - 1; i > 0; i--) {
points.splice(i, 0, generate_midpoint(points[i - 1], points[i], sd));
}
}
function generate_midpoint(p1, p2, sd) {
let p3 = p.createVector((p1.x + p2.x) / 2, (p1.y + p2.y) / 2, (p1.z + p2.z) / 2 * 0.45 * p.random(0.1, 3));
move_nearby(p3, sd);
return p3;
}
let move_nearby = function(pnt, sd) {
pnt.x = p.randomGaussian(pnt.x, pnt.z * sd);
pnt.y = p.randomGaussian(pnt.y, pnt.z * sd);
};
let deep_copy = function(arr) {
let narr = [];
for (var i = 0; i < arr.length; i++) {
narr.push(arr[i].copy());
}
return narr;
};
p.keyPressed = function() {
if (p.keyCode === 80) {
// P key
saveToFile();
} else if (p.keyCode === 65) {
// A key
auto_download = !auto_download;
} else if (p.keyCode === 67) {
// C key
use_custom_palette = !use_custom_palette;
}
};
let saveToFile = function() {
if (use_custom_palette) p.saveCanvas(filename + '_' + current_palette + '_' + THE_SEED, 'jpeg');
else p.saveCanvas(filename + '_' + THE_SEED, 'jpeg');
};
};
new p5(sketch);
|
/*!
* search-query-parser.js
* Copyright(c) 2014 Julien Buty <julien@nepsilon.net>
* MIT Licensed
*/
exports.parse = function (string, options) {
// Set an empty options object when none provided
if (!options) {
options = {};
}
// Regularize white spacing
// Make in-between white spaces a unique space
string = string.trim().replace(/\s+/g, ' ');
// When a simple string, return it
if (-1 === string.indexOf(':')) {
return string;
}
// When no keywords or ranges set, treat as a simple string
else if (!options.keywords && !options.ranges){
return string;
}
// Otherwise parse the advanced query syntax
else {
// Our object to store the query object
var query = {text: []};
// Get a list of search terms respecting single and double quotes
var terms = string.match(/(\S+:'(?:[^'\\]|\\.)*')|(\S+:"(?:[^"\\]|\\.)*")|\S+|\S+:\S+/g);
for (var i = 0; i < terms.length; i++) {
var sepIndex = terms[i].indexOf(':');
if(sepIndex !== -1) {
var split = terms[i].split(':'),
key = terms[i].slice(0, sepIndex),
val = terms[i].slice(sepIndex + 1);
// Strip surrounding quotes
val = val.replace(/^\"|\"$|^\'|\'$/g, '');
// Strip backslashes respecting escapes
val = (val + '').replace(/\\(.?)/g, function (s, n1) {
switch (n1) {
case '\\':
return '\\';
case '0':
return '\u0000';
case '':
return '';
default:
return n1;
}
});
terms[i] = key + ':' + val;
}
};
// Reverse to ensure proper order when pop()'ing.
terms.reverse();
// For each search term
while (term = terms.pop()) {
// Advanced search terms syntax has key and value
// separated with a colon
var sepIdx = term.indexOf(':');
// When just a simple term
if (-1 === sepIdx) {
// We add it as pure text
query.text.push(term);
}
// We got an advanced search syntax
else {
var key = term.slice(0, sepIdx);
// Check if the key is a registered keyword
options.keywords = options.keywords || [];
var isKeyword = !(-1 === options.keywords.indexOf(key));
// Check if the key is a registered range
options.ranges = options.ranges || [];
var isRange = !(-1 === options.ranges.indexOf(key));
// When the key matches a keyword
if (isKeyword) {
var value = term.slice(sepIdx + 1);
// When value is a thing
if (value.length) {
// Get an array of values when several are there
var values = value.split(',');
// If we already have seen that keyword...
if (query[key]) {
// ...many times...
if (query[key] instanceof Array) {
// ...and got several values this time...
if (values.length > 1) {
// ... concatenate both arrays.
query[key] = query[key].concat(values);
}
else {
// ... append the current single value.
query[key].push(value);
}
}
// We saw that keyword only once before
else {
// Put both the current value and the new
// value in an array
query[key] = [query[key]]
query[key].push(value);
}
}
// First time we see that keyword
else {
// ...and got several values this time...
if (values.length > 1) {
// ...add all values seen.
query[key] = values;
}
// Got only a single value this time
else {
// Record its value as a string
query[key] = value;
}
}
}
}
// The key allows a range
else if (isRange) {
var value = term.slice(sepIdx + 1);
// Range are separated with a dash
var rangeValues = value.split('-');
// When both end of the range are specified
// keyword:XXXX-YYYY
query[key] = {};
if (2 === rangeValues.length) {
query[key].from = rangeValues[0];
query[key].to = rangeValues[1];
}
// When pairs of ranges are specified
// keyword:XXXX-YYYY,AAAA-BBBB
else if (!rangeValues.length % 2) {
}
// When only getting a single value,
// or an odd number of values
else {
query[key].from = value;
}
}
else {
// We add it as pure text
query.text.push(term);
}
}
}
// Concatenate all text terms if any
if (query.text.length) {
query.text = query.text.join(' ').trim();
}
// Just remove the attribute text when it's empty
else {
delete query.text;
}
// Return forged query object
return query;
}
};
|
/******/ (() => { // webpackBootstrap
/******/ /************************************************************************/
// extracted by extract-css-chunks-webpack-plugin
if(false) { var cssReload; }
/******/ })()
;
|
import $ from 'jquery'
import page from 'page'
import Handlebars from 'hbsfy/runtime'
import * as pages from './pages'
const $nav = $('#nav')
page('*', function(ctx, next) {
$nav
.children()
.removeClass('active')
$nav
.find('a[href|="' + ctx.path + '"]')
.parent()
.addClass('active')
next()
})
page('/', '/home')
page('/home', pages.home)
page()
|
import React from 'react'
import BigCalendar from 'react-big-calendar'
import moment from 'moment'
moment.locale('nb')
BigCalendar.setLocalizer(
BigCalendar.momentLocalizer(moment)
)
class Calendar extends React.Component {
static propTypes = {
node: React.PropTypes.object
}
render() {
return (
<BigCalendar events={this.props.events} style={{flex: 1}}/>
)
}
}
export default Calendar
|
define('component_modules/marked', function(require, exports, module) {
/**
* marked - a markdown parser
* Copyright (c) 2011-2014, Christopher Jeffrey. (MIT Licensed)
* https://github.com/chjj/marked
*/
/**
* Block-Level Grammar
*/
var block = {
newline: /^\n+/,
code: /^( {4}[^\n]+\n*)+/,
fences: noop,
hr: /^( *[-*_]){3,} *(?:\n+|$)/,
heading: /^ *(#{1,6}) *([^\n]+?) *#* *(?:\n+|$)/,
nptable: noop,
lheading: /^([^\n]+)\n *(=|-){2,} *(?:\n+|$)/,
blockquote: /^( *>[^\n]+(\n(?!def)[^\n]+)*\n*)+/,
list: /^( *)(bull) [\s\S]+?(?:hr|def|\n{2,}(?! )(?!\1bull )\n*|\s*$)/,
html: /^ *(?:comment *(?:\n|\s*$)|closed *(?:\n{2,}|\s*$)|closing *(?:\n{2,}|\s*$))/,
def: /^ *\[([^\]]+)\]: *<?([^\s>]+)>?(?: +["(]([^\n]+)[")])? *(?:\n+|$)/,
table: noop,
paragraph: /^((?:[^\n]+\n?(?!hr|heading|lheading|blockquote|tag|def))+)\n*/,
text: /^[^\n]+/
};
block.bullet = /(?:[*+-]|\d+\.)/;
block.item = /^( *)(bull) [^\n]*(?:\n(?!\1bull )[^\n]*)*/;
block.item = replace(block.item, 'gm')
(/bull/g, block.bullet)
();
block.list = replace(block.list)
(/bull/g, block.bullet)
('hr', '\\n+(?=\\1?(?:[-*_] *){3,}(?:\\n+|$))')
('def', '\\n+(?=' + block.def.source + ')')
();
block.blockquote = replace(block.blockquote)
('def', block.def)
();
block._tag = '(?!(?:'
+ 'a|em|strong|small|s|cite|q|dfn|abbr|data|time|code'
+ '|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo'
+ '|span|br|wbr|ins|del|img)\\b)\\w+(?!:/|[^\\w\\s@]*@)\\b';
block.html = replace(block.html)
('comment', /<!--[\s\S]*?-->/)
('closed', /<(tag)[\s\S]+?<\/\1>/)
('closing', /<tag(?:"[^"]*"|'[^']*'|[^'">])*?>/)
(/tag/g, block._tag)
();
block.paragraph = replace(block.paragraph)
('hr', block.hr)
('heading', block.heading)
('lheading', block.lheading)
('blockquote', block.blockquote)
('tag', '<' + block._tag)
('def', block.def)
();
/**
* Normal Block Grammar
*/
block.normal = merge({}, block);
/**
* GFM Block Grammar
*/
block.gfm = merge({}, block.normal, {
fences: /^ *(`{3,}|~{3,})[ \.]*(\S+)? *\n([\s\S]+?)\s*\1 *(?:\n+|$)/,
paragraph: /^/,
heading: /^ *(#{1,6}) +([^\n]+?) *#* *(?:\n+|$)/
});
block.gfm.paragraph = replace(block.paragraph)
('(?!', '(?!'
+ block.gfm.fences.source.replace('\\1', '\\2') + '|'
+ block.list.source.replace('\\1', '\\3') + '|')
();
/**
* GFM + Tables Block Grammar
*/
block.tables = merge({}, block.gfm, {
nptable: /^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*/,
table: /^ *\|(.+)\n *\|( *[-:]+[-| :]*)\n((?: *\|.*(?:\n|$))*)\n*/
});
/**
* Block Lexer
*/
function Lexer(options) {
this.tokens = [];
this.tokens.links = {};
this.options = options || marked.defaults;
this.rules = block.normal;
if (this.options.gfm) {
if (this.options.tables) {
this.rules = block.tables;
} else {
this.rules = block.gfm;
}
}
}
/**
* Expose Block Rules
*/
Lexer.rules = block;
/**
* Static Lex Method
*/
Lexer.lex = function(src, options) {
var lexer = new Lexer(options);
return lexer.lex(src);
};
/**
* Preprocessing
*/
Lexer.prototype.lex = function(src) {
src = src
.replace(/\r\n|\r/g, '\n')
.replace(/\t/g, ' ')
.replace(/\u00a0/g, ' ')
.replace(/\u2424/g, '\n');
return this.token(src, true);
};
/**
* Lexing
*/
Lexer.prototype.token = function(src, top, bq) {
var src = src.replace(/^ +$/gm, '')
, next
, loose
, cap
, bull
, b
, item
, space
, i
, l;
while (src) {
// newline
if (cap = this.rules.newline.exec(src)) {
src = src.substring(cap[0].length);
if (cap[0].length > 1) {
this.tokens.push({
type: 'space'
});
}
}
// code
if (cap = this.rules.code.exec(src)) {
src = src.substring(cap[0].length);
cap = cap[0].replace(/^ {4}/gm, '');
this.tokens.push({
type: 'code',
text: !this.options.pedantic
? cap.replace(/\n+$/, '')
: cap
});
continue;
}
// fences (gfm)
if (cap = this.rules.fences.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'code',
lang: cap[2],
text: cap[3]
});
continue;
}
// heading
if (cap = this.rules.heading.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'heading',
depth: cap[1].length,
text: cap[2]
});
continue;
}
// table no leading pipe (gfm)
if (top && (cap = this.rules.nptable.exec(src))) {
src = src.substring(cap[0].length);
item = {
type: 'table',
header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
cells: cap[3].replace(/\n$/, '').split('\n')
};
for (i = 0; i < item.align.length; i++) {
if (/^ *-+: *$/.test(item.align[i])) {
item.align[i] = 'right';
} else if (/^ *:-+: *$/.test(item.align[i])) {
item.align[i] = 'center';
} else if (/^ *:-+ *$/.test(item.align[i])) {
item.align[i] = 'left';
} else {
item.align[i] = null;
}
}
for (i = 0; i < item.cells.length; i++) {
item.cells[i] = item.cells[i].split(/ *\| */);
}
this.tokens.push(item);
continue;
}
// lheading
if (cap = this.rules.lheading.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'heading',
depth: cap[2] === '=' ? 1 : 2,
text: cap[1]
});
continue;
}
// hr
if (cap = this.rules.hr.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'hr'
});
continue;
}
// blockquote
if (cap = this.rules.blockquote.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'blockquote_start'
});
cap = cap[0].replace(/^ *> ?/gm, '');
// Pass `top` to keep the current
// "toplevel" state. This is exactly
// how markdown.pl works.
this.token(cap, top, true);
this.tokens.push({
type: 'blockquote_end'
});
continue;
}
// list
if (cap = this.rules.list.exec(src)) {
src = src.substring(cap[0].length);
bull = cap[2];
this.tokens.push({
type: 'list_start',
ordered: bull.length > 1
});
// Get each top-level item.
cap = cap[0].match(this.rules.item);
next = false;
l = cap.length;
i = 0;
for (; i < l; i++) {
item = cap[i];
// Remove the list item's bullet
// so it is seen as the next token.
space = item.length;
item = item.replace(/^ *([*+-]|\d+\.) +/, '');
// Outdent whatever the
// list item contains. Hacky.
if (~item.indexOf('\n ')) {
space -= item.length;
item = !this.options.pedantic
? item.replace(new RegExp('^ {1,' + space + '}', 'gm'), '')
: item.replace(/^ {1,4}/gm, '');
}
// Determine whether the next list item belongs here.
// Backpedal if it does not belong in this list.
if (this.options.smartLists && i !== l - 1) {
b = block.bullet.exec(cap[i + 1])[0];
if (bull !== b && !(bull.length > 1 && b.length > 1)) {
src = cap.slice(i + 1).join('\n') + src;
i = l - 1;
}
}
// Determine whether item is loose or not.
// Use: /(^|\n)(?! )[^\n]+\n\n(?!\s*$)/
// for discount behavior.
loose = next || /\n\n(?!\s*$)/.test(item);
if (i !== l - 1) {
next = item.charAt(item.length - 1) === '\n';
if (!loose) loose = next;
}
this.tokens.push({
type: loose
? 'loose_item_start'
: 'list_item_start'
});
// Recurse.
this.token(item, false, bq);
this.tokens.push({
type: 'list_item_end'
});
}
this.tokens.push({
type: 'list_end'
});
continue;
}
// html
if (cap = this.rules.html.exec(src)) {
src = src.substring(cap[0].length);
this.tokens.push({
type: this.options.sanitize
? 'paragraph'
: 'html',
pre: !this.options.sanitizer
&& (cap[1] === 'pre' || cap[1] === 'script' || cap[1] === 'style'),
text: cap[0]
});
continue;
}
// def
if ((!bq && top) && (cap = this.rules.def.exec(src))) {
src = src.substring(cap[0].length);
this.tokens.links[cap[1].toLowerCase()] = {
href: cap[2],
title: cap[3]
};
continue;
}
// table (gfm)
if (top && (cap = this.rules.table.exec(src))) {
src = src.substring(cap[0].length);
item = {
type: 'table',
header: cap[1].replace(/^ *| *\| *$/g, '').split(/ *\| */),
align: cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
cells: cap[3].replace(/(?: *\| *)?\n$/, '').split('\n')
};
for (i = 0; i < item.align.length; i++) {
if (/^ *-+: *$/.test(item.align[i])) {
item.align[i] = 'right';
} else if (/^ *:-+: *$/.test(item.align[i])) {
item.align[i] = 'center';
} else if (/^ *:-+ *$/.test(item.align[i])) {
item.align[i] = 'left';
} else {
item.align[i] = null;
}
}
for (i = 0; i < item.cells.length; i++) {
item.cells[i] = item.cells[i]
.replace(/^ *\| *| *\| *$/g, '')
.split(/ *\| */);
}
this.tokens.push(item);
continue;
}
// top-level paragraph
if (top && (cap = this.rules.paragraph.exec(src))) {
src = src.substring(cap[0].length);
this.tokens.push({
type: 'paragraph',
text: cap[1].charAt(cap[1].length - 1) === '\n'
? cap[1].slice(0, -1)
: cap[1]
});
continue;
}
// text
if (cap = this.rules.text.exec(src)) {
// Top-level should never reach here.
src = src.substring(cap[0].length);
this.tokens.push({
type: 'text',
text: cap[0]
});
continue;
}
if (src) {
throw new
Error('Infinite loop on byte: ' + src.charCodeAt(0));
}
}
return this.tokens;
};
/**
* Inline-Level Grammar
*/
var inline = {
escape: /^\\([\\`*{}\[\]()#+\-.!_>])/,
autolink: /^<([^ >]+(@|:\/)[^ >]+)>/,
url: noop,
tag: /^<!--[\s\S]*?-->|^<\/?\w+(?:"[^"]*"|'[^']*'|[^'">])*?>/,
link: /^!?\[(inside)\]\(href\)/,
reflink: /^!?\[(inside)\]\s*\[([^\]]*)\]/,
nolink: /^!?\[((?:\[[^\]]*\]|[^\[\]])*)\]/,
strong: /^__([\s\S]+?)__(?!_)|^\*\*([\s\S]+?)\*\*(?!\*)/,
em: /^\b_((?:__|[\s\S])+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)/,
code: /^(`+)\s*([\s\S]*?[^`])\s*\1(?!`)/,
br: /^ {2,}\n(?!\s*$)/,
del: noop,
text: /^[\s\S]+?(?=[\\<!\[_*`]| {2,}\n|$)/
};
inline._inside = /(?:\[[^\]]*\]|[^\[\]]|\](?=[^\[]*\]))*/;
inline._href = /\s*<?([\s\S]*?)>?(?:\s+['"]([\s\S]*?)['"])?\s*/;
inline.link = replace(inline.link)
('inside', inline._inside)
('href', inline._href)
();
inline.reflink = replace(inline.reflink)
('inside', inline._inside)
();
/**
* Normal Inline Grammar
*/
inline.normal = merge({}, inline);
/**
* Pedantic Inline Grammar
*/
inline.pedantic = merge({}, inline.normal, {
strong: /^__(?=\S)([\s\S]*?\S)__(?!_)|^\*\*(?=\S)([\s\S]*?\S)\*\*(?!\*)/,
em: /^_(?=\S)([\s\S]*?\S)_(?!_)|^\*(?=\S)([\s\S]*?\S)\*(?!\*)/
});
/**
* GFM Inline Grammar
*/
inline.gfm = merge({}, inline.normal, {
escape: replace(inline.escape)('])', '~|])')(),
url: /^(https?:\/\/[^\s<]+[^<.,:;"')\]\s])/,
del: /^~~(?=\S)([\s\S]*?\S)~~/,
text: replace(inline.text)
(']|', '~]|')
('|', '|https?://|')
()
});
/**
* GFM + Line Breaks Inline Grammar
*/
inline.breaks = merge({}, inline.gfm, {
br: replace(inline.br)('{2,}', '*')(),
text: replace(inline.gfm.text)('{2,}', '*')()
});
/**
* Inline Lexer & Compiler
*/
function InlineLexer(links, options) {
this.options = options || marked.defaults;
this.links = links;
this.rules = inline.normal;
this.renderer = this.options.renderer || new Renderer;
this.renderer.options = this.options;
if (!this.links) {
throw new
Error('Tokens array requires a `links` property.');
}
if (this.options.gfm) {
if (this.options.breaks) {
this.rules = inline.breaks;
} else {
this.rules = inline.gfm;
}
} else if (this.options.pedantic) {
this.rules = inline.pedantic;
}
}
/**
* Expose Inline Rules
*/
InlineLexer.rules = inline;
/**
* Static Lexing/Compiling Method
*/
InlineLexer.output = function(src, links, options) {
var inline = new InlineLexer(links, options);
return inline.output(src);
};
/**
* Lexing/Compiling
*/
InlineLexer.prototype.output = function(src) {
var out = ''
, link
, text
, href
, cap;
while (src) {
// escape
if (cap = this.rules.escape.exec(src)) {
src = src.substring(cap[0].length);
out += cap[1];
continue;
}
// autolink
if (cap = this.rules.autolink.exec(src)) {
src = src.substring(cap[0].length);
if (cap[2] === '@') {
text = cap[1].charAt(6) === ':'
? this.mangle(cap[1].substring(7))
: this.mangle(cap[1]);
href = this.mangle('mailto:') + text;
} else {
text = escape(cap[1]);
href = text;
}
out += this.renderer.link(href, null, text);
continue;
}
// url (gfm)
if (!this.inLink && (cap = this.rules.url.exec(src))) {
src = src.substring(cap[0].length);
text = escape(cap[1]);
href = text;
out += this.renderer.link(href, null, text);
continue;
}
// tag
if (cap = this.rules.tag.exec(src)) {
if (!this.inLink && /^<a /i.test(cap[0])) {
this.inLink = true;
} else if (this.inLink && /^<\/a>/i.test(cap[0])) {
this.inLink = false;
}
src = src.substring(cap[0].length);
out += this.options.sanitize
? this.options.sanitizer
? this.options.sanitizer(cap[0])
: escape(cap[0])
: cap[0]
continue;
}
// link
if (cap = this.rules.link.exec(src)) {
src = src.substring(cap[0].length);
this.inLink = true;
out += this.outputLink(cap, {
href: cap[2],
title: cap[3]
});
this.inLink = false;
continue;
}
// reflink, nolink
if ((cap = this.rules.reflink.exec(src))
|| (cap = this.rules.nolink.exec(src))) {
src = src.substring(cap[0].length);
link = (cap[2] || cap[1]).replace(/\s+/g, ' ');
link = this.links[link.toLowerCase()];
if (!link || !link.href) {
out += cap[0].charAt(0);
src = cap[0].substring(1) + src;
continue;
}
this.inLink = true;
out += this.outputLink(cap, link);
this.inLink = false;
continue;
}
// strong
if (cap = this.rules.strong.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.strong(this.output(cap[2] || cap[1]));
continue;
}
// em
if (cap = this.rules.em.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.em(this.output(cap[2] || cap[1]));
continue;
}
// code
if (cap = this.rules.code.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.codespan(escape(cap[2], true));
continue;
}
// br
if (cap = this.rules.br.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.br();
continue;
}
// del (gfm)
if (cap = this.rules.del.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.del(this.output(cap[1]));
continue;
}
// text
if (cap = this.rules.text.exec(src)) {
src = src.substring(cap[0].length);
out += this.renderer.text(escape(this.smartypants(cap[0])));
continue;
}
if (src) {
throw new
Error('Infinite loop on byte: ' + src.charCodeAt(0));
}
}
return out;
};
/**
* Compile Link
*/
InlineLexer.prototype.outputLink = function(cap, link) {
var href = escape(link.href)
, title = link.title ? escape(link.title) : null;
return cap[0].charAt(0) !== '!'
? this.renderer.link(href, title, this.output(cap[1]))
: this.renderer.image(href, title, escape(cap[1]));
};
/**
* Smartypants Transformations
*/
InlineLexer.prototype.smartypants = function(text) {
if (!this.options.smartypants) return text;
return text
// em-dashes
.replace(/---/g, '\u2014')
// en-dashes
.replace(/--/g, '\u2013')
// opening singles
.replace(/(^|[-\u2014/(\[{"\s])'/g, '$1\u2018')
// closing singles & apostrophes
.replace(/'/g, '\u2019')
// opening doubles
.replace(/(^|[-\u2014/(\[{\u2018\s])"/g, '$1\u201c')
// closing doubles
.replace(/"/g, '\u201d')
// ellipses
.replace(/\.{3}/g, '\u2026');
};
/**
* Mangle Links
*/
InlineLexer.prototype.mangle = function(text) {
if (!this.options.mangle) return text;
var out = ''
, l = text.length
, i = 0
, ch;
for (; i < l; i++) {
ch = text.charCodeAt(i);
if (Math.random() > 0.5) {
ch = 'x' + ch.toString(16);
}
out += '&#' + ch + ';';
}
return out;
};
/**
* Renderer
*/
function Renderer(options) {
this.options = options || {};
}
Renderer.prototype.code = function(code, lang, escaped) {
if (this.options.highlight) {
var out = this.options.highlight(code, lang);
if (out != null && out !== code) {
escaped = true;
code = out;
}
}
if (!lang) {
return '<pre><code>'
+ (escaped ? code : escape(code, true))
+ '\n</code></pre>';
}
return '<pre><code class="'
+ this.options.langPrefix
+ escape(lang, true)
+ '">'
+ (escaped ? code : escape(code, true))
+ '\n</code></pre>\n';
};
Renderer.prototype.blockquote = function(quote) {
return '<blockquote>\n' + quote + '</blockquote>\n';
};
Renderer.prototype.html = function(html) {
return html;
};
Renderer.prototype.heading = function(text, level, raw) {
return '<h'
+ level
+ ' id="'
+ this.options.headerPrefix
+ raw.toLowerCase().replace(/[^\w]+/g, '-')
+ '">'
+ text
+ '</h'
+ level
+ '>\n';
};
Renderer.prototype.hr = function() {
return this.options.xhtml ? '<hr/>\n' : '<hr>\n';
};
Renderer.prototype.list = function(body, ordered) {
var type = ordered ? 'ol' : 'ul';
return '<' + type + '>\n' + body + '</' + type + '>\n';
};
Renderer.prototype.listitem = function(text) {
return '<li>' + text + '</li>\n';
};
Renderer.prototype.paragraph = function(text) {
return '<p>' + text + '</p>\n';
};
Renderer.prototype.table = function(header, body) {
return '<table>\n'
+ '<thead>\n'
+ header
+ '</thead>\n'
+ '<tbody>\n'
+ body
+ '</tbody>\n'
+ '</table>\n';
};
Renderer.prototype.tablerow = function(content) {
return '<tr>\n' + content + '</tr>\n';
};
Renderer.prototype.tablecell = function(content, flags) {
var type = flags.header ? 'th' : 'td';
var tag = flags.align
? '<' + type + ' style="text-align:' + flags.align + '">'
: '<' + type + '>';
return tag + content + '</' + type + '>\n';
};
// span level renderer
Renderer.prototype.strong = function(text) {
return '<strong>' + text + '</strong>';
};
Renderer.prototype.em = function(text) {
return '<em>' + text + '</em>';
};
Renderer.prototype.codespan = function(text) {
return '<code>' + text + '</code>';
};
Renderer.prototype.br = function() {
return this.options.xhtml ? '<br/>' : '<br>';
};
Renderer.prototype.del = function(text) {
return '<del>' + text + '</del>';
};
Renderer.prototype.link = function(href, title, text) {
if (this.options.sanitize) {
try {
var prot = decodeURIComponent(unescape(href))
.replace(/[^\w:]/g, '')
.toLowerCase();
} catch (e) {
return '';
}
if (prot.indexOf('javascript:') === 0 || prot.indexOf('vbscript:') === 0) {
return '';
}
}
var out = '<a href="' + href + '"';
if (title) {
out += ' title="' + title + '"';
}
out += '>' + text + '</a>';
return out;
};
Renderer.prototype.image = function(href, title, text) {
var out = '<img src="' + href + '" alt="' + text + '"';
if (title) {
out += ' title="' + title + '"';
}
out += this.options.xhtml ? '/>' : '>';
return out;
};
Renderer.prototype.text = function(text) {
return text;
};
/**
* Parsing & Compiling
*/
function Parser(options) {
this.tokens = [];
this.token = null;
this.options = options || marked.defaults;
this.options.renderer = this.options.renderer || new Renderer;
this.renderer = this.options.renderer;
this.renderer.options = this.options;
}
/**
* Static Parse Method
*/
Parser.parse = function(src, options, renderer) {
var parser = new Parser(options, renderer);
return parser.parse(src);
};
/**
* Parse Loop
*/
Parser.prototype.parse = function(src) {
this.inline = new InlineLexer(src.links, this.options, this.renderer);
this.tokens = src.reverse();
var out = '';
while (this.next()) {
out += this.tok();
}
return out;
};
/**
* Next Token
*/
Parser.prototype.next = function() {
return this.token = this.tokens.pop();
};
/**
* Preview Next Token
*/
Parser.prototype.peek = function() {
return this.tokens[this.tokens.length - 1] || 0;
};
/**
* Parse Text Tokens
*/
Parser.prototype.parseText = function() {
var body = this.token.text;
while (this.peek().type === 'text') {
body += '\n' + this.next().text;
}
return this.inline.output(body);
};
/**
* Parse Current Token
*/
Parser.prototype.tok = function() {
switch (this.token.type) {
case 'space': {
return '';
}
case 'hr': {
return this.renderer.hr();
}
case 'heading': {
return this.renderer.heading(
this.inline.output(this.token.text),
this.token.depth,
this.token.text);
}
case 'code': {
return this.renderer.code(this.token.text,
this.token.lang,
this.token.escaped);
}
case 'table': {
var header = ''
, body = ''
, i
, row
, cell
, flags
, j;
// header
cell = '';
for (i = 0; i < this.token.header.length; i++) {
flags = { header: true, align: this.token.align[i] };
cell += this.renderer.tablecell(
this.inline.output(this.token.header[i]),
{ header: true, align: this.token.align[i] }
);
}
header += this.renderer.tablerow(cell);
for (i = 0; i < this.token.cells.length; i++) {
row = this.token.cells[i];
cell = '';
for (j = 0; j < row.length; j++) {
cell += this.renderer.tablecell(
this.inline.output(row[j]),
{ header: false, align: this.token.align[j] }
);
}
body += this.renderer.tablerow(cell);
}
return this.renderer.table(header, body);
}
case 'blockquote_start': {
var body = '';
while (this.next().type !== 'blockquote_end') {
body += this.tok();
}
return this.renderer.blockquote(body);
}
case 'list_start': {
var body = ''
, ordered = this.token.ordered;
while (this.next().type !== 'list_end') {
body += this.tok();
}
return this.renderer.list(body, ordered);
}
case 'list_item_start': {
var body = '';
while (this.next().type !== 'list_item_end') {
body += this.token.type === 'text'
? this.parseText()
: this.tok();
}
return this.renderer.listitem(body);
}
case 'loose_item_start': {
var body = '';
while (this.next().type !== 'list_item_end') {
body += this.tok();
}
return this.renderer.listitem(body);
}
case 'html': {
var html = !this.token.pre && !this.options.pedantic
? this.inline.output(this.token.text)
: this.token.text;
return this.renderer.html(html);
}
case 'paragraph': {
return this.renderer.paragraph(this.inline.output(this.token.text));
}
case 'text': {
return this.renderer.paragraph(this.parseText());
}
}
};
/**
* Helpers
*/
function escape(html, encode) {
return html
.replace(!encode ? /&(?!#?\w+;)/g : /&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function unescape(html) {
return html.replace(/&([#\w]+);/g, function(_, n) {
n = n.toLowerCase();
if (n === 'colon') return ':';
if (n.charAt(0) === '#') {
return n.charAt(1) === 'x'
? String.fromCharCode(parseInt(n.substring(2), 16))
: String.fromCharCode(+n.substring(1));
}
return '';
});
}
function replace(regex, opt) {
regex = regex.source;
opt = opt || '';
return function self(name, val) {
if (!name) return new RegExp(regex, opt);
val = val.source || val;
val = val.replace(/(^|[^\[])\^/g, '$1');
regex = regex.replace(name, val);
return self;
};
}
function noop() {}
noop.exec = noop;
function merge(obj) {
var i = 1
, target
, key;
for (; i < arguments.length; i++) {
target = arguments[i];
for (key in target) {
if (Object.prototype.hasOwnProperty.call(target, key)) {
obj[key] = target[key];
}
}
}
return obj;
}
/**
* Marked
*/
function marked(src, opt, callback) {
if (callback || typeof opt === 'function') {
if (!callback) {
callback = opt;
opt = null;
}
opt = merge({}, marked.defaults, opt || {});
var highlight = opt.highlight
, tokens
, pending
, i = 0;
try {
tokens = Lexer.lex(src, opt)
} catch (e) {
return callback(e);
}
pending = tokens.length;
var done = function(err) {
if (err) {
opt.highlight = highlight;
return callback(err);
}
var out;
try {
out = Parser.parse(tokens, opt);
} catch (e) {
err = e;
}
opt.highlight = highlight;
return err
? callback(err)
: callback(null, out);
};
if (!highlight || highlight.length < 3) {
return done();
}
delete opt.highlight;
if (!pending) return done();
for (; i < tokens.length; i++) {
(function(token) {
if (token.type !== 'code') {
return --pending || done();
}
return highlight(token.text, token.lang, function(err, code) {
if (err) return done(err);
if (code == null || code === token.text) {
return --pending || done();
}
token.text = code;
token.escaped = true;
--pending || done();
});
})(tokens[i]);
}
return;
}
try {
if (opt) opt = merge({}, marked.defaults, opt);
return Parser.parse(Lexer.lex(src, opt), opt);
} catch (e) {
e.message += '\nPlease report this to https://github.com/chjj/marked.';
if ((opt || marked.defaults).silent) {
return '<p>An error occured:</p><pre>'
+ escape(e.message + '', true)
+ '</pre>';
}
throw e;
}
}
/**
* Options
*/
marked.options =
marked.setOptions = function(opt) {
merge(marked.defaults, opt);
return marked;
};
marked.defaults = {
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: false,
sanitizer: null,
mangle: true,
smartLists: false,
silent: false,
highlight: null,
langPrefix: 'lang-',
smartypants: false,
headerPrefix: '',
renderer: new Renderer,
xhtml: false
};
/**
* Expose
*/
marked.Parser = Parser;
marked.parser = Parser.parse;
marked.Renderer = Renderer;
marked.Lexer = Lexer;
marked.lexer = Lexer.lex;
marked.InlineLexer = InlineLexer;
marked.inlineLexer = InlineLexer.output;
marked.parse = marked;
module.exports = marked;
});
|
/**
* @fileoverview Enforce consistent usage of shorthand strings for test cases with no options
* @author Teddy Katz
*/
'use strict';
const utils = require('../utils');
// ------------------------------------------------------------------------------
// Rule Definition
// ------------------------------------------------------------------------------
/** @type {import('eslint').Rule.RuleModule} */
module.exports = {
meta: {
type: 'suggestion',
docs: {
description:
'enforce consistent usage of shorthand strings for test cases with no options',
category: 'Tests',
recommended: false,
url: 'https://github.com/not-an-aardvark/eslint-plugin-eslint-plugin/tree/HEAD/docs/rules/test-case-shorthand-strings.md',
},
fixable: 'code',
schema: [
{ enum: ['as-needed', 'never', 'consistent', 'consistent-as-needed'] },
],
messages: {
useShorthand:
'Use {{preferred}} for this test case instead of {{actual}}.',
},
},
create(context) {
const shorthandOption = context.options[0] || 'as-needed';
const sourceCode = context.getSourceCode();
// ----------------------------------------------------------------------
// Helpers
// ----------------------------------------------------------------------
/**
* Reports test cases as necessary
* @param {object[]} cases A list of test case nodes
* @returns {void}
*/
function reportTestCases(cases) {
const caseInfoList = cases
.map((testCase) => {
if (
testCase.type === 'Literal' ||
testCase.type === 'TemplateLiteral'
) {
return { node: testCase, shorthand: true, needsLongform: false };
}
if (testCase.type === 'ObjectExpression') {
return {
node: testCase,
shorthand: false,
needsLongform: !(
testCase.properties.length === 1 &&
utils.getKeyName(testCase.properties[0]) === 'code'
),
};
}
return null;
})
.filter(Boolean);
const isConsistent =
new Set(caseInfoList.map((caseInfo) => caseInfo.shorthand)).size <= 1;
const hasCaseNeedingLongform = caseInfoList.some(
(caseInfo) => caseInfo.needsLongform
);
caseInfoList
.filter(
{
'as-needed': (caseInfo) =>
!caseInfo.shorthand && !caseInfo.needsLongform,
never: (caseInfo) => caseInfo.shorthand,
consistent: isConsistent
? () => false
: (caseInfo) => caseInfo.shorthand,
'consistent-as-needed': (caseInfo) =>
caseInfo.shorthand === hasCaseNeedingLongform,
}[shorthandOption]
)
.forEach((badCaseInfo) => {
context.report({
node: badCaseInfo.node,
messageId: 'useShorthand',
data: {
preferred: badCaseInfo.shorthand ? 'an object' : 'a string',
actual: badCaseInfo.shorthand ? 'a string' : 'an object',
},
fix(fixer) {
return fixer.replaceText(
badCaseInfo.node,
badCaseInfo.shorthand
? `{code: ${sourceCode.getText(badCaseInfo.node)}}`
: sourceCode.getText(badCaseInfo.node.properties[0].value)
);
},
});
});
}
// ----------------------------------------------------------------------
// Public
// ----------------------------------------------------------------------
return {
Program(ast) {
utils
.getTestInfo(context, ast)
.map((testRun) => testRun.valid)
.filter(Boolean)
.forEach(reportTestCases);
},
};
},
};
|
const styles = {
input: {
height: '0.76rem',
padding: '0.12rem 0.2rem', /* The 6px vertically centers text on FF, ignored by Webkit */
backgroundColor: '#fff',
border: '0.02rem solid #D1D1D1',
borderRadius: '0.08rem',
boxShadow: 'none',
boxSizing: 'border-box',
'&:focus': {
border: '0.02rem solid #33C3F0',
outline: 0,
},
},
};
export default styles;
|
module.exports = function ({ $incremental, $lookup }) {
return {
object: function () {
const assert = require('assert')
return function (object, {
counter = (() => [ 0 ])()
} = {}) {
return function ($buffer, $start, $end) {
let $$ = [], $accumulator = {}
$accumulator['counter'] = counter
if ($end - $start < 3) {
return $incremental.object(object, {
counter: counter
}, 1, $$, $accumulator)($buffer, $start, $end)
}
$$[0] = (function ({ $_, counter }) {
console.log('>>>', counter)
assert.deepEqual(counter, [ 0 ])
return $_
})({
$_: object,
counter: $accumulator['counter']
})
$buffer[$start++] = $$[0].value.first & 0xff
$buffer[$start++] = $$[0].value.second & 0xff
$buffer[$start++] = $$[0].sentry & 0xff
return { start: $start, serialize: null }
}
}
} ()
}
}
|
'use strict';
var should = require('should'),
request = require('supertest'),
app = require('../../server'),
mongoose = require('mongoose'),
User = mongoose.model('User'),
Pessoa = mongoose.model('Pessoa'),
agent = request.agent(app);
/**
* Globals
*/
var credentials, user, pessoa;
/**
* Pessoa routes tests
*/
describe('Pessoa CRUD tests', function() {
beforeEach(function(done) {
// Create user credentials
credentials = {
username: 'username',
password: 'password'
};
// Create a new user
user = new User({
firstName: 'Full',
lastName: 'Name',
displayName: 'Full Name',
email: 'test@test.com',
username: credentials.username,
password: credentials.password,
provider: 'local'
});
// Save a user to the test db and create new Pessoa
user.save(function() {
pessoa = {
name: 'Pessoa Name'
};
done();
});
});
it('should be able to save Pessoa instance if logged in', function(done) {
agent.post('/auth/signin')
.send(credentials)
.expect(200)
.end(function(signinErr, signinRes) {
// Handle signin error
if (signinErr) done(signinErr);
// Get the userId
var userId = user.id;
// Save a new Pessoa
agent.post('/pessoas')
.send(pessoa)
.expect(200)
.end(function(pessoaSaveErr, pessoaSaveRes) {
// Handle Pessoa save error
if (pessoaSaveErr) done(pessoaSaveErr);
// Get a list of Pessoas
agent.get('/pessoas')
.end(function(pessoasGetErr, pessoasGetRes) {
// Handle Pessoa save error
if (pessoasGetErr) done(pessoasGetErr);
// Get Pessoas list
var pessoas = pessoasGetRes.body;
// Set assertions
(pessoas[0].user._id).should.equal(userId);
(pessoas[0].name).should.match('Pessoa Name');
// Call the assertion callback
done();
});
});
});
});
it('should not be able to save Pessoa instance if not logged in', function(done) {
agent.post('/pessoas')
.send(pessoa)
.expect(401)
.end(function(pessoaSaveErr, pessoaSaveRes) {
// Call the assertion callback
done(pessoaSaveErr);
});
});
it('should not be able to save Pessoa instance if no name is provided', function(done) {
// Invalidate name field
pessoa.name = '';
agent.post('/auth/signin')
.send(credentials)
.expect(200)
.end(function(signinErr, signinRes) {
// Handle signin error
if (signinErr) done(signinErr);
// Get the userId
var userId = user.id;
// Save a new Pessoa
agent.post('/pessoas')
.send(pessoa)
.expect(400)
.end(function(pessoaSaveErr, pessoaSaveRes) {
// Set message assertion
(pessoaSaveRes.body.message).should.match('Please fill Pessoa name');
// Handle Pessoa save error
done(pessoaSaveErr);
});
});
});
it('should be able to update Pessoa instance if signed in', function(done) {
agent.post('/auth/signin')
.send(credentials)
.expect(200)
.end(function(signinErr, signinRes) {
// Handle signin error
if (signinErr) done(signinErr);
// Get the userId
var userId = user.id;
// Save a new Pessoa
agent.post('/pessoas')
.send(pessoa)
.expect(200)
.end(function(pessoaSaveErr, pessoaSaveRes) {
// Handle Pessoa save error
if (pessoaSaveErr) done(pessoaSaveErr);
// Update Pessoa name
pessoa.name = 'WHY YOU GOTTA BE SO MEAN?';
// Update existing Pessoa
agent.put('/pessoas/' + pessoaSaveRes.body._id)
.send(pessoa)
.expect(200)
.end(function(pessoaUpdateErr, pessoaUpdateRes) {
// Handle Pessoa update error
if (pessoaUpdateErr) done(pessoaUpdateErr);
// Set assertions
(pessoaUpdateRes.body._id).should.equal(pessoaSaveRes.body._id);
(pessoaUpdateRes.body.name).should.match('WHY YOU GOTTA BE SO MEAN?');
// Call the assertion callback
done();
});
});
});
});
it('should be able to get a list of Pessoas if not signed in', function(done) {
// Create new Pessoa model instance
var pessoaObj = new Pessoa(pessoa);
// Save the Pessoa
pessoaObj.save(function() {
// Request Pessoas
request(app).get('/pessoas')
.end(function(req, res) {
// Set assertion
res.body.should.be.an.Array.with.lengthOf(1);
// Call the assertion callback
done();
});
});
});
it('should be able to get a single Pessoa if not signed in', function(done) {
// Create new Pessoa model instance
var pessoaObj = new Pessoa(pessoa);
// Save the Pessoa
pessoaObj.save(function() {
request(app).get('/pessoas/' + pessoaObj._id)
.end(function(req, res) {
// Set assertion
res.body.should.be.an.Object.with.property('name', pessoa.name);
// Call the assertion callback
done();
});
});
});
it('should be able to delete Pessoa instance if signed in', function(done) {
agent.post('/auth/signin')
.send(credentials)
.expect(200)
.end(function(signinErr, signinRes) {
// Handle signin error
if (signinErr) done(signinErr);
// Get the userId
var userId = user.id;
// Save a new Pessoa
agent.post('/pessoas')
.send(pessoa)
.expect(200)
.end(function(pessoaSaveErr, pessoaSaveRes) {
// Handle Pessoa save error
if (pessoaSaveErr) done(pessoaSaveErr);
// Delete existing Pessoa
agent.delete('/pessoas/' + pessoaSaveRes.body._id)
.send(pessoa)
.expect(200)
.end(function(pessoaDeleteErr, pessoaDeleteRes) {
// Handle Pessoa error error
if (pessoaDeleteErr) done(pessoaDeleteErr);
// Set assertions
(pessoaDeleteRes.body._id).should.equal(pessoaSaveRes.body._id);
// Call the assertion callback
done();
});
});
});
});
it('should not be able to delete Pessoa instance if not signed in', function(done) {
// Set Pessoa user
pessoa.user = user;
// Create new Pessoa model instance
var pessoaObj = new Pessoa(pessoa);
// Save the Pessoa
pessoaObj.save(function() {
// Try deleting Pessoa
request(app).delete('/pessoas/' + pessoaObj._id)
.expect(401)
.end(function(pessoaDeleteErr, pessoaDeleteRes) {
// Set message assertion
(pessoaDeleteRes.body.message).should.match('User is not logged in');
// Handle Pessoa error error
done(pessoaDeleteErr);
});
});
});
afterEach(function(done) {
User.remove().exec();
Pessoa.remove().exec();
done();
});
}); |
(function(){
'use strict';
angular
.module('app')
.factory('myInterceptors', myInterceptors)
.config(['$httpProvider',function($httpProvider) {
$httpProvider.interceptors.push('myInterceptors');
}]);
myInterceptors.$inject = ['$q','$injector'];
function myInterceptors($q, $injector){
var $state;
return {
request: function(config){
config.headers = config.headers || {};
if (sessionStorage.getItem('satellizer_token')) {
config.headers.Authorization = 'Bearer ' + sessionStorage.getItem('satellizer_token');
}
return config;
},
response: function(response){
//implements
return response;
},
responseError: function(rejection){
var $state = $state || $injector.get('$state');
if(rejection.status == 400){
$state.go('login',{});
}
return $q.reject(rejection);
}
};
}
})();
|
import { Meteor } from 'meteor/meteor';
import { FlowRouter } from 'meteor/kadira:flow-router';
import { Template } from 'meteor/templating';
Template.setupWizardFinal.onCreated(function() {
const isSetupWizardDone = localStorage.getItem('wizardFinal');
if (isSetupWizardDone === null) {
FlowRouter.go('setup-wizard');
}
this.autorun((c) => {
const showSetupWizard = RocketChat.settings.get('Show_Setup_Wizard');
if (!showSetupWizard) {
// Setup Wizard state is not defined yet
return;
}
const userId = Meteor.userId();
const user = userId && RocketChat.models.Users.findOne(userId, { fields: { status: true } });
if (userId && (!user || !user.status)) {
// User and its status are not defined yet
return;
}
c.stop();
const isComplete = showSetupWizard === 'completed';
const noUserLoggedInAndIsNotPending = !userId && showSetupWizard !== 'pending';
const userIsLoggedButIsNotAdmin = userId && !RocketChat.authz.hasRole(userId, 'admin');
if (isComplete || noUserLoggedInAndIsNotPending || userIsLoggedButIsNotAdmin) {
FlowRouter.go('home');
return;
}
});
});
Template.setupWizardFinal.onRendered(function() {
$('#initial-page-loading').remove();
});
Template.setupWizardFinal.events({
'click .js-finish'() {
RocketChat.settings.set('Show_Setup_Wizard', 'completed', function() {
localStorage.removeItem('wizard');
localStorage.removeItem('wizardFinal');
FlowRouter.go('home');
});
},
});
Template.setupWizardFinal.helpers({
siteUrl() {
return RocketChat.settings.get('Site_Url');
},
});
|
/* eslint-env mocha */
//import { expect } from 'chai';
import MergeSort from './MergeSort';
import sortTestHelpers from './Sort.test';
describe('MergeSort class', function() {
sortTestHelpers.functionality(MergeSort);
sortTestHelpers.randomised(MergeSort, true);
});
|
var Jimp = require('../index');
var utils = require('./utils');
/**
* Rotate a given image
* to the specified
* degrees
*
* @param src
* @param deg
* @param options
*/
module.exports = function rotate(src, deg, options) {
var rotation = Number(deg);
if (isNaN(rotation)) {
throw new TypeError('Jimp rotate expects rotation degrees to be a number. "' + deg + '" given');
}
var getOutputFile = utils.getOutputFileGenerator(src, options);
new Jimp(src, function (err, image) {
if (err) {
throw err;
}
image
.rotate(rotation)
.write(getOutputFile(src, ['rotated', rotation]));
console.log('Image %s rotated %d degrees', src, rotation);
});
};
|
'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema,
crypto = require('crypto');
/**
* A Validation function for local strategy properties
*/
var validateLocalStrategyProperty = function(property) {
return ((this.provider !== 'local' && !this.updated) || property.length);
};
/**
* A Validation function for local strategy password
*/
var validateLocalStrategyPassword = function(password) {
return (this.provider !== 'local' || (password && password.length > 6));
};
/**
* User Schema
*/
var UserSchema = new Schema({
firstName: {
type: String,
trim: true,
default: '',
validate: [validateLocalStrategyProperty, 'Please fill in your first name']
},
lastName: {
type: String,
trim: true,
default: '',
validate: [validateLocalStrategyProperty, 'Please fill in your last name']
},
displayName: {
type: String,
trim: true
},
email: {
type: String,
trim: true,
default: '',
validate: [validateLocalStrategyProperty, 'Please fill in your email'],
match: [/.+\@.+\..+/, 'Please fill a valid email address']
},
username: {
type: String,
unique: 'testing error message',
required: 'Please fill in a username',
trim: true
},
password: {
type: String,
default: '',
validate: [validateLocalStrategyPassword, 'Password should be longer']
},
salt: {
type: String
},
provider: {
type: String,
required: 'Provider is required'
},
providerData: {},
additionalProvidersData: {},
roles: {
role: {
type: [{
type: String,
enum: ['user', 'admin', 'monitor']
}],
default: ['user']
},
userid: {
type: String,
default: ''
}
},
updated: {
type: Date
},
created: {
type: Date,
default: Date.now
},
/* For reset password */
resetPasswordToken: {
type: String
},
resetPasswordExpires: {
type: Date
},
rijksregisternummer: {
type: String,
default: '',
trim: true
},
geboortedatum: {
type: Date,
default: Date.now,
},
adres: {
straat: {
type: String,
default: '',
trim: true
},
nummer: {
type: String,
default: '',
trim: true
},
bus: {
type: String,
default: '',
trim: true
},
gemeente: {
type: String,
default: '',
trim: true
},
postcode: {
type: String,
default: '',
trim: true
}
},
telefoonnummer: {
type: String,
default: '',
trim: true
},
kinderen: [{ type: String }]
});
/**
* Hook a pre save method to hash the password
*/
UserSchema.pre('save', function(next) {
if (this.password && this.password.length > 6) {
this.salt = new Buffer(crypto.randomBytes(16).toString('base64'), 'base64');
this.password = this.hashPassword(this.password);
}
next();
});
/**
* Create instance method for hashing a password
*/
UserSchema.methods.hashPassword = function(password) {
if (this.salt && password) {
return crypto.pbkdf2Sync(password, this.salt, 10000, 64).toString('base64');
} else {
return password;
}
};
/**
* Create instance method for authenticating user
*/
UserSchema.methods.authenticate = function(password) {
return this.password === this.hashPassword(password);
};
/**
* Find possible not used username
*/
UserSchema.statics.findUniqueUsername = function(username, suffix, callback) {
var _this = this;
var possibleUsername = username + (suffix || '');
_this.findOne({
username: possibleUsername
}, function(err, user) {
if (!err) {
if (!user) {
callback(possibleUsername);
} else {
return _this.findUniqueUsername(username, (suffix || 0) + 1, callback);
}
} else {
callback(null);
}
});
};
mongoose.model('User', UserSchema); |
import React, {Component} from 'react';
import {ngm} from './NagomeConn.js';
import {List, ListItem, Page, Toolbar, BackButton, Checkbox} from 'react-onsenui';
export default class SettingPlugin extends Component {
constructor() {
super();
this.state = {
plugs: [],
};
}
back() {
this.props.navigator.popPage();
}
renderToolbar() {
return (
<Toolbar>
<div className='left'>
<BackButton onClick={this.back.bind(this)}>
Back
</BackButton>
</div>
<div className='center'>Plugins</div>
</Toolbar>
);
}
handleEnable(no, e) {
ngm.pluginEnable(no, e.target.checked);
}
renderRow(row, i) {
return (
<ListItem key={i}>
<div className='left'>
<Checkbox
disabled={row.no === 0}
checked={row.state === 1}
inputId={`checkbox-${row}`}
onChange={this.handleEnable.bind(this, row.no)}
/>
</div>
<div className='center'>
<div className='list__item__title'>
{row.name}
</div>
<div className='list__item__subtitle'>
{row.description}
</div>
</div>
<div className='right'>
</div>
</ListItem>
);
}
updateList(list) {
this.setState({
plugs: list,
});
}
render() {
return (
<Page renderToolbar={this.renderToolbar.bind(this)}>
<List dataSource={this.state.plugs} renderRow={this.renderRow.bind(this)} />
</Page>
);
}
}
|
/**
* modalEffects.js v1.0.0
* http://www.codrops.com
*
* Licensed under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*
* Copyright 2013, Codrops
* http://www.codrops.com
*/
var count = true;
var ModalEffects = (function() {
function init() {
var overlay = document.querySelector( '.md-overlay' );
[].slice.call( document.querySelectorAll( '.md-trigger' ) ).forEach( function( el, i ) {
var modal = document.querySelector( '#' + el.getAttribute( 'data-modal' ) ),
validate = modal.querySelector( '.md-validate' ),
cancel = modal.querySelector('.md-cancel');
var form = modal.querySelector('#form');
function removeModal( hasPerspective ) {
classie.remove( modal, 'md-show' );
if( hasPerspective ) {
classie.remove( document.documentElement, 'md-perspective' );
}
}
function removeModalHandler() {
removeModal( classie.has( el, 'md-setperspective' ) );
}
el.addEventListener( 'click', function( ev ) {
classie.add( modal, 'md-show' );
overlay.removeEventListener( 'click', removeModalHandler );
overlay.addEventListener( 'click', removeModalHandler );
if( classie.has( el, 'md-setperspective' ) ) {
setTimeout( function() {
classie.add( document.documentElement, 'md-perspective' );
}, 25 );
}
});
validate.addEventListener( 'click', function( ev ) {
if(classie.has(validate, 'product') && count){
//Retrieve data input
var elDiv = document.getElementById('form').getElementsByTagName('*');
var product = {nom:"", lipides:"", glucides:"", protides:"", autres:"", image:"", section:""};
var err = false;
for(var i = 0; i < elDiv.length; i++){
if(elDiv[i].tagName == 'INPUT'){
if(elDiv[i].value == ''){
err =true;
break;
}else{
product[elDiv[i].name] = String(elDiv[i].value).toLowerCase();
}
}
}
// Get the category
if(document.getElementById('sections').selectedIndex == 0)
err=true;
else
product['section'] = document.getElementById('sections').selectedIndex-1;
if(err)
alert('Une erreur est survenue, un champ n\'a pas été renseigné.');
else{
// We add the product to the current database
DB.push(product);
// Update the table
updateTable();
}
}else if(classie.has(validate, 'category') && count){
var val = document.getElementById('new-cat').value;
if(val == '')
alert('Une erreur est survenue, un champ n\'a pas été renseigné.');
else{
SECTIONS.push(val);
updateSections();
}
}
count = !count;
ev.stopPropagation();
removeModalHandler();
});
cancel.addEventListener( 'click', function( ev ) {
ev.stopPropagation();
removeModalHandler();
});
} );
}
init();
})(); |
var clone = require('../objects/clone');
/**
* Generates a new array of given size. Each index is equal to the value given. If the value is a function, each index will be equal to the return value of the function.
* If a function is given as the value, that function will be called with the current index being generated: <i>callback(i)</i>
* @param count the size of the new array
* @param value the value (or generator function) for each index
* @returns {Array}
*/
function generate(count, value) {
var results = [];
for(var i = 0; i < count; i++) {
var v;
if(typeof value === 'function') {
v = value(i);
} else {
v = clone(value);
}
results.push(v);
}
return results;
}
module.exports = generate; |
const extendMiddleButton = new(class {
constructor() {
this.MIN_MOVEMENT = 10;
this.LEFT_BUTTON = 0;
this.MIDDLE_BUTTON = 1;
this.STATE_IDLE = 0;
this.STATE_WORKING = 2;
this.x1 = 0.0, this.y1 = 0.0;
this.x2 = 0.0, this.y2 = 0.0;
this.se = window.getSelection();
this.state = this.STATE_IDLE;
this.mouseup = this.mouseup.bind(this);
this.mousedown = this.mousedown.bind(this);
this.mousemove = this.mousemove.bind(this);
this.auxclick = this.auxclick.bind(this);
this.style = document.createElement("style");
this.style.textContent = "a { pointer-events:none; }";
}
start() {
document.addEventListener("mouseup", this.mouseup);
document.addEventListener("mousedown", this.mousedown);
document.addEventListener("mousemove", this.mousemove);
document.addEventListener("auxclick", this.auxclick);
}
stop() {
document.removeEventListener("mouseup", this.mouseup);
document.removeEventListener("mousedown", this.mousedown);
document.removeEventListener("mousemove", this.mousemove);
document.removeEventListener("auxclick", this.auxclick);
}
getRange(x, y) {
if (typeof document.caretPositionFromPoint === "function") {
const {
offsetNode: node,
offset: offset
} = document.caretPositionFromPoint(x, y);
return {
node,
offset,
};
}
else {
const {
startContainer: node,
startOffset: offset
} = document.caretRangeFromPoint(x, y);
return {
node,
offset,
};
}
}
mousedown(e) {
if (e.button !== this.MIDDLE_BUTTON) {
return;
}
e.preventDefault();
if (this.state === this.STATE_IDLE) {
this.state = this.STATE_WORKING;
this.x1 = e.clientX;
this.y1 = e.clientY;
const range = this.getRange(e.clientX, e.clientY);
this.se.setBaseAndExtent(range.node, range.offset, range.node, range.offset);
}
}
mouseup(e) {
this.state = this.STATE_IDLE;
if (e.button !== this.MIDDLE_BUTTON) {
return;
}
e.preventDefault();
}
mousemove(e) {
if (this.state === this.STATE_WORKING) {
const range = this.getRange(e.clientX, e.clientY);
this.se.extend(range.node, range.offset);
e.preventDefault();
}
}
auxclick(e) {
this.state = this.STATE_IDLE;
if (e.button === this.MIDDLE_BUTTON && this.se.toString() !== "") {
e.preventDefault();
}
}
})();
const scrollbarLocker = {
//https://stackoverflow.com/questions/13631730/how-to-lock-scrollbar-and-leave-it-visible
x: 0,
y: 0,
lock: () => {
scrollbarLocker.x = window.scrollX;
scrollbarLocker.y = window.scrollY;
window.addEventListener("scroll", scrollbarLocker.doLock, false);
},
free: () => {
window.removeEventListener("scroll", scrollbarLocker.doLock, false);
},
doLock: () => {
window.scrollTo(scrollbarLocker.x, scrollbarLocker.y);
},
};
// expose global variable
export var features = Object.freeze({
extendMiddleButton,
scrollbarLocker,
});
|
var node_generic_functions = require('node_generic_functions');
var mscSchedulizer_config = require('./config.js');
module.exports = {
classes_selected: JSON.parse(localStorage.getItem('classes_selected')) || [],
favorite_schedules: JSON.parse(localStorage.getItem('favorite_schedules')) || [],
schedule_filters: JSON.parse(localStorage.getItem('schedule_filters')) || {TimeBlocks:[],Professors:[],Campuses:{Morrisville:true,Norwich:false},NotFull:false,ShowOnline:true,ShowInternational:false},
gen_courses :[],
semester :JSON.parse(localStorage.getItem('semester')) || {TermCode: "", Description: "Unknown", TermStart: "", TermEnd: ""},
department :JSON.parse(localStorage.getItem('department')) || "",
department_courses :JSON.parse(localStorage.getItem('department_courses')) || "",
current_semester_list:JSON.parse(localStorage.getItem('current_semester_list')) || [],
gen_schedules:[],
num_loaded:0,
getTLD:function(url_location){
var parts = url_location.hostname.split('.');
var sndleveldomain = parts.slice(-2).join('.');
return sndleveldomain;
},
exportSchedule:function(crns){
var domain = mscSchedulizer.getTLD(window.location);
mscSchedulizer.setCookie("MSCschedulizer",JSON.stringify(crns),1,domain);
new PNotify({
title: 'Schedule Saved',
text: 'Login to <a href="http://webfor.morrisville.edu/webfor/bwskfreg.P_AltPin" target="_blank">Web for Students</a> and import the schedule from the add/drop form.',
type: 'success',
buttons: {
closer_hover: false,
closer: true,
sticker: false
}
});
},
exportURL:function(url,semester,department){
return url + (url.indexOf("?") === -1 ? "?" : "&") + "semester=" + semester + "&department=" + department;
},
setCookie:function(c_name, value, exdays, domain) {
var exdate = new Date();
exdate.setDate(exdate.getDate() + exdays);
domain = (domain && domain !== 'localhost') ? '; domain=' + '.' + (domain) : '';
var c_value = escape(value) + ((exdays === null) ? "" : "; expires=" + exdate.toUTCString() + domain + ";");
document.cookie = c_name + "=" + c_value;
},
getCookie:function(c_name) {
var i, x, y, ARRcookies = document.cookie.split(";");
for (i = 0; i < ARRcookies.length; i++) {
x = ARRcookies[i].substr(0, ARRcookies[i].indexOf("="));
y = ARRcookies[i].substr(ARRcookies[i].indexOf("=") + 1);
x = x.replace(/^\s+|\s+$/g, "");
if (x == c_name) {
return unescape(y);
}
}
},
setSemesterCurrentList:function(callback){
try{
var current_semester_list = mscSchedulizer.current_semester_list;
if(new Date()>new Date(current_semester_list[0].expires)){
mscSchedulizer.getSemestersList(callback);
}
else{
callback(current_semester_list);
}
}
catch(err){
mscSchedulizer.getSemestersList(callback);
}
},
setCurrentSemesterListVar:function(semesters){
var expiration = new Date();
expiration.setDate(expiration.getDate() + 1);
for(var i = 0; i < semesters.length; i++){
semesters[i].expires = expiration;
}
localStorage.setItem("current_semester_list", JSON.stringify(semesters));
mscSchedulizer.current_semester_list = semesters;
},
setSemester:function(semester){
try{
if(typeof semester !== 'undefined'){
var expiration = new Date();
expiration.setDate(expiration.getDate() + 1);
mscSchedulizer.semester.TermCode = semester;
mscSchedulizer.semester.expires = expiration;
mscSchedulizer.setSemesterVar(mscSchedulizer.semester);
}
else{
semester = JSON.parse(localStorage.getItem('semester')) || {};
if(new Date()>semester.expires){
mscSchedulizer.setSemesterVar(mscSchedulizer.current_semester_list[0]);
}
else if(node_generic_functions.isEmpty(semester)){
mscSchedulizer.setSemesterVar(mscSchedulizer.current_semester_list[0]);
}
else if(node_generic_functions.searchListDictionaries(mscSchedulizer.current_semester_list,{TermCode:mscSchedulizer.semester.TermCode},true)===-1){
mscSchedulizer.setSemesterVar(mscSchedulizer.current_semester_list[0]);
}
}
}
catch(err){
mscSchedulizer.setSemesterVar(mscSchedulizer.current_semester_list[0]);
}
},
setSemesterVar:function(semester){
localStorage.setItem("semester", JSON.stringify(semester));
mscSchedulizer.semester = semester;
},
setDepartmentVar:function(department){
localStorage.setItem("department", JSON.stringify(department));
mscSchedulizer.department = department;
},
queryData:function(queryString, preserveDuplicates){
// http://code.stephenmorley.org/javascript/parsing-query-strings-for-get-data/
var result = {};
// if a query string wasn't specified, use the query string from the URL
if (queryString === undefined){
queryString = location.search ? location.search : '';
}
// remove the leading question mark from the query string if it is present
if (queryString.charAt(0) == '?') queryString = queryString.substring(1);
// check whether the query string is empty
if (queryString.length > 0){
// replace plus signs in the query string with spaces
queryString = queryString.replace(/\+/g, ' ');
// split the query string around ampersands and semicolons
var queryComponents = queryString.split(/[&;]/g);
// loop over the query string components
for (var index = 0; index < queryComponents.length; index ++){
// extract this component's key-value pair
var keyValuePair = queryComponents[index].split('=');
var key = decodeURIComponent(keyValuePair[0].replace(/[\[\]]/g, ""));
var value = keyValuePair.length > 1 ? decodeURIComponent(keyValuePair[1]) : '';
// check whether duplicates should be preserved
if (preserveDuplicates){
// create the value array if necessary and store the value
if (!(key in result)) result[key] = [];
result[key].push(value);
}else{
// store the value
result[key] = value;
}
}
}
return result;
},
loadSelections: function(){
var output = "";
for (var i in mscSchedulizer.classes_selected) {
var course = mscSchedulizer.classes_selected[i];
output += "<a href=\"#\" data-value='"+escape(JSON.stringify(course))+"' class=\"a_selection\">"+course.DepartmentCode+" " + course.CourseNumber + ((course.CourseCRN!==null) ? " - " + course.CourseCRN : "") + " <i class=\"fa fa-times\"></i></a>";
}
$("#"+mscSchedulizer_config.html_elements.course_selections_list).html(output);
},
getDepartmentCourses: function(department){
department = typeof department !== 'undefined' ? department : $("#"+mscSchedulizer_config.html_elements.departments_select).val();
$.getJSON(mscSchedulizer_config.api_host + "/courses/?department_code=" + department + "&semester="+mscSchedulizer.semester.TermCode , function(results){
//remove this later
var output = "";
// Remove sections that are administrative entry
results = mscSchedulizer.removeAdministrativeSections(results);
for (var i in results) {
var course = results[i];
//Change to just one html output set
output += "<li><a class='a_course' data-value='"+escape(JSON.stringify({'DepartmentCode':course.DepartmentCode,'CourseNumber':course.CourseNumber,'CourseTitle':course.CourseTitle,'CourseCRN':null}))+"'>"+course.DepartmentCode+" " + course.CourseNumber +" - " + course.CourseTitle +"</a></li>";
}
$("#"+mscSchedulizer_config.html_elements.department_class_list).html(output);
})
.fail(function() {
$("#"+mscSchedulizer_config.html_elements.department_class_list).html("<li>Unable to load courses.</li>");
});
},
daysList: function(meeting, include_empty){
include_empty = typeof include_empty !== 'undefined' ? include_empty : true;
var result = [];
if(Boolean(meeting.Monday)){
result.push("M");
}
else if(include_empty)
{
result.push(" ");
}
if(Boolean(meeting.Tuesday)){
result.push("T");
}
else if(include_empty)
{
result.push(" ");
}
if(Boolean(meeting.Wednesday)){
result.push("W");
}
else if(include_empty)
{
result.push(" ");
}
if(Boolean(meeting.Thursday)){
result.push("R");
}
else if(include_empty)
{
result.push(" ");
}
if(Boolean(meeting.Friday)){
result.push("F");
}
else if(include_empty)
{
result.push(" ");
}
return result;
},
getDepartmentCoursesDetails: function(department){
department = typeof department !== 'undefined' ? department : $("#"+mscSchedulizer_config.html_elements.departments_select).val();
$.getJSON(mscSchedulizer_config.api_host + "/courses/?department_code=" + department + "&include_objects=1&semester="+mscSchedulizer.semester.TermCode, function(results){
// Remove sections that are administrative entry
results = mscSchedulizer.removeAdministrativeSections(results);
// Save results to mscschedulizer variable in localstorage
localStorage.setItem("department_courses", JSON.stringify(results));
mscSchedulizer.department_courses = results;
var output = mscSchedulizer.getDepartmentCoursesOutput(results);
$("#"+mscSchedulizer_config.html_elements.department_class_list).html(output);
})
.fail(function() {
$("#"+mscSchedulizer_config.html_elements.department_class_list).html("<p>Unable to load course listings.</p>");
})
.always(function() {
$('.course_details').basictable();
$('#modal_courseDescription').modal({show:false});
$('#modal_courseDescription').on('show.bs.modal', function (event) {
var trigger = $(event.relatedTarget); // Element that triggered the modal
var course = JSON.parse(unescape(trigger.data('course'))); // Extract info from data-* attributes
var modal = $(this);
modal.find('.modal-title').text(course.DepartmentCode + ' ' + course.CourseNumber + ' - ' + course.CourseTitle);
modal.find('.modal-body').text((course.Description !== null ? course.Description : 'The course description is currently unavailable.'));
});
});
},
getDepartmentCoursesOutput: function(courses){
var department_courses = JSON.parse(JSON.stringify(courses));
//Filter out sections based on user's filters
for (var c = department_courses.length-1; c >= 0; c--) {
for (var s = department_courses[c].Sections.length-1; s >= 0; s--) {
// Apply filters to section function
if(mscSchedulizer.applyFiltersToSection(department_courses[c].Sections[s],mscSchedulizer.schedule_filters)){
department_courses[c].Sections.splice(s, 1);
}
}
}
// Send filtered courses into detailed courses output.
var output = mscSchedulizer.detailedCoursesOutput(department_courses);
return output;
},
refreshDepartmentCoursesDetails: function(course){
if(course.CourseCRN === null)
{
var changedCourse = $(".a_course[data-value *= '" + escape(JSON.stringify(course)) + "']");
changedCourse.html("<i class=\"fa fa-plus-circle\"></i>");
}
else
{
var changedSection = $(".a_course_section[data-value *= " + course.CourseCRN + "]");
changedSection.removeClass('selected_section');
}
},
getSemestersList:function(callback){
$.getJSON(mscSchedulizer_config.api_host + "/semesters/", function(results){
mscSchedulizer.setCurrentSemesterListVar(results);
callback(results);
})
.fail(function() {
mscSchedulizer.setCurrentSemesterListVar(null);
callback(null);
});
},
getSemestersSelect:function(semesters_list){
var output = "";
for (var i in semesters_list){
var semester = semesters_list[i];
if(semester.TermCode == mscSchedulizer.semester.TermCode){
output += "<option class='a_semester' value='"+escape(JSON.stringify(semester)) + "' selected=\"selected\">" + semester.Description + "</option>";
}
else{
output += "<option class='a_semester' value='"+escape(JSON.stringify(semester)) + "'>" + semester.Description + "</option>";
}
}
$("#"+mscSchedulizer_config.html_elements.semesters_select).html(output);
},
getDepartments:function(callback){
$.getJSON(mscSchedulizer_config.api_host + "/departments/?semester="+mscSchedulizer.semester.TermCode, function(results){
var output = "";
for (var i in results) {
var department = results[i];
output += "<option class='a_department' value='"+department.DepartmentCode + "' " + (department.DepartmentCode === mscSchedulizer.department ? "selected=selected" : "") + ">" + department.DepartmentCode + ' ' + department.Name + "</option>";
}
$("#"+mscSchedulizer_config.html_elements.departments_select).html(output);
mscSchedulizer.setDepartmentVar($("#"+mscSchedulizer_config.html_elements.departments_select).val());
})
.fail(function() {
$("#"+mscSchedulizer_config.html_elements.departments_select).html("<option>Unable to load departments.</option>");
})
.always(function() {
$('.selectpicker').selectpicker({dropupAuto:false});
$('.selectpicker').selectpicker('refresh');
$(".bootstrap-select .dropdown-menu").niceScroll({
scrollspeed: 100,
mousescrollstep: 38,
cursorwidth: 10,
cursorborder: 0,
cursorcolor: '#333',
autohidemode: false,
zindex: 999999999,
horizrailenabled: false,
cursorborderradius: 0,
});
callback();
});
},
getLargeSchedule:function(crns,callback){
$.getJSON(mscSchedulizer_config.api_host + "/info/?crn=" + crns.join("&crn[]=") + "&semester="+mscSchedulizer.semester.TermCode, function(schedule){
var schedules = [];
schedules.push(schedule);
callback(schedules);
})
.fail(function() {
callback([]);
});
},
groupMeetings:function(meetings){
groupedMeetings = [];
for (var m in meetings) {
var meeting = meetings[m];
var index = node_generic_functions.searchListDictionaries(groupedMeetings,{CourseCRN:meeting.CourseCRN,StartTime:meeting.StartTime,EndTime:meeting.EndTime},true);
if(index !== -1){
groupedMeetings[index] = mscSchedulizer.mergeDays(groupedMeetings[index],meeting);
}
else{
groupedMeetings.push(meeting);
}
}
return groupedMeetings;
},
mergeDays:function(meeting1,meeting2){
var meeting = meeting1;
if(!Boolean(meeting.Monday) && Boolean(meeting2.Monday)){
meeting.Monday = 1;
}
if(!Boolean(meeting.Tuesday) && Boolean(meeting2.Tuesday)){
meeting.Tuesday = 1;
}
if(!Boolean(meeting.Wednesday) && Boolean(meeting2.Wednesday)){
meeting.Wednesday = 1;
}
if(!Boolean(meeting.Thursday) && Boolean(meeting2.Thursday)){
meeting.Thursday = 1;
}
if(!Boolean(meeting.Friday) && Boolean(meeting2.Friday)){
meeting.Friday = 1;
}
return meeting;
},
detailedCoursesOutput:function(courses,icon,show_crn_selections){
if(typeof icon === "undefined"){
icon = true;
}
if(typeof show_crn_selections === "undefined"){
show_crn_selections = true;
}
var output = "";
var terms = []; //List of term objects used in this department
for (var i in courses) {
var course = courses[i];
//Order by Section Number
course.Sections.sort(mscSchedulizer.sortSections);
//Table Header
var icon_str = "";
if(icon === true){
icon_str += "<a class=\"a_course\" data-value='"+escape(JSON.stringify({'DepartmentCode':course.DepartmentCode,'CourseNumber':course.CourseNumber,'CourseTitle':course.CourseTitle,'CourseCRN':null}))+"'>";
if(node_generic_functions.searchListDictionaries(mscSchedulizer.classes_selected,{'DepartmentCode':course.DepartmentCode,'CourseNumber':course.CourseNumber,'CourseTitle':course.CourseTitle,'CourseCRN':null},true) !== -1){
icon_str += "<i class=\"fa fa-minus-circle\"></i>";
}
else{
icon_str += "<i class=\"fa fa-plus-circle\"></i>";
}
icon_str += "</a> ";
}
output+=mscSchedulizer.modalTemplate('modal_courseDescription');
output+='<h4 class=\'classic-title\'><span>' + icon_str + '<span class=\'modal-trigger\'data-toggle=\'modal\' data-target=\'#modal_courseDescription\' data-course=\''+escape(JSON.stringify(course))+'\'>' + course.DepartmentCode + ' ' + course.CourseNumber + ' - ' + course.CourseTitle + '</span></span></h4>';
output+="<table class=\"course_details table\">";
output+="<thead><tr class=\"field-name\"><td>P/T</td><td>Campus</td><td>CRN</td><td>Sec</td><td>CrHr</td><td>Enrl/Max</td><td>Days</td><td>Time</td><td>Instructor</td></tr></thead><tbody>";
if(course.Sections.length === 0){
output += "<tr><td colspan=\"9\">All sections have been filtered out.</td></tr>";
}
for (var s in course.Sections) {
var section = course.Sections[s];
var groupedmeetings = mscSchedulizer.groupMeetings(section.Meetings);
groupedmeetings.sort(mscSchedulizer.sortMeetings);
for (var m in groupedmeetings) {
var meeting = groupedmeetings[m];
try
{
if(!moment(meeting.StartTime,"Hmm").isValid() || !moment(meeting.EndTime,"Hmm").isValid()){
throw("Not a valid date");
}
meeting.startTime = moment(meeting.StartTime,"Hmm").format("h:mma");
meeting.endTime = moment(meeting.EndTime,"Hmm").format("h:mma");
meeting.days = mscSchedulizer.daysList(meeting);
}
catch(err)
{
meeting.startTime = "TBD";
meeting.endTime = "";
meeting.days = [];
}
if(node_generic_functions.searchListDictionaries(terms,section.CourseTerm,true) == -1){
terms.push(section.CourseTerm);
}
if(section.Credits === null){
section.Credits = "variable";
}
output+="<tr class=\"a_course_section"+((node_generic_functions.searchListDictionaries(mscSchedulizer.classes_selected,{'DepartmentCode':course.DepartmentCode,'CourseNumber':course.CourseNumber,'CourseTitle':course.CourseTitle,'CourseCRN':section.CourseCRN},true)!==-1 && show_crn_selections === true) ? " selected_section" : "") +"\" data-value='" + escape(JSON.stringify({'DepartmentCode':course.DepartmentCode,'CourseNumber':course.CourseNumber,'CourseTitle':course.CourseTitle,'CourseCRN':section.CourseCRN})) + "'><td>" + section.Term + "</td><td>" + section.Campus + "</td><td>" + section.CourseCRN + "</td><td>" + section.SectionNumber + "</td><td>" + section.Credits + "</td><td>" + section.CurrentEnrollment + "/" + section.MaxEnrollment + "</td><td>" + meeting.days.join(" ") + " </td><td>" + meeting.startTime + " - " + meeting.endTime + "</td><td>" + section.Instructor + "</td></tr>";
}
}
output+="</tbody></table>";
}
// Term Table
var term_output = "<table class=\"term_details table\">" +
"<thead><tr class=\"field-name\">" +
"<td>Term Code</td><td>Start Date</td><td>End Date</td>" +
"</tr></thead>";
terms.sort(function(a, b) {
return a.TermCode - b.TermCode;
});
for (var t in terms) {
var term = terms[t];
term_output+= "<tr><td>" + term.TermCode + "</td><td>" + moment(term.TermStart).format("M/D/YY") + "</td><td>" + moment(term.TermEnd).format("M/D/YY") + "</td></tr>";
}
term_output += "</table>";
var special_msc_message = "";
// If it is a summer term
if(mscSchedulizer_config.msc_special_messages === true && node_generic_functions.endsWith("06",mscSchedulizer.semester.TermCode)){
var d_poterm = node_generic_functions.searchListDictionaries(terms,{TermCode:"D"}) ;
var e_poterm = node_generic_functions.searchListDictionaries(terms,{TermCode:"E"});
// Make this a function
if(d_poterm !== null){
special_msc_message += "<strong>Part of Term D Classes meeting:</strong><br/>";
special_msc_message += "Monday/Wednesday classes meet the following Fridays: " + moment(d_poterm.TermStart).day(5).format("MMMM D") + ", " + moment(d_poterm.TermStart).day(19).format("MMMM D") + ", " + moment(d_poterm.TermStart).day(33).format("MMMM D") + ". <br/>";
special_msc_message += "Tuesday/Thursday classes meet the following Fridays: " + moment(d_poterm.TermStart).day(12).format("MMMM D") + ", " + moment(d_poterm.TermStart).day(26).format("MMMM D") + ", " + moment(d_poterm.TermStart).day(40).format("MMMM D") + ". <br />";
}
if(e_poterm !== null){
special_msc_message += "<strong>Part of Term E Classes meeting:</strong><br/>";
special_msc_message += "Monday/Wednesday classes meet the following Fridays: " + moment(e_poterm.TermStart).day(5).format("MMMM D") + ", " + moment(e_poterm.TermStart).day(19).format("MMMM D") + ", " + moment(e_poterm.TermStart).day(33).format("MMMM D") + ". <br/>";
special_msc_message += "Tuesday/Thursday classes meet the following Fridays: " + moment(e_poterm.TermStart).day(12).format("MMMM D") + ", " + moment(e_poterm.TermStart).day(26).format("MMMM D") + ", " + moment(e_poterm.TermStart).day(40).format("MMMM D") + ". <br />";
}
special_msc_message += "<br/>";
}
output = term_output + special_msc_message + output;
return output;
},
getCourseInfos:function(callback,callback2){
// /info/?courses[]=343&courses[]=344&courses[]=345&courses[]=121
var courses_list = "";
for (var i in mscSchedulizer.classes_selected) {
var course = mscSchedulizer.classes_selected[i];
courses_list += "&courses[]=" + course.DepartmentCode + ' ' + course.CourseNumber + ' ' + encodeURIComponent(course.CourseTitle);
}
courses_list = courses_list.replace('&','?');
if(courses_list !== ""){
$.getJSON(mscSchedulizer_config.api_host + "/info/" + courses_list + "&semester="+mscSchedulizer.semester.TermCode, function(courses){
mscSchedulizer.gen_courses = courses;
return callback(mscSchedulizer.gen_courses,callback2);
})
.fail(function() {
mscSchedulizer.gen_courses = [];
$("#"+mscSchedulizer_config.html_elements.schedules_container).html("<p><span class=\"notice\">Unable to load combinations.</span></p>");
// return callback(mscSchedulizer.gen_courses,callback2);
});
}
else{
$("#"+mscSchedulizer_config.html_elements.schedules_container).html("<p><strong>No courses selected. <a href=\"select-classes.html\">Click here to select courses</a>.</strong></p>");
}
},
getCombinations:function(courses,callback){
var sectionCombinations = [];
var courseslist = [];
var outputCombinations = [];
for (var i in courses) {
var course = courses[i];
var aSectionCombination = mscSchedulizer.getSectionCombinations(course.Sections);
sectionCombinations.push(aSectionCombination);
courseslist.push({DepartmentCode:course.DepartmentCode,CourseNumber:course.CourseNumber,CourseTitle:course.CourseTitle});
}
var scheduleCombinations = mscSchedulizer.getScheduleCombinations(sectionCombinations);
// For each schedule
for (var h = scheduleCombinations.length-1; h >= 0; h--) {
outputCombinations[h] = [];
//for each class in the schedule
for (var c = scheduleCombinations[h].length-1; c >= 0; c--) {
var coursekey = node_generic_functions.searchListDictionaries(courseslist,{DepartmentCode:scheduleCombinations[h][c][0].DepartmentCode,CourseNumber:scheduleCombinations[h][c][0].CourseNumber,CourseTitle:scheduleCombinations[h][c][0].CourseTitle});
// Deep copy around ByRef
outputCombinations[h][c] = JSON.parse(JSON.stringify(coursekey));
outputCombinations[h][c].Sections = JSON.parse(JSON.stringify(scheduleCombinations[h][c]));
}
}
mscSchedulizer.gen_schedules = outputCombinations;
callback(outputCombinations);
},
getSectionCombinations:function(course_sections){
var grouped_sections = mscSchedulizer.groupSections(course_sections);
// Use Identifiers to generate combinations
var all_cp = [];
Object.keys(grouped_sections).forEach(function(campus) {
var identifiers_run = [];
Object.keys(grouped_sections[campus]).forEach(function(key) {
for (var s = grouped_sections[campus][key].length-1; s >= 0; s--) {
var section = grouped_sections[campus][key][s];
var cp_list = [];
if(identifiers_run.indexOf(section.Identifier) === -1 || identifiers_run.indexOf(section.Identifier) === identifiers_run.length - 1){
if(identifiers_run.indexOf(section.Identifier) === -1){
identifiers_run.push(section.Identifier);
}
if(section.RequiredIdentifiers !== null && typeof section.RequiredIdentifiers === 'string'){
var identifierRequirements = section.RequiredIdentifiers.split(";");
// for each requirement
for(var r in identifierRequirements){
var requirement = identifierRequirements[r];
identifiers_run.unshift(requirement);
// if key in object
if((requirement in grouped_sections[campus])){
cp_list.push(grouped_sections[campus][requirement]);
}
}
}
cp_list.push([section]);
var cp = Combinatorics.cartesianProduct.apply(null,cp_list);
cp = cp.toArray();
all_cp = all_cp.concat(cp);
}
}
});
});
// Checking the CRN requirements within each combination
var crnrequirements = node_generic_functions.searchListDictionaries(mscSchedulizer.classes_selected,{DepartmentCode:course_sections[0].DepartmentCode,CourseNumber:course_sections[0].CourseNumber,CourseTitle:course_sections[0].CourseTitle},false,true);
if(crnrequirements.length > 0){
for (var cp = all_cp.length-1; cp >= 0; cp--) {
var section_combination = all_cp[cp];
// If combination does not have all of the requirements
RequirementsLoop:
for (var c = crnrequirements.length-1; c >= 0; c--) {
// If CRN is not null, it is a crn requirement
if(crnrequirements[c].CourseCRN !== null){
if(node_generic_functions.searchListDictionaries(section_combination,crnrequirements[c],false,true).length===0){
all_cp.splice(cp, 1);
break RequirementsLoop;
}
}
}
}
}
// Check to see if the combination has sections that overlap
//For each combination
for (var i = all_cp.length-1; i >= 0; i--) {
var combination = all_cp[i];
combinationloop:
for (var s = combination.length-1; s >= 1; s--) {
var section1 = combination[s];
for (var t = s-1; t >= 0; t--) {
var section2 = combination[t];
if(mscSchedulizer.doSectionsOverlap(section1,section2)){
//If they do overlap, remove combination and break
all_cp.splice(i, 1);
//break out of section loop
break combinationloop;
}
}
}
}
return all_cp;
},
getScheduleCombinations:function(section_combinations){
// Make sure each class has at least one available section (After filters)
if(section_combinations.length === 0){
return [];
}
for (var i = section_combinations.length-1; i >= 0; i--) {
if(section_combinations[i].length === 0){
return [];
}
}
var cp = Combinatorics.cartesianProduct.apply(null,section_combinations);
cp = cp.toArray();
//filter based on overlapping
// returns list of schedules containing
// a list of classes containing
// a list of sections
// /info/?courses[]=121&courses[]=127
//for each schedule
for (var h = cp.length-1; h >= 0; h--) {
//for each class in the schedule
classloop:
for (var c = cp[h].length-1; c >= 1; c--) {
var course = cp[h][c];
//for each section in the class
for (var s = course.length-1; s >= 0; s--) {
var section1 = course[s];
// Compare against all other class sections within schedule
// don't need to compare against current class' sections because that was already done
for (var oc = c-1; oc >= 0; oc--) {
var acourse = cp[h][oc];
for (var os = acourse.length-1; os >= 0; os--) {
var section2 = acourse[os];
if(mscSchedulizer.doSectionsOverlap(section1,section2)){
//If they do overlap, remove combination and break
cp.splice(h, 1);
//Break out of course loop
break classloop;
}
}
}
}
}
}
return cp;
},
groupSections:function(course_sections){
// Sections are to be grouped by Campus and by identifier
var grouped_sections = {};
for (var i in course_sections) {
var course_section = course_sections[i];
var identifier = course_section.Identifier;
var campus = course_section.Campus;
// Apply Filters To SECTION
if(!mscSchedulizer.applyFiltersToSection(course_section,mscSchedulizer.schedule_filters)){
if(identifier === "" || identifier === null){
identifier = "empty";
}
if (!(campus in grouped_sections)){
grouped_sections[campus] = [];
}
if (!(identifier in grouped_sections[campus])){
grouped_sections[campus][identifier] = [];
}
grouped_sections[campus][identifier].push(course_section);
}
}
return grouped_sections;
},
filtersDisplay:function(){
var result = "<div id=\""+mscSchedulizer_config.html_elements.checkbox_filters+"\">";
result += "<span class=\"filtertooltiptrigger\" title=\"When enabled, only schedule combinations where all sections are not full (current enrollment is less than max enrollment) will be shown.\"><label><input type=\"checkbox\" name=\"notFull\" id=\""+mscSchedulizer_config.html_elements.filters.not_full+"\"> Hide Full</label></span>";
result += "<span class=\"filtertooltiptrigger\" title=\"When enabled, schedule combinations with Morrisville Campus sections will be shown.\"><label><input type=\"checkbox\" name=\"morrisville\" id=\""+mscSchedulizer_config.html_elements.filters.morrisville_campus+"\"> Morrisville Campus</label></span>";
result += "<span class=\"filtertooltiptrigger\" title=\"When enabled, schedule combinations with Norwich Campus sections will be shown.\"><label><input type=\"checkbox\" name=\"norwich\" id=\""+mscSchedulizer_config.html_elements.filters.norwich_campus+"\"> Norwich Campus</label></span>";
result += "<span class=\"filtertooltiptrigger\" title=\"When enabled, schedule combinations that include online sections will be shown.\"><label><input type=\"checkbox\" name=\"showOnline\" id=\""+mscSchedulizer_config.html_elements.filters.show_online+"\"> Online</label></span>";
result += "<span class=\"filtertooltiptrigger\" title=\"When enabled, schedule combinations with ONCAMPUS SUNY sections will be shown.\"><label><input type=\"checkbox\" name=\"showInternational\" id=\""+mscSchedulizer_config.html_elements.filters.show_international+"\"> ONCAMPUS SUNY</label></span>";
result += "</div>";
result += "<div id=\""+mscSchedulizer_config.html_elements.timeblock_filters+"\">";
result += mscSchedulizer.timeBlockDisplay(mscSchedulizer.schedule_filters.TimeBlocks);
result += "</div>";
return result;
},
updateFilters:function(schedule_filters){
mscSchedulizer.schedule_filters = schedule_filters;
localStorage.setItem('schedule_filters', JSON.stringify(schedule_filters));
mscSchedulizer.updateFiltersDisplay(mscSchedulizer.schedule_filters);
},
updateFiltersDisplay:function(filters){
mscSchedulizer.checkboxFilterDisplay(filters.NotFull,mscSchedulizer_config.html_elements.filters.not_full);
mscSchedulizer.checkboxFilterDisplay(filters.Campuses.Morrisville,mscSchedulizer_config.html_elements.filters.morrisville_campus);
mscSchedulizer.checkboxFilterDisplay(filters.Campuses.Norwich,mscSchedulizer_config.html_elements.filters.norwich_campus);
mscSchedulizer.checkboxFilterDisplay(filters.ShowOnline,mscSchedulizer_config.html_elements.filters.show_online);
mscSchedulizer.checkboxFilterDisplay(filters.ShowInternational,mscSchedulizer_config.html_elements.filters.show_international);
$("#"+mscSchedulizer_config.html_elements.timeblock_filters).html(mscSchedulizer.timeBlockDisplay(mscSchedulizer.schedule_filters.TimeBlocks));
mscSchedulizer.initTimeBlockPickers(filters.TimeBlocks);
// Initialize the tooltips for filters
$('.filtertooltiptrigger').tooltipster({ theme: 'tooltipster-punk',maxWidth:250,delay:750,iconTouch:true});
},
timeBlockDisplay:function(filters){
var result = "<span class=\"filtertooltiptrigger\" title=\"By adding time blocks filters, you can block out times that you do not want to have classes.\">Time block filters: <a onclick=\"mscSchedulizer.addTimeBlockFilter()\">Add</a></span>";
for(var i=0; i<filters.length;i++)
{
result += "<div id=\"timeOnly_"+i+"\"><span id=\"weekCal_"+i+"\"></span> " +
"<input type=\"text\" class=\"time start ui-timepicker-input\" autocomplete=\"off\"> to " +
"<input type=\"text\" class=\"time end ui-timepicker-input\" autocomplete=\"off\">" +
"<a onclick=\"mscSchedulizer.updateDayTimeBlockFilter("+i+")\"> Apply </a> <a onclick=\"mscSchedulizer.removeTimeBlockFilter("+i+")\"> Remove</a></div>";
}
return result;
},
addTimeBlockFilter:function(){
mscSchedulizer.schedule_filters.TimeBlocks[mscSchedulizer.schedule_filters.TimeBlocks.length] = {StartTime:"0000",EndTime:"2330",Days:""};
mscSchedulizer.updateFilters(mscSchedulizer.schedule_filters);
},
removeTimeBlockFilter:function(index){
mscSchedulizer.schedule_filters.TimeBlocks.splice(index, 1);
mscSchedulizer.updateFilters(mscSchedulizer.schedule_filters);
mscSchedulizer.getCombinations(mscSchedulizer.gen_courses,mscSchedulizer.createSchedules);
$("#"+mscSchedulizer_config.html_elements.department_class_list).html(mscSchedulizer.getDepartmentCoursesOutput(mscSchedulizer.department_courses));
},
updateDayTimeBlockFilter:function(index){
mscSchedulizer.schedule_filters.TimeBlocks[index] = {};
var timeOnlyExampleEl = document.getElementById("timeOnly_"+index);
var timeOnlyDatepair = new Datepair(timeOnlyExampleEl);
mscSchedulizer.schedule_filters.TimeBlocks[index].StartTime = node_generic_functions.padStr(node_generic_functions.convertToInttime(timeOnlyDatepair.startTimeInput.value).toString(),3);
mscSchedulizer.schedule_filters.TimeBlocks[index].EndTime = node_generic_functions.padStr(node_generic_functions.convertToInttime(timeOnlyDatepair.endTimeInput.value).toString(),3);
mscSchedulizer.schedule_filters.TimeBlocks[index].Days = $("#weekCal_"+index).weekLine('getSelected');
mscSchedulizer.updateFilters(mscSchedulizer.schedule_filters);
mscSchedulizer.getCombinations(mscSchedulizer.gen_courses,mscSchedulizer.createSchedules);
$("#"+mscSchedulizer_config.html_elements.department_class_list).html(mscSchedulizer.getDepartmentCoursesOutput(mscSchedulizer.department_courses));
},
initTimeBlockPickers:function(filters){
for(var i=0; i<filters.length;i++){
$("#timeOnly_"+i+" .time").timepicker({
'showDuration': true,
'timeFormat': 'g:ia',
"minTime":"12:00am",
"maxTime":"11:30pm"
});
$("#weekCal_"+i).weekLine({theme:"jquery-ui",dayLabels: ["Mon", "Tue", "Wed", "Thu", "Fri"]});
var timeOnlyExampleEl = document.getElementById("timeOnly_"+i);
var timeOnlyDatepair = new Datepair(timeOnlyExampleEl);
$("#timeOnly_"+i+" .start.time").timepicker('setTime', moment(filters[i].StartTime,"Hmm").format('h:mma'));
$("#timeOnly_"+i+" .end.time").timepicker('setTime', moment(filters[i].EndTime,"Hmm").format('h:mma'));
$("#weekCal_"+i).weekLine("setSelected", filters[i].Days);
}
},
checkboxFilterDisplay:function(filter,elementID){
if (filter)
{
document.getElementById(elementID).checked = true;
}
else
{
document.getElementById(elementID).checked = false;
}
},
concurrentEnrollmentFilter:function(section,filters){
if(section.SectionAttributes !== null){
var attributes = section.SectionAttributes.split(";");
if(node_generic_functions.inList("CHS", attributes) || node_generic_functions.inList("NHS", attributes) || node_generic_functions.inList("ETC", attributes) || node_generic_functions.inList("OCBB", attributes)){
return true;
}
}
return false;
},
removeAdministrativeSections:function(courses){
for (var c = courses.length-1; c >= 0; c--) {
if(typeof courses[c].Sections !== "undefined" && courses[c].Sections !== null){
for (var s = courses[c].Sections.length-1; s >= 0; s--) {
// Apply filters to section function
if(mscSchedulizer.requiredFilters(courses[c].Sections[s])){
courses[c].Sections.splice(s, 1);
}
}
if(courses[c].Sections.length === 0){
courses.splice(c, 1);
}
}
}
return courses;
},
requiredFilters:function(section){
var filteredOut = false;
filteredOut = mscSchedulizer.concurrentEnrollmentFilter(section);
return filteredOut;
},
applyFiltersToSection:function(section,filters){
var filteredOut = false;
filteredOut = mscSchedulizer.requiredFilters(section);
if(typeof filters.Campuses !== "undefined" && filteredOut === false){
filteredOut = mscSchedulizer.campusFilter(section,filters.Campuses);
}
// if(typeof filters.Professors !== "undefined" && filters.Professors != [] && filteredOut === false){
// filteredOut = mscSchedulizer.professorFilter(section,filters.Professors);
// }
if(typeof filters.TimeBlocks !== "undefined" && filters.TimeBlocks != [] && filteredOut === false){
filteredOut = mscSchedulizer.timeBlockFilter(section,filters.TimeBlocks);
}
if(typeof filters.NotFull !== "undefined" && filters.NotFull !== false && filteredOut === false){
filteredOut = mscSchedulizer.notFullFilter(section,filters.NotFull);
}
if((typeof filters.ShowOnline == "undefined" || filters.ShowOnline === false) && filteredOut === false){
filteredOut = mscSchedulizer.hideOnlineFilter(section,filters.ShowOnline);
}
if((typeof filters.ShowInternational === "undefined" || filters.ShowInternational === false) && filteredOut === false){
filteredOut = mscSchedulizer.hideInternationalFilter(section,filters.ShowInternational);
}
return filteredOut;
},
professorFilter:function(section,filter){
return false;
},
hideOnlineFilter:function(section,filters){
if(section.SectionAttributes !== null){
var attributes = section.SectionAttributes.split(";");
if(node_generic_functions.inList("ONLN", attributes)){
return true;
}
}
return false;
},
hideInternationalFilter:function(section,filters){
if(section.SectionNumber.indexOf("OL") === 0 || section.SectionNumber.indexOf("OC") === 0){
return true;
}
return false;
},
campusFilter:function(section,filter){
// Only filter out if it has a meeting location
try{
if(section.Meetings.length>0){
var count = 0;
for (var m in section.Meetings) {
var meeting = section.Meetings[m];
if(meeting.StartTime === null || meeting.EndTime === null || (meeting.Monday === 0 && meeting.Tuesday === 0 && meeting.Wednesday === 0 && meeting.Thursday === 0 && meeting.Friday === 0)){
count++;
}
}
if(count !== section.Meetings.length){
if((filter.Morrisville === false && section.Campus == "M")||(filter.Norwich === false && section.Campus == "N")){
return true;
}
}
}
}
catch (err){}
return false;
},
timeBlockFilter:function(section,filter){
try{
for (var m in section.Meetings){
for (var i in filter) {
if(mscSchedulizer.doTimesOverlap(filter[i],section.Meetings[m])===true){
if(mscSchedulizer.doBlockDaysOverlap(section.Meetings[m],filter[i].Days.split(","))){
return true;
}
}
}
}
}
catch (err){}
return false;
},
notFullFilter:function(section,filter){
// 0 is NOT unlimited, 0 means manual registration
// if(section.MaxEnrollment!=0){
if(section.CurrentEnrollment>=section.MaxEnrollment){
return true;
}
// }
return false;
},
doBlockDaysOverlap:function(meeting1,days){
if(meeting1.Monday==1 && node_generic_functions.inList("Mon",days)){
return true;
}
else if(meeting1.Tuesday==1 && node_generic_functions.inList("Tue",days)){
return true;
}
else if(meeting1.Wednesday==1 && node_generic_functions.inList("Wed",days)){
return true;
}
else if(meeting1.Thursday==1 && node_generic_functions.inList("Thu",days)){
return true;
}
else if(meeting1.Friday==1 && node_generic_functions.inList("Fri",days)){
return true;
}
return false;
},
doDaysOverlap:function(meeting1,meeting2){
if(meeting1.Monday==1&&meeting2.Monday==1){
return true;
}
else if(meeting1.Tuesday==1&&meeting2.Tuesday==1){
return true;
}
else if(meeting1.Wednesday==1&&meeting2.Wednesday==1){
return true;
}
else if(meeting1.Thursday==1&&meeting2.Thursday==1){
return true;
}
else if(meeting1.Friday==1&&meeting2.Friday==1){
return true;
}
return false;
},
doTimesOverlap:function(timeblock1,timeblock2){
if((parseInt(timeblock1.StartTime) <= parseInt(timeblock2.StartTime) && parseInt(timeblock1.EndTime) > parseInt(timeblock2.StartTime))||((parseInt(timeblock2.StartTime) <= parseInt(timeblock1.StartTime) && parseInt(timeblock2.EndTime) > parseInt(timeblock1.StartTime)))){
return true;
}
return false;
},
doTermsOverlap:function(term1,term2){
if((term1.TermStart <= term2.TermStart && term1.TermEnd > term2.TermStart)||((term2.TermStart <= term1.TermStart && term2.TermEnd > term1.TermStart))){
return true;
}
return false;
},
doMeetingDatesOverlap:function(meeting1,meeting2){
// One-day meetings have the same start and end date, in which case they should overlap
if(meeting1.StartDate !== null && meeting1.EndDate !== null && meeting2.StartDate !== null && meeting2.EndDate !== null){
if((meeting1.StartDate <= meeting2.StartDate && meeting1.EndDate >= meeting2.StartDate)||((meeting2.StartDate <= meeting1.StartDate && meeting2.EndDate >= meeting1.StartDate))){
return true;
}
}
return false;
},
doMeetingsOverlap:function(section1meetings,section2meetings){
//for each meeting in section1
if(typeof section1meetings !== 'undefined' && typeof section2meetings !== 'undefined'){
for (var i = section1meetings.length-1; i >= 0; i--) {
var s1meeting = section1meetings[i];
//for each meeting in section2
for (var m = section2meetings.length-1; m >= 0; m--) {
var s2meeting = section2meetings[m];
if(mscSchedulizer.doTimesOverlap({StartTime:s1meeting.StartTime,EndTime:s1meeting.EndTime},{StartTime:s2meeting.StartTime,EndTime:s2meeting.EndTime})){
if(mscSchedulizer.doDaysOverlap(s1meeting,s2meeting)){
if(mscSchedulizer.doMeetingDatesOverlap(s1meeting,s2meeting)){
return true;
}
}
}
}
}
}
return false;
},
doSectionsOverlap:function(section1,section2){
if(mscSchedulizer.doMeetingsOverlap(section1.Meetings,section2.Meetings)){
return true;
}
return false;
},
convertDate:function(dayOfWeek){
var today = new Date();
var weekDate = new Date();
if(dayOfWeek == "M"){
weekDate.setDate(today.getDate() - today.getDay()+1);
}
else if(dayOfWeek == "T"){
weekDate.setDate(today.getDate() - today.getDay()+2);
}
else if(dayOfWeek == "W"){
weekDate.setDate(today.getDate() - today.getDay()+3);
}
else if(dayOfWeek == "R"){
weekDate.setDate(today.getDate() - today.getDay()+4);
}
else if(dayOfWeek == "F"){
weekDate.setDate(today.getDate() - today.getDay()+5);
}
return weekDate;
},
splitMeetings:function(meeting){
var meetups = [];
var m_date;
var st;
var et;
if(meeting.Monday == 1){
m_date = mscSchedulizer.convertDate("M");
st = moment(m_date).format("YYYY-MM-DD") + moment(meeting.StartTime,"H:mm").format("THH:mm");
et = moment(m_date).format("YYYY-MM-DD") + moment(meeting.EndTime,"H:mm").format("THH:mm");
meetups.push({StartTime: st,EndTime: et});
}
if(meeting.Tuesday == 1){
m_date = mscSchedulizer.convertDate("T");
st = moment(m_date).format("YYYY-MM-DD") + moment(meeting.StartTime,"H:mm").format("THH:mm");
et = moment(m_date).format("YYYY-MM-DD") + moment(meeting.EndTime,"H:mm").format("THH:mm");
meetups.push({StartTime: st,EndTime: et});
}
if(meeting.Wednesday == 1){
m_date = mscSchedulizer.convertDate("W");
st = moment(m_date).format("YYYY-MM-DD") + moment(meeting.StartTime,"H:mm").format("THH:mm");
et = moment(m_date).format("YYYY-MM-DD") + moment(meeting.EndTime,"H:mm").format("THH:mm");
meetups.push({StartTime: st,EndTime: et});
}
if(meeting.Thursday == 1){
m_date = mscSchedulizer.convertDate("R");
st = moment(m_date).format("YYYY-MM-DD") + moment(meeting.StartTime,"H:mm").format("THH:mm");
et = moment(m_date).format("YYYY-MM-DD") + moment(meeting.EndTime,"H:mm").format("THH:mm");
meetups.push({StartTime: st,EndTime: et});
}
if(meeting.Friday == 1){
m_date = mscSchedulizer.convertDate("F");
st = moment(m_date).format("YYYY-MM-DD") + moment(meeting.StartTime,"H:mm").format("THH:mm");
et = moment(m_date).format("YYYY-MM-DD") + moment(meeting.EndTime,"H:mm").format("THH:mm");
meetups.push({StartTime: st,EndTime: et});
}
return meetups;
},
createSchedules:function(schedules){
mscSchedulizer.num_loaded = 0;
if(schedules !== null && schedules.length > 0 ){
var outputSchedules = "<span class=\"notice\">"+schedules.length + " schedule";
if(schedules.length != 1){outputSchedules += "s";}
outputSchedules +="</span>";
outputSchedules += mscSchedulizer.modalTemplate("modal_courseDetails","modal-lg");
for (var i in schedules) {
var schedule = schedules[i];
var events = [];
var noMeetings = [];
var earlyStartTime = 2400;
var lateEndTime = 0;
for (var c in schedule) {
var course = schedule[c];
var allSectionsHaveMeeting = true;
for (var s in course.Sections) {
var section = course.Sections[s];
if(section.Meetings.length === 0){
allSectionsHaveMeeting = false;
}
for (var m in section.Meetings) {
var meeting = section.Meetings[m];
if(meeting.StartTime === null || meeting.EndTime === null || (meeting.Monday === 0 && meeting.Tuesday === 0 && meeting.Wednesday === 0 && meeting.Thursday === 0 && meeting.Friday === 0)){
allSectionsHaveMeeting = false;
}
if(parseInt(meeting.StartTime) < parseInt(earlyStartTime)){
earlyStartTime = meeting.StartTime;
}
if(parseInt(meeting.EndTime) > parseInt(lateEndTime)){
lateEndTime = meeting.EndTime;
}
//Meeting could be on multiple days, needs to be split into separate events
var meetups = mscSchedulizer.splitMeetings(meeting);
for (var u in meetups) {
var meetup = meetups[u];
events.push({title:course.DepartmentCode + " " + course.CourseNumber,start:meetup.StartTime,end:meetup.EndTime,color: mscSchedulizer_config.colors[c]});
}
}
}
if(!allSectionsHaveMeeting){
noMeetings.push(course);
}
}
if(parseInt(earlyStartTime)>parseInt(lateEndTime)){
//Schedule does not have any meeting times
earlyStartTime = 0;
lateEndTime = 100;
}
schedule.earlyStartTime = earlyStartTime;
schedule.lateEndTime = lateEndTime;
schedule.events = events;
schedule.courseWithoutMeeting = noMeetings;
outputSchedules += "<div id=\"schedule_" + i + "\" class=\"schedule_combination\"></div>";
}
$("#"+mscSchedulizer_config.html_elements.schedules_container).html(outputSchedules);
$('#modal_courseDetails').modal({show:false});
$('#modal_courseDetails').on('show.bs.modal', function (event) {
var trigger = $(event.relatedTarget); // Element that triggered the modal
// var schedule = trigger.data('schedule'); // Extract info from data-* attributes
var schedule = JSON.parse(unescape(trigger.data('schedule'))); // Extract info from data-* attributes
var modal = $(this);
modal.find('.modal-title').text("Schedule Details");
modal.find('.modal-body').html('<div style=\'display:block;\'>' + mscSchedulizer.exportLink(schedule) + '</div>' + mscSchedulizer.detailedCoursesOutput(schedule,false,false));
$('.course_details').basictable();
});
mscSchedulizer.initSchedules(schedules,mscSchedulizer.num_loaded,mscSchedulizer_config.numToLoad);
}
else{
$("#"+mscSchedulizer_config.html_elements.schedules_container).html("<p><span class=\"notice\">No schedules. Adjust your selections and/or filters.</span></p>");
}
},
initSchedules:function(schedules,start,count){
for (var i = 0; i < count ; i++) {
var num = start + i;
if(schedules[num] !== undefined){
$('#schedule_' + num).fullCalendar({
editable: false,
handleWindowResize: true,
slotEventOverlap:false,
weekends: false, // Hide weekends
defaultView: 'agendaWeek', // Only show week view
header: false, // Hide buttons/titles
minTime: moment(schedules[num].earlyStartTime,"Hmm").format("HH:mm"), // Start time for the calendar
maxTime: moment(schedules[num].lateEndTime,"Hmm").format("HH:mm"), // End time for the calendar
columnFormat: {
week: 'ddd' // Only show day of the week names
},
displayEventTime: true,
height:'auto',
// allDayText: 'TBD',
allDaySlot: false,
events: schedules[num].events
});
var additionalOutput = "";
if(schedules[num].courseWithoutMeeting.length > 0){
additionalOutput += mscSchedulizer.genNoMeetingsOutput(schedules[num].courseWithoutMeeting);
}
additionalOutput += mscSchedulizer.optionsOutput(schedules[num]);
$('#schedule_' + num).append(additionalOutput);
mscSchedulizer.num_loaded++;
}
}
},
optionsOutput:function(schedule){
var result = "<div class=\"options\">";
result += mscSchedulizer.favoriteLinkOutput(schedule);
result += mscSchedulizer.detailsLinkOutput(schedule);
result += mscSchedulizer.previewLinkOutput(schedule);
result += mscSchedulizer.exportLink(schedule);
result+="</div>";
return result;
},
favoriteLinkOutput:function(schedule){
// If a favorite
if(node_generic_functions.searchListObjects(mscSchedulizer.favorite_schedules,schedule) !== -1){
return "<a class=\"unfavorite_schedule favoriting\" data-value='" + escape(JSON.stringify(schedule)) + "'>Unfavorite</a>";
}
return "<a class=\"favorite_schedule favoriting\" data-value='" + escape(JSON.stringify(schedule)) + "'>Favorite</a>";
},
detailsLinkOutput:function(schedule){
return '<a class=\'modal-trigger\'data-toggle=\'modal\' data-target=\'#modal_courseDetails\' data-schedule=\''+escape(JSON.stringify(schedule))+'\'>Details</a>';
},
previewLinkOutput:function(schedule){
var crns = [];
for(var i = 0; i < schedule.length; i++){
for(var s = 0; s < schedule[i].Sections.length; s++){
crns.push(schedule[i].Sections[s].CourseCRN);
}
}
return "<a target=\"_blank\" href=\"preview.html?crn[]="+crns.join("&crn[]=")+"\">Preview</a>";
},
genNoMeetingsOutput: function(courses){
try{
var output = "";
for(var i = 0; i < courses.length; i++){
var course = courses[i];
output += course.DepartmentCode + ' ' + course.CourseNumber + ', ';
}
if(output !== ""){
output = output.replace(/,+\s*$/, '');
output = "<div class='nomeetings'><h3>Online/TBD</h3>" + output + "</div>";
}
return output;
}
catch(err){
return "";
}
},
isScrolledIntoView:function(elem) {
var $elem = $(elem);
var $window = $(window);
var docViewTop = $window.scrollTop();
var docViewBottom = docViewTop + $window.height();
var elemTop = $elem.offset().top;
var elemBottom = elemTop + $elem.height();
// && for entire element || for any part of the element
return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
},
modalTemplate:function(id,classes){
classes = typeof classes !== 'undefined' ? classes : "";
var output = "";
//Modal
output += '<!-- Modal -->';
output += '<div class="modal fade" id="' + id + '" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">';
output += ' <div class="modal-dialog ' + classes + '" role="document">';
output += ' <div class="modal-content">';
output += ' <div class="modal-header">';
output += ' <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>';
output += ' <h4 class="modal-title"></h4>';
output += ' </div>';
output += ' <div class="modal-body">';
output += ' </div>';
output += ' <div class="modal-footer">';
output += ' <button type="button" class="btn btn-primary" data-dismiss="modal">Close</button>';
output += ' </div>';
output += ' </div>';
output += ' </div>';
output += '</div>';
//End modal
return output;
},
exportLink:function(schedule){
return '<a class=\'export_schedule\' onClick=\'mscSchedulizer.exportSchedule(mscSchedulizer.getScheduleCRNs("' + escape(JSON.stringify(schedule)) + '"));\'>Export Schedule</a>';
},
getScheduleCRNs:function(schedule){
var crns = [];
if(typeof schedule === 'string'){
schedule = JSON.parse(unescape(schedule));
}
for(var i = 0; i < schedule.length; i++){
for(var s = 0; s < schedule[i].Sections.length; s++){
crns.push(schedule[i].Sections[s].CourseCRN);
}
}
return crns;
},
sortSections:function(a,b){
return node_generic_functions.alphaNumericSort(a.SectionNumber,b.SectionNumber);
},
sortMeetings:function(a, b) {
if(moment(a.StartTime,"Hmm").isValid() && moment(b.StartTime,"Hmm").isValid()){
return moment(a.StartTime,"Hmm") - moment(b.StartTime,"Hmm");
}
return 0;
}
};
|
(function(){Template.__define__("pkg_force_ssl",Package.handlebars.Handlebars.json_ast_to_func([["#",[[0,"better_markdown"]],["\n## `force-ssl`\n\nThis package causes Meteor to redirect insecure connections (HTTP) to a\nsecure URL (HTTPS). Use this package to ensure that communication to the\nserver is always encrypted to protect users from active spoofing\nattacks.\n\nTo simplify development, unencrypted connections from `localhost` are\nalways accepted over HTTP.\n\nApplication bundles (`meteor bundle`) do not include an HTTPS server or\ncertificate. A proxy server that terminates SSL in front of a Meteor\nbundle must set the standard `x-forwarded-proto` header for the\n`force-ssl` package to work.\n\nApplications deployed to `meteor.com` subdomains with\n`meteor deploy` are automatically served via HTTPS using Meteor's\ncertificate.\n\n"]]]));
})();
|
var path = require('path')
var utils = require('./utils')
var config = require('../config')
var vueLoaderConfig = require('./vue-loader.conf')
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
module.exports = {
entry: {
app: './src/main.js'
},
output: {
path: config.build.assetsRoot,
filename: '[name].js',
publicPath: process.env.NODE_ENV === 'production'
? config.build.assetsPublicPath
: config.dev.assetsPublicPath
},
externals: {
'vue': 'Vue',
'vue-router': 'VueRouter',
'vuex': 'Vuex',
'axios': 'axios'
},
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'@': resolve('src'),
}
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue-loader',
options: vueLoaderConfig
},
{
test: /\.js$/,
loader: 'babel-loader',
include: [resolve('src'), resolve('test')]
},
{
test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
loader: 'url-loader',
query: {
limit: 10000,
name: utils.assetsPath('img/[name].[hash:7].[ext]')
}
},
{
test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
loader: 'url-loader',
query: {
limit: 10000,
name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
}
}
]
}
}
|
module.exports = (sequelize, DataTypes) => {
const Todo = sequelize.define('Todo', {
title: {
type: DataTypes.STRING,
allowNull: false,
},
}, {
classMethods: {
associate: (models) => {
Todo.hasMany(models.TodoItem, {
foreignKey: 'todoId',
as: 'todoItems',
});
},
},
});
return Todo;
}; |
import React from 'react';
export default class Friends extends React.Component {
render() {
return myFriends.map(friend => (
<FriendProfile key={friend.id} name={friend.name} age={friend.age} />
));
}
}
class FriendProfile extends React.Component {
render() {
if (this.props.age === undefined) {
return null;
}
return this.props.name;
}
}
const myFriends = [
{
id: 1,
name: 'Potatoes',
age: '4 months',
},
{
id: 2,
name: 'Flower',
age: '6 months',
},
{
id: 3,
name: 'Turtle',
},
];
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.